@omfalos/mokosh 0.4.0 → 0.4.1
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/cli.js +30 -30
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +30 -30
- package/dist/cli.mjs.map +1 -1
- package/dist/index.d.mts +35 -8
- package/dist/index.d.ts +35 -8
- package/dist/index.js +20 -20
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +20 -20
- package/dist/index.mjs.map +1 -1
- package/dist/mcp.js +22 -21
- package/dist/mcp.js.map +1 -1
- package/dist/mcp.mjs +23 -22
- package/dist/mcp.mjs.map +1 -1
- package/package.json +1 -1
package/dist/mcp.mjs
CHANGED
|
@@ -1,36 +1,37 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}};import
|
|
4
|
-
`).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=
|
|
5
|
-
`,o),a=i===-1?
|
|
6
|
-
`&&o++;i=a.index;let c=a[0],l=c;
|
|
7
|
-
`&&o++;i=a.index+c.length,a=
|
|
2
|
+
var nt=(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 _s from"path";import{fileURLToPath as Os}from"url";var js=()=>Os(import.meta.url),zs=()=>_s.dirname(js()),f=zs();import{StdioServerTransport as ol}from"@modelcontextprotocol/sdk/server/stdio.js";import{Server as rl}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as nl,ListToolsRequestSchema as sl}from"@modelcontextprotocol/sdk/types.js";import Xc from"fs";import Zc from"path";import at from"fs";import kr from"path";var Ws=[".config.","biome.json","tsconfig.json","package.json",".prettierrc",".eslintrc"],hr=[];function Te(t){hr.push(t)}function yr(t){return[...Ws,...hr].some(e=>typeof e=="string"?t.includes(e):e instanceof RegExp?e.test(t):e(t))}var $s=[".test.",".spec.","-test.","-spec."],xr=[];function Ee(t){xr.push(t)}function re(){return[...$s,...xr]}var Bs=["jest","vitest","playwright","cypress","@testing-library/"],br=[];function Ae(t){br.push(t)}function st(){return[...Bs,...br]}var Sr=.8;function ot(t){Sr=t}function it(){return Sr}var Us=["mokosh.config.js","mokosh.config.cjs","mokosh.config.json"];function ne(t,{allowJs:e=!0,isExplicitPath:r=!1}={}){if(r){let n=kr.resolve(t);return at.existsSync(n)?n.endsWith(".json")?vr(n):e?Cr(n):{}:{}}for(let n of Us){let s=kr.resolve(t,n);if(at.existsSync(s)){if(n.endsWith(".json"))return vr(s);if(e)return Cr(s)}}return{}}function vr(t){return JSON.parse(at.readFileSync(t,"utf-8"))}function Cr(t){let e=nt(t);return e&&typeof e=="object"&&"default"in e&&(e=e.default),typeof e=="function"?e({}):e}function ct(t){for(let e of t.configMatchers??[])Te(e);for(let e of t.testPatterns??[])Ee(e);for(let e of t.testLibraries??[])Ae(e);t.barrelThreshold!==void 0&&ot(t.barrelThreshold)}function V(t){return{gitStats:t?.gitStats??!1,parallelParsing:t?.parallelParsing,pathAliases:t?.pathAliases}}var lt="mokosh-cache",pt="duplication-tokens.json",j=["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage"],ut=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".go",".feature",".md",".mdx"];import Ks from"fs";import wr from"path";function ft(t,e){let r=wr.resolve(t,e);try{let n=Ks.readFileSync(r,"utf-8"),s=JSON.parse(n),o=new Map;for(let[i,a]of Object.entries(s)){if(i==="total")continue;let c=a?.lines?.pct;if(typeof c!="number")continue;let l=wr.relative(t,i);o.set(l,c)}return o}catch{return new Map}}var Pe={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 Fr from"fs";import Hs from"path";function mt(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 Tr(t,e){if(typeof t=="string")return mt(t,e);if(t&&typeof t=="object"){let r=t;for(let n of["import","require","default"]){let s=Tr(r[n],e);if(s)return s}}return null}function Vs(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 Qs(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 gt(t,e){let r=[],n=Hs.join(e,"package.json");if(Fr.existsSync(n))try{let s=JSON.parse(Fr.readFileSync(n,"utf8"));if(s.exports&&typeof s.exports=="object"&&!Array.isArray(s.exports))for(let o of Object.values(s.exports)){let i=Tr(o,t);i&&!r.includes(i)&&r.push(i)}else if(typeof s.exports=="string"){let o=mt(s.exports,t);o&&r.push(o)}if(r.length===0)for(let o of[s.main,s.module].filter(Boolean)){let i=mt(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 qs(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 Ys(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 Xs(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(d=>d.name===o))??n[0],p={name:o,definedIn:l,kind:Vs(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 Zs(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 dt(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=qs(t,e),n=Ys(t,r,e),s=Qs(t,e),o=Xs(s,n,t,e),{internalFiles:i,unreachableFromEntry:a,testFiles:c}=Zs(t,r,e);return{entryPoints:e,publicExports:o,internalFiles:i,unreachableFromEntry:a,testFiles:c}}function ht(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 _l from"fs";import jl from"path";function Er(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 yt(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:Er(t)}}function xt(t,e){return t.impact.get(e)??[]}import{readFile as Jr}from"fs/promises";import oe from"path";import _o from"piscina";import Ne from"fs";import eo from"path";import{load as Ar}from"js-yaml";var bt=["package-lock.json","yarn.lock","pnpm-lock.yaml"];function Pr(t){let e=t.lastIndexOf("@");return e>0?t.substring(0,e):t}function to(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)),Pr(r)}).filter(Boolean)}function ro(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 no(t){try{let e=Ar(t),r={dependencies:{}};for(let[n,s]of Object.entries(e))if(!(n==="__metadata"||!s?.version))for(let o of n.split(", ")){let i=Pr(o);i&&(r.dependencies[i]={version:s.version,...s.dependencies!==void 0&&{dependencies:s.dependencies}})}return r}catch{return null}}function so(t){let e={dependencies:{}};for(let r of t.split(/\n\n+/)){let n=r.split(`
|
|
4
|
+
`).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=to(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 oo(t){let e=Ne.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 io(t){let e=Ne.readFileSync(t,"utf-8");if(e.includes("__metadata:")){let r=no(e);if(r!==null)return r}return so(e)}function ao(t){let e=Ne.readFileSync(t,"utf-8"),r={dependencies:{}};try{let n=Ar(e);if(n.packages)for(let[s,o]of Object.entries(n.packages)){let{name:i,version:a}=ro(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}function Nr(t){let e={"package-lock.json":oo,"yarn.lock":io,"pnpm-lock.yaml":ao},r=bt.map(n=>[n,e[n]]);for(let[n,s]of r){let o=eo.join(t,n);if(Ne.existsSync(o))return s(o)}return null}var co=new Set(["css","scss","less","stylus"]);function Ir(t){return co.has(t)?"style":"code"}import Mr from"postcss";import*as lo from"postcss-less";var po=lo,Rr=new Set(["reference","inline"]);function Dr(t){return t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||t.startsWith("data:")}function uo(t){let e=t.trim();return e.length>0&&!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("//")&&!e.startsWith("data:")&&!e.startsWith("#")}function fo(t,e){let r=t.match(/^\(([^)]+)\)\s+['"]([^'"]+)['"]/);if(r){let o=r[1]?.trim()??"",i=r[2]??"";if(!i)return null;let a=Rr.has(o)?"side-effect":"static";return{fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a,...Dr(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",...Dr(s)?{isExternal:!0}:{}}:null}function mo(t,e){let r=[],n=/url\(['"]?([^'")]+)['"]?\)/g,s=n.exec(t);for(;s!==null;){let o=s[1]?.trim()??"";uo(o)&&r.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:"static"}),s=n.exec(t)}return r}function Lr(t,e){let r=[];return t.walk(n=>{if(n.type==="atrule"&&n.name==="import"){let s=fo(n.params,e);s&&r.push(s)}n.type==="decl"&&r.push(...mo(n.value,e))}),r}function go(t){return t.replace(/(?<!:)\/\/.*/g,"")}function ho(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=Rr.has(o)?"side-effect":"static";r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a})}s=n.exec(t)}return r}function Ie(t,e){let r=Mr.parse(go(t));return{imports:Lr(r,e),root:r}}function yo(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 De(t,e){try{let r=po.parse(t),{exports:n,tags:s}=yo(r);return{imports:Lr(r,e),root:r,exports:n,tags:s}}catch{return{imports:ho(t,e),root:Mr.parse(""),exports:[],tags:[]}}}import{parse as xo}from"postcss-scss";function Gr(t){return t.startsWith("_")||t.startsWith("-")}function bo(t){return!!(t.startsWith("sass:")||t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||!t.startsWith(".")&&!t.startsWith("/")&&!t.startsWith("_"))}function So(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 ko(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||Gr(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||Gr(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 Me(t,e){let r=xo(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}=So(c);if(!l)return;let u={fromPath:e,toPath:"",rawSpecifier:l,isStyle:!0,type:a==="forward"?"re-export":"static",...bo(l)?{isExternal:!0}:{}};p&&(u.symbols=[p]),n.push(u)});let{exports:s,tags:o}=ko(r);return{imports:n,root:r,exports:s,tags:o}}function vo(t){return t.trim().replace(/\s+/g," ")}function Co(t){try{return t.fileType==="scss"?Me(t.source,t.file).root:t.fileType==="less"?De(t.source,t.file).root:t.fileType==="css"?Ie(t.source,t.file).root:void 0}catch{return}}function wo(t){let e=Co(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()}:${vo(p.value)}`).join(";");r.push({file:t.file,startLine:a,endLine:c,lines:c-a+1,signature:l,declCount:s.length})}),r}function _r(t,e,r=2){let n=new Map;for(let o of t)for(let i of wo(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 Or(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 Fo=new Set(["{","}",":",",","[","]"]);function jr(t,e,r){let n=0;for(let s=e;s<e+r;s++)Fo.has(t[s].text)&&n++;return n/r}function zr(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 Wr(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 $r(t,e,r,n=.5){let s=[],o=[],i=new Map;for(let{file:u,tokens:d}of t)if(d.length!==0){i.set(u,d);for(let h=0;h<d.length;h++)s.push(d[h].text),o.push({file:u,localIndex:h});s.push(` ${u}`),o.push({file:u,localIndex:-1})}if(s.length===0)return[];let a=zr(s),c=Wr(s,a),l=Or(c),p=[];for(let u of l){let d=To(u,a,o,i,e,r,n);d&&p.push(d)}return p.sort((u,d)=>d.lines-u.lines)}function To(t,e,r,n,s,o,i){if(t.lcpLength<s)return;let a=[];for(let h=t.low;h<=t.high;h++){let k=r[e[h]];k.localIndex!==-1&&a.push(k)}if(a.length<2||!Eo(a,n))return;let c=Ao(a,t.lcpLength);if(c.length<2)return;let l=c[0],p=n.get(l.file);if(jr(p,l.localIndex,t.lcpLength)>i)return;let u=c.map(({file:h,localIndex:k})=>{let x=n.get(h);return{file:h,startLine:x[k].line,endLine:x[k+t.lcpLength-1].line}}),d=Math.min(...u.map(h=>h.endLine-h.startLine+1));if(!(d<o))return{occurrences:u,lines:d,tokens:t.lcpLength}}function Eo(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 Ao(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 Po={typescript:{line:["//"],block:[["/*","*/"]]},javascript:{line:["//"],block:[["/*","*/"]]},go:{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 Br(t,e,r){let n=t.slice(e,r).replace(/[^\n]/g," ");return t.slice(0,e)+n+t.slice(r)}function No(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=Br(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(`
|
|
5
|
+
`,o),a=i===-1?r.length:i;r=Br(r,o,a),s=a}}return r}var Io=["===","!==","...","=>","==","!=","<=",">=","&&","||","::","->","..","+=","-=","*=","/="],St=new RegExp(`${Io.map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")}|[A-Za-z_$][A-Za-z0-9_$]*|\\d+(?:\\.\\d+)?|"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`|\\S`,"g"),Do=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ur=/^\d+(?:\.\d+)?$/,Mo=/^(".*"|'.*'|`.*`)$/s,Ro=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 Kr(t,e,r=!0){let n=No(t,Po[e]),s=[],o=1,i=0;St.lastIndex=0;let a=St.exec(n);for(;a!==null;){for(let p=i;p<a.index;p++)n[p]===`
|
|
6
|
+
`&&o++;i=a.index;let c=a[0],l=c;Do.test(c)&&!Ro.has(c)?l="ID":r&&(Ur.test(c)||Mo.test(c))&&(l=Ur.test(c)?"NUM":"STR"),s.push({text:l,line:o});for(let p=i;p<a.index+c.length;p++)n[p]===`
|
|
7
|
+
`&&o++;i=a.index+c.length,a=St.exec(n)}return s}import se from"fs";import Lo from"path";function Go(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 Re(t){try{if(!se.existsSync(t))return new Map;let e=se.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"&&Go(s[1]));return new Map(n)}catch{return new Map}}function Le(t,e){let r=Lo.dirname(e);se.existsSync(r)||se.mkdirSync(r,{recursive:!0}),se.writeFileSync(e,JSON.stringify([...t.entries()]))}var Oo=20,jo=new Set(["css","scss","less"]);function zo(t){return bt.includes(oe.basename(t))}function Wo(t,e){if(e.length===0)return!1;let r=new Set(e);return t.split(oe.sep).some(n=>r.has(n))}async function kt(t,e,r={}){let{minLines:n=6,windowSize:s=15,ignoreLiterals:o=!0,maxPunctuationRatio:i=.5,limit:a=50,ignoreDirs:c=j,parallelTokenizing:l=!0,tokenCache:p}=r,u=[...t.nodes.values()].filter(h=>!zo(h.path)&&!Wo(h.path,c)),d=$o(l,u.length);try{let h=[],k=new Map;if(await Promise.all(u.map(async y=>{if(jo.has(y.type)){let H;try{H=await Jr(oe.join(e,y.path),"utf8")}catch{return}h.push({file:y.path,source:H,fileType:y.type});return}let C=p?.get(y.path),I=C&&C.mtime===y.mtime&&C.size===y.size&&C.ignoreLiterals===o,N;if(I)N=C.tokens;else{let H;try{H=await Jr(oe.join(e,y.path),"utf8")}catch{return}N=d?await d.run({source:H,fileType:y.type,ignoreLiterals:o}):Kr(H,y.type,o),p?.set(y.path,{mtime:y.mtime,size:y.size,ignoreLiterals:o,tokens:N})}let O=Ir(y.type),gr={file:y.path,tokens:N},dr=k.get(O);dr?dr.push(gr):k.set(O,[gr])})),p){let y=new Set(u.map(C=>C.path));for(let C of p.keys())y.has(C)||p.delete(C)}let x=_r(h,n);for(let[y,C]of k)for(let I of $r(C,s,n,i))x.push({...I,family:y});return{groups:x.sort((y,C)=>C.lines-y.lines).slice(0,a)}}finally{d&&await d.destroy()}}function $o(t,e){if(t===!1)return null;let r=typeof t=="object"?t:{},n=r.minFiles??Oo;if(e<n)return null;try{return new _o({filename:oe.join(f,"duplication-worker.js"),...r.maxThreads!==void 0?{maxThreads:r.maxThreads}:{}})}catch(s){return process.stderr.write(`
|
|
8
8
|
Warning: failed to start duplicate-detection worker pool, falling back to synchronous tokenizing: ${s}
|
|
9
|
-
`),null}}import De from"path";function jo(r){let e=new Map;for(let[t,n]of r){let s=n.imports.filter(o=>o.toPath&&!o.isExternal).length;s>0&&e.set(t,s)}return e}function Wo(r,e,t){let n=new Map;for(let[s,o]of e){if(o<t)continue;let i=r.get(s);if(!i||i.category==="test"||i.category==="barrel")continue;let a=De.extname(s),c=De.basename(s,a),l=c==="index"?De.basename(De.dirname(s)):c;n.set(s,{path:s,outDegree:o,tag:`feature:${l}`})}return n}function W(r,e){let t=e?.minOutDegree??5;return Wo(r,jo(r),t)}var zo=(r,e)=>r.outDegree-e.outDegree;function $o(r,e){let t=new Map;for(let n of e.values()){let s=new Set;r.traverse(n.path,o=>(o.path!==n.path&&s.add(o.path),!0),{direction:"outgoing"}),t.set(n.path,s)}return t}function Bo(r,e,t,n){let s=new Map;for(let[o]of r){if(e.has(o))continue;let i=null;for(let a of e.values())t.get(a.path)?.has(o)&&(!i||n(a,i)<0)&&(i=a);i&&s.set(o,i.path)}return s}function Uo(r,e){let t=new Map;for(let n of r.values()){let s=n.tag.replace("feature:",""),o=[];for(let[i,a]of e)a===n.path&&o.push(i);t.set(s,{hub:n.path,outDegree:n.outDegree,files:o})}return t}function Ko(r,e,t){let n=[];for(let s of r.keys())!e.has(s)&&!t.has(s)&&n.push(s);return n}function oe(r,e){let t=e?.detectFn??W,n=e?.hubComparator??zo,s=t(r.nodes,e),o=$o(r,s),i=Bo(r.nodes,s,o,n);return{features:Uo(s,i),unassigned:Ko(r.nodes,s,i)}}var $r=new Set(["typescript","javascript","python","go","scss","less","lua","coffeescript"]),Br=new Set(["typescript","javascript","python"]),Re=new Set(["typescript","javascript","go","python"]);function yt(r){let e=new Map;for(let t of r.nodes.values())e.set(t.type,(e.get(t.type)??0)+1);return[...e.entries()].map(([t,n])=>({type:t,fileCount:n,exportsTracked:$r.has(t),importSymbolsTracked:Br.has(t),callEdgesTracked:Re.has(t)})).sort((t,n)=>n.fileCount-t.fileCount)}var ie=class{constructor(e){this.nodes=e}nodes;findUnusedFiles(e){let t=new Set(this.nodes.keys());return e.filter(n=>!t.has(n))}findHighExportUsage(e){let t=[];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);t.push({path:n.path,maxExportUsage:n.maxExportUsage,tightestDep:s?.toPath??""})}return t.sort((n,s)=>s.maxExportUsage-n.maxExportUsage)}findCycles(){let e=[],t=new Set,n=new Set,s=[],o=i=>{t.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 t.has(c.toPath)||o(c.toPath)}n.delete(i),s.pop()};for(let i of this.nodes.keys())t.has(i)||o(i);return e}};var D=class r{constructor(e){this.nodes=e}nodes;_incomingEdgesCache=null;_callIncomingCache=null;serialize(){return{nodes:Array.from(this.nodes.values())}}static deserialize(e){let t=new Map;for(let n of e.nodes)t.set(n.path,n);return new r(t)}getIncomingEdgesMap(){if(this._incomingEdgesCache)return this._incomingEdgesCache;let e=new Map;for(let t of this.nodes.values())for(let n of t.imports)if(n.toPath){let s=e.get(n.toPath)||[];s.push(t.path),e.set(n.toPath,s)}return this._incomingEdgesCache=e,e}dfs(e,t,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),t(u,l,p)!==!1))for(let d of s(c))a(d,l+1,c)};a(e,0,null)}traverse(e,t,n={}){let s=n.direction??"outgoing",o=s==="incoming"?this.getIncomingEdgesMap():null;this.dfs(e,t,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 t of this.nodes.values())for(let n of t.callEdges??[]){let s=e.get(n.toFile)??[];s.push(t.path),e.set(n.toFile,s)}return this._callIncomingCache=e,e}traverseCalls(e,t,n={}){let s=n.direction??"outgoing",o=s==="incoming"?this.getCallIncomingCache():null;this.dfs(e,t,n,i=>s==="outgoing"?this.nodes.get(i)?.callEdges?.map(a=>a.toFile)??[]:o?.get(i)??[])}getCallers(e){let t=[];return this.traverseCalls(e,n=>(n.path!==e&&t.push(n.path),!0),{direction:"incoming",maxDepth:1}),t}getCallEdgesFor(e){return this.nodes.get(e)?.callEdges??[]}getNeighbors(e){let t=this.nodes.get(e);return t?t.imports.map(n=>this.nodes.get(n.toPath)).filter(n=>n!==void 0):[]}findUnusedFiles(e){return new ie(this.nodes).findUnusedFiles(e)}findCycles(){return new ie(this.nodes).findCycles()}};var z=class{affectedSymbols=new Map;constructor(e,t){this.affectedSymbols.set(e,new Set(["default",...t]))}updateAffectedSymbols(e,t){let n=this.affectedSymbols.get(t)||new Set,s=e.imports.find(c=>c.toPath===t);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 ae(r,e){let t=r.nodes.get(e);if(t)return{category:t.category,exports:t.exports.map(n=>n.name)}}function xt(r,e,t=1){let n=[];return r.traverse(e,(s,o,i)=>{if(s.path===e)return!0;let a=i?r.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:t}),n}function ce(r,e){let t=[];return r.traverse(e,n=>{if(n.path===e)return!0;let s=n.imports.find(o=>o.toPath===e);return t.push({path:n.path,...s?.symbols?{symbols:s.symbols}:{}}),!0},{direction:"incoming",maxDepth:1}),t}function bt(r,e,t={}){let{testsOnly:n=!1,changedSymbols:s}=t,o=s?new z(e,s):null,i=[];return r.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 St(r,e,t={}){let{depth:n=1,withEdgeDetail:s=!1}=t,o=[];return r.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 kt(r,e={}){let{metric:t="cognitiveComplexity",threshold:n=10,limit:s=20}=e;return[...r.nodes.values()].flatMap(o=>(o.functions??[]).filter(i=>i[t]>=n).map(i=>({file:o.path,name:i.name,line:i.line,complexity:i.complexity,cognitiveComplexity:i.cognitiveComplexity}))).sort((o,i)=>i[t]-o[t]).slice(0,s)}function vt(r){return{nodes:r.nodes.map(t=>({path:t.path,type:t.type,category:t.category,exports:t.exports.map(n=>n.name),tags:t.tags.filter(n=>n.kind==="comment-marker"||n.kind==="import").map(n=>n.name),importsFiles:t.imports.filter(n=>!n.isExternal&&n.toPath).map(n=>n.toPath),...t.description!==void 0&&{description:t.description},...t.testedBy!==void 0&&{testedBy:t.testedBy},...t.coveragePct!==void 0&&{coveragePct:t.coveragePct},...t.avgExportUsage!==void 0&&{avgExportUsage:t.avgExportUsage},...t.maxExportUsage!==void 0&&{maxExportUsage:t.maxExportUsage}})),cycles:r.cycles}}function wt(r){let e=r.getPackageDependencies(),t=Array.from(r.packages.values()).map(({graph:n,pkg:s})=>({name:s.name,relativeRoot:s.relativeRoot,nodeCount:n.nodes.size,dependsOn:e.get(s.name)??[]}));return{monorepoType:r.type,packageCount:t.length,packages:t}}function Ct(r){return[...r.nodes.values()].some(e=>e.coveragePct!==void 0)}function Ur(r){if(r.category==="test")return"test";if(r.category==="config")return"config";if(r.category==="type-only")return"types";let e=r.path;return v(e,"component")||v(e,"components")?"component":v(e,"controller")||v(e,"controllers")?"controller":v(e,"middleware")?"middleware":v(e,"router")||v(e,"routes")||v(e,"route")?"router":v(e,"store")||v(e,"stores")?"store":v(e,"service")||v(e,"services")?"service":v(e,"handler")||v(e,"handlers")?"handler":v(e,"adapter")||v(e,"adapters")?"adapter":v(e,"plugin")||v(e,"plugins")?"plugin":v(e,"api")?"api":v(e,"cli")||v(e,"commands")||le(e)==="cli"?"cli":v(e,"util")||v(e,"utils")||v(e,"helper")||v(e,"helpers")?"util":v(e,"model")||v(e,"models")||le(e)==="model"?"model":v(e,"parser")||v(e,"parsers")||le(e)==="parser"?"parser":le(e)==="builder"?"builder":le(e)==="resolver"?"resolver":"other"}function v(r,e){return r.includes(`/${e}/`)||r.includes(`/${e}.`)}function le(r){let e=r.slice(r.lastIndexOf("/")+1);return e.slice(0,e.lastIndexOf("."))||e}function Ft(r,e){let t=oe(r,e),n=new Map;for(let[o,i]of t.features){for(let a of i.files)n.set(a,o);n.set(i.hub,o)}let s=new Map;for(let o of r.nodes.values()){let i=n.get(o.path);s.set(o.path,{path:o.path,role:Ur(o),...o.description?{description:o.description}:{},exports:o.exports.map(a=>a.name),...i?{featureHub:i}:{}})}return s}function Tt(r,e){let t=[];for(let n of r.nodes.values())if(n.exports.some(s=>s.name===e))if(Re.has(n.type)){let s=[];for(let o of r.nodes.values())for(let i of o.callEdges??[])i.to===e&&s.push({file:o.path,callerFunction:i.from});t.push({path:n.path,category:n.category,precision:"call",callers:s})}else{let s=ce(r,n.path).map(o=>({file:o.path,...o.symbols?{symbols:o.symbols}:{}}));t.push({path:n.path,category:n.category,precision:"file-level",importers:s})}return t}function Jo(r){return r?r.startsWith("interface ")?"interface":r.startsWith("class ")?"class":r.startsWith("enum ")?"enum":"type":"type"}function Vo(r,e){if(e==="type-only")return!0;let t=r.signature??"";return t.startsWith("interface ")||t.startsWith("class ")||t.startsWith("enum ")}function Et(r){let e=new Map;for(let n of r.nodes.values())if(!(n.type!=="typescript"&&n.type!=="javascript"))for(let s of n.exports){if(!Vo(s,n.category))continue;let o=`${n.path}::${s.name}`;e.set(o,{name:s.name,file:n.path,kind:Jo(s.signature),...s.doc?{doc:s.doc}:{}})}let t=[];for(let n of r.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}`)&&t.push({fromFile:n.path,toType:o,toFile:s.toPath})}return{types:e,edges:t}}function Pt(r,e){let t=null;for(let o of r.types.values())if(o.name===e){t=o;break}if(!t)return{type:null,usedByFiles:[],uses:[]};let n=new Set,s=new Map;for(let o of r.edges)if(o.toType===e&&o.toFile===t.file&&n.add(o.fromFile),o.fromFile===t.file){let i=r.types.get(`${o.toFile}::${o.toType}`);i&&s.set(`${i.file}::${i.name}`,i)}return{type:t,usedByFiles:Array.from(n),uses:Array.from(s.values())}}import oi from"path";import Nt from"fs";import Hr from"path";import pe from"fs";import P from"path";import Kr from"fs";import Yp from"path";function Jr(r){try{return Kr.statSync(r,{throwIfNoEntry:!1})?.isDirectory()===!0}catch{return!1}}function Le(r){try{return Kr.statSync(r,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}function At(r,e){let t=P.join(e,"package.json");if(!pe.existsSync(t))return null;let n={};try{n=JSON.parse(pe.readFileSync(t,"utf-8"))}catch{return null}let s=n.name;return s?{name:s,root:e,relativeRoot:P.relative(r,e),entryPoints:Ho(e,n)}:null}function Ho(r,e){let t=[];if(e.exports){let s=e.exports;if(typeof s=="string")t.push(P.join(r,s));else if(typeof s=="object"&&s!==null){let o=s["."];if(typeof o=="string")t.push(P.join(r,o));else if(typeof o=="object"&&o!==null){let i=o.import??o.require??o.default;typeof i=="string"&&t.push(P.join(r,i))}}}e.main&&t.push(P.join(r,e.main));for(let s of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"])t.push(P.join(r,s));let n=t.filter(Le);return n.length>0?n.slice(0,1):t.slice(0,1)}function Q(r,e){let t=[],n=new Set;for(let s of e){let o=s.replace(/\/$/,"").replace(/^\.\//,"");Qo(r,o,n,t)}return t}function Qo(r,e,t,n){if(!e.includes("*")){qo(r,e,t,n);return}let s=e.split("/");s.includes("**")?Yo(r,s,t,n):Xo(r,s,t,n)}function qo(r,e,t,n){let s=P.join(r,e);if(t.has(s)||!Jr(s))return;t.add(s);let o=At(r,s);o&&n.push(o)}function Yo(r,e,t,n){let s=P.join(r,e[0]==="**"?"":e[0]??"");Vr(r,s,t,n)}function Xo(r,e,t,n){let s=e.findIndex(a=>a.includes("*")),o=P.join(r,...e.slice(0,s)),i;try{i=pe.readdirSync(o,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let c=P.join(o,a.name);if(t.has(c))continue;t.add(c);let l=At(r,c);l&&n.push(l)}}function Vr(r,e,t,n){let s;try{s=pe.readdirSync(e,{withFileTypes:!0})}catch{return}for(let o of s){if(!o.isDirectory()||o.name==="node_modules"||o.name.startsWith("."))continue;let i=P.join(e,o.name);if(pe.existsSync(P.join(i,"package.json"))&&!t.has(i)){t.add(i);let a=At(r,i);a&&n.push(a)}else Vr(r,i,t,n)}}var Qr={type:"npm",detect(r){let e=Hr.join(r,"package.json");if(!Nt.existsSync(e))return null;let t;try{t=JSON.parse(Nt.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!t||Nt.existsSync(Hr.join(r,"yarn.lock")))return null;let n=Array.isArray(t)?t:t.packages??[];return n.length===0?null:Q(r,n)}};import q from"fs";import T from"path";var qr={type:"nx",detect(r){return q.existsSync(T.join(r,"nx.json"))?Yr(r,r,new Set,0).map(t=>Zo(r,t,T.join(t,"project.json"))).filter(t=>t!==null):null}};function Yr(r,e,t,n){if(n>4)return[];let s;try{s=q.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=T.join(e,a);q.existsSync(T.join(c,"project.json"))&&!t.has(c)?(t.add(c),o.push(c)):o.push(...Yr(r,c,t,n+1))}return o}function Zo(r,e,t){let n={};try{n=JSON.parse(q.readFileSync(t,"utf-8"))}catch{return null}let s=n.name,o,i,a=T.join(e,"package.json");if(q.existsSync(a))try{let c=JSON.parse(q.readFileSync(a,"utf-8"));s=c.name??s,o=c.main,i=c.exports}catch{}return s?{name:s,root:e,relativeRoot:T.relative(r,e),entryPoints:ei(e,n,o,i)}:null}function ei(r,e,t,n){let s=[],o=e.targets?.build?.options?.main??e.targets?.build?.options?.entryFile;if(o){let a=T.resolve(r,"../..");s.push(T.resolve(a,o)),s.push(T.resolve(r,o))}if(n){let a=n;if(typeof a=="string")s.push(T.join(r,a));else if(typeof a=="object"&&a!==null){let c=a["."];typeof c=="string"&&s.push(T.join(r,c))}}if(t&&s.push(T.join(r,t)),e.sourceRoot){let a=T.resolve(r,"../.."),c=T.resolve(a,e.sourceRoot);s.push(T.join(c,"index.ts"),T.join(c,"index.tsx"))}for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx"])s.push(T.join(r,a));let i=s.filter(Le);return i.length>0?i.slice(0,1):s.slice(0,1)}import Xr from"fs";import ti from"path";import{load as ri}from"js-yaml";var Zr={type:"pnpm",detect(r){let e=ti.join(r,"pnpm-workspace.yaml");if(!Xr.existsSync(e))return null;let t=[];try{t=ri(Xr.readFileSync(e,"utf-8"))?.packages??[]}catch{return null}return Q(r,t)}};import ni from"fs";import si from"path";var en={type:"turborepo",detect(r){return ni.existsSync(si.join(r,"turbo.json"))?[]:null}};import It from"fs";import tn from"path";var rn={type:"yarn",detect(r){if(!It.existsSync(tn.join(r,"yarn.lock")))return null;let e=tn.join(r,"package.json");if(!It.existsSync(e))return null;let t;try{t=JSON.parse(It.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!t)return null;let n=Array.isArray(t)?t:t.packages??[];return n.length===0?null:Q(r,n)}};var nn=[];function R(r){nn.push(r)}function sn(){return nn}R(en);R(qr);R(Zr);R(rn);R(Qr);function ue(r,e=sn()){let t=oi.resolve(r),n=new Map,s=[];for(let i of e){let a=i.detect(t);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:t,type:"none",types:[],packages:[],packageMap:new Map};let o=Array.from(n.values());return{root:t,type:s[0],types:s,packages:o,packageMap:new Map(o.map(i=>[i.name,i]))}}var fe=class r{constructor(e,t){this.monorepoRoot=e;this.type=t}monorepoRoot;type;packages=new Map;addPackage(e,t){this.packages.set(e.name,{graph:t,pkg:e})}getPackageForFile(e){for(let{pkg:t}of this.packages.values())if(e===t.relativeRoot||e.startsWith(`${t.relativeRoot}/`))return t}getPackageDependencies(){let e=new Map;for(let{graph:t,pkg:n}of this.packages.values()){let s=new Set;for(let o of t.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 t=this.getPackageForFile(e);if(!t)return[];let n=this.packages.get(t.name);if(!n)return[];let s=[];n.graph.traverse(e,o=>(o.path!==e&&s.push({file:o.path,package:t.name}),!0),{direction:"incoming"});for(let{graph:o,pkg:i}of this.packages.values())if(i.name!==t.name)for(let a of o.nodes.values())a.imports.some(l=>l.isWorkspace&&l.workspacePackage===t.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:t})=>({pkg:{name:t.name,relativeRoot:t.relativeRoot,entryPoints:t.entryPoints},nodes:Array.from(e.nodes.values())}))}}static deserialize(e){let t=new r(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 D(o);t.packages.set(n.name,{graph:i,pkg:{...n,root:""}})}return t}};var on=new Map;function Y(r,e){on.set(r,e)}function an(r){return on.get(r)}function cn(r,e){return e.startsWith("!")?r!==e.slice(1):r===e}function ii(r,e){return e.startsWith("!")?!r.includes(e.slice(1)):r.includes(e)}var ai=(r,e)=>!e.category||cn(r.category,e.category),ci=(r,e)=>!e.type||cn(r.type,e.type),li=(r,e)=>e.lastAuthor?e.lastAuthor.startsWith("!")?r.lastAuthor!==e.lastAuthor.slice(1):r.lastAuthor!==void 0&&r.lastAuthor===e.lastAuthor:!0,pi=(r,e)=>!e.path||ii(r.path,e.path),ui=(r,e)=>e.isExternal===void 0?!0:r.imports.some(n=>n.isExternal)===e.isExternal,fi=(r,e)=>{if(!e.tags||e.tags.length===0)return!0;let t=e.tags.filter(s=>!s.startsWith("!")),n=e.tags.filter(s=>s.startsWith("!")).map(s=>s.slice(1));return!(t.length>0&&!t.some(s=>r.tags.some(o=>o.name===s))||n.some(s=>r.tags.some(o=>o.name===s)))},mi=(r,e)=>!e.allTags?.length||e.allTags.every(t=>r.tags.some(n=>n.name===t)),gi=(r,e)=>!e.importsFile||r.imports.some(t=>t.toPath?.includes(e.importsFile)),di=(r,e,t)=>e.importedBy===void 0?!0:(t?.get(r.path)??[]).some(s=>s.includes(e.importedBy)),hi=(r,e)=>e.minImports===void 0||r.imports.length>=e.minImports,yi=(r,e)=>e.maxImports===void 0||r.imports.length<=e.maxImports,xi=(r,e)=>e.minSize===void 0||r.size>=e.minSize,bi=(r,e)=>e.maxSize===void 0||r.size<=e.maxSize,Si=(r,e)=>e.hasDocstring===void 0||!!r.description===e.hasDocstring,ki=(r,e)=>e.isDocumented===void 0||!!r.documentedBy?.length===e.isDocumented,vi=(r,e)=>e.isStale===void 0||!!r.staleFor?.length===e.isStale,wi=(r,e)=>e.minCoverage===void 0||(r.coveragePct??101)>=e.minCoverage,Ci=(r,e)=>e.maxCoverage===void 0||(r.coveragePct??0)<=e.maxCoverage,Fi=(r,e)=>e.minExportUsage===void 0||(r.avgExportUsage??-1)>=e.minExportUsage,Ti=(r,e)=>e.maxExportUsage===void 0||(r.avgExportUsage??0)<=e.maxExportUsage,Ei=(r,e)=>e.minComplexity===void 0||(r.complexity??-1/0)>=e.minComplexity,Pi=(r,e)=>e.maxComplexity===void 0||(r.complexity??0)<=e.maxComplexity,Ai=(r,e)=>e.minCognitiveComplexity===void 0||(r.cognitiveComplexity??-1/0)>=e.minCognitiveComplexity,Ni=(r,e)=>e.maxCognitiveComplexity===void 0||(r.cognitiveComplexity??0)<=e.maxCognitiveComplexity,Ii=(r,e)=>e.minCommits===void 0||(r.commitCount90d??-1/0)>=e.minCommits,Mi=(r,e)=>e.maxCommits===void 0||(r.commitCount90d??0)<=e.maxCommits,Di=(r,e,t)=>!e.any?.length||e.any.some(n=>me(r,n,t)),Ri=[ai,ci,li,pi,ui,fi,mi,gi,di,hi,yi,xi,bi,Si,ki,vi,wi,Ci,Fi,Ti,Ei,Pi,Ai,Ni,Ii,Mi,Di];function me(r,e,t){return Ri.every(n=>n(r,e,t))}function Ge(r,e){let t=new Map;if(e.importedBy!==void 0){for(let i of r.nodes)for(let a of i.imports)if(a.toPath){let c=t.get(a.toPath)??[];c.push(i.path),t.set(a.toPath,c)}}let n=r.nodes.filter(i=>me(i,e,t)),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;return e.sort==="size"?l=c.size-a.size:e.sort==="imports"?l=c.imports.length-a.imports.length:e.sort==="commitCount90d"?l=(c.commitCount90d??0)-(a.commitCount90d??0):e.sort==="exportUsage"?l=(c.avgExportUsage??0)-(a.avgExportUsage??0):e.sort==="complexity"?l=(c.complexity??0)-(a.complexity??0):e.sort==="cognitiveComplexity"&&(l=(c.cognitiveComplexity??0)-(a.cognitiveComplexity??0)),l*i})}return e.limit!==void 0&&o.splice(e.limit),{nodes:o,cycles:r.cycles?.filter(i=>i.every(a=>s.has(a)))??void 0}}function ln(r,e){let t=e.indexOf(":");if(t===-1)return;let n=e.slice(0,t).trim().toLowerCase(),s=e.slice(t+1).trim();if(!(!n||!s))switch(n){case"category":r.category=s;break;case"type":r.type=s;break;case"tag":case"tags":s.includes("+")?r.allTags=[...r.allTags??[],...s.split("+")]:r.tags=[...r.tags??[],s];break;case"path":r.path=s;break;case"external":r.isExternal=s.toLowerCase()==="true";break;case"importsfile":r.importsFile=s;break;case"importedby":r.importedBy=s;break;case"minimports":r.minImports=parseInt(s,10);break;case"maximports":r.maxImports=parseInt(s,10);break;case"minsize":r.minSize=parseInt(s,10);break;case"maxsize":r.maxSize=parseInt(s,10);break;case"sort":r.sort=s;break;case"sortdir":r.sortDir=s.toLowerCase()==="asc"?"asc":"desc";break;case"limit":r.limit=parseInt(s,10);break;case"hasdocstring":r.hasDocstring=s.toLowerCase()!=="false";break;case"mincoverage":r.minCoverage=parseInt(s,10);break;case"maxcoverage":r.maxCoverage=parseInt(s,10);break;case"minexportusage":r.minExportUsage=parseFloat(s);break;case"maxexportusage":r.maxExportUsage=parseFloat(s);break;case"mincomplexity":r.minComplexity=parseInt(s,10);break;case"maxcomplexity":r.maxComplexity=parseInt(s,10);break;case"mincognitivecomplexity":r.minCognitiveComplexity=parseInt(s,10);break;case"maxcognitivecomplexity":r.maxCognitiveComplexity=parseInt(s,10);break;case"mincommits":r.minCommits=parseInt(s,10);break;case"maxcommits":r.maxCommits=parseInt(s,10);break;case"isdocumented":r.isDocumented=s.toLowerCase()!=="false";break;case"isstale":r.isStale=s.toLowerCase()!=="false";break;case"lastauthor":r.lastAuthor=s;break}}function Li(r){let e=[];for(let t of r.split("|")){let n=t.trim();if(!n)continue;let s={};ln(s,n),Object.keys(s).length>0&&e.push(s)}return e}function _e(r){let e={},t=r.split(",");for(let n of t){let s=n.trim();if(s.toLowerCase().startsWith("any(")&&s.endsWith(")")){let o=s.slice(4,-1),i=Li(o);i.length>0&&(e.any=[...e.any??[],...i]);continue}ln(e,n)}return e}import yn from"fs/promises";import oa from"path";import Bt from"path";import Je from"typescript";import Oi from"path";import Gi from"path";import F from"typescript";var pn=new Set(["describe","test","it"]);function $(r,e){let t=r[e];if(t===void 0)throw new Error(`Index ${e} out of bounds (length ${r.length})`);return t}function Mt(r){let e=[];for(let t of r.statements){if(!F.isExpressionStatement(t))continue;let n=t.expression;if(!F.isCallExpression(n))continue;let s=n.expression;F.isIdentifier(s)&&pn.has(s.text)&&e.push(n),F.isPropertyAccessExpression(s)&&F.isIdentifier(s.expression)&&pn.has(s.expression.text)&&e.push(n)}return e}function Dt(r,e,t){for(let n of r.arguments){if(!F.isObjectLiteralExpression(n))continue;let s=n.properties.find(o=>F.isPropertyAssignment(o)&&F.isIdentifier(o.name)&&o.name.text===e);if(!(!s||!F.isArrayLiteralExpression(s.initializer)))return s.initializer.elements.filter(F.isStringLiteral).map(o=>o.text)}return null}function Rt(r,e,t,n){if(r.arguments.length===0)return null;for(let o=1;o<r.arguments.length;o++){let i=$(r.arguments,o);if(!F.isObjectLiteralExpression(i))continue;let a=i.properties.find(l=>F.isPropertyAssignment(l)&&F.isIdentifier(l.name)&&l.name.text===e);if(a)return{start:a.initializer.getStart(n),end:a.initializer.getEnd(),text:t};let c=i.getEnd()-1;return{start:c,end:c,text:`${i.properties.length>0?", ":""}${e}: ${t}`}}let s=$(r.arguments,r.arguments.length-1);return{start:s.getStart(n),end:s.getStart(n),text:`{ ${e}: ${t} }, `}}function Lt(r,e,t){let n=r.arguments;for(let s=1;s<n.length;s++){let o=$(n,s);if(!F.isObjectLiteralExpression(o))continue;let i=o.properties.findIndex(c=>F.isPropertyAssignment(c)&&F.isIdentifier(c.name)&&c.name.text===e);if(i<0)continue;if(o.properties.length===1)return{start:$(n,s-1).getEnd(),end:o.getEnd(),text:""};let a=$(o.properties,i);return i===o.properties.length-1?{start:$(o.properties,i-1).getEnd(),end:a.getEnd(),text:""}:{start:a.getStart(t),end:$(o.properties,i+1).getStart(t),text:""}}return null}function Gt(r,e){let t=[...e].sort((s,o)=>o.start-s.start),n=r;for(let s of t)n=n.slice(0,s.start)+s.text+n.slice(s.end);return n}function _t(r){return`[${r.map(e=>JSON.stringify(e)).join(", ")}]`}var M=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);function _i(r){return r.map(e=>e.startsWith("@")?e.slice(1):e)}function Oe(r,e,t,n){let s=F.createSourceFile(Gi.basename(r),e,F.ScriptTarget.Latest,!0),o=Mt(s),[i]=o;if(!i)return e;let a=Dt(i,n,s),c=[...t].sort();if(a!==null&&JSON.stringify(_i(a).sort())===JSON.stringify(c))return e;let l=_t(c.map(u=>`@${u}`)),p=o.flatMap(u=>{let d=t.length===0?Lt(u,n,s):Rt(u,n,l,s);return d?[d]:[]});return p.length>0?Gt(e,p):e}var je=class{name="cypress";canHandle(e){return M.has(Oi.extname(e).toLowerCase())}apply(e,t,n){return Oe(e,t,n,"tags")}};import ji from"path";var Ot=/# <mokosh-tags>[\s\S]*?# <\/mokosh-tags>\n*/,jt=/^@([a-zA-Z0-9_-]+)/gm;function Wi(r){return`${["# <mokosh-tags>",...r.map(e=>`@${e}`),"# </mokosh-tags>"].join(`
|
|
9
|
+
`),null}}import Ge from"path";function Bo(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 Uo(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=Ge.extname(s),c=Ge.basename(s,a),l=c==="index"?Ge.basename(Ge.dirname(s)):c;n.set(s,{path:s,outDegree:o,tag:`feature:${l}`})}return n}function z(t,e){let r=e?.minOutDegree??5;return Uo(t,Bo(t),r)}var Ko=(t,e)=>t.outDegree-e.outDegree;function Jo(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 Ho(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 Vo(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 Qo(t,e,r){let n=[];for(let s of t.keys())!e.has(s)&&!r.has(s)&&n.push(s);return n}function ie(t,e){let r=e?.detectFn??z,n=e?.hubComparator??Ko,s=r(t.nodes,e),o=Jo(t,s),i=Ho(t.nodes,s,o,n);return{features:Vo(s,i),unassigned:Qo(t.nodes,s,i)}}var Hr=new Set(["typescript","javascript","python","go","scss","less","lua","coffeescript"]),Vr=new Set(["typescript","javascript","python"]),_e=new Set(["typescript","javascript","go","python"]);function vt(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:Hr.has(r),importSymbolsTracked:Vr.has(r),callEdgesTracked:_e.has(r)})).sort((r,n)=>n.fileCount-r.fileCount)}var ae=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 M=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 d of s(c))a(d,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 ae(this.nodes).findUnusedFiles(e)}findCycles(){return new ae(this.nodes).findCycles()}};var W=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 ce(t,e){let r=t.nodes.get(e);if(r)return{category:r.category,exports:r.exports.map(n=>n.name)}}function Ct(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 le(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 wt(t,e,r={}){let{testsOnly:n=!1,changedSymbols:s}=r,o=s?new W(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 Ft(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 Tt(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 Et(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 At(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 Pt(t){return[...t.nodes.values()].some(e=>e.coveragePct!==void 0)}function Qr(t){if(t.category==="test")return"test";if(t.category==="config")return"config";if(t.category==="type-only")return"types";let e=t.path;return v(e,"component")||v(e,"components")?"component":v(e,"controller")||v(e,"controllers")?"controller":v(e,"middleware")?"middleware":v(e,"router")||v(e,"routes")||v(e,"route")?"router":v(e,"store")||v(e,"stores")?"store":v(e,"service")||v(e,"services")?"service":v(e,"handler")||v(e,"handlers")?"handler":v(e,"adapter")||v(e,"adapters")?"adapter":v(e,"plugin")||v(e,"plugins")?"plugin":v(e,"api")?"api":v(e,"cli")||v(e,"commands")||pe(e)==="cli"?"cli":v(e,"util")||v(e,"utils")||v(e,"helper")||v(e,"helpers")?"util":v(e,"model")||v(e,"models")||pe(e)==="model"?"model":v(e,"parser")||v(e,"parsers")||pe(e)==="parser"?"parser":pe(e)==="builder"?"builder":pe(e)==="resolver"?"resolver":"other"}function v(t,e){return t.includes(`/${e}/`)||t.includes(`/${e}.`)}function pe(t){let e=t.slice(t.lastIndexOf("/")+1);return e.slice(0,e.lastIndexOf("."))||e}function Nt(t,e){let r=ie(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:Qr(o),...o.description?{description:o.description}:{},exports:o.exports.map(a=>a.name),...i?{featureHub:i}:{}})}return s}function It(t,e){let r=[];for(let n of t.nodes.values())if(n.exports.some(s=>s.name===e))if(_e.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=le(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 qo(t){return t?t.startsWith("interface ")?"interface":t.startsWith("class ")?"class":t.startsWith("enum ")?"enum":"type":"type"}function Yo(t,e){if(e==="type-only")return!0;let r=t.signature??"";return r.startsWith("interface ")||r.startsWith("class ")||r.startsWith("enum ")}function Dt(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(!Yo(s,n.category))continue;let o=`${n.path}::${s.name}`;e.set(o,{name:s.name,file:n.path,kind:qo(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 Mt(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 li from"path";import Lt from"fs";import Zr from"path";import ue from"fs";import A from"path";import qr from"fs";import fu from"path";function Yr(t){try{return qr.statSync(t,{throwIfNoEntry:!1})?.isDirectory()===!0}catch{return!1}}function Oe(t){try{return qr.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}function Rt(t,e){let r=A.join(e,"package.json");if(!ue.existsSync(r))return null;let n={};try{n=JSON.parse(ue.readFileSync(r,"utf-8"))}catch{return null}let s=n.name;return s?{name:s,root:e,relativeRoot:A.relative(t,e),entryPoints:Xo(e,n)}:null}function Xo(t,e){let r=[];if(e.exports){let s=e.exports;if(typeof s=="string")r.push(A.join(t,s));else if(typeof s=="object"&&s!==null){let o=s["."];if(typeof o=="string")r.push(A.join(t,o));else if(typeof o=="object"&&o!==null){let i=o.import??o.require??o.default;typeof i=="string"&&r.push(A.join(t,i))}}}e.main&&r.push(A.join(t,e.main));for(let s of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"])r.push(A.join(t,s));let n=r.filter(Oe);return n.length>0?n.slice(0,1):r.slice(0,1)}function Q(t,e){let r=[],n=new Set;for(let s of e){let o=s.replace(/\/$/,"").replace(/^\.\//,"");Zo(t,o,n,r)}return r}function Zo(t,e,r,n){if(!e.includes("*")){ei(t,e,r,n);return}let s=e.split("/");s.includes("**")?ti(t,s,r,n):ri(t,s,r,n)}function ei(t,e,r,n){let s=A.join(t,e);if(r.has(s)||!Yr(s))return;r.add(s);let o=Rt(t,s);o&&n.push(o)}function ti(t,e,r,n){let s=A.join(t,e[0]==="**"?"":e[0]??"");Xr(t,s,r,n)}function ri(t,e,r,n){let s=e.findIndex(a=>a.includes("*")),o=A.join(t,...e.slice(0,s)),i;try{i=ue.readdirSync(o,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let c=A.join(o,a.name);if(r.has(c))continue;r.add(c);let l=Rt(t,c);l&&n.push(l)}}function Xr(t,e,r,n){let s;try{s=ue.readdirSync(e,{withFileTypes:!0})}catch{return}for(let o of s){if(!o.isDirectory()||o.name==="node_modules"||o.name.startsWith("."))continue;let i=A.join(e,o.name);if(ue.existsSync(A.join(i,"package.json"))&&!r.has(i)){r.add(i);let a=Rt(t,i);a&&n.push(a)}else Xr(t,i,r,n)}}var en={type:"npm",detect(t){let e=Zr.join(t,"package.json");if(!Lt.existsSync(e))return null;let r;try{r=JSON.parse(Lt.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!r||Lt.existsSync(Zr.join(t,"yarn.lock")))return null;let n=Array.isArray(r)?r:r.packages??[];return n.length===0?null:Q(t,n)}};import q from"fs";import T from"path";var tn={type:"nx",detect(t){return q.existsSync(T.join(t,"nx.json"))?rn(t,t,new Set,0).map(r=>ni(t,r,T.join(r,"project.json"))).filter(r=>r!==null):null}};function rn(t,e,r,n){if(n>4)return[];let s;try{s=q.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=T.join(e,a);q.existsSync(T.join(c,"project.json"))&&!r.has(c)?(r.add(c),o.push(c)):o.push(...rn(t,c,r,n+1))}return o}function ni(t,e,r){let n={};try{n=JSON.parse(q.readFileSync(r,"utf-8"))}catch{return null}let s=n.name,o,i,a=T.join(e,"package.json");if(q.existsSync(a))try{let c=JSON.parse(q.readFileSync(a,"utf-8"));s=c.name??s,o=c.main,i=c.exports}catch{}return s?{name:s,root:e,relativeRoot:T.relative(t,e),entryPoints:si(e,n,o,i)}:null}function si(t,e,r,n){let s=[],o=e.targets?.build?.options?.main??e.targets?.build?.options?.entryFile;if(o){let a=T.resolve(t,"../..");s.push(T.resolve(a,o)),s.push(T.resolve(t,o))}if(n){let a=n;if(typeof a=="string")s.push(T.join(t,a));else if(typeof a=="object"&&a!==null){let c=a["."];typeof c=="string"&&s.push(T.join(t,c))}}if(r&&s.push(T.join(t,r)),e.sourceRoot){let a=T.resolve(t,"../.."),c=T.resolve(a,e.sourceRoot);s.push(T.join(c,"index.ts"),T.join(c,"index.tsx"))}for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx"])s.push(T.join(t,a));let i=s.filter(Oe);return i.length>0?i.slice(0,1):s.slice(0,1)}import nn from"fs";import oi from"path";import{load as ii}from"js-yaml";var sn={type:"pnpm",detect(t){let e=oi.join(t,"pnpm-workspace.yaml");if(!nn.existsSync(e))return null;let r=[];try{r=ii(nn.readFileSync(e,"utf-8"))?.packages??[]}catch{return null}return Q(t,r)}};import ai from"fs";import ci from"path";var on={type:"turborepo",detect(t){return ai.existsSync(ci.join(t,"turbo.json"))?[]:null}};import Gt from"fs";import an from"path";var cn={type:"yarn",detect(t){if(!Gt.existsSync(an.join(t,"yarn.lock")))return null;let e=an.join(t,"package.json");if(!Gt.existsSync(e))return null;let r;try{r=JSON.parse(Gt.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:Q(t,n)}};var ln=[];function L(t){ln.push(t)}function pn(){return ln}L(on);L(tn);L(sn);L(cn);L(en);function fe(t,e=pn()){let r=li.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 me=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})}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 M(o);r.packages.set(n.name,{graph:i,pkg:{...n,root:""}})}return r}};var un=new Map;function Y(t,e){un.set(t,e)}function fn(t){return un.get(t)}function mn(t,e){return e.startsWith("!")?t!==e.slice(1):t===e}function pi(t,e){return e.startsWith("!")?!t.includes(e.slice(1)):t.includes(e)}var ui=(t,e)=>!e.category||mn(t.category,e.category),fi=(t,e)=>!e.type||mn(t.type,e.type),mi=(t,e)=>e.lastAuthor?e.lastAuthor.startsWith("!")?t.lastAuthor!==e.lastAuthor.slice(1):t.lastAuthor!==void 0&&t.lastAuthor===e.lastAuthor:!0,gi=(t,e)=>!e.path||pi(t.path,e.path),di=(t,e)=>e.isExternal===void 0?!0:t.imports.some(n=>n.isExternal)===e.isExternal,hi=(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)))},yi=(t,e)=>!e.allTags?.length||e.allTags.every(r=>t.tags.some(n=>n.name===r)),xi=(t,e)=>!e.importsFile||t.imports.some(r=>r.toPath?.includes(e.importsFile)),bi=(t,e,r)=>e.importedBy===void 0?!0:(r?.get(t.path)??[]).some(s=>s.includes(e.importedBy)),Si=(t,e)=>e.minImports===void 0||t.imports.length>=e.minImports,ki=(t,e)=>e.maxImports===void 0||t.imports.length<=e.maxImports,vi=(t,e)=>e.minSize===void 0||t.size>=e.minSize,Ci=(t,e)=>e.maxSize===void 0||t.size<=e.maxSize,wi=(t,e)=>e.hasDocstring===void 0||!!t.description===e.hasDocstring,Fi=(t,e)=>e.isDocumented===void 0||!!t.documentedBy?.length===e.isDocumented,Ti=(t,e)=>e.isStale===void 0||!!t.staleFor?.length===e.isStale,Ei=(t,e)=>e.minCoverage===void 0||(t.coveragePct??101)>=e.minCoverage,Ai=(t,e)=>e.maxCoverage===void 0||(t.coveragePct??0)<=e.maxCoverage,Pi=(t,e)=>e.minExportUsage===void 0||(t.avgExportUsage??-1)>=e.minExportUsage,Ni=(t,e)=>e.maxExportUsage===void 0||(t.avgExportUsage??0)<=e.maxExportUsage,Ii=(t,e)=>e.minComplexity===void 0||(t.complexity??-1/0)>=e.minComplexity,Di=(t,e)=>e.maxComplexity===void 0||(t.complexity??0)<=e.maxComplexity,Mi=(t,e)=>e.minCognitiveComplexity===void 0||(t.cognitiveComplexity??-1/0)>=e.minCognitiveComplexity,Ri=(t,e)=>e.maxCognitiveComplexity===void 0||(t.cognitiveComplexity??0)<=e.maxCognitiveComplexity,Li=(t,e)=>e.minCommits===void 0||(t.commitCount90d??-1/0)>=e.minCommits,Gi=(t,e)=>e.maxCommits===void 0||(t.commitCount90d??0)<=e.maxCommits,_i=(t,e,r)=>!e.any?.length||e.any.some(n=>ge(t,n,r)),Oi=[ui,fi,mi,gi,di,hi,yi,xi,bi,Si,ki,vi,Ci,wi,Fi,Ti,Ei,Ai,Pi,Ni,Ii,Di,Mi,Ri,Li,Gi,_i];function ge(t,e,r){return Oi.every(n=>n(t,e,r))}function je(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=>ge(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;return e.sort==="size"?l=c.size-a.size:e.sort==="imports"?l=c.imports.length-a.imports.length:e.sort==="commitCount90d"?l=(c.commitCount90d??0)-(a.commitCount90d??0):e.sort==="exportUsage"?l=(c.avgExportUsage??0)-(a.avgExportUsage??0):e.sort==="complexity"?l=(c.complexity??0)-(a.complexity??0):e.sort==="cognitiveComplexity"&&(l=(c.cognitiveComplexity??0)-(a.cognitiveComplexity??0)),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}}function gn(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))switch(n){case"category":t.category=s;break;case"type":t.type=s;break;case"tag":case"tags":s.includes("+")?t.allTags=[...t.allTags??[],...s.split("+")]:t.tags=[...t.tags??[],s];break;case"path":t.path=s;break;case"external":t.isExternal=s.toLowerCase()==="true";break;case"importsfile":t.importsFile=s;break;case"importedby":t.importedBy=s;break;case"minimports":t.minImports=parseInt(s,10);break;case"maximports":t.maxImports=parseInt(s,10);break;case"minsize":t.minSize=parseInt(s,10);break;case"maxsize":t.maxSize=parseInt(s,10);break;case"sort":t.sort=s;break;case"sortdir":t.sortDir=s.toLowerCase()==="asc"?"asc":"desc";break;case"limit":t.limit=parseInt(s,10);break;case"hasdocstring":t.hasDocstring=s.toLowerCase()!=="false";break;case"mincoverage":t.minCoverage=parseInt(s,10);break;case"maxcoverage":t.maxCoverage=parseInt(s,10);break;case"minexportusage":t.minExportUsage=parseFloat(s);break;case"maxexportusage":t.maxExportUsage=parseFloat(s);break;case"mincomplexity":t.minComplexity=parseInt(s,10);break;case"maxcomplexity":t.maxComplexity=parseInt(s,10);break;case"mincognitivecomplexity":t.minCognitiveComplexity=parseInt(s,10);break;case"maxcognitivecomplexity":t.maxCognitiveComplexity=parseInt(s,10);break;case"mincommits":t.minCommits=parseInt(s,10);break;case"maxcommits":t.maxCommits=parseInt(s,10);break;case"isdocumented":t.isDocumented=s.toLowerCase()!=="false";break;case"isstale":t.isStale=s.toLowerCase()!=="false";break;case"lastauthor":t.lastAuthor=s;break}}function ji(t){let e=[];for(let r of t.split("|")){let n=r.trim();if(!n)continue;let s={};gn(s,n),Object.keys(s).length>0&&e.push(s)}return e}function ze(t){let e={},r=t.split(",");for(let n of r){let s=n.trim();if(s.toLowerCase().startsWith("any(")&&s.endsWith(")")){let o=s.slice(4,-1),i=ji(o);i.length>0&&(e.any=[...e.any??[],...i]);continue}gn(e,n)}return e}import vn from"fs/promises";import la from"path";import Vt from"path";import Qe from"typescript";import $i from"path";import zi from"path";import F from"typescript";var dn=new Set(["describe","test","it"]);function $(t,e){let r=t[e];if(r===void 0)throw new Error(`Index ${e} out of bounds (length ${t.length})`);return r}function _t(t){let e=[];for(let r of t.statements){if(!F.isExpressionStatement(r))continue;let n=r.expression;if(!F.isCallExpression(n))continue;let s=n.expression;F.isIdentifier(s)&&dn.has(s.text)&&e.push(n),F.isPropertyAccessExpression(s)&&F.isIdentifier(s.expression)&&dn.has(s.expression.text)&&e.push(n)}return e}function Ot(t,e,r){for(let n of t.arguments){if(!F.isObjectLiteralExpression(n))continue;let s=n.properties.find(o=>F.isPropertyAssignment(o)&&F.isIdentifier(o.name)&&o.name.text===e);if(!(!s||!F.isArrayLiteralExpression(s.initializer)))return s.initializer.elements.filter(F.isStringLiteral).map(o=>o.text)}return null}function jt(t,e,r,n){if(t.arguments.length===0)return null;for(let o=1;o<t.arguments.length;o++){let i=$(t.arguments,o);if(!F.isObjectLiteralExpression(i))continue;let a=i.properties.find(l=>F.isPropertyAssignment(l)&&F.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=$(t.arguments,t.arguments.length-1);return{start:s.getStart(n),end:s.getStart(n),text:`{ ${e}: ${r} }, `}}function zt(t,e,r){let n=t.arguments;for(let s=1;s<n.length;s++){let o=$(n,s);if(!F.isObjectLiteralExpression(o))continue;let i=o.properties.findIndex(c=>F.isPropertyAssignment(c)&&F.isIdentifier(c.name)&&c.name.text===e);if(i<0)continue;if(o.properties.length===1)return{start:$(n,s-1).getEnd(),end:o.getEnd(),text:""};let a=$(o.properties,i);return i===o.properties.length-1?{start:$(o.properties,i-1).getEnd(),end:a.getEnd(),text:""}:{start:a.getStart(r),end:$(o.properties,i+1).getStart(r),text:""}}return null}function Wt(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 $t(t){return`[${t.map(e=>JSON.stringify(e)).join(", ")}]`}var D=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);function Wi(t){return t.map(e=>e.startsWith("@")?e.slice(1):e)}function We(t,e,r,n){let s=F.createSourceFile(zi.basename(t),e,F.ScriptTarget.Latest,!0),o=_t(s),[i]=o;if(!i)return e;let a=Ot(i,n,s),c=[...r].sort();if(a!==null&&JSON.stringify(Wi(a).sort())===JSON.stringify(c))return e;let l=$t(c.map(u=>`@${u}`)),p=o.flatMap(u=>{let d=r.length===0?zt(u,n,s):jt(u,n,l,s);return d?[d]:[]});return p.length>0?Wt(e,p):e}var $e=class{name="cypress";canHandle(e){return D.has($i.extname(e).toLowerCase())}apply(e,r,n){return We(e,r,n,"tags")}};import Bi from"path";var Bt=/# <mokosh-tags>[\s\S]*?# <\/mokosh-tags>\n*/,Ut=/^@([a-zA-Z0-9_-]+)/gm;function Ui(t){return`${["# <mokosh-tags>",...t.map(e=>`@${e}`),"# </mokosh-tags>"].join(`
|
|
10
10
|
`)}
|
|
11
11
|
|
|
12
|
-
`}function
|
|
13
|
-
`}function
|
|
14
|
-
${
|
|
12
|
+
`}function Ki(t){let e=new Set;Ut.lastIndex=0;let r=Ut.exec(t);for(;r!==null;)r[1]&&e.add(r[1]),r=Ut.exec(t);return e}var Be=class{name="gherkin";canHandle(e){return Bi.extname(e).toLowerCase()===".feature"}apply(e,r,n){let s=r.replace(Bt,""),o=Ki(s),i=n.filter(c=>!o.has(c)),a=i.length>0?Ui(i):"";return Bt.test(r)?r.replace(Bt,a):a?r.replace(/^(Feature:)/m,`${a}$1`):r}};function hn(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 Ji from"path";var Kt=/^\/\/go:build mokosh_[^\n]+\n/m,Hi=/^package\s+\S+/m;function Vi(t){return`//go:build ${t.map(r=>`mokosh_${r}`).join(" || ")}
|
|
13
|
+
`}function Qi(t){let e=Kt.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 Ue=class{name="go";canHandle(e){return Ji.basename(e).endsWith("_test.go")}apply(e,r,n){let s=Qi(r),o=[...n].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(o))return r;if(n.length===0)return r.replace(Kt,"");let i=Vi(o);if(s!==null)return r.replace(Kt,i);let a=Hi.exec(r);if(!a)return r;let c=a.index;return`${r.slice(0,c)+i}
|
|
14
|
+
${r.slice(c)}`}};import qi from"path";var Yi=/^\/\*\*\n(?: \* @group .+\n)+ \*\/\n+/,Jt=/^ \* @group (.+)$/gm;function Xi(t){return`${["/**",...t.map(e=>` * @group ${e}`)," */"].join(`
|
|
15
15
|
`)}
|
|
16
16
|
|
|
17
|
-
`}function
|
|
17
|
+
`}function Zi(t){let e=[];Jt.lastIndex=0;let r=Jt.exec(t);for(;r!==null;)r[1]&&e.push(r[1]),r=Jt.exec(t);return e}var Ke=class{name="jest";canHandle(e){return D.has(qi.extname(e).toLowerCase())}apply(e,r,n){let s=Yi.exec(r),o=s?Zi(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:Xi(i)+a}};import ea from"path";var Je=class{name="playwright";canHandle(e){return D.has(ea.extname(e).toLowerCase())}apply(e,r,n){return We(e,r,n,"tag")}};import ta from"path";var Ht=/^pytestmark\s*=\s*.+$/m,ra=/^import pytest\s*$/m;function na(t){let e=t.map(r=>`pytest.mark.${r}`).join(", ");return t.length===1?`pytestmark = pytest.mark.${t[0]}`:`pytestmark = [${e}]`}function sa(t){let e=Ht.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 He=class{name="pytest";canHandle(e){return ta.extname(e).toLowerCase()===".py"}apply(e,r,n){let s=sa(r),o=[...n].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(o))return r;if(n.length===0)return r.replace(Ht,"").replace(/\n{3,}/g,`
|
|
18
18
|
|
|
19
|
-
`);let i=
|
|
19
|
+
`);let i=na(o);if(s!==null)return r.replace(Ht,i);let a=ra.test(r),c=oa(r),l=r.slice(0,c),p=r.slice(c),u=a?"":`import pytest
|
|
20
20
|
`,d=l.endsWith(`
|
|
21
21
|
|
|
22
22
|
`)?"":`
|
|
23
23
|
`;return`${l+d+u+i}
|
|
24
|
-
${p}`}};function
|
|
25
|
-
`),
|
|
26
|
-
`).map(o=>o.trim()).filter(o=>o!=="")}catch{return[]}});return Array.from(new Set(
|
|
27
|
-
`)){if(s.startsWith("\0")){let[,c,l]=s.slice(1).split(" ");
|
|
28
|
-
`&&t++;return t}function Sa(r,e){let t=1;function n(s){switch(s.type.name){case"IfStatement":case"ForStatement":t++;break;case"Case":{s.firstChild?.type.name==="case"&&t++;break}case"LogicOp":{let i=e.slice(s.from,s.to);(i==="&&"||i==="||")&&t++;break}}let o=s.firstChild;for(;o;)n(o),o=o.nextSibling}return n(r),t}function ka(r,e){let t=0;function n(s,o,i){let a=s.type.name;if(a==="IfStatement"){t+=i?1:1+o;let p=U(s),u=i?o:o+1,d=p[1];d&&d.type.name!=="Block"&&n(d,u,!1);let h=p.find(x=>x.type.name==="Block");h&&n(h,u,!1);let k=p.findIndex(x=>x.type.name==="else");if(k>=0){let x=p[k+1];x?.type.name==="IfStatement"?n(x,o,!0):x&&(t+=1,n(x,o+1,!1))}return}if(a==="ForStatement"||a==="SwitchStatement"||a==="SelectStatement"){t+=1+o;let p=s.firstChild;for(;p;)n(p,o+1,!1),p=p.nextSibling;return}if(a==="LogicOp"){let p=e.slice(s.from,s.to);(p==="&&"||p==="||")&&(t+=1)}if(o>0&&a==="FunctionLiteral"){t+=1+o;let p=s.firstChild;for(;p;)n(p,o+1,!1),p=p.nextSibling;return}let l=s.firstChild;for(;l;)n(l,o,!1),l=l.nextSibling}return n(r,0,!1),t}function Qe(r,e){return{complexity:Sa(r,e),cognitiveComplexity:ka(r,e)}}function Qt(r,e){let n=r.getChild("Parameters")?.getChild("Parameter"),s=n?.getChild("TypeName")??n?.getChild("PointerType")?.getChild("TypeName");return s?e.slice(s.from,s.to):void 0}function Tn(r,e){let t=[],n=r.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}=Qe(n.node,e);t.push({name:o,line:ge(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=Qt(n.node,e),a=i?`${i}.${o}`:o,{complexity:c,cognitiveComplexity:l}=Qe(n.node,e);t.push({name:a,line:ge(e,n.from),complexity:c,cognitiveComplexity:l})}}while(n.next());return t}var Ca=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/,Fa=/^\/\/go:build\s+(.+)$/,Ta=/^\/\/\s*\+build\s+(.+)$/;function Pn(r,e){let t=[],n=new Map,s=new Set,o=new Set,i=new Map,a=wa.parse(e),c=a.cursor();do switch(c.name){case"LineComment":{let y=e.slice(c.from,c.to),w=y.match(Ca);w?.[1]&&s.add(w[1]);let I=y.match(Fa);I&&En(I[1],o);let N=y.match(Ta);N&&En(N[1],o);break}case"ImportSpec":{let y=c.node.getChild("String");if(y){let I=e.slice(y.from,y.to).slice(1,-1);t.push({fromPath:r,toPath:"",rawSpecifier:I,isExternal:!0,isStyle:!1,type:"static"});let N=c.node.getChild("DefName"),O=N?e.slice(N.from,N.to):I.split("/").pop();O&&O!=="_"&&O!=="."&&i.set(O,I)}break}case"FunctionDecl":case"MethodDecl":case"TypeDecl":case"VarDecl":case"ConstDecl":{let y=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(y){let w=e.slice(y.from,y.to);w!=="_"&&/^[A-Z]/.test(w)&&!n.has(w)&&n.set(w,{name:w})}break}}while(c.next());let l=t.some(y=>y.rawSpecifier==="testing"),p=va.basename(r).endsWith("_test.go")||s.has("test")||l?"test":"logic",u=new Set([...s,...o]),{complexity:d,cognitiveComplexity:h}=Qe(a.topNode,e),k=Tn(a,e),x=p==="test"?[]:Ea(a,e,i);return{imports:t,exports:Array.from(n.values()),tags:Array.from(u).map(y=>({name:y,kind:"comment-marker"})),category:p,rawCallEdges:x,complexity:d,cognitiveComplexity:h,...k.length>0?{functions:k}:{}}}function Ea(r,e,t){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 d=e.slice(p.from,p.to),h=t.get(d);if(h){let k=e.slice(u.from,u.to);n.push({from:a,to:k,toSpecifier:h})}}}}let c=i.firstChild;for(;c;)s(c,a),c=c.nextSibling}let o=r.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=Qt(o.node,e);s(a,l?`${l}.${c}`:c)}}while(o.next());return n}function En(r,e){for(let t of r.split(/[\s,&|!()]+/)){let n=t.trim();n&&n!=="ignore"&&e.add(n)}}import Pa from"livescript";function K(r){if(r){if(typeof r.value=="string")return r.value;if(typeof r.base?.value=="string")return r.base.value}}function Aa(r){if(!r)return[];if(r.constructor?.name==="Class"){let t=K(r.title);return t?[{name:t}]:[]}if(r.constructor?.name==="Obj"&&Array.isArray(r.items))return r.items.map(t=>K(t.key)??K(t.val)).filter(t=>!!t).map(t=>({name:t}));let e=K(r);return e?[{name:e}]:[]}function Na(r){let e=r.constructor?.name||r.type;if(e==="Assign"&&r.left?.constructor?.name==="Chain"){let t=r.left,n=K(t.head),o=t.tails?.[0]?.key?.name;if(n==="module"&&o==="exports")return Aa(r.right);if(n==="exports"&&typeof o=="string")return[{name:o}];if(t.head?.verb==="out"&&typeof o=="string")return[{name:o}]}if(e==="Import"&&r.left?.verb==="out"){let t=r.right;if(t?.constructor?.name==="Obj"&&Array.isArray(t.items))return t.items.map(n=>K(n.val)??K(n.key)).filter(n=>!!n).map(n=>({name:n}))}return[]}var Ia=new Set(["first_line","first_column","last_line","last_column","line","column"]);function Ma(r,e){let t=r.constructor?.name||r.type;if(t==="Import"){let n=r.right?.value;if(typeof n=="string"){let s=G(n);return{fromPath:e,toPath:"",rawSpecifier:s,isStyle:A(s),type:"static"}}}if(t==="Chain"&&r.head?.value==="require"){let n=r.tails?.[0];if(n?.constructor?.name==="Call"||n?.type==="Call"){let s=n.args?.[0]?.value;if(typeof s=="string"){let o=G(s);return{fromPath:e,toPath:"",rawSpecifier:o,isStyle:A(o),type:"require"}}}}return null}function qt(r,e,t){if(!r||typeof r!="object")return[];let n=[],s=Ma(r,e);s&&n.push(s),t.push(...Na(r));for(let o in r){if(Ia.has(o))continue;let i=r[o];if(!(!i||typeof i!="object"))if(Array.isArray(i))for(let a of i)n.push(...qt(a,e,t));else n.push(...qt(i,e,t))}return n}function An(r,e){let t=X(e),n=Z(r,t),s=[],o=[];try{s=qt(Pa.ast(e),r,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(t).map(c=>({name:c,kind:"comment-marker"})),category:n}}import Da from"luaparse";function Ra(r,e){let t=[];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=G(i.raw))}else if(s.type==="StringCallExpression"){let i=s.argument;i?.type==="StringLiteral"&&(o=G(i.raw))}o&&t.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(r),t}function La(r){let e=new Set;for(let t of r)t.type==="LocalStatement"&&t.variables.forEach((n,s)=>{t.init[s]?.type==="TableConstructorExpression"&&e.add(n.name)});return e}function Ga(r){let e=r[r.length-1];if(e?.type!=="ReturnStatement")return[];let t=e.arguments[0];if(t?.type!=="TableConstructorExpression")return[];let n=[];for(let s of t.fields)s.type==="TableKeyString"&&n.push({name:s.key.name});return n}function _a(r){let e=r.body,t=La(e),n=Ga(e);for(let o of e)if(o.type==="FunctionDeclaration")o.identifier?.type==="MemberExpression"?o.identifier.base.type==="Identifier"&&t.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"&&t.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 Nn(r,e){let t=X(e),n=Z(r,t),s=[],o=[];try{let i=Da.parse(e);s=Ra(i,r),o=_a(i)}catch{}return{imports:s,exports:o,tags:Array.from(t).map(i=>({name:i,kind:"comment-marker"})),category:n}}var Oa=["http://","https://","mailto:","//"],ja="ts|tsx|js|jsx|mjs|cjs|py|go|lua|css|scss|less|styl|coffee|ls|feature|md|mdx|json",Wa=new RegExp(`(?:\\.{1,2}/)?[\\w.-]+(?:/[\\w.-]+)*\\.(?:${ja})\\b`,"g"),In;async function za(){return In??=(async()=>{let{unified:r}=await import("unified"),e=(await import("remark-parse")).default;return r().use(e)})(),In}function $a(r){let e=r.trim();return e.length===0||e.startsWith("#")||Oa.some(t=>e.startsWith(t))}function Ba(r,e){let t=r.match(Wa);return t?t.map(n=>({fromPath:e,toPath:"",rawSpecifier:n,isStyle:!1,type:"static"})):[]}function Mn(r,e,t){if(r.type==="link"&&typeof r.url=="string"&&!$a(r.url)&&t.push({fromPath:e,toPath:"",rawSpecifier:r.url,isStyle:!1,type:"static"}),(r.type==="code"||r.type==="inlineCode")&&typeof r.value=="string"&&t.push(...Ba(r.value,e)),Array.isArray(r.children))for(let n of r.children)Mn(n,e,t)}async function Dn(r,e){let n=(await za()).parse(e),s=[];Mn(n,r,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 Ja from"path";import{parser as Va}from"@lezer/python";function Ua(r){let e=1;function t(n){switch(n.type.name){case"IfStatement":{e+=U(n).filter(o=>o.type.name==="if"||o.type.name==="elif").length;break}case"TryStatement":{e+=U(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;)t(s),s=s.nextSibling}return t(r),e}function Ka(r){let e=0;function t(n,s){let o=n.type.name;if(o==="IfStatement"){let c=U(n),l=0,p=0;for(;p<c.length;){let u=c[p];if(u?.type.name==="if"||u?.type.name==="elif"){let d=l>0;e+=d?1:1+s;let h=d?s:s+1,k=c[p+1],x=c[p+2];k&&t(k,h),x&&t(x,h),l++,p+=3}else if(u?.type.name==="else"){e+=1;let d=c[p+1];d&&t(d,s+1),p+=2}else p++}return}if(o==="TryStatement"){let c=U(n),l=0;for(;l<c.length;){let p=c[l];if(p?.type.name==="except"){for(e+=1+s,l++;l<c.length&&c[l]?.type.name!=="Body";)t(c[l],s),l++;l<c.length&&(t(c[l],s),l++)}else p?.type.name==="Body"&&t(p,s),l++}return}if(o==="ForStatement"||o==="WhileStatement"){e+=1+s;let c=n.firstChild;for(;c;)t(c,s+1),c=c.nextSibling;return}if((o==="ConditionalExpression"||o==="and"||o==="or")&&(e+=1),s>0&&(o==="FunctionDefinition"||o==="LambdaExpression")){e+=1+s;let c=n.firstChild;for(;c;)t(c,s+1),c=c.nextSibling;return}let a=n.firstChild;for(;a;)t(a,s),a=a.nextSibling}return t(r,0),e}function Yt(r){return{complexity:Ua(r),cognitiveComplexity:Ka(r)}}function Rn(r,e){let t=[];function n(i,a){let{complexity:c,cognitiveComplexity:l}=Yt(i);t.push({name:a,line:ge(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"),d=u?e.slice(u.from,u.to):void 0;d&&n(p,c?`${c}.${d}`:d),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(r.topNode),t}var Ha=new Set(["pytest","unittest","nose","hypothesis"]);function Ln(r,e){let t=[],n=[],s=new Set,o=Ja.basename(r).toLowerCase(),i=Va.parse(e),a=i.cursor();do switch(a.name){case"Comment":{let h=e.slice(a.from,a.to).match(/#\s*@tag\s+([a-zA-Z0-9_-]+)/);h?.[1]&&s.add(h[1]);break}case"ImportStatement":{for(let h of Qa(a.node,e,r))t.push(h);break}case"FunctionDefinition":case"ClassDefinition":{let h=a.node.parent;if(h?.name==="Script"||h?.name==="DecoratedStatement"&&h.parent?.name==="Script"){let x=a.node.getChild("VariableName");x&&n.push({name:e.slice(x.from,x.to)})}break}case"AssignStatement":{if(a.node.parent?.name==="Script"){let h=a.node.firstChild;h?.name==="VariableName"&&n.push({name:e.slice(h.from,h.to)})}break}}while(a.next());let c=tc(o,t,s);c==="test"&&s.add("test");let{complexity:l,cognitiveComplexity:p}=Yt(i.topNode),u=Rn(i,e),d=c==="test"?[]:ec(i,e);return{imports:t,exports:n,tags:Array.from(s).map(h=>({name:h,kind:"comment-marker"})),category:c,rawCallEdges:d,complexity:l,cognitiveComplexity:p,...u.length>0?{functions:u}:{}}}function Qa(r,e,t){let n=r.firstChild;return n?n.name==="from"?qa(r,e,t):Ya(r,e,t):[]}function qa(r,e,t){let n=r.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=Xa(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[de(t,o,i,!0)];let l=a===1?"./":"../".repeat(a-1);return c?[de(t,l+c.replace(/\./g,"/"),i,!1)]:i[0]==="*"?[de(t,l.slice(0,-1),["*"],!1)]:i.map(p=>de(t,l+p,[p],!1))}function Ya(r,e,t){let n=[],s=r.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(de(t,o,["*"],!0))}s=s.nextSibling}return n}function Xa(r,e){let t=[],n=r;for(;n;)n.name==="*"?t.push("*"):n.name==="VariableName"&&(t.push(e.slice(n.from,n.to)),n.nextSibling?.name==="as"&&(n=n.nextSibling.nextSibling??n.nextSibling)),n=n.nextSibling;return t}function Za(r,e){let t=new Map,n=r.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 d=e.slice(u.from,u.to),h=d;if(u.nextSibling?.type.name==="as"){let x=u.nextSibling.nextSibling;x?.type.name==="VariableName"&&(h=e.slice(x.from,x.to),u=x)}let k=c===0?a:l?p+l.replace(/\./g,"/"):p+d;t.set(h,k)}u=u.nextSibling}}while(n.next());return t}function ec(r,e){let t=Za(r,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),d=t.get(u);d&&n.push({from:c,to:u,toSpecifier:d})}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 d=u.getChild("VariableName"),h=d?e.slice(d.from,d.to):void 0;h&&s(u,l?`${l}.${h}`:h)}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(r.topNode),n}function de(r,e,t,n){return{fromPath:r,toPath:"",rawSpecifier:e,isStyle:!1,isExternal:n,type:"static",symbols:t.length>0?t:void 0}}function tc(r,e,t){return r.startsWith("test_")||r.endsWith("_test.py")?"test":r==="conftest.py"||r==="setup.py"?"config":t.has("test")||e.some(n=>Ha.has(n.rawSpecifier))?"test":"logic"}import _n from"path";import g from"typescript";import b from"typescript";function rc(r){let e=1;function t(n){switch(n.kind){case b.SyntaxKind.IfStatement:case b.SyntaxKind.ConditionalExpression:case b.SyntaxKind.ForStatement:case b.SyntaxKind.ForInStatement:case b.SyntaxKind.ForOfStatement:case b.SyntaxKind.WhileStatement:case b.SyntaxKind.DoStatement:case b.SyntaxKind.CatchClause:case b.SyntaxKind.CaseClause:e++;break;case b.SyntaxKind.BinaryExpression:{let s=n.operatorToken.kind;(s===b.SyntaxKind.AmpersandAmpersandToken||s===b.SyntaxKind.BarBarToken||s===b.SyntaxKind.QuestionQuestionToken)&&e++;break}}b.forEachChild(n,t)}return t(r),e}function nc(r){let e=0;function t(n,s,o){if(b.isIfStatement(n)){e+=o?1:1+s;let a=o?s:s+1;t(n.expression,a,!1),t(n.thenStatement,a,!1),n.elseStatement&&(b.isIfStatement(n.elseStatement)?t(n.elseStatement,s,!0):(e+=1,t(n.elseStatement,s+1,!1)));return}if(b.isForStatement(n)||b.isForInStatement(n)||b.isForOfStatement(n)||b.isWhileStatement(n)||b.isDoStatement(n)||b.isSwitchStatement(n)){e+=1+s,b.forEachChild(n,a=>t(a,s+1,!1));return}if(b.isCatchClause(n)){e+=1+s,b.forEachChild(n,a=>t(a,s,!1));return}if(b.isConditionalExpression(n)&&(e+=1),b.isBinaryExpression(n)){let a=n.operatorToken.kind;(a===b.SyntaxKind.AmpersandAmpersandToken||a===b.SyntaxKind.BarBarToken||a===b.SyntaxKind.QuestionQuestionToken)&&(e+=1)}if(s>0&&(b.isFunctionDeclaration(n)||b.isFunctionExpression(n)||b.isArrowFunction(n))){e+=1+s,b.forEachChild(n,a=>t(a,s+1,!1));return}b.forEachChild(n,a=>t(a,s,!1))}return t(r,0,!1),e}function Xt(r){return{complexity:rc(r),cognitiveComplexity:nc(r)}}import C from"typescript";var Zt=new Set(["test","describe","it"]);function Gn(r,e){sc(r,e),ic(r,e),ac(r,e),cc(r,e)}function sc(r,e){if((C.isFunctionDeclaration(r)||C.isVariableDeclaration(r))&&r.name&&C.isIdentifier(r.name)&&oc(r)){let t;if(C.isFunctionDeclaration(r))t="function";else{let n=r.initializer;t=n&&(C.isArrowFunction(n)||C.isFunctionExpression(n))?"function":"variable"}e.tags.add({name:r.name.text,kind:t})}}function oc(r){if(C.isFunctionDeclaration(r))return C.isSourceFile(r.parent);let e=r.parent?.parent;return!!e&&C.isSourceFile(e.parent)}function ic(r,e){if(!C.isStringLiteral(r))return;let t=r.text.match(/@[\w-]+/g);if(t)for(let n of t)e.tags.add({name:n.substring(1),kind:"comment-marker"})}function ac(r,e){if(!C.isSourceFile(r))return;let t=/@tag\s+([a-zA-Z0-9_-]+)/g,n=r.getFullText(),s=t.exec(n);for(;s!==null;)s[1]&&e.tags.add({name:s[1],kind:"comment-marker"}),s=t.exec(n)}function cc(r,e){if(C.isCallExpression(r)&&lc(r.expression))for(let t of r.arguments)C.isObjectLiteralExpression(t)&&pc(t,e)}function lc(r){return C.isIdentifier(r)?Zt.has(r.text):!!(C.isPropertyAccessExpression(r)&&(Zt.has(r.name.text)||C.isIdentifier(r.expression)&&Zt.has(r.expression.text)))}function pc(r,e){for(let t of r.properties){if(!C.isPropertyAssignment(t)||!C.isIdentifier(t.name)||t.name.text!=="tags"&&t.name.text!=="tag")continue;let{initializer:n}=t,s=C.isArrayLiteralExpression(n)?n.elements.filter(C.isStringLiteral):t.name.text==="tag"&&C.isStringLiteral(n)?[n]:[];for(let o of s)e.tags.add({name:o.text.replace(/^@/,""),kind:"comment-marker"})}}function er(r,e,t){let n=[],s=new Map,o=new Set,i=g.createSourceFile(r,e,g.ScriptTarget.Latest,!0,t==="typescript"?g.ScriptKind.TSX:g.ScriptKind.JSX),a={filePath:r,imports:n,exports:s,tags:o,rawCallEdges:[],sourceFile:i,hasUI:!1,hasTypesOnly:!0,totalStatements:0,exportStatements:0},c=x=>{gc(x,a),g.forEachChild(x,c)};c(i);let l=Fc(r,a);(l==="test"||l==="barrel")&&o.add({name:l,kind:"comment-marker"}),l!=="test"&&Tc(a,i);let p=i.statements[0],u=p?jn(p):void 0,{complexity:d,cognitiveComplexity:h}=Xt(i),k=uc(i);return{imports:n,exports:Array.from(s.values()),tags:Array.from(o),category:l,rawCallEdges:a.rawCallEdges??[],complexity:d,cognitiveComplexity:h,...k.length>0?{functions:k}:{},...u!==void 0?{description:u}:{}}}function uc(r){let e=[],t=(s,o)=>{let{complexity:i,cognitiveComplexity:a}=Xt(o),c=r.getLineAndCharacterOfPosition(o.getStart(r)).line+1;e.push({name:s,line:c,complexity:i,cognitiveComplexity:a})},n=(s,o)=>{if(g.isFunctionDeclaration(s)&&s.name&&s.body?t(s.name.text,s):g.isVariableDeclaration(s)&&g.isIdentifier(s.name)&&s.initializer&&(g.isArrowFunction(s.initializer)||g.isFunctionExpression(s.initializer))?t(s.name.text,s.initializer):o&&g.isMethodDeclaration(s)&&g.isIdentifier(s.name)&&s.body?t(`${o}.${s.name.text}`,s):o&&g.isConstructorDeclaration(s)&&s.body?t(`${o}.constructor`,s):o&&g.isGetAccessorDeclaration(s)&&g.isIdentifier(s.name)&&s.body?t(`${o}.get ${s.name.text}`,s):o&&g.isSetAccessorDeclaration(s)&&g.isIdentifier(s.name)&&s.body&&t(`${o}.set ${s.name.text}`,s),g.isClassDeclaration(s)&&s.name){let i=s.name.text;g.forEachChild(s,a=>n(a,i));return}g.forEachChild(s,i=>n(i,o))};return n(r,void 0),e}function On(r,e,t,n){let s={name:r},o=jn(t);o!==void 0&&(s.doc=o);let i=fc(e);i!==void 0&&(s.flags=i);let a=mc(e,n);return a!==void 0&&(s.signature=a),s}function jn(r){let e=g.getJSDocCommentsAndTags(r);for(let t of e)if(g.isJSDoc(t)&&t.comment)return g.getTextOfJSDocComment(t.comment)||void 0}function fc(r){let e=new Set(["deprecated","internal","public","alpha","beta"]),t=g.getJSDocTags(r).map(n=>n.tagName.text).filter(n=>e.has(n));return t.length>0?t:void 0}function mc(r,e){let t=g.createPrinter({removeComments:!0}),n=s=>t.printNode(g.EmitHint.Unspecified,s,e);if(g.isFunctionDeclaration(r)||g.isMethodDeclaration(r)){let s=r.parameters.map(n).join(", "),o=r.type?n(r.type):"void";return`${r.typeParameters?`<${r.typeParameters.map(a=>a.name.text).join(", ")}>`:""}(${s}) => ${o}`}if(g.isVariableDeclaration(r)){if(r.type)return n(r.type);if(r.initializer&&(g.isArrowFunction(r.initializer)||g.isFunctionExpression(r.initializer))){let s=r.initializer,o=s.parameters.map(n).join(", "),i=s.type?n(s.type):"unknown";return`(${o}) => ${i}`}return}if(g.isClassDeclaration(r)&&r.name)return`class ${r.name.text}`;if(g.isInterfaceDeclaration(r))return`interface ${r.name.text}`;if(g.isTypeAliasDeclaration(r))return n(r.type);if(g.isEnumDeclaration(r))return`enum ${r.name.text}`}function gc(r,e){dc(r,e),hc(r,e),xc(r,e),bc(r,e),Cc(r,e),Gn(r,e)}function dc(r,e){if(!g.isSourceFile(r))return;let t=r.statements.filter(n=>!g.isEmptyStatement(n));e.totalStatements=t.length,e.exportStatements=t.filter(n=>g.isExportDeclaration(n)||g.isExportAssignment(n)||tr(n)).length}function hc(r,e){if(g.isJsxElement(r)||g.isJsxSelfClosingElement(r)||g.isJsxFragment(r)){e.hasUI=!0,e.hasTypesOnly=!1;return}if(g.isFunctionDeclaration(r)||g.isMethodDeclaration(r)||g.isArrowFunction(r)||g.isClassDeclaration(r)||g.isVariableStatement(r)||g.isEnumDeclaration(r)){e.hasTypesOnly=!1;return}g.isExportDeclaration(r)&&!yc(r)&&(e.hasTypesOnly=!1)}function yc(r){return r.isTypeOnly?!0:!r.exportClause||!g.isNamedExports(r.exportClause)?!1:r.exportClause.elements.every(e=>e.isTypeOnly)}function xc(r,e){if(!g.isImportDeclaration(r)||!r.moduleSpecifier||!g.isStringLiteral(r.moduleSpecifier))return;let t=[];if(r.importClause&&(r.importClause.name&&t.push("default"),r.importClause.namedBindings))if(g.isNamedImports(r.importClause.namedBindings))for(let s of r.importClause.namedBindings.elements)t.push(s.name.text);else g.isNamespaceImport(r.importClause.namedBindings)&&t.push("*");let n=t.length>0?"static":"side-effect";e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.moduleSpecifier.text,isStyle:A(r.moduleSpecifier.text),type:n,symbols:t.length>0?t:void 0})}function bc(r,e){g.isExportDeclaration(r)?Sc(r,e):g.isExportAssignment(r)?e.exports.set("default",{name:"default"}):tr(r)&&wc(r,e)}function Sc(r,e){if(r.moduleSpecifier&&g.isStringLiteral(r.moduleSpecifier))kc(r,r.moduleSpecifier.text,e);else if(r.exportClause&&g.isNamedExports(r.exportClause))for(let t of r.exportClause.elements){let n=t.name.text;e.exports.set(n,{name:n})}}function kc(r,e,t){let n=vc(r),s={fromPath:t.filePath,toPath:"",rawSpecifier:e,isStyle:A(e),type:"re-export"};n.length>0&&(s.symbols=n),t.imports.push(s)}function vc(r){return r.exportClause?g.isNamedExports(r.exportClause)?r.exportClause.elements.map(e=>e.name.text):[]:["*"]}function wc(r,e){if((g.isFunctionDeclaration(r)||g.isClassDeclaration(r)||g.isInterfaceDeclaration(r)||g.isTypeAliasDeclaration(r)||g.isEnumDeclaration(r))&&r.name){let n=r.name.text;e.exports.set(n,On(n,r,r,e.sourceFile));return}if(g.isVariableStatement(r)){for(let n of r.declarationList.declarations)if(g.isIdentifier(n.name)){let s=n.name.text;e.exports.set(s,On(s,n,r,e.sourceFile))}}}function Cc(r,e){if(!g.isCallExpression(r))return;let t=r.arguments[0];!t||!g.isStringLiteral(t)||(r.expression.kind===g.SyntaxKind.ImportKeyword?e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:t.text,isStyle:A(t.text),type:"dynamic"}):g.isIdentifier(r.expression)&&r.expression.text==="require"&&e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:t.text,isStyle:A(t.text),type:"require"}))}function Fc(r,e){let t=_n.basename(r).toLowerCase(),n=_n.extname(r).toLowerCase();return re().some(o=>t.includes(o))?"test":fr(t)?"config":e.imports.some(o=>tt().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>nt()?"barrel":"logic"}function tr(r){return g.canHaveModifiers(r)&&g.getModifiers(r)?.some(e=>e.kind===g.SyntaxKind.ExportKeyword)===!0}function Tc(r,e){let t=r.rawCallEdges??[];r.rawCallEdges=t;let n=new Map;for(let s of e.statements){if(!g.isImportDeclaration(s)||!g.isStringLiteral(s.moduleSpecifier))continue;let o=s.moduleSpecifier.text,i=s.importClause;if(i&&(i.name&&n.set(i.name.text,o),i.namedBindings&&g.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=Pc(s);if(o){let i=Ac(s);i&&qe(i,o,n,t);continue}g.isClassDeclaration(s)&&s.name&&Ec(s,s.name.text,n,t)}}function Ec(r,e,t,n){for(let s of r.members)g.isMethodDeclaration(s)&&s.body&&g.isIdentifier(s.name)?qe(s.body,`${e}.${s.name.text}`,t,n):g.isConstructorDeclaration(s)&&s.body&&qe(s.body,`${e}.constructor`,t,n)}function Pc(r){if(tr(r)){if(g.isFunctionDeclaration(r)&&r.name)return r.name.text;if(g.isVariableStatement(r)){for(let e of r.declarationList.declarations)if(g.isIdentifier(e.name)&&e.initializer&&(g.isArrowFunction(e.initializer)||g.isFunctionExpression(e.initializer)))return e.name.text}}}function Ac(r){if(g.isFunctionDeclaration(r))return r.body;if(g.isVariableStatement(r)){for(let e of r.declarationList.declarations)if(e.initializer&&(g.isArrowFunction(e.initializer)||g.isFunctionExpression(e.initializer)))return e.initializer}}function qe(r,e,t,n){if(g.isCallExpression(r)&&g.isIdentifier(r.expression)){let s=r.expression.text,o=t.get(s);o&&!n.some(i=>i.from===e&&i.to===s&&i.toSpecifier===o)&&n.push({from:e,to:s,toSpecifier:o})}g.forEachChild(r,s=>qe(s,e,t,n))}function Ye(r,e){if(e.length===0)return"ui";let t=!1;return r.walk(n=>{if(n.type==="rule")return t=!0,!1}),t?"ui":"barrel"}function Wn(r,e){let t=[],n=/@require\s+['"]([^'"]+)['"]/g,s=n.exec(r);for(;s!==null;){let i=s[1];i&&t.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"require"}),s=n.exec(r)}let o=/(?<!@)(?:import|require)\s*\(?\s*['"]([^'"]+)['"]/g;for(s=o.exec(r);s!==null;){let i=s[1];i&&t.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"static"}),s=o.exec(r)}return t}function zn(r,e){if(e.length===0)return"ui";try{let t=et("stylus");return new t.Parser(r).parse().nodes.some(o=>o.constructor.name!=="Import")?"ui":"barrel"}catch{return r.replace(/^\s*@?(?:require|import)\b.*/gm,"").trim().length>0?"ui":"barrel"}}function he(r,e){let t=L(r);if(t==="stylus"){let o=Wn(e,r);return{imports:o,exports:[],tags:[],category:zn(e,o)}}if(t==="scss"){let{imports:o,root:i,exports:a,tags:c}=Me(e,r);return{imports:o,exports:a,tags:c,category:Ye(i,o)}}if(t==="less"){let{imports:o,root:i,exports:a,tags:c}=Ie(e,r);return{imports:o,exports:a,tags:c,category:Ye(i,o)}}let{imports:n,root:s}=Ne(e,r);return{imports:n,exports:[],tags:[],category:Ye(s,n)}}for(let[r,e]of[["javascript",(t,n)=>er(t,n,"javascript")],["typescript",(t,n)=>er(t,n,"typescript")],["css",he],["scss",he],["less",he],["stylus",he],["coffeescript",Fn],["livescript",An],["lua",Nn],["python",Ln],["go",Pn],["gherkin",Ht],["markdown",Dn]])Y(r,e);async function $n(r,e){let t=L(r),n=an(t);return n?n(r,e):{imports:[],exports:[],tags:[],category:"other"}}import Bn from"path";function Kn(r,e){for(let t of r.values()){let n=e.get(t.path);n!==void 0&&(t.coveragePct=n)}}function Jn(r,e){for(let t of r)if(t.isExternal){let n=t.rawSpecifier.startsWith("@")?t.rawSpecifier.split("/").slice(0,2).join("/"):t.rawSpecifier.split("/")[0];n&&!e.some(s=>s.name===n)&&e.push({name:n,kind:"library"})}}function Vn(r){for(let e of r.values())if(e.category==="test")for(let t of e.imports){if(t.isExternal||!t.toPath)continue;let n=r.get(t.toPath);n&&(n.category!=="logic"&&n.category!=="barrel"||(n.testedBy??=[],n.testedBy.includes(e.path)||n.testedBy.push(e.path)))}}function Hn(r){for(let e of r.values())if(e.type==="markdown")for(let t of e.imports){if(t.isExternal||!t.toPath)continue;let n=r.get(t.toPath);!n||n===e||(n.documentedBy??=[],n.documentedBy.includes(e.path)||n.documentedBy.push(e.path),n.category==="logic"&&(n.lastCommitAt??0)>(e.lastCommitAt??0)&&(e.staleFor??=[],e.staleFor.includes(n.path)||e.staleFor.push(n.path)))}}function Un(r){return Math.round(r*1e4)/1e4}function Qn(r){for(let e of r.values()){let t=[];for(let n of e.imports){if(n.isExternal||!n.toPath)continue;let s=r.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=Un(Math.min(1,o)),t.push(n.exportUsageRatio)}t.length>0&&(e.avgExportUsage=Un(t.reduce((n,s)=>n+s,0)/t.length),e.maxExportUsage=Math.max(...t))}}function rr(r,e,t){e&&(r.some(n=>n.name===e&&n.kind===t)||r.push({name:e,kind:t}))}function Nc(r,e){let t=e.toPath,n=Bn.basename(t,Bn.extname(t)).replace(/\.(test|spec)$/,"");rr(r.tags,n,"import")}function Ic(r,e){if(!(!e.symbols||e.symbols.includes("*")))for(let t of e.symbols)rr(r.tags,t,"import")}function Mc(r,e,t){let n=t.get(e.toPath);if(!(!n||n.category==="test"))for(let s of n.tags)s.kind==="comment-marker"&&rr(r.tags,s.name,"comment-marker")}function qn(r){for(let e of r.values())if(e.category==="test")for(let t of e.imports)!t.toPath||t.isExternal||(Nc(e,t),Ic(e,t),Mc(e,t,r))}import Xe from"fs";import _ from"path";import Zn from"fs";import ee from"path";var ye=class{extensions=[".go"];goModCache=new Map;resolve(e,t,n,s){let{mod:o,replaces:i}=this.readGoMod(n);if(!o)return null;let a=this.applyReplace(t,i,n);if(a!==void 0)return Xn(a);if(t!==o&&!t.startsWith(`${o}/`))return null;let c=t.slice(o.length).replace(/^\//,"");return c?Xn(ee.join(n,c)):null}readGoMod(e){let t=this.goModCache.get(e);if(t!==void 0)return t;let n={mod:null,replaces:new Map};try{let s=Zn.readFileSync(ee.join(e,"go.mod"),"utf-8"),o=Dc(s,e);return this.goModCache.set(e,o),o}catch{return this.goModCache.set(e,n),n}}applyReplace(e,t,n){for(let[s,o]of t){if(e===s)return o;if(e.startsWith(`${s}/`)){let i=e.slice(s.length+1);return ee.join(o,i)}}}};function Dc(r,e){let t=r.split(`
|
|
29
|
-
`),n=null,s=new Map,o=!1;for(let i of
|
|
24
|
+
${p}`}};function oa(t){let e=t.split(`
|
|
25
|
+
`),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 yn from"path";import xn from"typescript";var ia=/\/\/ <mokosh-tags>[\s\S]*?\/\/ <\/mokosh-tags>\n*/,Ve=class{name="vitest";canHandle(e){return D.has(yn.extname(e).toLowerCase())}apply(e,r,n){let s=r.replace(ia,""),o=xn.createSourceFile(yn.basename(e),s,xn.ScriptTarget.Latest,!0),i=_t(o),[a]=i;if(!a)return s;let c=Ot(a,"tags",o),l=[...n].sort();if(c!==null&&JSON.stringify([...c].sort())===JSON.stringify(l))return s;let p=i.flatMap(u=>{let d=n.length===0?zt(u,"tags",o):jt(u,"tags",$t(l),o);return d?[d]:[]});return p.length>0?Wt(s,p):s}};var bn={vitest:()=>new Ve,playwright:()=>new Je,cypress:()=>new $e,jest:()=>new Ke},aa={"@playwright/test":"playwright",cypress:"cypress","@jest/globals":"jest",vitest:"vitest"};function ca(t){let e=Qe.createSourceFile("detect.ts",t,Qe.ScriptTarget.Latest,!0);for(let r of e.statements){if(!Qe.isImportDeclaration(r)||!Qe.isStringLiteral(r.moduleSpecifier))continue;let n=aa[r.moduleSpecifier.text];if(n)return n}return null}var Qt=class{constructor(e,r,n){this.rootDir=e;this.defaultFramework=r;this.frameworkOverrides=n}rootDir;defaultFramework;frameworkOverrides;name="auto";canHandle(e){return D.has(Vt.extname(e).toLowerCase())}apply(e,r,n){let s=ca(r)??this.matchOverride(e)??this.defaultFramework;return(bn[s]??bn.vitest)().apply(e,r,n)}matchOverride(e){let r=Vt.relative(this.rootDir,e).split(Vt.sep).join("/");for(let[n,s]of this.frameworkOverrides)if(hn(n,r))return s;return null}};function Sn(t="vitest",e={},r=process.cwd()){return[new Be,new He,new Ue,new Qt(r,t,Object.entries(e))]}function kn(t,e){return e.find(r=>r.canHandle(t))??null}var pa=/^[a-zA-Z][a-zA-Z0-9_-]{1,}$/,ua=new Set(["import"]),fa=new Set(["common","fixture","fixtures","helper","helpers","index","main","mock","mocks","setup","shared","spec","test","tests","types","util","utils"]);async function ma(t,e,r,n){let s;try{s=await vn.readFile(t,"utf8")}catch(a){return{path:t,status:"error",error:String(a)}}let o=kn(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 vn.writeFile(t,i,"utf8"),{path:t,status:"updated"})}async function qt(t,e,r){let n=ne(e),s=n.tagApplier?.framework??"vitest",o=n.tagApplier?.frameworkOverrides??{},i=Sn(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 h of c.tags)ua.has(h.kind)&&pa.test(h.name)&&(fa.has(h.name.toLowerCase())||l.has(h.name)||(l.add(h.name),p.push(h.name)));p.sort();let u=la.resolve(e,c.path),d=await ma(u,p,r.dryRun,i);d.path=c.path,a.files.push(d),d.status==="updated"?a.updated++:d.status==="unchanged"?a.unchanged++:a.errors++}return a}var qe=class{isTestNode(e){return e.category==="test"||e.tags.some(r=>r.name==="test")}};import Ce from"fs";import E from"path";import Hc from"piscina";import{execFileSync as Yt}from"child_process";var Ye=class{getChangedFiles(){try{let r=[["diff","--name-only"],["diff","--cached","--name-only"],["ls-files","--others","--exclude-standard"]].flatMap(n=>{try{return Yt("git",n,{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
26
|
+
`).map(o=>o.trim()).filter(o=>o!=="")}catch{return[]}});return Array.from(new Set(r))}catch(e){return console.error("Error getting git diff:",e),[]}}},Cn="%x00%H%x09%ae%x09%at",wn=256*1024*1024;function Fn(t,e){let r="",n=0;for(let s of t.split(`
|
|
27
|
+
`)){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 Tn(t){let e=new Map;try{let r=Yt("git",["-C",t,"log","--since=90 days ago","--name-status","-M",`--format=${Cn}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:wn});Fn(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=Yt("git",["-C",t,"log","--name-status","-M",`--format=${Cn}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:wn});Fn(r,(n,s,o)=>{e.has(n)||e.set(n,{commitCount90d:0,lastAuthor:void 0,lastCommitAt:o||void 0})})}catch{}return e}import En from"path";function G(t){switch(En.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":case".cpp":case".cc":case".cxx":case".c":return"unknown";case".feature":return"gherkin";case".md":case".mdx":return"markdown";default:return"unknown"}}function P(t){let e=En.extname(t).toLowerCase();return[".css",".scss",".sass",".less",".styl"].includes(e)}import ga from"coffeescript";function _(t){return t.startsWith("'")||t.startsWith('"')?t.slice(1,-1):t}function X(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 Z(t,e){let r=t.toLowerCase();return r.includes(".test.")||r.includes(".spec.")||e.has("test")?"test":"logic"}function Pn(t){if(t){if(typeof t.originalValue=="string")return t.originalValue;if(typeof t.value=="string")return _(t.value)}}function B(t){if(t){if(typeof t.value=="string")return t.value;if(typeof t.base?.value=="string")return t.base.value}}function da(t,e){let r=Pn(e.source);return r?{fromPath:t,toPath:"",rawSpecifier:r,isStyle:P(r),type:"static"}:null}function ha(t,e){let r=e.variable?.base?.value==="require",n=Pn(e.args?.[0]?.base);return!r||!n?null:{fromPath:t,toPath:"",rawSpecifier:n,isStyle:P(n),type:"require"}}function An(t,e){if(e)return[{name:e}];let r=t.value;if(r?.constructor?.name==="Class"){let s=B(r.variable);return s?[{name:s}]:[]}if(r?.base?.constructor?.name==="Obj"&&Array.isArray(r.base.properties))return r.base.properties.map(s=>B(s.variable)??B(s)).filter(s=>!!s).map(s=>({name:s}));let n=B(r);return n?[{name:n}]:[]}function ya(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=B(t.variable)??B(t.variable?.base);return e?[{name:e}]:[]}function xa(t,e,r,n){let s=e.constructor?.name;if(s==="ImportDeclaration"){let o=da(t,e);o&&r.push(o)}else if(s==="Call"){let o=ha(t,e);o&&r.push(o)}else if(s==="Assign"){let o=B(e.variable?.base),i=e.variable?.properties?.[0]?.name?.value;o==="module"&&i==="exports"?n.push(...An(e,void 0)):o==="exports"&&typeof i=="string"&&n.push(...An(e,i))}else s==="ExportNamedDeclaration"&&e.clause?n.push(...ya(e.clause)):s==="ExportDefaultDeclaration"&&n.push({name:"default"})}function Xt(t,e,r,n){if(!(!e||typeof e!="object")){xa(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)Xt(t,i,r,n);else Xt(t,o,r,n)}}}function Nn(t,e){let r=X(e),n=Z(t,r),s=[],o=[];try{Xt(t,ga.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 ba,GherkinClassicTokenMatcher as Sa,Parser as ka}from"@cucumber/gherkin";import{IdGenerator as va}from"@cucumber/messages";var Ca=va.uuid();function Zt(t,e){let r=new Set;try{let n=new ba(Ca),s=new Sa,i=new ka(n,s).parse(e);i.feature&&(i.feature.tags.forEach(a=>{r.add(a.name.startsWith("@")?a.name.slice(1):a.name)}),i.feature.children.forEach(a=>{a.scenario&&(a.scenario.tags.forEach(c=>{r.add(c.name.startsWith("@")?c.name.slice(1):c.name)}),a.scenario.examples.forEach(c=>{c.tags.forEach(l=>{r.add(l.name.startsWith("@")?l.name.slice(1):l.name)})})),a.rule&&a.rule.children.forEach(c=>{c.scenario&&c.scenario.tags.forEach(l=>{r.add(l.name.startsWith("@")?l.name.slice(1):l.name)})})}))}catch(n){console.warn(`[GherkinParser] Failed to parse ${t}:`,n)}return{imports:[],exports:[],tags:Array.from(r).map(n=>({name:n,kind:"comment-marker"})),category:"test"}}Y("gherkin",Zt);import Ta from"path";import{parser as Ea}from"@lezer/go";function U(t){let e=[],r=t.firstChild;for(;r;)e.push(r),r=r.nextSibling;return e}function de(t,e){let r=1;for(let n=0;n<e&&n<t.length;n++)t[n]===`
|
|
28
|
+
`&&r++;return r}function wa(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 Fa(t,e){let r=0;function n(s,o,i){let a=s.type.name;if(a==="IfStatement"){r+=i?1:1+o;let p=U(s),u=i?o:o+1,d=p[1];d&&d.type.name!=="Block"&&n(d,u,!1);let h=p.find(x=>x.type.name==="Block");h&&n(h,u,!1);let k=p.findIndex(x=>x.type.name==="else");if(k>=0){let x=p[k+1];x?.type.name==="IfStatement"?n(x,o,!0):x&&(r+=1,n(x,o+1,!1))}return}if(a==="ForStatement"||a==="SwitchStatement"||a==="SelectStatement"){r+=1+o;let p=s.firstChild;for(;p;)n(p,o+1,!1),p=p.nextSibling;return}if(a==="LogicOp"){let p=e.slice(s.from,s.to);(p==="&&"||p==="||")&&(r+=1)}if(o>0&&a==="FunctionLiteral"){r+=1+o;let p=s.firstChild;for(;p;)n(p,o+1,!1),p=p.nextSibling;return}let l=s.firstChild;for(;l;)n(l,o,!1),l=l.nextSibling}return n(t,0,!1),r}function Xe(t,e){return{complexity:wa(t,e),cognitiveComplexity:Fa(t,e)}}function er(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 In(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}=Xe(n.node,e);r.push({name:o,line:de(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=er(n.node,e),a=i?`${i}.${o}`:o,{complexity:c,cognitiveComplexity:l}=Xe(n.node,e);r.push({name:a,line:de(e,n.from),complexity:c,cognitiveComplexity:l})}}while(n.next());return r}var Aa=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/,Pa=/^\/\/go:build\s+(.+)$/,Na=/^\/\/\s*\+build\s+(.+)$/;function Mn(t,e){let r=[],n=new Map,s=new Set,o=new Set,i=new Map,a=Ea.parse(e),c=a.cursor();do switch(c.name){case"LineComment":{let y=e.slice(c.from,c.to),C=y.match(Aa);C?.[1]&&s.add(C[1]);let I=y.match(Pa);I&&Dn(I[1],o);let N=y.match(Na);N&&Dn(N[1],o);break}case"ImportSpec":{let y=c.node.getChild("String");if(y){let I=e.slice(y.from,y.to).slice(1,-1);r.push({fromPath:t,toPath:"",rawSpecifier:I,isExternal:!0,isStyle:!1,type:"static"});let N=c.node.getChild("DefName"),O=N?e.slice(N.from,N.to):I.split("/").pop();O&&O!=="_"&&O!=="."&&i.set(O,I)}break}case"FunctionDecl":case"MethodDecl":case"TypeDecl":case"VarDecl":case"ConstDecl":{let y=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(y){let C=e.slice(y.from,y.to);C!=="_"&&/^[A-Z]/.test(C)&&!n.has(C)&&n.set(C,{name:C})}break}}while(c.next());let l=r.some(y=>y.rawSpecifier==="testing"),p=Ta.basename(t).endsWith("_test.go")||s.has("test")||l?"test":"logic",u=new Set([...s,...o]),{complexity:d,cognitiveComplexity:h}=Xe(a.topNode,e),k=In(a,e),x=p==="test"?[]:Ia(a,e,i);return{imports:r,exports:Array.from(n.values()),tags:Array.from(u).map(y=>({name:y,kind:"comment-marker"})),category:p,rawCallEdges:x,complexity:d,cognitiveComplexity:h,...k.length>0?{functions:k}:{}}}function Ia(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 d=e.slice(p.from,p.to),h=r.get(d);if(h){let k=e.slice(u.from,u.to);n.push({from:a,to:k,toSpecifier:h})}}}}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=er(o.node,e);s(a,l?`${l}.${c}`:c)}}while(o.next());return n}function Dn(t,e){for(let r of t.split(/[\s,&|!()]+/)){let n=r.trim();n&&n!=="ignore"&&e.add(n)}}import Da from"livescript";function K(t){if(t){if(typeof t.value=="string")return t.value;if(typeof t.base?.value=="string")return t.base.value}}function Ma(t){if(!t)return[];if(t.constructor?.name==="Class"){let r=K(t.title);return r?[{name:r}]:[]}if(t.constructor?.name==="Obj"&&Array.isArray(t.items))return t.items.map(r=>K(r.key)??K(r.val)).filter(r=>!!r).map(r=>({name:r}));let e=K(t);return e?[{name:e}]:[]}function Ra(t){let e=t.constructor?.name||t.type;if(e==="Assign"&&t.left?.constructor?.name==="Chain"){let r=t.left,n=K(r.head),o=r.tails?.[0]?.key?.name;if(n==="module"&&o==="exports")return Ma(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=>K(n.val)??K(n.key)).filter(n=>!!n).map(n=>({name:n}))}return[]}var La=new Set(["first_line","first_column","last_line","last_column","line","column"]);function Ga(t,e){let r=t.constructor?.name||t.type;if(r==="Import"){let n=t.right?.value;if(typeof n=="string"){let s=_(n);return{fromPath:e,toPath:"",rawSpecifier:s,isStyle:P(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=_(s);return{fromPath:e,toPath:"",rawSpecifier:o,isStyle:P(o),type:"require"}}}}return null}function tr(t,e,r){if(!t||typeof t!="object")return[];let n=[],s=Ga(t,e);s&&n.push(s),r.push(...Ra(t));for(let o in t){if(La.has(o))continue;let i=t[o];if(!(!i||typeof i!="object"))if(Array.isArray(i))for(let a of i)n.push(...tr(a,e,r));else n.push(...tr(i,e,r))}return n}function Rn(t,e){let r=X(e),n=Z(t,r),s=[],o=[];try{s=tr(Da.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 _a from"luaparse";function Oa(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=_(i.raw))}else if(s.type==="StringCallExpression"){let i=s.argument;i?.type==="StringLiteral"&&(o=_(i.raw))}o&&r.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:P(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 ja(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 za(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 Wa(t){let e=t.body,r=ja(e),n=za(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 Ln(t,e){let r=X(e),n=Z(t,r),s=[],o=[];try{let i=_a.parse(e);s=Oa(i,t),o=Wa(i)}catch{}return{imports:s,exports:o,tags:Array.from(r).map(i=>({name:i,kind:"comment-marker"})),category:n}}var $a=["http://","https://","mailto:","//"],Ba="ts|tsx|js|jsx|mjs|cjs|py|go|lua|css|scss|less|styl|coffee|ls|feature|md|mdx|json",Ua=new RegExp(`(?:\\.{1,2}/)?[\\w.-]+(?:/[\\w.-]+)*\\.(?:${Ba})\\b`,"g"),Gn;async function Ka(){return Gn??=(async()=>{let{unified:t}=await import("unified"),e=(await import("remark-parse")).default;return t().use(e)})(),Gn}function Ja(t){let e=t.trim();return e.length===0||e.startsWith("#")||$a.some(r=>e.startsWith(r))}function Ha(t,e){let r=t.match(Ua);return r?r.map(n=>({fromPath:e,toPath:"",rawSpecifier:n,isStyle:!1,type:"static"})):[]}function _n(t,e,r){if(t.type==="link"&&typeof t.url=="string"&&!Ja(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(...Ha(t.value,e)),Array.isArray(t.children))for(let n of t.children)_n(n,e,r)}async function On(t,e){let n=(await Ka()).parse(e),s=[];_n(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 qa from"path";import{parser as Ya}from"@lezer/python";function Va(t){let e=1;function r(n){switch(n.type.name){case"IfStatement":{e+=U(n).filter(o=>o.type.name==="if"||o.type.name==="elif").length;break}case"TryStatement":{e+=U(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 Qa(t){let e=0;function r(n,s){let o=n.type.name;if(o==="IfStatement"){let c=U(n),l=0,p=0;for(;p<c.length;){let u=c[p];if(u?.type.name==="if"||u?.type.name==="elif"){let d=l>0;e+=d?1:1+s;let h=d?s:s+1,k=c[p+1],x=c[p+2];k&&r(k,h),x&&r(x,h),l++,p+=3}else if(u?.type.name==="else"){e+=1;let d=c[p+1];d&&r(d,s+1),p+=2}else p++}return}if(o==="TryStatement"){let c=U(n),l=0;for(;l<c.length;){let p=c[l];if(p?.type.name==="except"){for(e+=1+s,l++;l<c.length&&c[l]?.type.name!=="Body";)r(c[l],s),l++;l<c.length&&(r(c[l],s),l++)}else p?.type.name==="Body"&&r(p,s),l++}return}if(o==="ForStatement"||o==="WhileStatement"){e+=1+s;let c=n.firstChild;for(;c;)r(c,s+1),c=c.nextSibling;return}if((o==="ConditionalExpression"||o==="and"||o==="or")&&(e+=1),s>0&&(o==="FunctionDefinition"||o==="LambdaExpression")){e+=1+s;let c=n.firstChild;for(;c;)r(c,s+1),c=c.nextSibling;return}let a=n.firstChild;for(;a;)r(a,s),a=a.nextSibling}return r(t,0),e}function rr(t){return{complexity:Va(t),cognitiveComplexity:Qa(t)}}function jn(t,e){let r=[];function n(i,a){let{complexity:c,cognitiveComplexity:l}=rr(i);r.push({name:a,line:de(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"),d=u?e.slice(u.from,u.to):void 0;d&&n(p,c?`${c}.${d}`:d),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 Xa=new Set(["pytest","unittest","nose","hypothesis"]);function zn(t,e){let r=[],n=[],s=new Set,o=qa.basename(t).toLowerCase(),i=Ya.parse(e),a=i.cursor();do switch(a.name){case"Comment":{let h=e.slice(a.from,a.to).match(/#\s*@tag\s+([a-zA-Z0-9_-]+)/);h?.[1]&&s.add(h[1]);break}case"ImportStatement":{for(let h of Za(a.node,e,t))r.push(h);break}case"FunctionDefinition":case"ClassDefinition":{let h=a.node.parent;if(h?.name==="Script"||h?.name==="DecoratedStatement"&&h.parent?.name==="Script"){let x=a.node.getChild("VariableName");x&&n.push({name:e.slice(x.from,x.to)})}break}case"AssignStatement":{if(a.node.parent?.name==="Script"){let h=a.node.firstChild;h?.name==="VariableName"&&n.push({name:e.slice(h.from,h.to)})}break}}while(a.next());let c=oc(o,r,s);c==="test"&&s.add("test");let{complexity:l,cognitiveComplexity:p}=rr(i.topNode),u=jn(i,e),d=c==="test"?[]:sc(i,e);return{imports:r,exports:n,tags:Array.from(s).map(h=>({name:h,kind:"comment-marker"})),category:c,rawCallEdges:d,complexity:l,cognitiveComplexity:p,...u.length>0?{functions:u}:{}}}function Za(t,e,r){let n=t.firstChild;return n?n.name==="from"?ec(t,e,r):tc(t,e,r):[]}function ec(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=rc(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[he(r,o,i,!0)];let l=a===1?"./":"../".repeat(a-1);return c?[he(r,l+c.replace(/\./g,"/"),i,!1)]:i[0]==="*"?[he(r,l.slice(0,-1),["*"],!1)]:i.map(p=>he(r,l+p,[p],!1))}function tc(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(he(r,o,["*"],!0))}s=s.nextSibling}return n}function rc(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 nc(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 d=e.slice(u.from,u.to),h=d;if(u.nextSibling?.type.name==="as"){let x=u.nextSibling.nextSibling;x?.type.name==="VariableName"&&(h=e.slice(x.from,x.to),u=x)}let k=c===0?a:l?p+l.replace(/\./g,"/"):p+d;r.set(h,k)}u=u.nextSibling}}while(n.next());return r}function sc(t,e){let r=nc(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),d=r.get(u);d&&n.push({from:c,to:u,toSpecifier:d})}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 d=u.getChild("VariableName"),h=d?e.slice(d.from,d.to):void 0;h&&s(u,l?`${l}.${h}`:h)}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 he(t,e,r,n){return{fromPath:t,toPath:"",rawSpecifier:e,isStyle:!1,isExternal:n,type:"static",symbols:r.length>0?r:void 0}}function oc(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=>Xa.has(n.rawSpecifier))?"test":"logic"}import $n from"path";import g from"typescript";import b from"typescript";function ic(t){let e=1;function r(n){switch(n.kind){case b.SyntaxKind.IfStatement:case b.SyntaxKind.ConditionalExpression:case b.SyntaxKind.ForStatement:case b.SyntaxKind.ForInStatement:case b.SyntaxKind.ForOfStatement:case b.SyntaxKind.WhileStatement:case b.SyntaxKind.DoStatement:case b.SyntaxKind.CatchClause:case b.SyntaxKind.CaseClause:e++;break;case b.SyntaxKind.BinaryExpression:{let s=n.operatorToken.kind;(s===b.SyntaxKind.AmpersandAmpersandToken||s===b.SyntaxKind.BarBarToken||s===b.SyntaxKind.QuestionQuestionToken)&&e++;break}}b.forEachChild(n,r)}return r(t),e}function ac(t){let e=0;function r(n,s,o){if(b.isIfStatement(n)){e+=o?1:1+s;let a=o?s:s+1;r(n.expression,a,!1),r(n.thenStatement,a,!1),n.elseStatement&&(b.isIfStatement(n.elseStatement)?r(n.elseStatement,s,!0):(e+=1,r(n.elseStatement,s+1,!1)));return}if(b.isForStatement(n)||b.isForInStatement(n)||b.isForOfStatement(n)||b.isWhileStatement(n)||b.isDoStatement(n)||b.isSwitchStatement(n)){e+=1+s,b.forEachChild(n,a=>r(a,s+1,!1));return}if(b.isCatchClause(n)){e+=1+s,b.forEachChild(n,a=>r(a,s,!1));return}if(b.isConditionalExpression(n)&&(e+=1),b.isBinaryExpression(n)){let a=n.operatorToken.kind;(a===b.SyntaxKind.AmpersandAmpersandToken||a===b.SyntaxKind.BarBarToken||a===b.SyntaxKind.QuestionQuestionToken)&&(e+=1)}if(s>0&&(b.isFunctionDeclaration(n)||b.isFunctionExpression(n)||b.isArrowFunction(n))){e+=1+s,b.forEachChild(n,a=>r(a,s+1,!1));return}b.forEachChild(n,a=>r(a,s,!1))}return r(t,0,!1),e}function nr(t){return{complexity:ic(t),cognitiveComplexity:ac(t)}}import w from"typescript";var sr=new Set(["test","describe","it"]);function Wn(t,e){cc(t,e),pc(t,e),uc(t,e),fc(t,e)}function cc(t,e){if((w.isFunctionDeclaration(t)||w.isVariableDeclaration(t))&&t.name&&w.isIdentifier(t.name)&&lc(t)){let r;if(w.isFunctionDeclaration(t))r="function";else{let n=t.initializer;r=n&&(w.isArrowFunction(n)||w.isFunctionExpression(n))?"function":"variable"}e.tags.add({name:t.name.text,kind:r})}}function lc(t){if(w.isFunctionDeclaration(t))return w.isSourceFile(t.parent);let e=t.parent?.parent;return!!e&&w.isSourceFile(e.parent)}function pc(t,e){if(!w.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 uc(t,e){if(!w.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 fc(t,e){if(w.isCallExpression(t)&&mc(t.expression))for(let r of t.arguments)w.isObjectLiteralExpression(r)&&gc(r,e)}function mc(t){return w.isIdentifier(t)?sr.has(t.text):!!(w.isPropertyAccessExpression(t)&&(sr.has(t.name.text)||w.isIdentifier(t.expression)&&sr.has(t.expression.text)))}function gc(t,e){for(let r of t.properties){if(!w.isPropertyAssignment(r)||!w.isIdentifier(r.name)||r.name.text!=="tags"&&r.name.text!=="tag")continue;let{initializer:n}=r,s=w.isArrayLiteralExpression(n)?n.elements.filter(w.isStringLiteral):r.name.text==="tag"&&w.isStringLiteral(n)?[n]:[];for(let o of s)e.tags.add({name:o.text.replace(/^@/,""),kind:"comment-marker"})}}function or(t,e,r){let n=[],s=new Map,o=new Set,i=g.createSourceFile(t,e,g.ScriptTarget.Latest,!0,r==="typescript"?g.ScriptKind.TSX:g.ScriptKind.JSX),a={filePath:t,imports:n,exports:s,tags:o,rawCallEdges:[],sourceFile:i,hasUI:!1,hasTypesOnly:!0,totalStatements:0,exportStatements:0},c=x=>{xc(x,a),g.forEachChild(x,c)};c(i);let l=Pc(t,a);(l==="test"||l==="barrel")&&o.add({name:l,kind:"comment-marker"}),l!=="test"&&Nc(a,i);let p=i.statements[0],u=p?Un(p):void 0,{complexity:d,cognitiveComplexity:h}=nr(i),k=dc(i);return{imports:n,exports:Array.from(s.values()),tags:Array.from(o),category:l,rawCallEdges:a.rawCallEdges??[],complexity:d,cognitiveComplexity:h,...k.length>0?{functions:k}:{},...u!==void 0?{description:u}:{}}}function dc(t){let e=[],r=(s,o)=>{let{complexity:i,cognitiveComplexity:a}=nr(o),c=t.getLineAndCharacterOfPosition(o.getStart(t)).line+1;e.push({name:s,line:c,complexity:i,cognitiveComplexity:a})},n=(s,o)=>{if(g.isFunctionDeclaration(s)&&s.name&&s.body?r(s.name.text,s):g.isVariableDeclaration(s)&&g.isIdentifier(s.name)&&s.initializer&&(g.isArrowFunction(s.initializer)||g.isFunctionExpression(s.initializer))?r(s.name.text,s.initializer):o&&g.isMethodDeclaration(s)&&g.isIdentifier(s.name)&&s.body?r(`${o}.${s.name.text}`,s):o&&g.isConstructorDeclaration(s)&&s.body?r(`${o}.constructor`,s):o&&g.isGetAccessorDeclaration(s)&&g.isIdentifier(s.name)&&s.body?r(`${o}.get ${s.name.text}`,s):o&&g.isSetAccessorDeclaration(s)&&g.isIdentifier(s.name)&&s.body&&r(`${o}.set ${s.name.text}`,s),g.isClassDeclaration(s)&&s.name){let i=s.name.text;g.forEachChild(s,a=>n(a,i));return}g.forEachChild(s,i=>n(i,o))};return n(t,void 0),e}function Bn(t,e,r,n){let s={name:t},o=Un(r);o!==void 0&&(s.doc=o);let i=hc(e);i!==void 0&&(s.flags=i);let a=yc(e,n);return a!==void 0&&(s.signature=a),s}function Un(t){let e=g.getJSDocCommentsAndTags(t);for(let r of e)if(g.isJSDoc(r)&&r.comment)return g.getTextOfJSDocComment(r.comment)||void 0}function hc(t){let e=new Set(["deprecated","internal","public","alpha","beta"]),r=g.getJSDocTags(t).map(n=>n.tagName.text).filter(n=>e.has(n));return r.length>0?r:void 0}function yc(t,e){let r=g.createPrinter({removeComments:!0}),n=s=>r.printNode(g.EmitHint.Unspecified,s,e);if(g.isFunctionDeclaration(t)||g.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(g.isVariableDeclaration(t)){if(t.type)return n(t.type);if(t.initializer&&(g.isArrowFunction(t.initializer)||g.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(g.isClassDeclaration(t)&&t.name)return`class ${t.name.text}`;if(g.isInterfaceDeclaration(t))return`interface ${t.name.text}`;if(g.isTypeAliasDeclaration(t))return n(t.type);if(g.isEnumDeclaration(t))return`enum ${t.name.text}`}function xc(t,e){bc(t,e),Sc(t,e),vc(t,e),Cc(t,e),Ac(t,e),Wn(t,e)}function bc(t,e){if(!g.isSourceFile(t))return;let r=t.statements.filter(n=>!g.isEmptyStatement(n));e.totalStatements=r.length,e.exportStatements=r.filter(n=>g.isExportDeclaration(n)||g.isExportAssignment(n)||ir(n)).length}function Sc(t,e){if(g.isJsxElement(t)||g.isJsxSelfClosingElement(t)||g.isJsxFragment(t)){e.hasUI=!0,e.hasTypesOnly=!1;return}if(g.isFunctionDeclaration(t)||g.isMethodDeclaration(t)||g.isArrowFunction(t)||g.isClassDeclaration(t)||g.isVariableStatement(t)||g.isEnumDeclaration(t)){e.hasTypesOnly=!1;return}g.isExportDeclaration(t)&&!kc(t)&&(e.hasTypesOnly=!1)}function kc(t){return t.isTypeOnly?!0:!t.exportClause||!g.isNamedExports(t.exportClause)?!1:t.exportClause.elements.every(e=>e.isTypeOnly)}function vc(t,e){if(!g.isImportDeclaration(t)||!t.moduleSpecifier||!g.isStringLiteral(t.moduleSpecifier))return;let r=[];if(t.importClause&&(t.importClause.name&&r.push("default"),t.importClause.namedBindings))if(g.isNamedImports(t.importClause.namedBindings))for(let s of t.importClause.namedBindings.elements)r.push(s.name.text);else g.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:P(t.moduleSpecifier.text),type:n,symbols:r.length>0?r:void 0})}function Cc(t,e){g.isExportDeclaration(t)?wc(t,e):g.isExportAssignment(t)?e.exports.set("default",{name:"default"}):ir(t)&&Ec(t,e)}function wc(t,e){if(t.moduleSpecifier&&g.isStringLiteral(t.moduleSpecifier))Fc(t,t.moduleSpecifier.text,e);else if(t.exportClause&&g.isNamedExports(t.exportClause))for(let r of t.exportClause.elements){let n=r.name.text;e.exports.set(n,{name:n})}}function Fc(t,e,r){let n=Tc(t),s={fromPath:r.filePath,toPath:"",rawSpecifier:e,isStyle:P(e),type:"re-export"};n.length>0&&(s.symbols=n),r.imports.push(s)}function Tc(t){return t.exportClause?g.isNamedExports(t.exportClause)?t.exportClause.elements.map(e=>e.name.text):[]:["*"]}function Ec(t,e){if((g.isFunctionDeclaration(t)||g.isClassDeclaration(t)||g.isInterfaceDeclaration(t)||g.isTypeAliasDeclaration(t)||g.isEnumDeclaration(t))&&t.name){let n=t.name.text;e.exports.set(n,Bn(n,t,t,e.sourceFile));return}if(g.isVariableStatement(t)){for(let n of t.declarationList.declarations)if(g.isIdentifier(n.name)){let s=n.name.text;e.exports.set(s,Bn(s,n,t,e.sourceFile))}}}function Ac(t,e){if(!g.isCallExpression(t))return;let r=t.arguments[0];!r||!g.isStringLiteral(r)||(t.expression.kind===g.SyntaxKind.ImportKeyword?e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.text,isStyle:P(r.text),type:"dynamic"}):g.isIdentifier(t.expression)&&t.expression.text==="require"&&e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.text,isStyle:P(r.text),type:"require"}))}function Pc(t,e){let r=$n.basename(t).toLowerCase(),n=$n.extname(t).toLowerCase();return re().some(o=>r.includes(o))?"test":yr(r)?"config":e.imports.some(o=>st().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>it()?"barrel":"logic"}function ir(t){return g.canHaveModifiers(t)&&g.getModifiers(t)?.some(e=>e.kind===g.SyntaxKind.ExportKeyword)===!0}function Nc(t,e){let r=t.rawCallEdges??[];t.rawCallEdges=r;let n=new Map;for(let s of e.statements){if(!g.isImportDeclaration(s)||!g.isStringLiteral(s.moduleSpecifier))continue;let o=s.moduleSpecifier.text,i=s.importClause;if(i&&(i.name&&n.set(i.name.text,o),i.namedBindings&&g.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=Dc(s);if(o){let i=Mc(s);i&&Ze(i,o,n,r);continue}g.isClassDeclaration(s)&&s.name&&Ic(s,s.name.text,n,r)}}function Ic(t,e,r,n){for(let s of t.members)g.isMethodDeclaration(s)&&s.body&&g.isIdentifier(s.name)?Ze(s.body,`${e}.${s.name.text}`,r,n):g.isConstructorDeclaration(s)&&s.body&&Ze(s.body,`${e}.constructor`,r,n)}function Dc(t){if(ir(t)){if(g.isFunctionDeclaration(t)&&t.name)return t.name.text;if(g.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(g.isIdentifier(e.name)&&e.initializer&&(g.isArrowFunction(e.initializer)||g.isFunctionExpression(e.initializer)))return e.name.text}}}function Mc(t){if(g.isFunctionDeclaration(t))return t.body;if(g.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(e.initializer&&(g.isArrowFunction(e.initializer)||g.isFunctionExpression(e.initializer)))return e.initializer}}function Ze(t,e,r,n){if(g.isCallExpression(t)&&g.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})}g.forEachChild(t,s=>Ze(s,e,r,n))}function et(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"}function Kn(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 Jn(t,e){if(e.length===0)return"ui";try{let r=nt("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 ye(t,e){let r=G(t);if(r==="stylus"){let o=Kn(e,t);return{imports:o,exports:[],tags:[],category:Jn(e,o)}}if(r==="scss"){let{imports:o,root:i,exports:a,tags:c}=Me(e,t);return{imports:o,exports:a,tags:c,category:et(i,o)}}if(r==="less"){let{imports:o,root:i,exports:a,tags:c}=De(e,t);return{imports:o,exports:a,tags:c,category:et(i,o)}}let{imports:n,root:s}=Ie(e,t);return{imports:n,exports:[],tags:[],category:et(s,n)}}for(let[t,e]of[["javascript",(r,n)=>or(r,n,"javascript")],["typescript",(r,n)=>or(r,n,"typescript")],["css",ye],["scss",ye],["less",ye],["stylus",ye],["coffeescript",Nn],["livescript",Rn],["lua",Ln],["python",zn],["go",Mn],["gherkin",Zt],["markdown",On]])Y(t,e);async function Hn(t,e){let r=G(t),n=fn(r);return n?n(t,e):{imports:[],exports:[],tags:[],category:"other"}}import Vn from"path";function Rc(t,e){let r=e.get(t.path);r!==void 0&&(t.coveragePct=r)}function qn(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 Lc(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 Gc(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 Qn(t){return Math.round(t*1e4)/1e4}function _c(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=Qn(Math.min(1,o)),r.push(n.exportUsageRatio)}r.length>0&&(t.avgExportUsage=Qn(r.reduce((n,s)=>n+s,0)/r.length),t.maxExportUsage=Math.max(...r))}function ar(t,e,r){e&&(t.some(n=>n.name===e&&n.kind===r)||t.push({name:e,kind:r}))}function Oc(t,e){let r=e.toPath,n=Vn.basename(r,Vn.extname(r)).replace(/\.(test|spec)$/,"");ar(t.tags,n,"import")}function jc(t,e){if(!(!e.symbols||e.symbols.includes("*")))for(let r of e.symbols)ar(t.tags,r,"import")}function zc(t,e,r){let n=r.get(e.toPath);if(!(!n||n.category==="test"))for(let s of n.tags)s.kind==="comment-marker"&&ar(t.tags,s.name,"comment-marker")}function Wc(t,e,r){!e.toPath||e.isExternal||(Oc(t,e),jc(t,e),zc(t,e,r))}function Yn(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(_c(r,t),e.size>0&&Rc(r,e),r.category==="test")for(let n of r.imports)Lc(r,n,t),Wc(r,n,t);Gc(r,t)}}import tt from"fs";import R from"path";import es from"fs";import ee from"path";var xe=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 Zn(a);if(r!==o&&!r.startsWith(`${o}/`))return null;let c=r.slice(o.length).replace(/^\//,"");return c?Zn(ee.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=es.readFileSync(ee.join(e,"go.mod"),"utf-8"),o=$c(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 ee.join(o,i)}}}};function $c(t,e){let r=t.split(`
|
|
29
|
+
`),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("=>")){Xn(a,e,s);continue}!o&&/^replace\s+/.test(a)&&a.includes("=>")&&Xn(a.replace(/^replace\s+/,""),e,s)}return{mod:n,replaces:s}}function Xn(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=ee.isAbsolute(s)?s:ee.resolve(e,s);r.set(o,i)}function Zn(t){let e;try{e=es.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:ee.join(t,n.name),isExternal:!1})).sort((n,s)=>n.path.localeCompare(s.path));return r.length>0?r:null}import Bc from"fs";import cr from"path";var be=class{extensions=[".lua"];resolve(e,r,n,s){let o=r.replace(/\./g,cr.sep),i=[n,cr.join(n,"lib")];for(let a of i){if(!Bc.existsSync(a))continue;let c=s(cr.join(a,"_dummy.lua"),o);if(c)return[c]}return null}};import Uc from"path";var Se=class{extensions=[".md",".mdx"];resolve(e,r,n,s){let o=s(Uc.join(n,"_dummy"),`./${r}`);return o?[o]:null}};import Kc from"fs";import lr from"path";var ke=class{extensions=[".py"];resolve(e,r,n,s){let o=r.replace(/\./g,lr.sep),i=lr.join(n,`${o}.py`);if(ts(i))return[{path:i,isExternal:!1}];let a=lr.join(n,o,"__init__.py");return ts(a)?[{path:a,isExternal:!1}]:null}};function ts(t){try{return Kc.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}import rs from"path";var Jc=["~","http://","https://","//","data:","sass:"],ve=class{extensions=[".css",".scss",".sass",".less",".styl"];resolve(e,r,n,s){if(Jc.some(p=>r.startsWith(p)))return null;let o=s(e,r);if(o)return[o];let i=rs.dirname(r),a=rs.basename(r),c=i==="."?`_${a}`:`${i}/_${a}`,l=s(e,c);return l?[l]:null}};var J=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 ke,new be,new xe,new ve,new Se]}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`${R.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=R.dirname(e),s=r.startsWith("/")?r:R.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=R.join(e,`index${r}`);if(this.isFile(o))return{path:o,isExternal:n};if(r===".py"){let i=R.join(e,"__init__.py");if(this.isFile(i))return{path:i,isExternal:n}}return null}isFile(e){try{return tt.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=R.join(r,"tsconfig.json");if(tt.existsSync(n))try{let o=JSON.parse(tt.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=R.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=R.join(n,a);try{if(tt.statSync(c,{throwIfNoEntry:!1})?.isFile())return{...o,path:c}}catch{}}return{...o,path:n}}let i=this.resolveLocalPath(R.join(n,"_dummy"),s.slice(1));return i?{...o,path:i.path}:null}return null}};var Vc=["tests","test","__tests__","specs","spec"],ns=new Set(["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage"]),Qc=600;function qc(t,e){if(t.length===0)return e;let r=t.map(i=>E.dirname(i).split(E.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(E.sep)||E.sep,o=E.relative(e,s);return o.startsWith("..")||E.isAbsolute(o)?e:s}var we=class{constructor(e,r=null,n,s,o=!1,i=new Map,a=!0){this.rootDir=e;this.enableGitStats=o;this.coverageMap=i;this.parallelParsing=a;this.previousGraph=r,this.resolver=n||new J(e),this.lockFile=Nr(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;async build(e){let r=e.map(n=>E.isAbsolute(n)?n:E.resolve(this.rootDir,n));await this.initPool(),this.enableGitStats&&(this.gitStatsMap=Tn(this.rootDir));try{for(let n of r)this.enqueue(n);return await this.drain(),await this.processTestFiles(qc(r,this.rootDir)),await this.processDocFiles(),this.progressCallback&&this.visited.size>=100&&process.stderr.write(`
|
|
30
30
|
Done. Total processed: ${this.visited.size} nodes.
|
|
31
|
-
`),
|
|
31
|
+
`),Yn(this.graph.nodes,this.coverageMap),new M(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??Qc;if(!(r>0&&!this.hasAtLeastFiles(this.rootDir,r)))try{let n=E.join(f,"parse-worker.js");this.pool=new Hc({filename:n,...e.maxThreads!==void 0?{maxThreads:e.maxThreads}:{}})}catch(n){process.stderr.write(`
|
|
32
32
|
Warning: failed to start parse worker pool, falling back to synchronous parsing: ${n}
|
|
33
|
-
`),this.pool=null}}hasAtLeastFiles(e,
|
|
34
|
-
Warning: failed to parse ${
|
|
35
|
-
`),null}}parseContent(e,t){return this.pool?this.pool.run({filePath:e,content:t}):$n(e,t)}makeStubNode(e,t,n){return{path:t,type:L(e),category:"other",imports:[],exports:[],tags:[],mtime:n.mtimeMs,size:n.size}}resolveCallEdges(e,t){let n=[];for(let s of t??[])try{let o=this.resolver.resolve(e,s.toSpecifier);o&&!o.isExternal&&n.push({from:s.from,to:s.to,toFile:E.relative(this.rootDir,o.path)})}catch{}return n}buildNode(e,t,n,s,o){let{imports:i,exports:a,tags:c,category:l,description:p,complexity:u,cognitiveComplexity:d,functions:h}=s;return{path:t,type:L(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}:{},...d!==void 0?{cognitiveComplexity:d}:{},...h!==void 0?{functions:h}:{}}}attachGitStats(e,t){let n=this.gitStatsMap?.get(t);n&&(e.commitCount90d=n.commitCount90d,n.lastAuthor!==void 0&&(e.lastAuthor=n.lastAuthor),n.lastCommitAt!==void 0&&(e.lastCommitAt=n.lastCommitAt))}async resolveImports(e,t){let n=[];for(let s of t){let o=this.resolver.resolveAll(e,s.rawSpecifier);if(o.length!==0)for(let i of o){let a={...s,toPath:i.isExternal?i.path:E.relative(this.rootDir,i.path),isExternal:i.isExternal};i.isWorkspace&&(a.isWorkspace=!0,a.workspacePackage=i.workspacePackage),i.isExternal?this.attachLockfileVersion(a):this.enqueue(i.path),n.push(a)}}return n}attachLockfileVersion(e){if(!this.lockFile)return;let t=e.rawSpecifier.startsWith("@")?e.rawSpecifier.split("/").slice(0,2).join("/"):e.rawSpecifier.split("/")[0],n=t?this.lockFile.dependencies[t]:void 0;n&&(e.version=n.version)}showProgress(){this.progressCallback&&this.visited.size%100===0&&this.progressCallback(this.visited.size)}};function ns(r,e){return{identifier:e?.identifier??new Ve,featureMap:e?.featureDetection===!1?new Map:W(r.nodes,e?.featureDetection??void 0)}}function ss(r,e,t,n,s){for(let o of e){let i=r.nodes.get(o);if(!i)continue;let a=new z(o,["*",...i.exports.map(c=>c.name)]);r.traverse(o,(c,l,p)=>{if(!p)return!0;if(!a.updateAffectedSymbols(c,p))return!1;if(l>0){let u=t.get(c.path);if(u)return n(u),!1}return s(c),!0},{direction:"incoming"})}}function or(r,e,t){let{identifier:n,featureMap:s}=ns(r,t),o=new Set;for(let i of e){let a=s.get(i);a&&o.add(a.tag)}return ss(r,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 ir(r,e,t){let{identifier:n,featureMap:s}=ns(r,t),o=new Set;return ss(r,e,s,()=>{},i=>{n.isTestNode(i)&&o.add(i.path)}),Array.from(o)}import $c from"fs";import Ce from"path";async function os(r,e,t=null,n={}){let s=n.silent?void 0:a=>{process.stderr.write(`Processed ${a} files...\r`)},o=Ce.resolve(r);return await new we(o,t,n.pathAliases?new J(o,{pathAliases:n.pathAliases}):void 0,s,n.gitStats??!1,n.coverageMap??new Map,n.parallelParsing??!0).build(e)}async function is(r,e={}){let t=Ce.resolve(r),n=ue(t),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 fe(t,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 we(t,null,new J(t,{workspaceMap:o,tsconfigSearchPaths:[a.root,t],pathAliases:e.pathAliases}),c,e.gitStats??!1,new Map,e.parallelParsing??!0).build(a.entryPoints);i.addPackage(a,p)}return i}function as(r,e={}){let t=[],n=new Set([...e.ignoreDirs??j,...e.additionalIgnoreDirs??[]]),s=new Set([...e.extensions??it,...e.additionalExtensions??[]]);function o(i){try{let a=$c.readdirSync(i,{withFileTypes:!0});for(let c of a){let l=Ce.join(i,c.name);c.isDirectory()?n.has(c.name)||o(l):c.isFile()&&s.has(Ce.extname(c.name).toLowerCase())&&t.push(Ce.relative(r,l))}}catch{}}return o(r),t}var cs=/(?:^|[/\\])(?:node_modules|\.git|dist|build|coverage)(?:[/\\]|$)/;var Ze=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,t){this.configs.set(e,t)}getConfig(e){return this.configs.get(e)}async getOrBuild(e,t,n=new Map){let s=this.configs.get(e),o=await os(e,t,this.graphs.get(e)??null,{...H(s),coverageMap:n});return this.graphs.set(e,o),o}require(e){let t=this.graphs.get(e);if(!t)throw new Error('No graph cached for this root. Call "analyze" first.');return t}async getOrBuildWorkspace(e,t={}){let n=this.workspaceGraphs.get(e);if(n)return n;let s=await is(e,t);return this.workspaceGraphs.set(e,s),s}requireWorkspace(e){let t=this.workspaceGraphs.get(e);if(!t)throw new Error('No workspace graph cached for this root. Call "analyze" first.');return t}hasWorkspace(e){return this.workspaceGraphs.has(e)}getOrBuildChangeImpact(e){let t=this.changeImpactCaches.get(e);if(t)return t;let n=this.require(e),s=ft(n);return this.changeImpactCaches.set(e,s),s}storeLastAnalyze(e,t){this.lastAnalyze.set(e,t)}startWatching(e){if(!this.watchers.has(e))try{let t=Bc.watch(e,{recursive:!0},(n,s)=>{!s||cs.test(s)||this.dirtyRoots.add(e)});t.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,t)}catch{}}async ensureFresh(e){if(!this.dirtyRoots.has(e))return this.require(e);this.dirtyRoots.delete(e),this.changeImpactCaches.delete(e);let t=this.lastAnalyze.get(e);return t?.kind==="single"?this.getOrBuild(e,t.entryPoints,t.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 t=this.configs.get(e);return this.getOrBuildWorkspace(e,H(t))}getDuplicationTokenCache(e){let t=this.duplicationTokenCaches.get(e);return t||(t=new Map,this.duplicationTokenCaches.set(e,t)),t}invalidate(e){let t=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),t}};import te from"path";import Uc from"fs";import Kc from"os";import ar from"path";function S(r){return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}function ls(r){if(!ar.isAbsolute(r))throw new Error("root must be an absolute path");let e=ar.resolve(r),t=Kc.homedir();if(e!==t&&!e.startsWith(t+ar.sep))throw new Error("root must be within the user home directory");let n;try{n=Uc.statSync(e)}catch{throw new Error("root does not exist")}if(!n.isDirectory())throw new Error("root is not a directory")}async function ps(r,e){let{root:t,entryPoints:n}=e;if(!r.isConfigured(t)){let d=ne(t,{allowJs:!1});ot(d),r.storeConfig(t,d)}if(n.length===0){let d=ue(t);if(d.type!=="none"){let h=r.getConfig(t),k=await r.getOrBuildWorkspace(t,H(h));r.storeLastAnalyze(t,{kind:"workspace"}),r.startWatching(t);let x=Array.from(k.packages.values()).map(({graph:y,pkg:w})=>({package:w.name,relativeRoot:w.relativeRoot,nodeCount:y.nodes.size}));return S({monorepoType:d.type,packageCount:k.packages.size,packages:x})}}let s=n.map(d=>te.resolve(t,d)),o=r.getConfig(t),i=o?.coverageReportPath?at(t,o.coverageReportPath):new Map,a=await r.getOrBuild(t,s,i);r.storeLastAnalyze(t,{kind:"single",entryPoints:s,coverageMap:i}),r.startWatching(t);let c=a.serialize(),l=c.nodes.reduce((d,h)=>(d[h.category]=(d[h.category]??0)+1,d),{}),p=a.findCycles(),u=yt(a);return S({nodeCount:c.nodes.length,categories:l,cycles:p,languageCoverage:u})}async function us(r,e){let{root:t,file:n,depth:s=1,withMeta:o=!1}=e,i=await r.ensureFresh(t),a=xt(i,n,s),c=o?a.map(l=>({...l,...ae(i,l.path)})):a;return S({file:n,dependencies:c})}async function fs(r,e){let{root:t,file:n,withMeta:s=!1}=e,o=await r.ensureFresh(t),i=ce(o,n),a=s?i.map(c=>({...c,...ae(o,c.path)})):i;return S({file:n,dependents:a})}async function ms(r,e){let{root:t,file:n,testsOnly:s=!1,cached:o=!1,changedSymbols:i,withMeta:a=!1}=e,c=await r.ensureFresh(t),l=d=>a?d.map(h=>({path:h,...ae(c,h)})):d;if(o){let d=r.getOrBuildChangeImpact(t),h=mt(d,n),k=s?h.filter(y=>c.nodes.get(y)?.category==="test"):h,x=l(k);return S({file:n,affected:x,count:x.length})}let p=bt(c,n,{testsOnly:s,changedSymbols:i}),u=l(p);return S({file:n,affected:u,count:u.length})}async function gs(r,e){let{root:t,file:n,depth:s=1,withEdgeDetail:o=!1}=e,i=await r.ensureFresh(t),a=St(i,n,{depth:s,withEdgeDetail:o});return S({file:n,callers:a,count:a.length})}async function ds(r,e){let{root:t,entryPoints:n}=e,s=n?await r.getOrBuild(t,n.map(a=>te.resolve(t,a))):await r.ensureFresh(t),o=as(t),i=s.findUnusedFiles(o);return S({unusedFiles:i,count:i.length})}async function hs(r,e){let{root:t}=e,n=await r.ensureFresh(t),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 S({tags:o,count:o.length})}async function ys(r,e){let{root:t,coverageThreshold:n}=e,s=await r.ensureFresh(t),o=r.getConfig(t),i=n??o?.coverageThreshold??80;if(!Ct(s))return S({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 S({threshold:i,uncovered:a,count:a.length})}async function xs(r,e){let{root:t}=e,s=[...(await r.ensureFresh(t)).nodes.values()].filter(o=>o.type==="markdown"&&o.staleFor&&o.staleFor.length>0).map(o=>({doc:o.path,staleFor:o.staleFor}));return S({staleDocs:s,count:s.length})}async function bs(r,e){let{root:t,metric:n="cognitiveComplexity",threshold:s=10,limit:o=20}=e,i=await r.ensureFresh(t),a=kt(i,{metric:n,threshold:s,limit:o});return S({metric:n,threshold:s,functions:a,count:a.length})}async function Ss(r,e){let{root:t,minLines:n=6,ignoreLiterals:s=!0,maxPunctuationRatio:o=.5,limit:i=50}=e,a=await r.ensureFresh(t),c=e.ignoreDirs??[...j,...r.getConfig(t)?.ignoreDirs??[]],{groups:l}=await ht(a,t,{minLines:n,ignoreLiterals:s,maxPunctuationRatio:o,limit:i,ignoreDirs:c,tokenCache:r.getDuplicationTokenCache(t)});return S({minLines:n,groups:l,count:l.length})}async function ks(r,e){let{root:t,changedFiles:n,featureThreshold:s,format:o="tags"}=e,i=await r.ensureFresh(t),a=n??new He().getChangedFiles().map(p=>te.relative(t,te.resolve(t,p))),c=s!==void 0?{featureDetection:{minOutDegree:s}}:void 0;if(o==="paths"){let p=ir(i,a,c);return S({changedFiles:a,affectedTests:p,count:p.length})}let l=or(i,a,c);return S({changedFiles:a,proposedTags:l})}async function vs(r,e){let{root:t,entryPoints:n,featureThreshold:s}=e,o=n?await r.getOrBuild(t,n.map(c=>te.resolve(t,c))):await r.ensureFresh(t),i=W(o.nodes,s!==void 0?{minOutDegree:s}:void 0),a=Array.from(i.values()).sort((c,l)=>l.outDegree-c.outDegree);return S({features:a,count:a.length})}async function ws(r,e){let{root:t,entryPoints:n,filter:s,mermaid:o=!1,slim:i=!0}=e,a=n?await r.getOrBuild(t,n.map(l=>te.resolve(t,l))):await r.ensureFresh(t),c=Ge(a.serialize(),_e(s));return o?S(Pe.serialize(D.deserialize(c))):i?S(vt(c)):S(c)}async function Cs(r,e){let{root:t}=e,n=await r.ensureFreshWorkspace(t);return S(wt(n))}async function Fs(r,e){let{root:t,file:n}=e,o=(await r.ensureFreshWorkspace(t)).getAffectedAcrossPackages(n);return S({file:n,affected:o,count:o.length})}function Ts(r,e){let{root:t}=e,n=r.invalidate(t);return S({root:t,cleared:n,message:n?"Cache cleared. Call analyze to rebuild.":"No cache was present for this root."})}async function Es(r,e){let{root:t,type:n}=e,s=await r.ensureFresh(t),o=Et(s);if(n)return S(Pt(o,n));let i=Array.from(o.types.values());return S({count:i.length,types:i})}async function Ps(r,e){let{root:t,paths:n,minOutDegree:s}=e,o=await r.ensureFresh(t),i=Ft(o,s!==void 0?{minOutDegree:s}:void 0);if(n?.length){let c=n.map(l=>i.get(l)).filter(Boolean);return S({count:c.length,modules:c})}let a=Array.from(i.values());return S({count:a.length,modules:a})}async function As(r,e){let{root:t,minOutDegree:n}=e,s=await r.ensureFresh(t),o=oe(s,n!==void 0?{minOutDegree:n}:void 0),i=Object.fromEntries(o.features);return S({features:i,unassigned:o.unassigned})}async function Ns(r,e){let{root:t,function:n}=e,s=await r.ensureFresh(t);return S(ut(s,n))}async function Is(r,e){let{root:t,name:n}=e,s=await r.ensureFresh(t),o=Tt(s,n);return S({name:n,matches:o,count:o.length})}async function Ms(r,e){let{root:t,entryPoints:n}=e,s=await r.ensureFresh(t),o=n?.length?n:lt(s,t);if(o.length===0)throw new Error("No entry points found. Pass entryPoints explicitly or ensure package.json has a main/exports field.");return S(pt(s,o))}async function Ds(r,e){let t=await r.ensureFresh(e.root),n=await Kt(t,e.root,{dryRun:e.dryRun??!1});return S(n)}var Rs=[{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. Set testsOnly=true to get only test files. Set cached=true to use a pre-computed O(1) lookup cache instead of graph traversal \u2014 faster on repeated calls for the same root. Pass changedSymbols to restrict blast-radius to files that actually import those symbols \u2014 omit to treat the whole file as changed. Set withMeta=true to get { path, category, exports } objects instead of bare path strings.",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:"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_duplicates",description:"Find duplicated code blocks across the project, largest-first. Two matching strategies, picked per file: CSS/SCSS/Less are compared structurally by rule body \u2014 the literal, ordered property:value declarations a rule contains, independent of its selector \u2014 so a genuine copy-pasted declaration list is caught while rules that merely share shape (e.g. display:flex vs display:block) never match. Every other language mokosh parses (TypeScript/JavaScript, Python, Go, CoffeeScript, LiveScript, Lua, Gherkin, Markdown, and Stylus) is tokenized and matched via a suffix array over the whole candidate token stream instead, partitioned by language family so matching never crosses between Stylus and code languages \u2014 exact and complete regardless of how repetitive the repo is, with no truncation caveat. Identifiers \u2014 and by default literals \u2014 are normalized before matching in the token-based path, so renamed-variable copies are still caught; blocks that are mostly object/array-literal structural punctuation (e.g. schema/object-literal boilerplate) rather than substantive shared logic are gated out. A block repeated N times across the project is reported once with N occurrences, not as separate pairs. Lock files (package-lock.json, yarn.lock, pnpm-lock.yaml) and files under an ignored directory are always excluded, even if the graph itself contains them. On large repos, tokenizing is offloaded to a worker pool and tokenized files are cached per session, so repeated calls against an unchanged root only re-tokenize what actually changed. Requires a prior analyze() call.",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."},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, or path. Returns matching nodes as JSON or a Mermaid diagram. If entryPoints is omitted the cached graph from a prior 'analyze' call is used.",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 typically 85\u201395% fewer tokens than a full graph query.",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: TypeScript/JavaScript, Go, and Python get function-level callers (via call edges) \u2014 though coverage differs per language (Go only tracks package-qualified calls, Python only tracks bare calls to `from module import name` symbols); everything else (CoffeeScript, LiveScript, Lua, Gherkin, Markdown, CSS/SCSS/Stylus) falls back to whole-file dependents, which is import-level only \u2014 a listed importer might not even use this specific export. Files whose parser never records exports (CoffeeScript, LiveScript, Lua, Gherkin, Markdown, CSS/SCSS/Stylus) never appear as matches, so a name that only exists in one of those returns an empty result, same as a typo. Each match's `precision` field is 'call' | 'file-level' \u2014 check it before trusting caller/importer results as symbol-exact.",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. Expands export* chains so every symbol accessible to consumers is listed (not just those directly declared in the entry file). Each export is resolved to its defining file and tagged with a kind (function/class/interface/type/enum/const). The graph is partitioned into: internalFiles (implementation reachable from entry points), unreachableFromEntry (non-test files not reachable from any entry point \u2014 may be separate consumers like CLI/MCP, config, or dead code), and testFiles (test suite). Supports multiple public entry points for libraries with sub-path exports. Requires a prior analyze() call. When entryPoints is omitted, auto-detects all entry points from package.json exports/main/module.",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 for a project root, forcing the next analyze() call to rebuild from disk. Call this after editing source files mid-session \u2014 otherwise get_affected, get_dependencies, and other query tools will 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. Tags of kind 'import' (filename-derived) and 'comment-marker' (domain semantic, propagated from source files) are written as an idempotent block. Re-running is safe: the existing block is replaced in place. Tags already present in the file are excluded from the block to avoid duplication. Supports TypeScript/JavaScript (// <mokosh-tags> block with // @tag lines) and Gherkin .feature files (# <mokosh-tags> block with @tagname lines). Use dryRun=true to preview changes without writing to disk. Requires a prior analyze() call.",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 cr(){let r=new Ze,e=new Jc({name:"mokosh",version:"0.0.1"},{capabilities:{tools:{}}});return e.setRequestHandler(Hc,async()=>({tools:Rs})),e.setRequestHandler(Vc,async t=>{let{name:n,arguments:s}=t.params,o=s,a={analyze:c=>ps(r,c),get_dependencies:c=>us(r,c),get_dependents:c=>fs(r,c),get_affected:c=>ms(r,c),get_callers:c=>gs(r,c),find_symbol:c=>Is(r,c),find_unused:c=>ds(r,c),find_uncovered:c=>ys(r,c),list_tags:c=>hs(r,c),check_doc_drift:c=>xs(r,c),find_complex_functions:c=>bs(r,c),find_duplicates:c=>Ss(r,c),propose_tags:c=>ks(r,c),detect_features:c=>vs(r,c),get_type_graph:c=>Es(r,c),get_module_responsibility:c=>Ps(r,c),get_feature_graph:c=>As(r,c),get_call_graph:c=>Ns(r,c),get_api_surface:c=>Ms(r,c),query:c=>ws(r,c),get_workspace_packages:c=>Cs(r,c),get_workspace_affected:c=>Fs(r,c),clear_cache:c=>Ts(r,c),apply_tags:c=>Ds(r,c)}[n];if(!a)throw new Error(`Unknown tool: ${n}`);try{return ls(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 qc(){let r=cr(),e=new Qc;await r.connect(e)}qc().catch(console.error);export{cr as createMcpServer};
|
|
33
|
+
`),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=Ce.readdirSync(o,{withFileTypes:!0})}catch{continue}for(let a of i)if(a.isDirectory())ns.has(a.name)||s.push(E.join(o,a.name));else if(a.isFile()&&(n++,n>=r))return!0}return n>=r}async processTestFiles(e){let r=re(),n=o=>r.some(i=>o.name.includes(i));this.walkProject(e,n);let s=e;for(;s!==this.rootDir;){let o=E.dirname(s);if(o===s)break;for(let i of Vc){let a=E.join(o,i);try{Ce.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=Ce.readdirSync(e,{withFileTypes:!0})}catch{return}for(let s of n){let o=E.join(e,s.name);s.isDirectory()?ns.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=Ce.statSync(e,{throwIfNoEntry:!1});if(!r?.isFile())return;let n=E.relative(this.rootDir,e),s=await this.getNode(e,n,r);s.imports=await this.resolveImports(e,s.imports),qn(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=Ce.readFileSync(e,"utf-8");try{return await this.parseContent(e,n)}catch(s){return process.stderr.write(`
|
|
34
|
+
Warning: failed to parse ${r}: ${s}
|
|
35
|
+
`),null}}parseContent(e,r){return this.pool?this.pool.run({filePath:e,content:r}):Hn(e,r)}makeStubNode(e,r,n){return{path:r,type:G(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:E.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:d,functions:h}=s;return{path:r,type:G(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}:{},...d!==void 0?{cognitiveComplexity:d}:{},...h!==void 0?{functions:h}:{}}}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)for(let i of o){let a={...s,toPath:i.isExternal?i.path:E.relative(this.rootDir,i.path),isExternal:i.isExternal};i.isWorkspace&&(a.isWorkspace=!0,a.workspacePackage=i.workspacePackage),i.isExternal?this.attachLockfileVersion(a):this.enqueue(i.path),n.push(a)}}return n}attachLockfileVersion(e){if(!this.lockFile)return;let r=e.rawSpecifier.startsWith("@")?e.rawSpecifier.split("/").slice(0,2).join("/"):e.rawSpecifier.split("/")[0],n=r?this.lockFile.dependencies[r]:void 0;n&&(e.version=n.version)}showProgress(){this.progressCallback&&this.visited.size%100===0&&this.progressCallback(this.visited.size)}};function ss(t,e){return{identifier:e?.identifier??new qe,featureMap:e?.featureDetection===!1?new Map:z(t.nodes,e?.featureDetection??void 0)}}function os(t,e,r,n,s){for(let o of e){let i=t.nodes.get(o);if(!i)continue;let a=new W(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 pr(t,e,r){let{identifier:n,featureMap:s}=ss(t,r),o=new Set;for(let i of e){let a=s.get(i);a&&o.add(a.tag)}return os(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 ur(t,e,r){let{identifier:n,featureMap:s}=ss(t,r),o=new Set;return os(t,e,s,()=>{},i=>{n.isTestNode(i)&&o.add(i.path)}),Array.from(o)}import Yc from"fs";import Fe from"path";async function is(t,e,r=null,n={}){let s=n.silent?void 0:a=>{process.stderr.write(`Processed ${a} files...\r`)},o=Fe.resolve(t);return await new we(o,r,n.pathAliases?new J(o,{pathAliases:n.pathAliases}):void 0,s,n.gitStats??!1,n.coverageMap??new Map,n.parallelParsing??!0).build(e)}async function as(t,e={}){let r=Fe.resolve(t),n=fe(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 me(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 we(r,null,new J(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}function cs(t,e={}){let r=[],n=new Set([...e.ignoreDirs??j,...e.additionalIgnoreDirs??[]]),s=new Set([...e.extensions??ut,...e.additionalExtensions??[]]);function o(i){try{let a=Yc.readdirSync(i,{withFileTypes:!0});for(let c of a){let l=Fe.join(i,c.name);c.isDirectory()?n.has(c.name)||o(l):c.isFile()&&s.has(Fe.extname(c.name).toLowerCase())&&r.push(Fe.relative(t,l))}}catch{}}return o(t),r}var ls=/(?:^|[/\\])(?:node_modules|\.git|dist|build|coverage)(?:[/\\]|$)/;function ps(t){return Zc.join(t,lt,pt)}var rt=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=await is(e,r,this.graphs.get(e)??null,{...V(s),coverageMap:n});return this.graphs.set(e,o),o}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 as(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=yt(n);return this.changeImpactCaches.set(e,s),s}storeLastAnalyze(e,r){this.lastAnalyze.set(e,r)}startWatching(e){if(!this.watchers.has(e))try{let r=Xc.watch(e,{recursive:!0},(n,s)=>{!s||ls.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,V(r))}async getDuplicationTokenCache(e){let r=this.duplicationTokenCaches.get(e);return r||(r=Re(ps(e)),this.duplicationTokenCaches.set(e,r)),r}flushDuplicationTokenCache(e){let r=this.duplicationTokenCaches.get(e);if(r)try{Le(r,ps(e))}catch(n){process.stderr.write(`Warning: failed to persist duplication token cache: ${n}
|
|
36
|
+
`)}}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),r}};import te from"path";import el from"fs";import tl from"os";import fr from"path";function S(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function us(t){if(!fr.isAbsolute(t))throw new Error("root must be an absolute path");let e=fr.resolve(t),r=tl.homedir();if(e!==r&&!e.startsWith(r+fr.sep))throw new Error("root must be within the user home directory");let n;try{n=el.statSync(e)}catch{throw new Error("root does not exist")}if(!n.isDirectory())throw new Error("root is not a directory")}async function fs(t,e){let{root:r,entryPoints:n}=e;if(!t.isConfigured(r)){let d=ne(r,{allowJs:!1});ct(d),t.storeConfig(r,d)}if(n.length===0){let d=fe(r);if(d.type!=="none"){let h=t.getConfig(r),k=await t.getOrBuildWorkspace(r,V(h));t.storeLastAnalyze(r,{kind:"workspace"}),t.startWatching(r);let x=Array.from(k.packages.values()).map(({graph:y,pkg:C})=>({package:C.name,relativeRoot:C.relativeRoot,nodeCount:y.nodes.size}));return S({monorepoType:d.type,packageCount:k.packages.size,packages:x})}}let s=n.map(d=>te.resolve(r,d)),o=t.getConfig(r),i=o?.coverageReportPath?ft(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((d,h)=>(d[h.category]=(d[h.category]??0)+1,d),{}),p=a.findCycles(),u=vt(a);return S({nodeCount:c.nodes.length,categories:l,cycles:p,languageCoverage:u})}async function ms(t,e){let{root:r,file:n,depth:s=1,withMeta:o=!1}=e,i=await t.ensureFresh(r),a=Ct(i,n,s),c=o?a.map(l=>({...l,...ce(i,l.path)})):a;return S({file:n,dependencies:c})}async function gs(t,e){let{root:r,file:n,withMeta:s=!1}=e,o=await t.ensureFresh(r),i=le(o,n),a=s?i.map(c=>({...c,...ce(o,c.path)})):i;return S({file:n,dependents:a})}async function ds(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=d=>a?d.map(h=>({path:h,...ce(c,h)})):d;if(o){let d=t.getOrBuildChangeImpact(r),h=xt(d,n),k=s?h.filter(y=>c.nodes.get(y)?.category==="test"):h,x=l(k);return S({file:n,affected:x,count:x.length})}let p=wt(c,n,{testsOnly:s,changedSymbols:i}),u=l(p);return S({file:n,affected:u,count:u.length})}async function hs(t,e){let{root:r,file:n,depth:s=1,withEdgeDetail:o=!1}=e,i=await t.ensureFresh(r),a=Ft(i,n,{depth:s,withEdgeDetail:o});return S({file:n,callers:a,count:a.length})}async function ys(t,e){let{root:r,entryPoints:n}=e,s=n?await t.getOrBuild(r,n.map(a=>te.resolve(r,a))):await t.ensureFresh(r),o=cs(r),i=s.findUnusedFiles(o);return S({unusedFiles:i,count:i.length})}async function xs(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 S({tags:o,count:o.length})}async function bs(t,e){let{root:r,coverageThreshold:n}=e,s=await t.ensureFresh(r),o=t.getConfig(r),i=n??o?.coverageThreshold??80;if(!Pt(s))return S({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 S({threshold:i,uncovered:a,count:a.length})}async function Ss(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 S({staleDocs:s,count:s.length})}async function ks(t,e){let{root:r,metric:n="cognitiveComplexity",threshold:s=10,limit:o=20}=e,i=await t.ensureFresh(r),a=Tt(i,{metric:n,threshold:s,limit:o});return S({metric:n,threshold:s,functions:a,count:a.length})}async function vs(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??[...j,...t.getConfig(r)?.ignoreDirs??[]],{groups:l}=await kt(a,r,{minLines:n,ignoreLiterals:s,maxPunctuationRatio:o,limit:i,ignoreDirs:c,tokenCache:await t.getDuplicationTokenCache(r)});return t.flushDuplicationTokenCache(r),S({minLines:n,groups:l,count:l.length})}async function Cs(t,e){let{root:r,changedFiles:n,featureThreshold:s,format:o="tags"}=e,i=await t.ensureFresh(r),a=n??new Ye().getChangedFiles().map(p=>te.relative(r,te.resolve(r,p))),c=s!==void 0?{featureDetection:{minOutDegree:s}}:void 0;if(o==="paths"){let p=ur(i,a,c);return S({changedFiles:a,affectedTests:p,count:p.length})}let l=pr(i,a,c);return S({changedFiles:a,proposedTags:l})}async function ws(t,e){let{root:r,entryPoints:n,featureThreshold:s}=e,o=n?await t.getOrBuild(r,n.map(c=>te.resolve(r,c))):await t.ensureFresh(r),i=z(o.nodes,s!==void 0?{minOutDegree:s}:void 0),a=Array.from(i.values()).sort((c,l)=>l.outDegree-c.outDegree);return S({features:a,count:a.length})}async function Fs(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=>te.resolve(r,l))):await t.ensureFresh(r),c=je(a.serialize(),ze(s));return o?S(Pe.serialize(M.deserialize(c))):i?S(Et(c)):S(c)}async function Ts(t,e){let{root:r}=e,n=await t.ensureFreshWorkspace(r);return S(At(n))}async function Es(t,e){let{root:r,file:n}=e,o=(await t.ensureFreshWorkspace(r)).getAffectedAcrossPackages(n);return S({file:n,affected:o,count:o.length})}function As(t,e){let{root:r}=e,n=t.invalidate(r);return S({root:r,cleared:n,message:n?"Cache cleared. Call analyze to rebuild.":"No cache was present for this root."})}async function Ps(t,e){let{root:r,type:n}=e,s=await t.ensureFresh(r),o=Dt(s);if(n)return S(Mt(o,n));let i=Array.from(o.types.values());return S({count:i.length,types:i})}async function Ns(t,e){let{root:r,paths:n,minOutDegree:s}=e,o=await t.ensureFresh(r),i=Nt(o,s!==void 0?{minOutDegree:s}:void 0);if(n?.length){let c=n.map(l=>i.get(l)).filter(Boolean);return S({count:c.length,modules:c})}let a=Array.from(i.values());return S({count:a.length,modules:a})}async function Is(t,e){let{root:r,minOutDegree:n}=e,s=await t.ensureFresh(r),o=ie(s,n!==void 0?{minOutDegree:n}:void 0),i=Object.fromEntries(o.features);return S({features:i,unassigned:o.unassigned})}async function Ds(t,e){let{root:r,function:n}=e,s=await t.ensureFresh(r);return S(ht(s,n))}async function Ms(t,e){let{root:r,name:n}=e,s=await t.ensureFresh(r),o=It(s,n);return S({name:n,matches:o,count:o.length})}async function Rs(t,e){let{root:r,entryPoints:n}=e,s=await t.ensureFresh(r),o=n?.length?n:gt(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 S(dt(s,o))}async function Ls(t,e){let r=await t.ensureFresh(e.root),n=await qt(r,e.root,{dryRun:e.dryRun??!1});return S(n)}var Gs=[{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. Set testsOnly=true to get only test files. Set cached=true to use a pre-computed O(1) lookup cache instead of graph traversal \u2014 faster on repeated calls for the same root. Pass changedSymbols to restrict blast-radius to files that actually import those symbols \u2014 omit to treat the whole file as changed. Set withMeta=true to get { path, category, exports } objects instead of bare path strings.",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:"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_duplicates",description:"Find duplicated code blocks across the project, largest-first. Two matching strategies, picked per file: CSS/SCSS/Less are compared structurally by rule body \u2014 the literal, ordered property:value declarations a rule contains, independent of its selector \u2014 so a genuine copy-pasted declaration list is caught while rules that merely share shape (e.g. display:flex vs display:block) never match. Every other language mokosh parses (TypeScript/JavaScript, Python, Go, CoffeeScript, LiveScript, Lua, Gherkin, Markdown, and Stylus) is tokenized and matched via a suffix array over the whole candidate token stream instead, partitioned by language family so matching never crosses between Stylus and code languages \u2014 exact and complete regardless of how repetitive the repo is, with no truncation caveat. Identifiers \u2014 and by default literals \u2014 are normalized before matching in the token-based path, so renamed-variable copies are still caught; blocks that are mostly object/array-literal structural punctuation (e.g. schema/object-literal boilerplate) rather than substantive shared logic are gated out. A block repeated N times across the project is reported once with N occurrences, not as separate pairs. Lock files (package-lock.json, yarn.lock, pnpm-lock.yaml) and files under an ignored directory are always excluded, even if the graph itself contains them. On large repos, tokenizing is offloaded to a worker pool and tokenized files are cached per session, so repeated calls against an unchanged root only re-tokenize what actually changed. Requires a prior analyze() call.",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."},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, or path. Returns matching nodes as JSON or a Mermaid diagram. If entryPoints is omitted the cached graph from a prior 'analyze' call is used.",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 typically 85\u201395% fewer tokens than a full graph query.",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: TypeScript/JavaScript, Go, and Python get function-level callers (via call edges) \u2014 though coverage differs per language (Go only tracks package-qualified calls, Python only tracks bare calls to `from module import name` symbols); everything else (CoffeeScript, LiveScript, Lua, Gherkin, Markdown, CSS/SCSS/Stylus) falls back to whole-file dependents, which is import-level only \u2014 a listed importer might not even use this specific export. Files whose parser never records exports (CoffeeScript, LiveScript, Lua, Gherkin, Markdown, CSS/SCSS/Stylus) never appear as matches, so a name that only exists in one of those returns an empty result, same as a typo. Each match's `precision` field is 'call' | 'file-level' \u2014 check it before trusting caller/importer results as symbol-exact.",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. Expands export* chains so every symbol accessible to consumers is listed (not just those directly declared in the entry file). Each export is resolved to its defining file and tagged with a kind (function/class/interface/type/enum/const). The graph is partitioned into: internalFiles (implementation reachable from entry points), unreachableFromEntry (non-test files not reachable from any entry point \u2014 may be separate consumers like CLI/MCP, config, or dead code), and testFiles (test suite). Supports multiple public entry points for libraries with sub-path exports. Requires a prior analyze() call. When entryPoints is omitted, auto-detects all entry points from package.json exports/main/module.",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 for a project root, forcing the next analyze() call to rebuild from disk. Call this after editing source files mid-session \u2014 otherwise get_affected, get_dependencies, and other query tools will 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. Tags of kind 'import' (filename-derived) and 'comment-marker' (domain semantic, propagated from source files) are written as an idempotent block. Re-running is safe: the existing block is replaced in place. Tags already present in the file are excluded from the block to avoid duplication. Supports TypeScript/JavaScript (// <mokosh-tags> block with // @tag lines) and Gherkin .feature files (# <mokosh-tags> block with @tagname lines). Use dryRun=true to preview changes without writing to disk. Requires a prior analyze() call.",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 mr(){let t=new rt,e=new rl({name:"mokosh",version:"0.0.1"},{capabilities:{tools:{}}});return e.setRequestHandler(sl,async()=>({tools:Gs})),e.setRequestHandler(nl,async r=>{let{name:n,arguments:s}=r.params,o=s,a={analyze:c=>fs(t,c),get_dependencies:c=>ms(t,c),get_dependents:c=>gs(t,c),get_affected:c=>ds(t,c),get_callers:c=>hs(t,c),find_symbol:c=>Ms(t,c),find_unused:c=>ys(t,c),find_uncovered:c=>bs(t,c),list_tags:c=>xs(t,c),check_doc_drift:c=>Ss(t,c),find_complex_functions:c=>ks(t,c),find_duplicates:c=>vs(t,c),propose_tags:c=>Cs(t,c),detect_features:c=>ws(t,c),get_type_graph:c=>Ps(t,c),get_module_responsibility:c=>Ns(t,c),get_feature_graph:c=>Is(t,c),get_call_graph:c=>Ds(t,c),get_api_surface:c=>Rs(t,c),query:c=>Fs(t,c),get_workspace_packages:c=>Ts(t,c),get_workspace_affected:c=>Es(t,c),clear_cache:c=>As(t,c),apply_tags:c=>Ls(t,c)}[n];if(!a)throw new Error(`Unknown tool: ${n}`);try{return us(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 il(){let t=mr(),e=new ol;await t.connect(e)}il().catch(console.error);export{mr as createMcpServer};
|
|
36
37
|
//# sourceMappingURL=mcp.mjs.map
|