canopy-engine 0.1.5 → 0.1.7
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/LICENSE +3 -2
- package/PRIVACY.md +72 -0
- package/README.md +241 -231
- package/dist/canopy.js +92 -82
- package/dist/{chunk-AF33YUHF.js → chunk-4UV7T77F.js} +1 -1
- package/dist/{chunk-JZZ4VDNH.js → chunk-4XUKEJ3C.js} +1 -1
- package/dist/chunk-AGOP4Q7U.js +12 -0
- package/dist/{chunk-3NY67ODS.js → chunk-DRLW6UU3.js} +1 -1
- package/dist/{chunk-NW4RXPYG.js → chunk-F535OXGZ.js} +1 -1
- package/dist/{chunk-SR4HILUN.js → chunk-ILPARXQH.js} +1 -1
- package/dist/chunk-KFBDAACV.js +5 -0
- package/dist/{chunk-5KSCMRFH.js → chunk-LAKMPJML.js} +1 -1
- package/dist/{chunk-OGPL4QTW.js → chunk-MWFO5O33.js} +1 -1
- package/dist/chunk-SVREO35Y.js +5 -0
- package/dist/chunk-TV6NLY7O.js +14 -0
- package/dist/chunk-UTAZPOBT.js +6 -0
- package/dist/{chunk-KGDTP5LR.js → chunk-W57Z6UQP.js} +1 -1
- package/dist/chunk-WALU7QUQ.js +25 -0
- package/dist/chunk-ZE3NJMCS.js +5 -0
- package/dist/chunk-ZF5SEDQB.js +5 -0
- package/dist/chunk-ZQ6F3H6X.js +5 -0
- package/package.json +10 -2
- package/ui-react/dist/bundle.css +1 -1
- package/ui-react/dist/bundle.js +53 -48
- package/dist/chunk-67UE7CV6.js +0 -6
- package/dist/chunk-DVXET5T4.js +0 -5
- package/dist/chunk-LLZJOZFY.js +0 -20
- package/dist/chunk-WCTNLSYC.js +0 -14
package/dist/canopy.js
CHANGED
|
@@ -3,99 +3,99 @@ import{fileURLToPath as __cf,pathToFileURL as __cu}from"node:url";import{dirname
|
|
|
3
3
|
const require=__cr(import.meta.url);
|
|
4
4
|
globalThis.__canopyBundle??=__cj(__cd(__cf(import.meta.url)),"canopy.js");
|
|
5
5
|
globalThis.__canopyUrl??=(r)=>__cu(__cj(__cd(__cd(globalThis.__canopyBundle)),r)).href;
|
|
6
|
-
import{a as
|
|
7
|
-
`,o),c=(i<0?s.length:i)-o;if(c>r&&(r=c),i<0)break;o=i+1}if(r>
|
|
8
|
-
`)}function
|
|
9
|
-
`))}import An from"node:path";function Xt(e){let t=An.resolve(e),n=t.split(An.sep).join("/"),s=[[t.toLowerCase(),t.length,An.sep],[n.toLowerCase(),n.length,"/"]],o=Math.max(s[0][1],s[1][1])+1,r=i=>{if(typeof i!="string")return i;let c=i.length>o?i.slice(0,o).toLowerCase():i.toLowerCase();if(c===s[0][0]||c===s[1][0])return".";for(let[a,l,f]of s)if(c.startsWith(a+f)){let h=i.slice(l+1),u=h.indexOf("::");return(u<0?h:h.slice(0,u)).split("\\").join("/")+(u<0?"":h.slice(u))}return i};return{rel:r,repoRoot:n,replacer:(i,c)=>typeof c=="string"?r(c):c,json:(i,c)=>JSON.stringify(i,(a,l)=>typeof l=="string"?r(l):l,c),clone:i=>JSON.parse(JSON.stringify(i,(c,a)=>typeof a=="string"?r(a):a))}}function ws(e){let t=e.map((s,o)=>({e:s,i:o})).sort((s,o)=>String(s.e.fromNodeId).localeCompare(String(o.e.fromNodeId))||(s.e.line??0)-(o.e.line??0)||(s.e.column??0)-(o.e.column??0)||s.i-o.i),n=new Map;for(let{e:s}of t){let o=s.calleeNameRaw??s.eventName??s.url??"",r=`${s.fromNodeId??"\u2205"} | ${s.callKind??s.type} | ${o}`,i=(n.get(r)??0)+1;n.set(r,i),s.id=`${r} | #${i}`}return e}function xs(e){let t=new Map;for(let n of e)t.has(n.id)||t.set(n.id,[]),t.get(n.id).push(n);for(let[n,s]of t)s.length<2||(s.sort((o,r)=>o.startLine-r.startLine||o.endLine-r.endLine),s.forEach((o,r)=>{r>0&&(o.id=`${n}#${r+1}`)}));return e}function ie(e,t){let n=null;for(let s of t)s.type!=="moduleRoot"&&e>=s.startLine&&e<=s.endLine&&(!n||s.endLine-s.startLine<n.endLine-n.startLine)&&(n=s);return n||t.find(s=>s.type==="moduleRoot")}function Ss(e,t){let n=[];for(let[o,r]of e){let i=t.filter(c=>c.filePath===o);for(let c of r.calls){let a=ie(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,calleeNameRaw:c.calleeName,line:c.startLine,column:c.startColumn,branchPath:c.branchPath??[],firstArgText:c.firstArgText??null,deferred:c.deferred??!1,type:"call",callKind:c.callKind??"call",resolved:!1})}for(let c of r.methodCalls){let a=ie(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,calleeNameRaw:c.methodName,objectNameRaw:c.objectName,line:c.startLine,column:c.startColumn,branchPath:c.branchPath??[],firstArgText:c.firstArgText??null,deferred:c.deferred??!1,type:"methodCall",callKind:c.callKind??"methodCall",resolved:!1})}for(let c of r.returnEntries??[]){let a=ie(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,calleeNameRaw:c.label,line:c.startLine,column:c.startColumn,branchPath:c.branchPath??[],deferred:c.deferred??!1,type:"returnValue",resolved:!1})}for(let c of r.jsxElements){let a=ie(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,calleeNameRaw:c.calleeName,line:c.startLine,type:"call",callKind:"jsx",resolved:!1})}for(let c of r.callSites??[]){let a=ie(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,calleeNameRaw:c.calleeName,line:c.startLine,column:c.startColumn,branchPath:c.branchPath??[],firstArgText:c.firstArgText??null,deferred:c.deferred??!1,type:"callSite",callKind:c.callKind,chainHead:c.chainHead??null,chainHeadCalled:c.chainHeadCalled??!1,ctorName:c.ctorName??null,...c.thisProp?{thisProp:c.thisProp,thisMethod:c.thisMethod}:{},resolved:!1})}for(let c of r.socketEmits){let a=ie(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,eventName:c.eventName,line:c.startLine,type:"socketEmit",resolved:!1})}for(let c of r.rawSocketSends??[]){let a=ie(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,eventName:c.eventName,line:c.startLine,type:"rawSocketSend",resolved:!1})}for(let c of r.apiCalls){let a=ie(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,url:c.url,httpMethod:c.method,scope:c.scope,line:c.startLine,type:"apiCall",resolved:!1})}}let s=n.filter(o=>o.type==="apiCall").length;return n}function ae(e,t){let n=new Map;for(let s of t)s.filePath===e&&n.set(s.name,s.id);return n}function Nt(e,t,n,s,o=null){if(n.has(e.calleeNameRaw))return{...e,targetNodeId:n.get(e.calleeNameRaw),confidence:.95,matchType:"local",resolved:!0};let r=[...s],i=s.legacySize??r.length,c=([,l])=>{let f=o?o.scopeOf(l):ae(l,t);return f.has(e.calleeNameRaw)?{...e,targetNodeId:f.get(e.calleeNameRaw),confidence:.85,matchType:"import",resolved:!0}:null};for(let l=0;l<i;l++){let f=c(r[l]);if(f)return f}let a=o?.bind?.resolveName(e.fromFileId,e.calleeNameRaw);if(a)return{...e,targetNodeId:a.id,confidence:.85,matchType:"import",resolved:!0};for(let l=i;l<r.length;l++){let f=c(r[l]);if(f)return f}return{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function ks(e,t,n=null){let s=n?n.method(e.objectNameRaw,e.calleeNameRaw):t.find(r=>r.type==="classMethod"&&r.className===e.objectNameRaw&&r.name===e.calleeNameRaw);if(s)return{...e,targetNodeId:s.id,confidence:.6,matchType:"methodHeuristic",resolved:!0};let o=n?.bind?.resolveMember(e.fromFileId,e.objectNameRaw,e.calleeNameRaw);return o?{...e,targetNodeId:o.id,confidence:.85,matchType:"import",resolved:!0}:{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function $s(e){return{...e,targetNodeId:null,confidence:0,matchType:"unresolvedExternal",resolved:!1}}function bs(e,t,n,s,o=null){if(e.callKind==="new"&&e.ctorName){let r=Nt({...e,calleeNameRaw:e.ctorName},t,n,s,o);if(r.resolved)return{...r,calleeNameRaw:e.calleeNameRaw,matchType:r.matchType+"New"};let i=new Set([e.fromFileId,...s.values()]),c=o?o.ctorsOf(e.ctorName).find(a=>i.has(a.filePath)):t.find(a=>a.type==="classMethod"&&a.className===e.ctorName&&a.name==="constructor"&&i.has(a.filePath));return c?{...e,targetNodeId:c.id,confidence:c.filePath===e.fromFileId?.9:.8,matchType:(c.filePath===e.fromFileId?"local":"import")+"New",resolved:!0}:$s(e)}if(e.callKind==="chainedCall"&&e.chainHead&&e.chainHeadCalled){let r=Nt({...e,calleeNameRaw:e.chainHead},t,n,s,o);if(r.resolved)return{...e,targetNodeId:r.targetNodeId,confidence:r.confidence*.8,matchType:"chainHead",resolved:!0}}return $s(e)}import Bn from"node:path";import Ue from"node:fs";import G from"node:path";var Es=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],kc=["index.ts","index.tsx","index.mts","index.cts","index.js","index.jsx","index.mjs","index.cjs"],$c={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]};var Rs=null,_s=e=>{Rs=e},Cs=()=>Rs,Ns=e=>G.resolve(e);function It(e,t){e=G.resolve(e);let n=()=>{try{let i=G.join(e,"package.json");if(!Ue.existsSync(i))return null;let c=JSON.parse(Ue.readFileSync(i,"utf8")).main;if(typeof c!="string")return null;let a=G.resolve(e,c);return t.has(a)?a:bc(a,t)}catch{return null}},s=G.extname(e);if(s&&t.has(e))return e;let o=$c[s];if(o)for(let i of o){let c=e.slice(0,-s.length)+i;if(t.has(c))return c}for(let i of Es)if(t.has(e+i))return e+i;let r=n();if(r)return r;for(let i of kc){let c=G.join(e,i);if(t.has(c))return c}return null}function bc(e,t){if(G.extname(e)&&t.has(e))return e;for(let s of Es)if(t.has(e+s))return e+s;return null}var Fn=e=>{try{let n=Ue.readFileSync(e,"utf8").replace(/^/,"").replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,(s,o)=>o??"");return JSON.parse(n.replace(/,(\s*[}\]])/g,"$1"))}catch{return null}};function Ls(e,t=new Set){if(t.has(e))return{baseUrl:null,paths:null};t.add(e);let n=Fn(e);if(!n)return{baseUrl:null,paths:null};let s=null,o=null,r=n.extends?Array.isArray(n.extends)?n.extends:[n.extends]:[];for(let c of r){if(typeof c!="string"||!c.startsWith("."))continue;let a=G.resolve(G.dirname(e),c);(!Ue.existsSync(a)||Ue.statSync(a).isDirectory())&&(a=Ue.existsSync(a+".json")?a+".json":G.join(a,"tsconfig.json"));let l=Ls(a,t);l.baseUrl&&(s=l.baseUrl),l.paths&&(o=l.paths)}let i=n.compilerOptions??{};if(typeof i.baseUrl=="string"&&(s=G.resolve(G.dirname(e),i.baseUrl)),i.paths&&typeof i.paths=="object"){let c=s??G.dirname(e);o=Object.entries(i.paths).map(([a,l])=>{let f=a.indexOf("*");return{prefix:f<0?a:a.slice(0,f),suffix:f<0?"":a.slice(f+1),wildcard:f>=0,targets:(Array.isArray(l)?l:[]).filter(h=>typeof h=="string").map(h=>G.resolve(c,h))}}).sort((a,l)=>l.prefix.length-a.prefix.length)}return{baseUrl:s,paths:o}}function Nc(e,t){if(t=t.replace(/^\.\//,"").replace(/\/+$/,""),t.startsWith("!"))return[];let n=[],s=o=>{try{return Ue.readdirSync(o,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="node_modules"&&!r.name.startsWith(".")).map(r=>G.join(o,r.name))}catch{return[]}};if(t.endsWith("/**")){let o=G.join(e,t.slice(0,-3)),r=i=>{for(let c of s(i))n.push(c),r(c)};r(o)}else t.endsWith("/*")?n.push(...s(G.join(e,t.slice(0,-2)))):t.includes("*")||n.push(G.join(e,t));return n}function Ic(e){let t=[],s=Fn(G.join(e,"package.json"))?.workspaces;Array.isArray(s)?t.push(...s):Array.isArray(s?.packages)&&t.push(...s.packages);try{let o=Ue.readFileSync(G.join(e,"pnpm-workspace.yaml"),"utf8"),r=!1;for(let i of o.split(/\r?\n/)){if(/^packages\s*:/.test(i)){r=!0;continue}if(r){let c=/^\s*-\s*['"]?([^'"#\s]+)['"]?/.exec(i);c?t.push(c[1]):/^\S/.test(i)&&(r=!1)}}}catch{}return t}function Is(e,t){if(e==null)return null;let n=o=>{if(typeof o=="string")return o;if(Array.isArray(o)){for(let r of o){let i=n(r);if(i)return i}return null}if(o&&typeof o=="object"){for(let r of["source","import","module","default","require","node"])if(r in o){let i=n(o[r]);if(i)return i}}return null};if(typeof e=="string"||Array.isArray(e))return t==="."?n(e):null;let s=Object.keys(e);if(!s.some(o=>o.startsWith(".")))return t==="."?n(e):null;if(e[t]!=null)return n(e[t]);for(let o of s){let r=o.indexOf("*");if(r>0&&t.startsWith(o.slice(0,r))&&t.endsWith(o.slice(r+1))){let i=n(e[o]);if(i)return i.replace("*",t.slice(r,t.length-(o.length-r-1)))}}return null}function Ps(e,t,n={}){let s=Ns(e),o=new Set(t),r=new Map,i=u=>{if(r.has(u))return r.get(u);let v=null,d=G.join(u,"tsconfig.json");return Ue.existsSync(d)?v=Ls(d):u!==s&&G.dirname(u)!==u&&u.startsWith(s)&&(v=i(G.dirname(u))),r.set(u,v),v},c=new Map;for(let u of Ic(s))for(let v of Nc(s,u)){let d=Fn(G.join(v,"package.json"));d?.name&&!c.has(d.name)&&c.set(d.name,{dir:Ns(v),pkg:d})}let a=[...c.keys()].sort((u,v)=>v.length-u.length),l=(u,v,d)=>{let{dir:k,pkg:j}=c.get(u),p=[],S=$=>{if(!$)return;let w=G.resolve(k,$);p.push(w);let y=G.relative(k,w).split(G.sep);["dist","build","lib","out","esm","cjs"].includes(y[0])&&p.push(G.join(k,"src",...y.slice(1)))};if(v==="."){S(Is(j.exports,"."));for(let $ of["source","module","main"])typeof j[$]=="string"&&S(j[$]);p.push(G.join(k,"src","index"),G.join(k,"index"))}else S(Is(j.exports,v)),p.push(G.join(k,v),G.join(k,"src",v));for(let $ of p){let w=It($,d);if(w)return w}return null},f=u=>a.find(v=>u===v||u.startsWith(v+"/"))??null,h=(u,v)=>v?.paths?.some(d=>d.wildcard?u.startsWith(d.prefix)&&u.endsWith(d.suffix)&&u.length>=d.prefix.length+d.suffix.length:u===d.prefix)??!1;return{root:s,files:o,packages:c,isInternal(u,v){if(u.startsWith(".")||f(u))return!0;let d=i(G.dirname(v));return!!(h(u,d)||d?.baseUrl&&!u.startsWith("@")&&It(G.join(d.baseUrl,u),o))},resolve(u,v,d){if(u.startsWith("."))return It(G.resolve(G.dirname(v),u),d);let k=i(G.dirname(v));if(k?.paths&&n.paths!==!1)for(let p of k.paths){let S=null;if(p.wildcard?u.startsWith(p.prefix)&&u.endsWith(p.suffix)&&u.length>=p.prefix.length+p.suffix.length&&(S=u.slice(p.prefix.length,u.length-p.suffix.length)):u===p.prefix&&(S=""),S!=null){for(let $ of p.targets){let w=It($.replace("*",S),d);if(w)return w}break}}let j=n.workspaces===!1?null:f(u);if(j){let p=l(j,u===j?".":"./"+u.slice(j.length+1),d);if(p)return p}if(k?.baseUrl&&n.paths!==!1){let p=It(G.join(k.baseUrl,u),d);if(p)return p}return null}}}var js=new WeakMap;function Ms(e){if(e instanceof Set)return e;let t=js.get(e);return t||js.set(e,t=new Set(e)),t}var Ts=new WeakMap;function jc(e){let t=Ts.get(e);return(!t||t.n!==e.length)&&(t={n:e.length,set:new Set(e)},Ts.set(e,t)),t.set}function Dn(e,t,n){if(!e.startsWith("."))return null;let s=Bn.dirname(t),o=Bn.resolve(s,e),r=[o,...ss().map(i=>`${o}${i}`),...rs().map(i=>Bn.join(o,i))];for(let i of r)if(jc(n).has(i))return i;return null}function me(e,t,n){let s=Dn(e,t,n);if(s)return s;let o=Cs();return o?o.resolve(e,t,Ms(n)):null}function wt(e,t,n){let s=new Map;for(let o of t){let r=Dn(o.source,e,n);r&&s.set(o.source,r)}s.legacySize=s.size;for(let o of t){if(s.has(o.source))continue;let r=me(o.source,e,n);r&&s.set(o.source,r)}return s}function Os(e){let t=new Map,n=new Map,s=new Map;for(let o of e){if(o.type!=="classMethod")continue;let r=o.className+"\0"+o.name;n.has(r)||n.set(r,o),o.name==="constructor"&&(s.has(o.className)||s.set(o.className,[]),s.get(o.className).push(o))}return{scopeOf:o=>{let r=t.get(o);return r||(r=ae(o,e),t.set(o,r)),r},method:(o,r)=>n.get(o+"\0"+r),ctorsOf:o=>s.get(o)??[]}}function xt(e){return e?e.split("?")[0].split("/").map(t=>t.startsWith(":")||/^\d+$/.test(t)?"*":t).join("/"):""}var Ec=new Set(["function","arrowFunction"]);function As(e,t,n,s){let o=new Map;for(let l of t){let f=o.get(l.filePath);f||o.set(l.filePath,f=[]),f.push(l)}let r=new Set;for(let l of s)l.resolved&&l.fromNodeId&&l.targetNodeId&&r.add(l.fromNodeId+"\0"+l.targetNodeId);let i=(l,f)=>(o.get(l)??[]).find(h=>Ec.has(h.type)&&f(h))??null,c=[];c.argBindings=[];let a=(l,f,h,u,v,d,k)=>{!f||!h||f.id===h.id||r.has(f.id+"\0"+h.id)||c.push({fromFileId:l,fromNodeId:f.id,calleeNameRaw:u,line:v,column:d,branchPath:[],firstArgText:null,deferred:!1,type:"reference",callKind:"reference",targetNodeId:h.id,confidence:k==="local"?.95:.85,matchType:k,resolved:!0})};for(let[l,f]of e){let h=o.get(l);if(h){for(let u of f.refArgs??[]){let v=null,d="local";if(u.b==="fn"?v=i(l,j=>j.name===u.name&&j.startLine===u.declLine):u.b==="import"&&(d="import",(u.ik==="default"||u.ik==="named"||u.ik==="cjs")&&(v=n.nodeForImport(l,u.src,u.ik,u.imp))),!v)continue;let k=ie(u.line,h);a(l,k,v,u.name,u.line,u.column,d),u.callLine!=null&&k&&k.id!==v.id&&c.argBindings.push({file:l,line:u.callLine,column:u.callColumn,targetNodeId:v.id,matchType:d,direct:u.via==="arg"})}for(let u of h){if(u.type!=="inlineHandler")continue;let v=null;for(let d of h)d===u||d.type==="moduleRoot"||d.startLine<=u.startLine&&d.endLine>=u.endLine&&!(d.startLine===u.startLine&&d.endLine===u.endLine)&&(!v||d.endLine-d.startLine<v.endLine-v.startLine)&&(v=d);v??=h.find(d=>d.type==="moduleRoot"),a(l,v,u,u.name,u.startLine,0,"local")}}}return c}function Fs(e,t,n,s){let o=new Map,r=new Map;for(let c of e){if(r.set(c.id,c),c.type!=="classMethod")continue;let a=c.filePath+"\0"+c.className+"\0"+c.name,l=o.get(a);l?l.push(c):o.set(a,[c])}let i=(c,a)=>{for(let l of o.keys())if(l.startsWith(c+"\0"+a+"\0"))return!0;return!1};return function(a){let l=r.get(a.fromNodeId);if(!l||l.type!=="classMethod")return null;let f=t.get(a.fromFileId),h=(f?.classProps??[]).find(j=>j.className===l.className&&j.prop===a.thisProp);if(!h)return null;let u=null,v=null,d=(f.importBindings??[]).find(j=>j.local===h.type);if(d){let j=d.kind==="default"||d.kind==="named"?s.resolveImport(a.fromFileId,d.source,d.kind,d.imported):null;j?.local&&j.local!=="default"&&(u=j.file,v=j.local)}else i(a.fromFileId,h.type)&&(u=a.fromFileId,v=h.type);if(!u)return null;let k=o.get(u+"\0"+v+"\0"+a.thisMethod);return!k||k.length!==1?null:{...a,targetNodeId:k[0].id,confidence:.9,matchType:"typedProperty",resolved:!0}}}var Rc=new Set(["function","arrowFunction"]);function Kt(e,t,n){let s=new Map;for(let f of e){if(!Rc.has(f.type))continue;let h=f.filePath+"\0"+f.name;s.has(h)||s.set(h,f)}let o=new Map,r=(f,h)=>{let u=o.get(f);if(!u){u=new Map;for(let v of t.get(f)?.importBindings??[])u.has(v.local)||u.set(v.local,v);o.set(f,u)}return u.get(h)??null},i=(f,h)=>n(f).get(h)??null;function c(f,h,u=new Set){let v=f+"\0"+h;if(u.has(v))return null;u.add(v);let d=t.get(f)?.exportBindings;if(!d)return null;if(h==="default"){if(d.default)return{file:f,local:d.default==="<anon>"?"default":d.default}}else if(d.named?.[h])return{file:f,local:d.named[h]};for(let k of d.reexports??[]){if(k.exported!==h)continue;let j=i(f,k.source);if(j)return c(j,k.imported,u)}for(let k of d.nsReexports??[]){if(k.exported!==h)continue;let j=i(f,k.source);if(j)return{moduleFile:j}}if(h!=="default")for(let k of d.stars??[]){let j=i(f,k),p=j?c(j,h,u):null;if(p)return p}return null}let a=f=>f?.local?s.get(f.file+"\0"+f.local)??null:null;function l(f,h,u,v){let d=i(f,h);return d?u==="default"?c(d,"default"):u==="named"?c(d,v):{moduleFile:d,cjs:u==="cjs"}:null}return{lookupExport:c,resolveImport:l,nodeForImport(f,h,u,v){let d=l(f,h,u,v);return d?.moduleFile&&d.cjs?a(c(d.moduleFile,"default")):a(d)},resolveName(f,h){let u=r(f,h);return u?this.nodeForImport(f,u.source,u.kind,u.imported):null},resolveMember(f,h,u){let v=r(f,h);if(!v)return null;let d=l(f,v.source,v.kind,v.imported);return d?.moduleFile?a(c(d.moduleFile,u)):null},classForImport(f,h){let u=r(f,h);if(!u)return null;let v=l(f,u.source,u.kind,u.imported);return v?.local?{file:v.file,className:v.local==="default"?null:v.local}:null},bindingFor:r}}function Bs(e,t,n,s,o,r,i){let c=[],a=Os(t),l=new Map,f=p=>l.get(p)??wt(p,n.get(p)?.imports??[],s);a.bind=Kt(t,n,f);let h=Fs(t,n,f,a.bind),u=new Map;for(let p of e)u.has(p.fromFileId)||u.set(p.fromFileId,[]),u.get(p.fromFileId).push(p);for(let[p,S]of u){let $=n.get(p),w=ae(p,t),y=wt(p,$.imports,s);l.set(p,y);for(let m of S)if(m.type==="call")c.push(Nt(m,t,w,y,a));else if(m.type==="methodCall")c.push(ks(m,t,a));else if(m.type==="callSite")c.push((m.thisProp?h(m):null)??bs(m,t,w,y,a));else if(m.type==="returnValue")c.push({...m,targetNodeId:null,confidence:0,matchType:"returnValue",resolved:!1});else if(m.type==="apiCall")if(m.scope==="external")c.push({...m,targetNodeId:null,confidence:null,matchType:"externalService",resolved:!1});else{let b=xt(m.url),g=o.get(b);g?c.push({...m,targetNodeId:g,confidence:.5,matchType:"crossLayer",resolved:!0}):c.push({...m,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(m.type==="socketEmit"){let b=r.get(m.eventName);b?c.push({...m,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):c.push({...m,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(m.type==="rawSocketSend"){let b=i?.get(m.eventName);b?c.push({...m,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):c.push({...m,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}}let v=As(n,t,a.bind,c);for(let p of v)c.push(p);let d=new Map;for(let p of c){if(p.resolved||p.line==null||p.type!=="call"&&p.type!=="methodCall"&&p.type!=="callSite")continue;let S=p.fromFileId+" "+p.line+" "+p.column;(d.get(S)??d.set(S,[]).get(S)).push(p)}let k=[...v.argBindings].sort((p,S)=>S.direct-p.direct),j=new Set;for(let p of k){let S=p.file+" "+p.line+" "+p.column;if(j.has(S))continue;let $=(d.get(S)??[]).find(w=>w.fromNodeId!==p.targetNodeId);$&&(j.add(S),Object.assign($,{targetNodeId:p.targetNodeId,confidence:p.matchType==="local"?.95:.85,matchType:"argument",resolved:!0,viaArgument:!0}))}return c}function Ds(e){let t=new Map,n=new WeakMap,s=a=>{if(typeof a=="string")return a.length>=20?"s"+a:null;if(a&&typeof a=="object"){let l=n.get(a);if(l===void 0){let f=JSON.stringify(a);l=f.length>=40?"j"+f:"",n.set(a,l)}return l||null}return null};(function a(l){let f=s(l);if(f){let h=t.get(f)??0;if(t.set(f,h+1),h>0)return}if(Array.isArray(l))for(let h of l)a(h);else if(l&&typeof l=="object")for(let h of Object.values(l))a(h)})(e);let o=[],r=new Map,i=a=>{let l=s(a),f=l&&t.get(l)>1;if(f&&r.has(l))return r.get(l);let h;if(typeof a=="string"?h=JSON.stringify(a):Array.isArray(a)?h="["+a.map(i).join(",")+"]":a&&typeof a=="object"?h="{"+Object.entries(a).map(([v,d])=>JSON.stringify(v)+":"+i(d)).join(",")+"}":h=JSON.stringify(a),!f)return h;let u="$"+o.length.toString(36);return o.push(`const ${u}=${h};`),r.set(l,u),u},c=i(e);return`(() => {${o.join(`
|
|
6
|
+
import{a as ho,b as go,d as yo,e as vo,g as wo}from"./chunk-4UV7T77F.js";import{a as Ze,c as Yo}from"./chunk-KFBDAACV.js";import{a as Po,b as Mo,c as Oo,d as Ao,f as To,g as Fo,h as Bo,i as Do,j as Ho,k as zo,l as Wo,m as Uo,o as qo,p as Go}from"./chunk-DRLW6UU3.js";import{s as _o,t as Lo}from"./chunk-W57Z6UQP.js";import{a as xo,b as Ft,c as Bt,d as ge,e as Ce,f as Dt,g as ot,h as In,i as So,j as ko,k as $o,l as bo,m as No,n as Io,o as jo,p as Eo,q as Ro,r as Co}from"./chunk-LAKMPJML.js";import{b as jn,d as Jo}from"./chunk-F535OXGZ.js";import{a as Ae,b as Tt}from"./chunk-ZF5SEDQB.js";import{a as Ri,b as Ci}from"./chunk-ZQ6F3H6X.js";var ss=Ri((Ll,Wt)=>{function Zo(e){return Array.isArray(e)?e:[e]}var Li=void 0,Rn="",Xo=" ",En="\\",Pi=/^\s+$/,Mi=/(?:[^\\]|^)\\$/,Oi=/^\\!/,Ai=/^\\#/,Ti=/\r?\n/g,Fi=/^\.{0,2}\/|^\.{1,2}$/,Bi=/\/$/,ht="/",Qo="node-ignore";typeof Symbol<"u"&&(Qo=Symbol.for("node-ignore"));var es=Qo,gt=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),Di=/([0-z])-([0-z])/g,ts=()=>!1,Hi=e=>e.replace(Di,(t,n,s)=>n.charCodeAt(0)<=s.charCodeAt(0)?t:Rn),zi=e=>e.startsWith("!")||e.startsWith("\\^")?`^${e.slice(e[0]==="!"?1:2)}`:e,Wi=e=>{let{length:t}=e;return e.slice(0,t-t%2)},Ui=[[/^\uFEFF/,()=>Rn],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?Xo:Rn)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+Xo}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*(?:\\\*\\\*\\\/)+/,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>{let s=n.replace(/\\\*/g,"[^\\/]*");return t+s}],[/\\\\\\(?=[$.|*+(){^])/g,()=>En],[/\\\\/g,()=>En],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,s,o)=>t===En?`\\[${n}${Wi(s)}${o}`:o==="]"&&s.length%2===0?`[${zi(Hi(n))}${s}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],qi=/(^|\\\/)?\\\*$/,It="regex",Ht="checkRegex",Ko="_",Gi={[It](e,t){return`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Ht](e,t){return`${t?`${t}[^/]*`:"[^/]*"}(?=$|\\/$)`}},Yi=e=>Ui.reduce((t,[n,s])=>t.replace(n,s.bind(e)),e),zt=e=>typeof e=="string",Ji=e=>e&&zt(e)&&!Pi.test(e)&&!Mi.test(e)&&e.indexOf("#")!==0,Vi=e=>e.split(Ti).filter(Boolean),Cn=class{constructor(t,n,s,o,r,i){this.pattern=t,this.mark=n,this.negative=r,gt(this,"body",s),gt(this,"ignoreCase",o),gt(this,"regexPrefix",i)}get regex(){let t=Ko+It;return this[t]?this[t]:this._make(It,t)}get checkRegex(){let t=Ko+Ht;return this[t]?this[t]:this._make(Ht,t)}_make(t,n){let s=this.regexPrefix.replace(qi,Gi[t]),o=this.ignoreCase?new RegExp(s,"i"):new RegExp(s);return gt(this,n,o)}},Xi=({pattern:e,mark:t},n)=>{let s=!1,o=e;o.indexOf("!")===0&&(s=!0,o=o.substr(1)),o=o.replace(Oi,"!").replace(Ai,"#");let r=Yi(o);return new Cn(e,t,o,n,s,r)},_n=class{constructor(t){this._ignoreCase=t,this._rules=[]}_add(t){if(t&&t[es]){this._rules=this._rules.concat(t._rules._rules),this._added=!0;return}if(zt(t)&&(t={pattern:t}),Ji(t.pattern)){let n=Xi(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,Zo(zt(t)?Vi(t):t).forEach(this._add,this),this._added}test(t,n,s){let o=!1,r=!1,i;this._rules.forEach(a=>{let{negative:l}=a;r===l&&o!==r||l&&!o&&!r&&!n||!a[s].test(t)||(o=!l,r=l,i=l?Li:a)});let c={ignored:o,unignored:r};return i&&(c.rule=i),c}},Ki=(e,t)=>{throw new t(e)},ze=(e,t,n)=>zt(e)?e?ze.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${t}\``,TypeError),ns=e=>Fi.test(e);ze.isNotRelative=ns;ze.convert=e=>e;var Ln=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:s=!1}={}){gt(this,es,!0),this._rules=new _n(n),this._strictPathCheck=!s,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(t){return this._rules.add(t)&&this._initCache(),this}addPattern(t){return this.add(t)}_test(t,n,s,o){let r=t&&ze.convert(t);return ze(r,t,this._strictPathCheck?Ki:ts),this._t(r,n,s,o)}checkIgnore(t){if(!Bi.test(t))return this.test(t);let n=t.split(ht).filter(Boolean);if(n.pop(),n.length){let s=this._t(n.join(ht)+ht,this._testCache,!0,n);if(s.ignored)return s}return this._rules.test(t,!1,Ht)}_t(t,n,s,o){if(t in n)return n[t];if(o||(o=t.split(ht).filter(Boolean)),o.pop(),!o.length)return n[t]=this._rules.test(t,s,It);let r=this._t(o.join(ht)+ht,n,s,o);return n[t]=r.ignored?r:this._rules.test(t,s,It)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return Zo(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},Pn=e=>new Ln(e),Zi=e=>ze(e&&ze.convert(e),e,ts),os=()=>{let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");ze.convert=e;let t=/^[a-z]:\//i;ze.isNotRelative=n=>t.test(n)||ns(n)};typeof process<"u"&&process.platform==="win32"&&os();Wt.exports=Pn;Pn.default=Pn;Wt.exports.isPathValid=Zi;gt(Wt.exports,Symbol.for("setupWindows"),os)});import{isMainThread as Vo,workerData as _i}from"node:worker_threads";Vo&&!process.env.UV_THREADPOOL_SIZE&&(process.env.UV_THREADPOOL_SIZE="16");if(!Vo&&_i?.canopyParseWorker===!0){let{runParseWorker:e}=await import("./chunk-UTAZPOBT.js");await e(),await new Promise(()=>{})}import bn from"node:fs";import kt from"node:path";import Je from"node:fs";import Ta from"node:os";import ue from"node:path";import{fileURLToPath as Qr}from"node:url";import K from"node:path";import ve from"node:fs";import{fileURLToPath as Pa,pathToFileURL as Ma}from"node:url";var An=Ci(ss(),1);import yt from"node:fs";import be from"node:path";var Mn={javascript:[".js",".jsx",".mjs",".cjs"],typescript:[".ts",".tsx"]},rs=[".ts",".tsx",".mts",".cts"],Qi={javascript:["index.js","index.jsx"],typescript:["index.ts","index.tsx"]};function is(){return Object.values(Mn).flat()}function cs(){return Object.values(Qi).flat()}var as=["log","logger","console","debug","trace"];var fs=[".yarn",".pnp","vendor","dist","build","out","coverage",".next",".nuxt",".turbo",".cache","bower_components"],Tn=["node_modules",".git",".canopy",".canopy-cache"],ls=[".vue",".svelte"],ec=1024*1024,On=1e4;function tc(e,t=null){let n=[];function s(o,r){let i=be.join(o,".gitignore"),c=(0,An.default)().add(r);yt.existsSync(i)&&c.add(yt.readFileSync(i,"utf-8"));let a=yt.readdirSync(o,{withFileTypes:!0});for(let l of a){let f=be.join(o,l.name),y=be.relative(e,f).split(be.sep).join("/");if(!c.ignores(y)&&!(l.isDirectory()&&Tn.includes(l.name))){if(l.isDirectory()&&fs.includes(l.name)){t&&t.excludedDirs.push(f);continue}l.isDirectory()?s(f,c):l.isFile()&&n.push(f)}}}return s(e,(0,An.default)()),n}function nc(e,t,n=null){return e.filter(s=>!(n?be.relative(n,s):s).split(be.sep).some(r=>t.includes(r)))}function us(e,t){let n=0,s;try{s=yt.readdirSync(e,{withFileTypes:!0})}catch{return 0}for(let o of s)o.isDirectory()?Tn.includes(o.name)||(n+=us(be.join(e,o.name),t)):o.isFile()&&t.has(be.extname(o.name))&&n++;return n}var oc=e=>/\.d\.(ts|mts|cts)$/.test(e);function sc(e){let t=be.basename(e);if(/\.min\.js$/.test(t))return{kind:"minified",reason:"minified (*.min.js)"};if(/\.bundle\.js$/.test(t))return{kind:"bundled",reason:"bundled (*.bundle.js)"};let n;try{n=yt.statSync(e).size}catch{return null}if(n>ec)return{kind:"oversized",reason:`oversized (${(n/1048576).toFixed(1)} MB, limit 1 MB)`};if(n>On){let s=yt.readFileSync(e,"utf8"),o=0,r=0;for(;;){let i=s.indexOf(`
|
|
7
|
+
`,o),c=(i<0?s.length:i)-o;if(c>r&&(r=c),i<0)break;o=i+1}if(r>On)return{kind:"minified",reason:`line of ${r.toLocaleString("en-US")} characters (limit ${On.toLocaleString("en-US")}; minified/bundled)`}}return null}function jt(e,t=["javascript","typescript"]){let n=t.flatMap(y=>(y==="typescript"?rs:Mn[y])||[]),s={excludedDirs:[]},o=nc(tc(e,s),[...fs,...Tn],e),r=y=>be.relative(e,y).split(be.sep).join("/"),i=[],c=[],a={};for(let y of o){let d=be.extname(y);if(n.includes(d)){if(oc(y)){c.push({file:r(y),kind:"declaration",reason:"declaration file"});continue}let w=sc(y);w?c.push({file:r(y),kind:w.kind,reason:w.reason}):i.push(y)}else ls.includes(d)&&(a[d]=(a[d]??0)+1)}let l=new Set([...n,...ls]),f={};for(let y of s.excludedDirs){let d=be.basename(y),w=f[d]??={dirs:0,files:0};w.dirs++,w.files+=us(y,l)}return{files:i,skipped:c,unsupported:a,excludedDirs:f}}function Fn(e,t=["javascript","typescript"]){return jt(e,t).files}import rc from"node:path";var st=e=>e.toLocaleString("en-US"),Ut=(e,t,n=t+"s")=>`${st(e)} ${e===1?t:n}`,ic={".vue":"Vue",".svelte":"Svelte"},cc=[".vue",".svelte"],ac=new Set([".ts",".tsx",".mts",".cts"]);function ds({discovered:e,parseResults:t,scopeFiles:n,rel:s,rootService:o=null}){let r=(t.budgetSkips??[]).map(p=>({path:s(p.filePath),kind:"timeout",reason:p.reason})),i=new Set((t.budgetSkips??[]).map(p=>p.filePath)),c=[...e.skipped.map(p=>({path:p.file,kind:p.kind,reason:p.reason})),...r].sort((p,$)=>p.path<$.path?-1:p.path>$.path?1:0),a=e.files.filter(p=>!i.has(p)),l=a.filter(p=>t.get(p)?.hadErrors).map(s).sort(),f=a.flatMap(p=>(t.get(p)?.warnings??[]).map($=>({path:s(p),extractor:$.extractor,message:$.message}))).sort((p,$)=>p.path<$.path?-1:p.path>$.path?1:0),y=a.filter(p=>ac.has(rc.extname(p))).length,d={};for(let p of cc)e.unsupported[p]&&(d[p]=e.unsupported[p]);let w={};for(let p of c)w[p.kind]=(w[p.kind]??0)+1;return{analyzed:a.length,analyzedJs:a.length-y,analyzedTs:y,inService:a.filter(p=>n.has(p)).length,notAnalyzed:d,notAnalyzedTotal:Object.values(d).reduce((p,$)=>p+$,0),skipped:c,skippedByKind:w,parseErrors:l.length,parseErrorFiles:l.slice(0,50),parseWarnings:f.length,parseWarningList:f.slice(0,50),excludedDirs:e.excludedDirs,rootService:o}}function qt(e){let t=["Coverage"],n=[],s=new Map;for(let[c,a]of Object.entries(e.notAnalyzed)){let l=ic[c];s.has(l)||s.set(l,[]),s.get(l).push(`${st(a)} ${c}`)}for(let[c,a]of s)n.push(`${a.join(", ")} files (${c} not supported yet)`);if(e.skipped.length){let c=Object.entries(e.skippedByKind).map(([a,l])=>`${a}: ${l}`).join(", ");n.push(`${st(e.skipped.length)} skipped (${c})`)}e.parseErrors&&n.push(`${st(e.parseErrors)} with parse errors`),e.parseWarnings&&n.push(`${st(e.parseWarnings)} extractor warnings (a construct skipped; the rest of its file was analyzed)`);let o=e.analyzedTs?`${Ut(e.analyzedJs,"JS file")} and ${Ut(e.analyzedTs,"TS file")}`:Ut(e.analyzed,"JS file");t.push(` Analyzed ${o}, ${st(e.inService)} of them inside a service${e.analyzed?` (${Math.round(100*e.inService/e.analyzed)}%)`:""}.`),t.push(` Not analyzed: ${n.length?n.join(", "):"nothing"}.`);let r=e.skipped.filter(c=>c.kind!=="declaration");for(let c of r.slice(0,5))t.push(` skipped ${c.path}: ${c.reason}`);r.length>5&&t.push(` ... and ${st(r.length-5)} more (full list: meta.coverage.skipped)`);let i=Object.entries(e.excludedDirs);return i.length&&t.push(` Excluded directories: ${i.map(([c,a])=>`${c}/ x${a.dirs} (${Ut(a.files,"source file")})`).join(", ")}.`),e.rootService&&t.push(` Root service: ${e.rootService.reason}.`),t.join(`
|
|
8
|
+
`)}function Gt(e,t){return`${e}::${t}`}var ps=[{category:"frontend",patterns:["frontend","client","src/components","ui","src/pages","public"]},{category:"backend",patterns:["backend","server","api","realtime-backend"]},{category:"transport",patterns:["websocket","socket","realtime"]},{category:"data",patterns:["redis","database","models","db"]}];function Yt(e){let t=e.toLowerCase().replace(/\\/g,"/");for(let{category:n,patterns:s}of ps)for(let o of s)if(t.includes(o))return n;return"unknown"}import Bn from"node:fs";import we from"node:path";import Jt from"node:fs";import We from"node:path";var lc=["index.html","public/index.html","src/index.html"],fc=/^(build|esbuild|vite\.config|webpack\.config|rollup\.config|bundle)[\w.-]*\.(mjs|cjs|js|ts)$/i;function uc(e){let t=e.replace(/<!--[\s\S]*?-->/g,""),n=[];for(let s of t.matchAll(/<script\b[^>]*?\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)')/gi))n.push(s[1]??s[2]);return n}function dc(e){let t=[],n=[];try{n=Jt.readdirSync(e).filter(s=>fc.test(s)).sort()}catch{return t}for(let s of n){let o;try{o=Jt.readFileSync(We.join(e,s),"utf8")}catch{continue}let r=/\boutfile\s*:\s*["'`]([^"'`]+)["'`]/.exec(o)?.[1]??null,i=/\b(?:entryPoints|entry|input)\s*:\s*\[?\s*["'`]([^"'`]+)["'`]/.exec(o)?.[1]??null;i&&t.push({config:s,outfile:r,entry:i})}return t}function Vt(e,t,n=new Set(t.map(s=>We.resolve(s)))){for(let s of lc){let o=We.join(e,s);if(!Jt.existsSync(o))continue;let r;try{r=Jt.readFileSync(o,"utf8")}catch{continue}let i=We.dirname(o),c=f=>{let y=f.split(/[?#]/)[0];return!y||/^([a-z]+:)?\/\//i.test(y)?null:We.resolve(y.startsWith("/")?We.join(e,y):We.join(i,y))},a=uc(r).map(f=>({s:f,p:c(f)})).filter(f=>f.p);for(let{s:f,p:y}of a)if(n.has(y))return{indexHtml:o,script:f,entry:y,via:"script"};let l=dc(e);for(let{s:f,p:y}of a)for(let d of l){if(!d.outfile||We.resolve(e,d.outfile)!==y)continue;let w=We.resolve(e,d.entry);if(n.has(w))return{indexHtml:o,script:f,entry:w,via:`${d.config} (outfile ${d.outfile})`}}}return null}var pc=new Set(["test","tests","__tests__","fixtures","__fixtures__","__mocks__","e2e","cypress"]);function vt(e){let t=String(e).replace(/\\/g,"/").split("/").filter(Boolean);if(!t.length)return!1;for(let n of t.slice(0,-1))if(pc.has(n.toLowerCase()))return!0;return/\.(test|spec)\.[^./]+$/i.test(t[t.length-1])}function mc(e){let t=we.join(e,"package.json");if(!Bn.existsSync(t))return null;try{return JSON.parse(Bn.readFileSync(t,"utf-8"))}catch{return null}}function hc(e){return[...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{})]}function gc(e){let t=!!e.workspaces,n=Object.keys(e.dependencies??{}).length>0,s=!!(e.scripts&&e.scripts.start);return t&&!n&&!s}var yc=["react","vue","svelte","next","vite","webpack","parcel"],vc=["express","fastify","koa","hapi","socket.io","ws"],wc=[{deps:["mongodb","mongoose"],label:"MongoDB"},{deps:["redis","ioredis"],label:"Redis"},{deps:["pg","postgres"],label:"PostgreSQL"},{deps:["mysql","mysql2"],label:"MySQL"},{deps:["sqlite3","better-sqlite3"],label:"SQLite"},{deps:["@prisma/client"],label:"Prisma"},{deps:["drizzle-orm"],label:"Drizzle"}];function xc(e){let t=e.some(s=>yc.includes(s)),n=e.some(s=>vc.includes(s));return t&&!n?"client":n&&!t||n&&t?"server":"unknown"}function Sc(e){let t=[];for(let{deps:n,label:s}of wc)n.some(o=>e.includes(o))&&!t.includes(s)&&t.push(s);return t}function ms(e){let t=new Set(["node_modules",".git","dist","build",".next","coverage"]);try{return Bn.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!t.has(n.name)&&!n.name.startsWith(".")).map(n=>we.join(e,n.name))}catch{return[]}}function hs(e,t=null){let n=[e];for(let o of ms(e)){n.push(o);for(let r of ms(o))n.push(r)}let s=[];for(let o of n){let r=mc(o);if(!r||gc(r))continue;let i=hc(r);s.push({name:r.name||we.basename(o),rootPath:o,isRepoRoot:we.resolve(o)===we.resolve(e),kind:xc(i),datastores:Sc(i)})}if(t){let o=new Set(t.map(i=>we.resolve(i))),r=new Set(s.map(i=>we.resolve(i.rootPath)));for(let i of n)we.resolve(i)===we.resolve(e)||r.has(we.resolve(i))||vt(we.relative(e,i)+"/x")||Vt(i,t,o)&&s.push({name:we.basename(i),rootPath:i,isRepoRoot:!1,kind:"client",datastores:[],webRoot:!0})}return s}function rt(e,t){let n=null,s=-1;for(let o of t)o.isRepoRoot&&t.length>1&&!o.ownsLeftovers||(e===o.rootPath||e.startsWith(o.rootPath+we.sep))&&o.rootPath.length>s&&(n=o.name,s=o.rootPath.length);return n}var kc=5,$c=.1;function gs(e,t,n){let s=we.basename(we.resolve(n)),o=a=>({name:a,rootPath:n,isRepoRoot:!0,ownsLeftovers:!0,kind:"unknown",datastores:[]});if(!t.length)return{services:e,added:null};if(!e.length)return{services:[o(s)],added:{name:s,reason:"no package.json found: the repo root is the one service",leftover:t.length}};let r=t.filter(a=>!rt(a,e)).length;if(r<kc||r<$c*t.length)return{services:e,added:null,leftover:r};let i=e.find(a=>a.isRepoRoot);if(i)return i.ownsLeftovers=!0,{services:e,added:{name:i.name,reason:`${r} of ${t.length} files sit outside every nested package: owned by the root package ${i.name}`,leftover:r}};let c=s;return e.some(a=>a.name.toLowerCase()===c.toLowerCase())&&(c=`${s} (root)`),{services:[...e,o(c)],added:{name:c,reason:`${r} of ${t.length} files sit outside every nested package: owned by a service named after the repo folder`,leftover:r}}}function ys(e,t=[]){let n=[];for(let[s,o]of e){let r=Yt(s),i=rt(s,t);n.push({id:`${s}::__module_root__`,name:"module root",filePath:s,startLine:0,endLine:Number.MAX_SAFE_INTEGER,category:r,serviceName:i,type:"moduleRoot",bodyHash:o.moduleBodyHash??null});for(let c of o.functions)n.push({id:Gt(s,c.name),name:c.name,filePath:s,startLine:c.startLine,endLine:c.endLine,params:c.params,returns:c.returns,category:r,serviceName:i,bodyHash:c.bodyHash??null,type:"function"});for(let c of o.arrowFunctions)n.push({id:Gt(s,c.name),name:c.name,filePath:s,startLine:c.startLine,endLine:c.endLine,params:c.params,returns:c.returns,category:r,serviceName:i,bodyHash:c.bodyHash??null,type:"arrowFunction"});for(let c of o.classMethods)n.push({id:Gt(s,`${c.className}.${c.methodName}`),name:c.methodName,className:c.className,filePath:s,startLine:c.startLine,endLine:c.endLine,params:c.params,returns:c.returns,category:r,serviceName:i,bodyHash:c.bodyHash??null,type:"classMethod"})}return n}function Te(e,t){let n=[];for(let r of t.routes??[])r.isInlineHandler&&n.push({item:r,line:r.startLine,key:`route:${String(r.method).toUpperCase()} ${r.path}`});for(let r of t.listeners??[])r.isInlineHandler&&n.push({item:r,line:r.startLine,key:`listener:${r.targetName??"unknown"}.${r.eventName}`});for(let r of t.socketListeners??[])r.isInlineHandler&&n.push({item:r,line:r.startLine,key:`socket:${r.eventName}`});n.sort((r,i)=>r.line-i.line);let s=new Map,o=new Map;for(let{item:r,key:i}of n){let c=(s.get(i)??0)+1;s.set(i,c),o.set(r,`${e}::${i}${c>1?`#${c}`:""}`)}return o}function vs(e,t=[]){let n=[];for(let[s,o]of e){let r=Yt(s),i=rt(s,t),c=t.find(l=>l.name===i),a=Te(s,o);for(let l of o.routes??[]){if(!l.isInlineHandler)continue;let f=`${l.method.toUpperCase()} ${l.path}`;n.push({id:a.get(l),name:`${f} (inline handler)`,filePath:s,startLine:l.handlerStartLine??l.startLine,endLine:l.handlerEndLine??l.startLine,category:r,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:l.handlerBodyHash??null,trigger:{type:"route",label:f,resolvedVia:"inline"}})}for(let l of o.listeners??[])l.isInlineHandler&&n.push({id:a.get(l),name:`${l.eventName} (inline handler)`,filePath:s,startLine:l.handlerStartLine??l.startLine,endLine:l.handlerEndLine??l.startLine,category:r,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:l.handlerBodyHash??null,trigger:{type:"listener",label:l.eventName,resolvedVia:"inline"}});if(c?.kind==="server")for(let l of o.socketListeners??[])l.isInlineHandler&&n.push({id:a.get(l),name:`${l.eventName} (inline handler)`,filePath:s,startLine:l.handlerStartLine??l.startLine,endLine:l.handlerEndLine??l.startLine,category:r,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:l.handlerBodyHash??null,trigger:{type:"socketListener",label:l.eventName,resolvedVia:"inline"}})}return n}import bc from"node:fs";import Nc from"node:crypto";var ws=e=>Nc.createHash("sha256").update(e).digest("hex");function xs(e,t){return e.map(n=>[t(n),ws(bc.readFileSync(n))]).sort((n,s)=>n[0]<s[0]?-1:n[0]>s[0]?1:0)}function Xt(e){return ws(e.map(([t,n])=>`${t}\0${n}`).join(`
|
|
9
|
+
`))}import Dn from"node:path";function Kt(e){let t=Dn.resolve(e),n=t.split(Dn.sep).join("/"),s=[[t.toLowerCase(),t.length,Dn.sep],[n.toLowerCase(),n.length,"/"]],o=Math.max(s[0][1],s[1][1])+1,r=i=>{if(typeof i!="string")return i;let c=i.length>o?i.slice(0,o).toLowerCase():i.toLowerCase();if(c===s[0][0]||c===s[1][0])return".";for(let[a,l,f]of s)if(c.startsWith(a+f)){let y=i.slice(l+1),d=y.indexOf("::");return(d<0?y:y.slice(0,d)).split("\\").join("/")+(d<0?"":y.slice(d))}return i};return{rel:r,repoRoot:n,replacer:(i,c)=>typeof c=="string"?r(c):c,json:(i,c)=>JSON.stringify(i,(a,l)=>typeof l=="string"?r(l):l,c),clone:i=>JSON.parse(JSON.stringify(i,(c,a)=>typeof a=="string"?r(a):a))}}function Ss(e){let t=e.map((s,o)=>({e:s,i:o})).sort((s,o)=>String(s.e.fromNodeId).localeCompare(String(o.e.fromNodeId))||(s.e.line??0)-(o.e.line??0)||(s.e.column??0)-(o.e.column??0)||s.i-o.i),n=new Map;for(let{e:s}of t){let o=s.calleeNameRaw??s.eventName??s.url??"",r=`${s.fromNodeId??"\u2205"} | ${s.callKind??s.type} | ${o}`,i=(n.get(r)??0)+1;n.set(r,i),s.id=`${r} | #${i}`}return e}function ks(e){let t=new Map;for(let n of e)t.has(n.id)||t.set(n.id,[]),t.get(n.id).push(n);for(let[n,s]of t)s.length<2||(s.sort((o,r)=>o.startLine-r.startLine||o.endLine-r.endLine),s.forEach((o,r)=>{r>0&&(o.id=`${n}#${r+1}`)}));return e}function ce(e,t){let n=null;for(let s of t)s.type!=="moduleRoot"&&e>=s.startLine&&e<=s.endLine&&(!n||s.endLine-s.startLine<n.endLine-n.startLine)&&(n=s);return n||t.find(s=>s.type==="moduleRoot")}function $s(e,t){let n=[];for(let[o,r]of e){let i=t.filter(c=>c.filePath===o);for(let c of r.calls){let a=ce(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,calleeNameRaw:c.calleeName,line:c.startLine,column:c.startColumn,branchPath:c.branchPath??[],firstArgText:c.firstArgText??null,deferred:c.deferred??!1,type:"call",callKind:c.callKind??"call",resolved:!1})}for(let c of r.methodCalls){let a=ce(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,calleeNameRaw:c.methodName,objectNameRaw:c.objectName,line:c.startLine,column:c.startColumn,branchPath:c.branchPath??[],firstArgText:c.firstArgText??null,deferred:c.deferred??!1,type:"methodCall",callKind:c.callKind??"methodCall",resolved:!1})}for(let c of r.returnEntries??[]){let a=ce(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,calleeNameRaw:c.label,line:c.startLine,column:c.startColumn,branchPath:c.branchPath??[],deferred:c.deferred??!1,type:"returnValue",resolved:!1})}for(let c of r.jsxElements){let a=ce(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,calleeNameRaw:c.calleeName,line:c.startLine,type:"call",callKind:"jsx",resolved:!1})}for(let c of r.callSites??[]){let a=ce(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,calleeNameRaw:c.calleeName,line:c.startLine,column:c.startColumn,branchPath:c.branchPath??[],firstArgText:c.firstArgText??null,deferred:c.deferred??!1,type:"callSite",callKind:c.callKind,chainHead:c.chainHead??null,chainHeadCalled:c.chainHeadCalled??!1,ctorName:c.ctorName??null,...c.thisProp?{thisProp:c.thisProp,thisMethod:c.thisMethod}:{},resolved:!1})}for(let c of r.socketEmits){let a=ce(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,eventName:c.eventName,line:c.startLine,type:"socketEmit",resolved:!1})}for(let c of r.rawSocketSends??[]){let a=ce(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,eventName:c.eventName,line:c.startLine,type:"rawSocketSend",resolved:!1})}for(let c of r.apiCalls){let a=ce(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,url:c.url,httpMethod:c.method,scope:c.scope,line:c.startLine,type:"apiCall",resolved:!1})}}let s=n.filter(o=>o.type==="apiCall").length;return n}function fe(e,t){let n=new Map;for(let s of t)s.filePath===e&&n.set(s.name,s.id);return n}function Et(e,t,n,s,o=null){if(n.has(e.calleeNameRaw))return{...e,targetNodeId:n.get(e.calleeNameRaw),confidence:.95,matchType:"local",resolved:!0};let r=[...s],i=s.legacySize??r.length,c=([,l])=>{let f=o?o.scopeOf(l):fe(l,t);return f.has(e.calleeNameRaw)?{...e,targetNodeId:f.get(e.calleeNameRaw),confidence:.85,matchType:"import",resolved:!0}:null};for(let l=0;l<i;l++){let f=c(r[l]);if(f)return f}let a=o?.bind?.resolveName(e.fromFileId,e.calleeNameRaw);if(a)return{...e,targetNodeId:a.id,confidence:.85,matchType:"import",resolved:!0};for(let l=i;l<r.length;l++){let f=c(r[l]);if(f)return f}return{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function bs(e,t,n=null){let s=n?n.method(e.objectNameRaw,e.calleeNameRaw):t.find(r=>r.type==="classMethod"&&r.className===e.objectNameRaw&&r.name===e.calleeNameRaw);if(s)return{...e,targetNodeId:s.id,confidence:.6,matchType:"methodHeuristic",resolved:!0};let o=n?.bind?.resolveMember(e.fromFileId,e.objectNameRaw,e.calleeNameRaw);return o?{...e,targetNodeId:o.id,confidence:.85,matchType:"import",resolved:!0}:{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function Ns(e){return{...e,targetNodeId:null,confidence:0,matchType:"unresolvedExternal",resolved:!1}}function Is(e,t,n,s,o=null){if(e.callKind==="new"&&e.ctorName){let r=Et({...e,calleeNameRaw:e.ctorName},t,n,s,o);if(r.resolved)return{...r,calleeNameRaw:e.calleeNameRaw,matchType:r.matchType+"New"};let i=new Set([e.fromFileId,...s.values()]),c=o?o.ctorsOf(e.ctorName).find(a=>i.has(a.filePath)):t.find(a=>a.type==="classMethod"&&a.className===e.ctorName&&a.name==="constructor"&&i.has(a.filePath));return c?{...e,targetNodeId:c.id,confidence:c.filePath===e.fromFileId?.9:.8,matchType:(c.filePath===e.fromFileId?"local":"import")+"New",resolved:!0}:Ns(e)}if(e.callKind==="chainedCall"&&e.chainHead&&e.chainHeadCalled){let r=Et({...e,calleeNameRaw:e.chainHead},t,n,s,o);if(r.resolved)return{...e,targetNodeId:r.targetNodeId,confidence:r.confidence*.8,matchType:"chainHead",resolved:!0}}return Ns(e)}import zn from"node:path";import Ue from"node:fs";import Y from"node:path";var Cs=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Ic=["index.ts","index.tsx","index.mts","index.cts","index.js","index.jsx","index.mjs","index.cjs"],jc={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]};var _s=null,Ls=e=>{_s=e},Ps=()=>_s,js=e=>Y.resolve(e);function Rt(e,t){e=Y.resolve(e);let n=()=>{try{let i=Y.join(e,"package.json");if(!Ue.existsSync(i))return null;let c=JSON.parse(Ue.readFileSync(i,"utf8")).main;if(typeof c!="string")return null;let a=Y.resolve(e,c);return t.has(a)?a:Ec(a,t)}catch{return null}},s=Y.extname(e);if(s&&t.has(e))return e;let o=jc[s];if(o)for(let i of o){let c=e.slice(0,-s.length)+i;if(t.has(c))return c}for(let i of Cs)if(t.has(e+i))return e+i;let r=n();if(r)return r;for(let i of Ic){let c=Y.join(e,i);if(t.has(c))return c}return null}function Ec(e,t){if(Y.extname(e)&&t.has(e))return e;for(let s of Cs)if(t.has(e+s))return e+s;return null}var Hn=e=>{try{let n=Ue.readFileSync(e,"utf8").replace(/^/,"").replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,(s,o)=>o??"");return JSON.parse(n.replace(/,(\s*[}\]])/g,"$1"))}catch{return null}};function Ms(e,t=new Set){if(t.has(e))return{baseUrl:null,paths:null};t.add(e);let n=Hn(e);if(!n)return{baseUrl:null,paths:null};let s=null,o=null,r=n.extends?Array.isArray(n.extends)?n.extends:[n.extends]:[];for(let c of r){if(typeof c!="string"||!c.startsWith("."))continue;let a=Y.resolve(Y.dirname(e),c);(!Ue.existsSync(a)||Ue.statSync(a).isDirectory())&&(a=Ue.existsSync(a+".json")?a+".json":Y.join(a,"tsconfig.json"));let l=Ms(a,t);l.baseUrl&&(s=l.baseUrl),l.paths&&(o=l.paths)}let i=n.compilerOptions??{};if(typeof i.baseUrl=="string"&&(s=Y.resolve(Y.dirname(e),i.baseUrl)),i.paths&&typeof i.paths=="object"){let c=s??Y.dirname(e);o=Object.entries(i.paths).map(([a,l])=>{let f=a.indexOf("*");return{prefix:f<0?a:a.slice(0,f),suffix:f<0?"":a.slice(f+1),wildcard:f>=0,targets:(Array.isArray(l)?l:[]).filter(y=>typeof y=="string").map(y=>Y.resolve(c,y))}}).sort((a,l)=>l.prefix.length-a.prefix.length)}return{baseUrl:s,paths:o}}function Rc(e,t){if(t=t.replace(/^\.\//,"").replace(/\/+$/,""),t.startsWith("!"))return[];let n=[],s=o=>{try{return Ue.readdirSync(o,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="node_modules"&&!r.name.startsWith(".")).map(r=>Y.join(o,r.name))}catch{return[]}};if(t.endsWith("/**")){let o=Y.join(e,t.slice(0,-3)),r=i=>{for(let c of s(i))n.push(c),r(c)};r(o)}else t.endsWith("/*")?n.push(...s(Y.join(e,t.slice(0,-2)))):t.includes("*")||n.push(Y.join(e,t));return n}function Cc(e){let t=[],s=Hn(Y.join(e,"package.json"))?.workspaces;Array.isArray(s)?t.push(...s):Array.isArray(s?.packages)&&t.push(...s.packages);try{let o=Ue.readFileSync(Y.join(e,"pnpm-workspace.yaml"),"utf8"),r=!1;for(let i of o.split(/\r?\n/)){if(/^packages\s*:/.test(i)){r=!0;continue}if(r){let c=/^\s*-\s*['"]?([^'"#\s]+)['"]?/.exec(i);c?t.push(c[1]):/^\S/.test(i)&&(r=!1)}}}catch{}return t}function Es(e,t){if(e==null)return null;let n=o=>{if(typeof o=="string")return o;if(Array.isArray(o)){for(let r of o){let i=n(r);if(i)return i}return null}if(o&&typeof o=="object"){for(let r of["source","import","module","default","require","node"])if(r in o){let i=n(o[r]);if(i)return i}}return null};if(typeof e=="string"||Array.isArray(e))return t==="."?n(e):null;let s=Object.keys(e);if(!s.some(o=>o.startsWith(".")))return t==="."?n(e):null;if(e[t]!=null)return n(e[t]);for(let o of s){let r=o.indexOf("*");if(r>0&&t.startsWith(o.slice(0,r))&&t.endsWith(o.slice(r+1))){let i=n(e[o]);if(i)return i.replace("*",t.slice(r,t.length-(o.length-r-1)))}}return null}function Os(e,t,n={}){let s=js(e),o=new Set(t),r=new Map,i=d=>{if(r.has(d))return r.get(d);let w=null,p=Y.join(d,"tsconfig.json");return Ue.existsSync(p)?w=Ms(p):d!==s&&Y.dirname(d)!==d&&d.startsWith(s)&&(w=i(Y.dirname(d))),r.set(d,w),w},c=new Map;for(let d of Cc(s))for(let w of Rc(s,d)){let p=Hn(Y.join(w,"package.json"));p?.name&&!c.has(p.name)&&c.set(p.name,{dir:js(w),pkg:p})}let a=[...c.keys()].sort((d,w)=>w.length-d.length),l=(d,w,p)=>{let{dir:$,pkg:j}=c.get(d),g=[],k=b=>{if(!b)return;let S=Y.resolve($,b);g.push(S);let m=Y.relative($,S).split(Y.sep);["dist","build","lib","out","esm","cjs"].includes(m[0])&&g.push(Y.join($,"src",...m.slice(1)))};if(w==="."){k(Es(j.exports,"."));for(let b of["source","module","main"])typeof j[b]=="string"&&k(j[b]);g.push(Y.join($,"src","index"),Y.join($,"index"))}else k(Es(j.exports,w)),g.push(Y.join($,w),Y.join($,"src",w));for(let b of g){let S=Rt(b,p);if(S)return S}return null},f=d=>a.find(w=>d===w||d.startsWith(w+"/"))??null,y=(d,w)=>w?.paths?.some(p=>p.wildcard?d.startsWith(p.prefix)&&d.endsWith(p.suffix)&&d.length>=p.prefix.length+p.suffix.length:d===p.prefix)??!1;return{root:s,files:o,packages:c,isInternal(d,w){if(d.startsWith(".")||f(d))return!0;let p=i(Y.dirname(w));return!!(y(d,p)||p?.baseUrl&&!d.startsWith("@")&&Rt(Y.join(p.baseUrl,d),o))},resolve(d,w,p){if(d.startsWith("."))return Rt(Y.resolve(Y.dirname(w),d),p);let $=i(Y.dirname(w));if($?.paths&&n.paths!==!1)for(let g of $.paths){let k=null;if(g.wildcard?d.startsWith(g.prefix)&&d.endsWith(g.suffix)&&d.length>=g.prefix.length+g.suffix.length&&(k=d.slice(g.prefix.length,d.length-g.suffix.length)):d===g.prefix&&(k=""),k!=null){for(let b of g.targets){let S=Rt(b.replace("*",k),p);if(S)return S}break}}let j=n.workspaces===!1?null:f(d);if(j){let g=l(j,d===j?".":"./"+d.slice(j.length+1),p);if(g)return g}if($?.baseUrl&&n.paths!==!1){let g=Rt(Y.join($.baseUrl,d),p);if(g)return g}return null}}}var Rs=new WeakMap;function As(e){if(e instanceof Set)return e;let t=Rs.get(e);return t||Rs.set(e,t=new Set(e)),t}var Ts=new WeakMap;function _c(e){let t=Ts.get(e);return(!t||t.n!==e.length)&&(t={n:e.length,set:new Set(e)},Ts.set(e,t)),t.set}function Wn(e,t,n){if(!e.startsWith("."))return null;let s=zn.dirname(t),o=zn.resolve(s,e),r=[o,...is().map(i=>`${o}${i}`),...cs().map(i=>zn.join(o,i))];for(let i of r)if(_c(n).has(i))return i;return null}function ye(e,t,n){let s=Wn(e,t,n);if(s)return s;let o=Ps();return o?o.resolve(e,t,As(n)):null}function wt(e,t,n){let s=new Map;for(let o of t){let r=Wn(o.source,e,n);r&&s.set(o.source,r)}s.legacySize=s.size;for(let o of t){if(s.has(o.source))continue;let r=ye(o.source,e,n);r&&s.set(o.source,r)}return s}function Fs(e){let t=new Map,n=new Map,s=new Map;for(let o of e){if(o.type!=="classMethod")continue;let r=o.className+"\0"+o.name;n.has(r)||n.set(r,o),o.name==="constructor"&&(s.has(o.className)||s.set(o.className,[]),s.get(o.className).push(o))}return{scopeOf:o=>{let r=t.get(o);return r||(r=fe(o,e),t.set(o,r)),r},method:(o,r)=>n.get(o+"\0"+r),ctorsOf:o=>s.get(o)??[]}}function xt(e){return e?e.split("?")[0].split("/").map(t=>t.startsWith(":")||/^\d+$/.test(t)?"*":t).join("/"):""}var Lc=new Set(["function","arrowFunction"]);function Bs(e,t,n,s){let o=new Map;for(let l of t){let f=o.get(l.filePath);f||o.set(l.filePath,f=[]),f.push(l)}let r=new Set;for(let l of s)l.resolved&&l.fromNodeId&&l.targetNodeId&&r.add(l.fromNodeId+"\0"+l.targetNodeId);let i=(l,f)=>(o.get(l)??[]).find(y=>Lc.has(y.type)&&f(y))??null,c=[];c.argBindings=[];let a=(l,f,y,d,w,p,$)=>{!f||!y||f.id===y.id||r.has(f.id+"\0"+y.id)||c.push({fromFileId:l,fromNodeId:f.id,calleeNameRaw:d,line:w,column:p,branchPath:[],firstArgText:null,deferred:!1,type:"reference",callKind:"reference",targetNodeId:y.id,confidence:$==="local"?.95:.85,matchType:$,resolved:!0})};for(let[l,f]of e){let y=o.get(l);if(y){for(let d of f.refArgs??[]){let w=null,p="local";if(d.b==="fn"?w=i(l,j=>j.name===d.name&&j.startLine===d.declLine):d.b==="import"&&(p="import",(d.ik==="default"||d.ik==="named"||d.ik==="cjs")&&(w=n.nodeForImport(l,d.src,d.ik,d.imp))),!w)continue;let $=ce(d.line,y);a(l,$,w,d.name,d.line,d.column,p),d.callLine!=null&&$&&$.id!==w.id&&c.argBindings.push({file:l,line:d.callLine,column:d.callColumn,targetNodeId:w.id,matchType:p,direct:d.via==="arg"})}for(let d of y){if(d.type!=="inlineHandler")continue;let w=null;for(let p of y)p===d||p.type==="moduleRoot"||p.startLine<=d.startLine&&p.endLine>=d.endLine&&!(p.startLine===d.startLine&&p.endLine===d.endLine)&&(!w||p.endLine-p.startLine<w.endLine-w.startLine)&&(w=p);w??=y.find(p=>p.type==="moduleRoot"),a(l,w,d,d.name,d.startLine,0,"local")}}}return c}function Ds(e,t,n,s){let o=new Map,r=new Map;for(let c of e){if(r.set(c.id,c),c.type!=="classMethod")continue;let a=c.filePath+"\0"+c.className+"\0"+c.name,l=o.get(a);l?l.push(c):o.set(a,[c])}let i=(c,a)=>{for(let l of o.keys())if(l.startsWith(c+"\0"+a+"\0"))return!0;return!1};return function(a){let l=r.get(a.fromNodeId);if(!l||l.type!=="classMethod")return null;let f=t.get(a.fromFileId),y=(f?.classProps??[]).find(j=>j.className===l.className&&j.prop===a.thisProp);if(!y)return null;let d=null,w=null,p=(f.importBindings??[]).find(j=>j.local===y.type);if(p){let j=p.kind==="default"||p.kind==="named"?s.resolveImport(a.fromFileId,p.source,p.kind,p.imported):null;j?.local&&j.local!=="default"&&(d=j.file,w=j.local)}else i(a.fromFileId,y.type)&&(d=a.fromFileId,w=y.type);if(!d)return null;let $=o.get(d+"\0"+w+"\0"+a.thisMethod);return!$||$.length!==1?null:{...a,targetNodeId:$[0].id,confidence:.9,matchType:"typedProperty",resolved:!0}}}var Pc=new Set(["function","arrowFunction"]);function Zt(e,t,n){let s=new Map;for(let f of e){if(!Pc.has(f.type))continue;let y=f.filePath+"\0"+f.name;s.has(y)||s.set(y,f)}let o=new Map,r=(f,y)=>{let d=o.get(f);if(!d){d=new Map;for(let w of t.get(f)?.importBindings??[])d.has(w.local)||d.set(w.local,w);o.set(f,d)}return d.get(y)??null},i=(f,y)=>n(f).get(y)??null;function c(f,y,d=new Set){let w=f+"\0"+y;if(d.has(w))return null;d.add(w);let p=t.get(f)?.exportBindings;if(!p)return null;if(y==="default"){if(p.default)return{file:f,local:p.default==="<anon>"?"default":p.default}}else if(p.named?.[y])return{file:f,local:p.named[y]};for(let $ of p.reexports??[]){if($.exported!==y)continue;let j=i(f,$.source);if(j)return c(j,$.imported,d)}for(let $ of p.nsReexports??[]){if($.exported!==y)continue;let j=i(f,$.source);if(j)return{moduleFile:j}}if(y!=="default")for(let $ of p.stars??[]){let j=i(f,$),g=j?c(j,y,d):null;if(g)return g}return null}let a=f=>f?.local?s.get(f.file+"\0"+f.local)??null:null;function l(f,y,d,w){let p=i(f,y);return p?d==="default"?c(p,"default"):d==="named"?c(p,w):{moduleFile:p,cjs:d==="cjs"}:null}return{lookupExport:c,resolveImport:l,nodeForImport(f,y,d,w){let p=l(f,y,d,w);return p?.moduleFile&&p.cjs?a(c(p.moduleFile,"default")):a(p)},resolveName(f,y){let d=r(f,y);return d?this.nodeForImport(f,d.source,d.kind,d.imported):null},resolveMember(f,y,d){let w=r(f,y);if(!w)return null;let p=l(f,w.source,w.kind,w.imported);return p?.moduleFile?a(c(p.moduleFile,d)):null},classForImport(f,y){let d=r(f,y);if(!d)return null;let w=l(f,d.source,d.kind,d.imported);return w?.local?{file:w.file,className:w.local==="default"?null:w.local}:null},bindingFor:r}}function Hs(e,t,n,s,o,r,i){let c=[],a=Fs(t),l=new Map,f=g=>l.get(g)??wt(g,n.get(g)?.imports??[],s);a.bind=Zt(t,n,f);let y=Ds(t,n,f,a.bind),d=new Map;for(let g of e)d.has(g.fromFileId)||d.set(g.fromFileId,[]),d.get(g.fromFileId).push(g);for(let[g,k]of d){let b=n.get(g),S=fe(g,t),m=wt(g,b.imports,s);l.set(g,m);for(let u of k)if(u.type==="call")c.push(Et(u,t,S,m,a));else if(u.type==="methodCall")c.push(bs(u,t,a));else if(u.type==="callSite")c.push((u.thisProp?y(u):null)??Is(u,t,S,m,a));else if(u.type==="returnValue")c.push({...u,targetNodeId:null,confidence:0,matchType:"returnValue",resolved:!1});else if(u.type==="apiCall")if(u.scope==="external")c.push({...u,targetNodeId:null,confidence:null,matchType:"externalService",resolved:!1});else{let x=xt(u.url),h=o.get(x);h?c.push({...u,targetNodeId:h,confidence:.5,matchType:"crossLayer",resolved:!0}):c.push({...u,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(u.type==="socketEmit"){let x=r.get(u.eventName);x?c.push({...u,targetNodeId:x,confidence:.5,matchType:"crossLayer",resolved:!0}):c.push({...u,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(u.type==="rawSocketSend"){let x=i?.get(u.eventName);x?c.push({...u,targetNodeId:x,confidence:.5,matchType:"crossLayer",resolved:!0}):c.push({...u,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}}let w=Bs(n,t,a.bind,c);for(let g of w)c.push(g);let p=new Map;for(let g of c){if(g.resolved||g.line==null||g.type!=="call"&&g.type!=="methodCall"&&g.type!=="callSite")continue;let k=g.fromFileId+" "+g.line+" "+g.column;(p.get(k)??p.set(k,[]).get(k)).push(g)}let $=[...w.argBindings].sort((g,k)=>k.direct-g.direct),j=new Set;for(let g of $){let k=g.file+" "+g.line+" "+g.column;if(j.has(k))continue;let b=(p.get(k)??[]).find(S=>S.fromNodeId!==g.targetNodeId);b&&(j.add(k),Object.assign(b,{targetNodeId:g.targetNodeId,confidence:g.matchType==="local"?.95:.85,matchType:"argument",resolved:!0,viaArgument:!0}))}return c}function zs(e){let t=new Map,n=new WeakMap,s=a=>{if(typeof a=="string")return a.length>=20?"s"+a:null;if(a&&typeof a=="object"){let l=n.get(a);if(l===void 0){let f=JSON.stringify(a);l=f.length>=40?"j"+f:"",n.set(a,l)}return l||null}return null};(function a(l){let f=s(l);if(f){let y=t.get(f)??0;if(t.set(f,y+1),y>0)return}if(Array.isArray(l))for(let y of l)a(y);else if(l&&typeof l=="object")for(let y of Object.values(l))a(y)})(e);let o=[],r=new Map,i=a=>{let l=s(a),f=l&&t.get(l)>1;if(f&&r.has(l))return r.get(l);let y;if(typeof a=="string"?y=JSON.stringify(a):Array.isArray(a)?y="["+a.map(i).join(",")+"]":a&&typeof a=="object"?y="{"+Object.entries(a).map(([w,p])=>JSON.stringify(w)+":"+i(p)).join(",")+"}":y=JSON.stringify(a),!f)return y;let d="$"+o.length.toString(36);return o.push(`const ${d}=${y};`),r.set(l,d),d},c=i(e);return`(() => {${o.join(`
|
|
10
10
|
`)}
|
|
11
|
-
return ${c};})()`}function Hn(e,t,n,s){if(!e)return{targetId:null,via:null};if(n.has(e))return{targetId:n.get(e),via:"in-file"};if(s)for(let[,o]of s){let r=ae(o,t);if(r.has(e))return{targetId:r.get(e),via:"cross-file"}}return{targetId:null,via:null}}function Hs(e,t,n,s,o,r=[],i=null){if(!n.some(a=>!a.isInlineHandler)&&!s.some(a=>!a.isInlineHandler)&&!r.some(a=>!a.isInlineHandler))return e;let c=e.map(a=>({...a}));for(let a of n){if(a.isInlineHandler)continue;let l=a.nest?e.find(u=>u.type==="classMethod"&&u.filePath===t&&u.className===a.nest.className&&u.name===a.nest.methodName):null,{targetId:f,via:h}=a.nest?{targetId:l?.id??null,via:"in-file"}:Hn(a.handlerName,e,o,i);if(f){let u=c.find(v=>v.id===f);u&&(u.isEntryPoint=!0,u.trigger={type:"route",label:`${a.method.toUpperCase()} ${a.path}`,resolvedVia:h})}}for(let a of s){if(a.isInlineHandler)continue;let{targetId:l,via:f}=Hn(a.handlerName,e,o,i);if(l){let h=c.find(u=>u.id===l);h&&(h.isEntryPoint=!0,h.trigger={type:"listener",label:a.eventName,resolvedVia:f})}}for(let a of r){if(a.isInlineHandler)continue;let{targetId:l,via:f}=Hn(a.handlerName,e,o,i);if(l){let h=c.find(u=>u.id===l);h&&(h.isEntryPoint=!0,h.trigger={type:"socketListener",label:a.eventName,resolvedVia:f})}}return c}function zn(e){let t=new Map,n=new Map;for(let s of e)s.resolved&&(t.set(s.fromNodeId,(t.get(s.fromNodeId)??0)+1),n.set(s.targetNodeId,(n.get(s.targetNodeId)??0)+1));return{outgoing:t,incoming:n}}function zs(e,t,n=zn(t)){if(e.type==="moduleRoot")return 0;let s=n.outgoing.get(e.id)??0,o=n.incoming.get(e.id)??0,r=e.exported?1.5:1;return s/(o+1)*r}function Us(e,t){let n=zn(t),s=new Set;for(let i of e)n.incoming.has(i.id)&&s.add(i.filePath);let r=e.filter(i=>!(i.isEntryPoint||i.type==="moduleRoot"||!n.incoming.has(i.id)&&s.has(i.filePath))).map(i=>({...i,fallbackScore:zs(i,t,n)}));return r.sort((i,c)=>c.fallbackScore-i.fallbackScore),r.slice(0,15)}function Un(e){let t=new Map;for(let n of e)!n.resolved||!n.fromNodeId||!n.targetNodeId||(t.has(n.fromNodeId)||t.set(n.fromNodeId,[]),t.get(n.fromNodeId).push({targetNodeId:n.targetNodeId,line:n.line??null,column:n.column??null,branchPath:n.branchPath??[],edgeType:n.type}));return t}function Wn(e,t,n,s=8){let o=new Set([e]),r=a=>n.find(l=>l.id===a)?.category??"unknown",i=[{nodeId:e,depth:0,parentNodeId:null,category:r(e)}],c=[{nodeId:e,depth:0}];for(;c.length>0;){let a=c.shift();if(a.depth>=s)continue;let l=t.get(a.nodeId)||[];for(let f of l){let h=f.targetNodeId;if(o.has(h))continue;o.add(h);let u={nodeId:h,depth:a.depth+1,parentNodeId:a.nodeId,category:r(h),callLine:f.line,callColumn:f.column,branchPath:f.branchPath,edgeType:f.edgeType};i.push(u),c.push(u)}}return i}function Ws(e,t,n,s=null){return t.filter(r=>r.filePath===e.filePath&&r.id!==e.id&&r.type!=="moduleRoot").filter(r=>!(s?s.has(r.id):n.some(c=>c.resolved&&c.targetNodeId===r.id)))}var qs=new WeakMap,Gs=new WeakMap;function _c(e){let t=qs.get(e);if(t&&t.length===e.length)return t;let n=new Set,s=new Set,o=new Map;for(let r of e)r.resolved&&(r.targetNodeId===void 0||r.targetNodeId===null||(s.add(r.targetNodeId),r.matchType==="crossLayer"&&n.add(r.targetNodeId)),o.set(r.fromNodeId,(o.get(r.fromNodeId)??0)+1));return t={length:e.length,crossLayerTargets:n,incoming:s,outgoing:o},qs.set(e,t),t}function Cc(e,t,n){let s=Gs.get(e);if(s&&s.length===e.length&&s.edgesRef===n)return s.calledByFile;let o=new Map;for(let r of e){if(r.type==="moduleRoot"||!n.incoming.has(r.id))continue;let i=o.get(r.filePath);i||o.set(r.filePath,i=new Set),i.add(r.id)}return Gs.set(e,{length:e.length,edgesRef:n,calledByFile:o}),o}function Js(e,t,n){if(e.type==="moduleRoot")return!1;let s=_c(t);if(s.crossLayerTargets.has(e.id)||(s.outgoing.get(e.id)??0)>=4||new Set((e.returns||[]).map(a=>a.condition).filter(a=>a!==null)).size>=3)return!0;if(s.incoming.has(e.id)){let a=Cc(n,t,s).get(e.filePath);if(!(!!a&&a.size-(a.has(e.id)?1:0)>0)){let f=Ws(e,n,t,s.incoming);if(f.length>0)return e.lexicalSiblings=f.map(h=>h.id),!0}}return!1}function Ys(e,t,n,s,o=8,r=null){let i=[],c=new Set(e.map(f=>f.id)),a=[...e],l=new Map;for(let f of n)l.has(f.id)||l.set(f.id,f);for(;a.length>0;){let f=a.shift(),h=Wn(f.id,t,n,o);i.push({entryPointId:f.id,entryPointName:f.name,trigger:f.trigger??null,steps:h});let u=r?new Set(Wn(f.id,r,n,o).map(v=>v.nodeId)):null;for(let v of h){if(u&&!u.has(v.nodeId)||v.nodeId===f.id||c.has(v.nodeId))continue;let d=l.get(v.nodeId);d&&Js(d,s,n)&&(c.add(d.id),v.hasOwnSubTrace=!0,d.lexicalSiblings&&(v.lexicalSiblings=d.lexicalSiblings),a.push({id:d.id,name:d.name,trigger:null}))}}return i}function Vs(e,t,n=is){return e.filter((s,o)=>{if(o===0)return!0;let r=t.find(i=>i.id===s.nodeId);return r?!n.some(i=>r.name.toLowerCase().includes(i)):!0})}function Xs(e){return e.steps.filter(n=>n.depth>0).map(n=>n.nodeId).sort().join(" | ")}function Ks(e){let t=new Map;for(let n of e){let s=Xs(n),o=s===""?`__no_calls__${n.entryPointName}`:s;t.has(o)||t.set(o,[]),t.get(o).push(n)}return t}function Zs(e){let t=e[0];return{steps:t.steps,entryPointNames:e.map(n=>n.entryPointName),occurrences:e.length,name:t.entryPointName,trigger:t.trigger,tier:e.some(n=>n.origin==="physical")?"physical":"guessed",tierOrigin:e.some(n=>n.origin==="physical")?"physical":t.origin}}import Zt from"node:path";function Qs(e){if(!e.trigger)return null;if(e.trigger.type==="route")return`${e.trigger.label.split(" ")[1].split("/").filter(Boolean).join(" ").replace(/[-_]/g," ").split(" ").map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")} Flow`;if(e.trigger.type==="listener"){let t=e.trigger.label;return`${t.charAt(0).toUpperCase()+t.slice(1)} Flow`}return null}function er(e){return e.name.replace(/([A-Z])/g," $1").trim().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}var tr=60,Lc=24;function nr(e,t=null){let n=e.map(s=>{let o=Qs(s),r=s.trigger?.workflowName??o??er(s);return{...s,name:r}});return t?.nodes?Oc(n,t.nodes):n}var qn=(e,t)=>e.length>t?e.slice(0,t-1)+"\u2026":e,Pc=new Set(["function","arrowFunction","classMethod"]);function Mc(e){let t=new Map(e.map(o=>[o.id,o])),n=new Map,s=o=>{let r=n.get(o);return r||(r=e.filter(i=>i.filePath===o&&Pc.has(i.type)),n.set(o,r)),r};return o=>{let r=t.get(o.steps[0].nodeId);if(!r)return[null,null,null];let i=null;if(r.type==="classMethod")i=r.className;else{let l=null;for(let f of s(r.filePath))f===r||!(f.startLine<=r.startLine&&f.endLine>=r.endLine)||f.startLine===r.startLine&&f.endLine===r.endLine||(!l||f.endLine-f.startLine<l.endLine-l.startLine)&&(l=f);l&&(i=l.type==="classMethod"?l.className:l.name)}let c=null;if(o.trigger?.type==="route")c=String(o.trigger.label).split(" ")[0];else if(o.trigger?.type==="listener"){let l=/::listener:([^.#]+)\./.exec(r.id);l&&(c=l[1])}let a=Zt.basename(r.filePath,Zt.extname(r.filePath));return a==="index"&&(a=Zt.basename(Zt.dirname(r.filePath))),[i||null,c||null,a||null]}}var Tc=(e,t)=>{let n=t.map(s=>qn(s,Lc)).join(", ");return e.endsWith(")")?e.slice(0,-1)+", "+n+")":e+" ("+n+")"};function Oc(e,t){let n=Mc(t),s=e.map(i=>({w:i,base:i.name,parts:[],used:new Set,stuck:!1,q:null})),o=i=>i.parts.length?Tc(i.base,i.parts):i.base,r=()=>{let i=new Map;for(let c of s){let a=o(c);(i.get(a)??i.set(a,[]).get(a)).push(c)}return[...i.values()].filter(c=>c.length>1)};for(let i=0;i<4;i++){let c=!1;for(let a of r()){if(a.some(u=>u.stuck))continue;for(let u of a)u.q??=n(u.w);let l=[0,1,2].filter(u=>a.every(v=>!v.used.has(u))),f=l.find(u=>new Set(a.map(v=>v.q[u]??"")).size>1),h=f!==void 0;if(h||(f=l.find(u=>a.every(v=>v.q[u]))),f===void 0){for(let u of a)u.stuck=!0;continue}for(let u of a)u.used.add(f),u.q[f]&&u.parts.push(u.q[f]),h||(u.stuck=!0);c=!0}if(!c)break}for(let i of r())i.sort((c,a)=>c.w.steps[0].nodeId<a.w.steps[0].nodeId?-1:c.w.steps[0].nodeId>a.w.steps[0].nodeId?1:0),i.forEach((c,a)=>{a>0&&(c.suffix=` (${a+1})`)});return s.map(i=>{let c=o(i);return i.suffix&&(c=qn(c,tr-i.suffix.length)+i.suffix),{...i.w,name:qn(c,tr)}})}var Ac=e=>e;function or(e,t){let n=new Map;for(let[s,o]of e){let r=t.filter(l=>l.filePath===s);if(r[0]?.category!=="backend")continue;let i=o.routes??[],c=Me(s,o),a=ae(s,t);for(let l of i){let f=xt(l.path);if(l.isInlineHandler){let u=c.get(l);n.set(f,u);continue}if(l.nest){let u=Ac(r).find(v=>v.type==="classMethod"&&v.className===l.nest.className&&v.name===l.nest.methodName);u&&n.set(f,u.id);continue}if(!l.handlerName||!a.has(l.handlerName))continue;let h=a.get(l.handlerName);n.set(f,h)}}return n}import rt from"node:fs";import Q from"node:path";var Qt=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Fc=/(^|\/)(dist|build|out|built|compiled|esm|cjs|lib|output)(\/|$)/,sr=/(^|\/)(dist|build|out|built|compiled|esm|cjs|output)(\/|$)/,Bc=/\b(esbuild|tsup|tsdown|tsc|rollup|webpack|ncc|swc|babel|vite|parcel|bun\s+build|pkg|unbuild|microbundle|rspack)\b/,Dc=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild|rspack)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Te=e=>{try{return rt.statSync(e).isFile()}catch{return!1}},Gn=e=>e.split(Q.sep).join("/"),Jn=e=>{if(Te(e)&&Qt.includes(Q.extname(e))&&!/\.d\.ts$/.test(e))return e;let t=e.replace(/\.(m|c)?js$/,"");for(let n of Qt)if(Te(t+n)&&!/\.d\.ts$/.test(t+n))return t+n;return null},en=(e,t)=>{let n=Q.relative(e,t);return n&&!n.startsWith("..")&&!Q.isAbsolute(n)&&!/(^|[\\/])node_modules([\\/]|$)/.test(n)};function Hc(e,t){let n=Te(t+".map")?t+".map":null;if(!n&&Te(t))try{let c=rt.readFileSync(t,"utf8").slice(-400),a=/sourceMappingURL=([^\s*]+)/.exec(c);if(a&&!a[1].startsWith("data:")){let l=Q.resolve(Q.dirname(t),a[1]);Te(l)&&(n=l)}}catch{}if(!n)return null;let s;try{s=JSON.parse(rt.readFileSync(n,"utf8"))}catch{return null}let o=Q.resolve(Q.dirname(n),s.sourceRoot??""),r=(s.sources??[]).map(c=>Q.resolve(o,c)).filter(c=>en(e,c)&&Te(c)&&Qt.includes(Q.extname(c)));if(r.length===1)return r[0];let i=Q.basename(t).replace(/\.(m|c)?js$/,"");return r.find(c=>Q.basename(c).replace(/\.[^.]+$/,"")===i)??null}function zc(e){try{return JSON.parse(rt.readFileSync(e,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,"").replace(/,(\s*[}\]])/g,"$1"))}catch{return null}}function Uc(e,t){for(let n of["tsconfig.build.json","tsconfig.json"]){let o=zc(Q.join(e,n))?.compilerOptions;if(!o?.outDir)continue;let r=Gn(Q.normalize(o.outDir)).replace(/^\.\//,"").replace(/\/$/,"");if(!(t===r||t.startsWith(r+"/")))continue;let i=t.slice(r.length+1),c=o.rootDir?o.rootDir:rt.existsSync(Q.join(e,"src"))?"src":".",a=Jn(Q.resolve(e,c,i));if(a)return a}return null}function Wc(e,t){let n=t.split("/"),s=n.findIndex(r=>/^(dist|build|out|built|compiled|esm|cjs|lib|output)$/.test(r));if(s<0)return null;let o=n.slice(s+1).join("/");for(let r of["src","source","sources"]){let i=Jn(Q.resolve(e,...n.slice(0,s),r,o));if(i&&en(e,i))return i}return null}function qc(e,t,n){let s=Q.basename(n).replace(/\.(m|c)?js$/,"");for(let o of["build","compile","bundle","prepare","prepublishOnly","prepack","postinstall"]){let r=t.scripts?.[o];if(!r||!Bc.test(r))continue;let i=[];for(let l of r.split(/\s+/).map(f=>f.replace(/^["']|["']$/g,"").replace(/^--?[\w-]+=/,""))){if(!Qt.includes(Q.extname(l))||/\.d\.ts$/.test(l))continue;let f=Q.resolve(e,l);Te(f)&&en(e,f)&&!sr.test(Gn(Q.relative(e,f)))&&i.push(f)}let c=[...new Set(i)];if(c.length===1)return c[0];let a=c.filter(l=>Q.basename(l).replace(/\.[^.]+$/,"")===s);if(a.length===1)return a[0];if(c.length)return c[0]}return null}function Gc(e,t){let n=[];try{n=rt.readdirSync(e).filter(i=>Dc.test(i)).sort()}catch{return null}let s=Q.basename(t).replace(/\.(m|c)?js$/,""),o=[];for(let i of n){let c;try{c=rt.readFileSync(Q.join(e,i),"utf8")}catch{continue}for(let a of c.matchAll(/\bentry(?:Points)?\s*:\s*[[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/g)){let l=Jn(Q.resolve(e,a[1]));l&&en(e,l)&&o.push(l)}}let r=[...new Set(o)];return r.length===1?r[0]:r.find(i=>Q.basename(i).replace(/\.[^.]+$/,"")===s)??null}function tn(e,t,n){if(typeof t!="string"||!t)return null;let s=Gn(Q.normalize(t)).replace(/^\.\//,""),o=Q.resolve(e,s);if(!Fc.test(s)||Te(o)&&!sr.test(s)||Te(o)&&/\.ts$/.test(o))return null;let i=[["sourcemap",()=>Hc(e,o)],["tsconfig outDir",()=>Uc(e,s)],["convention",()=>Te(o)?null:Wc(e,s)],["build script",()=>qc(e,n??{},s)],["build config",()=>Gc(e,s)]];for(let[c,a]of i){let l=null;try{l=a()}catch{}if(l&&l!==o)return{file:l,how:c}}return null}function rr(e,t){let n=new Map;for(let[s,o]of e){let r=o.socketListeners??[],i=Me(s,o),c=ae(s,t);for(let a of r){if(a.isInlineHandler){let f=i.get(a);n.set(a.eventName,f);continue}if(!a.handlerName||!c.has(a.handlerName))continue;let l=c.get(a.handlerName);n.set(a.eventName,l)}}return n}import Yn from"node:fs";import W from"node:path";var ke=e=>String(e??"").trim().replace(/^["']|["']$/g,""),nn=e=>e.replace(/^\s*#.*$/,"").replace(/\s+#.*$/,"");function ir(e){let t=/^(\/[A-Za-z0-9_\-./]*?)\/?(?=$|[:(*{[])/.exec(String(e).trim()),n=t?t[1]:"";return n==="/"?"":n.replace(/\/+$/,"")}function cr(e,t){let n=e.split(/\r?\n/).map(nn),s=v=>v.length-v.trimStart().length,o=[],r=null,i=!1,c=null,a=!1,l=0,f=null,h=()=>{f?.key&&f.fromService&&f.fromService!=="?"&&r.hostRefs.push({name:f.key,service:f.fromService,property:f.property}),f=null},u=(v,d,k)=>{d==="name"?v.name=ke(k):d==="rootDir"?v.rootDir=ke(k):d==="startCommand"&&(v.startCommand=ke(k))};for(let v of n){if(!v.trim())continue;let d=s(v),k=v.trim();if(d===0){h(),r=null,a=!1,i=/^services\s*:/.test(k),c=null;continue}if(!i)continue;let j=k.startsWith("-");if(j&&(c==null||d===c)){c=d,h(),r={name:null,rootDir:null,startCommand:null,kept:[],hostRefs:[]},o.push(r),a=!1;let S=/^-\s*([A-Za-z]+)\s*:\s*(.*)$/.exec(k);S&&u(r,S[1],S[2]);continue}if(!r)continue;let p=/^(?:-\s*)?([A-Za-z]+)\s*:\s*(.*)$/.exec(k);if(p){if(p[1]==="envVars"){h(),a=!0,l=d;continue}if(a&&d>l){if(j&&(h(),f={key:null,fromService:null,property:null}),!f)continue;if(p[1]==="key")f.key=ke(p[2]);else if(p[1]==="value"&&f.key){let S=We(f.key,ke(p[2]),t);S&&r.kept.push(S)}else p[1]==="fromService"?f.fromService="?":p[1]==="name"&&f.fromService==="?"?f.fromService=ke(p[2]):p[1]==="property"&&(f.property=ke(p[2]));continue}a&&(h(),a=!1),u(r,p[1],p[2])}}return h(),o.filter(v=>v.name)}function ar(e,t){let n={app:null,ports:[],kept:[]},s="";for(let o of e.split(/\r?\n/)){let r=nn(o).trim();if(!r)continue;let i=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(r);if(i){s=i[1];continue}let c=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(r);if(!c)continue;let[,a,l]=c;if(s===""&&a==="app"){let f=ke(l);/^[a-z0-9][a-z0-9-]*$/i.test(f)&&(n.app=f)}else if(a==="internal_port"){let f=Number(ke(l));Number.isInteger(f)&&f>=1&&f<=65535&&n.ports.push(f)}else if(s==="env"){let f=We(a,ke(l),t);f&&n.kept.push(f)}}return n}function lr(e,t){let n={ports:[],kept:[]},s=e.replace(/\\\r?\n/g," ");for(let o of s.split(/\r?\n/)){let r=o.trim(),i=/^EXPOSE\s+(.+)$/i.exec(r);if(i){for(let a of i[1].split(/\s+/)){let l=Number(a.replace(/\/\w+$/,""));Number.isInteger(l)&&l>=1&&l<=65535&&n.ports.push(l)}continue}if(i=/^(?:ENV|ARG)\s+(.+)$/i.exec(r),!i)continue;let c=i[1];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(c)){let a=/([A-Za-z_][A-Za-z0-9_]*)=("([^"]*)"|'([^']*)'|\S*)/g,l;for(;l=a.exec(c);){let f=We(l[1],l[3]??l[4]??l[2],t);f&&n.kept.push(f)}}else{let a=/^([A-Za-z_][A-Za-z0-9_]*)\s+(.*)$/.exec(c);if(a){let l=We(a[1],ke(a[2]),t);l&&n.kept.push(l)}}}return n}function fr(e){let t;try{t=JSON.parse(e)}catch{return[]}let n=[];for(let s of["rewrites","redirects"])for(let o of Array.isArray(t?.[s])?t[s]:[]){let r=typeof o?.destination=="string"?o.destination:"",i=/\/:[A-Za-z_]+\*?$/.test(r)?qe(r.replace(/\/:[A-Za-z_]+\*?$/,"")):null;i&&typeof o.source=="string"&&n.push({prefix:ir(o.source),target:i,kind:`vercel.json ${s}`,strip:!0})}return n}function ur(e){let t=[],n=!1,s=null,o=()=>{if(s?.from&&s.to&&/\/:[A-Za-z_]+\*?$/.test(s.to)){let r=qe(s.to.replace(/\/:[A-Za-z_]+\*?$/,""));r&&t.push({prefix:ir(s.from),target:r,kind:"netlify.toml redirects",strip:!0})}s=null};for(let r of e.split(/\r?\n/)){let i=nn(r).trim();if(!i)continue;let c=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(c){o(),n=c[1]==="redirects",s=n?{}:null;continue}if(!n||!s)continue;let a=/^(from|to)\s*=\s*(.*)$/.exec(i);a&&(s[a[1]]=ke(a[2]))}return o(),t}function dr(e,t){let n;try{n=JSON.parse(e)}catch{return[]}let s=[],o=n&&typeof n=="object"?n.env:null;if(o&&typeof o=="object")for(let r of Object.keys(o).sort()){let i=o[r],c=typeof i=="string"?i:typeof i?.value=="string"?i.value:null,a=We(r,c,t);a&&s.push(a)}return s}function pr(e,t,n){let s=[];if(n){let o;try{o=JSON.parse(e)}catch{return s}let r=(i,c)=>{if(!(!i||typeof i!="object"||c>4))for(let a of Object.keys(i).sort()){let l=i[a];if(/^(env|envVars|variables|environment)$/i.test(a)&&l&&typeof l=="object"&&!Array.isArray(l))for(let f of Object.keys(l).sort()){let h=typeof l[f]=="string"?l[f]:typeof l[f]?.value=="string"?l[f].value:null,u=We(f,h,t);u&&s.push(u)}else r(l,c+1)}};r(o,0)}else{let o="";for(let r of e.split(/\r?\n/)){let i=nn(r).trim();if(!i)continue;let c=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(c){o=c[1];continue}let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(i);if(a&&/(^|\.)(env|variables|environment)$/i.test(o)){let l=We(a[1],ke(a[2]),t);l&&s.push(l)}}}return s}var Jc=[".env.local",".env",".env.development",".env.production",".env.example"],Yc=/^(PORT|HTTP_PORT|HTTPS_PORT|SERVER_PORT|API_PORT|APP_PORT|WS_PORT|WSS_PORT|WEBSOCKET_PORT|LISTEN_PORT)$/,Vc=/^PUBLIC_(?:[A-Z0-9]+_)*(?:ORIGIN|URL|HOST|BASE_URL)$/,Xc=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","host.docker.internal"]),Kc=512*1024,mr=e=>e.split(W.sep).join("/");function it(e){try{let t=Yn.lstatSync(e);return!t.isFile()||t.isSymbolicLink()||t.size>Kc?null:Yn.readFileSync(e,"utf8")}catch{return null}}function qe(e){let t=String(e).trim().replace(/^["']|["']$/g,"");if(!/^(https?|wss?):\/\//i.test(t))return null;try{let n=new URL(t);if(!n.hostname)return null;let s=n.protocol.replace(":",""),o=n.hostname.toLowerCase(),r=n.port?Number(n.port):null,i=n.pathname.replace(/\/+$/,"");return{scheme:s,host:o,port:r,origin:`${s}://${o}${r?":"+r:""}`,path:i}}catch{return null}}function Zc(e){let t=String(e).trim().replace(/^["']|["']$/g,"");return!/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:\d{1,5})?(\/[^\s?#]*)?$/i.test(t)||!/[a-z]/i.test(t.split(/[/:]/)[0])?null:qe("http://"+t)}var Vn=e=>{let t=String(e).trim().replace(/^["']|["']$/g,"");if(!/^\d{1,5}$/.test(t))return null;let n=Number(t);return n>=1&&n<=65535?n:null};function Qc(e){let t=new Map;for(let n of e.split(/\r?\n/)){let s=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(n);if(!s)continue;let o=s[2];if(/^["']/.test(o)){let r=o[0],i=o.indexOf(r,1);o=i>0?o.slice(1,i):o.slice(1)}else o=o.replace(/\s+#.*$/,"");t.set(s[1],o)}return t}function yr(e,t,n=0,s=new Set){let o=e.get(t);return o==null||n>5||s.has(t)||(s.add(t),o=o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}]*))?\}/g,(r,i,c)=>{let a=e.has(i)?yr(e,i,n+1,s):void 0;return a!=null&&a!==""?a:c??""}),s.delete(t)),o}function We(e,t,n){if(t==null)return null;if(Yc.test(e)){let o=Vn(t);return o?{name:e,kind:"port",file:n,port:o}:null}let s=qe(t)??(/(_URL|_URI|_HOST|_HOSTNAME|_ORIGIN|_ADDR|_ENDPOINT)$/i.test(e)?Zc(t):null);return s?{name:e,kind:"url",file:n,...s}:null}function hr(e,t){let n=[];for(let s of[...e.keys()].sort()){let o=yr(e,s);if(o==null)continue;let r=We(s,o,t);r&&n.push(r)}return n}function ea(e){let t=e.split(/\r?\n/).map(l=>l.replace(/\s+#.*$/,"").replace(/\t/g," ")),n=l=>l.length-l.trimStart().length,s=[],o=t.findIndex(l=>/^services\s*:\s*$/.test(l));if(o<0)return s;let r=null,i=null,c=null,a=0;for(o=o+1;o<t.length;o++){let l=t[o];if(!l.trim())continue;let f=n(l),h=l.trim();if(f===0)break;if(r==null&&(r=f),f===r){let u=/^([A-Za-z0-9_.-]+)\s*:\s*$/.exec(h);u&&(i={name:u[1],ports:[],env:new Map,build:null},s.push(i),c=null);continue}if(i){if(f<=r+4&&/^[A-Za-z_]+\s*:/.test(h)&&!h.startsWith("-")){let u=/^([A-Za-z_]+)\s*:\s*(.*)$/.exec(h);c=u[1],a=f,c==="build"&&u[2]&&(i.build=u[2].replace(/^["']|["']$/g,""));continue}if(c==="build"&&/^context\s*:/.test(h)){i.build=h.replace(/^context\s*:\s*/,"").replace(/^["']|["']$/g,"");continue}if(c==="ports"&&h.startsWith("-")){let v=h.slice(1).trim().replace(/^["']|["']$/g,"").replace(/\/\w+$/,"").split(":"),d=v.slice(-2).map(k=>Vn(k));v.length===1&&d[0]?i.ports.push({host:null,container:d[0]}):v.length>=2&&d[0]&&d[1]&&i.ports.push({host:d[0],container:d[1]});continue}if(c==="environment"&&f>a){let u=h.startsWith("-")?/^-\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(h):/^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/.exec(h);u&&i.env.set(u[1],u[2].replace(/^["']|["']$/g,""))}}}return s}function gr(e,t){let n=[];if(t==="vite"){let s=e.search(/\bproxy\s*:/);if(s<0)return n;let o=e.slice(s,s+2500),r=/["'`](\/[^"'`]*)["'`]\s*:\s*(?:["'`](https?:\/\/[^"'`]+)["'`]|\{[^{}]*?target\s*:\s*["'`](https?:\/\/[^"'`]+)["'`])/g,i;for(;i=r.exec(o);){let c=qe(i[2]??i[3]);c&&n.push({prefix:i[1].replace(/\/+$/,""),target:c,kind:"vite.config proxy"})}}else if(t==="next"){let s=/source\s*:\s*["'`](\/[^"'`:*]*)[^"'`]*["'`]\s*,\s*destination\s*:\s*["'`](https?:\/\/[^"'`]+?)(?:\/:[^"'`]*)?["'`]/g,o;for(;o=s.exec(e);){let r=qe(o[2]);r&&n.push({prefix:o[1].replace(/\/+$/,""),target:r,kind:"next.config rewrites"})}}return n}function vr(e,t,n){let s=p=>mr(W.relative(e,p)),o=new Map,r=new Map,i=new Map,c=(p,S,$)=>{(p.get(S)??p.set(S,new Set).get(S)).add($)},a=(p,S,$)=>{let w=i.get(p)??i.set(p,[]).get(p);w.some(y=>y.service===S&&y.via===$)||w.push({service:S,via:$})},l=p=>{let S=[],$=W.resolve(p),w=W.resolve(e);for(let y=0;y<8&&(S.push($),!($===w||W.dirname($)===$||($=W.dirname($),!$.startsWith(w))));y++);return S},f=new Map,h=new Map,u=(p,S)=>{let $=p.env.get(S.name)??p.env.set(S.name,[]).get(S.name);$.some(w=>w.file===S.file)||$.push(S),S.kind==="port"&&p.ports.add(S.port)};function v(p,S,$){let w=m=>s(W.join($,m)),y=m=>it(W.join($,m));for(let m of on($))if(m==="fly.toml"){let b=y(m);if(b){let g=ar(b,w(m));for(let x of g.ports)S.ports.add(x);for(let x of g.kept)u(S,x);g.app&&(a(`${g.app.toLowerCase()}.internal`,p.name,"fly.toml app name"),a(`${g.app.toLowerCase()}.fly.dev`,p.name,"fly.toml app name"))}}else if(/^Dockerfile(\..+)?$/.test(m)){let b=y(m);if(b){let g=lr(b,w(m));for(let x of g.ports)S.weakPorts.add(x);for(let x of g.kept)u(S,x)}}else if(m==="railway.json"||m==="railway.toml"){let b=y(m);if(b)for(let g of pr(b,w(m),m.endsWith(".json")))u(S,g)}else if(m==="app.json"){let b=y(m);if(b)for(let g of dr(b,w(m)))u(S,g)}else if(m==="vercel.json"){let b=y(m);if(b)for(let g of fr(b))S.proxies.push({...g,file:w(m)})}else if(m==="netlify.toml"){let b=y(m);if(b)for(let g of ur(b))S.proxies.push({...g,file:w(m)})}}for(let p of t){let S={env:new Map,ports:new Set,weakPorts:new Set,proxies:[],isServer:!1};o.set(p.name,S);for(let $ of l(p.rootPath)){for(let w of Jc){let y=it(W.join($,w));if(y!=null)for(let m of hr(Qc(y),s(W.join($,w)))){let b=S.env.get(m.name)??S.env.set(m.name,[]).get(m.name);b.some(g=>g.file===m.file)||b.push(m),m.kind==="port"&&$===W.resolve(p.rootPath)&&/(^|\/)\.env/.test(m.file)&&!/\.example$/.test(m.file)&&S.ports.add(m.port),m.kind==="port"&&$===W.resolve(p.rootPath)&&/\.example$/.test(m.file)&&S.ports.add(m.port)}}if($===W.resolve(p.rootPath)){try{let w=JSON.parse(it(W.join($,"package.json"))??"null"),y=typeof w?.proxy=="string"?qe(w.proxy):null;y&&S.proxies.push({prefix:"",target:y,kind:'package.json "proxy"',file:s(W.join($,"package.json"))})}catch{}for(let w of on($)){if(/^vite\.config\.(js|mjs|cjs|ts|mts)$/.test(w)){let y=it(W.join($,w));if(y)for(let m of gr(y,"vite"))S.proxies.push({...m,file:s(W.join($,w))})}if(/^next\.config\.(js|mjs|cjs|ts)$/.test(w)){let y=it(W.join($,w));if(y)for(let m of gr(y,"next"))S.proxies.push({...m,file:s(W.join($,w))})}}}$===W.resolve(p.rootPath)&&v(p,S,$);for(let w of on($))if(/^render\.ya?ml$/.test(w)&&!h.has(W.join($,w))){let y=it(W.join($,w));y&&h.set(W.join($,w),cr(y,s(W.join($,w))))}for(let w of on($)){if(!/^docker-compose.*\.ya?ml$/.test(w)||f.has(W.join($,w)))continue;let y=it(W.join($,w));y&&f.set(W.join($,w),ea(y))}}}for(let[p,S]of[...f].sort(($,w)=>$[0]<w[0]?-1:1)){let $=W.dirname(p);for(let w of S){let y=w.build?W.resolve($,w.build):null,m=t.find(g=>y&&W.resolve(g.rootPath)===y)??t.find(g=>g.name===w.name||W.basename(g.rootPath)===w.name);if(!m)continue;let b=o.get(m.name);for(let g of w.ports)b.ports.add(g.container),g.host&&b.ports.add(g.host);for(let g of hr(w.env,s(p)))(b.env.get(g.name)??b.env.set(g.name,[]).get(g.name)).push(g);a(w.name.toLowerCase(),m.name,"docker-compose service name")}}for(let[p,S]of[...h].sort(($,w)=>$[0]<w[0]?-1:1)){let $=W.dirname(p),w=new Map;for(let y of S){let m=W.resolve($,y.rootDir||"."),b=y.rootDir?t.find(x=>W.resolve(x.rootPath)===m):null;if(!b&&y.startCommand)for(let x of y.startCommand.split(/\s+/)){if(!/\.(c|m)?[jt]sx?$/.test(x)&&!/^[\w./-]+\/[\w.-]+$/.test(x))continue;let I=W.resolve(m,x),E=t.filter(M=>I.startsWith(W.resolve(M.rootPath)+W.sep)).sort((M,O)=>O.rootPath.length-M.rootPath.length)[0];if(E){b=E;break}}if(b=b??t.find(x=>x.name===y.name||W.basename(x.rootPath)===y.name),!b)continue;w.set(y.name,{target:b,c:y});let g=o.get(b.name);for(let x of y.kept)u(g,{...x,scoped:!0});a(y.name.toLowerCase(),b.name,"render.yaml service name"),a(`${y.name.toLowerCase()}.onrender.com`,b.name,"render.yaml service name (Render's default public address)")}for(let{target:y,c:m}of w.values())for(let b of m.hostRefs){let g=w.get(b.service);if(!g)continue;let x=[...g.c.kept].find(M=>M.kind==="port")?.port??null,I=b.property==="hostport"&&x,E=b.service.toLowerCase();u(o.get(y.name),{name:b.name,kind:"url",file:s(p),scheme:"http",host:E,port:I?x:null,origin:`http://${E}${I?":"+x:""}`,path:""})}}let d=p=>[...n.get(p.name)?.parseResults?.values()??[]].some(S=>(S.routes??[]).length>0);for(let p of t){let S=o.get(p.name);if(S.isServer=d(p),S.isServer){for(let[$,w]of S.env)if(Vc.test($))for(let y of w)y.kind==="url"&&y.file&&(y.scoped||W.posix.dirname(y.file)===(mr(W.relative(e,p.rootPath))||"."))&&a(y.host,p.name,`${$} in ${y.file} (the server's own public address)`)}}for(let p of t){let S=o.get(p.name);for(let[,$]of n.get(p.name)?.parseResults??[])for(let w of $.httpClients?.listens??[])for(let y of k(S,w.parts)){let m=Vn(y.text);m&&S.ports.add(m)}}for(let p of t)for(let S of o.get(p.name).ports)c(r,S,p.name);for(let p of t)for(let S of o.get(p.name).weakPorts)t.some($=>o.get($.name).ports.has(S))||c(r,S,p.name);function k(p,S){let $=[{text:"",evidence:[]}];for(let w of S){let y;if(w.t==="lit")y=[{text:w.v,evidence:[]}];else if(w.t==="env"){let b=p.env.get(w.name)??[];y=[];for(let g of b)y.push({text:g.kind==="port"?String(g.port):g.origin+g.path,evidence:[{env:w.name,file:g.file}]});!y.length&&w.fallback&&(y=k(p,w.fallback).map(x=>({text:x.text,evidence:[{env:w.name,file:null,fallback:!0},...x.evidence]})))}else y=[];if(!y.length)return[];let m=[];for(let b of $)for(let g of y)if(m.push({text:b.text+g.text,evidence:[...b.evidence,...g.evidence]}),m.length>=8)break;$=m.slice(0,8)}return $}let j=(p,S)=>{let $=[],w=p.host,y=i.get(w)??[];for(let m of y)$.push(m);if(Xc.has(w)||y.length&&y.some(m=>m.via==="docker-compose service name")){let m=p.port??(p.scheme==="https"||p.scheme==="wss",null);if(m)for(let b of r.get(m)??[])$.some(g=>g.service===b)||$.push({service:b,via:`port ${m} (a service listening there)`})}return $.filter(m=>m.service!==S)};return{resolveBase(p,S){let $=o.get(p);if(!$||!S.length)return{status:"unknown"};let w=k($,S);if(!w.length)return{status:"unknown"};let y=[],m=new Set;for(let x of w){let I=qe(x.text)??(x.text.startsWith("//"),null);if(I){m.add(I.origin);for(let E of j(I,p))y.push({...E,u:I,evidence:x.evidence})}}if(!m.size)return{status:"unknown"};let b=[...new Set(y.map(x=>x.service))];if(b.length===0)return{status:"external",origins:[...m].sort()};if(b.length>1)return{status:"ambiguous",services:b.sort()};let g=y[0];return{status:"service",service:g.service,via:g.via,origin:g.u.origin,basePath:g.u.path,evidence:g.evidence.filter((x,I,E)=>E.findIndex(M=>M.env===x.env&&M.file===x.file)===I)}},resolveProxy(p,S){let $=o.get(p);for(let w of $?.proxies??[]){if(w.prefix&&S!==w.prefix&&!S.startsWith(w.prefix+"/"))continue;let y=j(w.target,p),m=[...new Set(y.map(b=>b.service))];if(m.length===1)return{status:"service",service:m[0],via:`${w.kind} ${w.prefix||"/"} -> ${w.target.origin}`,origin:w.target.origin,basePath:w.target.path,strip:w.strip?w.prefix.split("/").filter(Boolean).length:0,evidence:[{env:null,file:w.file}]}}return{status:"unknown"}},portsOf:p=>[...o.get(p)?.ports??[]].sort((S,$)=>S-$),hostClaims:()=>[...i].sort((p,S)=>p[0]<S[0]?-1:1)}}function on(e){try{return Yn.readdirSync(e).sort()}catch{return[]}}var sn=e=>String(e).toLowerCase();function rn(e){let t=[];for(let n of e)n.t==="lit"&&t.length&&t[t.length-1].t==="lit"?t[t.length-1]={t:"lit",v:t[t.length-1].v+n.v}:t.push(n);return t}function wr(e,t){let n=[];for(let s of e){if(s.t!=="param"){n.push(s);continue}let o=t?.get(s.index);o?n.push(...o):n.push({t:"ref",name:s.name})}return rn(n)}function Xn(e){if(!e.length)return null;let t=e.slice(),n="none",s=null,o=t[0];if(o.t==="lit"){let l=/^(https?:)\/\/([^/?#]*)(.*)$/.exec(o.v);if(l){n="abs",s=l[2];let f=l[3];if(t=f?[{t:"lit",v:f},...t.slice(1)]:t.slice(1),/^(www\.)?(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)(:\d+)?$/.test(s)===!1&&!/\.(local|internal|svc)$/.test(s)&&!/^[a-z0-9-]+(:\d+)?$/.test(s))return null}else if(!o.v.startsWith("/"))return null}else{for(n="var";t.length&&t[0].t!=="lit";)t.shift();if(!t.length||!t[0].v.startsWith("/"))return null}let r="",i=0,c=!1;for(let l of t){if(c)break;if(l.t==="lit"){let f=l.v.search(/[?#]/);f>=0?(r+=l.v.slice(0,f),c=!0):r+=l.v}else r+="",i++}if(!r.startsWith("/")&&!(r===""&&n==="abs"))return null;r===""&&(r="/");let a=r.split("/").slice(1).map(l=>l.includes("")?":p":l);for(;a.length>1&&a[a.length-1]==="";)a.pop();return{base:n,host:s,segments:a,placeholders:i,literal:n==="none"&&i===0}}function xr(e){if(!e.length)return[];let t=e[0];if(t.t==="lit"){let s=/^((?:https?|wss?):\/\/[^/?#]*)/.exec(t.v);return s?[{t:"lit",v:s[1]}]:[]}let n=[];for(let s of e){if(s.t==="lit"&&s.v.startsWith("/"))break;n.push(s)}return n}var ta=e=>String(e||"").split("/").filter(Boolean),Sr=e=>[...new Set(e)];function kr(e){let t=e.evidence??[];return{env:Sr(t.filter(n=>n.env).map(n=>n.env)),files:Sr(t.filter(n=>n.file).map(n=>n.file)),origin:e.origin,via:e.via,...t.some(n=>n.fallback)?{usedFallback:!0}:{}}}var $r=(e,t)=>"base URL "+(e.env.length?e.env.join(", ")+(e.files.length?" in "+e.files.join(", "):"")+" = ":e.files.length?"(from "+e.files.join(", ")+") ":"")+e.origin+" belongs to "+t+" ("+e.via+")",na=e=>{let t=String(e).split(/[?#]/)[0].split("/").slice(1).map(n=>n.startsWith(":")||/^\{.*\}$/.test(n)||n==="*"?":p":n);for(;t.length>1&&t[t.length-1]==="";)t.pop();return t};function br(e,t){if(e.length===t.length){let n=!0,s=!0;for(let o=0;o<e.length;o++){let r=e[o],i=t[o];if(r!==i&&(n=!1),!(r===i||r===":p"||i===":p")){s=!1;break}}if(n)return 3;if(s)return 2}if(e[0]==="api"&&e.length>1){let n=e.slice(1);if(/^v\d+$/.test(n[0])&&n.length>1&&(n=n.slice(1)),n.length===t.length&&n.every((s,o)=>s===t[o]||s===":p"||t[o]===":p"))return 1}return 0}function oa(e,t,n,s,o){let r=(n.importBindings??[]).find(h=>h.local===s);if(!r)return null;let i=me(r.source,t,o);if(!i)return null;let c=e.parseResults.get(i),a=h=>e.nodes.find(u=>u.filePath===i&&u.name===h&&u.type!=="moduleRoot")?.id??null;if(r.kind==="named"&&r.imported)return a(r.imported);let l=c?.exportBindings;if(l?.default&&l.default!=="<anon>")return a(l.default);let f=Object.keys(l?.named??{});return f.length===1?a(f[0]):null}function sa(e){let t=[],n=[...e.parseResults.keys()];for(let[s,o]of e.parseResults){let r=e.nodes.filter(a=>a.filePath===s);if(r[0]?.category!=="backend")continue;let i=Me(s,o),c=ae(s,e.nodes);for(let a of o.routes??[]){let l=null;a.isInlineHandler?l=i.get(a):a.nest?l=r.find(h=>h.type==="classMethod"&&h.className===a.nest.className&&h.name===a.nest.methodName)?.id??null:a.handlerName&&c.has(a.handlerName)?l=c.get(a.handlerName):a.handlerName&&(l=oa(e,s,o,a.handlerName,n));let f=!1;l||(l=ie(a.startLine,r)?.id??null,f=!0),l&&t.push({method:sn(a.method),path:a.path,segments:na(a.path),literal:!/[:*{]/.test(a.path),nodeId:l,file:s,line:a.startLine,fallback:f})}}return t}var ra=/^(ws|uws|websocket|@nestjs\/platform-ws|@fastify\/websocket|fastify-websocket|express-ws)$/,ia=/^(socket\.io|@nestjs\/platform-socket\.io|socket\.io-client)$/;function Nr(e){let t=[...e].some(s=>ia.test(s)),n=[...e].some(s=>ra.test(s));return t&&n?"unknown":t?"socketio":n?"ws":null}function ca(e){let t=[],n=new Set;for(let[,s]of e.parseResults)for(let o of s.imports??[])n.add(o.source);for(let[s,o]of e.parseResults){let r=o.socketListeners??[],i=r.find(k=>k.eventName==="connection");if(!i)continue;let c=Me(s,o),a=ae(s,e.nodes),l=k=>k.isInlineHandler?c.get(k):k.handlerName&&a.has(k.handlerName)?a.get(k.handlerName):null,f=l(i);if(!f)continue;let h=k=>i.handlerStartLine!=null&&k.startLine>=i.handlerStartLine&&k.startLine<=i.handlerEndLine,u=r.find(k=>k.eventName==="message"&&h(k))??r.find(k=>k.eventName==="message"),v=o.httpClients?.wsServers??[],d=Nr(new Set((o.imports??[]).map(k=>k.source)))??Nr(n)??"unknown";t.push({filePath:s,nodeId:f,line:i.startLine,messageNodeId:u?l(u):null,messageLine:u?.startLine??null,pathParts:v.find(k=>k.path)?.path??null,kind:d})}return t}function Ir(e,t,n={}){let s=n.repoRoot?vr(n.repoRoot,e,t):null,o=[],r=new Set,i={restCalls:0,restLinked:0,wsClients:0,wsLinked:0,wsSends:0,wsSendsLinked:0},c=l=>{let f=[l.fromService,l.fromNodeId,l.toService,l.toNodeId,l.via,l.key].join("\0");r.has(f)||(r.add(f),o.push(l))},a=new Map;for(let l of e){let f=t.get(l.name);f&&a.set(l.name,{routes:sa(f),wsServers:ca(f)})}for(let l of e){let f=t.get(l.name);if(!f)continue;let h=[...f.parseResults.keys()],u=new Map,v=new Map;for(let[y,m]of f.parseResults){let b=m.httpClients;if(b){for(let g of b.httpInstances??[])(u.get(g.name)??u.set(g.name,[]).get(g.name)).push(g);for(let g of b.httpCalls??[])(g.parts.some(I=>I.t==="param")||g.method&&typeof g.method=="object")&&g.fn?.name&&(v.get(g.fn.name)??v.set(g.fn.name,[]).get(g.fn.name)).push({filePath:y,call:g})}}let d=y=>{if(!y.startsWith("inst:")&&!y.startsWith("obj:"))return[];let m=u.get(y.slice(y.indexOf(":")+1));return m&&m.length===1?m[0].parts:y.startsWith("obj:")?null:[{t:"ref",name:"?"}]},k=[],j=(y,m)=>ie(m,f.nodes.filter(b=>b.filePath===y)),p=new Set,S=y=>y.parts.some(m=>m.t==="param")||y.method&&typeof y.method=="object";for(let[y,m]of f.parseResults){let b=m.httpClients;if(b){for(let g of b.httpCalls??[]){if(S(g))continue;let x=d(g.client);if(x===null)continue;let I=j(y,g.line);I&&k.push({filePath:y,line:g.line,nodeId:I.id,method:g.method,parts:rn([...x,...g.parts]),via:g.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let g of b.pathCallsites??[]){let x=v.get(g.callee);if(x)for(let I of x){let E=I.filePath===y;if(!E){let B=(m.importBindings??[]).find(_=>_.local===g.callee||_.imported===g.callee);B&&me(B.source,y,h)===I.filePath&&(E=!0)}if(!E)continue;let M=new Map(g.args.map(B=>[B.i,B.parts])),O=typeof I.call.method=="object"&&I.call.method?(()=>{let B=M.get(I.call.method.param);return B&&B.length===1&&B[0].t==="lit"?B[0].v.toUpperCase():"?"})():I.call.method,L=j(y,g.line);L&&(p.add(I.call),k.push({filePath:y,line:g.line,nodeId:L.id,method:O,parts:wr([...d(I.call.client),...I.call.parts],M),via:I.call.client,wrapper:g.callee}))}}}}for(let[y,m]of f.parseResults)for(let b of m.httpClients?.httpCalls??[]){if(!S(b)||p.has(b))continue;let g=d(b.client);if(g===null)continue;let x=j(y,b.line);x&&k.push({filePath:y,line:b.line,nodeId:x.id,method:typeof b.method=="object"&&b.method?"?":b.method,parts:wr([...g,...b.parts],null),via:b.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let y of k){let m=Xn(y.parts);if(!m)continue;i.restCalls++;let b=0,g=[];for(let L of e){if(L.name===l.name)continue;let B=a.get(L.name);if(B)for(let _ of B.routes){if(!(y.method==="?"||y.method==null||_.method===sn(y.method)||_.method==="all"||_.method==="use"))continue;let V=br(m.segments,_.segments);V&&(V>b&&(b=V,g.length=0),V===b&&g.push({service:L.name,route:_}))}}let x={status:"unknown"};if(s){let L=rn(y.parts);if(m.base==="none"?x=s.resolveProxy(l.name,"/"+m.segments.join("/")):x=s.resolveBase(l.name,xr(L)),x.status==="service"){let B=ta(x.basePath);if(B.length||x.strip){let _=[...B,...m.segments.slice(x.strip||0)];for(let U of a.get(x.service)?.routes??[])(y.method==="?"||y.method==null||U.method===sn(y.method)||U.method==="all"||U.method==="use")&&br(_,U.segments)&&!g.some(R=>R.service===x.service&&R.route.nodeId===U.nodeId)&&g.push({service:x.service,route:U,viaBasePath:!0})}}}if(!g.length)continue;let I=new Set(g.map(L=>L.service+"\0"+L.route.nodeId)),E=typeof y.method=="string"&&y.method!=="?",M=b===3&&m.literal&&E&&I.size===1&&g[0].route.literal&&!g[0].route.fallback&&g[0].route.method===sn(y.method),O=[];m.base==="var"&&O.push("base URL is a variable, so the target service is guessed from the path"),m.base==="abs"&&O.push("absolute URL"),m.placeholders&&O.push("path has parameters"),b===1&&O.push("leading /api removed from the client path"),b===2&&O.push("route parameters matched fuzzily"),E||O.push("method not known"),I.size>1&&O.push(I.size+" candidate routes"),g.some(L=>L.route.fallback)&&O.push("route handler not resolved: linked to the function that registers the route"),x.status==="external"&&O.push("base URL is "+x.origins.join(" / ")+", which no service of this repo owns"),x.status==="ambiguous"&&O.push("base URL could belong to "+x.services.join(" or "));for(let L of g){i.restLinked++;let B=!M&&x.status==="service"&&x.service===L.service&&!L.route.fallback,_=B?kr(x):null,U=M?"exact":B?"resolved":"inferred",V=!M&&x.status==="service"&&x.service!==L.service?["base URL belongs to "+x.service+", not this service"]:[];c({fromService:l.name,fromNodeId:y.nodeId,toService:L.service,toNodeId:L.route.nodeId,via:"httpCall",key:`${E?y.method:"ANY"} ${"/"+m.segments.join("/")}`,confidence:U,method:E?y.method:null,url:"/"+m.segments.join("/"),client:y.via,...y.wrapper?{wrapper:y.wrapper}:{},line:y.line,...M?{}:B?{reason:$r(_,L.service)+(E?"":"; method not known"),resolvedFrom:_}:{reason:[...O,...V].join("; ")||"path-only match"}})}}let $=[];for(let[y,m]of f.parseResults)for(let b of m.httpClients?.wsClients??[])$.push({filePath:y,w:b});let w=y=>y.client==="io"?"socketio":"ws";for(let{filePath:y,w:m}of $){let b=j(y,m.line);if(!b)continue;i.wsClients++;let g=rn(m.parts),x=/^wss?:\/\//.test(g[0]?.v??"")?Xn([{t:"lit",v:g[0].v.replace(/^ws(s?):/,"http$1:")},...g.slice(1)]):Xn(g),I=s&&x?s.resolveBase(l.name,xr(g)):{status:"unknown"};for(let E of e)if(E.name!==l.name)for(let M of a.get(E.name)?.wsServers??[]){if(M.kind!=="unknown"&&M.kind!==w(m))continue;let O=M.pathParts&&M.pathParts.every(V=>V.t==="lit")?"/"+M.pathParts.map(V=>V.v).join("").replace(/^\//,""):null,L=x?"/"+x.segments.join("/"):null;if(O&&L&&O!==L&&O!=="/"&&L!=="/")continue;let B=!!(x&&x.literal&&O&&L===O&&M.kind!=="unknown"),_=!B&&I.status==="service"&&I.service===E.name,U=_?kr(I):null;i.wsLinked++,c({fromService:l.name,fromNodeId:b.id,toService:E.name,toNodeId:M.nodeId,via:"webSocket",key:L??"(url unknown)",confidence:B?"exact":_?"resolved":"inferred",url:L,client:m.client,line:m.line,...B?{}:_?{reason:$r(U,E.name),resolvedFrom:U}:{reason:"WebSocket connection matched to a WebSocket server of another service ("+(x?.base==="var"?"URL base is a variable":"no path on the server to compare")+(I.status==="external"?"; base URL is "+I.origins.join(" / ")+", which no service of this repo owns":"")+")"}})}}if($.length){let y=new Set($.map(({w:m})=>w(m)));for(let[m,b]of f.parseResults)for(let g of b.httpClients?.wsSends??[]){let x=j(m,g.line);if(x){i.wsSends++;for(let I of e)if(I.name!==l.name)for(let E of a.get(I.name)?.wsServers??[])!E.messageNodeId||E.kind!=="unknown"&&!y.has(E.kind)||(i.wsSendsLinked++,c({fromService:l.name,fromNodeId:x.id,toService:I.name,toNodeId:E.messageNodeId,via:"webSocketMessage",key:"message",eventName:"message",confidence:"inferred",client:g.recv,line:g.line,reason:"a message sent over a socket whose payload is built at run time; delivered to the message listener of a WebSocket server of another service"}))}}}}if(n.serverPush!==!1){let l=new Map;for(let h of o)if(h.via==="webSocket"){let u=h.fromService+"\0"+h.toService;(l.get(u)??l.set(u,[]).get(u)).push(h)}let f=new Map;for(let h of l.values())(f.get(h[0].toService)??f.set(h[0].toService,new Set).get(h[0].toService)).add(h[0].fromService);for(let[,h]of[...l].sort((u,v)=>u[0]<v[0]?-1:1)){let u=h[0].fromService,v=h[0].toService,d=t.get(u),k=t.get(v);if(!d||!k||!(a.get(v)?.wsServers??[]).length)continue;let j=new Set(h.map(w=>w.fromNodeId.split("::")[0])),p=[];for(let[w,y]of d.parseResults){if(!j.has(w))continue;let m=ae(w,d.nodes),b=Me(w,y),g=d.nodes.filter(x=>x.filePath===w);for(let x of y.httpClients?.wsReceivers??[]){let I=x.handlerName&&m.get(x.handlerName)||ie(x.line,g)?.id;I&&p.push({id:I,line:x.line})}for(let x of y.socketListeners??[]){if(x.eventName!=="message")continue;let I=x.isInlineHandler?b.get(x):x.handlerName&&m.get(x.handlerName)||null;I&&p.push({id:I,line:x.startLine})}}let S=new Set(d.resolvedEdges.filter(w=>w.resolved&&w.targetNodeId&&w.type!=="returnValue").map(w=>w.fromNodeId));for(let w=p.length-1;w>=0;w--)S.has(p[w].id)||p.splice(w,1);if(!p.length)continue;let $=f.get(v)?.size??1;for(let[w,y]of k.parseResults){let m=k.nodes.filter(b=>b.filePath===w);for(let b of[...y.httpClients?.wsSends??[],...y.httpClients?.wsServerSends??[]]){let g=ie(b.line,m);if(g)for(let x of p)i.wsPushLinked=(i.wsPushLinked??0)+1,c({fromService:v,fromNodeId:g.id,toService:u,toNodeId:x.id,via:"webSocketDelivery",key:"message",eventName:"message",confidence:"inferred",client:b.recv,line:b.line,receiverLine:x.line,reason:"a message the server sends over a WebSocket (payload built at run time) is taken in by the message handler of "+u+", which connects to this server"+($>1?"; "+$+" services connect to this server, so it may be meant for another one":""),...$>1?{candidates:$}:{}})}}}}return o.sort((l,f)=>l.fromService+l.fromNodeId+l.via+l.key+l.toService+l.toNodeId<f.fromService+f.fromNodeId+f.via+f.key+f.toService+f.toNodeId?-1:1),{edges:o,stats:i}}import jr from"node:fs";var aa=/\b(?:Queue|Bull|Worker|Processor|InjectQueue|WorkerHost)\b|\.process\s*\(/,le="[A-Za-z_$][\\w$]*",la=1024*1024;function Er(e){let t="",n=0,s=null;for(;n<e.length;){let o=e[n],r=e[n+1];if(s){if(t+=o,o==="\\"){t+=e[n+1]??"",n+=2;continue}o===s&&(s=null),n++}else if(o==="/"&&r==="/")for(;n<e.length&&e[n]!==`
|
|
11
|
+
return ${c};})()`}function Un(e,t,n,s){if(!e)return{targetId:null,via:null};if(n.has(e))return{targetId:n.get(e),via:"in-file"};if(s)for(let[,o]of s){let r=fe(o,t);if(r.has(e))return{targetId:r.get(e),via:"cross-file"}}return{targetId:null,via:null}}function Ws(e,t,n,s,o,r=[],i=null){if(!n.some(a=>!a.isInlineHandler)&&!s.some(a=>!a.isInlineHandler)&&!r.some(a=>!a.isInlineHandler))return e;let c=e.map(a=>({...a}));for(let a of n){if(a.isInlineHandler)continue;let l=a.nest?e.find(d=>d.type==="classMethod"&&d.filePath===t&&d.className===a.nest.className&&d.name===a.nest.methodName):null,{targetId:f,via:y}=a.nest?{targetId:l?.id??null,via:"in-file"}:Un(a.handlerName,e,o,i);if(f){let d=c.find(w=>w.id===f);d&&(d.isEntryPoint=!0,d.trigger={type:"route",label:`${a.method.toUpperCase()} ${a.path}`,resolvedVia:y})}}for(let a of s){if(a.isInlineHandler)continue;let{targetId:l,via:f}=Un(a.handlerName,e,o,i);if(l){let y=c.find(d=>d.id===l);y&&(y.isEntryPoint=!0,y.trigger={type:"listener",label:a.eventName,resolvedVia:f})}}for(let a of r){if(a.isInlineHandler)continue;let{targetId:l,via:f}=Un(a.handlerName,e,o,i);if(l){let y=c.find(d=>d.id===l);y&&(y.isEntryPoint=!0,y.trigger={type:"socketListener",label:a.eventName,resolvedVia:f})}}return c}function qn(e){let t=new Map,n=new Map;for(let s of e)s.resolved&&(t.set(s.fromNodeId,(t.get(s.fromNodeId)??0)+1),n.set(s.targetNodeId,(n.get(s.targetNodeId)??0)+1));return{outgoing:t,incoming:n}}function Us(e,t,n=qn(t)){if(e.type==="moduleRoot")return 0;let s=n.outgoing.get(e.id)??0,o=n.incoming.get(e.id)??0,r=e.exported?1.5:1;return s/(o+1)*r}function qs(e,t){let n=qn(t),s=new Set;for(let i of e)n.incoming.has(i.id)&&s.add(i.filePath);let r=e.filter(i=>!(i.isEntryPoint||i.type==="moduleRoot"||!n.incoming.has(i.id)&&s.has(i.filePath))).map(i=>({...i,fallbackScore:Us(i,t,n)}));return r.sort((i,c)=>c.fallbackScore-i.fallbackScore),r.slice(0,15)}function Gn(e){let t=new Map;for(let n of e)!n.resolved||!n.fromNodeId||!n.targetNodeId||(t.has(n.fromNodeId)||t.set(n.fromNodeId,[]),t.get(n.fromNodeId).push({targetNodeId:n.targetNodeId,line:n.line??null,column:n.column??null,branchPath:n.branchPath??[],edgeType:n.type}));return t}function Yn(e,t,n,s=8){let o=new Set([e]),r=a=>n.find(l=>l.id===a)?.category??"unknown",i=[{nodeId:e,depth:0,parentNodeId:null,category:r(e)}],c=[{nodeId:e,depth:0}];for(;c.length>0;){let a=c.shift();if(a.depth>=s)continue;let l=t.get(a.nodeId)||[];for(let f of l){let y=f.targetNodeId;if(o.has(y))continue;o.add(y);let d={nodeId:y,depth:a.depth+1,parentNodeId:a.nodeId,category:r(y),callLine:f.line,callColumn:f.column,branchPath:f.branchPath,edgeType:f.edgeType};i.push(d),c.push(d)}}return i}function Gs(e,t,n,s=null){return t.filter(r=>r.filePath===e.filePath&&r.id!==e.id&&r.type!=="moduleRoot").filter(r=>!(s?s.has(r.id):n.some(c=>c.resolved&&c.targetNodeId===r.id)))}var Ys=new WeakMap,Js=new WeakMap;function Mc(e){let t=Ys.get(e);if(t&&t.length===e.length)return t;let n=new Set,s=new Set,o=new Map;for(let r of e)r.resolved&&(r.targetNodeId===void 0||r.targetNodeId===null||(s.add(r.targetNodeId),r.matchType==="crossLayer"&&n.add(r.targetNodeId)),o.set(r.fromNodeId,(o.get(r.fromNodeId)??0)+1));return t={length:e.length,crossLayerTargets:n,incoming:s,outgoing:o},Ys.set(e,t),t}function Oc(e,t,n){let s=Js.get(e);if(s&&s.length===e.length&&s.edgesRef===n)return s.calledByFile;let o=new Map;for(let r of e){if(r.type==="moduleRoot"||!n.incoming.has(r.id))continue;let i=o.get(r.filePath);i||o.set(r.filePath,i=new Set),i.add(r.id)}return Js.set(e,{length:e.length,edgesRef:n,calledByFile:o}),o}function Vs(e,t,n){if(e.type==="moduleRoot")return!1;let s=Mc(t);if(s.crossLayerTargets.has(e.id)||(s.outgoing.get(e.id)??0)>=4||new Set((e.returns||[]).map(a=>a.condition).filter(a=>a!==null)).size>=3)return!0;if(s.incoming.has(e.id)){let a=Oc(n,t,s).get(e.filePath);if(!(!!a&&a.size-(a.has(e.id)?1:0)>0)){let f=Gs(e,n,t,s.incoming);if(f.length>0)return e.lexicalSiblings=f.map(y=>y.id),!0}}return!1}function Xs(e,t,n,s,o=8,r=null){let i=[],c=new Set(e.map(f=>f.id)),a=[...e],l=new Map;for(let f of n)l.has(f.id)||l.set(f.id,f);for(;a.length>0;){let f=a.shift(),y=Yn(f.id,t,n,o);i.push({entryPointId:f.id,entryPointName:f.name,trigger:f.trigger??null,steps:y});let d=r?new Set(Yn(f.id,r,n,o).map(w=>w.nodeId)):null;for(let w of y){if(d&&!d.has(w.nodeId)||w.nodeId===f.id||c.has(w.nodeId))continue;let p=l.get(w.nodeId);p&&Vs(p,s,n)&&(c.add(p.id),w.hasOwnSubTrace=!0,p.lexicalSiblings&&(w.lexicalSiblings=p.lexicalSiblings),a.push({id:p.id,name:p.name,trigger:null}))}}return i}function Ks(e,t,n=as){return e.filter((s,o)=>{if(o===0)return!0;let r=t.find(i=>i.id===s.nodeId);return r?!n.some(i=>r.name.toLowerCase().includes(i)):!0})}function Zs(e){return e.steps.filter(n=>n.depth>0).map(n=>n.nodeId).sort().join(" | ")}function Qs(e){let t=new Map;for(let n of e){let s=Zs(n),o=s===""?`__no_calls__${n.entryPointName}`:s;t.has(o)||t.set(o,[]),t.get(o).push(n)}return t}function er(e){let t=e[0];return{steps:t.steps,entryPointNames:e.map(n=>n.entryPointName),occurrences:e.length,name:t.entryPointName,trigger:t.trigger,tier:e.some(n=>n.origin==="physical")?"physical":"guessed",tierOrigin:e.some(n=>n.origin==="physical")?"physical":t.origin}}import Qt from"node:path";function tr(e){if(!e.trigger)return null;if(e.trigger.type==="route")return`${e.trigger.label.split(" ")[1].split("/").filter(Boolean).join(" ").replace(/[-_]/g," ").split(" ").map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")} Flow`;if(e.trigger.type==="listener"){let t=e.trigger.label;return`${t.charAt(0).toUpperCase()+t.slice(1)} Flow`}return null}function nr(e){return e.name.replace(/([A-Z])/g," $1").trim().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}var or=60,Ac=24;function sr(e,t=null){let n=e.map(s=>{let o=tr(s),r=s.trigger?.workflowName??o??nr(s);return{...s,name:r}});return t?.nodes?Dc(n,t.nodes):n}var Jn=(e,t)=>e.length>t?e.slice(0,t-1)+"\u2026":e,Tc=new Set(["function","arrowFunction","classMethod"]);function Fc(e){let t=new Map(e.map(o=>[o.id,o])),n=new Map,s=o=>{let r=n.get(o);return r||(r=e.filter(i=>i.filePath===o&&Tc.has(i.type)),n.set(o,r)),r};return o=>{let r=t.get(o.steps[0].nodeId);if(!r)return[null,null,null];let i=null;if(r.type==="classMethod")i=r.className;else{let l=null;for(let f of s(r.filePath))f===r||!(f.startLine<=r.startLine&&f.endLine>=r.endLine)||f.startLine===r.startLine&&f.endLine===r.endLine||(!l||f.endLine-f.startLine<l.endLine-l.startLine)&&(l=f);l&&(i=l.type==="classMethod"?l.className:l.name)}let c=null;if(o.trigger?.type==="route")c=String(o.trigger.label).split(" ")[0];else if(o.trigger?.type==="listener"){let l=/::listener:([^.#]+)\./.exec(r.id);l&&(c=l[1])}let a=Qt.basename(r.filePath,Qt.extname(r.filePath));return a==="index"&&(a=Qt.basename(Qt.dirname(r.filePath))),[i||null,c||null,a||null]}}var Bc=(e,t)=>{let n=t.map(s=>Jn(s,Ac)).join(", ");return e.endsWith(")")?e.slice(0,-1)+", "+n+")":e+" ("+n+")"};function Dc(e,t){let n=Fc(t),s=e.map(i=>({w:i,base:i.name,parts:[],used:new Set,stuck:!1,q:null})),o=i=>i.parts.length?Bc(i.base,i.parts):i.base,r=()=>{let i=new Map;for(let c of s){let a=o(c);(i.get(a)??i.set(a,[]).get(a)).push(c)}return[...i.values()].filter(c=>c.length>1)};for(let i=0;i<4;i++){let c=!1;for(let a of r()){if(a.some(d=>d.stuck))continue;for(let d of a)d.q??=n(d.w);let l=[0,1,2].filter(d=>a.every(w=>!w.used.has(d))),f=l.find(d=>new Set(a.map(w=>w.q[d]??"")).size>1),y=f!==void 0;if(y||(f=l.find(d=>a.every(w=>w.q[d]))),f===void 0){for(let d of a)d.stuck=!0;continue}for(let d of a)d.used.add(f),d.q[f]&&d.parts.push(d.q[f]),y||(d.stuck=!0);c=!0}if(!c)break}for(let i of r())i.sort((c,a)=>c.w.steps[0].nodeId<a.w.steps[0].nodeId?-1:c.w.steps[0].nodeId>a.w.steps[0].nodeId?1:0),i.forEach((c,a)=>{a>0&&(c.suffix=` (${a+1})`)});return s.map(i=>{let c=o(i);return i.suffix&&(c=Jn(c,or-i.suffix.length)+i.suffix),{...i.w,name:Jn(c,or)}})}var Hc=e=>e;function rr(e,t){let n=new Map;for(let[s,o]of e){let r=t.filter(l=>l.filePath===s);if(r[0]?.category!=="backend")continue;let i=o.routes??[],c=Te(s,o),a=fe(s,t);for(let l of i){let f=xt(l.path);if(l.isInlineHandler){let d=c.get(l);n.set(f,d);continue}if(l.nest){let d=Hc(r).find(w=>w.type==="classMethod"&&w.className===l.nest.className&&w.name===l.nest.methodName);d&&n.set(f,d.id);continue}if(!l.handlerName||!a.has(l.handlerName))continue;let y=a.get(l.handlerName);n.set(f,y)}}return n}import it from"node:fs";import te from"node:path";var en=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],zc=/(^|\/)(dist|build|out|built|compiled|esm|cjs|lib|output)(\/|$)/,ir=/(^|\/)(dist|build|out|built|compiled|esm|cjs|output)(\/|$)/,Wc=/\b(esbuild|tsup|tsdown|tsc|rollup|webpack|ncc|swc|babel|vite|parcel|bun\s+build|pkg|unbuild|microbundle|rspack)\b/,Uc=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild|rspack)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Fe=e=>{try{return it.statSync(e).isFile()}catch{return!1}},Vn=e=>e.split(te.sep).join("/"),Xn=e=>{if(Fe(e)&&en.includes(te.extname(e))&&!/\.d\.ts$/.test(e))return e;let t=e.replace(/\.(m|c)?js$/,"");for(let n of en)if(Fe(t+n)&&!/\.d\.ts$/.test(t+n))return t+n;return null},tn=(e,t)=>{let n=te.relative(e,t);return n&&!n.startsWith("..")&&!te.isAbsolute(n)&&!/(^|[\\/])node_modules([\\/]|$)/.test(n)};function qc(e,t){let n=Fe(t+".map")?t+".map":null;if(!n&&Fe(t))try{let c=it.readFileSync(t,"utf8").slice(-400),a=/sourceMappingURL=([^\s*]+)/.exec(c);if(a&&!a[1].startsWith("data:")){let l=te.resolve(te.dirname(t),a[1]);Fe(l)&&(n=l)}}catch{}if(!n)return null;let s;try{s=JSON.parse(it.readFileSync(n,"utf8"))}catch{return null}let o=te.resolve(te.dirname(n),s.sourceRoot??""),r=(s.sources??[]).map(c=>te.resolve(o,c)).filter(c=>tn(e,c)&&Fe(c)&&en.includes(te.extname(c)));if(r.length===1)return r[0];let i=te.basename(t).replace(/\.(m|c)?js$/,"");return r.find(c=>te.basename(c).replace(/\.[^.]+$/,"")===i)??null}function Gc(e){try{return JSON.parse(it.readFileSync(e,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,"").replace(/,(\s*[}\]])/g,"$1"))}catch{return null}}function Yc(e,t){for(let n of["tsconfig.build.json","tsconfig.json"]){let o=Gc(te.join(e,n))?.compilerOptions;if(!o?.outDir)continue;let r=Vn(te.normalize(o.outDir)).replace(/^\.\//,"").replace(/\/$/,"");if(!(t===r||t.startsWith(r+"/")))continue;let i=t.slice(r.length+1),c=o.rootDir?o.rootDir:it.existsSync(te.join(e,"src"))?"src":".",a=Xn(te.resolve(e,c,i));if(a)return a}return null}function Jc(e,t){let n=t.split("/"),s=n.findIndex(r=>/^(dist|build|out|built|compiled|esm|cjs|lib|output)$/.test(r));if(s<0)return null;let o=n.slice(s+1).join("/");for(let r of["src","source","sources"]){let i=Xn(te.resolve(e,...n.slice(0,s),r,o));if(i&&tn(e,i))return i}return null}function Vc(e,t,n){let s=te.basename(n).replace(/\.(m|c)?js$/,"");for(let o of["build","compile","bundle","prepare","prepublishOnly","prepack","postinstall"]){let r=t.scripts?.[o];if(!r||!Wc.test(r))continue;let i=[];for(let l of r.split(/\s+/).map(f=>f.replace(/^["']|["']$/g,"").replace(/^--?[\w-]+=/,""))){if(!en.includes(te.extname(l))||/\.d\.ts$/.test(l))continue;let f=te.resolve(e,l);Fe(f)&&tn(e,f)&&!ir.test(Vn(te.relative(e,f)))&&i.push(f)}let c=[...new Set(i)];if(c.length===1)return c[0];let a=c.filter(l=>te.basename(l).replace(/\.[^.]+$/,"")===s);if(a.length===1)return a[0];if(c.length)return c[0]}return null}function Xc(e,t){let n=[];try{n=it.readdirSync(e).filter(i=>Uc.test(i)).sort()}catch{return null}let s=te.basename(t).replace(/\.(m|c)?js$/,""),o=[];for(let i of n){let c;try{c=it.readFileSync(te.join(e,i),"utf8")}catch{continue}for(let a of c.matchAll(/\bentry(?:Points)?\s*:\s*[[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/g)){let l=Xn(te.resolve(e,a[1]));l&&tn(e,l)&&o.push(l)}}let r=[...new Set(o)];return r.length===1?r[0]:r.find(i=>te.basename(i).replace(/\.[^.]+$/,"")===s)??null}function nn(e,t,n){if(typeof t!="string"||!t)return null;let s=Vn(te.normalize(t)).replace(/^\.\//,""),o=te.resolve(e,s);if(!zc.test(s)||Fe(o)&&!ir.test(s)||Fe(o)&&/\.ts$/.test(o))return null;let i=[["sourcemap",()=>qc(e,o)],["tsconfig outDir",()=>Yc(e,s)],["convention",()=>Fe(o)?null:Jc(e,s)],["build script",()=>Vc(e,n??{},s)],["build config",()=>Xc(e,s)]];for(let[c,a]of i){let l=null;try{l=a()}catch{}if(l&&l!==o)return{file:l,how:c}}return null}function cr(e,t){let n=new Map;for(let[s,o]of e){let r=o.socketListeners??[],i=Te(s,o),c=fe(s,t);for(let a of r){if(a.isInlineHandler){let f=i.get(a);n.set(a.eventName,f);continue}if(!a.handlerName||!c.has(a.handlerName))continue;let l=c.get(a.handlerName);n.set(a.eventName,l)}}return n}import Kn from"node:fs";import U from"node:path";var Ne=e=>String(e??"").trim().replace(/^["']|["']$/g,""),on=e=>e.replace(/^\s*#.*$/,"").replace(/\s+#.*$/,"");function ar(e){let t=/^(\/[A-Za-z0-9_\-./]*?)\/?(?=$|[:(*{[])/.exec(String(e).trim()),n=t?t[1]:"";return n==="/"?"":n.replace(/\/+$/,"")}function lr(e,t){let n=e.split(/\r?\n/).map(on),s=w=>w.length-w.trimStart().length,o=[],r=null,i=!1,c=null,a=!1,l=0,f=null,y=()=>{f?.key&&f.fromService&&f.fromService!=="?"&&r.hostRefs.push({name:f.key,service:f.fromService,property:f.property}),f=null},d=(w,p,$)=>{p==="name"?w.name=Ne($):p==="rootDir"?w.rootDir=Ne($):p==="startCommand"&&(w.startCommand=Ne($))};for(let w of n){if(!w.trim())continue;let p=s(w),$=w.trim();if(p===0){y(),r=null,a=!1,i=/^services\s*:/.test($),c=null;continue}if(!i)continue;let j=$.startsWith("-");if(j&&(c==null||p===c)){c=p,y(),r={name:null,rootDir:null,startCommand:null,kept:[],hostRefs:[]},o.push(r),a=!1;let k=/^-\s*([A-Za-z]+)\s*:\s*(.*)$/.exec($);k&&d(r,k[1],k[2]);continue}if(!r)continue;let g=/^(?:-\s*)?([A-Za-z]+)\s*:\s*(.*)$/.exec($);if(g){if(g[1]==="envVars"){y(),a=!0,l=p;continue}if(a&&p>l){if(j&&(y(),f={key:null,fromService:null,property:null}),!f)continue;if(g[1]==="key")f.key=Ne(g[2]);else if(g[1]==="value"&&f.key){let k=qe(f.key,Ne(g[2]),t);k&&r.kept.push(k)}else g[1]==="fromService"?f.fromService="?":g[1]==="name"&&f.fromService==="?"?f.fromService=Ne(g[2]):g[1]==="property"&&(f.property=Ne(g[2]));continue}a&&(y(),a=!1),d(r,g[1],g[2])}}return y(),o.filter(w=>w.name)}function fr(e,t){let n={app:null,ports:[],kept:[]},s="";for(let o of e.split(/\r?\n/)){let r=on(o).trim();if(!r)continue;let i=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(r);if(i){s=i[1];continue}let c=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(r);if(!c)continue;let[,a,l]=c;if(s===""&&a==="app"){let f=Ne(l);/^[a-z0-9][a-z0-9-]*$/i.test(f)&&(n.app=f)}else if(a==="internal_port"){let f=Number(Ne(l));Number.isInteger(f)&&f>=1&&f<=65535&&n.ports.push(f)}else if(s==="env"){let f=qe(a,Ne(l),t);f&&n.kept.push(f)}}return n}function ur(e,t){let n={ports:[],kept:[]},s=e.replace(/\\\r?\n/g," ");for(let o of s.split(/\r?\n/)){let r=o.trim(),i=/^EXPOSE\s+(.+)$/i.exec(r);if(i){for(let a of i[1].split(/\s+/)){let l=Number(a.replace(/\/\w+$/,""));Number.isInteger(l)&&l>=1&&l<=65535&&n.ports.push(l)}continue}if(i=/^(?:ENV|ARG)\s+(.+)$/i.exec(r),!i)continue;let c=i[1];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(c)){let a=/([A-Za-z_][A-Za-z0-9_]*)=("([^"]*)"|'([^']*)'|\S*)/g,l;for(;l=a.exec(c);){let f=qe(l[1],l[3]??l[4]??l[2],t);f&&n.kept.push(f)}}else{let a=/^([A-Za-z_][A-Za-z0-9_]*)\s+(.*)$/.exec(c);if(a){let l=qe(a[1],Ne(a[2]),t);l&&n.kept.push(l)}}}return n}function dr(e){let t;try{t=JSON.parse(e)}catch{return[]}let n=[];for(let s of["rewrites","redirects"])for(let o of Array.isArray(t?.[s])?t[s]:[]){let r=typeof o?.destination=="string"?o.destination:"",i=/\/:[A-Za-z_]+\*?$/.test(r)?Ge(r.replace(/\/:[A-Za-z_]+\*?$/,"")):null;i&&typeof o.source=="string"&&n.push({prefix:ar(o.source),target:i,kind:`vercel.json ${s}`,strip:!0})}return n}function pr(e){let t=[],n=!1,s=null,o=()=>{if(s?.from&&s.to&&/\/:[A-Za-z_]+\*?$/.test(s.to)){let r=Ge(s.to.replace(/\/:[A-Za-z_]+\*?$/,""));r&&t.push({prefix:ar(s.from),target:r,kind:"netlify.toml redirects",strip:!0})}s=null};for(let r of e.split(/\r?\n/)){let i=on(r).trim();if(!i)continue;let c=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(c){o(),n=c[1]==="redirects",s=n?{}:null;continue}if(!n||!s)continue;let a=/^(from|to)\s*=\s*(.*)$/.exec(i);a&&(s[a[1]]=Ne(a[2]))}return o(),t}function mr(e,t){let n;try{n=JSON.parse(e)}catch{return[]}let s=[],o=n&&typeof n=="object"?n.env:null;if(o&&typeof o=="object")for(let r of Object.keys(o).sort()){let i=o[r],c=typeof i=="string"?i:typeof i?.value=="string"?i.value:null,a=qe(r,c,t);a&&s.push(a)}return s}function hr(e,t,n){let s=[];if(n){let o;try{o=JSON.parse(e)}catch{return s}let r=(i,c)=>{if(!(!i||typeof i!="object"||c>4))for(let a of Object.keys(i).sort()){let l=i[a];if(/^(env|envVars|variables|environment)$/i.test(a)&&l&&typeof l=="object"&&!Array.isArray(l))for(let f of Object.keys(l).sort()){let y=typeof l[f]=="string"?l[f]:typeof l[f]?.value=="string"?l[f].value:null,d=qe(f,y,t);d&&s.push(d)}else r(l,c+1)}};r(o,0)}else{let o="";for(let r of e.split(/\r?\n/)){let i=on(r).trim();if(!i)continue;let c=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(c){o=c[1];continue}let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(i);if(a&&/(^|\.)(env|variables|environment)$/i.test(o)){let l=qe(a[1],Ne(a[2]),t);l&&s.push(l)}}}return s}var Kc=[".env.local",".env",".env.development",".env.production",".env.example"],Zc=/^(PORT|HTTP_PORT|HTTPS_PORT|SERVER_PORT|API_PORT|APP_PORT|WS_PORT|WSS_PORT|WEBSOCKET_PORT|LISTEN_PORT)$/,Qc=/^PUBLIC_(?:[A-Z0-9]+_)*(?:ORIGIN|URL|HOST|BASE_URL)$/,ea=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","host.docker.internal"]),ta=512*1024,gr=e=>e.split(U.sep).join("/");function ct(e){try{let t=Kn.lstatSync(e);return!t.isFile()||t.isSymbolicLink()||t.size>ta?null:Kn.readFileSync(e,"utf8")}catch{return null}}function Ge(e){let t=String(e).trim().replace(/^["']|["']$/g,"");if(!/^(https?|wss?):\/\//i.test(t))return null;try{let n=new URL(t);if(!n.hostname)return null;let s=n.protocol.replace(":",""),o=n.hostname.toLowerCase(),r=n.port?Number(n.port):null,i=n.pathname.replace(/\/+$/,"");return{scheme:s,host:o,port:r,origin:`${s}://${o}${r?":"+r:""}`,path:i}}catch{return null}}function na(e){let t=String(e).trim().replace(/^["']|["']$/g,"");return!/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:\d{1,5})?(\/[^\s?#]*)?$/i.test(t)||!/[a-z]/i.test(t.split(/[/:]/)[0])?null:Ge("http://"+t)}var Zn=e=>{let t=String(e).trim().replace(/^["']|["']$/g,"");if(!/^\d{1,5}$/.test(t))return null;let n=Number(t);return n>=1&&n<=65535?n:null};function oa(e){let t=new Map;for(let n of e.split(/\r?\n/)){let s=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(n);if(!s)continue;let o=s[2];if(/^["']/.test(o)){let r=o[0],i=o.indexOf(r,1);o=i>0?o.slice(1,i):o.slice(1)}else o=o.replace(/\s+#.*$/,"");t.set(s[1],o)}return t}function wr(e,t,n=0,s=new Set){let o=e.get(t);return o==null||n>5||s.has(t)||(s.add(t),o=o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}]*))?\}/g,(r,i,c)=>{let a=e.has(i)?wr(e,i,n+1,s):void 0;return a!=null&&a!==""?a:c??""}),s.delete(t)),o}function qe(e,t,n){if(t==null)return null;if(Zc.test(e)){let o=Zn(t);return o?{name:e,kind:"port",file:n,port:o}:null}let s=Ge(t)??(/(_URL|_URI|_HOST|_HOSTNAME|_ORIGIN|_ADDR|_ENDPOINT)$/i.test(e)?na(t):null);return s?{name:e,kind:"url",file:n,...s}:null}function yr(e,t){let n=[];for(let s of[...e.keys()].sort()){let o=wr(e,s);if(o==null)continue;let r=qe(s,o,t);r&&n.push(r)}return n}function sa(e){let t=e.split(/\r?\n/).map(l=>l.replace(/\s+#.*$/,"").replace(/\t/g," ")),n=l=>l.length-l.trimStart().length,s=[],o=t.findIndex(l=>/^services\s*:\s*$/.test(l));if(o<0)return s;let r=null,i=null,c=null,a=0;for(o=o+1;o<t.length;o++){let l=t[o];if(!l.trim())continue;let f=n(l),y=l.trim();if(f===0)break;if(r==null&&(r=f),f===r){let d=/^([A-Za-z0-9_.-]+)\s*:\s*$/.exec(y);d&&(i={name:d[1],ports:[],env:new Map,build:null},s.push(i),c=null);continue}if(i){if(f<=r+4&&/^[A-Za-z_]+\s*:/.test(y)&&!y.startsWith("-")){let d=/^([A-Za-z_]+)\s*:\s*(.*)$/.exec(y);c=d[1],a=f,c==="build"&&d[2]&&(i.build=d[2].replace(/^["']|["']$/g,""));continue}if(c==="build"&&/^context\s*:/.test(y)){i.build=y.replace(/^context\s*:\s*/,"").replace(/^["']|["']$/g,"");continue}if(c==="ports"&&y.startsWith("-")){let w=y.slice(1).trim().replace(/^["']|["']$/g,"").replace(/\/\w+$/,"").split(":"),p=w.slice(-2).map($=>Zn($));w.length===1&&p[0]?i.ports.push({host:null,container:p[0]}):w.length>=2&&p[0]&&p[1]&&i.ports.push({host:p[0],container:p[1]});continue}if(c==="environment"&&f>a){let d=y.startsWith("-")?/^-\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(y):/^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/.exec(y);d&&i.env.set(d[1],d[2].replace(/^["']|["']$/g,""))}}}return s}function vr(e,t){let n=[];if(t==="vite"){let s=e.search(/\bproxy\s*:/);if(s<0)return n;let o=e.slice(s,s+2500),r=/["'`](\/[^"'`]*)["'`]\s*:\s*(?:["'`](https?:\/\/[^"'`]+)["'`]|\{[^{}]*?target\s*:\s*["'`](https?:\/\/[^"'`]+)["'`])/g,i;for(;i=r.exec(o);){let c=Ge(i[2]??i[3]);c&&n.push({prefix:i[1].replace(/\/+$/,""),target:c,kind:"vite.config proxy"})}}else if(t==="next"){let s=/source\s*:\s*["'`](\/[^"'`:*]*)[^"'`]*["'`]\s*,\s*destination\s*:\s*["'`](https?:\/\/[^"'`]+?)(?:\/:[^"'`]*)?["'`]/g,o;for(;o=s.exec(e);){let r=Ge(o[2]);r&&n.push({prefix:o[1].replace(/\/+$/,""),target:r,kind:"next.config rewrites"})}}return n}function xr(e,t,n){let s=g=>gr(U.relative(e,g)),o=new Map,r=new Map,i=new Map,c=(g,k,b)=>{(g.get(k)??g.set(k,new Set).get(k)).add(b)},a=(g,k,b)=>{let S=i.get(g)??i.set(g,[]).get(g);S.some(m=>m.service===k&&m.via===b)||S.push({service:k,via:b})},l=g=>{let k=[],b=U.resolve(g),S=U.resolve(e);for(let m=0;m<8&&(k.push(b),!(b===S||U.dirname(b)===b||(b=U.dirname(b),!b.startsWith(S))));m++);return k},f=new Map,y=new Map,d=(g,k)=>{let b=g.env.get(k.name)??g.env.set(k.name,[]).get(k.name);b.some(S=>S.file===k.file)||b.push(k),k.kind==="port"&&g.ports.add(k.port)};function w(g,k,b){let S=u=>s(U.join(b,u)),m=u=>ct(U.join(b,u));for(let u of sn(b))if(u==="fly.toml"){let x=m(u);if(x){let h=fr(x,S(u));for(let v of h.ports)k.ports.add(v);for(let v of h.kept)d(k,v);h.app&&(a(`${h.app.toLowerCase()}.internal`,g.name,"fly.toml app name"),a(`${h.app.toLowerCase()}.fly.dev`,g.name,"fly.toml app name"))}}else if(/^Dockerfile(\..+)?$/.test(u)){let x=m(u);if(x){let h=ur(x,S(u));for(let v of h.ports)k.weakPorts.add(v);for(let v of h.kept)d(k,v)}}else if(u==="railway.json"||u==="railway.toml"){let x=m(u);if(x)for(let h of hr(x,S(u),u.endsWith(".json")))d(k,h)}else if(u==="app.json"){let x=m(u);if(x)for(let h of mr(x,S(u)))d(k,h)}else if(u==="vercel.json"){let x=m(u);if(x)for(let h of dr(x))k.proxies.push({...h,file:S(u)})}else if(u==="netlify.toml"){let x=m(u);if(x)for(let h of pr(x))k.proxies.push({...h,file:S(u)})}}for(let g of t){let k={env:new Map,ports:new Set,weakPorts:new Set,proxies:[],isServer:!1};o.set(g.name,k);for(let b of l(g.rootPath)){for(let S of Kc){let m=ct(U.join(b,S));if(m!=null)for(let u of yr(oa(m),s(U.join(b,S)))){let x=k.env.get(u.name)??k.env.set(u.name,[]).get(u.name);x.some(h=>h.file===u.file)||x.push(u),u.kind==="port"&&b===U.resolve(g.rootPath)&&/(^|\/)\.env/.test(u.file)&&!/\.example$/.test(u.file)&&k.ports.add(u.port),u.kind==="port"&&b===U.resolve(g.rootPath)&&/\.example$/.test(u.file)&&k.ports.add(u.port)}}if(b===U.resolve(g.rootPath)){try{let S=JSON.parse(ct(U.join(b,"package.json"))??"null"),m=typeof S?.proxy=="string"?Ge(S.proxy):null;m&&k.proxies.push({prefix:"",target:m,kind:'package.json "proxy"',file:s(U.join(b,"package.json"))})}catch{}for(let S of sn(b)){if(/^vite\.config\.(js|mjs|cjs|ts|mts)$/.test(S)){let m=ct(U.join(b,S));if(m)for(let u of vr(m,"vite"))k.proxies.push({...u,file:s(U.join(b,S))})}if(/^next\.config\.(js|mjs|cjs|ts)$/.test(S)){let m=ct(U.join(b,S));if(m)for(let u of vr(m,"next"))k.proxies.push({...u,file:s(U.join(b,S))})}}}b===U.resolve(g.rootPath)&&w(g,k,b);for(let S of sn(b))if(/^render\.ya?ml$/.test(S)&&!y.has(U.join(b,S))){let m=ct(U.join(b,S));m&&y.set(U.join(b,S),lr(m,s(U.join(b,S))))}for(let S of sn(b)){if(!/^docker-compose.*\.ya?ml$/.test(S)||f.has(U.join(b,S)))continue;let m=ct(U.join(b,S));m&&f.set(U.join(b,S),sa(m))}}}for(let[g,k]of[...f].sort((b,S)=>b[0]<S[0]?-1:1)){let b=U.dirname(g);for(let S of k){let m=S.build?U.resolve(b,S.build):null,u=t.find(h=>m&&U.resolve(h.rootPath)===m)??t.find(h=>h.name===S.name||U.basename(h.rootPath)===S.name);if(!u)continue;let x=o.get(u.name);for(let h of S.ports)x.ports.add(h.container),h.host&&x.ports.add(h.host);for(let h of yr(S.env,s(g)))(x.env.get(h.name)??x.env.set(h.name,[]).get(h.name)).push(h);a(S.name.toLowerCase(),u.name,"docker-compose service name")}}for(let[g,k]of[...y].sort((b,S)=>b[0]<S[0]?-1:1)){let b=U.dirname(g),S=new Map;for(let m of k){let u=U.resolve(b,m.rootDir||"."),x=m.rootDir?t.find(v=>U.resolve(v.rootPath)===u):null;if(!x&&m.startCommand)for(let v of m.startCommand.split(/\s+/)){if(!/\.(c|m)?[jt]sx?$/.test(v)&&!/^[\w./-]+\/[\w.-]+$/.test(v))continue;let I=U.resolve(u,v),E=t.filter(M=>I.startsWith(U.resolve(M.rootPath)+U.sep)).sort((M,A)=>A.rootPath.length-M.rootPath.length)[0];if(E){x=E;break}}if(x=x??t.find(v=>v.name===m.name||U.basename(v.rootPath)===m.name),!x)continue;S.set(m.name,{target:x,c:m});let h=o.get(x.name);for(let v of m.kept)d(h,{...v,scoped:!0});a(m.name.toLowerCase(),x.name,"render.yaml service name"),a(`${m.name.toLowerCase()}.onrender.com`,x.name,"render.yaml service name (Render's default public address)")}for(let{target:m,c:u}of S.values())for(let x of u.hostRefs){let h=S.get(x.service);if(!h)continue;let v=[...h.c.kept].find(M=>M.kind==="port")?.port??null,I=x.property==="hostport"&&v,E=x.service.toLowerCase();d(o.get(m.name),{name:x.name,kind:"url",file:s(g),scheme:"http",host:E,port:I?v:null,origin:`http://${E}${I?":"+v:""}`,path:""})}}let p=g=>[...n.get(g.name)?.parseResults?.values()??[]].some(k=>(k.routes??[]).length>0);for(let g of t){let k=o.get(g.name);if(k.isServer=p(g),k.isServer){for(let[b,S]of k.env)if(Qc.test(b))for(let m of S)m.kind==="url"&&m.file&&(m.scoped||U.posix.dirname(m.file)===(gr(U.relative(e,g.rootPath))||"."))&&a(m.host,g.name,`${b} in ${m.file} (the server's own public address)`)}}for(let g of t){let k=o.get(g.name);for(let[,b]of n.get(g.name)?.parseResults??[])for(let S of b.httpClients?.listens??[])for(let m of $(k,S.parts)){let u=Zn(m.text);u&&k.ports.add(u)}}for(let g of t)for(let k of o.get(g.name).ports)c(r,k,g.name);for(let g of t)for(let k of o.get(g.name).weakPorts)t.some(b=>o.get(b.name).ports.has(k))||c(r,k,g.name);function $(g,k){let b=[{text:"",evidence:[]}];for(let S of k){let m;if(S.t==="lit")m=[{text:S.v,evidence:[]}];else if(S.t==="env"){let x=g.env.get(S.name)??[];m=[];for(let h of x)m.push({text:h.kind==="port"?String(h.port):h.origin+h.path,evidence:[{env:S.name,file:h.file}]});!m.length&&S.fallback&&(m=$(g,S.fallback).map(v=>({text:v.text,evidence:[{env:S.name,file:null,fallback:!0},...v.evidence]})))}else m=[];if(!m.length)return[];let u=[];for(let x of b)for(let h of m)if(u.push({text:x.text+h.text,evidence:[...x.evidence,...h.evidence]}),u.length>=8)break;b=u.slice(0,8)}return b}let j=(g,k)=>{let b=[],S=g.host,m=i.get(S)??[];for(let u of m)b.push(u);if(ea.has(S)||m.length&&m.some(u=>u.via==="docker-compose service name")){let u=g.port??(g.scheme==="https"||g.scheme==="wss",null);if(u)for(let x of r.get(u)??[])b.some(h=>h.service===x)||b.push({service:x,via:`port ${u} (a service listening there)`})}return b.filter(u=>u.service!==k)};return{resolveBase(g,k){let b=o.get(g);if(!b||!k.length)return{status:"unknown"};let S=$(b,k);if(!S.length)return{status:"unknown"};let m=[],u=new Set;for(let v of S){let I=Ge(v.text)??(v.text.startsWith("//"),null);if(I){u.add(I.origin);for(let E of j(I,g))m.push({...E,u:I,evidence:v.evidence})}}if(!u.size)return{status:"unknown"};let x=[...new Set(m.map(v=>v.service))];if(x.length===0)return{status:"external",origins:[...u].sort()};if(x.length>1)return{status:"ambiguous",services:x.sort()};let h=m[0];return{status:"service",service:h.service,via:h.via,origin:h.u.origin,basePath:h.u.path,evidence:h.evidence.filter((v,I,E)=>E.findIndex(M=>M.env===v.env&&M.file===v.file)===I)}},resolveProxy(g,k){let b=o.get(g);for(let S of b?.proxies??[]){if(S.prefix&&k!==S.prefix&&!k.startsWith(S.prefix+"/"))continue;let m=j(S.target,g),u=[...new Set(m.map(x=>x.service))];if(u.length===1)return{status:"service",service:u[0],via:`${S.kind} ${S.prefix||"/"} -> ${S.target.origin}`,origin:S.target.origin,basePath:S.target.path,strip:S.strip?S.prefix.split("/").filter(Boolean).length:0,evidence:[{env:null,file:S.file}]}}return{status:"unknown"}},portsOf:g=>[...o.get(g)?.ports??[]].sort((k,b)=>k-b),hostClaims:()=>[...i].sort((g,k)=>g[0]<k[0]?-1:1)}}function sn(e){try{return Kn.readdirSync(e).sort()}catch{return[]}}var rn=e=>String(e).toLowerCase();function cn(e){let t=[];for(let n of e)n.t==="lit"&&t.length&&t[t.length-1].t==="lit"?t[t.length-1]={t:"lit",v:t[t.length-1].v+n.v}:t.push(n);return t}function Sr(e,t){let n=[];for(let s of e){if(s.t!=="param"){n.push(s);continue}let o=t?.get(s.index);o?n.push(...o):n.push({t:"ref",name:s.name})}return cn(n)}function Qn(e){if(!e.length)return null;let t=e.slice(),n="none",s=null,o=t[0];if(o.t==="lit"){let l=/^(https?:)\/\/([^/?#]*)(.*)$/.exec(o.v);if(l){n="abs",s=l[2];let f=l[3];if(t=f?[{t:"lit",v:f},...t.slice(1)]:t.slice(1),/^(www\.)?(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)(:\d+)?$/.test(s)===!1&&!/\.(local|internal|svc)$/.test(s)&&!/^[a-z0-9-]+(:\d+)?$/.test(s))return null}else if(!o.v.startsWith("/"))return null}else{for(n="var";t.length&&t[0].t!=="lit";)t.shift();if(!t.length||!t[0].v.startsWith("/"))return null}let r="",i=0,c=!1;for(let l of t){if(c)break;if(l.t==="lit"){let f=l.v.search(/[?#]/);f>=0?(r+=l.v.slice(0,f),c=!0):r+=l.v}else r+="",i++}if(!r.startsWith("/")&&!(r===""&&n==="abs"))return null;r===""&&(r="/");let a=r.split("/").slice(1).map(l=>l.includes("")?":p":l);for(;a.length>1&&a[a.length-1]==="";)a.pop();return{base:n,host:s,segments:a,placeholders:i,literal:n==="none"&&i===0}}function kr(e){if(!e.length)return[];let t=e[0];if(t.t==="lit"){let s=/^((?:https?|wss?):\/\/[^/?#]*)/.exec(t.v);return s?[{t:"lit",v:s[1]}]:[]}let n=[];for(let s of e){if(s.t==="lit"&&s.v.startsWith("/"))break;n.push(s)}return n}var ra=e=>String(e||"").split("/").filter(Boolean),$r=e=>[...new Set(e)];function br(e){let t=e.evidence??[];return{env:$r(t.filter(n=>n.env).map(n=>n.env)),files:$r(t.filter(n=>n.file).map(n=>n.file)),origin:e.origin,via:e.via,...t.some(n=>n.fallback)?{usedFallback:!0}:{}}}var Nr=(e,t)=>"base URL "+(e.env.length?e.env.join(", ")+(e.files.length?" in "+e.files.join(", "):"")+" = ":e.files.length?"(from "+e.files.join(", ")+") ":"")+e.origin+" belongs to "+t+" ("+e.via+")",ia=e=>{let t=String(e).split(/[?#]/)[0].split("/").slice(1).map(n=>n.startsWith(":")||/^\{.*\}$/.test(n)||n==="*"?":p":n);for(;t.length>1&&t[t.length-1]==="";)t.pop();return t};function Ir(e,t){if(e.length===t.length){let n=!0,s=!0;for(let o=0;o<e.length;o++){let r=e[o],i=t[o];if(r!==i&&(n=!1),!(r===i||r===":p"||i===":p")){s=!1;break}}if(n)return 3;if(s)return 2}if(e[0]==="api"&&e.length>1){let n=e.slice(1);if(/^v\d+$/.test(n[0])&&n.length>1&&(n=n.slice(1)),n.length===t.length&&n.every((s,o)=>s===t[o]||s===":p"||t[o]===":p"))return 1}return 0}function ca(e,t,n,s,o){let r=(n.importBindings??[]).find(y=>y.local===s);if(!r)return null;let i=ye(r.source,t,o);if(!i)return null;let c=e.parseResults.get(i),a=y=>e.nodes.find(d=>d.filePath===i&&d.name===y&&d.type!=="moduleRoot")?.id??null;if(r.kind==="named"&&r.imported)return a(r.imported);let l=c?.exportBindings;if(l?.default&&l.default!=="<anon>")return a(l.default);let f=Object.keys(l?.named??{});return f.length===1?a(f[0]):null}function aa(e){let t=[],n=[...e.parseResults.keys()];for(let[s,o]of e.parseResults){let r=e.nodes.filter(a=>a.filePath===s);if(r[0]?.category!=="backend")continue;let i=Te(s,o),c=fe(s,e.nodes);for(let a of o.routes??[]){let l=null;a.isInlineHandler?l=i.get(a):a.nest?l=r.find(y=>y.type==="classMethod"&&y.className===a.nest.className&&y.name===a.nest.methodName)?.id??null:a.handlerName&&c.has(a.handlerName)?l=c.get(a.handlerName):a.handlerName&&(l=ca(e,s,o,a.handlerName,n));let f=!1;l||(l=ce(a.startLine,r)?.id??null,f=!0),l&&t.push({method:rn(a.method),path:a.path,segments:ia(a.path),literal:!/[:*{]/.test(a.path),nodeId:l,file:s,line:a.startLine,fallback:f})}}return t}var la=/^(ws|uws|websocket|@nestjs\/platform-ws|@fastify\/websocket|fastify-websocket|express-ws)$/,fa=/^(socket\.io|@nestjs\/platform-socket\.io|socket\.io-client)$/;function jr(e){let t=[...e].some(s=>fa.test(s)),n=[...e].some(s=>la.test(s));return t&&n?"unknown":t?"socketio":n?"ws":null}function ua(e){let t=[],n=new Set;for(let[,s]of e.parseResults)for(let o of s.imports??[])n.add(o.source);for(let[s,o]of e.parseResults){let r=o.socketListeners??[],i=r.find($=>$.eventName==="connection");if(!i)continue;let c=Te(s,o),a=fe(s,e.nodes),l=$=>$.isInlineHandler?c.get($):$.handlerName&&a.has($.handlerName)?a.get($.handlerName):null,f=l(i);if(!f)continue;let y=$=>i.handlerStartLine!=null&&$.startLine>=i.handlerStartLine&&$.startLine<=i.handlerEndLine,d=r.find($=>$.eventName==="message"&&y($))??r.find($=>$.eventName==="message"),w=o.httpClients?.wsServers??[],p=jr(new Set((o.imports??[]).map($=>$.source)))??jr(n)??"unknown";t.push({filePath:s,nodeId:f,line:i.startLine,messageNodeId:d?l(d):null,messageLine:d?.startLine??null,pathParts:w.find($=>$.path)?.path??null,kind:p})}return t}function Er(e,t,n={}){let s=n.repoRoot?xr(n.repoRoot,e,t):null,o=[],r=new Set,i={restCalls:0,restLinked:0,wsClients:0,wsLinked:0,wsSends:0,wsSendsLinked:0},c=l=>{let f=[l.fromService,l.fromNodeId,l.toService,l.toNodeId,l.via,l.key].join("\0");r.has(f)||(r.add(f),o.push(l))},a=new Map;for(let l of e){let f=t.get(l.name);f&&a.set(l.name,{routes:aa(f),wsServers:ua(f)})}for(let l of e){let f=t.get(l.name);if(!f)continue;let y=[...f.parseResults.keys()],d=new Map,w=new Map;for(let[m,u]of f.parseResults){let x=u.httpClients;if(x){for(let h of x.httpInstances??[])(d.get(h.name)??d.set(h.name,[]).get(h.name)).push(h);for(let h of x.httpCalls??[])(h.parts.some(I=>I.t==="param")||h.method&&typeof h.method=="object")&&h.fn?.name&&(w.get(h.fn.name)??w.set(h.fn.name,[]).get(h.fn.name)).push({filePath:m,call:h})}}let p=m=>{if(!m.startsWith("inst:")&&!m.startsWith("obj:"))return[];let u=d.get(m.slice(m.indexOf(":")+1));return u&&u.length===1?u[0].parts:m.startsWith("obj:")?null:[{t:"ref",name:"?"}]},$=[],j=(m,u)=>ce(u,f.nodes.filter(x=>x.filePath===m)),g=new Set,k=m=>m.parts.some(u=>u.t==="param")||m.method&&typeof m.method=="object";for(let[m,u]of f.parseResults){let x=u.httpClients;if(x){for(let h of x.httpCalls??[]){if(k(h))continue;let v=p(h.client);if(v===null)continue;let I=j(m,h.line);I&&$.push({filePath:m,line:h.line,nodeId:I.id,method:h.method,parts:cn([...v,...h.parts]),via:h.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let h of x.pathCallsites??[]){let v=w.get(h.callee);if(v)for(let I of v){let E=I.filePath===m;if(!E){let O=(u.importBindings??[]).find(R=>R.local===h.callee||R.imported===h.callee);O&&ye(O.source,m,y)===I.filePath&&(E=!0)}if(!E)continue;let M=new Map(h.args.map(O=>[O.i,O.parts])),A=typeof I.call.method=="object"&&I.call.method?(()=>{let O=M.get(I.call.method.param);return O&&O.length===1&&O[0].t==="lit"?O[0].v.toUpperCase():"?"})():I.call.method,L=j(m,h.line);L&&(g.add(I.call),$.push({filePath:m,line:h.line,nodeId:L.id,method:A,parts:Sr([...p(I.call.client),...I.call.parts],M),via:I.call.client,wrapper:h.callee}))}}}}for(let[m,u]of f.parseResults)for(let x of u.httpClients?.httpCalls??[]){if(!k(x)||g.has(x))continue;let h=p(x.client);if(h===null)continue;let v=j(m,x.line);v&&$.push({filePath:m,line:x.line,nodeId:v.id,method:typeof x.method=="object"&&x.method?"?":x.method,parts:Sr([...h,...x.parts],null),via:x.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let m of $){let u=Qn(m.parts);if(!u)continue;i.restCalls++;let x=0,h=[];for(let L of e){if(L.name===l.name)continue;let O=a.get(L.name);if(O)for(let R of O.routes){if(!(m.method==="?"||m.method==null||R.method===rn(m.method)||R.method==="all"||R.method==="use"))continue;let X=Ir(u.segments,R.segments);X&&(X>x&&(x=X,h.length=0),X===x&&h.push({service:L.name,route:R}))}}let v={status:"unknown"};if(s){let L=cn(m.parts);if(u.base==="none"?v=s.resolveProxy(l.name,"/"+u.segments.join("/")):v=s.resolveBase(l.name,kr(L)),v.status==="service"){let O=ra(v.basePath);if(O.length||v.strip){let R=[...O,...u.segments.slice(v.strip||0)];for(let z of a.get(v.service)?.routes??[])(m.method==="?"||m.method==null||z.method===rn(m.method)||z.method==="all"||z.method==="use")&&Ir(R,z.segments)&&!h.some(C=>C.service===v.service&&C.route.nodeId===z.nodeId)&&h.push({service:v.service,route:z,viaBasePath:!0})}}}if(!h.length)continue;let I=new Set(h.map(L=>L.service+"\0"+L.route.nodeId)),E=typeof m.method=="string"&&m.method!=="?",M=x===3&&u.literal&&E&&I.size===1&&h[0].route.literal&&!h[0].route.fallback&&h[0].route.method===rn(m.method),A=[];u.base==="var"&&A.push("base URL is a variable, so the target service is guessed from the path"),u.base==="abs"&&A.push("absolute URL"),u.placeholders&&A.push("path has parameters"),x===1&&A.push("leading /api removed from the client path"),x===2&&A.push("route parameters matched fuzzily"),E||A.push("method not known"),I.size>1&&A.push(I.size+" candidate routes"),h.some(L=>L.route.fallback)&&A.push("route handler not resolved: linked to the function that registers the route"),v.status==="external"&&A.push("base URL is "+v.origins.join(" / ")+", which no service of this repo owns"),v.status==="ambiguous"&&A.push("base URL could belong to "+v.services.join(" or "));for(let L of h){i.restLinked++;let O=!M&&v.status==="service"&&v.service===L.service&&!L.route.fallback,R=O?br(v):null,z=M?"exact":O?"resolved":"inferred",X=!M&&v.status==="service"&&v.service!==L.service?["base URL belongs to "+v.service+", not this service"]:[];c({fromService:l.name,fromNodeId:m.nodeId,toService:L.service,toNodeId:L.route.nodeId,via:"httpCall",key:`${E?m.method:"ANY"} ${"/"+u.segments.join("/")}`,confidence:z,method:E?m.method:null,url:"/"+u.segments.join("/"),client:m.via,...m.wrapper?{wrapper:m.wrapper}:{},line:m.line,...M?{}:O?{reason:Nr(R,L.service)+(E?"":"; method not known"),resolvedFrom:R}:{reason:[...A,...X].join("; ")||"path-only match"}})}}let b=[];for(let[m,u]of f.parseResults)for(let x of u.httpClients?.wsClients??[])b.push({filePath:m,w:x});let S=m=>m.client==="io"?"socketio":"ws";for(let{filePath:m,w:u}of b){let x=j(m,u.line);if(!x)continue;i.wsClients++;let h=cn(u.parts),v=/^wss?:\/\//.test(h[0]?.v??"")?Qn([{t:"lit",v:h[0].v.replace(/^ws(s?):/,"http$1:")},...h.slice(1)]):Qn(h),I=s&&v?s.resolveBase(l.name,kr(h)):{status:"unknown"};for(let E of e)if(E.name!==l.name)for(let M of a.get(E.name)?.wsServers??[]){if(M.kind!=="unknown"&&M.kind!==S(u))continue;let A=M.pathParts&&M.pathParts.every(X=>X.t==="lit")?"/"+M.pathParts.map(X=>X.v).join("").replace(/^\//,""):null,L=v?"/"+v.segments.join("/"):null;if(A&&L&&A!==L&&A!=="/"&&L!=="/")continue;let O=!!(v&&v.literal&&A&&L===A&&M.kind!=="unknown"),R=!O&&I.status==="service"&&I.service===E.name,z=R?br(I):null;i.wsLinked++,c({fromService:l.name,fromNodeId:x.id,toService:E.name,toNodeId:M.nodeId,via:"webSocket",key:L??"(url unknown)",confidence:O?"exact":R?"resolved":"inferred",url:L,client:u.client,line:u.line,...O?{}:R?{reason:Nr(z,E.name),resolvedFrom:z}:{reason:"WebSocket connection matched to a WebSocket server of another service ("+(v?.base==="var"?"URL base is a variable":"no path on the server to compare")+(I.status==="external"?"; base URL is "+I.origins.join(" / ")+", which no service of this repo owns":"")+")"}})}}if(b.length){let m=new Set(b.map(({w:u})=>S(u)));for(let[u,x]of f.parseResults)for(let h of x.httpClients?.wsSends??[]){let v=j(u,h.line);if(v){i.wsSends++;for(let I of e)if(I.name!==l.name)for(let E of a.get(I.name)?.wsServers??[])!E.messageNodeId||E.kind!=="unknown"&&!m.has(E.kind)||(i.wsSendsLinked++,c({fromService:l.name,fromNodeId:v.id,toService:I.name,toNodeId:E.messageNodeId,via:"webSocketMessage",key:"message",eventName:"message",confidence:"inferred",client:h.recv,line:h.line,reason:"a message sent over a socket whose payload is built at run time; delivered to the message listener of a WebSocket server of another service"}))}}}}if(n.serverPush!==!1){let l=new Map;for(let y of o)if(y.via==="webSocket"){let d=y.fromService+"\0"+y.toService;(l.get(d)??l.set(d,[]).get(d)).push(y)}let f=new Map;for(let y of l.values())(f.get(y[0].toService)??f.set(y[0].toService,new Set).get(y[0].toService)).add(y[0].fromService);for(let[,y]of[...l].sort((d,w)=>d[0]<w[0]?-1:1)){let d=y[0].fromService,w=y[0].toService,p=t.get(d),$=t.get(w);if(!p||!$||!(a.get(w)?.wsServers??[]).length)continue;let j=new Set(y.map(S=>S.fromNodeId.split("::")[0])),g=[];for(let[S,m]of p.parseResults){if(!j.has(S))continue;let u=fe(S,p.nodes),x=Te(S,m),h=p.nodes.filter(v=>v.filePath===S);for(let v of m.httpClients?.wsReceivers??[]){let I=v.handlerName&&u.get(v.handlerName)||ce(v.line,h)?.id;I&&g.push({id:I,line:v.line})}for(let v of m.socketListeners??[]){if(v.eventName!=="message")continue;let I=v.isInlineHandler?x.get(v):v.handlerName&&u.get(v.handlerName)||null;I&&g.push({id:I,line:v.startLine})}}let k=new Set(p.resolvedEdges.filter(S=>S.resolved&&S.targetNodeId&&S.type!=="returnValue").map(S=>S.fromNodeId));for(let S=g.length-1;S>=0;S--)k.has(g[S].id)||g.splice(S,1);if(!g.length)continue;let b=f.get(w)?.size??1;for(let[S,m]of $.parseResults){let u=$.nodes.filter(x=>x.filePath===S);for(let x of[...m.httpClients?.wsSends??[],...m.httpClients?.wsServerSends??[]]){let h=ce(x.line,u);if(h)for(let v of g)i.wsPushLinked=(i.wsPushLinked??0)+1,c({fromService:w,fromNodeId:h.id,toService:d,toNodeId:v.id,via:"webSocketDelivery",key:"message",eventName:"message",confidence:"inferred",client:x.recv,line:x.line,receiverLine:v.line,reason:"a message the server sends over a WebSocket (payload built at run time) is taken in by the message handler of "+d+", which connects to this server"+(b>1?"; "+b+" services connect to this server, so it may be meant for another one":""),...b>1?{candidates:b}:{}})}}}}return o.sort((l,f)=>l.fromService+l.fromNodeId+l.via+l.key+l.toService+l.toNodeId<f.fromService+f.fromNodeId+f.via+f.key+f.toService+f.toNodeId?-1:1),{edges:o,stats:i}}import Cr from"node:fs";var da=new Set("if for while switch catch return function super typeof new else do with await yield throw import export".split(" ")),pa=8;function Rr({files:e,resolveName:t,callArgs:n,matchClose:s,IDENT:o}){let r=new Map,i=m=>{let u=[],x=new RegExp(`\\bclass\\s+(${o})(?:\\s+extends\\s+(${o}))?[^{]*\\{`,"g"),h;for(;h=x.exec(m);){let v=h.index+h[0].length-1,I=s(m,v);I>0&&u.push({name:h[1],base:h[2]??null,open:v,close:I,start:h.index})}return u};for(let m of e){m.classes=i(m.t);for(let u of m.classes)r.set(u.name,(r.get(u.name)??0)+1)}let c=m=>r.get(m)===1,a=m=>{let u=m,x,h=/@[A-Za-z_$][\w$]*\s*\(/;for(;x=h.exec(u);){let v=s(u,x.index+x[0].length-1);if(v<0)break;u=u.slice(0,x.index)+u.slice(v+1)}return u},l="(?:(?:private|public|protected|readonly|override)\\s+)",f=m=>{let u=a(m).trim(),x=new RegExp(`^${l}*(${o})\\s*[?:=]`).exec(u)??new RegExp(`^${l}*(${o})\\s*$`).exec(u);return{name:x?x[1]:null,prop:new RegExp(`^${l}+`).test(u)}},y=(m,u)=>{let x=[],h=m.slice(u.open+1,u.close),v=new RegExp(`(?:^|[\\n;}{])\\s*(?:(?:public|private|protected|static|async|override)\\s+)*(${o})\\s*(?:<[^>(]*>)?\\s*\\(`,"g"),I;for(;I=v.exec(h);){if(da.has(I[1]))continue;let E=n(h,I.index+I[0].length-1);if(!E)continue;let M=E.close+1;for(;M<h.length&&/\s/.test(h[M]);)M++;if(h[M]===":"){let O=h.indexOf("{",M);if(O<0)continue;M=O}if(h[M]!=="{")continue;let A=s(h,M);if(A<0)continue;let L=E.args.map(O=>f(O.text));x.push({name:I[1],params:L.map(O=>O.name),paramProps:L.map(O=>O.prop),body:h.slice(M+1,A)}),v.lastIndex=A}return x};for(let m of e)for(let u of m.classes)u.methods=y(m.t,u),u.ctor=u.methods.find(x=>x.name==="constructor")??null;let d=new Map,w=new Map;for(let m of e)for(let u of m.classes)for(let x of u.methods){if(x.name==="constructor")continue;let h=new RegExp(`new\\s+(?:Queue|Bull|BullQueue)\\s*(?:<[^>]*>)?\\s*\\(\\s*(${o})\\s*[,)]`).exec(x.body);h&&x.params.includes(h[1])&&(d.has(x.name)||d.set(x.name,new Set),d.get(x.name).add(x.params.indexOf(h[1])));let v=new RegExp(`new\\s+Worker\\s*(?:<[^>]*>)?\\s*\\(\\s*(${o})\\s*,\\s*(${o})\\s*[,)]`).exec(x.body);v&&x.params.includes(v[1])&&x.params.includes(v[2])&&(w.has(x.name)||w.set(x.name,new Map),w.get(x.name).set(x.params.indexOf(v[1]),x.params.indexOf(v[2])))}let p=(m,u)=>{let x=m.ctor?.params[u];if(!x)return new Set;let h=new Set([x]);m.ctor.paramProps[u]&&h.add("this."+x);let v=new RegExp(`this\\.(${o})\\s*=\\s*${x.replace(/\$/g,"\\$")}\\s*[;,\\n]`,"g"),I;for(;I=v.exec(m.ctor.body);)h.add("this."+I[1]);return h},$=(m,u)=>{let x=[],h=new RegExp(`(?<![\\w$])${u}\\s*\\(`,"g"),v;for(;v=h.exec(m);){let I=n(m,v.index+v[0].length-1);I&&x.push(I.args.map(E=>E.text.trim()))}return x},j=new Map,g=new Map;for(let m of e)for(let u of m.classes){if(!c(u.name)||!u.ctor)continue;let x=m.t.slice(u.open,u.close),h=new RegExp(`new\\s+(?:Queue|Bull|BullQueue)\\s*(?:<[^>]*>)?\\s*\\(\\s*(${o})\\s*[,)]`).exec(u.ctor.body);if(h&&u.ctor.params.includes(h[1]))j.set(u.name,{file:m.file,paramIndex:u.ctor.params.indexOf(h[1])});else{let v=null;for(let I=0;I<u.ctor.params.length&&v===null;I++){let E=p(u,I);for(let[M,A]of d)for(let L of $(x,M))for(let O of A)L[O]!==void 0&&E.has(L[O])&&(v=I)}v!==null&&j.set(u.name,{file:m.file,paramIndex:v})}for(let v=0;v<u.ctor.params.length;v++){let I=p(u,v),E=new Map;for(let M of u.methods)for(let[A,L]of w)for(let O of $(M.body,A))for(let[R,z]of L)O[R]!==void 0&&I.has(O[R])&&O[z]!==void 0&&M.params.includes(O[z])&&E.set(M.name,M.params.indexOf(O[z]));for(let M=0;M<3&&E.size;M++)for(let A of u.methods)for(let[L,O]of[...E])for(let R of $(A.body,"this\\."+L))R[O]!==void 0&&A.params.includes(R[O])&&!E.has(A.name)&&E.set(A.name,A.params.indexOf(R[O]));if(E.size){g.set(u.name,{file:m.file,paramIndex:v,registrars:E});break}}}let k=m=>{for(let u=0;u<pa;u++){let x=!1;for(let h of e)for(let v of h.classes){if(!v.base||m.has(v.name)||!c(v.name)||!c(v.base))continue;let I=m.get(v.base);if(!I)continue;if(I.name!==void 0||!v.ctor){m.set(v.name,{...I}),x=!0;continue}let E=/\bsuper\s*\(/.exec(v.ctor.body);if(!E)continue;let A=n(v.ctor.body,E.index+E[0].length-1)?.args[I.paramIndex];if(!A)continue;let L=t(A.text,h.file,h.t);if(L){m.set(v.name,{...I,name:L.name,how:L.how+" passed to the base class"}),x=!0;continue}let O=v.ctor.params.indexOf(A.text.trim());O>=0&&(m.set(v.name,{...I,paramIndex:O}),x=!0)}if(!x)break}};k(j),k(g);let b=new Map,S=new Map;for(let[m,u]of j)u.name!==void 0&&b.set(m,{name:u.name,how:u.how});for(let[m,u]of g)u.name!==void 0&&S.set(m,u);return{producerClasses:b,workerClasses:S,unique:c}}var ma=/\b(?:Queue|Bull|Worker|Processor|InjectQueue|WorkerHost)\b|\.process\s*\(|\b[A-Za-z_$]*(?:Queue|Worker)[A-Za-z_$]*(?:Service|Base)\b|\b(?:createQueue|createWorker|initWorker)\b/,Ie="[A-Za-z_$][\\w$]*",ha=1024*1024;function _r(e){let t="",n=0,s=null;for(;n<e.length;){let o=e[n],r=e[n+1];if(s){if(t+=o,o==="\\"){t+=e[n+1]??"",n+=2;continue}o===s&&(s=null),n++}else if(o==="/"&&r==="/")for(;n<e.length&&e[n]!==`
|
|
12
12
|
`;)t+=" ",n++;else if(o==="/"&&r==="*"){for(t+=" ",n+=2;n<e.length&&!(e[n]==="*"&&e[n+1]==="/");)t+=e[n]===`
|
|
13
13
|
`?`
|
|
14
|
-
`:" ",n++;t+=" ",n+=2}else(o==='"'||o==="'"||o==="`")&&(s=o),t+=o,n++}return t}function
|
|
15
|
-
`&&t.push(n+1);return n=>{let s=0,o=t.length-1;for(;s<o;){let r=s+o+1>>1;t[r]<=n?s=r:o=r-1}return s+1}}var ua=e=>{let t=e.trim(),n=/^(['"])([^'"\\\n]*)\1$/.exec(t);return n?n[2]:(n=/^`([^`$\\]*)`$/.exec(t),n?n[1]:null)},Rr=e=>new RegExp(`(?:const|let|var|readonly|static)\\s+${e.replace(/\$/g,"\\$")}\\s*(?::[^=;{]+)?=\\s*(['"\`])([^'"\`$\\\\\\n]*)\\1`);function Kn(e,t){let n=t.exec(e);if(!n)return null;let s=e.indexOf("{",n.index+n[0].length-1);if(s<0)return null;let o=Zn(e,s);return o<0?null:e.slice(s+1,o)}function _r(e,t,n){let s=t.replace(/\$/g,"\\$"),o=n.replace(/\$/g,"\\$"),r=Kn(e,new RegExp(`\\benum\\s+${s}\\s*\\{`));if(r){let i=new RegExp(`(?:^|[,{\\s])${o}\\s*=\\s*(['"\`])([^'"\`$\\\\\\n]*)\\1`).exec(r);return i?i[2]:null}if(r=Kn(e,new RegExp(`(?:const|let|var)\\s+${s}\\s*(?::[^=]+)?=\\s*\\{`))??Kn(e,new RegExp(`\\bclass\\s+${s}\\b[^{]*\\{`)),r){let i=new RegExp(`(?:^|[,{\\s])(?:static\\s+(?:readonly\\s+)?)?${o}\\s*[:=]\\s*(['"\`])([^'"\`$\\\\\\n]*)\\1`).exec(r);return i?i[2]:null}return null}function da(e){let t=new Map,n=/import\s+(?:type\s+)?([^'";]*?)\s+from\s*['"]([^'"]+)['"]/g,s;for(;s=n.exec(e);){let o=s[1].trim(),r=s[2],i=/\{([^}]*)\}/.exec(o);if(i)for(let l of i[1].split(",")){let f=l.trim().replace(/^type\s+/,"");if(!f)continue;let h=/^(\S+)\s+as\s+(\S+)$/.exec(f);h?t.set(h[2],{spec:r,imported:h[1]}):t.set(f,{spec:r,imported:f})}let c=/\*\s*as\s+(\S+)/.exec(o);c&&t.set(c[1],{spec:r,imported:"*"});let a=/^([A-Za-z_$][\w$]*)\s*(?:,|$)/.exec(o);a&&!o.startsWith("{")&&!o.startsWith("*")&&t.set(a[1],{spec:r,imported:"default"})}return t}function Cr(e){let t=[],n,s=/export\s*\*\s*from\s*['"]([^'"]+)['"]/g;for(;n=s.exec(e);)t.push({spec:n[1],all:!0});let o=/export\s*\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g;for(;n=o.exec(e);){let r=new Map;for(let i of n[1].split(",")){let c=i.trim();if(!c)continue;let a=/^(\S+)\s+as\s+(\S+)$/.exec(c);a?r.set(a[2],a[1]):r.set(c,c)}t.push({spec:n[2],names:r})}return t}function Lr(e,t,{readFile:n=s=>jr.statSync(s).size>la?null:jr.readFileSync(s,"utf8")}={}){let s=[],o=new Map,r=new Map;for(let g of e){let x=t.get(g.name);if(x){for(let I of x.files??[])s.push(I),r.has(I)||r.set(I,g.name);for(let I of x.nodes){let E=g.name+"\0"+I.filePath;o.has(E)||o.set(E,[]),o.get(E).push(I)}}}let i=new Map,c=g=>{if(i.has(g))return i.get(g);let x=null;try{x=Er(n(g)??"")}catch{x=null}return i.size>400&&i.clear(),i.set(g,x),x},a=new Map,l=(g,x)=>{let I=a.get(g);return I||(I=da(x),a.set(g,I)),I};function f(g,x,I){let E=c(g);if(E==null||I>3)return null;let M=Rr(x).exec(E);if(M)return{value:M[2],how:"constant"};for(let O of Cr(E)){let L=O.all?x:O.names?.get(x);if(!L)continue;let B=me(O.spec,g,s);if(B){let _=f(B,L,I+1);if(_)return _}}return null}function h(g,x,I,E){let M=c(g);if(M==null||E>3)return null;let O=_r(M,x,I);if(O!=null)return{value:O,how:"enum or object member"};for(let L of Cr(M)){let B=L.all?x:L.names?.get(x);if(!B)continue;let _=me(L.spec,g,s);if(_){let U=h(_,B,I,E+1);if(U)return U}}return null}function u(g,x,I){let E=String(g).trim().replace(/\s+as\s+[\w.<>[\]| ]+$/,"").replace(/!$/,"").trim(),M=/^\{\s*name\s*:\s*([\s\S]+?)\s*[,}]?\s*\}?$/.exec(E);M&&!/^['"`]/.test(E)&&(E=M[1].trim());let O=ua(E);if(O!==null)return O?{name:O,how:"literal"}:null;let L=new RegExp(`^(${le})$`).exec(E);if(L){let B=Rr(L[1]).exec(I);if(B)return{name:B[2],how:"constant in the same file"};let _=l(x,I).get(L[1]);if(_&&_.imported!=="*"){let U=me(_.spec,x,s);if(U){let V=f(U,_.imported==="default"?L[1]:_.imported,0);if(V)return{name:V.value,how:"imported constant"}}}return null}if(L=new RegExp(`^(${le})\\.(${le})$`).exec(E),L){let B=_r(I,L[1],L[2]);if(B!=null)return{name:B,how:"enum or object member in the same file"};let _=l(x,I).get(L[1]);if(_){let U=me(_.spec,x,s);if(U){let V=_.imported==="*"?f(U,L[2],0):h(U,_.imported==="default"?L[1]:_.imported,L[2],0);if(V)return{name:V.value,how:_.imported==="*"?"imported constant":"imported enum or object member"}}}}return null}let v=[];for(let g of s){let x=r.get(g);if(!x)continue;let I=null;try{I=n(g)}catch{I=null}if(I==null||!aa.test(I))continue;let E=Er(I);v.push({file:g,service:x,t:E,line:fa(E)})}let d=new Map,k=new Map,j=g=>{let x=[],I=new RegExp(`\\bclass\\s+(${le})(?:\\s+extends\\s+(${le}))?[^{]*\\{`,"g"),E;for(;E=I.exec(g);){let M=E.index+E[0].length-1,O=Zn(g,M);O>0&&x.push({name:E[1],base:E[2]??null,open:M,close:O,start:E.index})}return x};for(let g of v)g.classes=j(g.t);for(let g of v)for(let x of g.classes){let I=g.t.slice(x.open,x.close),E=/\bconstructor\s*\(/.exec(I);if(!E)continue;let M=ct(I,E.index+E[0].length-1);if(!M)continue;let O=M.args.map(B=>{let _=new RegExp(`(${le})\\s*[?:=]`).exec(B.text.replace(/^\s*(?:@\w+\([^)]*\)\s*)*(?:(?:private|public|protected|readonly)\s+)*/,""))??new RegExp(`(${le})\\s*$`).exec(B.text);return _?_[1]:null}),L=new RegExp(`new\\s+(?:Queue|Bull|BullQueue)\\s*(?:<[^>]*>)?\\s*\\(\\s*(${le})\\s*[,)]`).exec(I);L&&O.includes(L[1])&&d.set(x.name,{file:g.file,paramIndex:O.indexOf(L[1])})}for(let g of v)for(let x of g.classes){if(!x.base||!d.has(x.base))continue;let I=g.t.slice(x.open,x.close),E=/\bsuper\s*\(/.exec(I);if(!E)continue;let O=ct(I,E.index+E[0].length-1)?.args[d.get(x.base).paramIndex];if(!O)continue;let L=u(O.text,g.file,g.t);L&&k.set(x.name,{...L,how:L.how+" passed to the base class"})}let p=[],S=[],$=0,w=0;for(let g of v){let{file:x,service:I,t:E}=g,M=o.get(I+"\0"+x)??[],O=H=>ie(g.line(H),M),L=new Map,B=(H,te)=>{(!L.has(H)||L.get(H)===null&&te)&&L.set(H,te)},_,U=new RegExp("new\\s+(?:Queue|Bull|BullQueue)\\s*(?:<[^>]*>)?\\s*\\(","g");for(;_=U.exec(E);){let H=E.slice(Math.max(0,_.index-160),_.index),te=new RegExp(`(${le})\\s*(?::[^=;]+)?=\\s*$`).exec(H),J=ct(E,_.index+_[0].length-1);!te||!J||!J.args[0]||B(te[1],u(J.args[0].text,x,E))}let V=new RegExp("@InjectQueue\\s*\\(","g");for(;_=V.exec(E);){let H=ct(E,_.index+_[0].length-1);if(!H)continue;let te=E.slice(H.close+1,H.close+200),J=new RegExp(`^\\s*(?:(?:private|public|protected|readonly)\\s+)*(${le})`).exec(te);J&&B(J[1],H.args[0]?u(H.args[0].text,x,E):null)}let R=new RegExp(`(?:private|public|protected)\\s+(?:readonly\\s+)?(${le})\\s*:\\s*(${le})`,"g");for(;_=R.exec(E);)k.has(_[2])&&B(_[1],k.get(_[2]));let z=new RegExp(`(${le})\\s*\\.\\s*(add|addBulk)\\s*\\(`,"g");for(;_=z.exec(E);){let H=L.get(_[1]);if(H===void 0)continue;let te=O(_.index);if(!H){$++;continue}te&&p.push({queue:H.name,how:H.how,service:I,nodeId:te.id,line:g.line(_.index)})}let X=(H,te)=>{let J=H.trim();if(/^(?:async\s+)?(?:function\b|\([^)]*\)\s*(?::[^=]+)?=>|[\w$]+\s*=>)/.test(J))return{node:O(te+H.indexOf(J)),how:"inline handler"};let be=new RegExp(`^this\\.(${le})(?:\\.bind\\(this\\))?$`).exec(J),Ce=be?be[1]:new RegExp(`^(${le})$`).exec(J)?.[1];if(!Ce)return null;let dt=M.filter(ge=>ge.type!=="moduleRoot"&&(ge.name===Ce||String(ge.name).endsWith("."+Ce)));if(dt.length===1)return{node:dt[0],how:"named handler"};let Be=l(x,E).get(Ce);if(Be){let ge=me(Be.spec,x,s);if(ge){let Qe=(o.get(r.get(ge)+"\0"+ge)??[]).filter(ye=>ye.type!=="moduleRoot"&&ye.name===(Be.imported==="default"?Ce:Be.imported));if(Qe.length===1)return{node:Qe[0],how:"imported handler",service:r.get(ge)}}}return null},se=new RegExp("new\\s+Worker\\s*(?:<[^>]*>)?\\s*\\(","g");for(;_=se.exec(E);){let H=ct(E,_.index+_[0].length-1);if(!H||H.args.length<2)continue;let te=u(H.args[0].text,x,E);if(!te){w++;continue}let J=X(H.args[1].text,H.args[1].start);J?.node&&S.push({queue:te.name,how:te.how+", "+J.how,service:J.service??I,nodeId:J.node.id,line:g.line(_.index)})}let re=new RegExp(`(${le})\\s*\\.\\s*process\\s*\\(`,"g");for(;_=re.exec(E);){let H=L.get(_[1]);if(H===void 0)continue;if(!H){w++;continue}let J=ct(E,_.index+_[0].length-1)?.args.at(-1);if(!J)continue;let be=X(J.text,J.start);be?.node&&S.push({queue:H.name,how:H.how+", "+be.how,service:be.service??I,nodeId:be.node.id,line:g.line(_.index)})}let ut=new RegExp("@Processor\\s*\\(","g");for(;_=ut.exec(E);){let H=ct(E,_.index+_[0].length-1);if(!H||!H.args[0])continue;let te=u(H.args[0].text,x,E),J=g.classes.find(ye=>ye.start>H.close&&ye.start-H.close<400);if(!J)continue;if(!te){w++;continue}let be=g.line(J.open),Ce=g.line(J.close),dt=E.slice(J.open,J.close),Be=new Set(["process"]),ge=new RegExp(`@Process\\s*\\([^)]*\\)\\s*(?:(?:public|private|protected|async)\\s+)*(${le})\\s*\\(`,"g"),Qe;for(;Qe=ge.exec(dt);)Be.add(Qe[1]);for(let ye of M){if(ye.type==="moduleRoot"||ye.startLine<be||ye.endLine>Ce)continue;let N=String(ye.name).split(".").pop();Be.has(N)&&S.push({queue:te.name,how:te.how+", @Processor class method",service:I,nodeId:ye.id,line:ye.startLine})}}}let y=new Map;for(let g of S)y.has(g.queue)||y.set(g.queue,new Map),y.get(g.queue).set(g.nodeId,g);let m=[],b=new Set;for(let g of p.sort((x,I)=>x.queue<I.queue?-1:x.queue>I.queue?1:x.nodeId<I.nodeId?-1:x.nodeId>I.nodeId?1:x.line-I.line)){let x=y.get(g.queue);if(x)for(let I of[...x.values()].sort((E,M)=>E.nodeId<M.nodeId?-1:E.nodeId>M.nodeId?1:0)){if(I.nodeId===g.nodeId)continue;let E=[g.service,g.nodeId,I.service,I.nodeId,g.queue,g.line].join("\0");b.has(E)||(b.add(E),m.push({fromService:g.service,fromNodeId:g.nodeId,toService:I.service,toNodeId:I.nodeId,via:"queue",key:g.queue,queueName:g.queue,confidence:"inferred",reason:`queue "${g.queue}" (name from ${g.how}; consumer: ${I.how})`,line:g.line}))}}return{edges:m,stats:{producers:p.length,consumers:S.length,unresolvedProducers:$,unresolvedConsumers:w,files:v.length}}}function Pr(e,t){let n=new Map;for(let[s,o]of e){let r=t.filter(c=>c.filePath===s),i=o.rawSocketTypeChecks??[];for(let c of i){let a=ie(c.startLine,r);a&&n.set(c.eventName,a.id)}}return n}import pa from"node:fs";import ma from"node:path";function Mr(e){let t=["index.html","public/index.html","client/index.html","frontend/index.html","src/index.html"];for(let n of t){let s=ma.join(e,n);if(pa.existsSync(s))return s}return null}import cn from"node:fs";import an from"node:path";var ha=new Set(["node","tsx","ts-node","nodemon","bun","deno","ts-node-esm"]),ga=new Set(["watch","run","start","dev"]),ya=/\.[cm]?[jt]sx?$/,va=["start","dev","serve","run"];function wa(e){for(let t of String(e).split(/&&|\|\||;|\|/)){let n=t.trim().split(/\s+/).filter(Boolean).map(o=>o.replace(/^["']|["']$/g,"")),s=n.findIndex(o=>ha.has(an.basename(o).replace(/\.cmd$/,"")));if(!(s<0)){for(let o of n.slice(s+1))if(!(o.startsWith("-")||ga.has(o)||o.includes("="))){if(ya.test(o))return o;break}}}return null}var xa=e=>String(e).replace(/^@[^/]+\//,"");function Tr(e){let t;try{t=JSON.parse(cn.readFileSync(an.join(e,"package.json"),"utf8"))}catch{return[]}let n=[],s=(o,r,i={})=>{if(typeof o!="string"||!o)return;let c=r==="script"?null:tn(e,o,t);c?n.push({file:c.file,kind:r,...i,mappedFrom:o,mappedBy:c.how}):n.push({file:an.resolve(e,o),kind:r,...i})};if(typeof t.bin=="string")s(t.bin,"bin",{binName:xa(t.name??an.basename(e))});else if(t.bin&&typeof t.bin=="object")for(let[o,r]of Object.entries(t.bin))s(r,"bin",{binName:o});for(let o of va){let r=t.scripts?.[o]&&wa(t.scripts[o]);r&&s(r,"script")}return s(t.main,"main"),n}function Or(e){try{let t=cn.openSync(e,"r"),n=Buffer.alloc(120),s=cn.readSync(t,n,0,120,0);return cn.closeSync(t),/^#!.*\b(node|tsx|ts-node|bun)\b/.test(n.toString("utf8",0,s).split(/\r?\n/)[0])}catch{return!1}}import ln from"node:fs";import at from"node:path";var Sa=50,ka=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Ar=["",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts","/index.js","/index.ts","/index.mjs","/index.cjs","/index.tsx","/index.jsx"];function Qn(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=Qn(t);if(n)return n}return null}if(e&&typeof e=="object")for(let t of["import","node","require","default"]){let n=Qn(e[t]);if(n)return n}return null}function Fr(e,t){let n;try{n=JSON.parse(ln.readFileSync(at.join(e,"package.json"),"utf8"))}catch{return null}let s=n.exports,o=typeof s=="string"||Array.isArray(s)?s:s&&typeof s=="object"?s["."]??(Object.keys(s).some(l=>l.startsWith("."))?null:s):null,r=Qn(o)??(typeof n.module=="string"?n.module:null)??(typeof n.main=="string"?n.main:null);if(!r)return null;let i=new Set(t.map(l=>at.resolve(l))),c=at.resolve(e,r);for(let l of Ar)if(i.has(c+l))return t.find(f=>at.resolve(f)===c+l);let a=[];try{a=ln.readdirSync(e).filter(l=>ka.test(l)).sort()}catch{}for(let l of a){let f;try{f=ln.readFileSync(at.join(e,l),"utf8")}catch{continue}let h=/\bentry(?:Points)?\s*:\s*[\[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/.exec(f);if(!h)continue;let u=at.resolve(e,h[1]);for(let v of Ar)if(i.has(u+v))return t.find(d=>at.resolve(d)===u+v)}return null}function Br(e,t,n,s,o=null){let r=new Map;for(let k of n){let j=r.get(k.filePath);j||r.set(k.filePath,j=[]),j.push(k)}let i=new Map,c=(k,j)=>{j&&(!i.has(j.id)||k<i.get(j.id))&&i.set(j.id,k)},a=new Map,l=(k,j)=>{let p=a.get(k);if(!p){p=new Map;let S="";try{S=ln.readFileSync(k,"utf8")}catch{}for(let $ of S.matchAll(/^[ \t]*(?:export\s+)?const\s+([\w$]+)\s*(?::[^=\n]+)?=\s*([\w$]+)\s*(?:as\s+[^;\n]+)?;?[ \t]*$/gm))$[1]!==$[2]&&p.set($[1],$[2]);a.set(k,p)}return p.get(j)??null},f=(k,j)=>(r.get(k)??[]).find(p=>(p.type==="function"||p.type==="arrowFunction")&&p.name===j),h=(k,j)=>(r.get(k)??[]).filter(p=>p.type==="classMethod"&&p.className===j&&p.name!=="constructor"&&!/^[_#]/.test(p.name)),u=new Set;function v(k,j,p,S=0){let $=f(k,p);if($){c(j,$);return}let w=h(k,p);for(let I of w)c(`${j}.${I.name}`,I);if(w.length||!o)return;let y=o.resolveName(k,p);if(y){c(j,y);return}let m=o.bindingFor(k,p),b=m&&S<3?o.resolveImport(k,m.source,m.kind,m.imported):null;if(b?.file&&b.local&&b.local!=="default"&&l(b.file,b.local)){v(b.file,j,b.local,S+1);return}let g=o.classForImport(k,p);if(g?.className)for(let I of h(g.file,g.className))c(`${j}.${I.name}`,I);if(g?.className)return;let x=l(k,p);x&&S<3&&v(k,j,x,S+1)}function d(k,j,p){let S=k+"|"+(p?[...p.keys()].sort().join(","):"*");if(u.has(S)||j>3)return;u.add(S);let $=t.get(k)?.exportBindings;if(!$)return;let w=y=>!p||p.has(y);for(let[y,m]of Object.entries($.named??{}))w(y)&&v(k,p?.get(y)??y,m);$.default&&w("default")&&$.default!=="<anon>"&&v(k,p?.get("default")??$.default,$.default);for(let y of $.reexports??[]){if(!w(y.exported))continue;let m=me(y.source,k,s);m&&d(m,j+1,new Map([[y.imported,p?.get(y.exported)??y.exported]]))}for(let y of $.stars??[]){let m=me(y,k,s);m&&(p?d(m,j+1,p):d(m,j+1,null))}}return d(e,0,null),[...i].map(([k,j])=>({name:j,nodeId:k})).sort((k,j)=>k.name<j.name?-1:k.name>j.name?1:k.nodeId<j.nodeId?-1:1).slice(0,Sa)}import fn from"node:fs";import jt from"node:path";var eo=null,to=null,Dr=()=>eo?jt.join(eo,".canopy","last-stage.txt"):null,Hr=e=>{eo=e?jt.resolve(e):null},un=()=>to;function $a(){let e=process.memoryUsage(),t=n=>Math.round(n/1048576);return{rssMB:t(e.rss),heapUsedMB:t(e.heapUsed),externalMB:t(e.external),arrayBuffersMB:t(e.arrayBuffers)}}var ba=()=>process.env.CANOPY_DEBUG_MEM==="1"||process.env.CANOPY_DEBUG_MEM==="true";function Ge(e){to=e;let t=Dr();if(t)try{fn.mkdirSync(jt.dirname(t),{recursive:!0}),fn.writeFileSync(t,e)}catch{}if(ba()){let n=$a();process.stderr.write(`[mem] ${e}: rss ${n.rssMB} MB, heapUsed ${n.heapUsedMB} MB, external ${n.externalMB} MB, arrayBuffers ${n.arrayBuffersMB} MB
|
|
16
|
-
`)}}function
|
|
14
|
+
`:" ",n++;t+=" ",n+=2}else(o==='"'||o==="'"||o==="`")&&(s=o),t+=o,n++}return t}function to(e,t){let n={"(":")","[":"]","{":"}"},s=[],o=null;for(let r=t;r<e.length;r++){let i=e[r];if(o){i==="\\"?r++:i===o&&(o=null);continue}if(i==='"'||i==="'"||i==="`"){o=i;continue}if(n[i])s.push(n[i]);else if(i===")"||i==="]"||i==="}"){if(s.pop()!==i)return-1;if(!s.length)return r}}return-1}function at(e,t){let n=to(e,t);if(n<0)return null;let s=[],o=0,r=null,i=t+1;for(let c=t+1;c<n;c++){let a=e[c];if(r){a==="\\"?c++:a===r&&(r=null);continue}if(a==='"'||a==="'"||a==="`"){r=a;continue}a==="("||a==="["||a==="{"?o++:a===")"||a==="]"||a==="}"?o--:a===","&&o===0&&(s.push({text:e.slice(i,c),start:i}),i=c+1)}return e.slice(i,n).trim()&&s.push({text:e.slice(i,n),start:i}),{args:s,close:n}}function ga(e){let t=[0];for(let n=0;n<e.length;n++)e[n]===`
|
|
15
|
+
`&&t.push(n+1);return n=>{let s=0,o=t.length-1;for(;s<o;){let r=s+o+1>>1;t[r]<=n?s=r:o=r-1}return s+1}}var ya=e=>{let t=e.trim(),n=/^(['"])([^'"\\\n]*)\1$/.exec(t);return n?n[2]:(n=/^`([^`$\\]*)`$/.exec(t),n?n[1]:null)},Lr=e=>new RegExp(`(?:const|let|var|readonly|static)\\s+${e.replace(/\$/g,"\\$")}\\s*(?::[^=;{]+)?=\\s*(['"\`])([^'"\`$\\\\\\n]*)\\1`);function eo(e,t){let n=t.exec(e);if(!n)return null;let s=e.indexOf("{",n.index+n[0].length-1);if(s<0)return null;let o=to(e,s);return o<0?null:e.slice(s+1,o)}function Pr(e,t,n){let s=t.replace(/\$/g,"\\$"),o=n.replace(/\$/g,"\\$"),r=eo(e,new RegExp(`\\benum\\s+${s}\\s*\\{`));if(r){let i=new RegExp(`(?:^|[,{\\s])${o}\\s*=\\s*(['"\`])([^'"\`$\\\\\\n]*)\\1`).exec(r);return i?i[2]:null}if(r=eo(e,new RegExp(`(?:const|let|var)\\s+${s}\\s*(?::[^=]+)?=\\s*\\{`))??eo(e,new RegExp(`\\bclass\\s+${s}\\b[^{]*\\{`)),r){let i=new RegExp(`(?:^|[,{\\s])(?:static\\s+(?:readonly\\s+)?)?${o}\\s*[:=]\\s*(['"\`])([^'"\`$\\\\\\n]*)\\1`).exec(r);return i?i[2]:null}return null}function va(e){let t=new Map,n=/import\s+(?:type\s+)?([^'";]*?)\s+from\s*['"]([^'"]+)['"]/g,s;for(;s=n.exec(e);){let o=s[1].trim(),r=s[2],i=/\{([^}]*)\}/.exec(o);if(i)for(let l of i[1].split(",")){let f=l.trim().replace(/^type\s+/,"");if(!f)continue;let y=/^(\S+)\s+as\s+(\S+)$/.exec(f);y?t.set(y[2],{spec:r,imported:y[1]}):t.set(f,{spec:r,imported:f})}let c=/\*\s*as\s+(\S+)/.exec(o);c&&t.set(c[1],{spec:r,imported:"*"});let a=/^([A-Za-z_$][\w$]*)\s*(?:,|$)/.exec(o);a&&!o.startsWith("{")&&!o.startsWith("*")&&t.set(a[1],{spec:r,imported:"default"})}return t}function Mr(e){let t=[],n,s=/export\s*\*\s*from\s*['"]([^'"]+)['"]/g;for(;n=s.exec(e);)t.push({spec:n[1],all:!0});let o=/export\s*\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g;for(;n=o.exec(e);){let r=new Map;for(let i of n[1].split(",")){let c=i.trim();if(!c)continue;let a=/^(\S+)\s+as\s+(\S+)$/.exec(c);a?r.set(a[2],a[1]):r.set(c,c)}t.push({spec:n[2],names:r})}return t}function Or(e,t,{readFile:n=s=>Cr.statSync(s).size>ha?null:Cr.readFileSync(s,"utf8")}={}){let s=[],o=new Map,r=new Map;for(let h of e){let v=t.get(h.name);if(v){for(let I of v.files??[])s.push(I),r.has(I)||r.set(I,h.name);for(let I of v.nodes){let E=h.name+"\0"+I.filePath;o.has(E)||o.set(E,[]),o.get(E).push(I)}}}let i=new Map,c=h=>{if(i.has(h))return i.get(h);let v=null;try{v=_r(n(h)??"")}catch{v=null}return i.size>400&&i.clear(),i.set(h,v),v},a=new Map,l=(h,v)=>{let I=a.get(h);return I||(I=va(v),a.set(h,I)),I};function f(h,v,I){let E=c(h);if(E==null||I>3)return null;let M=Lr(v).exec(E);if(M)return{value:M[2],how:"constant"};for(let A of Mr(E)){let L=A.all?v:A.names?.get(v);if(!L)continue;let O=ye(A.spec,h,s);if(O){let R=f(O,L,I+1);if(R)return R}}return null}function y(h,v,I,E){let M=c(h);if(M==null||E>3)return null;let A=Pr(M,v,I);if(A!=null)return{value:A,how:"enum or object member"};for(let L of Mr(M)){let O=L.all?v:L.names?.get(v);if(!O)continue;let R=ye(L.spec,h,s);if(R){let z=y(R,O,I,E+1);if(z)return z}}return null}function d(h,v,I){let E=String(h).trim().replace(/\s+as\s+[\w.<>[\]| ]+$/,"").replace(/!$/,"").trim(),M=/^\{\s*name\s*:\s*([\s\S]+?)\s*[,}]?\s*\}?$/.exec(E);M&&!/^['"`]/.test(E)&&(E=M[1].trim());let A=ya(E);if(A!==null)return A?{name:A,how:"literal"}:null;let L=new RegExp(`^(${Ie})$`).exec(E);if(L){let O=Lr(L[1]).exec(I);if(O)return{name:O[2],how:"constant in the same file"};let R=l(v,I).get(L[1]);if(R&&R.imported!=="*"){let z=ye(R.spec,v,s);if(z){let X=f(z,R.imported==="default"?L[1]:R.imported,0);if(X)return{name:X.value,how:"imported constant"}}}return null}if(L=new RegExp(`^(${Ie})\\.(${Ie})$`).exec(E),L){let O=Pr(I,L[1],L[2]);if(O!=null)return{name:O,how:"enum or object member in the same file"};let R=l(v,I).get(L[1]);if(R){let z=ye(R.spec,v,s);if(z){let X=R.imported==="*"?f(z,L[2],0):y(z,R.imported==="default"?L[1]:R.imported,L[2],0);if(X)return{name:X.value,how:R.imported==="*"?"imported constant":"imported enum or object member"}}}}return null}let w=[];for(let h of s){let v=r.get(h);if(!v)continue;let I=null;try{I=n(h)}catch{I=null}if(I==null||!ma.test(I))continue;let E=_r(I);w.push({file:h,service:v,t:E,line:ga(E)})}let{producerClasses:p,workerClasses:$,unique:j}=Rr({files:w,resolveName:d,callArgs:at,matchClose:to,IDENT:Ie}),g=[],k=[],b=0,S=0;for(let h of w){let{file:v,service:I,t:E}=h,M=o.get(I+"\0"+v)??[],A=F=>ce(h.line(F),M),L=new Map,O=(F,G)=>{(!L.has(F)||L.get(F)===null&&G)&&L.set(F,G)},R,z=new RegExp("new\\s+(?:Queue|Bull|BullQueue)\\s*(?:<[^>]*>)?\\s*\\(","g");for(;R=z.exec(E);){let F=E.slice(Math.max(0,R.index-160),R.index),G=new RegExp(`(${Ie})\\s*(?::[^=;]+)?=\\s*$`).exec(F),J=at(E,R.index+R[0].length-1);!G||!J||!J.args[0]||O(G[1],d(J.args[0].text,v,E))}let X=new RegExp("@InjectQueue\\s*\\(","g");for(;R=X.exec(E);){let F=at(E,R.index+R[0].length-1);if(!F)continue;let G=E.slice(F.close+1,F.close+200),J=new RegExp(`^\\s*(?:(?:private|public|protected|readonly)\\s+)*(${Ie})`).exec(G);J&&O(J[1],F.args[0]?d(F.args[0].text,v,E):null)}let C=new RegExp(`(?:private|public|protected)\\s+(?:readonly\\s+)?(${Ie})\\s*:\\s*(${Ie})`,"g"),W=new Map;for(;R=C.exec(E);)p.has(R[2])&&j(R[2])&&O(R[1],p.get(R[2])),$.has(R[2])&&j(R[2])&&W.set(R[1],$.get(R[2]));let Z=new RegExp(`(${Ie})\\s*\\.\\s*(add|addBulk)\\s*\\(`,"g");for(;R=Z.exec(E);){let F=L.get(R[1]);if(F===void 0)continue;let G=A(R.index);if(!F){b++;continue}G&&g.push({queue:F.name,how:F.how,service:I,nodeId:G.id,line:h.line(R.index)})}let oe=(F,G)=>{let J=F.trim();if(/^(?:async\s+)?(?:function\b|\([^)]*\)\s*(?::[^=]+)?=>|[\w$]+\s*=>)/.test(J))return{node:A(G+F.indexOf(J)),how:"inline handler"};let ae=new RegExp(`^this\\.(${Ie})(?:\\.bind\\(this\\)|\\(\\s*\\))?$`).exec(J),$e=ae?ae[1]:new RegExp(`^(${Ie})$`).exec(J)?.[1];if(!$e)return null;let he=M.filter(re=>re.type!=="moduleRoot"&&(re.name===$e||String(re.name).endsWith("."+$e)));if(he.length===1)return{node:he[0],how:"named handler"};if(ae&&he.length>1){let re=h.classes.filter(N=>N.open<=G&&G<=N.close).sort((N,_)=>_.open-N.open)[0];if(re){let N=he.filter(_=>_.startLine>=h.line(re.open)&&_.endLine<=h.line(re.close));if(N.length===1)return{node:N[0],how:"named handler"}}}let Me=l(v,E).get($e);if(Me){let re=ye(Me.spec,v,s);if(re){let N=(o.get(r.get(re)+"\0"+re)??[]).filter(_=>_.type!=="moduleRoot"&&_.name===(Me.imported==="default"?$e:Me.imported));if(N.length===1)return{node:N[0],how:"imported handler",service:r.get(re)}}}return null},ie=new RegExp("new\\s+Worker\\s*(?:<[^>]*>)?\\s*\\(","g");for(;R=ie.exec(E);){let F=at(E,R.index+R[0].length-1);if(!F||F.args.length<2)continue;let G=d(F.args[0].text,v,E);if(!G){S++;continue}let J=oe(F.args[1].text,F.args[1].start);J?.node&&k.push({queue:G.name,how:G.how+", "+J.how,service:J.service??I,nodeId:J.node.id,line:h.line(R.index)})}let dt=new RegExp(`(${Ie})\\s*\\.\\s*process\\s*\\(`,"g");for(;R=dt.exec(E);){let F=L.get(R[1]);if(F===void 0)continue;if(!F){S++;continue}let J=at(E,R.index+R[0].length-1)?.args.at(-1);if(!J)continue;let ae=oe(J.text,J.start);ae?.node&&k.push({queue:F.name,how:F.how+", "+ae.how,service:ae.service??I,nodeId:ae.node.id,line:h.line(R.index)})}let et=new RegExp("@Processor\\s*\\(","g");for(;R=et.exec(E);){let F=at(E,R.index+R[0].length-1);if(!F||!F.args[0])continue;let G=d(F.args[0].text,v,E),J=h.classes.find(_=>_.start>F.close&&_.start-F.close<400);if(!J)continue;if(!G){S++;continue}let ae=h.line(J.open),$e=h.line(J.close),he=E.slice(J.open,J.close),Me=new Set(["process"]),re=new RegExp(`@Process\\s*\\([^)]*\\)\\s*(?:(?:public|private|protected|async)\\s+)*(${Ie})\\s*\\(`,"g"),N;for(;N=re.exec(he);)Me.add(N[1]);for(let _ of M){if(_.type==="moduleRoot"||_.startLine<ae||_.endLine>$e)continue;let B=String(_.name).split(".").pop();Me.has(B)&&k.push({queue:G.name,how:G.how+", @Processor class method",service:I,nodeId:_.id,line:_.startLine})}}let bt=(F,G,J,ae,$e)=>{let he;for(;he=ae.exec(G);){let re=at(G,he.index+he[0].length-1)?.args[F.hi];if(!re)continue;let N=oe(re.text,J+re.start);N?.node&&k.push({queue:F.name,how:F.how+", "+N.how+" registered through the worker base class",service:N.service??I,nodeId:N.node.id,line:$e(J+he.index)})}};for(let F of h.classes){let G=$.get(F.name);if(!G||!j(F.name))continue;let J=E.slice(F.open,F.close);for(let[ae,$e]of G.registrars)bt({name:G.name,how:G.how,hi:$e},J,F.open,new RegExp(`this\\.${ae}\\s*\\(`,"g"),h.line)}for(let[F,G]of W)for(let[J,ae]of G.registrars)bt({name:G.name,how:G.how,hi:ae},E,0,new RegExp(`\\b${F.replace(/\$/g,"\\$")}\\s*\\.\\s*${J}\\s*\\(`,"g"),h.line)}let m=new Map;for(let h of k)m.has(h.queue)||m.set(h.queue,new Map),m.get(h.queue).set(h.nodeId,h);let u=[],x=new Set;for(let h of g.sort((v,I)=>v.queue<I.queue?-1:v.queue>I.queue?1:v.nodeId<I.nodeId?-1:v.nodeId>I.nodeId?1:v.line-I.line)){let v=m.get(h.queue);if(v)for(let I of[...v.values()].sort((E,M)=>E.nodeId<M.nodeId?-1:E.nodeId>M.nodeId?1:0)){if(I.nodeId===h.nodeId)continue;let E=[h.service,h.nodeId,I.service,I.nodeId,h.queue,h.line].join("\0");x.has(E)||(x.add(E),u.push({fromService:h.service,fromNodeId:h.nodeId,toService:I.service,toNodeId:I.nodeId,via:"queue",key:h.queue,queueName:h.queue,confidence:"inferred",reason:`queue "${h.queue}" (name from ${h.how}; consumer: ${I.how})`,line:h.line}))}}return{edges:u,stats:{producers:g.length,consumers:k.length,unresolvedProducers:b,unresolvedConsumers:S,files:w.length}}}function Ar(e,t){let n=new Map;for(let[s,o]of e){let r=t.filter(c=>c.filePath===s),i=o.rawSocketTypeChecks??[];for(let c of i){let a=ce(c.startLine,r);a&&n.set(c.eventName,a.id)}}return n}import wa from"node:fs";import xa from"node:path";function Tr(e){let t=["index.html","public/index.html","client/index.html","frontend/index.html","src/index.html"];for(let n of t){let s=xa.join(e,n);if(wa.existsSync(s))return s}return null}import an from"node:fs";import ln from"node:path";var Sa=new Set(["node","tsx","ts-node","nodemon","bun","deno","ts-node-esm"]),ka=new Set(["watch","run","start","dev"]),$a=/\.[cm]?[jt]sx?$/,ba=["start","dev","serve","run"];function Na(e){for(let t of String(e).split(/&&|\|\||;|\|/)){let n=t.trim().split(/\s+/).filter(Boolean).map(o=>o.replace(/^["']|["']$/g,"")),s=n.findIndex(o=>Sa.has(ln.basename(o).replace(/\.cmd$/,"")));if(!(s<0)){for(let o of n.slice(s+1))if(!(o.startsWith("-")||ka.has(o)||o.includes("="))){if($a.test(o))return o;break}}}return null}var Ia=e=>String(e).replace(/^@[^/]+\//,"");function Fr(e){let t;try{t=JSON.parse(an.readFileSync(ln.join(e,"package.json"),"utf8"))}catch{return[]}let n=[],s=(o,r,i={})=>{if(typeof o!="string"||!o)return;let c=r==="script"?null:nn(e,o,t);c?n.push({file:c.file,kind:r,...i,mappedFrom:o,mappedBy:c.how}):n.push({file:ln.resolve(e,o),kind:r,...i})};if(typeof t.bin=="string")s(t.bin,"bin",{binName:Ia(t.name??ln.basename(e))});else if(t.bin&&typeof t.bin=="object")for(let[o,r]of Object.entries(t.bin))s(r,"bin",{binName:o});for(let o of ba){let r=t.scripts?.[o]&&Na(t.scripts[o]);r&&s(r,"script")}return s(t.main,"main"),n}function Br(e){try{let t=an.openSync(e,"r"),n=Buffer.alloc(120),s=an.readSync(t,n,0,120,0);return an.closeSync(t),/^#!.*\b(node|tsx|ts-node|bun)\b/.test(n.toString("utf8",0,s).split(/\r?\n/)[0])}catch{return!1}}import fn from"node:fs";import lt from"node:path";var ja=50,Ea=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Dr=["",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts","/index.js","/index.ts","/index.mjs","/index.cjs","/index.tsx","/index.jsx"];function no(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=no(t);if(n)return n}return null}if(e&&typeof e=="object")for(let t of["import","node","require","default"]){let n=no(e[t]);if(n)return n}return null}function Hr(e,t){let n;try{n=JSON.parse(fn.readFileSync(lt.join(e,"package.json"),"utf8"))}catch{return null}let s=n.exports,o=typeof s=="string"||Array.isArray(s)?s:s&&typeof s=="object"?s["."]??(Object.keys(s).some(l=>l.startsWith("."))?null:s):null,r=no(o)??(typeof n.module=="string"?n.module:null)??(typeof n.main=="string"?n.main:null);if(!r)return null;let i=new Set(t.map(l=>lt.resolve(l))),c=lt.resolve(e,r);for(let l of Dr)if(i.has(c+l))return t.find(f=>lt.resolve(f)===c+l);let a=[];try{a=fn.readdirSync(e).filter(l=>Ea.test(l)).sort()}catch{}for(let l of a){let f;try{f=fn.readFileSync(lt.join(e,l),"utf8")}catch{continue}let y=/\bentry(?:Points)?\s*:\s*[\[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/.exec(f);if(!y)continue;let d=lt.resolve(e,y[1]);for(let w of Dr)if(i.has(d+w))return t.find(p=>lt.resolve(p)===d+w)}return null}function zr(e,t,n,s,o=null){let r=new Map;for(let $ of n){let j=r.get($.filePath);j||r.set($.filePath,j=[]),j.push($)}let i=new Map,c=($,j)=>{j&&(!i.has(j.id)||$<i.get(j.id))&&i.set(j.id,$)},a=new Map,l=($,j)=>{let g=a.get($);if(!g){g=new Map;let k="";try{k=fn.readFileSync($,"utf8")}catch{}for(let b of k.matchAll(/^[ \t]*(?:export\s+)?const\s+([\w$]+)\s*(?::[^=\n]+)?=\s*([\w$]+)\s*(?:as\s+[^;\n]+)?;?[ \t]*$/gm))b[1]!==b[2]&&g.set(b[1],b[2]);a.set($,g)}return g.get(j)??null},f=($,j)=>(r.get($)??[]).find(g=>(g.type==="function"||g.type==="arrowFunction")&&g.name===j),y=($,j)=>(r.get($)??[]).filter(g=>g.type==="classMethod"&&g.className===j&&g.name!=="constructor"&&!/^[_#]/.test(g.name)),d=new Set;function w($,j,g,k=0){let b=f($,g);if(b){c(j,b);return}let S=y($,g);for(let I of S)c(`${j}.${I.name}`,I);if(S.length||!o)return;let m=o.resolveName($,g);if(m){c(j,m);return}let u=o.bindingFor($,g),x=u&&k<3?o.resolveImport($,u.source,u.kind,u.imported):null;if(x?.file&&x.local&&x.local!=="default"&&l(x.file,x.local)){w(x.file,j,x.local,k+1);return}let h=o.classForImport($,g);if(h?.className)for(let I of y(h.file,h.className))c(`${j}.${I.name}`,I);if(h?.className)return;let v=l($,g);v&&k<3&&w($,j,v,k+1)}function p($,j,g){let k=$+"|"+(g?[...g.keys()].sort().join(","):"*");if(d.has(k)||j>3)return;d.add(k);let b=t.get($)?.exportBindings;if(!b)return;let S=m=>!g||g.has(m);for(let[m,u]of Object.entries(b.named??{}))S(m)&&w($,g?.get(m)??m,u);b.default&&S("default")&&b.default!=="<anon>"&&w($,g?.get("default")??b.default,b.default);for(let m of b.reexports??[]){if(!S(m.exported))continue;let u=ye(m.source,$,s);u&&p(u,j+1,new Map([[m.imported,g?.get(m.exported)??m.exported]]))}for(let m of b.stars??[]){let u=ye(m,$,s);u&&(g?p(u,j+1,g):p(u,j+1,null))}}return p(e,0,null),[...i].map(([$,j])=>({name:j,nodeId:$})).sort(($,j)=>$.name<j.name?-1:$.name>j.name?1:$.nodeId<j.nodeId?-1:1).slice(0,ja)}import un from"node:fs";import Ct from"node:path";var oo=null,so=null,Wr=()=>oo?Ct.join(oo,".canopy","last-stage.txt"):null,Ur=e=>{oo=e?Ct.resolve(e):null},dn=()=>so;function Ra(){let e=process.memoryUsage(),t=n=>Math.round(n/1048576);return{rssMB:t(e.rss),heapUsedMB:t(e.heapUsed),externalMB:t(e.external),arrayBuffersMB:t(e.arrayBuffers)}}var Ca=()=>process.env.CANOPY_DEBUG_MEM==="1"||process.env.CANOPY_DEBUG_MEM==="true";function Ye(e){so=e;let t=Wr();if(t)try{un.mkdirSync(Ct.dirname(t),{recursive:!0}),un.writeFileSync(t,e)}catch{}if(Ca()){let n=Ra();process.stderr.write(`[mem] ${e}: rss ${n.rssMB} MB, heapUsed ${n.heapUsedMB} MB, external ${n.externalMB} MB, arrayBuffers ${n.arrayBuffersMB} MB
|
|
16
|
+
`)}}function qr(){so=null;let e=Wr();if(e)try{un.rmSync(e,{force:!0})}catch{}}function Gr(e){try{return un.readFileSync(Ct.join(Ct.resolve(e),".canopy","last-stage.txt"),"utf8").trim().slice(0,120)||null}catch{return null}}import Jr from"node:path";import{fileURLToPath as _a}from"node:url";import{Parser as Yr,Language as La}from"web-tree-sitter";var hd=Jr.dirname(_a(globalThis.__canopyUrl("src/stage2_parse/initHtmlParser.js")));async function Vr(){await Yr.init();let e=new Yr,t=Jr.join(Tt("tree-sitter-html"),"tree-sitter-html.wasm"),n=await La.load(t);return e.setLanguage(n),{parser:e,language:n}}function Xr(e,t){let s=yo(t,"htmlScriptRoot.scm").matches(e.rootNode);for(let o of s){let r=o.captures.find(c=>c.name==="attr_name"),i=o.captures.find(c=>c.name==="script_src");if(r&&r.node.text==="src"&&i)return i.node.text}return null}function Kr(e,t,n){let s=[];e.forEach((a,l)=>{a.steps.forEach(f=>{if(!f.hasOwnSubTrace)return;let y=e.findIndex((d,w)=>w!==l&&d.steps[0]?.nodeId===f.nodeId);y!==-1&&s.push({fromWorkflowIndex:l,toWorkflowIndex:y,atNodeId:f.nodeId})})});let o=new Map;for(let a of t)o.set(a.id,a.serviceName??null);let r=new Map;function i(a,l,f,y){if(!a||!l||a===l)return;let d=`${a} -> ${l} -> ${f}`;r.has(d)?r.get(d).count+=1:r.set(d,{fromService:a,toService:l,viaMatchType:f,count:1});let w=r.get(d);y==="exact"?w.exact=(w.exact??0)+1:y==="inferred"?w.inferred=(w.inferred??0)+1:y==="resolved"&&(w.resolved=(w.resolved??0)+1)}for(let a of n){if(!a.resolved||!a.fromNodeId||!a.targetNodeId)continue;let l=o.get(a.fromNodeId)??null,f=o.get(a.targetNodeId)??null;i(l,f,a.matchType,a.confidence)}let c=Array.from(r.values());return{workflowLinks:s,serviceLinks:c}}var Oa=K.dirname(Pa(globalThis.__canopyUrl("src/index.js"))),Zr=24*1e3*1e3;async function ro(e,t={}){e=K.resolve(e),console.log(`
|
|
17
17
|
Analyzing: ${e}
|
|
18
|
-
`);let n=Date.now(),s=()=>{let N=Math.round((Date.now()-n)/1e3);return N>=60?`${Math.floor(N/60)} min ${N%60} s`:`${N} s`},o=N=>{try{t.onProgress?.(N)}catch{}};
|
|
19
|
-
Stage 1b: partitioning files by service...`);let f=
|
|
20
|
-
Stage 2: parsing (all files, once \u2014 see note above)...`),
|
|
21
|
-
--- Service: ${N.name} (${N.kind}) \u2014 ${
|
|
22
|
-
--- Stage 5 (stitch): cross-service edge resolution ---`),
|
|
23
|
-
`);return{available:!0,filePath:N,startLine:
|
|
24
|
-
Done: ${
|
|
25
|
-
`),
|
|
26
|
-
`+
|
|
27
|
-
workflows.json omitted (${(
|
|
28
|
-
Saved to output/workflows.json`),
|
|
29
|
-
Note on output shape: workflows.json entries gained two additive fields (serviceId, servicesTouched) \u2014 every field the old shape had (steps, name, trigger, occurrences, ...) is unchanged, so the existing viewer keeps working without modification.`);let
|
|
30
|
-
`)[0]+" (the map is fine; search falls back to the traced nodes)")}return{status:"new-version",version:j,ms:Date.now()-o,coverage:
|
|
31
|
-
`+
|
|
18
|
+
`);let n=Date.now(),s=()=>{let N=Math.round((Date.now()-n)/1e3);return N>=60?`${Math.floor(N/60)} min ${N%60} s`:`${N} s`},o=N=>{try{t.onProgress?.(N)}catch{}};Ye("finding source files"),console.log("Stage 1: finding source files...");let r=t.discovered??jt(e),i=r.files;Ls(Os(e,i)),console.log(` found ${i.length} files`);let{parser:c,language:a,grammars:l}=await go();await ho({grammars:l},i),console.log(`
|
|
19
|
+
Stage 1b: partitioning files by service...`);let f=hs(e,i),y=gs(f,i,e);f=y.services,y.added&&console.log(` note: ${y.added.reason} (service "${y.added.name}")`),console.log(` detected ${f.length} services: ${f.map(N=>`${N.name} (${N.kind})`).join(", ")}`);let d=new Map(f.map(N=>[N.name,[]])),w=[];for(let N of i){let _=rt(N,f);_?d.get(_).push(N):w.push(N)}console.log(" file partition:");for(let N of f)console.log(` ${N.name}: ${d.get(N.name).length} files`);console.log(` unassigned (shared/root-level): ${w.length} files`),w.length&&(console.log(" rule: these don't get their own Stage 5-7 run (no service of their own to have routes/listeners for) \u2014"),console.log(" each one is added to a service's parse scope ONLY if a file already in that"),console.log(" service actually imports it, so intra-service calls into shared code still resolve.")),console.log(`
|
|
20
|
+
Stage 2: parsing (all files, once \u2014 see note above)...`),Ye("reading files");let p=await wo(i,c,a,{onProgress:t.onProgress,grammars:l,noCache:!!t.noCache,say:o});function $(N){let _=new Set;for(let B of N){let P=p.get(B);if(P)for(let D of P.imports){let le=ye(D.source,B,i);le&&w.includes(le)&&_.add(le)}}return[..._]}let j=new Map;for(let N of f){let _=d.get(N.name),B=$(_);j.set(N.name,[..._,...B]),console.log(` ${N.name}: ${_.length} own + ${B.length} shared file(s) pulled in by real imports = ${_.length+B.length} total scope`)}let g=f.filter(N=>!j.get(N.name)?.length);g.length&&(console.log(` excluding ${g.length} service(s) with 0 files: ${g.map(N=>N.name).join(", ")}`),f=f.filter(N=>j.get(N.name)?.length));let k=null,b=Tr(e);if(b){let{parser:N,language:_}=await Vr(),B=ve.readFileSync(b,"utf-8"),P=N.parse(B),D=Xr(P,_);if(D){let le=K.dirname(b),H=K.join(le,D);i.includes(H)&&(k=H,console.log(` found HTML root: ${D} -> ${H}`))}}let S=new Map,m=0,u=0,x=0;for(let N of f){let _=j.get(N.name);if(m++,Ye(`linking calls: service ${m} of ${f.length}`),o(`linking calls: service ${m} of ${f.length} (${s()})`),console.log(`
|
|
21
|
+
--- Service: ${N.name} (${N.kind}) \u2014 ${_.length} files in scope ---`),!_.length){console.log(" 0 files \u2014 nothing to trace for this service."),S.set(N.name,{nodes:[],resolvedEdges:[],workflows:[],routeIndex:new Map,eventIndex:new Map,rawEventIndex:new Map,parseResults:new Map});continue}let B=vo(new Map(_.map(T=>[T,p.get(T)]))),P=ys(B,f),D=vs(B,f);P=ks(P.concat(D)),console.log(` Stage 3: materialized ${D.length} inline-handler nodes before edge construction`);let le=$s(B,P),H=rr(B,P),xe=cr(B,P),ee=Ar(B,P);for(let T of _){let ne=new Set(B.get(T)?.exportedNames??[]);for(let V of P.filter(q=>q.filePath===T))V.exported=ne.has(V.name)}let Se=Hs(le,P,B,_,H,xe,ee),Re=Se.filter(T=>T.resolved).length;console.log(` Stage 4 (scoped): resolved ${Re}/${Se.length} edges`);for(let T of _){let ne=B.get(T),V=ne?.routes??[],q=ne?.listeners??[],se=fe(T,P),Oe=wt(T,ne?.imports??[],_),At=[];N.kind==="server"&&(At=ne?.socketListeners??[]),P=Ws(P,T,V,q,se,At,Oe)}let _e=P.filter(T=>T.isEntryPoint),tt=_e.filter(T=>T.trigger?.resolvedVia==="in-file").length,Ke=_e.filter(T=>T.trigger?.resolvedVia==="cross-file").length,He=_e.filter(T=>T.trigger?.resolvedVia==="inline").length;console.log(` Stage 5 entry points by resolution: in-file named ${tt}, cross-file named (BUG A) ${Ke}, inline (BUG B) ${He}`);let Mt=Se.filter(T=>T.type!=="reference"&&!T.viaArgument),Ot=qs(P,Mt),nt=[];if(N.kind==="client"&&k&&_.includes(k)&&nt.push({id:`${k}::__module_root__`,name:"main",trigger:{type:"htmlRoot",label:"index.html script"}}),!nt.length){let T=Vt(N.rootPath,i),ne=T&&_.find(V=>K.resolve(V)===T.entry);ne&&(console.log(` found HTML root for ${N.name}: ${K.relative(e,T.indexHtml)} -> ${K.relative(e,ne)} (${T.via})`),nt.push({id:`${ne}::__module_root__`,name:"main",trigger:{type:"htmlRoot",label:"index.html script"}}))}let pt=[];if(N.kind==="server"){let T=K.join(N.rootPath,"package.json");if(ve.existsSync(T))try{let ne=JSON.parse(ve.readFileSync(T,"utf-8")),V=ne.main;if(!V&&ne.scripts?.start){let q=ne.scripts.start.match(/([\w./-]+\.(?:js|mjs|cjs|ts))/);q&&(V=q[1])}if(V){let q=K.resolve(N.rootPath,V),se=_.find(Oe=>K.resolve(Oe)===q);if(!se){let Oe=nn(N.rootPath,V,ne);Oe&&(se=_.find(At=>K.resolve(At)===Oe.file))}se?pt.push({id:`${se}::__module_root__`,name:"main",trigger:{type:"processBootstrap",label:`${V} (package.json main)`}}):console.log(` note: ${N.name}'s package.json names "${V}" as its entry, but that file isn't in this service's own traced scope \u2014 no bootstrap workflow added.`)}}catch{}}if(!nt.length){let T=new Set(pt.map(q=>q.id.split("::")[0])),ne=new Set;for(let q of Se)q.resolved&&q.fromNodeId.endsWith("::__module_root__")&&ne.add(q.fromNodeId);let V=Fr(N.rootPath).map(q=>({...q,file:_.find(se=>K.resolve(se)===q.file)})).filter(q=>q.file);for(let q of _)Br(q)&&!V.some(se=>se.file===q)&&V.push({file:q,kind:"shebang"});for(let q of V){if(T.has(q.file)||vt(K.relative(e,q.file))||!ne.has(`${q.file}::__module_root__`))continue;T.add(q.file);let se=K.relative(N.rootPath,q.file).split(K.sep).join("/"),Oe=q.kind==="bin"?`CLI: ${q.binName}`:`Start: ${se}`;pt.push({id:`${q.file}::__module_root__`,name:"main",trigger:{type:"processBootstrap",label:`${se} (${q.kind==="bin"?"package.json bin":q.kind==="script"?"package.json script":q.kind==="main"?"package.json main":"#! shebang"}${q.mappedFrom?`, built to ${q.mappedFrom}`:""})`,workflowName:Oe}})}}let Nt=[];if(nt.length+pt.length+_e.filter(T=>!vt(K.relative(e,T.filePath))).length===0){let T=Hr(N.rootPath,_);if(T){let ne=K.relative(N.rootPath,T).split(K.sep).join("/"),q=Zt(P,B,se=>wt(se,B.get(se)?.imports??[],_));for(let se of zr(T,B,P,_,q))Nt.push({id:se.nodeId,name:P.find(Oe=>Oe.id===se.nodeId)?.name??se.name,trigger:{type:"publicApi",label:`${se.name} (exported from ${ne})`,workflowName:`API: ${se.name}`}});Nt.length&&console.log(` public API of ${N.name}: ${Nt.length} exported function(s)/method(s) from ${ne}`)}}let uo=new Set(Nt.map(T=>T.id)),ki=uo.size?Ot.filter(T=>!uo.has(T.id)):Ot,Nn=[...nt,...pt,..._e,...Nt,...ki];console.log(` Stage 5 total entry points: ${Nn.length} (${nt.length} HTML root, ${pt.length} process bootstrap, ${_e.length} pattern-matched, ${Ot.length} fallback)`);let $i=Gn(Se),bi=Xs(Nn,$i,P,Mt,8,Mt.length===Se.length?null:Gn(Mt)),Ni=new Set(Ot.map(T=>T.id)),Ii=T=>T.trigger?"physical":Ni.has(T.entryPointId)?"fallback":"hub",ji=bi.map(T=>({...T,origin:Ii(T),steps:Ks(T.steps,P)})),Ei=Qs(ji),po=Array.from(Ei.values()).map(er),mo=po.filter(T=>!vt(K.relative(e,String(T.steps[0]?.nodeId??"").split("::")[0])));x+=po.length-mo.length;let mt=sr(mo,{nodes:P});if(mt.some(T=>T.trigger)){let T=new Set(Se.filter(V=>V.type!=="returnValue"&&V.type!=="reference").map(V=>V.fromNodeId)),ne=new Set(mt.filter(V=>!V.trigger&&V.steps.length===1&&!T.has(V.steps[0].nodeId)).map(V=>V.steps[0].nodeId));ne.size&&(mt=mt.filter(V=>V.trigger||!ne.has(V.steps[0].nodeId)||V.steps.length>1),u+=ne.size)}console.log(` Stage 6-7: -> ${mt.length} named workflows for ${N.name}`),S.set(N.name,{nodes:P,resolvedEdges:Se,routeIndex:H,eventIndex:xe,rawEventIndex:ee,workflows:mt,parseResults:B,files:_,entryPointCount:Nn.length})}console.log(`
|
|
22
|
+
--- Stage 5 (stitch): cross-service edge resolution ---`),Ye("linking services together"),o(`linking services together (${s()})`);let h=[],v=0,I=0;for(let N of f){let _=S.get(N.name);if(!_||!_.resolvedEdges.length)continue;let B=_.resolvedEdges.filter(P=>!P.resolved&&(P.type==="apiCall"||P.type==="socketEmit"||P.type==="rawSocketSend"));for(let P of B){let D=null,le=null;for(let H of f){if(H.name===N.name)continue;let xe=S.get(H.name);if(!xe)continue;let ee=null;if(P.type==="apiCall"&&P.scope!=="external"?ee=xe.routeIndex.get(xt(P.url)):P.type==="socketEmit"?ee=xe.eventIndex.get(P.eventName):P.type==="rawSocketSend"&&(ee=xe.rawEventIndex.get(P.eventName)),ee){D=ee,le=H.name;break}}D?(h.push({fromService:N.name,fromNodeId:P.fromNodeId,toService:le,toNodeId:D,via:P.type,key:P.url||P.eventName,confidence:"inferred",reason:"name-only match",...P.type==="apiCall"?{url:P.url}:{eventName:P.eventName}}),v++):I++}}console.log(` stitched ${v} cross-service edges`);let E=Er(f,S,{repoRoot:e});for(let N of E.edges)h.push(N);console.log(` + ${E.edges.length} links from HTTP clients / WebSockets (${E.edges.filter(N=>N.confidence==="exact").length} exact, ${E.edges.filter(N=>N.confidence==="resolved").length} resolved)`),console.log(` ${I} unresolved calls remain unresolved even after checking every other service`);try{let N=Or(f,S);for(let _ of N.edges)h.push(_);console.log(` + ${N.edges.length} queue links (${N.stats.producers} producers, ${N.stats.consumers} consumers with a known queue name; ${N.stats.unresolvedProducers+N.stats.unresolvedConsumers} left unlinked because the queue name could not be known for sure)`)}catch(N){console.log(` queue links skipped: ${N?.message??N}`)}if(t.lowMemory)for(let N of p.values())for(let _ of Object.keys(N))_!=="hadErrors"&&_!=="warnings"&&_!=="failed"&&_!=="skipped"&&_!=="errorMessage"&&delete N[_];let M=new Map;function A(N,_,B){if(!N||_==null||B==null)return{available:!1,reason:"no line range recorded for this node"};try{M.has(N)||(M.set(N,ve.readFileSync(N,"utf-8").split(/\r\n|\n/)),M.size>256&&M.delete(M.keys().next().value));let P=M.get(N),D=Math.max(_,1),le=Math.min(B,P.length);if(D>P.length)return{available:!1,reason:"recorded line range is past the end of the current file \u2014 source has likely moved"};let H=P.slice(D-1,le).join(`
|
|
23
|
+
`);return{available:!0,filePath:N,startLine:D,endLine:le,text:H}}catch(P){return{available:!1,reason:`source unavailable: ${P.code==="ENOENT"?"file not found (deleted or moved)":P.message}`}}}let L=/^(addEventListener|removeEventListener|on|once|postMessage|onmessage|subscribe)$/i,O=new Set(["call","methodCall","callSite"]),R=new WeakMap;function z(N,_){let B=R.get(N);if(!B||B.n!==N.length){B={n:N.length,by:new Map};for(let P of N){let D=B.by.get(P.fromNodeId);D||B.by.set(P.fromNodeId,D=[]),D.push(P)}R.set(N,B)}return B.by.get(_)??[]}function X(N,_,B,P,D=null){let le=H=>!!(D&&!P&&!H.deferred&&H.resolved&&H.targetNodeId&&O.has(H.type)&&H.targetNodeId!==N&&D.inWorkflow.has(H.targetNodeId)&&!D.children.has(H.targetNodeId));return z(_,N).filter(H=>H.type!=="apiCall").filter(H=>H.resolved&&H.targetNodeId?le(H):!!H.deferred===P).map(H=>{let xe=H.type==="returnValue",ee=!xe&&L.test(H.calleeNameRaw||""),Se=(H.branchPath??[]).map(Ke=>({...Ke,source:B?A(B,Ke.conditionLine,Ke.conditionLine):{available:!1,reason:"owning function's node not found"}})),Re=H.objectNameRaw?`${H.objectNameRaw}.${H.calleeNameRaw}`:H.calleeNameRaw,_e=xe?Re:H.firstArgText?`${Re}(${H.firstArgText})`:Re,tt=le(H);return{label:_e,line:H.line??null,column:H.column??null,branchPath:Se,source:B?A(B,H.line,H.line):{available:!1,reason:"owning function's node not found"},tag:tt?"called-elsewhere":xe?"return-value":ee?"runtime-dispatched":"unresolvable-call-site",...tt?{targetNodeId:H.targetNodeId}:{},reason:tt?"a call to a function this workflow shows under another step (a function is placed once, under the first step that reaches it); it runs here, at this line, in this order":xe?"the value this branch returns \u2014 not a function call, just what this path produces":ee?`registered via ${H.calleeNameRaw}(...) \u2014 the handler runs later, outside this function's own execution`:P?"runs later, outside this function's own execution (an effect cleanup, a deferred callback)":"call target could not be statically resolved to a declared function (dynamic dispatch, external/browser API, or computed member access) \u2014 but it still runs here, in this order"}})}function C(N,_,B){return X(N,_,B,!0)}function W(N,_,B,P){return X(N,_,B,!1,P)}let Z=[];for(let N of f){let _=S.get(N.name);if(!_)continue;let B=new Map(_.nodes.map(P=>[P.id,P]));for(let P of _.workflows){let D=new Set([N.name]),le=new Set(P.steps.map(ee=>ee.nodeId)),H=new Map;for(let ee of P.steps)ee.parentNodeId!=null&&(H.get(ee.parentNodeId)??H.set(ee.parentNodeId,new Set).get(ee.parentNodeId)).add(ee.nodeId);let xe=P.steps.map(ee=>{let Se=h.find(He=>He.via!=="queue"&&He.fromService===N.name&&He.fromNodeId===ee.nodeId),Re=B.get(ee.nodeId),_e=ee.parentNodeId?B.get(ee.parentNodeId):null,tt=(ee.branchPath??[]).map(He=>({...He,source:_e?A(_e.filePath,He.conditionLine,He.conditionLine):{available:!1,reason:"owning function's node not found"}})),Ke={...ee,branchPath:tt,source:Re?A(Re.filePath,Re.startLine,Re.endLine):{available:!1,reason:"node not found in this service's own graph"},alsoCallsRuntime:C(ee.nodeId,_.resolvedEdges,Re?.filePath),inlineCalls:W(ee.nodeId,_.resolvedEdges,Re?.filePath,{inWorkflow:le,children:H.get(ee.nodeId)??new Set})};return Se&&(D.add(Se.toService),Ke.crossesInto=Se.toService),Ke});Z.push({...P,steps:xe,serviceId:N.name,servicesTouched:[...D]})}}console.log(`
|
|
24
|
+
Done: ${Z.length} named workflows across all services
|
|
25
|
+
`),Z.forEach(N=>console.log(` - [${N.serviceId}] ${N.name} (${N.steps.length} steps, ${N.occurrences} entry point(s))`)),Ye("writing the map"),o(`writing the map (${s()})`);let oe=t.outputDir??process.env.CANOPY_OUTPUT_DIR??K.join(Oa,"..","output");ve.existsSync(oe)||ve.mkdirSync(oe,{recursive:!0});let ie=Kt(e),dt=new Set(f.flatMap(N=>j.get(N.name)??[])),et=ds({discovered:r,parseResults:p,scopeFiles:dt,rel:ie.rel,rootService:y.added});et.testWorkflowsExcluded=x,et.guessedWorkflowsDropped=u;let bt={repoRoot:ie.repoRoot,coverage:et};ve.writeFileSync(K.join(oe,"meta.js"),`const meta = ${JSON.stringify(bt,null,2)};`),ve.writeFileSync(K.join(oe,"meta.json"),JSON.stringify(bt,null,2)),console.log(`
|
|
26
|
+
`+qt(et)),ve.existsSync(K.join(oe,"history.js"))||ve.writeFileSync(K.join(oe,"history.js"),"const canopyHistory = null;");let F=ie.json(Z,2),G=F.length>Zr;if(G&&(F=ie.json(Z)),G&&F.length>Zr){let N=zs(JSON.parse(F));ve.writeFileSync(K.join(oe,"workflows.js"),`const workflows = ${N};`),ve.rmSync(K.join(oe,"workflows.json"),{force:!0}),console.log(`
|
|
27
|
+
workflows.json omitted (${(F.length/1e6).toFixed(1)} MB plain); workflows.js written with shared sub-structures (${(N.length/1e6).toFixed(1)} MB)`)}else ve.writeFileSync(K.join(oe,"workflows.json"),F),console.log(`
|
|
28
|
+
Saved to output/workflows.json`),ve.writeFileSync(K.join(oe,"workflows.js"),`const workflows = ${F};`),console.log("Saved to output/workflows.js (for the viewer)");let J=f.flatMap(N=>S.get(N.name)?.nodes??[]),ae=h.filter(N=>N.via!=="queue").map(N=>({fromNodeId:N.fromNodeId,targetNodeId:N.toNodeId,resolved:!0,matchType:"crossLayer",confidence:N.confidence})),$e=[...f.flatMap(N=>S.get(N.name)?.resolvedEdges??[]),...ae],he=Kr(Z,J,$e);he.crossServiceEdges=h,ve.writeFileSync(K.join(oe,"systemGraph.js"),`const systemGraph = ${ie.json(he,2)};`);let Me=f.map(({isRepoRoot:N,ownsLeftovers:_,...B})=>({...B,nodeCount:J.filter(P=>P.serviceName===B.name).length,workflowCount:Z.filter(P=>P.serviceId===B.name).length}));ve.writeFileSync(K.join(oe,"services.js"),`const services = ${ie.json(Me,2)};`),console.log(`Saved to output/systemGraph.js (${he.workflowLinks.length} workflow links, ${he.serviceLinks.length} service links)`),console.log("Saved to output/services.js"),console.log(`
|
|
29
|
+
Note on output shape: workflows.json entries gained two additive fields (serviceId, servicesTouched) \u2014 every field the old shape had (steps, name, trigger, occurrences, ...) is unchanged, so the existing viewer keeps working without modification.`);let re=new Map;for(let N of f){let _=S.get(N.name);if(!_)continue;let B=ie.clone(_.nodes.map(D=>({id:D.id,name:D.name,type:D.type,filePath:D.filePath,bodyHash:D.bodyHash??null,startLine:D.startLine===0?0:D.startLine,endLine:D.endLine===Number.MAX_SAFE_INTEGER?null:D.endLine,serviceName:D.serviceName,isEntryPoint:!!D.isEntryPoint}))),P=Ss(ie.clone(_.resolvedEdges.map(D=>({fromNodeId:D.fromNodeId,targetNodeId:D.targetNodeId??null,type:D.type,callKind:D.callKind,calleeNameRaw:D.calleeNameRaw,eventName:D.eventName,url:D.url,line:D.line??null,column:D.column??null,resolved:!!D.resolved,matchType:D.matchType??null}))));re.set(N.name,{nodes:B,edges:P})}return{workflows:Z,perService:S,crossServiceEdges:h,services:f,publicGraph:re,publicWorkflows:ie.clone(Z),publicCrossServiceEdges:ie.clone(h),fingerprint:Xt(xs(i,ie.rel)),analyzedFileCount:i.length,repoRoot:ie.repoRoot,coverage:et}}var Aa=process.argv[1]&&globalThis.__canopyUrl("src/index.js")===Ma(K.resolve(process.argv[1])).href;Aa&&ro(process.argv[2]||process.cwd()).catch(e=>{console.error("Pipeline failed:",e),process.exit(1)});var Fa=ue.join(ue.dirname(Qr(globalThis.__canopyUrl("src/history/sync.js"))),"..","..","output"),Ba=["workflows.json","workflows.js","systemGraph.js","services.js","meta.js","meta.json","history.js"],Da=ue.dirname(Qr(globalThis.__canopyUrl("src/history/sync.js"))).split(ue.sep).includes("node_modules"),Be=e=>process.env.CANOPY_OUTPUT_DIR||(Da&&e?ue.join(ue.resolve(e),".canopy","output"):Fa);async function Ha(e,t){let n=console.log;console.log=()=>{};try{return await ro(e,t)}finally{console.log=n}}function za(e){try{let t=JSON.parse(Je.readFileSync(ue.join(Be(e),"meta.json"),"utf8"));return t.coverage&&ue.resolve(t.repoRoot)===ue.resolve(e)?t.coverage:null}catch{return null}}async function Wa(e,{full:t=!1}={}){let n=ue.resolve(e),s=Kt(n),o=jt(n),r=await Bo(n,o.files,s.rel,{full:t});return{fingerprint:Xt(r.hashes),reused:r.reused,rehashed:r.rehashed,discovered:o}}async function Ua(e,{keep:t,say:n=()=>{},full:s=!1}){let o=Date.now(),r=ot(e),i=r.versions[r.versions.length-1],c=await Wa(e,{full:s}),a=c.fingerprint,l=!!i&&i.fingerprint===a&&(s||i.engineVersion!==Ft()||i.outputFormat!==xo);if(i&&i.fingerprint===a&&!l&&!s){try{Lo(e,Be(e))}catch{}return{status:"no-changes",version:i,ms:Date.now()-o,coverage:za(e),fast:c}}let f=Je.mkdtempSync(ue.join(Ta.tmpdir(),"canopy-sync-"));try{let y=await Ha(e,{outputDir:f,onProgress:n,lowMemory:!0,noCache:s,discovered:c.discovered});Ye("storing the version"),n(`storing the version (${Math.round((Date.now()-o)/1e3)} s)`);let d=Ho(y),w=Do(d),p={nodes:d.nodes.length,edges:d.edges.length,workflows:d.workflows.length,physicalWorkflows:d.workflows.filter(u=>u.tier==="physical").length,crossServiceEdges:d.crossServiceEdges.length},$=Ao(e),j=ko(e,w,d,p,t,{refresh:l,protect:$?[$.version]:[]}),g=So();g&&n("history: "+g);let k=Ce(e,["rev-parse","--abbrev-ref","HEAD"]),b=Ce(e,["rev-parse","HEAD^{tree}"]);Oo(e,{engineFingerprint:Ft(),projectRoot:ue.resolve(e),lastAnalysed:{version:j.version,fingerprint:j.fingerprint,headSha:j.headSha,treeHash:b,branch:k}});let S=await import("./chunk-ILPARXQH.js").catch(()=>null);S&&S.writeHistoryJs(e,f);let m=Be(e);Je.mkdirSync(m,{recursive:!0});for(let u of Ba)Je.existsSync(ue.join(f,u))?Je.copyFileSync(ue.join(f,u),ue.join(m,u)):Je.rmSync(ue.join(m,u),{force:!0});try{Ye("building the search index"),n(`building the search index (${Math.round((Date.now()-o)/1e3)} s)`),_o(e,m)}catch(u){n("the search index could not be built: "+String(u.message).split(`
|
|
30
|
+
`)[0]+" (the map is fine; search falls back to the traced nodes)")}return{status:"new-version",version:j,ms:Date.now()-o,coverage:y.coverage}}finally{Je.rmSync(f,{recursive:!0,force:!0})}}function qa(e,t=()=>{}){let n=To(e);if(!n.ok){let s=Fo(e);t(`The saved history in .canopy was damaged (${n.problems[0]}). It was moved to .canopy/${s} and Canopy is starting a fresh one; this run rebuilds everything.`)}Mo(e,Ft())}async function pn(e,{keep:t=Bt,say:n=console.log,full:s=!1}={}){if(e=ue.resolve(e),Dt(e),Je.mkdirSync(ge(e).root,{recursive:!0}),qa(e,n),!jo(e,process.env.CANOPY_VERSION??null,n))return Ro(e),n("sync already running - one rerun queued"),{status:"queued"};let o;try{do o=await Ua(e,{keep:t,say:n,full:s}),s=!1,o.status==="no-changes"?n(`no changes (v${o.version.version} ${o.version.fingerprint.slice(0,7)}) [${o.ms} ms]`):n(`v${o.version.version} ${o.version.fingerprint.slice(0,7)} stored: ${o.version.counts.nodes} nodes, ${o.version.counts.edges} edges, ${o.version.counts.workflows} workflows, ${(o.version.bytes/1024/1024).toFixed(2)} MB${o.version.gzip?" (gzip)":""} [${o.ms} ms]`),o.coverage&&n(`
|
|
31
|
+
`+qt(o.coverage));while(Co(e))}finally{Eo(e)}if(o&&o.status!=="queued")try{let r=null;try{r=JSON.parse(Je.readFileSync(ue.join(Be(e),"services.js"),"utf8").replace(/^const services = /,"").replace(/;\s*$/,"")).length}catch{}Ze().syncCompleted({ms:o.ms,files:o.coverage?.analyzed,services:r})}catch{}return o}import de from"node:fs";import Le from"node:path";import{spawn as Ga}from"node:child_process";import{fileURLToPath as Ya}from"node:url";var _t="# >>> canopy sync (managed block - do not edit) >>>",ni="# <<< canopy sync <<<",ft=["post-commit","post-merge"],Ja=globalThis.__canopyBundle??Le.join(Le.dirname(Ya(globalThis.__canopyUrl("src/history/hooks.js"))),"..","cli.js"),Va=e=>Le.resolve(e).split(Le.sep).join("/");function Lt(e){let t=Ce(e,["rev-parse","--git-path","hooks"]);if(!t)throw new Error(`not a git repository: ${e}`);return Le.resolve(e,t)}var ei=JSON.parse(de.readFileSync(Le.join(Ae,"package.json"),"utf8")),Xa=ei.name+"@"+ei.version,ti=e=>Va(e).replace(/(["$`\\])/g,"\\$1");function mn(e){return[_t,"(",` if command -v canopy >/dev/null 2>&1; then canopy sync --background "${ti(e)}" >/dev/null 2>&1 </dev/null`,` elif command -v npx >/dev/null 2>&1; then ( npx --yes ${Xa} sync --background "${ti(e)}" >/dev/null 2>&1 </dev/null & )`,' else echo "canopy not found; skipping map update"'," fi",") || true",ni].join(`
|
|
32
32
|
`)+`
|
|
33
|
-
`}var
|
|
34
|
-
`+
|
|
35
|
-
`+
|
|
33
|
+
`}var hn=()=>new RegExp(`\\n?${_t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}[\\s\\S]*?${ni.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\n?`);function Pt(e){let t=Lt(e);de.mkdirSync(t,{recursive:!0});let n=[];for(let s of ft){let o=Le.join(t,s),r=de.existsSync(o)?de.readFileSync(o,"utf8"):null,i;r===null?i=`#!/bin/sh
|
|
34
|
+
`+mn(e):hn().test(r)?i=r.replace(hn(),()=>`
|
|
35
|
+
`+mn(e)):i=r+(r.endsWith(`
|
|
36
36
|
`)?"":`
|
|
37
37
|
`)+`
|
|
38
|
-
`+
|
|
39
|
-
`));try{
|
|
40
|
-
`);i.replace(/^#!.*\n?/,"").trim()===""?
|
|
38
|
+
`+mn(e),de.writeFileSync(o,i.replace(/\r\n/g,`
|
|
39
|
+
`));try{de.chmodSync(o,493)}catch{}n.push(o)}return n}function oi(e){let t=Lt(e),n=[];for(let s of ft){let o=Le.join(t,s);if(!de.existsSync(o))continue;let r=de.readFileSync(o,"utf8");if(!hn().test(r))continue;let i=r.replace(hn(),`
|
|
40
|
+
`);i.replace(/^#!.*\n?/,"").trim()===""?de.rmSync(o,{force:!0}):de.writeFileSync(o,i.replace(/\n{3,}/g,`
|
|
41
41
|
|
|
42
|
-
`)),n.push(o)}return n}function
|
|
42
|
+
`)),n.push(o)}return n}function si(e){if(!de.existsSync(Le.resolve(e)))return null;let t=ge(e);de.mkdirSync(t.root,{recursive:!0});let n=de.openSync(t.log,"a");de.writeSync(n,`
|
|
43
43
|
--- ${new Date().toISOString()} sync requested (pid ${process.pid})
|
|
44
|
-
`);let s=Object.fromEntries(Object.entries(process.env).filter(([r])=>!/^GIT_/i.test(r)||r.toUpperCase()==="GIT_EXEC_PATH"))
|
|
45
|
-
`);c.includes(
|
|
46
|
-
`)[0]}t.push({name:s,critical:o,ok:c,detail:a,fix:i})};return n("Node version >= 18",!0,()=>({ok:Number(process.versions.node.split(".")[0])>=18,detail:"v"+process.versions.node}),"install Node 18 or newer from https://nodejs.org and run canopy again"),n("tree-sitter grammars (wasm)",!0,()=>{let s=[["web-tree-sitter","web-tree-sitter.wasm"],["tree-sitter-javascript","tree-sitter-javascript.wasm"],["tree-sitter-typescript","tree-sitter-typescript.wasm"],["tree-sitter-typescript","tree-sitter-tsx.wasm"],["tree-sitter-html","tree-sitter-html.wasm"]],o=s.filter(([r,i])=>!
|
|
44
|
+
`);let s=Object.fromEntries(Object.entries(process.env).filter(([r])=>!/^GIT_/i.test(r)||r.toUpperCase()==="GIT_EXEC_PATH"));s.CANOPY_HOOK="1";let o=Ga(process.execPath,[Ja,"sync",Le.resolve(e)],{detached:!0,stdio:["ignore",n,n],windowsHide:!0,env:s});return o.unref(),de.closeSync(n),o.pid}function ri(e){let t=Lt(e),n=mn(e),s=0,o=0;for(let r of ft){let i=Le.join(t,r);if(!de.existsSync(i))continue;let c=de.readFileSync(i,"utf8").replace(/\r\n/g,`
|
|
45
|
+
`);c.includes(_t)&&(s++,c.includes(n)&&o++)}return s<ft.length?"absent":o===ft.length?"current":"outdated"}import De from"node:fs";import Ve from"node:path";import{execFileSync as ii}from"node:child_process";function gn(e){let t=[],n=(s,o,r,i)=>{let c=!1,a="";try{let l=r();c=l===!0||!!(l&&l.ok),a=l&&l.detail?l.detail:""}catch(l){a=String(l.message??l).split(`
|
|
46
|
+
`)[0]}t.push({name:s,critical:o,ok:c,detail:a,fix:i})};return n("Node version >= 18",!0,()=>({ok:Number(process.versions.node.split(".")[0])>=18,detail:"v"+process.versions.node}),"install Node 18 or newer from https://nodejs.org and run canopy again"),n("tree-sitter grammars (wasm)",!0,()=>{let s=[["web-tree-sitter","web-tree-sitter.wasm"],["tree-sitter-javascript","tree-sitter-javascript.wasm"],["tree-sitter-typescript","tree-sitter-typescript.wasm"],["tree-sitter-typescript","tree-sitter-tsx.wasm"],["tree-sitter-html","tree-sitter-html.wasm"]],o=s.filter(([r,i])=>!De.existsSync(Ve.join(Tt(r),i))).map(([,r])=>r);return{ok:o.length===0,detail:o.length?"missing "+o.join(", "):s.length+" files"}},"reinstall canopy: npm install -g canopy-engine (or, in a checkout, npm install in the canopy-engine folder)"),n("query files (.scm)",!0,()=>{let s=[Ve.join(Ae,"src","stage2_parse","queries"),Ve.join(Ae,"dist","queries")].find(r=>De.existsSync(r))??Ve.join(Ae,"dist","queries"),o=De.readdirSync(s).filter(r=>r.endsWith(".scm")).length;return{ok:o>=10,detail:o+" files"}},"reinstall canopy: the package is missing its query files (dist/queries)"),n("write access to <path>/.canopy",!0,()=>{let s=ge(e).root;De.mkdirSync(s,{recursive:!0});let o=Ve.join(s,`.doctor-${process.pid}`);return De.writeFileSync(o,"x"),De.rmSync(o),{ok:!0,detail:s}},`make ${e} writable for your user, or run canopy on a folder you own`),n("git available",!1,()=>({ok:!!ii("git",["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}),detail:ii("git",["--version"],{encoding:"utf8"}).trim()}),"install git (https://git-scm.com); without it version history and the hook are limited"),n("map viewer present",!1,()=>({ok:De.existsSync(Ve.join(Ae,"ui-react","index.html"))&&De.existsSync(Ve.join(Ae,"ui-react","dist"))}),"canopy open needs the built viewer (ui-react/dist); reinstall from a build that includes it"),n("post-commit hook installed",!1,()=>{if(!Ce(e,["rev-parse","--git-dir"]))return{ok:!1,detail:"not a git repository"};let s=Lt(e),o=ft.every(r=>De.existsSync(Ve.join(s,r))&&De.readFileSync(Ve.join(s,r),"utf8").includes(_t));return{ok:o,detail:o?"post-commit, post-merge":""}},`canopy hook install "${e}"`),t}function ci(e,t,n,s=console.log){s(`canopy ${n} doctor (${t})
|
|
47
47
|
`);for(let r of e)s(`${r.ok?"OK ":"FAIL"} ${r.name}${r.detail?" - "+r.detail:""}${r.ok?"":`
|
|
48
48
|
fix: ${r.fix}`}${!r.ok&&!r.critical?" (not critical)":""}`);let o=e.filter(r=>r.critical&&!r.ok);return s(`
|
|
49
|
-
${o.length?`${o.length} critical problem(s) - fix them and run canopy doctor again`:"all critical checks passed"}`),o.length}import
|
|
50
|
-
`)),
|
|
51
|
-
`),
|
|
52
|
-
`))},say(
|
|
53
|
-
${r.done} ${
|
|
54
|
-
`)):/^\s{6}\S/.test(
|
|
55
|
-
`):
|
|
56
|
-
`);return}if(
|
|
57
|
-
`),
|
|
58
|
-
`),
|
|
59
|
-
`),
|
|
60
|
-
`)},banner(
|
|
61
|
-
`);return}
|
|
62
|
-
${f(
|
|
49
|
+
${o.length?`${o.length} critical problem(s) - fix them and run canopy doctor again`:"all critical checks passed"}`),o.length}import Nl from"node:readline";import pe from"node:fs";import sl from"node:net";import rl from"node:os";import Xe from"node:path";import il from"node:readline";function co({stream:e=process.stdout,env:t=process.env,flags:n={},platform:s=process.platform}={}){let o=!!e.isTTY,r="NO_COLOR"in t&&t.NO_COLOR!==""||!!n["no-color"]||n.color===!1||t.TERM==="dumb",i=o&&!r&&!n.quiet,c=i&&t.TERM!=="linux"&&(s!=="win32"||!!(t.WT_SESSION||t.TERM_PROGRAM||t.ConEmuANSI==="ON"||t.ANSICON)||/UTF-?8/i.test(`${t.LC_ALL??""}${t.LC_CTYPE??""}${t.LANG??""}`));return{tty:o,color:i,rich:i,unicode:c,columns:Math.max(40,Math.min(e.columns||80,200)),quiet:!!n.quiet}}var io={unicode:{ok:"\u2714",fail:"\u2716",line:"\u2502",top:"\u250C",cap:"\u2514",done:"\u25CF",bad:"\u25A0",spin:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],full:"\u2588",empty:"\u2591",arrow:"\u2192",dot:"\xB7"},ascii:{ok:"[ok]",fail:"[x]",line:"|",top:"+",cap:"+",done:"*",bad:"x",spin:["|","/","-","\\"],full:"#",empty:"-",arrow:"->",dot:"-"}},Ka=(e,t,n)=>e?`\x1B[${t}m${n}\x1B[0m`:n,ai=e=>e<59500?`${(e/1e3).toFixed(1)} s`:`${Math.floor(e/6e4)} min ${String(Math.round(e%6e4/1e3)).padStart(2,"0")} s`,Za=e=>!Number.isFinite(e)||e<0?"":e<1?"< 1 s":e<60?`${Math.round(e)} s`:`${Math.floor(e/60)} min ${Math.round(e%60)} s`;function Qa({done:e,total:t,unit:n="files",elapsedMs:s,width:o=24,sym:r=io.ascii}){let i=t>0?Math.min(1,e/t):0,c=Math.round(i*o),a=s>500?e/(s/1e3):0,l=a>0?(t-e)/a:NaN,f=r.full.repeat(c)+r.empty.repeat(o-c),y=String(Math.floor(i*100)).padStart(3)+"%";return`[${f}] ${y} ${e.toLocaleString("en-US")}/${t.toLocaleString("en-US")} ${n}${a?` ${Math.round(a).toLocaleString("en-US")} ${n}/s`:""}${l===l&&i<1?` ETA ${Za(l)}`:""}`}function li({stream:e=process.stdout,caps:t=co({stream:e}),now:n=()=>Date.now(),interval:s=80,onExitHook:o=!0}={}){let r=t.unicode?io.unicode:io.ascii,i=(C,W)=>Ka(t.color,C,W),c=C=>i("2",C),a=C=>i("32",C),l=C=>i("31",C),f=C=>i("1",C),y=C=>i("36",C),d=null,w=!0,p=!1,$=null,j=0,g=null,k=!1,b=!1,S=-1,m="",u=C=>{try{e.write(C)}catch{}},x=()=>{t.rich&&!b&&(u("\x1B[?25l"),b=!0)},h=()=>{b&&(u("\x1B[?25h"),b=!1)},v=()=>{k&&(u("\r\x1B[2K"),k=!1)},I=C=>C.replace(/\u001b\[[0-9;?]*[A-Za-z]/g,"").length;function E(C){let W=d.title,Z=C(W),oe=t.columns-1;I(Z)>oe&&(W=W.replace(/\s*\(.*\)\s*$/,""),Z=C(W));let ie=I(Z)-oe;if(ie>0){let dt=t.unicode?"\u2026":"...";W=W.slice(0,Math.max(6,W.length-ie-dt.length))+dt,Z=C(W)}return Z}function M(){let C=i("36",r.spin[j%r.spin.length]);return E($?W=>` ${C} ${W} ${Qa({done:$.done,total:$.total,unit:$.unit,elapsedMs:n()-$.started,width:Math.max(8,Math.min(24,t.columns-66)),sym:r})}`:W=>` ${C} ${W}${m?c(" "+m):""} ${c(ai(n()-d.started))}`)}function A(){!t.rich||!d||(x(),u(`\r\x1B[2K${M()}`),k=!0)}let L=()=>{j++,A()},O=()=>{t.rich&&s>0&&!g&&(g=setInterval(L,s),g.unref?.())},R=()=>{g&&(clearInterval(g),g=null)};function z(C=!0){if(!d)return;R();let W=ai(n()-d.started);t.rich&&(v(),u(` ${C?a(r.done):l(r.bad)} ${d.title} ${c(W)}
|
|
50
|
+
`)),w=w&&C,d=null,$=null,m="",S=-1,h()}let X={caps:t,line(C=""){t.quiet||(t.rich&&k?(v(),u(C+`
|
|
51
|
+
`),A()):u(C+`
|
|
52
|
+
`))},say(C){if(t.quiet)return;let W=/^\[(\d+)\/(\d+)\] (.*?)\.\.\.$/.exec(C);if(!t.rich){let Z=String(C);W?(p=!0,u(`${r.line}
|
|
53
|
+
${r.done} ${Z}
|
|
54
|
+
`)):/^\s{6}\S/.test(Z)?u(`${r.line}${Z.slice(1)}
|
|
55
|
+
`):u(Z+`
|
|
56
|
+
`);return}if(W){z(!0),p||(u(` ${a(r.top)}
|
|
57
|
+
`),p=!0),u(` ${w?a(r.line):l(r.line)}
|
|
58
|
+
`),d={n:+W[1],total:+W[2],title:W[3],started:n()},j=0,A(),O();return}if(/^\s{6}\S/.test(C)){X.line(` ${c(r.line)} ${c(String(C).trim())}`);return}X.line(String(C))},important(C){t.rich&&k?(v(),u(C+`
|
|
59
|
+
`),A()):u(String(C)+`
|
|
60
|
+
`)},banner(C,W,Z){if(!t.quiet){if(!t.rich){u(`${C} ${W} - ${Z}
|
|
61
|
+
`);return}u(`
|
|
62
|
+
${f(y(C))} ${c("v"+W)} ${c(r.dot)} ${Z}
|
|
63
63
|
|
|
64
|
-
`)}},progress(
|
|
65
|
-
`))},endProgress(){
|
|
66
|
-
`))},endStep:
|
|
67
|
-
${
|
|
68
|
-
`):
|
|
64
|
+
`)}},progress(C,W,Z="files",oe="reading files"){if(t.quiet)return;if(t.rich){$=$??{started:n()},Object.assign($,{done:C,total:W,unit:Z}),g||A();return}let ie=W>0?Math.floor(C/W*10):0;ie!==S&&(S=ie,u(`${r.line} ${oe}: ${C} of ${W}
|
|
65
|
+
`))},endProgress(){$=null,S=-1},status(C){t.quiet||(t.rich?($=null,m=C,A()):u(`${r.line} ${C}
|
|
66
|
+
`))},endStep:z,tick:L,close(){!p||t.quiet||(z(!0),p=!1,t.rich?u(` ${w?a(r.line):l(r.line)}
|
|
67
|
+
${w?a(r.cap):l(r.cap)}
|
|
68
|
+
`):u(`${r.line}
|
|
69
69
|
${r.cap}
|
|
70
|
-
`))},final({url:
|
|
71
|
-
`);return}if(!t.rich){
|
|
70
|
+
`))},final({url:C,changes:W=null,update:Z=null,hint:oe="press Ctrl+C to stop"}){if(z(!0),t.quiet){u(C+`
|
|
71
|
+
`);return}if(!t.rich){X.close();return}X.close(),u(`
|
|
72
72
|
${a(r.ok)} ${f("Canopy is ready")}
|
|
73
73
|
|
|
74
|
-
${c("Local:")} ${
|
|
75
|
-
`),
|
|
76
|
-
`),
|
|
77
|
-
`),
|
|
78
|
-
${c(
|
|
79
|
-
`)},restore(){
|
|
74
|
+
${c("Local:")} ${y(C)}
|
|
75
|
+
`),W&&u(` ${c("Since last visit:")} ${W}
|
|
76
|
+
`),Z&&u(` ${c("Update:")} ${Z}
|
|
77
|
+
`),u(`
|
|
78
|
+
${c(oe)}
|
|
79
|
+
`)},restore(){R(),k&&v(),h()}};if(o&&t.rich){let C=()=>X.restore();process.once("exit",C);for(let W of["SIGINT","SIGTERM"])process.once(W,()=>{C(),process.exit(W==="SIGINT"?130:143)})}return X}import St from"node:fs";import el from"node:http";import ao from"node:path";var ut=e=>ao.join(ge(e).root,"server.json"),fi=e=>ao.join(ge(e).root,"server.lock");function tl(e,{timeoutMs:t=1500}={}){return new Promise(n=>{let s=el.get({host:"127.0.0.1",port:e,path:"/api/health",headers:{host:`127.0.0.1:${e}`},timeout:t},o=>{let r="";o.on("data",i=>{r+=i}),o.on("end",()=>{try{let i=JSON.parse(r);n(o.statusCode===200&&i.ok&&i.app==="canopy"?i:null)}catch{n(null)}})});s.on("timeout",()=>{s.destroy(),n(null)}),s.on("error",()=>n(null))})}var nl=e=>{try{return Po(e)?.projectId??null}catch{return null}};async function ol(e){let t=null;try{t=JSON.parse(St.readFileSync(ut(e),"utf8"))}catch{return null}let s=t&&Number.isInteger(t.pid)&&t.pid!==process.pid&&$o(t.pid)&&Number.isInteger(t.port)?await tl(t.port):null;if(!(s&&(!t.projectId||!s.projectId||t.projectId===s.projectId))){try{St.rmSync(ut(e),{force:!0})}catch{}return null}return{...t,url:`http://127.0.0.1:${t.port}/`}}async function yn(e,t,{waitMs:n=6e3}={}){let s=Date.now()+n;for(;;){let o=await ol(e);if(o)return{ok:!1,running:o};if(No(fi(e),{},t).ok)return{ok:!0};if(Date.now()>s)return{ok:!1,running:null,busy:!0};await new Promise(i=>setTimeout(i,150))}}function vn(e,{port:t,version:n,navToken:s=null}){let o={pid:process.pid,port:t,startedAt:new Date().toISOString(),version:n,projectId:nl(e),...s?{navToken:s}:{}},r=ut(e)+"."+process.pid+".tmp";St.mkdirSync(ao.dirname(ut(e)),{recursive:!0}),St.writeFileSync(r,JSON.stringify(o,null,2),{mode:384}),St.renameSync(r,ut(e));let i=()=>{try{bo(ut(e))?.pid===process.pid&&St.rmSync(ut(e),{force:!0})}catch{}Io(fi(e))};return process.once("exit",i),{unregister:i}}var ui=Number(process.env.CANOPY_MIN_FREE_MB)||300,cl=".js .jsx .mjs .cjs .ts .tsx .mts .cts",wn=class extends Error{constructor(t,n){super(n),this.code=t,this.line=n}},je=(e,t)=>{throw new wn(e,t)};function al(e){let t=!!Ce(e,["rev-parse","--git-dir"]),n=Xe.join(e,".gitignore"),s=pe.existsSync(n);if(!t&&!s)return"skipped";let o=s?pe.readFileSync(n,"utf8"):"";if(o.split(/\r?\n/).some(i=>/^\/?\.canopy\/?$/.test(i.trim())))return"already";let r=/\r\n/.test(o)?`\r
|
|
80
80
|
`:`
|
|
81
|
-
`;return
|
|
81
|
+
`;return pe.appendFileSync(n,(o&&!/\r?\n$/.test(o)?r:"")+"# Canopy (code map output)"+r+".canopy/"+r),s?"added":"created"}var di=e=>Xe.join(ge(e).root,"prefs.json"),pi=e=>{try{return JSON.parse(pe.readFileSync(di(e),"utf8"))}catch{return{}}};function xn(e,t){let n={...pi(e),...t};for(let s of Object.keys(n))n[s]===void 0&&delete n[s];pe.mkdirSync(ge(e).root,{recursive:!0}),pe.writeFileSync(di(e),JSON.stringify(n,null,2))}function ll(e){return new Promise(t=>{let n=sl.createServer();n.once("error",s=>t({ok:!1,code:s.code,message:s.message})),n.listen(e,"127.0.0.1",()=>{let s=n.address().port;n.close(()=>t({ok:!0,port:s}))})})}function fl(e){try{let t=pe.statfsSync(e);return Math.floor(t.bavail*t.bsize/1048576)}catch{return null}}var ul=()=>!!(process.stdin.isTTY&&process.stdout.isTTY)||!!process.env.CANOPY_ASSUME_TTY;function dl(e,t){return new Promise(n=>{let s=il.createInterface({input:process.stdin,output:process.stdout,terminal:!1}),o=!1,r=i=>{o||(o=!0,s.close(),n(i))};s.question(e,i=>r(i.trim())),s.once("close",()=>r(""))}).then(n=>n===""?t:n)}function pl(e){try{return JSON.parse(pe.readFileSync(Xe.join(e,"meta.json"),"utf8"))}catch{return null}}function ml(e){try{return JSON.parse(pe.readFileSync(Xe.join(e,"services.js"),"utf8").replace(/^\s*const services\s*=\s*/,"").replace(/;\s*$/,""))}catch{return[]}}var hl=e=>`How did it go? ${e.canopyFeedbackUrl||"see FEEDBACK.md in the README (about 20 minutes)"}`;async function mi(e){let{startViewer:t,openBrowser:n,viewerProblem:s}=await import("./chunk-WALU7QUQ.js"),o=e.say?null:li({caps:co({flags:{quiet:e.quiet,"no-color":e.noColor}})}),r=e.say??(p=>o.say(p)),i=p=>o?o.important(p):r(p),{pkg:c}=e,a=null;try{return await l()}catch(p){if(o?.endStep(!1),o?.restore(),p instanceof wn){if(i(p.line),a)try{pe.rmdirSync(a)}catch{}return p.code}return i(`Canopy stopped because of an unexpected problem: ${String(p.message??p).split(`
|
|
82
82
|
`)[0]}
|
|
83
|
-
Run "canopy doctor", then send its output and .canopy/sync.log to whoever gave you Canopy.`),process.env.CANOPY_DEBUG&&r(
|
|
84
|
-
`),r("[1/6] Checking this computer..."),Number(process.versions.node.split(".")[0])<18
|
|
85
|
-
What to try next: run canopy inside the folder that holds your .js / .ts code (for a monorepo, the folder of one package), or pass it: canopy <folder>.`);let
|
|
86
|
-
`);let
|
|
87
|
-
`)[0]+"); skipping the commit hook.");return}if(j==="current"){r(" The map already updates on every commit.");return}if(j==="outdated"){try{
|
|
88
|
-
`)[0])}return}if(
|
|
89
|
-
`)[0]+". Continuing without it.")}}async function
|
|
83
|
+
Run "canopy doctor", then send its output and .canopy/sync.log to whoever gave you Canopy.`),process.env.CANOPY_DEBUG&&r(p.stack),1}async function l(){let p=Xe.resolve(e.target??process.cwd());o?o.banner("Canopy",c.version,"a map of what your JavaScript / TypeScript code does"):r(`Canopy ${c.version} - a map of what your JavaScript / TypeScript code does`),r(`Folder: ${Xe.basename(p)||p}
|
|
84
|
+
`),r("[1/6] Checking this computer..."),Number(process.versions.node.split(".")[0])<18&&je(1,`Canopy needs Node 18 or newer and this is Node ${process.versions.node}. Install the current LTS from https://nodejs.org and run canopy again.`);let $=pe.existsSync(p)&&pe.statSync(p).isDirectory();pe.existsSync(p)||je(1,`That folder does not exist: ${p}. Check the spelling, or run canopy inside your project folder.`),$||je(1,`${p} is a file, not a folder. Run canopy on the folder that contains it: canopy "${Xe.dirname(p)}"`);let j=pe.existsSync(ge(p).root),g=gn(p);j||(a=ge(p).root);let k=g.find(C=>C.critical&&!C.ok);k&&je(1,`${k.name} failed${k.detail?" ("+k.detail+")":""}. ${k.fix}.`.replace(/\.\.$/,"."));let b=!!Ce(p,["rev-parse","--git-dir"]),S=g.find(C=>C.name==="git available")?.ok,m=s();m&&!e.noOpen&&je(1,`Canopy cannot show the map: ${m.replace(/\n\s*/g,". ")}.`);let u=fl(p);if(u!==null&&u<ui&&je(1,`Only ${u} MB free on the disk holding ${p}; Canopy needs about ${ui} MB. Free some space and run canopy again.`),!e.noOpen){let C=await ll(e.port??0);C.ok||je(1,C.code==="EADDRINUSE"?`Port ${e.port} is already in use. Pick another with --port=NUMBER, or leave --port out and Canopy picks a free one.`:`Canopy cannot open a local port on 127.0.0.1 (${C.code||C.message}). Check your firewall or security software and run canopy again.`)}r(` Node ${process.versions.node}, ${S?"git found":"git not found (no version history or commit hook)"}, ${u===null?"disk space not checked":u+" MB free"}${e.noOpen?"":", a local port is free"}.`),r("[2/6] Looking at your project..."),pe.readdirSync(p).filter(C=>C!==".git"&&C!==".canopy").length===0&&je(1,`${p} is empty. Add some JavaScript or TypeScript code and run canopy again.`);let h=Fn(p);h.length===0&&je(3,`No JavaScript or TypeScript files found in ${p}. Canopy currently supports JavaScript and TypeScript (${cl}); other languages are not read yet.
|
|
85
|
+
What to try next: run canopy inside the folder that holds your .js / .ts code (for a monorepo, the folder of one package), or pass it: canopy <folder>.`);let v=b&&Ce(p,["rev-parse","--verify","-q","HEAD"])!==null;r(` ${h.length.toLocaleString("en-US")} JavaScript / TypeScript file${h.length===1?"":"s"}. ${b?v?"Git repository.":"Git repository with no commits yet (that is fine).":"Not a git repository (that is fine; version-aware features are limited)."}`),r("[3/6] Preparing the output folder..."),pe.mkdirSync(ge(p).root,{recursive:!0}),Dt(p);let I=al(p),E={added:"added .canopy/ to .gitignore",created:"created .gitignore with .canopy/ in it",already:".canopy/ is already in .gitignore",skipped:"no git repository, so no .gitignore change"}[I];r(` Map output goes to ${Xe.join(p,".canopy")} (${E}).`),r("[4/6] Commit hook..."),await f(p,b);let M=ot(p).versions.length>0;r(`[5/6] ${M?"Checking what changed since last time":"Building your map for the first time (a big project can take a few minutes)"}...`);let A=await y(p,h.length);d(p,A);let L=null;try{L=Go(qo(p))}catch{L=null}L&&!(o&&o.caps.rich)&&r(` ${L}.
|
|
86
|
+
`);let O=Be(p);if(e.noOpen)return r("[6/6] Not opening the map (--no-open). To view it later: canopy open"),w(),0;r("[6/6] Opening the map...");let R=await yn(p,c.version);if(!R.ok&&R.running){let C=R.running.url,W=n(C);return o&&o.caps.quiet?(o.final({url:C}),0):(r(` Canopy is already running for this project (started ${R.running.startedAt?.replace("T"," ").slice(0,16)??"earlier"}): ${C}`),r(W?" Opened it in your browser. Nothing else was started.":" Open that address in your browser. Nothing else was started."),(!o||!o.caps.rich)&&w(),0)}R.ok||je(1,"Another Canopy is just starting for this project. Wait a few seconds and run canopy again, or open the address it printed.");let z;try{z=await t(O,e.port??0,{repoRoot:p}),vn(p,{port:z.port,version:c.version,navToken:z.navToken})}catch(C){je(1,`Canopy cannot start the viewer: ${C.code||C.message}. ${C.code==="EADDRINUSE"?"Pick another port with --port=NUMBER.":"Check your firewall or security software."}`)}let X=n(z.url);return o&&o.caps.rich?o.final({url:z.url,changes:L,update:jn(c.version),hint:X?"your browser should open now; press Ctrl+C to stop":"open that address in your browser; press Ctrl+C to stop"}):o&&o.caps.quiet?o.final({url:z.url}):(r(` ${z.url}`),r(X?" Your browser should open now. If it does not, paste that address into one.":" Open that address in your browser."),w()),e.forSeconds?(await new Promise(C=>setTimeout(C,e.forSeconds*1e3)),z.server.close(),o?.restore(),0):((!o||!o.caps.rich)&&r("Press Ctrl+C to stop."),await new Promise(()=>{}),0)}async function f(p,$){if(e.noHook){r(" Commit hook skipped (--no-hook).");return}if(!$){r(" No git repository here, so there is no commit hook to set up.");return}if(!gl()){r(" git is not installed, so the commit hook is skipped.");return}let j;try{j=ri(p)}catch(k){r(" Could not look at the git hooks ("+String(k.message).split(`
|
|
87
|
+
`)[0]+"); skipping the commit hook.");return}if(j==="current"){r(" The map already updates on every commit.");return}if(j==="outdated"){try{Pt(p),r(" Refreshed the commit hook (it now matches this Canopy).")}catch(k){r(" Could not refresh the commit hook: "+String(k.message).split(`
|
|
88
|
+
`)[0])}return}if(pi(p).hook==="declined"&&!e.yes){r(" The commit hook is off (you chose that earlier). Turn it on with: canopy hook install");return}let g=!0;if(e.yes)r(" Update the map on every commit? [Y/n] Y (--yes)");else if(!ul())r(" Update the map on every commit? [Y/n] Y (default; no terminal to ask)");else{let k=await dl(" Update the map on every commit? [Y/n] ","Y");g=/^y(es)?$/i.test(k)}if(!g){xn(p,{hook:"declined"}),r(" Okay, no hook. Turn it on any time with: canopy hook install");return}try{Pt(p),xn(p,{hook:void 0}),r(" Done: after every commit and merge the map updates itself in the background (it never blocks or fails a commit). Remove it with: canopy hook uninstall")}catch(k){r(" Could not install the commit hook: "+String(k.message).split(`
|
|
89
|
+
`)[0]+". Continuing without it.")}}async function y(p,$){let j=Date.now(),g=S=>{let m=String(S),u=/parsing: (\d+)\/(\d+) files/.exec(m);if(u){let x=Number(u[1]);o?o.progress(x,Number(u[2])):r(` reading files: ${u[1]} of ${u[2]}`);return}/^(linking calls|linking services|writing the map|storing the version|building the search index)/.test(m)&&(o?(o.endProgress(),o.status(m)):r(` ${m}`))};r(` Reading ${$.toLocaleString("en-US")} file${$===1?"":"s"}, linking calls, finding entry points, tracing workflows...`);let k;for(let S=0;S<2&&(k=await pn(p,{say:m=>g(m),onProgress:g,full:!!e.full}).catch(m=>je(1,`The analysis failed: ${String(m.message??m).split(`
|
|
90
90
|
`)[0]}
|
|
91
|
-
Run "canopy doctor" and send its output with ${
|
|
92
|
-
Your map`),r(` services: ${
|
|
93
|
-
`)}function
|
|
94
|
-
`);return
|
|
95
|
-
`+
|
|
96
|
-
`)}catch{}
|
|
91
|
+
Run "canopy doctor" and send its output with ${Xe.join(p,".canopy","sync.log")} to whoever gave you Canopy.`)),k.status==="queued");S++){r(" Another update is already running; waiting for it to finish...");for(let m=0;m<1200&&pe.existsSync(ge(p).lock);m++)await new Promise(u=>setTimeout(u,500))}k.status==="queued"&&je(1,"Another Canopy update is still running. Wait for it to finish and run canopy again."),o?.endProgress();let b=((Date.now()-j)/1e3).toFixed(1);return r(k.status==="no-changes"?` Nothing changed since version ${k.version.version} (${b} s).`:` Saved version ${k.version.version} (${b} s).`),k}function d(p,$){let j=Be(p),g=$.coverage??pl(j)?.coverage,k=ml(j),b=$.version.counts??{};if(r(`
|
|
92
|
+
Your map`),r(` services: ${k.length}${k.length?" ("+k.map(S=>S.id??S.name).slice(0,8).join(", ")+(k.length>8?", ...":"")+")":""}`),r(` workflows: ${b.workflows??"?"}${b.physicalWorkflows!==void 0?` (${b.physicalWorkflows} traced from real code, ${b.workflows-b.physicalWorkflows} guessed)`:""}`),g){let S=g.analyzed?Math.round(g.inService/g.analyzed*100):0;r(` files inside a service: ${g.inService} of ${g.analyzed} (${S}%)`),r(` files with parse errors: ${g.parseErrors}${g.parseErrors?" ("+g.parseErrorFiles.slice(0,3).join(", ")+(g.parseErrorFiles.length>3?", ...":"")+")":""}`),g.notAnalyzedTotal&&r(` not read yet: ${g.notAnalyzedTotal} files in languages Canopy does not support (${Object.entries(g.notAnalyzed).map(([m,u])=>`${u} ${m}`).join(", ")})`)}k.length||r(" The map is empty: Canopy found no entry points (routes, listeners, a main file) it recognises in this project."),r("")}function w(){o&&o.close(),r("Next time just run `canopy`.");let p=jn(c.version);p&&r(p),r(hl(c))}}function gl(){return!!Ce(rl.tmpdir(),["--version"])}import Sn from"node:fs";import hi from"node:os";import Qe from"node:path";import{spawn as yl}from"node:child_process";var kn="CANOPY_CHILD",vl=2048,wl=8192,gi=1024*1024;function xl({env:e=process.env,nodeOptions:t=e.NODE_OPTIONS??"",totalmem:n=hi.totalmem()}={}){let s=Number(e.CANOPY_MAX_MEMORY_MB);if(Number.isFinite(s)&&s>=256)return{mb:Math.floor(s),source:"CANOPY_MAX_MEMORY_MB"};let o=/--max-old-space-size[= ](\d+)/.exec(t);return o?{mb:null,userMb:Number(o[1]),source:"NODE_OPTIONS"}:{mb:Math.max(vl,Math.min(wl,Math.floor(n*.75/gi))),source:"75% of this computer's memory"}}var Sl=new Set(["version","help","update","hook","install-hook","uninstall-hook","doctor","history","diff","open","mcp","install","uninstall"]);function lo(e){if(e.some(s=>s==="--version"||s==="--help"||s==="-v"||s==="-h"))return!1;let n=e.filter(s=>!s.startsWith("-"))[0];return n===void 0?!0:Sl.has(n)?!1:n==="sync"?!e.includes("--background"):Sn.existsSync(Qe.resolve(n))||/^[.~]|[\\/]/.test(n)}function $n(e,t=process.cwd()){let n=e.filter(s=>!s.startsWith("-"));return n[0]==="sync"?Qe.resolve(n[1]??t):Qe.resolve(n[0]??t)}var kl=/heap out of memory|Allocation failed|JavaScript heap|FatalProcessOutOfMemory|out of memory/i;function $l({code:e,signal:t,stderrTail:n="",platform:s=process.platform}){if(kl.test(n))return{kind:"memory",why:"Node reported that it ran out of memory"};if(t==="SIGINT"||t==="SIGTERM"||t==="SIGHUP")return null;if(t==="SIGABRT")return{kind:"memory",why:"the process aborted (usually out of memory)"};if(t==="SIGKILL")return{kind:"killed",why:"the system stopped the process (usually because the computer ran out of memory)"};if(t==="SIGSEGV"||t==="SIGBUS")return{kind:"crash",why:"the process crashed"};if(e==null)return t?{kind:"crash",why:`the process ended on signal ${t}`}:{kind:"crash",why:"the process ended without an exit code"};let o=e>>>0;if(s==="win32"){if(o>=3221225472)return{kind:o===3221226505?"memory":"crash",why:`Windows reported error 0x${o.toString(16).toUpperCase()} (a fatal stop, usually out of memory)`};if(o>255)return{kind:"crash",why:`the process ended with the unusual code ${o}`}}return e===134?{kind:"memory",why:"the process aborted (exit code 134, usually out of memory)"}:e===137?{kind:"killed",why:"the system stopped the process (exit code 137, usually out of memory)"}:e===139||e===135?{kind:"crash",why:`the process crashed (exit code ${e})`}:null}function bl(e,{projectRoot:t,stage:n,memory:s}){let o=[],r=e.kind==="memory"?"Canopy ran out of memory":e.kind==="killed"?"Canopy was stopped by the system, most likely because the computer ran out of memory":"Canopy stopped unexpectedly";return o.push(`${r}${n?` while it was working on: ${n}`:""}.`),o.push(` (${e.why}.)`),o.push(""),o.push("What to try next:"),o.push(" 1. Analyse one part of the project at a time: canopy <folder of a package or app>"),o.push(` 2. Give Canopy more memory: set CANOPY_MAX_MEMORY_MB (it used ${s?.mb??s?.userMb??"the default"} MB), for example CANOPY_MAX_MEMORY_MB=${Math.min(16384,Math.max(4096,(s?.mb??4096)*2))} canopy`),o.push(" 3. Close other programs, then run it again: the files already read are remembered, so the second run is faster."),t&&o.push("",`Details for a bug report (no code or secrets): ${Qe.join(".canopy","last-error.txt")} in the project folder.`),o.join(`
|
|
93
|
+
`)}function fo(e,{version:t,stage:n,code:s,signal:o,memory:r,totalmem:i=hi.totalmem()}){try{let c=Qe.join(e,".canopy");Sn.mkdirSync(c,{recursive:!0});let a=[`time: ${new Date().toISOString()}`,`engine version: ${t}`,`stage: ${n??"unknown"}`,`exit: ${o?"signal "+o:s}`,`memory ceiling: ${r?.mb??"left to NODE_OPTIONS"+(r?.userMb?" ("+r.userMb+" MB)":"")} MB (${r?.source??"?"}); computer memory ${Math.round(i/gi)} MB`,""].join(`
|
|
94
|
+
`);return Sn.writeFileSync(Qe.join(c,"last-error.txt"),a),Qe.join(c,"last-error.txt")}catch{return null}}function yi(e){let{args:t,scriptPath:n,version:s="?",env:o=process.env,projectRoot:r=$n(t),execPath:i=process.execPath,execArgv:c=process.execArgv,spawnFn:a=yl,platform:l=process.platform,err:f=process.stderr,onChild:y=null}=e,d=e.memory??xl({env:o}),w=[...d.mb?[`--max-old-space-size=${d.mb}`]:[],...c.filter(p=>!p.startsWith("--max-old-space-size")),n,...t];return new Promise(p=>{let $="",j=a(i,w,{env:{...o,[kn]:"1"},stdio:["inherit","inherit","pipe"],windowsHide:!1});y?.(j),j.stderr?.on("data",u=>{try{f.write(u)}catch{}$=($+u.toString("utf8")).slice(-4e3)});let g=u=>()=>{try{j.kill(u)}catch{}},k=g("SIGTERM");process.on("SIGTERM",k);let b=process.stdin.isTTY?()=>{}:g("SIGINT");process.on("SIGINT",b);let S=!1,m=(u,x)=>{if(S)return;S=!0,process.off("SIGTERM",k),process.off("SIGINT",b);let h=$l({code:u,signal:x,stderrTail:$,platform:l});if(!h){p(u??(x?1:0));return}let v=Gr(r);fo(r,{version:s,stage:v,code:u,signal:x,memory:d});try{Sn.rmSync(Qe.join(r,".canopy","last-stage.txt"),{force:!0})}catch{}try{f.write(`
|
|
95
|
+
`+bl(h,{projectRoot:r,stage:v,memory:d})+`
|
|
96
|
+
`)}catch{}p(1)};j.on("error",u=>{try{f.write(`Canopy could not start its worker process: ${String(u.message).split(`
|
|
97
97
|
`)[0]}
|
|
98
|
-
`)}catch{}
|
|
98
|
+
`)}catch{}m(1,null)}),j.on("close",(u,x)=>m(u,x))})}var ke=JSON.parse(bn.readFileSync(kt.join(Ae,"package.json"),"utf8")),Il={"-y":"--yes","-h":"--help","-v":"--version"},vi=process.argv.slice(2).map(e=>Il[e]??e),Q=Object.fromEntries(vi.filter(e=>e.startsWith("--")).map(e=>{let[t,n]=e.slice(2).split("=");return[t,n??!0]})),Ee=vi.filter(e=>!e.startsWith("--")),me=Ee.shift(),jl=e=>/^v?\d+$/.test(e??""),Pe=()=>kt.resolve(Ee[0]&&!jl(Ee[0])?Ee.shift():process.cwd()),wi=`canopy ${ke.version} - a map of what your JavaScript / TypeScript code does
|
|
99
99
|
|
|
100
100
|
usage: canopy [path] [-y] [--no-open] do everything in order: check this computer, look at the project, prepare .canopy/,
|
|
101
101
|
offer the commit hook, build the map, open it in your browser (default path: current folder)
|
|
@@ -107,6 +107,8 @@ usage: canopy [path] [-y] [--no-open] do everything in order: check this com
|
|
|
107
107
|
diff [path] [from] [to] what changed between two versions [--json]
|
|
108
108
|
hook install [path] run "canopy sync" in the background after every commit and merge (safe to repeat)
|
|
109
109
|
hook uninstall [path] remove it again
|
|
110
|
+
ai [path] which Claude Code the viewer's Ask AI panel would use (found automatically, e.g. the VS Code extension's copy)
|
|
111
|
+
telemetry on|off|status|show anonymous, opt-in usage counts (nothing is sent unless you say yes); "show" prints exactly what would be sent
|
|
110
112
|
mcp [path] a read-only MCP server (stdio) that lets your own AI tool search and read the map; Canopy never calls an AI service
|
|
111
113
|
install [path] [--yes] connect Claude Code / Cursor / Gemini CLI to it: shows the project files it will write, then asks [Y/n]; "uninstall" removes them
|
|
112
114
|
update [--check] look up the newest version on npm (the only command that uses the network); "update" installs it with npm
|
|
@@ -117,19 +119,27 @@ options for the one-command path: -y / --yes (do not ask; install the hook), --n
|
|
|
117
119
|
--full (ignore everything remembered and analyse from scratch), --quiet (only problems and the address), --no-color (also: NO_COLOR=1)
|
|
118
120
|
Memory: a whole analysis gets about 75% of this computer's memory (2-8 GB). CANOPY_MAX_MEMORY_MB=<number> sets it; CANOPY_DEBUG_MEM=1 prints the memory at each stage.
|
|
119
121
|
Exit codes: 0 ok, 1 a problem (the message says what to do), 3 no JavaScript / TypeScript files found.
|
|
120
|
-
Node >= 18 required. Output lives in <path>/.canopy/ (kept out of git automatically).`;async function
|
|
121
|
-
fix: canopy sync "${e}"`),process.exit(1));let{startViewer:n,viewerProblem:s}=await import("./chunk-
|
|
122
|
+
Node >= 18 required. Output lives in <path>/.canopy/ (kept out of git automatically).`;async function El(){let e=Pe(),t=Be(e);bn.existsSync(kt.join(t,"workflows.js"))||(console.error(`no map yet for ${e}
|
|
123
|
+
fix: canopy sync "${e}"`),process.exit(1));let{startViewer:n,viewerProblem:s}=await import("./chunk-WALU7QUQ.js"),o=s();o&&(console.error(o),process.exit(1));let r=await yn(e,ke.version);if(!r.ok&&r.running){console.log(`canopy map for ${e}
|
|
122
124
|
${r.running.url}
|
|
123
|
-
already running for this project (started ${r.running.startedAt??"earlier"}); nothing else was started`);return}r.ok||(console.error("another canopy is just starting for this project; wait a few seconds and try again"),process.exit(1));let{server:i,url:c,port:a,navToken:l}=await n(t,
|
|
124
|
-
${c}`),
|
|
125
|
-
|
|
126
|
-
|
|
125
|
+
already running for this project (started ${r.running.startedAt??"earlier"}); nothing else was started`);return}r.ok||(console.error("another canopy is just starting for this project; wait a few seconds and try again"),process.exit(1));let{server:i,url:c,port:a,navToken:l}=await n(t,Q.port?Number(Q.port):0,{repoRoot:e});if(vn(e,{port:a,version:ke.version,navToken:l}),console.log(`canopy map for ${e}
|
|
126
|
+
${c}`),Q.for){console.log(`serving for ${Number(Q.for)} s`),await new Promise(f=>setTimeout(f,Number(Q.for)*1e3)),i.close();return}console.log("press Ctrl+C to stop"),await new Promise(()=>{})}async function xi(e){try{let{describeClaude:t}=await import("./chunk-ZE3NJMCS.js");return await t(e)}catch{return"Ask AI: Claude Code could not be checked."}}async function Rl(){let e=Pe(),t=ci(gn(e),e,ke.version);console.log(await xi(e)),process.exit(t?1:0)}var $t={async sync(){let e=Pe();if(Q.background){let s=si(e);s?console.log(`sync started in the background (pid ${s}); log: .canopy/sync.log`):console.error(`not a directory, nothing to sync: ${e}`);return}let t=Q.keep?Number(Q.keep):Bt,n=await pn(e,{keep:t,full:!!Q.full});!Q.quiet&&n?.status!=="queued"&&console.log(Yo({version:ke.version})),await Ze().flush()},open:El,async doctor(){await Rl()},async ai(){console.log(await xi(Pe()))},async telemetry(){let e=Ee.shift()??"status",t=Ze({version:ke.version});if(e==="on")t.setConsent(!0),console.log(t.configured?"Anonymous usage counts are ON. Turn them off any time with: canopy telemetry off":"Saved as ON, but this build has no usage-statistics address, so nothing is sent.");else if(e==="off")t.setConsent(!1),console.log("Anonymous usage counts are OFF. The random install id was deleted.");else if(e==="show"){let n=t.show();console.log(`What would be sent for one event (the API key is not shown):
|
|
127
|
+
`+JSON.stringify(n.sample,null,2)+`
|
|
128
|
+
|
|
129
|
+
Everything that can ever be sent (any other key is dropped; values are fixed words or whole numbers):
|
|
130
|
+
`+n.fields.join(`
|
|
131
|
+
`)+`
|
|
132
|
+
|
|
133
|
+
Never sent: code, file paths, project / function / workflow names, search text, AI questions or answers, environment values, host names. No IP address is stored.`)}else if(e==="status"){let n=t.status();console.log(`Usage counts: ${n.active?"ON (sending)":n.choice==="on"?"ON, but not sending":n.choice==="off"?"OFF":"not chosen yet"}${n.hardOff?` (forced off: ${n.hardOff})`:""}${n.configured?"":" (this build has no usage-statistics address: dormant)"}
|
|
134
|
+
Choice file: ${n.file}`)}else console.error("usage: canopy telemetry on|off|status|show"),process.exit(2)},async mcp(){let e=Pe(),{runMcp:t}=await import("./chunk-TV6NLY7O.js");await t({repoRoot:e,outDir:Be(e),version:ke.version,aiPanel:!!Q["ai-panel"]})},async install(){let{installCommand:e}=await import("./chunk-4XUKEJ3C.js");process.exit(await e(Pe(),{yes:!!Q.yes}))},async uninstall(){let{uninstallCommand:e}=await import("./chunk-4XUKEJ3C.js");process.exit(await e(Pe()))},async update(){process.exit(await Jo({check:!!Q.check,version:ke.version}))},async diff(){let e=Pe(),t=ot(e);if(t.versions.length<2){console.log(t.versions.length?"only one version so far - nothing to diff yet":"no versions yet - run: canopy sync");return}let n=i=>{let c=Number(String(i).replace(/^v/,"")),a=t.versions.find(l=>l.version===c);if(!a)throw new Error(`no such version: ${i} (have ${t.versions.map(l=>"v"+l.version).join(", ")})`);return a},s=Ee[1]!==void 0?n(Ee[1]):t.versions[t.versions.length-1],o=Ee[0]!==void 0?n(Ee[0]):t.versions[t.versions.indexOf(s)-1];if(!o)throw new Error("no earlier version to compare against");let r=zo(In(e,o),In(e,s));console.log(Q.json?Wo(r):Uo(r,s,o))},async"install-hook"(){let e=Pe(),t=Pt(e);xn(e,{hook:void 0}),console.log("installed canopy block in: "+t.join(", "))},async"uninstall-hook"(){let e=oi(Pe());console.log(e.length?"removed canopy block from: "+e.join(", "):"no canopy hook block found")},async hook(){let e=Ee.shift();if(e==="install")return $t["install-hook"]();if(e==="uninstall")return $t["uninstall-hook"]();console.error("usage: canopy hook install|uninstall [path]"),process.exit(2)},async history(){let e=Pe(),t=ot(e);if(!t.versions.length)return console.log("no versions yet - run: canopy sync");for(let n of t.versions)console.log(`v${n.version} ${n.fingerprint.slice(0,7)} ${n.createdAt} ${n.headSha?n.headSha.slice(0,7):"-------"}${n.dirty?"*":" "} ${n.headMessage?JSON.stringify(n.headMessage):""} nodes ${n.counts.nodes} edges ${n.counts.edges} workflows ${n.counts.workflows} ${(n.bytes/1024).toFixed(0)} KB${n.gzip?" gz":""}`)}};Number(process.versions.node.split(".")[0])<18&&(console.error(`Canopy needs Node 18 or newer, and this is Node ${process.versions.node}.
|
|
135
|
+
What to try next: install the current LTS from https://nodejs.org (or run: nvm install --lts), open a new terminal, and run canopy again.`),process.exit(1));if(process.env[kn]!=="1"&&!Q.help&&!Q.version&&(me===void 0||me==="sync"||me==="open"||!$t[me]&&(bn.existsSync(kt.resolve(me))||/^[.~]|[\\/]/.test(me)))){let e=Ze({version:ke.version});if(e.shouldAsk({isTTY:!!(process.stdin.isTTY&&process.stdout.isTTY),quiet:!!Q.quiet,background:!!Q.background})){let t=Nl.createInterface({input:process.stdin,output:process.stdout}),n=await new Promise(s=>t.question("Help improve Canopy? Share anonymous usage counts (no code, no file or project names, no questions). You can change this any time with `canopy telemetry off`. [y/N] ",s));t.close(),e.setConsent(/^\s*y(es)?\s*$/i.test(String(n)))}}process.env[kn]!=="1"&&process.env.CANOPY_NO_RESPAWN!=="1"&&lo(process.argv.slice(2))&&process.exit(await yi({args:process.argv.slice(2),scriptPath:process.argv[1],version:ke.version}));var Si=e=>{let t=String(e?.message??e).split(`
|
|
136
|
+
`)[0].slice(0,200),n=$n(process.argv.slice(2));fo(n,{version:ke.version,stage:dn(),code:1,memory:{mb:null,source:"this run"}}),console.error(`Canopy stopped unexpectedly${dn()?" while it was working on: "+dn():""}.
|
|
127
137
|
(${t})
|
|
128
138
|
|
|
129
139
|
What to try next:
|
|
130
140
|
1. canopy doctor checks Node, the grammars and write access
|
|
131
141
|
2. canopy <folder> try one package or app at a time
|
|
132
142
|
3. run it again: the files already read are remembered
|
|
133
|
-
Details for a bug report (no code or secrets): .canopy/last-error.txt in the project folder.`),process.exit(1)};process.on("uncaughtException",
|
|
143
|
+
Details for a bug report (no code or secrets): .canopy/last-error.txt in the project folder.`);let s=Ze({version:ke.version});s.record("error",{error_code:"other"}),Promise.race([s.flush(),new Promise(o=>setTimeout(o,2200))]).finally(()=>process.exit(1))};process.on("uncaughtException",Si);process.on("unhandledRejection",Si);lo(process.argv.slice(2))&&Ur($n(process.argv.slice(2)));process.on("exit",()=>qr());(Q.version||me==="version")&&(console.log(ke.version),process.exit(0));(Q.help||me==="help")&&(console.log(wi),process.exit(0));if(me===void 0||!$t[me]&&(bn.existsSync(kt.resolve(me))||/^[.~]|[\\/]/.test(me))){me!==void 0&&Ee.unshift(me);let e=await mi({target:Ee[0]?kt.resolve(Ee[0]):process.cwd(),yes:!!Q.yes,noOpen:!!Q["no-open"],quiet:!!Q.quiet,noColor:!!Q["no-color"],noHook:!!Q["no-hook"],full:!!Q.full,port:Q.port?Number(Q.port):void 0,forSeconds:Q.for?Number(Q.for):void 0,pkg:ke});await Ze().flush(),process.exit(e)}$t[me]||(console.error(`unknown command: ${me}
|
|
134
144
|
|
|
135
|
-
${
|
|
145
|
+
${wi}`),process.exit(2));$t[me]().catch(e=>{console.error(e.stack||e.message),process.exit(1)});
|