@omfalos/mokosh 0.1.0 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.mjs CHANGED
@@ -1,28 +1,28 @@
1
1
  #!/usr/bin/env node
2
- var ae=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});import{StdioServerTransport as Di}from"@modelcontextprotocol/sdk/server/stdio.js";import{Server as Ri}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as Ni,ListToolsRequestSchema as Gi}from"@modelcontextprotocol/sdk/types.js";import Ai from"fs";import De from"fs";import Tt from"path";var vs=[".config.","biome.json","tsconfig.json","package.json",".prettierrc",".eslintrc"],kt=[];function pe(r){kt.push(r)}function wt(r){return[...vs,...kt].some(e=>typeof e=="string"?r.includes(e):e instanceof RegExp?e.test(r):e(r))}var ks=[".test.",".spec.","-test.","-spec."],Ct=[];function ce(r){Ct.push(r)}function q(){return[...ks,...Ct]}var ws=["jest","vitest","playwright","cypress","@testing-library/"],Ft=[];function le(r){Ft.push(r)}function Re(){return[...ws,...Ft]}var Et=.8;function Ne(r){Et=r}function Ge(){return Et}var Cs=["mokosh.config.js","mokosh.config.cjs","mokosh.config.json"];function K(r,{allowJs:e=!0,isExplicitPath:t=!1}={}){if(t){let s=Tt.resolve(r);return De.existsSync(s)?s.endsWith(".json")?At(s):e?Pt(s):{}:{}}for(let s of Cs){let n=Tt.resolve(r,s);if(De.existsSync(n)){if(s.endsWith(".json"))return At(n);if(e)return Pt(n)}}return{}}function At(r){return JSON.parse(De.readFileSync(r,"utf-8"))}function Pt(r){let e=ae(r);return e&&typeof e=="object"&&"default"in e&&(e=e.default),typeof e=="function"?e({}):e}function je(r){for(let e of r.configMatchers??[])pe(e);for(let e of r.testPatterns??[])ce(e);for(let e of r.testLibraries??[])le(e);r.barrelThreshold!==void 0&&Ne(r.barrelThreshold)}var _e=["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage"],Le=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".go",".feature"];import Fs from"fs";import It from"path";function Oe(r,e){let t=It.resolve(r,e);try{let s=Fs.readFileSync(t,"utf-8"),n=JSON.parse(s),o=new Map;for(let[i,a]of Object.entries(n)){if(i==="total")continue;let p=a?.lines?.pct;if(typeof p!="number")continue;let c=It.relative(r,i);o.set(c,p)}return o}catch{return new Map}}var ue={serialize(r){let e=["graph TD"],t=new Set;for(let s of r.nodes.values()){let n=`"${s.path}"`;for(let o of s.imports){if(!o.toPath)continue;let i=`"${o.toPath}"`,a=`${s.path} -> ${o.toPath}`;if(!t.has(a)){let p=o.isStyle?"-- styles -->":"-->";e.push(` ${n} ${p} ${i}`),t.add(a)}}}return e.join(`
3
- `)}};import Mt from"fs";import Ts from"path";function We(r,e){let t=r.replace(/^\.\//,"");if(e.nodes.has(t))return t;let s=t.replace(/^dist\//,"src/").replace(/\.(js|mjs|cjs)$/,".ts");return e.nodes.has(s)?s:null}function Rt(r,e){if(typeof r=="string")return We(r,e);if(r&&typeof r=="object"){let t=r;for(let s of["import","require","default"]){let n=Rt(t[s],e);if(n)return n}}return null}function As(r){if(!r)return"unknown";let e=r.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 Ps(r,e){let t=new Set,s=new Set,n=[...e];for(;n.length;){let o=n.shift();if(s.has(o))continue;s.add(o);let i=r.nodes.get(o);if(i){for(let a of i.exports)t.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 c=r.nodes.get(a.toPath);if(c)for(let u of c.exports)t.add(u.name);n.push(a.toPath)}else for(let c of a.symbols)t.add(c)}}}return t}function ze(r,e){let t=[],s=Ts.join(e,"package.json");if(Mt.existsSync(s))try{let n=JSON.parse(Mt.readFileSync(s,"utf8"));if(n.exports&&typeof n.exports=="object"&&!Array.isArray(n.exports))for(let o of Object.values(n.exports)){let i=Rt(o,r);i&&!t.includes(i)&&t.push(i)}else if(typeof n.exports=="string"){let o=We(n.exports,r);o&&t.push(o)}if(t.length===0)for(let o of[n.main,n.module].filter(Boolean)){let i=We(o,r);i&&!t.includes(i)&&t.push(i)}}catch{}if(t.length===0){for(let n of["src/index.ts","src/index.js","index.ts","index.js"])if(r.nodes.has(n)){t.push(n);break}}return t}function Is(r,e){let t=new Set(e);for(let s of e)r.traverse(s,n=>(t.add(n.path),!0),{direction:"outgoing"});return t}function Ms(r,e,t){let s=new Map;for(let n of e){if(t.includes(n))continue;let o=r.nodes.get(n);if(!o)continue;let i=o.category==="barrel";for(let a of o.exports){let p=s.get(a.name),c=!!(a.signature||a.doc);(!p||c&&!i)&&s.set(a.name,{file:n,symbol:a})}}return s}function Rs(r,e,t,s){let n=[];for(let o of r){let i=e.get(o),a=s.flatMap(f=>t.nodes.get(f)?.exports??[]).find(f=>f.name===o),p=i?.symbol??a,c=i?.file??s.find(f=>t.nodes.get(f)?.exports.some(g=>g.name===o))??s[0],u={name:o,definedIn:c,kind:As(p?.signature)};p?.doc&&(u.doc=p.doc),p?.signature&&(u.signature=p.signature),n.push(u)}return n.sort((o,i)=>o.name.localeCompare(i.name)),n}function Ns(r,e,t){let s=p=>r.nodes.get(p)?.category==="test",n=[...e].filter(p=>!t.includes(p)&&!s(p)),o=[...r.nodes.keys()].filter(p=>!e.has(p)),i=o.filter(p=>!s(p)),a=o.filter(p=>s(p));return{internalFiles:n,unreachableFromEntry:i,testFiles:a}}function $e(r,e){if(e.length===0)throw new Error("buildApiSurface requires at least one entry point");for(let c of e)if(!r.nodes.has(c))throw new Error(`Entry point not found in graph: ${c}`);let t=Is(r,e),s=Ms(r,t,e),n=Ps(r,e),o=Rs(n,s,r,e),{internalFiles:i,unreachableFromEntry:a,testFiles:p}=Ns(r,t,e);return{entryPoints:e,publicExports:o,internalFiles:i,unreachableFromEntry:a,testFiles:p}}function Be(r,e){let t=null,s=[];for(let o of r.nodes.values()){o.exports.some(i=>i.name===e)&&(t=o.path);for(let i of o.callEdges??[])i.to===e&&s.push({file:o.path,callerFunction:i.from})}let n=[];if(t){let o=r.nodes.get(t);for(let i of o?.callEdges??[])i.from===e&&n.push({file:i.toFile,calleeFunction:i.to})}return{functionName:e,definedIn:t,callers:s,callees:n}}import ra from"fs";import na from"path";function Nt(r){let e=[...r.nodes.entries()].sort(([s],[n])=>s.localeCompare(n)).map(([s,n])=>`${s}:${n.mtime}:${n.size}`).join("|"),t=2166136261;for(let s=0;s<e.length;s++)t^=e.charCodeAt(s),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Ue(r){let e=new Map;for(let t of r.nodes.keys()){let s=[];r.traverse(t,n=>(n.path!==t&&s.push(n.path),!0),{direction:"incoming"}),e.set(t,s)}return{impact:e,graphHash:Nt(r)}}function qe(r,e){return r.impact.get(e)??[]}import fe from"path";function Gs(r){let e=new Map;for(let[t,s]of r){let n=s.imports.filter(o=>o.toPath&&!o.isExternal).length;n>0&&e.set(t,n)}return e}function Ds(r,e,t){let s=new Map;for(let[n,o]of e){if(o<t)continue;let i=r.get(n);if(!i||i.category==="test"||i.category==="barrel")continue;let a=fe.extname(n),p=fe.basename(n,a),c=p==="index"?fe.basename(fe.dirname(n)):p;s.set(n,{path:n,outDegree:o,tag:`feature:${c}`})}return s}function I(r,e){let t=e?.minOutDegree??5;return Ds(r,Gs(r),t)}var js=(r,e)=>r.outDegree-e.outDegree;function _s(r,e){let t=new Map;for(let s of e.values()){let n=new Set;r.traverse(s.path,o=>(o.path!==s.path&&n.add(o.path),!0),{direction:"outgoing"}),t.set(s.path,n)}return t}function Ls(r,e,t,s){let n=new Map;for(let[o]of r){if(e.has(o))continue;let i=null;for(let a of e.values())t.get(a.path)?.has(o)&&(!i||s(a,i)<0)&&(i=a);i&&n.set(o,i.path)}return n}function Os(r,e){let t=new Map;for(let s of r.values()){let n=s.tag.replace("feature:",""),o=[];for(let[i,a]of e)a===s.path&&o.push(i);t.set(n,{hub:s.path,outDegree:s.outDegree,files:o})}return t}function Ws(r,e,t){let s=[];for(let n of r.keys())!e.has(n)&&!t.has(n)&&s.push(n);return s}function J(r,e){let t=e?.detectFn??I,s=e?.hubComparator??js,n=t(r.nodes,e),o=_s(r,n),i=Ls(r.nodes,n,o,s);return{features:Os(n,i),unassigned:Ws(r.nodes,n,i)}}var H=class{constructor(e){this.nodes=e}nodes;findUnusedFiles(e){let t=new Set(this.nodes.keys());return e.filter(s=>!t.has(s))}findHighExportUsage(e){let t=[];for(let s of this.nodes.values()){if(s.maxExportUsage===void 0||s.maxExportUsage<e)continue;let n=s.imports.reduce((o,i)=>(i.exportUsageRatio??0)>(o?.exportUsageRatio??0)?i:o,null);t.push({path:s.path,maxExportUsage:s.maxExportUsage,tightestDep:n?.toPath??""})}return t.sort((s,n)=>n.maxExportUsage-s.maxExportUsage)}findCycles(){let e=[],t=new Set,s=new Set,n=[],o=i=>{t.add(i),s.add(i),n.push(i);let a=this.nodes.get(i);if(a){for(let p of a.imports)if(!(!p.toPath||p.isExternal))if(s.has(p.toPath)){let c=n.indexOf(p.toPath);e.push([...n.slice(c),p.toPath])}else t.has(p.toPath)||o(p.toPath)}s.delete(i),n.pop()};for(let i of this.nodes.keys())t.has(i)||o(i);return e}};var E=class r{constructor(e){this.nodes=e}nodes;_incomingEdgesCache=null;_callIncomingCache=null;serialize(){return{nodes:Array.from(this.nodes.values())}}static deserialize(e){let t=new Map;for(let s of e.nodes)t.set(s.path,s);return new r(t)}getIncomingEdgesMap(){if(this._incomingEdgesCache)return this._incomingEdgesCache;let e=new Map;for(let t of this.nodes.values())for(let s of t.imports)if(s.toPath){let n=e.get(s.toPath)||[];n.push(t.path),e.set(s.toPath,n)}return this._incomingEdgesCache=e,e}dfs(e,t,s,n){let o=new Set,i=s.maxDepth??1/0,a=(p,c,u)=>{if(c>i||o.has(p))return;let f=this.nodes.get(p);if(f&&(o.add(p),t(f,c,u)!==!1))for(let g of n(p))a(g,c+1,p)};a(e,0,null)}traverse(e,t,s={}){let n=s.direction??"outgoing",o=n==="incoming"?this.getIncomingEdgesMap():null;this.dfs(e,t,s,i=>n==="outgoing"?this.nodes.get(i)?.imports.map(a=>a.toPath).filter(Boolean)??[]:o?.get(i)??[])}getCallIncomingCache(){if(this._callIncomingCache)return this._callIncomingCache;let e=new Map;for(let t of this.nodes.values())for(let s of t.callEdges??[]){let n=e.get(s.toFile)??[];n.push(t.path),e.set(s.toFile,n)}return this._callIncomingCache=e,e}traverseCalls(e,t,s={}){let n=s.direction??"outgoing",o=n==="incoming"?this.getCallIncomingCache():null;this.dfs(e,t,s,i=>n==="outgoing"?this.nodes.get(i)?.callEdges?.map(a=>a.toFile)??[]:o?.get(i)??[])}getCallers(e){let t=[];return this.traverseCalls(e,s=>(s.path!==e&&t.push(s.path),!0),{direction:"incoming",maxDepth:1}),t}getCallEdgesFor(e){return this.nodes.get(e)?.callEdges??[]}getNeighbors(e){let t=this.nodes.get(e);return t?t.imports.map(s=>this.nodes.get(s.toPath)).filter(s=>s!==void 0):[]}findUnusedFiles(e){return new H(this.nodes).findUnusedFiles(e)}findCycles(){return new H(this.nodes).findCycles()}};function Gt(r){if(r.category==="test")return"test";if(r.category==="config")return"config";if(r.category==="type-only")return"types";let e=r.path;return d(e,"component")||d(e,"components")?"component":d(e,"controller")||d(e,"controllers")?"controller":d(e,"middleware")?"middleware":d(e,"router")||d(e,"routes")||d(e,"route")?"router":d(e,"store")||d(e,"stores")?"store":d(e,"service")||d(e,"services")?"service":d(e,"handler")||d(e,"handlers")?"handler":d(e,"adapter")||d(e,"adapters")?"adapter":d(e,"plugin")||d(e,"plugins")?"plugin":d(e,"api")?"api":d(e,"cli")||d(e,"commands")||Q(e)==="cli"?"cli":d(e,"util")||d(e,"utils")||d(e,"helper")||d(e,"helpers")?"util":d(e,"model")||d(e,"models")||Q(e)==="model"?"model":d(e,"parser")||d(e,"parsers")||Q(e)==="parser"?"parser":Q(e)==="builder"?"builder":Q(e)==="resolver"?"resolver":"other"}function d(r,e){return r.includes(`/${e}/`)||r.includes(`/${e}.`)}function Q(r){let e=r.slice(r.lastIndexOf("/")+1);return e.slice(0,e.lastIndexOf("."))||e}function Ke(r,e){let t=J(r,e),s=new Map;for(let[o,i]of t.features){for(let a of i.files)s.set(a,o);s.set(i.hub,o)}let n=new Map;for(let o of r.nodes.values()){let i=s.get(o.path);n.set(o.path,{path:o.path,role:Gt(o),...o.description?{description:o.description}:{},exports:o.exports.map(a=>a.name),...i?{featureHub:i}:{}})}return n}var M=class{affectedSymbols=new Map;constructor(e,t){this.affectedSymbols.set(e,new Set(["default",...t]))}updateAffectedSymbols(e,t){let s=this.affectedSymbols.get(t)||new Set,n=e.imports.find(p=>p.toPath===t);if(!n)return!1;let o=n.symbols||["*"],i=new Set;for(let p of o)(p==="*"||s.has("*")||s.has(p))&&i.add("*");if(i.size===0)return!1;let a=this.affectedSymbols.get(e.path)||new Set;for(let p of i)a.add(p);return this.affectedSymbols.set(e.path,a),!0}};function zs(r){return r?r.startsWith("interface ")?"interface":r.startsWith("class ")?"class":r.startsWith("enum ")?"enum":"type":"type"}function $s(r,e){if(e==="type-only")return!0;let t=r.signature??"";return t.startsWith("interface ")||t.startsWith("class ")||t.startsWith("enum ")}function Je(r){let e=new Map;for(let s of r.nodes.values())if(!(s.type!=="typescript"&&s.type!=="javascript"))for(let n of s.exports){if(!$s(n,s.category))continue;let o=`${s.path}::${n.name}`;e.set(o,{name:n.name,file:s.path,kind:zs(n.signature),...n.doc?{doc:n.doc}:{}})}let t=[];for(let s of r.nodes.values())if(!(s.type!=="typescript"&&s.type!=="javascript")){for(let n of s.imports)if(!(!n.toPath||n.isExternal||!n.symbols?.length))for(let o of n.symbols)e.has(`${n.toPath}::${o}`)&&t.push({fromFile:s.path,toType:o,toFile:n.toPath})}return{types:e,edges:t}}function He(r,e){let t=null;for(let o of r.types.values())if(o.name===e){t=o;break}if(!t)return{type:null,usedByFiles:[],uses:[]};let s=new Set,n=new Map;for(let o of r.edges)if(o.toType===e&&o.toFile===t.file&&s.add(o.fromFile),o.fromFile===t.file){let i=r.types.get(`${o.toFile}::${o.toType}`);i&&n.set(`${i.file}::${i.name}`,i)}return{type:t,usedByFiles:Array.from(s),uses:Array.from(n.values())}}import en from"path";import Ve from"fs";import Lt from"path";import V from"fs";import k from"path";import Dt from"fs";import va from"path";function jt(r){try{return Dt.statSync(r,{throwIfNoEntry:!1})?.isDirectory()===!0}catch{return!1}}function ge(r){try{return Dt.statSync(r,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}function Qe(r,e){let t=k.join(e,"package.json");if(!V.existsSync(t))return null;let s={};try{s=JSON.parse(V.readFileSync(t,"utf-8"))}catch{return null}let n=s.name;return n?{name:n,root:e,relativeRoot:k.relative(r,e),entryPoints:Bs(e,s)}:null}function Bs(r,e){let t=[];if(e.exports){let n=e.exports;if(typeof n=="string")t.push(k.join(r,n));else if(typeof n=="object"&&n!==null){let o=n["."];if(typeof o=="string")t.push(k.join(r,o));else if(typeof o=="object"&&o!==null){let i=o.import??o.require??o.default;typeof i=="string"&&t.push(k.join(r,i))}}}e.main&&t.push(k.join(r,e.main));for(let n of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"])t.push(k.join(r,n));let s=t.filter(ge);return s.length>0?s.slice(0,1):t.slice(0,1)}function R(r,e){let t=[],s=new Set;for(let n of e){let o=n.replace(/\/$/,"").replace(/^\.\//,"");Us(r,o,s,t)}return t}function Us(r,e,t,s){if(!e.includes("*")){qs(r,e,t,s);return}let n=e.split("/");n.includes("**")?Ks(r,n,t,s):Js(r,n,t,s)}function qs(r,e,t,s){let n=k.join(r,e);if(t.has(n)||!jt(n))return;t.add(n);let o=Qe(r,n);o&&s.push(o)}function Ks(r,e,t,s){let n=k.join(r,e[0]==="**"?"":e[0]??"");_t(r,n,t,s)}function Js(r,e,t,s){let n=e.findIndex(a=>a.includes("*")),o=k.join(r,...e.slice(0,n)),i;try{i=V.readdirSync(o,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let p=k.join(o,a.name);if(t.has(p))continue;t.add(p);let c=Qe(r,p);c&&s.push(c)}}function _t(r,e,t,s){let n;try{n=V.readdirSync(e,{withFileTypes:!0})}catch{return}for(let o of n){if(!o.isDirectory()||o.name==="node_modules"||o.name.startsWith("."))continue;let i=k.join(e,o.name);if(V.existsSync(k.join(i,"package.json"))&&!t.has(i)){t.add(i);let a=Qe(r,i);a&&s.push(a)}else _t(r,i,t,s)}}var Ot={type:"npm",detect(r){let e=Lt.join(r,"package.json");if(!Ve.existsSync(e))return null;let t;try{t=JSON.parse(Ve.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!t||Ve.existsSync(Lt.join(r,"yarn.lock")))return null;let s=Array.isArray(t)?t:t.packages??[];return s.length===0?null:R(r,s)}};import N from"fs";import S from"path";var Wt={type:"nx",detect(r){return N.existsSync(S.join(r,"nx.json"))?zt(r,r,new Set,0).map(t=>Hs(r,t,S.join(t,"project.json"))).filter(t=>t!==null):null}};function zt(r,e,t,s){if(s>4)return[];let n;try{n=N.readdirSync(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let i of n){if(!i.isDirectory())continue;let a=i.name;if(a.startsWith(".")||a==="node_modules"||a==="dist"||a===".nx")continue;let p=S.join(e,a);N.existsSync(S.join(p,"project.json"))&&!t.has(p)?(t.add(p),o.push(p)):o.push(...zt(r,p,t,s+1))}return o}function Hs(r,e,t){let s={};try{s=JSON.parse(N.readFileSync(t,"utf-8"))}catch{return null}let n=s.name,o,i,a=S.join(e,"package.json");if(N.existsSync(a))try{let p=JSON.parse(N.readFileSync(a,"utf-8"));n=p.name??n,o=p.main,i=p.exports}catch{}return n?{name:n,root:e,relativeRoot:S.relative(r,e),entryPoints:Qs(e,s,o,i)}:null}function Qs(r,e,t,s){let n=[],o=e.targets?.build?.options?.main??e.targets?.build?.options?.entryFile;if(o){let a=S.resolve(r,"../..");n.push(S.resolve(a,o)),n.push(S.resolve(r,o))}if(s){let a=s;if(typeof a=="string")n.push(S.join(r,a));else if(typeof a=="object"&&a!==null){let p=a["."];typeof p=="string"&&n.push(S.join(r,p))}}if(t&&n.push(S.join(r,t)),e.sourceRoot){let a=S.resolve(r,"../.."),p=S.resolve(a,e.sourceRoot);n.push(S.join(p,"index.ts"),S.join(p,"index.tsx"))}for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx"])n.push(S.join(r,a));let i=n.filter(ge);return i.length>0?i.slice(0,1):n.slice(0,1)}import $t from"fs";import Vs from"path";import Xs from"js-yaml";var Bt={type:"pnpm",detect(r){let e=Vs.join(r,"pnpm-workspace.yaml");if(!$t.existsSync(e))return null;let t=[];try{t=Xs.load($t.readFileSync(e,"utf-8"))?.packages??[]}catch{return null}return R(r,t)}};import Zs from"fs";import Ys from"path";var Ut={type:"turborepo",detect(r){return Zs.existsSync(Ys.join(r,"turbo.json"))?[]:null}};import Xe from"fs";import qt from"path";var Kt={type:"yarn",detect(r){if(!Xe.existsSync(qt.join(r,"yarn.lock")))return null;let e=qt.join(r,"package.json");if(!Xe.existsSync(e))return null;let t;try{t=JSON.parse(Xe.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!t)return null;let s=Array.isArray(t)?t:t.packages??[];return s.length===0?null:R(r,s)}};var Jt=[];function T(r){Jt.push(r)}function Ht(){return Jt}T(Ut);T(Wt);T(Bt);T(Kt);T(Ot);function X(r,e=Ht()){let t=en.resolve(r),s=new Map,n=[];for(let i of e){let a=i.detect(t);if(a!==null){n.push(i.type);for(let p of a)s.has(p.name)||s.set(p.name,p)}}if(n.length===0)return{root:t,type:"none",types:[],packages:[],packageMap:new Map};let o=Array.from(s.values());return{root:t,type:n[0],types:n,packages:o,packageMap:new Map(o.map(i=>[i.name,i]))}}var Z=class r{constructor(e,t){this.monorepoRoot=e;this.type=t}monorepoRoot;type;packages=new Map;addPackage(e,t){this.packages.set(e.name,{graph:t,pkg:e})}getPackageForFile(e){for(let{pkg:t}of this.packages.values())if(e===t.relativeRoot||e.startsWith(`${t.relativeRoot}/`))return t}getPackageDependencies(){let e=new Map;for(let{graph:t,pkg:s}of this.packages.values()){let n=new Set;for(let o of t.nodes.values())for(let i of o.imports)i.isWorkspace&&i.workspacePackage&&n.add(i.workspacePackage);e.set(s.name,[...n])}return e}getAffectedAcrossPackages(e){let t=this.getPackageForFile(e);if(!t)return[];let s=this.packages.get(t.name);if(!s)return[];let n=[];s.graph.traverse(e,o=>(o.path!==e&&n.push({file:o.path,package:t.name}),!0),{direction:"incoming"});for(let{graph:o,pkg:i}of this.packages.values())if(i.name!==t.name)for(let a of o.nodes.values())a.imports.some(c=>c.isWorkspace&&c.workspacePackage===t.name)&&n.push({file:a.path,package:i.name});return n}serialize(){return{monorepoRoot:this.monorepoRoot,type:this.type,packages:Array.from(this.packages.values()).map(({graph:e,pkg:t})=>({pkg:{name:t.name,relativeRoot:t.relativeRoot,entryPoints:t.entryPoints},nodes:Array.from(e.nodes.values())}))}}static deserialize(e){let t=new r(e.monorepoRoot,e.type);for(let{pkg:s,nodes:n}of e.packages){let o=new Map(n.map(a=>[a.path,a])),i=new E(o);t.packages.set(s.name,{graph:i,pkg:{...s,root:""}})}return t}};var Qt=new Map;function G(r,e){Qt.set(r,e)}function Vt(r){return Qt.get(r)}function Xt(r,e){return e.startsWith("!")?r!==e.slice(1):r===e}function tn(r,e){return e.startsWith("!")?!r.includes(e.slice(1)):r.includes(e)}var rn=(r,e)=>!e.category||Xt(r.category,e.category),sn=(r,e)=>!e.type||Xt(r.type,e.type),nn=(r,e)=>!e.path||tn(r.path,e.path),on=(r,e)=>e.isExternal===void 0?!0:r.imports.some(s=>s.isExternal)===e.isExternal,an=(r,e)=>{if(!e.tags||e.tags.length===0)return!0;let t=e.tags.filter(n=>!n.startsWith("!")),s=e.tags.filter(n=>n.startsWith("!")).map(n=>n.slice(1));return!(t.length>0&&!t.some(n=>r.tags.some(o=>o.name===n))||s.some(n=>r.tags.some(o=>o.name===n)))},pn=(r,e)=>!e.allTags?.length||e.allTags.every(t=>r.tags.some(s=>s.name===t)),cn=(r,e)=>!e.importsFile||r.imports.some(t=>t.toPath?.includes(e.importsFile)),ln=(r,e,t)=>e.importedBy===void 0?!0:(t?.get(r.path)??[]).some(n=>n.includes(e.importedBy)),un=(r,e)=>e.minImports===void 0||r.imports.length>=e.minImports,fn=(r,e)=>e.maxImports===void 0||r.imports.length<=e.maxImports,gn=(r,e)=>e.minSize===void 0||r.size>=e.minSize,mn=(r,e)=>e.maxSize===void 0||r.size<=e.maxSize,dn=(r,e)=>e.hasDocstring===void 0||!!r.description===e.hasDocstring,hn=(r,e)=>e.minCoverage===void 0||(r.coveragePct??101)>=e.minCoverage,yn=(r,e)=>e.maxCoverage===void 0||(r.coveragePct??0)<=e.maxCoverage,xn=(r,e)=>e.minExportUsage===void 0||(r.avgExportUsage??-1)>=e.minExportUsage,Sn=(r,e)=>e.maxExportUsage===void 0||(r.avgExportUsage??0)<=e.maxExportUsage,Zt=[rn,sn,nn,on,an,pn,cn,ln,un,fn,gn,mn,dn,hn,yn,xn,Sn];function Yt(r,e,t){return Zt.every(s=>s(r,e,t))}function me(r,e){let t=new Map;if(e.importedBy!==void 0){for(let i of r.nodes)for(let a of i.imports)if(a.toPath){let p=t.get(a.toPath)??[];p.push(i.path),t.set(a.toPath,p)}}let s=r.nodes.filter(i=>Yt(i,e,t)),n=new Set(s.map(i=>i.path)),o=s.map(i=>({...i,imports:i.imports.filter(a=>!a.toPath||n.has(a.toPath))}));return e.sort&&o.sort((i,a)=>e.sort==="size"?a.size-i.size:e.sort==="imports"?a.imports.length-i.imports.length:e.sort==="commitCount90d"?(a.commitCount90d??0)-(i.commitCount90d??0):e.sort==="exportUsage"?(a.avgExportUsage??0)-(i.avgExportUsage??0):0),e.limit!==void 0&&o.splice(e.limit),{nodes:o,cycles:r.cycles?.filter(i=>i.every(a=>n.has(a)))??void 0}}function de(r){let e={},t=r.split(",");for(let s of t){let n=s.indexOf(":");if(n===-1)continue;let o=s.slice(0,n).trim().toLowerCase(),i=s.slice(n+1).trim();if(!(!o||!i))switch(o){case"category":e.category=i;break;case"type":e.type=i;break;case"tag":case"tags":i.includes("+")?e.allTags=[...e.allTags??[],...i.split("+")]:e.tags=[...e.tags??[],i];break;case"path":e.path=i;break;case"external":e.isExternal=i.toLowerCase()==="true";break;case"importsfile":e.importsFile=i;break;case"importedby":e.importedBy=i;break;case"minimports":e.minImports=parseInt(i,10);break;case"maximports":e.maxImports=parseInt(i,10);break;case"minsize":e.minSize=parseInt(i,10);break;case"maxsize":e.maxSize=parseInt(i,10);break;case"sort":e.sort=i;break;case"limit":e.limit=parseInt(i,10);break;case"hasdocstring":e.hasDocstring=i.toLowerCase()!=="false";break;case"mincoverage":e.minCoverage=parseInt(i,10);break;case"maxcoverage":e.maxCoverage=parseInt(i,10);break;case"minexportusage":e.minExportUsage=parseFloat(i);break;case"maxexportusage":e.maxExportUsage=parseFloat(i);break}}return e}import ur from"fs/promises";import Bn from"path";import st from"path";import we from"typescript";import tr from"path";import rr from"typescript";import b from"typescript";var er=new Set(["describe","test","it"]);function D(r){let e=[];for(let t of r.statements){if(!b.isExpressionStatement(t))continue;let s=t.expression;if(!b.isCallExpression(s))continue;let n=s.expression;b.isIdentifier(n)&&er.has(n.text)&&e.push(s),b.isPropertyAccessExpression(n)&&b.isIdentifier(n.expression)&&er.has(n.expression.text)&&e.push(s)}return e}function j(r,e,t){for(let s of r.arguments){if(!b.isObjectLiteralExpression(s))continue;let n=s.properties.find(o=>b.isPropertyAssignment(o)&&b.isIdentifier(o.name)&&o.name.text===e);if(!(!n||!b.isArrayLiteralExpression(n.initializer)))return n.initializer.elements.filter(b.isStringLiteral).map(o=>o.text)}return null}function _(r,e,t,s){if(r.arguments.length===0)return null;for(let o=1;o<r.arguments.length;o++){let i=r.arguments[o];if(!b.isObjectLiteralExpression(i))continue;let a=i.properties.find(c=>b.isPropertyAssignment(c)&&b.isIdentifier(c.name)&&c.name.text===e);if(a)return{start:a.initializer.getStart(s),end:a.initializer.getEnd(),text:t};let p=i.getEnd()-1;return{start:p,end:p,text:`${i.properties.length>0?", ":""}${e}: ${t}`}}let n=r.arguments[r.arguments.length-1];return{start:n.getStart(s),end:n.getStart(s),text:`{ ${e}: ${t} }, `}}function L(r,e,t){let s=r.arguments;for(let n=1;n<s.length;n++){let o=s[n];if(!b.isObjectLiteralExpression(o))continue;let i=o.properties.findIndex(p=>b.isPropertyAssignment(p)&&b.isIdentifier(p.name)&&p.name.text===e);if(i<0)continue;if(o.properties.length===1)return{start:s[n-1].getEnd(),end:o.getEnd(),text:""};let a=o.properties[i];return i===o.properties.length-1?{start:o.properties[i-1].getEnd(),end:a.getEnd(),text:""}:{start:a.getStart(t),end:o.properties[i+1].getStart(t),text:""}}return null}function O(r,e){let t=[...e].sort((n,o)=>o.start-n.start),s=r;for(let n of t)s=s.slice(0,n.start)+n.text+s.slice(n.end);return s}function W(r){return`[${r.map(e=>JSON.stringify(e)).join(", ")}]`}var C=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);function bn(r){return W(r.map(e=>`@${e}`))}function vn(r){return r.map(e=>e.startsWith("@")?e.slice(1):e)}var he=class{name="cypress";canHandle(e){return C.has(tr.extname(e).toLowerCase())}apply(e,t,s){let n=rr.createSourceFile(tr.basename(e),t,rr.ScriptTarget.Latest,!0),o=D(n);if(o.length===0)return t;let i=j(o[0],"tags",n),a=[...s].sort();if(i!==null&&JSON.stringify(vn(i).sort())===JSON.stringify(a))return t;let p=o.flatMap(c=>{let u=s.length===0?L(c,"tags",n):_(c,"tags",bn(a),n);return u?[u]:[]});return p.length>0?O(t,p):t}};import kn from"path";var Ze=/# <mokosh-tags>[\s\S]*?# <\/mokosh-tags>\n*/,Ye=/^@([a-zA-Z0-9_-]+)/gm;function wn(r){return["# <mokosh-tags>",...r.map(e=>`@${e}`),"# </mokosh-tags>"].join(`
2
+ var Re=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});import{StdioServerTransport as Oi}from"@modelcontextprotocol/sdk/server/stdio.js";import{Server as _i}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as ji,ListToolsRequestSchema as Li}from"@modelcontextprotocol/sdk/types.js";import Ri from"fs";import _e from"fs";import At from"path";var ws=[".config.","biome.json","tsconfig.json","package.json",".prettierrc",".eslintrc"],wt=[];function pe(r){wt.push(r)}function Ct(r){return[...ws,...wt].some(e=>typeof e=="string"?r.includes(e):e instanceof RegExp?e.test(r):e(r))}var Cs=[".test.",".spec.","-test.","-spec."],Ft=[];function ce(r){Ft.push(r)}function q(){return[...Cs,...Ft]}var Fs=["jest","vitest","playwright","cypress","@testing-library/"],Et=[];function le(r){Et.push(r)}function Ne(){return[...Fs,...Et]}var Tt=.8;function Ge(r){Tt=r}function De(){return Tt}var Es=["mokosh.config.js","mokosh.config.cjs","mokosh.config.json"];function K(r,{allowJs:e=!0,isExplicitPath:t=!1}={}){if(t){let s=At.resolve(r);return _e.existsSync(s)?s.endsWith(".json")?Pt(s):e?It(s):{}:{}}for(let s of Es){let n=At.resolve(r,s);if(_e.existsSync(n)){if(s.endsWith(".json"))return Pt(n);if(e)return It(n)}}return{}}function Pt(r){return JSON.parse(_e.readFileSync(r,"utf-8"))}function It(r){let e=Re(r);return e&&typeof e=="object"&&"default"in e&&(e=e.default),typeof e=="function"?e({}):e}function je(r){for(let e of r.configMatchers??[])pe(e);for(let e of r.testPatterns??[])ce(e);for(let e of r.testLibraries??[])le(e);r.barrelThreshold!==void 0&&Ge(r.barrelThreshold)}var Le=["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage"],Oe=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".go",".feature"];import Ts from"fs";import Mt from"path";function We(r,e){let t=Mt.resolve(r,e);try{let s=Ts.readFileSync(t,"utf-8"),n=JSON.parse(s),o=new Map;for(let[i,a]of Object.entries(n)){if(i==="total")continue;let p=a?.lines?.pct;if(typeof p!="number")continue;let c=Mt.relative(r,i);o.set(c,p)}return o}catch{return new Map}}var ue={serialize(r){let e=["graph TD"],t=new Set;for(let s of r.nodes.values()){let n=`"${s.path}"`;for(let o of s.imports){if(!o.toPath)continue;let i=`"${o.toPath}"`,a=`${s.path} -> ${o.toPath}`;if(!t.has(a)){let p=o.isStyle?"-- styles -->":"-->";e.push(` ${n} ${p} ${i}`),t.add(a)}}}return e.join(`
3
+ `)}};import Rt from"fs";import Ps from"path";function ze(r,e){let t=r.replace(/^\.\//,"");if(e.nodes.has(t))return t;let s=t.replace(/^dist\//,"src/").replace(/\.(js|mjs|cjs)$/,".ts");return e.nodes.has(s)?s:null}function Nt(r,e){if(typeof r=="string")return ze(r,e);if(r&&typeof r=="object"){let t=r;for(let s of["import","require","default"]){let n=Nt(t[s],e);if(n)return n}}return null}function Is(r){if(!r)return"unknown";let e=r.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 Ms(r,e){let t=new Set,s=new Set,n=[...e];for(;n.length;){let o=n.shift();if(s.has(o))continue;s.add(o);let i=r.nodes.get(o);if(i){for(let a of i.exports)t.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 c=r.nodes.get(a.toPath);if(c)for(let u of c.exports)t.add(u.name);n.push(a.toPath)}else for(let c of a.symbols)t.add(c)}}}return t}function $e(r,e){let t=[],s=Ps.join(e,"package.json");if(Rt.existsSync(s))try{let n=JSON.parse(Rt.readFileSync(s,"utf8"));if(n.exports&&typeof n.exports=="object"&&!Array.isArray(n.exports))for(let o of Object.values(n.exports)){let i=Nt(o,r);i&&!t.includes(i)&&t.push(i)}else if(typeof n.exports=="string"){let o=ze(n.exports,r);o&&t.push(o)}if(t.length===0)for(let o of[n.main,n.module].filter(Boolean)){let i=ze(o,r);i&&!t.includes(i)&&t.push(i)}}catch{}if(t.length===0){for(let n of["src/index.ts","src/index.js","index.ts","index.js"])if(r.nodes.has(n)){t.push(n);break}}return t}function Rs(r,e){let t=new Set(e);for(let s of e)r.traverse(s,n=>(t.add(n.path),!0),{direction:"outgoing"});return t}function Ns(r,e,t){let s=new Map;for(let n of e){if(t.includes(n))continue;let o=r.nodes.get(n);if(!o)continue;let i=o.category==="barrel";for(let a of o.exports){let p=s.get(a.name),c=!!(a.signature||a.doc);(!p||c&&!i)&&s.set(a.name,{file:n,symbol:a})}}return s}function Gs(r,e,t,s){let n=[];for(let o of r){let i=e.get(o),a=s.flatMap(f=>t.nodes.get(f)?.exports??[]).find(f=>f.name===o),p=i?.symbol??a,c=i?.file??s.find(f=>t.nodes.get(f)?.exports.some(g=>g.name===o))??s[0],u={name:o,definedIn:c,kind:Is(p?.signature)};p?.doc&&(u.doc=p.doc),p?.signature&&(u.signature=p.signature),n.push(u)}return n.sort((o,i)=>o.name.localeCompare(i.name)),n}function Ds(r,e,t){let s=p=>r.nodes.get(p)?.category==="test",n=[...e].filter(p=>!t.includes(p)&&!s(p)),o=[...r.nodes.keys()].filter(p=>!e.has(p)),i=o.filter(p=>!s(p)),a=o.filter(p=>s(p));return{internalFiles:n,unreachableFromEntry:i,testFiles:a}}function Be(r,e){if(e.length===0)throw new Error("buildApiSurface requires at least one entry point");for(let c of e)if(!r.nodes.has(c))throw new Error(`Entry point not found in graph: ${c}`);let t=Rs(r,e),s=Ns(r,t,e),n=Ms(r,e),o=Gs(n,s,r,e),{internalFiles:i,unreachableFromEntry:a,testFiles:p}=Ds(r,t,e);return{entryPoints:e,publicExports:o,internalFiles:i,unreachableFromEntry:a,testFiles:p}}function Ue(r,e){let t=null,s=[];for(let o of r.nodes.values()){o.exports.some(i=>i.name===e)&&(t=o.path);for(let i of o.callEdges??[])i.to===e&&s.push({file:o.path,callerFunction:i.from})}let n=[];if(t){let o=r.nodes.get(t);for(let i of o?.callEdges??[])i.from===e&&n.push({file:i.toFile,calleeFunction:i.to})}return{functionName:e,definedIn:t,callers:s,callees:n}}import ia from"fs";import pa from"path";function Gt(r){let e=[...r.nodes.entries()].sort(([s],[n])=>s.localeCompare(n)).map(([s,n])=>`${s}:${n.mtime}:${n.size}`).join("|"),t=2166136261;for(let s=0;s<e.length;s++)t^=e.charCodeAt(s),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function qe(r){let e=new Map;for(let t of r.nodes.keys()){let s=[];r.traverse(t,n=>(n.path!==t&&s.push(n.path),!0),{direction:"incoming"}),e.set(t,s)}return{impact:e,graphHash:Gt(r)}}function Ke(r,e){return r.impact.get(e)??[]}import fe from"path";function _s(r){let e=new Map;for(let[t,s]of r){let n=s.imports.filter(o=>o.toPath&&!o.isExternal).length;n>0&&e.set(t,n)}return e}function js(r,e,t){let s=new Map;for(let[n,o]of e){if(o<t)continue;let i=r.get(n);if(!i||i.category==="test"||i.category==="barrel")continue;let a=fe.extname(n),p=fe.basename(n,a),c=p==="index"?fe.basename(fe.dirname(n)):p;s.set(n,{path:n,outDegree:o,tag:`feature:${c}`})}return s}function I(r,e){let t=e?.minOutDegree??5;return js(r,_s(r),t)}var Ls=(r,e)=>r.outDegree-e.outDegree;function Os(r,e){let t=new Map;for(let s of e.values()){let n=new Set;r.traverse(s.path,o=>(o.path!==s.path&&n.add(o.path),!0),{direction:"outgoing"}),t.set(s.path,n)}return t}function Ws(r,e,t,s){let n=new Map;for(let[o]of r){if(e.has(o))continue;let i=null;for(let a of e.values())t.get(a.path)?.has(o)&&(!i||s(a,i)<0)&&(i=a);i&&n.set(o,i.path)}return n}function zs(r,e){let t=new Map;for(let s of r.values()){let n=s.tag.replace("feature:",""),o=[];for(let[i,a]of e)a===s.path&&o.push(i);t.set(n,{hub:s.path,outDegree:s.outDegree,files:o})}return t}function $s(r,e,t){let s=[];for(let n of r.keys())!e.has(n)&&!t.has(n)&&s.push(n);return s}function J(r,e){let t=e?.detectFn??I,s=e?.hubComparator??Ls,n=t(r.nodes,e),o=Os(r,n),i=Ws(r.nodes,n,o,s);return{features:zs(n,i),unassigned:$s(r.nodes,n,i)}}var H=class{constructor(e){this.nodes=e}nodes;findUnusedFiles(e){let t=new Set(this.nodes.keys());return e.filter(s=>!t.has(s))}findHighExportUsage(e){let t=[];for(let s of this.nodes.values()){if(s.maxExportUsage===void 0||s.maxExportUsage<e)continue;let n=s.imports.reduce((o,i)=>(i.exportUsageRatio??0)>(o?.exportUsageRatio??0)?i:o,null);t.push({path:s.path,maxExportUsage:s.maxExportUsage,tightestDep:n?.toPath??""})}return t.sort((s,n)=>n.maxExportUsage-s.maxExportUsage)}findCycles(){let e=[],t=new Set,s=new Set,n=[],o=i=>{t.add(i),s.add(i),n.push(i);let a=this.nodes.get(i);if(a){for(let p of a.imports)if(!(!p.toPath||p.isExternal))if(s.has(p.toPath)){let c=n.indexOf(p.toPath);e.push([...n.slice(c),p.toPath])}else t.has(p.toPath)||o(p.toPath)}s.delete(i),n.pop()};for(let i of this.nodes.keys())t.has(i)||o(i);return e}};var E=class r{constructor(e){this.nodes=e}nodes;_incomingEdgesCache=null;_callIncomingCache=null;serialize(){return{nodes:Array.from(this.nodes.values())}}static deserialize(e){let t=new Map;for(let s of e.nodes)t.set(s.path,s);return new r(t)}getIncomingEdgesMap(){if(this._incomingEdgesCache)return this._incomingEdgesCache;let e=new Map;for(let t of this.nodes.values())for(let s of t.imports)if(s.toPath){let n=e.get(s.toPath)||[];n.push(t.path),e.set(s.toPath,n)}return this._incomingEdgesCache=e,e}dfs(e,t,s,n){let o=new Set,i=s.maxDepth??1/0,a=(p,c,u)=>{if(c>i||o.has(p))return;let f=this.nodes.get(p);if(f&&(o.add(p),t(f,c,u)!==!1))for(let g of n(p))a(g,c+1,p)};a(e,0,null)}traverse(e,t,s={}){let n=s.direction??"outgoing",o=n==="incoming"?this.getIncomingEdgesMap():null;this.dfs(e,t,s,i=>n==="outgoing"?this.nodes.get(i)?.imports.map(a=>a.toPath).filter(Boolean)??[]:o?.get(i)??[])}getCallIncomingCache(){if(this._callIncomingCache)return this._callIncomingCache;let e=new Map;for(let t of this.nodes.values())for(let s of t.callEdges??[]){let n=e.get(s.toFile)??[];n.push(t.path),e.set(s.toFile,n)}return this._callIncomingCache=e,e}traverseCalls(e,t,s={}){let n=s.direction??"outgoing",o=n==="incoming"?this.getCallIncomingCache():null;this.dfs(e,t,s,i=>n==="outgoing"?this.nodes.get(i)?.callEdges?.map(a=>a.toFile)??[]:o?.get(i)??[])}getCallers(e){let t=[];return this.traverseCalls(e,s=>(s.path!==e&&t.push(s.path),!0),{direction:"incoming",maxDepth:1}),t}getCallEdgesFor(e){return this.nodes.get(e)?.callEdges??[]}getNeighbors(e){let t=this.nodes.get(e);return t?t.imports.map(s=>this.nodes.get(s.toPath)).filter(s=>s!==void 0):[]}findUnusedFiles(e){return new H(this.nodes).findUnusedFiles(e)}findCycles(){return new H(this.nodes).findCycles()}};function Dt(r){if(r.category==="test")return"test";if(r.category==="config")return"config";if(r.category==="type-only")return"types";let e=r.path;return d(e,"component")||d(e,"components")?"component":d(e,"controller")||d(e,"controllers")?"controller":d(e,"middleware")?"middleware":d(e,"router")||d(e,"routes")||d(e,"route")?"router":d(e,"store")||d(e,"stores")?"store":d(e,"service")||d(e,"services")?"service":d(e,"handler")||d(e,"handlers")?"handler":d(e,"adapter")||d(e,"adapters")?"adapter":d(e,"plugin")||d(e,"plugins")?"plugin":d(e,"api")?"api":d(e,"cli")||d(e,"commands")||Q(e)==="cli"?"cli":d(e,"util")||d(e,"utils")||d(e,"helper")||d(e,"helpers")?"util":d(e,"model")||d(e,"models")||Q(e)==="model"?"model":d(e,"parser")||d(e,"parsers")||Q(e)==="parser"?"parser":Q(e)==="builder"?"builder":Q(e)==="resolver"?"resolver":"other"}function d(r,e){return r.includes(`/${e}/`)||r.includes(`/${e}.`)}function Q(r){let e=r.slice(r.lastIndexOf("/")+1);return e.slice(0,e.lastIndexOf("."))||e}function Je(r,e){let t=J(r,e),s=new Map;for(let[o,i]of t.features){for(let a of i.files)s.set(a,o);s.set(i.hub,o)}let n=new Map;for(let o of r.nodes.values()){let i=s.get(o.path);n.set(o.path,{path:o.path,role:Dt(o),...o.description?{description:o.description}:{},exports:o.exports.map(a=>a.name),...i?{featureHub:i}:{}})}return n}var M=class{affectedSymbols=new Map;constructor(e,t){this.affectedSymbols.set(e,new Set(["default",...t]))}updateAffectedSymbols(e,t){let s=this.affectedSymbols.get(t)||new Set,n=e.imports.find(p=>p.toPath===t);if(!n)return!1;let o=n.symbols||["*"],i=new Set;for(let p of o)(p==="*"||s.has("*")||s.has(p))&&i.add("*");if(i.size===0)return!1;let a=this.affectedSymbols.get(e.path)||new Set;for(let p of i)a.add(p);return this.affectedSymbols.set(e.path,a),!0}};function Bs(r){return r?r.startsWith("interface ")?"interface":r.startsWith("class ")?"class":r.startsWith("enum ")?"enum":"type":"type"}function Us(r,e){if(e==="type-only")return!0;let t=r.signature??"";return t.startsWith("interface ")||t.startsWith("class ")||t.startsWith("enum ")}function He(r){let e=new Map;for(let s of r.nodes.values())if(!(s.type!=="typescript"&&s.type!=="javascript"))for(let n of s.exports){if(!Us(n,s.category))continue;let o=`${s.path}::${n.name}`;e.set(o,{name:n.name,file:s.path,kind:Bs(n.signature),...n.doc?{doc:n.doc}:{}})}let t=[];for(let s of r.nodes.values())if(!(s.type!=="typescript"&&s.type!=="javascript")){for(let n of s.imports)if(!(!n.toPath||n.isExternal||!n.symbols?.length))for(let o of n.symbols)e.has(`${n.toPath}::${o}`)&&t.push({fromFile:s.path,toType:o,toFile:n.toPath})}return{types:e,edges:t}}function Qe(r,e){let t=null;for(let o of r.types.values())if(o.name===e){t=o;break}if(!t)return{type:null,usedByFiles:[],uses:[]};let s=new Set,n=new Map;for(let o of r.edges)if(o.toType===e&&o.toFile===t.file&&s.add(o.fromFile),o.fromFile===t.file){let i=r.types.get(`${o.toFile}::${o.toType}`);i&&n.set(`${i.file}::${i.name}`,i)}return{type:t,usedByFiles:Array.from(s),uses:Array.from(n.values())}}import rn from"path";import Xe from"fs";import Ot from"path";import V from"fs";import k from"path";import _t from"fs";import Fa from"path";function jt(r){try{return _t.statSync(r,{throwIfNoEntry:!1})?.isDirectory()===!0}catch{return!1}}function ge(r){try{return _t.statSync(r,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}function Ve(r,e){let t=k.join(e,"package.json");if(!V.existsSync(t))return null;let s={};try{s=JSON.parse(V.readFileSync(t,"utf-8"))}catch{return null}let n=s.name;return n?{name:n,root:e,relativeRoot:k.relative(r,e),entryPoints:qs(e,s)}:null}function qs(r,e){let t=[];if(e.exports){let n=e.exports;if(typeof n=="string")t.push(k.join(r,n));else if(typeof n=="object"&&n!==null){let o=n["."];if(typeof o=="string")t.push(k.join(r,o));else if(typeof o=="object"&&o!==null){let i=o.import??o.require??o.default;typeof i=="string"&&t.push(k.join(r,i))}}}e.main&&t.push(k.join(r,e.main));for(let n of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"])t.push(k.join(r,n));let s=t.filter(ge);return s.length>0?s.slice(0,1):t.slice(0,1)}function R(r,e){let t=[],s=new Set;for(let n of e){let o=n.replace(/\/$/,"").replace(/^\.\//,"");Ks(r,o,s,t)}return t}function Ks(r,e,t,s){if(!e.includes("*")){Js(r,e,t,s);return}let n=e.split("/");n.includes("**")?Hs(r,n,t,s):Qs(r,n,t,s)}function Js(r,e,t,s){let n=k.join(r,e);if(t.has(n)||!jt(n))return;t.add(n);let o=Ve(r,n);o&&s.push(o)}function Hs(r,e,t,s){let n=k.join(r,e[0]==="**"?"":e[0]??"");Lt(r,n,t,s)}function Qs(r,e,t,s){let n=e.findIndex(a=>a.includes("*")),o=k.join(r,...e.slice(0,n)),i;try{i=V.readdirSync(o,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let p=k.join(o,a.name);if(t.has(p))continue;t.add(p);let c=Ve(r,p);c&&s.push(c)}}function Lt(r,e,t,s){let n;try{n=V.readdirSync(e,{withFileTypes:!0})}catch{return}for(let o of n){if(!o.isDirectory()||o.name==="node_modules"||o.name.startsWith("."))continue;let i=k.join(e,o.name);if(V.existsSync(k.join(i,"package.json"))&&!t.has(i)){t.add(i);let a=Ve(r,i);a&&s.push(a)}else Lt(r,i,t,s)}}var Wt={type:"npm",detect(r){let e=Ot.join(r,"package.json");if(!Xe.existsSync(e))return null;let t;try{t=JSON.parse(Xe.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!t||Xe.existsSync(Ot.join(r,"yarn.lock")))return null;let s=Array.isArray(t)?t:t.packages??[];return s.length===0?null:R(r,s)}};import N from"fs";import S from"path";var zt={type:"nx",detect(r){return N.existsSync(S.join(r,"nx.json"))?$t(r,r,new Set,0).map(t=>Vs(r,t,S.join(t,"project.json"))).filter(t=>t!==null):null}};function $t(r,e,t,s){if(s>4)return[];let n;try{n=N.readdirSync(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let i of n){if(!i.isDirectory())continue;let a=i.name;if(a.startsWith(".")||a==="node_modules"||a==="dist"||a===".nx")continue;let p=S.join(e,a);N.existsSync(S.join(p,"project.json"))&&!t.has(p)?(t.add(p),o.push(p)):o.push(...$t(r,p,t,s+1))}return o}function Vs(r,e,t){let s={};try{s=JSON.parse(N.readFileSync(t,"utf-8"))}catch{return null}let n=s.name,o,i,a=S.join(e,"package.json");if(N.existsSync(a))try{let p=JSON.parse(N.readFileSync(a,"utf-8"));n=p.name??n,o=p.main,i=p.exports}catch{}return n?{name:n,root:e,relativeRoot:S.relative(r,e),entryPoints:Xs(e,s,o,i)}:null}function Xs(r,e,t,s){let n=[],o=e.targets?.build?.options?.main??e.targets?.build?.options?.entryFile;if(o){let a=S.resolve(r,"../..");n.push(S.resolve(a,o)),n.push(S.resolve(r,o))}if(s){let a=s;if(typeof a=="string")n.push(S.join(r,a));else if(typeof a=="object"&&a!==null){let p=a["."];typeof p=="string"&&n.push(S.join(r,p))}}if(t&&n.push(S.join(r,t)),e.sourceRoot){let a=S.resolve(r,"../.."),p=S.resolve(a,e.sourceRoot);n.push(S.join(p,"index.ts"),S.join(p,"index.tsx"))}for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx"])n.push(S.join(r,a));let i=n.filter(ge);return i.length>0?i.slice(0,1):n.slice(0,1)}import Bt from"fs";import Zs from"path";import Ys from"js-yaml";var Ut={type:"pnpm",detect(r){let e=Zs.join(r,"pnpm-workspace.yaml");if(!Bt.existsSync(e))return null;let t=[];try{t=Ys.load(Bt.readFileSync(e,"utf-8"))?.packages??[]}catch{return null}return R(r,t)}};import en from"fs";import tn from"path";var qt={type:"turborepo",detect(r){return en.existsSync(tn.join(r,"turbo.json"))?[]:null}};import Ze from"fs";import Kt from"path";var Jt={type:"yarn",detect(r){if(!Ze.existsSync(Kt.join(r,"yarn.lock")))return null;let e=Kt.join(r,"package.json");if(!Ze.existsSync(e))return null;let t;try{t=JSON.parse(Ze.readFileSync(e,"utf-8")).workspaces}catch{return null}if(!t)return null;let s=Array.isArray(t)?t:t.packages??[];return s.length===0?null:R(r,s)}};var Ht=[];function T(r){Ht.push(r)}function Qt(){return Ht}T(qt);T(zt);T(Ut);T(Jt);T(Wt);function X(r,e=Qt()){let t=rn.resolve(r),s=new Map,n=[];for(let i of e){let a=i.detect(t);if(a!==null){n.push(i.type);for(let p of a)s.has(p.name)||s.set(p.name,p)}}if(n.length===0)return{root:t,type:"none",types:[],packages:[],packageMap:new Map};let o=Array.from(s.values());return{root:t,type:n[0],types:n,packages:o,packageMap:new Map(o.map(i=>[i.name,i]))}}var Z=class r{constructor(e,t){this.monorepoRoot=e;this.type=t}monorepoRoot;type;packages=new Map;addPackage(e,t){this.packages.set(e.name,{graph:t,pkg:e})}getPackageForFile(e){for(let{pkg:t}of this.packages.values())if(e===t.relativeRoot||e.startsWith(`${t.relativeRoot}/`))return t}getPackageDependencies(){let e=new Map;for(let{graph:t,pkg:s}of this.packages.values()){let n=new Set;for(let o of t.nodes.values())for(let i of o.imports)i.isWorkspace&&i.workspacePackage&&n.add(i.workspacePackage);e.set(s.name,[...n])}return e}getAffectedAcrossPackages(e){let t=this.getPackageForFile(e);if(!t)return[];let s=this.packages.get(t.name);if(!s)return[];let n=[];s.graph.traverse(e,o=>(o.path!==e&&n.push({file:o.path,package:t.name}),!0),{direction:"incoming"});for(let{graph:o,pkg:i}of this.packages.values())if(i.name!==t.name)for(let a of o.nodes.values())a.imports.some(c=>c.isWorkspace&&c.workspacePackage===t.name)&&n.push({file:a.path,package:i.name});return n}serialize(){return{monorepoRoot:this.monorepoRoot,type:this.type,packages:Array.from(this.packages.values()).map(({graph:e,pkg:t})=>({pkg:{name:t.name,relativeRoot:t.relativeRoot,entryPoints:t.entryPoints},nodes:Array.from(e.nodes.values())}))}}static deserialize(e){let t=new r(e.monorepoRoot,e.type);for(let{pkg:s,nodes:n}of e.packages){let o=new Map(n.map(a=>[a.path,a])),i=new E(o);t.packages.set(s.name,{graph:i,pkg:{...s,root:""}})}return t}};var Vt=new Map;function G(r,e){Vt.set(r,e)}function Xt(r){return Vt.get(r)}function Zt(r,e){return e.startsWith("!")?r!==e.slice(1):r===e}function sn(r,e){return e.startsWith("!")?!r.includes(e.slice(1)):r.includes(e)}var nn=(r,e)=>!e.category||Zt(r.category,e.category),on=(r,e)=>!e.type||Zt(r.type,e.type),an=(r,e)=>!e.path||sn(r.path,e.path),pn=(r,e)=>e.isExternal===void 0?!0:r.imports.some(s=>s.isExternal)===e.isExternal,cn=(r,e)=>{if(!e.tags||e.tags.length===0)return!0;let t=e.tags.filter(n=>!n.startsWith("!")),s=e.tags.filter(n=>n.startsWith("!")).map(n=>n.slice(1));return!(t.length>0&&!t.some(n=>r.tags.some(o=>o.name===n))||s.some(n=>r.tags.some(o=>o.name===n)))},ln=(r,e)=>!e.allTags?.length||e.allTags.every(t=>r.tags.some(s=>s.name===t)),un=(r,e)=>!e.importsFile||r.imports.some(t=>t.toPath?.includes(e.importsFile)),fn=(r,e,t)=>e.importedBy===void 0?!0:(t?.get(r.path)??[]).some(n=>n.includes(e.importedBy)),gn=(r,e)=>e.minImports===void 0||r.imports.length>=e.minImports,mn=(r,e)=>e.maxImports===void 0||r.imports.length<=e.maxImports,dn=(r,e)=>e.minSize===void 0||r.size>=e.minSize,hn=(r,e)=>e.maxSize===void 0||r.size<=e.maxSize,yn=(r,e)=>e.hasDocstring===void 0||!!r.description===e.hasDocstring,xn=(r,e)=>e.minCoverage===void 0||(r.coveragePct??101)>=e.minCoverage,Sn=(r,e)=>e.maxCoverage===void 0||(r.coveragePct??0)<=e.maxCoverage,bn=(r,e)=>e.minExportUsage===void 0||(r.avgExportUsage??-1)>=e.minExportUsage,vn=(r,e)=>e.maxExportUsage===void 0||(r.avgExportUsage??0)<=e.maxExportUsage,Yt=[nn,on,an,pn,cn,ln,un,fn,gn,mn,dn,hn,yn,xn,Sn,bn,vn];function er(r,e,t){return Yt.every(s=>s(r,e,t))}function me(r,e){let t=new Map;if(e.importedBy!==void 0){for(let i of r.nodes)for(let a of i.imports)if(a.toPath){let p=t.get(a.toPath)??[];p.push(i.path),t.set(a.toPath,p)}}let s=r.nodes.filter(i=>er(i,e,t)),n=new Set(s.map(i=>i.path)),o=s.map(i=>({...i,imports:i.imports.filter(a=>!a.toPath||n.has(a.toPath))}));return e.sort&&o.sort((i,a)=>e.sort==="size"?a.size-i.size:e.sort==="imports"?a.imports.length-i.imports.length:e.sort==="commitCount90d"?(a.commitCount90d??0)-(i.commitCount90d??0):e.sort==="exportUsage"?(a.avgExportUsage??0)-(i.avgExportUsage??0):0),e.limit!==void 0&&o.splice(e.limit),{nodes:o,cycles:r.cycles?.filter(i=>i.every(a=>n.has(a)))??void 0}}function de(r){let e={},t=r.split(",");for(let s of t){let n=s.indexOf(":");if(n===-1)continue;let o=s.slice(0,n).trim().toLowerCase(),i=s.slice(n+1).trim();if(!(!o||!i))switch(o){case"category":e.category=i;break;case"type":e.type=i;break;case"tag":case"tags":i.includes("+")?e.allTags=[...e.allTags??[],...i.split("+")]:e.tags=[...e.tags??[],i];break;case"path":e.path=i;break;case"external":e.isExternal=i.toLowerCase()==="true";break;case"importsfile":e.importsFile=i;break;case"importedby":e.importedBy=i;break;case"minimports":e.minImports=parseInt(i,10);break;case"maximports":e.maxImports=parseInt(i,10);break;case"minsize":e.minSize=parseInt(i,10);break;case"maxsize":e.maxSize=parseInt(i,10);break;case"sort":e.sort=i;break;case"limit":e.limit=parseInt(i,10);break;case"hasdocstring":e.hasDocstring=i.toLowerCase()!=="false";break;case"mincoverage":e.minCoverage=parseInt(i,10);break;case"maxcoverage":e.maxCoverage=parseInt(i,10);break;case"minexportusage":e.minExportUsage=parseFloat(i);break;case"maxexportusage":e.maxExportUsage=parseFloat(i);break}}return e}import fr from"fs/promises";import qn from"path";import nt from"path";import we from"typescript";import rr from"path";import sr from"typescript";import b from"typescript";var tr=new Set(["describe","test","it"]);function D(r){let e=[];for(let t of r.statements){if(!b.isExpressionStatement(t))continue;let s=t.expression;if(!b.isCallExpression(s))continue;let n=s.expression;b.isIdentifier(n)&&tr.has(n.text)&&e.push(s),b.isPropertyAccessExpression(n)&&b.isIdentifier(n.expression)&&tr.has(n.expression.text)&&e.push(s)}return e}function _(r,e,t){for(let s of r.arguments){if(!b.isObjectLiteralExpression(s))continue;let n=s.properties.find(o=>b.isPropertyAssignment(o)&&b.isIdentifier(o.name)&&o.name.text===e);if(!(!n||!b.isArrayLiteralExpression(n.initializer)))return n.initializer.elements.filter(b.isStringLiteral).map(o=>o.text)}return null}function j(r,e,t,s){if(r.arguments.length===0)return null;for(let o=1;o<r.arguments.length;o++){let i=r.arguments[o];if(!b.isObjectLiteralExpression(i))continue;let a=i.properties.find(c=>b.isPropertyAssignment(c)&&b.isIdentifier(c.name)&&c.name.text===e);if(a)return{start:a.initializer.getStart(s),end:a.initializer.getEnd(),text:t};let p=i.getEnd()-1;return{start:p,end:p,text:`${i.properties.length>0?", ":""}${e}: ${t}`}}let n=r.arguments[r.arguments.length-1];return{start:n.getStart(s),end:n.getStart(s),text:`{ ${e}: ${t} }, `}}function L(r,e,t){let s=r.arguments;for(let n=1;n<s.length;n++){let o=s[n];if(!b.isObjectLiteralExpression(o))continue;let i=o.properties.findIndex(p=>b.isPropertyAssignment(p)&&b.isIdentifier(p.name)&&p.name.text===e);if(i<0)continue;if(o.properties.length===1)return{start:s[n-1].getEnd(),end:o.getEnd(),text:""};let a=o.properties[i];return i===o.properties.length-1?{start:o.properties[i-1].getEnd(),end:a.getEnd(),text:""}:{start:a.getStart(t),end:o.properties[i+1].getStart(t),text:""}}return null}function O(r,e){let t=[...e].sort((n,o)=>o.start-n.start),s=r;for(let n of t)s=s.slice(0,n.start)+n.text+s.slice(n.end);return s}function W(r){return`[${r.map(e=>JSON.stringify(e)).join(", ")}]`}var C=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);function kn(r){return W(r.map(e=>`@${e}`))}function wn(r){return r.map(e=>e.startsWith("@")?e.slice(1):e)}var he=class{name="cypress";canHandle(e){return C.has(rr.extname(e).toLowerCase())}apply(e,t,s){let n=sr.createSourceFile(rr.basename(e),t,sr.ScriptTarget.Latest,!0),o=D(n);if(o.length===0)return t;let i=_(o[0],"tags",n),a=[...s].sort();if(i!==null&&JSON.stringify(wn(i).sort())===JSON.stringify(a))return t;let p=o.flatMap(c=>{let u=s.length===0?L(c,"tags",n):j(c,"tags",kn(a),n);return u?[u]:[]});return p.length>0?O(t,p):t}};import Cn from"path";var Ye=/# <mokosh-tags>[\s\S]*?# <\/mokosh-tags>\n*/,et=/^@([a-zA-Z0-9_-]+)/gm;function Fn(r){return["# <mokosh-tags>",...r.map(e=>`@${e}`),"# </mokosh-tags>"].join(`
4
4
  `)+`
5
5
 
6
- `}function Cn(r){let e=new Set;Ye.lastIndex=0;let t=Ye.exec(r);for(;t!==null;)t[1]&&e.add(t[1]),t=Ye.exec(r);return e}var ye=class{name="gherkin";canHandle(e){return kn.extname(e).toLowerCase()===".feature"}apply(e,t,s){let n=t.replace(Ze,""),o=Cn(n),i=s.filter(p=>!o.has(p)),a=i.length>0?wn(i):"";return Ze.test(t)?t.replace(Ze,a):a?t.replace(/^(Feature:)/m,`${a}$1`):t}};function sr(r,e){let t=r.replace(/\\/g,"/"),s=e.replace(/\\/g,"/"),n="";for(let o=0;o<t.length;o++){let i=t[o];i==="*"?t[o+1]==="*"?(n+=".*",o++):n+="[^/]*":i==="?"?n+="[^/]":i!==void 0&&(n+=i.replace(/[.+^${}()|[\]\\]/g,"\\$&"))}return new RegExp(`^${n}$`).test(s)}import Fn from"path";var et=/^\/\/go:build mokosh_[^\n]+\n/m,En=/^package\s+\S+/m;function Tn(r){return`//go:build ${r.map(t=>`mokosh_${t}`).join(" || ")}
7
- `}function An(r){let e=et.exec(r);if(!e)return null;let t=e[0],s=/mokosh_([a-zA-Z0-9_-]+)/g,n=[],o=s.exec(t);for(;o!==null;)o[1]&&n.push(o[1]),o=s.exec(t);return n}var xe=class{name="go";canHandle(e){return Fn.basename(e).endsWith("_test.go")}apply(e,t,s){let n=An(t),o=[...s].sort();if(n!==null&&JSON.stringify([...n].sort())===JSON.stringify(o))return t;if(s.length===0)return t.replace(et,"");let i=Tn(o);if(n!==null)return t.replace(et,i);let a=En.exec(t);if(!a)return t;let p=a.index;return t.slice(0,p)+i+`
8
- `+t.slice(p)}};import Pn from"path";var In=/^\/\*\*\n(?: \* @group .+\n)+ \*\/\n+/,tt=/^ \* @group (.+)$/gm;function Mn(r){return["/**",...r.map(e=>` * @group ${e}`)," */"].join(`
6
+ `}function En(r){let e=new Set;et.lastIndex=0;let t=et.exec(r);for(;t!==null;)t[1]&&e.add(t[1]),t=et.exec(r);return e}var ye=class{name="gherkin";canHandle(e){return Cn.extname(e).toLowerCase()===".feature"}apply(e,t,s){let n=t.replace(Ye,""),o=En(n),i=s.filter(p=>!o.has(p)),a=i.length>0?Fn(i):"";return Ye.test(t)?t.replace(Ye,a):a?t.replace(/^(Feature:)/m,`${a}$1`):t}};function nr(r,e){let t=r.replace(/\\/g,"/"),s=e.replace(/\\/g,"/"),n="";for(let o=0;o<t.length;o++){let i=t[o];i==="*"?t[o+1]==="*"?(n+=".*",o++):n+="[^/]*":i==="?"?n+="[^/]":i!==void 0&&(n+=i.replace(/[.+^${}()|[\]\\]/g,"\\$&"))}return new RegExp(`^${n}$`).test(s)}import Tn from"path";var tt=/^\/\/go:build mokosh_[^\n]+\n/m,An=/^package\s+\S+/m;function Pn(r){return`//go:build ${r.map(t=>`mokosh_${t}`).join(" || ")}
7
+ `}function In(r){let e=tt.exec(r);if(!e)return null;let t=e[0],s=/mokosh_([a-zA-Z0-9_-]+)/g,n=[],o=s.exec(t);for(;o!==null;)o[1]&&n.push(o[1]),o=s.exec(t);return n}var xe=class{name="go";canHandle(e){return Tn.basename(e).endsWith("_test.go")}apply(e,t,s){let n=In(t),o=[...s].sort();if(n!==null&&JSON.stringify([...n].sort())===JSON.stringify(o))return t;if(s.length===0)return t.replace(tt,"");let i=Pn(o);if(n!==null)return t.replace(tt,i);let a=An.exec(t);if(!a)return t;let p=a.index;return t.slice(0,p)+i+`
8
+ `+t.slice(p)}};import Mn from"path";var Rn=/^\/\*\*\n(?: \* @group .+\n)+ \*\/\n+/,rt=/^ \* @group (.+)$/gm;function Nn(r){return["/**",...r.map(e=>` * @group ${e}`)," */"].join(`
9
9
  `)+`
10
10
 
11
- `}function Rn(r){let e=[];tt.lastIndex=0;let t=tt.exec(r);for(;t!==null;)t[1]&&e.push(t[1]),t=tt.exec(r);return e}var Se=class{name="jest";canHandle(e){return C.has(Pn.extname(e).toLowerCase())}apply(e,t,s){let n=In.exec(t),o=n?Rn(n[0]):null,i=[...s].sort();if(o!==null&&JSON.stringify([...o].sort())===JSON.stringify(i))return t;let a=n?t.slice(n[0].length):t;return s.length===0?a:Mn(i)+a}};import nr from"path";import or from"typescript";function Nn(r){return W(r.map(e=>`@${e}`))}function Gn(r){return r.map(e=>e.startsWith("@")?e.slice(1):e)}var be=class{name="playwright";canHandle(e){return C.has(nr.extname(e).toLowerCase())}apply(e,t,s){let n=or.createSourceFile(nr.basename(e),t,or.ScriptTarget.Latest,!0),o=D(n);if(o.length===0)return t;let i=j(o[0],"tag",n),a=[...s].sort();if(i!==null&&JSON.stringify(Gn(i).sort())===JSON.stringify(a))return t;let p=o.flatMap(c=>{let u=s.length===0?L(c,"tag",n):_(c,"tag",Nn(a),n);return u?[u]:[]});return p.length>0?O(t,p):t}};import Dn from"path";var rt=/^pytestmark\s*=\s*.+$/m,jn=/^import pytest\s*$/m;function _n(r){let e=r.map(t=>`pytest.mark.${t}`).join(", ");return r.length===1?`pytestmark = pytest.mark.${r[0]}`:`pytestmark = [${e}]`}function Ln(r){let e=rt.exec(r);if(!e)return null;let t=e[0],s=[],n=/pytest\.mark\.([a-zA-Z0-9_-]+)/g,o=n.exec(t);for(;o!==null;)o[1]&&s.push(o[1]),o=n.exec(t);return s}var ve=class{name="pytest";canHandle(e){return Dn.extname(e).toLowerCase()===".py"}apply(e,t,s){let n=Ln(t),o=[...s].sort();if(n!==null&&JSON.stringify([...n].sort())===JSON.stringify(o))return t;if(s.length===0)return t.replace(rt,"").replace(/\n{3,}/g,`
11
+ `}function Gn(r){let e=[];rt.lastIndex=0;let t=rt.exec(r);for(;t!==null;)t[1]&&e.push(t[1]),t=rt.exec(r);return e}var Se=class{name="jest";canHandle(e){return C.has(Mn.extname(e).toLowerCase())}apply(e,t,s){let n=Rn.exec(t),o=n?Gn(n[0]):null,i=[...s].sort();if(o!==null&&JSON.stringify([...o].sort())===JSON.stringify(i))return t;let a=n?t.slice(n[0].length):t;return s.length===0?a:Nn(i)+a}};import or from"path";import ir from"typescript";function Dn(r){return W(r.map(e=>`@${e}`))}function _n(r){return r.map(e=>e.startsWith("@")?e.slice(1):e)}var be=class{name="playwright";canHandle(e){return C.has(or.extname(e).toLowerCase())}apply(e,t,s){let n=ir.createSourceFile(or.basename(e),t,ir.ScriptTarget.Latest,!0),o=D(n);if(o.length===0)return t;let i=_(o[0],"tag",n),a=[...s].sort();if(i!==null&&JSON.stringify(_n(i).sort())===JSON.stringify(a))return t;let p=o.flatMap(c=>{let u=s.length===0?L(c,"tag",n):j(c,"tag",Dn(a),n);return u?[u]:[]});return p.length>0?O(t,p):t}};import jn from"path";var st=/^pytestmark\s*=\s*.+$/m,Ln=/^import pytest\s*$/m;function On(r){let e=r.map(t=>`pytest.mark.${t}`).join(", ");return r.length===1?`pytestmark = pytest.mark.${r[0]}`:`pytestmark = [${e}]`}function Wn(r){let e=st.exec(r);if(!e)return null;let t=e[0],s=[],n=/pytest\.mark\.([a-zA-Z0-9_-]+)/g,o=n.exec(t);for(;o!==null;)o[1]&&s.push(o[1]),o=n.exec(t);return s}var ve=class{name="pytest";canHandle(e){return jn.extname(e).toLowerCase()===".py"}apply(e,t,s){let n=Wn(t),o=[...s].sort();if(n!==null&&JSON.stringify([...n].sort())===JSON.stringify(o))return t;if(s.length===0)return t.replace(st,"").replace(/\n{3,}/g,`
12
12
 
13
- `);let i=_n(o);if(n!==null)return t.replace(rt,i);let a=jn.test(t),p=On(t),c=t.slice(0,p),u=t.slice(p),f=a?"":`import pytest
13
+ `);let i=On(o);if(n!==null)return t.replace(st,i);let a=Ln.test(t),p=zn(t),c=t.slice(0,p),u=t.slice(p),f=a?"":`import pytest
14
14
  `,g=c.endsWith(`
15
15
 
16
16
  `)?"":`
17
17
  `;return c+g+f+i+`
18
- `+u}};function On(r){let e=r.split(`
19
- `),t=-1;for(let n=0;n<e.length;n++){let o=e[n].trimStart();(o.startsWith("import ")||o.startsWith("from "))&&(t=n)}if(t<0)return 0;let s=0;for(let n=0;n<=t;n++)s+=e[n].length+1;return s}import ir from"path";import ar from"typescript";var Wn=/\/\/ <mokosh-tags>[\s\S]*?\/\/ <\/mokosh-tags>\n*/,ke=class{name="vitest";canHandle(e){return C.has(ir.extname(e).toLowerCase())}apply(e,t,s){let n=t.replace(Wn,""),o=ar.createSourceFile(ir.basename(e),n,ar.ScriptTarget.Latest,!0),i=D(o);if(i.length===0)return n;let a=j(i[0],"tags",o),p=[...s].sort();if(a!==null&&JSON.stringify([...a].sort())===JSON.stringify(p))return n;let c=i.flatMap(u=>{let f=s.length===0?L(u,"tags",o):_(u,"tags",W(p),o);return f?[f]:[]});return c.length>0?O(n,c):n}};var pr={vitest:()=>new ke,playwright:()=>new be,cypress:()=>new he,jest:()=>new Se},zn={"@playwright/test":"playwright",cypress:"cypress","@jest/globals":"jest",vitest:"vitest"};function $n(r){let e=we.createSourceFile("detect.ts",r,we.ScriptTarget.Latest,!0);for(let t of e.statements){if(!we.isImportDeclaration(t)||!we.isStringLiteral(t.moduleSpecifier))continue;let s=zn[t.moduleSpecifier.text];if(s)return s}return null}var nt=class{constructor(e,t,s){this.rootDir=e;this.defaultFramework=t;this.frameworkOverrides=s}rootDir;defaultFramework;frameworkOverrides;name="auto";canHandle(e){return C.has(st.extname(e).toLowerCase())}apply(e,t,s){let n=$n(t)??this.matchOverride(e)??this.defaultFramework;return(pr[n]??pr.vitest)().apply(e,t,s)}matchOverride(e){let t=st.relative(this.rootDir,e).split(st.sep).join("/");for(let[s,n]of this.frameworkOverrides)if(sr(s,t))return n;return null}};function cr(r="vitest",e={},t=process.cwd()){return[new ye,new ve,new xe,new nt(t,r,Object.entries(e))]}function lr(r,e){return e.find(t=>t.canHandle(r))??null}var Un=/^[a-zA-Z][a-zA-Z0-9_-]{1,}$/,qn=new Set(["import"]),Kn=new Set(["common","fixture","fixtures","helper","helpers","index","main","mock","mocks","setup","shared","spec","test","tests","types","util","utils"]);async function Jn(r,e,t,s){let n;try{n=await ur.readFile(r,"utf8")}catch(a){return{path:r,status:"error",error:String(a)}}let o=lr(r,s);if(!o)return{path:r,status:"unchanged"};let i=o.apply(r,n,e);return i===n?{path:r,status:"unchanged"}:(t||await ur.writeFile(r,i,"utf8"),{path:r,status:"updated"})}async function ot(r,e,t){let s=K(e),n=s.tagApplier?.framework??"vitest",o=s.tagApplier?.frameworkOverrides??{},i=cr(n,o,e),a={updated:0,unchanged:0,errors:0,files:[]};for(let p of r.nodes.values()){if(p.category!=="test")continue;let c=new Set,u=[];for(let y of p.tags)qn.has(y.kind)&&Un.test(y.name)&&(Kn.has(y.name.toLowerCase())||c.has(y.name)||(c.add(y.name),u.push(y.name)));u.sort();let f=Bn.resolve(e,p.path),g=await Jn(f,u,t.dryRun,i);g.path=p.path,a.files.push(g),g.status==="updated"?a.updated++:g.status==="unchanged"?a.unchanged++:a.errors++}return a}var Ce=class{isTestNode(e){return e.category==="test"||e.tags.some(t=>t.name==="test")}};import Ie from"fs";import v from"path";import{execSync as fr}from"child_process";var Fe=class{getChangedFiles(){try{let t=["git diff --name-only","git diff --cached --name-only","git ls-files --others --exclude-standard"].flatMap(s=>{try{return fr(s,{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
20
- `).map(o=>o.trim()).filter(o=>o!=="")}catch{return[]}});return Array.from(new Set(t))}catch(e){return console.error("Error getting git diff:",e),[]}}};function gr(r,e){let s=fr(`git -C "${r}" log --follow --format="%ae" --since="90 days ago" -- "${e}"`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
21
- `).filter(Boolean);return{commitCount90d:s.length,lastAuthor:s[0]}}import Ee from"fs";import Hn from"path";import mr from"js-yaml";function dr(r){let e=r.lastIndexOf("@");return e>0?r.substring(0,e):r}function Qn(r){return r.replace(/:$/,"").split(",").map(e=>{let t=e.trim();return t.startsWith('"')&&(t=t.slice(1)),t.endsWith('"')&&(t=t.slice(0,-1)),dr(t)}).filter(Boolean)}function Vn(r,e){let t=r.startsWith("/")?r.slice(1):r,s=t.lastIndexOf("@");return s>0?{name:t.substring(0,s),version:e||t.substring(s+1)}:{name:t,version:e}}function Xn(r){try{let e=mr.load(r),t={dependencies:{}};for(let[s,n]of Object.entries(e))if(!(s==="__metadata"||!n?.version))for(let o of s.split(", ")){let i=dr(o);i&&(t.dependencies[i]={version:n.version,...n.dependencies!==void 0&&{dependencies:n.dependencies}})}return t}catch{return null}}function Zn(r){let e={dependencies:{}};for(let t of r.split(/\n\n+/)){let s=t.split(`
22
- `).filter(p=>p.trim().length>0&&!p.trim().startsWith("#"));if(s.length<2)continue;let n=s[0];if(!n||n.startsWith(" "))continue;let o=Qn(n);if(o.length===0)continue;let a=s.find(p=>p.trim().startsWith('version "'))?.match(/version "(.*?)"/)?.[1]??"";for(let p of o)e.dependencies[p]={version:a}}return e}function Yn(r){let e=Ee.readFileSync(r,"utf-8"),t=JSON.parse(e),s={dependencies:{}};if(t.packages)for(let[n,o]of Object.entries(t.packages)){if(!n.startsWith("node_modules/"))continue;let i=n.replace("node_modules/","");i.includes("node_modules/")||(s.dependencies[i]={version:o.version,...o.dependencies!==void 0&&{dependencies:o.dependencies}})}else if(t.dependencies)for(let[n,o]of Object.entries(t.dependencies))s.dependencies[n]={version:o.version,...o.dependencies!==void 0&&{dependencies:o.dependencies}};return s}function eo(r){let e=Ee.readFileSync(r,"utf-8");if(e.includes("__metadata:")){let t=Xn(e);if(t!==null)return t}return Zn(e)}function to(r){let e=Ee.readFileSync(r,"utf-8"),t={dependencies:{}};try{let s=mr.load(e);if(s.packages)for(let[n,o]of Object.entries(s.packages)){let{name:i,version:a}=Vn(n,o.version);i&&(t.dependencies[i]={version:a,...o.dependencies!==void 0&&{dependencies:o.dependencies}})}if(s.dependencies)for(let[n,o]of Object.entries(s.dependencies)){if(t.dependencies[n])continue;let i=typeof o=="string"?o:o.version;t.dependencies[n]={version:i||""}}}catch{}return t}function hr(r){let e=[["package-lock.json",Yn],["yarn.lock",eo],["pnpm-lock.yaml",to]];for(let[t,s]of e){let n=Hn.join(r,t);if(Ee.existsSync(n))return s(n)}return null}import yr from"path";function A(r){switch(yr.extname(r).toLowerCase()){case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".ts":case".tsx":return"typescript";case".css":return"css";case".scss":case".sass":return"scss";case".less":return"less";case".styl":return"stylus";case".coffee":return"coffeescript";case".ls":return"livescript";case".lua":return"lua";case".py":return"python";case".go":return"go";case".java":case".cpp":case".cc":case".cxx":case".c":return"unknown";case".feature":return"gherkin";default:return"unknown"}}function w(r){let e=yr.extname(r).toLowerCase();return[".css",".scss",".sass",".less",".styl"].includes(e)}import ro from"coffeescript";function so(r){let e=new Set,t=/@tag\s+([a-zA-Z0-9_-]+)/g,s=t.exec(r);for(;s!==null;)s[1]&&e.add(s[1]),s=t.exec(r);return e}function no(r,e){let t=r.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||e.has("test")?"test":"logic"}function oo(r,e){let t=e.source?.value;return t?{fromPath:r,toPath:"",rawSpecifier:t,isStyle:w(t),type:"static"}:null}function io(r,e){let t=e.variable?.base?.value==="require",s=e.args?.[0]?.base?.value;return!t||!s?null:{fromPath:r,toPath:"",rawSpecifier:s,isStyle:w(s),type:"require"}}function ao(r,e,t){let s=e.constructor?.name;if(s==="ImportDeclaration"){let n=oo(r,e);n&&t.push(n)}else if(s==="Call"){let n=io(r,e);n&&t.push(n)}}function it(r,e,t){if(!(!e||typeof e!="object")){ao(r,e,t);for(let s in e){if(s==="locationData")continue;let n=e[s];if(!(!n||typeof n!="object"))if(Array.isArray(n))for(let o of n)it(r,o,t);else it(r,n,t)}}}function xr(r,e){let t=so(e),s=no(r,t),n=[];try{it(r,ro.nodes(e),n)}catch{}return{imports:n,exports:[],tags:Array.from(t).map(o=>({name:o,kind:"comment-marker"})),category:s}}import{AstBuilder as po,GherkinClassicTokenMatcher as co,Parser as lo}from"@cucumber/gherkin";import{IdGenerator as uo}from"@cucumber/messages";var fo=uo.uuid();function at(r,e){let t=new Set;try{let s=new po(fo),n=new co,i=new lo(s,n).parse(e);i.feature&&(i.feature.tags.forEach(a=>{t.add(a.name.startsWith("@")?a.name.slice(1):a.name)}),i.feature.children.forEach(a=>{a.scenario&&(a.scenario.tags.forEach(p=>{t.add(p.name.startsWith("@")?p.name.slice(1):p.name)}),a.scenario.examples.forEach(p=>{p.tags.forEach(c=>{t.add(c.name.startsWith("@")?c.name.slice(1):c.name)})})),a.rule&&a.rule.children.forEach(p=>{p.scenario&&p.scenario.tags.forEach(c=>{t.add(c.name.startsWith("@")?c.name.slice(1):c.name)})})}))}catch(s){console.warn(`[GherkinParser] Failed to parse ${r}:`,s)}return{imports:[],exports:[],tags:Array.from(t).map(s=>({name:s,kind:"comment-marker"})),category:"test"}}G("gherkin",at);import go from"path";import{parser as mo}from"@lezer/go";var ho=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/,yo=/^\/\/go:build\s+(.+)$/,xo=/^\/\/\s*\+build\s+(.+)$/;function br(r,e){let t=[],s=new Map,n=new Set,o=new Set,a=mo.parse(e).cursor();do switch(a.name){case"LineComment":{let f=e.slice(a.from,a.to),g=f.match(ho);g?.[1]&&n.add(g[1]);let y=f.match(yo);y&&Sr(y[1],o);let F=f.match(xo);F&&Sr(F[1],o);break}case"ImportSpec":{let f=a.node.getChild("String");if(f){let y=e.slice(f.from,f.to).slice(1,-1);t.push({fromPath:r,toPath:"",rawSpecifier:y,isExternal:!0,isStyle:!1,type:"static"})}break}case"FunctionDecl":case"TypeDecl":case"VarDecl":case"ConstDecl":{let f=a.node.getChild("DefName")??a.node.getChild("TypeSpec")?.getChild("DefName")??a.node.getChild("VarSpec")?.getChild("DefName")??a.node.getChild("ConstSpec")?.getChild("DefName");if(f){let g=e.slice(f.from,f.to);g!=="_"&&/^[A-Z]/.test(g)&&!s.has(g)&&s.set(g,{name:g})}break}}while(a.next());let p=t.some(f=>f.rawSpecifier==="testing"),c=go.basename(r).endsWith("_test.go")||n.has("test")||p?"test":"logic",u=new Set([...n,...o]);return{imports:t,exports:Array.from(s.values()),tags:Array.from(u).map(f=>({name:f,kind:"comment-marker"})),category:c}}function Sr(r,e){for(let t of r.split(/[\s,&|!()]+/)){let s=t.trim();s&&s!=="ignore"&&e.add(s)}}import So from"livescript";function z(r){return r.startsWith("'")||r.startsWith('"')?r.slice(1,-1):r}function bo(r){let e=new Set,t=/@tag\s+([a-zA-Z0-9_-]+)/g,s=t.exec(r);for(;s!==null;)s[1]&&e.add(s[1]),s=t.exec(r);return e}function vo(r,e){let t=r.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||e.has("test")?"test":"logic"}var ko=new Set(["first_line","first_column","last_line","last_column","line","column"]);function wo(r,e){let t=r.constructor?.name||r.type;if(t==="Import"){let s=r.right?.value;if(typeof s=="string"){let n=z(s);return{fromPath:e,toPath:"",rawSpecifier:n,isStyle:w(n),type:"static"}}}if(t==="Chain"&&r.head?.value==="require"){let s=r.tails?.[0];if(s?.constructor?.name==="Call"||s?.type==="Call"){let n=s.args?.[0]?.value;if(typeof n=="string"){let o=z(n);return{fromPath:e,toPath:"",rawSpecifier:o,isStyle:w(o),type:"require"}}}}return null}function pt(r,e){if(!r||typeof r!="object")return[];let t=[],s=wo(r,e);s&&t.push(s);for(let n in r){if(ko.has(n))continue;let o=r[n];if(!(!o||typeof o!="object"))if(Array.isArray(o))for(let i of o)t.push(...pt(i,e));else t.push(...pt(o,e))}return t}function vr(r,e){let t=bo(e),s=vo(r,t),n=[];try{n=pt(So.ast(e),r)}catch{}return{imports:n,exports:[],tags:Array.from(t).map(o=>({name:o,kind:"comment-marker"})),category:s}}import Co from"luaparse";function Fo(r){let e=new Set,t=/@tag\s+([a-zA-Z0-9_-]+)/g,s=t.exec(r);for(;s!==null;)s[1]&&e.add(s[1]),s=t.exec(r);return e}function Eo(r,e){let t=r.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||e.has("test")?"test":"logic"}function To(r,e){let t=[];function s(n){if(!(!n||typeof n!="object")){if((n.type==="CallExpression"||n.type==="StringCallExpression")&&n.base?.type==="Identifier"&&n.base?.name==="require"){let o;if(n.type==="CallExpression"){let i=n.arguments?.[0];i?.type==="StringLiteral"&&(o=z(i.raw))}else if(n.type==="StringCallExpression"){let i=n.argument;i?.type==="StringLiteral"&&(o=z(i.raw))}o&&t.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:w(o),type:"require"})}for(let o in n){if(o==="loc")continue;let i=n[o];if(i&&typeof i=="object")if(Array.isArray(i))for(let a of i)s(a);else s(i)}}}return s(r),t}function kr(r,e){let t=Fo(e),s=Eo(r,t),n=[];try{let o=Co.parse(e);n=To(o,r)}catch{}return{imports:n,exports:[],tags:Array.from(t).map(o=>({name:o,kind:"comment-marker"})),category:s}}import Ao from"path";import{parser as Po}from"@lezer/python";var Io=new Set(["pytest","unittest","nose","hypothesis"]);function wr(r,e){let t=[],s=[],n=new Set,o=Ao.basename(r).toLowerCase(),a=Po.parse(e).cursor();do switch(a.name){case"Comment":{let c=e.slice(a.from,a.to).match(/#\s*@tag\s+([a-zA-Z0-9_-]+)/);c?.[1]&&n.add(c[1]);break}case"ImportStatement":{for(let c of Mo(a.node,e,r))t.push(c);break}case"FunctionDefinition":case"ClassDefinition":{let c=a.node.parent;if(c?.name==="Script"||c?.name==="DecoratedStatement"&&c.parent?.name==="Script"){let f=a.node.getChild("VariableName");f&&s.push({name:e.slice(f.from,f.to)})}break}case"AssignStatement":{if(a.node.parent?.name==="Script"){let c=a.node.firstChild;c?.name==="VariableName"&&s.push({name:e.slice(c.from,c.to)})}break}}while(a.next());let p=Do(o,t,n);return p==="test"&&n.add("test"),{imports:t,exports:s,tags:Array.from(n).map(c=>({name:c,kind:"comment-marker"})),category:p}}function Mo(r,e,t){let s=r.firstChild;return s?s.name==="from"?Ro(r,e,t):No(r,e,t):[]}function Ro(r,e,t){let s=r.firstChild;if(!s)return[];let n=s.nextSibling;for(;n&&n.name!=="import";)n=n.nextSibling;if(!n)return[];let o=e.slice(s.to,n.from).trim(),i=Go(n.nextSibling,e);if(!i.length)return[];let a=0;for(;a<o.length&&o[a]===".";)a++;let p=o.slice(a);if(a===0)return[Y(t,o,i,!0)];let c=a===1?"./":"../".repeat(a-1);return p?[Y(t,c+p.replace(/\./g,"/"),i,!1)]:i[0]==="*"?[Y(t,c.slice(0,-1),["*"],!1)]:i.map(u=>Y(t,c+u,[u],!1))}function No(r,e,t){let s=[],n=r.firstChild?.nextSibling??null;for(;n;){if(n.name==="VariableName"){let o=e.slice(n.from,n.to);for(;n.nextSibling?.name==="."&&n.nextSibling.nextSibling?.name==="VariableName";)n=n.nextSibling.nextSibling,o+=`.${e.slice(n.from,n.to)}`;n.nextSibling?.name==="as"&&(n=n.nextSibling.nextSibling??n.nextSibling),s.push(Y(t,o,["*"],!0))}n=n.nextSibling}return s}function Go(r,e){let t=[],s=r;for(;s;)s.name==="*"?t.push("*"):s.name==="VariableName"&&(t.push(e.slice(s.from,s.to)),s.nextSibling?.name==="as"&&(s=s.nextSibling.nextSibling??s.nextSibling)),s=s.nextSibling;return t}function Y(r,e,t,s){return{fromPath:r,toPath:"",rawSpecifier:e,isStyle:!1,isExternal:s,type:"static",symbols:t.length>0?t:void 0}}function Do(r,e,t){return r.startsWith("test_")||r.endsWith("_test.py")?"test":r==="conftest.py"||r==="setup.py"?"config":t.has("test")||e.some(s=>Io.has(s.rawSpecifier))?"test":"logic"}import Fr from"path";import l from"typescript";import m from"typescript";function jo(r){let e=1;function t(s){switch(s.kind){case m.SyntaxKind.IfStatement:case m.SyntaxKind.ConditionalExpression:case m.SyntaxKind.ForStatement:case m.SyntaxKind.ForInStatement:case m.SyntaxKind.ForOfStatement:case m.SyntaxKind.WhileStatement:case m.SyntaxKind.DoStatement:case m.SyntaxKind.CatchClause:case m.SyntaxKind.CaseClause:e++;break;case m.SyntaxKind.BinaryExpression:{let n=s.operatorToken.kind;(n===m.SyntaxKind.AmpersandAmpersandToken||n===m.SyntaxKind.BarBarToken||n===m.SyntaxKind.QuestionQuestionToken)&&e++;break}}m.forEachChild(s,t)}return t(r),e}function _o(r){let e=0;function t(s,n,o){if(m.isIfStatement(s)){e+=o?1:1+n;let a=o?n:n+1;t(s.expression,a,!1),t(s.thenStatement,a,!1),s.elseStatement&&(m.isIfStatement(s.elseStatement)?t(s.elseStatement,n,!0):(e+=1,t(s.elseStatement,n+1,!1)));return}if(m.isForStatement(s)||m.isForInStatement(s)||m.isForOfStatement(s)||m.isWhileStatement(s)||m.isDoStatement(s)||m.isSwitchStatement(s)){e+=1+n,m.forEachChild(s,a=>t(a,n+1,!1));return}if(m.isCatchClause(s)){e+=1+n,m.forEachChild(s,a=>t(a,n,!1));return}if(m.isConditionalExpression(s)&&(e+=1),m.isBinaryExpression(s)){let a=s.operatorToken.kind;(a===m.SyntaxKind.AmpersandAmpersandToken||a===m.SyntaxKind.BarBarToken||a===m.SyntaxKind.QuestionQuestionToken)&&(e+=1)}if(n>0&&(m.isFunctionDeclaration(s)||m.isFunctionExpression(s)||m.isArrowFunction(s))){e+=1+n,m.forEachChild(s,a=>t(a,n+1,!1));return}m.forEachChild(s,a=>t(a,n,!1))}return t(r,0,!1),e}function ct(r){return{complexity:jo(r),cognitiveComplexity:_o(r)}}import x from"typescript";var lt=new Set(["test","describe","it"]);function Cr(r,e){Lo(r,e),Wo(r,e),zo(r,e),$o(r,e)}function Lo(r,e){if((x.isFunctionDeclaration(r)||x.isVariableDeclaration(r))&&r.name&&x.isIdentifier(r.name)&&Oo(r)){let t;if(x.isFunctionDeclaration(r))t="function";else{let s=r.initializer;t=s&&(x.isArrowFunction(s)||x.isFunctionExpression(s))?"function":"variable"}e.tags.add({name:r.name.text,kind:t})}}function Oo(r){if(x.isFunctionDeclaration(r))return x.isSourceFile(r.parent);let e=r.parent?.parent;return!!e&&x.isSourceFile(e.parent)}function Wo(r,e){if(!x.isStringLiteral(r))return;let t=r.text.match(/@[\w-]+/g);if(t)for(let s of t)e.tags.add({name:s.substring(1),kind:"comment-marker"})}function zo(r,e){if(!x.isSourceFile(r))return;let t=/@tag\s+([a-zA-Z0-9_-]+)/g,s=r.getFullText(),n=t.exec(s);for(;n!==null;)n[1]&&e.tags.add({name:n[1],kind:"comment-marker"}),n=t.exec(s)}function $o(r,e){if(x.isCallExpression(r)&&Bo(r.expression))for(let t of r.arguments)x.isObjectLiteralExpression(t)&&Uo(t,e)}function Bo(r){return x.isIdentifier(r)?lt.has(r.text):!!(x.isPropertyAccessExpression(r)&&(lt.has(r.name.text)||x.isIdentifier(r.expression)&&lt.has(r.expression.text)))}function Uo(r,e){for(let t of r.properties){if(!x.isPropertyAssignment(t)||!x.isIdentifier(t.name)||t.name.text!=="tags"&&t.name.text!=="tag")continue;let{initializer:s}=t,n=x.isArrayLiteralExpression(s)?s.elements.filter(x.isStringLiteral):t.name.text==="tag"&&x.isStringLiteral(s)?[s]:[];for(let o of n)e.tags.add({name:o.text.replace(/^@/,""),kind:"comment-marker"})}}function ut(r,e,t){let s=[],n=new Map,o=new Set,i=l.createSourceFile(r,e,l.ScriptTarget.Latest,!0,t==="typescript"?l.ScriptKind.TSX:l.ScriptKind.JSX),a={filePath:r,imports:s,exports:n,tags:o,rawCallEdges:[],sourceFile:i,hasUI:!1,hasTypesOnly:!0,totalStatements:0,exportStatements:0},p=ie=>{Ho(ie,a),l.forEachChild(ie,p)};p(i);let c=oi(r,a);(c==="test"||c==="barrel")&&o.add({name:c,kind:"comment-marker"}),c!=="test"&&ii(a,i);let u=i.statements[0],f=u?Tr(u):void 0,{complexity:g,cognitiveComplexity:y}=ct(i),F=qo(i);return{imports:s,exports:Array.from(n.values()),tags:Array.from(o),category:c,rawCallEdges:a.rawCallEdges??[],complexity:g,cognitiveComplexity:y,...F.length>0?{functions:F}:{},...f!==void 0?{description:f}:{}}}function qo(r){let e=[],t=(n,o)=>{let{complexity:i,cognitiveComplexity:a}=ct(o),p=r.getLineAndCharacterOfPosition(o.getStart(r)).line+1;e.push({name:n,line:p,complexity:i,cognitiveComplexity:a})},s=(n,o)=>{if(l.isFunctionDeclaration(n)&&n.name&&n.body?t(n.name.text,n):l.isVariableDeclaration(n)&&l.isIdentifier(n.name)&&n.initializer&&(l.isArrowFunction(n.initializer)||l.isFunctionExpression(n.initializer))?t(n.name.text,n.initializer):o&&l.isMethodDeclaration(n)&&l.isIdentifier(n.name)&&n.body?t(`${o}.${n.name.text}`,n):o&&l.isConstructorDeclaration(n)&&n.body?t(`${o}.constructor`,n):o&&l.isGetAccessorDeclaration(n)&&l.isIdentifier(n.name)&&n.body?t(`${o}.get ${n.name.text}`,n):o&&l.isSetAccessorDeclaration(n)&&l.isIdentifier(n.name)&&n.body&&t(`${o}.set ${n.name.text}`,n),l.isClassDeclaration(n)&&n.name){let i=n.name.text;l.forEachChild(n,a=>s(a,i));return}l.forEachChild(n,i=>s(i,o))};return s(r,void 0),e}function Er(r,e,t,s){let n={name:r},o=Tr(t);o!==void 0&&(n.doc=o);let i=Ko(e);i!==void 0&&(n.flags=i);let a=Jo(e,s);return a!==void 0&&(n.signature=a),n}function Tr(r){let e=l.getJSDocCommentsAndTags(r);for(let t of e)if(l.isJSDoc(t)&&t.comment)return l.getTextOfJSDocComment(t.comment)||void 0}function Ko(r){let e=new Set(["deprecated","internal","public","alpha","beta"]),t=l.getJSDocTags(r).map(s=>s.tagName.text).filter(s=>e.has(s));return t.length>0?t:void 0}function Jo(r,e){let t=l.createPrinter({removeComments:!0}),s=n=>t.printNode(l.EmitHint.Unspecified,n,e);if(l.isFunctionDeclaration(r)||l.isMethodDeclaration(r)){let n=r.parameters.map(s).join(", "),o=r.type?s(r.type):"void";return`${r.typeParameters?`<${r.typeParameters.map(a=>a.name.text).join(", ")}>`:""}(${n}) => ${o}`}if(l.isVariableDeclaration(r)){if(r.type)return s(r.type);if(r.initializer&&(l.isArrowFunction(r.initializer)||l.isFunctionExpression(r.initializer))){let n=r.initializer,o=n.parameters.map(s).join(", "),i=n.type?s(n.type):"unknown";return`(${o}) => ${i}`}return}if(l.isClassDeclaration(r)&&r.name)return`class ${r.name.text}`;if(l.isInterfaceDeclaration(r))return`interface ${r.name.text}`;if(l.isTypeAliasDeclaration(r))return s(r.type);if(l.isEnumDeclaration(r))return`enum ${r.name.text}`}function Ho(r,e){Qo(r,e),Vo(r,e),Zo(r,e),Yo(r,e),ni(r,e),Cr(r,e)}function Qo(r,e){if(!l.isSourceFile(r))return;let t=r.statements.filter(s=>!l.isEmptyStatement(s));e.totalStatements=t.length,e.exportStatements=t.filter(s=>l.isExportDeclaration(s)||l.isExportAssignment(s)||ft(s)).length}function Vo(r,e){if(l.isJsxElement(r)||l.isJsxSelfClosingElement(r)||l.isJsxFragment(r)){e.hasUI=!0,e.hasTypesOnly=!1;return}if(l.isFunctionDeclaration(r)||l.isMethodDeclaration(r)||l.isArrowFunction(r)||l.isClassDeclaration(r)||l.isVariableStatement(r)||l.isEnumDeclaration(r)){e.hasTypesOnly=!1;return}l.isExportDeclaration(r)&&!Xo(r)&&(e.hasTypesOnly=!1)}function Xo(r){return r.isTypeOnly?!0:!r.exportClause||!l.isNamedExports(r.exportClause)?!1:r.exportClause.elements.every(e=>e.isTypeOnly)}function Zo(r,e){if(!l.isImportDeclaration(r)||!r.moduleSpecifier||!l.isStringLiteral(r.moduleSpecifier))return;let t=[];if(r.importClause&&(r.importClause.name&&t.push("default"),r.importClause.namedBindings))if(l.isNamedImports(r.importClause.namedBindings))for(let n of r.importClause.namedBindings.elements)t.push(n.name.text);else l.isNamespaceImport(r.importClause.namedBindings)&&t.push("*");let s=t.length>0?"static":"side-effect";e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.moduleSpecifier.text,isStyle:w(r.moduleSpecifier.text),type:s,symbols:t.length>0?t:void 0})}function Yo(r,e){l.isExportDeclaration(r)?ei(r,e):l.isExportAssignment(r)?e.exports.set("default",{name:"default"}):ft(r)&&si(r,e)}function ei(r,e){if(r.moduleSpecifier&&l.isStringLiteral(r.moduleSpecifier))ti(r,r.moduleSpecifier.text,e);else if(r.exportClause&&l.isNamedExports(r.exportClause))for(let t of r.exportClause.elements){let s=t.name.text;e.exports.set(s,{name:s})}}function ti(r,e,t){let s=ri(r),n={fromPath:t.filePath,toPath:"",rawSpecifier:e,isStyle:w(e),type:"re-export"};s.length>0&&(n.symbols=s),t.imports.push(n)}function ri(r){return r.exportClause?l.isNamedExports(r.exportClause)?r.exportClause.elements.map(e=>e.name.text):[]:["*"]}function si(r,e){if((l.isFunctionDeclaration(r)||l.isClassDeclaration(r)||l.isInterfaceDeclaration(r)||l.isTypeAliasDeclaration(r)||l.isEnumDeclaration(r))&&r.name){let s=r.name.text;e.exports.set(s,Er(s,r,r,e.sourceFile));return}if(l.isVariableStatement(r)){for(let s of r.declarationList.declarations)if(l.isIdentifier(s.name)){let n=s.name.text;e.exports.set(n,Er(n,s,r,e.sourceFile))}}}function ni(r,e){if(!l.isCallExpression(r))return;let t=r.arguments[0];!t||!l.isStringLiteral(t)||(r.expression.kind===l.SyntaxKind.ImportKeyword?e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:t.text,isStyle:w(t.text),type:"dynamic"}):l.isIdentifier(r.expression)&&r.expression.text==="require"&&e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:t.text,isStyle:w(t.text),type:"require"}))}function oi(r,e){let t=Fr.basename(r).toLowerCase(),s=Fr.extname(r).toLowerCase();return q().some(o=>t.includes(o))?"test":wt(t)?"config":e.imports.some(o=>Re().some(i=>o.rawSpecifier.includes(i)))?"test":s===".tsx"||s===".jsx"||e.hasUI?"ui":e.hasTypesOnly&&e.totalStatements>0?"type-only":e.totalStatements>0&&e.exportStatements/e.totalStatements>Ge()?"barrel":"logic"}function ft(r){return l.canHaveModifiers(r)&&l.getModifiers(r)?.some(e=>e.kind===l.SyntaxKind.ExportKeyword)===!0}function ii(r,e){let t=r.rawCallEdges??[];r.rawCallEdges=t;let s=new Map;for(let n of e.statements){if(!l.isImportDeclaration(n)||!l.isStringLiteral(n.moduleSpecifier))continue;let o=n.moduleSpecifier.text,i=n.importClause;if(i&&(i.name&&s.set(i.name.text,o),i.namedBindings&&l.isNamedImports(i.namedBindings)))for(let a of i.namedBindings.elements)s.set(a.name.text,o)}if(s.size!==0)for(let n of e.statements){let o=pi(n);if(o){let i=ci(n);i&&Te(i,o,s,t);continue}l.isClassDeclaration(n)&&n.name&&ai(n,s,t)}}function ai(r,e,t){let s=r.name.text;for(let n of r.members)l.isMethodDeclaration(n)&&n.body&&l.isIdentifier(n.name)?Te(n.body,`${s}.${n.name.text}`,e,t):l.isConstructorDeclaration(n)&&n.body&&Te(n.body,`${s}.constructor`,e,t)}function pi(r){if(ft(r)){if(l.isFunctionDeclaration(r)&&r.name)return r.name.text;if(l.isVariableStatement(r)){for(let e of r.declarationList.declarations)if(l.isIdentifier(e.name)&&e.initializer&&(l.isArrowFunction(e.initializer)||l.isFunctionExpression(e.initializer)))return e.name.text}}}function ci(r){if(l.isFunctionDeclaration(r))return r.body;if(l.isVariableStatement(r)){for(let e of r.declarationList.declarations)if(e.initializer&&(l.isArrowFunction(e.initializer)||l.isFunctionExpression(e.initializer)))return e.initializer}}function Te(r,e,t,s){if(l.isCallExpression(r)&&l.isIdentifier(r.expression)){let n=r.expression.text,o=t.get(n);o&&!s.some(i=>i.from===e&&i.to===n&&i.toSpecifier===o)&&s.push({from:e,to:n,toSpecifier:o})}l.forEachChild(r,n=>Te(n,e,t,s))}function Ae(r,e){if(e.length===0)return"ui";let t=!1;return r.walk(s=>{if(s.type==="rule")return t=!0,!1}),t?"ui":"barrel"}import Pr from"postcss";var li=ae("postcss-less"),Ir=new Set(["reference","inline"]);function Ar(r){return r.startsWith("~")||r.startsWith("http://")||r.startsWith("https://")||r.startsWith("//")||r.startsWith("data:")}function ui(r){let e=r.trim();return e.length>0&&!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("//")&&!e.startsWith("data:")&&!e.startsWith("#")}function fi(r,e){let t=r.match(/^\(([^)]+)\)\s+['"]([^'"]+)['"]/);if(t){let o=t[1]?.trim()??"",i=t[2]??"";if(!i)return null;let a=Ir.has(o)?"side-effect":"static";return{fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a,...Ar(i)?{isExternal:!0}:{}}}let s=r.match(/^url\(['"]?([^'")]+)['"]?\)/),n=s?s[1]?.trim()??"":r.match(/^['"]([^'"]+)['"]/)?.[1]??"";return n?{fromPath:e,toPath:"",rawSpecifier:n,isStyle:!0,type:"static",...Ar(n)?{isExternal:!0}:{}}:null}function gi(r,e){let t=[],s=/url\(['"]?([^'")]+)['"]?\)/g,n=s.exec(r);for(;n!==null;){let o=n[1]?.trim()??"";ui(o)&&t.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:"static"}),n=s.exec(r)}return t}function Mr(r,e){let t=[];return r.walk(s=>{if(s.type==="atrule"&&s.name==="import"){let n=fi(s.params,e);n&&t.push(n)}s.type==="decl"&&t.push(...gi(s.value,e))}),t}function mi(r){return r.replace(/(?<!:)\/\/.*/g,"")}function di(r,e){let t=[],s=/@import\s+(?:\(([^)]+)\)\s+)?['"]([^'"]+)['"]/g,n=s.exec(r);for(;n!==null;){let o=n[1]?.trim()??"",i=n[2]??"";if(i){let a=Ir.has(o)?"side-effect":"static";t.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a})}n=s.exec(r)}return t}function Rr(r,e){let t=Pr.parse(mi(r));return{imports:Mr(t,e),root:t}}function Nr(r,e){try{let t=li.parse(r);return{imports:Mr(t,e),root:t}}catch{return{imports:di(r,e),root:Pr.parse("")}}}import{parse as hi}from"postcss-scss";function yi(r){return!!(r.startsWith("sass:")||r.startsWith("~")||r.startsWith("http://")||r.startsWith("https://")||r.startsWith("//")||!r.startsWith(".")&&!r.startsWith("/")&&!r.startsWith("_"))}function xi(r){let e=r.match(/^['"]([^'"]+)['"]/);if(!e?.[1])return{specifier:""};let t=e[1],n=r.match(/\bas\s+(\S+)/)?.[1];return n!==void 0?{specifier:t,alias:n}:{specifier:t}}function Gr(r,e){let t=hi(r),s=[];return t.walk(n=>{if(n.type!=="atrule")return;let{name:o,params:i}=n;if(o!=="import"&&o!=="use"&&o!=="forward")return;let{specifier:a,alias:p}=xi(i);if(!a)return;let c={fromPath:e,toPath:"",rawSpecifier:a,isStyle:!0,type:o==="forward"?"re-export":"static",...yi(a)?{isExternal:!0}:{}};p&&(c.symbols=[p]),s.push(c)}),{imports:s,root:t}}function Dr(r,e){let t=[],s=/@require\s+['"]([^'"]+)['"]/g,n=s.exec(r);for(;n!==null;){let i=n[1];i&&t.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"require"}),n=s.exec(r)}let o=/(?<!@)(?:import|require)\s*\(?\s*['"]([^'"]+)['"]/g;for(n=o.exec(r);n!==null;){let i=n[1];i&&t.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"static"}),n=o.exec(r)}return t}function jr(r,e){if(e.length===0)return"ui";try{let t=ae("stylus");return new t.Parser(r).parse().nodes.some(o=>o.constructor.name!=="Import")?"ui":"barrel"}catch{return r.replace(/^\s*@?(?:require|import)\b.*/gm,"").trim().length>0?"ui":"barrel"}}function ee(r,e){let t=A(r);if(t==="stylus"){let o=Dr(e,r);return{imports:o,exports:[],tags:[],category:jr(e,o)}}if(t==="scss"){let{imports:o,root:i}=Gr(e,r);return{imports:o,exports:[],tags:[],category:Ae(i,o)}}if(t==="less"){let{imports:o,root:i}=Nr(e,r);return{imports:o,exports:[],tags:[],category:Ae(i,o)}}let{imports:s,root:n}=Rr(e,r);return{imports:s,exports:[],tags:[],category:Ae(n,s)}}for(let[r,e]of[["javascript",(t,s)=>ut(t,s,"javascript")],["typescript",(t,s)=>ut(t,s,"typescript")],["css",ee],["scss",ee],["less",ee],["stylus",ee],["coffeescript",xr],["livescript",vr],["lua",kr],["python",wr],["go",br],["gherkin",at]])G(r,e);async function _r(r,e){let t=A(r),s=Vt(t);return s?s(r,e):{imports:[],exports:[],tags:[],category:"other"}}import gt from"path";function Or(r,e){for(let t of r.values()){let s=e.get(t.path);s!==void 0&&(t.coveragePct=s)}}function Wr(r,e){for(let t of r)if(!t.rawSpecifier.startsWith(".")&&!gt.isAbsolute(t.rawSpecifier)){let s=t.rawSpecifier.startsWith("@")?t.rawSpecifier.split("/").slice(0,2).join("/"):t.rawSpecifier.split("/")[0];s&&!e.some(n=>n.name===s)&&e.push({name:s,kind:"library"})}}function zr(r){for(let e of r.values())if(e.category==="test")for(let t of e.imports){if(t.isExternal||!t.toPath)continue;let s=r.get(t.toPath);s&&(s.category!=="logic"&&s.category!=="barrel"||(s.testedBy??=[],s.testedBy.includes(e.path)||s.testedBy.push(e.path)))}}function Lr(r){return Math.round(r*1e4)/1e4}function $r(r){for(let e of r.values()){let t=[];for(let s of e.imports){if(s.isExternal||!s.toPath)continue;let n=r.get(s.toPath);if(!n||n.exports.length===0)continue;let o;if(s.symbols===void 0){if(s.type==="side-effect")continue;o=1}else s.symbols.includes("*")?o=1:o=s.symbols.length/n.exports.length;s.exportUsageRatio=Lr(Math.min(1,o)),t.push(s.exportUsageRatio)}t.length>0&&(e.avgExportUsage=Lr(t.reduce((s,n)=>s+n,0)/t.length),e.maxExportUsage=Math.max(...t))}}function mt(r,e,t){e&&(r.some(s=>s.name===e&&s.kind===t)||r.push({name:e,kind:t}))}function Si(r,e){let t=e.toPath,s=gt.basename(t,gt.extname(t)).replace(/\.(test|spec)$/,"");mt(r.tags,s,"import")}function bi(r,e){if(!(!e.symbols||e.symbols.includes("*")))for(let t of e.symbols)mt(r.tags,t,"import")}function vi(r,e,t){let s=t.get(e.toPath);if(!(!s||s.category==="test"))for(let n of s.tags)n.kind==="comment-marker"&&mt(r.tags,n.name,"comment-marker")}function Br(r){for(let e of r.values())if(e.category==="test")for(let t of e.imports)!t.toPath||t.isExternal||(Si(e,t),bi(e,t),vi(e,t,r))}import Pe from"fs";import P from"path";import Kr from"fs";import $ from"path";var te=class{extensions=[".go"];goModCache=new Map;resolve(e,t,s,n){let{mod:o,replaces:i}=this.readGoMod(s);if(!o)return null;let a=this.applyReplace(t,i,s);if(a!==void 0)return qr(a);if(t!==o&&!t.startsWith(`${o}/`))return null;let p=t.slice(o.length).replace(/^\//,"");return p?qr($.join(s,p)):null}readGoMod(e){let t=this.goModCache.get(e);if(t!==void 0)return t;let s={mod:null,replaces:new Map};try{let n=Kr.readFileSync($.join(e,"go.mod"),"utf-8"),o=ki(n,e);return this.goModCache.set(e,o),o}catch{return this.goModCache.set(e,s),s}}applyReplace(e,t,s){for(let[n,o]of t){if(e===n)return o;if(e.startsWith(`${n}/`)){let i=e.slice(n.length+1);return $.join(o,i)}}}};function ki(r,e){let t=r.split(`
23
- `),s=null,n=new Map,o=!1;for(let i of t){let a=i.trim();if(a.startsWith("module ")){s=a.slice(7).trim();continue}if(/^replace\s*\(/.test(a)){o=!0;continue}if(o&&a===")"){o=!1;continue}if(o&&a.includes("=>")){Ur(a,e,n);continue}!o&&/^replace\s+/.test(a)&&a.includes("=>")&&Ur(a.replace(/^replace\s+/,""),e,n)}return{mod:s,replaces:n}}function Ur(r,e,t){let[s,n]=r.split("=>").map(a=>a.trim());if(!s||!n)return;let o=s.split(/\s+/)[0];if(!n.startsWith(".")&&!n.startsWith("/"))return;let i=$.isAbsolute(n)?n:$.resolve(e,n);t.set(o,i)}function qr(r){let e;try{e=Kr.readdirSync(r,{withFileTypes:!0})}catch{return null}let t=e.filter(s=>s.isFile()&&s.name.endsWith(".go")&&!s.name.endsWith("_test.go")).map(s=>({path:$.join(r,s.name),isExternal:!1})).sort((s,n)=>s.path.localeCompare(n.path));return t.length>0?t:null}import wi from"fs";import dt from"path";var re=class{extensions=[".lua"];resolve(e,t,s,n){let o=t.replace(/\./g,dt.sep),i=[s,dt.join(s,"lib")];for(let a of i){if(!wi.existsSync(a))continue;let p=n(dt.join(a,"_dummy.lua"),o);if(p)return[p]}return null}};import Ci from"fs";import ht from"path";var se=class{extensions=[".py"];resolve(e,t,s,n){let o=t.replace(/\./g,ht.sep),i=ht.join(s,`${o}.py`);if(Jr(i))return[{path:i,isExternal:!1}];let a=ht.join(s,o,"__init__.py");return Jr(a)?[{path:a,isExternal:!1}]:null}};function Jr(r){try{return Ci.statSync(r,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}var B=class{constructor(e,t={}){this.rootDir=e;this.workspaceMap=t.workspaceMap??new Map,this.tsconfigSearchPaths=t.tsconfigSearchPaths??[e],this.langResolvers=t.langResolvers??[new se,new re,new te]}rootDir;workspaceMap;tsconfigSearchPaths;langResolvers;resolveAll(e,t){let s=this.resolvePathAlias(t);if(s)return[s];if(t.startsWith(".")||t.startsWith("/")){let i=this.resolveLocalPath(e,t);return i?[i]:[]}let n=(i,a)=>this.resolveLocalPath(i,a);for(let i of this.langResolvers)if(i.extensions.some(a=>e.endsWith(a))){let a=i.resolve(e,t,this.rootDir,n);if(a)return a}let o=this.resolveWorkspaceImport(t);return o?[o]:[{path:t,isExternal:!0}]}resolve(e,t){let s=this.resolvePathAlias(t);if(s)return s;if(t.startsWith(".")||t.startsWith("/"))return this.resolveLocalPath(e,t);let n=(i,a)=>this.resolveLocalPath(i,a);for(let i of this.langResolvers)if(i.extensions.some(a=>e.endsWith(a))){let a=i.resolve(e,t,this.rootDir,n);if(a)return a[0]??null}let o=this.resolveWorkspaceImport(t);return o||{path:t,isExternal:!0}}resolveLocalPath(e,t){let s=P.dirname(e),n=t.startsWith("/")?t:P.resolve(s,t),o=!n.startsWith(this.rootDir),i=["",".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".feature"],a=n.match(/\.(js|mjs|cjs)$/);if(a){let p=n.slice(0,-a[0].length);for(let c of[".ts",".tsx"]){let u=this.tryExtensions(p,c,o);if(u)return u}}for(let p of i){let c=this.tryExtensions(n,p,o);if(c)return c}return o?{path:n,isExternal:!0}:null}tryExtensions(e,t,s){let n=e+t;if(this.isFile(n))return{path:n,isExternal:s};let o=P.join(e,`index${t}`);if(this.isFile(o))return{path:o,isExternal:s};if(t===".py"){let i=P.join(e,"__init__.py");if(this.isFile(i))return{path:i,isExternal:s}}return null}isFile(e){try{return Pe.statSync(e,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}resolvePathAlias(e){for(let t of this.tsconfigSearchPaths){let s=P.join(t,"tsconfig.json");if(Pe.existsSync(s))try{let o=JSON.parse(Pe.readFileSync(s,"utf-8")).compilerOptions?.paths;if(!o)continue;for(let i in o){let a=this.matchAliasPattern(i,e);if(a){let p=this.tryAliasSubstitutions(o[i],a[1]||"",t);if(p)return p}}}catch{}}return null}aliasRegexCache=new Map;matchAliasPattern(e,t){let s=this.aliasRegexCache.get(e);if(!s){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\*","(.*)");s=new RegExp(`^${n}$`),this.aliasRegexCache.set(e,s)}return t.match(s)}tryAliasSubstitutions(e,t,s=this.rootDir){let n=["",".ts",".tsx",".js",".jsx",".coffee",".ls",".lua",".feature"];for(let o of e){let i=o.replace("*",t),a=P.resolve(s,i);for(let p of n){let c=this.tryExtensions(a,p,!1);if(c)return c}}return null}resolveWorkspaceImport(e){if(this.workspaceMap.size===0)return null;for(let[t,s]of this.workspaceMap){if(e!==t&&!e.startsWith(`${t}/`))continue;let n=e.slice(t.length),o={path:"",isExternal:!1,isWorkspace:!0,workspacePackage:t};if(!n){for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"]){let p=P.join(s,a);try{if(Pe.statSync(p,{throwIfNoEntry:!1})?.isFile())return{...o,path:p}}catch{}}return{...o,path:s}}let i=this.resolveLocalPath(P.join(s,"_dummy"),n.slice(1));return i?{...o,path:i.path}:null}return null}};var Fi=["tests","test","__tests__","specs","spec"];function Ei(r,e){if(r.length===0)return e;let t=r.map(i=>v.dirname(i).split(v.sep)),s=t[0];for(let i of t.slice(1)){let a=0;for(;a<s.length&&a<i.length&&s[a]===i[a];)a++;s=s.slice(0,a)}let n=s.join(v.sep)||v.sep,o=v.relative(e,n);return o.startsWith("..")||v.isAbsolute(o)?e:n}var ne=class{constructor(e,t=null,s,n,o=!1,i=new Map){this.rootDir=e;this.enableGitStats=o;this.coverageMap=i;this.previousGraph=t,this.resolver=s||new B(e),this.lockFile=hr(e),n&&(this.progressCallback=n)}rootDir;enableGitStats;coverageMap;graph={nodes:new Map};visited=new Set;previousGraph=null;resolver;lockFile=null;progressCallback;async build(e){let t=e.map(s=>v.isAbsolute(s)?s:v.resolve(this.rootDir,s));for(let s of t)await this.processFile(s);return await this.processTestFiles(Ei(t,this.rootDir)),this.progressCallback&&this.visited.size>=100&&process.stderr.write(`
18
+ `+u}};function zn(r){let e=r.split(`
19
+ `),t=-1;for(let n=0;n<e.length;n++){let o=e[n].trimStart();(o.startsWith("import ")||o.startsWith("from "))&&(t=n)}if(t<0)return 0;let s=0;for(let n=0;n<=t;n++)s+=e[n].length+1;return s}import ar from"path";import pr from"typescript";var $n=/\/\/ <mokosh-tags>[\s\S]*?\/\/ <\/mokosh-tags>\n*/,ke=class{name="vitest";canHandle(e){return C.has(ar.extname(e).toLowerCase())}apply(e,t,s){let n=t.replace($n,""),o=pr.createSourceFile(ar.basename(e),n,pr.ScriptTarget.Latest,!0),i=D(o);if(i.length===0)return n;let a=_(i[0],"tags",o),p=[...s].sort();if(a!==null&&JSON.stringify([...a].sort())===JSON.stringify(p))return n;let c=i.flatMap(u=>{let f=s.length===0?L(u,"tags",o):j(u,"tags",W(p),o);return f?[f]:[]});return c.length>0?O(n,c):n}};var cr={vitest:()=>new ke,playwright:()=>new be,cypress:()=>new he,jest:()=>new Se},Bn={"@playwright/test":"playwright",cypress:"cypress","@jest/globals":"jest",vitest:"vitest"};function Un(r){let e=we.createSourceFile("detect.ts",r,we.ScriptTarget.Latest,!0);for(let t of e.statements){if(!we.isImportDeclaration(t)||!we.isStringLiteral(t.moduleSpecifier))continue;let s=Bn[t.moduleSpecifier.text];if(s)return s}return null}var ot=class{constructor(e,t,s){this.rootDir=e;this.defaultFramework=t;this.frameworkOverrides=s}rootDir;defaultFramework;frameworkOverrides;name="auto";canHandle(e){return C.has(nt.extname(e).toLowerCase())}apply(e,t,s){let n=Un(t)??this.matchOverride(e)??this.defaultFramework;return(cr[n]??cr.vitest)().apply(e,t,s)}matchOverride(e){let t=nt.relative(this.rootDir,e).split(nt.sep).join("/");for(let[s,n]of this.frameworkOverrides)if(nr(s,t))return n;return null}};function lr(r="vitest",e={},t=process.cwd()){return[new ye,new ve,new xe,new ot(t,r,Object.entries(e))]}function ur(r,e){return e.find(t=>t.canHandle(r))??null}var Kn=/^[a-zA-Z][a-zA-Z0-9_-]{1,}$/,Jn=new Set(["import"]),Hn=new Set(["common","fixture","fixtures","helper","helpers","index","main","mock","mocks","setup","shared","spec","test","tests","types","util","utils"]);async function Qn(r,e,t,s){let n;try{n=await fr.readFile(r,"utf8")}catch(a){return{path:r,status:"error",error:String(a)}}let o=ur(r,s);if(!o)return{path:r,status:"unchanged"};let i=o.apply(r,n,e);return i===n?{path:r,status:"unchanged"}:(t||await fr.writeFile(r,i,"utf8"),{path:r,status:"updated"})}async function it(r,e,t){let s=K(e),n=s.tagApplier?.framework??"vitest",o=s.tagApplier?.frameworkOverrides??{},i=lr(n,o,e),a={updated:0,unchanged:0,errors:0,files:[]};for(let p of r.nodes.values()){if(p.category!=="test")continue;let c=new Set,u=[];for(let y of p.tags)Jn.has(y.kind)&&Kn.test(y.name)&&(Hn.has(y.name.toLowerCase())||c.has(y.name)||(c.add(y.name),u.push(y.name)));u.sort();let f=qn.resolve(e,p.path),g=await Qn(f,u,t.dryRun,i);g.path=p.path,a.files.push(g),g.status==="updated"?a.updated++:g.status==="unchanged"?a.unchanged++:a.errors++}return a}var Ce=class{isTestNode(e){return e.category==="test"||e.tags.some(t=>t.name==="test")}};import Ie from"fs";import v from"path";import{execSync as gr}from"child_process";var Fe=class{getChangedFiles(){try{let t=["git diff --name-only","git diff --cached --name-only","git ls-files --others --exclude-standard"].flatMap(s=>{try{return gr(s,{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
20
+ `).map(o=>o.trim()).filter(o=>o!=="")}catch{return[]}});return Array.from(new Set(t))}catch(e){return console.error("Error getting git diff:",e),[]}}};function mr(r,e){let s=gr(`git -C "${r}" log --follow --format="%ae" --since="90 days ago" -- "${e}"`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).split(`
21
+ `).filter(Boolean);return{commitCount90d:s.length,lastAuthor:s[0]}}import Ee from"fs";import Vn from"path";import dr from"js-yaml";function hr(r){let e=r.lastIndexOf("@");return e>0?r.substring(0,e):r}function Xn(r){return r.replace(/:$/,"").split(",").map(e=>{let t=e.trim();return t.startsWith('"')&&(t=t.slice(1)),t.endsWith('"')&&(t=t.slice(0,-1)),hr(t)}).filter(Boolean)}function Zn(r,e){let t=r.startsWith("/")?r.slice(1):r,s=t.lastIndexOf("@");return s>0?{name:t.substring(0,s),version:e||t.substring(s+1)}:{name:t,version:e}}function Yn(r){try{let e=dr.load(r),t={dependencies:{}};for(let[s,n]of Object.entries(e))if(!(s==="__metadata"||!n?.version))for(let o of s.split(", ")){let i=hr(o);i&&(t.dependencies[i]={version:n.version,...n.dependencies!==void 0&&{dependencies:n.dependencies}})}return t}catch{return null}}function eo(r){let e={dependencies:{}};for(let t of r.split(/\n\n+/)){let s=t.split(`
22
+ `).filter(p=>p.trim().length>0&&!p.trim().startsWith("#"));if(s.length<2)continue;let n=s[0];if(!n||n.startsWith(" "))continue;let o=Xn(n);if(o.length===0)continue;let a=s.find(p=>p.trim().startsWith('version "'))?.match(/version "(.*?)"/)?.[1]??"";for(let p of o)e.dependencies[p]={version:a}}return e}function to(r){let e=Ee.readFileSync(r,"utf-8"),t=JSON.parse(e),s={dependencies:{}};if(t.packages)for(let[n,o]of Object.entries(t.packages)){if(!n.startsWith("node_modules/"))continue;let i=n.replace("node_modules/","");i.includes("node_modules/")||(s.dependencies[i]={version:o.version,...o.dependencies!==void 0&&{dependencies:o.dependencies}})}else if(t.dependencies)for(let[n,o]of Object.entries(t.dependencies))s.dependencies[n]={version:o.version,...o.dependencies!==void 0&&{dependencies:o.dependencies}};return s}function ro(r){let e=Ee.readFileSync(r,"utf-8");if(e.includes("__metadata:")){let t=Yn(e);if(t!==null)return t}return eo(e)}function so(r){let e=Ee.readFileSync(r,"utf-8"),t={dependencies:{}};try{let s=dr.load(e);if(s.packages)for(let[n,o]of Object.entries(s.packages)){let{name:i,version:a}=Zn(n,o.version);i&&(t.dependencies[i]={version:a,...o.dependencies!==void 0&&{dependencies:o.dependencies}})}if(s.dependencies)for(let[n,o]of Object.entries(s.dependencies)){if(t.dependencies[n])continue;let i=typeof o=="string"?o:o.version;t.dependencies[n]={version:i||""}}}catch{}return t}function yr(r){let e=[["package-lock.json",to],["yarn.lock",ro],["pnpm-lock.yaml",so]];for(let[t,s]of e){let n=Vn.join(r,t);if(Ee.existsSync(n))return s(n)}return null}import xr from"path";function A(r){switch(xr.extname(r).toLowerCase()){case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".ts":case".tsx":return"typescript";case".css":return"css";case".scss":case".sass":return"scss";case".less":return"less";case".styl":return"stylus";case".coffee":return"coffeescript";case".ls":return"livescript";case".lua":return"lua";case".py":return"python";case".go":return"go";case".java":case".cpp":case".cc":case".cxx":case".c":return"unknown";case".feature":return"gherkin";default:return"unknown"}}function w(r){let e=xr.extname(r).toLowerCase();return[".css",".scss",".sass",".less",".styl"].includes(e)}import no from"coffeescript";function oo(r){let e=new Set,t=/@tag\s+([a-zA-Z0-9_-]+)/g,s=t.exec(r);for(;s!==null;)s[1]&&e.add(s[1]),s=t.exec(r);return e}function io(r,e){let t=r.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||e.has("test")?"test":"logic"}function ao(r,e){let t=e.source?.value;return t?{fromPath:r,toPath:"",rawSpecifier:t,isStyle:w(t),type:"static"}:null}function po(r,e){let t=e.variable?.base?.value==="require",s=e.args?.[0]?.base?.value;return!t||!s?null:{fromPath:r,toPath:"",rawSpecifier:s,isStyle:w(s),type:"require"}}function co(r,e,t){let s=e.constructor?.name;if(s==="ImportDeclaration"){let n=ao(r,e);n&&t.push(n)}else if(s==="Call"){let n=po(r,e);n&&t.push(n)}}function at(r,e,t){if(!(!e||typeof e!="object")){co(r,e,t);for(let s in e){if(s==="locationData")continue;let n=e[s];if(!(!n||typeof n!="object"))if(Array.isArray(n))for(let o of n)at(r,o,t);else at(r,n,t)}}}function Sr(r,e){let t=oo(e),s=io(r,t),n=[];try{at(r,no.nodes(e),n)}catch{}return{imports:n,exports:[],tags:Array.from(t).map(o=>({name:o,kind:"comment-marker"})),category:s}}import{AstBuilder as lo,GherkinClassicTokenMatcher as uo,Parser as fo}from"@cucumber/gherkin";import{IdGenerator as go}from"@cucumber/messages";var mo=go.uuid();function pt(r,e){let t=new Set;try{let s=new lo(mo),n=new uo,i=new fo(s,n).parse(e);i.feature&&(i.feature.tags.forEach(a=>{t.add(a.name.startsWith("@")?a.name.slice(1):a.name)}),i.feature.children.forEach(a=>{a.scenario&&(a.scenario.tags.forEach(p=>{t.add(p.name.startsWith("@")?p.name.slice(1):p.name)}),a.scenario.examples.forEach(p=>{p.tags.forEach(c=>{t.add(c.name.startsWith("@")?c.name.slice(1):c.name)})})),a.rule&&a.rule.children.forEach(p=>{p.scenario&&p.scenario.tags.forEach(c=>{t.add(c.name.startsWith("@")?c.name.slice(1):c.name)})})}))}catch(s){console.warn(`[GherkinParser] Failed to parse ${r}:`,s)}return{imports:[],exports:[],tags:Array.from(t).map(s=>({name:s,kind:"comment-marker"})),category:"test"}}G("gherkin",pt);import ho from"path";import{parser as yo}from"@lezer/go";var xo=/\/\/\s*@tag\s+([a-zA-Z0-9_-]+)/,So=/^\/\/go:build\s+(.+)$/,bo=/^\/\/\s*\+build\s+(.+)$/;function vr(r,e){let t=[],s=new Map,n=new Set,o=new Set,a=yo.parse(e).cursor();do switch(a.name){case"LineComment":{let f=e.slice(a.from,a.to),g=f.match(xo);g?.[1]&&n.add(g[1]);let y=f.match(So);y&&br(y[1],o);let F=f.match(bo);F&&br(F[1],o);break}case"ImportSpec":{let f=a.node.getChild("String");if(f){let y=e.slice(f.from,f.to).slice(1,-1);t.push({fromPath:r,toPath:"",rawSpecifier:y,isExternal:!0,isStyle:!1,type:"static"})}break}case"FunctionDecl":case"TypeDecl":case"VarDecl":case"ConstDecl":{let f=a.node.getChild("DefName")??a.node.getChild("TypeSpec")?.getChild("DefName")??a.node.getChild("VarSpec")?.getChild("DefName")??a.node.getChild("ConstSpec")?.getChild("DefName");if(f){let g=e.slice(f.from,f.to);g!=="_"&&/^[A-Z]/.test(g)&&!s.has(g)&&s.set(g,{name:g})}break}}while(a.next());let p=t.some(f=>f.rawSpecifier==="testing"),c=ho.basename(r).endsWith("_test.go")||n.has("test")||p?"test":"logic",u=new Set([...n,...o]);return{imports:t,exports:Array.from(s.values()),tags:Array.from(u).map(f=>({name:f,kind:"comment-marker"})),category:c}}function br(r,e){for(let t of r.split(/[\s,&|!()]+/)){let s=t.trim();s&&s!=="ignore"&&e.add(s)}}import vo from"livescript";function z(r){return r.startsWith("'")||r.startsWith('"')?r.slice(1,-1):r}function ko(r){let e=new Set,t=/@tag\s+([a-zA-Z0-9_-]+)/g,s=t.exec(r);for(;s!==null;)s[1]&&e.add(s[1]),s=t.exec(r);return e}function wo(r,e){let t=r.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||e.has("test")?"test":"logic"}var Co=new Set(["first_line","first_column","last_line","last_column","line","column"]);function Fo(r,e){let t=r.constructor?.name||r.type;if(t==="Import"){let s=r.right?.value;if(typeof s=="string"){let n=z(s);return{fromPath:e,toPath:"",rawSpecifier:n,isStyle:w(n),type:"static"}}}if(t==="Chain"&&r.head?.value==="require"){let s=r.tails?.[0];if(s?.constructor?.name==="Call"||s?.type==="Call"){let n=s.args?.[0]?.value;if(typeof n=="string"){let o=z(n);return{fromPath:e,toPath:"",rawSpecifier:o,isStyle:w(o),type:"require"}}}}return null}function ct(r,e){if(!r||typeof r!="object")return[];let t=[],s=Fo(r,e);s&&t.push(s);for(let n in r){if(Co.has(n))continue;let o=r[n];if(!(!o||typeof o!="object"))if(Array.isArray(o))for(let i of o)t.push(...ct(i,e));else t.push(...ct(o,e))}return t}function kr(r,e){let t=ko(e),s=wo(r,t),n=[];try{n=ct(vo.ast(e),r)}catch{}return{imports:n,exports:[],tags:Array.from(t).map(o=>({name:o,kind:"comment-marker"})),category:s}}import Eo from"luaparse";function To(r){let e=new Set,t=/@tag\s+([a-zA-Z0-9_-]+)/g,s=t.exec(r);for(;s!==null;)s[1]&&e.add(s[1]),s=t.exec(r);return e}function Ao(r,e){let t=r.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||e.has("test")?"test":"logic"}function Po(r,e){let t=[];function s(n){if(!(!n||typeof n!="object")){if((n.type==="CallExpression"||n.type==="StringCallExpression")&&n.base?.type==="Identifier"&&n.base?.name==="require"){let o;if(n.type==="CallExpression"){let i=n.arguments?.[0];i?.type==="StringLiteral"&&(o=z(i.raw))}else if(n.type==="StringCallExpression"){let i=n.argument;i?.type==="StringLiteral"&&(o=z(i.raw))}o&&t.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:w(o),type:"require"})}for(let o in n){if(o==="loc")continue;let i=n[o];if(i&&typeof i=="object")if(Array.isArray(i))for(let a of i)s(a);else s(i)}}}return s(r),t}function wr(r,e){let t=To(e),s=Ao(r,t),n=[];try{let o=Eo.parse(e);n=Po(o,r)}catch{}return{imports:n,exports:[],tags:Array.from(t).map(o=>({name:o,kind:"comment-marker"})),category:s}}import Io from"path";import{parser as Mo}from"@lezer/python";var Ro=new Set(["pytest","unittest","nose","hypothesis"]);function Cr(r,e){let t=[],s=[],n=new Set,o=Io.basename(r).toLowerCase(),a=Mo.parse(e).cursor();do switch(a.name){case"Comment":{let c=e.slice(a.from,a.to).match(/#\s*@tag\s+([a-zA-Z0-9_-]+)/);c?.[1]&&n.add(c[1]);break}case"ImportStatement":{for(let c of No(a.node,e,r))t.push(c);break}case"FunctionDefinition":case"ClassDefinition":{let c=a.node.parent;if(c?.name==="Script"||c?.name==="DecoratedStatement"&&c.parent?.name==="Script"){let f=a.node.getChild("VariableName");f&&s.push({name:e.slice(f.from,f.to)})}break}case"AssignStatement":{if(a.node.parent?.name==="Script"){let c=a.node.firstChild;c?.name==="VariableName"&&s.push({name:e.slice(c.from,c.to)})}break}}while(a.next());let p=jo(o,t,n);return p==="test"&&n.add("test"),{imports:t,exports:s,tags:Array.from(n).map(c=>({name:c,kind:"comment-marker"})),category:p}}function No(r,e,t){let s=r.firstChild;return s?s.name==="from"?Go(r,e,t):Do(r,e,t):[]}function Go(r,e,t){let s=r.firstChild;if(!s)return[];let n=s.nextSibling;for(;n&&n.name!=="import";)n=n.nextSibling;if(!n)return[];let o=e.slice(s.to,n.from).trim(),i=_o(n.nextSibling,e);if(!i.length)return[];let a=0;for(;a<o.length&&o[a]===".";)a++;let p=o.slice(a);if(a===0)return[Y(t,o,i,!0)];let c=a===1?"./":"../".repeat(a-1);return p?[Y(t,c+p.replace(/\./g,"/"),i,!1)]:i[0]==="*"?[Y(t,c.slice(0,-1),["*"],!1)]:i.map(u=>Y(t,c+u,[u],!1))}function Do(r,e,t){let s=[],n=r.firstChild?.nextSibling??null;for(;n;){if(n.name==="VariableName"){let o=e.slice(n.from,n.to);for(;n.nextSibling?.name==="."&&n.nextSibling.nextSibling?.name==="VariableName";)n=n.nextSibling.nextSibling,o+=`.${e.slice(n.from,n.to)}`;n.nextSibling?.name==="as"&&(n=n.nextSibling.nextSibling??n.nextSibling),s.push(Y(t,o,["*"],!0))}n=n.nextSibling}return s}function _o(r,e){let t=[],s=r;for(;s;)s.name==="*"?t.push("*"):s.name==="VariableName"&&(t.push(e.slice(s.from,s.to)),s.nextSibling?.name==="as"&&(s=s.nextSibling.nextSibling??s.nextSibling)),s=s.nextSibling;return t}function Y(r,e,t,s){return{fromPath:r,toPath:"",rawSpecifier:e,isStyle:!1,isExternal:s,type:"static",symbols:t.length>0?t:void 0}}function jo(r,e,t){return r.startsWith("test_")||r.endsWith("_test.py")?"test":r==="conftest.py"||r==="setup.py"?"config":t.has("test")||e.some(s=>Ro.has(s.rawSpecifier))?"test":"logic"}import Er from"path";import l from"typescript";import m from"typescript";function Lo(r){let e=1;function t(s){switch(s.kind){case m.SyntaxKind.IfStatement:case m.SyntaxKind.ConditionalExpression:case m.SyntaxKind.ForStatement:case m.SyntaxKind.ForInStatement:case m.SyntaxKind.ForOfStatement:case m.SyntaxKind.WhileStatement:case m.SyntaxKind.DoStatement:case m.SyntaxKind.CatchClause:case m.SyntaxKind.CaseClause:e++;break;case m.SyntaxKind.BinaryExpression:{let n=s.operatorToken.kind;(n===m.SyntaxKind.AmpersandAmpersandToken||n===m.SyntaxKind.BarBarToken||n===m.SyntaxKind.QuestionQuestionToken)&&e++;break}}m.forEachChild(s,t)}return t(r),e}function Oo(r){let e=0;function t(s,n,o){if(m.isIfStatement(s)){e+=o?1:1+n;let a=o?n:n+1;t(s.expression,a,!1),t(s.thenStatement,a,!1),s.elseStatement&&(m.isIfStatement(s.elseStatement)?t(s.elseStatement,n,!0):(e+=1,t(s.elseStatement,n+1,!1)));return}if(m.isForStatement(s)||m.isForInStatement(s)||m.isForOfStatement(s)||m.isWhileStatement(s)||m.isDoStatement(s)||m.isSwitchStatement(s)){e+=1+n,m.forEachChild(s,a=>t(a,n+1,!1));return}if(m.isCatchClause(s)){e+=1+n,m.forEachChild(s,a=>t(a,n,!1));return}if(m.isConditionalExpression(s)&&(e+=1),m.isBinaryExpression(s)){let a=s.operatorToken.kind;(a===m.SyntaxKind.AmpersandAmpersandToken||a===m.SyntaxKind.BarBarToken||a===m.SyntaxKind.QuestionQuestionToken)&&(e+=1)}if(n>0&&(m.isFunctionDeclaration(s)||m.isFunctionExpression(s)||m.isArrowFunction(s))){e+=1+n,m.forEachChild(s,a=>t(a,n+1,!1));return}m.forEachChild(s,a=>t(a,n,!1))}return t(r,0,!1),e}function lt(r){return{complexity:Lo(r),cognitiveComplexity:Oo(r)}}import x from"typescript";var ut=new Set(["test","describe","it"]);function Fr(r,e){Wo(r,e),$o(r,e),Bo(r,e),Uo(r,e)}function Wo(r,e){if((x.isFunctionDeclaration(r)||x.isVariableDeclaration(r))&&r.name&&x.isIdentifier(r.name)&&zo(r)){let t;if(x.isFunctionDeclaration(r))t="function";else{let s=r.initializer;t=s&&(x.isArrowFunction(s)||x.isFunctionExpression(s))?"function":"variable"}e.tags.add({name:r.name.text,kind:t})}}function zo(r){if(x.isFunctionDeclaration(r))return x.isSourceFile(r.parent);let e=r.parent?.parent;return!!e&&x.isSourceFile(e.parent)}function $o(r,e){if(!x.isStringLiteral(r))return;let t=r.text.match(/@[\w-]+/g);if(t)for(let s of t)e.tags.add({name:s.substring(1),kind:"comment-marker"})}function Bo(r,e){if(!x.isSourceFile(r))return;let t=/@tag\s+([a-zA-Z0-9_-]+)/g,s=r.getFullText(),n=t.exec(s);for(;n!==null;)n[1]&&e.tags.add({name:n[1],kind:"comment-marker"}),n=t.exec(s)}function Uo(r,e){if(x.isCallExpression(r)&&qo(r.expression))for(let t of r.arguments)x.isObjectLiteralExpression(t)&&Ko(t,e)}function qo(r){return x.isIdentifier(r)?ut.has(r.text):!!(x.isPropertyAccessExpression(r)&&(ut.has(r.name.text)||x.isIdentifier(r.expression)&&ut.has(r.expression.text)))}function Ko(r,e){for(let t of r.properties){if(!x.isPropertyAssignment(t)||!x.isIdentifier(t.name)||t.name.text!=="tags"&&t.name.text!=="tag")continue;let{initializer:s}=t,n=x.isArrayLiteralExpression(s)?s.elements.filter(x.isStringLiteral):t.name.text==="tag"&&x.isStringLiteral(s)?[s]:[];for(let o of n)e.tags.add({name:o.text.replace(/^@/,""),kind:"comment-marker"})}}function ft(r,e,t){let s=[],n=new Map,o=new Set,i=l.createSourceFile(r,e,l.ScriptTarget.Latest,!0,t==="typescript"?l.ScriptKind.TSX:l.ScriptKind.JSX),a={filePath:r,imports:s,exports:n,tags:o,rawCallEdges:[],sourceFile:i,hasUI:!1,hasTypesOnly:!0,totalStatements:0,exportStatements:0},p=ae=>{Vo(ae,a),l.forEachChild(ae,p)};p(i);let c=ai(r,a);(c==="test"||c==="barrel")&&o.add({name:c,kind:"comment-marker"}),c!=="test"&&pi(a,i);let u=i.statements[0],f=u?Ar(u):void 0,{complexity:g,cognitiveComplexity:y}=lt(i),F=Jo(i);return{imports:s,exports:Array.from(n.values()),tags:Array.from(o),category:c,rawCallEdges:a.rawCallEdges??[],complexity:g,cognitiveComplexity:y,...F.length>0?{functions:F}:{},...f!==void 0?{description:f}:{}}}function Jo(r){let e=[],t=(n,o)=>{let{complexity:i,cognitiveComplexity:a}=lt(o),p=r.getLineAndCharacterOfPosition(o.getStart(r)).line+1;e.push({name:n,line:p,complexity:i,cognitiveComplexity:a})},s=(n,o)=>{if(l.isFunctionDeclaration(n)&&n.name&&n.body?t(n.name.text,n):l.isVariableDeclaration(n)&&l.isIdentifier(n.name)&&n.initializer&&(l.isArrowFunction(n.initializer)||l.isFunctionExpression(n.initializer))?t(n.name.text,n.initializer):o&&l.isMethodDeclaration(n)&&l.isIdentifier(n.name)&&n.body?t(`${o}.${n.name.text}`,n):o&&l.isConstructorDeclaration(n)&&n.body?t(`${o}.constructor`,n):o&&l.isGetAccessorDeclaration(n)&&l.isIdentifier(n.name)&&n.body?t(`${o}.get ${n.name.text}`,n):o&&l.isSetAccessorDeclaration(n)&&l.isIdentifier(n.name)&&n.body&&t(`${o}.set ${n.name.text}`,n),l.isClassDeclaration(n)&&n.name){let i=n.name.text;l.forEachChild(n,a=>s(a,i));return}l.forEachChild(n,i=>s(i,o))};return s(r,void 0),e}function Tr(r,e,t,s){let n={name:r},o=Ar(t);o!==void 0&&(n.doc=o);let i=Ho(e);i!==void 0&&(n.flags=i);let a=Qo(e,s);return a!==void 0&&(n.signature=a),n}function Ar(r){let e=l.getJSDocCommentsAndTags(r);for(let t of e)if(l.isJSDoc(t)&&t.comment)return l.getTextOfJSDocComment(t.comment)||void 0}function Ho(r){let e=new Set(["deprecated","internal","public","alpha","beta"]),t=l.getJSDocTags(r).map(s=>s.tagName.text).filter(s=>e.has(s));return t.length>0?t:void 0}function Qo(r,e){let t=l.createPrinter({removeComments:!0}),s=n=>t.printNode(l.EmitHint.Unspecified,n,e);if(l.isFunctionDeclaration(r)||l.isMethodDeclaration(r)){let n=r.parameters.map(s).join(", "),o=r.type?s(r.type):"void";return`${r.typeParameters?`<${r.typeParameters.map(a=>a.name.text).join(", ")}>`:""}(${n}) => ${o}`}if(l.isVariableDeclaration(r)){if(r.type)return s(r.type);if(r.initializer&&(l.isArrowFunction(r.initializer)||l.isFunctionExpression(r.initializer))){let n=r.initializer,o=n.parameters.map(s).join(", "),i=n.type?s(n.type):"unknown";return`(${o}) => ${i}`}return}if(l.isClassDeclaration(r)&&r.name)return`class ${r.name.text}`;if(l.isInterfaceDeclaration(r))return`interface ${r.name.text}`;if(l.isTypeAliasDeclaration(r))return s(r.type);if(l.isEnumDeclaration(r))return`enum ${r.name.text}`}function Vo(r,e){Xo(r,e),Zo(r,e),ei(r,e),ti(r,e),ii(r,e),Fr(r,e)}function Xo(r,e){if(!l.isSourceFile(r))return;let t=r.statements.filter(s=>!l.isEmptyStatement(s));e.totalStatements=t.length,e.exportStatements=t.filter(s=>l.isExportDeclaration(s)||l.isExportAssignment(s)||gt(s)).length}function Zo(r,e){if(l.isJsxElement(r)||l.isJsxSelfClosingElement(r)||l.isJsxFragment(r)){e.hasUI=!0,e.hasTypesOnly=!1;return}if(l.isFunctionDeclaration(r)||l.isMethodDeclaration(r)||l.isArrowFunction(r)||l.isClassDeclaration(r)||l.isVariableStatement(r)||l.isEnumDeclaration(r)){e.hasTypesOnly=!1;return}l.isExportDeclaration(r)&&!Yo(r)&&(e.hasTypesOnly=!1)}function Yo(r){return r.isTypeOnly?!0:!r.exportClause||!l.isNamedExports(r.exportClause)?!1:r.exportClause.elements.every(e=>e.isTypeOnly)}function ei(r,e){if(!l.isImportDeclaration(r)||!r.moduleSpecifier||!l.isStringLiteral(r.moduleSpecifier))return;let t=[];if(r.importClause&&(r.importClause.name&&t.push("default"),r.importClause.namedBindings))if(l.isNamedImports(r.importClause.namedBindings))for(let n of r.importClause.namedBindings.elements)t.push(n.name.text);else l.isNamespaceImport(r.importClause.namedBindings)&&t.push("*");let s=t.length>0?"static":"side-effect";e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:r.moduleSpecifier.text,isStyle:w(r.moduleSpecifier.text),type:s,symbols:t.length>0?t:void 0})}function ti(r,e){l.isExportDeclaration(r)?ri(r,e):l.isExportAssignment(r)?e.exports.set("default",{name:"default"}):gt(r)&&oi(r,e)}function ri(r,e){if(r.moduleSpecifier&&l.isStringLiteral(r.moduleSpecifier))si(r,r.moduleSpecifier.text,e);else if(r.exportClause&&l.isNamedExports(r.exportClause))for(let t of r.exportClause.elements){let s=t.name.text;e.exports.set(s,{name:s})}}function si(r,e,t){let s=ni(r),n={fromPath:t.filePath,toPath:"",rawSpecifier:e,isStyle:w(e),type:"re-export"};s.length>0&&(n.symbols=s),t.imports.push(n)}function ni(r){return r.exportClause?l.isNamedExports(r.exportClause)?r.exportClause.elements.map(e=>e.name.text):[]:["*"]}function oi(r,e){if((l.isFunctionDeclaration(r)||l.isClassDeclaration(r)||l.isInterfaceDeclaration(r)||l.isTypeAliasDeclaration(r)||l.isEnumDeclaration(r))&&r.name){let s=r.name.text;e.exports.set(s,Tr(s,r,r,e.sourceFile));return}if(l.isVariableStatement(r)){for(let s of r.declarationList.declarations)if(l.isIdentifier(s.name)){let n=s.name.text;e.exports.set(n,Tr(n,s,r,e.sourceFile))}}}function ii(r,e){if(!l.isCallExpression(r))return;let t=r.arguments[0];!t||!l.isStringLiteral(t)||(r.expression.kind===l.SyntaxKind.ImportKeyword?e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:t.text,isStyle:w(t.text),type:"dynamic"}):l.isIdentifier(r.expression)&&r.expression.text==="require"&&e.imports.push({fromPath:e.filePath,toPath:"",rawSpecifier:t.text,isStyle:w(t.text),type:"require"}))}function ai(r,e){let t=Er.basename(r).toLowerCase(),s=Er.extname(r).toLowerCase();return q().some(o=>t.includes(o))?"test":Ct(t)?"config":e.imports.some(o=>Ne().some(i=>o.rawSpecifier.includes(i)))?"test":s===".tsx"||s===".jsx"||e.hasUI?"ui":e.hasTypesOnly&&e.totalStatements>0?"type-only":e.totalStatements>0&&e.exportStatements/e.totalStatements>De()?"barrel":"logic"}function gt(r){return l.canHaveModifiers(r)&&l.getModifiers(r)?.some(e=>e.kind===l.SyntaxKind.ExportKeyword)===!0}function pi(r,e){let t=r.rawCallEdges??[];r.rawCallEdges=t;let s=new Map;for(let n of e.statements){if(!l.isImportDeclaration(n)||!l.isStringLiteral(n.moduleSpecifier))continue;let o=n.moduleSpecifier.text,i=n.importClause;if(i&&(i.name&&s.set(i.name.text,o),i.namedBindings&&l.isNamedImports(i.namedBindings)))for(let a of i.namedBindings.elements)s.set(a.name.text,o)}if(s.size!==0)for(let n of e.statements){let o=li(n);if(o){let i=ui(n);i&&Te(i,o,s,t);continue}l.isClassDeclaration(n)&&n.name&&ci(n,s,t)}}function ci(r,e,t){let s=r.name.text;for(let n of r.members)l.isMethodDeclaration(n)&&n.body&&l.isIdentifier(n.name)?Te(n.body,`${s}.${n.name.text}`,e,t):l.isConstructorDeclaration(n)&&n.body&&Te(n.body,`${s}.constructor`,e,t)}function li(r){if(gt(r)){if(l.isFunctionDeclaration(r)&&r.name)return r.name.text;if(l.isVariableStatement(r)){for(let e of r.declarationList.declarations)if(l.isIdentifier(e.name)&&e.initializer&&(l.isArrowFunction(e.initializer)||l.isFunctionExpression(e.initializer)))return e.name.text}}}function ui(r){if(l.isFunctionDeclaration(r))return r.body;if(l.isVariableStatement(r)){for(let e of r.declarationList.declarations)if(e.initializer&&(l.isArrowFunction(e.initializer)||l.isFunctionExpression(e.initializer)))return e.initializer}}function Te(r,e,t,s){if(l.isCallExpression(r)&&l.isIdentifier(r.expression)){let n=r.expression.text,o=t.get(n);o&&!s.some(i=>i.from===e&&i.to===n&&i.toSpecifier===o)&&s.push({from:e,to:n,toSpecifier:o})}l.forEachChild(r,n=>Te(n,e,t,s))}function Ae(r,e){if(e.length===0)return"ui";let t=!1;return r.walk(s=>{if(s.type==="rule")return t=!0,!1}),t?"ui":"barrel"}import Ir from"postcss";import*as fi from"postcss-less";var gi=fi,Mr=new Set(["reference","inline"]);function Pr(r){return r.startsWith("~")||r.startsWith("http://")||r.startsWith("https://")||r.startsWith("//")||r.startsWith("data:")}function mi(r){let e=r.trim();return e.length>0&&!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("//")&&!e.startsWith("data:")&&!e.startsWith("#")}function di(r,e){let t=r.match(/^\(([^)]+)\)\s+['"]([^'"]+)['"]/);if(t){let o=t[1]?.trim()??"",i=t[2]??"";if(!i)return null;let a=Mr.has(o)?"side-effect":"static";return{fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a,...Pr(i)?{isExternal:!0}:{}}}let s=r.match(/^url\(['"]?([^'")]+)['"]?\)/),n=s?s[1]?.trim()??"":r.match(/^['"]([^'"]+)['"]/)?.[1]??"";return n?{fromPath:e,toPath:"",rawSpecifier:n,isStyle:!0,type:"static",...Pr(n)?{isExternal:!0}:{}}:null}function hi(r,e){let t=[],s=/url\(['"]?([^'")]+)['"]?\)/g,n=s.exec(r);for(;n!==null;){let o=n[1]?.trim()??"";mi(o)&&t.push({fromPath:e,toPath:"",rawSpecifier:o,isStyle:!0,type:"static"}),n=s.exec(r)}return t}function Rr(r,e){let t=[];return r.walk(s=>{if(s.type==="atrule"&&s.name==="import"){let n=di(s.params,e);n&&t.push(n)}s.type==="decl"&&t.push(...hi(s.value,e))}),t}function yi(r){return r.replace(/(?<!:)\/\/.*/g,"")}function xi(r,e){let t=[],s=/@import\s+(?:\(([^)]+)\)\s+)?['"]([^'"]+)['"]/g,n=s.exec(r);for(;n!==null;){let o=n[1]?.trim()??"",i=n[2]??"";if(i){let a=Mr.has(o)?"side-effect":"static";t.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:a})}n=s.exec(r)}return t}function Nr(r,e){let t=Ir.parse(yi(r));return{imports:Rr(t,e),root:t}}function Gr(r,e){try{let t=gi.parse(r);return{imports:Rr(t,e),root:t}}catch{return{imports:xi(r,e),root:Ir.parse("")}}}import{parse as Si}from"postcss-scss";function bi(r){return!!(r.startsWith("sass:")||r.startsWith("~")||r.startsWith("http://")||r.startsWith("https://")||r.startsWith("//")||!r.startsWith(".")&&!r.startsWith("/")&&!r.startsWith("_"))}function vi(r){let e=r.match(/^['"]([^'"]+)['"]/);if(!e?.[1])return{specifier:""};let t=e[1],n=r.match(/\bas\s+(\S+)/)?.[1];return n!==void 0?{specifier:t,alias:n}:{specifier:t}}function Dr(r,e){let t=Si(r),s=[];return t.walk(n=>{if(n.type!=="atrule")return;let{name:o,params:i}=n;if(o!=="import"&&o!=="use"&&o!=="forward")return;let{specifier:a,alias:p}=vi(i);if(!a)return;let c={fromPath:e,toPath:"",rawSpecifier:a,isStyle:!0,type:o==="forward"?"re-export":"static",...bi(a)?{isExternal:!0}:{}};p&&(c.symbols=[p]),s.push(c)}),{imports:s,root:t}}function _r(r,e){let t=[],s=/@require\s+['"]([^'"]+)['"]/g,n=s.exec(r);for(;n!==null;){let i=n[1];i&&t.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"require"}),n=s.exec(r)}let o=/(?<!@)(?:import|require)\s*\(?\s*['"]([^'"]+)['"]/g;for(n=o.exec(r);n!==null;){let i=n[1];i&&t.push({fromPath:e,toPath:"",rawSpecifier:i,isStyle:!0,type:"static"}),n=o.exec(r)}return t}function jr(r,e){if(e.length===0)return"ui";try{let t=Re("stylus");return new t.Parser(r).parse().nodes.some(o=>o.constructor.name!=="Import")?"ui":"barrel"}catch{return r.replace(/^\s*@?(?:require|import)\b.*/gm,"").trim().length>0?"ui":"barrel"}}function ee(r,e){let t=A(r);if(t==="stylus"){let o=_r(e,r);return{imports:o,exports:[],tags:[],category:jr(e,o)}}if(t==="scss"){let{imports:o,root:i}=Dr(e,r);return{imports:o,exports:[],tags:[],category:Ae(i,o)}}if(t==="less"){let{imports:o,root:i}=Gr(e,r);return{imports:o,exports:[],tags:[],category:Ae(i,o)}}let{imports:s,root:n}=Nr(e,r);return{imports:s,exports:[],tags:[],category:Ae(n,s)}}for(let[r,e]of[["javascript",(t,s)=>ft(t,s,"javascript")],["typescript",(t,s)=>ft(t,s,"typescript")],["css",ee],["scss",ee],["less",ee],["stylus",ee],["coffeescript",Sr],["livescript",kr],["lua",wr],["python",Cr],["go",vr],["gherkin",pt]])G(r,e);async function Lr(r,e){let t=A(r),s=Xt(t);return s?s(r,e):{imports:[],exports:[],tags:[],category:"other"}}import mt from"path";function Wr(r,e){for(let t of r.values()){let s=e.get(t.path);s!==void 0&&(t.coveragePct=s)}}function zr(r,e){for(let t of r)if(!t.rawSpecifier.startsWith(".")&&!mt.isAbsolute(t.rawSpecifier)){let s=t.rawSpecifier.startsWith("@")?t.rawSpecifier.split("/").slice(0,2).join("/"):t.rawSpecifier.split("/")[0];s&&!e.some(n=>n.name===s)&&e.push({name:s,kind:"library"})}}function $r(r){for(let e of r.values())if(e.category==="test")for(let t of e.imports){if(t.isExternal||!t.toPath)continue;let s=r.get(t.toPath);s&&(s.category!=="logic"&&s.category!=="barrel"||(s.testedBy??=[],s.testedBy.includes(e.path)||s.testedBy.push(e.path)))}}function Or(r){return Math.round(r*1e4)/1e4}function Br(r){for(let e of r.values()){let t=[];for(let s of e.imports){if(s.isExternal||!s.toPath)continue;let n=r.get(s.toPath);if(!n||n.exports.length===0)continue;let o;if(s.symbols===void 0){if(s.type==="side-effect")continue;o=1}else s.symbols.includes("*")?o=1:o=s.symbols.length/n.exports.length;s.exportUsageRatio=Or(Math.min(1,o)),t.push(s.exportUsageRatio)}t.length>0&&(e.avgExportUsage=Or(t.reduce((s,n)=>s+n,0)/t.length),e.maxExportUsage=Math.max(...t))}}function dt(r,e,t){e&&(r.some(s=>s.name===e&&s.kind===t)||r.push({name:e,kind:t}))}function ki(r,e){let t=e.toPath,s=mt.basename(t,mt.extname(t)).replace(/\.(test|spec)$/,"");dt(r.tags,s,"import")}function wi(r,e){if(!(!e.symbols||e.symbols.includes("*")))for(let t of e.symbols)dt(r.tags,t,"import")}function Ci(r,e,t){let s=t.get(e.toPath);if(!(!s||s.category==="test"))for(let n of s.tags)n.kind==="comment-marker"&&dt(r.tags,n.name,"comment-marker")}function Ur(r){for(let e of r.values())if(e.category==="test")for(let t of e.imports)!t.toPath||t.isExternal||(ki(e,t),wi(e,t),Ci(e,t,r))}import Pe from"fs";import P from"path";import Jr from"fs";import $ from"path";var te=class{extensions=[".go"];goModCache=new Map;resolve(e,t,s,n){let{mod:o,replaces:i}=this.readGoMod(s);if(!o)return null;let a=this.applyReplace(t,i,s);if(a!==void 0)return Kr(a);if(t!==o&&!t.startsWith(`${o}/`))return null;let p=t.slice(o.length).replace(/^\//,"");return p?Kr($.join(s,p)):null}readGoMod(e){let t=this.goModCache.get(e);if(t!==void 0)return t;let s={mod:null,replaces:new Map};try{let n=Jr.readFileSync($.join(e,"go.mod"),"utf-8"),o=Fi(n,e);return this.goModCache.set(e,o),o}catch{return this.goModCache.set(e,s),s}}applyReplace(e,t,s){for(let[n,o]of t){if(e===n)return o;if(e.startsWith(`${n}/`)){let i=e.slice(n.length+1);return $.join(o,i)}}}};function Fi(r,e){let t=r.split(`
23
+ `),s=null,n=new Map,o=!1;for(let i of t){let a=i.trim();if(a.startsWith("module ")){s=a.slice(7).trim();continue}if(/^replace\s*\(/.test(a)){o=!0;continue}if(o&&a===")"){o=!1;continue}if(o&&a.includes("=>")){qr(a,e,n);continue}!o&&/^replace\s+/.test(a)&&a.includes("=>")&&qr(a.replace(/^replace\s+/,""),e,n)}return{mod:s,replaces:n}}function qr(r,e,t){let[s,n]=r.split("=>").map(a=>a.trim());if(!s||!n)return;let o=s.split(/\s+/)[0];if(!n.startsWith(".")&&!n.startsWith("/"))return;let i=$.isAbsolute(n)?n:$.resolve(e,n);t.set(o,i)}function Kr(r){let e;try{e=Jr.readdirSync(r,{withFileTypes:!0})}catch{return null}let t=e.filter(s=>s.isFile()&&s.name.endsWith(".go")&&!s.name.endsWith("_test.go")).map(s=>({path:$.join(r,s.name),isExternal:!1})).sort((s,n)=>s.path.localeCompare(n.path));return t.length>0?t:null}import Ei from"fs";import ht from"path";var re=class{extensions=[".lua"];resolve(e,t,s,n){let o=t.replace(/\./g,ht.sep),i=[s,ht.join(s,"lib")];for(let a of i){if(!Ei.existsSync(a))continue;let p=n(ht.join(a,"_dummy.lua"),o);if(p)return[p]}return null}};import Ti from"fs";import yt from"path";var se=class{extensions=[".py"];resolve(e,t,s,n){let o=t.replace(/\./g,yt.sep),i=yt.join(s,`${o}.py`);if(Hr(i))return[{path:i,isExternal:!1}];let a=yt.join(s,o,"__init__.py");return Hr(a)?[{path:a,isExternal:!1}]:null}};function Hr(r){try{return Ti.statSync(r,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}import Qr from"path";var Ai=["~","http://","https://","//","data:","sass:"],ne=class{extensions=[".css",".scss",".sass",".less",".styl"];resolve(e,t,s,n){if(Ai.some(u=>t.startsWith(u)))return null;let o=n(e,t);if(o)return[o];let i=Qr.dirname(t),a=Qr.basename(t),p=i==="."?`_${a}`:`${i}/_${a}`,c=n(e,p);return c?[c]:null}};var B=class{constructor(e,t={}){this.rootDir=e;this.workspaceMap=t.workspaceMap??new Map,this.tsconfigSearchPaths=t.tsconfigSearchPaths??[e],this.langResolvers=t.langResolvers??[new se,new re,new te,new ne]}rootDir;workspaceMap;tsconfigSearchPaths;langResolvers;resolveAll(e,t){let s=this.resolvePathAlias(t);if(s)return[s];if(t.startsWith(".")||t.startsWith("/")){let i=this.resolveLocalPath(e,t);return i?[i]:[]}let n=(i,a)=>this.resolveLocalPath(i,a);for(let i of this.langResolvers)if(i.extensions.some(a=>e.endsWith(a))){let a=i.resolve(e,t,this.rootDir,n);if(a)return a}let o=this.resolveWorkspaceImport(t);return o?[o]:[{path:t,isExternal:!0}]}resolve(e,t){let s=this.resolvePathAlias(t);if(s)return s;if(t.startsWith(".")||t.startsWith("/"))return this.resolveLocalPath(e,t);let n=(i,a)=>this.resolveLocalPath(i,a);for(let i of this.langResolvers)if(i.extensions.some(a=>e.endsWith(a))){let a=i.resolve(e,t,this.rootDir,n);if(a)return a[0]??null}let o=this.resolveWorkspaceImport(t);return o||{path:t,isExternal:!0}}resolveLocalPath(e,t){let s=P.dirname(e),n=t.startsWith("/")?t:P.resolve(s,t),o=!n.startsWith(this.rootDir),i=["",".ts",".tsx",".js",".jsx",".mjs",".cjs",".css",".scss",".sass",".less",".styl",".coffee",".ls",".lua",".py",".feature"],a=n.match(/\.(js|mjs|cjs)$/);if(a){let p=n.slice(0,-a[0].length);for(let c of[".ts",".tsx"]){let u=this.tryExtensions(p,c,o);if(u)return u}}for(let p of i){let c=this.tryExtensions(n,p,o);if(c)return c}return o?{path:n,isExternal:!0}:null}tryExtensions(e,t,s){let n=e+t;if(this.isFile(n))return{path:n,isExternal:s};let o=P.join(e,`index${t}`);if(this.isFile(o))return{path:o,isExternal:s};if(t===".py"){let i=P.join(e,"__init__.py");if(this.isFile(i))return{path:i,isExternal:s}}return null}isFile(e){try{return Pe.statSync(e,{throwIfNoEntry:!1})?.isFile()===!0}catch{return!1}}resolvePathAlias(e){for(let t of this.tsconfigSearchPaths){let s=P.join(t,"tsconfig.json");if(Pe.existsSync(s))try{let o=JSON.parse(Pe.readFileSync(s,"utf-8")).compilerOptions?.paths;if(!o)continue;for(let i in o){let a=this.matchAliasPattern(i,e);if(a){let p=this.tryAliasSubstitutions(o[i],a[1]||"",t);if(p)return p}}}catch{}}return null}aliasRegexCache=new Map;matchAliasPattern(e,t){let s=this.aliasRegexCache.get(e);if(!s){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace("\\*","(.*)");s=new RegExp(`^${n}$`),this.aliasRegexCache.set(e,s)}return t.match(s)}tryAliasSubstitutions(e,t,s=this.rootDir){let n=["",".ts",".tsx",".js",".jsx",".coffee",".ls",".lua",".feature"];for(let o of e){let i=o.replace("*",t),a=P.resolve(s,i);for(let p of n){let c=this.tryExtensions(a,p,!1);if(c)return c}}return null}resolveWorkspaceImport(e){if(this.workspaceMap.size===0)return null;for(let[t,s]of this.workspaceMap){if(e!==t&&!e.startsWith(`${t}/`))continue;let n=e.slice(t.length),o={path:"",isExternal:!1,isWorkspace:!0,workspacePackage:t};if(!n){for(let a of["src/index.ts","src/index.tsx","index.ts","index.tsx","index.js"]){let p=P.join(s,a);try{if(Pe.statSync(p,{throwIfNoEntry:!1})?.isFile())return{...o,path:p}}catch{}}return{...o,path:s}}let i=this.resolveLocalPath(P.join(s,"_dummy"),n.slice(1));return i?{...o,path:i.path}:null}return null}};var Pi=["tests","test","__tests__","specs","spec"];function Ii(r,e){if(r.length===0)return e;let t=r.map(i=>v.dirname(i).split(v.sep)),s=t[0];for(let i of t.slice(1)){let a=0;for(;a<s.length&&a<i.length&&s[a]===i[a];)a++;s=s.slice(0,a)}let n=s.join(v.sep)||v.sep,o=v.relative(e,n);return o.startsWith("..")||v.isAbsolute(o)?e:n}var oe=class{constructor(e,t=null,s,n,o=!1,i=new Map){this.rootDir=e;this.enableGitStats=o;this.coverageMap=i;this.previousGraph=t,this.resolver=s||new B(e),this.lockFile=yr(e),n&&(this.progressCallback=n)}rootDir;enableGitStats;coverageMap;graph={nodes:new Map};visited=new Set;previousGraph=null;resolver;lockFile=null;progressCallback;async build(e){let t=e.map(s=>v.isAbsolute(s)?s:v.resolve(this.rootDir,s));for(let s of t)await this.processFile(s);return await this.processTestFiles(Ii(t,this.rootDir)),this.progressCallback&&this.visited.size>=100&&process.stderr.write(`
24
24
  Done. Total processed: ${this.visited.size} nodes.
25
- `),Br(this.graph.nodes),zr(this.graph.nodes),$r(this.graph.nodes),this.coverageMap.size>0&&Or(this.graph.nodes,this.coverageMap),new E(this.graph.nodes)}async processTestFiles(e){let t=q(),s=new Set(["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage"]),n=async i=>{let a;try{a=Ie.readdirSync(i,{withFileTypes:!0})}catch{return}for(let p of a){let c=v.join(i,p.name);p.isDirectory()?s.has(p.name)||await n(c):p.isFile()&&t.some(u=>p.name.includes(u))&&await this.processFile(c)}};await n(e);let o=e;for(;o!==this.rootDir;){let i=v.dirname(o);if(i===o)break;for(let a of Fi){let p=v.join(i,a);try{Ie.statSync(p).isDirectory()&&await n(p)}catch{}}o=i}}async processFile(e){if(this.visited.has(e))return;this.visited.add(e),this.showProgress();let t=Ie.statSync(e,{throwIfNoEntry:!1});if(!t?.isFile())return;let s=v.relative(this.rootDir,e),n=await this.getNode(e,s,t);n.imports=await this.resolveImports(e,n.imports),this.graph.nodes.set(n.path,n)}async getNode(e,t,s){let n=this.previousGraph?.nodes.get(t);if(n&&n.mtime===s.mtimeMs&&n.size===s.size)return{...n};let o=await this.tryParse(e,t);if(!o)return this.makeStubNode(e,t,s);Wr(o.imports,o.tags);let i=this.resolveCallEdges(e,o.rawCallEdges),a=this.buildNode(e,t,s,o,i);return this.attachGitStats(a,t),a}async tryParse(e,t){let s=Ie.readFileSync(e,"utf-8");try{return await _r(e,s)}catch(n){return process.stderr.write(`
25
+ `),Ur(this.graph.nodes),$r(this.graph.nodes),Br(this.graph.nodes),this.coverageMap.size>0&&Wr(this.graph.nodes,this.coverageMap),new E(this.graph.nodes)}async processTestFiles(e){let t=q(),s=new Set(["node_modules",".git","dist","build",".next",".cache","mokosh-cache","coverage"]),n=async i=>{let a;try{a=Ie.readdirSync(i,{withFileTypes:!0})}catch{return}for(let p of a){let c=v.join(i,p.name);p.isDirectory()?s.has(p.name)||await n(c):p.isFile()&&t.some(u=>p.name.includes(u))&&await this.processFile(c)}};await n(e);let o=e;for(;o!==this.rootDir;){let i=v.dirname(o);if(i===o)break;for(let a of Pi){let p=v.join(i,a);try{Ie.statSync(p).isDirectory()&&await n(p)}catch{}}o=i}}async processFile(e){if(this.visited.has(e))return;this.visited.add(e),this.showProgress();let t=Ie.statSync(e,{throwIfNoEntry:!1});if(!t?.isFile())return;let s=v.relative(this.rootDir,e),n=await this.getNode(e,s,t);n.imports=await this.resolveImports(e,n.imports),this.graph.nodes.set(n.path,n)}async getNode(e,t,s){let n=this.previousGraph?.nodes.get(t);if(n&&n.mtime===s.mtimeMs&&n.size===s.size)return{...n};let o=await this.tryParse(e,t);if(!o)return this.makeStubNode(e,t,s);zr(o.imports,o.tags);let i=this.resolveCallEdges(e,o.rawCallEdges),a=this.buildNode(e,t,s,o,i);return this.attachGitStats(a,t),a}async tryParse(e,t){let s=Ie.readFileSync(e,"utf-8");try{return await Lr(e,s)}catch(n){return process.stderr.write(`
26
26
  Warning: failed to parse ${t}: ${n}
27
- `),null}}makeStubNode(e,t,s){return{path:t,type:A(e),category:"other",imports:[],exports:[],tags:[],mtime:s.mtimeMs,size:s.size}}resolveCallEdges(e,t){let s=[];for(let n of t??[])try{let o=this.resolver.resolve(e,n.toSpecifier);o&&!o.isExternal&&s.push({from:n.from,to:n.to,toFile:v.relative(this.rootDir,o.path)})}catch{}return s}buildNode(e,t,s,n,o){let{imports:i,exports:a,tags:p,category:c,description:u,complexity:f,cognitiveComplexity:g,functions:y}=n;return{path:t,type:A(e),category:c,imports:i,exports:a,tags:p,mtime:s.mtimeMs,size:s.size,...u!==void 0?{description:u}:{},...o.length>0?{callEdges:o}:{},...f!==void 0?{complexity:f}:{},...g!==void 0?{cognitiveComplexity:g}:{},...y!==void 0?{functions:y}:{}}}attachGitStats(e,t){if(this.enableGitStats)try{let s=gr(this.rootDir,t);e.commitCount90d=s.commitCount90d,s.lastAuthor!==void 0&&(e.lastAuthor=s.lastAuthor)}catch{}}async resolveImports(e,t){let s=[];for(let n of t){let o=this.resolver.resolveAll(e,n.rawSpecifier);if(o.length!==0)for(let i of o){let a={...n,toPath:i.isExternal?i.path:v.relative(this.rootDir,i.path),isExternal:i.isExternal};i.isWorkspace&&(a.isWorkspace=!0,a.workspacePackage=i.workspacePackage),i.isExternal?this.attachLockfileVersion(a):await this.processFile(i.path),s.push(a)}}return s}attachLockfileVersion(e){if(!this.lockFile)return;let t=e.rawSpecifier.startsWith("@")?e.rawSpecifier.split("/").slice(0,2).join("/"):e.rawSpecifier.split("/")[0],s=t?this.lockFile.dependencies[t]:void 0;s&&(e.version=s.version)}showProgress(){this.progressCallback&&this.visited.size%100===0&&this.progressCallback(this.visited.size)}};function Hr(r,e){return{identifier:e?.identifier??new Ce,featureMap:e?.featureDetection===!1?new Map:I(r.nodes,e?.featureDetection??void 0)}}function Qr(r,e,t,s,n){for(let o of e){let i=r.nodes.get(o);if(!i)continue;let a=new M(o,["*",...i.exports.map(p=>p.name)]);r.traverse(o,(p,c,u)=>{if(!u)return!0;if(!a.updateAffectedSymbols(p,u))return!1;if(c>0){let f=t.get(p.path);if(f)return s(f),!1}return n(p),!0},{direction:"incoming"})}}function yt(r,e,t){let{identifier:s,featureMap:n}=Hr(r,t),o=new Set;for(let i of e){let a=n.get(i);a&&o.add(a.tag)}return Qr(r,e,n,i=>o.add(i.tag),i=>{if(s.isTestNode(i))for(let a of i.tags)o.add(a.name)}),Array.from(o)}function xt(r,e,t){let{identifier:s,featureMap:n}=Hr(r,t),o=new Set;return Qr(r,e,n,()=>{},i=>{s.isTestNode(i)&&o.add(i.path)}),Array.from(o)}import Ti from"fs";import oe from"path";async function Vr(r,e,t=null,s={}){let n=s.silent?void 0:i=>{process.stderr.write(`Processed ${i} files...\r`)};return await new ne(oe.resolve(r),t,void 0,n,s.gitStats??!1,s.coverageMap??new Map).build(e)}async function Xr(r,e={}){let t=oe.resolve(r),s=X(t),n=e.packages?s.packages.filter(a=>e.packages?.includes(a.name)||e.packages?.includes(a.relativeRoot)):s.packages,o=new Map(s.packages.map(a=>[a.name,a.root])),i=new Z(t,s.type);for(let a of n){let p=e.silent?void 0:f=>{process.stderr.write(`[${a.name}] Processed ${f} files...\r`)},u=await new ne(t,null,new B(t,{workspaceMap:o,tsconfigSearchPaths:[a.root,t]}),p,e.gitStats??!1).build(a.entryPoints);i.addPackage(a,u)}return i}function Zr(r,e={}){let t=[],s=new Set([...e.ignoreDirs??_e,...e.additionalIgnoreDirs??[]]),n=new Set([...e.extensions??Le,...e.additionalExtensions??[]]);function o(i){try{let a=Ti.readdirSync(i,{withFileTypes:!0});for(let p of a){let c=oe.join(i,p.name);p.isDirectory()?s.has(p.name)||o(c):p.isFile()&&n.has(oe.extname(p.name).toLowerCase())&&t.push(oe.relative(r,c))}}catch{}}return o(r),t}var Pi=/(?:^|[/\\])(?:node_modules|\.git|dist|build|coverage)(?:[/\\]|$)/,Me=class{graphs=new Map;configs=new Map;workspaceGraphs=new Map;changeImpactCaches=new Map;dirtyRoots=new Set;watchers=new Map;lastAnalyze=new Map;isConfigured(e){return this.configs.has(e)}storeConfig(e,t){this.configs.set(e,t)}getConfig(e){return this.configs.get(e)}async getOrBuild(e,t,s=new Map){let n=this.configs.get(e),o=await Vr(e,t,this.graphs.get(e)??null,{gitStats:n?.gitStats??!1,coverageMap:s});return this.graphs.set(e,o),o}require(e){let t=this.graphs.get(e);if(!t)throw new Error('No graph cached for this root. Call "analyze" first.');return t}async getOrBuildWorkspace(e,t={}){let s=this.workspaceGraphs.get(e);if(s)return s;let n=await Xr(e,t);return this.workspaceGraphs.set(e,n),n}requireWorkspace(e){let t=this.workspaceGraphs.get(e);if(!t)throw new Error('No workspace graph cached for this root. Call "analyze" first.');return t}hasWorkspace(e){return this.workspaceGraphs.has(e)}getOrBuildChangeImpact(e){let t=this.changeImpactCaches.get(e);if(t)return t;let s=this.require(e),n=Ue(s);return this.changeImpactCaches.set(e,n),n}storeLastAnalyze(e,t){this.lastAnalyze.set(e,t)}startWatching(e){if(!this.watchers.has(e))try{let t=Ai.watch(e,{recursive:!0},(s,n)=>{!n||Pi.test(n)||this.dirtyRoots.add(e)});t.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,t)}catch{}}async ensureFresh(e){if(!this.dirtyRoots.has(e))return this.require(e);this.dirtyRoots.delete(e),this.changeImpactCaches.delete(e);let t=this.lastAnalyze.get(e);return t?.kind==="single"?this.getOrBuild(e,t.entryPoints,t.coverageMap):this.require(e)}async ensureFreshWorkspace(e){if(!this.dirtyRoots.has(e))return this.requireWorkspace(e);this.dirtyRoots.delete(e),this.changeImpactCaches.delete(e),this.workspaceGraphs.delete(e);let t=this.configs.get(e);return this.getOrBuildWorkspace(e,{gitStats:t?.gitStats??!1})}invalidate(e){let t=this.graphs.has(e)||this.workspaceGraphs.has(e);return this.graphs.delete(e),this.workspaceGraphs.delete(e),this.changeImpactCaches.delete(e),this.dirtyRoots.delete(e),t}};import U from"path";import Ii from"fs";import Mi from"os";import St from"path";function h(r){return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}function Yr(r){if(!St.isAbsolute(r))throw new Error("root must be an absolute path");let e=St.resolve(r),t=Mi.homedir();if(e!==t&&!e.startsWith(t+St.sep))throw new Error("root must be within the user home directory");let s;try{s=Ii.statSync(e)}catch{throw new Error("root does not exist")}if(!s.isDirectory())throw new Error("root is not a directory")}async function es(r,e){let{root:t,entryPoints:s}=e;if(!r.isConfigured(t)){let f=K(t,{allowJs:!1});je(f),r.storeConfig(t,f)}if(s.length===0){let f=X(t);if(f.type!=="none"){let g=r.getConfig(t),y=await r.getOrBuildWorkspace(t,{gitStats:g?.gitStats??!1});r.storeLastAnalyze(t,{kind:"workspace"}),r.startWatching(t);let F=Array.from(y.packages.values()).map(({graph:ie,pkg:vt})=>({package:vt.name,relativeRoot:vt.relativeRoot,nodeCount:ie.nodes.size}));return h({monorepoType:f.type,packageCount:y.packages.size,packages:F})}}let n=s.map(f=>U.resolve(t,f)),o=r.getConfig(t),i=o?.coverageReportPath?Oe(t,o.coverageReportPath):new Map,a=await r.getOrBuild(t,n,i);r.storeLastAnalyze(t,{kind:"single",entryPoints:n,coverageMap:i}),r.startWatching(t);let p=a.serialize(),c=p.nodes.reduce((f,g)=>(f[g.category]=(f[g.category]??0)+1,f),{}),u=a.findCycles();return h({nodeCount:p.nodes.length,categories:c,cycles:u})}async function ts(r,e){let{root:t,file:s,depth:n=1}=e,o=await r.ensureFresh(t),i=[];return o.traverse(s,(a,p,c)=>{if(a.path===s)return!0;let u=c?o.nodes.get(c)?.imports.find(f=>f.toPath===a.path):void 0;return i.push({path:a.path,...u?.symbols?{symbols:u.symbols}:{}}),!0},{direction:"outgoing",maxDepth:n}),h({file:s,dependencies:i})}async function rs(r,e){let{root:t,file:s}=e,n=await r.ensureFresh(t),o=[];return n.traverse(s,i=>{if(i.path===s)return!0;let a=i.imports.find(p=>p.toPath===s);return o.push({path:i.path,...a?.symbols?{symbols:a.symbols}:{}}),!0},{direction:"incoming",maxDepth:1}),h({file:s,dependents:o})}async function ss(r,e){let{root:t,file:s,testsOnly:n=!1,cached:o=!1,changedSymbols:i}=e,a=await r.ensureFresh(t);if(o){let u=r.getOrBuildChangeImpact(t),f=qe(u,s),g=n?f.filter(y=>a.nodes.get(y)?.category==="test"):f;return h({file:s,affected:g,count:g.length})}let p=i?new M(s,i):null,c=[];return a.traverse(s,(u,f,g)=>{if(u.path===s)return!0;if(p&&g&&!p.updateAffectedSymbols(u,g))return!1;let y=u.category==="test"||u.tags.some(F=>F.name==="test");return(!n||y)&&c.push(u.path),!0},{direction:"incoming"}),h({file:s,affected:c,count:c.length})}async function ns(r,e){let{root:t,file:s,depth:n=1,withEdgeDetail:o=!1}=e,i=await r.ensureFresh(t),a=[];return i.traverseCalls(s,p=>{if(p.path===s)return!0;let c={file:p.path};return o&&(c.edges=(p.callEdges??[]).filter(u=>u.toFile===s).map(u=>({from:u.from,to:u.to}))),a.push(c),!0},{direction:"incoming",maxDepth:n}),h({file:s,callers:a,count:a.length})}async function os(r,e){let{root:t,entryPoints:s}=e,n=s.map(p=>U.resolve(t,p)),o=await r.getOrBuild(t,n),i=Zr(t),a=o.findUnusedFiles(i);return h({unusedFiles:a,count:a.length})}async function is(r,e){let{root:t,coverageThreshold:s}=e,n=await r.ensureFresh(t),o=r.getConfig(t),i=s??o?.coverageThreshold??80;if(![...n.nodes.values()].some(c=>c.coveragePct!==void 0))return h({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let p=[...n.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 h({threshold:i,uncovered:p,count:p.length})}async function as(r,e){let{root:t,metric:s="cognitiveComplexity",threshold:n=10,limit:o=20}=e,a=[...(await r.ensureFresh(t)).nodes.values()].flatMap(p=>(p.functions??[]).filter(c=>c[s]>=n).map(c=>({file:p.path,name:c.name,line:c.line,complexity:c.complexity,cognitiveComplexity:c.cognitiveComplexity}))).sort((p,c)=>c[s]-p[s]).slice(0,o);return h({metric:s,threshold:n,functions:a,count:a.length})}async function ps(r,e){let{root:t,changedFiles:s,featureThreshold:n,format:o="tags"}=e,i=await r.ensureFresh(t),a=s??new Fe().getChangedFiles().map(u=>U.relative(t,U.resolve(t,u))),p=n!==void 0?{featureDetection:{minOutDegree:n}}:void 0;if(o==="paths"){let u=xt(i,a,p);return h({changedFiles:a,affectedTests:u,count:u.length})}let c=yt(i,a,p);return h({changedFiles:a,proposedTags:c})}async function cs(r,e){let{root:t,entryPoints:s,featureThreshold:n}=e,o=s?await r.getOrBuild(t,s.map(p=>U.resolve(t,p))):await r.ensureFresh(t),i=I(o.nodes,n!==void 0?{minOutDegree:n}:void 0),a=Array.from(i.values()).sort((p,c)=>c.outDegree-p.outDegree);return h({features:a,count:a.length})}async function ls(r,e){let{root:t,entryPoints:s,filter:n,mermaid:o=!1,slim:i=!0}=e,a=s?await r.getOrBuild(t,s.map(c=>U.resolve(t,c))):await r.ensureFresh(t),p=me(a.serialize(),de(n));if(o)return h(ue.serialize(E.deserialize(p)));if(i){let c=p.nodes.map(u=>({path:u.path,type:u.type,category:u.category,exports:u.exports.map(f=>f.name),tags:u.tags.filter(f=>f.kind==="comment-marker"||f.kind==="import").map(f=>f.name),importsFiles:u.imports.filter(f=>!f.isExternal&&f.toPath).map(f=>f.toPath),...u.description!==void 0&&{description:u.description},...u.testedBy!==void 0&&{testedBy:u.testedBy},...u.coveragePct!==void 0&&{coveragePct:u.coveragePct},...u.avgExportUsage!==void 0&&{avgExportUsage:u.avgExportUsage},...u.maxExportUsage!==void 0&&{maxExportUsage:u.maxExportUsage}}));return h({nodes:c,cycles:p.cycles})}return h(p)}async function us(r,e){let{root:t}=e,s=await r.ensureFreshWorkspace(t),n=s.getPackageDependencies(),o=Array.from(s.packages.values()).map(({graph:i,pkg:a})=>({name:a.name,relativeRoot:a.relativeRoot,nodeCount:i.nodes.size,dependsOn:n.get(a.name)??[]}));return h({monorepoType:s.type,packageCount:o.length,packages:o})}async function fs(r,e){let{root:t,file:s}=e,o=(await r.ensureFreshWorkspace(t)).getAffectedAcrossPackages(s);return h({file:s,affected:o,count:o.length})}function gs(r,e){let{root:t}=e,s=r.invalidate(t);return h({root:t,cleared:s,message:s?"Cache cleared. Call analyze to rebuild.":"No cache was present for this root."})}async function ms(r,e){let{root:t,type:s}=e,n=await r.ensureFresh(t),o=Je(n);if(s)return h(He(o,s));let i=Array.from(o.types.values());return h({count:i.length,types:i})}async function ds(r,e){let{root:t,paths:s,minOutDegree:n}=e,o=await r.ensureFresh(t),i=Ke(o,n!==void 0?{minOutDegree:n}:void 0);if(s?.length){let p=s.map(c=>i.get(c)).filter(Boolean);return h({count:p.length,modules:p})}let a=Array.from(i.values());return h({count:a.length,modules:a})}async function hs(r,e){let{root:t,minOutDegree:s}=e,n=await r.ensureFresh(t),o=J(n,s!==void 0?{minOutDegree:s}:void 0),i=Object.fromEntries(o.features);return h({features:i,unassigned:o.unassigned})}async function ys(r,e){let{root:t,function:s}=e,n=await r.ensureFresh(t);return h(Be(n,s))}async function xs(r,e){let{root:t,entryPoints:s}=e,n=await r.ensureFresh(t),o=s?.length?s:ze(n,t);if(o.length===0)throw new Error("No entry points found. Pass entryPoints explicitly or ensure package.json has a main/exports field.");return h($e(n,o))}async function Ss(r,e){let t=await r.ensureFresh(e.root),s=await ot(t,e.root,{dryRun:e.dryRun??!1});return h(s)}var bs=[{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)"}},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"}},required:["root","file"]}},{name:"get_affected",description:"Get all files transitively affected if a given file changes \u2014 full incoming traversal upward. Use before a refactor to understand blast radius. Set testsOnly=true to get only test files. Set cached=true to use a pre-computed O(1) lookup cache instead of graph traversal \u2014 faster on repeated calls for the same root. Pass changedSymbols to restrict blast-radius to files that actually import those symbols \u2014 omit to treat the whole file as changed.",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)."}},required:["root","file"]}},{name:"get_callers",description:"Get files whose exported functions call into a given file (call-graph dependents). More precise than get_affected: only files with actual runtime call edges, not mere imports. Requires prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to project root"},file:{type:"string",description:"File path relative to root"},depth:{type:"number",description:"Max traversal depth (default: 1)"},withEdgeDetail:{type:"boolean",description:"Include from/to function names per edge (default: false)"}},required:["root","file"]}},{name:"find_unused",description:"Find files in the project that are not reachable from any entry point. Useful before cleanup passes.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"}}},required:["root","entryPoints"]}},{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:"find_complex_functions",description:"Find individual functions/methods above a cognitive (or cyclomatic) complexity threshold, sorted worst-first. Requires a prior analyze() call. TypeScript/JavaScript only.",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:"propose_tags",description:"Propose what to run based on changed files. Pass changedFiles explicitly or omit to use git diff. format='tags' (default) returns test tags for CI tag-filtering; format='paths' returns test file paths ready to pipe directly to a test runner (e.g. vitest). Feature hubs act as traversal boundaries in both modes.",inputSchema:{type:"object",properties:{root:{type:"string"},changedFiles:{type:"array",items:{type:"string"},description:"Changed files relative to root. Omit to read from git diff."},featureThreshold:{type:"number",description:"Min importers for a file to be treated as a feature hub (default: 5). A hub short-circuits traversal and emits a feature:<name> tag instead of all downstream tags."},format:{type:"string",enum:["tags","paths"],description:"Output format: 'tags' returns test tag names for CI filtering (default); 'paths' returns test file paths to pipe to a test runner."}},required:["root"]}},{name:"detect_features",description:"Identify feature hub files \u2014 non-test files that import many other internal modules (orchestrators / aggregators like src/parser.ts or src/cli/runner.ts). Returns a list sorted by import count descending.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root. Omit to use the cached graph."},featureThreshold:{type:"number",description:"Min internal imports a file must have to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"query",description:"Filter the graph by category, tag, or path. Returns matching nodes as JSON or a Mermaid diagram. If entryPoints is omitted the cached graph from a prior 'analyze' call is used.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry points to build the graph. Omit to reuse the cached graph from a prior 'analyze' call."},filter:{type:"string",description:"Query string e.g. 'category:logic' or 'category:logic,tag:auth'. Supports: category, type, tag, path, external, importsFile, importedBy, minImports, maxImports, minSize, maxSize, hasDocstring, minCoverage, maxCoverage, minExportUsage, maxExportUsage. sort: size|imports|commitCount90d|exportUsage. 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. Pass false only when full edge metadata is needed."}},required:["root","filter"]}},{name:"get_workspace_packages",description:"List all workspace packages detected in a monorepo, with their node counts and inter-package dependencies. Requires a prior analyze() call with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"}},required:["root"]}},{name:"get_workspace_affected",description:"Cross-package blast-radius analysis. Returns every file that could be affected if a given file changes, annotated with the package it belongs to. Requires a prior analyze() call with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"},file:{type:"string",description:"Monorepo-root-relative path of the changed file (e.g. 'packages/shared/src/utils.ts')"}},required:["root","file"]}},{name:"get_type_graph",description:"Return type-level relationships for the project. Without a type name, returns an inventory of all interfaces, classes, enums, and type aliases with their file and kind. With a type name, returns which files import that type (usedByFiles) and which types the defining file imports (uses). Requires a prior analyze() call. Only covers TypeScript/JavaScript files.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},type:{type:"string",description:"Exact exported name of the type to look up (e.g. 'FileNode'). Omit to get the full type inventory."}},required:["root"]}},{name:"get_module_responsibility",description:"Return what each file is responsible for: its semantic role, JSDoc description (when present), exported symbol names, and which feature hub it belongs to. Pass specific paths to filter, or omit paths to get all files. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},paths:{type:"array",items:{type:"string"},description:"Project-relative file paths to include. Omit to return all files."},minOutDegree:{type:"number",description:"Min imports for a file to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"get_feature_graph",description:"Group files by domain: returns which files each feature hub (high-import orchestrator) transitively owns. Each file is assigned to the most specific hub that can reach it (lowest out-degree wins). Use this instead of a full query when answering 'what files are in the X feature/module?' \u2014 typically 85\u201395% fewer tokens than a full graph query.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},minOutDegree:{type:"number",description:"Minimum internal imports a file must have to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"get_call_graph",description:"Look up callers and callees for a named function. Returns the file that defines the function, all files/functions that call it, and all files/functions it calls. Always requires a function name \u2014 never returns the full call graph unfiltered. Call edges are only populated for TypeScript/JavaScript files.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},function:{type:"string",description:"Exact name of the function to look up (e.g. 'parseFile')."}},required:["root","function"]}},{name:"get_api_surface",description:"Build the API surface report for a project. Expands export* chains so every symbol accessible to consumers is listed (not just those directly declared in the entry file). Each export is resolved to its defining file and tagged with a kind (function/class/interface/type/enum/const). The graph is partitioned into: internalFiles (implementation reachable from entry points), unreachableFromEntry (non-test files not reachable from any entry point \u2014 may be separate consumers like CLI/MCP, config, or dead code), and testFiles (test suite). Supports multiple public entry points for libraries with sub-path exports. Requires a prior analyze() call. When entryPoints is omitted, auto-detects all entry points from package.json exports/main/module.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},entryPoints:{type:"array",items:{type:"string"},description:"Project-relative paths of public entry points (e.g. ['src/index.ts', 'src/utils.ts']). Omit to auto-detect from package.json exports / main / module fields."}},required:["root"]}},{name:"clear_cache",description:"Drop the cached dependency graph for a project root, forcing the next analyze() call to rebuild from disk. Call this after editing source files mid-session \u2014 otherwise get_affected, get_dependencies, and other query tools will reason from stale data.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root to invalidate."}},required:["root"]}},{name:"apply_tags",description:"Write @tag annotations into test file source code based on the dependency graph. Tags of kind 'import' (filename-derived) and 'comment-marker' (domain semantic, propagated from source files) are written as an idempotent block. Re-running is safe: the existing block is replaced in place. Tags already present in the file are excluded from the block to avoid duplication. Supports TypeScript/JavaScript (// <mokosh-tags> block with // @tag lines) and Gherkin .feature files (# <mokosh-tags> block with @tagname lines). Use dryRun=true to preview changes without writing to disk. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root."},dryRun:{type:"boolean",description:"When true, computes which files would change but does not write to disk (default: false)."}},required:["root"]}}];function bt(){let r=new Me,e=new Ri({name:"mokosh",version:"0.0.1"},{capabilities:{tools:{}}});return e.setRequestHandler(Gi,async()=>({tools:bs})),e.setRequestHandler(Ni,async t=>{let{name:s,arguments:n}=t.params,o=n,a={analyze:p=>es(r,p),get_dependencies:p=>ts(r,p),get_dependents:p=>rs(r,p),get_affected:p=>ss(r,p),get_callers:p=>ns(r,p),find_unused:p=>os(r,p),find_uncovered:p=>is(r,p),find_complex_functions:p=>as(r,p),propose_tags:p=>ps(r,p),detect_features:p=>cs(r,p),get_type_graph:p=>ms(r,p),get_module_responsibility:p=>ds(r,p),get_feature_graph:p=>hs(r,p),get_call_graph:p=>ys(r,p),get_api_surface:p=>xs(r,p),query:p=>ls(r,p),get_workspace_packages:p=>us(r,p),get_workspace_affected:p=>fs(r,p),clear_cache:p=>gs(r,p),apply_tags:p=>Ss(r,p)}[s];if(!a)throw new Error(`Unknown tool: ${s}`);try{return Yr(o.root),await a(o)}catch(p){return{content:[{type:"text",text:`Error: ${p instanceof Error?p.message:String(p)}`}],isError:!0}}}),e}async function ji(){let r=bt(),e=new Di;await r.connect(e)}ji().catch(console.error);export{bt as createMcpServer};
27
+ `),null}}makeStubNode(e,t,s){return{path:t,type:A(e),category:"other",imports:[],exports:[],tags:[],mtime:s.mtimeMs,size:s.size}}resolveCallEdges(e,t){let s=[];for(let n of t??[])try{let o=this.resolver.resolve(e,n.toSpecifier);o&&!o.isExternal&&s.push({from:n.from,to:n.to,toFile:v.relative(this.rootDir,o.path)})}catch{}return s}buildNode(e,t,s,n,o){let{imports:i,exports:a,tags:p,category:c,description:u,complexity:f,cognitiveComplexity:g,functions:y}=n;return{path:t,type:A(e),category:c,imports:i,exports:a,tags:p,mtime:s.mtimeMs,size:s.size,...u!==void 0?{description:u}:{},...o.length>0?{callEdges:o}:{},...f!==void 0?{complexity:f}:{},...g!==void 0?{cognitiveComplexity:g}:{},...y!==void 0?{functions:y}:{}}}attachGitStats(e,t){if(this.enableGitStats)try{let s=mr(this.rootDir,t);e.commitCount90d=s.commitCount90d,s.lastAuthor!==void 0&&(e.lastAuthor=s.lastAuthor)}catch{}}async resolveImports(e,t){let s=[];for(let n of t){let o=this.resolver.resolveAll(e,n.rawSpecifier);if(o.length!==0)for(let i of o){let a={...n,toPath:i.isExternal?i.path:v.relative(this.rootDir,i.path),isExternal:i.isExternal};i.isWorkspace&&(a.isWorkspace=!0,a.workspacePackage=i.workspacePackage),i.isExternal?this.attachLockfileVersion(a):await this.processFile(i.path),s.push(a)}}return s}attachLockfileVersion(e){if(!this.lockFile)return;let t=e.rawSpecifier.startsWith("@")?e.rawSpecifier.split("/").slice(0,2).join("/"):e.rawSpecifier.split("/")[0],s=t?this.lockFile.dependencies[t]:void 0;s&&(e.version=s.version)}showProgress(){this.progressCallback&&this.visited.size%100===0&&this.progressCallback(this.visited.size)}};function Vr(r,e){return{identifier:e?.identifier??new Ce,featureMap:e?.featureDetection===!1?new Map:I(r.nodes,e?.featureDetection??void 0)}}function Xr(r,e,t,s,n){for(let o of e){let i=r.nodes.get(o);if(!i)continue;let a=new M(o,["*",...i.exports.map(p=>p.name)]);r.traverse(o,(p,c,u)=>{if(!u)return!0;if(!a.updateAffectedSymbols(p,u))return!1;if(c>0){let f=t.get(p.path);if(f)return s(f),!1}return n(p),!0},{direction:"incoming"})}}function xt(r,e,t){let{identifier:s,featureMap:n}=Vr(r,t),o=new Set;for(let i of e){let a=n.get(i);a&&o.add(a.tag)}return Xr(r,e,n,i=>o.add(i.tag),i=>{if(s.isTestNode(i))for(let a of i.tags)o.add(a.name)}),Array.from(o)}function St(r,e,t){let{identifier:s,featureMap:n}=Vr(r,t),o=new Set;return Xr(r,e,n,()=>{},i=>{s.isTestNode(i)&&o.add(i.path)}),Array.from(o)}import Mi from"fs";import ie from"path";async function Zr(r,e,t=null,s={}){let n=s.silent?void 0:i=>{process.stderr.write(`Processed ${i} files...\r`)};return await new oe(ie.resolve(r),t,void 0,n,s.gitStats??!1,s.coverageMap??new Map).build(e)}async function Yr(r,e={}){let t=ie.resolve(r),s=X(t),n=e.packages?s.packages.filter(a=>e.packages?.includes(a.name)||e.packages?.includes(a.relativeRoot)):s.packages,o=new Map(s.packages.map(a=>[a.name,a.root])),i=new Z(t,s.type);for(let a of n){let p=e.silent?void 0:f=>{process.stderr.write(`[${a.name}] Processed ${f} files...\r`)},u=await new oe(t,null,new B(t,{workspaceMap:o,tsconfigSearchPaths:[a.root,t]}),p,e.gitStats??!1).build(a.entryPoints);i.addPackage(a,u)}return i}function es(r,e={}){let t=[],s=new Set([...e.ignoreDirs??Le,...e.additionalIgnoreDirs??[]]),n=new Set([...e.extensions??Oe,...e.additionalExtensions??[]]);function o(i){try{let a=Mi.readdirSync(i,{withFileTypes:!0});for(let p of a){let c=ie.join(i,p.name);p.isDirectory()?s.has(p.name)||o(c):p.isFile()&&n.has(ie.extname(p.name).toLowerCase())&&t.push(ie.relative(r,c))}}catch{}}return o(r),t}var Ni=/(?:^|[/\\])(?:node_modules|\.git|dist|build|coverage)(?:[/\\]|$)/,Me=class{graphs=new Map;configs=new Map;workspaceGraphs=new Map;changeImpactCaches=new Map;dirtyRoots=new Set;watchers=new Map;lastAnalyze=new Map;isConfigured(e){return this.configs.has(e)}storeConfig(e,t){this.configs.set(e,t)}getConfig(e){return this.configs.get(e)}async getOrBuild(e,t,s=new Map){let n=this.configs.get(e),o=await Zr(e,t,this.graphs.get(e)??null,{gitStats:n?.gitStats??!1,coverageMap:s});return this.graphs.set(e,o),o}require(e){let t=this.graphs.get(e);if(!t)throw new Error('No graph cached for this root. Call "analyze" first.');return t}async getOrBuildWorkspace(e,t={}){let s=this.workspaceGraphs.get(e);if(s)return s;let n=await Yr(e,t);return this.workspaceGraphs.set(e,n),n}requireWorkspace(e){let t=this.workspaceGraphs.get(e);if(!t)throw new Error('No workspace graph cached for this root. Call "analyze" first.');return t}hasWorkspace(e){return this.workspaceGraphs.has(e)}getOrBuildChangeImpact(e){let t=this.changeImpactCaches.get(e);if(t)return t;let s=this.require(e),n=qe(s);return this.changeImpactCaches.set(e,n),n}storeLastAnalyze(e,t){this.lastAnalyze.set(e,t)}startWatching(e){if(!this.watchers.has(e))try{let t=Ri.watch(e,{recursive:!0},(s,n)=>{!n||Ni.test(n)||this.dirtyRoots.add(e)});t.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,t)}catch{}}async ensureFresh(e){if(!this.dirtyRoots.has(e))return this.require(e);this.dirtyRoots.delete(e),this.changeImpactCaches.delete(e);let t=this.lastAnalyze.get(e);return t?.kind==="single"?this.getOrBuild(e,t.entryPoints,t.coverageMap):this.require(e)}async ensureFreshWorkspace(e){if(!this.dirtyRoots.has(e))return this.requireWorkspace(e);this.dirtyRoots.delete(e),this.changeImpactCaches.delete(e),this.workspaceGraphs.delete(e);let t=this.configs.get(e);return this.getOrBuildWorkspace(e,{gitStats:t?.gitStats??!1})}invalidate(e){let t=this.graphs.has(e)||this.workspaceGraphs.has(e);return this.graphs.delete(e),this.workspaceGraphs.delete(e),this.changeImpactCaches.delete(e),this.dirtyRoots.delete(e),t}};import U from"path";import Gi from"fs";import Di from"os";import bt from"path";function h(r){return{content:[{type:"text",text:JSON.stringify(r,null,2)}]}}function ts(r){if(!bt.isAbsolute(r))throw new Error("root must be an absolute path");let e=bt.resolve(r),t=Di.homedir();if(e!==t&&!e.startsWith(t+bt.sep))throw new Error("root must be within the user home directory");let s;try{s=Gi.statSync(e)}catch{throw new Error("root does not exist")}if(!s.isDirectory())throw new Error("root is not a directory")}async function rs(r,e){let{root:t,entryPoints:s}=e;if(!r.isConfigured(t)){let f=K(t,{allowJs:!1});je(f),r.storeConfig(t,f)}if(s.length===0){let f=X(t);if(f.type!=="none"){let g=r.getConfig(t),y=await r.getOrBuildWorkspace(t,{gitStats:g?.gitStats??!1});r.storeLastAnalyze(t,{kind:"workspace"}),r.startWatching(t);let F=Array.from(y.packages.values()).map(({graph:ae,pkg:kt})=>({package:kt.name,relativeRoot:kt.relativeRoot,nodeCount:ae.nodes.size}));return h({monorepoType:f.type,packageCount:y.packages.size,packages:F})}}let n=s.map(f=>U.resolve(t,f)),o=r.getConfig(t),i=o?.coverageReportPath?We(t,o.coverageReportPath):new Map,a=await r.getOrBuild(t,n,i);r.storeLastAnalyze(t,{kind:"single",entryPoints:n,coverageMap:i}),r.startWatching(t);let p=a.serialize(),c=p.nodes.reduce((f,g)=>(f[g.category]=(f[g.category]??0)+1,f),{}),u=a.findCycles();return h({nodeCount:p.nodes.length,categories:c,cycles:u})}async function ss(r,e){let{root:t,file:s,depth:n=1}=e,o=await r.ensureFresh(t),i=[];return o.traverse(s,(a,p,c)=>{if(a.path===s)return!0;let u=c?o.nodes.get(c)?.imports.find(f=>f.toPath===a.path):void 0;return i.push({path:a.path,...u?.symbols?{symbols:u.symbols}:{}}),!0},{direction:"outgoing",maxDepth:n}),h({file:s,dependencies:i})}async function ns(r,e){let{root:t,file:s}=e,n=await r.ensureFresh(t),o=[];return n.traverse(s,i=>{if(i.path===s)return!0;let a=i.imports.find(p=>p.toPath===s);return o.push({path:i.path,...a?.symbols?{symbols:a.symbols}:{}}),!0},{direction:"incoming",maxDepth:1}),h({file:s,dependents:o})}async function os(r,e){let{root:t,file:s,testsOnly:n=!1,cached:o=!1,changedSymbols:i}=e,a=await r.ensureFresh(t);if(o){let u=r.getOrBuildChangeImpact(t),f=Ke(u,s),g=n?f.filter(y=>a.nodes.get(y)?.category==="test"):f;return h({file:s,affected:g,count:g.length})}let p=i?new M(s,i):null,c=[];return a.traverse(s,(u,f,g)=>{if(u.path===s)return!0;if(p&&g&&!p.updateAffectedSymbols(u,g))return!1;let y=u.category==="test"||u.tags.some(F=>F.name==="test");return(!n||y)&&c.push(u.path),!0},{direction:"incoming"}),h({file:s,affected:c,count:c.length})}async function is(r,e){let{root:t,file:s,depth:n=1,withEdgeDetail:o=!1}=e,i=await r.ensureFresh(t),a=[];return i.traverseCalls(s,p=>{if(p.path===s)return!0;let c={file:p.path};return o&&(c.edges=(p.callEdges??[]).filter(u=>u.toFile===s).map(u=>({from:u.from,to:u.to}))),a.push(c),!0},{direction:"incoming",maxDepth:n}),h({file:s,callers:a,count:a.length})}async function as(r,e){let{root:t,entryPoints:s}=e,n=s.map(p=>U.resolve(t,p)),o=await r.getOrBuild(t,n),i=es(t),a=o.findUnusedFiles(i);return h({unusedFiles:a,count:a.length})}async function ps(r,e){let{root:t,coverageThreshold:s}=e,n=await r.ensureFresh(t),o=r.getConfig(t),i=s??o?.coverageThreshold??80;if(![...n.nodes.values()].some(c=>c.coveragePct!==void 0))return h({error:"No coverage data available. Set coverageReportPath in mokosh.config and call analyze again."});let p=[...n.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 h({threshold:i,uncovered:p,count:p.length})}async function cs(r,e){let{root:t,metric:s="cognitiveComplexity",threshold:n=10,limit:o=20}=e,a=[...(await r.ensureFresh(t)).nodes.values()].flatMap(p=>(p.functions??[]).filter(c=>c[s]>=n).map(c=>({file:p.path,name:c.name,line:c.line,complexity:c.complexity,cognitiveComplexity:c.cognitiveComplexity}))).sort((p,c)=>c[s]-p[s]).slice(0,o);return h({metric:s,threshold:n,functions:a,count:a.length})}async function ls(r,e){let{root:t,changedFiles:s,featureThreshold:n,format:o="tags"}=e,i=await r.ensureFresh(t),a=s??new Fe().getChangedFiles().map(u=>U.relative(t,U.resolve(t,u))),p=n!==void 0?{featureDetection:{minOutDegree:n}}:void 0;if(o==="paths"){let u=St(i,a,p);return h({changedFiles:a,affectedTests:u,count:u.length})}let c=xt(i,a,p);return h({changedFiles:a,proposedTags:c})}async function us(r,e){let{root:t,entryPoints:s,featureThreshold:n}=e,o=s?await r.getOrBuild(t,s.map(p=>U.resolve(t,p))):await r.ensureFresh(t),i=I(o.nodes,n!==void 0?{minOutDegree:n}:void 0),a=Array.from(i.values()).sort((p,c)=>c.outDegree-p.outDegree);return h({features:a,count:a.length})}async function fs(r,e){let{root:t,entryPoints:s,filter:n,mermaid:o=!1,slim:i=!0}=e,a=s?await r.getOrBuild(t,s.map(c=>U.resolve(t,c))):await r.ensureFresh(t),p=me(a.serialize(),de(n));if(o)return h(ue.serialize(E.deserialize(p)));if(i){let c=p.nodes.map(u=>({path:u.path,type:u.type,category:u.category,exports:u.exports.map(f=>f.name),tags:u.tags.filter(f=>f.kind==="comment-marker"||f.kind==="import").map(f=>f.name),importsFiles:u.imports.filter(f=>!f.isExternal&&f.toPath).map(f=>f.toPath),...u.description!==void 0&&{description:u.description},...u.testedBy!==void 0&&{testedBy:u.testedBy},...u.coveragePct!==void 0&&{coveragePct:u.coveragePct},...u.avgExportUsage!==void 0&&{avgExportUsage:u.avgExportUsage},...u.maxExportUsage!==void 0&&{maxExportUsage:u.maxExportUsage}}));return h({nodes:c,cycles:p.cycles})}return h(p)}async function gs(r,e){let{root:t}=e,s=await r.ensureFreshWorkspace(t),n=s.getPackageDependencies(),o=Array.from(s.packages.values()).map(({graph:i,pkg:a})=>({name:a.name,relativeRoot:a.relativeRoot,nodeCount:i.nodes.size,dependsOn:n.get(a.name)??[]}));return h({monorepoType:s.type,packageCount:o.length,packages:o})}async function ms(r,e){let{root:t,file:s}=e,o=(await r.ensureFreshWorkspace(t)).getAffectedAcrossPackages(s);return h({file:s,affected:o,count:o.length})}function ds(r,e){let{root:t}=e,s=r.invalidate(t);return h({root:t,cleared:s,message:s?"Cache cleared. Call analyze to rebuild.":"No cache was present for this root."})}async function hs(r,e){let{root:t,type:s}=e,n=await r.ensureFresh(t),o=He(n);if(s)return h(Qe(o,s));let i=Array.from(o.types.values());return h({count:i.length,types:i})}async function ys(r,e){let{root:t,paths:s,minOutDegree:n}=e,o=await r.ensureFresh(t),i=Je(o,n!==void 0?{minOutDegree:n}:void 0);if(s?.length){let p=s.map(c=>i.get(c)).filter(Boolean);return h({count:p.length,modules:p})}let a=Array.from(i.values());return h({count:a.length,modules:a})}async function xs(r,e){let{root:t,minOutDegree:s}=e,n=await r.ensureFresh(t),o=J(n,s!==void 0?{minOutDegree:s}:void 0),i=Object.fromEntries(o.features);return h({features:i,unassigned:o.unassigned})}async function Ss(r,e){let{root:t,function:s}=e,n=await r.ensureFresh(t);return h(Ue(n,s))}async function bs(r,e){let{root:t,entryPoints:s}=e,n=await r.ensureFresh(t),o=s?.length?s:$e(n,t);if(o.length===0)throw new Error("No entry points found. Pass entryPoints explicitly or ensure package.json has a main/exports field.");return h(Be(n,o))}async function vs(r,e){let t=await r.ensureFresh(e.root),s=await it(t,e.root,{dryRun:e.dryRun??!1});return h(s)}var ks=[{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)"}},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"}},required:["root","file"]}},{name:"get_affected",description:"Get all files transitively affected if a given file changes \u2014 full incoming traversal upward. Use before a refactor to understand blast radius. Set testsOnly=true to get only test files. Set cached=true to use a pre-computed O(1) lookup cache instead of graph traversal \u2014 faster on repeated calls for the same root. Pass changedSymbols to restrict blast-radius to files that actually import those symbols \u2014 omit to treat the whole file as changed.",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)."}},required:["root","file"]}},{name:"get_callers",description:"Get files whose exported functions call into a given file (call-graph dependents). More precise than get_affected: only files with actual runtime call edges, not mere imports. Requires prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to project root"},file:{type:"string",description:"File path relative to root"},depth:{type:"number",description:"Max traversal depth (default: 1)"},withEdgeDetail:{type:"boolean",description:"Include from/to function names per edge (default: false)"}},required:["root","file"]}},{name:"find_unused",description:"Find files in the project that are not reachable from any entry point. Useful before cleanup passes.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"}}},required:["root","entryPoints"]}},{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:"find_complex_functions",description:"Find individual functions/methods above a cognitive (or cyclomatic) complexity threshold, sorted worst-first. Requires a prior analyze() call. TypeScript/JavaScript only.",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:"propose_tags",description:"Propose what to run based on changed files. Pass changedFiles explicitly or omit to use git diff. format='tags' (default) returns test tags for CI tag-filtering; format='paths' returns test file paths ready to pipe directly to a test runner (e.g. vitest). Feature hubs act as traversal boundaries in both modes.",inputSchema:{type:"object",properties:{root:{type:"string"},changedFiles:{type:"array",items:{type:"string"},description:"Changed files relative to root. Omit to read from git diff."},featureThreshold:{type:"number",description:"Min importers for a file to be treated as a feature hub (default: 5). A hub short-circuits traversal and emits a feature:<name> tag instead of all downstream tags."},format:{type:"string",enum:["tags","paths"],description:"Output format: 'tags' returns test tag names for CI filtering (default); 'paths' returns test file paths to pipe to a test runner."}},required:["root"]}},{name:"detect_features",description:"Identify feature hub files \u2014 non-test files that import many other internal modules (orchestrators / aggregators like src/parser.ts or src/cli/runner.ts). Returns a list sorted by import count descending.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry point files relative to root. Omit to use the cached graph."},featureThreshold:{type:"number",description:"Min internal imports a file must have to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"query",description:"Filter the graph by category, tag, or path. Returns matching nodes as JSON or a Mermaid diagram. If entryPoints is omitted the cached graph from a prior 'analyze' call is used.",inputSchema:{type:"object",properties:{root:{type:"string"},entryPoints:{type:"array",items:{type:"string"},description:"Entry points to build the graph. Omit to reuse the cached graph from a prior 'analyze' call."},filter:{type:"string",description:"Query string e.g. 'category:logic' or 'category:logic,tag:auth'. Supports: category, type, tag, path, external, importsFile, importedBy, minImports, maxImports, minSize, maxSize, hasDocstring, minCoverage, maxCoverage, minExportUsage, maxExportUsage. sort: size|imports|commitCount90d|exportUsage. 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. Pass false only when full edge metadata is needed."}},required:["root","filter"]}},{name:"get_workspace_packages",description:"List all workspace packages detected in a monorepo, with their node counts and inter-package dependencies. Requires a prior analyze() call with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"}},required:["root"]}},{name:"get_workspace_affected",description:"Cross-package blast-radius analysis. Returns every file that could be affected if a given file changes, annotated with the package it belongs to. Requires a prior analyze() call with empty entryPoints on a monorepo root.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the monorepo root"},file:{type:"string",description:"Monorepo-root-relative path of the changed file (e.g. 'packages/shared/src/utils.ts')"}},required:["root","file"]}},{name:"get_type_graph",description:"Return type-level relationships for the project. Without a type name, returns an inventory of all interfaces, classes, enums, and type aliases with their file and kind. With a type name, returns which files import that type (usedByFiles) and which types the defining file imports (uses). Requires a prior analyze() call. Only covers TypeScript/JavaScript files.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},type:{type:"string",description:"Exact exported name of the type to look up (e.g. 'FileNode'). Omit to get the full type inventory."}},required:["root"]}},{name:"get_module_responsibility",description:"Return what each file is responsible for: its semantic role, JSDoc description (when present), exported symbol names, and which feature hub it belongs to. Pass specific paths to filter, or omit paths to get all files. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},paths:{type:"array",items:{type:"string"},description:"Project-relative file paths to include. Omit to return all files."},minOutDegree:{type:"number",description:"Min imports for a file to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"get_feature_graph",description:"Group files by domain: returns which files each feature hub (high-import orchestrator) transitively owns. Each file is assigned to the most specific hub that can reach it (lowest out-degree wins). Use this instead of a full query when answering 'what files are in the X feature/module?' \u2014 typically 85\u201395% fewer tokens than a full graph query.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},minOutDegree:{type:"number",description:"Minimum internal imports a file must have to qualify as a feature hub (default: 5)."}},required:["root"]}},{name:"get_call_graph",description:"Look up callers and callees for a named function. Returns the file that defines the function, all files/functions that call it, and all files/functions it calls. Always requires a function name \u2014 never returns the full call graph unfiltered. Call edges are only populated for TypeScript/JavaScript files.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},function:{type:"string",description:"Exact name of the function to look up (e.g. 'parseFile')."}},required:["root","function"]}},{name:"get_api_surface",description:"Build the API surface report for a project. Expands export* chains so every symbol accessible to consumers is listed (not just those directly declared in the entry file). Each export is resolved to its defining file and tagged with a kind (function/class/interface/type/enum/const). The graph is partitioned into: internalFiles (implementation reachable from entry points), unreachableFromEntry (non-test files not reachable from any entry point \u2014 may be separate consumers like CLI/MCP, config, or dead code), and testFiles (test suite). Supports multiple public entry points for libraries with sub-path exports. Requires a prior analyze() call. When entryPoints is omitted, auto-detects all entry points from package.json exports/main/module.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root"},entryPoints:{type:"array",items:{type:"string"},description:"Project-relative paths of public entry points (e.g. ['src/index.ts', 'src/utils.ts']). Omit to auto-detect from package.json exports / main / module fields."}},required:["root"]}},{name:"clear_cache",description:"Drop the cached dependency graph for a project root, forcing the next analyze() call to rebuild from disk. Call this after editing source files mid-session \u2014 otherwise get_affected, get_dependencies, and other query tools will reason from stale data.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root to invalidate."}},required:["root"]}},{name:"apply_tags",description:"Write @tag annotations into test file source code based on the dependency graph. Tags of kind 'import' (filename-derived) and 'comment-marker' (domain semantic, propagated from source files) are written as an idempotent block. Re-running is safe: the existing block is replaced in place. Tags already present in the file are excluded from the block to avoid duplication. Supports TypeScript/JavaScript (// <mokosh-tags> block with // @tag lines) and Gherkin .feature files (# <mokosh-tags> block with @tagname lines). Use dryRun=true to preview changes without writing to disk. Requires a prior analyze() call.",inputSchema:{type:"object",properties:{root:{type:"string",description:"Absolute path to the project root."},dryRun:{type:"boolean",description:"When true, computes which files would change but does not write to disk (default: false)."}},required:["root"]}}];function vt(){let r=new Me,e=new _i({name:"mokosh",version:"0.0.1"},{capabilities:{tools:{}}});return e.setRequestHandler(Li,async()=>({tools:ks})),e.setRequestHandler(ji,async t=>{let{name:s,arguments:n}=t.params,o=n,a={analyze:p=>rs(r,p),get_dependencies:p=>ss(r,p),get_dependents:p=>ns(r,p),get_affected:p=>os(r,p),get_callers:p=>is(r,p),find_unused:p=>as(r,p),find_uncovered:p=>ps(r,p),find_complex_functions:p=>cs(r,p),propose_tags:p=>ls(r,p),detect_features:p=>us(r,p),get_type_graph:p=>hs(r,p),get_module_responsibility:p=>ys(r,p),get_feature_graph:p=>xs(r,p),get_call_graph:p=>Ss(r,p),get_api_surface:p=>bs(r,p),query:p=>fs(r,p),get_workspace_packages:p=>gs(r,p),get_workspace_affected:p=>ms(r,p),clear_cache:p=>ds(r,p),apply_tags:p=>vs(r,p)}[s];if(!a)throw new Error(`Unknown tool: ${s}`);try{return ts(o.root),await a(o)}catch(p){return{content:[{type:"text",text:`Error: ${p instanceof Error?p.message:String(p)}`}],isError:!0}}}),e}async function Wi(){let r=vt(),e=new Oi;await r.connect(e)}Wi().catch(console.error);export{vt as createMcpServer};
28
28
  //# sourceMappingURL=mcp.mjs.map