@omfalos/mokosh 0.5.0 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +104 -56
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +104 -56
- package/dist/cli.mjs.map +1 -1
- package/dist/duplication-worker.d.mts +1 -1
- package/dist/duplication-worker.d.ts +1 -1
- package/dist/duplication-worker.js +6 -4
- package/dist/duplication-worker.js.map +1 -1
- package/dist/duplication-worker.mjs +6 -4
- package/dist/duplication-worker.mjs.map +1 -1
- package/dist/index.d.mts +1164 -48
- package/dist/index.d.ts +1164 -48
- package/dist/index.js +48 -37
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +48 -37
- package/dist/index.mjs.map +1 -1
- package/dist/mcp.js +52 -39
- package/dist/mcp.js.map +1 -1
- package/dist/mcp.mjs +52 -39
- package/dist/mcp.mjs.map +1 -1
- package/dist/parse-worker.d.mts +1 -1
- package/dist/parse-worker.d.ts +1 -1
- package/dist/parse-worker.js +6 -6
- package/dist/parse-worker.js.map +1 -1
- package/dist/parse-worker.mjs +6 -6
- package/dist/parse-worker.mjs.map +1 -1
- package/dist/{tokenizer-DIbb0GLe.d.mts → tokenizer-D9P-y7lH.d.mts} +1 -1
- package/dist/{tokenizer-DIbb0GLe.d.ts → tokenizer-D9P-y7lH.d.ts} +1 -1
- package/dist/{types-y90pqeDR.d.ts → types-B4jVIqMD.d.ts} +7 -0
- package/dist/{types-C153Tz5u.d.mts → types-qfwcXiZS.d.mts} +7 -0
- package/package.json +1 -1
- package/templates/skill/SKILL.md +1 -1
- package/templates/skill/mokosh.md +1 -1
package/dist/mcp.js
CHANGED
|
@@ -1,53 +1,66 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`)}};var gr=g(require("fs")),Kn=g(require("path"));function dr(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 qn(t,e){if(typeof t=="string")return dr(t,e);if(t&&typeof t=="object"){let r=t;for(let n of["import","require","default"]){let s=qn(r[n],e);if(s)return s}}return null}function wa(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 Ea(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 hr(t,e){let r=[],n=Kn.default.join(e,"package.json");if(gr.default.existsSync(n))try{let s=JSON.parse(gr.default.readFileSync(n,"utf8"));if(s.exports&&typeof s.exports=="object"&&!Array.isArray(s.exports))for(let o of Object.values(s.exports)){let i=qn(o,t);i&&!r.includes(i)&&r.push(i)}else if(typeof s.exports=="string"){let o=dr(s.exports,t);o&&r.push(o)}if(r.length===0)for(let o of[s.main,s.module].filter(Boolean)){let i=dr(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 Fa(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 Ta(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 Pa(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(m=>m.name===o))??n[0],p={name:o,definedIn:l,kind:wa(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 Aa(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 yr(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=Fa(t,e),n=Ta(t,r,e),s=Ea(t,e),o=Pa(s,n,t,e),{internalFiles:i,unreachableFromEntry:a,testFiles:c}=Aa(t,r,e);return{entryPoints:e,publicExports:o,internalFiles:i,unreachableFromEntry:a,testFiles:c}}function xr(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}}var Na=g(require("fs")),Da=g(require("path"));function Vn(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 br(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:Vn(t)}}function Sr(t,e){return t.impact.get(e)??[]}var jo=g(require("path"));var ce=g(require("fs")),vr=g(require("path"));var Ie=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 A=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 m of s(c))a(m,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 Ie(this.nodes).findUnusedFiles(e)}findCycles(){return new Ie(this.nodes).findCycles()}};function ft(t){return vr.default.join(t,ae,pr)}function Qn(t,e){return vr.default.join(ft(t),`${e}.json`)}function Yn(t,e){let r=Qn(t,e);if(!ce.default.existsSync(r))return null;try{let n=ce.default.readFileSync(r,"utf-8");return A.deserialize(JSON.parse(n))}catch{return null}}function Zn(t,e,r){let n=ft(t);ce.default.existsSync(n)||ce.default.mkdirSync(n,{recursive:!0}),ce.default.writeFileSync(Qn(t,e),JSON.stringify(r.serialize()))}var xe=g(require("fs")),F=g(require("path")),yo=g(require("piscina"));var mt=require("child_process"),gt=class{getChangedFiles(e,r){try{let s=[["diff","--name-only"],["diff","--cached","--name-only"],["ls-files","--others","--exclude-standard"],...r?[["diff","--name-only","--end-of-options",`${r}...HEAD`]]:[]].flatMap(o=>{try{return(0,mt.execFileSync)("git",o,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
4
|
-
`).map(a=>a.trim()).filter(a=>a!=="")}catch{return[]}});return Array.from(new Set(s))}catch(
|
|
5
|
-
`)){if(s.startsWith("\0")){let[,c,l]=s.slice(1).split(" ");
|
|
6
|
-
`).filter(c=>c.trim().length>0&&!c.trim().startsWith("#"));if(
|
|
7
|
-
`&&
|
|
8
|
-
`)){let s=
|
|
9
|
-
`),
|
|
10
|
-
`),o=[],i=new Set;for(let l of s){let p=l.match(yc);if(p?.[1]){o.push(he(t,p[1]));continue}let u=l.match(xc);if(u?.[2]){i.add(u[2]);continue}let m=l.match(bc);if(m?.[1]){i.add(m[1]);continue}let h=l.match(Sc);h?.[1]&&i.add(h[1])}let a=I(e,!1);a&&o.push(B(t,a));let c=Array.from(i,l=>({name:l}));return{imports:o,exports:c,tags:Array.from(r).map(l=>({name:l,kind:"comment-marker"})),category:O(t,o.map(l=>l.rawSpecifier),{typeNames:[...i],annotations:de(e).annotations})}}var Ds=g(require("livescript"));function Q(t){if(t){if(typeof t.value=="string")return t.value;if(typeof t.base?.value=="string")return t.base.value}}function vc(t){if(!t)return[];if(t.constructor?.name==="Class"){let r=Q(t.title);return r?[{name:r}]:[]}if(t.constructor?.name==="Obj"&&Array.isArray(t.items))return t.items.map(r=>Q(r.key)??Q(r.val)).filter(r=>!!r).map(r=>({name:r}));let e=Q(t);return e?[{name:e}]:[]}function kc(t){let e=t.constructor?.name||t.type;if(e==="Assign"&&t.left?.constructor?.name==="Chain"){let r=t.left,n=Q(r.head),o=r.tails?.[0]?.key?.name;if(n==="module"&&o==="exports")return vc(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=>Q(n.val)??Q(n.key)).filter(n=>!!n).map(n=>({name:n}))}return[]}var Cc=new Set(["first_line","first_column","last_line","last_column","line","column"]);function wc(t,e){let r=t.constructor?.name||t.type;if(r==="Import"){let n=t.right?.value;if(typeof n=="string"){let s=W(n);return{fromPath:e,toPath:"",rawSpecifier:s,isStyle:N(s),type:"static"}}}if(r==="Chain"&&t.head?.value==="require"){let n=t.tails?.[0];if(n?.constructor?.name==="Call"||n?.type==="Call"){let s=n.args?.[0]?.value;if(typeof s=="string"){let o=W(s);return{fromPath:e,toPath:"",rawSpecifier:o,isStyle:N(o),type:"require"}}}}return null}function _r(t,e,r){if(!t||typeof t!="object")return[];let n=[],s=wc(t,e);s&&n.push(s),r.push(...kc(t));for(let o in t){if(Cc.has(o))continue;let i=t[o];if(!(!i||typeof i!="object"))if(Array.isArray(i))for(let a of i)n.push(..._r(a,e,r));else n.push(..._r(i,e,r))}return n}function Rs(t,e){let r=le(e),n=pe(t,r),s=[],o=[];try{s=_r(Ds.default.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}}var Is=g(require("luaparse"));function Ec(t,e){let r=[];function n(s){if(!(!s||typeof s!="object")){if((s.type==="CallExpression"||s.type==="StringCallExpression")&&s.base?.type==="Identifier"&&s.base?.name==="require"){let o;if(s.type==="CallExpression"){let i=s.arguments?.[0];i?.type==="StringLiteral"&&(o=W(i.raw))}else if(s.type==="StringCallExpression"){let i=s.argument;i?.type==="StringLiteral"&&(o=W(i.raw))}o&&r.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:N(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 Fc(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 Tc(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 Pc(t){let e=t.body,r=Fc(e),n=Tc(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 Ms(t,e){let r=le(e),n=pe(t,r),s=[],o=[];try{let i=Is.default.parse(e);s=Ec(i,t),o=Pc(i)}catch{}return{imports:s,exports:o,tags:Array.from(r).map(i=>({name:i,kind:"comment-marker"})),category:n}}var Ac=["http://","https://","mailto:","//"],Nc="ts|tsx|js|jsx|mjs|cjs|py|go|lua|css|scss|less|styl|coffee|ls|feature|md|mdx|json",Dc=new RegExp(`(?:\\.{1,2}/)?[\\w.-]+(?:/[\\w.-]+)*\\.(?:${Nc})\\b`,"g"),Ls;async function Rc(){return Ls??=(async()=>{let{unified:t}=await import("unified"),e=(await import("remark-parse")).default;return t().use(e)})(),Ls}function Ic(t){let e=t.trim();return e.length===0||e.startsWith("#")||Ac.some(r=>e.startsWith(r))}function Mc(t,e){let r=t.match(Dc);return r?r.map(n=>({fromPath:e,toPath:"",rawSpecifier:n,isStyle:!1,type:"static"})):[]}function _s(t,e,r){if(t.type==="link"&&typeof t.url=="string"&&!Ic(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(...Mc(t.value,e)),Array.isArray(t.children))for(let n of t.children)_s(n,e,r)}async function Gs(t,e){let n=(await Rc()).parse(e),s=[];_s(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"}}var zs=g(require("path")),Ws=require("@lezer/python");function Lc(t){let e=1;function r(n){switch(n.type.name){case"IfStatement":{e+=q(n).filter(o=>o.type.name==="if"||o.type.name==="elif").length;break}case"TryStatement":{e+=q(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 _c(t,e){let r=0,n=q(t),s=0,o=0;for(;o<n.length;){let i=n[o];if(i?.type.name==="if"||i?.type.name==="elif"){let a=s>0;r+=a?1:1+e;let c=a?e:e+1,l=n[o+1],p=n[o+2];l&&(r+=j(l,c)),p&&(r+=j(p,c)),s++,o+=3}else if(i?.type.name==="else"){r+=1;let a=n[o+1];a&&(r+=j(a,e+1)),o+=2}else o++}return r}function Gc(t,e){let r=0,n=q(t),s=0;for(;s<n.length;){let o=n[s];if(o?.type.name==="except"){for(r+=1+e,s++;s<n.length&&n[s]?.type.name!=="Body";)r+=j(n[s],e),s++;s<n.length&&(r+=j(n[s],e),s++)}else o?.type.name==="Body"&&(r+=j(o,e)),s++}return r}function Os(t,e){let r=1+e,n=t.firstChild;for(;n;)r+=j(n,e+1),n=n.nextSibling;return r}function Oc(t,e){let r=0,n=t.firstChild;for(;n;)r+=j(n,e),n=n.nextSibling;return r}function j(t,e){let r=t.type.name;switch(r){case"IfStatement":return _c(t,e);case"TryStatement":return Gc(t,e);case"ForStatement":case"WhileStatement":return Os(t,e);default:{let n=r==="ConditionalExpression"||r==="and"||r==="or"?1:0;return e>0&&(r==="FunctionDefinition"||r==="LambdaExpression")?n+Os(t,e):n+Oc(t,e)}}}function jc(t){return j(t,0)}function Gr(t){return{complexity:Lc(t),cognitiveComplexity:jc(t)}}function js(t,e){let r=[];function n(i,a){let{complexity:c,cognitiveComplexity:l}=Gr(i);r.push({name:a,line:V(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"),m=u?e.slice(u.from,u.to):void 0;m&&n(p,c?`${c}.${m}`:m),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 zc=new Set(["pytest","unittest","nose","hypothesis"]);function $s(t,e){let r=[],n=[],s=new Set,o=zs.default.basename(t).toLowerCase(),i=Ws.parser.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 Wc(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 v=a.node.getChild("VariableName");v&&n.push({name:e.slice(v.from,v.to)})}break}case"AssignStatement":{if(a.node.parent?.name==="Script"){let h=a.node.firstChild;h?.name==="VariableName"&&n.push({name:e.slice(h.from,h.to)})}break}}while(a.next());let c=Kc(o,r,s);c==="test"&&s.add("test");let{complexity:l,cognitiveComplexity:p}=Gr(i.topNode),u=js(i,e),m=c==="test"?[]:Jc(i,e);return{imports:r,exports:n,tags:Array.from(s).map(h=>({name:h,kind:"comment-marker"})),category:c,rawCallEdges:m,complexity:l,cognitiveComplexity:p,...u.length>0?{functions:u}:{}}}function Wc(t,e,r){let n=t.firstChild;return n?n.name==="from"?$c(t,e,r):Bc(t,e,r):[]}function $c(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=Hc(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[je(r,o,i,!0)];let l=a===1?"./":"../".repeat(a-1);return c?[je(r,l+c.replace(/\./g,"/"),i,!1)]:i[0]==="*"?[je(r,l.slice(0,-1),["*"],!1)]:i.map(p=>je(r,l+p,[p],!1))}function Bc(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(je(r,o,["*"],!0))}s=s.nextSibling}return n}function Hc(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 Uc(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 m=e.slice(u.from,u.to),h=m;if(u.nextSibling?.type.name==="as"){let v=u.nextSibling.nextSibling;v?.type.name==="VariableName"&&(h=e.slice(v.from,v.to),u=v)}let y=c===0?a:l?p+l.replace(/\./g,"/"):p+m;r.set(h,y)}u=u.nextSibling}}while(n.next());return r}function Jc(t,e){let r=Uc(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),m=r.get(u);m&&n.push({from:c,to:u,toSpecifier:m})}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 m=u.getChild("VariableName"),h=m?e.slice(m.from,m.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 je(t,e,r,n){return{fromPath:t,toPath:"",rawSpecifier:e,isStyle:!1,isExternal:n,type:"static",symbols:r.length>0?r:void 0}}function Kc(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=>zc.has(n.rawSpecifier))?"test":"logic"}var qc=/^\s*import\s+(.+?)\s*$/,Vc=/^(?:@\w+\s+)*(?:private\s+|protected\s+|final\s+|sealed\s+|abstract\s+|implicit\s+|case\s+)*(class|trait|object|type|enum)\s+([A-Za-z_$][A-Za-z0-9_$]*)/;function Qc(t,e){let r=e.split("=>")[0]?.trim();return r?r==="_"||r==="*"||r==="given"?`${t}.*`:`${t}.${r}`:null}function Yc(t){let e=t.indexOf("{");if(e!==-1){let n=t.indexOf("}",e),s=t.slice(0,e).trim().replace(/\.$/,""),o=t.slice(e+1,n===-1?void 0:n);return s?o.split(",").map(i=>Qc(s,i.trim())).filter(i=>i!=null):[]}let r=[];for(let n of t.split(",")){let s=n.trim().replace(/\s+as\s+\w+$/,"");if(s)if(s.endsWith("._")||s.endsWith(".*")||s.endsWith(".given")){let o=s.replace(/\.(_|\*|given)$/,"");o&&r.push(`${o}.*`)}else r.push(s)}return r}function Bs(t,e){let r=ge(e),s=$(e).split(`
|
|
11
|
-
`),o=[],i=new Set;for(let l of s){let p=l.match(qc);if(p?.[1]){for(let m of Yc(p[1]))o.push(he(t,m));continue}let u=l.match(Vc);u?.[2]&&i.add(u[2])}let a=I(e,!0);a&&o.push(B(t,a));let c=Array.from(i,l=>({name:l}));return{imports:o,exports:c,tags:Array.from(r).map(l=>({name:l,kind:"comment-marker"})),category:O(t,o.map(l=>l.rawSpecifier),{typeNames:[...i],annotations:de(e).annotations})}}var zr=g(require("path")),d=g(require("typescript"));var S=g(require("typescript"));function Zc(t){let e=1;function r(n){switch(n.kind){case S.default.SyntaxKind.IfStatement:case S.default.SyntaxKind.ConditionalExpression:case S.default.SyntaxKind.ForStatement:case S.default.SyntaxKind.ForInStatement:case S.default.SyntaxKind.ForOfStatement:case S.default.SyntaxKind.WhileStatement:case S.default.SyntaxKind.DoStatement:case S.default.SyntaxKind.CatchClause:case S.default.SyntaxKind.CaseClause:e++;break;case S.default.SyntaxKind.BinaryExpression:{let s=n.operatorToken.kind;(s===S.default.SyntaxKind.AmpersandAmpersandToken||s===S.default.SyntaxKind.BarBarToken||s===S.default.SyntaxKind.QuestionQuestionToken)&&e++;break}}S.default.forEachChild(n,r)}return r(t),e}function Us(t,e,r){let n=r?1:1+e,s=r?e:e+1;return n+=Y(t.expression,s,!1),n+=Y(t.thenStatement,s,!1),t.elseStatement&&(S.default.isIfStatement(t.elseStatement)?n+=Us(t.elseStatement,e,!0):n+=1+Y(t.elseStatement,e+1,!1)),n}function Hs(t,e){let r=1+e;return S.default.forEachChild(t,n=>{r+=Y(n,e+1,!1)}),r}function Xc(t,e){let r=1+e;return S.default.forEachChild(t,n=>{r+=Y(n,e,!1)}),r}function el(t,e){let r=0;return S.default.forEachChild(t,n=>{r+=Y(n,e,!1)}),r}function tl(t){let e=t.operatorToken.kind;return e===S.default.SyntaxKind.AmpersandAmpersandToken||e===S.default.SyntaxKind.BarBarToken||e===S.default.SyntaxKind.QuestionQuestionToken}function Y(t,e,r){if(S.default.isIfStatement(t))return Us(t,e,r);if(S.default.isForStatement(t)||S.default.isForInStatement(t)||S.default.isForOfStatement(t)||S.default.isWhileStatement(t)||S.default.isDoStatement(t)||S.default.isSwitchStatement(t))return Hs(t,e);if(S.default.isCatchClause(t))return Xc(t,e);let n=0;return S.default.isConditionalExpression(t)&&(n+=1),S.default.isBinaryExpression(t)&&tl(t)&&(n+=1),e>0&&(S.default.isFunctionDeclaration(t)||S.default.isFunctionExpression(t)||S.default.isArrowFunction(t))?n+Hs(t,e):n+el(t,e)}function rl(t){return Y(t,0,!1)}function Or(t){return{complexity:Zc(t),cognitiveComplexity:rl(t)}}var C=g(require("typescript")),jr=new Set(["test","describe","it"]);function Js(t,e){nl(t,e),ol(t,e),il(t,e),al(t,e)}function nl(t,e){if((C.default.isFunctionDeclaration(t)||C.default.isVariableDeclaration(t))&&t.name&&C.default.isIdentifier(t.name)&&sl(t)){let r;if(C.default.isFunctionDeclaration(t))r="function";else{let n=t.initializer;r=n&&(C.default.isArrowFunction(n)||C.default.isFunctionExpression(n))?"function":"variable"}e.tags.add({name:t.name.text,kind:r})}}function sl(t){if(C.default.isFunctionDeclaration(t))return C.default.isSourceFile(t.parent);let e=t.parent?.parent;return!!e&&C.default.isSourceFile(e.parent)}function ol(t,e){if(!C.default.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 il(t,e){if(!C.default.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 al(t,e){if(C.default.isCallExpression(t)&&cl(t.expression))for(let r of t.arguments)C.default.isObjectLiteralExpression(r)&&ll(r,e)}function cl(t){return C.default.isIdentifier(t)?jr.has(t.text):!!(C.default.isPropertyAccessExpression(t)&&(jr.has(t.name.text)||C.default.isIdentifier(t.expression)&&jr.has(t.expression.text)))}function ll(t,e){for(let r of t.properties){if(!C.default.isPropertyAssignment(r)||!C.default.isIdentifier(r.name)||r.name.text!=="tags"&&r.name.text!=="tag")continue;let{initializer:n}=r,s=C.default.isArrayLiteralExpression(n)?n.elements.filter(C.default.isStringLiteral):r.name.text==="tag"&&C.default.isStringLiteral(n)?[n]:[];for(let o of s)e.tags.add({name:o.text.replace(/^@/,""),kind:"comment-marker"})}}function Wr(t,e,r){let n=[],s=new Map,o=new Set,i=d.default.createSourceFile(t,e,d.default.ScriptTarget.Latest,!0,r==="typescript"?d.default.ScriptKind.TSX:d.default.ScriptKind.JSX),a={filePath:t,imports:n,exports:s,tags:o,rawCallEdges:[],sourceFile:i,hasUI:!1,hasTypesOnly:!0,totalStatements:0,exportStatements:0},c=v=>{ml(v,a),d.default.forEachChild(v,c)};c(i);let l=wl(t,a);(l==="test"||l==="barrel")&&o.add({name:l,kind:"comment-marker"}),l!=="test"&&El(a,i);let p=i.statements[0],u=p?qs(p):void 0,{complexity:m,cognitiveComplexity:h}=Or(i),y=pl(i);return{imports:n,exports:Array.from(s.values()),tags:Array.from(o),category:l,rawCallEdges:a.rawCallEdges??[],complexity:m,cognitiveComplexity:h,...y.length>0?{functions:y}:{},...u!==void 0?{description:u}:{}}}function pl(t){let e=[],r=(s,o)=>{let{complexity:i,cognitiveComplexity:a}=Or(o),c=t.getLineAndCharacterOfPosition(o.getStart(t)).line+1;e.push({name:s,line:c,complexity:i,cognitiveComplexity:a})},n=(s,o)=>{if(d.default.isFunctionDeclaration(s)&&s.name&&s.body?r(s.name.text,s):d.default.isVariableDeclaration(s)&&d.default.isIdentifier(s.name)&&s.initializer&&(d.default.isArrowFunction(s.initializer)||d.default.isFunctionExpression(s.initializer))?r(s.name.text,s.initializer):o&&d.default.isMethodDeclaration(s)&&d.default.isIdentifier(s.name)&&s.body?r(`${o}.${s.name.text}`,s):o&&d.default.isConstructorDeclaration(s)&&s.body?r(`${o}.constructor`,s):o&&d.default.isGetAccessorDeclaration(s)&&d.default.isIdentifier(s.name)&&s.body?r(`${o}.get ${s.name.text}`,s):o&&d.default.isSetAccessorDeclaration(s)&&d.default.isIdentifier(s.name)&&s.body&&r(`${o}.set ${s.name.text}`,s),d.default.isClassDeclaration(s)&&s.name){let i=s.name.text;d.default.forEachChild(s,a=>n(a,i));return}d.default.forEachChild(s,i=>n(i,o))};return n(t,void 0),e}function Ks(t,e,r,n){let s={name:t},o=qs(r);o!==void 0&&(s.doc=o);let i=ul(e);i!==void 0&&(s.flags=i);let a=fl(e,n);return a!==void 0&&(s.signature=a),s}function qs(t){let e=d.default.getJSDocCommentsAndTags(t);for(let r of e)if(d.default.isJSDoc(r)&&r.comment)return d.default.getTextOfJSDocComment(r.comment)||void 0}function ul(t){let e=new Set(["deprecated","internal","public","alpha","beta"]),r=d.default.getJSDocTags(t).map(n=>n.tagName.text).filter(n=>e.has(n));return r.length>0?r:void 0}function fl(t,e){let r=d.default.createPrinter({removeComments:!0}),n=s=>r.printNode(d.default.EmitHint.Unspecified,s,e);if(d.default.isFunctionDeclaration(t)||d.default.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(d.default.isVariableDeclaration(t)){if(t.type)return n(t.type);if(t.initializer&&(d.default.isArrowFunction(t.initializer)||d.default.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(d.default.isClassDeclaration(t)&&t.name)return`class ${t.name.text}`;if(d.default.isInterfaceDeclaration(t))return`interface ${t.name.text}`;if(d.default.isTypeAliasDeclaration(t))return n(t.type);if(d.default.isEnumDeclaration(t))return`enum ${t.name.text}`}function ml(t,e){gl(t,e),dl(t,e),yl(t,e),xl(t,e),Cl(t,e),Js(t,e)}function gl(t,e){if(!d.default.isSourceFile(t))return;let r=t.statements.filter(n=>!d.default.isEmptyStatement(n));e.totalStatements=r.length,e.exportStatements=r.filter(n=>d.default.isExportDeclaration(n)||d.default.isExportAssignment(n)||$r(n)).length}function dl(t,e){if(d.default.isJsxElement(t)||d.default.isJsxSelfClosingElement(t)||d.default.isJsxFragment(t)){e.hasUI=!0,e.hasTypesOnly=!1;return}if(d.default.isFunctionDeclaration(t)||d.default.isMethodDeclaration(t)||d.default.isArrowFunction(t)||d.default.isClassDeclaration(t)||d.default.isVariableStatement(t)||d.default.isEnumDeclaration(t)){e.hasTypesOnly=!1;return}d.default.isExportDeclaration(t)&&!hl(t)&&(e.hasTypesOnly=!1)}function hl(t){return t.isTypeOnly?!0:!t.exportClause||!d.default.isNamedExports(t.exportClause)?!1:t.exportClause.elements.every(e=>e.isTypeOnly)}function yl(t,e){if(!d.default.isImportDeclaration(t)||!t.moduleSpecifier||!d.default.isStringLiteral(t.moduleSpecifier))return;let r=[];if(t.importClause&&(t.importClause.name&&r.push("default"),t.importClause.namedBindings))if(d.default.isNamedImports(t.importClause.namedBindings))for(let s of t.importClause.namedBindings.elements)r.push(s.name.text);else d.default.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:N(t.moduleSpecifier.text),type:n,symbols:r.length>0?r:void 0})}function xl(t,e){d.default.isExportDeclaration(t)?bl(t,e):d.default.isExportAssignment(t)?e.exports.set("default",{name:"default"}):$r(t)&&kl(t,e)}function bl(t,e){if(t.moduleSpecifier&&d.default.isStringLiteral(t.moduleSpecifier))Sl(t,t.moduleSpecifier.text,e);else if(t.exportClause&&d.default.isNamedExports(t.exportClause))for(let r of t.exportClause.elements){let n=r.name.text;e.exports.set(n,{name:n})}}function Sl(t,e,r){let n=vl(t),s={fromPath:r.filePath,toPath:"",rawSpecifier:e,isStyle:N(e),type:"re-export"};n.length>0&&(s.symbols=n),r.imports.push(s)}function vl(t){return t.exportClause?d.default.isNamedExports(t.exportClause)?t.exportClause.elements.map(e=>e.name.text):[]:["*"]}function kl(t,e){if((d.default.isFunctionDeclaration(t)||d.default.isClassDeclaration(t)||d.default.isInterfaceDeclaration(t)||d.default.isTypeAliasDeclaration(t)||d.default.isEnumDeclaration(t))&&t.name){let n=t.name.text;e.exports.set(n,Ks(n,t,t,e.sourceFile));return}if(d.default.isVariableStatement(t)){for(let n of t.declarationList.declarations)if(d.default.isIdentifier(n.name)){let s=n.name.text;e.exports.set(s,Ks(s,n,t,e.sourceFile))}}}function Cl(t,e){if(!d.default.isCallExpression(t))return;let r=t.arguments[0];!r||!d.default.isStringLiteral(r)||(t.expression.kind===d.default.SyntaxKind.ImportKeyword?e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.text,isStyle:N(r.text),type:"dynamic"}):d.default.isIdentifier(t.expression)&&t.expression.text==="require"&&e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.text,isStyle:N(r.text),type:"require"}))}function wl(t,e){let r=zr.default.basename(t).toLowerCase(),n=zr.default.extname(t).toLowerCase();return Ne().some(o=>r.includes(o))?"test":$n(r)?"config":e.imports.some(o=>nr().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>ir()?"barrel":"logic"}function $r(t){return d.default.canHaveModifiers(t)&&d.default.getModifiers(t)?.some(e=>e.kind===d.default.SyntaxKind.ExportKeyword)===!0}function El(t,e){let r=t.rawCallEdges??[];t.rawCallEdges=r;let n=new Map;for(let s of e.statements){if(!d.default.isImportDeclaration(s)||!d.default.isStringLiteral(s.moduleSpecifier))continue;let o=s.moduleSpecifier.text,i=s.importClause;if(i&&(i.name&&n.set(i.name.text,o),i.namedBindings&&d.default.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=Tl(s);if(o){let i=Pl(s);i&&yt(i,o,n,r);continue}d.default.isClassDeclaration(s)&&s.name&&Fl(s,s.name.text,n,r)}}function Fl(t,e,r,n){for(let s of t.members)d.default.isMethodDeclaration(s)&&s.body&&d.default.isIdentifier(s.name)?yt(s.body,`${e}.${s.name.text}`,r,n):d.default.isConstructorDeclaration(s)&&s.body&&yt(s.body,`${e}.constructor`,r,n)}function Tl(t){if($r(t)){if(d.default.isFunctionDeclaration(t)&&t.name)return t.name.text;if(d.default.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(d.default.isIdentifier(e.name)&&e.initializer&&(d.default.isArrowFunction(e.initializer)||d.default.isFunctionExpression(e.initializer)))return e.name.text}}}function Pl(t){if(d.default.isFunctionDeclaration(t))return t.body;if(d.default.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(e.initializer&&(d.default.isArrowFunction(e.initializer)||d.default.isFunctionExpression(e.initializer)))return e.initializer}}function yt(t,e,r,n){if(d.default.isCallExpression(t)&&d.default.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})}d.default.forEachChild(t,s=>yt(s,e,r,n))}function xt(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"}var Br=g(require("postcss")),Al=g(require("postcss-less")),Nl=Al,Qs=new Set(["reference","inline"]);function Vs(t){return t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||t.startsWith("data:")}function Dl(t){let e=t.trim();return e.length>0&&!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("//")&&!e.startsWith("data:")&&!e.startsWith("#")}function Rl(t,e){let r=t.match(/^\(([^)]+)\)\s+['"]([^'"]+)['"]/);if(r){let o=r[1]?.trim()??"",i=r[2]??"";if(!i)return null;let a=Qs.has(o)?"side-effect":"static";return{fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a,...Vs(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",...Vs(s)?{isExternal:!0}:{}}:null}function Il(t,e){let r=[],n=/url\(['"]?([^'")]+)['"]?\)/g,s=n.exec(t);for(;s!==null;){let o=s[1]?.trim()??"";Dl(o)&&r.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:"static"}),s=n.exec(t)}return r}function Ys(t,e){let r=[];return t.walk(n=>{if(n.type==="atrule"&&n.name==="import"){let s=Rl(n.params,e);s&&r.push(s)}n.type==="decl"&&r.push(...Il(n.value,e))}),r}function Ml(t){return t.replace(/(?<!:)\/\/.*/g,"")}function Ll(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=Qs.has(o)?"side-effect":"static";r.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a})}s=n.exec(t)}return r}function bt(t,e){let r=Br.default.parse(Ml(t));return{imports:Ys(r,e),root:r}}function _l(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 St(t,e){try{let r=Nl.parse(t),{exports:n,tags:s}=_l(r);return{imports:Ys(r,e),root:r,exports:n,tags:s}}catch{return{imports:Ll(t,e),root:Br.default.parse(""),exports:[],tags:[]}}}var Xs=require("postcss-scss");function Zs(t){return t.startsWith("_")||t.startsWith("-")}function Gl(t){return!!(t.startsWith("sass:")||t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||!t.startsWith(".")&&!t.startsWith("/")&&!t.startsWith("_"))}function Ol(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 jl(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||Zs(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||Zs(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 vt(t,e){let r=(0,Xs.parse)(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}=Ol(c);if(!l)return;let u={fromPath:e,toPath:"",rawSpecifier:l,isStyle:!0,type:a==="forward"?"re-export":"static",...Gl(l)?{isExternal:!0}:{}};p&&(u.symbols=[p]),n.push(u)});let{exports:s,tags:o}=jl(r);return{imports:n,root:r,exports:s,tags:o}}function eo(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 to(t,e){if(e.length===0)return"ui";try{let r=require("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 ze(t,e){let r=G(t);if(r==="stylus"){let o=eo(e,t);return{imports:o,exports:[],tags:[],category:to(e,o)}}if(r==="scss"){let{imports:o,root:i,exports:a,tags:c}=vt(e,t);return{imports:o,exports:a,tags:c,category:xt(i,o)}}if(r==="less"){let{imports:o,root:i,exports:a,tags:c}=St(e,t);return{imports:o,exports:a,tags:c,category:xt(i,o)}}let{imports:n,root:s}=bt(e,t);return{imports:n,exports:[],tags:[],category:xt(s,n)}}for(let[t,e]of[["javascript",(r,n)=>Wr(r,n,"javascript")],["typescript",(r,n)=>Wr(r,n,"typescript")],["css",ze],["scss",ze],["less",ze],["stylus",ze],["coffeescript",ms],["livescript",Rs],["lua",Ms],["python",$s],["go",Cs],["java",As],["kotlin",Ns],["scala",Bs],["groovy",ws],["gherkin",Nr],["markdown",Gs]])ue(t,e);async function ro(t,e){let r=G(t),n=ds(r);return n?n(t,e):{imports:[],exports:[],tags:[],category:"other"}}var Hr=g(require("path"));function zl(t,e){let r=e.get(t.path);r!==void 0&&(t.coveragePct=r)}function so(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 Wl(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 $l(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 no(t){return Math.round(t*1e4)/1e4}function Bl(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=no(Math.min(1,o)),r.push(n.exportUsageRatio)}r.length>0&&(t.avgExportUsage=no(r.reduce((n,s)=>n+s,0)/r.length),t.maxExportUsage=Math.max(...r))}function Ur(t,e,r){e&&(t.some(n=>n.name===e&&n.kind===r)||t.push({name:e,kind:r}))}function Hl(t,e){let r=e.toPath,n=Hr.default.basename(r,Hr.default.extname(r)).replace(/\.(test|spec)$/,"");Ur(t.tags,n,"import")}function Ul(t,e){if(!(!e.symbols||e.symbols.includes("*")))for(let r of e.symbols)Ur(t.tags,r,"import")}function Jl(t,e,r){let n=r.get(e.toPath);if(!(!n||n.category==="test"))for(let s of n.tags)s.kind==="comment-marker"&&Ur(t.tags,s.name,"comment-marker")}function Kl(t,e,r){!e.toPath||e.isExternal||(Hl(t,e),Ul(t,e),Jl(t,e,r))}function oo(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(Bl(r,t),e.size>0&&zl(r,e),r.category==="test")for(let n of r.imports)Wl(r,n,t),Kl(r,n,t);$l(r,t)}}var io=new Set(["java","kotlin","scala","groovy"]),ao=new Set(["typescript","javascript","python","go","java","kotlin","scala","groovy","scss","less","lua","coffeescript"]),co=new Set(["typescript","javascript","python"]),kt=new Set(["typescript","javascript","go","python","java"]);function Jr(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:ao.has(r),importSymbolsTracked:co.has(r),callEdgesTracked:kt.has(r)})).sort((r,n)=>n.fileCount-r.fileCount)}var Ve=g(require("fs")),M=g(require("path"));var Kr=g(require("fs")),Z=g(require("path")),We=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 po(a);if(r!==o&&!r.startsWith(`${o}/`))return null;let c=r.slice(o.length).replace(/^\//,"");return c?po(Z.default.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=Kr.default.readFileSync(Z.default.join(e,"go.mod"),"utf-8"),o=ql(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 Z.default.join(o,i)}}}};function ql(t,e){let r=t.split(`
|
|
12
|
-
`),
|
|
2
|
+
"use strict";var Wl=Object.create;var Vt=Object.defineProperty;var $l=Object.getOwnPropertyDescriptor;var zl=Object.getOwnPropertyNames;var Bl=Object.getPrototypeOf,Ul=Object.prototype.hasOwnProperty;var Kl=(t,e)=>{for(var n in e)Vt(t,n,{get:e[n],enumerable:!0})},Ei=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of zl(e))!Ul.call(t,s)&&s!==n&&Vt(t,s,{get:()=>e[s],enumerable:!(r=$l(e,s))||r.enumerable});return t};var h=(t,e,n)=>(n=t!=null?Wl(Bl(t)):{},Ei(e||!t||!t.__esModule?Vt(n,"default",{value:t,enumerable:!0}):n,t)),Hl=t=>Ei(Vt({},"__esModule",{value:!0}),t);var oh={};Kl(oh,{createMcpServer:()=>ur});module.exports=Hl(oh);var _l=require("child_process"),vi=h(require("fs")),Gl=h(require("path")),Ol=h(require("v8")),jl=require("@modelcontextprotocol/sdk/server/stdio.js");var Il=require("@modelcontextprotocol/sdk/server/index.js"),pr=require("@modelcontextprotocol/sdk/types.js");var qc=h(require("crypto")),ar=h(require("fs")),z=h(require("path"));var Hc=h(require("crypto")),ie=h(require("fs")),Se=h(require("path"));var de="mokosh-cache",ht="duplication-tokens.json",dr="duplication-result.json",hr="graph.json",yr="workspace-graph.json",xr="workspace",yt="manifest.json";var br="branch-graphs",j=["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage",".pytest_cache","__pycache__",".gradle","target"],kr=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".go",".java",".kt",".kts",".scala",".sc",".groovy",".gradle",".feature",".md",".mdx"];var nn=h(require("fs")),Nr=h(require("path"));var Jl=[".config.","biome.json","tsconfig.json","package.json",".prettierrc",".eslintrc"],Sr=[];function Qt(t){Sr.push(t)}function Ti(t){return[...Jl,...Sr].some(e=>typeof e=="string"?t.includes(e):e instanceof RegExp?e.test(t):e(t))}var Vl=[".test.",".spec.","-test.","-spec."],vr=[];function Yt(t){vr.push(t)}function xt(){return[...Vl,...vr]}var Ql=["jest","vitest","playwright","cypress","@testing-library/"],Cr=[];function Xt(t){Cr.push(t)}function wr(){return[...Ql,...Cr]}var Fi=.8,Er=Fi;function Tr(t){Er=t}function Fr(){return Er}function Zt(){Sr.length=0,vr.length=0,Cr.length=0,Er=Fi}var qt=["comment-marker","import"],Di=new Set(["test","barrel"]),Pi=/^[a-zA-Z][a-zA-Z0-9_-]{1,}$/,en=new Set(["index","main","common","shared","types","type","constants","const","config","util","utils","helper","helpers","mock","mocks","fixture","fixtures","setup","spec","test","tests","args","props","options","opts","context","ctx","handler","handlers","callback","cb","fn","impl","run","get","set","use","name","value","data","item","result","node","org","linux","darwin","windows","freebsd","openbsd","netbsd","dragonfly","solaris","android","ios","js","wasm","wasip1","plan9","aix","illumos","amd64","arm","arm64","ppc64","ppc64le","mips","mips64","riscv64","s390x","loong64","cgo","gc","gccgo","unix"]),Dr=new Set(en);function Pr(t){let e=new Set(en);for(let n of t?.blocklist??[])e.add(n.toLowerCase());for(let n of t?.allowlist??[])e.delete(n.toLowerCase());Dr=e}function Ar(){Dr=new Set(en)}function tn(t){if(!Pi.test(t))return!1;let e=t.toLowerCase();return!Di.has(e)&&!Dr.has(e)}function we(t){return qt.includes(t.kind)&&tn(t.name)}function Rr(t){let e=new Set,n=[];for(let r of t)!we(r)||e.has(r.name)||(e.add(r.name),n.push(r.name));return n}var Yl=["mokosh.config.js","mokosh.config.cjs","mokosh.config.json"];function bt(t,{allowJs:e=!0,isExplicitPath:n=!1}={}){if(n){let r=Nr.default.resolve(t);return nn.default.existsSync(r)?r.endsWith(".json")?Ai(r):e?Ri(r):{}:{}}for(let r of Yl){let s=Nr.default.resolve(t,r);if(nn.default.existsSync(s)){if(r.endsWith(".json"))return Ai(s);if(e)return Ri(s)}}return{}}function Ai(t){return JSON.parse(nn.default.readFileSync(t,"utf-8"))}function Ri(t){let e=require(t);return e&&typeof e=="object"&&"default"in e&&(e=e.default),typeof e=="function"?e({}):e}function Mr(t){Zt(),Ar(),Pr(t.tags);for(let e of t.configMatchers??[])Qt(e);for(let e of t.testPatterns??[])Yt(e);for(let e of t.testLibraries??[])Xt(e);t.barrelThreshold!==void 0&&Tr(t.barrelThreshold)}function he(t){return{gitStats:t?.gitStats??!1,parallelParsing:t?.parallelParsing,pathAliases:t?.pathAliases,additionalIgnoreDirs:t?.ignoreDirs}}var Ni=h(require("fs")),Ir=h(require("path"));function Lr(t,e){let n=Ir.default.resolve(t,e);try{let r=Ni.default.readFileSync(n,"utf-8"),s=JSON.parse(r),i=new Map;if(typeof s!="object"||s===null)return i;for(let[o,a]of Object.entries(s)){if(o==="total")continue;let c=a?.lines?.pct;if(typeof c!="number")continue;let l=Ir.default.relative(t,o);i.set(l,c)}return i}catch{return new Map}}var rn={serialize(t){let e=["graph TD"],n=new Set;for(let r of t.nodes.values()){let s=`"${r.path}"`;for(let i of r.imports){if(!i.toPath)continue;let o=`"${i.toPath}"`,a=`${r.path} -> ${i.toPath}`;if(!n.has(a)){let c=i.isStyle?"-- styles -->":"-->";e.push(` ${s} ${c} ${o}`),n.add(a)}}}return e.join(`
|
|
3
|
+
`)}};var $e=class{constructor(e){this.nodes=e}nodes;findUnusedFiles(e){let n=new Set(this.nodes.keys());return e.filter(r=>!n.has(r))}findHighExportUsage(e){let n=[];for(let r of this.nodes.values()){if(r.maxExportUsage===void 0||r.maxExportUsage<e)continue;let s=r.imports.reduce((i,o)=>(o.exportUsageRatio??0)>(i?.exportUsageRatio??0)?o:i,null);n.push({path:r.path,maxExportUsage:r.maxExportUsage,tightestDep:s?.toPath??""})}return n.sort((r,s)=>s.maxExportUsage-r.maxExportUsage)}traversableTargets(e,n){let r=this.nodes.get(e);if(!r)return[];let s=new Set;for(let i of r.imports)!i.toPath||i.isExternal||i.isSamePackage&&!n.has("samePackage")||i.isDocReference&&!n.has("docReference")||s.add(i.toPath);return[...s]}findCycles(e={}){let n=new Set(e.includeKinds??[]),r=[],s=new Set,i=new Set,o=[],a=c=>{s.add(c),i.add(c),o.push(c);for(let l of this.traversableTargets(c,n))if(i.has(l)){let p=o.indexOf(l);r.push([...o.slice(p),l])}else s.has(l)||a(l);i.delete(c),o.pop()};for(let c of this.nodes.keys())s.has(c)||a(c);return e.expandComponents?r:this.collapseByComponent(r,n)}collapseByComponent(e,n){if(e.length<=1)return e;let r=this.componentIds(n),s=new Map,i=new Map;for(let[o,a]of e.entries()){let c=r.get(a[0]);if(c===void 0)continue;i.has(c)||i.set(c,o);let l=s.get(c);(l===void 0||Zl(a,l))&&s.set(c,a)}return[...s.entries()].sort(([o],[a])=>i.get(o)-i.get(a)).map(([,o])=>o)}componentIds(e){let n=new Map,r=new Map,s=new Set,i=[],o=new Map,a=0,c=0;for(let l of this.nodes.keys()){if(n.has(l))continue;let p=[{node:l,targets:this.traversableTargets(l,e),next:0}];for(n.set(l,a),r.set(l,a),a++,i.push(l),s.add(l);p.length>0;){let u=p[p.length-1];if(u.next<u.targets.length){let f=u.targets[u.next++];n.has(f)?s.has(f)&&r.set(u.node,Math.min(r.get(u.node),n.get(f))):(n.set(f,a),r.set(f,a),a++,i.push(f),s.add(f),p.push({node:f,targets:this.traversableTargets(f,e),next:0}))}else{if(r.get(u.node)===n.get(u.node)){let m=[],d;do d=i.pop(),s.delete(d),m.push(d);while(d!==u.node);if(m.length>1){for(let b of m)o.set(b,c);c++}}p.pop();let f=p[p.length-1];f&&r.set(f.node,Math.min(r.get(f.node),r.get(u.node)))}}}return o}};function Zl(t,e){return t.length!==e.length?t.length<e.length:t.join("\0")<e.join("\0")}var _r=h(require("fs")),Mi=h(require("path")),ql=25,ep=30,tp=50;function Gr(t,e={}){let n=e.maxExports??ep,r=e.maxUnreachable??tp,s={};for(let c of t.publicExports)s[c.kind]=(s[c.kind]??0)+1;let i=t.publicExports.slice(0,n).map(c=>({name:c.name,kind:c.kind})),o=t.unreachableFromEntry.slice(0,r),a={entryPoints:t.entryPoints.slice(0,ql),entryPointCount:t.entryPoints.length,publicExportCount:t.publicExports.length,publicExports:i,byKind:s,internalFileCount:t.internalFiles.length,unreachableFromEntryCount:t.unreachableFromEntry.length,unreachableFromEntry:o,testFileCount:t.testFiles.length,hint:`Pass view:"exports" for all ${t.publicExports.length} exports with docs, signatures and definedIn; view:"full" for that plus the internalFiles / testFiles path lists.`};return t.entryPoints.length>a.entryPoints.length&&(a.entryPointsTruncated=!0),i.length<t.publicExports.length&&(a.publicExportsTruncated=!0),o.length<t.unreachableFromEntry.length&&(a.unreachableFromEntryTruncated=!0),a}function sn(t,e){let n=t.replace(/^\.\//,"");if(e.nodes.has(n))return n;let r=n.replace(/^dist\//,"src/").replace(/\.(js|mjs|cjs)$/,".ts");return e.nodes.has(r)?r:null}function Ii(t,e){if(typeof t=="string")return sn(t,e);if(t&&typeof t=="object"){let n=t;for(let r of["import","require","default"]){let s=Ii(n[r],e);if(s)return s}}return null}function np(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 rp(t,e){let n=new Set,r=new Set,s=[...e];for(;s.length;){let i=s.shift();if(r.has(i))continue;r.add(i);let o=t.nodes.get(i);if(o){for(let a of o.exports)n.add(a.name);for(let a of o.imports){if(a.type!=="re-export"||a.isExternal||!a.toPath)continue;if(!a.symbols?.length||a.symbols.includes("*")){let l=t.nodes.get(a.toPath);if(l)for(let p of l.exports)n.add(p.name);s.push(a.toPath)}else for(let l of a.symbols)n.add(l)}}}return n}function Or(t,e){let n=[],r=Mi.default.join(e,"package.json");if(_r.default.existsSync(r))try{let s=JSON.parse(_r.default.readFileSync(r,"utf8"));if(s.exports&&typeof s.exports=="object"&&!Array.isArray(s.exports))for(let o of Object.values(s.exports)){let a=Ii(o,t);a&&!n.includes(a)&&n.push(a)}else if(typeof s.exports=="string"){let o=sn(s.exports,t);o&&n.push(o)}let i=typeof s.bin=="string"?[s.bin]:s.bin&&typeof s.bin=="object"&&!Array.isArray(s.bin)?Object.values(s.bin).filter(o=>typeof o=="string"):[];for(let o of i){let a=sn(o,t);a&&!n.includes(a)&&n.push(a)}if(n.length===0)for(let o of[s.main,s.module].filter(Boolean)){let a=sn(o,t);a&&!n.includes(a)&&n.push(a)}}catch{}if(n.length===0){for(let s of["src/index.ts","src/index.js","index.ts","index.js"])if(t.nodes.has(s)){n.push(s);break}}return n.length===0?op(t):n}var sp=new Set(["java","kotlin","scala","groovy"]);function ip(t){return t.endsWith("_test.go")||/(^|\/)(test|tests|__tests__|testdata)\//.test(t)||/[._-](test|spec)\.[^/]+$/.test(t)}function op(t){let e=[...t.nodes.values()],n=o=>e.filter(a=>o(a.type)&&a.category!=="test"&&!ip(a.path)),r=n(o=>o==="python");if(r.length>0){let o=r.filter(a=>a.path.replace(/^.*\//,"")==="__init__.py");if(o.length>0){let a=Math.min(...o.map(c=>c.path.split("/").length));return o.filter(c=>c.path.split("/").length===a).map(c=>c.path).sort()}return r.map(a=>a.path).sort()}let s=n(o=>o==="go");if(s.length>0)return s.map(o=>o.path).sort();let i=n(o=>sp.has(o));return i.length>0?i.map(o=>o.path).sort():[]}function ap(t,e){let n=new Set(e);for(let r of e)t.traverse(r,s=>(n.add(s.path),!0),{direction:"outgoing"});return n}function cp(t,e,n){let r=new Map;for(let s of e){if(n.includes(s))continue;let i=t.nodes.get(s);if(!i)continue;let o=i.category==="barrel";for(let a of i.exports){let c=r.get(a.name),l=!!(a.signature||a.doc);(!c||l&&!o)&&r.set(a.name,{file:s,symbol:a})}}return r}function lp(t,e,n,r){let s=[];for(let i of t){let o=e.get(i),a=r.flatMap(u=>n.nodes.get(u)?.exports??[]).find(u=>u.name===i),c=o?.symbol??a,l=o?.file??r.find(u=>n.nodes.get(u)?.exports.some(f=>f.name===i))??r[0],p={name:i,definedIn:l,kind:np(c?.signature)};c?.doc&&(p.doc=c.doc),c?.signature&&(p.signature=c.signature),s.push(p)}return s.sort((i,o)=>i.name.localeCompare(o.name)),s}function pp(t,e,n){let r=c=>t.nodes.get(c)?.category==="test",s=[...e].filter(c=>!n.includes(c)&&!r(c)),i=[...t.nodes.keys()].filter(c=>!e.has(c)),o=i.filter(c=>!r(c)),a=i.filter(c=>r(c));return{internalFiles:s,unreachableFromEntry:o,testFiles:a}}function on(t,e){if(e.length===0)throw new Error("buildApiSurface requires at least one entry point");for(let l of e)if(!t.nodes.has(l))throw new Error(`Entry point not found in graph: ${l}`);let n=ap(t,e),r=cp(t,n,e),s=rp(t,e),i=lp(s,r,t,e),{internalFiles:o,unreachableFromEntry:a,testFiles:c}=pp(t,n,e);return{entryPoints:e,publicExports:i,internalFiles:o,unreachableFromEntry:a,testFiles:c}}function jr(t,e){let n=null,r=[];for(let i of t.nodes.values()){i.exports.some(o=>o.name===e)&&(n=i.path);for(let o of i.callEdges??[])o.to===e&&r.push({file:i.path,callerFunction:o.from})}let s=[];if(n){let i=t.nodes.get(n);for(let o of i?.callEdges??[])o.from===e&&s.push({file:o.toFile,calleeFunction:o.to})}return{functionName:e,definedIn:n,callers:r,callees:s}}var up=h(require("fs")),fp=h(require("path"));function Li(t){let e=[...t.nodes.entries()].sort(([r],[s])=>r.localeCompare(s)).map(([r,s])=>`${r}:${s.mtime}:${s.size}`).join("|"),n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,"0")}function Wr(t){let e=new Map;for(let n of t.nodes.keys()){let r=[];t.traverse(n,s=>(s.path!==n&&r.push(s.path),!0),{direction:"incoming"}),e.set(n,r)}return{impact:e,graphHash:Li(t)}}function $r(t,e){return t.impact.get(e)??[]}var Xa=h(require("path"));var ze=h(require("fs")),zr=h(require("path"));var A=class t{constructor(e){this.nodes=e}nodes;_incomingEdgesCache=null;_callIncomingCache=null;serialize(){return{nodes:Array.from(this.nodes.values())}}static deserialize(e){let n=new Map;for(let r of e.nodes)n.set(r.path,r);return new t(n)}getIncomingEdgesMap(){if(this._incomingEdgesCache)return this._incomingEdgesCache;let e=new Map;for(let n of this.nodes.values())for(let r of n.imports)if(r.toPath){let s=e.get(r.toPath)||[];s.push(n.path),e.set(r.toPath,s)}return this._incomingEdgesCache=e,e}dfs(e,n,r,s){let i=new Set,o=r.maxDepth??1/0,a=[{path:e,depth:0,parent:null}];for(;a.length>0;){let c=a.pop(),{path:l,depth:p,parent:u}=c;if(p>o||i.has(l))continue;let f=this.nodes.get(l);if(!f||(i.add(l),n(f,p,u)===!1))continue;let m=s(l);for(let d=m.length-1;d>=0;d--)a.push({path:m[d],depth:p+1,parent:l})}}traverse(e,n,r={}){let s=r.direction??"outgoing",i=s==="incoming"?this.getIncomingEdgesMap():null;this.dfs(e,n,r,o=>s==="outgoing"?this.nodes.get(o)?.imports.map(a=>a.toPath).filter(Boolean)??[]:i?.get(o)??[])}getCallIncomingCache(){if(this._callIncomingCache)return this._callIncomingCache;let e=new Map;for(let n of this.nodes.values())for(let r of n.callEdges??[]){let s=e.get(r.toFile)??[];s.push(n.path),e.set(r.toFile,s)}return this._callIncomingCache=e,e}traverseCalls(e,n,r={}){let s=r.direction??"outgoing",i=s==="incoming"?this.getCallIncomingCache():null;this.dfs(e,n,r,o=>s==="outgoing"?this.nodes.get(o)?.callEdges?.map(a=>a.toFile)??[]:i?.get(o)??[])}getCallers(e){let n=[];return this.traverseCalls(e,r=>(r.path!==e&&n.push(r.path),!0),{direction:"incoming",maxDepth:1}),n}getCallEdgesFor(e){return this.nodes.get(e)?.callEdges??[]}getNeighbors(e){let n=this.nodes.get(e);return n?n.imports.map(r=>this.nodes.get(r.toPath)).filter(r=>r!==void 0):[]}findUnusedFiles(e){return new $e(this.nodes).findUnusedFiles(e)}findCycles(e){return new $e(this.nodes).findCycles(e)}};function an(t){return zr.default.join(t,de,br)}function _i(t,e){return zr.default.join(an(t),`${e}.json`)}function Gi(t,e){let n=_i(t,e);if(!ze.default.existsSync(n))return null;try{let r=ze.default.readFileSync(n,"utf-8");return A.deserialize(JSON.parse(r))}catch{return null}}function Oi(t,e,n){let r=an(t);ze.default.existsSync(r)||ze.default.mkdirSync(r,{recursive:!0}),ze.default.writeFileSync(_i(t,e),JSON.stringify(n.serialize()))}var qe=h(require("fs")),L=h(require("path")),la=h(require("piscina"));var cn=require("child_process"),ln=class{getChangedFiles(e,n){try{let s=[["diff","--name-only"],["diff","--cached","--name-only"],["ls-files","--others","--exclude-standard"],...n?[["diff","--name-only","--end-of-options",`${n}...HEAD`]]:[]].flatMap(i=>{try{return(0,cn.execFileSync)("git",i,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
|
|
4
|
+
`).map(a=>a.trim()).filter(a=>a!=="")}catch{return[]}});return Array.from(new Set(s))}catch(r){return console.error("Error getting git diff:",r),[]}}},ji="%x00%H%x09%ae%x09%at",Wi=256*1024*1024;function $i(t,e){let n="",r=0;for(let s of t.split(`
|
|
5
|
+
`)){if(s.startsWith("\0")){let[,c,l]=s.slice(1).split(" ");n=c??"",r=l?Number(l)*1e3:0;continue}if(s==="")continue;let i=s.split(" "),o=i[0];if(!o)continue;let a=o.startsWith("R")||o.startsWith("C")?i[2]:i[1];a&&e(a,n,r)}}function zi(t){let e=new Map;try{let n=(0,cn.execFileSync)("git",["-C",t,"log","--since=90 days ago","--name-status","-M",`--format=${ji}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:Wi});$i(n,(r,s,i)=>{let o=e.get(r);if(o){o.commitCount90d+=1;return}e.set(r,{commitCount90d:1,lastAuthor:s||void 0,lastCommitAt:i||void 0})})}catch{return e}try{let n=(0,cn.execFileSync)("git",["-C",t,"log","--name-status","-M",`--format=${ji}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],maxBuffer:Wi});$i(n,(r,s,i)=>{e.has(r)||e.set(r,{commitCount90d:0,lastAuthor:void 0,lastCommitAt:i||void 0})})}catch{}return e}var St=h(require("fs")),Bi=h(require("path")),Br=require("js-yaml");var kt=["package-lock.json","yarn.lock","pnpm-lock.yaml"];function Ui(t){let e=t.lastIndexOf("@");return e>0?t.substring(0,e):t}function mp(t){return t.replace(/:$/,"").split(",").map(e=>{let n=e.trim();return n.startsWith('"')&&(n=n.slice(1)),n.endsWith('"')&&(n=n.slice(0,-1)),Ui(n)}).filter(Boolean)}function gp(t,e){let n=t.startsWith("/")?t.slice(1):t,r=n.lastIndexOf("@");return r>0?{name:n.substring(0,r),version:e||n.substring(r+1)}:{name:n,version:e}}function dp(t){try{let e=(0,Br.load)(t),n={dependencies:{}};for(let[r,s]of Object.entries(e))if(!(r==="__metadata"||!s?.version))for(let i of r.split(", ")){let o=Ui(i);o&&(n.dependencies[o]={version:s.version,...s.dependencies!==void 0&&{dependencies:s.dependencies}})}return n}catch{return null}}function hp(t){let e={dependencies:{}};for(let n of t.split(/\n\n+/)){let r=n.split(`
|
|
6
|
+
`).filter(c=>c.trim().length>0&&!c.trim().startsWith("#"));if(r.length<2)continue;let s=r[0];if(!s||s.startsWith(" "))continue;let i=mp(s);if(i.length===0)continue;let a=r.find(c=>c.trim().startsWith('version "'))?.match(/version "(.*?)"/)?.[1]??"";for(let c of i)e.dependencies[c]={version:a}}return e}function Ki(t){let e=St.default.readFileSync(t,"utf-8"),n=JSON.parse(e),r={dependencies:{}};if(n.packages)for(let[s,i]of Object.entries(n.packages)){if(!s.startsWith("node_modules/"))continue;let o=s.replace("node_modules/","");o.includes("node_modules/")||(r.dependencies[o]={version:i.version,...i.dependencies!==void 0&&{dependencies:i.dependencies}})}else if(n.dependencies)for(let[s,i]of Object.entries(n.dependencies))r.dependencies[s]={version:i.version,...i.dependencies!==void 0&&{dependencies:i.dependencies}};return r}function Hi(t){let e=St.default.readFileSync(t,"utf-8");if(e.includes("__metadata:")){let n=dp(e);if(n!==null)return n}return hp(e)}function Ji(t){let e=St.default.readFileSync(t,"utf-8"),n={dependencies:{}};try{let r=(0,Br.load)(e);if(r.packages)for(let[s,i]of Object.entries(r.packages)){let{name:o,version:a}=gp(s,i.version);o&&(n.dependencies[o]={version:a,...i.dependencies!==void 0&&{dependencies:i.dependencies}})}if(r.dependencies)for(let[s,i]of Object.entries(r.dependencies)){if(n.dependencies[s])continue;let o=typeof i=="string"?i:i.version;n.dependencies[s]={version:o||""}}}catch{}return n}var yp={"package-lock.json":Ki,"yarn.lock":Hi,"pnpm-lock.yaml":Ji};function Ur(t){for(let e of kt){let n=Bi.default.join(t,e);if(St.default.existsSync(n))return yp[e](n)}return null}var wt=h(require("fs")),Ct=h(require("path"));function Vi(t){let e=t.trim();return e.length>=2&&(e[0]==='"'||e[0]==="'")&&e[e.length-1]===e[0]?e.slice(1,-1):e}function xp(t){let e=t.trim();if(e.startsWith('"')||e.startsWith("'")){let a=Vi(e).split(":");return a.length>=3&&a[0]&&a[2]?{group:a[0],version:a[2]}:null}if(!e.startsWith("{"))return null;let n=e.match(/module\s*=\s*["']([^"']+)["']/),r=e.match(/group\s*=\s*["']([^"']+)["']/),s=n?n[1].split(":")[0]:r?.[1];if(!s)return null;let i=e.match(/version\.ref\s*=\s*["']([^"']+)["']/)??e.match(/version\s*=\s*\{\s*ref\s*=\s*["']([^"']+)["']/),o=e.match(/version\s*=\s*["']([^"']+)["']/);return{group:s,...o?.[1]!==void 0&&{version:o[1]},...i?.[1]!==void 0&&{versionRef:i[1]}}}function Kr(t){let e=t.split(/\r?\n/).map(i=>i.replace(/#.*$/,"").trim()),n={},r="";for(let i of e){let o=i.match(/^\[([\w.-]+)\]$/);if(o){r=o[1];continue}if(r!=="versions"||!i)continue;let a=i.indexOf("=");if(a===-1)continue;let c=i.slice(0,a).trim(),l=Vi(i.slice(a+1));c&&l&&(n[c]=l)}let s={};r="";for(let i of e){let o=i.match(/^\[([\w.-]+)\]$/);if(o){r=o[1];continue}if(r!=="libraries"||!i)continue;let a=i.indexOf("=");if(a===-1)continue;let c=xp(i.slice(a+1));if(!c)continue;let l=c.versionRef?n[c.versionRef]:c.version;l&&(s[c.group]=l)}return s}function Hr(t){let e={};for(let n of t.split(/\r?\n/)){let r=n.trim();if(!r||r.startsWith("#")||r.startsWith("empty="))continue;let i=r.split("=")[0].split(":");i.length>=3&&i[0]&&i[2]&&(e[i[0]]=i[2])}return e}function Jr(t){let e={},n=/["']([\w.-]+):([\w.-]+):([\w.\-+]+)["']/g;for(let s=n.exec(t);s;s=n.exec(t)){let[,i,,o]=s;i&&o&&/\d/.test(o)&&(e[i]=o)}let r=/group:\s*["']([\w.-]+)["'][^\n)]*?version:\s*["']([\w.\-+]+)["']/g;for(let s=r.exec(t);s;s=r.exec(t))s[1]&&s[2]&&/\d/.test(s[2])&&(e[s[1]]=s[2]);return e}function pn(t){let e={},n=/["']([\w.-]+)["']\s*%%?\s*["']([\w.-]+)["']\s*%\s*["']([\w.\-+]+)["']/g;for(let r=n.exec(t);r;r=n.exec(t)){let[,s,,i]=r;s&&i&&(e[s]=i)}return e}var bp=new Set(["node_modules","build",".gradle","target",".git","dist"]),kp=2;function vt(t){try{return wt.default.existsSync(t)?wt.default.readFileSync(t,"utf-8"):null}catch{return null}}function Vr(t){let e={},n=p=>{for(let[u,f]of Object.entries(p))!e[u]&&f&&(e[u]=f)},r=vt(Ct.default.join(t,"gradle","libs.versions.toml"));r&&n(Kr(r));let s=[],i=[],o=[],a=(p,u)=>{let f;try{f=wt.default.readdirSync(p,{withFileTypes:!0})}catch{return}for(let m of f){let d=Ct.default.join(p,m.name);if(m.isDirectory()){u<kp&&!m.name.startsWith(".")&&!bp.has(m.name)&&a(d,u+1);continue}m.isFile()&&(m.name==="gradle.lockfile"?s.push(d):m.name==="build.gradle"||m.name==="build.gradle.kts"?i.push(d):m.name==="build.sbt"&&o.push(d))}};a(t,0);for(let p of s){let u=vt(p);u&&n(Hr(u))}for(let p of i){let u=vt(p);u&&n(Jr(u))}for(let p of o){let u=vt(p);u&&n(pn(u))}try{let p=Ct.default.join(t,"project");for(let u of wt.default.readdirSync(p,{withFileTypes:!0}))if(u.isFile()&&u.name.endsWith(".scala")){let f=vt(Ct.default.join(p,u.name));f&&n(pn(f))}}catch{}let c=Object.keys(e);if(c.length===0)return null;let l={};for(let p of c)l[p]={version:e[p]};return l}function Qi(t){let e=Ur(t),n=Vr(t);return n?{...e??{dependencies:{}},jvmDependencies:n}:e}var Qr=h(require("path"));function V(t){switch(Qr.default.extname(t).toLowerCase()){case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".ts":case".tsx":return"typescript";case".css":return"css";case".scss":case".sass":return"scss";case".less":return"less";case".styl":return"stylus";case".coffee":return"coffeescript";case".ls":return"livescript";case".lua":return"lua";case".py":return"python";case".go":return"go";case".java":return"java";case".kt":case".kts":return"kotlin";case".scala":case".sc":return"scala";case".groovy":case".gradle":return"groovy";case".cpp":case".cc":case".cxx":case".c":return"unknown";case".feature":return"gherkin";case".md":case".mdx":return"markdown";default:return"unknown"}}function W(t){let e=Qr.default.extname(t).toLowerCase();return[".css",".scss",".sass",".less",".styl"].includes(e)}var Xi=h(require("coffeescript"));function ye(t){return t.startsWith("'")||t.startsWith('"')?t.slice(1,-1):t}function Be(t){let e=new Set,n=/@tag\s+([a-zA-Z0-9_-]+)/g,r=n.exec(t);for(;r!==null;)r[1]&&e.add(r[1]),r=n.exec(t);return e}function Ue(t,e){let n=t.toLowerCase();return n.includes(".test.")||n.includes(".spec.")||e.has("test")?"test":"logic"}function Zi(t){if(t){if(typeof t.originalValue=="string")return t.originalValue;if(typeof t.value=="string")return ye(t.value)}}function Ee(t){if(t){if(typeof t.value=="string")return t.value;if(typeof t.base?.value=="string")return t.base.value}}function Sp(t,e){let n=Zi(e.source);return n?{fromPath:t,toPath:"",rawSpecifier:n,isStyle:W(n),type:"static"}:null}function vp(t,e){let n=e.variable?.base?.value==="require",r=Zi(e.args?.[0]?.base);return!n||!r?null:{fromPath:t,toPath:"",rawSpecifier:r,isStyle:W(r),type:"require"}}function Yi(t,e){if(e)return[{name:e}];let n=t.value;if(n?.constructor?.name==="Class"){let s=Ee(n.variable);return s?[{name:s}]:[]}if(n?.base?.constructor?.name==="Obj"&&Array.isArray(n.base.properties))return n.base.properties.map(s=>Ee(s.variable)??Ee(s)).filter(s=>!!s).map(s=>({name:s}));let r=Ee(n);return r?[{name:r}]:[]}function Cp(t){if(Array.isArray(t.specifiers))return t.specifiers.map(n=>n.identifier??n.original?.value).filter(n=>!!n).map(n=>({name:n}));let e=Ee(t.variable)??Ee(t.variable?.base);return e?[{name:e}]:[]}function wp(t,e,n,r){let s=e.constructor?.name;if(s==="ImportDeclaration"){let i=Sp(t,e);i&&n.push(i)}else if(s==="Call"){let i=vp(t,e);i&&n.push(i)}else if(s==="Assign"){let i=Ee(e.variable?.base),o=e.variable?.properties?.[0]?.name?.value;i==="module"&&o==="exports"?r.push(...Yi(e,void 0)):i==="exports"&&typeof o=="string"&&r.push(...Yi(e,o))}else s==="ExportNamedDeclaration"&&e.clause?r.push(...Cp(e.clause)):s==="ExportDefaultDeclaration"&&r.push({name:"default"})}function Yr(t,e,n,r){if(!(!e||typeof e!="object")){wp(t,e,n,r);for(let s in e){if(s==="locationData")continue;let i=e[s];if(!(!i||typeof i!="object"))if(Array.isArray(i))for(let o of i)Yr(t,o,n,r);else Yr(t,i,n,r)}}}function qi(t,e){let n=Be(e),r=Ue(t,n),s=[],i=[];try{Yr(t,Xi.default.nodes(e),s,i)}catch{}let o=new Set,a=i.filter(c=>o.has(c.name)?!1:(o.add(c.name),!0));return{imports:s,exports:a,tags:Array.from(n).map(c=>({name:c,kind:"comment-marker"})),category:r}}var He=require("@cucumber/gherkin"),no=require("@cucumber/messages");var eo=new Map;function Ke(t,e){eo.set(t,e)}function to(t){return eo.get(t)}var Ep=no.IdGenerator.uuid();function Xr(t,e){let n=new Set,r=s=>{for(let i of s)n.add(i.name.startsWith("@")?i.name.slice(1):i.name)};try{let s=new He.AstBuilder(Ep),i=new He.GherkinClassicTokenMatcher,a=new He.Parser(s,i).parse(e);if(a.feature){r(a.feature.tags);for(let c of a.feature.children){if(c.scenario){r(c.scenario.tags);for(let l of c.scenario.examples)r(l.tags)}if(c.rule)for(let l of c.rule.children)l.scenario&&r(l.scenario.tags)}}}catch(s){console.warn(`[GherkinParser] Failed to parse ${t}:`,s)}return{imports:[],exports:[],tags:Array.from(n).map(s=>({name:s,kind:"comment-marker"})),category:"test"}}Ke("gherkin",Xr);var ao=h(require("path")),co=require("@lezer/go");function Te(t){let e=[],n=t.firstChild;for(;n;)e.push(n),n=n.nextSibling;return e}function Fe(t,e){let n=1;for(let r=0;r<e&&r<t.length;r++)t[r]===`
|
|
7
|
+
`&&n++;return n}function Tp(t,e){let n=1;function r(s){switch(s.type.name){case"IfStatement":case"ForStatement":n++;break;case"Case":{s.firstChild?.type.name==="case"&&n++;break}case"LogicOp":{let o=e.slice(s.from,s.to);(o==="&&"||o==="||")&&n++;break}}let i=s.firstChild;for(;i;)r(i),i=i.nextSibling}return r(t),n}function so(t,e,n,r){let s=n?1:1+e,i=Te(t),o=n?e:e+1,a=i[1];a&&a.type.name!=="Block"&&(s+=Je(a,o,!1,r));let c=i.find(p=>p.type.name==="Block");c&&(s+=Je(c,o,!1,r));let l=i.findIndex(p=>p.type.name==="else");if(l>=0){let p=i[l+1];p?.type.name==="IfStatement"?s+=so(p,e,!0,r):p&&(s+=1+Je(p,e+1,!1,r))}return s}function ro(t,e,n){let r=1+e,s=t.firstChild;for(;s;)r+=Je(s,e+1,!1,n),s=s.nextSibling;return r}function Fp(t,e,n){let r=0,s=t.firstChild;for(;s;)r+=Je(s,e,!1,n),s=s.nextSibling;return r}function Dp(t,e){let n=e.slice(t.from,t.to);return n==="&&"||n==="||"}function Je(t,e,n,r){let s=t.type.name;if(s==="IfStatement")return so(t,e,n,r);if(s==="ForStatement"||s==="SwitchStatement"||s==="SelectStatement")return ro(t,e,r);let i=s==="LogicOp"&&Dp(t,r)?1:0;return e>0&&s==="FunctionLiteral"?i+ro(t,e,r):i+Fp(t,e,r)}function Pp(t,e){return Je(t,0,!1,e)}function un(t,e){return{complexity:Tp(t,e),cognitiveComplexity:Pp(t,e)}}function Zr(t,e){let r=t.getChild("Parameters")?.getChild("Parameter"),s=r?.getChild("TypeName")??r?.getChild("PointerType")?.getChild("TypeName");return s?e.slice(s.from,s.to):void 0}function io(t,e){let n=[],r=t.cursor();do if(r.name==="FunctionDecl"){let s=r.node.getChild("DefName");if(s){let i=e.slice(s.from,s.to),{complexity:o,cognitiveComplexity:a}=un(r.node,e);n.push({name:i,line:Fe(e,r.from),complexity:o,cognitiveComplexity:a})}}else if(r.name==="MethodDecl"){let s=r.node.getChild("FieldName");if(s){let i=e.slice(s.from,s.to),o=Zr(r.node,e),a=o?`${o}.${i}`:i,{complexity:c,cognitiveComplexity:l}=un(r.node,e);n.push({name:a,line:Fe(e,r.from),complexity:c,cognitiveComplexity:l})}}while(r.next());return n}var Ap=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/,Rp=/^\/\/go:build\s+(.+)$/,Np=/^\/\/\s*\+build\s+(.+)$/;function lo(t,e){let n=[],r=new Map,s=new Set,i=new Set,o=new Map,a=co.parser.parse(e),c=a.cursor();do switch(c.name){case"LineComment":{let k=e.slice(c.from,c.to),S=k.match(Ap);S?.[1]&&s.add(S[1]);let w=k.match(Rp);w&&oo(w[1],i);let I=k.match(Np);I&&oo(I[1],i);break}case"ImportSpec":{let k=c.node.getChild("String");if(k){let w=e.slice(k.from,k.to).slice(1,-1);n.push({fromPath:t,toPath:"",rawSpecifier:w,isExternal:!0,isStyle:!1,type:"static"});let I=c.node.getChild("DefName"),_=I?e.slice(I.from,I.to):w.split("/").pop();_&&_!=="_"&&_!=="."&&o.set(_,w)}break}case"FunctionDecl":case"MethodDecl":case"TypeDecl":case"VarDecl":case"ConstDecl":{let k=c.node.getChild("DefName")??c.node.getChild("FieldName")??c.node.getChild("TypeSpec")?.getChild("DefName")??c.node.getChild("VarSpec")?.getChild("DefName")??c.node.getChild("ConstSpec")?.getChild("DefName");if(k){let S=e.slice(k.from,k.to);S!=="_"&&/^[A-Z]/.test(S)&&!r.has(S)&&r.set(S,{name:S})}break}}while(c.next());let l=n.some(k=>k.rawSpecifier==="testing"),p=ao.default.basename(t).endsWith("_test.go")||s.has("test")||l?"test":"logic",u=new Set([...s,...i]),{complexity:f,cognitiveComplexity:m}=un(a.topNode,e),d=io(a,e),b=p==="test"?[]:Mp(a,e,o);return{imports:n,exports:Array.from(r.values()),tags:Array.from(u).map(k=>({name:k,kind:"comment-marker"})),category:p,rawCallEdges:b,complexity:f,cognitiveComplexity:m,...d.length>0?{functions:d}:{}}}function Mp(t,e,n){let r=[];function s(o,a){if(o.type.name==="CallExpr"){let l=o.firstChild;if(l?.type.name==="SelectorExpr"){let p=l.firstChild,u=l.getChild("FieldName");if(p?.type.name==="VariableName"&&u){let f=e.slice(p.from,p.to),m=n.get(f);if(m){let d=e.slice(u.from,u.to);r.push({from:a,to:d,toSpecifier:m})}}}}let c=o.firstChild;for(;c;)s(c,a),c=c.nextSibling}let i=t.cursor();do if(i.name==="FunctionDecl"){let o=i.node.getChild("DefName"),a=i.node.getChild("Block");if(o&&a){let c=e.slice(o.from,o.to);/^[A-Z]/.test(c)&&s(a,c)}}else if(i.name==="MethodDecl"){let o=i.node.getChild("FieldName"),a=i.node.getChild("Block");if(o&&a){let c=e.slice(o.from,o.to),l=Zr(i.node,e);s(a,l?`${l}.${c}`:c)}}while(i.next());return r}function oo(t,e){for(let n of t.split(/[\s,&|!()]+/)){let r=n.trim();r&&r!=="ignore"&&e.add(r)}}var Ip=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/g,Lp=["org.junit","androidx.test","org.robolectric","org.mockito","org.scalatest","munit","spock.lang","io.kotest","org.spekframework","org.testng","org.assertj","com.google.truth","org.hamcrest","io.mockk","com.nhaarman.mockitokotlin2"],qr=["test","androidTest","integrationTest","it"],_p=new RegExp(`/src/(${qr.join("|")})/`),Gp=/(?:Test|Tests|Spec|IT|ITCase)$/;function es(t){let e=t.replace(/\.\w+$/,"");return Gp.test(e)}function Ve(t){let e=new Set;for(let n of t.matchAll(Ip))n[1]&&e.add(n[1]);return e}function xe(t){let e=t.replace(/\/\*[\s\S]*?\*\//g,n=>n.replace(/[^\n]/g," "));return e=e.replace(/\/\/[^\n]*/g,n=>" ".repeat(n.length)),e}function Qe(t){let e=xe(t),n=new Set;for(let s of e.matchAll(/@([A-Z]\w*)/g))s[1]&&n.add(s[1]);let r=new Set;for(let s of e.matchAll(/\b(?:class|object|interface|trait|enum)\s+([A-Za-z_]\w*)/g))s[1]&&r.add(s[1]);return{annotations:[...n],typeNames:[...r]}}function fn(t){let e=t.split(".").pop();return e&&e!=="*"?e:void 0}function Ye(t,e,n=e){let r=fn(n);return{fromPath:t,toPath:"",rawSpecifier:e,isExternal:!0,isStyle:!1,type:"static",symbols:r?[r]:void 0}}function be(t,e){return{fromPath:t,toPath:"",rawSpecifier:`${e}.*`,isExternal:!0,isStyle:!1,type:"side-effect",isSamePackage:!0}}function ee(t,e){let n=[];for(let r of xe(t).split(`
|
|
8
|
+
`)){let s=r.trim();if(!s||s.startsWith("@")||s.startsWith("*"))continue;let i=s.match(/^package\s+(?:object\s+)?([\w.]+)/);if(i?.[1]){if(n.push(i[1]),!e)break;continue}if(!(e&&/^import\s/.test(s)))break}return n.length>0?n.join("."):null}var Op=new Set(["Configuration","SpringBootApplication","EnableAutoConfiguration"]),jp=new Set(["Composable","Preview"]),Wp=new Set(["RestController","Controller","Service","Repository","Component","Entity","MappedSuperclass","Embeddable"]),$p=["Activity","Fragment","ViewModel","Screen","Composable"];function ae(t,e,n={}){let r=t.replace(/\\/g,"/"),s=r.split("/").pop()??"";if(s.endsWith(".gradle")||s==="build.gradle.kts"||s==="settings.gradle.kts")return"config";if(_p.test(r)||e.some(o=>Lp.some(a=>o===a||o.startsWith(`${a}.`))))return"test";let i=n.annotations??[];return i.some(o=>Op.has(o))?"config":i.some(o=>jp.has(o))||(n.typeNames??[]).some(o=>$p.some(a=>o.endsWith(a)))?"ui":i.some(o=>Wp.has(o))?"logic":es(s)?"test":"logic"}var zp=/^\s*import\s+(static\s+)?([\w.]+(?:\.\*)?)(?:\s+as\s+\w+)?\s*$/,Bp=/^(?:@\w+\s+)*(?:public\s+|private\s+|protected\s+|final\s+|abstract\s+|static\s+)*(class|interface|trait|enum|def)\s+([A-Za-z_][A-Za-z0-9_]*)/;function Up(t,e){return t?e.endsWith(".*")?e.slice(0,-2)||null:e.split(".").slice(0,-1).join(".")||null:e||null}function po(t,e){let n=Ve(e),s=xe(e).split(`
|
|
9
|
+
`),i=[],o=new Set;for(let l of s){let p=l.match(zp);if(p?.[2]){let f=Up(!!p[1],p[2]);f&&i.push(Ye(t,f,p[2]));continue}let u=l.match(Bp);u?.[2]&&o.add(u[2])}let a=ee(e,!1);a&&i.push(be(t,a));let c=Array.from(o,l=>({name:l}));return{imports:i,exports:c,tags:Array.from(n).map(l=>({name:l,kind:"comment-marker"})),category:ae(t,i.map(l=>l.rawSpecifier),{typeNames:[...o],annotations:Qe(e).annotations})}}var go=require("@lezer/java");var uo=new Set(["ForStatement","EnhancedForStatement","WhileStatement","DoStatement"]),Kp=new Set(["ClassDeclaration","InterfaceDeclaration","EnumDeclaration","RecordDeclaration","AnnotationTypeDeclaration"]);function Hp(t,e){let n=1;function r(s){let i=s.type.name;if(i==="IfStatement"||i==="CatchClause"||i==="TernaryExpression")n++;else if(uo.has(i))n++;else if(i==="SwitchLabel")s.firstChild?.type.name==="case"&&n++;else if(i==="LogicOp"){let a=e.slice(s.from,s.to);(a==="&&"||a==="||")&&n++}let o=s.firstChild;for(;o;)r(o),o=o.nextSibling}return r(t),n}function fo(t,e,n,r){let s=n?1:1+e,i=[];for(let p=t.firstChild;p;p=p.nextSibling)i.push(p);let o=n?e:e+1,a=i[1];a&&a.type.name!=="Block"&&(s+=Xe(a,o,!1,r));let c=i.find(p=>p.type.name==="Block");c&&(s+=Xe(c,o,!1,r));let l=i.findIndex(p=>p.type.name==="else");if(l>=0){let p=i[l+1];p?.type.name==="IfStatement"?s+=fo(p,e,!0,r):p&&(s+=1+Xe(p,e+1,!1,r))}return s}function ts(t,e,n){let r=1+e,s=t.firstChild;for(;s;)r+=Xe(s,e+1,!1,n),s=s.nextSibling;return r}function Jp(t,e,n){let r=0,s=t.firstChild;for(;s;)r+=Xe(s,e,!1,n),s=s.nextSibling;return r}function Vp(t,e){let n=e.slice(t.from,t.to);return n==="&&"||n==="||"}function Xe(t,e,n,r){let s=t.type.name;if(s==="IfStatement")return fo(t,e,n,r);if(uo.has(s)||s==="SwitchStatement"||s==="CatchClause"||s==="TernaryExpression")return ts(t,e,r);let i=s==="LogicOp"&&Vp(t,r)?1:0;return e>0&&s==="LambdaExpression"?i+ts(t,e,r):i+Jp(t,e,r)}function Qp(t,e){return Xe(t,0,!1,e)}function ns(t,e){return{complexity:Hp(t,e),cognitiveComplexity:Qp(t,e)}}function rs(t,e){for(let n=t.parent;n;n=n.parent)if(Kp.has(n.type.name)){let r=n.getChild("Definition");if(r)return e.slice(r.from,r.to)}}function mo(t,e){let n=[],r=t.cursor();do if(r.name==="MethodDeclaration"||r.name==="ConstructorDeclaration"){let s=r.node.getChild("Definition");if(s){let i=e.slice(s.from,s.to),o=rs(r.node,e),a=o&&r.name==="MethodDeclaration"?`${o}.${i}`:i,{complexity:c,cognitiveComplexity:l}=ns(r.node,e);n.push({name:a,line:Fe(e,r.from),complexity:c,cognitiveComplexity:l})}}while(r.next());return n}var Yp=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/;function Xp(t,e){let n=t.getChild("ScopedIdentifier");if(!n)return null;let r=t.getChild("static")!=null,s=t.getChild("Asterisk")!=null,i=e.slice(n.from,n.to);if(r){if(s)return i?{specifier:i,wildcard:!1}:null;let o=i.split(".").slice(0,-1).join(".");return o?{specifier:o,wildcard:!1,symbol:fn(i)}:null}return s?{specifier:`${i}.*`,wildcard:!0}:{specifier:i,wildcard:!1,symbol:fn(i)}}function Zp(t){let e=new Map;for(let n of t){if(n.type==="side-effect")continue;let r=n.rawSpecifier;if(r.endsWith(".*"))continue;let s=r.split(".").pop();s&&e.set(s,r)}return e}function qp(t,e){let n=t;if(n.name==="GenericType"&&(n=n.firstChild),!n)return null;if(n.name==="TypeName")return e.slice(n.from,n.to);if(n.name==="ScopedTypeName"){let r=null;for(let s=n.firstChild;s;s=s.nextSibling)s.name==="TypeName"&&(r=s);return r?e.slice(r.from,r.to):null}return null}function eu(t,e,n){let r=[];function s(o,a){let c=o.type.name;if(c==="MethodInvocation"){let p=o.firstChild;if(p?.type.name==="Identifier"){let u=n.get(e.slice(p.from,p.to)),f=o.getChild("MethodName");u&&f&&r.push({from:a,to:e.slice(f.from,f.to),toSpecifier:u})}}else if(c==="ObjectCreationExpression"){let p=o.getChild("TypeName")??o.getChild("GenericType")??o.getChild("ScopedTypeName"),u=p&&qp(p,e);if(u){let f=n.get(u);f&&r.push({from:a,to:"new",toSpecifier:f})}}let l=o.firstChild;for(;l;)s(l,a),l=l.nextSibling}let i=t.cursor();do if(i.name==="MethodDeclaration"||i.name==="ConstructorDeclaration"){let o=i.node.getChild("Definition"),a=i.node.getChild("Block")??i.node.getChild("ConstructorBody");if(o&&a){let c=e.slice(o.from,o.to),l=rs(i.node,e),p=l&&i.name==="MethodDeclaration"?`${l}.${c}`:c;s(a,p)}}while(i.next());return r}function ho(t,e){let n=[],r=new Map,s=new Set,i=new Set,o;try{o=go.parser.parse(e)}catch{return{imports:[],exports:[],tags:[],category:ae(t,[])}}let a=o.cursor();do switch(a.name){case"LineComment":{let d=e.slice(a.from,a.to).match(Yp);d?.[1]&&s.add(d[1]);break}case"MarkerAnnotation":case"Annotation":{let d=a.node.getChild("Identifier");d&&i.add(e.slice(d.from,d.to));break}case"ImportDeclaration":{let d=Xp(a.node,e);d&&n.push({fromPath:t,toPath:"",rawSpecifier:d.specifier,isExternal:!0,isStyle:!1,type:"static",symbols:d.symbol?[d.symbol]:void 0});break}case"ClassDeclaration":case"InterfaceDeclaration":case"EnumDeclaration":case"AnnotationTypeDeclaration":{if(a.node.parent?.name==="Program"){let d=a.node.getChild("Definition");if(d){let b=e.slice(d.from,d.to);r.has(b)||r.set(b,{name:b})}}break}}while(a.next());let c=ee(e,!1);c&&n.push(be(t,c));let l=ae(t,n.map(d=>d.rawSpecifier),{typeNames:[...r.keys()],annotations:[...i]}),{complexity:p,cognitiveComplexity:u}=ns(o.topNode,e),f=mo(o,e),m=l==="test"?[]:eu(o,e,Zp(n));return{imports:n,exports:Array.from(r.values()),tags:Array.from(s).map(d=>({name:d,kind:"comment-marker"})),category:l,rawCallEdges:m,complexity:p,cognitiveComplexity:u,...f.length>0?{functions:f}:{}}}var tu=/^\s*import\s+([\w.]+(?:\.\*)?)(?:\s+as\s+\w+)?\s*$/,ss="(?:public\\s+|internal\\s+|private\\s+|protected\\s+|open\\s+|abstract\\s+|final\\s+|sealed\\s+|data\\s+|value\\s+|inline\\s+|noinline\\s+|crossinline\\s+|external\\s+|expect\\s+|actual\\s+|suspend\\s+|operator\\s+|infix\\s+|tailrec\\s+|const\\s+|lateinit\\s+)*",nu=new RegExp(`^(?:@[\\w.]+(?:\\([^)]*\\))?\\s+)*${ss}(?:(?:enum|annotation)\\s+)?(class|interface|object|typealias)\\s+([A-Za-z_][A-Za-z0-9_]*)`),ru=new RegExp(`^(?:@[\\w.]+(?:\\([^)]*\\))?\\s+)*${ss}fun\\s+(?:<[^>]*>\\s*)?(?:[A-Za-z_][\\w.]*(?:<[^>]*>)?\\.)?([A-Za-z_][A-Za-z0-9_]*)\\s*[(<]`),su=new RegExp(`^(?:@[\\w.]+(?:\\([^)]*\\))?\\s+)*${ss}(?:val|var)\\s+(?:<[^>]*>\\s*)?([A-Za-z_][A-Za-z0-9_]*)`);function yo(t,e){let n=Ve(e),s=xe(e).split(`
|
|
10
|
+
`),i=[],o=new Set;for(let l of s){let p=l.match(tu);if(p?.[1]){i.push(Ye(t,p[1]));continue}let u=l.match(nu);if(u?.[2]){o.add(u[2]);continue}let f=l.match(ru);if(f?.[1]){o.add(f[1]);continue}let m=l.match(su);m?.[1]&&o.add(m[1])}let a=ee(e,!1);a&&i.push(be(t,a));let c=Array.from(o,l=>({name:l}));return{imports:i,exports:c,tags:Array.from(n).map(l=>({name:l,kind:"comment-marker"})),category:ae(t,i.map(l=>l.rawSpecifier),{typeNames:[...o],annotations:Qe(e).annotations})}}var xo=h(require("livescript"));function De(t){if(t){if(typeof t.value=="string")return t.value;if(typeof t.base?.value=="string")return t.base.value}}function iu(t){if(!t)return[];if(t.constructor?.name==="Class"){let n=De(t.title);return n?[{name:n}]:[]}if(t.constructor?.name==="Obj"&&Array.isArray(t.items))return t.items.map(n=>De(n.key)??De(n.val)).filter(n=>!!n).map(n=>({name:n}));let e=De(t);return e?[{name:e}]:[]}function ou(t){let e=t.constructor?.name||t.type;if(e==="Assign"&&t.left?.constructor?.name==="Chain"){let n=t.left,r=De(n.head),i=n.tails?.[0]?.key?.name;if(r==="module"&&i==="exports")return iu(t.right);if(r==="exports"&&typeof i=="string")return[{name:i}];if(n.head?.verb==="out"&&typeof i=="string")return[{name:i}]}if(e==="Import"&&t.left?.verb==="out"){let n=t.right;if(n?.constructor?.name==="Obj"&&Array.isArray(n.items))return n.items.map(r=>De(r.val)??De(r.key)).filter(r=>!!r).map(r=>({name:r}))}return[]}var au=new Set(["first_line","first_column","last_line","last_column","line","column"]);function cu(t,e){let n=t.constructor?.name||t.type;if(n==="Import"){let r=t.right?.value;if(typeof r=="string"){let s=ye(r);return{fromPath:e,toPath:"",rawSpecifier:s,isStyle:W(s),type:"static"}}}if(n==="Chain"&&t.head?.value==="require"){let r=t.tails?.[0];if(r?.constructor?.name==="Call"||r?.type==="Call"){let s=r.args?.[0]?.value;if(typeof s=="string"){let i=ye(s);return{fromPath:e,toPath:"",rawSpecifier:i,isStyle:W(i),type:"require"}}}}return null}function is(t,e,n){if(!t||typeof t!="object")return[];let r=[],s=cu(t,e);s&&r.push(s),n.push(...ou(t));for(let i in t){if(au.has(i))continue;let o=t[i];if(!(!o||typeof o!="object"))if(Array.isArray(o))for(let a of o)r.push(...is(a,e,n));else r.push(...is(o,e,n))}return r}function bo(t,e){let n=Be(e),r=Ue(t,n),s=[],i=[];try{s=is(xo.default.ast(e),t,i)}catch{}let o=new Set,a=i.filter(c=>o.has(c.name)?!1:(o.add(c.name),!0));return{imports:s,exports:a,tags:Array.from(n).map(c=>({name:c,kind:"comment-marker"})),category:r}}var ko=h(require("luaparse"));function lu(t,e){let n=[];function r(s){if(!(!s||typeof s!="object")){if((s.type==="CallExpression"||s.type==="StringCallExpression")&&s.base?.type==="Identifier"&&s.base?.name==="require"){let i;if(s.type==="CallExpression"){let o=s.arguments?.[0];o?.type==="StringLiteral"&&(i=ye(o.raw))}else if(s.type==="StringCallExpression"){let o=s.argument;o?.type==="StringLiteral"&&(i=ye(o.raw))}i&&n.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:W(i),type:"require"})}for(let i in s){if(i==="loc")continue;let o=s[i];if(o&&typeof o=="object")if(Array.isArray(o))for(let a of o)r(a);else r(o)}}}return r(t),n}function pu(t){let e=new Set;for(let n of t)n.type==="LocalStatement"&&n.variables.forEach((r,s)=>{n.init[s]?.type==="TableConstructorExpression"&&e.add(r.name)});return e}function uu(t){let e=t[t.length-1];if(e?.type!=="ReturnStatement")return[];let n=e.arguments[0];if(n?.type!=="TableConstructorExpression")return[];let r=[];for(let s of n.fields)s.type==="TableKeyString"&&r.push({name:s.key.name});return r}function fu(t){let e=t.body,n=pu(e),r=uu(e);for(let i of e)if(i.type==="FunctionDeclaration")i.identifier?.type==="MemberExpression"?i.identifier.base.type==="Identifier"&&n.has(i.identifier.base.name)&&r.push({name:i.identifier.identifier.name}):i.identifier?.type==="Identifier"&&!i.isLocal&&r.push({name:i.identifier.name});else if(i.type==="AssignmentStatement")for(let o of i.variables)o.type==="MemberExpression"&&o.base.type==="Identifier"&&n.has(o.base.name)&&r.push({name:o.identifier.name});let s=new Set;return r.filter(i=>s.has(i.name)?!1:(s.add(i.name),!0))}function So(t,e){let n=Be(e),r=Ue(t,n),s=[],i=[];try{let o=ko.default.parse(e);s=lu(o,t),i=fu(o)}catch{}return{imports:s,exports:i,tags:Array.from(n).map(o=>({name:o,kind:"comment-marker"})),category:r}}var mu=["http://","https://","mailto:","//"],gu="ts|tsx|js|jsx|mjs|cjs|py|go|lua|css|scss|less|styl|coffee|ls|feature|md|mdx|json",du=new RegExp(`(?:\\.{1,2}/)?[\\w.-]+(?:/[\\w.-]+)*\\.(?:${gu})\\b`,"g"),vo;async function hu(){return vo??=(async()=>{let{unified:t}=await import("unified"),e=(await import("remark-parse")).default;return t().use(e)})(),vo}function yu(t){let e=t.trim();return e.length===0||e.startsWith("#")||mu.some(n=>e.startsWith(n))}function xu(t,e){let n=t.match(du);return n?n.map(r=>({fromPath:e,toPath:"",rawSpecifier:r,isStyle:!1,type:"static",isDocReference:!0})):[]}function Co(t,e,n){if(t.type==="link"&&typeof t.url=="string"&&!yu(t.url)&&n.push({fromPath:e,toPath:"",rawSpecifier:t.url,isStyle:!1,type:"static",isDocReference:!0}),(t.type==="code"||t.type==="inlineCode")&&typeof t.value=="string"&&n.push(...xu(t.value,e)),Array.isArray(t.children))for(let r of t.children)Co(r,e,n)}async function wo(t,e){let r=(await hu()).parse(e),s=[];Co(r,t,s);let i=new Set;return{imports:s.filter(a=>i.has(a.rawSpecifier)?!1:(i.add(a.rawSpecifier),!0)),exports:[],tags:[],category:"other"}}var Fo=h(require("path")),Do=require("@lezer/python");function bu(t){let e=1;function n(r){switch(r.type.name){case"IfStatement":{e+=Te(r).filter(i=>i.type.name==="if"||i.type.name==="elif").length;break}case"TryStatement":{e+=Te(r).filter(i=>i.type.name==="except").length;break}case"ForStatement":case"WhileStatement":case"ConditionalExpression":e++;break;case"and":case"or":e++;break}let s=r.firstChild;for(;s;)n(s),s=s.nextSibling}return n(t),e}function ku(t,e){let n=0,r=Te(t),s=0,i=0;for(;i<r.length;){let o=r[i];if(o?.type.name==="if"||o?.type.name==="elif"){let a=s>0;n+=a?1:1+e;let c=a?e:e+1,l=r[i+1],p=r[i+2];l&&(n+=ce(l,c)),p&&(n+=ce(p,c)),s++,i+=3}else if(o?.type.name==="else"){n+=1;let a=r[i+1];a&&(n+=ce(a,e+1)),i+=2}else i++}return n}function Su(t,e){let n=0,r=Te(t),s=0;for(;s<r.length;){let i=r[s];if(i?.type.name==="except"){for(n+=1+e,s++;s<r.length&&r[s]?.type.name!=="Body";)n+=ce(r[s],e),s++;s<r.length&&(n+=ce(r[s],e),s++)}else i?.type.name==="Body"&&(n+=ce(i,e)),s++}return n}function Eo(t,e){let n=1+e,r=t.firstChild;for(;r;)n+=ce(r,e+1),r=r.nextSibling;return n}function vu(t,e){let n=0,r=t.firstChild;for(;r;)n+=ce(r,e),r=r.nextSibling;return n}function ce(t,e){let n=t.type.name;switch(n){case"IfStatement":return ku(t,e);case"TryStatement":return Su(t,e);case"ForStatement":case"WhileStatement":return Eo(t,e);default:{let r=n==="ConditionalExpression"||n==="and"||n==="or"?1:0;return e>0&&(n==="FunctionDefinition"||n==="LambdaExpression")?r+Eo(t,e):r+vu(t,e)}}}function Cu(t){return ce(t,0)}function os(t){return{complexity:bu(t),cognitiveComplexity:Cu(t)}}function To(t,e){let n=[];function r(o,a){let{complexity:c,cognitiveComplexity:l}=os(o);n.push({name:a,line:Fe(e,o.from),complexity:c,cognitiveComplexity:l})}function s(o){let a=o.firstChild;for(;a;)i(a),a=a.nextSibling}function i(o){if(o.type.name==="ClassDefinition"){let a=o.getChild("VariableName"),c=a?e.slice(a.from,a.to):void 0,l=o.getChild("Body");if(l){let p=l.firstChild;for(;p;){if(p.type.name==="FunctionDefinition"){let u=p.getChild("VariableName"),f=u?e.slice(u.from,u.to):void 0;f&&r(p,c?`${c}.${f}`:f),s(p)}else i(p);p=p.nextSibling}}return}if(o.type.name==="FunctionDefinition"){let a=o.getChild("VariableName");a&&r(o,e.slice(a.from,a.to)),s(o);return}s(o)}return i(t.topNode),n}var wu=new Set(["pytest","unittest","nose","hypothesis"]);function Po(t,e){let n=[],r=[],s=new Set,i=Fo.default.basename(t).toLowerCase(),o=Do.parser.parse(e),a=o.cursor();do switch(a.name){case"Comment":{let m=e.slice(a.from,a.to).match(/#\s*@tag\s+([a-zA-Z0-9_-]+)/);m?.[1]&&s.add(m[1]);break}case"ImportStatement":{for(let m of Eu(a.node,e,t))n.push(m);break}case"FunctionDefinition":case"ClassDefinition":{let m=a.node.parent;if(m?.name==="Script"||m?.name==="DecoratedStatement"&&m.parent?.name==="Script"){let b=a.node.getChild("VariableName");b&&r.push({name:e.slice(b.from,b.to)})}break}case"AssignStatement":{if(a.node.parent?.name==="Script"){let m=a.node.firstChild;m?.name==="VariableName"&&r.push({name:e.slice(m.from,m.to)})}break}}while(a.next());let c=Ru(i,n,s);c==="test"&&s.add("test");let{complexity:l,cognitiveComplexity:p}=os(o.topNode),u=To(o,e),f=c==="test"?[]:Au(o,e);return{imports:n,exports:r,tags:Array.from(s).map(m=>({name:m,kind:"comment-marker"})),category:c,rawCallEdges:f,complexity:l,cognitiveComplexity:p,...u.length>0?{functions:u}:{}}}function Eu(t,e,n){let r=t.firstChild;return r?r.name==="from"?Tu(t,e,n):Fu(t,e,n):[]}function Tu(t,e,n){let r=t.firstChild;if(!r)return[];let s=r.nextSibling;for(;s&&s.name!=="import";)s=s.nextSibling;if(!s)return[];let i=e.slice(r.to,s.from).trim(),o=Du(s.nextSibling,e);if(!o.length)return[];let a=0;for(;a<i.length&&i[a]===".";)a++;let c=i.slice(a);if(a===0)return[Et(n,i,o,!0)];let l=a===1?"./":"../".repeat(a-1);return c?[Et(n,l+c.replace(/\./g,"/"),o,!1)]:o[0]==="*"?[Et(n,l.slice(0,-1),["*"],!1)]:o.map(p=>Et(n,l+p,[p],!1))}function Fu(t,e,n){let r=[],s=t.firstChild?.nextSibling??null;for(;s;){if(s.name==="VariableName"){let i=e.slice(s.from,s.to);for(;s.nextSibling?.name==="."&&s.nextSibling.nextSibling?.name==="VariableName";)s=s.nextSibling.nextSibling,i+=`.${e.slice(s.from,s.to)}`;s.nextSibling?.name==="as"&&(s=s.nextSibling.nextSibling??s.nextSibling),r.push(Et(n,i,["*"],!0))}s=s.nextSibling}return r}function Du(t,e){let n=[],r=t;for(;r;)r.name==="*"?n.push("*"):r.name==="VariableName"&&(n.push(e.slice(r.from,r.to)),r.nextSibling?.name==="as"&&(r=r.nextSibling.nextSibling??r.nextSibling)),r=r.nextSibling;return n}function Pu(t,e){let n=new Map,r=t.cursor();do{if(r.name!=="ImportStatement")continue;let i=r.node.firstChild;if(i?.type.name!=="from")continue;let o=i.nextSibling;for(;o&&o.type.name!=="import";)o=o.nextSibling;if(!o)continue;let a=e.slice(i.to,o.from).trim(),c=0;for(;c<a.length&&a[c]===".";)c++;let l=a.slice(c),p=c<=1?"./":"../".repeat(c-1),u=o.nextSibling;for(;u;){if(u.type.name==="VariableName"){let f=e.slice(u.from,u.to),m=f;if(u.nextSibling?.type.name==="as"){let b=u.nextSibling.nextSibling;b?.type.name==="VariableName"&&(m=e.slice(b.from,b.to),u=b)}let d=c===0?a:l?p+l.replace(/\./g,"/"):p+f;n.set(m,d)}u=u.nextSibling}}while(r.next());return n}function Au(t,e){let n=Pu(t,e),r=[];function s(a,c){if(a.type.name==="CallExpression"&&a.firstChild?.type.name==="VariableName"){let p=a.firstChild,u=e.slice(p.from,p.to),f=n.get(u);f&&r.push({from:c,to:u,toSpecifier:f})}let l=a.firstChild;for(;l;)s(l,c),l=l.nextSibling}function i(a){let c=a.firstChild;for(;c;)o(c),c=c.nextSibling}function o(a){if(a.type.name==="ClassDefinition"){let c=a.getChild("VariableName"),l=c?e.slice(c.from,c.to):void 0,p=a.getChild("Body");if(p){let u=p.firstChild;for(;u;){if(u.type.name==="FunctionDefinition"){let f=u.getChild("VariableName"),m=f?e.slice(f.from,f.to):void 0;m&&s(u,l?`${l}.${m}`:m)}else o(u);u=u.nextSibling}}return}if(a.type.name==="FunctionDefinition"){let c=a.getChild("VariableName");c&&s(a,e.slice(c.from,c.to));return}i(a)}return o(t.topNode),r}function Et(t,e,n,r){return{fromPath:t,toPath:"",rawSpecifier:e,isStyle:!1,isExternal:r,type:"static",symbols:n.length>0?n:void 0}}function Ru(t,e,n){return t.startsWith("test_")||t.endsWith("_test.py")?"test":t==="conftest.py"||t==="setup.py"?"config":n.has("test")||e.some(r=>wu.has(r.rawSpecifier))?"test":"logic"}var Nu=/^\s*import\s+(.+?)\s*$/,Mu=/^(?:@\w+\s+)*(?:private\s+|protected\s+|final\s+|sealed\s+|abstract\s+|implicit\s+|case\s+)*(class|trait|object|type|enum)\s+([A-Za-z_$][A-Za-z0-9_$]*)/;function Iu(t,e){let n=e.split("=>")[0]?.trim();return n?n==="_"||n==="*"||n==="given"?`${t}.*`:`${t}.${n}`:null}function Lu(t){let e=t.indexOf("{");if(e!==-1){let r=t.indexOf("}",e),s=t.slice(0,e).trim().replace(/\.$/,""),i=t.slice(e+1,r===-1?void 0:r);return s?i.split(",").map(o=>Iu(s,o.trim())).filter(o=>o!=null):[]}let n=[];for(let r of t.split(",")){let s=r.trim().replace(/\s+as\s+\w+$/,"");if(s)if(s.endsWith("._")||s.endsWith(".*")||s.endsWith(".given")){let i=s.replace(/\.(_|\*|given)$/,"");i&&n.push(`${i}.*`)}else n.push(s)}return n}function Ao(t,e){let n=Ve(e),s=xe(e).split(`
|
|
11
|
+
`),i=[],o=new Set;for(let l of s){let p=l.match(Nu);if(p?.[1]){for(let f of Lu(p[1]))i.push(Ye(t,f));continue}let u=l.match(Mu);u?.[2]&&o.add(u[2])}let a=ee(e,!0);a&&i.push(be(t,a));let c=Array.from(o,l=>({name:l}));return{imports:i,exports:c,tags:Array.from(n).map(l=>({name:l,kind:"comment-marker"})),category:ae(t,i.map(l=>l.rawSpecifier),{typeNames:[...o],annotations:Qe(e).annotations})}}var ls=h(require("path")),y=h(require("typescript"));var C=h(require("typescript"));function _u(t){let e=1;function n(r){switch(r.kind){case C.default.SyntaxKind.IfStatement:case C.default.SyntaxKind.ConditionalExpression:case C.default.SyntaxKind.ForStatement:case C.default.SyntaxKind.ForInStatement:case C.default.SyntaxKind.ForOfStatement:case C.default.SyntaxKind.WhileStatement:case C.default.SyntaxKind.DoStatement:case C.default.SyntaxKind.CatchClause:case C.default.SyntaxKind.CaseClause:e++;break;case C.default.SyntaxKind.BinaryExpression:{let s=r.operatorToken.kind;(s===C.default.SyntaxKind.AmpersandAmpersandToken||s===C.default.SyntaxKind.BarBarToken||s===C.default.SyntaxKind.QuestionQuestionToken)&&e++;break}}C.default.forEachChild(r,n)}return n(t),e}function No(t,e,n){let r=n?1:1+e,s=n?e:e+1;return r+=Pe(t.expression,s,!1),r+=Pe(t.thenStatement,s,!1),t.elseStatement&&(C.default.isIfStatement(t.elseStatement)?r+=No(t.elseStatement,e,!0):r+=1+Pe(t.elseStatement,e+1,!1)),r}function Ro(t,e){let n=1+e;return C.default.forEachChild(t,r=>{n+=Pe(r,e+1,!1)}),n}function Gu(t,e){let n=1+e;return C.default.forEachChild(t,r=>{n+=Pe(r,e,!1)}),n}function Ou(t,e){let n=0;return C.default.forEachChild(t,r=>{n+=Pe(r,e,!1)}),n}function ju(t){let e=t.operatorToken.kind;return e===C.default.SyntaxKind.AmpersandAmpersandToken||e===C.default.SyntaxKind.BarBarToken||e===C.default.SyntaxKind.QuestionQuestionToken}function Pe(t,e,n){if(C.default.isIfStatement(t))return No(t,e,n);if(C.default.isForStatement(t)||C.default.isForInStatement(t)||C.default.isForOfStatement(t)||C.default.isWhileStatement(t)||C.default.isDoStatement(t)||C.default.isSwitchStatement(t))return Ro(t,e);if(C.default.isCatchClause(t))return Gu(t,e);let r=0;return C.default.isConditionalExpression(t)&&(r+=1),C.default.isBinaryExpression(t)&&ju(t)&&(r+=1),e>0&&(C.default.isFunctionDeclaration(t)||C.default.isFunctionExpression(t)||C.default.isArrowFunction(t))?r+Ro(t,e):r+Ou(t,e)}function Wu(t){return Pe(t,0,!1)}function as(t){return{complexity:_u(t),cognitiveComplexity:Wu(t)}}var E=h(require("typescript")),cs=new Set(["test","describe","it"]);function Mo(t,e){$u(t,e),Bu(t,e),Uu(t,e)}function $u(t,e){if((E.default.isFunctionDeclaration(t)||E.default.isVariableDeclaration(t))&&t.name&&E.default.isIdentifier(t.name)&&zu(t)){let n;if(E.default.isFunctionDeclaration(t))n="function";else{let r=t.initializer;n=r&&(E.default.isArrowFunction(r)||E.default.isFunctionExpression(r))?"function":"variable"}e.tags.add({name:t.name.text,kind:n})}}function zu(t){if(E.default.isFunctionDeclaration(t))return E.default.isSourceFile(t.parent);let e=t.parent?.parent;return!!e&&E.default.isSourceFile(e.parent)}function Bu(t,e){if(!E.default.isSourceFile(t))return;let n=/@tag\s+([a-zA-Z0-9_-]+)/g,r=t.getFullText(),s=n.exec(r);for(;s!==null;)s[1]&&e.tags.add({name:s[1],kind:"comment-marker"}),s=n.exec(r)}function Uu(t,e){if(!E.default.isCallExpression(t)||!Ku(t.expression))return;let[n]=t.arguments;if(n&&E.default.isStringLiteral(n))for(let r of n.text.match(/@[\w-]+/g)??[])e.tags.add({name:r.substring(1),kind:"comment-marker"});for(let r of t.arguments)E.default.isObjectLiteralExpression(r)&&Hu(r,e)}function Ku(t){return E.default.isIdentifier(t)?cs.has(t.text):!!(E.default.isPropertyAccessExpression(t)&&(cs.has(t.name.text)||E.default.isIdentifier(t.expression)&&cs.has(t.expression.text)))}function Hu(t,e){for(let n of t.properties){if(!E.default.isPropertyAssignment(n)||!E.default.isIdentifier(n.name)||n.name.text!=="tags"&&n.name.text!=="tag")continue;let{initializer:r}=n,s=E.default.isArrayLiteralExpression(r)?r.elements.filter(E.default.isStringLiteral):n.name.text==="tag"&&E.default.isStringLiteral(r)?[r]:[];for(let i of s)e.tags.add({name:i.text.replace(/^@/,""),kind:"comment-marker"})}}function ps(t,e,n){let r=[],s=new Map,i=new Set,o=y.default.createSourceFile(t,e,y.default.ScriptTarget.Latest,!0,n==="typescript"?y.default.ScriptKind.TSX:y.default.ScriptKind.JSX),a={filePath:t,imports:r,exports:s,tags:i,rawCallEdges:[],sourceFile:o,hasUI:!1,hasTypesOnly:!0,totalStatements:0,exportStatements:0},c=b=>{Yu(b,a),y.default.forEachChild(b,c)};c(o);let l=cf(t,a);(l==="test"||l==="barrel")&&i.add({name:l,kind:"comment-marker"}),l!=="test"&&lf(a,o);let p=o.statements[0],u=p?Lo(p):void 0,{complexity:f,cognitiveComplexity:m}=as(o),d=Ju(o);return{imports:r,exports:Array.from(s.values()),tags:Array.from(i),category:l,rawCallEdges:a.rawCallEdges??[],complexity:f,cognitiveComplexity:m,...d.length>0?{functions:d}:{},...u!==void 0?{description:u}:{}}}function Ju(t){let e=[],n=(s,i)=>{let{complexity:o,cognitiveComplexity:a}=as(i),c=t.getLineAndCharacterOfPosition(i.getStart(t)).line+1;e.push({name:s,line:c,complexity:o,cognitiveComplexity:a})},r=(s,i)=>{if(y.default.isFunctionDeclaration(s)&&s.name&&s.body?n(s.name.text,s):y.default.isVariableDeclaration(s)&&y.default.isIdentifier(s.name)&&s.initializer&&(y.default.isArrowFunction(s.initializer)||y.default.isFunctionExpression(s.initializer))?n(s.name.text,s.initializer):i&&y.default.isMethodDeclaration(s)&&y.default.isIdentifier(s.name)&&s.body?n(`${i}.${s.name.text}`,s):i&&y.default.isConstructorDeclaration(s)&&s.body?n(`${i}.constructor`,s):i&&y.default.isGetAccessorDeclaration(s)&&y.default.isIdentifier(s.name)&&s.body?n(`${i}.get ${s.name.text}`,s):i&&y.default.isSetAccessorDeclaration(s)&&y.default.isIdentifier(s.name)&&s.body&&n(`${i}.set ${s.name.text}`,s),y.default.isClassDeclaration(s)&&s.name){let o=s.name.text;y.default.forEachChild(s,a=>r(a,o));return}y.default.forEachChild(s,o=>r(o,i))};return r(t,void 0),e}function Io(t,e,n,r){let s={name:t},i=Lo(n);i!==void 0&&(s.doc=i);let o=Vu(e);o!==void 0&&(s.flags=o);let a=Qu(e,r);return a!==void 0&&(s.signature=a),s}function Lo(t){let e=y.default.getJSDocCommentsAndTags(t);for(let n of e)if(y.default.isJSDoc(n)&&n.comment)return y.default.getTextOfJSDocComment(n.comment)||void 0}function Vu(t){let e=new Set(["deprecated","internal","public","alpha","beta"]),n=y.default.getJSDocTags(t).map(r=>r.tagName.text).filter(r=>e.has(r));return n.length>0?n:void 0}function Qu(t,e){let n=y.default.createPrinter({removeComments:!0}),r=s=>n.printNode(y.default.EmitHint.Unspecified,s,e);if(y.default.isFunctionDeclaration(t)||y.default.isMethodDeclaration(t)){let s=t.parameters.map(r).join(", "),i=t.type?r(t.type):"void";return`${t.typeParameters?`<${t.typeParameters.map(a=>a.name.text).join(", ")}>`:""}(${s}) => ${i}`}if(y.default.isVariableDeclaration(t)){if(t.type)return r(t.type);if(t.initializer&&(y.default.isArrowFunction(t.initializer)||y.default.isFunctionExpression(t.initializer))){let s=t.initializer,i=s.parameters.map(r).join(", "),o=s.type?r(s.type):"unknown";return`(${i}) => ${o}`}return}if(y.default.isClassDeclaration(t)&&t.name)return`class ${t.name.text}`;if(y.default.isInterfaceDeclaration(t))return`interface ${t.name.text}`;if(y.default.isTypeAliasDeclaration(t))return r(t.type);if(y.default.isEnumDeclaration(t))return`enum ${t.name.text}`}function Yu(t,e){Xu(t,e),Zu(t,e),ef(t,e),tf(t,e),af(t,e),Mo(t,e)}function Xu(t,e){if(!y.default.isSourceFile(t))return;let n=t.statements.filter(r=>!y.default.isEmptyStatement(r));e.totalStatements=n.length,e.exportStatements=n.filter(r=>y.default.isExportDeclaration(r)||y.default.isExportAssignment(r)||us(r)).length}function Zu(t,e){if(y.default.isJsxElement(t)||y.default.isJsxSelfClosingElement(t)||y.default.isJsxFragment(t)){e.hasUI=!0,e.hasTypesOnly=!1;return}if(y.default.isFunctionDeclaration(t)||y.default.isMethodDeclaration(t)||y.default.isArrowFunction(t)||y.default.isClassDeclaration(t)||y.default.isVariableStatement(t)||y.default.isEnumDeclaration(t)){e.hasTypesOnly=!1;return}y.default.isExportDeclaration(t)&&!qu(t)&&(e.hasTypesOnly=!1)}function qu(t){return t.isTypeOnly?!0:!t.exportClause||!y.default.isNamedExports(t.exportClause)?!1:t.exportClause.elements.every(e=>e.isTypeOnly)}function ef(t,e){if(!y.default.isImportDeclaration(t)||!t.moduleSpecifier||!y.default.isStringLiteral(t.moduleSpecifier))return;let n=[];if(t.importClause&&(t.importClause.name&&n.push("default"),t.importClause.namedBindings))if(y.default.isNamedImports(t.importClause.namedBindings))for(let s of t.importClause.namedBindings.elements)n.push(s.name.text);else y.default.isNamespaceImport(t.importClause.namedBindings)&&n.push("*");let r=n.length>0?"static":"side-effect";e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:t.moduleSpecifier.text,isStyle:W(t.moduleSpecifier.text),type:r,symbols:n.length>0?n:void 0})}function tf(t,e){y.default.isExportDeclaration(t)?nf(t,e):y.default.isExportAssignment(t)?e.exports.set("default",{name:"default"}):us(t)&&of(t,e)}function nf(t,e){if(t.moduleSpecifier&&y.default.isStringLiteral(t.moduleSpecifier))rf(t,t.moduleSpecifier.text,e);else if(t.exportClause&&y.default.isNamedExports(t.exportClause))for(let n of t.exportClause.elements){let r=n.name.text;e.exports.set(r,{name:r})}}function rf(t,e,n){let r=sf(t),s={fromPath:n.filePath,toPath:"",rawSpecifier:e,isStyle:W(e),type:"re-export"};r.length>0&&(s.symbols=r),n.imports.push(s)}function sf(t){return t.exportClause?y.default.isNamedExports(t.exportClause)?t.exportClause.elements.map(e=>e.name.text):[]:["*"]}function of(t,e){if((y.default.isFunctionDeclaration(t)||y.default.isClassDeclaration(t)||y.default.isInterfaceDeclaration(t)||y.default.isTypeAliasDeclaration(t)||y.default.isEnumDeclaration(t))&&t.name){let r=t.name.text;e.exports.set(r,Io(r,t,t,e.sourceFile));return}if(y.default.isVariableStatement(t)){for(let r of t.declarationList.declarations)if(y.default.isIdentifier(r.name)){let s=r.name.text;e.exports.set(s,Io(s,r,t,e.sourceFile))}}}function af(t,e){if(!y.default.isCallExpression(t))return;let n=t.arguments[0];!n||!y.default.isStringLiteral(n)||(t.expression.kind===y.default.SyntaxKind.ImportKeyword?e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:n.text,isStyle:W(n.text),type:"dynamic"}):y.default.isIdentifier(t.expression)&&t.expression.text==="require"&&e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:n.text,isStyle:W(n.text),type:"require"}))}function cf(t,e){let n=ls.default.basename(t).toLowerCase(),r=ls.default.extname(t).toLowerCase();return xt().some(i=>n.includes(i))?"test":Ti(n)?"config":e.imports.some(i=>wr().some(o=>i.rawSpecifier.includes(o)))?"test":r===".tsx"||r===".jsx"||e.hasUI?"ui":e.hasTypesOnly&&e.totalStatements>0?"type-only":e.totalStatements>0&&e.exportStatements/e.totalStatements>Fr()?"barrel":"logic"}function us(t){return y.default.canHaveModifiers(t)&&y.default.getModifiers(t)?.some(e=>e.kind===y.default.SyntaxKind.ExportKeyword)===!0}function lf(t,e){let n=t.rawCallEdges??[];t.rawCallEdges=n;let r=new Map;for(let s of e.statements){if(!y.default.isImportDeclaration(s)||!y.default.isStringLiteral(s.moduleSpecifier))continue;let i=s.moduleSpecifier.text,o=s.importClause;if(o&&(o.name&&r.set(o.name.text,i),o.namedBindings&&y.default.isNamedImports(o.namedBindings)))for(let a of o.namedBindings.elements)r.set(a.name.text,i)}if(r.size!==0)for(let s of e.statements){let i=uf(s);if(i){let o=ff(s);o&&mn(o,i,r,n);continue}y.default.isClassDeclaration(s)&&s.name&&pf(s,s.name.text,r,n)}}function pf(t,e,n,r){for(let s of t.members)y.default.isMethodDeclaration(s)&&s.body&&y.default.isIdentifier(s.name)?mn(s.body,`${e}.${s.name.text}`,n,r):y.default.isConstructorDeclaration(s)&&s.body&&mn(s.body,`${e}.constructor`,n,r)}function uf(t){if(us(t)){if(y.default.isFunctionDeclaration(t)&&t.name)return t.name.text;if(y.default.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(y.default.isIdentifier(e.name)&&e.initializer&&(y.default.isArrowFunction(e.initializer)||y.default.isFunctionExpression(e.initializer)))return e.name.text}}}function ff(t){if(y.default.isFunctionDeclaration(t))return t.body;if(y.default.isVariableStatement(t)){for(let e of t.declarationList.declarations)if(e.initializer&&(y.default.isArrowFunction(e.initializer)||y.default.isFunctionExpression(e.initializer)))return e.initializer}}function mn(t,e,n,r){if(y.default.isCallExpression(t)&&y.default.isIdentifier(t.expression)){let s=t.expression.text,i=n.get(s);i&&!r.some(o=>o.from===e&&o.to===s&&o.toSpecifier===i)&&r.push({from:e,to:s,toSpecifier:i})}y.default.forEachChild(t,s=>mn(s,e,n,r))}function gn(t,e){if(e.length===0)return"ui";let n=!1;return t.walk(r=>{if(r.type==="rule")return n=!0,!1}),n?"ui":"barrel"}var fs=h(require("postcss")),mf=h(require("postcss-less")),gf=mf,Go=new Set(["reference","inline"]);function _o(t){return t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||t.startsWith("data:")}function df(t){let e=t.trim();return e.length>0&&!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("//")&&!e.startsWith("data:")&&!e.startsWith("#")}function hf(t,e){let n=t.match(/^\(([^)]+)\)\s+['"]([^'"]+)['"]/);if(n){let i=n[1]?.trim()??"",o=n[2]??"";if(!o)return null;let a=Go.has(i)?"side-effect":"static";return{fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:a,..._o(o)?{isExternal:!0}:{}}}let r=t.match(/^url\(['"]?([^'")]+)['"]?\)/),s=r?r[1]?.trim()??"":t.match(/^['"]([^'"]+)['"]/)?.[1]??"";return s?{fromPath:e,toPath:"",rawSpecifier:s,isStyle:!0,type:"static",..._o(s)?{isExternal:!0}:{}}:null}function yf(t,e){let n=[],r=/url\(['"]?([^'")]+)['"]?\)/g,s=r.exec(t);for(;s!==null;){let i=s[1]?.trim()??"";df(i)&&n.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"static"}),s=r.exec(t)}return n}function Oo(t,e){let n=[];return t.walk(r=>{if(r.type==="atrule"&&r.name==="import"){let s=hf(r.params,e);s&&n.push(s)}r.type==="decl"&&n.push(...yf(r.value,e))}),n}function xf(t){return t.replace(/(?<!:)\/\/.*/g,"")}function bf(t,e){let n=[],r=/@import\s+(?:\(([^)]+)\)\s+)?['"]([^'"]+)['"]/g,s=r.exec(t);for(;s!==null;){let i=s[1]?.trim()??"",o=s[2]??"";if(o){let a=Go.has(i)?"side-effect":"static";n.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:a})}s=r.exec(t)}return n}function dn(t,e){let n=fs.default.parse(xf(t));return{imports:Oo(n,e),root:n}}function kf(t){let e=[],n=[];for(let r of t.nodes??[]){if(r.type!=="atrule")continue;let{value:s}=r;if(s===void 0)continue;let i=r.name;i&&(e.push({name:i}),n.push({name:i,kind:"variable"}))}return{exports:e,tags:n}}function hn(t,e){try{let n=gf.parse(t),{exports:r,tags:s}=kf(n);return{imports:Oo(n,e),root:n,exports:r,tags:s}}catch{return{imports:bf(t,e),root:fs.default.parse(""),exports:[],tags:[]}}}var Wo=require("postcss-scss");function jo(t){return t.startsWith("_")||t.startsWith("-")}function Sf(t){return!!(t.startsWith("sass:")||t.startsWith("~")||t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||!t.startsWith(".")&&!t.startsWith("/")&&!t.startsWith("_"))}function vf(t){let e=t.match(/^['"]([^'"]+)['"]/);if(!e?.[1])return{specifier:""};let n=e[1],s=t.match(/\bas\s+(\S+)/)?.[1];return s!==void 0?{specifier:n,alias:s}:{specifier:n}}function Cf(t){let e=[],n=[];for(let r of t.nodes??[]){if(r.type==="decl"&&r.prop.startsWith("$")){let s=r.prop.slice(1);if(!s||jo(s))continue;e.push({name:s}),n.push({name:s,kind:"variable"});continue}if(r.type==="atrule"&&(r.name==="mixin"||r.name==="function")){let i=r.params.match(/^([\w-]+)/)?.[1];if(!i||jo(i))continue;let o=r.params.trim();e.push(o.includes("(")?{name:i,signature:o}:{name:i}),n.push({name:i,kind:"function"})}}return{exports:e,tags:n}}function yn(t,e){let n=(0,Wo.parse)(t),r=[];n.walk(o=>{if(o.type!=="atrule")return;let{name:a,params:c}=o;if(a!=="import"&&a!=="use"&&a!=="forward")return;let{specifier:l,alias:p}=vf(c);if(!l)return;let u={fromPath:e,toPath:"",rawSpecifier:l,isStyle:!0,type:a==="forward"?"re-export":"static",...Sf(l)?{isExternal:!0}:{}};p&&(u.symbols=[p]),r.push(u)});let{exports:s,tags:i}=Cf(n);return{imports:r,root:n,exports:s,tags:i}}function $o(t,e){let n=[],r=/@require\s+['"]([^'"]+)['"]/g,s=r.exec(t);for(;s!==null;){let o=s[1];o&&n.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:"require"}),s=r.exec(t)}let i=/(?<!@)(?:import|require)\s*\(?\s*['"]([^'"]+)['"]/g;for(s=i.exec(t);s!==null;){let o=s[1];o&&n.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:"static"}),s=i.exec(t)}return n}function zo(t,e){if(e.length===0)return"ui";try{let n=require("stylus");return new n.Parser(t).parse().nodes.some(i=>i.constructor.name!=="Import")?"ui":"barrel"}catch{return t.replace(/^\s*@?(?:require|import)\b.*/gm,"").trim().length>0?"ui":"barrel"}}function Tt(t,e){let n=V(t);if(n==="stylus"){let i=$o(e,t);return{imports:i,exports:[],tags:[],category:zo(e,i)}}if(n==="scss"){let{imports:i,root:o,exports:a,tags:c}=yn(e,t);return{imports:i,exports:a,tags:c,category:gn(o,i)}}if(n==="less"){let{imports:i,root:o,exports:a,tags:c}=hn(e,t);return{imports:i,exports:a,tags:c,category:gn(o,i)}}let{imports:r,root:s}=dn(e,t);return{imports:r,exports:[],tags:[],category:gn(s,r)}}for(let[t,e]of[["javascript",(n,r)=>ps(n,r,"javascript")],["typescript",(n,r)=>ps(n,r,"typescript")],["css",Tt],["scss",Tt],["less",Tt],["stylus",Tt],["coffeescript",qi],["livescript",bo],["lua",So],["python",Po],["go",lo],["java",ho],["kotlin",yo],["scala",Ao],["groovy",po],["gherkin",Xr],["markdown",wo]])Ke(t,e);async function Bo(t,e){let n=V(t),r=to(n);return r?r(t,e):{imports:[],exports:[],tags:[],category:"other"}}var ms=h(require("path"));function wf(t,e){let n=e.get(t.path);n!==void 0&&(t.coveragePct=n)}function Ko(t,e){for(let n of t)if(n.isExternal){let r=n.rawSpecifier.startsWith("@")?n.rawSpecifier.split("/").slice(0,2).join("/"):n.rawSpecifier.split("/")[0];r&&!e.some(s=>s.name===r)&&e.push({name:r,kind:"library"})}}function Ef(t,e,n){if(e.isExternal||!e.toPath)return;let r=n.get(e.toPath);r&&(r.category!=="logic"&&r.category!=="barrel"||(r.testedBy??=[],r.testedBy.includes(t.path)||r.testedBy.push(t.path)))}function Tf(t,e){if(t.type==="markdown")for(let n of t.imports){if(n.isExternal||!n.toPath)continue;let r=e.get(n.toPath);!r||r===t||(r.documentedBy??=[],r.documentedBy.includes(t.path)||r.documentedBy.push(t.path),r.category==="logic"&&(r.lastCommitAt??0)>(t.lastCommitAt??0)&&(t.staleFor??=[],t.staleFor.includes(r.path)||t.staleFor.push(r.path)))}}function Uo(t){return Math.round(t*1e4)/1e4}function Ff(t,e){let n=[];for(let r of t.imports){if(r.isExternal||!r.toPath)continue;let s=e.get(r.toPath);if(!s||s.exports.length===0)continue;let i;if(r.symbols===void 0){if(r.type==="side-effect")continue;i=1}else r.symbols.includes("*")?i=1:i=r.symbols.length/s.exports.length;r.exportUsageRatio=Uo(Math.min(1,i)),n.push(r.exportUsageRatio)}n.length>0&&(t.avgExportUsage=Uo(n.reduce((r,s)=>r+s,0)/n.length),t.maxExportUsage=Math.max(...n))}function Ho(t,e,n){e&&(t.some(r=>r.name===e&&r.kind===n)||t.push({name:e,kind:n}))}function Df(t,e){let n=e.toPath,r=ms.default.basename(n,ms.default.extname(n)).replace(/\.(test|spec)$/,"");Ho(t.tags,r,"import")}function Pf(t,e,n){let r=n.get(e.toPath);if(!(!r||r.category==="test"))for(let s of r.tags)s.kind==="comment-marker"&&Ho(t.tags,s.name,"comment-marker")}function Af(t,e,n){!e.toPath||e.isExternal||(Df(t,e),Pf(t,e,n))}function Jo(t,e){for(let n of t.values())delete n.testedBy,delete n.documentedBy,delete n.staleFor,n.category==="test"&&(n.tags=n.tags.filter(r=>r.kind!=="import"));for(let n of t.values()){if(Ff(n,t),e.size>0&&wf(n,e),n.category==="test")for(let r of n.imports)Ef(n,r,t),Af(n,r,t);Tf(n,t)}}var Vo=new Set(["java","kotlin","scala","groovy"]),Qo=new Set(["typescript","javascript","python","go","java","kotlin","scala","groovy","scss","less","lua","coffeescript"]),Yo=new Set(["typescript","javascript","python","java","kotlin","scala","groovy"]),Ft=new Set(["typescript","javascript","go","python","java"]),Xo=new Set(["typescript","javascript","go","python","java"]);var Zo=new Set(["typescript","javascript"]),Rf={callEdges:Ft,functionComplexity:Xo,typeGraph:Zo},Nf={callEdges:"call edges",functionComplexity:"per-function complexity",typeGraph:"type extraction"};function Ze(t,e){let n=Array.isArray(t)?t:[t],r=Rf[e],s=new Set;for(let c of n)for(let l of c.nodes.values()){if(r.has(l.type))return;l.type!=="markdown"&&l.type!=="unknown"&&s.add(l.type)}let i=[...s].sort(),o=i.length===0?"this project":i.join(", "),a=i.length===1?"is":"are";return`${Nf[e]} is only tracked for ${[...r].sort().join(", ")} \u2014 ${o} ${a} unsupported, so this result is empty by design.`}function R(t,e,n,r,s,i,o,a){return{importResolution:t,exportSymbols:e,importSymbols:n,callEdges:r,complexity:s,category:i,duplication:o,testTags:a}}var gs={typescript:R("full","full","full","full","full","full","partial","full"),javascript:R("full","full","full","full","full","full","partial","full"),python:R("full","partial","partial","full","full","partial","partial","full"),go:R("full","partial","none","full","full","partial","partial","full"),java:R("partial","partial","partial","partial","full","partial","partial","full"),kotlin:R("partial","partial","partial","none","none","partial","partial","full"),scala:R("partial","partial","partial","none","none","partial","partial","full"),groovy:R("partial","partial","partial","none","none","partial","partial","full"),coffeescript:R("partial","partial","none","none","none","partial","partial","none"),livescript:R("partial","none","none","none","none","partial","partial","none"),lua:R("partial","partial","none","none","none","partial","partial","none"),css:R("full","none","none","none","none","full","full","none"),scss:R("full","partial","none","none","none","full","full","none"),less:R("full","partial","none","none","none","full","full","none"),stylus:R("full","none","none","none","none","full","partial","none"),gherkin:R("none","none","none","none","none","full","partial","full"),markdown:R("partial","none","none","none","none","full","partial","none"),unknown:R("none","none","none","none","none","none","none","none")},Mf={importResolution:"import resolution",exportSymbols:"export symbols",importSymbols:"per-import symbol tracking",callEdges:"call edges",complexity:"complexity",category:"category classification",duplication:"duplicate detection",testTags:"test-tag strategy"},If={python:{exportSymbols:"tracked at module level, not per-symbol",importSymbols:"only star imports and re-exports are tracked (ADR-002)"},go:{exportSymbols:"identifier-level, no per-symbol doc/signature",importSymbols:"not tracked \u2014 per-import symbol resolution is not implemented"},java:{importResolution:"index-based: matched by type name across the module, not by resolving the exact package path (ADR-017)",exportSymbols:"top-level types only, no field/method-level exports",importSymbols:"one symbol per import (the FQN's last segment, or the static member for `import static`); wildcard imports carry none, and re-exports aren't tracked",callEdges:"static calls and constructors only (incl. through generics), not virtual dispatch"},kotlin:{importResolution:"index-based, shared with Java's JvmLangResolver (ADR-017)",exportSymbols:"top-level types only",importSymbols:"one symbol per import (the FQN's last segment); wildcard imports carry none, and re-exports aren't tracked",callEdges:"not extracted \u2014 Kotlin needs its own grammar (issue 8c)",complexity:"not computed \u2014 Kotlin needs its own grammar (issue 8c)"},scala:{importResolution:"index-based, shared with Java's JvmLangResolver; brace-package imports are a known gap",exportSymbols:"top-level types only",importSymbols:"one symbol per import (the FQN's last segment, brace groups expanded to one edge per member); wildcard imports carry none, and re-exports aren't tracked",callEdges:"not extracted \u2014 Scala needs its own grammar (issue 8c)",complexity:"not computed \u2014 Scala needs its own grammar (issue 8c)"},groovy:{importResolution:"index-based, shared with Java's JvmLangResolver",exportSymbols:"top-level types only",importSymbols:"one symbol per import (the FQN's last segment, or the static member for `import static`); wildcard imports carry none, and re-exports aren't tracked",callEdges:"not extracted \u2014 Groovy needs its own grammar (issue 8c)",complexity:"not computed \u2014 Groovy needs its own grammar (issue 8c)"},coffeescript:{importResolution:"generic relative-path fallback, no ecosystem-specific rules",exportSymbols:"best-effort, less validated than TS/JS",callEdges:"not extracted (backfill planned \u2014 see the language coverage roadmap)",complexity:"not computed (backfill planned \u2014 see the language coverage roadmap)",testTags:"no framework-aware strategy \u2014 falls back to the generic path-glob applier"},livescript:{importResolution:"generic relative-path fallback",exportSymbols:"not tracked",callEdges:"not extracted (backfill planned)",complexity:"not computed (backfill planned)",testTags:"no framework-aware strategy \u2014 falls back to the generic path-glob applier"},lua:{importResolution:"basic dot-path handling only",exportSymbols:"best-effort module-return inspection",callEdges:"not extracted (backfill planned)",complexity:"not computed (backfill planned)",testTags:"no framework-aware strategy \u2014 falls back to the generic path-glob applier"},scss:{exportSymbols:"root-level $/@ variables, mixins and functions only"},less:{exportSymbols:"root-level $/@ variables, mixins and functions only"},stylus:{duplication:"generic token pipeline \u2014 no shared PostCSS AST for structural comparison"},markdown:{importResolution:"edges only via code-span file references (`` `src/foo.ts` ``) (ADR-009)"},gherkin:{importResolution:"feature files have no imports"}},Lf=["importResolution","exportSymbols","importSymbols","callEdges","complexity"];function Q(t,e){let n=Array.isArray(t)?t:[t],r=new Set;for(let i of n)for(let o of i.nodes.values())o.type!=="markdown"&&o.type!=="unknown"&&r.add(o.type);let s=[];for(let i of r){let o=gs[i][e];if(o==="full")continue;let a=If[i]?.[e];!a&&o!=="none"||s.push(`${i}: ${Mf[e]} is ${a??"not available for this language \u2014 see docs/language-support.md"}`)}return s.sort()}function ds(t){let e=new Set;for(let n of Lf)for(let r of Q(t,n))e.add(r);return[...e].sort()}function hs(t){let e=new Map;for(let n of t.nodes.values())e.set(n.type,(e.get(n.type)??0)+1);return[...e.entries()].map(([n,r])=>({type:n,fileCount:r,exportsTracked:Qo.has(n),importSymbolsTracked:Yo.has(n),callEdgesTracked:Ft.has(n),fidelity:gs[n]})).sort((n,r)=>r.fileCount-n.fileCount)}var Lt=h(require("fs")),te=h(require("path"));var ys=h(require("fs")),Ae=h(require("path")),Dt=class{extensions=[".go"];goModCache=new Map;resolve(e,n,r,s){let{mod:i,replaces:o}=this.readGoMod(r);if(!i)return null;let a=this.applyReplace(n,o,r);if(a!==void 0)return ea(a);if(n!==i&&!n.startsWith(`${i}/`))return null;let c=n.slice(i.length).replace(/^\//,"");return c?ea(Ae.default.join(r,c)):null}readGoMod(e){let n=this.goModCache.get(e);if(n!==void 0)return n;let r={mod:null,replaces:new Map};try{let s=ys.default.readFileSync(Ae.default.join(e,"go.mod"),"utf-8"),i=_f(s,e);return this.goModCache.set(e,i),i}catch{return this.goModCache.set(e,r),r}}applyReplace(e,n,r){for(let[s,i]of n){if(e===s)return i;if(e.startsWith(`${s}/`)){let o=e.slice(s.length+1);return Ae.default.join(i,o)}}}};function _f(t,e){let n=t.split(`
|
|
12
|
+
`),r=null,s=new Map,i=!1;for(let o of n){let a=o.trim();if(a.startsWith("module ")){r=a.slice(7).trim();continue}if(/^replace\s*\(/.test(a)){i=!0;continue}if(i&&a===")"){i=!1;continue}if(i&&a.includes("=>")){qo(a,e,s);continue}!i&&/^replace\s+/.test(a)&&a.includes("=>")&&qo(a.replace(/^replace\s+/,""),e,s)}return{mod:r,replaces:s}}function qo(t,e,n){let[r,s]=t.split("=>").map(a=>a.trim());if(!r||!s)return;let i=r.split(/\s+/)[0];if(!s.startsWith(".")&&!s.startsWith("/"))return;let o=Ae.default.isAbsolute(s)?s:Ae.default.resolve(e,s);n.set(i,o)}function ea(t){let e;try{e=ys.default.readdirSync(t,{withFileTypes:!0})}catch{return null}let n=e.filter(r=>r.isFile()&&r.name.endsWith(".go")&&!r.name.endsWith("_test.go")).map(r=>({path:Ae.default.join(t,r.name),isExternal:!1})).sort((r,s)=>r.path.localeCompare(s.path));return n.length>0?n:null}var Pt=h(require("fs")),At=h(require("path"));var Gf=new Set([".java",".kt",".kts",".scala",".sc",".groovy"]),Of=12,ta=4096,jf=new Set(qr);function ra(t){let e=t.replace(/\\/g,"/"),n=e.match(/^(.*)\/src\/([^/]+)(?:\/|$)/);if(!n?.[1]||!n[2]){let i=e.lastIndexOf("/");return{module:i===-1?e:e.slice(0,i),rootSegment:"",sourceRoot:"unknown"}}let r=n[2],s=r==="main"?"main":jf.has(r)?r:"unknown";return{module:n[1],rootSegment:r,sourceRoot:s}}var Re=class{constructor(e=[]){this.extraIgnoreDirs=e}extraIgnoreDirs;extensions=[".java",".kt",".kts",".scala",".sc",".groovy",".gradle"];indexCache=new Map;resolve(e,n,r,s){let i=this.getIndex(r);if(i.size===0)return null;let o=n.endsWith(".*"),a=(o?n.slice(0,-2):n).split(".").filter(Boolean);if(a.length===0)return null;if(o){let c=i.get(a.join("."));if(!c)return null;let l=ra(e),p=c.filter(m=>m.module===l.module&&m.rootSegment===l.rootSegment),u=l.sourceRoot!=="main"&&l.sourceRoot!=="unknown",f=p.flatMap(m=>u?m.files:m.files.filter(d=>!es(na(d))));return xs(f)}for(let c=a.length-1;c>=1;c--){let l=$f(i,a.slice(0,c).join("."));if(!l)continue;let p=a[c],u=l.filter(f=>na(f)===p);if(u.length>0)return xs(u);if(c===a.length-1)return xs(l)}return null}getIndex(e){let n=this.indexCache.get(e);if(n)return n;let r=Wf(e,this.extraIgnoreDirs);return this.indexCache.set(e,r),r}};function Wf(t,e=[]){let n=new Map,r=(process.env.MOKOSH_IGNORE_DIRS??"").split(",").map(a=>a.trim()).filter(Boolean),s=new Set([...j,...r,...e]),i=(a,c)=>{let{module:l,rootSegment:p,sourceRoot:u}=ra(c),f=n.get(a);if(!f){n.set(a,[{module:l,rootSegment:p,sourceRoot:u,files:[c]}]);return}let m=f.find(d=>d.module===l&&d.rootSegment===p);m?m.files.push(c):f.push({module:l,rootSegment:p,sourceRoot:u,files:[c]})},o=(a,c)=>{if(c>Of)return;let l;try{l=Pt.default.readdirSync(a,{withFileTypes:!0})}catch{return}for(let p of l){let u=At.default.join(a,p.name);if(p.isDirectory()){!p.name.startsWith(".")&&!s.has(p.name)&&o(u,c+1);continue}if(!p.isFile())continue;let f=At.default.extname(p.name);if(!Gf.has(f))continue;let m=zf(u,f===".scala"||f===".sc");m&&i(m,u)}};o(t,0);for(let a of n.values())for(let c of a)c.files.sort();return n}function $f(t,e){let n=t.get(e);if(!(!n||n.length===0))return n.length===1?n[0]?.files:n.flatMap(r=>r.files).sort()}function zf(t,e){let n;try{let r=Pt.default.openSync(t,"r");try{let s=Buffer.alloc(ta),i=Pt.default.readSync(r,s,0,ta,0);n=s.toString("utf8",0,i)}finally{Pt.default.closeSync(r)}}catch{return null}return ee(n,e)}function xs(t){return!t||t.length===0?null:t.map(e=>({path:e,isExternal:!1}))}function na(t){return At.default.basename(t,At.default.extname(t))}var sa=h(require("fs")),xn=h(require("path")),Rt=class{extensions=[".lua"];resolve(e,n,r,s){let i=n.replace(/\./g,xn.default.sep),o=[r,xn.default.join(r,"lib")];for(let a of o){if(!sa.default.existsSync(a))continue;let c=s(xn.default.join(a,"_dummy.lua"),i);if(c)return[c]}return null}};var ia=h(require("path"));var Bf=new Set(j),Nt=class{extensions=[".md",".mdx"];resolve(e,n,r,s){let i=n.replace(/^\.\//,"").split("/")[0];if(i&&Bf.has(i))return null;let o=s(ia.default.join(r,"_dummy"),`./${n}`);return o?[o]:null}};var aa=h(require("fs")),bn=h(require("path")),Mt=class{extensions=[".py"];resolve(e,n,r,s){let i=n.replace(/\./g,bn.default.sep),o=bn.default.join(r,`${i}.py`);if(oa(o))return[{path:o,isExternal:!1}];let a=bn.default.join(r,i,"__init__.py");return oa(a)?[{path:a,isExternal:!1}]:null}};function oa(t){try{return aa.default.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}var bs=h(require("path")),Uf=["~","http://","https://","//","data:","sass:"],It=class{extensions=[".css",".scss",".sass",".less",".styl"];resolve(e,n,r,s){if(Uf.some(p=>n.startsWith(p)))return null;let i=s(e,n);if(i)return[i];let o=bs.default.dirname(n),a=bs.default.basename(n),c=o==="."?`_${a}`:`${o}/_${a}`,l=s(e,c);return l?[l]:null}};function kn(t={}){return[new Mt,new Rt,new Dt,t.jvm??new Re,new It,new Nt]}var ca=new Set;function Kf(t,e){let n=t.constructor?.name??"LangResolver";if(ca.has(n))return;ca.add(n);let r=e instanceof Error?e.message:String(e);process.stderr.write(`
|
|
13
|
+
Warning: ${n}.resolve() threw (${r}); affected imports are left unresolved.
|
|
14
|
+
`)}var le=class{constructor(e,n={}){this.rootDir=e;this.workspaceMap=n.workspaceMap??new Map,this.tsconfigSearchPaths=n.tsconfigSearchPaths??[e],this.pathAliases=n.pathAliases,this.langResolvers=n.langResolvers??kn()}rootDir;workspaceMap;tsconfigSearchPaths;pathAliases;langResolvers;resolutionCache=new Map;langBucketFor(e){for(let n=0;n<this.langResolvers.length;n++)if(this.langResolvers[n]?.extensions.some(r=>e.endsWith(r)))return String(n);return"none"}cacheKey(e,n){return`${te.default.dirname(e)}\0${this.langBucketFor(e)}\0${n}`}resolveAll(e,n){let r=this.cacheKey(e,n),s=this.resolutionCache.get(r);if(s!==void 0)return s??[];let i=this.resolveAllUncached(e,n);return this.resolutionCache.set(r,i.length>0?i:null),i}resolveAllUncached(e,n){let r=this.resolvePathAlias(n);if(r)return[r];if(n.startsWith(".")||n.startsWith("/")){let o=this.resolveLocalPath(e,n);return o?[o]:[]}let s=(o,a)=>this.resolveLocalPath(o,a);for(let o of this.langResolvers)if(o.extensions.some(a=>e.endsWith(a))){let a=null;try{a=o.resolve(e,n,this.rootDir,s)}catch(c){Kf(o,c)}if(a)return a}let i=this.resolveWorkspaceImport(n);return i?[i]:[{path:n,isExternal:!0}]}resolve(e,n){return this.resolveAll(e,n)[0]??null}resolveLocalPath(e,n){let r=te.default.dirname(e),s=n.startsWith("/")?n:te.default.resolve(r,n),i=!s.startsWith(this.rootDir),o=["",".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".feature",".md",".mdx"],a=s.match(/\.(js|mjs|cjs)$/);if(a){let c=s.slice(0,-a[0].length);for(let l of[".ts",".tsx"]){let p=this.tryExtensions(c,l,i);if(p)return p}}for(let c of o){let l=this.tryExtensions(s,c,i);if(l)return l}return i?{path:s,isExternal:!0}:null}tryExtensions(e,n,r){let s=e+n;if(this.isFile(s))return{path:s,isExternal:r};let i=te.default.join(e,`index${n}`);if(this.isFile(i))return{path:i,isExternal:r};if(n===".py"){let o=te.default.join(e,"__init__.py");if(this.isFile(o))return{path:o,isExternal:r}}return null}isFile(e){try{return Lt.default.statSync(e,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}resolvePathAlias(e){if(this.pathAliases)for(let n in this.pathAliases){let r=this.matchAliasPattern(n,e),s=this.pathAliases[n];if(r&&s){let i=this.tryAliasSubstitutions(s,r[1]||"");if(i)return i}}for(let n of this.tsconfigSearchPaths){let r=te.default.join(n,"tsconfig.json");if(Lt.default.existsSync(r))try{let i=JSON.parse(Lt.default.readFileSync(r,"utf-8")).compilerOptions?.paths;if(!i)continue;for(let o in i){let a=this.matchAliasPattern(o,e);if(a){let c=this.tryAliasSubstitutions(i[o],a[1]||"",n);if(c)return c}}}catch{}}return null}aliasRegexCache=new Map;matchAliasPattern(e,n){let r=this.aliasRegexCache.get(e);if(!r){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\*","(.*)");r=new RegExp(`^${s}$`),this.aliasRegexCache.set(e,r)}return n.match(r)}tryAliasSubstitutions(e,n,r=this.rootDir){let s=["",".ts",".tsx",".js",".jsx",".coffee",".ls",".lua",".feature"];for(let i of e){let o=i.replace("*",n),a=te.default.resolve(r,o);for(let c of s){let l=this.tryExtensions(a,c,!1);if(l)return l}}return null}resolveWorkspaceImport(e){if(this.workspaceMap.size===0)return null;for(let[n,r]of this.workspaceMap){if(e!==n&&!e.startsWith(`${n}/`))continue;let s=e.slice(n.length),i={path:"",isExternal:!1,isWorkspace:!0,workspacePackage:n};if(!s){for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"]){let c=te.default.join(r,a);try{if(Lt.default.statSync(c,{throwIfNoEntry:!1})?.isFile())return{...i,path:c}}catch{}}return{...i,path:r}}let o=this.resolveLocalPath(te.default.join(r,"_dummy"),s.slice(1));return o?{...i,path:o.path}:null}return null}};var Hf=["tests","test","__tests__","specs","spec"],Jf=["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage",".pytest_cache","__pycache__"],Vf=600;function Qf(){return(process.env.MOKOSH_IGNORE_DIRS??"").split(",").map(t=>t.trim()).filter(Boolean)}function Yf(t,e){if(t.length===0)return e;let n=t.map(o=>L.default.dirname(o).split(L.default.sep)),r=n[0]??[];for(let o of n.slice(1)){let a=0;for(;a<r.length&&a<o.length&&r[a]===o[a];)a++;r=r.slice(0,a)}let s=r.join(L.default.sep)||L.default.sep,i=L.default.relative(e,s);return i.startsWith("..")||L.default.isAbsolute(i)?e:s}var Ne=class{constructor(e,n=null,r,s,i=!1,o=new Map,a=!0,c=[],l=null){this.rootDir=e;this.enableGitStats=i;this.coverageMap=o;this.parallelParsing=a;this.docFiles=l;this.previousGraph=n,this.walkIgnoreDirs=new Set([...Jf,...c,...Qf()]),this.resolver=r||new le(e),this.lockFile=Qi(e),s&&(this.progressCallback=s)}rootDir;enableGitStats;coverageMap;parallelParsing;docFiles;graph={nodes:new Map};visited=new Set;queue=[];previousGraph=null;resolver;lockFile=null;progressCallback;pool=null;gitStatsMap=null;walkIgnoreDirs;async build(e){let n=e.map(r=>L.default.isAbsolute(r)?r:L.default.resolve(this.rootDir,r));await this.initPool(),this.enableGitStats&&(this.gitStatsMap=zi(this.rootDir));try{for(let r of n)this.enqueue(r);return await this.drain(),await this.processTestFiles(Yf(n,this.rootDir)),await this.processDocFiles(),this.progressCallback&&this.visited.size>=100&&process.stderr.write(`
|
|
13
15
|
Done. Total processed: ${this.visited.size} nodes.
|
|
14
|
-
`),
|
|
16
|
+
`),Jo(this.graph.nodes,this.coverageMap),new A(this.graph.nodes)}finally{this.pool&&(await this.pool.destroy(),this.pool=null)}}async initPool(){if(this.parallelParsing===!1)return;let e=typeof this.parallelParsing=="object"?this.parallelParsing:{},n=e.minFiles??Vf;if(!(n>0&&!this.hasAtLeastFiles(this.rootDir,n))){e.maxThreads!==void 0&&e.maxThreads<1&&process.stderr.write(`
|
|
15
17
|
Warning: parallelParsing.maxThreads (${e.maxThreads}) must be at least 1; using 1.
|
|
16
|
-
`);try{let
|
|
17
|
-
Warning: failed to start parse worker pool, falling back to synchronous parsing: ${
|
|
18
|
-
`),this.pool=null}}}hasAtLeastFiles(e,
|
|
19
|
-
Warning: failed to parse ${
|
|
20
|
-
`),null}}parseContent(e,r){return this.pool?this.pool.run({filePath:e,content:r}):ro(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:F.default.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:m,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}:{},...m!==void 0?{cognitiveComplexity:m}:{},...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||s.type==="side-effect"&&s.rawSpecifier.endsWith(".*")&&o.every(a=>a.isExternal)))for(let a of o){if(!a.isExternal&&a.path===e)continue;let c={...s,toPath:a.isExternal?a.path:F.default.relative(this.rootDir,a.path),isExternal:a.isExternal};a.isWorkspace&&(c.isWorkspace=!0,c.workspacePackage=a.workspacePackage),a.isExternal?this.attachLockfileVersion(c):this.enqueue(a.path),n.push(c)}}return n}attachLockfileVersion(e){if(!this.lockFile)return;let r=this.lockFile.jvmDependencies;if(r&&io.has(G(e.fromPath))){let o=e.rawSpecifier.replace(/\.\*$/,""),i="";for(let a of Object.keys(r))(o===a||o.startsWith(`${a}.`))&&a.length>i.length&&(i=a);i&&(e.version=r[i]?.version);return}let n=e.rawSpecifier.startsWith("@")?e.rawSpecifier.split("/").slice(0,2).join("/"):e.rawSpecifier.split("/")[0],s=n?this.lockFile.dependencies[n]:void 0;s&&(e.version=s.version)}showProgress(){this.progressCallback&&this.visited.size%100===0&&this.progressCallback(this.visited.size)}};var Yr=require("fs/promises"),ke=g(require("path")),Ao=g(require("piscina"));var ap=new Set(["css","scss","less","stylus"]);function xo(t){return ap.has(t)?"style":"code"}function cp(t){return t.trim().replace(/\s+/g," ")}function lp(t){try{return t.fileType==="scss"?vt(t.source,t.file).root:t.fileType==="less"?St(t.source,t.file).root:t.fileType==="css"?bt(t.source,t.file).root:void 0}catch{return}}function pp(t){let e=lp(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()}:${cp(p.value)}`).join(";");r.push({file:t.file,startLine:a,endLine:c,lines:c-a+1,signature:l,declCount:s.length})}),r}function bo(t,e,r=2){let n=new Map;for(let o of t)for(let i of pp(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 So(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 up=new Set(["{","}",":",",","[","]"]);function vo(t,e,r){let n=0;for(let s=e;s<e+r;s++)up.has(t[s].text)&&n++;return n/r}function ko(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 Co(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 wo(t,e,r,n=.5){let s=[],o=[],i=new Map;for(let{file:u,tokens:m}of t)if(m.length!==0){i.set(u,m);for(let h=0;h<m.length;h++)s.push(m[h].text),o.push({file:u,localIndex:h});s.push(` ${u}`),o.push({file:u,localIndex:-1})}if(s.length===0)return[];let a=ko(s),c=Co(s,a),l=So(c),p=[];for(let u of l){let m=fp(u,a,o,i,e,r,n);m&&p.push(m)}return p.sort((u,m)=>m.lines-u.lines)}function fp(t,e,r,n,s,o,i){if(t.lcpLength<s)return;let a=[];for(let h=t.low;h<=t.high;h++){let y=r[e[h]];y.localIndex!==-1&&a.push(y)}if(a.length<2||!mp(a,n))return;let c=gp(a,t.lcpLength);if(c.length<2)return;let l=c[0],p=n.get(l.file);if(vo(p,l.localIndex,t.lcpLength)>i)return;let u=c.map(({file:h,localIndex:y})=>{let v=n.get(h);return{file:h,startLine:v[y].line,endLine:v[y+t.lcpLength-1].line}}),m=Math.min(...u.map(h=>h.endLine-h.startLine+1));if(!(m<o))return{occurrences:u,lines:m,tokens:t.lcpLength}}function mp(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 gp(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 dp={typescript:{line:["//"],block:[["/*","*/"]]},javascript:{line:["//"],block:[["/*","*/"]]},go:{line:["//"],block:[["/*","*/"]]},java:{line:["//"],block:[["/*","*/"]]},kotlin:{line:["//"],block:[["/*","*/"]]},scala:{line:["//"],block:[["/*","*/"]]},groovy:{line:["//"],block:[["/*","*/"]]},css:{block:[["/*","*/"]]},scss:{line:["//"],block:[["/*","*/"]]},less:{line:["//"],block:[["/*","*/"]]},stylus:{line:["//"],block:[["/*","*/"]]},python:{line:["#"]},gherkin:{line:["#"]},coffeescript:{line:["#"],block:[["###","###"]]},livescript:{line:["#"],block:[["###","###"]]},lua:{line:["--"],block:[["--[[","]]"]]},markdown:{block:[["<!--","-->"]]}};function Eo(t,e,r){let n=t.slice(e,r).replace(/[^\n]/g," ");return t.slice(0,e)+n+t.slice(r)}function hp(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=Eo(r,i,c),o=c}}for(let n of e.line??[]){let s=0;for(;;){let o=r.indexOf(n,s);if(o===-1)break;let i=r.indexOf(`
|
|
21
|
-
`,
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
18
|
+
`);try{let r=L.default.join(__dirname,"parse-worker.js");this.pool=new la.default({filename:r,...e.maxThreads!==void 0?{maxThreads:Math.max(1,e.maxThreads)}:{}})}catch(r){process.stderr.write(`
|
|
19
|
+
Warning: failed to start parse worker pool, falling back to synchronous parsing: ${r}
|
|
20
|
+
`),this.pool=null}}}hasAtLeastFiles(e,n){let r=0,s=[e];for(;s.length>0;){let i=s.pop();if(i===void 0)continue;let o;try{o=qe.default.readdirSync(i,{withFileTypes:!0})}catch{continue}for(let a of o)if(a.isDirectory())this.walkIgnoreDirs.has(a.name)||s.push(L.default.join(i,a.name));else if(a.isFile()&&(r++,r>=n))return!0}return r>=n}async processTestFiles(e){let n=xt(),r=i=>n.some(o=>i.name.includes(o));this.walkProject(e,r);let s=e;for(;s!==this.rootDir;){let i=L.default.dirname(s);if(i===s)break;for(let o of Hf){let a=L.default.join(i,o);try{qe.default.statSync(a).isDirectory()&&this.walkProject(a,r)}catch{}}s=i}await this.drain()}async processDocFiles(){if(this.docFiles!==null){for(let e of this.docFiles)this.enqueue(e);await this.drain();return}this.walkProject(this.rootDir,e=>e.name.endsWith(".md")||e.name.endsWith(".mdx")),await this.drain()}walkProject(e,n){let r;try{r=qe.default.readdirSync(e,{withFileTypes:!0})}catch{return}for(let s of r){let i=L.default.join(e,s.name);s.isDirectory()?this.walkIgnoreDirs.has(s.name)||this.walkProject(i,n):s.isFile()&&n(s)&&this.enqueue(i)}}enqueue(e){this.visited.has(e)||(this.visited.add(e),this.showProgress(),this.queue.push(e))}async drain(){for(;this.queue.length>0;){let e=this.queue;this.queue=[],await Promise.all(e.map(n=>this.finishFile(n)))}}async finishFile(e){let n=qe.default.statSync(e,{throwIfNoEntry:!1});if(!n?.isFile())return;let r=L.default.relative(this.rootDir,e),s=await this.getNode(e,r,n);s.imports=await this.resolveImports(e,s.imports),Ko(s.imports,s.tags),this.graph.nodes.set(s.path,s)}async getNode(e,n,r){let s=this.previousGraph?.nodes.get(n);if(s&&s.mtime===r.mtimeMs&&s.size===r.size)return{...s};let i=await this.tryParse(e,n);if(!i)return this.makeStubNode(e,n,r);let o=this.resolveCallEdges(e,i.rawCallEdges),a=this.buildNode(e,n,r,i,o);return this.attachGitStats(a,n),a}async tryParse(e,n){let r=qe.default.readFileSync(e,"utf-8");try{return await this.parseContent(e,r)}catch(s){return process.stderr.write(`
|
|
21
|
+
Warning: failed to parse ${n}: ${s}
|
|
22
|
+
`),null}}parseContent(e,n){return this.pool?this.pool.run({filePath:e,content:n}):Bo(e,n)}makeStubNode(e,n,r){return{path:n,type:V(e),category:"other",imports:[],exports:[],tags:[],mtime:r.mtimeMs,size:r.size}}resolveCallEdges(e,n){let r=[];for(let s of n??[])try{let i=this.resolver.resolve(e,s.toSpecifier);i&&!i.isExternal&&r.push({from:s.from,to:s.to,toFile:L.default.relative(this.rootDir,i.path)})}catch{}return r}buildNode(e,n,r,s,i){let{imports:o,exports:a,tags:c,category:l,description:p,complexity:u,cognitiveComplexity:f,functions:m}=s;return{path:n,type:V(e),category:l,imports:o,exports:a,tags:c,mtime:r.mtimeMs,size:r.size,...p!==void 0?{description:p}:{},...i.length>0?{callEdges:i}:{},...u!==void 0?{complexity:u}:{},...f!==void 0?{cognitiveComplexity:f}:{},...m!==void 0?{functions:m}:{}}}attachGitStats(e,n){let r=this.gitStatsMap?.get(n);r&&(e.commitCount90d=r.commitCount90d,r.lastAuthor!==void 0&&(e.lastAuthor=r.lastAuthor),r.lastCommitAt!==void 0&&(e.lastCommitAt=r.lastCommitAt))}async resolveImports(e,n){let r=[];for(let s of n){let i=this.resolver.resolveAll(e,s.rawSpecifier);if(!(i.length===0||s.type==="side-effect"&&s.rawSpecifier.endsWith(".*")&&i.every(a=>a.isExternal)))for(let a of i){if(!a.isExternal&&a.path===e)continue;let c={...s,toPath:a.isExternal?a.path:L.default.relative(this.rootDir,a.path),isExternal:a.isExternal};a.isWorkspace&&(c.isWorkspace=!0,c.workspacePackage=a.workspacePackage),a.isExternal?this.attachLockfileVersion(c):this.enqueue(a.path),r.push(c)}}return r}attachLockfileVersion(e){if(!this.lockFile)return;let n=this.lockFile.jvmDependencies;if(n&&Vo.has(V(e.fromPath))){let i=e.rawSpecifier.replace(/\.\*$/,""),o="";for(let a of Object.keys(n))(i===a||i.startsWith(`${a}.`))&&a.length>o.length&&(o=a);o&&(e.version=n[o]?.version);return}let r=e.rawSpecifier.startsWith("@")?e.rawSpecifier.split("/").slice(0,2).join("/"):e.rawSpecifier.split("/")[0],s=r?this.lockFile.dependencies[r]:void 0;s&&(e.version=s.version)}showProgress(){this.progressCallback&&this.visited.size%100===0&&this.progressCallback(this.visited.size)}};var Mn=require("fs/promises"),Me=h(require("path")),$a=h(require("piscina"));function ks(t,e){return t.startsWith("!")?e!==t.slice(1):e===t}function pa(t){return t.score??t.lines}function Sn(t,e){let n=t.occurrences.map(s=>s.file);if(e.path!==void 0){let s=e.path,i=o=>o.includes(s.startsWith("!")?s.slice(1):s);if(s.startsWith("!")?n.some(i):!n.some(i))return!1}if(e.allPaths!==void 0){let s=e.allPaths,i=s.startsWith("!")?s.slice(1):s,o=n.length>0&&n.every(a=>a.includes(i));if(s.startsWith("!")?o:!o)return!1}if(e.family!==void 0&&!ks(e.family,t.family))return!1;if(e.type!==void 0){let s=e.type.startsWith("!")?e.type.slice(1):e.type,i=n.length>0&&n.every(o=>V(o)===s);if(e.type.startsWith("!")?i:!i)return!1}if(e.kind!==void 0&&!ks(e.kind,t.kind??"block")||e.defKind!==void 0&&!ks(e.defKind,t.defKind)||e.minLines!==void 0&&t.lines<e.minLines||e.maxLines!==void 0&&t.lines>e.maxLines)return!1;let r=pa(t);if(e.minScore!==void 0&&r<e.minScore||e.maxScore!==void 0&&r>e.maxScore||e.minOccurrences!==void 0&&t.occurrences.length<e.minOccurrences||e.crossFile!==void 0&&new Set(n).size>=2!==e.crossFile)return!1;if(e.signals!==void 0&&e.signals.length>0){let s=new Set(t.signals??[]),i=e.signals.filter(a=>!a.startsWith("!"));if(e.signals.filter(a=>a.startsWith("!")).map(a=>a.slice(1)).some(a=>s.has(a))||i.length>0&&!i.some(a=>s.has(a)))return!1}return!0}function vn(t,e){let n=t;if(e.sort){let r=e.sortDir==="asc"?-1:1,s=e.sort==="score"?pa:e.sort==="occurrences"?i=>i.occurrences.length:i=>i.lines;n=[...n].sort((i,o)=>(s(o)-s(i))*r)}return e.limit!==void 0&&(n=n.slice(0,Math.max(0,e.limit))),n}var ma={path:{field:"path",kind:"string"},allpaths:{field:"allPaths",kind:"string"},family:{field:"family",kind:"string"},type:{field:"type",kind:"string"},kind:{field:"kind",kind:"string"},defkind:{field:"defKind",kind:"string"},minlines:{field:"minLines",kind:"int"},maxlines:{field:"maxLines",kind:"int"},minscore:{field:"minScore",kind:"int"},maxscore:{field:"maxScore",kind:"int"},minoccurrences:{field:"minOccurrences",kind:"int"},crossfile:{field:"crossFile",kind:"bool"},limit:{field:"limit",kind:"int"}},ua=new Set(["lines","score","occurrences"]),fa=new Set([...Object.keys(ma),"signal","signals","sort","sortdir"]);function Xf(t,e,n,r,s){let i=t;if(n==="string"){i[e]=s;return}if(n==="bool"){i[e]=s.toLowerCase()==="true";return}let o=Number(s);if(!Number.isFinite(o))throw new Error(`find_duplicates filter: "${r}" expects a number, got "${s}"`);i[e]=o}function Zf(t,e){let n=e.indexOf(":");if(n===-1)throw new Error(`find_duplicates filter: clause "${e}" is not "key:value"`);let r=e.slice(0,n).trim().toLowerCase(),s=e.slice(n+1).trim();if(!r||!s)return;if(!fa.has(r))throw new Error(`find_duplicates filter: unknown key "${r}". Known keys: ${[...fa].sort().join(", ")}`);if(r==="signal"||r==="signals"){t.signals=[...t.signals??[],s];return}if(r==="sort"){if(!ua.has(s))throw new Error(`find_duplicates filter: sort must be one of ${[...ua].join(", ")}, got "${s}"`);t.sort=s;return}if(r==="sortdir"){t.sortDir=s.toLowerCase()==="asc"?"asc":"desc";return}let i=ma[r];i&&Xf(t,i.field,i.kind,r,s)}function et(t){let e={};for(let n of t.split(",")){let r=n.trim();r&&Zf(e,r)}return e}function qf(t){let e=[...t].sort((r,s)=>r.start-s.start),n=[];for(let r of e){let s=n.at(-1);s&&r.start<=s.end+1?s.end=Math.max(s.end,r.end):n.push({...r})}return n}function em(t,e,n){let r=e.flatMap(a=>a.occurrences).filter(a=>a.file===t).map(a=>({start:a.startLine,end:a.endLine})),s=qf(r).reduce((a,c)=>a+(c.end-c.start+1),0),i=n?.get(t),o=i!==void 0&&i>0?Math.round(s/i*1e3)/10:void 0;return{file:t,coveredLines:s,totalLines:i,coveragePct:o}}function ga(t,e){let n=new Map;for(let s of t){let i=[...new Set(s.occurrences.map(c=>c.file))].sort(),o=i.join("\0"),a=n.get(o);a?a.groups.push(s):n.set(o,{files:i,groups:[s]})}let r=[];for(let{files:s,groups:i}of n.values()){let o=Math.max(...i.map(a=>a.lines));r.push({files:s,groups:[...i].sort((a,c)=>c.lines-a.lines),matchCount:i.length,longestMatch:o,coverage:s.map(a=>em(a,i,e))})}return r.sort((s,i)=>i.longestMatch-s.longestMatch||i.matchCount-s.matchCount)}var tm={css:"style",scss:"style",less:"style",stylus:"style",javascript:"js",typescript:"js",coffeescript:"js",livescript:"js",java:"jvm",kotlin:"jvm",scala:"jvm",groovy:"jvm",python:"python",go:"go",lua:"lua",markdown:"markdown",gherkin:"gherkin"};function da(t){return tm[t]??"other"}var Ss=h(require("path")),nm=new Set(["generated","__generated__","__generated","gen","__snapshots__"]),rm=[".pb.go",".pb.ts",".pb.js","_pb2.py","_pb2.pyi","_pb.dart",".g.dart",".generated.ts",".generated.tsx",".generated.js",".generated.jsx","_generated.go",".gen.go",".gen.ts",".snap"],sm=["@generated","do not edit","code generated by","autogenerated","auto-generated","this file was automatically generated","this is a generated file","jest snapshot v1"],im=500;function om(t,e){let n=t.split(/[\\/]/),r=/^\*\*\/(.+?)\/\*\*$/.exec(e);return r?n.includes(r[1]):e.startsWith("*.")?Ss.default.basename(t).endsWith(e.slice(1)):n.includes(e)}function Cn(t,e=[]){if(t.split(/[\\/]/).some(s=>nm.has(s)))return!0;let r=Ss.default.basename(t);return rm.some(s=>r.endsWith(s))?!0:e.some(s=>om(t,s))}function _t(t){let e=t.slice(0,im).toLowerCase();return sm.some(n=>e.includes(n))}var T=h(require("typescript"));function ha(t,e,n){let r=t.tagName.getText(e),s=[];for(let i of t.attributes.properties){if(T.default.isJsxSpreadAttribute(i))return;let o=i.name.getText(e);if(!i.initializer)s.push(o);else if(T.default.isStringLiteral(i.initializer))s.push(`${o}=${i.initializer.text}`);else if(T.default.isJsxExpression(i.initializer))if(!i.initializer.expression)s.push(`${o}={}`);else{let a=n.printNode(T.default.EmitHint.Unspecified,i.initializer.expression,e);s.push(`${o}=${a}`)}else return}return s.sort(),s.length>0?`${r} ${s.join(" ")}`:r}function am(t,e,n){if(T.default.isJsxText(t)){let r=t.text.trim().replace(/\s+/g," ");return r.length===0?"":`T:${r}`}if(T.default.isJsxExpression(t))return t.expression?`E:${n.printNode(T.default.EmitHint.Unspecified,t.expression,e)}`:"";if(T.default.isJsxElement(t)||T.default.isJsxSelfClosingElement(t)||T.default.isJsxFragment(t))return ya(t,e,n)}function ya(t,e,n){if(T.default.isJsxSelfClosingElement(t)){let i=ha(t,e,n);return i===void 0?void 0:`<${i}/>`}let r=[];for(let i of t.children){let o=am(i,e,n);if(o===void 0)return;r.push(o)}if(T.default.isJsxFragment(t))return`<>${r.join("")}</>`;let s=ha(t.openingElement,e,n);return s===void 0?void 0:`<${s}>${r.join("")}</>`}function cm(t,e){let n=T.default.createSourceFile(t.file,t.source,T.default.ScriptTarget.Latest,!0,T.default.ScriptKind.TSX),r=T.default.createPrinter({removeComments:!0}),s=[],i=a=>n.getLineAndCharacterOfPosition(a).line+1,o=a=>{if(T.default.isJsxElement(a)||T.default.isJsxSelfClosingElement(a)||T.default.isJsxFragment(a)){let c=ya(a,n,r);c!==void 0&&c.length>=e&&s.push({file:t.file,startLine:i(a.getStart(n)),endLine:i(a.getEnd()),canonicalShape:c})}T.default.forEachChild(a,o)};return o(n),s}function lm(t){let e=[...t].sort((s,i)=>i[0].canonicalShape.length-s[0].canonicalShape.length),n=new Map,r=[];for(let s of e){let i=s.filter(o=>!n.get(o.file)?.some(c=>c.start<=o.startLine&&o.endLine<=c.end));if(!(i.length<2)){for(let o of i){let a={start:o.startLine,end:o.endLine},c=n.get(o.file);c?c.push(a):n.set(o.file,[a])}r.push(i)}}return r}function xa(t,e=40){let n=new Map;for(let i of t)for(let o of cm(i,e)){let a=n.get(o.canonicalShape);a?a.push(o):n.set(o.canonicalShape,[o])}let r=[...n.values()].filter(i=>i.length>=2),s=[];for(let i of lm(r)){let o=i[0],a=i.map(c=>({file:c.file,startLine:c.startLine,endLine:c.endLine}));s.push({occurrences:a,lines:Math.max(...i.map(c=>c.endLine-c.startLine+1)),tokens:o.canonicalShape.length,kind:"definition",defKind:"jsxElement"})}return s}var N=h(require("typescript"));function pm(t){let e=t;for(;N.default.isAsExpression(e)||N.default.isSatisfiesExpression(e)||N.default.isParenthesizedExpression(e);)e=e.expression;return e}function um(t,e,n){if(N.default.isPropertyAssignment(n)){if(N.default.isComputedPropertyName(n.name))return;let r=n.name.getText(e),s=t.printNode(N.default.EmitHint.Unspecified,n.initializer,e);return`${r}:${s}`}if(N.default.isShorthandPropertyAssignment(n)){let r=n.name.getText(e);return`${r}:${r}`}}function fm(t){let e=t.filter(n=>n!==void 0);if(!(e.length<2||e.length!==t.length))return[...e].sort().join(";")}function mm(t){let e=N.default.createSourceFile(t.file,t.source,N.default.ScriptTarget.Latest,!0,N.default.ScriptKind.TSX),n=N.default.createPrinter({removeComments:!0}),r=[],s=o=>e.getLineAndCharacterOfPosition(o).line+1,i=o=>{if(N.default.isVariableDeclaration(o)&&N.default.isIdentifier(o.name)&&o.initializer&&N.default.isVariableDeclarationList(o.parent)&&(o.parent.flags&N.default.NodeFlags.Const)!==0){let a=pm(o.initializer);if(N.default.isObjectLiteralExpression(a)){let c=fm(a.properties.map(l=>um(n,e,l)));c!==void 0&&r.push({file:t.file,name:o.name.text,startLine:s(o.getStart(e)),endLine:s(o.getEnd()),memberCount:a.properties.length,canonicalShape:c})}}N.default.forEachChild(o,i)};return i(e),r}function ba(t,e=3){let n=new Map;for(let s of t)for(let i of mm(s)){if(i.memberCount<e)continue;let o=n.get(i.canonicalShape);o?o.push(i):n.set(i.canonicalShape,[i])}let r=[];for(let s of n.values()){if(s.length<2)continue;let i=s[0],o=s.map(a=>({file:a.file,startLine:a.startLine,endLine:a.endLine,name:a.name}));r.push({occurrences:o,lines:Math.max(...s.map(a=>a.endLine-a.startLine+1)),tokens:i.memberCount,kind:"definition",defKind:"objectLiteral"})}return r}function wn(t){return t.trim().replace(/\s+/g," ")}function vs(t){try{return t.fileType==="scss"?yn(t.source,t.file).root:t.fileType==="less"?hn(t.source,t.file).root:t.fileType==="css"?dn(t.source,t.file).root:void 0}catch{return}}function gm(t){let e=vs(t);if(!e)return[];let n=[];return e.walkRules(r=>{let s=r.nodes?.filter(p=>p.type==="decl")??[];if(s.length===0)return;let i=s[0],o=s[s.length-1],a=r.source?.start?.line??i?.source?.start?.line,c=o?.source?.end?.line??o?.source?.start?.line??a;if(a===void 0||c===void 0)return;let l=s.map(p=>`${p.prop.trim().toLowerCase()}:${wn(p.value)}`).join(";");n.push({file:t.file,startLine:a,endLine:c,lines:c-a+1,signature:l,declCount:s.length})}),n}function ka(t,e,n=2){let r=new Map;for(let i of t)for(let o of gm(i)){if(o.declCount<n||o.lines<e)continue;let a=r.get(o.signature);a?a.push(o):r.set(o.signature,[o])}let s=[];for(let i of r.values())for(let o=0;o<i.length;o++)for(let a=o+1;a<i.length;a++){let c=i[o],l=i[a];if(c.file===l.file&&c.startLine===l.startLine&&c.endLine===l.endLine)continue;let p={file:c.file,startLine:c.startLine,endLine:c.endLine},u={file:l.file,startLine:l.startLine,endLine:l.endLine};s.push({occurrences:[p,u],lines:Math.min(c.lines,l.lines),tokens:c.declCount,family:"style"})}return s.sort((i,o)=>o.lines-i.lines)}function dm(t){let e=vs(t);if(!e)return[];let n=[];return e.walkDecls(r=>{let s=r.prop.startsWith("--"),i=t.fileType==="scss"&&r.prop.startsWith("$");if(!s&&!i)return;let o=r.source?.start?.line;o!==void 0&&n.push({file:t.file,line:o,name:r.prop,value:wn(r.value)})}),t.fileType==="less"&&e.walkAtRules(r=>{let{value:s}=r;if(s===void 0)return;let i=r.source?.start?.line;i!==void 0&&n.push({file:t.file,line:i,name:`@${r.name}`,value:wn(s)})}),n}function Sa(t,e=2){let n=t.flatMap(dm),r=new Map,s=new Map;for(let a of n){let c=r.get(a.value);c?c.push(a):r.set(a.value,[a]);let l=s.get(a.name);l?l.push(a):s.set(a.name,[a])}let i=(a,c)=>({file:a.file,startLine:a.line,endLine:a.line,name:a.name,...c?{value:a.value}:{}}),o=[];for(let a of r.values())a.length<e||o.push({occurrences:a.map(c=>i(c,!1)),lines:1,tokens:1,kind:"definition",defKind:"cssVar"});for(let a of s.values())a.length<e||new Set(a.map(l=>l.value)).size<2||o.push({occurrences:a.map(l=>i(l,!0)),lines:1,tokens:1,kind:"definition",defKind:"cssVar",signals:["value-drift"]});return o}function va(t){let e=t.length,n=[],r=[{lcpLength:0,low:0}];for(let s=1;s<e;s++){let i=s-1;for(;t[s]<r[r.length-1].lcpLength;){let o=r.pop();n.push({lcpLength:o.lcpLength,low:o.low,high:s-1}),i=o.low}t[s]>r[r.length-1].lcpLength&&r.push({lcpLength:t[s],low:i})}for(;r.length>1;){let s=r.pop();n.push({lcpLength:s.lcpLength,low:s.low,high:e-1})}return n}var hm={typescript:{line:["//"],block:[["/*","*/"]]},javascript:{line:["//"],block:[["/*","*/"]]},go:{line:["//"],block:[["/*","*/"]]},java:{line:["//"],block:[["/*","*/"]]},kotlin:{line:["//"],block:[["/*","*/"]]},scala:{line:["//"],block:[["/*","*/"]]},groovy:{line:["//"],block:[["/*","*/"]]},css:{block:[["/*","*/"]]},scss:{line:["//"],block:[["/*","*/"]]},less:{line:["//"],block:[["/*","*/"]]},stylus:{line:["//"],block:[["/*","*/"]]},python:{line:["#"]},gherkin:{line:["#"]},coffeescript:{line:["#"],block:[["###","###"]]},livescript:{line:["#"],block:[["###","###"]]},lua:{line:["--"],block:[["--[[","]]"]]},markdown:{block:[["<!--","-->"]]}};function Ca(t,e,n){let r=t.slice(e,n).replace(/[^\n]/g," ");return t.slice(0,e)+r+t.slice(n)}function ym(t,e){if(!e)return t;let n=t;for(let[r,s]of e.block??[]){let i=0;for(;;){let o=n.indexOf(r,i);if(o===-1)break;let a=n.indexOf(s,o+r.length),c=a===-1?n.length:a+s.length;n=Ca(n,o,c),i=c}}for(let r of e.line??[]){let s=0;for(;;){let i=n.indexOf(r,s);if(i===-1)break;let o=n.indexOf(`
|
|
23
|
+
`,i),a=o===-1?n.length:o;n=Ca(n,i,a),s=a}}return n}var xm={typescript:[/^\s*import[\s{("*]/,/^\s*export\s.*\sfrom\s/],javascript:[/^\s*import[\s{("*]/,/^\s*export\s.*\sfrom\s/],python:[/^\s*import\s+\S/,/^\s*from\s+\S+\s+import[\s(]/],go:[/^\s*import\s+["(]/],java:[/^\s*import\s+/],kotlin:[/^\s*import\s+/],scala:[/^\s*import\s+/],groovy:[/^\s*import\s+/]};function bm(t,e){let n=xm[e];if(!n)return t;let r=t.split(`
|
|
24
|
+
`),s=e==="go",i=!1,o=!1;for(let a=0;a<r.length;a++){let c=r[a],l=()=>{r[a]=c.replace(/[^\r]/g," ")};if(i){l(),c.includes(")")&&(i=!1);continue}if(o){l(),(/}\s*from\s/.test(c)||c.includes("}"))&&(o=!1);continue}n.some(p=>p.test(c))&&(l(),s&&/^\s*import\s+\(/.test(c)&&!c.includes(")")?i=!0:(e==="typescript"||e==="javascript")&&/^\s*import\b/.test(c)&&c.includes("{")&&!c.includes("}")&&(o=!0))}return r.join(`
|
|
25
|
+
`)}var Ea=["===","!==","...","=>","==","!=","<=",">=","&&","||","::","->","..","+=","-=","*=","/="],Cs=new RegExp(`${Ea.map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|")}|[A-Za-z_$][A-Za-z0-9_$]*|\\d+(?:\\.\\d+)?|"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`|\\S`,"g"),km=/^[A-Za-z_$][A-Za-z0-9_$]*$/,wa=/^\d+(?:\.\d+)?$/,Sm=/^(".*"|'.*'|`.*`)$/s,Ta=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"]),vm=new Set(["+","-","*","%","&","|","!","^","~","?"]),Cm=new Set(Ea);function Fa(t){return t==="ID"||t==="NUM"||t==="STR"?!1:Ta.has(t)?!0:t.length===1?vm.has(t):Cm.has(t)}function Da(t,e,n=!0){let r=bm(ym(t,hm[e]),e),s=[],i=1,o=0;Cs.lastIndex=0;let a=Cs.exec(r);for(;a!==null;){for(let p=o;p<a.index;p++)r[p]===`
|
|
26
|
+
`&&i++;o=a.index;let c=a[0],l=c;km.test(c)&&!Ta.has(c)?l="ID":n&&(wa.test(c)||Sm.test(c))&&(l=wa.test(c)?"NUM":"STR"),s.push({text:l,line:i});for(let p=o;p<a.index+c.length;p++)r[p]===`
|
|
27
|
+
`&&i++;o=a.index+c.length,a=Cs.exec(r)}return s}var wm=new Set(["{","}",":",",","[","]"]);function Pa(t,e,n){let r=0;for(let s=e;s<e+n;s++)wm.has(t[s].text)&&r++;return r/n}function Aa(t,e,n){let r=0;for(let s=e;s<e+n;s++)Fa(t[s].text)&&r++;return r}function Ra(t){let e=t.length;if(e===0)return[];let n=Array.from({length:e},(i,o)=>o),r=new Array(e);{let i=[...new Set(t)].sort(),o=new Map(i.map((a,c)=>[a,c]));for(let a=0;a<e;a++)r[a]=o.get(t[a])}let s=new Array(e).fill(0);for(let i=1;i<e;i*=2){let o=a=>a+i<e?r[a+i]:-1;n.sort((a,c)=>{let l=r[a]-r[c];return l!==0?l:o(a)-o(c)}),s[n[0]]=0;for(let a=1;a<e;a++){let c=n[a-1],l=n[a],p=r[c]===r[l],u=o(c)===o(l);s[l]=s[c]+(p&&u?0:1)}if([r,s]=[s,r],r[n[e-1]]===e-1)break}return n}function Na(t,e){let n=t.length,r=new Array(n).fill(0);if(n===0)return r;let s=new Array(n);for(let o=0;o<n;o++)s[e[o]]=o;let i=0;for(let o=0;o<n;o++){let a=s[o];if(a>0){let c=e[a-1];for(;o+i<n&&c+i<n&&t[o+i]===t[c+i];)i++;r[a]=i,i>0&&i--}else i=0}return r}function Ma(t,e,n,r=.5){let s=[],i=[],o=new Map;for(let{file:f,tokens:m}of t)if(m.length!==0){o.set(f,m);for(let d=0;d<m.length;d++)s.push(m[d].text),i.push({file:f,localIndex:d});s.push(` ${f}`),i.push({file:f,localIndex:-1})}if(s.length===0)return[];let a=Ra(s),c=Na(s,a),l=va(c),p=[];for(let f of l){let m=Em(f,a,i,o,e,n,r);m&&p.push(m)}return Tm(p,o).sort((f,m)=>m.lines-f.lines)}function Em(t,e,n,r,s,i,o){if(t.lcpLength<s)return;let a=[];for(let f=t.low;f<=t.high;f++){let m=n[e[f]];m.localIndex!==-1&&a.push(m)}if(a.length<2||!Fm(a,r))return;let c=Dm(a,t.lcpLength);if(c.length<2)return;let l=c[0],p=r.get(l.file);if(!(Pa(p,l.localIndex,t.lcpLength)>o||Math.min(...c.map(({file:f,localIndex:m})=>{let d=r.get(f),b=d[m].line;return d[m+t.lcpLength-1].line-b+1}))<i))return{occurrences:c,lcpLength:t.lcpLength}}function Tm(t,e){let n=[...t].sort((i,o)=>o.lcpLength-i.lcpLength),r=new Map,s=[];for(let i of n){let o=i.occurrences.filter(({file:u,localIndex:f})=>{let m=f+i.lcpLength;return!r.get(u)?.some(b=>b.start<=f&&m<=b.end)});if(o.length<2)continue;for(let{file:u,localIndex:f}of o){let m={start:f,end:f+i.lcpLength},d=r.get(u);d?d.push(m):r.set(u,[m])}let a=o.map(({file:u,localIndex:f})=>{let m=e.get(u);return{file:u,startLine:m[f].line,endLine:m[f+i.lcpLength-1].line}}),c=Math.min(...a.map(u=>u.endLine-u.startLine+1)),l=o[0],p=Aa(e.get(l.file),l.localIndex,i.lcpLength);s.push({occurrences:a,lines:c,tokens:i.lcpLength,score:p})}return s}function Fm(t,e){let n=null;for(let{file:r,localIndex:s}of t){if(s===0)return!0;let o=e.get(r)[s-1].text;if(n===null)n=o;else if(n!==o)return!0}return!1}function Dm(t,e){let n=new Map;for(let{file:s,localIndex:i}of t){let o=n.get(s);o?o.push(i):n.set(s,[i])}let r=[];for(let[s,i]of n){i.sort((a,c)=>a-c);let o=Number.NEGATIVE_INFINITY;for(let a of i)a>=o&&(r.push({file:s,localIndex:a}),o=a+e)}return r}var Pm=/<\/?\s*(?:svg|path|g|circle|ellipse|rect|line|polygon|polyline|defs|use|symbol|mask|clipPath|linearGradient|radialGradient|stop|pattern|filter|fe[A-Z][A-Za-z]*|marker|foreignObject|tspan|textPath)\b/,Am=/\b(?:viewBox|xmlns(?::xlink)?|xlink:href|fill-rule|clip-rule|stroke-width|stroke-linecap|stroke-linejoin|stroke-dasharray|stroke-miterlimit|gradientUnits|gradientTransform|patternUnits|patternTransform|preserveAspectRatio|pathLength|d|points|cx|cy|rx|ry)\s*=/,Rm=/^\s*(?:<\/?[A-Za-z>]|\/?>\s*$|[A-Za-z_$][\w:.$-]*\s*=\s*["'{])/;function Ia(t,e,n,r=.6){let s=t.split(`
|
|
28
|
+
`).slice(Math.max(0,e-1),n),i=0,o=0,a=!1;for(let c of s){if(c.trim().length===0)continue;i++;let l=Pm.test(c)||Am.test(c);l&&(a=!0),(l||Rm.test(c))&&o++}return a&&i>0&&o/i>=r}var Y=h(require("typescript"));function Nm(t,e,n){if(!Y.default.isPropertySignature(n)||!n.type)return;let r=n.name.getText(e),s=n.questionToken?"?":"",i=t.printNode(Y.default.EmitHint.Unspecified,n.type,e);return`${r}${s}:${i}`}function Mm(t){let e=t.filter(n=>n!==void 0);if(!(e.length<2||e.length!==t.length))return[...e].sort().join(";")}function Im(t){let e=Y.default.createSourceFile(t.file,t.source,Y.default.ScriptTarget.Latest,!0,Y.default.ScriptKind.TSX),n=Y.default.createPrinter({removeComments:!0}),r=[],s=o=>e.getLineAndCharacterOfPosition(o).line+1,i=o=>{let a,c,l;if(Y.default.isInterfaceDeclaration(o)?(a=o.name.text,c="interface",l=o.members):Y.default.isTypeAliasDeclaration(o)&&Y.default.isTypeLiteralNode(o.type)&&(a=o.name.text,c="type",l=o.type.members),a&&c&&l){let p=Mm(l.map(u=>Nm(n,e,u)));p!==void 0&&r.push({file:t.file,name:a,defKind:c,startLine:s(o.getStart(e)),endLine:s(o.getEnd()),memberCount:l.length,canonicalShape:p})}Y.default.forEachChild(o,i)};return i(e),r}function La(t,e=2){let n=new Map;for(let s of t)for(let i of Im(s)){if(i.memberCount<e)continue;let o=n.get(i.canonicalShape);o?o.push(i):n.set(i.canonicalShape,[i])}let r=[];for(let s of n.values()){if(s.length<2)continue;let i=s[0],o=s.map(a=>({file:a.file,startLine:a.startLine,endLine:a.endLine,name:a.name}));r.push({occurrences:o,lines:Math.max(...s.map(a=>a.endLine-a.startLine+1)),tokens:i.memberCount,kind:"definition",defKind:i.defKind})}return r}var _a=h(require("crypto")),tt=h(require("fs")),Ga=h(require("path"));function En(t){let e=[];for(let r of t)e.push(`${r.path}\0${r.mtime}\0${r.size}`);e.sort();let n=_a.default.createHash("sha256");for(let r of e)n.update(`${r}
|
|
29
|
+
`);return n.digest("hex")}function Tn(t){return JSON.stringify({minLines:t.minLines,ignoreLiterals:t.ignoreLiterals,maxPunctuationRatio:t.maxPunctuationRatio,limit:t.limit,scope:t.scope??null,includeGenerated:t.includeGenerated,includeSameFile:t.includeSameFile,includeSvgMarkup:t.includeSvgMarkup,includeDocs:t.includeDocs,ignoreDirs:[...t.ignoreDirs].sort(),ignoreGlobs:[...t.ignoreGlobs].sort()})}function Lm(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.digest=="string"&&typeof e.paramsKey=="string"&&Array.isArray(e.groups)&&Array.isArray(e.clusters)}function Fn(t,e,n){try{if(!tt.default.existsSync(t))return null;let r=JSON.parse(tt.default.readFileSync(t,"utf-8"));return!Lm(r)||r.digest!==e||r.paramsKey!==n?null:{groups:r.groups,clusters:r.clusters}}catch{return null}}function Dn(t,e,n,r,s){try{let i=Ga.default.dirname(t);tt.default.existsSync(i)||tt.default.mkdirSync(i,{recursive:!0});let o={digest:e,paramsKey:n,groups:[...r],clusters:[...s]};tt.default.writeFileSync(t,JSON.stringify(o))}catch(i){process.stderr.write(`Warning: failed to persist duplication result cache: ${i}
|
|
30
|
+
`)}}function ws(t){let e=t.indexOf("/");return e===-1?".":t.slice(0,e)}function Oa(t){let e={};for(let n of t)e[n]=(e[n]??0)+1;return e}function ja(t){return[...Gt(t)].sort().join("|")}function Pn(t,e){let n=new Set;for(let r of e)if(!(r.matchCount<2))for(let s of r.groups)n.add(ja(s));return t.filter(r=>!n.has(ja(r)))}function An(t){let e={},n=[],r=0;for(let s of t){s.lines>r&&(r=s.lines);for(let i of s.signals??[])n.push(i);for(let i of new Set(s.occurrences.map(o=>ws(o.file))))e[i]=(e[i]??0)+1}return{matched:t.length,byFamily:Oa(t.map(s=>s.family??"other")),byTopDir:e,bySignal:Oa(n),largestLines:r}}function Gt(t){return t.occurrences.map(e=>`${e.file}:${e.startLine}-${e.endLine}`)}function Rn(t){let e=t.package;return{lines:t.lines,...t.score!==void 0&&{score:t.score},...t.family!==void 0&&{family:t.family},...t.kind!==void 0&&{kind:t.kind},...t.defKind!==void 0&&{defKind:t.defKind},...t.signals!==void 0&&{signals:t.signals},...e!==void 0&&{package:e},occurrences:Gt(t)}}function Nn(t){let e=t.package,n=t.groups[0];return{files:t.files,matchCount:t.matchCount,longestMatch:t.longestMatch,...n!==void 0&&{longestMatchAt:Gt(n)},coverage:t.coverage,...e!==void 0&&{package:e}}}var nt=h(require("fs")),Wa=h(require("path"));function _m(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.mtime=="number"&&typeof e.size=="number"&&typeof e.ignoreLiterals=="boolean"&&typeof e.generated=="boolean"&&Array.isArray(e.tokens)}function rt(t){try{if(!nt.default.existsSync(t))return new Map;let e=nt.default.readFileSync(t,"utf-8"),n=JSON.parse(e);if(!Array.isArray(n))return new Map;let r=n.filter(s=>Array.isArray(s)&&s.length===2&&typeof s[0]=="string"&&_m(s[1]));return new Map(r)}catch{return new Map}}function st(t,e){let n=Wa.default.dirname(e);nt.default.existsSync(n)||nt.default.mkdirSync(n,{recursive:!0}),nt.default.writeFileSync(e,JSON.stringify([...t.entries()]))}var Gm=20,Om=new Set(["css","scss","less"]),jm=/(?:^|\/)(?:__tests__|__mocks__|__snapshots__|tests?|e2e)\/|\.(?:test|spec)\.[^/]*$|\.snap$/,Wm=3,$m=6,zm=120;function Bm(t){return kt.includes(Me.default.basename(t))}function Um(t,e){if(e.length===0)return!1;let n=new Set(e);return t.split(Me.default.sep).some(r=>n.has(r))}function it(t,e,n){let r=[...t.signals??[]];return new Set(t.occurrences.map(s=>s.file)).size===1&&r.push("same-file"),t.occurrences.some(s=>e.has(s.file))&&r.push("generated"),t.occurrences.some(s=>jm.test(s.file))&&r.push("test"),t.family==="markdown"&&r.push("docs"),t.occurrences.length>0&&t.occurrences.every(s=>{let i=n.get(s.file);return i!==void 0&&Ia(i,s.startLine,s.endLine)})&&r.push("svg-markup"),r.length>0?{...t,signals:r}:t}function Km(t){return Math.max(0,...t.groups.map(n=>n.tokens))>=zm?!0:t.groups.length>=Wm&&t.files.length<=$m}function Hm(t,e){if(e==="all")return!0;let n=t.groups.some(r=>r.signals?.includes("test"));return e==="tests"?n&&Km(t):!n}async function ot(t,e,n={}){let{minLines:r=6,windowSize:s=15,ignoreLiterals:i=!0,maxPunctuationRatio:o=.5,limit:a=50,ignoreDirs:c=j,includeGenerated:l=!1,includeSameFile:p=!1,includeSvgMarkup:u=!1,includeDocs:f=!1,scope:m="src",minScore:d=0,ignoreGlobs:b=[],parallelTokenizing:k=!0,tokenCache:S,filter:w}=n,I=w?et(w):void 0,_=[...t.nodes.values()].filter(U=>U.type!=="unknown"&&!Bm(U.path)&&!Um(U.path,c)),Z=new Set,fe=new Map,ve=Jm(k,_.length);try{let U=[],oe=[],Ce=new Map;if(await Promise.all(_.map(async x=>{let F=Cn(x.path,b);if(F&&!l)return;if(Om.has(x.type)){let O;try{O=await(0,Mn.readFile)(Me.default.join(e,x.path),"utf8")}catch{return}let We=F||_t(O);if(We&&!l)return;We&&Z.add(x.path),fe.set(x.path,O.split(`
|
|
31
|
+
`).length),U.push({file:x.path,source:O,fileType:x.type});return}let H=S?.get(x.path),Jt=H&&H.mtime===x.mtime&&H.size===x.size&&H.ignoreLiterals===i,ge,q,J;if(Jt)ge=H.tokens,q=H.generated;else{let O;try{O=await(0,Mn.readFile)(Me.default.join(e,x.path),"utf8")}catch{return}if(q=F||_t(O),q&&!l)return;ge=ve?await ve.run({source:O,fileType:x.type,ignoreLiterals:i}):Da(O,x.type,i),S?.set(x.path,{mtime:x.mtime,size:x.size,ignoreLiterals:i,generated:q,tokens:ge}),J=O}if(q&&!l)return;if(q&&Z.add(x.path),fe.set(x.path,J!==void 0?J.split(`
|
|
32
|
+
`).length:ge.at(-1)?.line??0),x.type==="typescript"||x.type==="javascript"){if(J===void 0)try{J=await(0,Mn.readFile)(Me.default.join(e,x.path),"utf8")}catch{J=void 0}J!==void 0&&oe.push({file:x.path,source:J})}let D=da(x.type),G={file:x.path,tokens:ge},dt=Ce.get(D);dt?dt.push(G):Ce.set(D,[G])})),S){let x=new Set(_.map(F=>F.path));for(let F of S.keys())x.has(F)||S.delete(F)}let me=new Map(oe.map(x=>[x.file,x.source])),K=ka(U,r).map(x=>it(x,Z,me));for(let[x,F]of Ce)for(let H of Ma(F,s,r,o))K.push(it({...H,family:x},Z,me));for(let x of Sa(U))K.push(it({...x,family:"style"},Z,me));for(let x of La(oe))K.push(it({...x,family:"js"},Z,me));for(let x of ba(oe))K.push(it({...x,family:"js"},Z,me));for(let x of xa(oe))K.push(it({...x,family:"js"},Z,me));let mt=K.filter(x=>!(!p&&x.signals?.includes("same-file")||!u&&x.signals?.includes("svg-markup")||!f&&x.signals?.includes("docs")||d>0&&(x.kind??"block")==="block"&&(x.score??x.tokens)<d||I&&!Sn(x,I))),gt=ga(mt,fe).filter(x=>Hm(x,m)),gr=new Set(gt.flatMap(x=>x.groups)),$=x=>x.score??x.lines;return{groups:mt.filter(x=>gr.has(x)).sort((x,F)=>$(F)-$(x)||F.lines-x.lines).slice(0,a),clusters:gt.sort((x,F)=>Math.max(...F.groups.map($))-Math.max(...x.groups.map($))||F.longestMatch-x.longestMatch).slice(0,a)}}finally{ve&&await ve.destroy()}}function Jm(t,e){if(t===!1)return null;let n=typeof t=="object"?t:{},r=n.minFiles??Gm;if(e<r)return null;n.maxThreads!==void 0&&n.maxThreads<1&&process.stderr.write(`
|
|
33
|
+
Warning: parallelTokenizing.maxThreads (${n.maxThreads}) must be at least 1; using 1.
|
|
34
|
+
`);try{return new $a.default({filename:Me.default.join(__dirname,"duplication-worker.js"),...n.maxThreads!==void 0?{maxThreads:Math.max(1,n.maxThreads)}:{}})}catch(s){return process.stderr.write(`
|
|
26
35
|
Warning: failed to start duplicate-detection worker pool, falling back to synchronous tokenizing: ${s}
|
|
27
|
-
`),null}}var ee=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 Qe(t,e){let r=t.nodes.get(e);if(r)return{category:r.category,exports:r.exports.map(n=>n.name)}}function Zr(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 Ye(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 Xr(t,e,r={}){let{testsOnly:n=!1,changedSymbols:s}=r,o=s?new ee(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 en(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 we(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 tn(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 rn(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 te(t){return[...t.nodes.values()].some(e=>e.coveragePct!==void 0)}function No(t){return[...t.nodes.values()].some(e=>e.commitCount90d!==void 0)}function Ee(t,e={}){let{metric:r="cognitiveComplexity",minComplexity:n=10,maxCoveragePct:s=50,minChurn:o=0,limit:i=20}=e,a=No(t),c=[...t.nodes.values()].filter(l=>l.coveragePct!==void 0&&l.coveragePct<=s&&(!a||(l.commitCount90d??0)>=o)).flatMap(l=>(l.functions??[]).filter(p=>p[r]>=n).map(p=>({file:l.path,name:p.name,line:p.line,complexity:p.complexity,cognitiveComplexity:p.cognitiveComplexity,coveragePct:l.coveragePct,...l.commitCount90d!==void 0&&{commitCount90d:l.commitCount90d}}))).sort((l,p)=>p[r]-l[r]).slice(0,i);return{hotspots:c,count:c.length,churnDataAvailable:a}}var Ft=require("child_process"),Et=g(require("fs")),Do=g(require("os")),Ro=g(require("path"));function nn(t,e){try{return(0,Ft.execFileSync)("git",["rev-parse","--verify",`${e}^{commit}`],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error(`Could not resolve git ref "${e}" in ${t}`)}}async function Io(t,e,r){let n=Et.default.mkdtempSync(Ro.default.join(Do.default.tmpdir(),`mokosh-worktree-${e.slice(0,12)}-`));Et.default.rmdirSync(n);try{return(0,Ft.execFileSync)("git",["worktree","add","--detach",n,e],{cwd:t,stdio:["ignore","pipe","pipe"]}),await r(n)}finally{try{(0,Ft.execFileSync)("git",["worktree","remove","--force",n],{cwd:t,stdio:["ignore","pipe","pipe"]})}catch{Et.default.rmSync(n,{recursive:!0,force:!0})}}}async function zo(t,e,r,n={}){let s=nn(t,e),o=Yn(t,s);if(o)return{sha:s,graph:o};let i=await Io(t,s,async a=>{let c=n.pathAliases?new z(a,{pathAliases:n.pathAliases}):void 0;return new X(a,null,c,void 0,n.gitStats??!1,new Map,n.parallelParsing??!0,n.additionalIgnoreDirs??[]).build(r)});return Zn(t,s,i),{sha:s,graph:i}}var Mo=t=>Math.round(t*100)/100,Lo=t=>t.length>8?t.slice(0,8):t;function Tp(t,e){return`${t.file}:${t.line} ${t.name} (${t[e]})`}function Pp(t,e){return`${t.file}:${t.line} ${t.name} (${t[e]}, cov ${t.coveragePct}%)`}function Ap(t,e=4){let r=t.occurrences.slice(0,e).map(o=>`${o.file}:${o.startLine}-${o.endLine}`),n=t.occurrences.length-r.length,s=n>0?`, +${n} more`:"";return`${t.lines}L x${t.occurrences.length}: ${r.join(", ")}${s}`}var re=(t,e)=>`${t} ${e}${t===1?"":"s"}`;function Np(t,e){let{files:r,staleReferences:n,duplication:s,complexity:o,docDrift:i,coverage:a}=t,c=[],l=[r.added.length&&`${r.added.length} added`,r.changed.length&&`${r.changed.length} changed`,r.removed.length&&`${r.removed.length} removed`].filter(Boolean);c.push(l.length?`Files: ${l.join(", ")}`:"No file changes"),n.length>0&&c.push(`\u26A0 ${re(n.length,"stale reference")} \u2014 removed export still imported`);let p=o.newHotspots[0];return p?c.push(`+${re(o.newHotspots.length,"complexity hotspot")} (max ${e} ${p[e]} in ${p.file})`):o.resolvedHotspots.length>0&&c.push(`${re(o.resolvedHotspots.length,"complexity hotspot")} resolved`),s.newGroups.length>0?c.push(`+${re(s.newGroups.length,"duplication group")}`):s.resolvedGroups.length>0&&c.push(`${re(s.resolvedGroups.length,"duplication group")} resolved`),i.newlyStale.length>0&&c.push(`${re(i.newlyStale.length,"doc")} newly stale`),a&&a.newHotspots.length>0&&c.push(`+${re(a.newHotspots.length,"risk hotspot")}`),c}function Dp(t){let{staleReferences:e,duplication:r,complexity:n,docDrift:s,coverage:o}=t;return e.length>0||(o?.newHotspots.length??0)>0?"attention":n.newHotspots.length>0||r.newGroups.length>0||s.newlyStale.length>0?"review-worthy":"clean"}function sn(t,e={}){let r=e.metric??"cognitiveComplexity",n=e.maxItems??8,s=e.maxPathList??100,{files:o,staleReferences:i,duplication:a,complexity:c,docDrift:l,coverage:p}=t,u=Mo(c.head.avgCognitiveComplexity-c.base.avgCognitiveComplexity),m=o.added.length+o.changed.length+o.removed.length,h={base:`${t.base.ref}@${Lo(t.base.sha)}`,head:`${t.head.ref}@${Lo(t.head.sha)}`,verdict:Dp(t),headline:Np(t,r),files:{added:o.added.length,changed:o.changed.length,removed:o.removed.length,...m<=s?{paths:{added:o.added,changed:o.changed,removed:o.removed}}:{}}};return i.length>0&&(h.staleReferences=i),(c.newHotspots.length>0||c.resolvedHotspots.length>0)&&(h.complexity={avgDelta:u,newHotspots:c.newHotspots.slice(0,n).map(y=>Tp(y,r)),newHotspotCount:c.newHotspots.length,resolvedCount:c.resolvedHotspots.length}),(a.newGroups.length>0||a.resolvedGroups.length>0)&&(h.duplication={newGroups:a.newGroups.slice(0,n).map(y=>Ap(y)),newGroupCount:a.newGroups.length,resolvedCount:a.resolvedGroups.length,totalGroups:a.head.groups}),(l.newlyStale.length>0||l.resolved.length>0)&&(h.docDrift={newlyStale:l.newlyStale.slice(0,n).map(y=>y.replace("::"," \u2192 ")),newlyStaleCount:l.newlyStale.length,resolvedCount:l.resolved.length}),p&&(p.newHotspots.length>0||p.resolvedHotspots.length>0)&&(h.coverage={avgDelta:Mo(p.head.avgCoveragePct-p.base.avgCoveragePct),newHotspots:p.newHotspots.slice(0,n).map(y=>Pp(y,r)),newHotspotCount:p.newHotspots.length,resolvedCount:p.resolvedHotspots.length}),h}function Rp(t,e){let r=[],n=[];for(let[o,i]of e.nodes){let a=t.nodes.get(o);if(!a){r.push(o);continue}let c=JSON.stringify({category:a.category,exports:a.exports.map(p=>p.name).sort(),imports:a.imports.map(p=>p.toPath).sort()}),l=JSON.stringify({category:i.category,exports:i.exports.map(p=>p.name).sort(),imports:i.imports.map(p=>p.toPath).sort()});c!==l&&n.push(o)}let s=[...t.nodes.keys()].filter(o=>!e.nodes.has(o));return{added:r,removed:s,changed:n}}function Ip(t,e){let r=[];for(let[n,s]of t.nodes){let o=e.nodes.get(n);if(!o)continue;let i=new Set(o.exports.map(c=>c.name)),a=s.exports.map(c=>c.name).filter(c=>!i.has(c));if(a.length!==0)for(let c of a){let l=[...e.nodes.values()].filter(p=>p.imports.some(u=>u.toPath===n&&u.symbols?.includes(c))).map(p=>p.path);l.length>0&&r.push({file:n,symbol:c,stillReferencedBy:l})}}return r}function Tt(t){return t.occurrences.map(e=>`${e.file}:${e.startLine}-${e.endLine}`).sort().join("|")}async function Mp(t,e,r,n,s){let o=jo.default.join(ft(t),`${n}-${Re}`),i=Se(o),[{groups:a},{groups:c}]=await Promise.all([Ce(e,t,{minLines:s,tokenCache:i}),Ce(r,t,{minLines:s})]);ve(i,o);let l=new Set(a.map(Tt)),p=new Set(c.map(Tt));return{base:{groups:a.length},head:{groups:c.length},newGroups:c.filter(u=>!l.has(Tt(u))),resolvedGroups:a.filter(u=>!p.has(Tt(u)))}}function _o(t){let e=[...t.nodes.values()].map(r=>r.cognitiveComplexity).filter(r=>r!==void 0);return e.length===0?0:e.reduce((r,n)=>r+n,0)/e.length}function Lp(t,e,r,n){let s=we(t,{metric:r,threshold:n,limit:1/0}),o=we(e,{metric:r,threshold:n,limit:1/0}),i=l=>`${l.file}:${l.name}`,a=new Set(s.map(i)),c=new Set(o.map(i));return{base:{avgCognitiveComplexity:_o(t)},head:{avgCognitiveComplexity:_o(e)},newHotspots:o.filter(l=>!a.has(i(l))),resolvedHotspots:s.filter(l=>!c.has(i(l)))}}function Go(t){let e=new Set;for(let r of t.nodes.values())if(!(r.type!=="markdown"||!r.staleFor))for(let n of r.staleFor)e.add(`${r.path}::${n}`);return e}function _p(t,e){let r=Go(t),n=Go(e);return{base:{staleCount:r.size},head:{staleCount:n.size},newlyStale:[...n].filter(s=>!r.has(s)),resolved:[...r].filter(s=>!n.has(s))}}function Oo(t){let e=[...t.nodes.values()].map(r=>r.coveragePct).filter(r=>r!==void 0);return e.length===0?0:e.reduce((r,n)=>r+n,0)/e.length}function Gp(t,e,r){if(!te(t)||!te(e))return null;let n=Ee(t,{maxCoveragePct:r,limit:1/0}).hotspots,s=Ee(e,{maxCoveragePct:r,limit:1/0}).hotspots,o=c=>`${c.file}:${c.name}`,i=new Set(n.map(o)),a=new Set(s.map(o));return{base:{avgCoveragePct:Oo(t)},head:{avgCoveragePct:Oo(e)},newHotspots:s.filter(c=>!i.has(o(c))),resolvedHotspots:n.filter(c=>!a.has(o(c)))}}async function on(t,e,r,n={}){let{sha:s,graph:o}=await zo(t,e,n.entryPoints??[],n),i=nn(t,n.headRef??"HEAD"),[a,c]=await Promise.all([Mp(t,o,r,s,n.minDuplicateLines),Promise.resolve(Gp(o,r,n.maxCoveragePct))]);return{base:{ref:e,sha:s},head:{ref:n.headRef??"HEAD",sha:i},files:Rp(o,r),staleReferences:Ip(o,r),duplication:a,complexity:Lp(o,r,n.complexityMetric,n.complexityThreshold),docDrift:_p(o,r),coverage:c}}var Ze=g(require("path"));function Op(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 jp(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=Ze.default.extname(s),c=Ze.default.basename(s,a),l=c==="index"?Ze.default.basename(Ze.default.dirname(s)):c;n.set(s,{path:s,outDegree:o,tag:`feature:${l}`})}return n}function ne(t,e){let r=e?.minOutDegree??5;return jp(t,Op(t),r)}var zp=(t,e)=>t.outDegree-e.outDegree;function Wp(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 $p(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 Bp(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 Hp(t,e,r){let n=[];for(let s of t.keys())!e.has(s)&&!r.has(s)&&n.push(s);return n}function Xe(t,e){let r=e?.detectFn??ne,n=e?.hubComparator??zp,s=r(t.nodes,e),o=Wp(t,s),i=$p(t.nodes,s,o,n);return{features:Bp(s,i),unassigned:Hp(t.nodes,s,i)}}var Up=[{role:"component",segments:["component","components"]},{role:"controller",segments:["controller","controllers"]},{role:"middleware",segments:["middleware"]},{role:"router",segments:["router","routes","route"]},{role:"store",segments:["store","stores"]},{role:"service",segments:["service","services"]},{role:"handler",segments:["handler","handlers"]},{role:"adapter",segments:["adapter","adapters"]},{role:"plugin",segments:["plugin","plugins"]},{role:"api",segments:["api"]},{role:"cli",segments:["cli","commands"],basenames:["cli"]},{role:"util",segments:["util","utils","helper","helpers"]},{role:"model",segments:["model","models"],basenames:["model"]},{role:"parser",segments:["parser","parsers"],basenames:["parser"]},{role:"builder",basenames:["builder"]},{role:"resolver",basenames:["resolver"]}];function Wo(t){if(t.category==="test")return"test";if(t.category==="config")return"config";if(t.category==="type-only")return"types";let e=t.path,r=Kp(e);for(let n of Up)if(n.segments?.some(s=>Jp(e,s))||n.basenames?.includes(r))return n.role;return"other"}function Jp(t,e){return t.includes(`/${e}/`)||t.includes(`/${e}.`)}function Kp(t){let e=t.slice(t.lastIndexOf("/")+1);return e.slice(0,e.lastIndexOf("."))||e}function an(t,e){let r=Xe(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:Wo(o),...o.description?{description:o.description}:{},exports:o.exports.map(a=>a.name),...i?{featureHub:i}:{}})}return s}function cn(t,e){let r=[];for(let n of t.nodes.values())if(n.exports.some(s=>s.name===e))if(kt.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=Ye(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 qp(t){return t?t.startsWith("interface ")?"interface":t.startsWith("class ")?"class":t.startsWith("enum ")?"enum":"type":"type"}function Vp(t,e){if(e==="type-only")return!0;let r=t.signature??"";return r.startsWith("interface ")||r.startsWith("class ")||r.startsWith("enum ")}function ln(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(!Vp(s,n.category))continue;let o=`${n.path}::${s.name}`;e.set(o,{name:s.name,file:n.path,kind:qp(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 pn(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())}}var oi=g(require("path"));var fn=g(require("fs")),mn=g(require("path"));var $o=g(require("fs")),Nt=g(require("path"));var un=g(require("fs")),Qp=g(require("path"));function Pt(t){try{return un.default.statSync(t,{throwIfNoEntry:!1})?.isDirectory()===!0}catch{return!1}}function At(t){try{return un.default.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}var Yp=new Set([".java",".kt",".kts",".scala",".sc",".groovy",".gradle"]),Zp=new Set(P);function Bo(t,e=[]){let r;try{r=$o.default.readdirSync(t,{withFileTypes:!0})}catch{return e}for(let n of r){let s=Nt.default.join(t,n.name);n.isDirectory()?!Zp.has(n.name)&&!n.name.startsWith(".")&&Bo(s,e):n.isFile()&&Yp.has(Nt.default.extname(n.name).toLowerCase())&&e.push(s)}return e}function Dt(t,e,r){if(!Pt(e))return null;let n=Bo(e);return n.length===0?null:{name:r,root:e,relativeRoot:Nt.default.relative(t,e),entryPoints:n}}function Xp(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function eu(t){let e=Xp(t),r=new Set;for(let n of e.matchAll(/['"](:[A-Za-z0-9_\-.:]+)['"]/g)){let s=n[1].replace(/^:/,"").replace(/:$/,"");s&&r.add(s)}return[...r]}var Ho={type:"gradle",detect(t){let e=["settings.gradle.kts","settings.gradle"].map(o=>mn.default.join(t,o)).find(o=>fn.default.existsSync(o));if(!e)return null;let r;try{r=fn.default.readFileSync(e,"utf-8")}catch{return null}let n=eu(r);if(n.length===0)return null;let s=[];for(let o of n){let i=mn.default.join(t,...o.split(":")),a=Dt(t,i,o);a&&s.push(a)}return s.length>0?s:null}};var Rt=g(require("fs")),dn=g(require("path"));var Fe=g(require("fs")),T=g(require("path"));function gn(t,e){let r=T.default.join(e,"package.json");if(!Fe.default.existsSync(r))return null;let n={};try{n=JSON.parse(Fe.default.readFileSync(r,"utf-8"))}catch{return null}let s=n.name;return s?{name:s,root:e,relativeRoot:T.default.relative(t,e),entryPoints:tu(e,n)}:null}function tu(t,e){let r=[];if(e.exports){let s=e.exports;if(typeof s=="string")r.push(T.default.join(t,s));else if(typeof s=="object"&&s!==null){let o=s["."];if(typeof o=="string")r.push(T.default.join(t,o));else if(typeof o=="object"&&o!==null){let i=o.import??o.require??o.default;typeof i=="string"&&r.push(T.default.join(t,i))}}}e.main&&r.push(T.default.join(t,e.main));for(let s of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"])r.push(T.default.join(t,s));let n=r.filter(At);return n.length>0?n.slice(0,1):r.slice(0,1)}function Te(t,e){let r=[],n=new Set;for(let s of e){let o=s.replace(/\/$/,"").replace(/^\.\//,"");ru(t,o,n,r)}return r}function ru(t,e,r,n){if(!e.includes("*")){nu(t,e,r,n);return}let s=e.split("/");s.includes("**")?su(t,s,r,n):ou(t,s,r,n)}function nu(t,e,r,n){let s=T.default.join(t,e);if(r.has(s)||!Pt(s))return;r.add(s);let o=gn(t,s);o&&n.push(o)}function su(t,e,r,n){let s=T.default.join(t,e[0]==="**"?"":e[0]??"");Uo(t,s,r,n)}function ou(t,e,r,n){let s=e.findIndex(a=>a.includes("*")),o=T.default.join(t,...e.slice(0,s)),i;try{i=Fe.default.readdirSync(o,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let c=T.default.join(o,a.name);if(r.has(c))continue;r.add(c);let l=gn(t,c);l&&n.push(l)}}function Uo(t,e,r,n){let s;try{s=Fe.default.readdirSync(e,{withFileTypes:!0})}catch{return}for(let o of s){if(!o.isDirectory()||o.name==="node_modules"||o.name.startsWith("."))continue;let i=T.default.join(e,o.name);if(Fe.default.existsSync(T.default.join(i,"package.json"))&&!r.has(i)){r.add(i);let a=gn(t,i);a&&n.push(a)}else Uo(t,i,r,n)}}var Jo={type:"npm",detect(t){let e=dn.default.join(t,"package.json");if(!Rt.default.existsSync(e))return null;let r;try{r=JSON.parse(Rt.default.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!r||Rt.default.existsSync(dn.default.join(t,"yarn.lock")))return null;let n=Array.isArray(r)?r:r.packages??[];return n.length===0?null:Te(t,n)}};var se=g(require("fs")),E=g(require("path"));var Ko={type:"nx",detect(t){return se.default.existsSync(E.default.join(t,"nx.json"))?qo(t,t,new Set,0).map(r=>iu(t,r,E.default.join(r,"project.json"))).filter(r=>r!==null):null}};function qo(t,e,r,n){if(n>4)return[];let s;try{s=se.default.readdirSync(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let i of s){if(!i.isDirectory())continue;let a=i.name;if(a.startsWith(".")||a==="node_modules"||a==="dist"||a===".nx")continue;let c=E.default.join(e,a);se.default.existsSync(E.default.join(c,"project.json"))&&!r.has(c)?(r.add(c),o.push(c)):o.push(...qo(t,c,r,n+1))}return o}function iu(t,e,r){let n={};try{n=JSON.parse(se.default.readFileSync(r,"utf-8"))}catch{return null}let s=n.name,o,i,a=E.default.join(e,"package.json");if(se.default.existsSync(a))try{let c=JSON.parse(se.default.readFileSync(a,"utf-8"));s=c.name??s,o=c.main,i=c.exports}catch{}return s?{name:s,root:e,relativeRoot:E.default.relative(t,e),entryPoints:au(e,n,o,i)}:null}function au(t,e,r,n){let s=[],o=e.targets?.build?.options?.main??e.targets?.build?.options?.entryFile;if(o){let a=E.default.resolve(t,"../..");s.push(E.default.resolve(a,o)),s.push(E.default.resolve(t,o))}if(n){let a=n;if(typeof a=="string")s.push(E.default.join(t,a));else if(typeof a=="object"&&a!==null){let c=a["."];typeof c=="string"&&s.push(E.default.join(t,c))}}if(r&&s.push(E.default.join(t,r)),e.sourceRoot){let a=E.default.resolve(t,"../.."),c=E.default.resolve(a,e.sourceRoot);s.push(E.default.join(c,"index.ts"),E.default.join(c,"index.tsx"))}for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx"])s.push(E.default.join(t,a));let i=s.filter(At);return i.length>0?i.slice(0,1):s.slice(0,1)}var hn=g(require("fs")),Vo=g(require("path")),Qo=require("js-yaml");var Yo={type:"pnpm",detect(t){let e=Vo.default.join(t,"pnpm-workspace.yaml");if(!hn.default.existsSync(e))return null;let r=[];try{r=(0,Qo.load)(hn.default.readFileSync(e,"utf-8"))?.packages??[]}catch{return null}return Te(t,r)}};var Pe=g(require("fs")),et=g(require("path"));function cu(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function lu(t){let e=cu(t),r=new Map;for(let n of e.matchAll(/(?:lazy\s+)?val\s+([A-Za-z0-9_]+)\s*=\s*\(?\s*project\b([^\n]*)/g)){let s=n[1],i=n[2].match(/\bfile\s*\(\s*["']([^"']+)["']\s*\)/),a=i?i[1]:s;if(a==="."||a==="./")continue;let c=a.replace(/^\.\//,"").replace(/\/$/,"");r.has(c)||r.set(c,{name:s,dir:c})}return[...r.values()]}var Zo={type:"sbt",detect(t){let e=et.default.join(t,"build.sbt"),r=et.default.join(t,"project");if(!Pe.default.existsSync(e)||!Pe.default.existsSync(r))return null;let n=[];try{n.push(Pe.default.readFileSync(e,"utf-8"))}catch{return null}try{for(let a of Pe.default.readdirSync(r))a.endsWith(".scala")&&n.push(Pe.default.readFileSync(et.default.join(r,a),"utf-8"))}catch{}let s=new Set,o=[];for(let a of n)for(let c of lu(a))s.has(c.dir)||(s.add(c.dir),o.push(c));if(o.length===0)return null;let i=[];for(let a of o){let c=et.default.join(t,...a.dir.split("/")),l=Dt(t,c,a.name);l&&i.push(l)}return i.length>0?i:null}};var Xo=g(require("fs")),ei=g(require("path")),ti={type:"turborepo",detect(t){return Xo.default.existsSync(ei.default.join(t,"turbo.json"))?[]:null}};var It=g(require("fs")),yn=g(require("path"));var ri={type:"yarn",detect(t){if(!It.default.existsSync(yn.default.join(t,"yarn.lock")))return null;let e=yn.default.join(t,"package.json");if(!It.default.existsSync(e))return null;let r;try{r=JSON.parse(It.default.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:Te(t,n)}};var ni=[];function L(t){ni.push(t)}function si(){return ni}L(ti);L(Ko);L(Yo);L(ri);L(Jo);L(Ho);L(Zo);function tt(t,e=si()){let r=oi.default.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 rt=class t{constructor(e,r){this.monorepoRoot=e;this.type=r}monorepoRoot;type;packages=new Map;addPackage(e,r){this.packages.set(e.name,{graph:r,pkg:e})}annotateCrossPackageEdges(){for(let{graph:e}of this.packages.values())for(let r of e.nodes.values()){let n=this.getPackageForFile(r.path);if(n)for(let s of r.imports){if(s.isExternal||s.isWorkspace)continue;let o=this.getPackageForFile(s.toPath);o&&o.name!==n.name&&(s.isWorkspace=!0,s.workspacePackage=o.name)}}}getPackageForFile(e){for(let{pkg:r}of this.packages.values())if(e===r.relativeRoot||e.startsWith(`${r.relativeRoot}/`))return r}getPackageDependencies(){let e=new Map;for(let{graph:r,pkg:n}of this.packages.values()){let s=new Set;for(let o of r.nodes.values())for(let i of o.imports)i.isWorkspace&&i.workspacePackage&&s.add(i.workspacePackage);e.set(n.name,[...s])}return e}getAffectedAcrossPackages(e){let r=this.getPackageForFile(e);if(!r)return[];let n=this.packages.get(r.name);if(!n)return[];let s=[];n.graph.traverse(e,o=>(o.path!==e&&s.push({file:o.path,package:r.name}),!0),{direction:"incoming"});for(let{graph:o,pkg:i}of this.packages.values())if(i.name!==r.name)for(let a of o.nodes.values())a.imports.some(l=>l.isWorkspace&&l.workspacePackage===r.name)&&s.push({file:a.path,package:i.name});return s}serialize(){return{monorepoRoot:this.monorepoRoot,type:this.type,packages:Array.from(this.packages.values()).map(({graph:e,pkg:r})=>({pkg:{name:r.name,relativeRoot:r.relativeRoot,entryPoints:r.entryPoints},nodes:Array.from(e.nodes.values())}))}}static deserialize(e){let r=new t(e.monorepoRoot,e.type);for(let{pkg:n,nodes:s}of e.packages){let o=new Map(s.map(a=>[a.path,a])),i=new A(o);r.packages.set(n.name,{graph:i,pkg:{...n,root:""}})}return r}};function ii(t,e){return e.startsWith("!")?t!==e.slice(1):t===e}function pu(t,e){return e.startsWith("!")?!t.includes(e.slice(1)):t.includes(e)}var uu=(t,e)=>!e.category||ii(t.category,e.category),fu=(t,e)=>!e.type||ii(t.type,e.type),mu=(t,e)=>e.lastAuthor?e.lastAuthor.startsWith("!")?t.lastAuthor!==e.lastAuthor.slice(1):t.lastAuthor!==void 0&&t.lastAuthor===e.lastAuthor:!0,gu=(t,e)=>!e.path||pu(t.path,e.path),du=(t,e)=>e.isExternal===void 0?!0:t.imports.some(n=>n.isExternal)===e.isExternal,hu=(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)))},yu=(t,e)=>!e.allTags?.length||e.allTags.every(r=>t.tags.some(n=>n.name===r)),xu=(t,e)=>!e.importsFile||t.imports.some(r=>r.toPath?.includes(e.importsFile)),bu=(t,e,r)=>e.importedBy===void 0?!0:(r?.get(t.path)??[]).some(s=>s.includes(e.importedBy)),Su=(t,e)=>e.minImports===void 0||t.imports.length>=e.minImports,vu=(t,e)=>e.maxImports===void 0||t.imports.length<=e.maxImports,ku=(t,e)=>e.minSize===void 0||t.size>=e.minSize,Cu=(t,e)=>e.maxSize===void 0||t.size<=e.maxSize,wu=(t,e)=>e.hasDocstring===void 0||!!t.description===e.hasDocstring,Eu=(t,e)=>e.isDocumented===void 0||!!t.documentedBy?.length===e.isDocumented,Fu=(t,e)=>e.isStale===void 0||!!t.staleFor?.length===e.isStale,Tu=(t,e)=>e.minCoverage===void 0||(t.coveragePct??101)>=e.minCoverage,Pu=(t,e)=>e.maxCoverage===void 0||(t.coveragePct??0)<=e.maxCoverage,Au=(t,e)=>e.minExportUsage===void 0||(t.avgExportUsage??-1)>=e.minExportUsage,Nu=(t,e)=>e.maxExportUsage===void 0||(t.avgExportUsage??0)<=e.maxExportUsage,Du=(t,e)=>e.minComplexity===void 0||(t.complexity??-1/0)>=e.minComplexity,Ru=(t,e)=>e.maxComplexity===void 0||(t.complexity??0)<=e.maxComplexity,Iu=(t,e)=>e.minCognitiveComplexity===void 0||(t.cognitiveComplexity??-1/0)>=e.minCognitiveComplexity,Mu=(t,e)=>e.maxCognitiveComplexity===void 0||(t.cognitiveComplexity??0)<=e.maxCognitiveComplexity,Lu=(t,e)=>e.minCommits===void 0||(t.commitCount90d??-1/0)>=e.minCommits,_u=(t,e)=>e.maxCommits===void 0||(t.commitCount90d??0)<=e.maxCommits,Gu=(t,e,r)=>!e.any?.length||e.any.some(n=>nt(t,n,r)),Ou=[uu,fu,mu,gu,du,hu,yu,xu,bu,Su,vu,ku,Cu,wu,Eu,Fu,Tu,Pu,Au,Nu,Du,Ru,Iu,Mu,Lu,_u,Gu];function nt(t,e,r){return Ou.every(n=>n(t,e,r))}function Mt(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=>nt(i,e,r)),s=new Set(n.map(i=>i.path)),o=n.map(i=>({...i,imports:i.imports.filter(a=>!a.toPath||s.has(a.toPath))}));if(e.sort){let i=e.sortDir==="asc"?-1:1;o.sort((a,c)=>{let l=0;switch(e.sort){case"size":l=c.size-a.size;break;case"imports":l=c.imports.length-a.imports.length;break;case"commitCount90d":l=(c.commitCount90d??0)-(a.commitCount90d??0);break;case"exportUsage":l=(c.avgExportUsage??0)-(a.avgExportUsage??0);break;case"complexity":l=(c.complexity??0)-(a.complexity??0);break;case"cognitiveComplexity":l=(c.cognitiveComplexity??0)-(a.cognitiveComplexity??0);break}return l*i})}return e.limit!==void 0&&o.splice(e.limit),{nodes:o,cycles:t.cycles?.filter(i=>i.every(a=>s.has(a)))??void 0}}var ju={category:{field:"category",kind:"string"},type:{field:"type",kind:"string"},path:{field:"path",kind:"string"},importsfile:{field:"importsFile",kind:"string"},importedby:{field:"importedBy",kind:"string"},lastauthor:{field:"lastAuthor",kind:"string"},external:{field:"isExternal",kind:"boolIsTrue"},hasdocstring:{field:"hasDocstring",kind:"boolNotFalse"},isdocumented:{field:"isDocumented",kind:"boolNotFalse"},isstale:{field:"isStale",kind:"boolNotFalse"},minimports:{field:"minImports",kind:"int"},maximports:{field:"maxImports",kind:"int"},minsize:{field:"minSize",kind:"int"},maxsize:{field:"maxSize",kind:"int"},limit:{field:"limit",kind:"int"},mincoverage:{field:"minCoverage",kind:"int"},maxcoverage:{field:"maxCoverage",kind:"int"},minexportusage:{field:"minExportUsage",kind:"float"},maxexportusage:{field:"maxExportUsage",kind:"float"},mincomplexity:{field:"minComplexity",kind:"int"},maxcomplexity:{field:"maxComplexity",kind:"int"},mincognitivecomplexity:{field:"minCognitiveComplexity",kind:"int"},maxcognitivecomplexity:{field:"maxCognitiveComplexity",kind:"int"},mincommits:{field:"minCommits",kind:"int"},maxcommits:{field:"maxCommits",kind:"int"}};function zu(t,e,r,n){let s=t;switch(r){case"string":s[e]=n;break;case"int":s[e]=parseInt(n,10);break;case"float":s[e]=parseFloat(n);break;case"boolNotFalse":s[e]=n.toLowerCase()!=="false";break;case"boolIsTrue":s[e]=n.toLowerCase()==="true";break}}function ci(t,e){let r=e.indexOf(":");if(r===-1)return;let n=e.slice(0,r).trim().toLowerCase(),s=e.slice(r+1).trim();if(!n||!s)return;if(n==="tag"||n==="tags"){s.includes("+")?t.allTags=[...t.allTags??[],...s.split("+")]:t.tags=[...t.tags??[],s];return}if(n==="sort"){t.sort=s;return}if(n==="sortdir"){t.sortDir=s.toLowerCase()==="asc"?"asc":"desc";return}let o=ju[n];o&&zu(t,o.field,o.kind,s)}function Wu(t){let e=[];for(let r of t.split("|")){let n=r.trim();if(!n)continue;let s={};ci(s,n),Object.keys(s).length>0&&e.push(s)}return e}var ai="any(";function Lt(t){let e={},r=t.split(",");for(let n of r){let s=n.trim();if(s.toLowerCase().startsWith(ai)&&s.endsWith(")")){let o=s.slice(ai.length,-1),i=Wu(o);i.length>0&&(e.any=[...e.any??[],...i]);continue}ci(e,n)}return e}var Ln=g(require("fs/promises")),Ei=g(require("path"));var Jt=g(require("path")),st=g(require("typescript"));var ui=g(require("path"));var pi=g(require("path")),w=g(require("typescript")),li=new Set(["describe","test","it"]);function oe(t,e){let r=t[e];if(r===void 0)throw new Error(`Index ${e} out of bounds (length ${t.length})`);return r}function xn(t){let e=[];for(let r of t.statements){if(!w.default.isExpressionStatement(r))continue;let n=r.expression;if(!w.default.isCallExpression(n))continue;let s=n.expression;w.default.isIdentifier(s)&&li.has(s.text)&&e.push(n),w.default.isPropertyAccessExpression(s)&&w.default.isIdentifier(s.expression)&&li.has(s.expression.text)&&e.push(n)}return e}function bn(t,e,r){for(let n of t.arguments){if(!w.default.isObjectLiteralExpression(n))continue;let s=n.properties.find(o=>w.default.isPropertyAssignment(o)&&w.default.isIdentifier(o.name)&&o.name.text===e);if(!(!s||!w.default.isArrayLiteralExpression(s.initializer)))return s.initializer.elements.filter(w.default.isStringLiteral).map(o=>o.text)}return null}function Sn(t,e,r,n){if(t.arguments.length===0)return null;for(let o=1;o<t.arguments.length;o++){let i=oe(t.arguments,o);if(!w.default.isObjectLiteralExpression(i))continue;let a=i.properties.find(l=>w.default.isPropertyAssignment(l)&&w.default.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=oe(t.arguments,t.arguments.length-1);return{start:s.getStart(n),end:s.getStart(n),text:`{ ${e}: ${r} }, `}}function vn(t,e,r){let n=t.arguments;for(let s=1;s<n.length;s++){let o=oe(n,s);if(!w.default.isObjectLiteralExpression(o))continue;let i=o.properties.findIndex(c=>w.default.isPropertyAssignment(c)&&w.default.isIdentifier(c.name)&&c.name.text===e);if(i<0)continue;if(o.properties.length===1)return{start:oe(n,s-1).getEnd(),end:o.getEnd(),text:""};let a=oe(o.properties,i);return i===o.properties.length-1?{start:oe(o.properties,i-1).getEnd(),end:a.getEnd(),text:""}:{start:a.getStart(r),end:oe(o.properties,i+1).getStart(r),text:""}}return null}function kn(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 Cn(t){return`[${t.map(e=>JSON.stringify(e)).join(", ")}]`}var _=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);function $u(t){return t.map(e=>e.startsWith("@")?e.slice(1):e)}function _t(t,e,r,n){let s=w.default.createSourceFile(pi.default.basename(t),e,w.default.ScriptTarget.Latest,!0),o=xn(s),[i]=o;if(!i)return e;let a=bn(i,n,s),c=[...r].sort();if(a!==null&&JSON.stringify($u(a).sort())===JSON.stringify(c))return e;let l=Cn(c.map(u=>`@${u}`)),p=o.flatMap(u=>{let m=r.length===0?vn(u,n,s):Sn(u,n,l,s);return m?[m]:[]});return p.length>0?kn(e,p):e}var Gt=class{name="cypress";canHandle(e){return _.has(ui.default.extname(e).toLowerCase())}apply(e,r,n){return _t(e,r,n,"tags")}};var fi=g(require("path")),wn=/# <mokosh-tags>[\s\S]*?# <\/mokosh-tags>\n*/,En=/^@([a-zA-Z0-9_-]+)/gm;function Bu(t){return`${["# <mokosh-tags>",...t.map(e=>`@${e}`),"# </mokosh-tags>"].join(`
|
|
36
|
+
`),null}}var Ie=class{affectedSymbols=new Map;constructor(e,n){this.affectedSymbols.set(e,new Set(["default",...n]))}updateAffectedSymbols(e,n){let r=this.affectedSymbols.get(n)||new Set,s=e.imports.find(c=>c.toPath===n);if(!s)return!1;let i=s.symbols||["*"],o=new Set;for(let c of i)(c==="*"||r.has("*")||r.has(c))&&o.add("*");if(o.size===0)return!1;let a=this.affectedSymbols.get(e.path)||new Set;for(let c of o)a.add(c);return this.affectedSymbols.set(e.path,a),!0}};function Ot(t,e){let n=t.nodes.get(e);if(n)return{category:n.category,exports:n.exports.map(r=>r.name)}}function Es(t,e,n=1){let r=[];return t.traverse(e,(s,i,o)=>{if(s.path===e)return!0;let a=o?t.nodes.get(o)?.imports.find(c=>c.toPath===s.path):void 0;return r.push({path:s.path,...a?.symbols?{symbols:a.symbols}:{}}),!0},{direction:"outgoing",maxDepth:n}),r}function jt(t,e){let n=[];return t.traverse(e,r=>{if(r.path===e)return!0;let s=r.imports.find(i=>i.toPath===e);return n.push({path:r.path,...s?.symbols?{symbols:s.symbols}:{}}),!0},{direction:"incoming",maxDepth:1}),n}function Ts(t,e,n={}){let{testsOnly:r=!1,changedSymbols:s}=n,i=s?new Ie(e,s):null,o=[];return t.traverse(e,(a,c,l)=>{if(a.path===e)return!0;if(i&&l&&!i.updateAffectedSymbols(a,l))return!1;let p=a.category==="test"||a.tags.some(u=>u.name==="test");return(!r||p)&&o.push(a.path),!0},{direction:"incoming"}),o}function Fs(t,e,n={}){let{depth:r=1,withEdgeDetail:s=!1}=n,i=[];return t.traverseCalls(e,o=>{if(o.path===e)return!0;let a={file:o.path};return s&&(a.edges=(o.callEdges??[]).filter(c=>c.toFile===e).map(c=>({from:c.from,to:c.to}))),i.push(a),!0},{direction:"incoming",maxDepth:r}),i}function at(t,e={}){let{metric:n="cognitiveComplexity",threshold:r=10,limit:s=20}=e;return[...t.nodes.values()].flatMap(i=>(i.functions??[]).filter(o=>o[n]>=r).map(o=>({file:i.path,name:o.name,line:o.line,complexity:o.complexity,cognitiveComplexity:o.cognitiveComplexity}))).sort((i,o)=>o[n]-i[n]).slice(0,s)}function Ds(t){return{nodes:t.nodes.map(n=>({path:n.path,type:n.type,category:n.category,exports:n.exports.map(r=>r.name),tags:n.tags.filter(r=>r.kind==="comment-marker"||r.kind==="import").map(r=>r.name),importsFiles:n.imports.filter(r=>!r.isExternal&&r.toPath).map(r=>r.toPath),...n.package!==void 0&&{package:n.package},...n.description!==void 0&&{description:n.description},...n.testedBy!==void 0&&{testedBy:n.testedBy},...n.coveragePct!==void 0&&{coveragePct:n.coveragePct},...n.avgExportUsage!==void 0&&{avgExportUsage:n.avgExportUsage},...n.maxExportUsage!==void 0&&{maxExportUsage:n.maxExportUsage}})),cycles:t.cycles}}function Le(t){return[...t.nodes.values()].some(e=>e.coveragePct!==void 0)}function za(t){return[...t.nodes.values()].some(e=>e.commitCount90d!==void 0)}function Ps(t){return[...t.nodes.values()].some(e=>e.lastCommitAt!==void 0)}function ct(t,e={}){let{metric:n="cognitiveComplexity",minComplexity:r=10,maxCoveragePct:s=50,minChurn:i=0,limit:o=20}=e,a=za(t),c=[...t.nodes.values()].filter(l=>l.coveragePct!==void 0&&l.coveragePct<=s&&(!a||(l.commitCount90d??0)>=i)).flatMap(l=>(l.functions??[]).filter(p=>p[n]>=r).map(p=>({file:l.path,name:p.name,line:p.line,complexity:p.complexity,cognitiveComplexity:p.cognitiveComplexity,coveragePct:l.coveragePct,...l.commitCount90d!==void 0&&{commitCount90d:l.commitCount90d}}))).sort((l,p)=>p[n]-l[n]).slice(0,o);return{hotspots:c,count:c.length,churnDataAvailable:a}}var Ln=require("child_process"),In=h(require("fs")),Ba=h(require("os")),Ua=h(require("path"));function As(t,e){try{return(0,Ln.execFileSync)("git",["rev-parse","--verify",`${e}^{commit}`],{cwd:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()}catch{throw new Error(`Could not resolve git ref "${e}" in ${t}`)}}async function Ka(t,e,n){let r=In.default.mkdtempSync(Ua.default.join(Ba.default.tmpdir(),`mokosh-worktree-${e.slice(0,12)}-`));In.default.rmdirSync(r);try{return(0,Ln.execFileSync)("git",["worktree","add","--detach",r,e],{cwd:t,stdio:["ignore","pipe","pipe"]}),await n(r)}finally{try{(0,Ln.execFileSync)("git",["worktree","remove","--force",r],{cwd:t,stdio:["ignore","pipe","pipe"]})}catch{In.default.rmSync(r,{recursive:!0,force:!0})}}}async function Za(t,e,n,r={}){let s=As(t,e),i=Gi(t,s);if(i)return{sha:s,graph:i};let o=await Ka(t,s,async a=>{if(r.workspaceBuilder)return r.workspaceBuilder(a);let c=r.pathAliases?new le(a,{pathAliases:r.pathAliases}):void 0;return new Ne(a,null,c,void 0,r.gitStats??!1,new Map,r.parallelParsing??!0,r.additionalIgnoreDirs??[]).build(n)});return Oi(t,s,o),{sha:s,graph:o}}var Ha=t=>Math.round(t*100)/100,Ja=t=>t.length>8?t.slice(0,8):t;function Vm(t,e){return`${t.file}:${t.line} ${t.name} (${t[e]})`}function Qm(t,e){return`${t.file}:${t.line} ${t.name} (${t[e]}, cov ${t.coveragePct}%)`}function Ym(t,e=4){let n=t.occurrences.slice(0,e).map(i=>`${i.file}:${i.startLine}-${i.endLine}`),r=t.occurrences.length-n.length,s=r>0?`, +${r} more`:"";return`${t.lines}L x${t.occurrences.length}: ${n.join(", ")}${s}`}var _e=(t,e)=>`${t} ${e}${t===1?"":"s"}`;function Xm(t,e){let{files:n,staleReferences:r,duplication:s,complexity:i,docDrift:o,coverage:a}=t,c=[],l=[n.added.length&&`${n.added.length} added`,n.changed.length&&`${n.changed.length} changed`,n.removed.length&&`${n.removed.length} removed`].filter(Boolean);c.push(l.length?`Files: ${l.join(", ")}`:"No file changes"),r.length>0&&c.push(`\u26A0 ${_e(r.length,"stale reference")} \u2014 removed export still imported`);let p=i.newHotspots[0];return p?c.push(`+${_e(i.newHotspots.length,"complexity hotspot")} (max ${e} ${p[e]} in ${p.file})`):i.resolvedHotspots.length>0&&c.push(`${_e(i.resolvedHotspots.length,"complexity hotspot")} resolved`),s.newGroups.length>0?c.push(`+${_e(s.newGroups.length,"duplication group")}`):s.resolvedGroups.length>0&&c.push(`${_e(s.resolvedGroups.length,"duplication group")} resolved`),o.newlyStale.length>0&&c.push(`${_e(o.newlyStale.length,"doc")} newly stale`),a&&a.newHotspots.length>0&&c.push(`+${_e(a.newHotspots.length,"risk hotspot")}`),c}function Zm(t){let{staleReferences:e,duplication:n,complexity:r,docDrift:s,coverage:i}=t;return e.length>0||(i?.newHotspots.length??0)>0?"attention":r.newHotspots.length>0||n.newGroups.length>0||s.newlyStale.length>0?"review-worthy":"clean"}function Gn(t,e={}){let n=e.metric??"cognitiveComplexity",r=e.maxItems??8,s=e.maxPathList??100,{files:i,staleReferences:o,duplication:a,complexity:c,docDrift:l,coverage:p}=t,u=Ha(c.head.avgCognitiveComplexity-c.base.avgCognitiveComplexity),f=i.added.length+i.changed.length+i.removed.length,m={base:`${t.base.ref}@${Ja(t.base.sha)}`,head:`${t.head.ref}@${Ja(t.head.sha)}`,verdict:Zm(t),headline:Xm(t,n),files:{added:i.added.length,changed:i.changed.length,removed:i.removed.length,...f<=s?{paths:{added:i.added,changed:i.changed,removed:i.removed}}:{}}};return o.length>0&&(m.staleReferences=o),(c.newHotspots.length>0||c.resolvedHotspots.length>0)&&(m.complexity={avgDelta:u,newHotspots:c.newHotspots.slice(0,r).map(d=>Vm(d,n)),newHotspotCount:c.newHotspots.length,resolvedCount:c.resolvedHotspots.length}),(a.newGroups.length>0||a.resolvedGroups.length>0)&&(m.duplication={newGroups:a.newGroups.slice(0,r).map(d=>Ym(d)),newGroupCount:a.newGroups.length,resolvedCount:a.resolvedGroups.length,totalGroups:a.head.groups}),(l.newlyStale.length>0||l.resolved.length>0)&&(m.docDrift={newlyStale:l.newlyStale.slice(0,r).map(d=>d.replace("::"," \u2192 ")),newlyStaleCount:l.newlyStale.length,resolvedCount:l.resolved.length}),p&&(p.newHotspots.length>0||p.resolvedHotspots.length>0)&&(m.coverage={avgDelta:Ha(p.head.avgCoveragePct-p.base.avgCoveragePct),newHotspots:p.newHotspots.slice(0,r).map(d=>Qm(d,n)),newHotspotCount:p.newHotspots.length,resolvedCount:p.resolvedHotspots.length}),m}function qm(t,e){let n=[],r=[];for(let[i,o]of e.nodes){let a=t.nodes.get(i);if(!a){n.push(i);continue}let c=JSON.stringify({category:a.category,exports:a.exports.map(p=>p.name).sort(),imports:a.imports.map(p=>p.toPath).sort()}),l=JSON.stringify({category:o.category,exports:o.exports.map(p=>p.name).sort(),imports:o.imports.map(p=>p.toPath).sort()});c!==l&&r.push(i)}let s=[...t.nodes.keys()].filter(i=>!e.nodes.has(i));return{added:n,removed:s,changed:r}}function eg(t,e){let n=[];for(let[r,s]of t.nodes){let i=e.nodes.get(r);if(!i)continue;let o=new Set(i.exports.map(c=>c.name)),a=s.exports.map(c=>c.name).filter(c=>!o.has(c));if(a.length!==0)for(let c of a){let l=[...e.nodes.values()].filter(p=>p.imports.some(u=>u.toPath===r&&u.symbols?.includes(c))).map(p=>p.path);l.length>0&&n.push({file:r,symbol:c,stillReferencedBy:l})}}return n}function _n(t){return t.occurrences.map(e=>`${e.file}:${e.startLine}-${e.endLine}`).sort().join("|")}async function tg(t,e,n,r,s){let i=Xa.default.join(an(t),`${r}-${ht}`),o=rt(i),[{groups:a},{groups:c}]=await Promise.all([ot(e,t,{minLines:s,tokenCache:o}),ot(n,t,{minLines:s})]);st(o,i);let l=new Set(a.map(_n)),p=new Set(c.map(_n));return{base:{groups:a.length},head:{groups:c.length},newGroups:c.filter(u=>!l.has(_n(u))),resolvedGroups:a.filter(u=>!p.has(_n(u)))}}function Va(t){let e=[...t.nodes.values()].map(n=>n.cognitiveComplexity).filter(n=>n!==void 0);return e.length===0?0:e.reduce((n,r)=>n+r,0)/e.length}function ng(t,e,n,r){let s=at(t,{metric:n,threshold:r,limit:1/0}),i=at(e,{metric:n,threshold:r,limit:1/0}),o=l=>`${l.file}:${l.name}`,a=new Set(s.map(o)),c=new Set(i.map(o));return{base:{avgCognitiveComplexity:Va(t)},head:{avgCognitiveComplexity:Va(e)},newHotspots:i.filter(l=>!a.has(o(l))),resolvedHotspots:s.filter(l=>!c.has(o(l)))}}function Qa(t){let e=new Set;for(let n of t.nodes.values())if(!(n.type!=="markdown"||!n.staleFor))for(let r of n.staleFor)e.add(`${n.path}::${r}`);return e}function rg(t,e){let n=Qa(t),r=Qa(e);return{base:{staleCount:n.size},head:{staleCount:r.size},newlyStale:[...r].filter(s=>!n.has(s)),resolved:[...n].filter(s=>!r.has(s))}}function Ya(t){let e=[...t.nodes.values()].map(n=>n.coveragePct).filter(n=>n!==void 0);return e.length===0?0:e.reduce((n,r)=>n+r,0)/e.length}function sg(t,e,n){if(!Le(t)||!Le(e))return null;let r=ct(t,{maxCoveragePct:n,limit:1/0}).hotspots,s=ct(e,{maxCoveragePct:n,limit:1/0}).hotspots,i=c=>`${c.file}:${c.name}`,o=new Set(r.map(i)),a=new Set(s.map(i));return{base:{avgCoveragePct:Ya(t)},head:{avgCoveragePct:Ya(e)},newHotspots:s.filter(c=>!o.has(i(c))),resolvedHotspots:r.filter(c=>!a.has(i(c)))}}async function On(t,e,n,r={}){let{sha:s,graph:i}=await Za(t,e,r.entryPoints??[],r),o=As(t,r.headRef??"HEAD"),[a,c]=await Promise.all([tg(t,i,n,s,r.minDuplicateLines),Promise.resolve(sg(i,n,r.maxCoveragePct))]);return{base:{ref:e,sha:s},head:{ref:r.headRef??"HEAD",sha:o},files:qm(i,n),staleReferences:eg(i,n),duplication:a,complexity:ng(i,n,r.complexityMetric,r.complexityThreshold),docDrift:rg(i,n),coverage:c}}var Wt=h(require("path"));function ig(t){let e=new Map;for(let[n,r]of t){let s=r.imports.filter(i=>i.toPath&&!i.isExternal).length;s>0&&e.set(n,s)}return e}function og(t,e,n){let r=new Map;for(let[s,i]of e){if(i<n)continue;let o=t.get(s);if(!o||o.category==="test"||o.category==="barrel")continue;let a=Wt.default.extname(s),c=Wt.default.basename(s,a),l=c==="index"?Wt.default.basename(Wt.default.dirname(s)):c;r.set(s,{path:s,outDegree:i,tag:`feature:${l}`})}return r}function ke(t,e){let n=e?.minOutDegree??5;return og(t,ig(t),n)}var ag=(t,e)=>t.outDegree-e.outDegree;function cg(t,e){let n=new Map;for(let r of e.values()){let s=new Set;t.traverse(r.path,i=>(i.path!==r.path&&s.add(i.path),!0),{direction:"outgoing"}),n.set(r.path,s)}return n}function lg(t,e,n,r){let s=new Map;for(let[i]of t){if(e.has(i))continue;let o=null;for(let a of e.values())n.get(a.path)?.has(i)&&(!o||r(a,o)<0)&&(o=a);o&&s.set(i,o.path)}return s}function pg(t,e){let n=new Map;for(let r of t.values()){let s=r.tag.replace("feature:",""),i=[];for(let[o,a]of e)a===r.path&&i.push(o);n.set(s,{hub:r.path,outDegree:r.outDegree,files:i})}return n}function ug(t,e,n){let r=[];for(let s of t.keys())!e.has(s)&&!n.has(s)&&r.push(s);return r}function $t(t,e){let n=e?.detectFn??ke,r=e?.hubComparator??ag,s=n(t.nodes,e),i=cg(t,s),o=lg(t.nodes,s,i,r);return{features:pg(s,o),unassigned:ug(t.nodes,s,o)}}var fg=[{role:"component",segments:["component","components"]},{role:"controller",segments:["controller","controllers"]},{role:"middleware",segments:["middleware"]},{role:"router",segments:["router","routes","route"]},{role:"store",segments:["store","stores"]},{role:"service",segments:["service","services"]},{role:"handler",segments:["handler","handlers"]},{role:"adapter",segments:["adapter","adapters"]},{role:"plugin",segments:["plugin","plugins"]},{role:"api",segments:["api"]},{role:"cli",segments:["cli","commands"],basenames:["cli"]},{role:"util",segments:["util","utils","helper","helpers"]},{role:"model",segments:["model","models"],basenames:["model"]},{role:"parser",segments:["parser","parsers"],basenames:["parser"]},{role:"builder",basenames:["builder"]},{role:"resolver",basenames:["resolver"]}];function qa(t){if(t.category==="test")return"test";if(t.category==="config")return"config";if(t.category==="type-only")return"types";let e=t.path,n=gg(e);for(let r of fg)if(r.segments?.some(s=>mg(e,s))||r.basenames?.includes(n))return r.role;return"other"}function mg(t,e){return t.includes(`/${e}/`)||t.includes(`/${e}.`)}function gg(t){let e=t.slice(t.lastIndexOf("/")+1);return e.slice(0,e.lastIndexOf("."))||e}function Rs(t,e){let n=$t(t,e),r=new Map;for(let[i,o]of n.features){for(let a of o.files)r.set(a,i);r.set(o.hub,i)}let s=new Map;for(let i of t.nodes.values()){let o=r.get(i.path);s.set(i.path,{path:i.path,role:qa(i),...i.description?{description:i.description}:{},exports:i.exports.map(a=>a.name),...o?{featureHub:o}:{}})}return s}function Ns(t,e){let n=[];for(let r of t.nodes.values())if(r.exports.some(s=>s.name===e))if(Ft.has(r.type)){let s=[];for(let i of t.nodes.values())for(let o of i.callEdges??[])o.to===e&&s.push({file:i.path,callerFunction:o.from});n.push({path:r.path,category:r.category,precision:"call",callers:s})}else{let s=jt(t,r.path).map(i=>({file:i.path,...i.symbols?{symbols:i.symbols}:{}}));n.push({path:r.path,category:r.category,precision:"file-level",importers:s})}return n}var Ms=qt,tc=2,nc=50,Is=250,ec=["function","class","variable","type","import","library","comment-marker"];function Ls(t){let e=new Map;for(let r of t)for(let s of r.nodes.values())for(let i of s.tags){let o=e.get(i.name);o===void 0&&(o={name:i.name,count:0,kinds:[]},e.set(i.name,o)),o.count+=1,o.kinds.includes(i.kind)||o.kinds.push(i.kind)}let n={};for(let r of e.values()){r.kinds.sort((s,i)=>ec.indexOf(s)-ec.indexOf(i));for(let s of r.kinds)n[s]=(n[s]??0)+1}return{entries:e,byKind:n,totalDistinct:e.size}}function _s(t,e={}){let n=Number.isFinite(e.minCount)?Math.max(1,Math.trunc(e.minCount)):tc,r=Number.isFinite(e.limit)?Math.max(0,Math.trunc(e.limit)):nc,s=Math.min(r,Is),i=e.prefix?.toLowerCase(),o=m=>e.kind===void 0?m.kinds.some(d=>Ms.includes(d))&&tn(m.name):e.kind==="all"?!0:m.kinds.includes(e.kind),a=[...t.entries.values()].filter(m=>m.count>=n&&o(m)&&(i===void 0||m.name.toLowerCase().includes(i))).sort((m,d)=>d.count-m.count||m.name.localeCompare(d.name)),c=a.length,l=a.slice(0,s),p=e.kind===void 0?`${Ms.join(" + ")} kinds, noise-filtered`:e.kind==="all"?"all kinds":`${e.kind} kind`,u=c>l.length,f={tags:l.map(m=>({name:m.name,count:m.count,kinds:m.kinds})),count:l.length,matched:c,totalDistinct:t.totalDistinct,byKind:t.byKind,hint:`${c} tag${c===1?"":"s"} match (${p}, count>=${n})${u?`; showing the top ${l.length}`:""}. ${t.totalDistinct} distinct tag names exist across all kinds \u2014 see byKind. Narrow with prefix:"\u2026", a higher minCount, or kind:"comment-marker"|"import"|"function"|"variable"|"library"|"all". This response is always capped at ${Is} tags.`};return u&&(f.truncated=!0),f}function dg(t){return t?t.startsWith("interface ")?"interface":t.startsWith("class ")?"class":t.startsWith("enum ")?"enum":"type":"type"}function hg(t,e){if(e==="type-only")return!0;let n=t.signature??"";return n.startsWith("interface ")||n.startsWith("class ")||n.startsWith("enum ")}function Gs(t){let e=new Map;for(let r of t.nodes.values())if(!(r.type!=="typescript"&&r.type!=="javascript"))for(let s of r.exports){if(!hg(s,r.category))continue;let i=`${r.path}::${s.name}`;e.set(i,{name:s.name,file:r.path,kind:dg(s.signature),...s.doc?{doc:s.doc}:{}})}let n=[];for(let r of t.nodes.values())if(!(r.type!=="typescript"&&r.type!=="javascript")){for(let s of r.imports)if(!(!s.toPath||s.isExternal||!s.symbols?.length))for(let i of s.symbols)e.has(`${s.toPath}::${i}`)&&n.push({fromFile:r.path,toType:i,toFile:s.toPath})}return{types:e,edges:n}}function Os(t,e){let n=null;for(let i of t.types.values())if(i.name===e){n=i;break}if(!n)return{type:null,usedByFiles:[],uses:[]};let r=new Set,s=new Map;for(let i of t.edges)if(i.toType===e&&i.toFile===n.file&&r.add(i.fromFile),i.fromFile===n.file){let o=t.types.get(`${i.toFile}::${i.toType}`);o&&s.set(`${o.file}::${o.name}`,o)}return{type:n,usedByFiles:Array.from(r),uses:Array.from(s.values())}}var vc=h(require("path"));var Ws=h(require("fs")),$s=h(require("path"));var rc=h(require("fs")),$n=h(require("path"));var js=h(require("fs")),yg=h(require("path"));function jn(t){try{return js.default.statSync(t,{throwIfNoEntry:!1})?.isDirectory()===!0}catch{return!1}}function Wn(t){try{return js.default.statSync(t,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}var xg=new Set([".java",".kt",".kts",".scala",".sc",".groovy",".gradle"]),bg=new Set(j);function sc(t,e=[]){let n;try{n=rc.default.readdirSync(t,{withFileTypes:!0})}catch{return e}for(let r of n){let s=$n.default.join(t,r.name);r.isDirectory()?!bg.has(r.name)&&!r.name.startsWith(".")&&sc(s,e):r.isFile()&&xg.has($n.default.extname(r.name).toLowerCase())&&e.push(s)}return e}function zn(t,e,n){if(!jn(e))return null;let r=sc(e);return r.length===0?null:{name:n,root:e,relativeRoot:$n.default.relative(t,e),entryPoints:r}}function kg(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Sg(t){let e=kg(t),n=new Set;for(let r of e.matchAll(/['"](:[A-Za-z0-9_\-.:]+)['"]/g)){let s=r[1].replace(/^:/,"").replace(/:$/,"");s&&n.add(s)}return[...n]}var ic={type:"gradle",detect(t){let e=["settings.gradle.kts","settings.gradle"].map(i=>$s.default.join(t,i)).find(i=>Ws.default.existsSync(i));if(!e)return null;let n;try{n=Ws.default.readFileSync(e,"utf-8")}catch{return null}let r=Sg(n);if(r.length===0)return null;let s=[];for(let i of r){let o=$s.default.join(t,...i.split(":")),a=zn(t,o,i);a&&s.push(a)}return s.length>0?s:null}};var Bn=h(require("fs")),Us=h(require("path"));var lt=h(require("fs")),ne=h(require("path"));function Bs(t,e){let n=ne.default.join(e,"package.json");if(!lt.default.existsSync(n))return null;let r={};try{r=JSON.parse(lt.default.readFileSync(n,"utf-8"))}catch{return null}let s=r.name;return s?{name:s,root:e,relativeRoot:ne.default.relative(t,e),entryPoints:Cg(e,r)}:null}var vg=/\.[mc]?[jt]sx?$/;function zs(t,e){if(typeof t=="string"){vg.test(t)&&!t.endsWith(".d.ts")&&e(t);return}if(t&&typeof t=="object"&&!Array.isArray(t))for(let[n,r]of Object.entries(t))n!=="types"&&zs(r,e)}function Cg(t,e){let n=[],r=new Set,s=a=>{let c=ne.default.join(t,a);r.has(c)||(r.add(c),n.push(c))},i=e.exports;if(typeof i=="string")zs(i,s);else if(i&&typeof i=="object"&&!Array.isArray(i))for(let a of Object.values(i))zs(a,s);e.main&&s(e.main);for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"])s(a);let o=n.filter(Wn);return o.length>0?o:n.slice(0,1)}function pt(t,e){let n=[],r=new Set;for(let s of e){let i=s.replace(/\/$/,"").replace(/^\.\//,"");wg(t,i,r,n)}return n}function wg(t,e,n,r){if(!e.includes("*")){Eg(t,e,n,r);return}let s=e.split("/");s.includes("**")?Tg(t,s,n,r):Fg(t,s,n,r)}function Eg(t,e,n,r){let s=ne.default.join(t,e);if(n.has(s)||!jn(s))return;n.add(s);let i=Bs(t,s);i&&r.push(i)}function Tg(t,e,n,r){let s=ne.default.join(t,e[0]==="**"?"":e[0]??"");oc(t,s,n,r)}function Fg(t,e,n,r){let s=e.findIndex(a=>a.includes("*")),i=ne.default.join(t,...e.slice(0,s)),o;try{o=lt.default.readdirSync(i,{withFileTypes:!0})}catch{return}for(let a of o){if(!a.isDirectory())continue;let c=ne.default.join(i,a.name);if(n.has(c))continue;n.add(c);let l=Bs(t,c);l&&r.push(l)}}function oc(t,e,n,r){let s;try{s=lt.default.readdirSync(e,{withFileTypes:!0})}catch{return}for(let i of s){if(!i.isDirectory()||i.name==="node_modules"||i.name.startsWith("."))continue;let o=ne.default.join(e,i.name);if(lt.default.existsSync(ne.default.join(o,"package.json"))&&!n.has(o)){n.add(o);let a=Bs(t,o);a&&r.push(a)}else oc(t,o,n,r)}}var ac={type:"npm",detect(t){let e=Us.default.join(t,"package.json");if(!Bn.default.existsSync(e))return null;let n;try{n=JSON.parse(Bn.default.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!n||Bn.default.existsSync(Us.default.join(t,"yarn.lock")))return null;let r=Array.isArray(n)?n:n.packages??[];return r.length===0?null:pt(t,r)}};var Ge=h(require("fs")),M=h(require("path"));var cc={type:"nx",detect(t){return Ge.default.existsSync(M.default.join(t,"nx.json"))?lc(t,t,new Set,0).map(n=>Dg(t,n,M.default.join(n,"project.json"))).filter(n=>n!==null):null}};function lc(t,e,n,r){if(r>4)return[];let s;try{s=Ge.default.readdirSync(e,{withFileTypes:!0})}catch{return[]}let i=[];for(let o of s){if(!o.isDirectory())continue;let a=o.name;if(a.startsWith(".")||a==="node_modules"||a==="dist"||a===".nx")continue;let c=M.default.join(e,a);Ge.default.existsSync(M.default.join(c,"project.json"))&&!n.has(c)?(n.add(c),i.push(c)):i.push(...lc(t,c,n,r+1))}return i}function Dg(t,e,n){let r={};try{r=JSON.parse(Ge.default.readFileSync(n,"utf-8"))}catch{return null}let s=r.name,i,o,a=M.default.join(e,"package.json");if(Ge.default.existsSync(a))try{let c=JSON.parse(Ge.default.readFileSync(a,"utf-8"));s=c.name??s,i=c.main,o=c.exports}catch{}return s?{name:s,root:e,relativeRoot:M.default.relative(t,e),entryPoints:Pg(e,r,i,o)}:null}function Pg(t,e,n,r){let s=[],i=e.targets?.build?.options?.main??e.targets?.build?.options?.entryFile;if(i){let a=M.default.resolve(t,"../..");s.push(M.default.resolve(a,i)),s.push(M.default.resolve(t,i))}if(r){let a=r;if(typeof a=="string")s.push(M.default.join(t,a));else if(typeof a=="object"&&a!==null){let c=a["."];typeof c=="string"&&s.push(M.default.join(t,c))}}if(n&&s.push(M.default.join(t,n)),e.sourceRoot){let a=M.default.resolve(t,"../.."),c=M.default.resolve(a,e.sourceRoot);s.push(M.default.join(c,"index.ts"),M.default.join(c,"index.tsx"))}for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx"])s.push(M.default.join(t,a));let o=s.filter(Wn);return o.length>0?o.slice(0,1):s.slice(0,1)}var Ks=h(require("fs")),pc=h(require("path")),uc=require("js-yaml");var fc={type:"pnpm",detect(t){let e=pc.default.join(t,"pnpm-workspace.yaml");if(!Ks.default.existsSync(e))return null;let n=[];try{n=(0,uc.load)(Ks.default.readFileSync(e,"utf-8"))?.packages??[]}catch{return null}return pt(t,n)}};var ut=h(require("fs")),zt=h(require("path"));function Ag(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Rg(t){let e=Ag(t),n=new Map;for(let r of e.matchAll(/(?:lazy\s+)?val\s+([A-Za-z0-9_]+)\s*=\s*\(?\s*project\b([^\n]*)/g)){let s=r[1],o=r[2].match(/\bfile\s*\(\s*["']([^"']+)["']\s*\)/),a=o?o[1]:s;if(a==="."||a==="./")continue;let c=a.replace(/^\.\//,"").replace(/\/$/,"");n.has(c)||n.set(c,{name:s,dir:c})}return[...n.values()]}var mc={type:"sbt",detect(t){let e=zt.default.join(t,"build.sbt"),n=zt.default.join(t,"project");if(!ut.default.existsSync(e)||!ut.default.existsSync(n))return null;let r=[];try{r.push(ut.default.readFileSync(e,"utf-8"))}catch{return null}try{for(let a of ut.default.readdirSync(n))a.endsWith(".scala")&&r.push(ut.default.readFileSync(zt.default.join(n,a),"utf-8"))}catch{}let s=new Set,i=[];for(let a of r)for(let c of Rg(a))s.has(c.dir)||(s.add(c.dir),i.push(c));if(i.length===0)return null;let o=[];for(let a of i){let c=zt.default.join(t,...a.dir.split("/")),l=zn(t,c,a.name);l&&o.push(l)}return o.length>0?o:null}};var gc=h(require("fs")),dc=h(require("path")),hc={type:"turborepo",detect(t){return gc.default.existsSync(dc.default.join(t,"turbo.json"))?[]:null}};var Un=h(require("fs")),Hs=h(require("path"));var yc={type:"yarn",detect(t){if(!Un.default.existsSync(Hs.default.join(t,"yarn.lock")))return null;let e=Hs.default.join(t,"package.json");if(!Un.default.existsSync(e))return null;let n;try{n=JSON.parse(Un.default.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!n)return null;let r=Array.isArray(n)?n:n.packages??[];return r.length===0?null:pt(t,r)}};var xc=[];function re(t){xc.push(t)}function bc(){return xc}var kc=h(require("fs")),Sc=h(require("path")),Ng=["dependencies","devDependencies","peerDependencies","optionalDependencies"];function Mg(t){try{let e=kc.default.readFileSync(Sc.default.join(t,"package.json"),"utf-8"),n=JSON.parse(e),r=new Set;for(let s of Ng){let i=n[s];if(i&&typeof i=="object")for(let o of Object.keys(i))r.add(o)}return r}catch{return null}}function Bt(t,e){if(e){let i=e.getPackageDependencies(),o=Array.from(e.packages.values()).map(({graph:a,pkg:c})=>({name:c.name,relativeRoot:c.relativeRoot,dependsOn:i.get(c.name)??[],nodeCount:a.nodes.size}));return{monorepoType:t.type,monorepoTypes:t.types,packageCount:o.length,packages:o,dependsOnResolved:!0,nodeCountsResolved:!0}}let n=new Set(t.packages.map(i=>i.name)),r=!0,s=t.packages.map(i=>{let o=Mg(i.root);if(o===null)return r=!1,{name:i.name,relativeRoot:i.relativeRoot,dependsOn:[]};let a=[...o].filter(c=>c!==i.name&&n.has(c)).sort();return{name:i.name,relativeRoot:i.relativeRoot,dependsOn:a}});return{monorepoType:t.type,monorepoTypes:t.types,packageCount:s.length,packages:s,dependsOnResolved:r,nodeCountsResolved:!1,note:"Layout only \u2014 per-package node counts and (for build-system monorepos without package.json) dependency edges require a full graph. Call analyze with empty entryPoints, then get_workspace_packages again."}}re(hc);re(cc);re(fc);re(yc);re(ac);re(ic);re(mc);function Ut(t,e=bc()){let n=vc.default.resolve(t),r=new Map,s=[];for(let o of e){let a=o.detect(n);if(a!==null){s.push(o.type);for(let c of a)r.has(c.name)||r.set(c.name,c)}}if(s.length===0)return{root:n,type:"none",types:[],packages:[],packageMap:new Map};let i=Array.from(r.values());return{root:n,type:s[0],types:s,packages:i,packageMap:new Map(i.map(o=>[o.name,o]))}}function ft(t,e){return t===e.relativeRoot||t.startsWith(`${e.relativeRoot}/`)}var Oe=class t{constructor(e,n){this.monorepoRoot=e;this.type=n}monorepoRoot;type;packages=new Map;flattened;addPackage(e,n){this.packages.set(e.name,{graph:n,pkg:e})}annotateCrossPackageEdges(){for(let{graph:e}of this.packages.values())for(let n of e.nodes.values()){let r=this.getPackageForFile(n.path);if(r)for(let s of n.imports){if(s.isExternal||s.isWorkspace)continue;let i=this.getPackageForFile(s.toPath);i&&i.name!==r.name&&(s.isWorkspace=!0,s.workspacePackage=i.name)}}}flatten(){if(this.flattened)return this.flattened;let e=new Map,n=new Map;for(let{graph:r,pkg:s}of this.packages.values())for(let[i,o]of r.nodes)ft(i,s)&&(e.set(i,o),n.set(i,s.name));return this.flattened={graph:new A(e),packageOf:n},this.flattened}getPackageForFile(e){for(let{pkg:n}of this.packages.values())if(e===n.relativeRoot||e.startsWith(`${n.relativeRoot}/`))return n}getPackageDependencies(){let e=new Map;for(let{graph:n,pkg:r}of this.packages.values()){let s=new Set;for(let i of n.nodes.values())for(let o of i.imports)o.isWorkspace&&o.workspacePackage&&s.add(o.workspacePackage);e.set(r.name,[...s])}return e}getAffectedAcrossPackages(e){let{graph:n,packageOf:r}=this.flatten();if(!n.nodes.has(e))return[];let s=[];return n.traverse(e,i=>(i.path!==e&&s.push({file:i.path,package:r.get(i.path)??""}),!0),{direction:"incoming"}),s}summarizeAffectedAcrossPackages(e,n={}){let r=n.maxFilesPerPackage??10,s=this.getAffectedAcrossPackages(e),i=new Map;for(let{file:c,package:l}of s){let p=i.get(l)??[];p.push(c),i.set(l,p)}let o=!1,a=[...i.entries()].map(([c,l])=>{let p=l.slice(0,r),u=l.length-p.length;return u>0&&(o=!0),{package:c,count:l.length,sample:p,more:u}}).sort((c,l)=>l.count-c.count);return{file:e,totalAffected:s.length,packageCount:a.length,byPackage:a,truncated:o}}serialize(){return{monorepoRoot:this.monorepoRoot,type:this.type,packages:Array.from(this.packages.values()).map(({graph:e,pkg:n})=>({pkg:{name:n.name,relativeRoot:n.relativeRoot,entryPoints:n.entryPoints},nodes:Array.from(e.nodes.values())}))}}static deserialize(e){let n=new t(e.monorepoRoot,e.type);for(let{pkg:r,nodes:s}of e.packages){let i=new Map(s.map(a=>[a.path,a])),o=new A(i);n.packages.set(r.name,{graph:o,pkg:{...r,root:""}})}return n}};function Js(t,e){return e.startsWith("!")?t!==e.slice(1):t===e}function Ig(t,e){return e.startsWith("!")?!t.includes(e.slice(1)):t.includes(e)}var Lg=(t,e)=>!e.category||Js(t.category,e.category),_g=(t,e)=>!e.type||Js(t.type,e.type),Gg=(t,e)=>e.lastAuthor?e.lastAuthor.startsWith("!")?t.lastAuthor!==e.lastAuthor.slice(1):t.lastAuthor!==void 0&&t.lastAuthor===e.lastAuthor:!0,Og=(t,e)=>!e.path||Ig(t.path,e.path),jg=(t,e,n,r)=>{if(!e.package||!r)return!0;let s=r.get(t.path)??"";return Js(s,e.package)},Wg=(t,e)=>e.isExternal===void 0?!0:t.imports.some(r=>r.isExternal)===e.isExternal,$g=(t,e)=>{if(!e.tags||e.tags.length===0)return!0;let n=new Set(t.tags.filter(we).map(i=>i.name)),r=e.tags.filter(i=>!i.startsWith("!")),s=e.tags.filter(i=>i.startsWith("!")).map(i=>i.slice(1));return!(r.length>0&&!r.some(i=>n.has(i))||s.some(i=>n.has(i)))},zg=(t,e)=>{if(!e.allTags?.length)return!0;let n=new Set(t.tags.filter(we).map(r=>r.name));return e.allTags.every(r=>n.has(r))},Bg=(t,e)=>!e.importsFile||t.imports.some(n=>n.toPath?.includes(e.importsFile)),Ug=(t,e,n)=>e.importedBy===void 0?!0:(n?.get(t.path)??[]).some(s=>s.includes(e.importedBy)),Kg=(t,e)=>e.minImports===void 0||t.imports.length>=e.minImports,Hg=(t,e)=>e.maxImports===void 0||t.imports.length<=e.maxImports,Jg=(t,e)=>e.minSize===void 0||t.size>=e.minSize,Vg=(t,e)=>e.maxSize===void 0||t.size<=e.maxSize,Qg=(t,e)=>e.hasDocstring===void 0||!!t.description===e.hasDocstring,Yg=(t,e)=>e.isDocumented===void 0||!!t.documentedBy?.length===e.isDocumented,Xg=(t,e)=>e.isStale===void 0||!!t.staleFor?.length===e.isStale,Zg=(t,e)=>e.minCoverage===void 0||(t.coveragePct??101)>=e.minCoverage,qg=(t,e)=>e.maxCoverage===void 0||(t.coveragePct??0)<=e.maxCoverage,ed=(t,e)=>e.minExportUsage===void 0||(t.avgExportUsage??-1)>=e.minExportUsage,td=(t,e)=>e.maxExportUsage===void 0||(t.avgExportUsage??0)<=e.maxExportUsage,nd=(t,e)=>e.minComplexity===void 0||(t.complexity??-1/0)>=e.minComplexity,rd=(t,e)=>e.maxComplexity===void 0||(t.complexity??0)<=e.maxComplexity,sd=(t,e)=>e.minCognitiveComplexity===void 0||(t.cognitiveComplexity??-1/0)>=e.minCognitiveComplexity,id=(t,e)=>e.maxCognitiveComplexity===void 0||(t.cognitiveComplexity??0)<=e.maxCognitiveComplexity,od=(t,e)=>e.minCommits===void 0||(t.commitCount90d??-1/0)>=e.minCommits,ad=(t,e)=>e.maxCommits===void 0||(t.commitCount90d??0)<=e.maxCommits,cd=(t,e,n,r)=>!e.any?.length||e.any.some(s=>Kt(t,s,n,r)),ld=[Lg,_g,Gg,Og,jg,Wg,$g,zg,Bg,Ug,Kg,Hg,Jg,Vg,Qg,Yg,Xg,Zg,qg,ed,td,nd,rd,sd,id,od,ad,cd];function Kt(t,e,n,r){return ld.every(s=>s(t,e,n,r))}function Kn(t,e,n={}){let{packageOf:r}=n,s=new Map;if(e.importedBy!==void 0){for(let c of t.nodes)for(let l of c.imports)if(l.toPath){let p=s.get(l.toPath)??[];p.push(c.path),s.set(l.toPath,p)}}let i=t.nodes.filter(c=>Kt(c,e,s,r)),o=new Set(i.map(c=>c.path)),a=i.map(c=>{let l=r?.get(c.path);return{...c,imports:c.imports.filter(p=>!p.toPath||o.has(p.toPath)),...l!==void 0&&{package:l}}});if(e.sort){let c=e.sortDir==="asc"?-1:1;a.sort((l,p)=>{let u=0;switch(e.sort){case"size":u=p.size-l.size;break;case"imports":u=p.imports.length-l.imports.length;break;case"commitCount90d":u=(p.commitCount90d??0)-(l.commitCount90d??0);break;case"exportUsage":u=(p.avgExportUsage??0)-(l.avgExportUsage??0);break;case"complexity":u=(p.complexity??0)-(l.complexity??0);break;case"cognitiveComplexity":u=(p.cognitiveComplexity??0)-(l.cognitiveComplexity??0);break}return u*c})}return e.limit!==void 0&&a.splice(e.limit),{nodes:a,cycles:t.cycles?.filter(c=>c.every(l=>o.has(l)))??void 0}}var pd={category:{field:"category",kind:"string"},type:{field:"type",kind:"string"},path:{field:"path",kind:"string"},package:{field:"package",kind:"string"},importsfile:{field:"importsFile",kind:"string"},importedby:{field:"importedBy",kind:"string"},lastauthor:{field:"lastAuthor",kind:"string"},external:{field:"isExternal",kind:"boolIsTrue"},hasdocstring:{field:"hasDocstring",kind:"boolNotFalse"},isdocumented:{field:"isDocumented",kind:"boolNotFalse"},isstale:{field:"isStale",kind:"boolNotFalse"},minimports:{field:"minImports",kind:"int"},maximports:{field:"maxImports",kind:"int"},minsize:{field:"minSize",kind:"int"},maxsize:{field:"maxSize",kind:"int"},limit:{field:"limit",kind:"int"},mincoverage:{field:"minCoverage",kind:"int"},maxcoverage:{field:"maxCoverage",kind:"int"},minexportusage:{field:"minExportUsage",kind:"float"},maxexportusage:{field:"maxExportUsage",kind:"float"},mincomplexity:{field:"minComplexity",kind:"int"},maxcomplexity:{field:"maxComplexity",kind:"int"},mincognitivecomplexity:{field:"minCognitiveComplexity",kind:"int"},maxcognitivecomplexity:{field:"maxCognitiveComplexity",kind:"int"},mincommits:{field:"minCommits",kind:"int"},maxcommits:{field:"maxCommits",kind:"int"}};function ud(t,e,n,r){let s=t;switch(n){case"string":s[e]=r;break;case"int":s[e]=parseInt(r,10);break;case"float":s[e]=parseFloat(r);break;case"boolNotFalse":s[e]=r.toLowerCase()!=="false";break;case"boolIsTrue":s[e]=r.toLowerCase()==="true";break}}function wc(t,e){let n=e.indexOf(":");if(n===-1)return;let r=e.slice(0,n).trim().toLowerCase(),s=e.slice(n+1).trim();if(!r||!s)return;if(r==="tag"||r==="tags"){s.includes("+")?t.allTags=[...t.allTags??[],...s.split("+")]:t.tags=[...t.tags??[],s];return}if(r==="sort"){t.sort=s;return}if(r==="sortdir"){t.sortDir=s.toLowerCase()==="asc"?"asc":"desc";return}let i=pd[r];i&&ud(t,i.field,i.kind,s)}function fd(t){let e=[];for(let n of t.split("|")){let r=n.trim();if(!r)continue;let s={};wc(s,r),Object.keys(s).length>0&&e.push(s)}return e}var Cc="any(";function Hn(t){let e={},n=t.split(",");for(let r of n){let s=r.trim();if(s.toLowerCase().startsWith(Cc)&&s.endsWith(")")){let i=s.slice(Cc.length,-1),o=fd(i);o.length>0&&(e.any=[...e.any??[],...o]);continue}wc(e,r)}return e}var ui=h(require("fs/promises")),jc=h(require("path"));var rr=h(require("path")),Ht=h(require("typescript"));var Fc=h(require("path"));var Tc=h(require("path")),P=h(require("typescript")),Ec=new Set(["describe","test","it"]);function je(t,e){let n=t[e];if(n===void 0)throw new Error(`Index ${e} out of bounds (length ${t.length})`);return n}function Vs(t){let e=[];for(let n of t.statements){if(!P.default.isExpressionStatement(n))continue;let r=n.expression;if(!P.default.isCallExpression(r))continue;let s=r.expression;P.default.isIdentifier(s)&&Ec.has(s.text)&&e.push(r),P.default.isPropertyAccessExpression(s)&&P.default.isIdentifier(s.expression)&&Ec.has(s.expression.text)&&e.push(r)}return e}function Qs(t,e,n){for(let r of t.arguments){if(!P.default.isObjectLiteralExpression(r))continue;let s=r.properties.find(i=>P.default.isPropertyAssignment(i)&&P.default.isIdentifier(i.name)&&i.name.text===e);if(!(!s||!P.default.isArrayLiteralExpression(s.initializer)))return s.initializer.elements.filter(P.default.isStringLiteral).map(i=>i.text)}return null}function Ys(t,e,n,r){if(t.arguments.length===0)return null;for(let i=1;i<t.arguments.length;i++){let o=je(t.arguments,i);if(!P.default.isObjectLiteralExpression(o))continue;let a=o.properties.find(l=>P.default.isPropertyAssignment(l)&&P.default.isIdentifier(l.name)&&l.name.text===e);if(a)return{start:a.initializer.getStart(r),end:a.initializer.getEnd(),text:n};let c=o.getEnd()-1;return{start:c,end:c,text:`${o.properties.length>0?", ":""}${e}: ${n}`}}let s=je(t.arguments,t.arguments.length-1);return{start:s.getStart(r),end:s.getStart(r),text:`{ ${e}: ${n} }, `}}function Xs(t,e,n){let r=t.arguments;for(let s=1;s<r.length;s++){let i=je(r,s);if(!P.default.isObjectLiteralExpression(i))continue;let o=i.properties.findIndex(c=>P.default.isPropertyAssignment(c)&&P.default.isIdentifier(c.name)&&c.name.text===e);if(o<0)continue;if(i.properties.length===1)return{start:je(r,s-1).getEnd(),end:i.getEnd(),text:""};let a=je(i.properties,o);return o===i.properties.length-1?{start:je(i.properties,o-1).getEnd(),end:a.getEnd(),text:""}:{start:a.getStart(n),end:je(i.properties,o+1).getStart(n),text:""}}return null}function Zs(t,e){let n=[...e].sort((s,i)=>i.start-s.start),r=t;for(let s of n)r=r.slice(0,s.start)+s.text+r.slice(s.end);return r}function qs(t){return`[${t.map(e=>JSON.stringify(e)).join(", ")}]`}var se=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);function gd(t){return t.map(e=>e.startsWith("@")?e.slice(1):e)}function Jn(t,e,n,r){let s=P.default.createSourceFile(Tc.default.basename(t),e,P.default.ScriptTarget.Latest,!0),i=Vs(s),[o]=i;if(!o)return e;let a=Qs(o,r,s),c=[...n].sort();if(a!==null&&JSON.stringify(gd(a).sort())===JSON.stringify(c))return e;let l=qs(c.map(u=>`@${u}`)),p=i.flatMap(u=>{let f=n.length===0?Xs(u,r,s):Ys(u,r,l,s);return f?[f]:[]});return p.length>0?Zs(e,p):e}var Vn=class{name="cypress";canHandle(e){return se.has(Fc.default.extname(e).toLowerCase())}apply(e,n,r){return Jn(e,n,r,"tags")}};var Dc=h(require("path")),ei=/# <mokosh-tags>[\s\S]*?# <\/mokosh-tags>\n*/,ti=/^@([a-zA-Z0-9_-]+)/gm;function dd(t){return`${["# <mokosh-tags>",...t.map(e=>`@${e}`),"# </mokosh-tags>"].join(`
|
|
28
37
|
`)}
|
|
29
38
|
|
|
30
|
-
`}function
|
|
31
|
-
`}function
|
|
32
|
-
${
|
|
39
|
+
`}function hd(t){let e=new Set;ti.lastIndex=0;let n=ti.exec(t);for(;n!==null;)n[1]&&e.add(n[1]),n=ti.exec(t);return e}var Qn=class{name="gherkin";canHandle(e){return Dc.default.extname(e).toLowerCase()===".feature"}apply(e,n,r){let s=n.replace(ei,""),i=hd(s),o=r.filter(c=>!i.has(c)),a=o.length>0?dd(o):"";return ei.test(n)?n.replace(ei,a):a?n.replace(/^(Feature:)/m,`${a}$1`):n}};function Pc(t,e){let n=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/"),s="";for(let i=0;i<n.length;i++){let o=n[i];o==="*"?n[i+1]==="*"?(s+=".*",i++):s+="[^/]*":o==="?"?s+="[^/]":o!==void 0&&(s+=o.replace(/[.+^${}()|[\]\\]/g,"\\$&"))}return new RegExp(`^${s}$`).test(r)}var Ac=h(require("path")),ni=/^\/\/go:build mokosh_[^\n]+\n/m,yd=/^package\s+\S+/m;function xd(t){return`//go:build ${t.map(n=>`mokosh_${n}`).join(" || ")}
|
|
40
|
+
`}function bd(t){let e=ni.exec(t);if(!e)return null;let n=e[0]??"",r=/mokosh_([a-zA-Z0-9_-]+)/g,s=[],i=r.exec(n);for(;i!==null;)i[1]&&s.push(i[1]),i=r.exec(n);return s}var Yn=class{name="go";canHandle(e){return Ac.default.basename(e).endsWith("_test.go")}apply(e,n,r){let s=bd(n),i=[...r].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(i))return n;if(r.length===0)return n.replace(ni,"");let o=xd(i);if(s!==null)return n.replace(ni,o);let a=yd.exec(n);if(!a)return n;let c=a.index;return`${n.slice(0,c)+o}
|
|
41
|
+
${n.slice(c)}`}};var Rc=h(require("path"));var kd=/^\/\*\*\n(?: \* @group .+\n)+ \*\/\n+/,ri=/^ \* @group (.+)$/gm;function Sd(t){return`${["/**",...t.map(e=>` * @group ${e}`)," */"].join(`
|
|
33
42
|
`)}
|
|
34
43
|
|
|
35
|
-
`}function
|
|
44
|
+
`}function vd(t){let e=[];ri.lastIndex=0;let n=ri.exec(t);for(;n!==null;)n[1]&&e.push(n[1]),n=ri.exec(t);return e}var Xn=class{name="jest";canHandle(e){return se.has(Rc.default.extname(e).toLowerCase())}apply(e,n,r){let s=kd.exec(n),i=s?vd(s[0]):null,o=[...r].sort();if(i!==null&&JSON.stringify([...i].sort())===JSON.stringify(o))return n;let a=s?n.slice(s[0].length):n;return r.length===0?a:Sd(o)+a}};var si=h(require("path")),Cd="// mokosh:tags",ii=/^\/\/ mokosh:tags\n(?:[ \t]*@Tag\("[^"]*"\)\n)*/m,wd=/\/src\/(test|androidTest|integrationTest|it)\//,Ed=/(Test|Tests|Spec|IT)\.(java|groovy|kt)$/,Td={importLine:"import org.junit.jupiter.api.Tag;",importRe:/^import org\.junit\.jupiter\.api\.Tag;?\n/m,typeDeclRe:/^(?:public\s+|final\s+|abstract\s+|sealed\s+|non-sealed\s+|strictfp\s+)*(?:class|interface|enum|record|@interface)\s+\w+/m,lastImportRe:/^import\s+[^\n]+;\n(?![\s\S]*^import\s)/m,packageRe:/^package\s+[^\n]+;\n/m},Fd={importLine:"import org.junit.jupiter.api.Tag",importRe:/^import org\.junit\.jupiter\.api\.Tag;?\n/m,typeDeclRe:/^(?:public\s+|private\s+|protected\s+|internal\s+|open\s+|abstract\s+|final\s+|sealed\s+|data\s+|inner\s+|value\s+|annotation\s+)*(?:enum\s+)?(?:class|interface|object)\s+\w+/m,lastImportRe:/^import\s+[^\n]+\n(?![\s\S]*^import\s)/m,packageRe:/^package\s+[^\n]+\n/m};function Dd(t){let e=ii.exec(t);if(!e)return null;let n=[],r=/@Tag\("([^"]*)"\)/g,s=r.exec(e[0]);for(;s!==null;)s[1]&&n.push(s[1]),s=r.exec(e[0]);return n}function Pd(t){return`${Cd}
|
|
36
45
|
${t.map(e=>`@Tag("${e}")`).join(`
|
|
37
46
|
`)}
|
|
38
|
-
`}function
|
|
39
|
-
`+t.slice(
|
|
40
|
-
`+
|
|
41
|
-
`+t.slice(
|
|
42
|
-
`+t}function
|
|
47
|
+
`}function Nc(t,e){if(e.importRe.test(t))return t;let n=e.lastImportRe.exec(t);if(n){let s=n.index+n[0].length;return t.slice(0,s)+e.importLine+`
|
|
48
|
+
`+t.slice(s)}let r=e.packageRe.exec(t);if(r){let s=r.index+r[0].length;return t.slice(0,s)+`
|
|
49
|
+
`+e.importLine+`
|
|
50
|
+
`+t.slice(s)}return e.importLine+`
|
|
51
|
+
`+t}function Ad(t,e){return/@Tag\b/.test(t)?t:t.replace(e.importRe,"")}var Zn=class{name="junit";canHandle(e){let n=e.replace(/\\/g,"/"),r=si.default.extname(n).toLowerCase();return r!==".java"&&r!==".groovy"&&r!==".kt"?!1:wd.test(n)||Ed.test(n)}apply(e,n,r){let s=si.default.extname(e.replace(/\\/g,"/")).toLowerCase()===".kt"?Fd:Td,i=Dd(n),o=[...r].sort();if(i!==null&&JSON.stringify([...i].sort())===JSON.stringify(o))return n;if(r.length===0)return i===null?n:Ad(n.replace(ii,""),s);let a=Pd(o);if(i!==null)return Nc(n.replace(ii,a),s);let c=s.typeDeclRe.exec(n);if(!c)return n;let l=n.slice(0,c.index)+a+n.slice(c.index);return Nc(l,s)}};var Mc=h(require("path"));var qn=class{name="playwright";canHandle(e){return se.has(Mc.default.extname(e).toLowerCase())}apply(e,n,r){return Jn(e,n,r,"tag")}};var Ic=h(require("path")),oi=/^pytestmark\s*=\s*.+$/m,Rd=/^import pytest\s*$/m;function Nd(t){let e=t.map(n=>`pytest.mark.${n}`).join(", ");return t.length===1?`pytestmark = pytest.mark.${t[0]}`:`pytestmark = [${e}]`}function Md(t){let e=oi.exec(t);if(!e)return null;let n=e[0],r=[],s=/pytest\.mark\.([a-zA-Z0-9_-]+)/g,i=s.exec(n);for(;i!==null;)i[1]&&r.push(i[1]),i=s.exec(n);return r}var er=class{name="pytest";canHandle(e){return Ic.default.extname(e).toLowerCase()===".py"}apply(e,n,r){let s=Md(n),i=[...r].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(i))return n;if(r.length===0)return n.replace(oi,"").replace(/\n{3,}/g,`
|
|
43
52
|
|
|
44
|
-
`);let
|
|
45
|
-
`,
|
|
53
|
+
`);let o=Nd(i);if(s!==null)return n.replace(oi,o);let a=Rd.test(n),c=Id(n),l=n.slice(0,c),p=n.slice(c),u=a?"":`import pytest
|
|
54
|
+
`,f=l.endsWith(`
|
|
46
55
|
|
|
47
56
|
`)?"":`
|
|
48
|
-
`;return`${l+
|
|
49
|
-
${p}`}};function
|
|
50
|
-
`),
|
|
51
|
-
`;if(s!==null)return
|
|
52
|
-
`)}}invalidate(e){let r=this.graphs.has(e)||this.workspaceGraphs.has(e);return this.graphs.delete(e),this.workspaceGraphs.delete(e),this.changeImpactCaches.delete(e),this.dirtyRoots.delete(e),this.duplicationTokenCaches.delete(e),this.configs.delete(e),r}};var H=g(require("path"));var Mi=g(require("fs")),Li=g(require("os")),Yt=g(require("path"));function b(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}function _i(t){if(!Yt.default.isAbsolute(t))throw new Error("root must be an absolute path");let e=Yt.default.resolve(t),r=Li.default.homedir();if(e!==r&&!e.startsWith(r+Yt.default.sep))throw new Error("root must be within the user home directory");let n;try{n=Mi.default.statSync(e)}catch{throw new Error("root does not exist")}if(!n.isDirectory())throw new Error("root is not a directory")}async function Gi(t,e){let{root:r,entryPoints:n}=e;if(!t.isConfigured(r)){let m=De(r,{allowJs:!1});cr(m),t.storeConfig(r,m)}if(n.length===0){let m=tt(r);if(m.type!=="none"){let h=t.getConfig(r),y=await t.getOrBuildWorkspace(r,J(h));t.storeLastAnalyze(r,{kind:"workspace"}),t.startWatching(r);let v=Array.from(y.packages.values()).map(({graph:x,pkg:k})=>({package:k.name,relativeRoot:k.relativeRoot,nodeCount:x.nodes.size}));return b({monorepoType:m.type,packageCount:y.packages.size,packages:v})}}let s=n.map(m=>H.default.resolve(r,m)),o=t.getConfig(r),i=o?.coverageReportPath?mr(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((m,h)=>(m[h.category]=(m[h.category]??0)+1,m),{}),p=a.findCycles(),u=Jr(a);return b({nodeCount:c.nodes.length,categories:l,cycles:p,languageCoverage:u})}async function Oi(t,e){let{root:r,file:n,depth:s=1,withMeta:o=!1}=e,i=await t.ensureFresh(r),a=Zr(i,n,s),c=o?a.map(l=>({...l,...Qe(i,l.path)})):a;return b({file:n,dependencies:c})}async function ji(t,e){let{root:r,file:n,withMeta:s=!1}=e,o=await t.ensureFresh(r),i=Ye(o,n),a=s?i.map(c=>({...c,...Qe(o,c.path)})):i;return b({file:n,dependents:a})}async function zi(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=m=>a?m.map(h=>({path:h,...Qe(c,h)})):m;if(o){let m=t.getOrBuildChangeImpact(r),h=Sr(m,n),y=s?h.filter(x=>c.nodes.get(x)?.category==="test"):h,v=l(y);return b({file:n,affected:v,count:v.length})}let p=Xr(c,n,{testsOnly:s,changedSymbols:i}),u=l(p);return b({file:n,affected:u,count:u.length})}async function Wi(t,e){let{root:r,baseRef:n,headRef:s,minDuplicateLines:o,complexityMetric:i,complexityThreshold:a}=e,c=await t.ensureFresh(r),l=e.entryPoints??t.getLastEntryPoints(r)?.map(u=>H.default.relative(r,u))??[],p=await on(r,n,c,{headRef:s,entryPoints:l,minDuplicateLines:o,complexityMetric:i,complexityThreshold:a,maxCoveragePct:e.maxCoveragePct,...J(t.getConfig(r))});return e.detail==="full"?b(p):b(sn(p,{metric:i,maxItems:e.maxItems}))}async function $i(t,e){let{root:r,file:n,depth:s=1,withEdgeDetail:o=!1}=e,i=await t.ensureFresh(r),a=en(i,n,{depth:s,withEdgeDetail:o});return b({file:n,callers:a,count:a.length})}async function Bi(t,e){let{root:r,entryPoints:n}=e,s=n?await t.getOrBuild(r,n.map(c=>H.default.resolve(r,c))):await t.ensureFresh(r),o=t.getConfig(r),i=Di(r,{additionalIgnoreDirs:o?.ignoreDirs??[],additionalExtensions:o?.extensions??[]}),a=s.findUnusedFiles(i);return b({unusedFiles:a,count:a.length})}async function Hi(t,e){let{root:r}=e,n=await t.ensureFresh(r),s=new Map;for(let i of n.nodes.values())for(let a of i.tags)s.set(a.name,(s.get(a.name)??0)+1);let o=[...s.entries()].map(([i,a])=>({name:i,count:a})).sort((i,a)=>a.count-i.count);return b({tags:o,count:o.length})}async function Ui(t,e){let{root:r,coverageThreshold:n}=e,s=await t.ensureFresh(r),o=t.getConfig(r),i=n??o?.coverageThreshold??80;if(!te(s))return b({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let a=[...s.nodes.values()].filter(c=>c.category!=="test"&&c.category!=="config").filter(c=>c.coveragePct!==void 0&&c.coveragePct<i).map(c=>({file:c.path,coveragePct:c.coveragePct}));return b({threshold:i,uncovered:a,count:a.length})}async function Ji(t,e){let{root:r}=e,s=[...(await t.ensureFresh(r)).nodes.values()].filter(o=>o.type==="markdown"&&o.staleFor&&o.staleFor.length>0).map(o=>({doc:o.path,staleFor:o.staleFor}));return b({staleDocs:s,count:s.length})}async function Ki(t,e){let{root:r,metric:n="cognitiveComplexity",threshold:s=10,limit:o=20}=e,i=await t.ensureFresh(r),a=we(i,{metric:n,threshold:s,limit:o});return b({metric:n,threshold:s,functions:a,count:a.length})}async function qi(t,e){let{root:r,metric:n="cognitiveComplexity",minComplexity:s=10,maxCoveragePct:o=50,minChurn:i=0,limit:a=20}=e,c=await t.ensureFresh(r);if(!te(c))return b({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let{hotspots:l,count:p,churnDataAvailable:u}=Ee(c,{metric:n,minComplexity:s,maxCoveragePct:o,minChurn:i,limit:a});return b({metric:n,minComplexity:s,maxCoveragePct:o,minChurn:i,churnDataAvailable:u,hotspots:l,count:p})}async function Vi(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??[...P,...t.getConfig(r)?.ignoreDirs??[]],{groups:l}=await Ce(a,r,{minLines:n,ignoreLiterals:s,maxPunctuationRatio:o,limit:i,ignoreDirs:c,tokenCache:await t.getDuplicationTokenCache(r)});return t.flushDuplicationTokenCache(r),b({minLines:n,groups:l,count:l.length})}async function Qi(t,e){let{root:r,changedFiles:n,base:s,featureThreshold:o,format:i="tags"}=e,a=await t.ensureFresh(r),c=n??new gt().getChangedFiles(r,s).map(u=>H.default.relative(r,H.default.resolve(r,u))),l=o!==void 0?{featureDetection:{minOutDegree:o}}:void 0;if(i==="paths"){let u=On(a,c,l);return b({changedFiles:c,affectedTests:u,count:u.length})}let p=Gn(a,c,l);return b({changedFiles:c,proposedTags:p})}async function Yi(t,e){let{root:r,entryPoints:n,featureThreshold:s}=e,o=n?await t.getOrBuild(r,n.map(c=>H.default.resolve(r,c))):await t.ensureFresh(r),i=ne(o.nodes,s!==void 0?{minOutDegree:s}:void 0),a=Array.from(i.values()).sort((c,l)=>l.outDegree-c.outDegree);return b({features:a,count:a.length})}async function Zi(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=>H.default.resolve(r,l))):await t.ensureFresh(r),c=Mt(a.serialize(),Lt(s));return o?b(ut.serialize(A.deserialize(c))):i?b(tn(c)):b(c)}async function Xi(t,e){let{root:r}=e,n=await t.ensureFreshWorkspace(r);return b(rn(n))}async function ea(t,e){let{root:r,file:n}=e,o=(await t.ensureFreshWorkspace(r)).getAffectedAcrossPackages(n);return b({file:n,affected:o,count:o.length})}function ta(t,e){let{root:r}=e,n=t.invalidate(r);return b({root:r,cleared:n,message:n?"Cache cleared. Call analyze to rebuild.":"No cache was present for this root."})}async function ra(t,e){let{root:r,type:n}=e,s=await t.ensureFresh(r),o=ln(s);if(n)return b(pn(o,n));let i=Array.from(o.types.values());return b({count:i.length,types:i})}async function na(t,e){let{root:r,paths:n,minOutDegree:s}=e,o=await t.ensureFresh(r),i=an(o,s!==void 0?{minOutDegree:s}:void 0);if(n?.length){let c=n.map(l=>i.get(l)).filter(Boolean);return b({count:c.length,modules:c})}let a=Array.from(i.values());return b({count:a.length,modules:a})}async function sa(t,e){let{root:r,minOutDegree:n}=e,s=await t.ensureFresh(r),o=Xe(s,n!==void 0?{minOutDegree:n}:void 0),i=Object.fromEntries(o.features);return b({features:i,unassigned:o.unassigned})}async function oa(t,e){let{root:r,function:n}=e,s=await t.ensureFresh(r);return b(xr(s,n))}async function ia(t,e){let{root:r,name:n}=e,s=await t.ensureFresh(r),o=cn(s,n);return b({name:n,matches:o,count:o.length})}async function aa(t,e){let{root:r,entryPoints:n}=e,s=await t.ensureFresh(r),o=n?.length?n:hr(s,r);if(o.length===0)throw new Error("No entry points found. Pass entryPoints explicitly or ensure package.json has a main/exports field.");return b(yr(s,o))}async function ca(t,e){let r=await t.ensureFresh(e.root),n=await _n(r,e.root,{dryRun:e.dryRun??!1});return b(n)}var la=[{name:"analyze",description:"Build the dependency graph for a project from entry points. Returns a summary of node count, categories, and cycles. Must be called before get_dependencies, get_dependents, get_affected, or propose_tags. Pass an empty entryPoints array to auto-detect a monorepo (pnpm/npm/yarn/Nx/Turborepo) and build per-package graphs \u2014 use get_workspace_packages and get_workspace_affected for monorepo queries.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root (or monorepo root)"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root (e.g. ['src/index.ts']). Pass [] to trigger monorepo auto-detection."}},required:["root","entryPoints"]}},{name:"get_dependencies",description:"Get files that a given file imports (outgoing traversal). depth=1 returns immediate imports; omit for the full transitive tree. Each result includes the specific symbols imported from that file (when known).",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},depth:{type:"number",description:"Max traversal depth (default: 1)"},withMeta:{type:"boolean",description:"Include each result's category and export names alongside the path (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"get_dependents",description:"Get files that directly import a given file (one-hop incoming edges). Each result includes the specific symbols that dependent file imports from this file (when known).",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},withMeta:{type:"boolean",description:"Include each result's category and export names alongside the path (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"get_affected",description:"Get all files transitively affected if a given file changes \u2014 full incoming traversal upward. Use before a refactor to understand blast radius. See docs/mcp.md for details on the testsOnly, cached, changedSymbols, and withMeta options.",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},testsOnly:{type:"boolean",description:"Return only test/spec files (default: false)"},cached:{type:"boolean",description:"Use a pre-computed impact cache for O(1) lookup instead of graph traversal. Cache is built lazily on first use and reused for the session (default: false)."},changedSymbols:{type:"array",items:{type:"string"},description:"Restrict blast-radius to files that import at least one of these symbols. Omit to treat the whole file as changed (conservative, same as before)."},withMeta:{type:"boolean",description:"Return each affected file as { path, category, exports } instead of a bare path string (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"compare_branches",description:"Compare the current graph (root) against baseRef, for reviewing a PR/branch: file diff, stale post-rename references, and deltas for duplication, complexity, doc drift, and coverage/risk hotspots. Returns a compact summary by default (verdict + headline + capped delta lists); pass detail:'full' for every entry. See docs/mcp.md for details. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},baseRef:{type:"string",description:"Git ref to compare against, e.g. 'main', 'origin/main', or a commit sha"},headRef:{type:"string",description:"Git ref to label the head side of the comparison (default: 'HEAD'). The graph itself always comes from the already-analyzed root, not a checkout of this ref."},entryPoints:{type:"array",items:{type:"string"},description:"Entry points to build the base-ref graph from, relative to root. Defaults to the entry points from the last analyze() call for this root."},minDuplicateLines:{type:"number",description:"Minimum duplicated block size, in source lines, for the duplication delta (default: 6)"},complexityMetric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which per-function score drives the complexity delta (default: cognitiveComplexity)"},complexityThreshold:{type:"number",description:"Minimum per-function score to count as a complexity hotspot (default: 10)"},maxCoveragePct:{type:"number",description:"Maximum containing-file coverage % to count as a risk hotspot (default: 50)"},detail:{type:"string",enum:["summary","full"],description:"'summary' (default): verdict, headline, and each delta list capped at maxItems with true counts; empty sections omitted. 'full': the complete BranchComparison with every entry."},maxItems:{type:"number",description:"In summary mode, max entries kept per delta list (complexity/duplication/doc-drift/coverage); the true count is always reported alongside (default: 8). Stale references are never truncated."}},required:["root","baseRef"]}},{name:"get_callers",description:"Get files whose exported functions call into a given file (call-graph dependents). More precise than get_affected: only files with actual runtime call edges, not mere imports. Requires prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to project root"},file:{type:"string",description:"File path relative to root"},depth:{type:"number",description:"Max traversal depth (default: 1)"},withEdgeDetail:{type:"boolean",description:"Include from/to function names per edge (default: false)"}},required:["root","file"]}},{name:"find_unused",description:"Find files in the project that are not reachable from any entry point. Useful before cleanup passes. Omit entryPoints to reuse the cached graph from a prior analyze() call instead of rebuilding.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root. Omit to reuse the cached graph from a prior analyze() call."}},required:["root"]}},{name:"list_tags",description:"List every distinct tag name present in the graph, with how many nodes carry each one. Call this before querying with tag:<name> to avoid a speculative filter silently returning zero results. Includes all tag kinds \u2014 a superset of what query's slim mode keeps (slim only retains comment-marker and import tags).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"}},required:["root"]}},{name:"find_uncovered",description:"Find non-test files whose line coverage is below the configured threshold. Requires a prior analyze() call and coverageReportPath set in mokosh.config. coverageThreshold overrides the config default (default: 80).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},coverageThreshold:{type:"number",description:"Line-coverage % below which a file is considered uncovered. Overrides config value."}},required:["root"]}},{name:"check_doc_drift",description:"Find markdown docs whose referenced files changed more recently than the doc itself \u2014 a commit-recency heuristic for stale documentation, not a content diff. Requires a prior analyze() call with gitStats: true in mokosh.config (otherwise no file has commit-timestamp data and nothing is flagged). See docs/adr-009-markdown-parsing.md for known limitations.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"}},required:["root"]}},{name:"find_complex_functions",description:"Find individual functions/methods above a cognitive (or cyclomatic) complexity threshold, sorted worst-first. Requires a prior analyze() call. Populated for TypeScript/JavaScript, Go, and Python.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},metric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which score to threshold/sort on (default: cognitiveComplexity)"},threshold:{type:"number",description:"Minimum score to include (default: 10)"},limit:{type:"number",description:"Max results to return, worst-first (default: 20)"}},required:["root"]}},{name:"find_risk_hotspots",description:"Find functions that are complex, in a poorly-covered file, and \u2014 when gitStats is enabled in mokosh.config \u2014 in a frequently-changed file. Requires a prior analyze() call and coverageReportPath set in mokosh.config; errors if no coverage data was loaded. Churn filtering is skipped (churnDataAvailable: false) when gitStats wasn't enabled, since complexity + low coverage alone is still a meaningful signal.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},metric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which per-function score to filter/sort on (default: cognitiveComplexity)"},minComplexity:{type:"number",description:"Minimum per-function complexity score to include (default: 10)"},maxCoveragePct:{type:"number",description:"Maximum containing-file coverage % to include (default: 50)"},minChurn:{type:"number",description:"Minimum containing-file 90-day commit count to include (default: 0). Ignored when gitStats wasn't enabled at analyze time."},limit:{type:"number",description:"Max results to return, worst-first by metric (default: 20)"}},required:["root"]}},{name:"find_duplicates",description:"Find duplicated code blocks across the project, largest-first. CSS/SCSS/Less are matched structurally by rule body; every other parsed language is tokenized and matched via suffix array. Lock files and ignored directories are always excluded. Requires a prior analyze() call. See docs/mcp.md for matching-strategy, normalization, and caching details.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},minLines:{type:"number",description:"Minimum duplicated block size in lines to report (default: 6)"},ignoreLiterals:{type:"boolean",description:"Normalize string/number literals too, not just identifiers, so only structural shape drives a match (default: true). Set false for stricter, exact-text-only matching."},maxPunctuationRatio:{type:"number",description:"Maximum fraction of a token-shingled block's window that may be object/array-literal structural punctuation ({ } : , [ ]) (default: 0.5). Filters out blocks that are mostly schema/object-literal shape instead of substantive shared logic. Does not apply to the CSS/Less/SCSS structural comparator. Set 1 to disable."},ignoreDirs:{type:"array",items:{type:"string"},description:"Directory names to exclude, matched against any path segment (default: DEFAULT_IGNORE_DIRS merged with this root's configured ignoreDirs, if any). Pass [] to disable."},limit:{type:"number",description:"Max duplicate blocks to return, largest-first (default: 50)"}},required:["root"]}},{name:"propose_tags",description:"Propose what to run based on changed files. Pass changedFiles explicitly or omit to use git diff. format='tags' (default) returns test tags for CI tag-filtering; format='paths' returns test file paths ready to pipe directly to a test runner (e.g. vitest). Feature hubs act as traversal boundaries in both modes.",inputSchema:{type:"object",properties:{root:{type:"string"},changedFiles:{type:"array",items:{type:"string"},description:"Changed files relative to root. Omit to read from git diff."},base:{type:"string",description:"Diff against this ref (e.g. 'origin/main') instead of only local working-tree/staged/untracked changes. Ignored when changedFiles is given. Needed in CI, where the checkout is already clean."},featureThreshold:{type:"number",description:"Min importers for a file to be treated as a feature hub (default: 5). A hub short-circuits traversal and emits a feature:<name> tag instead of all downstream tags."},format:{type:"string",enum:["tags","paths"],description:"Output format: 'tags' returns test tag names for CI filtering (default); 'paths' returns test file paths to pipe to a test runner."}},required:["root"]}},{name:"detect_features",description:"Identify feature hub files \u2014 non-test files that import many other internal modules (orchestrators / aggregators like src/parser.ts or src/cli/runner.ts). Returns a list sorted by import count descending.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root. Omit to use the cached graph."},featureThreshold:{type:"number",description:"Min internal imports a file must have to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"query",description:"Filter the graph by category, tag, path, or other node metadata. Returns matching nodes as JSON or a Mermaid diagram. If entryPoints is omitted the cached graph from a prior 'analyze' call is used. See docs/mcp.md for the full query DSL reference.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry points to build the graph. Omit to reuse the cached graph from a prior 'analyze' call."},filter:{type:"string",description:"Query string e.g. 'category:logic' or 'category:logic,tag:auth'. Supports: category, type, tag, path, external, importsFile, importedBy, minImports, maxImports, minSize, maxSize, hasDocstring, minCoverage, maxCoverage, minExportUsage, maxExportUsage, minComplexity, maxComplexity, minCognitiveComplexity, maxCognitiveComplexity, minCommits, maxCommits, isDocumented, isStale, lastAuthor. OR logic: any(key:val|key:val) matches if any single-key clause holds, ANDed with the rest of the query. sort: size|imports|commitCount90d|exportUsage|complexity|cognitiveComplexity, with sortDir: asc|desc (default desc). limit: N."},mermaid:{type:"boolean",description:"Return a Mermaid diagram (default: false)"},slim:{type:"boolean",description:"Compact response mode (default: true). Returns export names, meaningful tags, and a flat importsFiles path list \u2014 no edge objects, no mtime/size. Tags are filtered to kinds comment-marker and import only; function/class/variable/type/library tags are dropped in slim output. Use list_tags to see the full tag inventory, or pass slim: false to get every tag kind on matching nodes."}},required:["root","filter"]}},{name:"get_workspace_packages",description:"List all workspace packages detected in a monorepo, with their node counts and inter-package dependencies. Requires a prior analyze() call with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"}},required:["root"]}},{name:"get_workspace_affected",description:"Cross-package blast-radius analysis. Returns every file that could be affected if a given file changes, annotated with the package it belongs to. Requires a prior analyze() call with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"},file:{type:"string",description:"Monorepo-root-relative path of the changed file (e.g. 'packages/shared/src/utils.ts')"}},required:["root","file"]}},{name:"get_type_graph",description:"Return type-level relationships for the project. Without a type name, returns an inventory of all interfaces, classes, enums, and type aliases with their file and kind. With a type name, returns which files import that type (usedByFiles) and which types the defining file imports (uses). Requires a prior analyze() call. Only covers TypeScript/JavaScript files.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},type:{type:"string",description:"Exact exported name of the type to look up (e.g. 'FileNode'). Omit to get the full type inventory."}},required:["root"]}},{name:"get_module_responsibility",description:"Return what each file is responsible for: its semantic role, JSDoc description (when present), exported symbol names, and which feature hub it belongs to. Pass specific paths to filter, or omit paths to get all files. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},paths:{type:"array",items:{type:"string"},description:"Project-relative file paths to include. Omit to return all files."},minOutDegree:{type:"number",description:"Min imports for a file to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"get_feature_graph",description:"Group files by domain: returns which files each feature hub (high-import orchestrator) transitively owns. Each file is assigned to the most specific hub that can reach it (lowest out-degree wins). Use this instead of a full query when answering 'what files are in the X feature/module?' \u2014 it returns only paths grouped by hub, so it's substantially smaller than a full graph query for the same question; compare output sizes yourself if you need an exact figure for your repo.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},minOutDegree:{type:"number",description:"Minimum internal imports a file must have to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"get_call_graph",description:"Look up callers and callees for a named function. Returns the file that defines the function, all files/functions that call it, and all files/functions it calls. Always requires a function name \u2014 never returns the full call graph unfiltered. Call edges are only populated for TypeScript/JavaScript files.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},function:{type:"string",description:"Exact name of the function to look up (e.g. 'parseFile')."}},required:["root","function"]}},{name:"find_symbol",description:"Find every file that exports a symbol by exact name, with the best available usage info per match. Precision varies by the defining file's language \u2014 check each match's `precision` field ('call' | 'file-level') before trusting caller/importer results as symbol-exact. See docs/mcp.md for per-language coverage details.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},name:{type:"string",description:"Exact export name to look up (e.g. 'parseFile')."}},required:["root","name"]}},{name:"get_api_surface",description:"Build the API surface report for a project: every exported symbol resolved to its defining file and kind, partitioned into internalFiles, unreachableFromEntry, and testFiles. Requires a prior analyze() call. When entryPoints is omitted, auto-detects from package.json exports/main/module. See docs/mcp.md for the export* expansion and partition semantics.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},entryPoints:{type:"array",items:{type:"string"},description:"Project-relative paths of public entry points (e.g. ['src/index.ts', 'src/utils.ts']). Omit to auto-detect from package.json exports / main / module fields."}},required:["root"]}},{name:"clear_cache",description:"Drop the cached dependency graph and loaded mokosh.config.json for a project root, forcing the next analyze() call to rebuild from disk and re-read config. Call this after editing source files OR mokosh.config.json mid-session \u2014 otherwise get_affected, get_dependencies, and other query tools will reason from stale data (or a stale config).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root to invalidate."}},required:["root"]}},{name:"apply_tags",description:"Write @tag annotations into test file source code based on the dependency graph, as an idempotent block \u2014 re-running is safe, the existing block is replaced in place. Use dryRun=true to preview changes without writing to disk. Requires a prior analyze() call. See docs/mcp.md for tag-kind and per-language block syntax details.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root."},dryRun:{type:"boolean",description:"When true, computes which files would change but does not write to disk (default: false)."}},required:["root"]}}];function Xt(){let t=new Qt,e=new pa.Server({name:"mokosh",version:"0.0.1"},{capabilities:{tools:{}}});return e.setRequestHandler(Zt.ListToolsRequestSchema,async()=>({tools:la})),e.setRequestHandler(Zt.CallToolRequestSchema,async r=>{let{name:n,arguments:s}=r.params,o=s,a={analyze:c=>Gi(t,c),get_dependencies:c=>Oi(t,c),get_dependents:c=>ji(t,c),get_affected:c=>zi(t,c),compare_branches:c=>Wi(t,c),get_callers:c=>$i(t,c),find_symbol:c=>ia(t,c),find_unused:c=>Bi(t,c),find_uncovered:c=>Ui(t,c),list_tags:c=>Hi(t,c),check_doc_drift:c=>Ji(t,c),find_complex_functions:c=>Ki(t,c),find_risk_hotspots:c=>qi(t,c),find_duplicates:c=>Vi(t,c),propose_tags:c=>Qi(t,c),detect_features:c=>Yi(t,c),get_type_graph:c=>ra(t,c),get_module_responsibility:c=>na(t,c),get_feature_graph:c=>sa(t,c),get_call_graph:c=>oa(t,c),get_api_surface:c=>aa(t,c),query:c=>Zi(t,c),get_workspace_packages:c=>Xi(t,c),get_workspace_affected:c=>ea(t,c),clear_cache:c=>ta(t,c),apply_tags:c=>ca(t,c)}[n];if(!a)throw new Error(`Unknown tool: ${n}`);try{return _i(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 wf(){let t=Xt(),e=new ua.StdioServerTransport;await t.connect(e)}wf().catch(console.error);0&&(module.exports={createMcpServer});
|
|
57
|
+
`;return`${l+f+u+o}
|
|
58
|
+
${p}`}};function Id(t){let e=t.split(`
|
|
59
|
+
`),n=-1;return e.forEach((s,i)=>{(s.trimStart().startsWith("import ")||s.trimStart().startsWith("from "))&&(n=i)}),n<0?0:e.slice(0,n+1).reduce((s,i)=>s+i.length+1,0)}var Lc=h(require("path")),ai=/^\/\/ mokosh:tags .*\n/m,Ld=/^(?:sealed\s+|abstract\s+|final\s+|private\s+|implicit\s+|case\s+)*(?:class|object|trait)\s+\w+/m,_d=/\/src\/(test|it)\//,Gd=/(Spec|Suite|Test|Props)\.scala$/;function Od(t){let e=ai.exec(t);return e?e[0].replace(/^\/\/ mokosh:tags /,"").trim().split(/\s*,\s*/).filter(Boolean):null}var tr=class{name="scalatest";canHandle(e){let n=e.replace(/\\/g,"/");return Lc.default.extname(n).toLowerCase()!==".scala"?!1:_d.test(n)||Gd.test(n)}apply(e,n,r){let s=Od(n),i=[...r].sort();if(s!==null&&JSON.stringify([...s].sort())===JSON.stringify(i))return n;if(r.length===0)return s===null?n:n.replace(ai,"");let o=`// mokosh:tags ${i.join(", ")}
|
|
60
|
+
`;if(s!==null)return n.replace(ai,o);let a=Ld.exec(n);return a?n.slice(0,a.index)+o+n.slice(a.index):n}};var ci=h(require("path")),li=h(require("typescript"));var jd=/\/\/ <mokosh-tags>[\s\S]*?\/\/ <\/mokosh-tags>\n*/,nr=class{name="vitest";canHandle(e){return se.has(ci.default.extname(e).toLowerCase())}apply(e,n,r){let s=n.replace(jd,""),i=li.default.createSourceFile(ci.default.basename(e),s,li.default.ScriptTarget.Latest,!0),o=Vs(i),[a]=o;if(!a)return s;let c=Qs(a,"tags",i),l=[...r].sort();if(c!==null&&JSON.stringify([...c].sort())===JSON.stringify(l))return s;let p=o.flatMap(u=>{let f=r.length===0?Xs(u,"tags",i):Ys(u,"tags",qs(l),i);return f?[f]:[]});return p.length>0?Zs(s,p):s}};var _c={vitest:()=>new nr,playwright:()=>new qn,cypress:()=>new Vn,jest:()=>new Xn},Wd={"@playwright/test":"playwright",cypress:"cypress","@jest/globals":"jest",vitest:"vitest"};function $d(t){let e=Ht.default.createSourceFile("detect.ts",t,Ht.default.ScriptTarget.Latest,!0);for(let n of e.statements){if(!Ht.default.isImportDeclaration(n)||!Ht.default.isStringLiteral(n.moduleSpecifier))continue;let r=Wd[n.moduleSpecifier.text];if(r)return r}return null}var pi=class{constructor(e,n,r){this.rootDir=e;this.defaultFramework=n;this.frameworkOverrides=r}rootDir;defaultFramework;frameworkOverrides;name="auto";canHandle(e){return se.has(rr.default.extname(e).toLowerCase())}apply(e,n,r){let s=$d(n)??this.matchOverride(e)??this.defaultFramework;return(_c[s]??_c.vitest)().apply(e,n,r)}matchOverride(e){let n=rr.default.relative(this.rootDir,e).split(rr.default.sep).join("/");for(let[r,s]of this.frameworkOverrides)if(Pc(r,n))return s;return null}};function Gc(t="vitest",e={},n=process.cwd()){return[new Qn,new er,new Yn,new Zn,new tr,new pi(n,t,Object.entries(e))]}function Oc(t,e){return e.find(n=>n.canHandle(t))??null}async function zd(t,e,n,r){let s;try{s=await ui.default.readFile(t,"utf8")}catch(a){return{path:t,status:"error",error:String(a)}}let i=Oc(t,r);if(!i)return{path:t,status:"unchanged"};let o=i.apply(t,s,e);return o===s?{path:t,status:"unchanged"}:(n||await ui.default.writeFile(t,o,"utf8"),{path:t,status:"updated"})}async function fi(t,e,n){let r=bt(e),s=r.tagApplier?.framework??"vitest",i=r.tagApplier?.frameworkOverrides??{},o=Gc(s,i,e),a={updated:0,unchanged:0,errors:0,files:[]};for(let c of t.nodes.values()){if(c.category!=="test")continue;let l=new Set,p=[];for(let m of c.tags)we(m)&&(l.has(m.name)||(l.add(m.name),p.push(m.name)));p.sort();let u=jc.default.resolve(e,c.path),f=await zd(u,p,n.dryRun,o);f.path=c.path,a.files.push(f),f.status==="updated"?a.updated++:f.status==="unchanged"?a.unchanged++:a.errors++}return a}var sr=class{isTestNode(e){return e.category==="test"||e.tags.some(n=>n.name==="test")}};function Wc(t,e){return{identifier:e?.identifier??new sr,featureMap:e?.featureDetection===!1?new Map:ke(t.nodes,e?.featureDetection??void 0)}}function $c(t,e,n,r,s){for(let i of e){let o=t.nodes.get(i);if(!o)continue;let a=new Ie(i,["*",...o.exports.map(c=>c.name)]);t.traverse(i,(c,l,p)=>{if(!p)return!0;if(!a.updateAffectedSymbols(c,p))return!1;if(l>0){let u=n.get(c.path);if(u)return r(u),!1}return s(c),!0},{direction:"incoming"})}}function mi(t,e,n){let{identifier:r,featureMap:s}=Wc(t,n),i=new Set;for(let o of e){let a=s.get(o);a&&i.add(a.tag)}return $c(t,e,s,o=>i.add(o.tag),o=>{if(r.isTestNode(o))for(let a of Rr(o.tags))i.add(a)}),Array.from(i)}function gi(t,e,n){let{identifier:r,featureMap:s}=Wc(t,n),i=new Set;return $c(t,e,s,()=>{},o=>{r.isTestNode(o)&&i.add(o.path)}),Array.from(i)}var hi=h(require("crypto")),yi=h(require("fs")),Bc=h(require("os")),pe=h(require("path"));async function Uc(t,e,n=null,r={}){let s=r.silent?void 0:a=>{process.stderr.write(`Processed ${a} files...\r`)},i=pe.default.resolve(t);return await new Ne(i,n,r.pathAliases?new le(i,{pathAliases:r.pathAliases}):void 0,s,r.gitStats??!1,r.coverageMap??new Map,r.parallelParsing??!0,r.additionalIgnoreDirs??[],r.docFiles??null).build(e)}function Bd(t){let e=Number.parseInt(process.env.MOKOSH_WORKSPACE_CONCURRENCY??"",10),n=Number.isFinite(e)&&e>0?e:Bc.default.cpus().length||1;return Math.max(1,Math.min(n,Math.max(1,t)))}function Ud(t,e,n){let r=new Map(e.map(i=>[i.name,[]])),s=[...e].sort((i,o)=>o.root.length-i.root.length);for(let i of n){if(!i.endsWith(".md")&&!i.endsWith(".mdx"))continue;let o=pe.default.join(t,i),a=s.find(c=>o===c.root||o.startsWith(`${c.root}${pe.default.sep}`));a&&r.get(a.name)?.push(o)}return r}function xi(t){let e=or(t),n=hi.default.createHash("sha256");for(let r of[...e].sort())n.update(`${Kc(t,r)}
|
|
61
|
+
`);return{digest:n.digest("hex"),files:e}}function Kc(t,e){try{let n=yi.default.statSync(pe.default.join(t,e));return`${e}\0${n.mtimeMs}\0${n.size}`}catch{return`${e}\0?\0?`}}function bi(t,e,n){let r=[...e].sort((c,l)=>l.relativeRoot.length-c.relativeRoot.length),s=new Map(e.map(c=>[c.name,[]])),i=[];for(let c of n){let l=r.find(p=>ft(c,p));(l?s.get(l.name):i).push(c)}let o=c=>{let l=hi.default.createHash("sha256");for(let p of[...c].sort())l.update(`${Kc(t,p)}
|
|
62
|
+
`);return l.digest("hex")},a=new Map;for(let[c,l]of s)a.set(c,o(l));return{rootDigest:o(i),packageDigests:a}}async function ir(t,e={}){let n=pe.default.resolve(t),r=e.layout??Ut(n),s=e.projectFiles??or(n),i=e.additionalIgnoreDirs??[],o=e.packages?r.packages.filter(k=>e.packages?.includes(k.name)||e.packages?.includes(k.relativeRoot)):r.packages,a=new Map(r.packages.map(k=>[k.name,k.root])),c=new Oe(n,r.type),l=new Re(i),p=Ud(n,o,s),u=Bd(o.length),f=u>1?!1:e.parallelParsing??!0,m=new Array(o.length),d=0,b=async()=>{for(let k=d++;k<o.length;k=d++){let S=o[k],w=e.silent?void 0:_=>{process.stderr.write(`[${S.name}] Processed ${_} files...\r`)},I=new Ne(n,e.previousWorkspace?.packages.get(S.name)?.graph??null,new le(n,{workspaceMap:a,tsconfigSearchPaths:[S.root,n],pathAliases:e.pathAliases,langResolvers:kn({jvm:l})}),w,e.gitStats??!1,new Map,f,i,p.get(S.name)??[]);m[k]=await I.build(S.entryPoints)}};return await Promise.all(Array.from({length:u},b)),o.forEach((k,S)=>{c.addPackage(k,m[S])}),c.annotateCrossPackageEdges(),c}function or(t,e={}){let n=[],r=new Set([...e.ignoreDirs??j,...e.additionalIgnoreDirs??[]]),s=new Set([...e.extensions??kr,...e.additionalExtensions??[]]);function i(o){try{let a=yi.default.readdirSync(o,{withFileTypes:!0});for(let c of a){let l=pe.default.join(o,c.name);c.isDirectory()?r.has(c.name)||i(l):c.isFile()&&s.has(pe.default.extname(c.name).toLowerCase())&&n.push(pe.default.relative(t,l))}}catch{}}return i(t),n}function Jc(t){return Se.default.join(t,xr)}function Kd(t){let e=t.replace(/[^a-zA-Z0-9._-]+/g,"_").replace(/^_+|_+$/g,"")||"pkg",n=Hc.default.createHash("sha1").update(t).digest("hex").slice(0,8);return`${e}-${n}.json`}function Hd(t){try{ie.default.rmSync(Se.default.join(t,yr),{force:!0})}catch{}}function Vc(t,e,n,r=()=>{}){try{let s=Jc(t);ie.default.mkdirSync(s,{recursive:!0});let i=n.serialize(),{rootDigest:o,packageDigests:a}=bi(n.monorepoRoot,i.packages.map(({pkg:u})=>u),e),c=[],l=new Set([yt]);for(let{pkg:u,nodes:f}of i.packages){let m=a.get(u.name)??"",d=JSON.stringify({nodes:f});if(Buffer.byteLength(d)>50331648){c.push({name:u.name,relativeRoot:u.relativeRoot,entryPoints:u.entryPoints,digest:m,nodeCount:f.length,skipped:!0});continue}let b=Kd(u.name);ie.default.writeFileSync(Se.default.join(s,b),d),l.add(b),c.push({name:u.name,relativeRoot:u.relativeRoot,entryPoints:u.entryPoints,file:b,digest:m,nodeCount:f.length})}for(let u of ie.default.readdirSync(s))u.endsWith(".json")&&!l.has(u)&&ie.default.rmSync(Se.default.join(s,u),{force:!0});let p={version:1,monorepoRoot:n.monorepoRoot,type:n.type,rootDigest:o,packages:c};ie.default.writeFileSync(Se.default.join(s,yt),JSON.stringify(p)),Hd(t)}catch(s){r(`failed to persist workspace graph cache: ${s}`)}}function Qc(t,e){try{let n=Jc(t),r=Se.default.join(n,yt);if(!ie.default.existsSync(r))return null;let s=JSON.parse(ie.default.readFileSync(r,"utf-8"));if(s.version!==1||!Array.isArray(s.packages))return null;let{rootDigest:i,packageDigests:o}=bi(s.monorepoRoot,s.packages.map(c=>({name:c.name,relativeRoot:c.relativeRoot})),e);if(i!==s.rootDigest)return null;let a=new Oe(s.monorepoRoot,s.type);for(let c of s.packages){if(c.skipped||!c.file||o.get(c.name)!==c.digest)return null;let l=ie.default.readFileSync(Se.default.join(n,c.file),"utf-8"),{nodes:p}=JSON.parse(l),u=new A(new Map(p.map(f=>[f.path,f])));a.addPackage({name:c.name,relativeRoot:c.relativeRoot,entryPoints:c.entryPoints,root:""},u)}return a}catch{return null}}var Yc=/(?:^|[/\\])(?:node_modules|\.git|dist|build|coverage)(?:[/\\]|$)/;function Xc(t){return z.default.join(t,de,ht)}function Jd(t,e,n){let r=e?.cachePath?z.default.dirname(z.default.resolve(t,e.cachePath)):z.default.join(t,de);if(!n)return z.default.join(r,dr);let s=qc.default.createHash("sha1").update(n).digest("hex").slice(0,8);return z.default.join(r,`duplication-result-${s}.json`)}function Vd(t,e){return e?.cachePath?z.default.resolve(t,e.cachePath):z.default.join(t,de,hr)}function Qd(t,e){return e?.cachePath?z.default.dirname(z.default.resolve(t,e.cachePath)):z.default.join(t,de)}function Yd(t){try{if(!ar.default.existsSync(t))return null;let e=ar.default.readFileSync(t,"utf-8");return A.deserialize(JSON.parse(e))}catch{return null}}function Zc(t,e){let n=new Map([...t.nodes].filter(([r])=>ft(r,e)));return new A(n)}function Xd(t,e){let n=new Map([...t.graph.nodes].filter(([s])=>t.packageOf.get(s)===e)),r=new Map([...t.packageOf].filter(([s])=>n.has(s)));return{graph:new A(n),packageOf:r}}var cr=class{graphs=new Map;configs=new Map;workspaceGraphs=new Map;workspaceDigests=new Map;layouts=new Map;workspaceBuilds=new Map;changeImpactCaches=new Map;dirtyRoots=new Set;watchers=new Map;lastAnalyze=new Map;duplicationTokenCaches=new Map;isConfigured(e){return this.configs.has(e)}storeConfig(e,n){this.configs.set(e,n)}getConfig(e){return this.configs.get(e)}async getOrBuild(e,n,r=new Map){let s=this.configs.get(e),i=this.graphs.get(e)??Yd(Vd(e,s)),o=await Uc(e,n,i,{...he(s),coverageMap:r});return this.graphs.set(e,o),o}require(e){let n=this.graphs.get(e);if(!n)throw new Error('No graph cached for this root. Call "analyze" first.');return n}getLayout(e){let n=this.layouts.get(e);if(n)return n;let r=Ut(e);return this.layouts.set(e,r),r}async getOrBuildWorkspace(e,n={}){let r=this.workspaceGraphs.get(e);if(r)return r;let s=this.workspaceBuilds.get(e);if(s)return s;let{forceFresh:i,...o}=n,a=Qd(e,this.configs.get(e)),{digest:c,files:l}=xi(e),p=i?null:Qc(a,l);if(p)return this.workspaceGraphs.set(e,p),this.workspaceDigests.set(e,c),p;let u=ir(e,{...o,layout:this.getLayout(e),projectFiles:l}).then(f=>(this.workspaceGraphs.set(e,f),this.workspaceDigests.set(e,c),Vc(a,l,f,m=>process.stderr.write(`Warning: ${m}
|
|
63
|
+
`)),f)).finally(()=>{this.workspaceBuilds.delete(e)});return this.workspaceBuilds.set(e,u),u}requireWorkspace(e){let n=this.workspaceGraphs.get(e);if(!n)throw new Error('No workspace graph cached for this root. Call "analyze" first.');return n}hasWorkspace(e){return this.workspaceGraphs.has(e)}getOrBuildChangeImpact(e){return this.getOrBuildChangeImpactFor(e,()=>this.require(e))}getOrBuildChangeImpactFor(e,n){let r=this.changeImpactCaches.get(e);if(r)return r;let s=Wr(n());return this.changeImpactCaches.set(e,s),s}async getOrBuildChangeImpactForFile(e,n,r){if(!this.isWorkspaceRoot(e))return this.getOrBuildChangeImpactFor(e,()=>r);if(!(await this.ensureFreshWorkspace(e)).getPackageForFile(n))throw new Error(`No workspace package owns "${n}". Call get_workspace_packages to list packages.`);return this.getOrBuildChangeImpactFor(`${e}::__flat__`,()=>r)}clearChangeImpactCachesFor(e){this.changeImpactCaches.delete(e);let n=`${e}::`;for(let r of this.changeImpactCaches.keys())r.startsWith(n)&&this.changeImpactCaches.delete(r)}isWorkspaceRoot(e){return this.lastAnalyze.get(e)?.kind==="workspace"}async resolveGraphForFile(e,n){return(await this.resolveFlatGraphForFile(e,n)).graph}async resolveFlatGraphForFile(e,n){if(!this.isWorkspaceRoot(e))return{graph:await this.ensureFresh(e),packageOf:new Map};let r=await this.ensureFreshWorkspace(e);if(!r.getPackageForFile(n))throw new Error(`No workspace package owns "${n}". Call get_workspace_packages to list packages.`);return r.flatten()}async resolveGraphs(e,n){if(!this.isWorkspaceRoot(e))return[{package:"",graph:await this.ensureFresh(e)}];let r=await this.ensureFreshWorkspace(e);if(n){let s=r.packages.get(n);if(!s)throw new Error(`Unknown workspace package "${n}". Call get_workspace_packages to list packages.`);return[{package:n,graph:Zc(s.graph,s.pkg)}]}return Array.from(r.packages.entries()).map(([s,{graph:i,pkg:o}])=>({package:s,graph:Zc(i,o)}))}async resolveFlatGraph(e,n){if(!this.isWorkspaceRoot(e))return{graph:await this.ensureFresh(e),packageOf:new Map};let r=await this.ensureFreshWorkspace(e),s=r.flatten();if(n){if(!r.packages.has(n))throw new Error(`Unknown workspace package "${n}". Call get_workspace_packages to list packages.`);return Xd(s,n)}return s}storeLastAnalyze(e,n){this.lastAnalyze.set(e,n)}getLastEntryPoints(e){let n=this.lastAnalyze.get(e);return n?.kind==="single"?n.entryPoints:void 0}startWatching(e){if(!this.watchers.has(e))try{let n=ar.default.watch(e,{recursive:!0},(r,s)=>{!s||Yc.test(s)||this.dirtyRoots.add(e)});n.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,n)}catch{}}async ensureFresh(e){if(!this.dirtyRoots.has(e))return this.require(e);this.dirtyRoots.delete(e),this.clearChangeImpactCachesFor(e);let n=this.lastAnalyze.get(e);return n?.kind==="single"?this.getOrBuild(e,n.entryPoints,n.coverageMap):this.require(e)}async ensureFreshWorkspace(e){if(!this.dirtyRoots.has(e)){let i=this.workspaceGraphs.get(e);return i||this.getOrBuildWorkspace(e,he(this.configs.get(e)))}this.dirtyRoots.delete(e);let n=this.workspaceGraphs.get(e);if(n){let{digest:i}=xi(e);if(i===this.workspaceDigests.get(e))return n}this.clearChangeImpactCachesFor(e);let r=this.workspaceGraphs.get(e);this.workspaceGraphs.delete(e),this.workspaceDigests.delete(e);let s=this.configs.get(e);return this.getOrBuildWorkspace(e,{...he(s),forceFresh:!0,previousWorkspace:r})}async getDuplicationTokenCache(e){let n=this.duplicationTokenCaches.get(e);return n||(n=rt(Xc(e)),this.duplicationTokenCaches.set(e,n)),n}flushDuplicationTokenCache(e){let n=this.duplicationTokenCaches.get(e);if(n)try{st(n,Xc(e))}catch(r){process.stderr.write(`Warning: failed to persist duplication token cache: ${r}
|
|
64
|
+
`)}}duplicationResultCachePath(e,n){return Jd(e,this.configs.get(e),n)}invalidate(e){let n=this.graphs.has(e)||this.workspaceGraphs.has(e);return this.graphs.delete(e),this.workspaceGraphs.delete(e),this.workspaceDigests.delete(e),this.workspaceBuilds.delete(e),this.layouts.delete(e),this.clearChangeImpactCachesFor(e),this.dirtyRoots.delete(e),this.duplicationTokenCaches.delete(e),this.configs.delete(e),n}};var ue=h(require("path"));var el=h(require("fs")),tl=h(require("os")),lr=h(require("path"));function v(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}function nl(t){if(!lr.default.isAbsolute(t))throw new Error("root must be an absolute path");let e=lr.default.resolve(t),n=tl.default.homedir();if(e!==n&&!e.startsWith(n+lr.default.sep))throw new Error("root must be within the user home directory");let r;try{r=el.default.statSync(e)}catch{throw new Error("root does not exist")}if(!r.isDirectory())throw new Error("root is not a directory")}var rl=500,Zd=12e4,qd=8;function ki(t,e){return e.size===0?t:t.map(n=>{let r=e.get(n.path);return r?{...n,package:r}:n})}function X(t,e,n){return n&&e?t.map(r=>({...r,package:e})):t}async function al(t,e){let{root:n,entryPoints:r}=e;if(!t.isConfigured(n)){let m=bt(n,{allowJs:!1});Mr(m),t.storeConfig(n,m)}if(r.length===0){let m=t.getLayout(n);if(m.type!=="none"){let d=t.getConfig(n),b={...he(d),packages:e.packages};if(t.storeLastAnalyze(n,{kind:"workspace"}),t.startWatching(n),!e.eager){let w=t.hasWorkspace(n)?t.requireWorkspace(n):void 0;return v(Bt(m,w))}let k=await t.getOrBuildWorkspace(n,b),S=Array.from(k.packages.values()).map(({graph:w,pkg:I})=>({package:I.name,relativeRoot:I.relativeRoot,nodeCount:w.nodes.size}));return v({monorepoType:m.type,packageCount:k.packages.size,packages:S})}}let s=r.map(m=>ue.default.resolve(n,m)),i=t.getConfig(n),o=i?.coverageReportPath?Lr(n,i.coverageReportPath):new Map,a=await t.getOrBuild(n,s,o);t.storeLastAnalyze(n,{kind:"single",entryPoints:s,coverageMap:o}),t.startWatching(n);let c=a.serialize(),l=c.nodes.reduce((m,d)=>(m[d.category]=(m[d.category]??0)+1,m),{}),p=a.findCycles({includeKinds:e.cycleKinds}),u=hs(a),f=ds(a);return v({nodeCount:c.nodes.length,categories:l,cycles:p,languageCoverage:u,...f.length>0&&{caveats:f}})}async function cl(t,e){let{root:n,file:r,depth:s=1,withMeta:i=!1}=e,{graph:o,packageOf:a}=await t.resolveFlatGraphForFile(n,r),c=Es(o,r,s),l=i?c.map(f=>({...f,...Ot(o,f.path)})):c,p=ki(l,a),u=Q(o,"importResolution");return v({file:r,dependencies:p,...u.length>0&&{caveats:u}})}async function ll(t,e){let{root:n,file:r,withMeta:s=!1}=e,{graph:i,packageOf:o}=await t.resolveFlatGraphForFile(n,r),a=jt(i,r),c=s?a.map(u=>({...u,...Ot(i,u.path)})):a,l=ki(c,o),p=Q(i,"importResolution");return v({file:r,dependents:l,...p.length>0&&{caveats:p}})}async function pl(t,e){let{root:n,file:r,testsOnly:s=!1,cached:i=!1,changedSymbols:o,withMeta:a=!1}=e,{graph:c,packageOf:l}=await t.resolveFlatGraphForFile(n,r),p=m=>a?ki(m.map(d=>({path:d,...Ot(c,d)})),l):m;if(i){let m=await t.getOrBuildChangeImpactForFile(n,r,c),d=$r(m,r),b=s?d.filter(S=>c.nodes.get(S)?.category==="test"):d,k=p(b);return v({file:r,affected:k,count:k.length})}let u=Ts(c,r,{testsOnly:s,changedSymbols:o}),f=p(u);return v({file:r,affected:f,count:f.length})}async function ul(t,e){let{root:n,baseRef:r,headRef:s,minDuplicateLines:i,complexityMetric:o,complexityThreshold:a}=e,c=he(t.getConfig(n));if(t.isWorkspaceRoot(n)){if(e.entryPoints?.length)throw new Error("compare_branches on a monorepo root compares the whole workspace \u2014 omit entryPoints. To compare one package, point root at that package's directory.");let f=(await t.ensureFreshWorkspace(n)).flatten().graph,m=await On(n,r,f,{headRef:s,entryPoints:[],minDuplicateLines:i,complexityMetric:o,complexityThreshold:a,maxCoveragePct:e.maxCoveragePct,...c,workspaceBuilder:async d=>(await ir(d,{silent:!0,...c})).flatten().graph});return e.detail==="full"?v(m):v(Gn(m,{metric:o,maxItems:e.maxItems}))}let l=await t.ensureFresh(n),p=e.entryPoints??t.getLastEntryPoints(n)?.map(f=>ue.default.relative(n,f))??[],u=await On(n,r,l,{headRef:s,entryPoints:p,minDuplicateLines:i,complexityMetric:o,complexityThreshold:a,maxCoveragePct:e.maxCoveragePct,...c});return e.detail==="full"?v(u):v(Gn(u,{metric:o,maxItems:e.maxItems}))}async function fl(t,e){let{root:n,file:r,depth:s=1,withEdgeDetail:i=!1}=e,{graph:o,packageOf:a}=await t.resolveFlatGraphForFile(n,r),c=Fs(o,r,{depth:s,withEdgeDetail:i}),l=a.size===0?c:c.map(f=>{let m=a.get(f.file);return m?{...f,package:m}:f}),p=l.length===0?Ze(o,"callEdges"):void 0,u=l.length>0?Q(o,"callEdges"):[];return v({file:r,callers:l,count:l.length,...p&&{note:p},...u.length>0&&{caveats:u}})}async function ml(t,e){let{root:n,entryPoints:r,package:s}=e,i=t.getConfig(n),o=or(n,{additionalIgnoreDirs:i?.ignoreDirs??[],additionalExtensions:i?.extensions??[]});if(!r&&t.isWorkspaceRoot(n)){let l=await t.ensureFreshWorkspace(n),p=s?[l.packages.get(s)].filter(f=>!!f):Array.from(l.packages.values());if(s&&p.length===0)throw new Error(`Unknown workspace package "${s}". Call get_workspace_packages to list packages.`);let u=p.flatMap(({graph:f,pkg:m})=>{let d=o.filter(b=>b===m.relativeRoot||b.startsWith(`${m.relativeRoot}/`));return f.findUnusedFiles(d)});return v({unusedFiles:u,count:u.length})}let c=(r?await t.getOrBuild(n,r.map(l=>ue.default.resolve(n,l))):await t.ensureFresh(n)).findUnusedFiles(o);return v({unusedFiles:c,count:c.length})}async function gl(t,e){let{root:n,package:r,kind:s,prefix:i,minCount:o,limit:a}=e,c=await t.resolveGraphs(n,r),l=Ls(c.map(({graph:p})=>p));return v(_s(l,{kind:s,prefix:i,minCount:o,limit:a}))}async function dl(t,e){let{root:n,coverageThreshold:r,package:s}=e,i=await t.resolveGraphs(n,s),o=t.getConfig(n),a=r??o?.coverageThreshold??80,c=i.length>1;if(!i.some(({graph:p})=>Le(p)))return v({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let l=i.flatMap(({graph:p,package:u})=>X([...p.nodes.values()].filter(f=>f.category!=="test"&&f.category!=="config").filter(f=>f.coveragePct!==void 0&&f.coveragePct<a).map(f=>({file:f.path,coveragePct:f.coveragePct})),u,c));return v({threshold:a,uncovered:l,count:l.length})}async function hl(t,e){let{root:n,package:r}=e,s=await t.resolveGraphs(n,r),i=s.length>1;if(!s.some(({graph:a})=>Ps(a)))return v({error:"No git-stats data available. Set gitStats: true in mokosh.config and call analyze again."});let o=s.flatMap(({graph:a,package:c})=>X([...a.nodes.values()].filter(l=>l.type==="markdown"&&l.staleFor&&l.staleFor.length>0).map(l=>({doc:l.path,staleFor:l.staleFor})),c,i));return v({staleDocs:o,count:o.length})}async function yl(t,e){let{root:n,metric:r="cognitiveComplexity",threshold:s=10,limit:i=20,package:o}=e,a=await t.resolveGraphs(n,o),c=a.length>1,l=a.flatMap(({graph:m,package:d})=>X(at(m,{metric:r,threshold:s,limit:c?1/0:i}),d,c)).sort((m,d)=>d[r]-m[r]).slice(0,i),p=a.map(({graph:m})=>m),u=l.length===0?Ze(p,"functionComplexity"):void 0,f=l.length>0?Q(p,"complexity"):[];return v({metric:r,threshold:s,functions:l,count:l.length,...u&&{note:u},...f.length>0&&{caveats:f}})}async function xl(t,e){let{root:n,metric:r="cognitiveComplexity",minComplexity:s=10,maxCoveragePct:i=50,minChurn:o=0,limit:a=20,package:c}=e,l=await t.resolveGraphs(n,c),p=l.length>1;if(!l.some(({graph:b})=>Le(b)))return v({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let u=l.map(({graph:b,package:k})=>({pkgName:k,...ct(b,{metric:r,minComplexity:s,maxCoveragePct:i,minChurn:o,limit:p?1/0:a})})),f=u.flatMap(({hotspots:b,pkgName:k})=>X(b,k,p)).sort((b,k)=>k[r]-b[r]).slice(0,a),m=u.some(b=>b.churnDataAvailable),d=f.length>0?Q(l.map(({graph:b})=>b),"complexity"):[];return v({metric:r,minComplexity:s,maxCoveragePct:i,minChurn:o,churnDataAvailable:m,hotspots:f,count:f.length,...d.length>0&&{caveats:d}})}function eh(t){let e=Object.keys(t.byTopDir).length,n=Object.keys(t.byFamily).filter(s=>s!=="other"),r=n.length>1?` or filter:"family:${n[0]},sort:score"`:"";return`${t.matched} duplicate group${t.matched===1?"":"s"} across ${e} ${e===1?"dir":"dirs"}; showing the top clusters. Narrow with filter, e.g. filter:"path:src,minScore:15"${r}. Pass view:"groups" for raw spans or view:"full" for both lists.`}async function bl(t,e){let{root:n,minLines:r=6,ignoreLiterals:s=!0,maxPunctuationRatio:i=.5,limit:o=20,filter:a,slim:c=!0,package:l}=e,p=a?et(a):void 0,u=p?.limit??o,f=await t.resolveGraphs(n,l),m=f.length>1,d=t.getConfig(n),b=e.ignoreDirs??[...j,...d?.ignoreDirs??[]],k=Math.max(m||p?u*4:u,rl),S={includeGenerated:e.includeGenerated??d?.duplication?.includeGenerated??!1,includeSameFile:e.includeSameFile??d?.duplication?.includeSameFile??!1,includeSvgMarkup:e.includeSvgMarkup??d?.duplication?.includeSvgMarkup??!1,includeDocs:e.includeDocs??d?.duplication?.includeDocs??!1,scope:e.scope??d?.duplication?.scope,ignoreGlobs:d?.duplication?.ignoreGlobs??[]},w={minLines:r,ignoreLiterals:s,maxPunctuationRatio:i,limit:k,scope:S.scope,includeGenerated:S.includeGenerated,includeSameFile:S.includeSameFile,includeSvgMarkup:S.includeSvgMarkup,includeDocs:S.includeDocs,ignoreDirs:b,ignoreGlobs:S.ignoreGlobs},I=Tn(w),_=a===void 0,Z=await t.getDuplicationTokenCache(n),fe=[],ve=!1;for(let{graph:D,package:G}of f){let dt=t.duplicationResultCachePath(n,m?G:void 0),O=_?En(D.nodes.values()):"",We=_?Fn(dt,O,I):null;if(We){fe.push({groups:X(We.groups,G,m),clusters:X(We.clusters,G,m)});continue}ve=!0;let{groups:Ci,clusters:wi}=await ot(D,n,{minLines:r,ignoreLiterals:s,maxPunctuationRatio:i,limit:k,ignoreDirs:b,includeGenerated:S.includeGenerated,includeSameFile:S.includeSameFile,includeSvgMarkup:S.includeSvgMarkup,includeDocs:S.includeDocs,scope:S.scope,ignoreGlobs:S.ignoreGlobs,...a!==void 0&&{filter:a},tokenCache:Z});_&&Dn(dt,O,I,Ci,wi),fe.push({groups:X(Ci,G,m),clusters:X(wi,G,m)})}ve&&t.flushDuplicationTokenCache(n);let U=fe.flatMap(D=>D.groups),oe=An(U),Ce=p?.sort?vn(U,p):[...U].sort((D,G)=>G.lines-D.lines),me=fe.flatMap(D=>D.clusters).sort((D,G)=>G.longestMatch-D.longestMatch||G.matchCount-D.matchCount),K=e.view??"summary",mt=a===void 0&&e.view===void 0,mr=K==="groups"||K==="full",gt=K!=="groups",gr=mt?qd:u,$=gt?me.slice(0,gr):[],x=[],F;if(mr)if(K==="full"){let D=Pn(Ce,$);F=Ce.length-D.length,x=D.slice(0,u)}else x=Ce.slice(0,u);let H=F!==void 0?{...oe,clusteredGroups:F}:oe,Jt=()=>c?x.map(Rn):x,ge=()=>c?$.map(Nn):$,q=!1;for(;(x.length>1||$.length>1)&&JSON.stringify({minLines:r,summary:H,groups:Jt(),clusters:ge()}).length>Zd;)x=x.slice(0,Math.max(1,Math.floor(x.length/2))),$=$.slice(0,Math.max(1,Math.floor($.length/2))),q=!0;let J=Q(f.map(({graph:D})=>D),"duplication");return v({minLines:r,...a!==void 0&&{filter:a},summary:H,...gt&&{clusters:ge()},...mr&&{groups:Jt(),count:x.length},...mt&&{hint:eh(oe)},...J.length>0&&{caveats:J},...q&&{truncated:q}})}async function kl(t,e){let{root:n,changedFiles:r,base:s,featureThreshold:i,format:o="tags"}=e,a=r??new ln().getChangedFiles(n,s).map(u=>ue.default.relative(n,ue.default.resolve(n,u))),c=i!==void 0?{featureDetection:{minOutDegree:i}}:void 0,l=t.isWorkspaceRoot(n)?await th(t,n,a):[{graph:await t.ensureFresh(n),files:a}];if(o==="paths"){let u=[...new Set(l.flatMap(({graph:f,files:m})=>gi(f,m,c)))];return v({changedFiles:a,affectedTests:u,count:u.length})}let p=[...new Set(l.flatMap(({graph:u,files:f})=>mi(u,f,c)))];return v({changedFiles:a,proposedTags:p})}async function th(t,e,n){let r=await t.ensureFreshWorkspace(e),s=new Map;for(let i of n){let o=r.getPackageForFile(i);if(!o)continue;let a=s.get(o.name);a?a.push(i):s.set(o.name,[i])}return Array.from(s.entries()).map(([i,o])=>({graph:r.packages.get(i)?.graph,files:o})).filter(i=>!!i.graph)}async function Sl(t,e){let{root:n,entryPoints:r,featureThreshold:s,package:i}=e,o=s!==void 0?{minOutDegree:s}:void 0;if(r){let p=await t.getOrBuild(n,r.map(m=>ue.default.resolve(n,m))),u=ke(p.nodes,o),f=Array.from(u.values()).sort((m,d)=>d.outDegree-m.outDegree);return v({features:f,count:f.length})}let a=await t.resolveGraphs(n,i),c=a.length>1,l=a.flatMap(({graph:p,package:u})=>X(Array.from(ke(p.nodes,o).values()),u,c)).sort((p,u)=>u.outDegree-p.outDegree);return v({features:l,count:l.length})}async function vl(t,e){let{root:n,entryPoints:r,filter:s,mermaid:i=!1,slim:o=!0,package:a}=e;if(r){let p=await t.getOrBuild(n,r.map(u=>ue.default.resolve(n,u)));return sl(p,s,i,o)}let{graph:c,packageOf:l}=await t.resolveFlatGraph(n,a);return sl(c,s,i,o,l)}function sl(t,e,n,r,s=new Map){let i=Kn(t.serialize(),Hn(e),{packageOf:s});return n?v(rn.serialize(A.deserialize(i))):v(r?Ds(i):i)}async function Cl(t,e){let{root:n}=e,r=t.getLayout(n);if(r.type==="none")throw new Error(`${n} is not a recognized monorepo root (no pnpm/npm/yarn/Nx/Turborepo/Gradle/sbt workspace detected).`);let s=t.hasWorkspace(n)?t.requireWorkspace(n):void 0;return v(Bt(r,s))}async function wl(t,e){let{root:n,file:r,maxFilesPerPackage:s}=e,o=(await t.ensureFreshWorkspace(n)).summarizeAffectedAcrossPackages(r,s!==void 0?{maxFilesPerPackage:s}:{});return v(o)}function El(t,e){let{root:n}=e,r=t.invalidate(n);return v({root:n,cleared:r,message:r?"Cache cleared. Call analyze to rebuild.":"No cache was present for this root."})}async function Tl(t,e){let{root:n,type:r,package:s}=e,{graph:i}=await t.resolveFlatGraph(n,s),o=Gs(i);if(r)return v(Os(o,r));let a=Array.from(o.types.values()),c=a.length===0?Ze(i,"typeGraph"):void 0;return v({count:a.length,types:a,...c&&{note:c}})}async function Fl(t,e){let{root:n,paths:r,minOutDegree:s,package:i}=e,o=await t.resolveGraphs(n,i),a=o.length>1,c=s!==void 0?{minOutDegree:s}:void 0,l=o.flatMap(({graph:p,package:u})=>{let f=Rs(p,c),m=r?.length?r.map(d=>f.get(d)).filter(d=>!!d):Array.from(f.values());return X(m,u,a)});return v({count:l.length,modules:l})}async function Dl(t,e){let{root:n,minOutDegree:r,package:s}=e,{graph:i}=await t.resolveFlatGraph(n,s),o=$t(i,r!==void 0?{minOutDegree:r}:void 0),a=Object.fromEntries(o.features);return v({features:a,unassigned:o.unassigned})}async function Pl(t,e){let{root:n,function:r,package:s}=e,{graph:i}=await t.resolveFlatGraph(n,s),o=jr(i,r),a=o.callers.length===0&&o.callees.length===0,c=a?Ze(i,"callEdges"):void 0,l=a?[]:Q(i,"callEdges");return v({...o,...c&&{note:c},...l.length>0&&{caveats:l}})}async function Al(t,e){let{root:n,name:r,package:s}=e,i=await t.resolveGraphs(n,s),o=i.length>1,a=i.flatMap(({graph:l,package:p})=>X(Ns(l,r),p,o)),c=a.length>0?Q(i.map(({graph:l})=>l),"callEdges"):[];return v({name:r,matches:a,count:a.length,...c.length>0&&{caveats:c}})}var il=25;function nh(t){return t.length<=il?{entryPoints:t,entryPointCount:t.length}:{entryPoints:t.slice(0,il),entryPointCount:t.length,entryPointsTruncated:!0}}function ol(t,e,n){if(e==="full")return v({...t,...nh(t.entryPoints)});let r=Gr(t,n===void 0?{}:{maxExports:n});if(e==="exports"){let{publicExportsTruncated:s,...i}=r;return v({...i,publicExports:t.publicExports,hint:'Pass view:"full" for the internalFiles / testFiles path lists.'})}return v(r)}async function Rl(t,e){let{root:n,entryPoints:r,package:s,view:i="summary",maxExports:o}=e,a=e.maxExportsPerPackage??10;if(!t.isWorkspaceRoot(n)){let d=await t.ensureFresh(n),b=r?.length?r:Or(d,n);if(b.length===0)throw new Error("No entry points found. Pass entryPoints explicitly, or (JS) ensure package.json has a main/exports field.");return ol(on(d,b),i,o)}let c=await t.ensureFreshWorkspace(n),l=await t.resolveGraphs(n,s),p=(d,b)=>{let S=(r?.length?r:(c.packages.get(d)?.pkg.entryPoints??[]).map(w=>ue.default.relative(n,w))).filter(w=>b.nodes.has(w));return S.length?on(b,S):null};if(l.length===1){let d=l[0];if(!d)throw new Error("get_api_surface: no graph resolved for this root.");let b=p(d.package,d.graph);if(!b)throw new Error(`No entry point for package "${d.package}" is present in the analyzed graph. Pass entryPoints explicitly.`);return ol(b,i,o)}let u=[],f=[],m=!1;for(let{package:d,graph:b}of l){let k=p(d,b);if(!k){f.push({package:d,reason:"no entry point resolvable from the WorkspaceGraph"});continue}let S={package:d,entryPointCount:k.entryPoints.length,publicExportCount:k.publicExports.length,internalFileCount:k.internalFiles.length,unreachableFromEntryCount:k.unreachableFromEntry.length,testFileCount:k.testFiles.length};a>0?(S.publicExports=k.publicExports.slice(0,a).map(w=>({name:w.name,kind:w.kind})),S.publicExports.length<k.publicExports.length&&(m=!0)):k.publicExports.length>0&&(m=!0),u.push(S)}return v({packages:u,skipped:f,truncated:m})}async function Nl(t,e){let n=await t.resolveGraphs(e.root,e.package),s=(await Promise.all(n.map(({graph:i})=>fi(i,e.root,{dryRun:e.dryRun??!1})))).reduce((i,o)=>({updated:i.updated+o.updated,unchanged:i.unchanged+o.unchanged,errors:i.errors+o.errors,files:[...i.files,...o.files]}));return v(s)}var B={type:"string"},Si={type:"string",description:"Monorepo: narrow to one package (else whole workspace)."},Ml=[{name:"analyze",description:"Build the dependency graph from entry points; returns node count, categories, and cycles. Call before get_dependencies/get_dependents/get_affected/propose_tags. Empty entryPoints auto-detects a monorepo (pnpm/npm/yarn/Nx/Turborepo/Gradle/sbt): returns the layout at once, builds per-package graphs lazily on the first workspace-aware call \u2014 eager:true builds all up front. Whole-graph tools then run against the flattened workspace; pass package to narrow.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root (or monorepo root)"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root (e.g. ['src/index.ts']). Pass [] to trigger monorepo auto-detection."},eager:{type:"boolean",description:"Monorepo only: build every package graph before returning (restores the { nodeCount, categories, cycles } payload) instead of the fast layout-only response. Default false."},packages:{type:"array",items:{type:"string"},description:"Monorepo only: restrict the build to these package names or relative roots. The escape hatch for very large monorepos."},cycleKinds:{type:"array",items:{type:"string",enum:["docReference","samePackage"]},description:"Include normally-filtered cycle edge kinds in the `cycles` output: 'docReference' (Markdown doc cross-links, ADR-009), 'samePackage' (JVM same-package siblings). Default: none \u2014 only genuine import cycles are reported."}},required:["root","entryPoints"]}},{name:"get_dependencies",description:"Get files that a given file imports (outgoing traversal). depth=1 returns immediate imports; omit for the full transitive tree. Each result includes the specific symbols imported from that file (when known).",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},depth:{type:"number",description:"Max traversal depth (default: 1)"},withMeta:{type:"boolean",description:"Include each result's category and export names alongside the path (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"get_dependents",description:"Get files that directly import a given file (one-hop incoming edges). Each result includes the specific symbols that dependent file imports from this file (when known).",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},withMeta:{type:"boolean",description:"Include each result's category and export names alongside the path (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"get_affected",description:"Get all files transitively affected if a given file changes \u2014 full incoming traversal upward. Use before a refactor to understand blast radius. On a monorepo root, blast radius is fully transitive across packages. See docs/mcp.md for the testsOnly, cached, changedSymbols, and withMeta options.",inputSchema:{type:"object",properties:{root:{type:"string"},file:{type:"string",description:"File path relative to root"},testsOnly:{type:"boolean",description:"Return only test/spec files (default: false)"},cached:{type:"boolean",description:"Use a pre-computed impact cache for O(1) lookup instead of graph traversal. Cache is built lazily on first use and reused for the session (default: false)."},changedSymbols:{type:"array",items:{type:"string"},description:"Restrict blast-radius to files that import at least one of these symbols. Omit to treat the whole file as changed (conservative, same as before)."},withMeta:{type:"boolean",description:"Return each affected file as { path, category, exports } instead of a bare path string (default: false). Set true when you need to decide what to do with a result without a follow-up lookup."}},required:["root","file"]}},{name:"compare_branches",description:"Compare the current graph (root) against baseRef, for reviewing a PR/branch: file diff, stale post-rename references, and deltas for duplication, complexity, doc drift, and coverage/risk hotspots. Returns a compact summary by default (verdict + headline + capped delta lists); pass detail:'full' for every entry. Monorepo root: whole flattened workspace, no entryPoints. See docs/mcp.md. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},baseRef:{type:"string",description:"Git ref to compare against, e.g. 'main', 'origin/main', or a commit sha"},headRef:{type:"string",description:"Git ref to label the head side of the comparison (default: 'HEAD'). The graph itself always comes from the already-analyzed root, not a checkout of this ref."},entryPoints:{type:"array",items:{type:"string"},description:"Entry points to build the base-ref graph from, relative to root. Defaults to the entry points from the last analyze() call for this root."},minDuplicateLines:{type:"number",description:"Minimum duplicated block size, in source lines, for the duplication delta (default: 6)"},complexityMetric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which per-function score drives the complexity delta (default: cognitiveComplexity)"},complexityThreshold:{type:"number",description:"Minimum per-function score to count as a complexity hotspot (default: 10)"},maxCoveragePct:{type:"number",description:"Maximum containing-file coverage % to count as a risk hotspot (default: 50)"},detail:{type:"string",enum:["summary","full"],description:"'summary' (default): verdict, headline, and each delta list capped at maxItems with true counts; empty sections omitted. 'full': the complete BranchComparison with every entry."},maxItems:{type:"number",description:"In summary mode, max entries kept per delta list (complexity/duplication/doc-drift/coverage); the true count is always reported alongside (default: 8). Stale references are never truncated."}},required:["root","baseRef"]}},{name:"get_callers",description:"Get files whose exported functions call into a given file (call-graph dependents). More precise than get_affected: only files with actual runtime call edges, not mere imports. Requires prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to project root"},file:{type:"string",description:"File path relative to root"},depth:{type:"number",description:"Max traversal depth (default: 1)"},withEdgeDetail:{type:"boolean",description:"Include from/to function names per edge (default: false)"}},required:["root","file"]}},{name:"find_unused",description:"Find files in the project that are not reachable from any entry point. Useful before cleanup passes. Omit entryPoints to reuse the cached graph from a prior analyze() call instead of rebuilding.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root. Omit to reuse the cached graph from a prior analyze() call."},package:B},required:["root"]}},{name:"list_tags",description:"Discover tag:<name> values. Bounded: capped at 250 tags, no full mode. Default = comment-marker + import kinds, count>=2, top 50, plus a byKind histogram over all kinds, totalDistinct and a hint. Narrow with kind, prefix or minCount. See docs/mcp.md.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},kind:{type:"string",enum:["comment-marker","import","function","variable","library","all"],description:'One tag kind, or "all" \u2014 overrides the default comment-marker+import filter. import/library = per-imported file/package on tests; function/variable = declaration names.'},prefix:{type:"string",description:"Case-insensitive substring match on the name."},minCount:{type:"number",description:"Min node count per tag (default 2)."},limit:{type:"number",description:"Max tags returned (default 50, max 250)."},package:B},required:["root"]}},{name:"find_uncovered",description:"Find non-test files whose line coverage is below the configured threshold. Requires a prior analyze() call and coverageReportPath set in mokosh.config. coverageThreshold overrides the config default (default: 80).",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},coverageThreshold:{type:"number",description:"Line-coverage % below which a file is considered uncovered. Overrides config value."},package:B},required:["root"]}},{name:"check_doc_drift",description:"Find markdown docs whose referenced files changed more recently than the doc itself \u2014 a commit-recency heuristic for stale docs, not a content diff. Requires a prior analyze() with gitStats: true in mokosh.config (else no commit-timestamp data, nothing flagged). See docs/adr-009-markdown-parsing.md for limitations.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},package:B},required:["root"]}},{name:"find_complex_functions",description:"Find individual functions/methods above a cognitive (or cyclomatic) complexity threshold, sorted worst-first. Requires a prior analyze() call. Populated for TypeScript/JavaScript, Go, and Python.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},metric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which score to threshold/sort on (default: cognitiveComplexity)"},threshold:{type:"number",description:"Minimum score to include (default: 10)"},limit:{type:"number",description:"Max results to return, worst-first (default: 20)"},package:B},required:["root"]}},{name:"find_risk_hotspots",description:"Find functions that are complex, in a poorly-covered file, and \u2014 when gitStats is enabled in mokosh.config \u2014 frequently changed. Requires a prior analyze() and coverageReportPath in mokosh.config; errors if no coverage loaded. Churn filtering is skipped (churnDataAvailable: false) without gitStats, since complexity + low coverage alone is still a meaningful signal.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},metric:{type:"string",enum:["cognitiveComplexity","complexity"],description:"Which per-function score to filter/sort on (default: cognitiveComplexity)"},minComplexity:{type:"number",description:"Minimum per-function complexity score to include (default: 10)"},maxCoveragePct:{type:"number",description:"Maximum containing-file coverage % to include (default: 50)"},minChurn:{type:"number",description:"Minimum containing-file 90-day commit count to include (default: 0). Ignored when gitStats wasn't enabled at analyze time."},limit:{type:"number",description:"Max results to return, worst-first by metric (default: 20)"},package:B},required:["root"]}},{name:"find_duplicates",description:"Find duplicated code, largest-first. Summary-first: default = `summary` + `clusters` preview + `hint`, no `groups`. Narrow with `filter`; `view` adds groups. Requires analyze().",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},minLines:{type:"number",description:"Min duplicated block size in lines (default 6)"},ignoreLiterals:{type:"boolean",description:"Normalize string/number literals (default true); false = exact text."},maxPunctuationRatio:{type:"number",description:"Max object/array-punctuation fraction (default 0.5); 1 disables."},ignoreDirs:{type:"array",items:{type:"string"},description:"Directory names to exclude (default: DEFAULT_IGNORE_DIRS + config). [] disables."},limit:{type:"number",description:"Max clusters/groups returned (default 20); ignored for the summary view."},includeGenerated:{type:"boolean",description:"Scan generated/vendored files too (default false). signals:['generated']."},includeSameFile:{type:"boolean",description:"Include single-file matches (default false). signals:['same-file']."},includeSvgMarkup:{type:"boolean",description:"Include inline-SVG/JSX-markup matches (default false). signals:['svg-markup']."},scope:{type:"string",enum:["src","tests","all"],description:"Test-file dups (default 'src'): 'src' drops test clusters, 'tests' only substantive test logic, 'all' keeps all."},includeDocs:{type:"boolean",description:"Include markdown-family matches (default false). signals:['docs']."},filter:{type:"string",description:"key:value result filter (AND across keys): path, allPaths, family, type, kind, defKind, min/maxLines, min/maxScore, minOccurrences, crossFile, signal ('!' negates), sort, sortDir, limit. See docs/query.md."},view:{type:"string",enum:["summary","groups","full"],description:"'summary' (default): clusters preview + hint, no groups. 'groups': raw spans, no clusters. 'full': both, groups de-duped vs clusters."},slim:{type:"boolean",description:"Compact response (default true): terse groups, 'path:start-end' occurrences, clusters carry longestMatchAt not group bodies. false = full."},package:B},required:["root"]}},{name:"propose_tags",description:"Propose what to run based on changed files. Pass changedFiles explicitly or omit to use git diff. format='tags' (default) returns test tags for CI tag-filtering; format='paths' returns test file paths ready to pipe directly to a test runner (e.g. vitest). Feature hubs act as traversal boundaries in both modes.",inputSchema:{type:"object",properties:{root:{type:"string"},changedFiles:{type:"array",items:{type:"string"},description:"Changed files relative to root. Omit to read from git diff."},base:{type:"string",description:"Diff against this ref (e.g. 'origin/main') instead of only local working-tree/staged/untracked changes. Ignored when changedFiles is given. Needed in CI, where the checkout is already clean."},featureThreshold:{type:"number",description:"Min importers for a file to be treated as a feature hub (default: 5). A hub short-circuits traversal and emits a feature:<name> tag instead of all downstream tags."},format:{type:"string",enum:["tags","paths"],description:"Output format: 'tags' returns test tag names for CI filtering (default); 'paths' returns test file paths to pipe to a test runner."}},required:["root"]}},{name:"detect_features",description:"Identify feature hub files \u2014 non-test files that import many other internal modules (orchestrators / aggregators like src/parser.ts or src/cli/runner.ts). Returns a list sorted by import count descending.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root. Omit to use the cached graph."},featureThreshold:{type:"number",description:"Min internal imports a file must have to qualify as a feature hub (default: 5)."},package:B},required:["root"]}},{name:"query",description:"Filter the graph by category, tag, path, or other node metadata. Returns matching nodes as JSON or a Mermaid diagram. If entryPoints is omitted the cached graph from a prior 'analyze' call is used. On a monorepo root: runs against the flattened workspace (global sort/limit, cross-package edges, per-node package); package:<name> narrows. See docs/mcp.md for the full query DSL reference.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry points to build the graph. Omit to reuse the cached graph from a prior 'analyze' call."},filter:{type:"string",description:"Query string e.g. 'category:logic' or 'category:logic,tag:auth'. Keys: category, type, tag, path, package, external, importsFile, importedBy, min/maxImports, min/maxSize, hasDocstring, min/maxCoverage, min/maxExportUsage, min/maxComplexity, min/maxCognitiveComplexity, min/maxCommits, isDocumented, isStale, lastAuthor. OR: any(k:v|k:v). sort: size|imports|commitCount90d|exportUsage|complexity|cognitiveComplexity + sortDir asc|desc. limit: N. Full reference: docs/query.md."},mermaid:{type:"boolean",description:"Return a Mermaid diagram (default: false)"},slim:{type:"boolean",description:"Compact response mode (default: true). Export names, meaningful tags (comment-marker + import kinds only), and a flat importsFiles path list \u2014 no edge objects, no mtime/size. Pass slim: false for every tag kind and full edge metadata; use list_tags (bounded; its byKind histogram shows per-kind totals) to discover tag names."},package:{type:"string",description:"Monorepo: narrow to one package (same as a package:<name> filter clause)."}},required:["root","filter"]}},{name:"get_workspace_packages",description:"List workspace packages in a monorepo: name, relativeRoot, dependsOn. Reads repo layout + package.json manifests alone \u2014 no analyze(), no graph build, fast on large monorepos. Per-package nodeCount (and exact dependsOn edges for Gradle/sbt) appear only when a prior analyze() built the workspace graph; check the dependsOnResolved / nodeCountsResolved flags.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"}},required:["root"]}},{name:"get_workspace_affected",description:"Cross-package blast-radius analysis: files affected if a given file changes, grouped by owning package with each package's sample list capped (counts stay exact). For the full uncapped list call get_affected on the same file. Requires a prior analyze() with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"},file:{type:"string",description:"Monorepo-root-relative path of the changed file (e.g. 'packages/shared/src/utils.ts')"},maxFilesPerPackage:{type:"number",description:"Cap each package's sample list (default 10; 0 = counts only)."}},required:["root","file"]}},{name:"get_type_graph",description:"Type-level relationships. Without a type name: an inventory of all interfaces, classes, enums and type aliases with their file and kind. With a type name: which files import it (usedByFiles) and which types the defining file imports (uses). Requires a prior analyze(). TypeScript/JavaScript only.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},type:{type:"string",description:"Exact exported name of the type to look up (e.g. 'FileNode'). Omit to get the full type inventory."},package:Si},required:["root"]}},{name:"get_module_responsibility",description:"Return what each file is responsible for: its semantic role, JSDoc description (when present), exported symbol names, and which feature hub it belongs to. Pass specific paths to filter, or omit paths to get all files. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},paths:{type:"array",items:{type:"string"},description:"Project-relative file paths to include. Omit to return all files."},minOutDegree:{type:"number",description:"Min imports for a file to qualify as a feature hub (default: 5)."},package:B},required:["root"]}},{name:"get_feature_graph",description:"Group files by domain: which files each feature hub (high-import orchestrator) transitively owns. Each file goes to the most specific hub that can reach it (lowest out-degree wins). Prefer over a full query for 'what files are in feature X?' \u2014 returns only paths grouped by hub, so it's smaller than a full graph query for the same question.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},minOutDegree:{type:"number",description:"Minimum internal imports a file must have to qualify as a feature hub (default: 5)."},package:Si},required:["root"]}},{name:"get_call_graph",description:"Look up callers and callees for a named function. Returns the file that defines the function, all files/functions that call it, and all files/functions it calls. Always requires a function name \u2014 never returns the full call graph unfiltered. Call edges are only populated for TypeScript/JavaScript files.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},function:{type:"string",description:"Exact name of the function to look up (e.g. 'parseFile')."},package:Si},required:["root","function"]}},{name:"find_symbol",description:"Find every file that exports a symbol by exact name, with the best available usage info per match. Precision varies by the defining file's language \u2014 check each match's `precision` field ('call' | 'file-level') before trusting caller/importer results as symbol-exact. See docs/mcp.md for per-language coverage details.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},name:{type:"string",description:"Exact export name to look up (e.g. 'parseFile')."},package:B},required:["root","name"]}},{name:"get_api_surface",description:"API surface report: exported symbols resolved to defining file + kind, plus internalFiles / unreachableFromEntry / testFiles partitions. Needs a prior analyze(). Entry points auto-detect from package.json exports/bin/main (JS/TS) or every non-test source file (Go/Python/JVM). Summary-first: view 'summary' (default) = counts + byKind + a capped sample + the short unreachableFromEntry list; 'exports'/'full' widen it. Monorepo root without `package`: per-package breakdown + `skipped`. See docs/mcp.md.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},entryPoints:{type:"array",items:{type:"string"},description:"Public entry-point paths. Omit to auto-detect (exports / bin / main)."},package:B,view:{type:"string",enum:["summary","exports","full"],description:"summary (default) | exports (+full publicExports) | full (+path lists)."},maxExports:{type:"number",description:"view 'summary': cap the {name,kind} sample (default 30)."},maxExportsPerPackage:{type:"number",description:"Monorepo, no `package`: cap each package's sample (default 10; 0 = counts)."}},required:["root"]}},{name:"clear_cache",description:"Drop the cached dependency graph and mokosh.config.json for a root, forcing the next analyze() to rebuild from disk and re-read config. Call after editing source files or mokosh.config.json mid-session \u2014 otherwise get_affected, get_dependencies and other query tools reason from stale data.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root to invalidate."}},required:["root"]}},{name:"apply_tags",description:"Write @tag annotations into test file source code based on the dependency graph, as an idempotent block \u2014 re-running is safe, the existing block is replaced in place. Use dryRun=true to preview changes without writing to disk. Requires a prior analyze() call. See docs/mcp.md for tag-kind and per-language block syntax details.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root."},dryRun:{type:"boolean",description:"When true, computes which files would change but does not write to disk (default: false)."},package:B},required:["root"]}}];function ur(){let t=new cr,e=new Il.Server({name:"mokosh",version:"0.0.1"},{capabilities:{tools:{}}});return e.setRequestHandler(pr.ListToolsRequestSchema,async()=>({tools:Ml})),e.setRequestHandler(pr.CallToolRequestSchema,async n=>{let{name:r,arguments:s}=n.params,i=s,a={analyze:c=>al(t,c),get_dependencies:c=>cl(t,c),get_dependents:c=>ll(t,c),get_affected:c=>pl(t,c),compare_branches:c=>ul(t,c),get_callers:c=>fl(t,c),find_symbol:c=>Al(t,c),find_unused:c=>ml(t,c),find_uncovered:c=>dl(t,c),list_tags:c=>gl(t,c),check_doc_drift:c=>hl(t,c),find_complex_functions:c=>yl(t,c),find_risk_hotspots:c=>xl(t,c),find_duplicates:c=>bl(t,c),propose_tags:c=>kl(t,c),detect_features:c=>Sl(t,c),get_type_graph:c=>Tl(t,c),get_module_responsibility:c=>Fl(t,c),get_feature_graph:c=>Dl(t,c),get_call_graph:c=>Pl(t,c),get_api_surface:c=>Rl(t,c),query:c=>vl(t,c),get_workspace_packages:c=>Cl(t,c),get_workspace_affected:c=>wl(t,c),clear_cache:c=>El(t,c),apply_tags:c=>Nl(t,c)}[r];if(!a)throw new Error(`Unknown tool: ${r}`);try{return nl(i.root),await a(i)}catch(c){return{content:[{type:"text",text:`Error: ${c instanceof Error?c.message:String(c)}`}],isError:!0}}}),e}var rh=(()=>{try{let t=process.argv[1];return t?vi.default.realpathSync(Gl.default.resolve(t))===vi.default.realpathSync(__filename):!1}catch{return!1}})(),Ll=4096;function sh(){if(process.env.MOKOSH_MCP_CHILD==="1"||Ol.default.getHeapStatistics().heap_size_limit/1024/1024>=Ll)return!1;let e=process.argv[1];if(!e)return!1;let n=`${process.env.NODE_OPTIONS??""} --max-old-space-size=${Ll}`.trim(),r=(0,_l.spawnSync)(process.execPath,[e,...process.argv.slice(2)],{stdio:"inherit",env:{...process.env,MOKOSH_MCP_CHILD:"1",NODE_OPTIONS:n}});if(r.error)return fr("re-exec",r.error),!1;process.exit(r.status??(r.signal?1:0))}function fr(t,e){let n=e instanceof Error?e.stack??e.message:String(e);process.stderr.write(`[mokosh-mcp] FATAL ${t}: ${n}
|
|
65
|
+
`)}async function ih(){process.on("uncaughtException",n=>{fr("uncaughtException",n),process.exit(1)}),process.on("unhandledRejection",n=>{fr("unhandledRejection",n),process.exit(1)});let t=ur(),e=new jl.StdioServerTransport;await t.connect(e)}rh&&!sh()&&ih().catch(t=>{fr("startup",t),process.exit(1)});0&&(module.exports={createMcpServer});
|
|
53
66
|
//# sourceMappingURL=mcp.js.map
|