canopy-engine 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/canopy.js CHANGED
@@ -3,66 +3,77 @@ import{fileURLToPath as __cf,pathToFileURL as __cu}from"node:url";import{dirname
3
3
  const require=__cr(import.meta.url);
4
4
  globalThis.__canopyBundle=__cf(import.meta.url);
5
5
  globalThis.__canopyUrl=(r)=>__cu(__cj(__cd(__cd(globalThis.__canopyBundle)),r)).href;
6
- var Oa=Object.create;var Zn=Object.defineProperty;var Ma=Object.getOwnPropertyDescriptor;var Ha=Object.getOwnPropertyNames;var Da=Object.getPrototypeOf,Ua=Object.prototype.hasOwnProperty;var wt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Ba=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},za=(e,t)=>{for(var n in t)Zn(e,n,{get:t[n],enumerable:!0})},Wa=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ha(t))!Ua.call(e,o)&&o!==n&&Zn(e,o,{get:()=>t[o],enumerable:!(r=Ma(t,o))||r.enumerable});return e};var qa=(e,t,n)=>(n=e!=null?Oa(Da(e)):{},Wa(t||!e||!e.__esModule?Zn(n,"default",{value:e,enumerable:!0}):n,e));var dr=Ba((jf,sn)=>{function rr(e){return Array.isArray(e)?e:[e]}var Ga=void 0,eo="",nr=" ",Qn="\\",Ja=/^\s+$/,Ka=/(?:[^\\]|^)\\$/,Va=/^\\!/,Ya=/^\\#/,Xa=/\r?\n/g,Za=/^\.{0,2}\/|^\.{1,2}$/,Qa=/\/$/,St="/",sr="node-ignore";typeof Symbol<"u"&&(sr=Symbol.for("node-ignore"));var ir=sr,kt=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),ec=/([0-z])-([0-z])/g,ar=()=>!1,tc=e=>e.replace(ec,(t,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?t:eo),nc=e=>e.startsWith("!")||e.startsWith("\\^")?`^${e.slice(e[0]==="!"?1:2)}`:e,oc=e=>{let{length:t}=e;return e.slice(0,t-t%2)},rc=[[/^\uFEFF/,()=>eo],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?nr:eo)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+nr}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*(?:\\\*\\\*\\\/)+/,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>{let r=n.replace(/\\\*/g,"[^\\/]*");return t+r}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Qn],[/\\\\/g,()=>Qn],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,o)=>t===Qn?`\\[${n}${oc(r)}${o}`:o==="]"&&r.length%2===0?`[${nc(tc(n))}${r}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],sc=/(^|\\\/)?\\\*$/,At="regex",on="checkRegex",or="_",ic={[At](e,t){return`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`},[on](e,t){return`${t?`${t}[^/]*`:"[^/]*"}(?=$|\\/$)`}},ac=e=>rc.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),rn=e=>typeof e=="string",cc=e=>e&&rn(e)&&!Ja.test(e)&&!Ka.test(e)&&e.indexOf("#")!==0,lc=e=>e.split(Xa).filter(Boolean),to=class{constructor(t,n,r,o,s,i){this.pattern=t,this.mark=n,this.negative=s,kt(this,"body",r),kt(this,"ignoreCase",o),kt(this,"regexPrefix",i)}get regex(){let t=or+At;return this[t]?this[t]:this._make(At,t)}get checkRegex(){let t=or+on;return this[t]?this[t]:this._make(on,t)}_make(t,n){let r=this.regexPrefix.replace(sc,ic[t]),o=this.ignoreCase?new RegExp(r,"i"):new RegExp(r);return kt(this,n,o)}},dc=({pattern:e,mark:t},n)=>{let r=!1,o=e;o.indexOf("!")===0&&(r=!0,o=o.substr(1)),o=o.replace(Va,"!").replace(Ya,"#");let s=ac(o);return new to(e,t,o,n,r,s)},no=class{constructor(t){this._ignoreCase=t,this._rules=[]}_add(t){if(t&&t[ir]){this._rules=this._rules.concat(t._rules._rules),this._added=!0;return}if(rn(t)&&(t={pattern:t}),cc(t.pattern)){let n=dc(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,rr(rn(t)?lc(t):t).forEach(this._add,this),this._added}test(t,n,r){let o=!1,s=!1,i;this._rules.forEach(l=>{let{negative:c}=l;s===c&&o!==s||c&&!o&&!s&&!n||!l[r].test(t)||(o=!c,s=c,i=c?Ga:l)});let a={ignored:o,unignored:s};return i&&(a.rule=i),a}},fc=(e,t)=>{throw new t(e)},We=(e,t,n)=>rn(e)?e?We.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),cr=e=>Za.test(e);We.isNotRelative=cr;We.convert=e=>e;var oo=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:r=!1}={}){kt(this,ir,!0),this._rules=new no(n),this._strictPathCheck=!r,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,r,o){let s=t&&We.convert(t);return We(s,t,this._strictPathCheck?fc:ar),this._t(s,n,r,o)}checkIgnore(t){if(!Qa.test(t))return this.test(t);let n=t.split(St).filter(Boolean);if(n.pop(),n.length){let r=this._t(n.join(St)+St,this._testCache,!0,n);if(r.ignored)return r}return this._rules.test(t,!1,on)}_t(t,n,r,o){if(t in n)return n[t];if(o||(o=t.split(St).filter(Boolean)),o.pop(),!o.length)return n[t]=this._rules.test(t,r,At);let s=this._t(o.join(St)+St,n,r,o);return n[t]=s.ignored?s:this._rules.test(t,r,At)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return rr(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},ro=e=>new oo(e),uc=e=>We(e&&We.convert(e),e,ar),lr=()=>{let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");We.convert=e;let t=/^[a-z]:\//i;We.isNotRelative=n=>t.test(n)||cr(n)};typeof process<"u"&&process.platform==="win32"&&lr();sn.exports=ro;ro.default=ro;sn.exports.isPathValid=uc;kt(sn.exports,Symbol.for("setupWindows"),lr)});import vr from"node:fs";import Qe from"node:path";import{fileURLToPath as Nc}from"node:url";function je(e){let t=Qe.join(re,"vendor",e);if(bt()&&vr.existsSync(t))return t;for(let n=re;;n=Qe.dirname(n)){let r=Qe.join(n,"node_modules",e);if(vr.existsSync(r))return r;if(Qe.dirname(n)===n)break}return Qe.join(re,"node_modules",e)}var re,bt,Le=wt(()=>{re=Qe.join(Qe.dirname(Nc(globalThis.__canopyUrl("src/utils/pkgPath.js"))),"..","..");bt=()=>re.split(Qe.sep).includes("node_modules")});import Et from"node:fs";import Me from"node:path";import wd from"node:crypto";import{fileURLToPath as Sd}from"node:url";function Bo(e){let t=[];for(let n of Et.readdirSync(e,{withFileTypes:!0}).sort((r,o)=>r.name<o.name?-1:1)){let r=Me.join(e,n.name);n.isDirectory()?t.push(...Bo(r)):/\.(js|scm)$/.test(n.name)&&t.push(r)}return t}function On(){if(Uo)return Uo;let e=wd.createHash("sha256");if(!Et.existsSync(Do)&&globalThis.__canopyBundle){let t=globalThis.__canopyBundle;e.update("bundle\0").update(Et.readFileSync(t));let n=Me.join(Me.dirname(t),"queries");if(Et.existsSync(n))for(let r of Bo(n))e.update(Me.relative(n,r).split(Me.sep).join("/")).update("\0").update(Gi(r)).update("\0")}else for(let t of Bo(Do))e.update(Me.relative(Do,t).split(Me.sep).join("/")).update("\0").update(Gi(t)).update("\0");for(let t of["web-tree-sitter","tree-sitter-javascript","tree-sitter-typescript","tree-sitter-html"])try{e.update(t+"@"+JSON.parse(Et.readFileSync(Me.join(je(t),"package.json"),"utf8")).version)}catch{e.update(t+"@?")}return Uo=e.digest("hex").slice(0,16)}var An,Do,Gi,Uo,zo=wt(()=>{Le();An=1,Do=Me.join(Me.dirname(Sd(globalThis.__canopyUrl("src/history/engineVersion.js"))),"..");Gi=e=>Et.readFileSync(e).toString("utf8").replace(/\r\n/g,`
7
- `),Uo=null});function Pt(e){let t=n=>Array.isArray(n)?n.map(t):n&&typeof n=="object"?Object.fromEntries(Object.keys(n).sort().map(r=>[r,t(n[r])])):n;return JSON.stringify(t(e))}function Ji(e){let t=[],n=[],r=[];for(let[i,a]of e.publicGraph){for(let l of a.nodes)t.push({id:l.id,service:i,kind:l.type,name:l.name,filePath:l.filePath,startLine:l.startLine,endLine:l.endLine,bodyHash:l.bodyHash});for(let l of a.edges)n.push({id:l.id,service:i,from:l.fromNodeId,callKind:l.callKind??l.type,calleeNameRaw:l.calleeNameRaw??l.eventName??l.url??null,resolvedTo:l.targetNodeId??null})}let o=new Map;for(let i of e.publicWorkflows){let a=i.steps[0]?.nodeId??null,l=`${i.serviceId} | ${a} | ${i.name}`,c=(o.get(l)??0)+1;o.set(l,c),r.push({id:c>1?`${l} #${c}`:l,service:i.serviceId,tier:i.tier,tierOrigin:i.tierOrigin,entry:a,steps:i.steps.map(d=>d.nodeId)})}t.sort(Mn(i=>i.service+"\0"+i.id)),n.sort(Mn(i=>i.service+"\0"+i.id)),r.sort(Mn(i=>i.id));let s=e.publicCrossServiceEdges.map(i=>({fromService:i.fromService,fromNodeId:i.fromNodeId,toService:i.toService,toNodeId:i.toNodeId,via:i.via,key:i.key??null,confidence:i.confidence??null})).sort(Mn(i=>[i.fromService,i.fromNodeId,i.toService,i.toNodeId,i.via,i.key].join("\0")));return{schema:1,fingerprint:e.fingerprint,nodes:t,edges:n,workflows:r,crossServiceEdges:s}}var Mn,Hn=wt(()=>{Mn=e=>(t,n)=>{let r=e(t),o=e(n);return r<o?-1:r>o?1:0}});import X from"node:fs";import we from"node:path";import Ki from"node:zlib";import{execFileSync as kd}from"node:child_process";function be(e,t){try{return kd("git",["-C",we.resolve(e),...t],{stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim()}catch{return null}}function Dn(e){let t=be(e,["rev-parse","--git-path","info/exclude"]);if(!t)return!1;let n=we.resolve(e,t);X.mkdirSync(we.dirname(n),{recursive:!0});let r=X.existsSync(n)?X.readFileSync(n,"utf8"):"";return r.split(/\r?\n/).some(o=>o.trim()===".canopy/")||X.appendFileSync(n,(r&&!r.endsWith(`
6
+ var ic=Object.create;var oo=Object.defineProperty;var ac=Object.getOwnPropertyDescriptor;var cc=Object.getOwnPropertyNames;var lc=Object.getPrototypeOf,dc=Object.prototype.hasOwnProperty;var _t=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(s){throw n=[s],s}};var fc=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},uc=(e,t)=>{for(var n in t)oo(e,n,{get:t[n],enumerable:!0})},pc=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of cc(t))!dc.call(e,o)&&o!==n&&oo(e,o,{get:()=>t[o],enumerable:!(s=ac(t,o))||s.enumerable});return e};var mc=(e,t,n)=>(n=e!=null?ic(lc(e)):{},pc(t||!e||!e.__esModule?oo(n,"default",{value:e,enumerable:!0}):n,e));var ws=fc((vu,ln)=>{function ms(e){return Array.isArray(e)?e:[e]}var hc=void 0,ro="",us=" ",so="\\",gc=/^\s+$/,yc=/(?:[^\\]|^)\\$/,xc=/^\\!/,vc=/^\\#/,wc=/\r?\n/g,Sc=/^\.{0,2}\/|^\.{1,2}$/,kc=/\/$/,$t="/",hs="node-ignore";typeof Symbol<"u"&&(hs=Symbol.for("node-ignore"));var gs=hs,It=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),Nc=/([0-z])-([0-z])/g,ys=()=>!1,bc=e=>e.replace(Nc,(t,n,s)=>n.charCodeAt(0)<=s.charCodeAt(0)?t:ro),_c=e=>e.startsWith("!")||e.startsWith("\\^")?`^${e.slice(e[0]==="!"?1:2)}`:e,$c=e=>{let{length:t}=e;return e.slice(0,t-t%2)},Ic=[[/^\uFEFF/,()=>ro],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?us:ro)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+us}],[/[\\$.|*+(){^]/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,()=>so],[/\\\\/g,()=>so],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,s,o)=>t===so?`\\[${n}${$c(s)}${o}`:o==="]"&&s.length%2===0?`[${_c(bc(n))}${s}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],Fc=/(^|\\\/)?\\\*$/,Bt="regex",an="checkRegex",ps="_",jc={[Bt](e,t){return`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`},[an](e,t){return`${t?`${t}[^/]*`:"[^/]*"}(?=$|\\/$)`}},Cc=e=>Ic.reduce((t,[n,s])=>t.replace(n,s.bind(e)),e),cn=e=>typeof e=="string",Ec=e=>e&&cn(e)&&!gc.test(e)&&!yc.test(e)&&e.indexOf("#")!==0,Pc=e=>e.split(wc).filter(Boolean),io=class{constructor(t,n,s,o,r,i){this.pattern=t,this.mark=n,this.negative=r,It(this,"body",s),It(this,"ignoreCase",o),It(this,"regexPrefix",i)}get regex(){let t=ps+Bt;return this[t]?this[t]:this._make(Bt,t)}get checkRegex(){let t=ps+an;return this[t]?this[t]:this._make(an,t)}_make(t,n){let s=this.regexPrefix.replace(Fc,jc[t]),o=this.ignoreCase?new RegExp(s,"i"):new RegExp(s);return It(this,n,o)}},Lc=({pattern:e,mark:t},n)=>{let s=!1,o=e;o.indexOf("!")===0&&(s=!0,o=o.substr(1)),o=o.replace(xc,"!").replace(vc,"#");let r=Cc(o);return new io(e,t,o,n,s,r)},ao=class{constructor(t){this._ignoreCase=t,this._rules=[]}_add(t){if(t&&t[gs]){this._rules=this._rules.concat(t._rules._rules),this._added=!0;return}if(cn(t)&&(t={pattern:t}),Ec(t.pattern)){let n=Lc(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,ms(cn(t)?Pc(t):t).forEach(this._add,this),this._added}test(t,n,s){let o=!1,r=!1,i;this._rules.forEach(l=>{let{negative:c}=l;r===c&&o!==r||c&&!o&&!r&&!n||!l[s].test(t)||(o=!c,r=c,i=c?hc:l)});let a={ignored:o,unignored:r};return i&&(a.rule=i),a}},Tc=(e,t)=>{throw new t(e)},Ke=(e,t,n)=>cn(e)?e?Ke.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),xs=e=>Sc.test(e);Ke.isNotRelative=xs;Ke.convert=e=>e;var co=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:s=!1}={}){It(this,gs,!0),this._rules=new ao(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&&Ke.convert(t);return Ke(r,t,this._strictPathCheck?Tc:ys),this._t(r,n,s,o)}checkIgnore(t){if(!kc.test(t))return this.test(t);let n=t.split($t).filter(Boolean);if(n.pop(),n.length){let s=this._t(n.join($t)+$t,this._testCache,!0,n);if(s.ignored)return s}return this._rules.test(t,!1,an)}_t(t,n,s,o){if(t in n)return n[t];if(o||(o=t.split($t).filter(Boolean)),o.pop(),!o.length)return n[t]=this._rules.test(t,s,Bt);let r=this._t(o.join($t)+$t,n,s,o);return n[t]=r.ignored?r:this._rules.test(t,s,Bt)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return ms(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},lo=e=>new co(e),Rc=e=>Ke(e&&Ke.convert(e),e,ys),vs=()=>{let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");Ke.convert=e;let t=/^[a-z]:\//i;Ke.isNotRelative=n=>t.test(n)||xs(n)};typeof process<"u"&&process.platform==="win32"&&vs();ln.exports=lo;lo.default=lo;ln.exports.isPathValid=Rc;It(ln.exports,Symbol.for("setupWindows"),vs)});import js from"node:fs";import ot from"node:path";import{fileURLToPath as Gc}from"node:url";function Ae(e){let t=ot.join(re,"vendor",e);if(jt()&&js.existsSync(t))return t;for(let n=re;;n=ot.dirname(n)){let s=ot.join(n,"node_modules",e);if(js.existsSync(s))return s;if(ot.dirname(n)===n)break}return ot.join(re,"node_modules",e)}var re,jt,De=_t(()=>{re=ot.join(ot.dirname(Gc(globalThis.__canopyUrl("src/utils/pkgPath.js"))),"..","..");jt=()=>re.split(ot.sep).includes("node_modules")});import At from"node:fs";import qe from"node:path";import zd from"node:crypto";import{fileURLToPath as Wd}from"node:url";function Jo(e){let t=[];for(let n of At.readdirSync(e,{withFileTypes:!0}).sort((s,o)=>s.name<o.name?-1:1)){let s=qe.join(e,n.name);n.isDirectory()?t.push(...Jo(s)):/\.(js|scm)$/.test(n.name)&&t.push(s)}return t}function Dn(){if(Go)return Go;let e=zd.createHash("sha256");if(!At.existsSync(qo)&&globalThis.__canopyBundle){let t=globalThis.__canopyBundle;e.update("bundle\0").update(At.readFileSync(t));let n=qe.join(qe.dirname(t),"queries");if(At.existsSync(n))for(let s of Jo(n))e.update(qe.relative(n,s).split(qe.sep).join("/")).update("\0").update(na(s)).update("\0")}else for(let t of Jo(qo))e.update(qe.relative(qo,t).split(qe.sep).join("/")).update("\0").update(na(t)).update("\0");for(let t of["web-tree-sitter","tree-sitter-javascript","tree-sitter-typescript","tree-sitter-html"])try{e.update(t+"@"+JSON.parse(At.readFileSync(qe.join(Ae(t),"package.json"),"utf8")).version)}catch{e.update(t+"@?")}return Go=e.digest("hex").slice(0,16)}var Hn,qo,na,Go,Ko=_t(()=>{De();Hn=1,qo=qe.join(qe.dirname(Wd(globalThis.__canopyUrl("src/history/engineVersion.js"))),"..");na=e=>At.readFileSync(e).toString("utf8").replace(/\r\n/g,`
7
+ `),Go=null});function Ot(e){let t=n=>Array.isArray(n)?n.map(t):n&&typeof n=="object"?Object.fromEntries(Object.keys(n).sort().map(s=>[s,t(n[s])])):n;return JSON.stringify(t(e))}function oa(e){let t=[],n=[],s=[];for(let[i,a]of e.publicGraph){for(let l of a.nodes)t.push({id:l.id,service:i,kind:l.type,name:l.name,filePath:l.filePath,startLine:l.startLine,endLine:l.endLine,bodyHash:l.bodyHash});for(let l of a.edges)n.push({id:l.id,service:i,from:l.fromNodeId,callKind:l.callKind??l.type,calleeNameRaw:l.calleeNameRaw??l.eventName??l.url??null,resolvedTo:l.targetNodeId??null})}let o=new Map;for(let i of e.publicWorkflows){let a=i.steps[0]?.nodeId??null,l=`${i.serviceId} | ${a} | ${i.name}`,c=(o.get(l)??0)+1;o.set(l,c),s.push({id:c>1?`${l} #${c}`:l,service:i.serviceId,tier:i.tier,tierOrigin:i.tierOrigin,entry:a,steps:i.steps.map(d=>d.nodeId)})}t.sort(Bn(i=>i.service+"\0"+i.id)),n.sort(Bn(i=>i.service+"\0"+i.id)),s.sort(Bn(i=>i.id));let r=e.publicCrossServiceEdges.map(i=>({fromService:i.fromService,fromNodeId:i.fromNodeId,toService:i.toService,toNodeId:i.toNodeId,via:i.via,key:i.key??null,confidence:i.confidence??null})).sort(Bn(i=>[i.fromService,i.fromNodeId,i.toService,i.toNodeId,i.via,i.key].join("\0")));return{schema:1,fingerprint:e.fingerprint,nodes:t,edges:n,workflows:s,crossServiceEdges:r}}var Bn,Un=_t(()=>{Bn=e=>(t,n)=>{let s=e(t),o=e(n);return s<o?-1:s>o?1:0}});import Z from"node:fs";import ke from"node:path";import sa from"node:zlib";import{execFileSync as qd}from"node:child_process";function Ie(e,t){try{return qd("git",["-C",ke.resolve(e),...t],{stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim()}catch{return null}}function zn(e){let t=Ie(e,["rev-parse","--git-path","info/exclude"]);if(!t)return!1;let n=ke.resolve(e,t);Z.mkdirSync(ke.dirname(n),{recursive:!0});let s=Z.existsSync(n)?Z.readFileSync(n,"utf8"):"";return s.split(/\r?\n/).some(o=>o.trim()===".canopy/")||Z.appendFileSync(n,(s&&!s.endsWith(`
8
8
  `)?`
9
9
  `:"")+`.canopy/
10
- `),!0}function He(e){let t=se(e);try{return JSON.parse(X.readFileSync(t.index,"utf8"))}catch{return{schema:1,nextVersion:1,versions:[]}}}function Fd(e,t){let n=se(e);X.mkdirSync(n.history,{recursive:!0});let r=n.index+"."+process.pid+".tmp";X.writeFileSync(r,JSON.stringify(t,null,2)),X.renameSync(r,n.index)}function Lt(e,t){let n=X.readFileSync(we.join(se(e).history,t.file));return JSON.parse((t.gzip?Ki.gunzipSync(n):n).toString("utf8"))}function Vi(e,t,n,r,o=Wt,{refresh:s=!1}={}){let i=se(e);X.mkdirSync(i.history,{recursive:!0});let a=He(e),l=!0,c=n.fingerprint+(l?".json.gz":".json"),d=we.join(i.history,c);(s||!X.existsSync(d))&&X.writeFileSync(d,l?Ki.gzipSync(t):t);let p=(be(e,["status","--porcelain"])||"").split(`
11
- `).some(w=>w.trim()&&!/\.canopy(\/|$)/.test(w)),f=s?a.versions.pop():null,u={version:f?f.version:a.nextVersion,fingerprint:n.fingerprint,createdAt:new Date().toISOString(),headSha:be(e,["rev-parse","HEAD"]),headMessage:be(e,["log","-1","--format=%s"]),dirty:p,counts:r,file:c,gzip:l,bytes:X.statSync(d).size,engineVersion:On(),outputFormat:An};for(a.versions.push(u),f||a.nextVersion++;a.versions.length>o;)a.versions.shift();let m=_d(),h=w=>{try{return X.statSync(we.join(i.history,w.file)).size}catch{return w.bytes??0}},v=a.versions.reduce((w,S)=>w+h(S),0);for(;v>m&&a.versions.length>bd;)v-=h(a.versions.shift());let g=new Set(a.versions.map(w=>w.file));for(let w of X.readdirSync(i.history))/\.json(\.gz)?$/.test(w)&&w!=="index.json"&&!g.has(w)&&X.rmSync(we.join(i.history,w),{force:!0});return Fd(e,a),u}function Yi(e){let t=se(e);X.mkdirSync(t.root,{recursive:!0});for(let n=0;n<2;n++)try{let r=X.openSync(t.lock,"wx");return X.writeSync(r,JSON.stringify({pid:process.pid,startedAt:Date.now()})),X.closeSync(r),!0}catch(r){if(r.code!=="EEXIST")throw r;let o=1/0;try{o=Date.now()-X.statSync(t.lock).mtimeMs}catch{continue}if(o<$d)return!1;X.rmSync(t.lock,{force:!0})}return!1}var Nd,bd,_d,$d,Wt,se,Xi,Zi,Qi,pt=wt(()=>{zo();Nd=200,bd=2,_d=()=>{let e=Number(process.env.CANOPY_SNAPSHOT_MAX_MB);return(Number.isFinite(e)&&e>0?e:Nd)*1024*1024},$d=600*1e3,Wt=50,se=e=>{let t=we.join(we.resolve(e),".canopy");return{root:t,history:we.join(t,"history"),index:we.join(t,"history","index.json"),lock:we.join(t,"sync.lock"),pending:we.join(t,"sync.pending"),log:we.join(t,"sync.log")}};Xi=e=>X.rmSync(se(e).lock,{force:!0}),Zi=e=>{let t=se(e);X.mkdirSync(t.root,{recursive:!0}),X.writeFileSync(t.pending,String(Date.now()))},Qi=e=>{let t=se(e);return X.existsSync(t.pending)?(X.rmSync(t.pending,{force:!0}),!0):!1}});function ea(e){let t=new Map;for(let n of e.nodes){let r=t.get(n.id);r?r.services.push(n.service):t.set(n.id,{id:n.id,services:[n.service],kind:n.kind,name:n.name,filePath:n.filePath,bodyHash:n.bodyHash})}for(let n of t.values())n.services.sort();return t}function jd(e){return t=>{if(t==null)return t;if(e.has(t))return e.get(t);for(let[n,r]of e)if(t.startsWith(n+" | "))return r+t.slice(n.length);return t}}function qo(e,t){let n=a=>a.reduce((l,c)=>l.set(c,(l.get(c)??0)+1),new Map),r=n(e),o=n(t),s=[],i=[];for(let[a,l]of o)for(let c=0;c<l-(r.get(a)??0);c++)s.push(a);for(let[a,l]of r)for(let c=0;c<l-(o.get(a)??0);c++)i.push(a);return{added:s.sort(),removed:i.sort()}}function Un(e,t){let n=ea(e),r=ea(t),o=[...r.values()].filter(_=>!n.has(_.id)),s=[...n.values()].filter(_=>!r.has(_.id)),i=[];for(let[_,C]of r){let M=n.get(_);M&&M.bodyHash!==C.bodyHash&&i.push({...Wo(C),from:M.bodyHash,to:C.bodyHash})}let a=[],l=new Map,c=_=>[_.kind,_.name,_.bodyHash].join("\0"),d=new Map;for(let _ of Se(o,C=>C.id)){let C=c(_);d.has(C)||d.set(C,[]),d.get(C).push(_)}let p=[],f=new Set;for(let _ of Se(s,C=>C.id)){let M=(d.get(c(_))??[]).find(ie=>!f.has(ie.id)&&ie.filePath!==_.filePath&&ie.id.split("::").pop()===_.id.split("::").pop());M?(f.add(M.id),a.push({kind:_.kind,name:_.name,services:M.services,fromId:_.id,toId:M.id,fromPath:_.filePath,toPath:M.filePath}),l.set(_.id,M.id)):p.push(_)}o=Se(o.filter(_=>!f.has(_.id)),_=>_.id),s=Se(p,_=>_.id);let u=jd(l),m=_=>_.service+"\0"+_.id,h=new Map(e.edges.map(_=>[m({service:_.service,id:u(_.id)}),{..._,id:u(_.id),from:u(_.from),resolvedTo:u(_.resolvedTo)}])),v=new Map(t.edges.map(_=>[m(_),_])),g=_=>({id:_.id,service:_.service,from:_.from,callKind:_.callKind,calleeNameRaw:_.calleeNameRaw,resolvedTo:_.resolvedTo}),w=[],S=[],N=[];for(let[_,C]of v){let M=h.get(_);M?M.resolvedTo!==C.resolvedTo&&N.push({id:C.id,service:C.service,from:C.from,calleeNameRaw:C.calleeNameRaw,fromTarget:M.resolvedTo,toTarget:C.resolvedTo}):w.push(g(C))}for(let[_,C]of h)v.has(_)||S.push(g(C));let y=_=>_.service+"\0"+_.id,x=_=>({..._,id:_.id.replace(_.entry??"\0",u(_.entry)),entry:u(_.entry),steps:_.steps.map(u)}),b=new Map(e.workflows.map(_=>{let C=x(_);return[C.id,C]})),k=new Map(t.workflows.map(_=>[_.id,_])),$={added:[],removed:[],changed:[]},j={added:[],removed:[],changed:[]},D=_=>({id:_.id,service:_.service,tier:_.tier,steps:_.steps.length});for(let[_,C]of k){let M=b.get(_);if(!M){(C.tier==="physical"?$:j).added.push(D(C));continue}let ie=qo(M.steps,C.steps),ze=!ie.added.length&&!ie.removed.length&&M.steps.join(`
12
- `)!==C.steps.join(`
13
- `),F=M.tier!==C.tier?`${M.tier} -> ${C.tier}`:null;if(!ie.added.length&&!ie.removed.length&&!ze&&!F)continue;let P={id:_,service:C.service,tier:C.tier,stepsAdded:ie.added,stepsRemoved:ie.removed,reordered:ze,tierChange:F};(M.tier==="physical"||C.tier==="physical"?$:j).changed.push(P)}for(let[_,C]of b)k.has(_)||(C.tier==="physical"?$:j).removed.push(D(C));for(let _ of[$,j])for(let C of["added","removed","changed"])_[C]=Se(_[C],M=>M.id);let L=_=>[_.fromService,_.fromNodeId,_.toService,_.toNodeId,_.via,_.key].join(" | "),K=new Map(e.crossServiceEdges.map(_=>[L({..._,fromNodeId:u(_.fromNodeId),toNodeId:u(_.toNodeId)}),{..._,fromNodeId:u(_.fromNodeId),toNodeId:u(_.toNodeId)}])),z=new Map(t.crossServiceEdges.map(_=>[L(_),_])),O=Se([...z].filter(([_])=>!K.has(_)).map(([,_])=>_),L),W=Se([...K].filter(([_])=>!z.has(_)).map(([,_])=>_),L),G=new Map,te=new Map,ge=(_,C,M)=>{_.has(C)||_.set(C,new Set),_.get(C).add(M)};for(let _ of s)ge(G,_.id,"removed");for(let _ of o)ge(te,_.id,"added");for(let _ of i)ge(G,_.id,"modified"),ge(te,_.id,"modified");for(let _ of a)ge(G,_.fromId,"moved"),ge(te,_.toId,"moved");let rt=[],Be=new Set([...b.keys(),...k.keys()]);for(let _ of Be){let C=b.get(_),M=k.get(_);if(!(C&&C.tier==="physical"||M&&M.tier==="physical"))continue;let ie=new Map;for(let[F,P]of[[C,G],[M,te]])if(F)for(let R of new Set(F.steps))for(let I of P.get(Qt(R,F===C,l))??[])ie.set(R+"\0"+I,{node:R,why:I});let ze=C&&M&&(qo(C.steps,M.steps).added.length||qo(C.steps,M.steps).removed.length);ie.size&&rt.push({workflow:_,service:(M??C).service,status:C?M?"changed":"removed":"new",stepsChanged:!!ze,reasons:Se([...ie.values()],F=>F.node+"\0"+F.why)})}function Qt(_,C,M){if(!C)return _;for(let[ie,ze]of M)if(ze===_)return ie;return _}let Rt={schema:1,from:e.fingerprint,to:t.fingerprint,nodes:{added:o.map(Wo),removed:s.map(Wo),modified:Se(i,_=>_.id),moved:Se(a,_=>_.toId)},edges:{added:Se(w,y),removed:Se(S,y),retargeted:Se(N,y)},workflows:{physical:$,guessed:j},crossServiceEdges:{added:O,removed:W},touched:Se(rt,_=>_.workflow)};return Rt.counts={nodes:{added:o.length,removed:s.length,modified:i.length,moved:a.length},edges:{added:w.length,removed:S.length,retargeted:N.length},physicalWorkflows:{added:$.added.length,removed:$.removed.length,changed:$.changed.length},guessedWorkflows:{added:j.added.length,removed:j.removed.length,changed:j.changed.length},crossServiceEdges:{added:O.length,removed:W.length},touched:rt.length,touchedNew:rt.filter(_=>_.status==="new").length},Rt}function na(e,t,n,{limit:r=40}={}){let o=e.counts,s=t?`v${t.version} (${(t.headSha??t.fingerprint).slice(0,7)}${t.headMessage?` ${JSON.stringify(t.headMessage)}`:""})`:"to",i=[];i.push(`${s} \u2190 ${n?"v"+n.version:"from"}: nodes +${o.nodes.added} \u2212${o.nodes.removed} ~${o.nodes.modified} \u21A6${o.nodes.moved} | edges +${o.edges.added} \u2212${o.edges.removed}${o.edges.retargeted?` ~${o.edges.retargeted}`:""} | physical workflows touched: ${o.touched} (${o.touchedNew} new)`);let a=(c,d,p)=>{if(d.length){i.push("",`${c} (${d.length})`);for(let f of d.slice(0,r))i.push(" "+p(f));d.length>r&&i.push(` ... ${d.length-r} more`)}};a("Touched physical workflows",e.touched,c=>`[${c.service}] ${c.workflow.split(" | ").slice(2).join(" | ")} <${c.status}> because: ${c.reasons.slice(0,4).map(d=>`${d.why} ${mt(d.node)}`).join(", ")}${c.reasons.length>4?`, +${c.reasons.length-4}`:""}`),a("Nodes added",e.nodes.added,c=>`+ ${c.id}`),a("Nodes removed",e.nodes.removed,c=>`- ${c.id}`),a("Nodes modified",e.nodes.modified,c=>`~ ${c.id}`),a("Nodes moved",e.nodes.moved,c=>`\u21A6 ${c.name}: ${c.fromPath} \u2192 ${c.toPath}`),a("Edges added",e.edges.added,c=>`+ [${c.service}] ${mt(c.from)} \u2192 ${c.calleeNameRaw}${c.resolvedTo?` (resolved to ${mt(c.resolvedTo)})`:""}`),a("Edges removed",e.edges.removed,c=>`- [${c.service}] ${mt(c.from)} \u2192 ${c.calleeNameRaw}`),a("Edges retargeted",e.edges.retargeted,c=>`~ [${c.service}] ${mt(c.from)} \u2192 ${c.calleeNameRaw}: ${mt(c.fromTarget)||"unresolved"} \u2192 ${mt(c.toTarget)||"unresolved"}`),a("Physical workflows changed",e.workflows.physical.changed,c=>`~ ${c.id.split(" | ").slice(2).join(" | ")} +${c.stepsAdded.length} \u2212${c.stepsRemoved.length} steps${c.tierChange?`, tier ${c.tierChange}`:""}${c.reordered?", reordered":""}`),a("Physical workflows added",e.workflows.physical.added,c=>`+ ${c.id.split(" | ").slice(2).join(" | ")} (${c.steps} steps)`),a("Physical workflows removed",e.workflows.physical.removed,c=>`- ${c.id.split(" | ").slice(2).join(" | ")}`),a("Cross-service edges added",e.crossServiceEdges.added,c=>`+ ${c.fromService} \u2192 ${c.toService} via ${c.via} ${c.key??""}`),a("Cross-service edges removed",e.crossServiceEdges.removed,c=>`- ${c.fromService} \u2192 ${c.toService} via ${c.via} ${c.key??""}`);let l=o.guessedWorkflows;return l.added+l.removed+l.changed&&i.push("",`Informational (guessed workflows, never counted as changes): +${l.added} \u2212${l.removed} ~${l.changed}`),i.join(`
14
- `)}var Id,Se,Wo,ta,mt,Go=wt(()=>{Hn();Id=(e,t)=>e<t?-1:e>t?1:0,Se=(e,t)=>e.slice().sort((n,r)=>Id(t(n),t(r)));Wo=e=>({id:e.id,services:e.services,kind:e.kind,name:e.name,filePath:e.filePath});ta=e=>Pt(e),mt=e=>(e??"").split("::").slice(-2).join("::")});var ia={};za(ia,{UI_VERSIONS:()=>ra,buildUiHistory:()=>sa,writeHistoryJs:()=>Pd});import oa from"node:fs";import Cd from"node:path";function Ed(e){let t=JSON.parse(JSON.stringify(e));t.truncated={};let n=(r,o)=>{for(let[s,i]of Object.entries(r))Array.isArray(i)&&i.length>Bn&&(t.truncated[`${o}.${s}`]=i.length,r[s]=i.slice(0,Bn))};return n(t.nodes,"nodes"),n(t.edges,"edges"),n(t.workflows.physical,"workflows.physical"),n(t.crossServiceEdges,"crossServiceEdges"),t.touched.length>Bn&&(t.truncated.touched=t.touched.length,t.touched=t.touched.slice(0,Bn)),t}function sa(e){let n=He(e).versions.slice(-ra),r={};for(let o=1;o<n.length;o++)r[n[o].version]=Ed(Un(Lt(e,n[o-1]),Lt(e,n[o])));return{schema:1,versions:n.map(o=>({version:o.version,fingerprint:o.fingerprint,createdAt:o.createdAt,headSha:o.headSha,headMessage:o.headMessage,dirty:o.dirty,counts:o.counts})),diffs:r}}function Pd(e,t){oa.mkdirSync(t,{recursive:!0}),oa.writeFileSync(Cd.join(t,"history.js"),`const canopyHistory = ${Pt(sa(e))};`)}var ra,Bn,aa=wt(()=>{pt();Go();Hn();ra=20,Bn=200});import Zo from"node:fs";import Yt from"node:path";import nt from"node:fs";import Ld from"node:os";import he from"node:path";import{fileURLToPath as ca}from"node:url";import J from"node:path";import me from"node:fs";import{fileURLToPath as gd,pathToFileURL as yd}from"node:url";var ao=qa(dr(),1);import Nt from"node:fs";import ke from"node:path";var so={javascript:[".js",".jsx",".mjs",".cjs"],typescript:[".ts",".tsx"]},fr=[".ts",".tsx",".mts",".cts"],pc={javascript:["index.js","index.jsx"],typescript:["index.ts","index.tsx"]};function ur(){return Object.values(so).flat()}function pr(){return Object.values(pc).flat()}var mr=["log","logger","console","debug","trace"];var gr=[".yarn",".pnp","vendor","dist","build","out","coverage",".next",".nuxt",".turbo",".cache","bower_components"],co=["node_modules",".git",".canopy",".canopy-cache"],hr=[".vue",".svelte"],mc=1024*1024,io=1e4;function hc(e,t=null){let n=[];function r(o,s){let i=ke.join(o,".gitignore"),a=(0,ao.default)().add(s);Nt.existsSync(i)&&a.add(Nt.readFileSync(i,"utf-8"));let l=Nt.readdirSync(o,{withFileTypes:!0});for(let c of l){let d=ke.join(o,c.name),p=ke.relative(e,d).split(ke.sep).join("/");if(!a.ignores(p)&&!(c.isDirectory()&&co.includes(c.name))){if(c.isDirectory()&&gr.includes(c.name)){t&&t.excludedDirs.push(d);continue}c.isDirectory()?r(d,a):c.isFile()&&n.push(d)}}}return r(e,(0,ao.default)()),n}function gc(e,t,n=null){return e.filter(r=>!(n?ke.relative(n,r):r).split(ke.sep).some(s=>t.includes(s)))}function yr(e,t){let n=0,r;try{r=Nt.readdirSync(e,{withFileTypes:!0})}catch{return 0}for(let o of r)o.isDirectory()?co.includes(o.name)||(n+=yr(ke.join(e,o.name),t)):o.isFile()&&t.has(ke.extname(o.name))&&n++;return n}var yc=e=>/\.d\.(ts|mts|cts)$/.test(e);function xc(e){let t=ke.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=Nt.statSync(e).size}catch{return null}if(n>mc)return{kind:"oversized",reason:`oversized (${(n/1048576).toFixed(1)} MB, limit 1 MB)`};if(n>io){let r=Nt.readFileSync(e,"utf8"),o=0,s=0;for(;;){let i=r.indexOf(`
15
- `,o),a=(i<0?r.length:i)-o;if(a>s&&(s=a),i<0)break;o=i+1}if(s>io)return{kind:"minified",reason:`line of ${s.toLocaleString("en-US")} characters (limit ${io.toLocaleString("en-US")}; minified/bundled)`}}return null}function lo(e,t=["javascript","typescript"]){let n=t.flatMap(p=>(p==="typescript"?fr:so[p])||[]),r={excludedDirs:[]},o=gc(hc(e,r),[...gr,...co],e),s=p=>ke.relative(e,p).split(ke.sep).join("/"),i=[],a=[],l={};for(let p of o){let f=ke.extname(p);if(n.includes(f)){if(yc(p)){a.push({file:s(p),kind:"declaration",reason:"declaration file"});continue}let u=xc(p);u?a.push({file:s(p),kind:u.kind,reason:u.reason}):i.push(p)}else hr.includes(f)&&(l[f]=(l[f]??0)+1)}let c=new Set([...n,...hr]),d={};for(let p of r.excludedDirs){let f=ke.basename(p),u=d[f]??={dirs:0,files:0};u.dirs++,u.files+=yr(p,c)}return{files:i,skipped:a,unsupported:l,excludedDirs:d}}function an(e,t=["javascript","typescript"]){return lo(e,t).files}import vc from"node:path";var at=e=>e.toLocaleString("en-US"),cn=(e,t,n=t+"s")=>`${at(e)} ${e===1?t:n}`,wc={".vue":"Vue",".svelte":"Svelte"},Sc=[".vue",".svelte"],kc=new Set([".ts",".tsx",".mts",".cts"]);function xr({discovered:e,parseResults:t,scopeFiles:n,rel:r,rootService:o=null}){let s=(t.budgetSkips??[]).map(m=>({path:r(m.filePath),kind:"timeout",reason:m.reason})),i=new Set((t.budgetSkips??[]).map(m=>m.filePath)),a=[...e.skipped.map(m=>({path:m.file,kind:m.kind,reason:m.reason})),...s].sort((m,h)=>m.path<h.path?-1:m.path>h.path?1:0),l=e.files.filter(m=>!i.has(m)),c=l.filter(m=>t.get(m)?.hadErrors).map(r).sort(),d=l.flatMap(m=>(t.get(m)?.warnings??[]).map(h=>({path:r(m),extractor:h.extractor,message:h.message}))).sort((m,h)=>m.path<h.path?-1:m.path>h.path?1:0),p=l.filter(m=>kc.has(vc.extname(m))).length,f={};for(let m of Sc)e.unsupported[m]&&(f[m]=e.unsupported[m]);let u={};for(let m of a)u[m.kind]=(u[m.kind]??0)+1;return{analyzed:l.length,analyzedJs:l.length-p,analyzedTs:p,inService:l.filter(m=>n.has(m)).length,notAnalyzed:f,notAnalyzedTotal:Object.values(f).reduce((m,h)=>m+h,0),skipped:a,skippedByKind:u,parseErrors:c.length,parseErrorFiles:c.slice(0,50),parseWarnings:d.length,parseWarningList:d.slice(0,50),excludedDirs:e.excludedDirs,rootService:o}}function ln(e){let t=["Coverage"],n=[],r=new Map;for(let[a,l]of Object.entries(e.notAnalyzed)){let c=wc[a];r.has(c)||r.set(c,[]),r.get(c).push(`${at(l)} ${a}`)}for(let[a,l]of r)n.push(`${l.join(", ")} files (${a} not supported yet)`);if(e.skipped.length){let a=Object.entries(e.skippedByKind).map(([l,c])=>`${l}: ${c}`).join(", ");n.push(`${at(e.skipped.length)} skipped (${a})`)}e.parseErrors&&n.push(`${at(e.parseErrors)} with parse errors`),e.parseWarnings&&n.push(`${at(e.parseWarnings)} extractor warnings (a construct skipped; the rest of its file was analyzed)`);let o=e.analyzedTs?`${cn(e.analyzedJs,"JS file")} and ${cn(e.analyzedTs,"TS file")}`:cn(e.analyzed,"JS file");t.push(` Analyzed ${o}, ${at(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 s=e.skipped.filter(a=>a.kind!=="declaration");for(let a of s.slice(0,5))t.push(` skipped ${a.path}: ${a.reason}`);s.length>5&&t.push(` ... and ${at(s.length-5)} more (full list: meta.coverage.skipped)`);let i=Object.entries(e.excludedDirs);return i.length&&t.push(` Excluded directories: ${i.map(([a,l])=>`${a}/ x${l.dirs} (${cn(l.files,"source file")})`).join(", ")}.`),e.rootService&&t.push(` Root service: ${e.rootService.reason}.`),t.join(`
16
- `)}Le();import{Parser as fo,Language as wr}from"web-tree-sitter";import dn from"node:path";import{fileURLToPath as bc}from"node:url";var qf=dn.dirname(bc(globalThis.__canopyUrl("src/stage2_parse/initParser.js")));var uo=new WeakMap,Ot=e=>uo.get(e)??"javascript",et=e=>Ot(e)!=="javascript";function po(e){let t=dn.extname(e);return t===".tsx"?"tsx":t===".ts"||t===".mts"||t===".cts"?"typescript":"javascript"}var _c={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm"};async function Sr(e,t){for(let n of new Set(t.map(po))){if(e.grammars.has(n))continue;let r=dn.join(je("tree-sitter-typescript"),_c[n]),o=await wr.load(r);uo.set(o,n);let s=new fo;s.setLanguage(o),e.grammars.set(n,{parser:s,language:o})}return e}async function kr(){await fo.init();let e=new fo,t=dn.join(je("tree-sitter-javascript"),"tree-sitter-javascript.wasm"),n=await wr.load(t);return e.setLanguage(n),uo.set(n,"javascript"),{parser:e,language:n,grammars:new Map([["javascript",{parser:e,language:n}]])}}import $c from"node:fs";function $r(e,t){let n=$c.readFileSync(t,"utf-8"),r=e.parse(n);if(mo(r)||n.includes("\0")){let o=n,s=_r(r);for(let i of Fc){let a=i.apply(o);if(a===o)continue;let l=e.parse(a),c=_r(l);(c<s||i.always)&&(o=a,r=l,s=c)}o!==n&&(r.canopyOriginalSource=n)}return{tree:r,source:n,filePath:t}}var Fr=e=>e.replace(/[^\n]/g," "),Nr=e=>"any"+Fr(e).slice(3),br=/(?<![&])&(?![&=])/g,Fc=[{name:"NUL byte",always:!0,apply:e=>e.replace(/\0/g," ")},{name:"export type * from",apply:e=>e.replace(/\bexport\s+type\s+\*\s*(?:as\s+[\w$]+\s+)?from\s*(["'])[^"'\n]*\1\s*;?/g,Fr)},{name:"typeof import()",apply:e=>e.replace(/typeof\s+import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)*/g,Nr)},{name:"import().Type",apply:e=>e.replace(/(?<=[:<,|&?]\s*|\breadonly\s+|\bkeyof\s+|\bextends\s+|\bas\s+)import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)+(?!\s*\()/g,Nr)},{name:"generic call signature after a member",apply:e=>e.replace(/(?<=\n[ \t]*)[ ](?=<\s*[A-Za-z_$][\w$]*\s*(?:extends\b|=|,|>\s*\())/g,";")},{name:"& in JSX text",apply:e=>e.replace(/>[^<>{}"'`]*&[^<>{}"'`]*</g,t=>t.replace(br,"+"))},{name:"& in JSX attribute",apply:e=>e.replace(/(\s[\w:-]+=)"([^"\n]*)"/g,(t,n,r)=>n+'"'+r.replace(br,"+")+'"')}];function _r(e){let t=0;return(function n(r){if(r.type==="ERROR"){t++;return}for(let o=0;o<r.childCount;o++)n(r.child(o))})(e.rootNode),t}function mo(e){let t=!1;function n(r){if(r.type==="ERROR"){t=!0;return}for(let o=0;o<r.childCount;o++)n(r.child(o))}return n(e.rootNode),t}import ho from"node:fs";import Mt from"node:path";import{fileURLToPath as Ic}from"node:url";import{Query as jc}from"web-tree-sitter";var Ir=Mt.dirname(Ic(globalThis.__canopyUrl("src/utils/loadQuery.js"))),jr=new WeakMap;function ee(e,t){let n=jr.get(e);if(n||jr.set(e,n=new Map),n.has(t))return n.get(t);let r=Mt.join(Ir,"..","stage2_parse","queries"),o=ho.existsSync(r)?r:Mt.join(Ir,"..","..","dist","queries"),s=Ot(e),l=(s==="javascript"?[]:s==="tsx"?["tsx","typescript"]:[s]).map(p=>Mt.join(o,p,t)).find(p=>ho.existsSync(p))??Mt.join(o,t),c=ho.readFileSync(l,"utf-8"),d=new jc(e,c);return n.set(t,d),d}var Cr="javascript",Er=e=>{Cr=e};var fn=()=>Cr!=="javascript";var Cc=new Set(["non_null_expression","as_expression","satisfies_expression","type_assertion"]);function ce(e){for(;e;)if(Cc.has(e.type))e=e.type==="type_assertion"?e.namedChild(e.namedChildCount-1):e.namedChild(0);else if(e.type==="parenthesized_expression"&&e.namedChildCount===1){let t=ce(e.namedChild(0));if(t===e.namedChild(0))break;e=t}else break;return e}function Ec(e){let t=e;for(;t;){t=ce(t);for(let n=0;n<t.childCount;n++)if(t.child(n).type==="optional_chain")return!0;if(t.type==="member_expression"||t.type==="subscript_expression")t=t.childForFieldName("object");else if(t.type==="call_expression")t=t.childForFieldName("function");else break}return!1}function tt(e){let t=e.childForFieldName("function"),n=e.childForFieldName("arguments");if(!t)return{kind:"callOfCall",oldShape:!1,nameNode:e};let r=t.type==="identifier",o=t.type==="member_expression"?t.childForFieldName("property"):null,s=t.type==="member_expression"?ce(t.childForFieldName("object")):null,i=r||s?.type==="identifier"&&o?.type==="property_identifier",a=o??t;if(fn()&&e.parent?.type==="decorator")return{kind:"decorator",oldShape:i,nameNode:a};if(n&&n.type==="template_string")return{kind:"taggedTemplate",oldShape:i,nameNode:a};if(Ec(e))return{kind:"optionalCall",oldShape:i,nameNode:a};if(r)return{kind:"call",oldShape:i,nameNode:a};if(t.type==="subscript_expression")return{kind:"computed",oldShape:!1,nameNode:t};if(t.type==="member_expression")return s.type==="super"?{kind:"super",oldShape:!1,nameNode:a}:s.type==="this"?{kind:"thisCall",oldShape:!1,nameNode:a}:i?{kind:"methodCall",oldShape:!0,nameNode:a}:{kind:"chainedCall",oldShape:!1,nameNode:a};if(t.type==="import")return{kind:"dynamicImport",oldShape:!1,nameNode:t};if(t.type==="super")return{kind:"super",oldShape:!1,nameNode:t};let l=t;for(;l.type==="parenthesized_expression"&&l.namedChildCount===1;)l=l.namedChild(0);return l.type==="arrow_function"||l.type==="function_expression"||l.type==="function"||l.type==="generator_function"?{kind:"iife",oldShape:!1,nameNode:t}:{kind:"callOfCall",oldShape:!1,nameNode:t}}function Pr(e){let t=e.childForFieldName("name");return t?t.type==="identifier"?/^[A-Z]/.test(t.text)?{kind:"jsx",oldShape:!0,nameNode:t}:null:t.type==="member_expression"||t.type==="nested_identifier"?{kind:"jsxMember",oldShape:!1,nameNode:t}:null:null}function un(e){let t=e;for(;t&&t.type!=="call_expression";)t=t.parent;return t}function Lr(e){let t=e.childForFieldName("function"),n=!1;for(;t;)if(t=ce(t),t.type==="member_expression"||t.type==="subscript_expression")t=t.childForFieldName("object");else if(t.type==="call_expression")n=!0,t=t.childForFieldName("function");else if(t.type==="await_expression"||t.type==="parenthesized_expression"||t.type==="non_null_expression")t=t.namedChild(0);else break;return t&&t.type==="identifier"?{head:t.text,called:n}:{head:null,called:!1}}function Rr(e){let t=e.text.replace(/\s+/g," ");return t.length>120?t.slice(0,117)+"...":t}function Ar(e,t){let o=ee(t,"functionDeclarations.scm").matches(e.rootNode).map(s=>{let i=s.captures.find(c=>c.name==="func_name"),a=s.captures.find(c=>c.name==="func_params"),l=s.captures.find(c=>c.name==="func_declaration");return{name:i.node.text,params:a.node.text,startLine:l.node.startPosition.row+1,endLine:l.node.endPosition.row+1,startIndex:l.node.startIndex,endIndex:l.node.endIndex,node:i.node}});return et(t)&&o.push(...Pc(e,t)),o}function Pc(e,t){return ee(t,"defaultExports.scm").matches(e.rootNode).map(n=>{let r=n.captures.find(s=>s.name==="func_declaration").node;return{name:"default",params:n.captures.find(s=>s.name==="func_params").node.text,startLine:r.startPosition.row+1,endLine:r.endPosition.row+1,startIndex:r.startIndex,endIndex:r.endIndex,node:r}})}function Or(e,t){return ee(t,"arrowFunctions.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(l=>l.name==="func_name"),i=o.captures.find(l=>l.name==="func_params"),a=o.captures.find(l=>l.name==="func_declaration");return{name:s.node.text,params:i.node.text,startLine:a.node.startPosition.row+1,endLine:a.node.endPosition.row+1,startIndex:a.node.startIndex,endIndex:a.node.endIndex,node:s.node}})}function Mr(e,t){let r=ee(t,"classMethods.scm").matches(e.rootNode),o=et(t);return r.map(s=>{let i=s.captures.find(p=>p.name==="class_name"),a=s.captures.find(p=>p.name==="method_name"),l=s.captures.find(p=>p.name==="method_params"),c=s.captures.find(p=>p.name==="method_declaration"),d=c.node;if(o)for(let p=d.previousNamedSibling;p&&p.type==="decorator";p=p.previousNamedSibling)d=p;return{className:i?i.node.text:"default",methodName:a.node.text,params:l.node.text,startLine:d.startPosition.row+1,endLine:c.node.endPosition.row+1,startIndex:d.startIndex,endIndex:c.node.endIndex,node:a.node}})}function Hr(e,t){let r=ee(t,"imports.scm").matches(e.rootNode),o=et(t);return r.filter(s=>!(o&&Lc(s.captures[0].node))).map(s=>{let i=s.captures[0].node;return{source:i.text,startLine:i.startPosition.row+1}})}function Lc(e){let t=e;for(;t&&t.type!=="import_statement";)t=t.parent;if(!t)return!1;if(t.children.some(s=>s.type==="type"))return!0;let n=t.namedChildren.find(s=>s.type==="import_clause");if(!n)return!1;let r=n.namedChildren;if(r.length!==1||r[0].type!=="named_imports")return!1;let o=r[0].namedChildren.filter(s=>s.type==="import_specifier");return o.length>0&&o.every(s=>s.children.some(i=>i.type==="type"))}function Ht(e){let t=e;for(;t&&t.type!=="call_expression"&&t.type!=="new_expression";)t=t.parent;if(!t)return null;let n=t.childForFieldName("arguments");if(!n)return null;let r=n.namedChildren?.[0];return!r||r.type==="arrow_function"||r.type==="function_expression"?null:r.text}var Rc=/^(addEventListener|removeEventListener|on|once|postMessage|onmessage|subscribe)$/i;function _t(e){let t=e;for(;t.parent;){let n=t.parent;if(n.type==="arrow_function"||n.type==="function_expression"){let r=n.parent;if(r&&(r.type==="variable_declarator"||r.type==="public_field_definition"))break;if(r&&r.type==="return_statement")return!0;if(r&&r.type==="arguments"&&r.parent?.type==="call_expression"){let o=r.parent.childForFieldName("function"),s=o?.type==="member_expression"?o.childForFieldName("property")?.text:o?.text;if(s&&Rc.test(s))return!0}}else if(n.type==="function_declaration"||n.type==="method_definition")break;t=n}return!1}function Dr(e,t){return ee(t,"callExpressions.scm").matches(e.rootNode).map(o=>{let s=o.captures[0].node;return{calleeName:s.text,startLine:s.startPosition.row+1,startColumn:s.startPosition.column,branchPath:$t(s),firstArgText:Ht(s),deferred:_t(s),callKind:tt(un(s)).kind}})}function Ur(e,t){return et(t)?Tc(e):ee(t,"methodCalls.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(a=>a.name==="object_name"),i=o.captures.find(a=>a.name==="method_name");return{objectName:s.node.text,methodName:i.node.text,startLine:i.node.startPosition.row+1,startColumn:i.node.startPosition.column,firstArgText:Ht(i.node),branchPath:$t(i.node),deferred:_t(i.node),callKind:tt(un(i.node)).kind}})}function Tc(e){let t=[];for(let n of e.rootNode.descendantsOfType("call_expression")){let r=n.childForFieldName("function");if(!r||r.type!=="member_expression")continue;let o=ce(r.childForFieldName("object")),s=r.childForFieldName("property");!o||o.type!=="identifier"||!s||s.type!=="property_identifier"||t.push({objectName:o.text,methodName:s.text,startLine:s.startPosition.row+1,startColumn:s.startPosition.column,firstArgText:Ht(s),branchPath:$t(s),deferred:_t(s),callKind:tt(un(s)).kind})}return t}function Ac(e){if(!e)return"return";if(e.type==="object"){let t=e.namedChildren.filter(r=>r.type==="pair"),n=t.find(r=>r.childForFieldName("key")?.text?.replace(/^['"]|['"]$/g,"")==="type")??t.find(r=>r.childForFieldName("key")?.text?.replace(/^['"]|['"]$/g,"")==="entity");if(n){let r=n.childForFieldName("key"),o=n.childForFieldName("value");return`return { ${r.text}: ${o.text} }`}}return"return "+e.text.split(/\r?\n/)[0].trim()}function Br(e,t){return ee(t,"returns.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(l=>l.name==="return_statement"),i=o.captures.find(l=>l.name==="return_value"),a=s.node;return{label:Ac(i?.node),startLine:a.startPosition.row+1,startColumn:a.startPosition.column,branchPath:$t(a),deferred:_t(a)}})}var Oc=new Set(["function_declaration","arrow_function","function_expression","method_definition"]);function pn(e,t){return!(!t||e.row<t.startPosition.row||e.row>t.endPosition.row||e.row===t.startPosition.row&&e.column<t.startPosition.column||e.row===t.endPosition.row&&e.column>t.endPosition.column)}function $t(e){let t=[],n=e,r=e.startPosition;for(;n.parent;){let o=n.parent;if(Oc.has(o.type))break;if(o.type==="if_statement"){let s=o.childForFieldName("condition"),i=o.childForFieldName("consequence"),a=o.childForFieldName("alternative");pn(r,i)?t.push({type:"if",conditionText:s?s.text:"",conditionLine:(s??o).startPosition.row+1,outcome:"true"}):pn(r,a)&&t.push({type:"if",conditionText:s?s.text:"",conditionLine:(s??o).startPosition.row+1,outcome:"false"})}else if(o.type==="switch_case"||o.type==="switch_default"){let s=o.parent,i=s&&s.type==="switch_body"?s.parent:null;if(i){let a=i.childForFieldName("value"),l=o.childForFieldName("value");t.push({type:"switch",conditionText:a?a.text:"",conditionLine:(a??i).startPosition.row+1,outcome:o.type==="switch_default"?"default":l?l.text:"case"})}}else if(o.type==="try_statement"){let s=o.childForFieldName("handler"),i=o.childForFieldName("finalizer"),a="try";pn(r,s)?a="catch":pn(r,i)&&(a="finally"),t.push({type:"try",conditionText:"try / catch",conditionLine:o.startPosition.row+1,outcome:a})}n=o}return t.reverse()}function zr(e,t){return ee(t,"exports.scm").matches(e.rootNode).map(r=>r.captures[0].node.text)}var Tr=new WeakMap;function Mc(e,t){let n=Tr.get(e);return n||(n=ee(t,"returns.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(a=>a.name==="return_statement"),i=o.captures.find(a=>a.name==="return_value");return{stmtNode:s.node,valueNode:i?.node}}),Tr.set(e,n)),n}function Wr(e,t,n){return Mc(e,t).filter(r=>r.stmtNode.startPosition.row+1>=n.startLine&&r.stmtNode.endPosition.row+1<=n.endLine).map(r=>({shape:Hc(r.valueNode),condition:Dc(r.stmtNode,n),line:r.stmtNode.startPosition.row+1}))}function Hc(e){if(!e)return"nothing";switch(e.type){case"true":case"false":return"boolean";case"number":return"number";case"string":return"string";case"null":return"null";case"identifier":return`variable (${e.text})`;case"object":return"object";case"array":return"array";case"call_expression":return`result of ${e.text.split("(")[0]}()`;case"binary_expression":return"boolean (comparison)";case"ternary_expression":return"conditional value";default:return"expression"}}function Dc(e,t){let n=e.parent;for(;n;){if(n.type==="if_statement"){let r=n.childForFieldName("condition");if(r)return r.text}n=n.parent}return null}function qr(e,t){return Ot(t)==="typescript"?[]:ee(t,"jsxElements.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(i=>i.name==="jsx_tag");return{calleeName:s.node.text,startLine:s.node.startPosition.row+1}}).filter(o=>/^[A-Z]/.test(o.calleeName))}function Gr(e,t){return ee(t,"fetchApiCalls.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(c=>c.name==="url"),i=o.captures.find(c=>c.name==="http_method"),a=s.node.text,l=/^https?:\/\//.test(a)?"external":"internal";return{url:a,method:i?.node.text??"get",startLine:s.node.startPosition.row+1,scope:l}})}function Jr(e,t){return ee(t,"socketEmit.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(i=>i.name==="event_name");return{eventName:s.node.text,startLine:s.node.startPosition.row+1}})}function Kr(e,t){return ee(t,"rawSocketSend.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(i=>i.name==="event_name");return{eventName:s.node.text,startLine:s.node.startPosition.row+1}})}function Vr(e,t){return ee(t,"rawSocketTypeCheck.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(i=>i.name==="event_name");return{eventName:s.node.text,startLine:s.node.startPosition.row+1}})}function Yr(e,t){return ee(t,"socketOn.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(l=>l.name==="event_name"),i=o.captures.find(l=>l.name==="handler_ref"),a=o.captures.find(l=>l.name==="handler_inline");return{eventName:s.node.text,startLine:s.node.startPosition.row+1,handlerName:i?i.node.text:null,isInlineHandler:!!a,handlerStartLine:a?a.node.startPosition.row+1:null,handlerEndLine:a?a.node.endPosition.row+1:null,handlerStartIndex:a?a.node.startIndex:null,handlerEndIndex:a?a.node.endIndex:null}})}function Xr(e){let t=e.rootNode.descendantsOfType(["call_expression","new_expression","jsx_opening_element","jsx_self_closing_element",...fn()?["decorator"]:[]]),n=[];for(let r of t){let o,s,i,a=null,l=null,c=!1,d=null,p=null;if(r.type==="new_expression"){if(i=r.childForFieldName("constructor"),!i)continue;o="new",s=i,a=i.type==="identifier"?i.text:null;let u=r.childForFieldName("arguments")?.namedChildren?.[0];d=u&&u.type!=="arrow_function"&&u.type!=="function_expression"?u.text:null}else if(r.type==="decorator"){let f=r.namedChild(0);if(!f||f.type==="call_expression")continue;o="decorator",s=f.type==="member_expression"?f.childForFieldName("property")??f:f,i=f}else if(r.type==="call_expression"){let f=tt(r);if(f.oldShape)continue;if(o=f.kind,s=f.nameNode,i=r.childForFieldName("function")??r,o==="chainedCall"){let u=Lr(r);l=u.head,c=u.called;let m=r.childForFieldName("function"),h=m?.type==="member_expression"?ce(m.childForFieldName("object")):null;h?.type==="member_expression"&&ce(h.childForFieldName("object"))?.type==="this"&&h.childForFieldName("property")?.type==="property_identifier"&&m.childForFieldName("property")&&(p={thisProp:h.childForFieldName("property").text,thisMethod:m.childForFieldName("property").text})}d=Ht(s)}else{let f=Pr(r);if(!f||f.oldShape)continue;o=f.kind,s=f.nameNode,i=f.nameNode}n.push({callKind:o,calleeName:Rr(i),startLine:s.startPosition.row+1,startColumn:s.startPosition.column,branchPath:$t(s),firstArgText:d,deferred:_t(s),chainHead:l,chainHeadCalled:c,ctorName:a,...p??{}})}return n.sort((r,o)=>r.startLine-o.startLine||r.startColumn-o.startColumn)}var go=new Set(["get","post","put","patch","delete","head","options"]),yo=new Set(["axios","ky","got","superagent","$http"]),Uc=new Set(["function_declaration","function_expression","function","arrow_function","method_definition","generator_function_declaration","generator_function"]),Bc=new Set(["WebSocket","ReconnectingWebSocket","SockJS","W3CWebSocket"]),xo=/^(ws|socket|sock|websocket|webSocket|wsClient|socketRef|wsRef|[A-Za-z]+Socket|[A-Za-z]+Ws|[A-Za-z]+WebSocket)$/,Z=e=>{for(;e&&(e.type==="parenthesized_expression"||e.type==="as_expression"||e.type==="non_null_expression"||e.type==="await_expression"||e.type==="satisfies_expression"||e.type==="type_assertion")&&(e=e.namedChildren.find(t=>t.type!=="type_annotation"&&t.type!=="predefined_type"&&!/_type$/.test(t.type))??e.namedChildren[0],!!e););return e},Dt=e=>e.namedChildren.length?e.namedChildren.filter(t=>t.type==="string_fragment"||t.type==="escape_sequence").map(t=>t.text).join(""):e.text.slice(1,-1);function Ft(e){for(let t=e.parent;t;t=t.parent)if(Uc.has(t.type))return t;return null}function Zr(e){if(!e)return null;let t=e.childForFieldName("name")?.text??null;if(!t&&e.parent){let o=e.parent;o.type==="variable_declarator"?t=o.childForFieldName("name")?.text??null:o.type==="assignment_expression"?t=o.childForFieldName("left")?.text??null:o.type==="pair"&&(t=o.childForFieldName("key")?.text??null)}let n=[],r=e.childForFieldName("parameters");if(r)r.namedChildren.forEach((o,s)=>{let i=o.type==="identifier"?o:o.type==="assignment_pattern"?o.childForFieldName("left"):o.type==="required_parameter"||o.type==="optional_parameter"?o.childForFieldName("pattern")??o.namedChildren[0]:null;n[s]=i&&i.type==="identifier"?i.text:null});else{let o=e.childForFieldName("parameter");o&&o.type==="identifier"&&(n[0]=o.text)}return{name:t,params:n}}function Qr(e){let t=e.rootNode,n={httpCalls:[],pathCallsites:[],httpInstances:[],wsClients:[],wsServers:[],wsSends:[],wsServerSends:[],listens:[],wsReceivers:[]},r=new Map;for(let u of t.descendantsOfType("variable_declarator")){let m=u.childForFieldName("name"),h=u.childForFieldName("value");if(!m||m.type!=="identifier"||!h)continue;(r.get(m.text)??r.set(m.text,[]).get(m.text)).push({value:h,fn:Ft(u)})}let o=(u,m)=>{let h=r.get(u);if(!h)return null;for(let g=Ft(m);g;g=Ft(g)){let w=h.filter(S=>S.fn&&S.fn.id===g.id);if(w.length===1)return w[0].value}let v=h.filter(g=>!g.fn);return v.length===1?v[0].value:h.length===1?h[0].value:null},s=(u,m)=>{for(let h=Ft(m);h;h=Ft(h)){let g=Zr(h).params.indexOf(u);if(g>=0)return g}return-1};function i(u,m=0){if(u=Z(u),!u)return[{t:"ref",name:""}];switch(u.type){case"string":return[{t:"lit",v:Dt(u)}];case"template_string":{let h=[];for(let v of u.namedChildren)v.type==="string_fragment"||v.type==="escape_sequence"?h.push({t:"lit",v:v.text}):v.type==="template_substitution"&&h.push(...i(v.namedChildren[0],m+1));return h.length?h:[{t:"lit",v:""}]}case"number":return[{t:"lit",v:u.text}];case"binary_expression":{let h=u.childForFieldName("operator")?.text;if(h==="||"||h==="??"){let v=i(u.childForFieldName("left"),m+1);if(v.length===1&&v[0].t==="env")return[{...v[0],fallback:i(u.childForFieldName("right"),m+1)}]}return h!=="+"?[{t:"ref",name:u.text.slice(0,60)}]:[...i(u.childForFieldName("left"),m+1),...i(u.childForFieldName("right"),m+1)]}case"shorthand_property_identifier":case"identifier":{let h=u.text,v=s(h,u);if(v>=0)return[{t:"param",name:h,index:v}];if(m<4){let g=o(h,u);if(g&&g.id!==u.id)return i(g,m+1)}return[{t:"ref",name:h}]}case"member_expression":{let h=u.text,v=/^(?:process\.env|import\.meta\.env)\.([A-Za-z0-9_$]+)$/.exec(h)??/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(h);return v?[{t:"env",name:v[1]}]:[{t:"ref",name:h.slice(0,60)}]}case"subscript_expression":{let h=/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(u.text);return h?[{t:"env",name:h[1]}]:[{t:"ref",name:u.text.slice(0,60)}]}case"call_expression":{let h=u.childForFieldName("function")?.text,v=u.childForFieldName("arguments")?.namedChildren[0];if(v&&(h==="encodeURIComponent"||h==="String"||h==="encodeURI"))return i(v,m+1);let g=Z(u.childForFieldName("function"));if(g&&g.type==="member_expression"&&/^(replace|replaceAll|trim|trimEnd|trimStart|toString|toLowerCase)$/.test(g.childForFieldName("property")?.text??"")){let w=g.childForFieldName("object");if(w){let S=i(w,m+1);if(S.length&&S.every(N=>N.t!=="ref"))return S}}return[{t:"ref",name:u.text.slice(0,60)}]}default:return[{t:"ref",name:u.text.slice(0,60)}]}}let a=(u,m)=>{if(u=Z(u),!(!u||u.type!=="object")){for(let h of u.namedChildren)if(h.type==="pair"){let v=h.childForFieldName("key");if((v?v.type==="string"?Dt(v):v.text:null)===m)return h.childForFieldName("value")}else if(h.type==="shorthand_property_identifier"&&h.text===m)return h}},l=u=>u.childForFieldName("arguments")?.namedChildren.filter(m=>m.type!=="comment")??[],c=u=>{if(!u)return null;let m=i(u);return m.length===1&&m[0].t==="lit"?m[0].v.toUpperCase():m.length===1&&m[0].t==="param"?{param:m[0].index}:"?"},d=(u,m,h,v)=>({client:u,method:m,parts:h,line:v.startPosition.row+1,fn:Zr(Ft(v))});for(let u of t.descendantsOfType("variable_declarator")){let m=u.childForFieldName("name"),h=Z(u.childForFieldName("value"));if(!m||m.type!=="identifier"||!h||h.type!=="call_expression")continue;let v=Z(h.childForFieldName("function"));if(!v||v.type!=="member_expression")continue;let g=v.childForFieldName("object")?.text,w=v.childForFieldName("property")?.text;if(!(yo.has(g)&&(w==="create"||w==="extend")))continue;let S=l(h)[0],N=a(S,"baseURL")??a(S,"baseUrl")??a(S,"prefixUrl")??a(S,"prefix_url");n.httpInstances.push({name:m.text,parts:N?i(N):[],line:u.startPosition.row+1})}let p=new Set(n.httpInstances.map(u=>u.name));for(let u of t.descendantsOfType("call_expression")){let m=Z(u.childForFieldName("function"));if(!m)continue;let h=l(u),v=!1;if(m.type==="identifier"){let g=m.text;if(g==="fetch"&&h[0]){let w=Z(h[0]);if(w&&w.type==="new_expression")continue;let S=a(h[1],"method");n.httpCalls.push(d("fetch",S?c(S):h[1]&&Z(h[1])?.type!=="object"?"?":"GET",i(h[0]),u)),v=!0}else if((yo.has(g)||p.has(g))&&h[0]){let w=Z(h[0]);if(w&&w.type==="object"){let S=a(w,"url");if(S){let N=a(w,"baseURL");n.httpCalls.push(d(p.has(g)?"inst:"+g:g,c(a(w,"method"))??"GET",[...N?i(N):[],...i(S)],u)),v=!0}}else n.httpCalls.push(d(p.has(g)?"inst:"+g:g,h[1]&&a(h[1],"method")?c(a(h[1],"method")):"GET",i(h[0]),u)),v=!0}else g==="io"&&h[0]&&(n.wsClients.push({client:"io",parts:i(h[0]),line:u.startPosition.row+1}),v=!0)}else if(m.type==="member_expression"){let w=m.childForFieldName("object")?.text??"",S=m.childForFieldName("property")?.text??"",N=yo.has(w)||p.has(w);if(N&&go.has(S)&&h[0])n.httpCalls.push(d(p.has(w)?"inst:"+w:w,S.toUpperCase(),i(h[0]),u)),v=!0;else if(!N&&go.has(S)&&/^[A-Za-z_$][\w$]*$/.test(w)&&h[0]&&(Z(h[0])?.type==="string"||Z(h[0])?.type==="template_string")){let y=i(h[0]);y[0]?.t==="lit"&&(y[0].v.startsWith("/")||/^https?:\/\//.test(y[0].v))&&(n.httpCalls.push(d("obj:"+w,S.toUpperCase(),y,u)),v=!0)}else if(N&&S==="request"&&h[0]){let y=a(h[0],"url");if(y){let x=a(h[0],"baseURL");n.httpCalls.push(d(p.has(w)?"inst:"+w:w,c(a(h[0],"method"))??"GET",[...x?i(x):[],...i(y)],u)),v=!0}}else if(S==="open"&&h.length>=2&&Z(h[0])?.type==="string"&&/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/i.test(Dt(Z(h[0]))))n.httpCalls.push(d("xhr",Dt(Z(h[0])).toUpperCase(),i(h[1]),u)),v=!0;else if(w==="io"&&S==="connect"&&h[0])n.wsClients.push({client:"io",parts:i(h[0]),line:u.startPosition.row+1}),v=!0;else if(S==="listen"&&h[0]){let y=Z(h[0]),x=y&&y.type==="object"?a(y,"port"):y;x&&n.listens.push({parts:i(x),line:u.startPosition.row+1}),v=!0}else if(S==="send"&&/^(client|conn|connection|peer)$/.test(w.replace(/^this./,"").split(".").pop())&&h[0]){let y=Z(h[0]),x=!1;if(y&&y.type==="call_expression"&&y.childForFieldName("function")?.text==="JSON.stringify"){let b=l(y)[0];x=!!(b&&(a(b,"type")||a(b,"event"))&&Z(a(b,"type")??a(b,"event"))?.type==="string")}x||n.wsServerSends.push({recv:w,line:u.startPosition.row+1}),v=!0}else if(S==="send"&&xo.test(w.replace(/^this\./,"").replace(/\.current$/,"").split(".").pop())){let y=h[0]?Z(h[0]):null,x=!1;if(y&&y.type==="call_expression"&&y.childForFieldName("function")?.text==="JSON.stringify"){let b=l(y)[0];x=!!(b&&(a(b,"type")||a(b,"event"))&&Z(a(b,"type")??a(b,"event"))?.type==="string")}x||n.wsSends.push({recv:w,line:u.startPosition.row+1}),v=!0}}if(!v){let g=null;if(m.type==="identifier"?g=m.text:m.type==="member_expression"&&(g=m.childForFieldName("property")?.text??null),!g||go.has(g)||h.length===0||h.length>6)continue;let w=[],S=!1;h.slice(0,5).forEach((N,y)=>{let x=Z(N);if(!x||x.type!=="string"&&x.type!=="template_string")return;let b=i(x);w.push({i:y,parts:b});let k=b[0];k&&k.t==="lit"&&(k.v.startsWith("/")||/^https?:\/\//.test(k.v))&&k.v.length>1&&(S=!0)}),S&&n.pathCallsites.push({callee:g,args:w,line:u.startPosition.row+1})}}let f=u=>u.replace(/^this./,"").replace(/.current$/,"").split(".").pop();for(let u of t.descendantsOfType("assignment_expression")){let m=u.childForFieldName("left");if(!m||m.type!=="member_expression"||m.childForFieldName("property")?.text!=="onmessage"||!xo.test(f(m.childForFieldName("object")?.text??"")))continue;let h=Z(u.childForFieldName("right"));n.wsReceivers.push({line:u.startPosition.row+1,handlerName:h&&h.type==="identifier"?h.text:null})}for(let u of t.descendantsOfType("call_expression")){let m=Z(u.childForFieldName("function"));if(!m||m.type!=="member_expression"||m.childForFieldName("property")?.text!=="addEventListener")continue;let h=l(u),v=h[0]&&Z(h[0]);if(!v||v.type!=="string"||Dt(v)!=="message"||!xo.test(f(m.childForFieldName("object")?.text??"")))continue;let g=h[1]&&Z(h[1]);n.wsReceivers.push({line:u.startPosition.row+1,handlerName:g&&g.type==="identifier"?g.text:null})}for(let u of t.descendantsOfType("new_expression")){let m=Z(u.childForFieldName("constructor"));if(!m)continue;let h=m.text,v=l(u);if(Bc.has(h)&&v[0])n.wsClients.push({client:h,parts:i(v[0]),line:u.startPosition.row+1});else if(/^(WebSocketServer|WebSocket\.Server|WebSocket\.WebSocketServer|ws\.Server|ws\.WebSocketServer|Server)$/.test(h)){if(h==="Server"&&!/socket\.io|socketio/i.test(e.rootNode.text.slice(0,4e3)+""))continue;let g=a(v.find(w=>Z(w)?.type==="object"),"path");n.wsServers.push({path:g?i(g):null,line:u.startPosition.row+1})}}return n}var zc=new Set(["function_declaration","generator_function_declaration","function_expression","generator_function","arrow_function","method_definition"]),Wc=new Set(["arrow_function","function_expression","generator_function"]);function qe(e,t){if(e)switch(e.type){case"identifier":case"shorthand_property_identifier_pattern":t.push(e.text);return;case"assignment_pattern":qe(e.childForFieldName("left"),t);return;case"rest_pattern":case"object_pattern":case"array_pattern":case"pair_pattern":case"required_parameter":case"optional_parameter":for(let n of e.namedChildren)qe(e.type==="pair_pattern"?e.childForFieldName("value"):n,t);return;default:if(e.type==="pattern"||e.namedChildCount){let n=e.childForFieldName?.("pattern");n&&qe(n,t)}}}function qc(e,t){let n=e;if(n.type==="export_statement"&&(n=n.childForFieldName("declaration")),!n)return null;if(n.type==="function_declaration"||n.type==="generator_function_declaration")return n.childForFieldName("name")?.text===t?{kind:"fn",declLine:n.startPosition.row+1}:null;if(n.type==="lexical_declaration"||n.type==="variable_declaration"){for(let r of n.namedChildren){if(r.type!=="variable_declarator")continue;let o=r.childForFieldName("name");if(o?.type==="identifier"){if(o.text!==t)continue;let i=ce(r.childForFieldName("value"));return i&&Wc.has(i.type)?{kind:"fn",declLine:r.startPosition.row+1}:{kind:"other"}}let s=[];if(qe(o,s),s.includes(t))return{kind:"other"}}return null}return(n.type==="class_declaration"||n.type==="abstract_class_declaration"||n.type==="enum_declaration")&&n.childForFieldName("name")?.text===t?{kind:"other"}:null}function Gc(e){let t=e.namedChildren.find(o=>o.type==="string")?.text.slice(1,-1)??null,n=e.namedChildren.find(o=>o.type==="import_clause"),r=[];if(!n||t==null)return{src:t,out:r};for(let o of n.namedChildren)if(o.type==="identifier")r.push({kind:"default",local:o.text,imported:null});else if(o.type==="namespace_import"){let s=o.namedChildren.find(i=>i.type==="identifier");s&&r.push({kind:"ns",local:s.text,imported:null})}else if(o.type==="named_imports")for(let s of o.namedChildren){if(s.type!=="import_specifier")continue;let i=s.childForFieldName("name"),a=s.childForFieldName("alias");i&&r.push({kind:"named",local:(a??i).text,imported:i.text})}return{src:t,out:r}}function es(e){let t=[];for(let n of e.rootNode.namedChildren)if(n.type==="import_statement"){if(n.children.some(i=>i.type==="type"))continue;let r=n.namedChildren.find(i=>i.type==="import_require_clause");if(r){let i=r.namedChildren.find(l=>l.type==="identifier"),a=r.namedChildren.find(l=>l.type==="string");i&&a&&t.push({source:Ut(a),kind:"cjs",local:i.text,imported:null});continue}let{src:o,out:s}=Gc(n);for(let i of s)t.push({source:o,...i})}else if(n.type==="lexical_declaration"||n.type==="variable_declaration")for(let r of n.namedChildren){if(r.type!=="variable_declarator")continue;let o=ce(r.childForFieldName("value")),s=null;o?.type==="member_expression"&&(s=o.childForFieldName("property")?.text??null,o=ce(o.childForFieldName("object")));let i=mn(o);if(i==null)continue;let a=r.childForFieldName("name");if(a?.type==="identifier")t.push({source:i,kind:s?"named":"cjs",local:a.text,imported:s});else if(a?.type==="object_pattern"&&!s){for(let l of a.namedChildren)if(l.type==="shorthand_property_identifier_pattern")t.push({source:i,kind:"named",local:l.text,imported:l.text});else if(l.type==="pair_pattern"){let c=l.childForFieldName("key"),d=l.childForFieldName("value");c&&d?.type==="identifier"&&t.push({source:i,kind:"named",local:d.text,imported:c.text})}}}return t}var Ut=e=>e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("");function mn(e){if(e?.type!=="call_expression")return null;let t=e.childForFieldName("function"),n=e.childForFieldName("arguments");if(t?.type!=="identifier"||t.text!=="require"||!n||n.namedChildCount!==1)return null;let r=n.namedChildren[0];return r.type==="string"?Ut(r):null}function ts(e){let t=[];return(function n(r){if(r.type==="export_statement"){let o=r.childForFieldName("source");o&&!r.children.some(s=>s.type==="type")&&t.push({source:Ut(o),startLine:o.startPosition.row+1})}else if(r.type==="import_require_clause"){let o=r.namedChildren.find(s=>s.type==="string");o&&t.push({source:Ut(o),startLine:o.startPosition.row+1})}else if(r.type==="call_expression"){let o=mn(r);o!=null&&t.push({source:o,startLine:r.startPosition.row+1})}for(let o of r.namedChildren)n(o)})(e.rootNode),t}function ns(e){let t={default:null,named:{},reexports:[],stars:[],nsReexports:[]};for(let n of e.rootNode.namedChildren){if(n.type!=="export_statement")continue;let r=n.children.some(i=>i.type==="default"),o=n.childForFieldName("declaration"),s=n.childForFieldName("source")!=null;if(r){if(o){let i=o.childForFieldName("name");t.default=i&&(o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"||o.type==="abstract_class_declaration")?i.text:"<anon>"}else{let i=ce(n.childForFieldName("value"));t.default=i?.type==="identifier"?i.text:"<anon>"}continue}if(o){if(o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"||o.type==="abstract_class_declaration"){let i=o.childForFieldName("name")?.text;i&&(t.named[i]=i)}else if(o.type==="lexical_declaration"||o.type==="variable_declaration")for(let i of o.namedChildren){let a=i.type==="variable_declarator"?i.childForFieldName("name"):null;a?.type==="identifier"&&(t.named[a.text]=a.text)}continue}if(s){if(n.children.some(c=>c.type==="type"))continue;let i=Ut(n.childForFieldName("source")),a=n.namedChildren.find(c=>c.type==="export_clause"),l=n.namedChildren.find(c=>c.type==="namespace_export");if(a)for(let c of a.namedChildren){if(c.type!=="export_specifier")continue;let d=c.childForFieldName("name")?.text,p=c.childForFieldName("alias")?.text;d&&t.reexports.push({exported:p??d,imported:d,source:i})}else if(l){let c=l.namedChildren.find(d=>d.type==="identifier");c&&t.nsReexports.push({exported:c.text,source:i})}else t.stars.push(i);continue}for(let i of n.namedChildren)if(i.type==="export_clause")for(let a of i.namedChildren){if(a.type!=="export_specifier")continue;let l=a.childForFieldName("name")?.text,c=a.childForFieldName("alias")?.text;l&&(c==="default"?t.default=l:t.named[c??l]=l)}}for(let n of e.rootNode.namedChildren){let r=n.type==="expression_statement"?n.namedChildren[0]:null;if(r?.type!=="assignment_expression")continue;let o=r.childForFieldName("left"),s=ce(r.childForFieldName("right"));if(o?.type!=="member_expression")continue;let i=o.childForFieldName("object"),a=o.childForFieldName("property")?.text,l=c=>c?.type==="member_expression"&&c.childForFieldName("object")?.text==="module"&&c.childForFieldName("property")?.text==="exports";if(l(o))if(s?.type==="identifier")t.default=s.text;else if(s?.type==="object"){for(let c of s.namedChildren)if(c.type==="shorthand_property_identifier")t.named[c.text]=c.text;else if(c.type==="pair"){let d=c.childForFieldName("key"),p=ce(c.childForFieldName("value"));d&&p?.type==="identifier"&&(t.named[d.text.replace(/^['"]|['"]$/g,"")]=p.text)}t.default??="<object>"}else mn(s)!=null?t.stars.push(mn(s)):t.default="<anon>";else a&&(i?.type==="identifier"&&i.text==="exports"||l(i))&&s?.type==="identifier"&&(t.named[a]=s.text)}return t}function Jc(e,t,n){for(let r=e.parent;r;r=r.parent)if(zc.has(r.type)){let o=[],s=r.childForFieldName("parameters");if(s)for(let a of s.namedChildren)qe(a,o);let i=r.childForFieldName("parameter");if(i&&qe(i,o),r.type==="function_expression"||r.type==="generator_function"){let a=r.childForFieldName("name");a&&o.push(a.text)}if(o.includes(t))return{kind:"other"}}else if(r.type==="catch_clause"){let o=[];if(qe(r.childForFieldName("parameter"),o),o.includes(t))return{kind:"other"}}else if(r.type==="for_in_statement"||r.type==="for_statement"){let o=[],s=r.type==="for_statement"?r.childForFieldName("initializer"):r.childForFieldName("left");if(s)if(s.type==="lexical_declaration"||s.type==="variable_declaration")for(let i of s.namedChildren)qe(i.childForFieldName?.("name"),o);else qe(s,o);if(o.includes(t))return{kind:"other"}}else if(r.type==="statement_block"||r.type==="program"||r.type==="switch_body"){if(r.type==="program"&&n.has(t))return{kind:"import",imp:n.get(t)};for(let o of r.namedChildren){let s=qc(o,t);if(s)return s}if(r.type==="program"&&n.has(t))return{kind:"import",imp:n.get(t)}}return null}var Kc=e=>(e.childForFieldName("function")?.text??"").replace(/\s+/g," ").slice(0,40);function os(e,t){let n=new Map(t.map(s=>[s.local,s])),r=[],o=(s,i,a)=>{let l=ce(s);if(!l||l.type!=="identifier"&&l.type!=="shorthand_property_identifier")return;let c=l.text,d=Jc(l,c,n);if(!d||d.kind==="other")return;let p=tt(a).nameNode,f={name:c,line:l.startPosition.row+1,column:l.startPosition.column,via:i,callee:Kc(a),callLine:p.startPosition.row+1,callColumn:p.startPosition.column,b:d.kind};d.kind==="fn"?f.declLine=d.declLine:(f.src=d.imp.source,f.ik=d.imp.kind,f.imp=d.imp.imported),r.push(f)};return(function s(i){if(i.type==="call_expression"){let a=i.childForFieldName("arguments");for(let l of a?.namedChildren??[]){let c=ce(l);if(c)if(c.type==="array")for(let d of c.namedChildren)o(d,"array",i);else if(c.type==="object")for(let d of c.namedChildren)d.type==="pair"?o(d.childForFieldName("value"),"object",i):d.type==="shorthand_property_identifier"&&o(d,"object",i);else o(c,"arg",i)}}for(let a of i.namedChildren)s(a)})(e.rootNode),r}function rs(e){let t=[],n=o=>{let s=o?.namedChildren.find(i=>i.type!=="comment");return s?.type==="type_identifier"?s.text:null},r=o=>{let s=o.childForFieldName("name")?.text,i=o.childForFieldName("body");if(!(!s||!i)){for(let a of i.namedChildren)if(a.type==="public_field_definition"){let l=a.childForFieldName("name"),c=n(a.childForFieldName("type"));l?.type==="property_identifier"&&c&&t.push({className:s,prop:l.text,type:c})}else if(a.type==="method_definition"&&a.childForFieldName("name")?.text==="constructor")for(let l of a.childForFieldName("parameters")?.namedChildren??[]){if(l.type!=="required_parameter"&&l.type!=="optional_parameter"||!l.namedChildren.some(p=>p.type==="accessibility_modifier")&&!l.children.some(p=>p.type==="readonly"))continue;let c=l.childForFieldName("pattern"),d=n(l.childForFieldName("type"));c?.type==="identifier"&&d&&t.push({className:s,prop:c.text,type:d})}}};for(let o of e.rootNode.namedChildren){let s=o.type==="export_statement"?o.childForFieldName("declaration"):o;s&&(s.type==="class_declaration"||s.type==="abstract_class_declaration")&&r(s)}return t}var Vc={Get:"get",Post:"post",Put:"put",Patch:"patch",Delete:"delete",All:"all"};function ss(e){let t=e.namedChildren[0];if(!t)return null;if(t.type==="call_expression"){let n=t.childForFieldName("function"),r=n?.type==="identifier"?n.text:null;return r?{name:r,args:t.childForFieldName("arguments")}:null}return t.type==="identifier"?{name:t.text,args:null}:null}var ct=e=>e?e.type==="string"?e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join(""):e.type==="template_string"&&!e.namedChildren.some(t=>t.type==="template_substitution")?e.text.slice(1,-1):null:null;function is(e){let t=e?.namedChildren.find(n=>n.type!=="comment");if(!t)return"";if(t.type==="array")return ct(t.namedChildren.find(n=>n.type!=="comment"))??"";if(t.type==="object"){for(let n of t.namedChildren){if(n.type!=="pair")continue;let r=n.childForFieldName("key");if(r?.text==="path"||r?.text==="'path'"||r?.text==='"path"'){let o=n.childForFieldName("value");return(o?.type==="array"?ct(o.namedChildren[0]):ct(o))??""}}return""}return ct(t)??""}var hn=(...e)=>"/"+e.map(n=>String(n??"").replace(/^\/+|\/+$/g,"")).filter(Boolean).join("/");function as(e){let t=[],n=(r,o)=>{let s=r.childForFieldName("name")?.text,i=r.childForFieldName("body");if(!s||!i)return;let l=[...o,...r.namedChildren.filter(p=>p.type==="decorator")].map(ss).filter(Boolean).find(p=>p.name==="Controller");if(!l)return;let c=is(l.args),d=[];for(let p of i.namedChildren)if(p.type!=="comment"){if(p.type==="decorator"){d.push(p);continue}if(p.type==="method_definition"){let f=p.childForFieldName("name")?.text;for(let u of d.map(ss).filter(Boolean)){let m=Vc[u.name];!m||!f||t.push({method:m,path:hn(c,is(u.args)),startLine:p.startPosition.row+1,handlerName:null,isInlineHandler:!1,handlerStartLine:null,handlerEndLine:null,handlerStartIndex:null,handlerEndIndex:null,nest:{className:s,methodName:f}})}}d=[]}};for(let r of e.rootNode.namedChildren)if(r.type==="export_statement"){let o=r.childForFieldName("declaration");o&&(o.type==="class_declaration"||o.type==="abstract_class_declaration")&&n(o,r.namedChildren.filter(s=>s.type==="decorator"))}else(r.type==="class_declaration"||r.type==="abstract_class_declaration")&&n(r,[]);return t}function cs(e){let t=[];return(function n(r){if(r.type==="call_expression"){let o=r.childForFieldName("function");if(o?.type==="member_expression"&&o.childForFieldName("property")?.text==="setGlobalPrefix"){let s=(r.childForFieldName("arguments")?.namedChildren??[]).filter(c=>c.type!=="comment"),i=s[0]?ct(s[0]):null,a=[],l=s[1];if(l?.type==="object")for(let c of l.namedChildren){if(c.type!=="pair"||c.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")!=="exclude")continue;let d=c.childForFieldName("value");for(let p of d?.type==="array"?d.namedChildren:[])if(p.type==="object"){for(let f of p.namedChildren)if(f.type==="pair"&&f.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")==="path"){let u=ct(f.childForFieldName("value"));u!=null&&a.push(u)}}else{let f=ct(p);f!=null&&a.push(f)}}t.push({prefix:i||null,exclude:a})}}for(let o of r.namedChildren)n(o)})(e.rootNode),t}function ls(e){let t=[];for(let s of e.values())for(let i of s?.globalPrefix??[])t.push(i);if(!t.length||t.some(s=>!s.prefix||s.prefix!==t[0].prefix))return e;let n=t[0].prefix,r=new Set(t.flatMap(s=>s.exclude).map(s=>hn(s))),o=new Map;for(let[s,i]of e){if(!i?.routes?.some(a=>a.nest)){o.set(s,i);continue}o.set(s,{...i,routes:i.routes.map(a=>a.nest&&!r.has(hn(a.path))?{...a,path:hn(n,a.path)}:a)})}return o}import Yc from"node:crypto";var ds=e=>Yc.createHash("sha256").update(e).digest("hex");function Xc(e,t=null){let n=[],r=o=>{if(o.childCount===0){if(o.type==="comment")return;let s=t?t.slice(o.startIndex,o.endIndex):o.text,i=o.type==="jsx_text"?s.replace(/\s+/g," ").trim():s;if(i==="")return;n.push({s:o.startIndex,e:o.endIndex,t:i});return}for(let s=0;s<o.childCount;s++)r(o.child(s))};return r(e),n}function fs(e,t){let n=[];for(let s of[t.functions,t.arrowFunctions,t.classMethods])for(let i of s??[])i.startIndex!=null&&n.push({s:i.startIndex,e:i.endIndex,item:i,field:"bodyHash"});for(let s of[t.routes,t.listeners,t.socketListeners])for(let i of s??[])i.isInlineHandler&&i.handlerStartIndex!=null&&n.push({s:i.handlerStartIndex,e:i.handlerEndIndex,item:i,field:"handlerBodyHash"});let r=new Map(n.map(s=>[s,[]])),o=[];for(let s of Xc(e.rootNode,e.canopyOriginalSource??null)){let i=null,a=1/0;for(let l of n)s.s>=l.s&&s.e<=l.e&&l.e-l.s<a&&(i=l,a=l.e-l.s);(i?r.get(i):o).push(s.t)}for(let s of n)s.item[s.field]=ds(r.get(s).join(" "));t.moduleBodyHash=ds(o.join(" "))}function us(e,t){return ee(t,"matchFastifyRoutes.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(c=>c.name==="http_method"),i=o.captures.find(c=>c.name==="route_path"),a=o.captures.find(c=>c.name==="handler_ref"),l=o.captures.find(c=>c.name==="handler_inline");return{method:s.node.text,path:i.node.text,startLine:s.node.startPosition.row+1,handlerName:a?a.node.text:null,isInlineHandler:!!l,handlerStartLine:l?l.node.startPosition.row+1:null,handlerEndLine:l?l.node.endPosition.row+1:null,handlerStartIndex:l?l.node.startIndex:null,handlerEndIndex:l?l.node.endIndex:null}})}function ps(e,t){return ee(t,"matchExtensionListeners.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(m=>m.name==="event_type"),i=o.captures.find(m=>m.name==="event_name"),a=o.captures.find(m=>m.name==="method_name"||m.name==="listener_method"),l=o.captures.find(m=>m.name==="handler_ref"),c=o.captures.find(m=>m.name==="target"),d=o.captures.find(m=>m.name==="root_object"),p=o.captures.find(m=>m.name==="sub_object"),f=c?c.node.text:d?d.node.text+(p?"."+p.node.text:""):null,u=o.captures.find(m=>m.name==="handler_inline");return{eventName:s?.node.text??i?.node.text??"unknown",targetName:f,startLine:a.node.startPosition.row+1,handlerName:l?l.node.text:null,isInlineHandler:!!u,handlerStartLine:u?u.node.startPosition.row+1:null,handlerEndLine:u?u.node.endPosition.row+1:null,handlerStartIndex:u?u.node.startIndex:null,handlerEndIndex:u?u.node.endIndex:null}})}import nl from"node:fs";Le();import Re from"node:fs";import oe from"node:path";import Zc from"node:os";import hs from"node:crypto";import{fileURLToPath as Qc}from"node:url";var el=oe.dirname(Qc(globalThis.__canopyUrl("src/stage2_parse/parseCache.js"))),gs=oe.join(el,"..",".."),vo=process.env.CANOPY_CACHE_DIR||(bt()?oe.join(Zc.homedir(),".canopy-cache"):oe.join(gs,".canopy-cache")),ms=e=>hs.createHash("sha256").update(e).digest("hex");function gn(e,t){return Re.readdirSync(e,{withFileTypes:!0}).flatMap(n=>n.isDirectory()?gn(oe.join(e,n.name),t):t.some(r=>n.name.endsWith(r))?[oe.join(e,n.name)]:[]).sort()}var wo=null;function tl(){if(wo)return wo;let e=oe.join(gs,"src"),t=!Re.existsSync(e)&&globalThis.__canopyBundle,n=t?[t,...gn(oe.join(oe.dirname(t),"queries"),[".scm"])]:[...gn(oe.join(e,"stage2_parse"),[".js",".scm"]),...gn(oe.join(e,"stage5_entrypoints"),[".js"]).filter(o=>/match/i.test(oe.basename(o))),oe.join(e,"utils","loadQuery.js")],r=hs.createHash("sha256");for(let o of n)r.update(oe.relative(t?oe.dirname(t):e,o).split(oe.sep).join("/")).update("\0").update(Re.readFileSync(o).toString("utf8").replace(/\r\n/g,`
17
- `)).update("\0");for(let o of["web-tree-sitter","tree-sitter-javascript","tree-sitter-typescript"])try{r.update(o+"@"+JSON.parse(Re.readFileSync(oe.join(je(o),"package.json"),"utf8")).version)}catch{r.update(o+"@?")}return wo=r.digest("hex").slice(0,16)}function ys(){let e=tl(),t=oe.join(vo,e);Re.mkdirSync(t,{recursive:!0});for(let n of Re.readdirSync(vo,{withFileTypes:!0}))n.isDirectory()&&n.name!==e&&Re.rmSync(oe.join(vo,n.name),{recursive:!0,force:!0});return{version:e,keyFor:(n,r="javascript")=>ms(r==="javascript"?n:Buffer.concat([Buffer.from(r+"\0"),n])),get(n){try{return JSON.parse(Re.readFileSync(oe.join(t,n+".json"),"utf8"))}catch{return null}},set(n,r){let o=oe.join(t,`${n}.${process.pid}.tmp`);Re.writeFileSync(o,JSON.stringify(r)),Re.renameSync(o,oe.join(t,n+".json"))}}}function xs(e){return JSON.parse(JSON.stringify(e,(t,n)=>n&&typeof n=="object"&&n.startPosition&&n.endPosition&&"type"in n&&"tree"in n?void 0:n))}var vs=Number(process.env.CANOPY_PARSE_BUDGET_MS)||3e4,ko=class extends Error{constructor(t){super(`parse time budget exceeded (limit ${vs/1e3} s; stopped after ${(t/1e3).toFixed(1)} s)`),this.name="ParseBudgetError"}},ol=100;function So(e,t,n){return e.map(r=>({...r,returns:Wr(t,n,r)}))}function ws(e,t,n,{cache:r=!0,onProgress:o=console.log,grammars:s=null}={}){let i=new Map,a=0,l=0,c=0,d=r?ys():null,p=[],f=0;for(let u of e){f>0&&f%ol===0&&o(` parsing: ${f}/${e.length} files (${c} from cache)`),f++;try{let m=nl.readFileSync(u),h=po(u),v=d?.keyFor(m,h),g=d?d.get(v):null;if(g){i.set(u,g),c++;continue}l++;let w=performance.now(),S=()=>{let O=performance.now()-w;if(O>vs)throw new ko(O)},N=h==="javascript"?{parser:t,language:n}:s?.get(h);if(!N)throw new Error(`no ${h} grammar loaded`);let y=N.language;Er(h);let{tree:x}=$r(N.parser,u);S();let b=[],k=(O,W,G=[])=>{try{return W()}catch(te){if(te.name==="ParseBudgetError")throw te;return b.push({extractor:O,message:String(te.message).slice(0,160)}),G}},$=k("functionDeclarations",()=>So(Ar(x,y),x,y));S();let j=k("arrowFunctions",()=>So(Or(x,y),x,y));S();let D=k("classMethods",()=>So(Mr(x,y),x,y));S();let L=k("importBindings",()=>es(x)),K={functions:$,arrowFunctions:j,classMethods:D,imports:k("imports",()=>[...Hr(x,y),...ts(x)]),calls:(S(),k("calls",()=>Dr(x,y))),methodCalls:(S(),k("methodCalls",()=>Ur(x,y))),returnEntries:k("returnEntries",()=>Br(x,y)),jsxElements:k("jsxElements",()=>qr(x,y)),callSites:(S(),k("callSites",()=>Xr(x))),apiCalls:(S(),k("apiCalls",()=>Gr(x,y))),socketEmits:k("socketEmits",()=>Jr(x,y)),socketListeners:k("socketListeners",()=>Yr(x,y)),rawSocketSends:k("rawSocketSends",()=>Kr(x,y)),rawSocketTypeChecks:k("rawSocketTypeChecks",()=>Vr(x,y)),routes:k("routes",()=>[...us(x,y),...et(y)?as(x):[]]),listeners:k("listeners",()=>ps(x,y)),refArgs:k("refArgs",()=>os(x,L)),globalPrefix:k("globalPrefix",()=>cs(x)),importBindings:L,classProps:k("classProps",()=>et(y)?rs(x):[]),httpClients:k("httpClients",()=>Qr(x),null),exportBindings:k("exportBindings",()=>ns(x),null),hadErrors:mo(x),exportedNames:k("exports",()=>zr(x,y)),failed:!1,warnings:b};k("bodyHash",()=>fs(x,K),null);let z=xs(K);d&&d.set(v,z),i.set(u,z)}catch(m){if(m.name==="ParseBudgetError"){p.push({filePath:u,reason:m.message}),i.set(u,{functions:[],arrowFunctions:[],classMethods:[],imports:[],calls:[],methodCalls:[],returnEntries:[],jsxElements:[],callSites:[],apiCalls:[],socketEmits:[],socketListeners:[],rawSocketSends:[],rawSocketTypeChecks:[],routes:[],listeners:[],hadErrors:!1,failed:!1,skipped:m.message}),console.warn(` ! Skipped ${u}: ${m.message}`);continue}a++,i.set(u,{functions:[],arrowFunctions:[],classMethods:[],imports:[],calls:[],methodCalls:[],returnEntries:[],jsxElements:[],callSites:[],apiCalls:[],socketEmits:[],socketListeners:[],rawSocketSends:[],rawSocketTypeChecks:[],routes:[],listeners:[],hadErrors:!0,failed:!0,errorMessage:m.message}),console.warn(` ! Failed to parse ${u}: ${m.message}`)}}return console.log(`Parsed ${i.size} files (${a} failed)`),console.log(` parse cache: ${l} file(s) parsed, ${c} served from cache`),i.cacheStats={parsed:l,cacheHits:c},i.budgetSkips=p,i}function yn(e,t){return`${e}::${t}`}var Ss=[{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 xn(e){let t=e.toLowerCase().replace(/\\/g,"/");for(let{category:n,patterns:r}of Ss)for(let o of r)if(t.includes(o))return n;return"unknown"}import No from"node:fs";import ye from"node:path";import vn from"node:fs";import Ge from"node:path";var rl=["index.html","public/index.html","src/index.html"],sl=/^(build|esbuild|vite\.config|webpack\.config|rollup\.config|bundle)[\w.-]*\.(mjs|cjs|js|ts)$/i;function il(e){let t=e.replace(/<!--[\s\S]*?-->/g,""),n=[];for(let r of t.matchAll(/<script\b[^>]*?\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)')/gi))n.push(r[1]??r[2]);return n}function al(e){let t=[],n=[];try{n=vn.readdirSync(e).filter(r=>sl.test(r)).sort()}catch{return t}for(let r of n){let o;try{o=vn.readFileSync(Ge.join(e,r),"utf8")}catch{continue}let s=/\boutfile\s*:\s*["'`]([^"'`]+)["'`]/.exec(o)?.[1]??null,i=/\b(?:entryPoints|entry|input)\s*:\s*\[?\s*["'`]([^"'`]+)["'`]/.exec(o)?.[1]??null;i&&t.push({config:r,outfile:s,entry:i})}return t}function wn(e,t,n=new Set(t.map(r=>Ge.resolve(r)))){for(let r of rl){let o=Ge.join(e,r);if(!vn.existsSync(o))continue;let s;try{s=vn.readFileSync(o,"utf8")}catch{continue}let i=Ge.dirname(o),a=d=>{let p=d.split(/[?#]/)[0];return!p||/^([a-z]+:)?\/\//i.test(p)?null:Ge.resolve(p.startsWith("/")?Ge.join(e,p):Ge.join(i,p))},l=il(s).map(d=>({s:d,p:a(d)})).filter(d=>d.p);for(let{s:d,p}of l)if(n.has(p))return{indexHtml:o,script:d,entry:p,via:"script"};let c=al(e);for(let{s:d,p}of l)for(let f of c){if(!f.outfile||Ge.resolve(e,f.outfile)!==p)continue;let u=Ge.resolve(e,f.entry);if(n.has(u))return{indexHtml:o,script:d,entry:u,via:`${f.config} (outfile ${f.outfile})`}}}return null}var cl=new Set(["test","tests","__tests__","fixtures","__fixtures__","__mocks__","e2e","cypress"]);function It(e){let t=String(e).replace(/\\/g,"/").split("/").filter(Boolean);if(!t.length)return!1;for(let n of t.slice(0,-1))if(cl.has(n.toLowerCase()))return!0;return/\.(test|spec)\.[^./]+$/i.test(t[t.length-1])}function ll(e){let t=ye.join(e,"package.json");if(!No.existsSync(t))return null;try{return JSON.parse(No.readFileSync(t,"utf-8"))}catch{return null}}function dl(e){return[...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{})]}function fl(e){let t=!!e.workspaces,n=Object.keys(e.dependencies??{}).length>0,r=!!(e.scripts&&e.scripts.start);return t&&!n&&!r}var ul=["react","vue","svelte","next","vite","webpack","parcel"],pl=["express","fastify","koa","hapi","socket.io","ws"],ml=[{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 hl(e){let t=e.some(r=>ul.includes(r)),n=e.some(r=>pl.includes(r));return t&&!n?"client":n&&!t||n&&t?"server":"unknown"}function gl(e){let t=[];for(let{deps:n,label:r}of ml)n.some(o=>e.includes(o))&&!t.includes(r)&&t.push(r);return t}function ks(e){let t=new Set(["node_modules",".git","dist","build",".next","coverage"]);try{return No.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!t.has(n.name)&&!n.name.startsWith(".")).map(n=>ye.join(e,n.name))}catch{return[]}}function Ns(e,t=null){let n=[e];for(let o of ks(e)){n.push(o);for(let s of ks(o))n.push(s)}let r=[];for(let o of n){let s=ll(o);if(!s||fl(s))continue;let i=dl(s);r.push({name:s.name||ye.basename(o),rootPath:o,isRepoRoot:ye.resolve(o)===ye.resolve(e),kind:hl(i),datastores:gl(i)})}if(t){let o=new Set(t.map(i=>ye.resolve(i))),s=new Set(r.map(i=>ye.resolve(i.rootPath)));for(let i of n)ye.resolve(i)===ye.resolve(e)||s.has(ye.resolve(i))||It(ye.relative(e,i)+"/x")||wn(i,t,o)&&r.push({name:ye.basename(i),rootPath:i,isRepoRoot:!1,kind:"client",datastores:[],webRoot:!0})}return r}function lt(e,t){let n=null,r=-1;for(let o of t)o.isRepoRoot&&t.length>1&&!o.ownsLeftovers||(e===o.rootPath||e.startsWith(o.rootPath+ye.sep))&&o.rootPath.length>r&&(n=o.name,r=o.rootPath.length);return n}var yl=5,xl=.1;function bs(e,t,n){let r=ye.basename(ye.resolve(n)),o=l=>({name:l,rootPath:n,isRepoRoot:!0,ownsLeftovers:!0,kind:"unknown",datastores:[]});if(!t.length)return{services:e,added:null};if(!e.length)return{services:[o(r)],added:{name:r,reason:"no package.json found: the repo root is the one service",leftover:t.length}};let s=t.filter(l=>!lt(l,e)).length;if(s<yl||s<xl*t.length)return{services:e,added:null,leftover:s};let i=e.find(l=>l.isRepoRoot);if(i)return i.ownsLeftovers=!0,{services:e,added:{name:i.name,reason:`${s} of ${t.length} files sit outside every nested package: owned by the root package ${i.name}`,leftover:s}};let a=r;return e.some(l=>l.name.toLowerCase()===a.toLowerCase())&&(a=`${r} (root)`),{services:[...e,o(a)],added:{name:a,reason:`${s} of ${t.length} files sit outside every nested package: owned by a service named after the repo folder`,leftover:s}}}function _s(e,t=[]){let n=[];for(let[r,o]of e){let s=xn(r),i=lt(r,t);n.push({id:`${r}::__module_root__`,name:"module root",filePath:r,startLine:0,endLine:Number.MAX_SAFE_INTEGER,category:s,serviceName:i,type:"moduleRoot",bodyHash:o.moduleBodyHash??null});for(let a of o.functions)n.push({id:yn(r,a.name),name:a.name,filePath:r,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:s,serviceName:i,bodyHash:a.bodyHash??null,type:"function"});for(let a of o.arrowFunctions)n.push({id:yn(r,a.name),name:a.name,filePath:r,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:s,serviceName:i,bodyHash:a.bodyHash??null,type:"arrowFunction"});for(let a of o.classMethods)n.push({id:yn(r,`${a.className}.${a.methodName}`),name:a.methodName,className:a.className,filePath:r,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:s,serviceName:i,bodyHash:a.bodyHash??null,type:"classMethod"})}return n}function Te(e,t){let n=[];for(let s of t.routes??[])s.isInlineHandler&&n.push({item:s,line:s.startLine,key:`route:${String(s.method).toUpperCase()} ${s.path}`});for(let s of t.listeners??[])s.isInlineHandler&&n.push({item:s,line:s.startLine,key:`listener:${s.targetName??"unknown"}.${s.eventName}`});for(let s of t.socketListeners??[])s.isInlineHandler&&n.push({item:s,line:s.startLine,key:`socket:${s.eventName}`});n.sort((s,i)=>s.line-i.line);let r=new Map,o=new Map;for(let{item:s,key:i}of n){let a=(r.get(i)??0)+1;r.set(i,a),o.set(s,`${e}::${i}${a>1?`#${a}`:""}`)}return o}function $s(e,t=[]){let n=[];for(let[r,o]of e){let s=xn(r),i=lt(r,t),a=t.find(c=>c.name===i),l=Te(r,o);for(let c of o.routes??[]){if(!c.isInlineHandler)continue;let d=`${c.method.toUpperCase()} ${c.path}`;n.push({id:l.get(c),name:`${d} (inline handler)`,filePath:r,startLine:c.handlerStartLine??c.startLine,endLine:c.handlerEndLine??c.startLine,category:s,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:c.handlerBodyHash??null,trigger:{type:"route",label:d,resolvedVia:"inline"}})}for(let c of o.listeners??[])c.isInlineHandler&&n.push({id:l.get(c),name:`${c.eventName} (inline handler)`,filePath:r,startLine:c.handlerStartLine??c.startLine,endLine:c.handlerEndLine??c.startLine,category:s,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:c.handlerBodyHash??null,trigger:{type:"listener",label:c.eventName,resolvedVia:"inline"}});if(a?.kind==="server")for(let c of o.socketListeners??[])c.isInlineHandler&&n.push({id:l.get(c),name:`${c.eventName} (inline handler)`,filePath:r,startLine:c.handlerStartLine??c.startLine,endLine:c.handlerEndLine??c.startLine,category:s,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:c.handlerBodyHash??null,trigger:{type:"socketListener",label:c.eventName,resolvedVia:"inline"}})}return n}import vl from"node:fs";import wl from"node:crypto";var Fs=e=>wl.createHash("sha256").update(e).digest("hex");function Sn(e,t){return e.map(n=>[t(n),Fs(vl.readFileSync(n))]).sort((n,r)=>n[0]<r[0]?-1:n[0]>r[0]?1:0)}function kn(e){return Fs(e.map(([t,n])=>`${t}\0${n}`).join(`
18
- `))}import bo from"node:path";function Nn(e){let t=bo.resolve(e),n=t.split(bo.sep).join("/"),r=[[t.toLowerCase(),t.length,bo.sep],[n.toLowerCase(),n.length,"/"]],o=s=>{if(typeof s!="string")return s;let i=s.toLowerCase();if(i===r[0][0]||i===r[1][0])return".";for(let[a,l,c]of r)if(i.startsWith(a+c)){let d=s.slice(l+1),p=d.indexOf("::");return(p<0?d:d.slice(0,p)).split("\\").join("/")+(p<0?"":d.slice(p))}return s};return{rel:o,repoRoot:n,replacer:(s,i)=>typeof i=="string"?o(i):i,json:(s,i)=>JSON.stringify(s,(a,l)=>typeof l=="string"?o(l):l,i),clone:s=>JSON.parse(JSON.stringify(s,(i,a)=>typeof a=="string"?o(a):a))}}function Is(e){let t=e.map((r,o)=>({e:r,i:o})).sort((r,o)=>String(r.e.fromNodeId).localeCompare(String(o.e.fromNodeId))||(r.e.line??0)-(o.e.line??0)||(r.e.column??0)-(o.e.column??0)||r.i-o.i),n=new Map;for(let{e:r}of t){let o=r.calleeNameRaw??r.eventName??r.url??"",s=`${r.fromNodeId??"\u2205"} | ${r.callKind??r.type} | ${o}`,i=(n.get(s)??0)+1;n.set(s,i),r.id=`${s} | #${i}`}return e}function js(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,r]of t)r.length<2||(r.sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine),r.forEach((o,s)=>{s>0&&(o.id=`${n}#${s+1}`)}));return e}function fe(e,t){let n=null;for(let r of t)r.type!=="moduleRoot"&&e>=r.startLine&&e<=r.endLine&&(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r);return n||t.find(r=>r.type==="moduleRoot")}function Cs(e,t){let n=[];for(let[o,s]of e){let i=t.filter(a=>a.filePath===o);for(let a of s.calls){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"call",callKind:a.callKind??"call",resolved:!1})}for(let a of s.methodCalls){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.methodName,objectNameRaw:a.objectName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"methodCall",callKind:a.callKind??"methodCall",resolved:!1})}for(let a of s.returnEntries??[]){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.label,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],deferred:a.deferred??!1,type:"returnValue",resolved:!1})}for(let a of s.jsxElements){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,type:"call",callKind:"jsx",resolved:!1})}for(let a of s.callSites??[]){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"callSite",callKind:a.callKind,chainHead:a.chainHead??null,chainHeadCalled:a.chainHeadCalled??!1,ctorName:a.ctorName??null,...a.thisProp?{thisProp:a.thisProp,thisMethod:a.thisMethod}:{},resolved:!1})}for(let a of s.socketEmits){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,eventName:a.eventName,line:a.startLine,type:"socketEmit",resolved:!1})}for(let a of s.rawSocketSends??[]){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,eventName:a.eventName,line:a.startLine,type:"rawSocketSend",resolved:!1})}for(let a of s.apiCalls){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,url:a.url,httpMethod:a.method,scope:a.scope,line:a.startLine,type:"apiCall",resolved:!1})}}let r=n.filter(o=>o.type==="apiCall").length;return n}function le(e,t){let n=new Map;for(let r of t)r.filePath===e&&n.set(r.name,r.id);return n}function Bt(e,t,n,r,o=null){if(n.has(e.calleeNameRaw))return{...e,targetNodeId:n.get(e.calleeNameRaw),confidence:.95,matchType:"local",resolved:!0};let s=[...r],i=r.legacySize??s.length,a=([,c])=>{let d=o?o.scopeOf(c):le(c,t);return d.has(e.calleeNameRaw)?{...e,targetNodeId:d.get(e.calleeNameRaw),confidence:.85,matchType:"import",resolved:!0}:null};for(let c=0;c<i;c++){let d=a(s[c]);if(d)return d}let l=o?.bind?.resolveName(e.fromFileId,e.calleeNameRaw);if(l)return{...e,targetNodeId:l.id,confidence:.85,matchType:"import",resolved:!0};for(let c=i;c<s.length;c++){let d=a(s[c]);if(d)return d}return{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function Es(e,t,n=null){let r=n?n.method(e.objectNameRaw,e.calleeNameRaw):t.find(s=>s.type==="classMethod"&&s.className===e.objectNameRaw&&s.name===e.calleeNameRaw);if(r)return{...e,targetNodeId:r.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 Ps(e){return{...e,targetNodeId:null,confidence:0,matchType:"unresolvedExternal",resolved:!1}}function Ls(e,t,n,r,o=null){if(e.callKind==="new"&&e.ctorName){let s=Bt({...e,calleeNameRaw:e.ctorName},t,n,r,o);if(s.resolved)return{...s,calleeNameRaw:e.calleeNameRaw,matchType:s.matchType+"New"};let i=new Set([e.fromFileId,...r.values()]),a=o?o.ctorsOf(e.ctorName).find(l=>i.has(l.filePath)):t.find(l=>l.type==="classMethod"&&l.className===e.ctorName&&l.name==="constructor"&&i.has(l.filePath));return a?{...e,targetNodeId:a.id,confidence:a.filePath===e.fromFileId?.9:.8,matchType:(a.filePath===e.fromFileId?"local":"import")+"New",resolved:!0}:Ps(e)}if(e.callKind==="chainedCall"&&e.chainHead&&e.chainHeadCalled){let s=Bt({...e,calleeNameRaw:e.chainHead},t,n,r,o);if(s.resolved)return{...e,targetNodeId:s.targetNodeId,confidence:s.confidence*.8,matchType:"chainHead",resolved:!0}}return Ps(e)}import $o from"node:path";import Je from"node:fs";import B from"node:path";var Os=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Sl=["index.ts","index.tsx","index.mts","index.cts","index.js","index.jsx","index.mjs","index.cjs"],kl={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]};var Ms=null,Hs=e=>{Ms=e},Ds=()=>Ms,Rs=e=>B.resolve(e);function zt(e,t){e=B.resolve(e);let n=()=>{try{let i=B.join(e,"package.json");if(!Je.existsSync(i))return null;let a=JSON.parse(Je.readFileSync(i,"utf8")).main;if(typeof a!="string")return null;let l=B.resolve(e,a);return t.has(l)?l:Nl(l,t)}catch{return null}},r=B.extname(e);if(r&&t.has(e))return e;let o=kl[r];if(o)for(let i of o){let a=e.slice(0,-r.length)+i;if(t.has(a))return a}for(let i of Os)if(t.has(e+i))return e+i;let s=n();if(s)return s;for(let i of Sl){let a=B.join(e,i);if(t.has(a))return a}return null}function Nl(e,t){if(B.extname(e)&&t.has(e))return e;for(let r of Os)if(t.has(e+r))return e+r;return null}var _o=e=>{try{let n=Je.readFileSync(e,"utf8").replace(/^/,"").replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,(r,o)=>o??"");return JSON.parse(n.replace(/,(\s*[}\]])/g,"$1"))}catch{return null}};function Us(e,t=new Set){if(t.has(e))return{baseUrl:null,paths:null};t.add(e);let n=_o(e);if(!n)return{baseUrl:null,paths:null};let r=null,o=null,s=n.extends?Array.isArray(n.extends)?n.extends:[n.extends]:[];for(let a of s){if(typeof a!="string"||!a.startsWith("."))continue;let l=B.resolve(B.dirname(e),a);(!Je.existsSync(l)||Je.statSync(l).isDirectory())&&(l=Je.existsSync(l+".json")?l+".json":B.join(l,"tsconfig.json"));let c=Us(l,t);c.baseUrl&&(r=c.baseUrl),c.paths&&(o=c.paths)}let i=n.compilerOptions??{};if(typeof i.baseUrl=="string"&&(r=B.resolve(B.dirname(e),i.baseUrl)),i.paths&&typeof i.paths=="object"){let a=r??B.dirname(e);o=Object.entries(i.paths).map(([l,c])=>{let d=l.indexOf("*");return{prefix:d<0?l:l.slice(0,d),suffix:d<0?"":l.slice(d+1),wildcard:d>=0,targets:(Array.isArray(c)?c:[]).filter(p=>typeof p=="string").map(p=>B.resolve(a,p))}}).sort((l,c)=>c.prefix.length-l.prefix.length)}return{baseUrl:r,paths:o}}function bl(e,t){if(t=t.replace(/^\.\//,"").replace(/\/+$/,""),t.startsWith("!"))return[];let n=[],r=o=>{try{return Je.readdirSync(o,{withFileTypes:!0}).filter(s=>s.isDirectory()&&s.name!=="node_modules"&&!s.name.startsWith(".")).map(s=>B.join(o,s.name))}catch{return[]}};if(t.endsWith("/**")){let o=B.join(e,t.slice(0,-3)),s=i=>{for(let a of r(i))n.push(a),s(a)};s(o)}else t.endsWith("/*")?n.push(...r(B.join(e,t.slice(0,-2)))):t.includes("*")||n.push(B.join(e,t));return n}function _l(e){let t=[],r=_o(B.join(e,"package.json"))?.workspaces;Array.isArray(r)?t.push(...r):Array.isArray(r?.packages)&&t.push(...r.packages);try{let o=Je.readFileSync(B.join(e,"pnpm-workspace.yaml"),"utf8"),s=!1;for(let i of o.split(/\r?\n/)){if(/^packages\s*:/.test(i)){s=!0;continue}if(s){let a=/^\s*-\s*['"]?([^'"#\s]+)['"]?/.exec(i);a?t.push(a[1]):/^\S/.test(i)&&(s=!1)}}}catch{}return t}function Ts(e,t){if(e==null)return null;let n=o=>{if(typeof o=="string")return o;if(Array.isArray(o)){for(let s of o){let i=n(s);if(i)return i}return null}if(o&&typeof o=="object"){for(let s of["source","import","module","default","require","node"])if(s in o){let i=n(o[s]);if(i)return i}}return null};if(typeof e=="string"||Array.isArray(e))return t==="."?n(e):null;let r=Object.keys(e);if(!r.some(o=>o.startsWith(".")))return t==="."?n(e):null;if(e[t]!=null)return n(e[t]);for(let o of r){let s=o.indexOf("*");if(s>0&&t.startsWith(o.slice(0,s))&&t.endsWith(o.slice(s+1))){let i=n(e[o]);if(i)return i.replace("*",t.slice(s,t.length-(o.length-s-1)))}}return null}function Bs(e,t,n={}){let r=Rs(e),o=new Set(t),s=new Map,i=f=>{if(s.has(f))return s.get(f);let u=null,m=B.join(f,"tsconfig.json");return Je.existsSync(m)?u=Us(m):f!==r&&B.dirname(f)!==f&&f.startsWith(r)&&(u=i(B.dirname(f))),s.set(f,u),u},a=new Map;for(let f of _l(r))for(let u of bl(r,f)){let m=_o(B.join(u,"package.json"));m?.name&&!a.has(m.name)&&a.set(m.name,{dir:Rs(u),pkg:m})}let l=[...a.keys()].sort((f,u)=>u.length-f.length),c=(f,u,m)=>{let{dir:h,pkg:v}=a.get(f),g=[],w=S=>{if(!S)return;let N=B.resolve(h,S);g.push(N);let y=B.relative(h,N).split(B.sep);["dist","build","lib","out","esm","cjs"].includes(y[0])&&g.push(B.join(h,"src",...y.slice(1)))};if(u==="."){w(Ts(v.exports,"."));for(let S of["source","module","main"])typeof v[S]=="string"&&w(v[S]);g.push(B.join(h,"src","index"),B.join(h,"index"))}else w(Ts(v.exports,u)),g.push(B.join(h,u),B.join(h,"src",u));for(let S of g){let N=zt(S,m);if(N)return N}return null},d=f=>l.find(u=>f===u||f.startsWith(u+"/"))??null,p=(f,u)=>u?.paths?.some(m=>m.wildcard?f.startsWith(m.prefix)&&f.endsWith(m.suffix)&&f.length>=m.prefix.length+m.suffix.length:f===m.prefix)??!1;return{root:r,files:o,packages:a,isInternal(f,u){if(f.startsWith(".")||d(f))return!0;let m=i(B.dirname(u));return!!(p(f,m)||m?.baseUrl&&!f.startsWith("@")&&zt(B.join(m.baseUrl,f),o))},resolve(f,u,m){if(f.startsWith("."))return zt(B.resolve(B.dirname(u),f),m);let h=i(B.dirname(u));if(h?.paths&&n.paths!==!1)for(let g of h.paths){let w=null;if(g.wildcard?f.startsWith(g.prefix)&&f.endsWith(g.suffix)&&f.length>=g.prefix.length+g.suffix.length&&(w=f.slice(g.prefix.length,f.length-g.suffix.length)):f===g.prefix&&(w=""),w!=null){for(let S of g.targets){let N=zt(S.replace("*",w),m);if(N)return N}break}}let v=n.workspaces===!1?null:d(f);if(v){let g=c(v,f===v?".":"./"+f.slice(v.length+1),m);if(g)return g}if(h?.baseUrl&&n.paths!==!1){let g=zt(B.join(h.baseUrl,f),m);if(g)return g}return null}}}var As=new WeakMap;function zs(e){if(e instanceof Set)return e;let t=As.get(e);return t||As.set(e,t=new Set(e)),t}function Fo(e,t,n){if(!e.startsWith("."))return null;let r=$o.dirname(t),o=$o.resolve(r,e),s=[o,...ur().map(i=>`${o}${i}`),...pr().map(i=>$o.join(o,i))];for(let i of s)if(n.includes(i))return i;return null}function Ae(e,t,n){let r=Fo(e,t,n);if(r)return r;let o=Ds();return o?o.resolve(e,t,zs(n)):null}function jt(e,t,n){let r=new Map;for(let o of t){let s=Fo(o.source,e,n);s&&r.set(o.source,s)}r.legacySize=r.size;for(let o of t){if(r.has(o.source))continue;let s=Ae(o.source,e,n);s&&r.set(o.source,s)}return r}function Ws(e){let t=new Map,n=new Map,r=new Map;for(let o of e){if(o.type!=="classMethod")continue;let s=o.className+"\0"+o.name;n.has(s)||n.set(s,o),o.name==="constructor"&&(r.has(o.className)||r.set(o.className,[]),r.get(o.className).push(o))}return{scopeOf:o=>{let s=t.get(o);return s||(s=le(o,e),t.set(o,s)),s},method:(o,s)=>n.get(o+"\0"+s),ctorsOf:o=>r.get(o)??[]}}function Ct(e){return e?e.split("?")[0].split("/").map(t=>t.startsWith(":")||/^\d+$/.test(t)?"*":t).join("/"):""}var $l=new Set(["function","arrowFunction"]);function qs(e,t,n,r){let o=new Map;for(let c of t){let d=o.get(c.filePath);d||o.set(c.filePath,d=[]),d.push(c)}let s=new Set;for(let c of r)c.resolved&&c.fromNodeId&&c.targetNodeId&&s.add(c.fromNodeId+"\0"+c.targetNodeId);let i=(c,d)=>(o.get(c)??[]).find(p=>$l.has(p.type)&&d(p))??null,a=[];a.argBindings=[];let l=(c,d,p,f,u,m,h)=>{!d||!p||d.id===p.id||s.has(d.id+"\0"+p.id)||a.push({fromFileId:c,fromNodeId:d.id,calleeNameRaw:f,line:u,column:m,branchPath:[],firstArgText:null,deferred:!1,type:"reference",callKind:"reference",targetNodeId:p.id,confidence:h==="local"?.95:.85,matchType:h,resolved:!0})};for(let[c,d]of e){let p=o.get(c);if(p){for(let f of d.refArgs??[]){let u=null,m="local";if(f.b==="fn"?u=i(c,v=>v.name===f.name&&v.startLine===f.declLine):f.b==="import"&&(m="import",(f.ik==="default"||f.ik==="named"||f.ik==="cjs")&&(u=n.nodeForImport(c,f.src,f.ik,f.imp))),!u)continue;let h=fe(f.line,p);l(c,h,u,f.name,f.line,f.column,m),f.callLine!=null&&h&&h.id!==u.id&&a.argBindings.push({file:c,line:f.callLine,column:f.callColumn,targetNodeId:u.id,matchType:m,direct:f.via==="arg"})}for(let f of p){if(f.type!=="inlineHandler")continue;let u=null;for(let m of p)m===f||m.type==="moduleRoot"||m.startLine<=f.startLine&&m.endLine>=f.endLine&&!(m.startLine===f.startLine&&m.endLine===f.endLine)&&(!u||m.endLine-m.startLine<u.endLine-u.startLine)&&(u=m);u??=p.find(m=>m.type==="moduleRoot"),l(c,u,f,f.name,f.startLine,0,"local")}}}return a}function Gs(e,t,n,r){let o=new Map,s=new Map;for(let a of e){if(s.set(a.id,a),a.type!=="classMethod")continue;let l=a.filePath+"\0"+a.className+"\0"+a.name,c=o.get(l);c?c.push(a):o.set(l,[a])}let i=(a,l)=>{for(let c of o.keys())if(c.startsWith(a+"\0"+l+"\0"))return!0;return!1};return function(l){let c=s.get(l.fromNodeId);if(!c||c.type!=="classMethod")return null;let d=t.get(l.fromFileId),p=(d?.classProps??[]).find(v=>v.className===c.className&&v.prop===l.thisProp);if(!p)return null;let f=null,u=null,m=(d.importBindings??[]).find(v=>v.local===p.type);if(m){let v=m.kind==="default"||m.kind==="named"?r.resolveImport(l.fromFileId,m.source,m.kind,m.imported):null;v?.local&&v.local!=="default"&&(f=v.file,u=v.local)}else i(l.fromFileId,p.type)&&(f=l.fromFileId,u=p.type);if(!f)return null;let h=o.get(f+"\0"+u+"\0"+l.thisMethod);return!h||h.length!==1?null:{...l,targetNodeId:h[0].id,confidence:.9,matchType:"typedProperty",resolved:!0}}}var Fl=new Set(["function","arrowFunction"]);function bn(e,t,n){let r=new Map;for(let d of e){if(!Fl.has(d.type))continue;let p=d.filePath+"\0"+d.name;r.has(p)||r.set(p,d)}let o=new Map,s=(d,p)=>{let f=o.get(d);if(!f){f=new Map;for(let u of t.get(d)?.importBindings??[])f.has(u.local)||f.set(u.local,u);o.set(d,f)}return f.get(p)??null},i=(d,p)=>n(d).get(p)??null;function a(d,p,f=new Set){let u=d+"\0"+p;if(f.has(u))return null;f.add(u);let m=t.get(d)?.exportBindings;if(!m)return null;if(p==="default"){if(m.default)return{file:d,local:m.default==="<anon>"?"default":m.default}}else if(m.named?.[p])return{file:d,local:m.named[p]};for(let h of m.reexports??[]){if(h.exported!==p)continue;let v=i(d,h.source);if(v)return a(v,h.imported,f)}for(let h of m.nsReexports??[]){if(h.exported!==p)continue;let v=i(d,h.source);if(v)return{moduleFile:v}}if(p!=="default")for(let h of m.stars??[]){let v=i(d,h),g=v?a(v,p,f):null;if(g)return g}return null}let l=d=>d?.local?r.get(d.file+"\0"+d.local)??null:null;function c(d,p,f,u){let m=i(d,p);return m?f==="default"?a(m,"default"):f==="named"?a(m,u):{moduleFile:m,cjs:f==="cjs"}:null}return{lookupExport:a,resolveImport:c,nodeForImport(d,p,f,u){let m=c(d,p,f,u);return m?.moduleFile&&m.cjs?l(a(m.moduleFile,"default")):l(m)},resolveName(d,p){let f=s(d,p);return f?this.nodeForImport(d,f.source,f.kind,f.imported):null},resolveMember(d,p,f){let u=s(d,p);if(!u)return null;let m=c(d,u.source,u.kind,u.imported);return m?.moduleFile?l(a(m.moduleFile,f)):null},classForImport(d,p){let f=s(d,p);if(!f)return null;let u=c(d,f.source,f.kind,f.imported);return u?.local?{file:u.file,className:u.local==="default"?null:u.local}:null},bindingFor:s}}function Js(e,t,n,r,o,s,i){let a=[],l=Ws(t),c=new Map,d=g=>c.get(g)??jt(g,n.get(g)?.imports??[],r);l.bind=bn(t,n,d);let p=Gs(t,n,d,l.bind),f=new Map;for(let g of e)f.has(g.fromFileId)||f.set(g.fromFileId,[]),f.get(g.fromFileId).push(g);for(let[g,w]of f){let S=n.get(g),N=le(g,t),y=jt(g,S.imports,r);c.set(g,y);for(let x of w)if(x.type==="call")a.push(Bt(x,t,N,y,l));else if(x.type==="methodCall")a.push(Es(x,t,l));else if(x.type==="callSite")a.push((x.thisProp?p(x):null)??Ls(x,t,N,y,l));else if(x.type==="returnValue")a.push({...x,targetNodeId:null,confidence:0,matchType:"returnValue",resolved:!1});else if(x.type==="apiCall")if(x.scope==="external")a.push({...x,targetNodeId:null,confidence:null,matchType:"externalService",resolved:!1});else{let b=Ct(x.url),k=o.get(b);k?a.push({...x,targetNodeId:k,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...x,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(x.type==="socketEmit"){let b=s.get(x.eventName);b?a.push({...x,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...x,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(x.type==="rawSocketSend"){let b=i?.get(x.eventName);b?a.push({...x,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...x,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}}let u=qs(n,t,l.bind,a);for(let g of u)a.push(g);let m=new Map;for(let g of a){if(g.resolved||g.line==null||g.type!=="call"&&g.type!=="methodCall"&&g.type!=="callSite")continue;let w=g.fromFileId+" "+g.line+" "+g.column;(m.get(w)??m.set(w,[]).get(w)).push(g)}let h=[...u.argBindings].sort((g,w)=>w.direct-g.direct),v=new Set;for(let g of h){let w=g.file+" "+g.line+" "+g.column;if(v.has(w))continue;let S=(m.get(w)??[]).find(N=>N.fromNodeId!==g.targetNodeId);S&&(v.add(w),Object.assign(S,{targetNodeId:g.targetNodeId,confidence:g.matchType==="local"?.95:.85,matchType:"argument",resolved:!0,viaArgument:!0}))}return a}function Ks(e){let t=new Map,n=new WeakMap,r=l=>{if(typeof l=="string")return l.length>=20?"s"+l:null;if(l&&typeof l=="object"){let c=n.get(l);if(c===void 0){let d=JSON.stringify(l);c=d.length>=40?"j"+d:"",n.set(l,c)}return c||null}return null};(function l(c){let d=r(c);if(d){let p=t.get(d)??0;if(t.set(d,p+1),p>0)return}if(Array.isArray(c))for(let p of c)l(p);else if(c&&typeof c=="object")for(let p of Object.values(c))l(p)})(e);let o=[],s=new Map,i=l=>{let c=r(l),d=c&&t.get(c)>1;if(d&&s.has(c))return s.get(c);let p;if(typeof l=="string"?p=JSON.stringify(l):Array.isArray(l)?p="["+l.map(i).join(",")+"]":l&&typeof l=="object"?p="{"+Object.entries(l).map(([u,m])=>JSON.stringify(u)+":"+i(m)).join(",")+"}":p=JSON.stringify(l),!d)return p;let f="$"+o.length.toString(36);return o.push(`const ${f}=${p};`),s.set(c,f),f},a=i(e);return`(() => {${o.join(`
10
+ `),!0}function Ge(e){let t=ae(e);try{return JSON.parse(Z.readFileSync(t.index,"utf8"))}catch{return{schema:1,nextVersion:1,versions:[]}}}function Xd(e,t){let n=ae(e);Z.mkdirSync(n.history,{recursive:!0});let s=n.index+"."+process.pid+".tmp";Z.writeFileSync(s,JSON.stringify(t,null,2)),Z.renameSync(s,n.index)}function Mt(e,t){let n=Z.readFileSync(ke.join(ae(e).history,t.file));return JSON.parse((t.gzip?sa.gunzipSync(n):n).toString("utf8"))}function ra(e,t,n,s,o=Vt,{refresh:r=!1}={}){let i=ae(e);Z.mkdirSync(i.history,{recursive:!0});let a=Ge(e),l=!0,c=n.fingerprint+(l?".json.gz":".json"),d=ke.join(i.history,c);(r||!Z.existsSync(d))&&Z.writeFileSync(d,l?sa.gzipSync(t):t);let m=(Ie(e,["status","--porcelain"])||"").split(`
11
+ `).some(w=>w.trim()&&!/\.canopy(\/|$)/.test(w)),f=r?a.versions.pop():null,u={version:f?f.version:a.nextVersion,fingerprint:n.fingerprint,createdAt:new Date().toISOString(),headSha:Ie(e,["rev-parse","HEAD"]),headMessage:Ie(e,["log","-1","--format=%s"]),dirty:m,counts:s,file:c,gzip:l,bytes:Z.statSync(d).size,engineVersion:Dn(),outputFormat:Hn};for(a.versions.push(u),f||a.nextVersion++;a.versions.length>o;)a.versions.shift();let p=Kd(),h=w=>{try{return Z.statSync(ke.join(i.history,w.file)).size}catch{return w.bytes??0}},v=a.versions.reduce((w,S)=>w+h(S),0);for(;v>p&&a.versions.length>Jd;)v-=h(a.versions.shift());let g=new Set(a.versions.map(w=>w.file));for(let w of Z.readdirSync(i.history))/\.json(\.gz)?$/.test(w)&&w!=="index.json"&&!g.has(w)&&Z.rmSync(ke.join(i.history,w),{force:!0});return Xd(e,a),u}function ia(e){let t=ae(e);Z.mkdirSync(t.root,{recursive:!0});for(let n=0;n<2;n++)try{let s=Z.openSync(t.lock,"wx");return Z.writeSync(s,JSON.stringify({pid:process.pid,startedAt:Date.now()})),Z.closeSync(s),!0}catch(s){if(s.code!=="EEXIST")throw s;let o=1/0;try{o=Date.now()-Z.statSync(t.lock).mtimeMs}catch{continue}if(o<Vd)return!1;Z.rmSync(t.lock,{force:!0})}return!1}var Gd,Jd,Kd,Vd,Vt,ae,aa,ca,la,yt=_t(()=>{Ko();Gd=200,Jd=2,Kd=()=>{let e=Number(process.env.CANOPY_SNAPSHOT_MAX_MB);return(Number.isFinite(e)&&e>0?e:Gd)*1024*1024},Vd=600*1e3,Vt=50,ae=e=>{let t=ke.join(ke.resolve(e),".canopy");return{root:t,history:ke.join(t,"history"),index:ke.join(t,"history","index.json"),lock:ke.join(t,"sync.lock"),pending:ke.join(t,"sync.pending"),log:ke.join(t,"sync.log")}};aa=e=>Z.rmSync(ae(e).lock,{force:!0}),ca=e=>{let t=ae(e);Z.mkdirSync(t.root,{recursive:!0}),Z.writeFileSync(t.pending,String(Date.now()))},la=e=>{let t=ae(e);return Z.existsSync(t.pending)?(Z.rmSync(t.pending,{force:!0}),!0):!1}});function da(e){let t=new Map;for(let n of e.nodes){let s=t.get(n.id);s?s.services.push(n.service):t.set(n.id,{id:n.id,services:[n.service],kind:n.kind,name:n.name,filePath:n.filePath,bodyHash:n.bodyHash})}for(let n of t.values())n.services.sort();return t}function Zd(e){return t=>{if(t==null)return t;if(e.has(t))return e.get(t);for(let[n,s]of e)if(t.startsWith(n+" | "))return s+t.slice(n.length);return t}}function Xo(e,t){let n=a=>a.reduce((l,c)=>l.set(c,(l.get(c)??0)+1),new Map),s=n(e),o=n(t),r=[],i=[];for(let[a,l]of o)for(let c=0;c<l-(s.get(a)??0);c++)r.push(a);for(let[a,l]of s)for(let c=0;c<l-(o.get(a)??0);c++)i.push(a);return{added:r.sort(),removed:i.sort()}}function Wn(e,t){let n=da(e),s=da(t),o=[...s.values()].filter(_=>!n.has(_.id)),r=[...n.values()].filter(_=>!s.has(_.id)),i=[];for(let[_,E]of s){let C=n.get(_);C&&C.bodyHash!==E.bodyHash&&i.push({...Vo(E),from:C.bodyHash,to:E.bodyHash})}let a=[],l=new Map,c=_=>[_.kind,_.name,_.bodyHash].join("\0"),d=new Map;for(let _ of Ne(o,E=>E.id)){let E=c(_);d.has(E)||d.set(E,[]),d.get(E).push(_)}let m=[],f=new Set;for(let _ of Ne(r,E=>E.id)){let C=(d.get(c(_))??[]).find(B=>!f.has(B.id)&&B.filePath!==_.filePath&&B.id.split("::").pop()===_.id.split("::").pop());C?(f.add(C.id),a.push({kind:_.kind,name:_.name,services:C.services,fromId:_.id,toId:C.id,fromPath:_.filePath,toPath:C.filePath}),l.set(_.id,C.id)):m.push(_)}o=Ne(o.filter(_=>!f.has(_.id)),_=>_.id),r=Ne(m,_=>_.id);let u=Zd(l),p=_=>_.service+"\0"+_.id,h=new Map(e.edges.map(_=>[p({service:_.service,id:u(_.id)}),{..._,id:u(_.id),from:u(_.from),resolvedTo:u(_.resolvedTo)}])),v=new Map(t.edges.map(_=>[p(_),_])),g=_=>({id:_.id,service:_.service,from:_.from,callKind:_.callKind,calleeNameRaw:_.calleeNameRaw,resolvedTo:_.resolvedTo}),w=[],S=[],k=[];for(let[_,E]of v){let C=h.get(_);C?C.resolvedTo!==E.resolvedTo&&k.push({id:E.id,service:E.service,from:E.from,calleeNameRaw:E.calleeNameRaw,fromTarget:C.resolvedTo,toTarget:E.resolvedTo}):w.push(g(E))}for(let[_,E]of h)v.has(_)||S.push(g(E));let y=_=>_.service+"\0"+_.id,x=_=>({..._,id:_.id.replace(_.entry??"\0",u(_.entry)),entry:u(_.entry),steps:_.steps.map(u)}),b=new Map(e.workflows.map(_=>{let E=x(_);return[E.id,E]})),N=new Map(t.workflows.map(_=>[_.id,_])),$={added:[],removed:[],changed:[]},F={added:[],removed:[],changed:[]},H=_=>({id:_.id,service:_.service,tier:_.tier,steps:_.steps.length});for(let[_,E]of N){let C=b.get(_);if(!C){(E.tier==="physical"?$:F).added.push(H(E));continue}let B=Xo(C.steps,E.steps),be=!B.added.length&&!B.removed.length&&C.steps.join(`
12
+ `)!==E.steps.join(`
13
+ `),I=C.tier!==E.tier?`${C.tier} -> ${E.tier}`:null;if(!B.added.length&&!B.removed.length&&!be&&!I)continue;let T={id:_,service:E.service,tier:E.tier,stepsAdded:B.added,stepsRemoved:B.removed,reordered:be,tierChange:I};(C.tier==="physical"||E.tier==="physical"?$:F).changed.push(T)}for(let[_,E]of b)N.has(_)||(E.tier==="physical"?$:F).removed.push(H(E));for(let _ of[$,F])for(let E of["added","removed","changed"])_[E]=Ne(_[E],C=>C.id);let P=_=>[_.fromService,_.fromNodeId,_.toService,_.toNodeId,_.via,_.key].join(" | "),K=new Map(e.crossServiceEdges.map(_=>[P({..._,fromNodeId:u(_.fromNodeId),toNodeId:u(_.toNodeId)}),{..._,fromNodeId:u(_.fromNodeId),toNodeId:u(_.toNodeId)}])),U=new Map(t.crossServiceEdges.map(_=>[P(_),_])),D=Ne([...U].filter(([_])=>!K.has(_)).map(([,_])=>_),P),R=Ne([...K].filter(([_])=>!U.has(_)).map(([,_])=>_),P),G=new Map,ee=new Map,ne=(_,E,C)=>{_.has(E)||_.set(E,new Set),_.get(E).add(C)};for(let _ of r)ne(G,_.id,"removed");for(let _ of o)ne(ee,_.id,"added");for(let _ of i)ne(G,_.id,"modified"),ne(ee,_.id,"modified");for(let _ of a)ne(G,_.fromId,"moved"),ne(ee,_.toId,"moved");let ye=[],Ee=new Set([...b.keys(),...N.keys()]);for(let _ of Ee){let E=b.get(_),C=N.get(_);if(!(E&&E.tier==="physical"||C&&C.tier==="physical"))continue;let B=new Map;for(let[I,T]of[[E,G],[C,ee]])if(I)for(let A of new Set(I.steps))for(let j of T.get(ct(A,I===E,l))??[])B.set(A+"\0"+j,{node:A,why:j});let be=E&&C&&(Xo(E.steps,C.steps).added.length||Xo(E.steps,C.steps).removed.length);B.size&&ye.push({workflow:_,service:(C??E).service,status:E?C?"changed":"removed":"new",stepsChanged:!!be,reasons:Ne([...B.values()],I=>I.node+"\0"+I.why)})}function ct(_,E,C){if(!E)return _;for(let[B,be]of C)if(be===_)return B;return _}let xe={schema:1,from:e.fingerprint,to:t.fingerprint,nodes:{added:o.map(Vo),removed:r.map(Vo),modified:Ne(i,_=>_.id),moved:Ne(a,_=>_.toId)},edges:{added:Ne(w,y),removed:Ne(S,y),retargeted:Ne(k,y)},workflows:{physical:$,guessed:F},crossServiceEdges:{added:D,removed:R},touched:Ne(ye,_=>_.workflow)};return xe.counts={nodes:{added:o.length,removed:r.length,modified:i.length,moved:a.length},edges:{added:w.length,removed:S.length,retargeted:k.length},physicalWorkflows:{added:$.added.length,removed:$.removed.length,changed:$.changed.length},guessedWorkflows:{added:F.added.length,removed:F.removed.length,changed:F.changed.length},crossServiceEdges:{added:D.length,removed:R.length},touched:ye.length,touchedNew:ye.filter(_=>_.status==="new").length},xe}function ua(e,t,n,{limit:s=40}={}){let o=e.counts,r=t?`v${t.version} (${(t.headSha??t.fingerprint).slice(0,7)}${t.headMessage?` ${JSON.stringify(t.headMessage)}`:""})`:"to",i=[];i.push(`${r} \u2190 ${n?"v"+n.version:"from"}: nodes +${o.nodes.added} \u2212${o.nodes.removed} ~${o.nodes.modified} \u21A6${o.nodes.moved} | edges +${o.edges.added} \u2212${o.edges.removed}${o.edges.retargeted?` ~${o.edges.retargeted}`:""} | physical workflows touched: ${o.touched} (${o.touchedNew} new)`);let a=(c,d,m)=>{if(d.length){i.push("",`${c} (${d.length})`);for(let f of d.slice(0,s))i.push(" "+m(f));d.length>s&&i.push(` ... ${d.length-s} more`)}};a("Touched physical workflows",e.touched,c=>`[${c.service}] ${c.workflow.split(" | ").slice(2).join(" | ")} <${c.status}> because: ${c.reasons.slice(0,4).map(d=>`${d.why} ${xt(d.node)}`).join(", ")}${c.reasons.length>4?`, +${c.reasons.length-4}`:""}`),a("Nodes added",e.nodes.added,c=>`+ ${c.id}`),a("Nodes removed",e.nodes.removed,c=>`- ${c.id}`),a("Nodes modified",e.nodes.modified,c=>`~ ${c.id}`),a("Nodes moved",e.nodes.moved,c=>`\u21A6 ${c.name}: ${c.fromPath} \u2192 ${c.toPath}`),a("Edges added",e.edges.added,c=>`+ [${c.service}] ${xt(c.from)} \u2192 ${c.calleeNameRaw}${c.resolvedTo?` (resolved to ${xt(c.resolvedTo)})`:""}`),a("Edges removed",e.edges.removed,c=>`- [${c.service}] ${xt(c.from)} \u2192 ${c.calleeNameRaw}`),a("Edges retargeted",e.edges.retargeted,c=>`~ [${c.service}] ${xt(c.from)} \u2192 ${c.calleeNameRaw}: ${xt(c.fromTarget)||"unresolved"} \u2192 ${xt(c.toTarget)||"unresolved"}`),a("Physical workflows changed",e.workflows.physical.changed,c=>`~ ${c.id.split(" | ").slice(2).join(" | ")} +${c.stepsAdded.length} \u2212${c.stepsRemoved.length} steps${c.tierChange?`, tier ${c.tierChange}`:""}${c.reordered?", reordered":""}`),a("Physical workflows added",e.workflows.physical.added,c=>`+ ${c.id.split(" | ").slice(2).join(" | ")} (${c.steps} steps)`),a("Physical workflows removed",e.workflows.physical.removed,c=>`- ${c.id.split(" | ").slice(2).join(" | ")}`),a("Cross-service edges added",e.crossServiceEdges.added,c=>`+ ${c.fromService} \u2192 ${c.toService} via ${c.via} ${c.key??""}`),a("Cross-service edges removed",e.crossServiceEdges.removed,c=>`- ${c.fromService} \u2192 ${c.toService} via ${c.via} ${c.key??""}`);let l=o.guessedWorkflows;return l.added+l.removed+l.changed&&i.push("",`Informational (guessed workflows, never counted as changes): +${l.added} \u2212${l.removed} ~${l.changed}`),i.join(`
14
+ `)}var Yd,Ne,Vo,fa,xt,Yo=_t(()=>{Un();Yd=(e,t)=>e<t?-1:e>t?1:0,Ne=(e,t)=>e.slice().sort((n,s)=>Yd(t(n),t(s)));Vo=e=>({id:e.id,services:e.services,kind:e.kind,name:e.name,filePath:e.filePath});fa=e=>Ot(e),xt=e=>(e??"").split("::").slice(-2).join("::")});var ga={};uc(ga,{UI_VERSIONS:()=>ma,buildUiHistory:()=>ha,writeHistoryJs:()=>tf});import pa from"node:fs";import Qd from"node:path";function ef(e){let t=JSON.parse(JSON.stringify(e));t.truncated={};let n=(s,o)=>{for(let[r,i]of Object.entries(s))Array.isArray(i)&&i.length>qn&&(t.truncated[`${o}.${r}`]=i.length,s[r]=i.slice(0,qn))};return n(t.nodes,"nodes"),n(t.edges,"edges"),n(t.workflows.physical,"workflows.physical"),n(t.crossServiceEdges,"crossServiceEdges"),t.touched.length>qn&&(t.truncated.touched=t.touched.length,t.touched=t.touched.slice(0,qn)),t}function ha(e){let n=Ge(e).versions.slice(-ma),s={};for(let o=1;o<n.length;o++)s[n[o].version]=ef(Wn(Mt(e,n[o-1]),Mt(e,n[o])));return{schema:1,versions:n.map(o=>({version:o.version,fingerprint:o.fingerprint,createdAt:o.createdAt,headSha:o.headSha,headMessage:o.headMessage,dirty:o.dirty,counts:o.counts})),diffs:s}}function tf(e,t){pa.mkdirSync(t,{recursive:!0}),pa.writeFileSync(Qd.join(t,"history.js"),`const canopyHistory = ${Ot(ha(e))};`)}var ma,qn,ya=_t(()=>{yt();Yo();Un();ma=20,qn=200});import cs from"node:fs";import en from"node:path";import it from"node:fs";import nf from"node:os";import ge from"node:path";import{fileURLToPath as xa}from"node:url";import V from"node:path";import he from"node:fs";import{fileURLToPath as Hd,pathToFileURL as Dd}from"node:url";var po=mc(ws(),1);import Ft from"node:fs";import _e from"node:path";var fo={javascript:[".js",".jsx",".mjs",".cjs"],typescript:[".ts",".tsx"]},Ss=[".ts",".tsx",".mts",".cts"],Ac={javascript:["index.js","index.jsx"],typescript:["index.ts","index.tsx"]};function ks(){return Object.values(fo).flat()}function Ns(){return Object.values(Ac).flat()}var bs=["log","logger","console","debug","trace"];var $s=[".yarn",".pnp","vendor","dist","build","out","coverage",".next",".nuxt",".turbo",".cache","bower_components"],mo=["node_modules",".git",".canopy",".canopy-cache"],_s=[".vue",".svelte"],Oc=1024*1024,uo=1e4;function Mc(e,t=null){let n=[];function s(o,r){let i=_e.join(o,".gitignore"),a=(0,po.default)().add(r);Ft.existsSync(i)&&a.add(Ft.readFileSync(i,"utf-8"));let l=Ft.readdirSync(o,{withFileTypes:!0});for(let c of l){let d=_e.join(o,c.name),m=_e.relative(e,d).split(_e.sep).join("/");if(!a.ignores(m)&&!(c.isDirectory()&&mo.includes(c.name))){if(c.isDirectory()&&$s.includes(c.name)){t&&t.excludedDirs.push(d);continue}c.isDirectory()?s(d,a):c.isFile()&&n.push(d)}}}return s(e,(0,po.default)()),n}function Hc(e,t,n=null){return e.filter(s=>!(n?_e.relative(n,s):s).split(_e.sep).some(r=>t.includes(r)))}function Is(e,t){let n=0,s;try{s=Ft.readdirSync(e,{withFileTypes:!0})}catch{return 0}for(let o of s)o.isDirectory()?mo.includes(o.name)||(n+=Is(_e.join(e,o.name),t)):o.isFile()&&t.has(_e.extname(o.name))&&n++;return n}var Dc=e=>/\.d\.(ts|mts|cts)$/.test(e);function Bc(e){let t=_e.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=Ft.statSync(e).size}catch{return null}if(n>Oc)return{kind:"oversized",reason:`oversized (${(n/1048576).toFixed(1)} MB, limit 1 MB)`};if(n>uo){let s=Ft.readFileSync(e,"utf8"),o=0,r=0;for(;;){let i=s.indexOf(`
15
+ `,o),a=(i<0?s.length:i)-o;if(a>r&&(r=a),i<0)break;o=i+1}if(r>uo)return{kind:"minified",reason:`line of ${r.toLocaleString("en-US")} characters (limit ${uo.toLocaleString("en-US")}; minified/bundled)`}}return null}function ho(e,t=["javascript","typescript"]){let n=t.flatMap(m=>(m==="typescript"?Ss:fo[m])||[]),s={excludedDirs:[]},o=Hc(Mc(e,s),[...$s,...mo],e),r=m=>_e.relative(e,m).split(_e.sep).join("/"),i=[],a=[],l={};for(let m of o){let f=_e.extname(m);if(n.includes(f)){if(Dc(m)){a.push({file:r(m),kind:"declaration",reason:"declaration file"});continue}let u=Bc(m);u?a.push({file:r(m),kind:u.kind,reason:u.reason}):i.push(m)}else _s.includes(f)&&(l[f]=(l[f]??0)+1)}let c=new Set([...n,..._s]),d={};for(let m of s.excludedDirs){let f=_e.basename(m),u=d[f]??={dirs:0,files:0};u.dirs++,u.files+=Is(m,c)}return{files:i,skipped:a,unsupported:l,excludedDirs:d}}function dn(e,t=["javascript","typescript"]){return ho(e,t).files}import Uc from"node:path";var ft=e=>e.toLocaleString("en-US"),fn=(e,t,n=t+"s")=>`${ft(e)} ${e===1?t:n}`,zc={".vue":"Vue",".svelte":"Svelte"},Wc=[".vue",".svelte"],qc=new Set([".ts",".tsx",".mts",".cts"]);function Fs({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)),a=[...e.skipped.map(p=>({path:p.file,kind:p.kind,reason:p.reason})),...r].sort((p,h)=>p.path<h.path?-1:p.path>h.path?1:0),l=e.files.filter(p=>!i.has(p)),c=l.filter(p=>t.get(p)?.hadErrors).map(s).sort(),d=l.flatMap(p=>(t.get(p)?.warnings??[]).map(h=>({path:s(p),extractor:h.extractor,message:h.message}))).sort((p,h)=>p.path<h.path?-1:p.path>h.path?1:0),m=l.filter(p=>qc.has(Uc.extname(p))).length,f={};for(let p of Wc)e.unsupported[p]&&(f[p]=e.unsupported[p]);let u={};for(let p of a)u[p.kind]=(u[p.kind]??0)+1;return{analyzed:l.length,analyzedJs:l.length-m,analyzedTs:m,inService:l.filter(p=>n.has(p)).length,notAnalyzed:f,notAnalyzedTotal:Object.values(f).reduce((p,h)=>p+h,0),skipped:a,skippedByKind:u,parseErrors:c.length,parseErrorFiles:c.slice(0,50),parseWarnings:d.length,parseWarningList:d.slice(0,50),excludedDirs:e.excludedDirs,rootService:o}}function un(e){let t=["Coverage"],n=[],s=new Map;for(let[a,l]of Object.entries(e.notAnalyzed)){let c=zc[a];s.has(c)||s.set(c,[]),s.get(c).push(`${ft(l)} ${a}`)}for(let[a,l]of s)n.push(`${l.join(", ")} files (${a} not supported yet)`);if(e.skipped.length){let a=Object.entries(e.skippedByKind).map(([l,c])=>`${l}: ${c}`).join(", ");n.push(`${ft(e.skipped.length)} skipped (${a})`)}e.parseErrors&&n.push(`${ft(e.parseErrors)} with parse errors`),e.parseWarnings&&n.push(`${ft(e.parseWarnings)} extractor warnings (a construct skipped; the rest of its file was analyzed)`);let o=e.analyzedTs?`${fn(e.analyzedJs,"JS file")} and ${fn(e.analyzedTs,"TS file")}`:fn(e.analyzed,"JS file");t.push(` Analyzed ${o}, ${ft(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(a=>a.kind!=="declaration");for(let a of r.slice(0,5))t.push(` skipped ${a.path}: ${a.reason}`);r.length>5&&t.push(` ... and ${ft(r.length-5)} more (full list: meta.coverage.skipped)`);let i=Object.entries(e.excludedDirs);return i.length&&t.push(` Excluded directories: ${i.map(([a,l])=>`${a}/ x${l.dirs} (${fn(l.files,"source file")})`).join(", ")}.`),e.rootService&&t.push(` Root service: ${e.rootService.reason}.`),t.join(`
16
+ `)}De();import{Parser as go,Language as Cs}from"web-tree-sitter";import pn from"node:path";import{fileURLToPath as Jc}from"node:url";var Ru=pn.dirname(Jc(globalThis.__canopyUrl("src/stage2_parse/initParser.js")));var yo=new WeakMap,Ut=e=>yo.get(e)??"javascript",st=e=>Ut(e)!=="javascript";function xo(e){let t=pn.extname(e);return t===".tsx"?"tsx":t===".ts"||t===".mts"||t===".cts"?"typescript":"javascript"}var Kc={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm"};async function Es(e,t){for(let n of new Set(t.map(xo))){if(e.grammars.has(n))continue;let s=pn.join(Ae("tree-sitter-typescript"),Kc[n]),o=await Cs.load(s);yo.set(o,n);let r=new go;r.setLanguage(o),e.grammars.set(n,{parser:r,language:o})}return e}async function Ps(){await go.init();let e=new go,t=pn.join(Ae("tree-sitter-javascript"),"tree-sitter-javascript.wasm"),n=await Cs.load(t);return e.setLanguage(n),yo.set(n,"javascript"),{parser:e,language:n,grammars:new Map([["javascript",{parser:e,language:n}]])}}import Vc from"node:fs";function As(e,t){let n=Vc.readFileSync(t,"utf-8"),s=e.parse(n);if(vo(s)||n.includes("\0")){let o=n,r=Rs(s);for(let i of Xc){let a=i.apply(o);if(a===o)continue;let l=e.parse(a),c=Rs(l);(c<r||i.always)&&(o=a,s=l,r=c)}o!==n&&(s.canopyOriginalSource=n)}return{tree:s,source:n,filePath:t}}var Os=e=>e.replace(/[^\n]/g," "),Ls=e=>"any"+Os(e).slice(3),Ts=/(?<![&])&(?![&=])/g,Xc=[{name:"NUL byte",always:!0,apply:e=>e.replace(/\0/g," ")},{name:"export type * from",apply:e=>e.replace(/\bexport\s+type\s+\*\s*(?:as\s+[\w$]+\s+)?from\s*(["'])[^"'\n]*\1\s*;?/g,Os)},{name:"typeof import()",apply:e=>e.replace(/typeof\s+import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)*/g,Ls)},{name:"import().Type",apply:e=>e.replace(/(?<=[:<,|&?]\s*|\breadonly\s+|\bkeyof\s+|\bextends\s+|\bas\s+)import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)+(?!\s*\()/g,Ls)},{name:"generic call signature after a member",apply:e=>e.replace(/(?<=\n[ \t]*)[ ](?=<\s*[A-Za-z_$][\w$]*\s*(?:extends\b|=|,|>\s*\())/g,";")},{name:"& in JSX text",apply:e=>e.replace(/>[^<>{}"'`]*&[^<>{}"'`]*</g,t=>t.replace(Ts,"+"))},{name:"& in JSX attribute",apply:e=>e.replace(/(\s[\w:-]+=)"([^"\n]*)"/g,(t,n,s)=>n+'"'+s.replace(Ts,"+")+'"')}];function Rs(e){let t=0;return(function n(s){if(s.type==="ERROR"){t++;return}for(let o=0;o<s.childCount;o++)n(s.child(o))})(e.rootNode),t}function vo(e){let t=!1;function n(s){if(s.type==="ERROR"){t=!0;return}for(let o=0;o<s.childCount;o++)n(s.child(o))}return n(e.rootNode),t}import wo from"node:fs";import zt from"node:path";import{fileURLToPath as Yc}from"node:url";import{Query as Zc}from"web-tree-sitter";var Ms=zt.dirname(Yc(globalThis.__canopyUrl("src/utils/loadQuery.js"))),Hs=new WeakMap;function oe(e,t){let n=Hs.get(e);if(n||Hs.set(e,n=new Map),n.has(t))return n.get(t);let s=zt.join(Ms,"..","stage2_parse","queries"),o=wo.existsSync(s)?s:zt.join(Ms,"..","..","dist","queries"),r=Ut(e),l=(r==="javascript"?[]:r==="tsx"?["tsx","typescript"]:[r]).map(m=>zt.join(o,m,t)).find(m=>wo.existsSync(m))??zt.join(o,t),c=wo.readFileSync(l,"utf-8"),d=new Zc(e,c);return n.set(t,d),d}var Ds="javascript",Bs=e=>{Ds=e};var mn=()=>Ds!=="javascript";var Qc=new Set(["non_null_expression","as_expression","satisfies_expression","type_assertion"]);function le(e){for(;e;)if(Qc.has(e.type))e=e.type==="type_assertion"?e.namedChild(e.namedChildCount-1):e.namedChild(0);else if(e.type==="parenthesized_expression"&&e.namedChildCount===1){let t=le(e.namedChild(0));if(t===e.namedChild(0))break;e=t}else break;return e}function el(e){let t=e;for(;t;){t=le(t);for(let n=0;n<t.childCount;n++)if(t.child(n).type==="optional_chain")return!0;if(t.type==="member_expression"||t.type==="subscript_expression")t=t.childForFieldName("object");else if(t.type==="call_expression")t=t.childForFieldName("function");else break}return!1}function rt(e){let t=e.childForFieldName("function"),n=e.childForFieldName("arguments");if(!t)return{kind:"callOfCall",oldShape:!1,nameNode:e};let s=t.type==="identifier",o=t.type==="member_expression"?t.childForFieldName("property"):null,r=t.type==="member_expression"?le(t.childForFieldName("object")):null,i=s||r?.type==="identifier"&&o?.type==="property_identifier",a=o??t;if(mn()&&e.parent?.type==="decorator")return{kind:"decorator",oldShape:i,nameNode:a};if(n&&n.type==="template_string")return{kind:"taggedTemplate",oldShape:i,nameNode:a};if(el(e))return{kind:"optionalCall",oldShape:i,nameNode:a};if(s)return{kind:"call",oldShape:i,nameNode:a};if(t.type==="subscript_expression")return{kind:"computed",oldShape:!1,nameNode:t};if(t.type==="member_expression")return r.type==="super"?{kind:"super",oldShape:!1,nameNode:a}:r.type==="this"?{kind:"thisCall",oldShape:!1,nameNode:a}:i?{kind:"methodCall",oldShape:!0,nameNode:a}:{kind:"chainedCall",oldShape:!1,nameNode:a};if(t.type==="import")return{kind:"dynamicImport",oldShape:!1,nameNode:t};if(t.type==="super")return{kind:"super",oldShape:!1,nameNode:t};let l=t;for(;l.type==="parenthesized_expression"&&l.namedChildCount===1;)l=l.namedChild(0);return l.type==="arrow_function"||l.type==="function_expression"||l.type==="function"||l.type==="generator_function"?{kind:"iife",oldShape:!1,nameNode:t}:{kind:"callOfCall",oldShape:!1,nameNode:t}}function Us(e){let t=e.childForFieldName("name");return t?t.type==="identifier"?/^[A-Z]/.test(t.text)?{kind:"jsx",oldShape:!0,nameNode:t}:null:t.type==="member_expression"||t.type==="nested_identifier"?{kind:"jsxMember",oldShape:!1,nameNode:t}:null:null}function hn(e){let t=e;for(;t&&t.type!=="call_expression";)t=t.parent;return t}function zs(e){let t=e.childForFieldName("function"),n=!1;for(;t;)if(t=le(t),t.type==="member_expression"||t.type==="subscript_expression")t=t.childForFieldName("object");else if(t.type==="call_expression")n=!0,t=t.childForFieldName("function");else if(t.type==="await_expression"||t.type==="parenthesized_expression"||t.type==="non_null_expression")t=t.namedChild(0);else break;return t&&t.type==="identifier"?{head:t.text,called:n}:{head:null,called:!1}}function Ws(e){let t=e.text.replace(/\s+/g," ");return t.length>120?t.slice(0,117)+"...":t}function Gs(e,t){let o=oe(t,"functionDeclarations.scm").matches(e.rootNode).map(r=>{let i=r.captures.find(c=>c.name==="func_name"),a=r.captures.find(c=>c.name==="func_params"),l=r.captures.find(c=>c.name==="func_declaration");return{name:i.node.text,params:a.node.text,startLine:l.node.startPosition.row+1,endLine:l.node.endPosition.row+1,startIndex:l.node.startIndex,endIndex:l.node.endIndex,node:i.node}});return st(t)&&o.push(...tl(e,t)),o}function tl(e,t){return oe(t,"defaultExports.scm").matches(e.rootNode).map(n=>{let s=n.captures.find(r=>r.name==="func_declaration").node;return{name:"default",params:n.captures.find(r=>r.name==="func_params").node.text,startLine:s.startPosition.row+1,endLine:s.endPosition.row+1,startIndex:s.startIndex,endIndex:s.endIndex,node:s}})}function Js(e,t){return oe(t,"arrowFunctions.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(l=>l.name==="func_name"),i=o.captures.find(l=>l.name==="func_params"),a=o.captures.find(l=>l.name==="func_declaration");return{name:r.node.text,params:i.node.text,startLine:a.node.startPosition.row+1,endLine:a.node.endPosition.row+1,startIndex:a.node.startIndex,endIndex:a.node.endIndex,node:r.node}})}function Ks(e,t){let s=oe(t,"classMethods.scm").matches(e.rootNode),o=st(t);return s.map(r=>{let i=r.captures.find(m=>m.name==="class_name"),a=r.captures.find(m=>m.name==="method_name"),l=r.captures.find(m=>m.name==="method_params"),c=r.captures.find(m=>m.name==="method_declaration"),d=c.node;if(o)for(let m=d.previousNamedSibling;m&&m.type==="decorator";m=m.previousNamedSibling)d=m;return{className:i?i.node.text:"default",methodName:a.node.text,params:l.node.text,startLine:d.startPosition.row+1,endLine:c.node.endPosition.row+1,startIndex:d.startIndex,endIndex:c.node.endIndex,node:a.node}})}function Vs(e,t){let s=oe(t,"imports.scm").matches(e.rootNode),o=st(t);return s.filter(r=>!(o&&nl(r.captures[0].node))).map(r=>{let i=r.captures[0].node;return{source:i.text,startLine:i.startPosition.row+1}})}function nl(e){let t=e;for(;t&&t.type!=="import_statement";)t=t.parent;if(!t)return!1;if(t.children.some(r=>r.type==="type"))return!0;let n=t.namedChildren.find(r=>r.type==="import_clause");if(!n)return!1;let s=n.namedChildren;if(s.length!==1||s[0].type!=="named_imports")return!1;let o=s[0].namedChildren.filter(r=>r.type==="import_specifier");return o.length>0&&o.every(r=>r.children.some(i=>i.type==="type"))}function Wt(e){let t=e;for(;t&&t.type!=="call_expression"&&t.type!=="new_expression";)t=t.parent;if(!t)return null;let n=t.childForFieldName("arguments");if(!n)return null;let s=n.namedChildren?.[0];return!s||s.type==="arrow_function"||s.type==="function_expression"?null:s.text}var ol=/^(addEventListener|removeEventListener|on|once|postMessage|onmessage|subscribe)$/i;function Ct(e){let t=e;for(;t.parent;){let n=t.parent;if(n.type==="arrow_function"||n.type==="function_expression"){let s=n.parent;if(s&&(s.type==="variable_declarator"||s.type==="public_field_definition"))break;if(s&&s.type==="return_statement")return!0;if(s&&s.type==="arguments"&&s.parent?.type==="call_expression"){let o=s.parent.childForFieldName("function"),r=o?.type==="member_expression"?o.childForFieldName("property")?.text:o?.text;if(r&&ol.test(r))return!0}}else if(n.type==="function_declaration"||n.type==="method_definition")break;t=n}return!1}function Xs(e,t){return oe(t,"callExpressions.scm").matches(e.rootNode).map(o=>{let r=o.captures[0].node;return{calleeName:r.text,startLine:r.startPosition.row+1,startColumn:r.startPosition.column,branchPath:Et(r),firstArgText:Wt(r),deferred:Ct(r),callKind:rt(hn(r)).kind}})}function Ys(e,t){return st(t)?sl(e):oe(t,"methodCalls.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(a=>a.name==="object_name"),i=o.captures.find(a=>a.name==="method_name");return{objectName:r.node.text,methodName:i.node.text,startLine:i.node.startPosition.row+1,startColumn:i.node.startPosition.column,firstArgText:Wt(i.node),branchPath:Et(i.node),deferred:Ct(i.node),callKind:rt(hn(i.node)).kind}})}function sl(e){let t=[];for(let n of e.rootNode.descendantsOfType("call_expression")){let s=n.childForFieldName("function");if(!s||s.type!=="member_expression")continue;let o=le(s.childForFieldName("object")),r=s.childForFieldName("property");!o||o.type!=="identifier"||!r||r.type!=="property_identifier"||t.push({objectName:o.text,methodName:r.text,startLine:r.startPosition.row+1,startColumn:r.startPosition.column,firstArgText:Wt(r),branchPath:Et(r),deferred:Ct(r),callKind:rt(hn(r)).kind})}return t}function rl(e){if(!e)return"return";if(e.type==="object"){let t=e.namedChildren.filter(s=>s.type==="pair"),n=t.find(s=>s.childForFieldName("key")?.text?.replace(/^['"]|['"]$/g,"")==="type")??t.find(s=>s.childForFieldName("key")?.text?.replace(/^['"]|['"]$/g,"")==="entity");if(n){let s=n.childForFieldName("key"),o=n.childForFieldName("value");return`return { ${s.text}: ${o.text} }`}}return"return "+e.text.split(/\r?\n/)[0].trim()}function Zs(e,t){return oe(t,"returns.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(l=>l.name==="return_statement"),i=o.captures.find(l=>l.name==="return_value"),a=r.node;return{label:rl(i?.node),startLine:a.startPosition.row+1,startColumn:a.startPosition.column,branchPath:Et(a),deferred:Ct(a)}})}var il=new Set(["function_declaration","arrow_function","function_expression","method_definition"]);function gn(e,t){return!(!t||e.row<t.startPosition.row||e.row>t.endPosition.row||e.row===t.startPosition.row&&e.column<t.startPosition.column||e.row===t.endPosition.row&&e.column>t.endPosition.column)}function Et(e){let t=[],n=e,s=e.startPosition;for(;n.parent;){let o=n.parent;if(il.has(o.type))break;if(o.type==="if_statement"){let r=o.childForFieldName("condition"),i=o.childForFieldName("consequence"),a=o.childForFieldName("alternative");gn(s,i)?t.push({type:"if",conditionText:r?r.text:"",conditionLine:(r??o).startPosition.row+1,outcome:"true"}):gn(s,a)&&t.push({type:"if",conditionText:r?r.text:"",conditionLine:(r??o).startPosition.row+1,outcome:"false"})}else if(o.type==="switch_case"||o.type==="switch_default"){let r=o.parent,i=r&&r.type==="switch_body"?r.parent:null;if(i){let a=i.childForFieldName("value"),l=o.childForFieldName("value");t.push({type:"switch",conditionText:a?a.text:"",conditionLine:(a??i).startPosition.row+1,outcome:o.type==="switch_default"?"default":l?l.text:"case"})}}else if(o.type==="try_statement"){let r=o.childForFieldName("handler"),i=o.childForFieldName("finalizer"),a="try";gn(s,r)?a="catch":gn(s,i)&&(a="finally"),t.push({type:"try",conditionText:"try / catch",conditionLine:o.startPosition.row+1,outcome:a})}n=o}return t.reverse()}function Qs(e,t){return oe(t,"exports.scm").matches(e.rootNode).map(s=>s.captures[0].node.text)}var qs=new WeakMap;function al(e,t){let n=qs.get(e);return n||(n=oe(t,"returns.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(a=>a.name==="return_statement"),i=o.captures.find(a=>a.name==="return_value");return{stmtNode:r.node,valueNode:i?.node}}),qs.set(e,n)),n}function er(e,t,n){return al(e,t).filter(s=>s.stmtNode.startPosition.row+1>=n.startLine&&s.stmtNode.endPosition.row+1<=n.endLine).map(s=>({shape:cl(s.valueNode),condition:ll(s.stmtNode,n),line:s.stmtNode.startPosition.row+1}))}function cl(e){if(!e)return"nothing";switch(e.type){case"true":case"false":return"boolean";case"number":return"number";case"string":return"string";case"null":return"null";case"identifier":return`variable (${e.text})`;case"object":return"object";case"array":return"array";case"call_expression":return`result of ${e.text.split("(")[0]}()`;case"binary_expression":return"boolean (comparison)";case"ternary_expression":return"conditional value";default:return"expression"}}function ll(e,t){let n=e.parent;for(;n;){if(n.type==="if_statement"){let s=n.childForFieldName("condition");if(s)return s.text}n=n.parent}return null}function tr(e,t){return Ut(t)==="typescript"?[]:oe(t,"jsxElements.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(i=>i.name==="jsx_tag");return{calleeName:r.node.text,startLine:r.node.startPosition.row+1}}).filter(o=>/^[A-Z]/.test(o.calleeName))}function nr(e,t){return oe(t,"fetchApiCalls.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(c=>c.name==="url"),i=o.captures.find(c=>c.name==="http_method"),a=r.node.text,l=/^https?:\/\//.test(a)?"external":"internal";return{url:a,method:i?.node.text??"get",startLine:r.node.startPosition.row+1,scope:l}})}function or(e,t){return oe(t,"socketEmit.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(i=>i.name==="event_name");return{eventName:r.node.text,startLine:r.node.startPosition.row+1}})}function sr(e,t){return oe(t,"rawSocketSend.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(i=>i.name==="event_name");return{eventName:r.node.text,startLine:r.node.startPosition.row+1}})}function rr(e,t){return oe(t,"rawSocketTypeCheck.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(i=>i.name==="event_name");return{eventName:r.node.text,startLine:r.node.startPosition.row+1}})}function ir(e,t){return oe(t,"socketOn.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(l=>l.name==="event_name"),i=o.captures.find(l=>l.name==="handler_ref"),a=o.captures.find(l=>l.name==="handler_inline");return{eventName:r.node.text,startLine:r.node.startPosition.row+1,handlerName:i?i.node.text:null,isInlineHandler:!!a,handlerStartLine:a?a.node.startPosition.row+1:null,handlerEndLine:a?a.node.endPosition.row+1:null,handlerStartIndex:a?a.node.startIndex:null,handlerEndIndex:a?a.node.endIndex:null}})}function ar(e){let t=e.rootNode.descendantsOfType(["call_expression","new_expression","jsx_opening_element","jsx_self_closing_element",...mn()?["decorator"]:[]]),n=[];for(let s of t){let o,r,i,a=null,l=null,c=!1,d=null,m=null;if(s.type==="new_expression"){if(i=s.childForFieldName("constructor"),!i)continue;o="new",r=i,a=i.type==="identifier"?i.text:null;let u=s.childForFieldName("arguments")?.namedChildren?.[0];d=u&&u.type!=="arrow_function"&&u.type!=="function_expression"?u.text:null}else if(s.type==="decorator"){let f=s.namedChild(0);if(!f||f.type==="call_expression")continue;o="decorator",r=f.type==="member_expression"?f.childForFieldName("property")??f:f,i=f}else if(s.type==="call_expression"){let f=rt(s);if(f.oldShape)continue;if(o=f.kind,r=f.nameNode,i=s.childForFieldName("function")??s,o==="chainedCall"){let u=zs(s);l=u.head,c=u.called;let p=s.childForFieldName("function"),h=p?.type==="member_expression"?le(p.childForFieldName("object")):null;h?.type==="member_expression"&&le(h.childForFieldName("object"))?.type==="this"&&h.childForFieldName("property")?.type==="property_identifier"&&p.childForFieldName("property")&&(m={thisProp:h.childForFieldName("property").text,thisMethod:p.childForFieldName("property").text})}d=Wt(r)}else{let f=Us(s);if(!f||f.oldShape)continue;o=f.kind,r=f.nameNode,i=f.nameNode}n.push({callKind:o,calleeName:Ws(i),startLine:r.startPosition.row+1,startColumn:r.startPosition.column,branchPath:Et(r),firstArgText:d,deferred:Ct(r),chainHead:l,chainHeadCalled:c,ctorName:a,...m??{}})}return n.sort((s,o)=>s.startLine-o.startLine||s.startColumn-o.startColumn)}var So=new Set(["get","post","put","patch","delete","head","options"]),ko=new Set(["axios","ky","got","superagent","$http"]),dl=new Set(["function_declaration","function_expression","function","arrow_function","method_definition","generator_function_declaration","generator_function"]),fl=new Set(["WebSocket","ReconnectingWebSocket","SockJS","W3CWebSocket"]),No=/^(ws|socket|sock|websocket|webSocket|wsClient|socketRef|wsRef|[A-Za-z]+Socket|[A-Za-z]+Ws|[A-Za-z]+WebSocket)$/,Q=e=>{for(;e&&(e.type==="parenthesized_expression"||e.type==="as_expression"||e.type==="non_null_expression"||e.type==="await_expression"||e.type==="satisfies_expression"||e.type==="type_assertion")&&(e=e.namedChildren.find(t=>t.type!=="type_annotation"&&t.type!=="predefined_type"&&!/_type$/.test(t.type))??e.namedChildren[0],!!e););return e},qt=e=>e.namedChildren.length?e.namedChildren.filter(t=>t.type==="string_fragment"||t.type==="escape_sequence").map(t=>t.text).join(""):e.text.slice(1,-1);function Pt(e){for(let t=e.parent;t;t=t.parent)if(dl.has(t.type))return t;return null}function cr(e){if(!e)return null;let t=e.childForFieldName("name")?.text??null;if(!t&&e.parent){let o=e.parent;o.type==="variable_declarator"?t=o.childForFieldName("name")?.text??null:o.type==="assignment_expression"?t=o.childForFieldName("left")?.text??null:o.type==="pair"&&(t=o.childForFieldName("key")?.text??null)}let n=[],s=e.childForFieldName("parameters");if(s)s.namedChildren.forEach((o,r)=>{let i=o.type==="identifier"?o:o.type==="assignment_pattern"?o.childForFieldName("left"):o.type==="required_parameter"||o.type==="optional_parameter"?o.childForFieldName("pattern")??o.namedChildren[0]:null;n[r]=i&&i.type==="identifier"?i.text:null});else{let o=e.childForFieldName("parameter");o&&o.type==="identifier"&&(n[0]=o.text)}return{name:t,params:n}}function lr(e){let t=e.rootNode,n={httpCalls:[],pathCallsites:[],httpInstances:[],wsClients:[],wsServers:[],wsSends:[],wsServerSends:[],listens:[],wsReceivers:[]},s=new Map;for(let u of t.descendantsOfType("variable_declarator")){let p=u.childForFieldName("name"),h=u.childForFieldName("value");if(!p||p.type!=="identifier"||!h)continue;(s.get(p.text)??s.set(p.text,[]).get(p.text)).push({value:h,fn:Pt(u)})}let o=(u,p)=>{let h=s.get(u);if(!h)return null;for(let g=Pt(p);g;g=Pt(g)){let w=h.filter(S=>S.fn&&S.fn.id===g.id);if(w.length===1)return w[0].value}let v=h.filter(g=>!g.fn);return v.length===1?v[0].value:h.length===1?h[0].value:null},r=(u,p)=>{for(let h=Pt(p);h;h=Pt(h)){let g=cr(h).params.indexOf(u);if(g>=0)return g}return-1};function i(u,p=0){if(u=Q(u),!u)return[{t:"ref",name:""}];switch(u.type){case"string":return[{t:"lit",v:qt(u)}];case"template_string":{let h=[];for(let v of u.namedChildren)v.type==="string_fragment"||v.type==="escape_sequence"?h.push({t:"lit",v:v.text}):v.type==="template_substitution"&&h.push(...i(v.namedChildren[0],p+1));return h.length?h:[{t:"lit",v:""}]}case"number":return[{t:"lit",v:u.text}];case"binary_expression":{let h=u.childForFieldName("operator")?.text;if(h==="||"||h==="??"){let v=i(u.childForFieldName("left"),p+1);if(v.length===1&&v[0].t==="env")return[{...v[0],fallback:i(u.childForFieldName("right"),p+1)}]}return h!=="+"?[{t:"ref",name:u.text.slice(0,60)}]:[...i(u.childForFieldName("left"),p+1),...i(u.childForFieldName("right"),p+1)]}case"shorthand_property_identifier":case"identifier":{let h=u.text,v=r(h,u);if(v>=0)return[{t:"param",name:h,index:v}];if(p<4){let g=o(h,u);if(g&&g.id!==u.id)return i(g,p+1)}return[{t:"ref",name:h}]}case"member_expression":{let h=u.text,v=/^(?:process\.env|import\.meta\.env)\.([A-Za-z0-9_$]+)$/.exec(h)??/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(h);return v?[{t:"env",name:v[1]}]:[{t:"ref",name:h.slice(0,60)}]}case"subscript_expression":{let h=/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(u.text);return h?[{t:"env",name:h[1]}]:[{t:"ref",name:u.text.slice(0,60)}]}case"call_expression":{let h=u.childForFieldName("function")?.text,v=u.childForFieldName("arguments")?.namedChildren[0];if(v&&(h==="encodeURIComponent"||h==="String"||h==="encodeURI"))return i(v,p+1);let g=Q(u.childForFieldName("function"));if(g&&g.type==="member_expression"&&/^(replace|replaceAll|trim|trimEnd|trimStart|toString|toLowerCase)$/.test(g.childForFieldName("property")?.text??"")){let w=g.childForFieldName("object");if(w){let S=i(w,p+1);if(S.length&&S.every(k=>k.t!=="ref"))return S}}return[{t:"ref",name:u.text.slice(0,60)}]}default:return[{t:"ref",name:u.text.slice(0,60)}]}}let a=(u,p)=>{if(u=Q(u),!(!u||u.type!=="object")){for(let h of u.namedChildren)if(h.type==="pair"){let v=h.childForFieldName("key");if((v?v.type==="string"?qt(v):v.text:null)===p)return h.childForFieldName("value")}else if(h.type==="shorthand_property_identifier"&&h.text===p)return h}},l=u=>u.childForFieldName("arguments")?.namedChildren.filter(p=>p.type!=="comment")??[],c=u=>{if(!u)return null;let p=i(u);return p.length===1&&p[0].t==="lit"?p[0].v.toUpperCase():p.length===1&&p[0].t==="param"?{param:p[0].index}:"?"},d=(u,p,h,v)=>({client:u,method:p,parts:h,line:v.startPosition.row+1,fn:cr(Pt(v))});for(let u of t.descendantsOfType("variable_declarator")){let p=u.childForFieldName("name"),h=Q(u.childForFieldName("value"));if(!p||p.type!=="identifier"||!h||h.type!=="call_expression")continue;let v=Q(h.childForFieldName("function"));if(!v||v.type!=="member_expression")continue;let g=v.childForFieldName("object")?.text,w=v.childForFieldName("property")?.text;if(!(ko.has(g)&&(w==="create"||w==="extend")))continue;let S=l(h)[0],k=a(S,"baseURL")??a(S,"baseUrl")??a(S,"prefixUrl")??a(S,"prefix_url");n.httpInstances.push({name:p.text,parts:k?i(k):[],line:u.startPosition.row+1})}let m=new Set(n.httpInstances.map(u=>u.name));for(let u of t.descendantsOfType("call_expression")){let p=Q(u.childForFieldName("function"));if(!p)continue;let h=l(u),v=!1;if(p.type==="identifier"){let g=p.text;if(g==="fetch"&&h[0]){let w=Q(h[0]);if(w&&w.type==="new_expression")continue;let S=a(h[1],"method");n.httpCalls.push(d("fetch",S?c(S):h[1]&&Q(h[1])?.type!=="object"?"?":"GET",i(h[0]),u)),v=!0}else if((ko.has(g)||m.has(g))&&h[0]){let w=Q(h[0]);if(w&&w.type==="object"){let S=a(w,"url");if(S){let k=a(w,"baseURL");n.httpCalls.push(d(m.has(g)?"inst:"+g:g,c(a(w,"method"))??"GET",[...k?i(k):[],...i(S)],u)),v=!0}}else n.httpCalls.push(d(m.has(g)?"inst:"+g:g,h[1]&&a(h[1],"method")?c(a(h[1],"method")):"GET",i(h[0]),u)),v=!0}else g==="io"&&h[0]&&(n.wsClients.push({client:"io",parts:i(h[0]),line:u.startPosition.row+1}),v=!0)}else if(p.type==="member_expression"){let w=p.childForFieldName("object")?.text??"",S=p.childForFieldName("property")?.text??"",k=ko.has(w)||m.has(w);if(k&&So.has(S)&&h[0])n.httpCalls.push(d(m.has(w)?"inst:"+w:w,S.toUpperCase(),i(h[0]),u)),v=!0;else if(!k&&So.has(S)&&/^[A-Za-z_$][\w$]*$/.test(w)&&h[0]&&(Q(h[0])?.type==="string"||Q(h[0])?.type==="template_string")){let y=i(h[0]);y[0]?.t==="lit"&&(y[0].v.startsWith("/")||/^https?:\/\//.test(y[0].v))&&(n.httpCalls.push(d("obj:"+w,S.toUpperCase(),y,u)),v=!0)}else if(k&&S==="request"&&h[0]){let y=a(h[0],"url");if(y){let x=a(h[0],"baseURL");n.httpCalls.push(d(m.has(w)?"inst:"+w:w,c(a(h[0],"method"))??"GET",[...x?i(x):[],...i(y)],u)),v=!0}}else if(S==="open"&&h.length>=2&&Q(h[0])?.type==="string"&&/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/i.test(qt(Q(h[0]))))n.httpCalls.push(d("xhr",qt(Q(h[0])).toUpperCase(),i(h[1]),u)),v=!0;else if(w==="io"&&S==="connect"&&h[0])n.wsClients.push({client:"io",parts:i(h[0]),line:u.startPosition.row+1}),v=!0;else if(S==="listen"&&h[0]){let y=Q(h[0]),x=y&&y.type==="object"?a(y,"port"):y;x&&n.listens.push({parts:i(x),line:u.startPosition.row+1}),v=!0}else if(S==="send"&&/^(client|conn|connection|peer)$/.test(w.replace(/^this./,"").split(".").pop())&&h[0]){let y=Q(h[0]),x=!1;if(y&&y.type==="call_expression"&&y.childForFieldName("function")?.text==="JSON.stringify"){let b=l(y)[0];x=!!(b&&(a(b,"type")||a(b,"event"))&&Q(a(b,"type")??a(b,"event"))?.type==="string")}x||n.wsServerSends.push({recv:w,line:u.startPosition.row+1}),v=!0}else if(S==="send"&&No.test(w.replace(/^this\./,"").replace(/\.current$/,"").split(".").pop())){let y=h[0]?Q(h[0]):null,x=!1;if(y&&y.type==="call_expression"&&y.childForFieldName("function")?.text==="JSON.stringify"){let b=l(y)[0];x=!!(b&&(a(b,"type")||a(b,"event"))&&Q(a(b,"type")??a(b,"event"))?.type==="string")}x||n.wsSends.push({recv:w,line:u.startPosition.row+1}),v=!0}}if(!v){let g=null;if(p.type==="identifier"?g=p.text:p.type==="member_expression"&&(g=p.childForFieldName("property")?.text??null),!g||So.has(g)||h.length===0||h.length>6)continue;let w=[],S=!1;h.slice(0,5).forEach((k,y)=>{let x=Q(k);if(!x||x.type!=="string"&&x.type!=="template_string")return;let b=i(x);w.push({i:y,parts:b});let N=b[0];N&&N.t==="lit"&&(N.v.startsWith("/")||/^https?:\/\//.test(N.v))&&N.v.length>1&&(S=!0)}),S&&n.pathCallsites.push({callee:g,args:w,line:u.startPosition.row+1})}}let f=u=>u.replace(/^this./,"").replace(/.current$/,"").split(".").pop();for(let u of t.descendantsOfType("assignment_expression")){let p=u.childForFieldName("left");if(!p||p.type!=="member_expression"||p.childForFieldName("property")?.text!=="onmessage"||!No.test(f(p.childForFieldName("object")?.text??"")))continue;let h=Q(u.childForFieldName("right"));n.wsReceivers.push({line:u.startPosition.row+1,handlerName:h&&h.type==="identifier"?h.text:null})}for(let u of t.descendantsOfType("call_expression")){let p=Q(u.childForFieldName("function"));if(!p||p.type!=="member_expression"||p.childForFieldName("property")?.text!=="addEventListener")continue;let h=l(u),v=h[0]&&Q(h[0]);if(!v||v.type!=="string"||qt(v)!=="message"||!No.test(f(p.childForFieldName("object")?.text??"")))continue;let g=h[1]&&Q(h[1]);n.wsReceivers.push({line:u.startPosition.row+1,handlerName:g&&g.type==="identifier"?g.text:null})}for(let u of t.descendantsOfType("new_expression")){let p=Q(u.childForFieldName("constructor"));if(!p)continue;let h=p.text,v=l(u);if(fl.has(h)&&v[0])n.wsClients.push({client:h,parts:i(v[0]),line:u.startPosition.row+1});else if(/^(WebSocketServer|WebSocket\.Server|WebSocket\.WebSocketServer|ws\.Server|ws\.WebSocketServer|Server)$/.test(h)){if(h==="Server"&&!/socket\.io|socketio/i.test(e.rootNode.text.slice(0,4e3)+""))continue;let g=a(v.find(w=>Q(w)?.type==="object"),"path");n.wsServers.push({path:g?i(g):null,line:u.startPosition.row+1})}}return n}var ul=new Set(["function_declaration","generator_function_declaration","function_expression","generator_function","arrow_function","method_definition"]),pl=new Set(["arrow_function","function_expression","generator_function"]);function Ve(e,t){if(e)switch(e.type){case"identifier":case"shorthand_property_identifier_pattern":t.push(e.text);return;case"assignment_pattern":Ve(e.childForFieldName("left"),t);return;case"rest_pattern":case"object_pattern":case"array_pattern":case"pair_pattern":case"required_parameter":case"optional_parameter":for(let n of e.namedChildren)Ve(e.type==="pair_pattern"?e.childForFieldName("value"):n,t);return;default:if(e.type==="pattern"||e.namedChildCount){let n=e.childForFieldName?.("pattern");n&&Ve(n,t)}}}function ml(e,t){let n=e;if(n.type==="export_statement"&&(n=n.childForFieldName("declaration")),!n)return null;if(n.type==="function_declaration"||n.type==="generator_function_declaration")return n.childForFieldName("name")?.text===t?{kind:"fn",declLine:n.startPosition.row+1}:null;if(n.type==="lexical_declaration"||n.type==="variable_declaration"){for(let s of n.namedChildren){if(s.type!=="variable_declarator")continue;let o=s.childForFieldName("name");if(o?.type==="identifier"){if(o.text!==t)continue;let i=le(s.childForFieldName("value"));return i&&pl.has(i.type)?{kind:"fn",declLine:s.startPosition.row+1}:{kind:"other"}}let r=[];if(Ve(o,r),r.includes(t))return{kind:"other"}}return null}return(n.type==="class_declaration"||n.type==="abstract_class_declaration"||n.type==="enum_declaration")&&n.childForFieldName("name")?.text===t?{kind:"other"}:null}function hl(e){let t=e.namedChildren.find(o=>o.type==="string")?.text.slice(1,-1)??null,n=e.namedChildren.find(o=>o.type==="import_clause"),s=[];if(!n||t==null)return{src:t,out:s};for(let o of n.namedChildren)if(o.type==="identifier")s.push({kind:"default",local:o.text,imported:null});else if(o.type==="namespace_import"){let r=o.namedChildren.find(i=>i.type==="identifier");r&&s.push({kind:"ns",local:r.text,imported:null})}else if(o.type==="named_imports")for(let r of o.namedChildren){if(r.type!=="import_specifier")continue;let i=r.childForFieldName("name"),a=r.childForFieldName("alias");i&&s.push({kind:"named",local:(a??i).text,imported:i.text})}return{src:t,out:s}}function dr(e){let t=[];for(let n of e.rootNode.namedChildren)if(n.type==="import_statement"){if(n.children.some(i=>i.type==="type"))continue;let s=n.namedChildren.find(i=>i.type==="import_require_clause");if(s){let i=s.namedChildren.find(l=>l.type==="identifier"),a=s.namedChildren.find(l=>l.type==="string");i&&a&&t.push({source:Gt(a),kind:"cjs",local:i.text,imported:null});continue}let{src:o,out:r}=hl(n);for(let i of r)t.push({source:o,...i})}else if(n.type==="lexical_declaration"||n.type==="variable_declaration")for(let s of n.namedChildren){if(s.type!=="variable_declarator")continue;let o=le(s.childForFieldName("value")),r=null;o?.type==="member_expression"&&(r=o.childForFieldName("property")?.text??null,o=le(o.childForFieldName("object")));let i=yn(o);if(i==null)continue;let a=s.childForFieldName("name");if(a?.type==="identifier")t.push({source:i,kind:r?"named":"cjs",local:a.text,imported:r});else if(a?.type==="object_pattern"&&!r){for(let l of a.namedChildren)if(l.type==="shorthand_property_identifier_pattern")t.push({source:i,kind:"named",local:l.text,imported:l.text});else if(l.type==="pair_pattern"){let c=l.childForFieldName("key"),d=l.childForFieldName("value");c&&d?.type==="identifier"&&t.push({source:i,kind:"named",local:d.text,imported:c.text})}}}return t}var Gt=e=>e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("");function yn(e){if(e?.type!=="call_expression")return null;let t=e.childForFieldName("function"),n=e.childForFieldName("arguments");if(t?.type!=="identifier"||t.text!=="require"||!n||n.namedChildCount!==1)return null;let s=n.namedChildren[0];return s.type==="string"?Gt(s):null}function fr(e){let t=[];return(function n(s){if(s.type==="export_statement"){let o=s.childForFieldName("source");o&&!s.children.some(r=>r.type==="type")&&t.push({source:Gt(o),startLine:o.startPosition.row+1})}else if(s.type==="import_require_clause"){let o=s.namedChildren.find(r=>r.type==="string");o&&t.push({source:Gt(o),startLine:o.startPosition.row+1})}else if(s.type==="call_expression"){let o=yn(s);o!=null&&t.push({source:o,startLine:s.startPosition.row+1})}for(let o of s.namedChildren)n(o)})(e.rootNode),t}function ur(e){let t={default:null,named:{},reexports:[],stars:[],nsReexports:[]};for(let n of e.rootNode.namedChildren){if(n.type!=="export_statement")continue;let s=n.children.some(i=>i.type==="default"),o=n.childForFieldName("declaration"),r=n.childForFieldName("source")!=null;if(s){if(o){let i=o.childForFieldName("name");t.default=i&&(o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"||o.type==="abstract_class_declaration")?i.text:"<anon>"}else{let i=le(n.childForFieldName("value"));t.default=i?.type==="identifier"?i.text:"<anon>"}continue}if(o){if(o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"||o.type==="abstract_class_declaration"){let i=o.childForFieldName("name")?.text;i&&(t.named[i]=i)}else if(o.type==="lexical_declaration"||o.type==="variable_declaration")for(let i of o.namedChildren){let a=i.type==="variable_declarator"?i.childForFieldName("name"):null;a?.type==="identifier"&&(t.named[a.text]=a.text)}continue}if(r){if(n.children.some(c=>c.type==="type"))continue;let i=Gt(n.childForFieldName("source")),a=n.namedChildren.find(c=>c.type==="export_clause"),l=n.namedChildren.find(c=>c.type==="namespace_export");if(a)for(let c of a.namedChildren){if(c.type!=="export_specifier")continue;let d=c.childForFieldName("name")?.text,m=c.childForFieldName("alias")?.text;d&&t.reexports.push({exported:m??d,imported:d,source:i})}else if(l){let c=l.namedChildren.find(d=>d.type==="identifier");c&&t.nsReexports.push({exported:c.text,source:i})}else t.stars.push(i);continue}for(let i of n.namedChildren)if(i.type==="export_clause")for(let a of i.namedChildren){if(a.type!=="export_specifier")continue;let l=a.childForFieldName("name")?.text,c=a.childForFieldName("alias")?.text;l&&(c==="default"?t.default=l:t.named[c??l]=l)}}for(let n of e.rootNode.namedChildren){let s=n.type==="expression_statement"?n.namedChildren[0]:null;if(s?.type!=="assignment_expression")continue;let o=s.childForFieldName("left"),r=le(s.childForFieldName("right"));if(o?.type!=="member_expression")continue;let i=o.childForFieldName("object"),a=o.childForFieldName("property")?.text,l=c=>c?.type==="member_expression"&&c.childForFieldName("object")?.text==="module"&&c.childForFieldName("property")?.text==="exports";if(l(o))if(r?.type==="identifier")t.default=r.text;else if(r?.type==="object"){for(let c of r.namedChildren)if(c.type==="shorthand_property_identifier")t.named[c.text]=c.text;else if(c.type==="pair"){let d=c.childForFieldName("key"),m=le(c.childForFieldName("value"));d&&m?.type==="identifier"&&(t.named[d.text.replace(/^['"]|['"]$/g,"")]=m.text)}t.default??="<object>"}else yn(r)!=null?t.stars.push(yn(r)):t.default="<anon>";else a&&(i?.type==="identifier"&&i.text==="exports"||l(i))&&r?.type==="identifier"&&(t.named[a]=r.text)}return t}function gl(e,t,n){for(let s=e.parent;s;s=s.parent)if(ul.has(s.type)){let o=[],r=s.childForFieldName("parameters");if(r)for(let a of r.namedChildren)Ve(a,o);let i=s.childForFieldName("parameter");if(i&&Ve(i,o),s.type==="function_expression"||s.type==="generator_function"){let a=s.childForFieldName("name");a&&o.push(a.text)}if(o.includes(t))return{kind:"other"}}else if(s.type==="catch_clause"){let o=[];if(Ve(s.childForFieldName("parameter"),o),o.includes(t))return{kind:"other"}}else if(s.type==="for_in_statement"||s.type==="for_statement"){let o=[],r=s.type==="for_statement"?s.childForFieldName("initializer"):s.childForFieldName("left");if(r)if(r.type==="lexical_declaration"||r.type==="variable_declaration")for(let i of r.namedChildren)Ve(i.childForFieldName?.("name"),o);else Ve(r,o);if(o.includes(t))return{kind:"other"}}else if(s.type==="statement_block"||s.type==="program"||s.type==="switch_body"){if(s.type==="program"&&n.has(t))return{kind:"import",imp:n.get(t)};for(let o of s.namedChildren){let r=ml(o,t);if(r)return r}if(s.type==="program"&&n.has(t))return{kind:"import",imp:n.get(t)}}return null}var yl=e=>(e.childForFieldName("function")?.text??"").replace(/\s+/g," ").slice(0,40);function pr(e,t){let n=new Map(t.map(r=>[r.local,r])),s=[],o=(r,i,a)=>{let l=le(r);if(!l||l.type!=="identifier"&&l.type!=="shorthand_property_identifier")return;let c=l.text,d=gl(l,c,n);if(!d||d.kind==="other")return;let m=rt(a).nameNode,f={name:c,line:l.startPosition.row+1,column:l.startPosition.column,via:i,callee:yl(a),callLine:m.startPosition.row+1,callColumn:m.startPosition.column,b:d.kind};d.kind==="fn"?f.declLine=d.declLine:(f.src=d.imp.source,f.ik=d.imp.kind,f.imp=d.imp.imported),s.push(f)};return(function r(i){if(i.type==="call_expression"){let a=i.childForFieldName("arguments");for(let l of a?.namedChildren??[]){let c=le(l);if(c)if(c.type==="array")for(let d of c.namedChildren)o(d,"array",i);else if(c.type==="object")for(let d of c.namedChildren)d.type==="pair"?o(d.childForFieldName("value"),"object",i):d.type==="shorthand_property_identifier"&&o(d,"object",i);else o(c,"arg",i)}}for(let a of i.namedChildren)r(a)})(e.rootNode),s}function mr(e){let t=[],n=o=>{let r=o?.namedChildren.find(i=>i.type!=="comment");return r?.type==="type_identifier"?r.text:null},s=o=>{let r=o.childForFieldName("name")?.text,i=o.childForFieldName("body");if(!(!r||!i)){for(let a of i.namedChildren)if(a.type==="public_field_definition"){let l=a.childForFieldName("name"),c=n(a.childForFieldName("type"));l?.type==="property_identifier"&&c&&t.push({className:r,prop:l.text,type:c})}else if(a.type==="method_definition"&&a.childForFieldName("name")?.text==="constructor")for(let l of a.childForFieldName("parameters")?.namedChildren??[]){if(l.type!=="required_parameter"&&l.type!=="optional_parameter"||!l.namedChildren.some(m=>m.type==="accessibility_modifier")&&!l.children.some(m=>m.type==="readonly"))continue;let c=l.childForFieldName("pattern"),d=n(l.childForFieldName("type"));c?.type==="identifier"&&d&&t.push({className:r,prop:c.text,type:d})}}};for(let o of e.rootNode.namedChildren){let r=o.type==="export_statement"?o.childForFieldName("declaration"):o;r&&(r.type==="class_declaration"||r.type==="abstract_class_declaration")&&s(r)}return t}var xl={Get:"get",Post:"post",Put:"put",Patch:"patch",Delete:"delete",All:"all"};function hr(e){let t=e.namedChildren[0];if(!t)return null;if(t.type==="call_expression"){let n=t.childForFieldName("function"),s=n?.type==="identifier"?n.text:null;return s?{name:s,args:t.childForFieldName("arguments")}:null}return t.type==="identifier"?{name:t.text,args:null}:null}var ut=e=>e?e.type==="string"?e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join(""):e.type==="template_string"&&!e.namedChildren.some(t=>t.type==="template_substitution")?e.text.slice(1,-1):null:null;function gr(e){let t=e?.namedChildren.find(n=>n.type!=="comment");if(!t)return"";if(t.type==="array")return ut(t.namedChildren.find(n=>n.type!=="comment"))??"";if(t.type==="object"){for(let n of t.namedChildren){if(n.type!=="pair")continue;let s=n.childForFieldName("key");if(s?.text==="path"||s?.text==="'path'"||s?.text==='"path"'){let o=n.childForFieldName("value");return(o?.type==="array"?ut(o.namedChildren[0]):ut(o))??""}}return""}return ut(t)??""}var xn=(...e)=>"/"+e.map(n=>String(n??"").replace(/^\/+|\/+$/g,"")).filter(Boolean).join("/");function yr(e){let t=[],n=(s,o)=>{let r=s.childForFieldName("name")?.text,i=s.childForFieldName("body");if(!r||!i)return;let l=[...o,...s.namedChildren.filter(m=>m.type==="decorator")].map(hr).filter(Boolean).find(m=>m.name==="Controller");if(!l)return;let c=gr(l.args),d=[];for(let m of i.namedChildren)if(m.type!=="comment"){if(m.type==="decorator"){d.push(m);continue}if(m.type==="method_definition"){let f=m.childForFieldName("name")?.text;for(let u of d.map(hr).filter(Boolean)){let p=xl[u.name];!p||!f||t.push({method:p,path:xn(c,gr(u.args)),startLine:m.startPosition.row+1,handlerName:null,isInlineHandler:!1,handlerStartLine:null,handlerEndLine:null,handlerStartIndex:null,handlerEndIndex:null,nest:{className:r,methodName:f}})}}d=[]}};for(let s of e.rootNode.namedChildren)if(s.type==="export_statement"){let o=s.childForFieldName("declaration");o&&(o.type==="class_declaration"||o.type==="abstract_class_declaration")&&n(o,s.namedChildren.filter(r=>r.type==="decorator"))}else(s.type==="class_declaration"||s.type==="abstract_class_declaration")&&n(s,[]);return t}function xr(e){let t=[];return(function n(s){if(s.type==="call_expression"){let o=s.childForFieldName("function");if(o?.type==="member_expression"&&o.childForFieldName("property")?.text==="setGlobalPrefix"){let r=(s.childForFieldName("arguments")?.namedChildren??[]).filter(c=>c.type!=="comment"),i=r[0]?ut(r[0]):null,a=[],l=r[1];if(l?.type==="object")for(let c of l.namedChildren){if(c.type!=="pair"||c.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")!=="exclude")continue;let d=c.childForFieldName("value");for(let m of d?.type==="array"?d.namedChildren:[])if(m.type==="object"){for(let f of m.namedChildren)if(f.type==="pair"&&f.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")==="path"){let u=ut(f.childForFieldName("value"));u!=null&&a.push(u)}}else{let f=ut(m);f!=null&&a.push(f)}}t.push({prefix:i||null,exclude:a})}}for(let o of s.namedChildren)n(o)})(e.rootNode),t}function vr(e){let t=[];for(let r of e.values())for(let i of r?.globalPrefix??[])t.push(i);if(!t.length||t.some(r=>!r.prefix||r.prefix!==t[0].prefix))return e;let n=t[0].prefix,s=new Set(t.flatMap(r=>r.exclude).map(r=>xn(r))),o=new Map;for(let[r,i]of e){if(!i?.routes?.some(a=>a.nest)){o.set(r,i);continue}o.set(r,{...i,routes:i.routes.map(a=>a.nest&&!s.has(xn(a.path))?{...a,path:xn(n,a.path)}:a)})}return o}import vl from"node:crypto";var wr=e=>vl.createHash("sha256").update(e).digest("hex");function wl(e,t=null){let n=[],s=o=>{if(o.childCount===0){if(o.type==="comment")return;let r=t?t.slice(o.startIndex,o.endIndex):o.text,i=o.type==="jsx_text"?r.replace(/\s+/g," ").trim():r;if(i==="")return;n.push({s:o.startIndex,e:o.endIndex,t:i});return}for(let r=0;r<o.childCount;r++)s(o.child(r))};return s(e),n}function Sr(e,t){let n=[];for(let r of[t.functions,t.arrowFunctions,t.classMethods])for(let i of r??[])i.startIndex!=null&&n.push({s:i.startIndex,e:i.endIndex,item:i,field:"bodyHash"});for(let r of[t.routes,t.listeners,t.socketListeners])for(let i of r??[])i.isInlineHandler&&i.handlerStartIndex!=null&&n.push({s:i.handlerStartIndex,e:i.handlerEndIndex,item:i,field:"handlerBodyHash"});let s=new Map(n.map(r=>[r,[]])),o=[];for(let r of wl(e.rootNode,e.canopyOriginalSource??null)){let i=null,a=1/0;for(let l of n)r.s>=l.s&&r.e<=l.e&&l.e-l.s<a&&(i=l,a=l.e-l.s);(i?s.get(i):o).push(r.t)}for(let r of n)r.item[r.field]=wr(s.get(r).join(" "));t.moduleBodyHash=wr(o.join(" "))}function kr(e,t){return oe(t,"matchFastifyRoutes.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(c=>c.name==="http_method"),i=o.captures.find(c=>c.name==="route_path"),a=o.captures.find(c=>c.name==="handler_ref"),l=o.captures.find(c=>c.name==="handler_inline");return{method:r.node.text,path:i.node.text,startLine:r.node.startPosition.row+1,handlerName:a?a.node.text:null,isInlineHandler:!!l,handlerStartLine:l?l.node.startPosition.row+1:null,handlerEndLine:l?l.node.endPosition.row+1:null,handlerStartIndex:l?l.node.startIndex:null,handlerEndIndex:l?l.node.endIndex:null}})}function Nr(e,t){return oe(t,"matchExtensionListeners.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(p=>p.name==="event_type"),i=o.captures.find(p=>p.name==="event_name"),a=o.captures.find(p=>p.name==="method_name"||p.name==="listener_method"),l=o.captures.find(p=>p.name==="handler_ref"),c=o.captures.find(p=>p.name==="target"),d=o.captures.find(p=>p.name==="root_object"),m=o.captures.find(p=>p.name==="sub_object"),f=c?c.node.text:d?d.node.text+(m?"."+m.node.text:""):null,u=o.captures.find(p=>p.name==="handler_inline");return{eventName:r?.node.text??i?.node.text??"unknown",targetName:f,startLine:a.node.startPosition.row+1,handlerName:l?l.node.text:null,isInlineHandler:!!u,handlerStartLine:u?u.node.startPosition.row+1:null,handlerEndLine:u?u.node.endPosition.row+1:null,handlerStartIndex:u?u.node.startIndex:null,handlerEndIndex:u?u.node.endIndex:null}})}import _l from"node:fs";De();import Be from"node:fs";import ie from"node:path";import Sl from"node:os";import _r from"node:crypto";import{fileURLToPath as kl}from"node:url";var Nl=ie.dirname(kl(globalThis.__canopyUrl("src/stage2_parse/parseCache.js"))),$r=ie.join(Nl,"..",".."),bo=process.env.CANOPY_CACHE_DIR||(jt()?ie.join(Sl.homedir(),".canopy-cache"):ie.join($r,".canopy-cache")),br=e=>_r.createHash("sha256").update(e).digest("hex");function vn(e,t){return Be.readdirSync(e,{withFileTypes:!0}).flatMap(n=>n.isDirectory()?vn(ie.join(e,n.name),t):t.some(s=>n.name.endsWith(s))?[ie.join(e,n.name)]:[]).sort()}var _o=null;function bl(){if(_o)return _o;let e=ie.join($r,"src"),t=!Be.existsSync(e)&&globalThis.__canopyBundle,n=t?[t,...vn(ie.join(ie.dirname(t),"queries"),[".scm"])]:[...vn(ie.join(e,"stage2_parse"),[".js",".scm"]),...vn(ie.join(e,"stage5_entrypoints"),[".js"]).filter(o=>/match/i.test(ie.basename(o))),ie.join(e,"utils","loadQuery.js")],s=_r.createHash("sha256");for(let o of n)s.update(ie.relative(t?ie.dirname(t):e,o).split(ie.sep).join("/")).update("\0").update(Be.readFileSync(o).toString("utf8").replace(/\r\n/g,`
17
+ `)).update("\0");for(let o of["web-tree-sitter","tree-sitter-javascript","tree-sitter-typescript"])try{s.update(o+"@"+JSON.parse(Be.readFileSync(ie.join(Ae(o),"package.json"),"utf8")).version)}catch{s.update(o+"@?")}return _o=s.digest("hex").slice(0,16)}function Ir(){let e=bl(),t=ie.join(bo,e);Be.mkdirSync(t,{recursive:!0});for(let n of Be.readdirSync(bo,{withFileTypes:!0}))n.isDirectory()&&n.name!==e&&Be.rmSync(ie.join(bo,n.name),{recursive:!0,force:!0});return{version:e,keyFor:(n,s="javascript")=>br(s==="javascript"?n:Buffer.concat([Buffer.from(s+"\0"),n])),get(n){try{return JSON.parse(Be.readFileSync(ie.join(t,n+".json"),"utf8"))}catch{return null}},set(n,s){let o=ie.join(t,`${n}.${process.pid}.tmp`);Be.writeFileSync(o,JSON.stringify(s)),Be.renameSync(o,ie.join(t,n+".json"))}}}function Fr(e){return JSON.parse(JSON.stringify(e,(t,n)=>n&&typeof n=="object"&&n.startPosition&&n.endPosition&&"type"in n&&"tree"in n?void 0:n))}var jr=Number(process.env.CANOPY_PARSE_BUDGET_MS)||3e4,Io=class extends Error{constructor(t){super(`parse time budget exceeded (limit ${jr/1e3} s; stopped after ${(t/1e3).toFixed(1)} s)`),this.name="ParseBudgetError"}},$l=100;function $o(e,t,n){return e.map(s=>({...s,returns:er(t,n,s)}))}function Cr(e,t,n,{cache:s=!0,onProgress:o=console.log,grammars:r=null}={}){let i=new Map,a=0,l=0,c=0,d=s?Ir():null,m=[],f=0;for(let u of e){f>0&&f%$l===0&&o(` parsing: ${f}/${e.length} files (${c} from cache)`),f++;try{let p=_l.readFileSync(u),h=xo(u),v=d?.keyFor(p,h),g=d?d.get(v):null;if(g){i.set(u,g),c++;continue}l++;let w=performance.now(),S=()=>{let D=performance.now()-w;if(D>jr)throw new Io(D)},k=h==="javascript"?{parser:t,language:n}:r?.get(h);if(!k)throw new Error(`no ${h} grammar loaded`);let y=k.language;Bs(h);let{tree:x}=As(k.parser,u);S();let b=[],N=(D,R,G=[])=>{try{return R()}catch(ee){if(ee.name==="ParseBudgetError")throw ee;return b.push({extractor:D,message:String(ee.message).slice(0,160)}),G}},$=N("functionDeclarations",()=>$o(Gs(x,y),x,y));S();let F=N("arrowFunctions",()=>$o(Js(x,y),x,y));S();let H=N("classMethods",()=>$o(Ks(x,y),x,y));S();let P=N("importBindings",()=>dr(x)),K={functions:$,arrowFunctions:F,classMethods:H,imports:N("imports",()=>[...Vs(x,y),...fr(x)]),calls:(S(),N("calls",()=>Xs(x,y))),methodCalls:(S(),N("methodCalls",()=>Ys(x,y))),returnEntries:N("returnEntries",()=>Zs(x,y)),jsxElements:N("jsxElements",()=>tr(x,y)),callSites:(S(),N("callSites",()=>ar(x))),apiCalls:(S(),N("apiCalls",()=>nr(x,y))),socketEmits:N("socketEmits",()=>or(x,y)),socketListeners:N("socketListeners",()=>ir(x,y)),rawSocketSends:N("rawSocketSends",()=>sr(x,y)),rawSocketTypeChecks:N("rawSocketTypeChecks",()=>rr(x,y)),routes:N("routes",()=>[...kr(x,y),...st(y)?yr(x):[]]),listeners:N("listeners",()=>Nr(x,y)),refArgs:N("refArgs",()=>pr(x,P)),globalPrefix:N("globalPrefix",()=>xr(x)),importBindings:P,classProps:N("classProps",()=>st(y)?mr(x):[]),httpClients:N("httpClients",()=>lr(x),null),exportBindings:N("exportBindings",()=>ur(x),null),hadErrors:vo(x),exportedNames:N("exports",()=>Qs(x,y)),failed:!1,warnings:b};N("bodyHash",()=>Sr(x,K),null);let U=Fr(K);d&&d.set(v,U),i.set(u,U)}catch(p){if(p.name==="ParseBudgetError"){m.push({filePath:u,reason:p.message}),i.set(u,{functions:[],arrowFunctions:[],classMethods:[],imports:[],calls:[],methodCalls:[],returnEntries:[],jsxElements:[],callSites:[],apiCalls:[],socketEmits:[],socketListeners:[],rawSocketSends:[],rawSocketTypeChecks:[],routes:[],listeners:[],hadErrors:!1,failed:!1,skipped:p.message}),console.warn(` ! Skipped ${u}: ${p.message}`);continue}a++,i.set(u,{functions:[],arrowFunctions:[],classMethods:[],imports:[],calls:[],methodCalls:[],returnEntries:[],jsxElements:[],callSites:[],apiCalls:[],socketEmits:[],socketListeners:[],rawSocketSends:[],rawSocketTypeChecks:[],routes:[],listeners:[],hadErrors:!0,failed:!0,errorMessage:p.message}),console.warn(` ! Failed to parse ${u}: ${p.message}`)}}return console.log(`Parsed ${i.size} files (${a} failed)`),console.log(` parse cache: ${l} file(s) parsed, ${c} served from cache`),i.cacheStats={parsed:l,cacheHits:c},i.budgetSkips=m,i}function wn(e,t){return`${e}::${t}`}var Er=[{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 Sn(e){let t=e.toLowerCase().replace(/\\/g,"/");for(let{category:n,patterns:s}of Er)for(let o of s)if(t.includes(o))return n;return"unknown"}import Fo from"node:fs";import ve from"node:path";import kn from"node:fs";import Xe from"node:path";var Il=["index.html","public/index.html","src/index.html"],Fl=/^(build|esbuild|vite\.config|webpack\.config|rollup\.config|bundle)[\w.-]*\.(mjs|cjs|js|ts)$/i;function jl(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 Cl(e){let t=[],n=[];try{n=kn.readdirSync(e).filter(s=>Fl.test(s)).sort()}catch{return t}for(let s of n){let o;try{o=kn.readFileSync(Xe.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 Nn(e,t,n=new Set(t.map(s=>Xe.resolve(s)))){for(let s of Il){let o=Xe.join(e,s);if(!kn.existsSync(o))continue;let r;try{r=kn.readFileSync(o,"utf8")}catch{continue}let i=Xe.dirname(o),a=d=>{let m=d.split(/[?#]/)[0];return!m||/^([a-z]+:)?\/\//i.test(m)?null:Xe.resolve(m.startsWith("/")?Xe.join(e,m):Xe.join(i,m))},l=jl(r).map(d=>({s:d,p:a(d)})).filter(d=>d.p);for(let{s:d,p:m}of l)if(n.has(m))return{indexHtml:o,script:d,entry:m,via:"script"};let c=Cl(e);for(let{s:d,p:m}of l)for(let f of c){if(!f.outfile||Xe.resolve(e,f.outfile)!==m)continue;let u=Xe.resolve(e,f.entry);if(n.has(u))return{indexHtml:o,script:d,entry:u,via:`${f.config} (outfile ${f.outfile})`}}}return null}var El=new Set(["test","tests","__tests__","fixtures","__fixtures__","__mocks__","e2e","cypress"]);function Lt(e){let t=String(e).replace(/\\/g,"/").split("/").filter(Boolean);if(!t.length)return!1;for(let n of t.slice(0,-1))if(El.has(n.toLowerCase()))return!0;return/\.(test|spec)\.[^./]+$/i.test(t[t.length-1])}function Pl(e){let t=ve.join(e,"package.json");if(!Fo.existsSync(t))return null;try{return JSON.parse(Fo.readFileSync(t,"utf-8"))}catch{return null}}function Ll(e){return[...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{})]}function Tl(e){let t=!!e.workspaces,n=Object.keys(e.dependencies??{}).length>0,s=!!(e.scripts&&e.scripts.start);return t&&!n&&!s}var Rl=["react","vue","svelte","next","vite","webpack","parcel"],Al=["express","fastify","koa","hapi","socket.io","ws"],Ol=[{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 Ml(e){let t=e.some(s=>Rl.includes(s)),n=e.some(s=>Al.includes(s));return t&&!n?"client":n&&!t||n&&t?"server":"unknown"}function Hl(e){let t=[];for(let{deps:n,label:s}of Ol)n.some(o=>e.includes(o))&&!t.includes(s)&&t.push(s);return t}function Pr(e){let t=new Set(["node_modules",".git","dist","build",".next","coverage"]);try{return Fo.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!t.has(n.name)&&!n.name.startsWith(".")).map(n=>ve.join(e,n.name))}catch{return[]}}function Lr(e,t=null){let n=[e];for(let o of Pr(e)){n.push(o);for(let r of Pr(o))n.push(r)}let s=[];for(let o of n){let r=Pl(o);if(!r||Tl(r))continue;let i=Ll(r);s.push({name:r.name||ve.basename(o),rootPath:o,isRepoRoot:ve.resolve(o)===ve.resolve(e),kind:Ml(i),datastores:Hl(i)})}if(t){let o=new Set(t.map(i=>ve.resolve(i))),r=new Set(s.map(i=>ve.resolve(i.rootPath)));for(let i of n)ve.resolve(i)===ve.resolve(e)||r.has(ve.resolve(i))||Lt(ve.relative(e,i)+"/x")||Nn(i,t,o)&&s.push({name:ve.basename(i),rootPath:i,isRepoRoot:!1,kind:"client",datastores:[],webRoot:!0})}return s}function pt(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+ve.sep))&&o.rootPath.length>s&&(n=o.name,s=o.rootPath.length);return n}var Dl=5,Bl=.1;function Tr(e,t,n){let s=ve.basename(ve.resolve(n)),o=l=>({name:l,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(l=>!pt(l,e)).length;if(r<Dl||r<Bl*t.length)return{services:e,added:null,leftover:r};let i=e.find(l=>l.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 a=s;return e.some(l=>l.name.toLowerCase()===a.toLowerCase())&&(a=`${s} (root)`),{services:[...e,o(a)],added:{name:a,reason:`${r} of ${t.length} files sit outside every nested package: owned by a service named after the repo folder`,leftover:r}}}function Rr(e,t=[]){let n=[];for(let[s,o]of e){let r=Sn(s),i=pt(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 a of o.functions)n.push({id:wn(s,a.name),name:a.name,filePath:s,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:r,serviceName:i,bodyHash:a.bodyHash??null,type:"function"});for(let a of o.arrowFunctions)n.push({id:wn(s,a.name),name:a.name,filePath:s,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:r,serviceName:i,bodyHash:a.bodyHash??null,type:"arrowFunction"});for(let a of o.classMethods)n.push({id:wn(s,`${a.className}.${a.methodName}`),name:a.methodName,className:a.className,filePath:s,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:r,serviceName:i,bodyHash:a.bodyHash??null,type:"classMethod"})}return n}function Ue(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 a=(s.get(i)??0)+1;s.set(i,a),o.set(r,`${e}::${i}${a>1?`#${a}`:""}`)}return o}function Ar(e,t=[]){let n=[];for(let[s,o]of e){let r=Sn(s),i=pt(s,t),a=t.find(c=>c.name===i),l=Ue(s,o);for(let c of o.routes??[]){if(!c.isInlineHandler)continue;let d=`${c.method.toUpperCase()} ${c.path}`;n.push({id:l.get(c),name:`${d} (inline handler)`,filePath:s,startLine:c.handlerStartLine??c.startLine,endLine:c.handlerEndLine??c.startLine,category:r,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:c.handlerBodyHash??null,trigger:{type:"route",label:d,resolvedVia:"inline"}})}for(let c of o.listeners??[])c.isInlineHandler&&n.push({id:l.get(c),name:`${c.eventName} (inline handler)`,filePath:s,startLine:c.handlerStartLine??c.startLine,endLine:c.handlerEndLine??c.startLine,category:r,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:c.handlerBodyHash??null,trigger:{type:"listener",label:c.eventName,resolvedVia:"inline"}});if(a?.kind==="server")for(let c of o.socketListeners??[])c.isInlineHandler&&n.push({id:l.get(c),name:`${c.eventName} (inline handler)`,filePath:s,startLine:c.handlerStartLine??c.startLine,endLine:c.handlerEndLine??c.startLine,category:r,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:c.handlerBodyHash??null,trigger:{type:"socketListener",label:c.eventName,resolvedVia:"inline"}})}return n}import Ul from"node:fs";import zl from"node:crypto";var Or=e=>zl.createHash("sha256").update(e).digest("hex");function bn(e,t){return e.map(n=>[t(n),Or(Ul.readFileSync(n))]).sort((n,s)=>n[0]<s[0]?-1:n[0]>s[0]?1:0)}function _n(e){return Or(e.map(([t,n])=>`${t}\0${n}`).join(`
18
+ `))}import jo from"node:path";function $n(e){let t=jo.resolve(e),n=t.split(jo.sep).join("/"),s=[[t.toLowerCase(),t.length,jo.sep],[n.toLowerCase(),n.length,"/"]],o=r=>{if(typeof r!="string")return r;let i=r.toLowerCase();if(i===s[0][0]||i===s[1][0])return".";for(let[a,l,c]of s)if(i.startsWith(a+c)){let d=r.slice(l+1),m=d.indexOf("::");return(m<0?d:d.slice(0,m)).split("\\").join("/")+(m<0?"":d.slice(m))}return r};return{rel:o,repoRoot:n,replacer:(r,i)=>typeof i=="string"?o(i):i,json:(r,i)=>JSON.stringify(r,(a,l)=>typeof l=="string"?o(l):l,i),clone:r=>JSON.parse(JSON.stringify(r,(i,a)=>typeof a=="string"?o(a):a))}}function Mr(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 Hr(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 ue(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 Dr(e,t){let n=[];for(let[o,r]of e){let i=t.filter(a=>a.filePath===o);for(let a of r.calls){let l=ue(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"call",callKind:a.callKind??"call",resolved:!1})}for(let a of r.methodCalls){let l=ue(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.methodName,objectNameRaw:a.objectName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"methodCall",callKind:a.callKind??"methodCall",resolved:!1})}for(let a of r.returnEntries??[]){let l=ue(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.label,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],deferred:a.deferred??!1,type:"returnValue",resolved:!1})}for(let a of r.jsxElements){let l=ue(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,type:"call",callKind:"jsx",resolved:!1})}for(let a of r.callSites??[]){let l=ue(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"callSite",callKind:a.callKind,chainHead:a.chainHead??null,chainHeadCalled:a.chainHeadCalled??!1,ctorName:a.ctorName??null,...a.thisProp?{thisProp:a.thisProp,thisMethod:a.thisMethod}:{},resolved:!1})}for(let a of r.socketEmits){let l=ue(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,eventName:a.eventName,line:a.startLine,type:"socketEmit",resolved:!1})}for(let a of r.rawSocketSends??[]){let l=ue(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,eventName:a.eventName,line:a.startLine,type:"rawSocketSend",resolved:!1})}for(let a of r.apiCalls){let l=ue(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,url:a.url,httpMethod:a.method,scope:a.scope,line:a.startLine,type:"apiCall",resolved:!1})}}let s=n.filter(o=>o.type==="apiCall").length;return n}function de(e,t){let n=new Map;for(let s of t)s.filePath===e&&n.set(s.name,s.id);return n}function Jt(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,a=([,c])=>{let d=o?o.scopeOf(c):de(c,t);return d.has(e.calleeNameRaw)?{...e,targetNodeId:d.get(e.calleeNameRaw),confidence:.85,matchType:"import",resolved:!0}:null};for(let c=0;c<i;c++){let d=a(r[c]);if(d)return d}let l=o?.bind?.resolveName(e.fromFileId,e.calleeNameRaw);if(l)return{...e,targetNodeId:l.id,confidence:.85,matchType:"import",resolved:!0};for(let c=i;c<r.length;c++){let d=a(r[c]);if(d)return d}return{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function Br(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 Ur(e){return{...e,targetNodeId:null,confidence:0,matchType:"unresolvedExternal",resolved:!1}}function zr(e,t,n,s,o=null){if(e.callKind==="new"&&e.ctorName){let r=Jt({...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()]),a=o?o.ctorsOf(e.ctorName).find(l=>i.has(l.filePath)):t.find(l=>l.type==="classMethod"&&l.className===e.ctorName&&l.name==="constructor"&&i.has(l.filePath));return a?{...e,targetNodeId:a.id,confidence:a.filePath===e.fromFileId?.9:.8,matchType:(a.filePath===e.fromFileId?"local":"import")+"New",resolved:!0}:Ur(e)}if(e.callKind==="chainedCall"&&e.chainHead&&e.chainHeadCalled){let r=Jt({...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 Ur(e)}import Eo from"node:path";import Ye from"node:fs";import q from"node:path";var Jr=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Wl=["index.ts","index.tsx","index.mts","index.cts","index.js","index.jsx","index.mjs","index.cjs"],ql={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]};var Kr=null,Vr=e=>{Kr=e},Xr=()=>Kr,Wr=e=>q.resolve(e);function Kt(e,t){e=q.resolve(e);let n=()=>{try{let i=q.join(e,"package.json");if(!Ye.existsSync(i))return null;let a=JSON.parse(Ye.readFileSync(i,"utf8")).main;if(typeof a!="string")return null;let l=q.resolve(e,a);return t.has(l)?l:Gl(l,t)}catch{return null}},s=q.extname(e);if(s&&t.has(e))return e;let o=ql[s];if(o)for(let i of o){let a=e.slice(0,-s.length)+i;if(t.has(a))return a}for(let i of Jr)if(t.has(e+i))return e+i;let r=n();if(r)return r;for(let i of Wl){let a=q.join(e,i);if(t.has(a))return a}return null}function Gl(e,t){if(q.extname(e)&&t.has(e))return e;for(let s of Jr)if(t.has(e+s))return e+s;return null}var Co=e=>{try{let n=Ye.readFileSync(e,"utf8").replace(/^/,"").replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,(s,o)=>o??"");return JSON.parse(n.replace(/,(\s*[}\]])/g,"$1"))}catch{return null}};function Yr(e,t=new Set){if(t.has(e))return{baseUrl:null,paths:null};t.add(e);let n=Co(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 a of r){if(typeof a!="string"||!a.startsWith("."))continue;let l=q.resolve(q.dirname(e),a);(!Ye.existsSync(l)||Ye.statSync(l).isDirectory())&&(l=Ye.existsSync(l+".json")?l+".json":q.join(l,"tsconfig.json"));let c=Yr(l,t);c.baseUrl&&(s=c.baseUrl),c.paths&&(o=c.paths)}let i=n.compilerOptions??{};if(typeof i.baseUrl=="string"&&(s=q.resolve(q.dirname(e),i.baseUrl)),i.paths&&typeof i.paths=="object"){let a=s??q.dirname(e);o=Object.entries(i.paths).map(([l,c])=>{let d=l.indexOf("*");return{prefix:d<0?l:l.slice(0,d),suffix:d<0?"":l.slice(d+1),wildcard:d>=0,targets:(Array.isArray(c)?c:[]).filter(m=>typeof m=="string").map(m=>q.resolve(a,m))}}).sort((l,c)=>c.prefix.length-l.prefix.length)}return{baseUrl:s,paths:o}}function Jl(e,t){if(t=t.replace(/^\.\//,"").replace(/\/+$/,""),t.startsWith("!"))return[];let n=[],s=o=>{try{return Ye.readdirSync(o,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="node_modules"&&!r.name.startsWith(".")).map(r=>q.join(o,r.name))}catch{return[]}};if(t.endsWith("/**")){let o=q.join(e,t.slice(0,-3)),r=i=>{for(let a of s(i))n.push(a),r(a)};r(o)}else t.endsWith("/*")?n.push(...s(q.join(e,t.slice(0,-2)))):t.includes("*")||n.push(q.join(e,t));return n}function Kl(e){let t=[],s=Co(q.join(e,"package.json"))?.workspaces;Array.isArray(s)?t.push(...s):Array.isArray(s?.packages)&&t.push(...s.packages);try{let o=Ye.readFileSync(q.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 a=/^\s*-\s*['"]?([^'"#\s]+)['"]?/.exec(i);a?t.push(a[1]):/^\S/.test(i)&&(r=!1)}}}catch{}return t}function qr(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 Zr(e,t,n={}){let s=Wr(e),o=new Set(t),r=new Map,i=f=>{if(r.has(f))return r.get(f);let u=null,p=q.join(f,"tsconfig.json");return Ye.existsSync(p)?u=Yr(p):f!==s&&q.dirname(f)!==f&&f.startsWith(s)&&(u=i(q.dirname(f))),r.set(f,u),u},a=new Map;for(let f of Kl(s))for(let u of Jl(s,f)){let p=Co(q.join(u,"package.json"));p?.name&&!a.has(p.name)&&a.set(p.name,{dir:Wr(u),pkg:p})}let l=[...a.keys()].sort((f,u)=>u.length-f.length),c=(f,u,p)=>{let{dir:h,pkg:v}=a.get(f),g=[],w=S=>{if(!S)return;let k=q.resolve(h,S);g.push(k);let y=q.relative(h,k).split(q.sep);["dist","build","lib","out","esm","cjs"].includes(y[0])&&g.push(q.join(h,"src",...y.slice(1)))};if(u==="."){w(qr(v.exports,"."));for(let S of["source","module","main"])typeof v[S]=="string"&&w(v[S]);g.push(q.join(h,"src","index"),q.join(h,"index"))}else w(qr(v.exports,u)),g.push(q.join(h,u),q.join(h,"src",u));for(let S of g){let k=Kt(S,p);if(k)return k}return null},d=f=>l.find(u=>f===u||f.startsWith(u+"/"))??null,m=(f,u)=>u?.paths?.some(p=>p.wildcard?f.startsWith(p.prefix)&&f.endsWith(p.suffix)&&f.length>=p.prefix.length+p.suffix.length:f===p.prefix)??!1;return{root:s,files:o,packages:a,isInternal(f,u){if(f.startsWith(".")||d(f))return!0;let p=i(q.dirname(u));return!!(m(f,p)||p?.baseUrl&&!f.startsWith("@")&&Kt(q.join(p.baseUrl,f),o))},resolve(f,u,p){if(f.startsWith("."))return Kt(q.resolve(q.dirname(u),f),p);let h=i(q.dirname(u));if(h?.paths&&n.paths!==!1)for(let g of h.paths){let w=null;if(g.wildcard?f.startsWith(g.prefix)&&f.endsWith(g.suffix)&&f.length>=g.prefix.length+g.suffix.length&&(w=f.slice(g.prefix.length,f.length-g.suffix.length)):f===g.prefix&&(w=""),w!=null){for(let S of g.targets){let k=Kt(S.replace("*",w),p);if(k)return k}break}}let v=n.workspaces===!1?null:d(f);if(v){let g=c(v,f===v?".":"./"+f.slice(v.length+1),p);if(g)return g}if(h?.baseUrl&&n.paths!==!1){let g=Kt(q.join(h.baseUrl,f),p);if(g)return g}return null}}}var Gr=new WeakMap;function Qr(e){if(e instanceof Set)return e;let t=Gr.get(e);return t||Gr.set(e,t=new Set(e)),t}function Po(e,t,n){if(!e.startsWith("."))return null;let s=Eo.dirname(t),o=Eo.resolve(s,e),r=[o,...ks().map(i=>`${o}${i}`),...Ns().map(i=>Eo.join(o,i))];for(let i of r)if(n.includes(i))return i;return null}function ze(e,t,n){let s=Po(e,t,n);if(s)return s;let o=Xr();return o?o.resolve(e,t,Qr(n)):null}function Tt(e,t,n){let s=new Map;for(let o of t){let r=Po(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=ze(o.source,e,n);r&&s.set(o.source,r)}return s}function ei(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=de(o,e),t.set(o,r)),r},method:(o,r)=>n.get(o+"\0"+r),ctorsOf:o=>s.get(o)??[]}}function Rt(e){return e?e.split("?")[0].split("/").map(t=>t.startsWith(":")||/^\d+$/.test(t)?"*":t).join("/"):""}var Vl=new Set(["function","arrowFunction"]);function ti(e,t,n,s){let o=new Map;for(let c of t){let d=o.get(c.filePath);d||o.set(c.filePath,d=[]),d.push(c)}let r=new Set;for(let c of s)c.resolved&&c.fromNodeId&&c.targetNodeId&&r.add(c.fromNodeId+"\0"+c.targetNodeId);let i=(c,d)=>(o.get(c)??[]).find(m=>Vl.has(m.type)&&d(m))??null,a=[];a.argBindings=[];let l=(c,d,m,f,u,p,h)=>{!d||!m||d.id===m.id||r.has(d.id+"\0"+m.id)||a.push({fromFileId:c,fromNodeId:d.id,calleeNameRaw:f,line:u,column:p,branchPath:[],firstArgText:null,deferred:!1,type:"reference",callKind:"reference",targetNodeId:m.id,confidence:h==="local"?.95:.85,matchType:h,resolved:!0})};for(let[c,d]of e){let m=o.get(c);if(m){for(let f of d.refArgs??[]){let u=null,p="local";if(f.b==="fn"?u=i(c,v=>v.name===f.name&&v.startLine===f.declLine):f.b==="import"&&(p="import",(f.ik==="default"||f.ik==="named"||f.ik==="cjs")&&(u=n.nodeForImport(c,f.src,f.ik,f.imp))),!u)continue;let h=ue(f.line,m);l(c,h,u,f.name,f.line,f.column,p),f.callLine!=null&&h&&h.id!==u.id&&a.argBindings.push({file:c,line:f.callLine,column:f.callColumn,targetNodeId:u.id,matchType:p,direct:f.via==="arg"})}for(let f of m){if(f.type!=="inlineHandler")continue;let u=null;for(let p of m)p===f||p.type==="moduleRoot"||p.startLine<=f.startLine&&p.endLine>=f.endLine&&!(p.startLine===f.startLine&&p.endLine===f.endLine)&&(!u||p.endLine-p.startLine<u.endLine-u.startLine)&&(u=p);u??=m.find(p=>p.type==="moduleRoot"),l(c,u,f,f.name,f.startLine,0,"local")}}}return a}function ni(e,t,n,s){let o=new Map,r=new Map;for(let a of e){if(r.set(a.id,a),a.type!=="classMethod")continue;let l=a.filePath+"\0"+a.className+"\0"+a.name,c=o.get(l);c?c.push(a):o.set(l,[a])}let i=(a,l)=>{for(let c of o.keys())if(c.startsWith(a+"\0"+l+"\0"))return!0;return!1};return function(l){let c=r.get(l.fromNodeId);if(!c||c.type!=="classMethod")return null;let d=t.get(l.fromFileId),m=(d?.classProps??[]).find(v=>v.className===c.className&&v.prop===l.thisProp);if(!m)return null;let f=null,u=null,p=(d.importBindings??[]).find(v=>v.local===m.type);if(p){let v=p.kind==="default"||p.kind==="named"?s.resolveImport(l.fromFileId,p.source,p.kind,p.imported):null;v?.local&&v.local!=="default"&&(f=v.file,u=v.local)}else i(l.fromFileId,m.type)&&(f=l.fromFileId,u=m.type);if(!f)return null;let h=o.get(f+"\0"+u+"\0"+l.thisMethod);return!h||h.length!==1?null:{...l,targetNodeId:h[0].id,confidence:.9,matchType:"typedProperty",resolved:!0}}}var Xl=new Set(["function","arrowFunction"]);function In(e,t,n){let s=new Map;for(let d of e){if(!Xl.has(d.type))continue;let m=d.filePath+"\0"+d.name;s.has(m)||s.set(m,d)}let o=new Map,r=(d,m)=>{let f=o.get(d);if(!f){f=new Map;for(let u of t.get(d)?.importBindings??[])f.has(u.local)||f.set(u.local,u);o.set(d,f)}return f.get(m)??null},i=(d,m)=>n(d).get(m)??null;function a(d,m,f=new Set){let u=d+"\0"+m;if(f.has(u))return null;f.add(u);let p=t.get(d)?.exportBindings;if(!p)return null;if(m==="default"){if(p.default)return{file:d,local:p.default==="<anon>"?"default":p.default}}else if(p.named?.[m])return{file:d,local:p.named[m]};for(let h of p.reexports??[]){if(h.exported!==m)continue;let v=i(d,h.source);if(v)return a(v,h.imported,f)}for(let h of p.nsReexports??[]){if(h.exported!==m)continue;let v=i(d,h.source);if(v)return{moduleFile:v}}if(m!=="default")for(let h of p.stars??[]){let v=i(d,h),g=v?a(v,m,f):null;if(g)return g}return null}let l=d=>d?.local?s.get(d.file+"\0"+d.local)??null:null;function c(d,m,f,u){let p=i(d,m);return p?f==="default"?a(p,"default"):f==="named"?a(p,u):{moduleFile:p,cjs:f==="cjs"}:null}return{lookupExport:a,resolveImport:c,nodeForImport(d,m,f,u){let p=c(d,m,f,u);return p?.moduleFile&&p.cjs?l(a(p.moduleFile,"default")):l(p)},resolveName(d,m){let f=r(d,m);return f?this.nodeForImport(d,f.source,f.kind,f.imported):null},resolveMember(d,m,f){let u=r(d,m);if(!u)return null;let p=c(d,u.source,u.kind,u.imported);return p?.moduleFile?l(a(p.moduleFile,f)):null},classForImport(d,m){let f=r(d,m);if(!f)return null;let u=c(d,f.source,f.kind,f.imported);return u?.local?{file:u.file,className:u.local==="default"?null:u.local}:null},bindingFor:r}}function oi(e,t,n,s,o,r,i){let a=[],l=ei(t),c=new Map,d=g=>c.get(g)??Tt(g,n.get(g)?.imports??[],s);l.bind=In(t,n,d);let m=ni(t,n,d,l.bind),f=new Map;for(let g of e)f.has(g.fromFileId)||f.set(g.fromFileId,[]),f.get(g.fromFileId).push(g);for(let[g,w]of f){let S=n.get(g),k=de(g,t),y=Tt(g,S.imports,s);c.set(g,y);for(let x of w)if(x.type==="call")a.push(Jt(x,t,k,y,l));else if(x.type==="methodCall")a.push(Br(x,t,l));else if(x.type==="callSite")a.push((x.thisProp?m(x):null)??zr(x,t,k,y,l));else if(x.type==="returnValue")a.push({...x,targetNodeId:null,confidence:0,matchType:"returnValue",resolved:!1});else if(x.type==="apiCall")if(x.scope==="external")a.push({...x,targetNodeId:null,confidence:null,matchType:"externalService",resolved:!1});else{let b=Rt(x.url),N=o.get(b);N?a.push({...x,targetNodeId:N,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...x,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(x.type==="socketEmit"){let b=r.get(x.eventName);b?a.push({...x,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...x,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(x.type==="rawSocketSend"){let b=i?.get(x.eventName);b?a.push({...x,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...x,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}}let u=ti(n,t,l.bind,a);for(let g of u)a.push(g);let p=new Map;for(let g of a){if(g.resolved||g.line==null||g.type!=="call"&&g.type!=="methodCall"&&g.type!=="callSite")continue;let w=g.fromFileId+" "+g.line+" "+g.column;(p.get(w)??p.set(w,[]).get(w)).push(g)}let h=[...u.argBindings].sort((g,w)=>w.direct-g.direct),v=new Set;for(let g of h){let w=g.file+" "+g.line+" "+g.column;if(v.has(w))continue;let S=(p.get(w)??[]).find(k=>k.fromNodeId!==g.targetNodeId);S&&(v.add(w),Object.assign(S,{targetNodeId:g.targetNodeId,confidence:g.matchType==="local"?.95:.85,matchType:"argument",resolved:!0,viaArgument:!0}))}return a}function si(e){let t=new Map,n=new WeakMap,s=l=>{if(typeof l=="string")return l.length>=20?"s"+l:null;if(l&&typeof l=="object"){let c=n.get(l);if(c===void 0){let d=JSON.stringify(l);c=d.length>=40?"j"+d:"",n.set(l,c)}return c||null}return null};(function l(c){let d=s(c);if(d){let m=t.get(d)??0;if(t.set(d,m+1),m>0)return}if(Array.isArray(c))for(let m of c)l(m);else if(c&&typeof c=="object")for(let m of Object.values(c))l(m)})(e);let o=[],r=new Map,i=l=>{let c=s(l),d=c&&t.get(c)>1;if(d&&r.has(c))return r.get(c);let m;if(typeof l=="string"?m=JSON.stringify(l):Array.isArray(l)?m="["+l.map(i).join(",")+"]":l&&typeof l=="object"?m="{"+Object.entries(l).map(([u,p])=>JSON.stringify(u)+":"+i(p)).join(",")+"}":m=JSON.stringify(l),!d)return m;let f="$"+o.length.toString(36);return o.push(`const ${f}=${m};`),r.set(c,f),f},a=i(e);return`(() => {${o.join(`
19
19
  `)}
20
- return ${a};})()`}function Io(e,t,n,r){if(!e)return{targetId:null,via:null};if(n.has(e))return{targetId:n.get(e),via:"in-file"};if(r)for(let[,o]of r){let s=le(o,t);if(s.has(e))return{targetId:s.get(e),via:"cross-file"}}return{targetId:null,via:null}}function Vs(e,t,n,r,o,s=[],i=null){if(!n.some(l=>!l.isInlineHandler)&&!r.some(l=>!l.isInlineHandler)&&!s.some(l=>!l.isInlineHandler))return e;let a=e.map(l=>({...l}));for(let l of n){if(l.isInlineHandler)continue;let c=l.nest?e.find(f=>f.type==="classMethod"&&f.filePath===t&&f.className===l.nest.className&&f.name===l.nest.methodName):null,{targetId:d,via:p}=l.nest?{targetId:c?.id??null,via:"in-file"}:Io(l.handlerName,e,o,i);if(d){let f=a.find(u=>u.id===d);f&&(f.isEntryPoint=!0,f.trigger={type:"route",label:`${l.method.toUpperCase()} ${l.path}`,resolvedVia:p})}}for(let l of r){if(l.isInlineHandler)continue;let{targetId:c,via:d}=Io(l.handlerName,e,o,i);if(c){let p=a.find(f=>f.id===c);p&&(p.isEntryPoint=!0,p.trigger={type:"listener",label:l.eventName,resolvedVia:d})}}for(let l of s){if(l.isInlineHandler)continue;let{targetId:c,via:d}=Io(l.handlerName,e,o,i);if(c){let p=a.find(f=>f.id===c);p&&(p.isEntryPoint=!0,p.trigger={type:"socketListener",label:l.eventName,resolvedVia:d})}}return a}function jo(e){let t=new Map,n=new Map;for(let r of e)r.resolved&&(t.set(r.fromNodeId,(t.get(r.fromNodeId)??0)+1),n.set(r.targetNodeId,(n.get(r.targetNodeId)??0)+1));return{outgoing:t,incoming:n}}function Ys(e,t,n=jo(t)){if(e.type==="moduleRoot")return 0;let r=n.outgoing.get(e.id)??0,o=n.incoming.get(e.id)??0,s=e.exported?1.5:1;return r/(o+1)*s}function Xs(e,t){let n=jo(t),r=new Set;for(let i of e)n.incoming.has(i.id)&&r.add(i.filePath);let s=e.filter(i=>!(i.isEntryPoint||i.type==="moduleRoot"||!n.incoming.has(i.id)&&r.has(i.filePath))).map(i=>({...i,fallbackScore:Ys(i,t,n)}));return s.sort((i,a)=>a.fallbackScore-i.fallbackScore),s.slice(0,15)}function Co(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 Eo(e,t,n,r=8){let o=new Set([e]),s=l=>n.find(c=>c.id===l)?.category??"unknown",i=[{nodeId:e,depth:0,parentNodeId:null,category:s(e)}],a=[{nodeId:e,depth:0}];for(;a.length>0;){let l=a.shift();if(l.depth>=r)continue;let c=t.get(l.nodeId)||[];for(let d of c){let p=d.targetNodeId;if(o.has(p))continue;o.add(p);let f={nodeId:p,depth:l.depth+1,parentNodeId:l.nodeId,category:s(p),callLine:d.line,callColumn:d.column,branchPath:d.branchPath,edgeType:d.edgeType};i.push(f),a.push(f)}}return i}function Zs(e,t,n){return t.filter(o=>o.filePath===e.filePath&&o.id!==e.id&&o.type!=="moduleRoot").filter(o=>!n.some(i=>i.resolved&&i.targetNodeId===o.id))}function Qs(e,t,n){if(e.type==="moduleRoot")return!1;if(t.some(a=>a.resolved&&a.targetNodeId===e.id&&a.matchType==="crossLayer")||t.filter(a=>a.resolved&&a.fromNodeId===e.id).length>=4||new Set((e.returns||[]).map(a=>a.condition).filter(a=>a!==null)).size>=3)return!0;if(t.some(a=>a.resolved&&a.targetNodeId===e.id)&&!n.some(l=>l.filePath===e.filePath&&l.id!==e.id&&l.type!=="moduleRoot"&&t.some(c=>c.resolved&&c.targetNodeId===l.id))){let l=Zs(e,n,t);if(l.length>0)return e.lexicalSiblings=l.map(c=>c.id),!0}return!1}function ei(e,t,n,r,o=8,s=null){let i=[],a=new Set(e.map(c=>c.id)),l=[...e];for(;l.length>0;){let c=l.shift(),d=Eo(c.id,t,n,o);i.push({entryPointId:c.id,entryPointName:c.name,trigger:c.trigger??null,steps:d});let p=s?new Set(Eo(c.id,s,n,o).map(f=>f.nodeId)):null;for(let f of d){if(p&&!p.has(f.nodeId)||f.nodeId===c.id||a.has(f.nodeId))continue;let u=n.find(m=>m.id===f.nodeId);u&&Qs(u,r,n)&&(a.add(u.id),f.hasOwnSubTrace=!0,u.lexicalSiblings&&(f.lexicalSiblings=u.lexicalSiblings),l.push({id:u.id,name:u.name,trigger:null}))}}return i}function ti(e,t,n=mr){return e.filter((r,o)=>{if(o===0)return!0;let s=t.find(i=>i.id===r.nodeId);return s?!n.some(i=>s.name.toLowerCase().includes(i)):!0})}function ni(e){return e.steps.filter(n=>n.depth>0).map(n=>n.nodeId).sort().join(" | ")}function oi(e){let t=new Map;for(let n of e){let r=ni(n),o=r===""?`__no_calls__${n.entryPointName}`:r;t.has(o)||t.set(o,[]),t.get(o).push(n)}return t}function ri(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 _n from"node:path";function si(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 ii(e){return e.name.replace(/([A-Z])/g," $1").trim().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}var ai=60,Il=24;function ci(e,t=null){let n=e.map(r=>{let o=si(r),s=r.trigger?.workflowName??o??ii(r);return{...r,name:s}});return t?.nodes?Pl(n,t.nodes):n}var Po=(e,t)=>e.length>t?e.slice(0,t-1)+"\u2026":e,jl=new Set(["function","arrowFunction","classMethod"]);function Cl(e){let t=new Map(e.map(o=>[o.id,o])),n=new Map,r=o=>{let s=n.get(o);return s||(s=e.filter(i=>i.filePath===o&&jl.has(i.type)),n.set(o,s)),s};return o=>{let s=t.get(o.steps[0].nodeId);if(!s)return[null,null,null];let i=null;if(s.type==="classMethod")i=s.className;else{let c=null;for(let d of r(s.filePath))d===s||!(d.startLine<=s.startLine&&d.endLine>=s.endLine)||d.startLine===s.startLine&&d.endLine===s.endLine||(!c||d.endLine-d.startLine<c.endLine-c.startLine)&&(c=d);c&&(i=c.type==="classMethod"?c.className:c.name)}let a=null;if(o.trigger?.type==="route")a=String(o.trigger.label).split(" ")[0];else if(o.trigger?.type==="listener"){let c=/::listener:([^.#]+)\./.exec(s.id);c&&(a=c[1])}let l=_n.basename(s.filePath,_n.extname(s.filePath));return l==="index"&&(l=_n.basename(_n.dirname(s.filePath))),[i||null,a||null,l||null]}}var El=(e,t)=>{let n=t.map(r=>Po(r,Il)).join(", ");return e.endsWith(")")?e.slice(0,-1)+", "+n+")":e+" ("+n+")"};function Pl(e,t){let n=Cl(t),r=e.map(i=>({w:i,base:i.name,parts:[],used:new Set,stuck:!1,q:null})),o=i=>i.parts.length?El(i.base,i.parts):i.base,s=()=>{let i=new Map;for(let a of r){let l=o(a);(i.get(l)??i.set(l,[]).get(l)).push(a)}return[...i.values()].filter(a=>a.length>1)};for(let i=0;i<4;i++){let a=!1;for(let l of s()){if(l.some(f=>f.stuck))continue;for(let f of l)f.q??=n(f.w);let c=[0,1,2].filter(f=>l.every(u=>!u.used.has(f))),d=c.find(f=>new Set(l.map(u=>u.q[f]??"")).size>1),p=d!==void 0;if(p||(d=c.find(f=>l.every(u=>u.q[f]))),d===void 0){for(let f of l)f.stuck=!0;continue}for(let f of l)f.used.add(d),f.q[d]&&f.parts.push(f.q[d]),p||(f.stuck=!0);a=!0}if(!a)break}for(let i of s())i.sort((a,l)=>a.w.steps[0].nodeId<l.w.steps[0].nodeId?-1:a.w.steps[0].nodeId>l.w.steps[0].nodeId?1:0),i.forEach((a,l)=>{l>0&&(a.suffix=` (${l+1})`)});return r.map(i=>{let a=o(i);return i.suffix&&(a=Po(a,ai-i.suffix.length)+i.suffix),{...i.w,name:Po(a,ai)}})}var Ll=e=>e;function li(e,t){let n=new Map;for(let[r,o]of e){let s=t.filter(c=>c.filePath===r);if(s[0]?.category!=="backend")continue;let i=o.routes??[],a=Te(r,o),l=le(r,t);for(let c of i){let d=Ct(c.path);if(c.isInlineHandler){let f=a.get(c);n.set(d,f);continue}if(c.nest){let f=Ll(s).find(u=>u.type==="classMethod"&&u.className===c.nest.className&&u.name===c.nest.methodName);f&&n.set(d,f.id);continue}if(!c.handlerName||!l.has(c.handlerName))continue;let p=l.get(c.handlerName);n.set(d,p)}}return n}import dt from"node:fs";import Y from"node:path";var $n=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Rl=/(^|\/)(dist|build|out|built|compiled|esm|cjs|lib|output)(\/|$)/,di=/(^|\/)(dist|build|out|built|compiled|esm|cjs|output)(\/|$)/,Tl=/\b(esbuild|tsup|tsdown|tsc|rollup|webpack|ncc|swc|babel|vite|parcel|bun\s+build|pkg|unbuild|microbundle|rspack)\b/,Al=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild|rspack)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Oe=e=>{try{return dt.statSync(e).isFile()}catch{return!1}},Lo=e=>e.split(Y.sep).join("/"),Ro=e=>{if(Oe(e)&&$n.includes(Y.extname(e))&&!/\.d\.ts$/.test(e))return e;let t=e.replace(/\.(m|c)?js$/,"");for(let n of $n)if(Oe(t+n)&&!/\.d\.ts$/.test(t+n))return t+n;return null},Fn=(e,t)=>{let n=Y.relative(e,t);return n&&!n.startsWith("..")&&!Y.isAbsolute(n)&&!/(^|[\\/])node_modules([\\/]|$)/.test(n)};function Ol(e,t){let n=Oe(t+".map")?t+".map":null;if(!n&&Oe(t))try{let a=dt.readFileSync(t,"utf8").slice(-400),l=/sourceMappingURL=([^\s*]+)/.exec(a);if(l&&!l[1].startsWith("data:")){let c=Y.resolve(Y.dirname(t),l[1]);Oe(c)&&(n=c)}}catch{}if(!n)return null;let r;try{r=JSON.parse(dt.readFileSync(n,"utf8"))}catch{return null}let o=Y.resolve(Y.dirname(n),r.sourceRoot??""),s=(r.sources??[]).map(a=>Y.resolve(o,a)).filter(a=>Fn(e,a)&&Oe(a)&&$n.includes(Y.extname(a)));if(s.length===1)return s[0];let i=Y.basename(t).replace(/\.(m|c)?js$/,"");return s.find(a=>Y.basename(a).replace(/\.[^.]+$/,"")===i)??null}function Ml(e){try{return JSON.parse(dt.readFileSync(e,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,"").replace(/,(\s*[}\]])/g,"$1"))}catch{return null}}function Hl(e,t){for(let n of["tsconfig.build.json","tsconfig.json"]){let o=Ml(Y.join(e,n))?.compilerOptions;if(!o?.outDir)continue;let s=Lo(Y.normalize(o.outDir)).replace(/^\.\//,"").replace(/\/$/,"");if(!(t===s||t.startsWith(s+"/")))continue;let i=t.slice(s.length+1),a=o.rootDir?o.rootDir:dt.existsSync(Y.join(e,"src"))?"src":".",l=Ro(Y.resolve(e,a,i));if(l)return l}return null}function Dl(e,t){let n=t.split("/"),r=n.findIndex(s=>/^(dist|build|out|built|compiled|esm|cjs|lib|output)$/.test(s));if(r<0)return null;let o=n.slice(r+1).join("/");for(let s of["src","source","sources"]){let i=Ro(Y.resolve(e,...n.slice(0,r),s,o));if(i&&Fn(e,i))return i}return null}function Ul(e,t,n){let r=Y.basename(n).replace(/\.(m|c)?js$/,"");for(let o of["build","compile","bundle","prepare","prepublishOnly","prepack","postinstall"]){let s=t.scripts?.[o];if(!s||!Tl.test(s))continue;let i=[];for(let c of s.split(/\s+/).map(d=>d.replace(/^["']|["']$/g,"").replace(/^--?[\w-]+=/,""))){if(!$n.includes(Y.extname(c))||/\.d\.ts$/.test(c))continue;let d=Y.resolve(e,c);Oe(d)&&Fn(e,d)&&!di.test(Lo(Y.relative(e,d)))&&i.push(d)}let a=[...new Set(i)];if(a.length===1)return a[0];let l=a.filter(c=>Y.basename(c).replace(/\.[^.]+$/,"")===r);if(l.length===1)return l[0];if(a.length)return a[0]}return null}function Bl(e,t){let n=[];try{n=dt.readdirSync(e).filter(i=>Al.test(i)).sort()}catch{return null}let r=Y.basename(t).replace(/\.(m|c)?js$/,""),o=[];for(let i of n){let a;try{a=dt.readFileSync(Y.join(e,i),"utf8")}catch{continue}for(let l of a.matchAll(/\bentry(?:Points)?\s*:\s*[[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/g)){let c=Ro(Y.resolve(e,l[1]));c&&Fn(e,c)&&o.push(c)}}let s=[...new Set(o)];return s.length===1?s[0]:s.find(i=>Y.basename(i).replace(/\.[^.]+$/,"")===r)??null}function In(e,t,n){if(typeof t!="string"||!t)return null;let r=Lo(Y.normalize(t)).replace(/^\.\//,""),o=Y.resolve(e,r);if(!Rl.test(r)||Oe(o)&&!di.test(r)||Oe(o)&&/\.ts$/.test(o))return null;let i=[["sourcemap",()=>Ol(e,o)],["tsconfig outDir",()=>Hl(e,r)],["convention",()=>Oe(o)?null:Dl(e,r)],["build script",()=>Ul(e,n??{},r)],["build config",()=>Bl(e,r)]];for(let[a,l]of i){let c=null;try{c=l()}catch{}if(c&&c!==o)return{file:c,how:a}}return null}function fi(e,t){let n=new Map;for(let[r,o]of e){let s=o.socketListeners??[],i=Te(r,o),a=le(r,t);for(let l of s){if(l.isInlineHandler){let d=i.get(l);n.set(l.eventName,d);continue}if(!l.handlerName||!a.has(l.handlerName))continue;let c=a.get(l.handlerName);n.set(l.eventName,c)}}return n}import To from"node:fs";import H from"node:path";var Ne=e=>String(e??"").trim().replace(/^["']|["']$/g,""),jn=e=>e.replace(/^\s*#.*$/,"").replace(/\s+#.*$/,"");function ui(e){let t=/^(\/[A-Za-z0-9_\-./]*?)\/?(?=$|[:(*{[])/.exec(String(e).trim()),n=t?t[1]:"";return n==="/"?"":n.replace(/\/+$/,"")}function pi(e,t){let n=e.split(/\r?\n/).map(jn),r=u=>u.length-u.trimStart().length,o=[],s=null,i=!1,a=null,l=!1,c=0,d=null,p=()=>{d?.key&&d.fromService&&d.fromService!=="?"&&s.hostRefs.push({name:d.key,service:d.fromService,property:d.property}),d=null},f=(u,m,h)=>{m==="name"?u.name=Ne(h):m==="rootDir"?u.rootDir=Ne(h):m==="startCommand"&&(u.startCommand=Ne(h))};for(let u of n){if(!u.trim())continue;let m=r(u),h=u.trim();if(m===0){p(),s=null,l=!1,i=/^services\s*:/.test(h),a=null;continue}if(!i)continue;let v=h.startsWith("-");if(v&&(a==null||m===a)){a=m,p(),s={name:null,rootDir:null,startCommand:null,kept:[],hostRefs:[]},o.push(s),l=!1;let w=/^-\s*([A-Za-z]+)\s*:\s*(.*)$/.exec(h);w&&f(s,w[1],w[2]);continue}if(!s)continue;let g=/^(?:-\s*)?([A-Za-z]+)\s*:\s*(.*)$/.exec(h);if(g){if(g[1]==="envVars"){p(),l=!0,c=m;continue}if(l&&m>c){if(v&&(p(),d={key:null,fromService:null,property:null}),!d)continue;if(g[1]==="key")d.key=Ne(g[2]);else if(g[1]==="value"&&d.key){let w=Ke(d.key,Ne(g[2]),t);w&&s.kept.push(w)}else g[1]==="fromService"?d.fromService="?":g[1]==="name"&&d.fromService==="?"?d.fromService=Ne(g[2]):g[1]==="property"&&(d.property=Ne(g[2]));continue}l&&(p(),l=!1),f(s,g[1],g[2])}}return p(),o.filter(u=>u.name)}function mi(e,t){let n={app:null,ports:[],kept:[]},r="";for(let o of e.split(/\r?\n/)){let s=jn(o).trim();if(!s)continue;let i=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(s);if(i){r=i[1];continue}let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(s);if(!a)continue;let[,l,c]=a;if(r===""&&l==="app"){let d=Ne(c);/^[a-z0-9][a-z0-9-]*$/i.test(d)&&(n.app=d)}else if(l==="internal_port"){let d=Number(Ne(c));Number.isInteger(d)&&d>=1&&d<=65535&&n.ports.push(d)}else if(r==="env"){let d=Ke(l,Ne(c),t);d&&n.kept.push(d)}}return n}function hi(e,t){let n={ports:[],kept:[]},r=e.replace(/\\\r?\n/g," ");for(let o of r.split(/\r?\n/)){let s=o.trim(),i=/^EXPOSE\s+(.+)$/i.exec(s);if(i){for(let l of i[1].split(/\s+/)){let c=Number(l.replace(/\/\w+$/,""));Number.isInteger(c)&&c>=1&&c<=65535&&n.ports.push(c)}continue}if(i=/^(?:ENV|ARG)\s+(.+)$/i.exec(s),!i)continue;let a=i[1];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(a)){let l=/([A-Za-z_][A-Za-z0-9_]*)=("([^"]*)"|'([^']*)'|\S*)/g,c;for(;c=l.exec(a);){let d=Ke(c[1],c[3]??c[4]??c[2],t);d&&n.kept.push(d)}}else{let l=/^([A-Za-z_][A-Za-z0-9_]*)\s+(.*)$/.exec(a);if(l){let c=Ke(l[1],Ne(l[2]),t);c&&n.kept.push(c)}}}return n}function gi(e){let t;try{t=JSON.parse(e)}catch{return[]}let n=[];for(let r of["rewrites","redirects"])for(let o of Array.isArray(t?.[r])?t[r]:[]){let s=typeof o?.destination=="string"?o.destination:"",i=/\/:[A-Za-z_]+\*?$/.test(s)?Ve(s.replace(/\/:[A-Za-z_]+\*?$/,"")):null;i&&typeof o.source=="string"&&n.push({prefix:ui(o.source),target:i,kind:`vercel.json ${r}`,strip:!0})}return n}function yi(e){let t=[],n=!1,r=null,o=()=>{if(r?.from&&r.to&&/\/:[A-Za-z_]+\*?$/.test(r.to)){let s=Ve(r.to.replace(/\/:[A-Za-z_]+\*?$/,""));s&&t.push({prefix:ui(r.from),target:s,kind:"netlify.toml redirects",strip:!0})}r=null};for(let s of e.split(/\r?\n/)){let i=jn(s).trim();if(!i)continue;let a=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(a){o(),n=a[1]==="redirects",r=n?{}:null;continue}if(!n||!r)continue;let l=/^(from|to)\s*=\s*(.*)$/.exec(i);l&&(r[l[1]]=Ne(l[2]))}return o(),t}function xi(e,t){let n;try{n=JSON.parse(e)}catch{return[]}let r=[],o=n&&typeof n=="object"?n.env:null;if(o&&typeof o=="object")for(let s of Object.keys(o).sort()){let i=o[s],a=typeof i=="string"?i:typeof i?.value=="string"?i.value:null,l=Ke(s,a,t);l&&r.push(l)}return r}function vi(e,t,n){let r=[];if(n){let o;try{o=JSON.parse(e)}catch{return r}let s=(i,a)=>{if(!(!i||typeof i!="object"||a>4))for(let l of Object.keys(i).sort()){let c=i[l];if(/^(env|envVars|variables|environment)$/i.test(l)&&c&&typeof c=="object"&&!Array.isArray(c))for(let d of Object.keys(c).sort()){let p=typeof c[d]=="string"?c[d]:typeof c[d]?.value=="string"?c[d].value:null,f=Ke(d,p,t);f&&r.push(f)}else s(c,a+1)}};s(o,0)}else{let o="";for(let s of e.split(/\r?\n/)){let i=jn(s).trim();if(!i)continue;let a=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(a){o=a[1];continue}let l=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(i);if(l&&/(^|\.)(env|variables|environment)$/i.test(o)){let c=Ke(l[1],Ne(l[2]),t);c&&r.push(c)}}}return r}var zl=[".env.local",".env",".env.development",".env.production",".env.example"],Wl=/^(PORT|HTTP_PORT|HTTPS_PORT|SERVER_PORT|API_PORT|APP_PORT|WS_PORT|WSS_PORT|WEBSOCKET_PORT|LISTEN_PORT)$/,ql=/^PUBLIC_(?:[A-Z0-9]+_)*(?:ORIGIN|URL|HOST|BASE_URL)$/,Gl=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","host.docker.internal"]),Jl=512*1024,wi=e=>e.split(H.sep).join("/");function ft(e){try{let t=To.lstatSync(e);return!t.isFile()||t.isSymbolicLink()||t.size>Jl?null:To.readFileSync(e,"utf8")}catch{return null}}function Ve(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 r=n.protocol.replace(":",""),o=n.hostname.toLowerCase(),s=n.port?Number(n.port):null,i=n.pathname.replace(/\/+$/,"");return{scheme:r,host:o,port:s,origin:`${r}://${o}${s?":"+s:""}`,path:i}}catch{return null}}function Kl(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:Ve("http://"+t)}var Ao=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 Vl(e){let t=new Map;for(let n of e.split(/\r?\n/)){let r=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(n);if(!r)continue;let o=r[2];if(/^["']/.test(o)){let s=o[0],i=o.indexOf(s,1);o=i>0?o.slice(1,i):o.slice(1)}else o=o.replace(/\s+#.*$/,"");t.set(r[1],o)}return t}function Ni(e,t,n=0,r=new Set){let o=e.get(t);return o==null||n>5||r.has(t)||(r.add(t),o=o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}]*))?\}/g,(s,i,a)=>{let l=e.has(i)?Ni(e,i,n+1,r):void 0;return l!=null&&l!==""?l:a??""}),r.delete(t)),o}function Ke(e,t,n){if(t==null)return null;if(Wl.test(e)){let o=Ao(t);return o?{name:e,kind:"port",file:n,port:o}:null}let r=Ve(t)??(/(_URL|_URI|_HOST|_HOSTNAME|_ORIGIN|_ADDR|_ENDPOINT)$/i.test(e)?Kl(t):null);return r?{name:e,kind:"url",file:n,...r}:null}function Si(e,t){let n=[];for(let r of[...e.keys()].sort()){let o=Ni(e,r);if(o==null)continue;let s=Ke(r,o,t);s&&n.push(s)}return n}function Yl(e){let t=e.split(/\r?\n/).map(c=>c.replace(/\s+#.*$/,"").replace(/\t/g," ")),n=c=>c.length-c.trimStart().length,r=[],o=t.findIndex(c=>/^services\s*:\s*$/.test(c));if(o<0)return r;let s=null,i=null,a=null,l=0;for(o=o+1;o<t.length;o++){let c=t[o];if(!c.trim())continue;let d=n(c),p=c.trim();if(d===0)break;if(s==null&&(s=d),d===s){let f=/^([A-Za-z0-9_.-]+)\s*:\s*$/.exec(p);f&&(i={name:f[1],ports:[],env:new Map,build:null},r.push(i),a=null);continue}if(i){if(d<=s+4&&/^[A-Za-z_]+\s*:/.test(p)&&!p.startsWith("-")){let f=/^([A-Za-z_]+)\s*:\s*(.*)$/.exec(p);a=f[1],l=d,a==="build"&&f[2]&&(i.build=f[2].replace(/^["']|["']$/g,""));continue}if(a==="build"&&/^context\s*:/.test(p)){i.build=p.replace(/^context\s*:\s*/,"").replace(/^["']|["']$/g,"");continue}if(a==="ports"&&p.startsWith("-")){let u=p.slice(1).trim().replace(/^["']|["']$/g,"").replace(/\/\w+$/,"").split(":"),m=u.slice(-2).map(h=>Ao(h));u.length===1&&m[0]?i.ports.push({host:null,container:m[0]}):u.length>=2&&m[0]&&m[1]&&i.ports.push({host:m[0],container:m[1]});continue}if(a==="environment"&&d>l){let f=p.startsWith("-")?/^-\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(p):/^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/.exec(p);f&&i.env.set(f[1],f[2].replace(/^["']|["']$/g,""))}}}return r}function ki(e,t){let n=[];if(t==="vite"){let r=e.search(/\bproxy\s*:/);if(r<0)return n;let o=e.slice(r,r+2500),s=/["'`](\/[^"'`]*)["'`]\s*:\s*(?:["'`](https?:\/\/[^"'`]+)["'`]|\{[^{}]*?target\s*:\s*["'`](https?:\/\/[^"'`]+)["'`])/g,i;for(;i=s.exec(o);){let a=Ve(i[2]??i[3]);a&&n.push({prefix:i[1].replace(/\/+$/,""),target:a,kind:"vite.config proxy"})}}else if(t==="next"){let r=/source\s*:\s*["'`](\/[^"'`:*]*)[^"'`]*["'`]\s*,\s*destination\s*:\s*["'`](https?:\/\/[^"'`]+?)(?:\/:[^"'`]*)?["'`]/g,o;for(;o=r.exec(e);){let s=Ve(o[2]);s&&n.push({prefix:o[1].replace(/\/+$/,""),target:s,kind:"next.config rewrites"})}}return n}function bi(e,t,n){let r=g=>wi(H.relative(e,g)),o=new Map,s=new Map,i=new Map,a=(g,w,S)=>{(g.get(w)??g.set(w,new Set).get(w)).add(S)},l=(g,w,S)=>{let N=i.get(g)??i.set(g,[]).get(g);N.some(y=>y.service===w&&y.via===S)||N.push({service:w,via:S})},c=g=>{let w=[],S=H.resolve(g),N=H.resolve(e);for(let y=0;y<8&&(w.push(S),!(S===N||H.dirname(S)===S||(S=H.dirname(S),!S.startsWith(N))));y++);return w},d=new Map,p=new Map,f=(g,w)=>{let S=g.env.get(w.name)??g.env.set(w.name,[]).get(w.name);S.some(N=>N.file===w.file)||S.push(w),w.kind==="port"&&g.ports.add(w.port)};function u(g,w,S){let N=x=>r(H.join(S,x)),y=x=>ft(H.join(S,x));for(let x of Cn(S))if(x==="fly.toml"){let b=y(x);if(b){let k=mi(b,N(x));for(let $ of k.ports)w.ports.add($);for(let $ of k.kept)f(w,$);k.app&&(l(`${k.app.toLowerCase()}.internal`,g.name,"fly.toml app name"),l(`${k.app.toLowerCase()}.fly.dev`,g.name,"fly.toml app name"))}}else if(/^Dockerfile(\..+)?$/.test(x)){let b=y(x);if(b){let k=hi(b,N(x));for(let $ of k.ports)w.weakPorts.add($);for(let $ of k.kept)f(w,$)}}else if(x==="railway.json"||x==="railway.toml"){let b=y(x);if(b)for(let k of vi(b,N(x),x.endsWith(".json")))f(w,k)}else if(x==="app.json"){let b=y(x);if(b)for(let k of xi(b,N(x)))f(w,k)}else if(x==="vercel.json"){let b=y(x);if(b)for(let k of gi(b))w.proxies.push({...k,file:N(x)})}else if(x==="netlify.toml"){let b=y(x);if(b)for(let k of yi(b))w.proxies.push({...k,file:N(x)})}}for(let g of t){let w={env:new Map,ports:new Set,weakPorts:new Set,proxies:[],isServer:!1};o.set(g.name,w);for(let S of c(g.rootPath)){for(let N of zl){let y=ft(H.join(S,N));if(y!=null)for(let x of Si(Vl(y),r(H.join(S,N)))){let b=w.env.get(x.name)??w.env.set(x.name,[]).get(x.name);b.some(k=>k.file===x.file)||b.push(x),x.kind==="port"&&S===H.resolve(g.rootPath)&&/(^|\/)\.env/.test(x.file)&&!/\.example$/.test(x.file)&&w.ports.add(x.port),x.kind==="port"&&S===H.resolve(g.rootPath)&&/\.example$/.test(x.file)&&w.ports.add(x.port)}}if(S===H.resolve(g.rootPath)){try{let N=JSON.parse(ft(H.join(S,"package.json"))??"null"),y=typeof N?.proxy=="string"?Ve(N.proxy):null;y&&w.proxies.push({prefix:"",target:y,kind:'package.json "proxy"',file:r(H.join(S,"package.json"))})}catch{}for(let N of Cn(S)){if(/^vite\.config\.(js|mjs|cjs|ts|mts)$/.test(N)){let y=ft(H.join(S,N));if(y)for(let x of ki(y,"vite"))w.proxies.push({...x,file:r(H.join(S,N))})}if(/^next\.config\.(js|mjs|cjs|ts)$/.test(N)){let y=ft(H.join(S,N));if(y)for(let x of ki(y,"next"))w.proxies.push({...x,file:r(H.join(S,N))})}}}S===H.resolve(g.rootPath)&&u(g,w,S);for(let N of Cn(S))if(/^render\.ya?ml$/.test(N)&&!p.has(H.join(S,N))){let y=ft(H.join(S,N));y&&p.set(H.join(S,N),pi(y,r(H.join(S,N))))}for(let N of Cn(S)){if(!/^docker-compose.*\.ya?ml$/.test(N)||d.has(H.join(S,N)))continue;let y=ft(H.join(S,N));y&&d.set(H.join(S,N),Yl(y))}}}for(let[g,w]of[...d].sort((S,N)=>S[0]<N[0]?-1:1)){let S=H.dirname(g);for(let N of w){let y=N.build?H.resolve(S,N.build):null,x=t.find(k=>y&&H.resolve(k.rootPath)===y)??t.find(k=>k.name===N.name||H.basename(k.rootPath)===N.name);if(!x)continue;let b=o.get(x.name);for(let k of N.ports)b.ports.add(k.container),k.host&&b.ports.add(k.host);for(let k of Si(N.env,r(g)))(b.env.get(k.name)??b.env.set(k.name,[]).get(k.name)).push(k);l(N.name.toLowerCase(),x.name,"docker-compose service name")}}for(let[g,w]of[...p].sort((S,N)=>S[0]<N[0]?-1:1)){let S=H.dirname(g),N=new Map;for(let y of w){let x=H.resolve(S,y.rootDir||"."),b=y.rootDir?t.find($=>H.resolve($.rootPath)===x):null;if(!b&&y.startCommand)for(let $ of y.startCommand.split(/\s+/)){if(!/\.(c|m)?[jt]sx?$/.test($)&&!/^[\w./-]+\/[\w.-]+$/.test($))continue;let j=H.resolve(x,$),D=t.filter(L=>j.startsWith(H.resolve(L.rootPath)+H.sep)).sort((L,K)=>K.rootPath.length-L.rootPath.length)[0];if(D){b=D;break}}if(b=b??t.find($=>$.name===y.name||H.basename($.rootPath)===y.name),!b)continue;N.set(y.name,{target:b,c:y});let k=o.get(b.name);for(let $ of y.kept)f(k,{...$,scoped:!0});l(y.name.toLowerCase(),b.name,"render.yaml service name"),l(`${y.name.toLowerCase()}.onrender.com`,b.name,"render.yaml service name (Render's default public address)")}for(let{target:y,c:x}of N.values())for(let b of x.hostRefs){let k=N.get(b.service);if(!k)continue;let $=[...k.c.kept].find(L=>L.kind==="port")?.port??null,j=b.property==="hostport"&&$,D=b.service.toLowerCase();f(o.get(y.name),{name:b.name,kind:"url",file:r(g),scheme:"http",host:D,port:j?$:null,origin:`http://${D}${j?":"+$:""}`,path:""})}}let m=g=>[...n.get(g.name)?.parseResults?.values()??[]].some(w=>(w.routes??[]).length>0);for(let g of t){let w=o.get(g.name);if(w.isServer=m(g),w.isServer){for(let[S,N]of w.env)if(ql.test(S))for(let y of N)y.kind==="url"&&y.file&&(y.scoped||H.posix.dirname(y.file)===(wi(H.relative(e,g.rootPath))||"."))&&l(y.host,g.name,`${S} in ${y.file} (the server's own public address)`)}}for(let g of t){let w=o.get(g.name);for(let[,S]of n.get(g.name)?.parseResults??[])for(let N of S.httpClients?.listens??[])for(let y of h(w,N.parts)){let x=Ao(y.text);x&&w.ports.add(x)}}for(let g of t)for(let w of o.get(g.name).ports)a(s,w,g.name);for(let g of t)for(let w of o.get(g.name).weakPorts)t.some(S=>o.get(S.name).ports.has(w))||a(s,w,g.name);function h(g,w){let S=[{text:"",evidence:[]}];for(let N of w){let y;if(N.t==="lit")y=[{text:N.v,evidence:[]}];else if(N.t==="env"){let b=g.env.get(N.name)??[];y=[];for(let k of b)y.push({text:k.kind==="port"?String(k.port):k.origin+k.path,evidence:[{env:N.name,file:k.file}]});!y.length&&N.fallback&&(y=h(g,N.fallback).map($=>({text:$.text,evidence:[{env:N.name,file:null,fallback:!0},...$.evidence]})))}else y=[];if(!y.length)return[];let x=[];for(let b of S)for(let k of y)if(x.push({text:b.text+k.text,evidence:[...b.evidence,...k.evidence]}),x.length>=8)break;S=x.slice(0,8)}return S}let v=(g,w)=>{let S=[],N=g.host,y=i.get(N)??[];for(let x of y)S.push(x);if(Gl.has(N)||y.length&&y.some(x=>x.via==="docker-compose service name")){let x=g.port??(g.scheme==="https"||g.scheme==="wss",null);if(x)for(let b of s.get(x)??[])S.some(k=>k.service===b)||S.push({service:b,via:`port ${x} (a service listening there)`})}return S.filter(x=>x.service!==w)};return{resolveBase(g,w){let S=o.get(g);if(!S||!w.length)return{status:"unknown"};let N=h(S,w);if(!N.length)return{status:"unknown"};let y=[],x=new Set;for(let $ of N){let j=Ve($.text)??($.text.startsWith("//"),null);if(j){x.add(j.origin);for(let D of v(j,g))y.push({...D,u:j,evidence:$.evidence})}}if(!x.size)return{status:"unknown"};let b=[...new Set(y.map($=>$.service))];if(b.length===0)return{status:"external",origins:[...x].sort()};if(b.length>1)return{status:"ambiguous",services:b.sort()};let k=y[0];return{status:"service",service:k.service,via:k.via,origin:k.u.origin,basePath:k.u.path,evidence:k.evidence.filter(($,j,D)=>D.findIndex(L=>L.env===$.env&&L.file===$.file)===j)}},resolveProxy(g,w){let S=o.get(g);for(let N of S?.proxies??[]){if(N.prefix&&w!==N.prefix&&!w.startsWith(N.prefix+"/"))continue;let y=v(N.target,g),x=[...new Set(y.map(b=>b.service))];if(x.length===1)return{status:"service",service:x[0],via:`${N.kind} ${N.prefix||"/"} -> ${N.target.origin}`,origin:N.target.origin,basePath:N.target.path,strip:N.strip?N.prefix.split("/").filter(Boolean).length:0,evidence:[{env:null,file:N.file}]}}return{status:"unknown"}},portsOf:g=>[...o.get(g)?.ports??[]].sort((w,S)=>w-S),hostClaims:()=>[...i].sort((g,w)=>g[0]<w[0]?-1:1)}}function Cn(e){try{return To.readdirSync(e).sort()}catch{return[]}}var En=e=>String(e).toLowerCase();function Pn(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 _i(e,t){let n=[];for(let r of e){if(r.t!=="param"){n.push(r);continue}let o=t?.get(r.index);o?n.push(...o):n.push({t:"ref",name:r.name})}return Pn(n)}function Oo(e){if(!e.length)return null;let t=e.slice(),n="none",r=null,o=t[0];if(o.t==="lit"){let c=/^(https?:)\/\/([^/?#]*)(.*)$/.exec(o.v);if(c){n="abs",r=c[2];let d=c[3];if(t=d?[{t:"lit",v:d},...t.slice(1)]:t.slice(1),/^(www\.)?(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)(:\d+)?$/.test(r)===!1&&!/\.(local|internal|svc)$/.test(r)&&!/^[a-z0-9-]+(:\d+)?$/.test(r))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 s="",i=0,a=!1;for(let c of t){if(a)break;if(c.t==="lit"){let d=c.v.search(/[?#]/);d>=0?(s+=c.v.slice(0,d),a=!0):s+=c.v}else s+="",i++}if(!s.startsWith("/")&&!(s===""&&n==="abs"))return null;s===""&&(s="/");let l=s.split("/").slice(1).map(c=>c.includes("")?":p":c);for(;l.length>1&&l[l.length-1]==="";)l.pop();return{base:n,host:r,segments:l,placeholders:i,literal:n==="none"&&i===0}}function $i(e){if(!e.length)return[];let t=e[0];if(t.t==="lit"){let r=/^((?:https?|wss?):\/\/[^/?#]*)/.exec(t.v);return r?[{t:"lit",v:r[1]}]:[]}let n=[];for(let r of e){if(r.t==="lit"&&r.v.startsWith("/"))break;n.push(r)}return n}var Xl=e=>String(e||"").split("/").filter(Boolean),Fi=e=>[...new Set(e)];function Ii(e){let t=e.evidence??[];return{env:Fi(t.filter(n=>n.env).map(n=>n.env)),files:Fi(t.filter(n=>n.file).map(n=>n.file)),origin:e.origin,via:e.via,...t.some(n=>n.fallback)?{usedFallback:!0}:{}}}var ji=(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+")",Zl=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 Ci(e,t){if(e.length===t.length){let n=!0,r=!0;for(let o=0;o<e.length;o++){let s=e[o],i=t[o];if(s!==i&&(n=!1),!(s===i||s===":p"||i===":p")){r=!1;break}}if(n)return 3;if(r)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((r,o)=>r===t[o]||r===":p"||t[o]===":p"))return 1}return 0}function Ql(e,t,n,r,o){let s=(n.importBindings??[]).find(p=>p.local===r);if(!s)return null;let i=Ae(s.source,t,o);if(!i)return null;let a=e.parseResults.get(i),l=p=>e.nodes.find(f=>f.filePath===i&&f.name===p&&f.type!=="moduleRoot")?.id??null;if(s.kind==="named"&&s.imported)return l(s.imported);let c=a?.exportBindings;if(c?.default&&c.default!=="<anon>")return l(c.default);let d=Object.keys(c?.named??{});return d.length===1?l(d[0]):null}function ed(e){let t=[],n=[...e.parseResults.keys()];for(let[r,o]of e.parseResults){let s=e.nodes.filter(l=>l.filePath===r);if(s[0]?.category!=="backend")continue;let i=Te(r,o),a=le(r,e.nodes);for(let l of o.routes??[]){let c=null;l.isInlineHandler?c=i.get(l):l.nest?c=s.find(p=>p.type==="classMethod"&&p.className===l.nest.className&&p.name===l.nest.methodName)?.id??null:l.handlerName&&a.has(l.handlerName)?c=a.get(l.handlerName):l.handlerName&&(c=Ql(e,r,o,l.handlerName,n));let d=!1;c||(c=fe(l.startLine,s)?.id??null,d=!0),c&&t.push({method:En(l.method),path:l.path,segments:Zl(l.path),literal:!/[:*{]/.test(l.path),nodeId:c,file:r,line:l.startLine,fallback:d})}}return t}var td=/^(ws|uws|websocket|@nestjs\/platform-ws|@fastify\/websocket|fastify-websocket|express-ws)$/,nd=/^(socket\.io|@nestjs\/platform-socket\.io|socket\.io-client)$/;function Ei(e){let t=[...e].some(r=>nd.test(r)),n=[...e].some(r=>td.test(r));return t&&n?"unknown":t?"socketio":n?"ws":null}function od(e){let t=[],n=new Set;for(let[,r]of e.parseResults)for(let o of r.imports??[])n.add(o.source);for(let[r,o]of e.parseResults){let s=o.socketListeners??[],i=s.find(h=>h.eventName==="connection");if(!i)continue;let a=Te(r,o),l=le(r,e.nodes),c=h=>h.isInlineHandler?a.get(h):h.handlerName&&l.has(h.handlerName)?l.get(h.handlerName):null,d=c(i);if(!d)continue;let p=h=>i.handlerStartLine!=null&&h.startLine>=i.handlerStartLine&&h.startLine<=i.handlerEndLine,f=s.find(h=>h.eventName==="message"&&p(h))??s.find(h=>h.eventName==="message"),u=o.httpClients?.wsServers??[],m=Ei(new Set((o.imports??[]).map(h=>h.source)))??Ei(n)??"unknown";t.push({filePath:r,nodeId:d,line:i.startLine,messageNodeId:f?c(f):null,messageLine:f?.startLine??null,pathParts:u.find(h=>h.path)?.path??null,kind:m})}return t}function Pi(e,t,n={}){let r=n.repoRoot?bi(n.repoRoot,e,t):null,o=[],s=new Set,i={restCalls:0,restLinked:0,wsClients:0,wsLinked:0,wsSends:0,wsSendsLinked:0},a=c=>{let d=[c.fromService,c.fromNodeId,c.toService,c.toNodeId,c.via,c.key].join("\0");s.has(d)||(s.add(d),o.push(c))},l=new Map;for(let c of e){let d=t.get(c.name);d&&l.set(c.name,{routes:ed(d),wsServers:od(d)})}for(let c of e){let d=t.get(c.name);if(!d)continue;let p=[...d.parseResults.keys()],f=new Map,u=new Map;for(let[y,x]of d.parseResults){let b=x.httpClients;if(b){for(let k of b.httpInstances??[])(f.get(k.name)??f.set(k.name,[]).get(k.name)).push(k);for(let k of b.httpCalls??[])(k.parts.some(j=>j.t==="param")||k.method&&typeof k.method=="object")&&k.fn?.name&&(u.get(k.fn.name)??u.set(k.fn.name,[]).get(k.fn.name)).push({filePath:y,call:k})}}let m=y=>{if(!y.startsWith("inst:")&&!y.startsWith("obj:"))return[];let x=f.get(y.slice(y.indexOf(":")+1));return x&&x.length===1?x[0].parts:y.startsWith("obj:")?null:[{t:"ref",name:"?"}]},h=[],v=(y,x)=>fe(x,d.nodes.filter(b=>b.filePath===y)),g=new Set,w=y=>y.parts.some(x=>x.t==="param")||y.method&&typeof y.method=="object";for(let[y,x]of d.parseResults){let b=x.httpClients;if(b){for(let k of b.httpCalls??[]){if(w(k))continue;let $=m(k.client);if($===null)continue;let j=v(y,k.line);j&&h.push({filePath:y,line:k.line,nodeId:j.id,method:k.method,parts:Pn([...$,...k.parts]),via:k.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let k of b.pathCallsites??[]){let $=u.get(k.callee);if($)for(let j of $){let D=j.filePath===y;if(!D){let O=(x.importBindings??[]).find(W=>W.local===k.callee||W.imported===k.callee);O&&Ae(O.source,y,p)===j.filePath&&(D=!0)}if(!D)continue;let L=new Map(k.args.map(O=>[O.i,O.parts])),K=typeof j.call.method=="object"&&j.call.method?(()=>{let O=L.get(j.call.method.param);return O&&O.length===1&&O[0].t==="lit"?O[0].v.toUpperCase():"?"})():j.call.method,z=v(y,k.line);z&&(g.add(j.call),h.push({filePath:y,line:k.line,nodeId:z.id,method:K,parts:_i([...m(j.call.client),...j.call.parts],L),via:j.call.client,wrapper:k.callee}))}}}}for(let[y,x]of d.parseResults)for(let b of x.httpClients?.httpCalls??[]){if(!w(b)||g.has(b))continue;let k=m(b.client);if(k===null)continue;let $=v(y,b.line);$&&h.push({filePath:y,line:b.line,nodeId:$.id,method:typeof b.method=="object"&&b.method?"?":b.method,parts:_i([...k,...b.parts],null),via:b.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let y of h){let x=Oo(y.parts);if(!x)continue;i.restCalls++;let b=0,k=[];for(let z of e){if(z.name===c.name)continue;let O=l.get(z.name);if(O)for(let W of O.routes){if(!(y.method==="?"||y.method==null||W.method===En(y.method)||W.method==="all"||W.method==="use"))continue;let te=Ci(x.segments,W.segments);te&&(te>b&&(b=te,k.length=0),te===b&&k.push({service:z.name,route:W}))}}let $={status:"unknown"};if(r){let z=Pn(y.parts);if(x.base==="none"?$=r.resolveProxy(c.name,"/"+x.segments.join("/")):$=r.resolveBase(c.name,$i(z)),$.status==="service"){let O=Xl($.basePath);if(O.length||$.strip){let W=[...O,...x.segments.slice($.strip||0)];for(let G of l.get($.service)?.routes??[])(y.method==="?"||y.method==null||G.method===En(y.method)||G.method==="all"||G.method==="use")&&Ci(W,G.segments)&&!k.some(ge=>ge.service===$.service&&ge.route.nodeId===G.nodeId)&&k.push({service:$.service,route:G,viaBasePath:!0})}}}if(!k.length)continue;let j=new Set(k.map(z=>z.service+"\0"+z.route.nodeId)),D=typeof y.method=="string"&&y.method!=="?",L=b===3&&x.literal&&D&&j.size===1&&k[0].route.literal&&!k[0].route.fallback&&k[0].route.method===En(y.method),K=[];x.base==="var"&&K.push("base URL is a variable, so the target service is guessed from the path"),x.base==="abs"&&K.push("absolute URL"),x.placeholders&&K.push("path has parameters"),b===1&&K.push("leading /api removed from the client path"),b===2&&K.push("route parameters matched fuzzily"),D||K.push("method not known"),j.size>1&&K.push(j.size+" candidate routes"),k.some(z=>z.route.fallback)&&K.push("route handler not resolved: linked to the function that registers the route"),$.status==="external"&&K.push("base URL is "+$.origins.join(" / ")+", which no service of this repo owns"),$.status==="ambiguous"&&K.push("base URL could belong to "+$.services.join(" or "));for(let z of k){i.restLinked++;let O=!L&&$.status==="service"&&$.service===z.service&&!z.route.fallback,W=O?Ii($):null,G=L?"exact":O?"resolved":"inferred",te=!L&&$.status==="service"&&$.service!==z.service?["base URL belongs to "+$.service+", not this service"]:[];a({fromService:c.name,fromNodeId:y.nodeId,toService:z.service,toNodeId:z.route.nodeId,via:"httpCall",key:`${D?y.method:"ANY"} ${"/"+x.segments.join("/")}`,confidence:G,method:D?y.method:null,url:"/"+x.segments.join("/"),client:y.via,...y.wrapper?{wrapper:y.wrapper}:{},line:y.line,...L?{}:O?{reason:ji(W,z.service)+(D?"":"; method not known"),resolvedFrom:W}:{reason:[...K,...te].join("; ")||"path-only match"}})}}let S=[];for(let[y,x]of d.parseResults)for(let b of x.httpClients?.wsClients??[])S.push({filePath:y,w:b});let N=y=>y.client==="io"?"socketio":"ws";for(let{filePath:y,w:x}of S){let b=v(y,x.line);if(!b)continue;i.wsClients++;let k=Pn(x.parts),$=/^wss?:\/\//.test(k[0]?.v??"")?Oo([{t:"lit",v:k[0].v.replace(/^ws(s?):/,"http$1:")},...k.slice(1)]):Oo(k),j=r&&$?r.resolveBase(c.name,$i(k)):{status:"unknown"};for(let D of e)if(D.name!==c.name)for(let L of l.get(D.name)?.wsServers??[]){if(L.kind!=="unknown"&&L.kind!==N(x))continue;let K=L.pathParts&&L.pathParts.every(te=>te.t==="lit")?"/"+L.pathParts.map(te=>te.v).join("").replace(/^\//,""):null,z=$?"/"+$.segments.join("/"):null;if(K&&z&&K!==z&&K!=="/"&&z!=="/")continue;let O=!!($&&$.literal&&K&&z===K&&L.kind!=="unknown"),W=!O&&j.status==="service"&&j.service===D.name,G=W?Ii(j):null;i.wsLinked++,a({fromService:c.name,fromNodeId:b.id,toService:D.name,toNodeId:L.nodeId,via:"webSocket",key:z??"(url unknown)",confidence:O?"exact":W?"resolved":"inferred",url:z,client:x.client,line:x.line,...O?{}:W?{reason:ji(G,D.name),resolvedFrom:G}:{reason:"WebSocket connection matched to a WebSocket server of another service ("+($?.base==="var"?"URL base is a variable":"no path on the server to compare")+(j.status==="external"?"; base URL is "+j.origins.join(" / ")+", which no service of this repo owns":"")+")"}})}}if(S.length){let y=new Set(S.map(({w:x})=>N(x)));for(let[x,b]of d.parseResults)for(let k of b.httpClients?.wsSends??[]){let $=v(x,k.line);if($){i.wsSends++;for(let j of e)if(j.name!==c.name)for(let D of l.get(j.name)?.wsServers??[])!D.messageNodeId||D.kind!=="unknown"&&!y.has(D.kind)||(i.wsSendsLinked++,a({fromService:c.name,fromNodeId:$.id,toService:j.name,toNodeId:D.messageNodeId,via:"webSocketMessage",key:"message",eventName:"message",confidence:"inferred",client:k.recv,line:k.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 c=new Map;for(let p of o)if(p.via==="webSocket"){let f=p.fromService+"\0"+p.toService;(c.get(f)??c.set(f,[]).get(f)).push(p)}let d=new Map;for(let p of c.values())(d.get(p[0].toService)??d.set(p[0].toService,new Set).get(p[0].toService)).add(p[0].fromService);for(let[,p]of[...c].sort((f,u)=>f[0]<u[0]?-1:1)){let f=p[0].fromService,u=p[0].toService,m=t.get(f),h=t.get(u);if(!m||!h||!(l.get(u)?.wsServers??[]).length)continue;let v=new Set(p.map(N=>N.fromNodeId.split("::")[0])),g=[];for(let[N,y]of m.parseResults){if(!v.has(N))continue;let x=le(N,m.nodes),b=Te(N,y),k=m.nodes.filter($=>$.filePath===N);for(let $ of y.httpClients?.wsReceivers??[]){let j=$.handlerName&&x.get($.handlerName)||fe($.line,k)?.id;j&&g.push({id:j,line:$.line})}for(let $ of y.socketListeners??[]){if($.eventName!=="message")continue;let j=$.isInlineHandler?b.get($):$.handlerName&&x.get($.handlerName)||null;j&&g.push({id:j,line:$.startLine})}}let w=new Set(m.resolvedEdges.filter(N=>N.resolved&&N.targetNodeId&&N.type!=="returnValue").map(N=>N.fromNodeId));for(let N=g.length-1;N>=0;N--)w.has(g[N].id)||g.splice(N,1);if(!g.length)continue;let S=d.get(u)?.size??1;for(let[N,y]of h.parseResults){let x=h.nodes.filter(b=>b.filePath===N);for(let b of[...y.httpClients?.wsSends??[],...y.httpClients?.wsServerSends??[]]){let k=fe(b.line,x);if(k)for(let $ of g)i.wsPushLinked=(i.wsPushLinked??0)+1,a({fromService:u,fromNodeId:k.id,toService:f,toNodeId:$.id,via:"webSocketDelivery",key:"message",eventName:"message",confidence:"inferred",client:b.recv,line:b.line,receiverLine:$.line,reason:"a message the server sends over a WebSocket (payload built at run time) is taken in by the message handler of "+f+", which connects to this server"+(S>1?"; "+S+" services connect to this server, so it may be meant for another one":""),...S>1?{candidates:S}:{}})}}}}return o.sort((c,d)=>c.fromService+c.fromNodeId+c.via+c.key+c.toService+c.toNodeId<d.fromService+d.fromNodeId+d.via+d.key+d.toService+d.toNodeId?-1:1),{edges:o,stats:i}}function Li(e,t){let n=new Map;for(let[r,o]of e){let s=t.filter(a=>a.filePath===r),i=o.rawSocketTypeChecks??[];for(let a of i){let l=fe(a.startLine,s);l&&n.set(a.eventName,l.id)}}return n}import rd from"node:fs";import sd from"node:path";function Ri(e){let t=["index.html","public/index.html","client/index.html","frontend/index.html","src/index.html"];for(let n of t){let r=sd.join(e,n);if(rd.existsSync(r))return r}return null}import Ln from"node:fs";import Rn from"node:path";var id=new Set(["node","tsx","ts-node","nodemon","bun","deno","ts-node-esm"]),ad=new Set(["watch","run","start","dev"]),cd=/\.[cm]?[jt]sx?$/,ld=["start","dev","serve","run"];function dd(e){for(let t of String(e).split(/&&|\|\||;|\|/)){let n=t.trim().split(/\s+/).filter(Boolean).map(o=>o.replace(/^["']|["']$/g,"")),r=n.findIndex(o=>id.has(Rn.basename(o).replace(/\.cmd$/,"")));if(!(r<0)){for(let o of n.slice(r+1))if(!(o.startsWith("-")||ad.has(o)||o.includes("="))){if(cd.test(o))return o;break}}}return null}var fd=e=>String(e).replace(/^@[^/]+\//,"");function Ti(e){let t;try{t=JSON.parse(Ln.readFileSync(Rn.join(e,"package.json"),"utf8"))}catch{return[]}let n=[],r=(o,s,i={})=>{if(typeof o!="string"||!o)return;let a=s==="script"?null:In(e,o,t);a?n.push({file:a.file,kind:s,...i,mappedFrom:o,mappedBy:a.how}):n.push({file:Rn.resolve(e,o),kind:s,...i})};if(typeof t.bin=="string")r(t.bin,"bin",{binName:fd(t.name??Rn.basename(e))});else if(t.bin&&typeof t.bin=="object")for(let[o,s]of Object.entries(t.bin))r(s,"bin",{binName:o});for(let o of ld){let s=t.scripts?.[o]&&dd(t.scripts[o]);s&&r(s,"script")}return r(t.main,"main"),n}function Ai(e){try{let t=Ln.openSync(e,"r"),n=Buffer.alloc(120),r=Ln.readSync(t,n,0,120,0);return Ln.closeSync(t),/^#!.*\b(node|tsx|ts-node|bun)\b/.test(n.toString("utf8",0,r).split(/\r?\n/)[0])}catch{return!1}}import Tn from"node:fs";import ut from"node:path";var ud=50,pd=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Oi=["",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts","/index.js","/index.ts","/index.mjs","/index.cjs","/index.tsx","/index.jsx"];function Mo(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=Mo(t);if(n)return n}return null}if(e&&typeof e=="object")for(let t of["import","node","require","default"]){let n=Mo(e[t]);if(n)return n}return null}function Mi(e,t){let n;try{n=JSON.parse(Tn.readFileSync(ut.join(e,"package.json"),"utf8"))}catch{return null}let r=n.exports,o=typeof r=="string"||Array.isArray(r)?r:r&&typeof r=="object"?r["."]??(Object.keys(r).some(c=>c.startsWith("."))?null:r):null,s=Mo(o)??(typeof n.module=="string"?n.module:null)??(typeof n.main=="string"?n.main:null);if(!s)return null;let i=new Set(t.map(c=>ut.resolve(c))),a=ut.resolve(e,s);for(let c of Oi)if(i.has(a+c))return t.find(d=>ut.resolve(d)===a+c);let l=[];try{l=Tn.readdirSync(e).filter(c=>pd.test(c)).sort()}catch{}for(let c of l){let d;try{d=Tn.readFileSync(ut.join(e,c),"utf8")}catch{continue}let p=/\bentry(?:Points)?\s*:\s*[\[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/.exec(d);if(!p)continue;let f=ut.resolve(e,p[1]);for(let u of Oi)if(i.has(f+u))return t.find(m=>ut.resolve(m)===f+u)}return null}function Hi(e,t,n,r,o=null){let s=new Map;for(let h of n){let v=s.get(h.filePath);v||s.set(h.filePath,v=[]),v.push(h)}let i=new Map,a=(h,v)=>{v&&(!i.has(v.id)||h<i.get(v.id))&&i.set(v.id,h)},l=new Map,c=(h,v)=>{let g=l.get(h);if(!g){g=new Map;let w="";try{w=Tn.readFileSync(h,"utf8")}catch{}for(let S of w.matchAll(/^[ \t]*(?:export\s+)?const\s+([\w$]+)\s*(?::[^=\n]+)?=\s*([\w$]+)\s*(?:as\s+[^;\n]+)?;?[ \t]*$/gm))S[1]!==S[2]&&g.set(S[1],S[2]);l.set(h,g)}return g.get(v)??null},d=(h,v)=>(s.get(h)??[]).find(g=>(g.type==="function"||g.type==="arrowFunction")&&g.name===v),p=(h,v)=>(s.get(h)??[]).filter(g=>g.type==="classMethod"&&g.className===v&&g.name!=="constructor"&&!/^[_#]/.test(g.name)),f=new Set;function u(h,v,g,w=0){let S=d(h,g);if(S){a(v,S);return}let N=p(h,g);for(let j of N)a(`${v}.${j.name}`,j);if(N.length||!o)return;let y=o.resolveName(h,g);if(y){a(v,y);return}let x=o.bindingFor(h,g),b=x&&w<3?o.resolveImport(h,x.source,x.kind,x.imported):null;if(b?.file&&b.local&&b.local!=="default"&&c(b.file,b.local)){u(b.file,v,b.local,w+1);return}let k=o.classForImport(h,g);if(k?.className)for(let j of p(k.file,k.className))a(`${v}.${j.name}`,j);if(k?.className)return;let $=c(h,g);$&&w<3&&u(h,v,$,w+1)}function m(h,v,g){let w=h+"|"+(g?[...g.keys()].sort().join(","):"*");if(f.has(w)||v>3)return;f.add(w);let S=t.get(h)?.exportBindings;if(!S)return;let N=y=>!g||g.has(y);for(let[y,x]of Object.entries(S.named??{}))N(y)&&u(h,g?.get(y)??y,x);S.default&&N("default")&&S.default!=="<anon>"&&u(h,g?.get("default")??S.default,S.default);for(let y of S.reexports??[]){if(!N(y.exported))continue;let x=Ae(y.source,h,r);x&&m(x,v+1,new Map([[y.imported,g?.get(y.exported)??y.exported]]))}for(let y of S.stars??[]){let x=Ae(y,h,r);x&&(g?m(x,v+1,g):m(x,v+1,null))}}return m(e,0,null),[...i].map(([h,v])=>({name:v,nodeId:h})).sort((h,v)=>h.name<v.name?-1:h.name>v.name?1:h.nodeId<v.nodeId?-1:1).slice(0,ud)}Le();import Ui from"node:path";import{fileURLToPath as md}from"node:url";import{Parser as Di,Language as hd}from"web-tree-sitter";var lh=Ui.dirname(md(globalThis.__canopyUrl("src/stage2_parse/initHtmlParser.js")));async function Bi(){await Di.init();let e=new Di,t=Ui.join(je("tree-sitter-html"),"tree-sitter-html.wasm"),n=await hd.load(t);return e.setLanguage(n),{parser:e,language:n}}function zi(e,t){let r=ee(t,"htmlScriptRoot.scm").matches(e.rootNode);for(let o of r){let s=o.captures.find(a=>a.name==="attr_name"),i=o.captures.find(a=>a.name==="script_src");if(s&&s.node.text==="src"&&i)return i.node.text}return null}function Wi(e,t,n){let r=[];e.forEach((l,c)=>{l.steps.forEach(d=>{if(!d.hasOwnSubTrace)return;let p=e.findIndex((f,u)=>u!==c&&f.steps[0]?.nodeId===d.nodeId);p!==-1&&r.push({fromWorkflowIndex:c,toWorkflowIndex:p,atNodeId:d.nodeId})})});let o=new Map;for(let l of t)o.set(l.id,l.serviceName??null);let s=new Map;function i(l,c,d,p){if(!l||!c||l===c)return;let f=`${l} -> ${c} -> ${d}`;s.has(f)?s.get(f).count+=1:s.set(f,{fromService:l,toService:c,viaMatchType:d,count:1});let u=s.get(f);p==="exact"?u.exact=(u.exact??0)+1:p==="inferred"?u.inferred=(u.inferred??0)+1:p==="resolved"&&(u.resolved=(u.resolved??0)+1)}for(let l of n){if(!l.resolved||!l.fromNodeId||!l.targetNodeId)continue;let c=o.get(l.fromNodeId)??null,d=o.get(l.targetNodeId)??null;i(c,d,l.matchType,l.confidence)}let a=Array.from(s.values());return{workflowLinks:r,serviceLinks:a}}var xd=J.dirname(gd(globalThis.__canopyUrl("src/index.js"))),qi=24*1e3*1e3;async function Ho(e,t={}){e=J.resolve(e),console.log(`
20
+ return ${a};})()`}function Lo(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=de(o,t);if(r.has(e))return{targetId:r.get(e),via:"cross-file"}}return{targetId:null,via:null}}function ri(e,t,n,s,o,r=[],i=null){if(!n.some(l=>!l.isInlineHandler)&&!s.some(l=>!l.isInlineHandler)&&!r.some(l=>!l.isInlineHandler))return e;let a=e.map(l=>({...l}));for(let l of n){if(l.isInlineHandler)continue;let c=l.nest?e.find(f=>f.type==="classMethod"&&f.filePath===t&&f.className===l.nest.className&&f.name===l.nest.methodName):null,{targetId:d,via:m}=l.nest?{targetId:c?.id??null,via:"in-file"}:Lo(l.handlerName,e,o,i);if(d){let f=a.find(u=>u.id===d);f&&(f.isEntryPoint=!0,f.trigger={type:"route",label:`${l.method.toUpperCase()} ${l.path}`,resolvedVia:m})}}for(let l of s){if(l.isInlineHandler)continue;let{targetId:c,via:d}=Lo(l.handlerName,e,o,i);if(c){let m=a.find(f=>f.id===c);m&&(m.isEntryPoint=!0,m.trigger={type:"listener",label:l.eventName,resolvedVia:d})}}for(let l of r){if(l.isInlineHandler)continue;let{targetId:c,via:d}=Lo(l.handlerName,e,o,i);if(c){let m=a.find(f=>f.id===c);m&&(m.isEntryPoint=!0,m.trigger={type:"socketListener",label:l.eventName,resolvedVia:d})}}return a}function To(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 ii(e,t,n=To(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 ai(e,t){let n=To(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:ii(i,t,n)}));return r.sort((i,a)=>a.fallbackScore-i.fallbackScore),r.slice(0,15)}function Ro(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 Ao(e,t,n,s=8){let o=new Set([e]),r=l=>n.find(c=>c.id===l)?.category??"unknown",i=[{nodeId:e,depth:0,parentNodeId:null,category:r(e)}],a=[{nodeId:e,depth:0}];for(;a.length>0;){let l=a.shift();if(l.depth>=s)continue;let c=t.get(l.nodeId)||[];for(let d of c){let m=d.targetNodeId;if(o.has(m))continue;o.add(m);let f={nodeId:m,depth:l.depth+1,parentNodeId:l.nodeId,category:r(m),callLine:d.line,callColumn:d.column,branchPath:d.branchPath,edgeType:d.edgeType};i.push(f),a.push(f)}}return i}function ci(e,t,n){return t.filter(o=>o.filePath===e.filePath&&o.id!==e.id&&o.type!=="moduleRoot").filter(o=>!n.some(i=>i.resolved&&i.targetNodeId===o.id))}function li(e,t,n){if(e.type==="moduleRoot")return!1;if(t.some(a=>a.resolved&&a.targetNodeId===e.id&&a.matchType==="crossLayer")||t.filter(a=>a.resolved&&a.fromNodeId===e.id).length>=4||new Set((e.returns||[]).map(a=>a.condition).filter(a=>a!==null)).size>=3)return!0;if(t.some(a=>a.resolved&&a.targetNodeId===e.id)&&!n.some(l=>l.filePath===e.filePath&&l.id!==e.id&&l.type!=="moduleRoot"&&t.some(c=>c.resolved&&c.targetNodeId===l.id))){let l=ci(e,n,t);if(l.length>0)return e.lexicalSiblings=l.map(c=>c.id),!0}return!1}function di(e,t,n,s,o=8,r=null){let i=[],a=new Set(e.map(c=>c.id)),l=[...e];for(;l.length>0;){let c=l.shift(),d=Ao(c.id,t,n,o);i.push({entryPointId:c.id,entryPointName:c.name,trigger:c.trigger??null,steps:d});let m=r?new Set(Ao(c.id,r,n,o).map(f=>f.nodeId)):null;for(let f of d){if(m&&!m.has(f.nodeId)||f.nodeId===c.id||a.has(f.nodeId))continue;let u=n.find(p=>p.id===f.nodeId);u&&li(u,s,n)&&(a.add(u.id),f.hasOwnSubTrace=!0,u.lexicalSiblings&&(f.lexicalSiblings=u.lexicalSiblings),l.push({id:u.id,name:u.name,trigger:null}))}}return i}function fi(e,t,n=bs){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 ui(e){return e.steps.filter(n=>n.depth>0).map(n=>n.nodeId).sort().join(" | ")}function pi(e){let t=new Map;for(let n of e){let s=ui(n),o=s===""?`__no_calls__${n.entryPointName}`:s;t.has(o)||t.set(o,[]),t.get(o).push(n)}return t}function mi(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 Fn from"node:path";function hi(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 gi(e){return e.name.replace(/([A-Z])/g," $1").trim().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}var yi=60,Yl=24;function xi(e,t=null){let n=e.map(s=>{let o=hi(s),r=s.trigger?.workflowName??o??gi(s);return{...s,name:r}});return t?.nodes?td(n,t.nodes):n}var Oo=(e,t)=>e.length>t?e.slice(0,t-1)+"\u2026":e,Zl=new Set(["function","arrowFunction","classMethod"]);function Ql(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&&Zl.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 c=null;for(let d of s(r.filePath))d===r||!(d.startLine<=r.startLine&&d.endLine>=r.endLine)||d.startLine===r.startLine&&d.endLine===r.endLine||(!c||d.endLine-d.startLine<c.endLine-c.startLine)&&(c=d);c&&(i=c.type==="classMethod"?c.className:c.name)}let a=null;if(o.trigger?.type==="route")a=String(o.trigger.label).split(" ")[0];else if(o.trigger?.type==="listener"){let c=/::listener:([^.#]+)\./.exec(r.id);c&&(a=c[1])}let l=Fn.basename(r.filePath,Fn.extname(r.filePath));return l==="index"&&(l=Fn.basename(Fn.dirname(r.filePath))),[i||null,a||null,l||null]}}var ed=(e,t)=>{let n=t.map(s=>Oo(s,Yl)).join(", ");return e.endsWith(")")?e.slice(0,-1)+", "+n+")":e+" ("+n+")"};function td(e,t){let n=Ql(t),s=e.map(i=>({w:i,base:i.name,parts:[],used:new Set,stuck:!1,q:null})),o=i=>i.parts.length?ed(i.base,i.parts):i.base,r=()=>{let i=new Map;for(let a of s){let l=o(a);(i.get(l)??i.set(l,[]).get(l)).push(a)}return[...i.values()].filter(a=>a.length>1)};for(let i=0;i<4;i++){let a=!1;for(let l of r()){if(l.some(f=>f.stuck))continue;for(let f of l)f.q??=n(f.w);let c=[0,1,2].filter(f=>l.every(u=>!u.used.has(f))),d=c.find(f=>new Set(l.map(u=>u.q[f]??"")).size>1),m=d!==void 0;if(m||(d=c.find(f=>l.every(u=>u.q[f]))),d===void 0){for(let f of l)f.stuck=!0;continue}for(let f of l)f.used.add(d),f.q[d]&&f.parts.push(f.q[d]),m||(f.stuck=!0);a=!0}if(!a)break}for(let i of r())i.sort((a,l)=>a.w.steps[0].nodeId<l.w.steps[0].nodeId?-1:a.w.steps[0].nodeId>l.w.steps[0].nodeId?1:0),i.forEach((a,l)=>{l>0&&(a.suffix=` (${l+1})`)});return s.map(i=>{let a=o(i);return i.suffix&&(a=Oo(a,yi-i.suffix.length)+i.suffix),{...i.w,name:Oo(a,yi)}})}var nd=e=>e;function vi(e,t){let n=new Map;for(let[s,o]of e){let r=t.filter(c=>c.filePath===s);if(r[0]?.category!=="backend")continue;let i=o.routes??[],a=Ue(s,o),l=de(s,t);for(let c of i){let d=Rt(c.path);if(c.isInlineHandler){let f=a.get(c);n.set(d,f);continue}if(c.nest){let f=nd(r).find(u=>u.type==="classMethod"&&u.className===c.nest.className&&u.name===c.nest.methodName);f&&n.set(d,f.id);continue}if(!c.handlerName||!l.has(c.handlerName))continue;let m=l.get(c.handlerName);n.set(d,m)}}return n}import mt from"node:fs";import Y from"node:path";var jn=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],od=/(^|\/)(dist|build|out|built|compiled|esm|cjs|lib|output)(\/|$)/,wi=/(^|\/)(dist|build|out|built|compiled|esm|cjs|output)(\/|$)/,sd=/\b(esbuild|tsup|tsdown|tsc|rollup|webpack|ncc|swc|babel|vite|parcel|bun\s+build|pkg|unbuild|microbundle|rspack)\b/,rd=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild|rspack)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,We=e=>{try{return mt.statSync(e).isFile()}catch{return!1}},Mo=e=>e.split(Y.sep).join("/"),Ho=e=>{if(We(e)&&jn.includes(Y.extname(e))&&!/\.d\.ts$/.test(e))return e;let t=e.replace(/\.(m|c)?js$/,"");for(let n of jn)if(We(t+n)&&!/\.d\.ts$/.test(t+n))return t+n;return null},Cn=(e,t)=>{let n=Y.relative(e,t);return n&&!n.startsWith("..")&&!Y.isAbsolute(n)&&!/(^|[\\/])node_modules([\\/]|$)/.test(n)};function id(e,t){let n=We(t+".map")?t+".map":null;if(!n&&We(t))try{let a=mt.readFileSync(t,"utf8").slice(-400),l=/sourceMappingURL=([^\s*]+)/.exec(a);if(l&&!l[1].startsWith("data:")){let c=Y.resolve(Y.dirname(t),l[1]);We(c)&&(n=c)}}catch{}if(!n)return null;let s;try{s=JSON.parse(mt.readFileSync(n,"utf8"))}catch{return null}let o=Y.resolve(Y.dirname(n),s.sourceRoot??""),r=(s.sources??[]).map(a=>Y.resolve(o,a)).filter(a=>Cn(e,a)&&We(a)&&jn.includes(Y.extname(a)));if(r.length===1)return r[0];let i=Y.basename(t).replace(/\.(m|c)?js$/,"");return r.find(a=>Y.basename(a).replace(/\.[^.]+$/,"")===i)??null}function ad(e){try{return JSON.parse(mt.readFileSync(e,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,"").replace(/,(\s*[}\]])/g,"$1"))}catch{return null}}function cd(e,t){for(let n of["tsconfig.build.json","tsconfig.json"]){let o=ad(Y.join(e,n))?.compilerOptions;if(!o?.outDir)continue;let r=Mo(Y.normalize(o.outDir)).replace(/^\.\//,"").replace(/\/$/,"");if(!(t===r||t.startsWith(r+"/")))continue;let i=t.slice(r.length+1),a=o.rootDir?o.rootDir:mt.existsSync(Y.join(e,"src"))?"src":".",l=Ho(Y.resolve(e,a,i));if(l)return l}return null}function ld(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=Ho(Y.resolve(e,...n.slice(0,s),r,o));if(i&&Cn(e,i))return i}return null}function dd(e,t,n){let s=Y.basename(n).replace(/\.(m|c)?js$/,"");for(let o of["build","compile","bundle","prepare","prepublishOnly","prepack","postinstall"]){let r=t.scripts?.[o];if(!r||!sd.test(r))continue;let i=[];for(let c of r.split(/\s+/).map(d=>d.replace(/^["']|["']$/g,"").replace(/^--?[\w-]+=/,""))){if(!jn.includes(Y.extname(c))||/\.d\.ts$/.test(c))continue;let d=Y.resolve(e,c);We(d)&&Cn(e,d)&&!wi.test(Mo(Y.relative(e,d)))&&i.push(d)}let a=[...new Set(i)];if(a.length===1)return a[0];let l=a.filter(c=>Y.basename(c).replace(/\.[^.]+$/,"")===s);if(l.length===1)return l[0];if(a.length)return a[0]}return null}function fd(e,t){let n=[];try{n=mt.readdirSync(e).filter(i=>rd.test(i)).sort()}catch{return null}let s=Y.basename(t).replace(/\.(m|c)?js$/,""),o=[];for(let i of n){let a;try{a=mt.readFileSync(Y.join(e,i),"utf8")}catch{continue}for(let l of a.matchAll(/\bentry(?:Points)?\s*:\s*[[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/g)){let c=Ho(Y.resolve(e,l[1]));c&&Cn(e,c)&&o.push(c)}}let r=[...new Set(o)];return r.length===1?r[0]:r.find(i=>Y.basename(i).replace(/\.[^.]+$/,"")===s)??null}function En(e,t,n){if(typeof t!="string"||!t)return null;let s=Mo(Y.normalize(t)).replace(/^\.\//,""),o=Y.resolve(e,s);if(!od.test(s)||We(o)&&!wi.test(s)||We(o)&&/\.ts$/.test(o))return null;let i=[["sourcemap",()=>id(e,o)],["tsconfig outDir",()=>cd(e,s)],["convention",()=>We(o)?null:ld(e,s)],["build script",()=>dd(e,n??{},s)],["build config",()=>fd(e,s)]];for(let[a,l]of i){let c=null;try{c=l()}catch{}if(c&&c!==o)return{file:c,how:a}}return null}function Si(e,t){let n=new Map;for(let[s,o]of e){let r=o.socketListeners??[],i=Ue(s,o),a=de(s,t);for(let l of r){if(l.isInlineHandler){let d=i.get(l);n.set(l.eventName,d);continue}if(!l.handlerName||!a.has(l.handlerName))continue;let c=a.get(l.handlerName);n.set(l.eventName,c)}}return n}import Do from"node:fs";import z from"node:path";var $e=e=>String(e??"").trim().replace(/^["']|["']$/g,""),Pn=e=>e.replace(/^\s*#.*$/,"").replace(/\s+#.*$/,"");function ki(e){let t=/^(\/[A-Za-z0-9_\-./]*?)\/?(?=$|[:(*{[])/.exec(String(e).trim()),n=t?t[1]:"";return n==="/"?"":n.replace(/\/+$/,"")}function Ni(e,t){let n=e.split(/\r?\n/).map(Pn),s=u=>u.length-u.trimStart().length,o=[],r=null,i=!1,a=null,l=!1,c=0,d=null,m=()=>{d?.key&&d.fromService&&d.fromService!=="?"&&r.hostRefs.push({name:d.key,service:d.fromService,property:d.property}),d=null},f=(u,p,h)=>{p==="name"?u.name=$e(h):p==="rootDir"?u.rootDir=$e(h):p==="startCommand"&&(u.startCommand=$e(h))};for(let u of n){if(!u.trim())continue;let p=s(u),h=u.trim();if(p===0){m(),r=null,l=!1,i=/^services\s*:/.test(h),a=null;continue}if(!i)continue;let v=h.startsWith("-");if(v&&(a==null||p===a)){a=p,m(),r={name:null,rootDir:null,startCommand:null,kept:[],hostRefs:[]},o.push(r),l=!1;let w=/^-\s*([A-Za-z]+)\s*:\s*(.*)$/.exec(h);w&&f(r,w[1],w[2]);continue}if(!r)continue;let g=/^(?:-\s*)?([A-Za-z]+)\s*:\s*(.*)$/.exec(h);if(g){if(g[1]==="envVars"){m(),l=!0,c=p;continue}if(l&&p>c){if(v&&(m(),d={key:null,fromService:null,property:null}),!d)continue;if(g[1]==="key")d.key=$e(g[2]);else if(g[1]==="value"&&d.key){let w=Ze(d.key,$e(g[2]),t);w&&r.kept.push(w)}else g[1]==="fromService"?d.fromService="?":g[1]==="name"&&d.fromService==="?"?d.fromService=$e(g[2]):g[1]==="property"&&(d.property=$e(g[2]));continue}l&&(m(),l=!1),f(r,g[1],g[2])}}return m(),o.filter(u=>u.name)}function bi(e,t){let n={app:null,ports:[],kept:[]},s="";for(let o of e.split(/\r?\n/)){let r=Pn(o).trim();if(!r)continue;let i=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(r);if(i){s=i[1];continue}let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(r);if(!a)continue;let[,l,c]=a;if(s===""&&l==="app"){let d=$e(c);/^[a-z0-9][a-z0-9-]*$/i.test(d)&&(n.app=d)}else if(l==="internal_port"){let d=Number($e(c));Number.isInteger(d)&&d>=1&&d<=65535&&n.ports.push(d)}else if(s==="env"){let d=Ze(l,$e(c),t);d&&n.kept.push(d)}}return n}function _i(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 l of i[1].split(/\s+/)){let c=Number(l.replace(/\/\w+$/,""));Number.isInteger(c)&&c>=1&&c<=65535&&n.ports.push(c)}continue}if(i=/^(?:ENV|ARG)\s+(.+)$/i.exec(r),!i)continue;let a=i[1];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(a)){let l=/([A-Za-z_][A-Za-z0-9_]*)=("([^"]*)"|'([^']*)'|\S*)/g,c;for(;c=l.exec(a);){let d=Ze(c[1],c[3]??c[4]??c[2],t);d&&n.kept.push(d)}}else{let l=/^([A-Za-z_][A-Za-z0-9_]*)\s+(.*)$/.exec(a);if(l){let c=Ze(l[1],$e(l[2]),t);c&&n.kept.push(c)}}}return n}function $i(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:ki(o.source),target:i,kind:`vercel.json ${s}`,strip:!0})}return n}function Ii(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:ki(s.from),target:r,kind:"netlify.toml redirects",strip:!0})}s=null};for(let r of e.split(/\r?\n/)){let i=Pn(r).trim();if(!i)continue;let a=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(a){o(),n=a[1]==="redirects",s=n?{}:null;continue}if(!n||!s)continue;let l=/^(from|to)\s*=\s*(.*)$/.exec(i);l&&(s[l[1]]=$e(l[2]))}return o(),t}function Fi(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],a=typeof i=="string"?i:typeof i?.value=="string"?i.value:null,l=Ze(r,a,t);l&&s.push(l)}return s}function ji(e,t,n){let s=[];if(n){let o;try{o=JSON.parse(e)}catch{return s}let r=(i,a)=>{if(!(!i||typeof i!="object"||a>4))for(let l of Object.keys(i).sort()){let c=i[l];if(/^(env|envVars|variables|environment)$/i.test(l)&&c&&typeof c=="object"&&!Array.isArray(c))for(let d of Object.keys(c).sort()){let m=typeof c[d]=="string"?c[d]:typeof c[d]?.value=="string"?c[d].value:null,f=Ze(d,m,t);f&&s.push(f)}else r(c,a+1)}};r(o,0)}else{let o="";for(let r of e.split(/\r?\n/)){let i=Pn(r).trim();if(!i)continue;let a=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(a){o=a[1];continue}let l=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(i);if(l&&/(^|\.)(env|variables|environment)$/i.test(o)){let c=Ze(l[1],$e(l[2]),t);c&&s.push(c)}}}return s}var ud=[".env.local",".env",".env.development",".env.production",".env.example"],pd=/^(PORT|HTTP_PORT|HTTPS_PORT|SERVER_PORT|API_PORT|APP_PORT|WS_PORT|WSS_PORT|WEBSOCKET_PORT|LISTEN_PORT)$/,md=/^PUBLIC_(?:[A-Z0-9]+_)*(?:ORIGIN|URL|HOST|BASE_URL)$/,hd=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","host.docker.internal"]),gd=512*1024,Ci=e=>e.split(z.sep).join("/");function ht(e){try{let t=Do.lstatSync(e);return!t.isFile()||t.isSymbolicLink()||t.size>gd?null:Do.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 yd(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 Bo=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 xd(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 Li(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,a)=>{let l=e.has(i)?Li(e,i,n+1,s):void 0;return l!=null&&l!==""?l:a??""}),s.delete(t)),o}function Ze(e,t,n){if(t==null)return null;if(pd.test(e)){let o=Bo(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)?yd(t):null);return s?{name:e,kind:"url",file:n,...s}:null}function Ei(e,t){let n=[];for(let s of[...e.keys()].sort()){let o=Li(e,s);if(o==null)continue;let r=Ze(s,o,t);r&&n.push(r)}return n}function vd(e){let t=e.split(/\r?\n/).map(c=>c.replace(/\s+#.*$/,"").replace(/\t/g," ")),n=c=>c.length-c.trimStart().length,s=[],o=t.findIndex(c=>/^services\s*:\s*$/.test(c));if(o<0)return s;let r=null,i=null,a=null,l=0;for(o=o+1;o<t.length;o++){let c=t[o];if(!c.trim())continue;let d=n(c),m=c.trim();if(d===0)break;if(r==null&&(r=d),d===r){let f=/^([A-Za-z0-9_.-]+)\s*:\s*$/.exec(m);f&&(i={name:f[1],ports:[],env:new Map,build:null},s.push(i),a=null);continue}if(i){if(d<=r+4&&/^[A-Za-z_]+\s*:/.test(m)&&!m.startsWith("-")){let f=/^([A-Za-z_]+)\s*:\s*(.*)$/.exec(m);a=f[1],l=d,a==="build"&&f[2]&&(i.build=f[2].replace(/^["']|["']$/g,""));continue}if(a==="build"&&/^context\s*:/.test(m)){i.build=m.replace(/^context\s*:\s*/,"").replace(/^["']|["']$/g,"");continue}if(a==="ports"&&m.startsWith("-")){let u=m.slice(1).trim().replace(/^["']|["']$/g,"").replace(/\/\w+$/,"").split(":"),p=u.slice(-2).map(h=>Bo(h));u.length===1&&p[0]?i.ports.push({host:null,container:p[0]}):u.length>=2&&p[0]&&p[1]&&i.ports.push({host:p[0],container:p[1]});continue}if(a==="environment"&&d>l){let f=m.startsWith("-")?/^-\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(m):/^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/.exec(m);f&&i.env.set(f[1],f[2].replace(/^["']|["']$/g,""))}}}return s}function Pi(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 a=Qe(i[2]??i[3]);a&&n.push({prefix:i[1].replace(/\/+$/,""),target:a,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 Ti(e,t,n){let s=g=>Ci(z.relative(e,g)),o=new Map,r=new Map,i=new Map,a=(g,w,S)=>{(g.get(w)??g.set(w,new Set).get(w)).add(S)},l=(g,w,S)=>{let k=i.get(g)??i.set(g,[]).get(g);k.some(y=>y.service===w&&y.via===S)||k.push({service:w,via:S})},c=g=>{let w=[],S=z.resolve(g),k=z.resolve(e);for(let y=0;y<8&&(w.push(S),!(S===k||z.dirname(S)===S||(S=z.dirname(S),!S.startsWith(k))));y++);return w},d=new Map,m=new Map,f=(g,w)=>{let S=g.env.get(w.name)??g.env.set(w.name,[]).get(w.name);S.some(k=>k.file===w.file)||S.push(w),w.kind==="port"&&g.ports.add(w.port)};function u(g,w,S){let k=x=>s(z.join(S,x)),y=x=>ht(z.join(S,x));for(let x of Ln(S))if(x==="fly.toml"){let b=y(x);if(b){let N=bi(b,k(x));for(let $ of N.ports)w.ports.add($);for(let $ of N.kept)f(w,$);N.app&&(l(`${N.app.toLowerCase()}.internal`,g.name,"fly.toml app name"),l(`${N.app.toLowerCase()}.fly.dev`,g.name,"fly.toml app name"))}}else if(/^Dockerfile(\..+)?$/.test(x)){let b=y(x);if(b){let N=_i(b,k(x));for(let $ of N.ports)w.weakPorts.add($);for(let $ of N.kept)f(w,$)}}else if(x==="railway.json"||x==="railway.toml"){let b=y(x);if(b)for(let N of ji(b,k(x),x.endsWith(".json")))f(w,N)}else if(x==="app.json"){let b=y(x);if(b)for(let N of Fi(b,k(x)))f(w,N)}else if(x==="vercel.json"){let b=y(x);if(b)for(let N of $i(b))w.proxies.push({...N,file:k(x)})}else if(x==="netlify.toml"){let b=y(x);if(b)for(let N of Ii(b))w.proxies.push({...N,file:k(x)})}}for(let g of t){let w={env:new Map,ports:new Set,weakPorts:new Set,proxies:[],isServer:!1};o.set(g.name,w);for(let S of c(g.rootPath)){for(let k of ud){let y=ht(z.join(S,k));if(y!=null)for(let x of Ei(xd(y),s(z.join(S,k)))){let b=w.env.get(x.name)??w.env.set(x.name,[]).get(x.name);b.some(N=>N.file===x.file)||b.push(x),x.kind==="port"&&S===z.resolve(g.rootPath)&&/(^|\/)\.env/.test(x.file)&&!/\.example$/.test(x.file)&&w.ports.add(x.port),x.kind==="port"&&S===z.resolve(g.rootPath)&&/\.example$/.test(x.file)&&w.ports.add(x.port)}}if(S===z.resolve(g.rootPath)){try{let k=JSON.parse(ht(z.join(S,"package.json"))??"null"),y=typeof k?.proxy=="string"?Qe(k.proxy):null;y&&w.proxies.push({prefix:"",target:y,kind:'package.json "proxy"',file:s(z.join(S,"package.json"))})}catch{}for(let k of Ln(S)){if(/^vite\.config\.(js|mjs|cjs|ts|mts)$/.test(k)){let y=ht(z.join(S,k));if(y)for(let x of Pi(y,"vite"))w.proxies.push({...x,file:s(z.join(S,k))})}if(/^next\.config\.(js|mjs|cjs|ts)$/.test(k)){let y=ht(z.join(S,k));if(y)for(let x of Pi(y,"next"))w.proxies.push({...x,file:s(z.join(S,k))})}}}S===z.resolve(g.rootPath)&&u(g,w,S);for(let k of Ln(S))if(/^render\.ya?ml$/.test(k)&&!m.has(z.join(S,k))){let y=ht(z.join(S,k));y&&m.set(z.join(S,k),Ni(y,s(z.join(S,k))))}for(let k of Ln(S)){if(!/^docker-compose.*\.ya?ml$/.test(k)||d.has(z.join(S,k)))continue;let y=ht(z.join(S,k));y&&d.set(z.join(S,k),vd(y))}}}for(let[g,w]of[...d].sort((S,k)=>S[0]<k[0]?-1:1)){let S=z.dirname(g);for(let k of w){let y=k.build?z.resolve(S,k.build):null,x=t.find(N=>y&&z.resolve(N.rootPath)===y)??t.find(N=>N.name===k.name||z.basename(N.rootPath)===k.name);if(!x)continue;let b=o.get(x.name);for(let N of k.ports)b.ports.add(N.container),N.host&&b.ports.add(N.host);for(let N of Ei(k.env,s(g)))(b.env.get(N.name)??b.env.set(N.name,[]).get(N.name)).push(N);l(k.name.toLowerCase(),x.name,"docker-compose service name")}}for(let[g,w]of[...m].sort((S,k)=>S[0]<k[0]?-1:1)){let S=z.dirname(g),k=new Map;for(let y of w){let x=z.resolve(S,y.rootDir||"."),b=y.rootDir?t.find($=>z.resolve($.rootPath)===x):null;if(!b&&y.startCommand)for(let $ of y.startCommand.split(/\s+/)){if(!/\.(c|m)?[jt]sx?$/.test($)&&!/^[\w./-]+\/[\w.-]+$/.test($))continue;let F=z.resolve(x,$),H=t.filter(P=>F.startsWith(z.resolve(P.rootPath)+z.sep)).sort((P,K)=>K.rootPath.length-P.rootPath.length)[0];if(H){b=H;break}}if(b=b??t.find($=>$.name===y.name||z.basename($.rootPath)===y.name),!b)continue;k.set(y.name,{target:b,c:y});let N=o.get(b.name);for(let $ of y.kept)f(N,{...$,scoped:!0});l(y.name.toLowerCase(),b.name,"render.yaml service name"),l(`${y.name.toLowerCase()}.onrender.com`,b.name,"render.yaml service name (Render's default public address)")}for(let{target:y,c:x}of k.values())for(let b of x.hostRefs){let N=k.get(b.service);if(!N)continue;let $=[...N.c.kept].find(P=>P.kind==="port")?.port??null,F=b.property==="hostport"&&$,H=b.service.toLowerCase();f(o.get(y.name),{name:b.name,kind:"url",file:s(g),scheme:"http",host:H,port:F?$:null,origin:`http://${H}${F?":"+$:""}`,path:""})}}let p=g=>[...n.get(g.name)?.parseResults?.values()??[]].some(w=>(w.routes??[]).length>0);for(let g of t){let w=o.get(g.name);if(w.isServer=p(g),w.isServer){for(let[S,k]of w.env)if(md.test(S))for(let y of k)y.kind==="url"&&y.file&&(y.scoped||z.posix.dirname(y.file)===(Ci(z.relative(e,g.rootPath))||"."))&&l(y.host,g.name,`${S} in ${y.file} (the server's own public address)`)}}for(let g of t){let w=o.get(g.name);for(let[,S]of n.get(g.name)?.parseResults??[])for(let k of S.httpClients?.listens??[])for(let y of h(w,k.parts)){let x=Bo(y.text);x&&w.ports.add(x)}}for(let g of t)for(let w of o.get(g.name).ports)a(r,w,g.name);for(let g of t)for(let w of o.get(g.name).weakPorts)t.some(S=>o.get(S.name).ports.has(w))||a(r,w,g.name);function h(g,w){let S=[{text:"",evidence:[]}];for(let k of w){let y;if(k.t==="lit")y=[{text:k.v,evidence:[]}];else if(k.t==="env"){let b=g.env.get(k.name)??[];y=[];for(let N of b)y.push({text:N.kind==="port"?String(N.port):N.origin+N.path,evidence:[{env:k.name,file:N.file}]});!y.length&&k.fallback&&(y=h(g,k.fallback).map($=>({text:$.text,evidence:[{env:k.name,file:null,fallback:!0},...$.evidence]})))}else y=[];if(!y.length)return[];let x=[];for(let b of S)for(let N of y)if(x.push({text:b.text+N.text,evidence:[...b.evidence,...N.evidence]}),x.length>=8)break;S=x.slice(0,8)}return S}let v=(g,w)=>{let S=[],k=g.host,y=i.get(k)??[];for(let x of y)S.push(x);if(hd.has(k)||y.length&&y.some(x=>x.via==="docker-compose service name")){let x=g.port??(g.scheme==="https"||g.scheme==="wss",null);if(x)for(let b of r.get(x)??[])S.some(N=>N.service===b)||S.push({service:b,via:`port ${x} (a service listening there)`})}return S.filter(x=>x.service!==w)};return{resolveBase(g,w){let S=o.get(g);if(!S||!w.length)return{status:"unknown"};let k=h(S,w);if(!k.length)return{status:"unknown"};let y=[],x=new Set;for(let $ of k){let F=Qe($.text)??($.text.startsWith("//"),null);if(F){x.add(F.origin);for(let H of v(F,g))y.push({...H,u:F,evidence:$.evidence})}}if(!x.size)return{status:"unknown"};let b=[...new Set(y.map($=>$.service))];if(b.length===0)return{status:"external",origins:[...x].sort()};if(b.length>1)return{status:"ambiguous",services:b.sort()};let N=y[0];return{status:"service",service:N.service,via:N.via,origin:N.u.origin,basePath:N.u.path,evidence:N.evidence.filter(($,F,H)=>H.findIndex(P=>P.env===$.env&&P.file===$.file)===F)}},resolveProxy(g,w){let S=o.get(g);for(let k of S?.proxies??[]){if(k.prefix&&w!==k.prefix&&!w.startsWith(k.prefix+"/"))continue;let y=v(k.target,g),x=[...new Set(y.map(b=>b.service))];if(x.length===1)return{status:"service",service:x[0],via:`${k.kind} ${k.prefix||"/"} -> ${k.target.origin}`,origin:k.target.origin,basePath:k.target.path,strip:k.strip?k.prefix.split("/").filter(Boolean).length:0,evidence:[{env:null,file:k.file}]}}return{status:"unknown"}},portsOf:g=>[...o.get(g)?.ports??[]].sort((w,S)=>w-S),hostClaims:()=>[...i].sort((g,w)=>g[0]<w[0]?-1:1)}}function Ln(e){try{return Do.readdirSync(e).sort()}catch{return[]}}var Tn=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 Ri(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 Uo(e){if(!e.length)return null;let t=e.slice(),n="none",s=null,o=t[0];if(o.t==="lit"){let c=/^(https?:)\/\/([^/?#]*)(.*)$/.exec(o.v);if(c){n="abs",s=c[2];let d=c[3];if(t=d?[{t:"lit",v:d},...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,a=!1;for(let c of t){if(a)break;if(c.t==="lit"){let d=c.v.search(/[?#]/);d>=0?(r+=c.v.slice(0,d),a=!0):r+=c.v}else r+="",i++}if(!r.startsWith("/")&&!(r===""&&n==="abs"))return null;r===""&&(r="/");let l=r.split("/").slice(1).map(c=>c.includes("")?":p":c);for(;l.length>1&&l[l.length-1]==="";)l.pop();return{base:n,host:s,segments:l,placeholders:i,literal:n==="none"&&i===0}}function Ai(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 wd=e=>String(e||"").split("/").filter(Boolean),Oi=e=>[...new Set(e)];function Mi(e){let t=e.evidence??[];return{env:Oi(t.filter(n=>n.env).map(n=>n.env)),files:Oi(t.filter(n=>n.file).map(n=>n.file)),origin:e.origin,via:e.via,...t.some(n=>n.fallback)?{usedFallback:!0}:{}}}var Hi=(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+")",Sd=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 Di(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 kd(e,t,n,s,o){let r=(n.importBindings??[]).find(m=>m.local===s);if(!r)return null;let i=ze(r.source,t,o);if(!i)return null;let a=e.parseResults.get(i),l=m=>e.nodes.find(f=>f.filePath===i&&f.name===m&&f.type!=="moduleRoot")?.id??null;if(r.kind==="named"&&r.imported)return l(r.imported);let c=a?.exportBindings;if(c?.default&&c.default!=="<anon>")return l(c.default);let d=Object.keys(c?.named??{});return d.length===1?l(d[0]):null}function Nd(e){let t=[],n=[...e.parseResults.keys()];for(let[s,o]of e.parseResults){let r=e.nodes.filter(l=>l.filePath===s);if(r[0]?.category!=="backend")continue;let i=Ue(s,o),a=de(s,e.nodes);for(let l of o.routes??[]){let c=null;l.isInlineHandler?c=i.get(l):l.nest?c=r.find(m=>m.type==="classMethod"&&m.className===l.nest.className&&m.name===l.nest.methodName)?.id??null:l.handlerName&&a.has(l.handlerName)?c=a.get(l.handlerName):l.handlerName&&(c=kd(e,s,o,l.handlerName,n));let d=!1;c||(c=ue(l.startLine,r)?.id??null,d=!0),c&&t.push({method:Tn(l.method),path:l.path,segments:Sd(l.path),literal:!/[:*{]/.test(l.path),nodeId:c,file:s,line:l.startLine,fallback:d})}}return t}var bd=/^(ws|uws|websocket|@nestjs\/platform-ws|@fastify\/websocket|fastify-websocket|express-ws)$/,_d=/^(socket\.io|@nestjs\/platform-socket\.io|socket\.io-client)$/;function Bi(e){let t=[...e].some(s=>_d.test(s)),n=[...e].some(s=>bd.test(s));return t&&n?"unknown":t?"socketio":n?"ws":null}function $d(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(h=>h.eventName==="connection");if(!i)continue;let a=Ue(s,o),l=de(s,e.nodes),c=h=>h.isInlineHandler?a.get(h):h.handlerName&&l.has(h.handlerName)?l.get(h.handlerName):null,d=c(i);if(!d)continue;let m=h=>i.handlerStartLine!=null&&h.startLine>=i.handlerStartLine&&h.startLine<=i.handlerEndLine,f=r.find(h=>h.eventName==="message"&&m(h))??r.find(h=>h.eventName==="message"),u=o.httpClients?.wsServers??[],p=Bi(new Set((o.imports??[]).map(h=>h.source)))??Bi(n)??"unknown";t.push({filePath:s,nodeId:d,line:i.startLine,messageNodeId:f?c(f):null,messageLine:f?.startLine??null,pathParts:u.find(h=>h.path)?.path??null,kind:p})}return t}function Ui(e,t,n={}){let s=n.repoRoot?Ti(n.repoRoot,e,t):null,o=[],r=new Set,i={restCalls:0,restLinked:0,wsClients:0,wsLinked:0,wsSends:0,wsSendsLinked:0},a=c=>{let d=[c.fromService,c.fromNodeId,c.toService,c.toNodeId,c.via,c.key].join("\0");r.has(d)||(r.add(d),o.push(c))},l=new Map;for(let c of e){let d=t.get(c.name);d&&l.set(c.name,{routes:Nd(d),wsServers:$d(d)})}for(let c of e){let d=t.get(c.name);if(!d)continue;let m=[...d.parseResults.keys()],f=new Map,u=new Map;for(let[y,x]of d.parseResults){let b=x.httpClients;if(b){for(let N of b.httpInstances??[])(f.get(N.name)??f.set(N.name,[]).get(N.name)).push(N);for(let N of b.httpCalls??[])(N.parts.some(F=>F.t==="param")||N.method&&typeof N.method=="object")&&N.fn?.name&&(u.get(N.fn.name)??u.set(N.fn.name,[]).get(N.fn.name)).push({filePath:y,call:N})}}let p=y=>{if(!y.startsWith("inst:")&&!y.startsWith("obj:"))return[];let x=f.get(y.slice(y.indexOf(":")+1));return x&&x.length===1?x[0].parts:y.startsWith("obj:")?null:[{t:"ref",name:"?"}]},h=[],v=(y,x)=>ue(x,d.nodes.filter(b=>b.filePath===y)),g=new Set,w=y=>y.parts.some(x=>x.t==="param")||y.method&&typeof y.method=="object";for(let[y,x]of d.parseResults){let b=x.httpClients;if(b){for(let N of b.httpCalls??[]){if(w(N))continue;let $=p(N.client);if($===null)continue;let F=v(y,N.line);F&&h.push({filePath:y,line:N.line,nodeId:F.id,method:N.method,parts:Rn([...$,...N.parts]),via:N.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let N of b.pathCallsites??[]){let $=u.get(N.callee);if($)for(let F of $){let H=F.filePath===y;if(!H){let D=(x.importBindings??[]).find(R=>R.local===N.callee||R.imported===N.callee);D&&ze(D.source,y,m)===F.filePath&&(H=!0)}if(!H)continue;let P=new Map(N.args.map(D=>[D.i,D.parts])),K=typeof F.call.method=="object"&&F.call.method?(()=>{let D=P.get(F.call.method.param);return D&&D.length===1&&D[0].t==="lit"?D[0].v.toUpperCase():"?"})():F.call.method,U=v(y,N.line);U&&(g.add(F.call),h.push({filePath:y,line:N.line,nodeId:U.id,method:K,parts:Ri([...p(F.call.client),...F.call.parts],P),via:F.call.client,wrapper:N.callee}))}}}}for(let[y,x]of d.parseResults)for(let b of x.httpClients?.httpCalls??[]){if(!w(b)||g.has(b))continue;let N=p(b.client);if(N===null)continue;let $=v(y,b.line);$&&h.push({filePath:y,line:b.line,nodeId:$.id,method:typeof b.method=="object"&&b.method?"?":b.method,parts:Ri([...N,...b.parts],null),via:b.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let y of h){let x=Uo(y.parts);if(!x)continue;i.restCalls++;let b=0,N=[];for(let U of e){if(U.name===c.name)continue;let D=l.get(U.name);if(D)for(let R of D.routes){if(!(y.method==="?"||y.method==null||R.method===Tn(y.method)||R.method==="all"||R.method==="use"))continue;let ee=Di(x.segments,R.segments);ee&&(ee>b&&(b=ee,N.length=0),ee===b&&N.push({service:U.name,route:R}))}}let $={status:"unknown"};if(s){let U=Rn(y.parts);if(x.base==="none"?$=s.resolveProxy(c.name,"/"+x.segments.join("/")):$=s.resolveBase(c.name,Ai(U)),$.status==="service"){let D=wd($.basePath);if(D.length||$.strip){let R=[...D,...x.segments.slice($.strip||0)];for(let G of l.get($.service)?.routes??[])(y.method==="?"||y.method==null||G.method===Tn(y.method)||G.method==="all"||G.method==="use")&&Di(R,G.segments)&&!N.some(ne=>ne.service===$.service&&ne.route.nodeId===G.nodeId)&&N.push({service:$.service,route:G,viaBasePath:!0})}}}if(!N.length)continue;let F=new Set(N.map(U=>U.service+"\0"+U.route.nodeId)),H=typeof y.method=="string"&&y.method!=="?",P=b===3&&x.literal&&H&&F.size===1&&N[0].route.literal&&!N[0].route.fallback&&N[0].route.method===Tn(y.method),K=[];x.base==="var"&&K.push("base URL is a variable, so the target service is guessed from the path"),x.base==="abs"&&K.push("absolute URL"),x.placeholders&&K.push("path has parameters"),b===1&&K.push("leading /api removed from the client path"),b===2&&K.push("route parameters matched fuzzily"),H||K.push("method not known"),F.size>1&&K.push(F.size+" candidate routes"),N.some(U=>U.route.fallback)&&K.push("route handler not resolved: linked to the function that registers the route"),$.status==="external"&&K.push("base URL is "+$.origins.join(" / ")+", which no service of this repo owns"),$.status==="ambiguous"&&K.push("base URL could belong to "+$.services.join(" or "));for(let U of N){i.restLinked++;let D=!P&&$.status==="service"&&$.service===U.service&&!U.route.fallback,R=D?Mi($):null,G=P?"exact":D?"resolved":"inferred",ee=!P&&$.status==="service"&&$.service!==U.service?["base URL belongs to "+$.service+", not this service"]:[];a({fromService:c.name,fromNodeId:y.nodeId,toService:U.service,toNodeId:U.route.nodeId,via:"httpCall",key:`${H?y.method:"ANY"} ${"/"+x.segments.join("/")}`,confidence:G,method:H?y.method:null,url:"/"+x.segments.join("/"),client:y.via,...y.wrapper?{wrapper:y.wrapper}:{},line:y.line,...P?{}:D?{reason:Hi(R,U.service)+(H?"":"; method not known"),resolvedFrom:R}:{reason:[...K,...ee].join("; ")||"path-only match"}})}}let S=[];for(let[y,x]of d.parseResults)for(let b of x.httpClients?.wsClients??[])S.push({filePath:y,w:b});let k=y=>y.client==="io"?"socketio":"ws";for(let{filePath:y,w:x}of S){let b=v(y,x.line);if(!b)continue;i.wsClients++;let N=Rn(x.parts),$=/^wss?:\/\//.test(N[0]?.v??"")?Uo([{t:"lit",v:N[0].v.replace(/^ws(s?):/,"http$1:")},...N.slice(1)]):Uo(N),F=s&&$?s.resolveBase(c.name,Ai(N)):{status:"unknown"};for(let H of e)if(H.name!==c.name)for(let P of l.get(H.name)?.wsServers??[]){if(P.kind!=="unknown"&&P.kind!==k(x))continue;let K=P.pathParts&&P.pathParts.every(ee=>ee.t==="lit")?"/"+P.pathParts.map(ee=>ee.v).join("").replace(/^\//,""):null,U=$?"/"+$.segments.join("/"):null;if(K&&U&&K!==U&&K!=="/"&&U!=="/")continue;let D=!!($&&$.literal&&K&&U===K&&P.kind!=="unknown"),R=!D&&F.status==="service"&&F.service===H.name,G=R?Mi(F):null;i.wsLinked++,a({fromService:c.name,fromNodeId:b.id,toService:H.name,toNodeId:P.nodeId,via:"webSocket",key:U??"(url unknown)",confidence:D?"exact":R?"resolved":"inferred",url:U,client:x.client,line:x.line,...D?{}:R?{reason:Hi(G,H.name),resolvedFrom:G}:{reason:"WebSocket connection matched to a WebSocket server of another service ("+($?.base==="var"?"URL base is a variable":"no path on the server to compare")+(F.status==="external"?"; base URL is "+F.origins.join(" / ")+", which no service of this repo owns":"")+")"}})}}if(S.length){let y=new Set(S.map(({w:x})=>k(x)));for(let[x,b]of d.parseResults)for(let N of b.httpClients?.wsSends??[]){let $=v(x,N.line);if($){i.wsSends++;for(let F of e)if(F.name!==c.name)for(let H of l.get(F.name)?.wsServers??[])!H.messageNodeId||H.kind!=="unknown"&&!y.has(H.kind)||(i.wsSendsLinked++,a({fromService:c.name,fromNodeId:$.id,toService:F.name,toNodeId:H.messageNodeId,via:"webSocketMessage",key:"message",eventName:"message",confidence:"inferred",client:N.recv,line:N.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 c=new Map;for(let m of o)if(m.via==="webSocket"){let f=m.fromService+"\0"+m.toService;(c.get(f)??c.set(f,[]).get(f)).push(m)}let d=new Map;for(let m of c.values())(d.get(m[0].toService)??d.set(m[0].toService,new Set).get(m[0].toService)).add(m[0].fromService);for(let[,m]of[...c].sort((f,u)=>f[0]<u[0]?-1:1)){let f=m[0].fromService,u=m[0].toService,p=t.get(f),h=t.get(u);if(!p||!h||!(l.get(u)?.wsServers??[]).length)continue;let v=new Set(m.map(k=>k.fromNodeId.split("::")[0])),g=[];for(let[k,y]of p.parseResults){if(!v.has(k))continue;let x=de(k,p.nodes),b=Ue(k,y),N=p.nodes.filter($=>$.filePath===k);for(let $ of y.httpClients?.wsReceivers??[]){let F=$.handlerName&&x.get($.handlerName)||ue($.line,N)?.id;F&&g.push({id:F,line:$.line})}for(let $ of y.socketListeners??[]){if($.eventName!=="message")continue;let F=$.isInlineHandler?b.get($):$.handlerName&&x.get($.handlerName)||null;F&&g.push({id:F,line:$.startLine})}}let w=new Set(p.resolvedEdges.filter(k=>k.resolved&&k.targetNodeId&&k.type!=="returnValue").map(k=>k.fromNodeId));for(let k=g.length-1;k>=0;k--)w.has(g[k].id)||g.splice(k,1);if(!g.length)continue;let S=d.get(u)?.size??1;for(let[k,y]of h.parseResults){let x=h.nodes.filter(b=>b.filePath===k);for(let b of[...y.httpClients?.wsSends??[],...y.httpClients?.wsServerSends??[]]){let N=ue(b.line,x);if(N)for(let $ of g)i.wsPushLinked=(i.wsPushLinked??0)+1,a({fromService:u,fromNodeId:N.id,toService:f,toNodeId:$.id,via:"webSocketDelivery",key:"message",eventName:"message",confidence:"inferred",client:b.recv,line:b.line,receiverLine:$.line,reason:"a message the server sends over a WebSocket (payload built at run time) is taken in by the message handler of "+f+", which connects to this server"+(S>1?"; "+S+" services connect to this server, so it may be meant for another one":""),...S>1?{candidates:S}:{}})}}}}return o.sort((c,d)=>c.fromService+c.fromNodeId+c.via+c.key+c.toService+c.toNodeId<d.fromService+d.fromNodeId+d.via+d.key+d.toService+d.toNodeId?-1:1),{edges:o,stats:i}}function zi(e,t){let n=new Map;for(let[s,o]of e){let r=t.filter(a=>a.filePath===s),i=o.rawSocketTypeChecks??[];for(let a of i){let l=ue(a.startLine,r);l&&n.set(a.eventName,l.id)}}return n}import Id from"node:fs";import Fd from"node:path";function Wi(e){let t=["index.html","public/index.html","client/index.html","frontend/index.html","src/index.html"];for(let n of t){let s=Fd.join(e,n);if(Id.existsSync(s))return s}return null}import An from"node:fs";import On from"node:path";var jd=new Set(["node","tsx","ts-node","nodemon","bun","deno","ts-node-esm"]),Cd=new Set(["watch","run","start","dev"]),Ed=/\.[cm]?[jt]sx?$/,Pd=["start","dev","serve","run"];function Ld(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=>jd.has(On.basename(o).replace(/\.cmd$/,"")));if(!(s<0)){for(let o of n.slice(s+1))if(!(o.startsWith("-")||Cd.has(o)||o.includes("="))){if(Ed.test(o))return o;break}}}return null}var Td=e=>String(e).replace(/^@[^/]+\//,"");function qi(e){let t;try{t=JSON.parse(An.readFileSync(On.join(e,"package.json"),"utf8"))}catch{return[]}let n=[],s=(o,r,i={})=>{if(typeof o!="string"||!o)return;let a=r==="script"?null:En(e,o,t);a?n.push({file:a.file,kind:r,...i,mappedFrom:o,mappedBy:a.how}):n.push({file:On.resolve(e,o),kind:r,...i})};if(typeof t.bin=="string")s(t.bin,"bin",{binName:Td(t.name??On.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 Pd){let r=t.scripts?.[o]&&Ld(t.scripts[o]);r&&s(r,"script")}return s(t.main,"main"),n}function Gi(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 Mn from"node:fs";import gt from"node:path";var Rd=50,Ad=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Ji=["",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts","/index.js","/index.ts","/index.mjs","/index.cjs","/index.tsx","/index.jsx"];function zo(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=zo(t);if(n)return n}return null}if(e&&typeof e=="object")for(let t of["import","node","require","default"]){let n=zo(e[t]);if(n)return n}return null}function Ki(e,t){let n;try{n=JSON.parse(Mn.readFileSync(gt.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(c=>c.startsWith("."))?null:s):null,r=zo(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(c=>gt.resolve(c))),a=gt.resolve(e,r);for(let c of Ji)if(i.has(a+c))return t.find(d=>gt.resolve(d)===a+c);let l=[];try{l=Mn.readdirSync(e).filter(c=>Ad.test(c)).sort()}catch{}for(let c of l){let d;try{d=Mn.readFileSync(gt.join(e,c),"utf8")}catch{continue}let m=/\bentry(?:Points)?\s*:\s*[\[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/.exec(d);if(!m)continue;let f=gt.resolve(e,m[1]);for(let u of Ji)if(i.has(f+u))return t.find(p=>gt.resolve(p)===f+u)}return null}function Vi(e,t,n,s,o=null){let r=new Map;for(let h of n){let v=r.get(h.filePath);v||r.set(h.filePath,v=[]),v.push(h)}let i=new Map,a=(h,v)=>{v&&(!i.has(v.id)||h<i.get(v.id))&&i.set(v.id,h)},l=new Map,c=(h,v)=>{let g=l.get(h);if(!g){g=new Map;let w="";try{w=Mn.readFileSync(h,"utf8")}catch{}for(let S of w.matchAll(/^[ \t]*(?:export\s+)?const\s+([\w$]+)\s*(?::[^=\n]+)?=\s*([\w$]+)\s*(?:as\s+[^;\n]+)?;?[ \t]*$/gm))S[1]!==S[2]&&g.set(S[1],S[2]);l.set(h,g)}return g.get(v)??null},d=(h,v)=>(r.get(h)??[]).find(g=>(g.type==="function"||g.type==="arrowFunction")&&g.name===v),m=(h,v)=>(r.get(h)??[]).filter(g=>g.type==="classMethod"&&g.className===v&&g.name!=="constructor"&&!/^[_#]/.test(g.name)),f=new Set;function u(h,v,g,w=0){let S=d(h,g);if(S){a(v,S);return}let k=m(h,g);for(let F of k)a(`${v}.${F.name}`,F);if(k.length||!o)return;let y=o.resolveName(h,g);if(y){a(v,y);return}let x=o.bindingFor(h,g),b=x&&w<3?o.resolveImport(h,x.source,x.kind,x.imported):null;if(b?.file&&b.local&&b.local!=="default"&&c(b.file,b.local)){u(b.file,v,b.local,w+1);return}let N=o.classForImport(h,g);if(N?.className)for(let F of m(N.file,N.className))a(`${v}.${F.name}`,F);if(N?.className)return;let $=c(h,g);$&&w<3&&u(h,v,$,w+1)}function p(h,v,g){let w=h+"|"+(g?[...g.keys()].sort().join(","):"*");if(f.has(w)||v>3)return;f.add(w);let S=t.get(h)?.exportBindings;if(!S)return;let k=y=>!g||g.has(y);for(let[y,x]of Object.entries(S.named??{}))k(y)&&u(h,g?.get(y)??y,x);S.default&&k("default")&&S.default!=="<anon>"&&u(h,g?.get("default")??S.default,S.default);for(let y of S.reexports??[]){if(!k(y.exported))continue;let x=ze(y.source,h,s);x&&p(x,v+1,new Map([[y.imported,g?.get(y.exported)??y.exported]]))}for(let y of S.stars??[]){let x=ze(y,h,s);x&&(g?p(x,v+1,g):p(x,v+1,null))}}return p(e,0,null),[...i].map(([h,v])=>({name:v,nodeId:h})).sort((h,v)=>h.name<v.name?-1:h.name>v.name?1:h.nodeId<v.nodeId?-1:1).slice(0,Rd)}De();import Yi from"node:path";import{fileURLToPath as Od}from"node:url";import{Parser as Xi,Language as Md}from"web-tree-sitter";var Qh=Yi.dirname(Od(globalThis.__canopyUrl("src/stage2_parse/initHtmlParser.js")));async function Zi(){await Xi.init();let e=new Xi,t=Yi.join(Ae("tree-sitter-html"),"tree-sitter-html.wasm"),n=await Md.load(t);return e.setLanguage(n),{parser:e,language:n}}function Qi(e,t){let s=oe(t,"htmlScriptRoot.scm").matches(e.rootNode);for(let o of s){let r=o.captures.find(a=>a.name==="attr_name"),i=o.captures.find(a=>a.name==="script_src");if(r&&r.node.text==="src"&&i)return i.node.text}return null}function ea(e,t,n){let s=[];e.forEach((l,c)=>{l.steps.forEach(d=>{if(!d.hasOwnSubTrace)return;let m=e.findIndex((f,u)=>u!==c&&f.steps[0]?.nodeId===d.nodeId);m!==-1&&s.push({fromWorkflowIndex:c,toWorkflowIndex:m,atNodeId:d.nodeId})})});let o=new Map;for(let l of t)o.set(l.id,l.serviceName??null);let r=new Map;function i(l,c,d,m){if(!l||!c||l===c)return;let f=`${l} -> ${c} -> ${d}`;r.has(f)?r.get(f).count+=1:r.set(f,{fromService:l,toService:c,viaMatchType:d,count:1});let u=r.get(f);m==="exact"?u.exact=(u.exact??0)+1:m==="inferred"?u.inferred=(u.inferred??0)+1:m==="resolved"&&(u.resolved=(u.resolved??0)+1)}for(let l of n){if(!l.resolved||!l.fromNodeId||!l.targetNodeId)continue;let c=o.get(l.fromNodeId)??null,d=o.get(l.targetNodeId)??null;i(c,d,l.matchType,l.confidence)}let a=Array.from(r.values());return{workflowLinks:s,serviceLinks:a}}var Bd=V.dirname(Hd(globalThis.__canopyUrl("src/index.js"))),ta=24*1e3*1e3;async function Wo(e,t={}){e=V.resolve(e),console.log(`
21
21
  Analyzing: ${e}
22
- `),console.log("Stage 1: finding source files...");let n=lo(e),r=n.files;Hs(Bs(e,r)),console.log(` found ${r.length} files`);let{parser:o,language:s,grammars:i}=await kr();await Sr({grammars:i},r),console.log(`
23
- Stage 1b: partitioning files by service...`);let a=Ns(e,r),l=bs(a,r,e);a=l.services,l.added&&console.log(` note: ${l.added.reason} (service "${l.added.name}")`),console.log(` detected ${a.length} services: ${a.map(F=>`${F.name} (${F.kind})`).join(", ")}`);let c=new Map(a.map(F=>[F.name,[]])),d=[];for(let F of r){let P=lt(F,a);P?c.get(P).push(F):d.push(F)}console.log(" file partition:");for(let F of a)console.log(` ${F.name}: ${c.get(F.name).length} files`);console.log(` unassigned (shared/root-level): ${d.length} files`),d.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(`
24
- Stage 2: parsing (all files, once \u2014 see note above)...`);let p=await ws(r,o,s,{onProgress:t.onProgress,grammars:i});function f(F){let P=new Set;for(let R of F){let I=p.get(R);if(I)for(let A of I.imports){let ae=Ae(A.source,R,r);ae&&d.includes(ae)&&P.add(ae)}}return[...P]}let u=new Map;for(let F of a){let P=c.get(F.name),R=f(P);u.set(F.name,[...P,...R]),console.log(` ${F.name}: ${P.length} own + ${R.length} shared file(s) pulled in by real imports = ${P.length+R.length} total scope`)}let m=a.filter(F=>!u.get(F.name)?.length);m.length&&(console.log(` excluding ${m.length} service(s) with 0 files: ${m.map(F=>F.name).join(", ")}`),a=a.filter(F=>u.get(F.name)?.length));let h=null,v=Ri(e);if(v){let{parser:F,language:P}=await Bi(),R=me.readFileSync(v,"utf-8"),I=F.parse(R),A=zi(I,P);if(A){let ae=J.dirname(v),T=J.join(ae,A);r.includes(T)&&(h=T,console.log(` found HTML root: ${A} -> ${T}`))}}let g=new Map,w=0,S=0;for(let F of a){let P=u.get(F.name);if(console.log(`
25
- --- Service: ${F.name} (${F.kind}) \u2014 ${P.length} files in scope ---`),!P.length){console.log(" 0 files \u2014 nothing to trace for this service."),g.set(F.name,{nodes:[],resolvedEdges:[],workflows:[],routeIndex:new Map,eventIndex:new Map,rawEventIndex:new Map,parseResults:new Map});continue}let R=ls(new Map(P.map(E=>[E,p.get(E)]))),I=_s(R,a),A=$s(R,a);I=js(I.concat(A)),console.log(` Stage 3: materialized ${A.length} inline-handler nodes before edge construction`);let ae=Cs(R,I),T=li(R,I),xe=fi(R,I),V=Li(R,I);for(let E of P){let Q=new Set(R.get(E)?.exportedNames??[]);for(let q of I.filter(U=>U.filePath===E))q.exported=Q.has(q.name)}let ve=Js(ae,I,R,P,T,xe,V),_e=ve.filter(E=>E.resolved).length;console.log(` Stage 4 (scoped): resolved ${_e}/${ve.length} edges`);for(let E of P){let Q=R.get(E),q=Q?.routes??[],U=Q?.listeners??[],ne=le(E,I),Pe=jt(E,Q?.imports??[],P),nn=[];F.kind==="server"&&(nn=Q?.socketListeners??[]),I=Vs(I,E,q,U,ne,nn,Pe)}let Ie=I.filter(E=>E.isEntryPoint),st=Ie.filter(E=>E.trigger?.resolvedVia==="in-file").length,Xe=Ie.filter(E=>E.trigger?.resolvedVia==="cross-file").length,Ze=Ie.filter(E=>E.trigger?.resolvedVia==="inline").length;console.log(` Stage 5 entry points by resolution: in-file named ${st}, cross-file named (BUG A) ${Xe}, inline (BUG B) ${Ze}`);let en=ve.filter(E=>E.type!=="reference"&&!E.viaArgument),tn=Xs(I,en),it=[];if(F.kind==="client"&&h&&P.includes(h)&&it.push({id:`${h}::__module_root__`,name:"main",trigger:{type:"htmlRoot",label:"index.html script"}}),!it.length){let E=wn(F.rootPath,r),Q=E&&P.find(q=>J.resolve(q)===E.entry);Q&&(console.log(` found HTML root for ${F.name}: ${J.relative(e,E.indexHtml)} -> ${J.relative(e,Q)} (${E.via})`),it.push({id:`${Q}::__module_root__`,name:"main",trigger:{type:"htmlRoot",label:"index.html script"}}))}let xt=[];if(F.kind==="server"){let E=J.join(F.rootPath,"package.json");if(me.existsSync(E))try{let Q=JSON.parse(me.readFileSync(E,"utf-8")),q=Q.main;if(!q&&Q.scripts?.start){let U=Q.scripts.start.match(/([\w./-]+\.(?:js|mjs|cjs|ts))/);U&&(q=U[1])}if(q){let U=J.resolve(F.rootPath,q),ne=P.find(Pe=>J.resolve(Pe)===U);if(!ne){let Pe=In(F.rootPath,q,Q);Pe&&(ne=P.find(nn=>J.resolve(nn)===Pe.file))}ne?xt.push({id:`${ne}::__module_root__`,name:"main",trigger:{type:"processBootstrap",label:`${q} (package.json main)`}}):console.log(` note: ${F.name}'s package.json names "${q}" as its entry, but that file isn't in this service's own traced scope \u2014 no bootstrap workflow added.`)}}catch{}}if(!it.length){let E=new Set(xt.map(U=>U.id.split("::")[0])),Q=new Set;for(let U of ve)U.resolved&&U.fromNodeId.endsWith("::__module_root__")&&Q.add(U.fromNodeId);let q=Ti(F.rootPath).map(U=>({...U,file:P.find(ne=>J.resolve(ne)===U.file)})).filter(U=>U.file);for(let U of P)Ai(U)&&!q.some(ne=>ne.file===U)&&q.push({file:U,kind:"shebang"});for(let U of q){if(E.has(U.file)||It(J.relative(e,U.file))||!Q.has(`${U.file}::__module_root__`))continue;E.add(U.file);let ne=J.relative(F.rootPath,U.file).split(J.sep).join("/"),Pe=U.kind==="bin"?`CLI: ${U.binName}`:`Start: ${ne}`;xt.push({id:`${U.file}::__module_root__`,name:"main",trigger:{type:"processBootstrap",label:`${ne} (${U.kind==="bin"?"package.json bin":U.kind==="script"?"package.json script":U.kind==="main"?"package.json main":"#! shebang"}${U.mappedFrom?`, built to ${U.mappedFrom}`:""})`,workflowName:Pe}})}}let Tt=[];if(it.length+xt.length+Ie.filter(E=>!It(J.relative(e,E.filePath))).length===0){let E=Mi(F.rootPath,P);if(E){let Q=J.relative(F.rootPath,E).split(J.sep).join("/"),U=bn(I,R,ne=>jt(ne,R.get(ne)?.imports??[],P));for(let ne of Hi(E,R,I,P,U))Tt.push({id:ne.nodeId,name:I.find(Pe=>Pe.id===ne.nodeId)?.name??ne.name,trigger:{type:"publicApi",label:`${ne.name} (exported from ${Q})`,workflowName:`API: ${ne.name}`}});Tt.length&&console.log(` public API of ${F.name}: ${Tt.length} exported function(s)/method(s) from ${Q}`)}}let Qo=new Set(Tt.map(E=>E.id)),Ca=Qo.size?tn.filter(E=>!Qo.has(E.id)):tn,Xn=[...it,...xt,...Ie,...Tt,...Ca];console.log(` Stage 5 total entry points: ${Xn.length} (${it.length} HTML root, ${xt.length} process bootstrap, ${Ie.length} pattern-matched, ${tn.length} fallback)`);let Ea=Co(ve),Pa=ei(Xn,Ea,I,en,8,en.length===ve.length?null:Co(en)),La=new Set(tn.map(E=>E.id)),Ra=E=>E.trigger?"physical":La.has(E.entryPointId)?"fallback":"hub",Ta=Pa.map(E=>({...E,origin:Ra(E),steps:ti(E.steps,I)})),Aa=oi(Ta),er=Array.from(Aa.values()).map(ri),tr=er.filter(E=>!It(J.relative(e,String(E.steps[0]?.nodeId??"").split("::")[0])));S+=er.length-tr.length;let vt=ci(tr,{nodes:I});if(vt.some(E=>E.trigger)){let E=new Set(ve.filter(q=>q.type!=="returnValue"&&q.type!=="reference").map(q=>q.fromNodeId)),Q=new Set(vt.filter(q=>!q.trigger&&q.steps.length===1&&!E.has(q.steps[0].nodeId)).map(q=>q.steps[0].nodeId));Q.size&&(vt=vt.filter(q=>q.trigger||!Q.has(q.steps[0].nodeId)||q.steps.length>1),w+=Q.size)}console.log(` Stage 6-7: -> ${vt.length} named workflows for ${F.name}`),g.set(F.name,{nodes:I,resolvedEdges:ve,routeIndex:T,eventIndex:xe,rawEventIndex:V,workflows:vt,parseResults:R,files:P,entryPointCount:Xn.length})}console.log(`
26
- --- Stage 5 (stitch): cross-service edge resolution ---`);let N=[],y=0,x=0;for(let F of a){let P=g.get(F.name);if(!P||!P.resolvedEdges.length)continue;let R=P.resolvedEdges.filter(I=>!I.resolved&&(I.type==="apiCall"||I.type==="socketEmit"||I.type==="rawSocketSend"));for(let I of R){let A=null,ae=null;for(let T of a){if(T.name===F.name)continue;let xe=g.get(T.name);if(!xe)continue;let V=null;if(I.type==="apiCall"&&I.scope!=="external"?V=xe.routeIndex.get(Ct(I.url)):I.type==="socketEmit"?V=xe.eventIndex.get(I.eventName):I.type==="rawSocketSend"&&(V=xe.rawEventIndex.get(I.eventName)),V){A=V,ae=T.name;break}}A?(N.push({fromService:F.name,fromNodeId:I.fromNodeId,toService:ae,toNodeId:A,via:I.type,key:I.url||I.eventName,confidence:"inferred",reason:"name-only match",...I.type==="apiCall"?{url:I.url}:{eventName:I.eventName}}),y++):x++}}console.log(` stitched ${y} cross-service edges`);let b=Pi(a,g,{repoRoot:e});for(let F of b.edges)N.push(F);console.log(` + ${b.edges.length} links from HTTP clients / WebSockets (${b.edges.filter(F=>F.confidence==="exact").length} exact, ${b.edges.filter(F=>F.confidence==="resolved").length} resolved)`),console.log(` ${x} unresolved calls remain unresolved even after checking every other service`);let k=new Map;function $(F,P,R){if(!F||P==null||R==null)return{available:!1,reason:"no line range recorded for this node"};try{k.has(F)||k.set(F,me.readFileSync(F,"utf-8").split(/\r\n|\n/));let I=k.get(F),A=Math.max(P,1),ae=Math.min(R,I.length);if(A>I.length)return{available:!1,reason:"recorded line range is past the end of the current file \u2014 source has likely moved"};let T=I.slice(A-1,ae).join(`
27
- `);return{available:!0,filePath:F,startLine:A,endLine:ae,text:T}}catch(I){return{available:!1,reason:`source unavailable: ${I.code==="ENOENT"?"file not found (deleted or moved)":I.message}`}}}let j=/^(addEventListener|removeEventListener|on|once|postMessage|onmessage|subscribe)$/i,D=new Set(["call","methodCall","callSite"]);function L(F,P,R,I,A=null){let ae=T=>!!(A&&!I&&!T.deferred&&T.resolved&&T.targetNodeId&&D.has(T.type)&&T.targetNodeId!==F&&A.inWorkflow.has(T.targetNodeId)&&!A.children.has(T.targetNodeId));return P.filter(T=>T.fromNodeId===F&&T.type!=="apiCall").filter(T=>T.resolved&&T.targetNodeId?ae(T):!!T.deferred===I).map(T=>{let xe=T.type==="returnValue",V=!xe&&j.test(T.calleeNameRaw||""),ve=(T.branchPath??[]).map(Xe=>({...Xe,source:R?$(R,Xe.conditionLine,Xe.conditionLine):{available:!1,reason:"owning function's node not found"}})),_e=T.objectNameRaw?`${T.objectNameRaw}.${T.calleeNameRaw}`:T.calleeNameRaw,Ie=xe?_e:T.firstArgText?`${_e}(${T.firstArgText})`:_e,st=ae(T);return{label:Ie,line:T.line??null,column:T.column??null,branchPath:ve,source:R?$(R,T.line,T.line):{available:!1,reason:"owning function's node not found"},tag:st?"called-elsewhere":xe?"return-value":V?"runtime-dispatched":"unresolvable-call-site",...st?{targetNodeId:T.targetNodeId}:{},reason:st?"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":V?`registered via ${T.calleeNameRaw}(...) \u2014 the handler runs later, outside this function's own execution`:I?"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 K(F,P,R){return L(F,P,R,!0)}function z(F,P,R,I){return L(F,P,R,!1,I)}let O=[];for(let F of a){let P=g.get(F.name);if(!P)continue;let R=new Map(P.nodes.map(I=>[I.id,I]));for(let I of P.workflows){let A=new Set([F.name]),ae=new Set(I.steps.map(V=>V.nodeId)),T=new Map;for(let V of I.steps)V.parentNodeId!=null&&(T.get(V.parentNodeId)??T.set(V.parentNodeId,new Set).get(V.parentNodeId)).add(V.nodeId);let xe=I.steps.map(V=>{let ve=N.find(Ze=>Ze.fromService===F.name&&Ze.fromNodeId===V.nodeId),_e=R.get(V.nodeId),Ie=V.parentNodeId?R.get(V.parentNodeId):null,st=(V.branchPath??[]).map(Ze=>({...Ze,source:Ie?$(Ie.filePath,Ze.conditionLine,Ze.conditionLine):{available:!1,reason:"owning function's node not found"}})),Xe={...V,branchPath:st,source:_e?$(_e.filePath,_e.startLine,_e.endLine):{available:!1,reason:"node not found in this service's own graph"},alsoCallsRuntime:K(V.nodeId,P.resolvedEdges,_e?.filePath),inlineCalls:z(V.nodeId,P.resolvedEdges,_e?.filePath,{inWorkflow:ae,children:T.get(V.nodeId)??new Set})};return ve&&(A.add(ve.toService),Xe.crossesInto=ve.toService),Xe});O.push({...I,steps:xe,serviceId:F.name,servicesTouched:[...A]})}}console.log(`
28
- Done: ${O.length} named workflows across all services
29
- `),O.forEach(F=>console.log(` - [${F.serviceId}] ${F.name} (${F.steps.length} steps, ${F.occurrences} entry point(s))`));let W=t.outputDir??process.env.CANOPY_OUTPUT_DIR??J.join(xd,"..","output");me.existsSync(W)||me.mkdirSync(W,{recursive:!0});let G=Nn(e),te=new Set(a.flatMap(F=>u.get(F.name)??[])),ge=xr({discovered:n,parseResults:p,scopeFiles:te,rel:G.rel,rootService:l.added});ge.testWorkflowsExcluded=S,ge.guessedWorkflowsDropped=w;let rt={repoRoot:G.repoRoot,coverage:ge};me.writeFileSync(J.join(W,"meta.js"),`const meta = ${JSON.stringify(rt,null,2)};`),me.writeFileSync(J.join(W,"meta.json"),JSON.stringify(rt,null,2)),console.log(`
30
- `+ln(ge)),me.existsSync(J.join(W,"history.js"))||me.writeFileSync(J.join(W,"history.js"),"const canopyHistory = null;");let Be=G.json(O,2),Qt=Be.length>qi;if(Qt&&(Be=G.json(O)),Qt&&Be.length>qi){let F=Ks(JSON.parse(Be));me.writeFileSync(J.join(W,"workflows.js"),`const workflows = ${F};`),me.rmSync(J.join(W,"workflows.json"),{force:!0}),console.log(`
31
- workflows.json omitted (${(Be.length/1e6).toFixed(1)} MB plain); workflows.js written with shared sub-structures (${(F.length/1e6).toFixed(1)} MB)`)}else me.writeFileSync(J.join(W,"workflows.json"),Be),console.log(`
32
- Saved to output/workflows.json`),me.writeFileSync(J.join(W,"workflows.js"),`const workflows = ${Be};`),console.log("Saved to output/workflows.js (for the viewer)");let Rt=a.flatMap(F=>g.get(F.name)?.nodes??[]),_=N.map(F=>({fromNodeId:F.fromNodeId,targetNodeId:F.toNodeId,resolved:!0,matchType:"crossLayer",confidence:F.confidence})),C=[...a.flatMap(F=>g.get(F.name)?.resolvedEdges??[]),..._],M=Wi(O,Rt,C);M.crossServiceEdges=N,me.writeFileSync(J.join(W,"systemGraph.js"),`const systemGraph = ${G.json(M,2)};`);let ie=a.map(({isRepoRoot:F,ownsLeftovers:P,...R})=>({...R,nodeCount:Rt.filter(I=>I.serviceName===R.name).length,workflowCount:O.filter(I=>I.serviceId===R.name).length}));me.writeFileSync(J.join(W,"services.js"),`const services = ${G.json(ie,2)};`),console.log(`Saved to output/systemGraph.js (${M.workflowLinks.length} workflow links, ${M.serviceLinks.length} service links)`),console.log("Saved to output/services.js"),console.log(`
33
- 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 ze=new Map;for(let F of a){let P=g.get(F.name);if(!P)continue;let R=G.clone(P.nodes.map(A=>({id:A.id,name:A.name,type:A.type,filePath:A.filePath,bodyHash:A.bodyHash??null,startLine:A.startLine===0?0:A.startLine,endLine:A.endLine===Number.MAX_SAFE_INTEGER?null:A.endLine,serviceName:A.serviceName,isEntryPoint:!!A.isEntryPoint}))),I=Is(G.clone(P.resolvedEdges.map(A=>({fromNodeId:A.fromNodeId,targetNodeId:A.targetNodeId??null,type:A.type,callKind:A.callKind,calleeNameRaw:A.calleeNameRaw,eventName:A.eventName,url:A.url,line:A.line??null,column:A.column??null,resolved:!!A.resolved,matchType:A.matchType??null}))));ze.set(F.name,{nodes:R,edges:I})}return{workflows:O,perService:g,crossServiceEdges:N,services:a,publicGraph:ze,publicWorkflows:G.clone(O),publicCrossServiceEdges:G.clone(N),fingerprint:kn(Sn(r,G.rel)),analyzedFileCount:r.length,repoRoot:G.repoRoot,coverage:ge}}var vd=process.argv[1]&&globalThis.__canopyUrl("src/index.js")===yd(J.resolve(process.argv[1])).href;vd&&Ho(process.argv[2]||process.cwd()).catch(e=>{console.error("Pipeline failed:",e),process.exit(1)});zo();Hn();pt();var Rd=he.join(he.dirname(ca(globalThis.__canopyUrl("src/history/sync.js"))),"..","..","output"),Td=["workflows.json","workflows.js","systemGraph.js","services.js","meta.js","meta.json","history.js"],Ad=he.dirname(ca(globalThis.__canopyUrl("src/history/sync.js"))).split(he.sep).includes("node_modules"),ht=e=>process.env.CANOPY_OUTPUT_DIR||(Ad&&e?he.join(he.resolve(e),".canopy","output"):Rd);async function Od(e,t){let n=console.log;console.log=()=>{};try{return await Ho(e,t)}finally{console.log=n}}function Md(e){let t=he.resolve(e),n=Nn(t);return kn(Sn(an(t),n.rel))}function Hd(e){try{let t=JSON.parse(nt.readFileSync(he.join(ht(e),"meta.json"),"utf8"));return t.coverage&&he.resolve(t.repoRoot)===he.resolve(e)?t.coverage:null}catch{return null}}async function Dd(e,{keep:t,say:n=()=>{}}){let r=Date.now(),o=He(e),s=o.versions[o.versions.length-1],i=Md(e),a=!!s&&s.fingerprint===i&&(s.engineVersion!==On()||s.outputFormat!==An);if(s&&s.fingerprint===i&&!a)return{status:"no-changes",version:s,ms:Date.now()-r,coverage:Hd(e)};let l=nt.mkdtempSync(he.join(Ld.tmpdir(),"canopy-sync-"));try{let c=await Od(e,{outputDir:l,onProgress:n}),d=Ji(c),p=Pt(d),f={nodes:d.nodes.length,edges:d.edges.length,workflows:d.workflows.length,physicalWorkflows:d.workflows.filter(v=>v.tier==="physical").length,crossServiceEdges:d.crossServiceEdges.length},u=Vi(e,p,d,f,t,{refresh:a}),m=await Promise.resolve().then(()=>(aa(),ia)).catch(()=>null);m&&m.writeHistoryJs(e,l);let h=ht(e);nt.mkdirSync(h,{recursive:!0});for(let v of Td)nt.existsSync(he.join(l,v))?nt.copyFileSync(he.join(l,v),he.join(h,v)):nt.rmSync(he.join(h,v),{force:!0});return{status:"new-version",version:u,ms:Date.now()-r,coverage:c.coverage}}finally{nt.rmSync(l,{recursive:!0,force:!0})}}async function zn(e,{keep:t=Wt,say:n=console.log}={}){if(e=he.resolve(e),Dn(e),nt.mkdirSync(se(e).root,{recursive:!0}),!Yi(e))return Zi(e),n("sync already running - one rerun queued"),{status:"queued"};let r;try{do r=await Dd(e,{keep:t,say:n}),r.status==="no-changes"?n(`no changes (v${r.version.version} ${r.version.fingerprint.slice(0,7)}) [${r.ms} ms]`):n(`v${r.version.version} ${r.version.fingerprint.slice(0,7)} stored: ${r.version.counts.nodes} nodes, ${r.version.counts.edges} edges, ${r.version.counts.workflows} workflows, ${(r.version.bytes/1024/1024).toFixed(2)} MB${r.version.gzip?" (gzip)":""} [${r.ms} ms]`),r.coverage&&n(`
34
- `+ln(r.coverage));while(Qi(e))}finally{Xi(e)}return r}pt();pt();Le();import ue from"node:fs";import Ce from"node:path";import{spawn as Ud}from"node:child_process";import{fileURLToPath as Bd}from"node:url";var qt="# >>> canopy sync (managed block - do not edit) >>>",fa="# <<< canopy sync <<<",gt=["post-commit","post-merge"],zd=globalThis.__canopyBundle??Ce.join(Ce.dirname(Bd(globalThis.__canopyUrl("src/history/hooks.js"))),"..","cli.js"),Wd=e=>Ce.resolve(e).split(Ce.sep).join("/");function Gt(e){let t=be(e,["rev-parse","--git-path","hooks"]);if(!t)throw new Error(`not a git repository: ${e}`);return Ce.resolve(e,t)}var la=JSON.parse(ue.readFileSync(Ce.join(re,"package.json"),"utf8")),qd=la.name+"@"+la.version,da=e=>Wd(e).replace(/(["$`\\])/g,"\\$1");function Wn(e){return[qt,"(",` if command -v canopy >/dev/null 2>&1; then canopy sync --background "${da(e)}" >/dev/null 2>&1 </dev/null`,` elif command -v npx >/dev/null 2>&1; then ( npx --yes ${qd} sync --background "${da(e)}" >/dev/null 2>&1 </dev/null & )`,' else echo "canopy not found; skipping map update"'," fi",") || true",fa].join(`
22
+ `),console.log("Stage 1: finding source files...");let n=ho(e),s=n.files;Vr(Zr(e,s)),console.log(` found ${s.length} files`);let{parser:o,language:r,grammars:i}=await Ps();await Es({grammars:i},s),console.log(`
23
+ Stage 1b: partitioning files by service...`);let a=Lr(e,s),l=Tr(a,s,e);a=l.services,l.added&&console.log(` note: ${l.added.reason} (service "${l.added.name}")`),console.log(` detected ${a.length} services: ${a.map(I=>`${I.name} (${I.kind})`).join(", ")}`);let c=new Map(a.map(I=>[I.name,[]])),d=[];for(let I of s){let T=pt(I,a);T?c.get(T).push(I):d.push(I)}console.log(" file partition:");for(let I of a)console.log(` ${I.name}: ${c.get(I.name).length} files`);console.log(` unassigned (shared/root-level): ${d.length} files`),d.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(`
24
+ Stage 2: parsing (all files, once \u2014 see note above)...`);let m=await Cr(s,o,r,{onProgress:t.onProgress,grammars:i});function f(I){let T=new Set;for(let A of I){let j=m.get(A);if(j)for(let M of j.imports){let ce=ze(M.source,A,s);ce&&d.includes(ce)&&T.add(ce)}}return[...T]}let u=new Map;for(let I of a){let T=c.get(I.name),A=f(T);u.set(I.name,[...T,...A]),console.log(` ${I.name}: ${T.length} own + ${A.length} shared file(s) pulled in by real imports = ${T.length+A.length} total scope`)}let p=a.filter(I=>!u.get(I.name)?.length);p.length&&(console.log(` excluding ${p.length} service(s) with 0 files: ${p.map(I=>I.name).join(", ")}`),a=a.filter(I=>u.get(I.name)?.length));let h=null,v=Wi(e);if(v){let{parser:I,language:T}=await Zi(),A=he.readFileSync(v,"utf-8"),j=I.parse(A),M=Qi(j,T);if(M){let ce=V.dirname(v),O=V.join(ce,M);s.includes(O)&&(h=O,console.log(` found HTML root: ${M} -> ${O}`))}}let g=new Map,w=0,S=0;for(let I of a){let T=u.get(I.name);if(console.log(`
25
+ --- Service: ${I.name} (${I.kind}) \u2014 ${T.length} files in scope ---`),!T.length){console.log(" 0 files \u2014 nothing to trace for this service."),g.set(I.name,{nodes:[],resolvedEdges:[],workflows:[],routeIndex:new Map,eventIndex:new Map,rawEventIndex:new Map,parseResults:new Map});continue}let A=vr(new Map(T.map(L=>[L,m.get(L)]))),j=Rr(A,a),M=Ar(A,a);j=Hr(j.concat(M)),console.log(` Stage 3: materialized ${M.length} inline-handler nodes before edge construction`);let ce=Dr(A,j),O=vi(A,j),we=Si(A,j),X=zi(A,j);for(let L of T){let te=new Set(A.get(L)?.exportedNames??[]);for(let J of j.filter(W=>W.filePath===L))J.exported=te.has(J.name)}let Se=oi(ce,j,A,T,O,we,X),Pe=Se.filter(L=>L.resolved).length;console.log(` Stage 4 (scoped): resolved ${Pe}/${Se.length} edges`);for(let L of T){let te=A.get(L),J=te?.routes??[],W=te?.listeners??[],se=de(L,j),He=Tt(L,te?.imports??[],T),rn=[];I.kind==="server"&&(rn=te?.socketListeners??[]),j=ri(j,L,J,W,se,rn,He)}let Re=j.filter(L=>L.isEntryPoint),lt=Re.filter(L=>L.trigger?.resolvedVia==="in-file").length,tt=Re.filter(L=>L.trigger?.resolvedVia==="cross-file").length,nt=Re.filter(L=>L.trigger?.resolvedVia==="inline").length;console.log(` Stage 5 entry points by resolution: in-file named ${lt}, cross-file named (BUG A) ${tt}, inline (BUG B) ${nt}`);let on=Se.filter(L=>L.type!=="reference"&&!L.viaArgument),sn=ai(j,on),dt=[];if(I.kind==="client"&&h&&T.includes(h)&&dt.push({id:`${h}::__module_root__`,name:"main",trigger:{type:"htmlRoot",label:"index.html script"}}),!dt.length){let L=Nn(I.rootPath,s),te=L&&T.find(J=>V.resolve(J)===L.entry);te&&(console.log(` found HTML root for ${I.name}: ${V.relative(e,L.indexHtml)} -> ${V.relative(e,te)} (${L.via})`),dt.push({id:`${te}::__module_root__`,name:"main",trigger:{type:"htmlRoot",label:"index.html script"}}))}let Nt=[];if(I.kind==="server"){let L=V.join(I.rootPath,"package.json");if(he.existsSync(L))try{let te=JSON.parse(he.readFileSync(L,"utf-8")),J=te.main;if(!J&&te.scripts?.start){let W=te.scripts.start.match(/([\w./-]+\.(?:js|mjs|cjs|ts))/);W&&(J=W[1])}if(J){let W=V.resolve(I.rootPath,J),se=T.find(He=>V.resolve(He)===W);if(!se){let He=En(I.rootPath,J,te);He&&(se=T.find(rn=>V.resolve(rn)===He.file))}se?Nt.push({id:`${se}::__module_root__`,name:"main",trigger:{type:"processBootstrap",label:`${J} (package.json main)`}}):console.log(` note: ${I.name}'s package.json names "${J}" as its entry, but that file isn't in this service's own traced scope \u2014 no bootstrap workflow added.`)}}catch{}}if(!dt.length){let L=new Set(Nt.map(W=>W.id.split("::")[0])),te=new Set;for(let W of Se)W.resolved&&W.fromNodeId.endsWith("::__module_root__")&&te.add(W.fromNodeId);let J=qi(I.rootPath).map(W=>({...W,file:T.find(se=>V.resolve(se)===W.file)})).filter(W=>W.file);for(let W of T)Gi(W)&&!J.some(se=>se.file===W)&&J.push({file:W,kind:"shebang"});for(let W of J){if(L.has(W.file)||Lt(V.relative(e,W.file))||!te.has(`${W.file}::__module_root__`))continue;L.add(W.file);let se=V.relative(I.rootPath,W.file).split(V.sep).join("/"),He=W.kind==="bin"?`CLI: ${W.binName}`:`Start: ${se}`;Nt.push({id:`${W.file}::__module_root__`,name:"main",trigger:{type:"processBootstrap",label:`${se} (${W.kind==="bin"?"package.json bin":W.kind==="script"?"package.json script":W.kind==="main"?"package.json main":"#! shebang"}${W.mappedFrom?`, built to ${W.mappedFrom}`:""})`,workflowName:He}})}}let Dt=[];if(dt.length+Nt.length+Re.filter(L=>!Lt(V.relative(e,L.filePath))).length===0){let L=Ki(I.rootPath,T);if(L){let te=V.relative(I.rootPath,L).split(V.sep).join("/"),W=In(j,A,se=>Tt(se,A.get(se)?.imports??[],T));for(let se of Vi(L,A,j,T,W))Dt.push({id:se.nodeId,name:j.find(He=>He.id===se.nodeId)?.name??se.name,trigger:{type:"publicApi",label:`${se.name} (exported from ${te})`,workflowName:`API: ${se.name}`}});Dt.length&&console.log(` public API of ${I.name}: ${Dt.length} exported function(s)/method(s) from ${te}`)}}let ls=new Set(Dt.map(L=>L.id)),Qa=ls.size?sn.filter(L=>!ls.has(L.id)):sn,no=[...dt,...Nt,...Re,...Dt,...Qa];console.log(` Stage 5 total entry points: ${no.length} (${dt.length} HTML root, ${Nt.length} process bootstrap, ${Re.length} pattern-matched, ${sn.length} fallback)`);let ec=Ro(Se),tc=di(no,ec,j,on,8,on.length===Se.length?null:Ro(on)),nc=new Set(sn.map(L=>L.id)),oc=L=>L.trigger?"physical":nc.has(L.entryPointId)?"fallback":"hub",sc=tc.map(L=>({...L,origin:oc(L),steps:fi(L.steps,j)})),rc=pi(sc),ds=Array.from(rc.values()).map(mi),fs=ds.filter(L=>!Lt(V.relative(e,String(L.steps[0]?.nodeId??"").split("::")[0])));S+=ds.length-fs.length;let bt=xi(fs,{nodes:j});if(bt.some(L=>L.trigger)){let L=new Set(Se.filter(J=>J.type!=="returnValue"&&J.type!=="reference").map(J=>J.fromNodeId)),te=new Set(bt.filter(J=>!J.trigger&&J.steps.length===1&&!L.has(J.steps[0].nodeId)).map(J=>J.steps[0].nodeId));te.size&&(bt=bt.filter(J=>J.trigger||!te.has(J.steps[0].nodeId)||J.steps.length>1),w+=te.size)}console.log(` Stage 6-7: -> ${bt.length} named workflows for ${I.name}`),g.set(I.name,{nodes:j,resolvedEdges:Se,routeIndex:O,eventIndex:we,rawEventIndex:X,workflows:bt,parseResults:A,files:T,entryPointCount:no.length})}console.log(`
26
+ --- Stage 5 (stitch): cross-service edge resolution ---`);let k=[],y=0,x=0;for(let I of a){let T=g.get(I.name);if(!T||!T.resolvedEdges.length)continue;let A=T.resolvedEdges.filter(j=>!j.resolved&&(j.type==="apiCall"||j.type==="socketEmit"||j.type==="rawSocketSend"));for(let j of A){let M=null,ce=null;for(let O of a){if(O.name===I.name)continue;let we=g.get(O.name);if(!we)continue;let X=null;if(j.type==="apiCall"&&j.scope!=="external"?X=we.routeIndex.get(Rt(j.url)):j.type==="socketEmit"?X=we.eventIndex.get(j.eventName):j.type==="rawSocketSend"&&(X=we.rawEventIndex.get(j.eventName)),X){M=X,ce=O.name;break}}M?(k.push({fromService:I.name,fromNodeId:j.fromNodeId,toService:ce,toNodeId:M,via:j.type,key:j.url||j.eventName,confidence:"inferred",reason:"name-only match",...j.type==="apiCall"?{url:j.url}:{eventName:j.eventName}}),y++):x++}}console.log(` stitched ${y} cross-service edges`);let b=Ui(a,g,{repoRoot:e});for(let I of b.edges)k.push(I);console.log(` + ${b.edges.length} links from HTTP clients / WebSockets (${b.edges.filter(I=>I.confidence==="exact").length} exact, ${b.edges.filter(I=>I.confidence==="resolved").length} resolved)`),console.log(` ${x} unresolved calls remain unresolved even after checking every other service`);let N=new Map;function $(I,T,A){if(!I||T==null||A==null)return{available:!1,reason:"no line range recorded for this node"};try{N.has(I)||N.set(I,he.readFileSync(I,"utf-8").split(/\r\n|\n/));let j=N.get(I),M=Math.max(T,1),ce=Math.min(A,j.length);if(M>j.length)return{available:!1,reason:"recorded line range is past the end of the current file \u2014 source has likely moved"};let O=j.slice(M-1,ce).join(`
27
+ `);return{available:!0,filePath:I,startLine:M,endLine:ce,text:O}}catch(j){return{available:!1,reason:`source unavailable: ${j.code==="ENOENT"?"file not found (deleted or moved)":j.message}`}}}let F=/^(addEventListener|removeEventListener|on|once|postMessage|onmessage|subscribe)$/i,H=new Set(["call","methodCall","callSite"]);function P(I,T,A,j,M=null){let ce=O=>!!(M&&!j&&!O.deferred&&O.resolved&&O.targetNodeId&&H.has(O.type)&&O.targetNodeId!==I&&M.inWorkflow.has(O.targetNodeId)&&!M.children.has(O.targetNodeId));return T.filter(O=>O.fromNodeId===I&&O.type!=="apiCall").filter(O=>O.resolved&&O.targetNodeId?ce(O):!!O.deferred===j).map(O=>{let we=O.type==="returnValue",X=!we&&F.test(O.calleeNameRaw||""),Se=(O.branchPath??[]).map(tt=>({...tt,source:A?$(A,tt.conditionLine,tt.conditionLine):{available:!1,reason:"owning function's node not found"}})),Pe=O.objectNameRaw?`${O.objectNameRaw}.${O.calleeNameRaw}`:O.calleeNameRaw,Re=we?Pe:O.firstArgText?`${Pe}(${O.firstArgText})`:Pe,lt=ce(O);return{label:Re,line:O.line??null,column:O.column??null,branchPath:Se,source:A?$(A,O.line,O.line):{available:!1,reason:"owning function's node not found"},tag:lt?"called-elsewhere":we?"return-value":X?"runtime-dispatched":"unresolvable-call-site",...lt?{targetNodeId:O.targetNodeId}:{},reason:lt?"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":we?"the value this branch returns \u2014 not a function call, just what this path produces":X?`registered via ${O.calleeNameRaw}(...) \u2014 the handler runs later, outside this function's own execution`:j?"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 K(I,T,A){return P(I,T,A,!0)}function U(I,T,A,j){return P(I,T,A,!1,j)}let D=[];for(let I of a){let T=g.get(I.name);if(!T)continue;let A=new Map(T.nodes.map(j=>[j.id,j]));for(let j of T.workflows){let M=new Set([I.name]),ce=new Set(j.steps.map(X=>X.nodeId)),O=new Map;for(let X of j.steps)X.parentNodeId!=null&&(O.get(X.parentNodeId)??O.set(X.parentNodeId,new Set).get(X.parentNodeId)).add(X.nodeId);let we=j.steps.map(X=>{let Se=k.find(nt=>nt.fromService===I.name&&nt.fromNodeId===X.nodeId),Pe=A.get(X.nodeId),Re=X.parentNodeId?A.get(X.parentNodeId):null,lt=(X.branchPath??[]).map(nt=>({...nt,source:Re?$(Re.filePath,nt.conditionLine,nt.conditionLine):{available:!1,reason:"owning function's node not found"}})),tt={...X,branchPath:lt,source:Pe?$(Pe.filePath,Pe.startLine,Pe.endLine):{available:!1,reason:"node not found in this service's own graph"},alsoCallsRuntime:K(X.nodeId,T.resolvedEdges,Pe?.filePath),inlineCalls:U(X.nodeId,T.resolvedEdges,Pe?.filePath,{inWorkflow:ce,children:O.get(X.nodeId)??new Set})};return Se&&(M.add(Se.toService),tt.crossesInto=Se.toService),tt});D.push({...j,steps:we,serviceId:I.name,servicesTouched:[...M]})}}console.log(`
28
+ Done: ${D.length} named workflows across all services
29
+ `),D.forEach(I=>console.log(` - [${I.serviceId}] ${I.name} (${I.steps.length} steps, ${I.occurrences} entry point(s))`));let R=t.outputDir??process.env.CANOPY_OUTPUT_DIR??V.join(Bd,"..","output");he.existsSync(R)||he.mkdirSync(R,{recursive:!0});let G=$n(e),ee=new Set(a.flatMap(I=>u.get(I.name)??[])),ne=Fs({discovered:n,parseResults:m,scopeFiles:ee,rel:G.rel,rootService:l.added});ne.testWorkflowsExcluded=S,ne.guessedWorkflowsDropped=w;let ye={repoRoot:G.repoRoot,coverage:ne};he.writeFileSync(V.join(R,"meta.js"),`const meta = ${JSON.stringify(ye,null,2)};`),he.writeFileSync(V.join(R,"meta.json"),JSON.stringify(ye,null,2)),console.log(`
30
+ `+un(ne)),he.existsSync(V.join(R,"history.js"))||he.writeFileSync(V.join(R,"history.js"),"const canopyHistory = null;");let Ee=G.json(D,2),ct=Ee.length>ta;if(ct&&(Ee=G.json(D)),ct&&Ee.length>ta){let I=si(JSON.parse(Ee));he.writeFileSync(V.join(R,"workflows.js"),`const workflows = ${I};`),he.rmSync(V.join(R,"workflows.json"),{force:!0}),console.log(`
31
+ workflows.json omitted (${(Ee.length/1e6).toFixed(1)} MB plain); workflows.js written with shared sub-structures (${(I.length/1e6).toFixed(1)} MB)`)}else he.writeFileSync(V.join(R,"workflows.json"),Ee),console.log(`
32
+ Saved to output/workflows.json`),he.writeFileSync(V.join(R,"workflows.js"),`const workflows = ${Ee};`),console.log("Saved to output/workflows.js (for the viewer)");let xe=a.flatMap(I=>g.get(I.name)?.nodes??[]),_=k.map(I=>({fromNodeId:I.fromNodeId,targetNodeId:I.toNodeId,resolved:!0,matchType:"crossLayer",confidence:I.confidence})),E=[...a.flatMap(I=>g.get(I.name)?.resolvedEdges??[]),..._],C=ea(D,xe,E);C.crossServiceEdges=k,he.writeFileSync(V.join(R,"systemGraph.js"),`const systemGraph = ${G.json(C,2)};`);let B=a.map(({isRepoRoot:I,ownsLeftovers:T,...A})=>({...A,nodeCount:xe.filter(j=>j.serviceName===A.name).length,workflowCount:D.filter(j=>j.serviceId===A.name).length}));he.writeFileSync(V.join(R,"services.js"),`const services = ${G.json(B,2)};`),console.log(`Saved to output/systemGraph.js (${C.workflowLinks.length} workflow links, ${C.serviceLinks.length} service links)`),console.log("Saved to output/services.js"),console.log(`
33
+ 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 be=new Map;for(let I of a){let T=g.get(I.name);if(!T)continue;let A=G.clone(T.nodes.map(M=>({id:M.id,name:M.name,type:M.type,filePath:M.filePath,bodyHash:M.bodyHash??null,startLine:M.startLine===0?0:M.startLine,endLine:M.endLine===Number.MAX_SAFE_INTEGER?null:M.endLine,serviceName:M.serviceName,isEntryPoint:!!M.isEntryPoint}))),j=Mr(G.clone(T.resolvedEdges.map(M=>({fromNodeId:M.fromNodeId,targetNodeId:M.targetNodeId??null,type:M.type,callKind:M.callKind,calleeNameRaw:M.calleeNameRaw,eventName:M.eventName,url:M.url,line:M.line??null,column:M.column??null,resolved:!!M.resolved,matchType:M.matchType??null}))));be.set(I.name,{nodes:A,edges:j})}return{workflows:D,perService:g,crossServiceEdges:k,services:a,publicGraph:be,publicWorkflows:G.clone(D),publicCrossServiceEdges:G.clone(k),fingerprint:_n(bn(s,G.rel)),analyzedFileCount:s.length,repoRoot:G.repoRoot,coverage:ne}}var Ud=process.argv[1]&&globalThis.__canopyUrl("src/index.js")===Dd(V.resolve(process.argv[1])).href;Ud&&Wo(process.argv[2]||process.cwd()).catch(e=>{console.error("Pipeline failed:",e),process.exit(1)});Ko();Un();yt();var of=ge.join(ge.dirname(xa(globalThis.__canopyUrl("src/history/sync.js"))),"..","..","output"),sf=["workflows.json","workflows.js","systemGraph.js","services.js","meta.js","meta.json","history.js"],rf=ge.dirname(xa(globalThis.__canopyUrl("src/history/sync.js"))).split(ge.sep).includes("node_modules"),vt=e=>process.env.CANOPY_OUTPUT_DIR||(rf&&e?ge.join(ge.resolve(e),".canopy","output"):of);async function af(e,t){let n=console.log;console.log=()=>{};try{return await Wo(e,t)}finally{console.log=n}}function cf(e){let t=ge.resolve(e),n=$n(t);return _n(bn(dn(t),n.rel))}function lf(e){try{let t=JSON.parse(it.readFileSync(ge.join(vt(e),"meta.json"),"utf8"));return t.coverage&&ge.resolve(t.repoRoot)===ge.resolve(e)?t.coverage:null}catch{return null}}async function df(e,{keep:t,say:n=()=>{}}){let s=Date.now(),o=Ge(e),r=o.versions[o.versions.length-1],i=cf(e),a=!!r&&r.fingerprint===i&&(r.engineVersion!==Dn()||r.outputFormat!==Hn);if(r&&r.fingerprint===i&&!a)return{status:"no-changes",version:r,ms:Date.now()-s,coverage:lf(e)};let l=it.mkdtempSync(ge.join(nf.tmpdir(),"canopy-sync-"));try{let c=await af(e,{outputDir:l,onProgress:n}),d=oa(c),m=Ot(d),f={nodes:d.nodes.length,edges:d.edges.length,workflows:d.workflows.length,physicalWorkflows:d.workflows.filter(v=>v.tier==="physical").length,crossServiceEdges:d.crossServiceEdges.length},u=ra(e,m,d,f,t,{refresh:a}),p=await Promise.resolve().then(()=>(ya(),ga)).catch(()=>null);p&&p.writeHistoryJs(e,l);let h=vt(e);it.mkdirSync(h,{recursive:!0});for(let v of sf)it.existsSync(ge.join(l,v))?it.copyFileSync(ge.join(l,v),ge.join(h,v)):it.rmSync(ge.join(h,v),{force:!0});return{status:"new-version",version:u,ms:Date.now()-s,coverage:c.coverage}}finally{it.rmSync(l,{recursive:!0,force:!0})}}async function Gn(e,{keep:t=Vt,say:n=console.log}={}){if(e=ge.resolve(e),zn(e),it.mkdirSync(ae(e).root,{recursive:!0}),!ia(e))return ca(e),n("sync already running - one rerun queued"),{status:"queued"};let s;try{do s=await df(e,{keep:t,say:n}),s.status==="no-changes"?n(`no changes (v${s.version.version} ${s.version.fingerprint.slice(0,7)}) [${s.ms} ms]`):n(`v${s.version.version} ${s.version.fingerprint.slice(0,7)} stored: ${s.version.counts.nodes} nodes, ${s.version.counts.edges} edges, ${s.version.counts.workflows} workflows, ${(s.version.bytes/1024/1024).toFixed(2)} MB${s.version.gzip?" (gzip)":""} [${s.ms} ms]`),s.coverage&&n(`
34
+ `+un(s.coverage));while(la(e))}finally{aa(e)}return s}yt();yt();De();import pe from"node:fs";import Oe from"node:path";import{spawn as ff}from"node:child_process";import{fileURLToPath as uf}from"node:url";var Xt="# >>> canopy sync (managed block - do not edit) >>>",Sa="# <<< canopy sync <<<",wt=["post-commit","post-merge"],pf=globalThis.__canopyBundle??Oe.join(Oe.dirname(uf(globalThis.__canopyUrl("src/history/hooks.js"))),"..","cli.js"),mf=e=>Oe.resolve(e).split(Oe.sep).join("/");function Yt(e){let t=Ie(e,["rev-parse","--git-path","hooks"]);if(!t)throw new Error(`not a git repository: ${e}`);return Oe.resolve(e,t)}var va=JSON.parse(pe.readFileSync(Oe.join(re,"package.json"),"utf8")),hf=va.name+"@"+va.version,wa=e=>mf(e).replace(/(["$`\\])/g,"\\$1");function Jn(e){return[Xt,"(",` if command -v canopy >/dev/null 2>&1; then canopy sync --background "${wa(e)}" >/dev/null 2>&1 </dev/null`,` elif command -v npx >/dev/null 2>&1; then ( npx --yes ${hf} sync --background "${wa(e)}" >/dev/null 2>&1 </dev/null & )`,' else echo "canopy not found; skipping map update"'," fi",") || true",Sa].join(`
35
35
  `)+`
36
- `}var qn=()=>new RegExp(`\\n?${qt.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}[\\s\\S]*?${fa.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\n?`);function Jt(e){let t=Gt(e);ue.mkdirSync(t,{recursive:!0});let n=[];for(let r of gt){let o=Ce.join(t,r),s=ue.existsSync(o)?ue.readFileSync(o,"utf8"):null,i;s===null?i=`#!/bin/sh
37
- `+Wn(e):qn().test(s)?i=s.replace(qn(),()=>`
38
- `+Wn(e)):i=s+(s.endsWith(`
36
+ `}var Kn=()=>new RegExp(`\\n?${Xt.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}[\\s\\S]*?${Sa.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\n?`);function Zt(e){let t=Yt(e);pe.mkdirSync(t,{recursive:!0});let n=[];for(let s of wt){let o=Oe.join(t,s),r=pe.existsSync(o)?pe.readFileSync(o,"utf8"):null,i;r===null?i=`#!/bin/sh
37
+ `+Jn(e):Kn().test(r)?i=r.replace(Kn(),()=>`
38
+ `+Jn(e)):i=r+(r.endsWith(`
39
39
  `)?"":`
40
40
  `)+`
41
- `+Wn(e),ue.writeFileSync(o,i.replace(/\r\n/g,`
42
- `));try{ue.chmodSync(o,493)}catch{}n.push(o)}return n}function ua(e){let t=Gt(e),n=[];for(let r of gt){let o=Ce.join(t,r);if(!ue.existsSync(o))continue;let s=ue.readFileSync(o,"utf8");if(!qn().test(s))continue;let i=s.replace(qn(),`
43
- `);i.replace(/^#!.*\n?/,"").trim()===""?ue.rmSync(o,{force:!0}):ue.writeFileSync(o,i.replace(/\n{3,}/g,`
41
+ `+Jn(e),pe.writeFileSync(o,i.replace(/\r\n/g,`
42
+ `));try{pe.chmodSync(o,493)}catch{}n.push(o)}return n}function ka(e){let t=Yt(e),n=[];for(let s of wt){let o=Oe.join(t,s);if(!pe.existsSync(o))continue;let r=pe.readFileSync(o,"utf8");if(!Kn().test(r))continue;let i=r.replace(Kn(),`
43
+ `);i.replace(/^#!.*\n?/,"").trim()===""?pe.rmSync(o,{force:!0}):pe.writeFileSync(o,i.replace(/\n{3,}/g,`
44
44
 
45
- `)),n.push(o)}return n}function pa(e){if(!ue.existsSync(Ce.resolve(e)))return null;let t=se(e);ue.mkdirSync(t.root,{recursive:!0});let n=ue.openSync(t.log,"a");ue.writeSync(n,`
45
+ `)),n.push(o)}return n}function Na(e){if(!pe.existsSync(Oe.resolve(e)))return null;let t=ae(e);pe.mkdirSync(t.root,{recursive:!0});let n=pe.openSync(t.log,"a");pe.writeSync(n,`
46
46
  --- ${new Date().toISOString()} sync requested (pid ${process.pid})
47
- `);let r=Object.fromEntries(Object.entries(process.env).filter(([s])=>!/^GIT_/i.test(s)||s.toUpperCase()==="GIT_EXEC_PATH")),o=Ud(process.execPath,[zd,"sync",Ce.resolve(e)],{detached:!0,stdio:["ignore",n,n],windowsHide:!0,env:r});return o.unref(),ue.closeSync(n),o.pid}function ma(e){let t=Gt(e),n=Wn(e),r=0,o=0;for(let s of gt){let i=Ce.join(t,s);if(!ue.existsSync(i))continue;let a=ue.readFileSync(i,"utf8").replace(/\r\n/g,`
48
- `);a.includes(qt)&&(r++,a.includes(n)&&o++)}return r<gt.length?"absent":o===gt.length?"current":"outdated"}Go();Le();Le();import Vt from"node:fs";import rf from"node:http";import De from"node:path";import{spawn as sf}from"node:child_process";Le();import Gd from"node:fs";import Jd from"node:http";import Kd from"node:https";import Ko from"node:path";import{spawn as Vd,spawnSync as ga}from"node:child_process";var Yo="https://registry.npmjs.org/canopy-engine/latest",Jo="npm install -g canopy-engine@latest",ha=1e4,Yd=256*1024,Vo=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,Xd=e=>typeof e=="string"&&e.length<=64&&Vo.test(e);function Zd(e,t){let n=Vo.exec(e),r=Vo.exec(t);for(let o=1;o<=3;o++){let s=Number(n[o])-Number(r[o]);if(s)return s>0?1:-1}return n[4]&&!r[4]?-1:!n[4]&&r[4]?1:n[4]===r[4]?0:n[4]>r[4]?1:-1}function Qd(e=process.env){let t=e.CANOPY_REGISTRY_URL;return t&&/^http:\/\/127\.0\.0\.1:\d{1,5}(\/|$)/.test(t)?t:Yo}function ef(e=process.env){let t=Qd(e),n=t.startsWith("https:")?Kd:Jd;return new Promise((r,o)=>{let s=!1,i=(l,c)=>{s||(s=!0,l(c))},a=n.get(t,{headers:{accept:"application/json","user-agent":"canopy-engine-update-check"}},l=>{if(l.statusCode!==200)return l.resume(),i(o,new Error(`the registry answered HTTP ${l.statusCode}`));let c=0,d=[];l.on("data",p=>{if(c+=p.length,c>Yd){i(o,new Error("the registry's answer is larger than 256 KB; ignored")),a.destroy();return}d.push(p)}),l.on("end",()=>{let p;try{p=JSON.parse(Buffer.concat(d).toString("utf8"))?.version}catch{return i(o,new Error("the registry's answer is not valid JSON"))}if(!Xd(p))return i(o,new Error("the registry's answer has no valid version number"));i(r,p)}),l.on("error",p=>i(o,new Error("the connection broke: "+p.message)))});a.setTimeout(ha,()=>{i(o,new Error(`no answer from the registry within ${ha/1e3} s`)),a.destroy()}),a.on("error",l=>i(o,new Error("could not reach the registry: "+(l.code||l.message))))})}function Xo(e=re,t=bt()){return e.split(Ko.sep).includes("_npx")?"npx":t?"installed":"dev"}function ya(e=process.env){let t=e.CANOPY_NPM_BIN;return t?/\.(c|m)?js$/i.test(t)?{cmd:process.execPath,pre:[t],shell:!1}:{cmd:t,pre:[],shell:process.platform==="win32"&&/\.(cmd|bat)$/i.test(t)}:{cmd:process.platform==="win32"?"npm.cmd":"npm",pre:[],shell:process.platform==="win32"}}var Kt=(e,t)=>t&&/[\s"]/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e;function tf(e,t){let{cmd:n,pre:r,shell:o}=ya(t);return new Promise(s=>{let i=Vd(Kt(n,o),[...r,...e].map(a=>Kt(a,o)),{stdio:"inherit",shell:o,env:t});i.on("error",()=>s(1)),i.on("close",a=>s(a??1))})}function nf(e,t){let{cmd:n,pre:r,shell:o}=ya(t),s=ga(Kt(n,o),[...r,...e].map(i=>Kt(i,o)),{encoding:"utf8",shell:o,env:t,timeout:3e4});return s.status===0?s.stdout.trim():null}function of(e){let t=nf(["prefix","-g"],e),n=["canopy","canopy-engine"],r=[];if(t)for(let o of n)r.push(process.platform==="win32"?Ko.join(t,o+".cmd"):Ko.join(t,"bin",o));for(let o of r){if(!Gd.existsSync(o))continue;let s=process.platform==="win32"&&/\.(cmd|bat)$/i.test(o),i=ga(Kt(o,s),["--version"],{encoding:"utf8",shell:s,env:e,timeout:3e4});if(i.status===0)return i.stdout.trim().split(/\r?\n/).pop().trim()}return null}async function xa({check:e,version:t,root:n=re,installed:r=bt(),env:o=process.env,out:s=console.log,err:i=console.error}){let a=Xo(n,r);if(a==="dev")return s("dev checkout: update disabled"),0;if(a==="npx")return s("You are running via npx; npx canopy-engine@latest always uses the newest version"),0;let l;try{l=await ef(o)}catch(p){return i(`could not check for updates: ${p.message}`),i(" you can look it up yourself: npm view canopy-engine version"),1}if(Zd(l,t)<=0)return s(`up to date (${t})`),0;if(e)return s(`${l} available (you have ${t}). Run: canopy update`),0;s(`Updating canopy-engine ${t} -> ${l}`),s(` running: ${Jo}`);let c=await tf(["install","-g","canopy-engine@latest"],o);if(c!==0)return i(`The update did not finish (npm exited with ${c}). Run it yourself: ${Jo}`),1;let d=of(o);return d!==l?(i(`npm finished, but the installed canopy reports ${d??"no version"} instead of ${l}. Run it yourself: ${Jo}`),1):(s(`Updated: canopy ${d} is installed.`),0)}var wa={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".json":"application/json",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".woff2":"font/woff2",".map":"application/json"};function va(e,t,n){let r=De.join(e,De.normalize(t).replace(/^([/\\]|\.\.[/\\])+/,""));if(!r.startsWith(e+De.sep)&&r!==e){n.writeHead(403).end("forbidden");return}Vt.readFile(r,(o,s)=>{if(o){n.writeHead(404,{"content-type":"text/plain"}).end("not found: "+t);return}n.writeHead(200,{"content-type":wa[De.extname(r).toLowerCase()]??"application/octet-stream","cache-control":"no-store"}).end(s)})}var af=(()=>{try{return JSON.parse(Vt.readFileSync(De.join(re,"package.json"),"utf8")).version}catch{return null}})();function cf({env:e=process.env,version:t=af,kind:n=Xo()}={}){return e.CANOPY_NO_UPDATE_CHECK==="1"||e.CANOPY_NO_UPDATE_CHECK==="true"||n!=="installed"||!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(String(t))?"":`<meta name="canopy-update-check" content="${Yo}" data-current="${t}">`}function lf(e,t,n){Vt.readFile(De.join(e,"index.html"),"utf8",(r,o)=>{if(r){t.writeHead(404,{"content-type":"text/plain"}).end("not found: index.html");return}t.writeHead(200,{"content-type":wa[".html"],"cache-control":"no-store"}).end(n?o.replace("</head>",n+`
49
- </head>`):o)})}var Gn=()=>{let e=De.join(re,"ui-react");return!Vt.existsSync(De.join(e,"index.html"))||!Vt.existsSync(De.join(e,"dist"))?`this install has no built viewer (ui-react/dist is missing)
50
- fix: reinstall canopy from a build that includes the viewer`:null};async function Jn(e,t=0,{updateTag:n=cf()}={}){let r=De.join(re,"ui-react"),o=rf.createServer((i,a)=>{let l;try{l=decodeURIComponent((i.url??"/").split("?")[0])}catch{a.writeHead(400).end("bad request");return}if(l==="/"||l==="/index.html"){a.writeHead(302,{location:"/ui-react/index.html"}).end();return}if(l==="/ui-react/index.html")return lf(r,a,n);if(l.startsWith("/ui-react/"))return va(r,l.slice(10),a);if(l.startsWith("/output/"))return va(e,l.slice(8),a);a.writeHead(404).end("not found")});await new Promise((i,a)=>{o.once("error",a),o.listen(t,"127.0.0.1",i)});let s=o.address().port;return{server:o,port:s,url:`http://127.0.0.1:${s}/`}}function Sa(e){if(process.env.CANOPY_NO_BROWSER)return!1;try{let t,n;if(process.platform==="win32")t="cmd.exe",n=["/c","start","",e];else if(process.platform==="darwin")t="open",n=[e];else if(process.env.DISPLAY||process.env.WAYLAND_DISPLAY)t="xdg-open",n=[e];else return!1;let r=sf(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),!0}catch{return!1}}Le();pt();import Ue from"node:fs";import Ye from"node:path";import{execFileSync as ka}from"node:child_process";function Kn(e){let t=[],n=(r,o,s,i)=>{let a=!1,l="";try{let c=s();a=c===!0||!!(c&&c.ok),l=c&&c.detail?c.detail:""}catch(c){l=String(c.message??c).split(`
51
- `)[0]}t.push({name:r,critical:o,ok:a,detail:l,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 r=[["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=r.filter(([s,i])=>!Ue.existsSync(Ye.join(je(s),i))).map(([,s])=>s);return{ok:o.length===0,detail:o.length?"missing "+o.join(", "):r.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 r=[Ye.join(re,"src","stage2_parse","queries"),Ye.join(re,"dist","queries")].find(s=>Ue.existsSync(s))??Ye.join(re,"dist","queries"),o=Ue.readdirSync(r).filter(s=>s.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 r=se(e).root;Ue.mkdirSync(r,{recursive:!0});let o=Ye.join(r,`.doctor-${process.pid}`);return Ue.writeFileSync(o,"x"),Ue.rmSync(o),{ok:!0,detail:r}},`make ${e} writable for your user, or run canopy on a folder you own`),n("git available",!1,()=>({ok:!!ka("git",["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}),detail:ka("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:Ue.existsSync(Ye.join(re,"ui-react","index.html"))&&Ue.existsSync(Ye.join(re,"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(!be(e,["rev-parse","--git-dir"]))return{ok:!1,detail:"not a git repository"};let r=Gt(e),o=gt.every(s=>Ue.existsSync(Ye.join(r,s))&&Ue.readFileSync(Ye.join(r,s),"utf8").includes(qt));return{ok:o,detail:o?"post-commit, post-merge":""}},`canopy hook install "${e}"`),t}function Na(e,t,n,r=console.log){r(`canopy ${n} doctor (${t})
52
- `);for(let s of e)r(`${s.ok?"OK ":"FAIL"} ${s.name}${s.detail?" - "+s.detail:""}${s.ok?"":`
53
- fix: ${s.fix}`}${!s.ok&&!s.critical?" (not critical)":""}`);let o=e.filter(s=>s.critical&&!s.ok);return r(`
54
- ${o.length?`${o.length} critical problem(s) - fix them and run canopy doctor again`:"all critical checks passed"}`),o.length}import pe from"node:fs";import df from"node:net";import ff from"node:os";import ot from"node:path";import uf from"node:readline";pt();var ba=Number(process.env.CANOPY_MIN_FREE_MB)||300,pf=".js .jsx .mjs .cjs .ts .tsx .mts .cts",Vn=class extends Error{constructor(t,n){super(n),this.code=t,this.line=n}},$e=(e,t)=>{throw new Vn(e,t)};function mf(e){let t=!!be(e,["rev-parse","--git-dir"]),n=ot.join(e,".gitignore"),r=pe.existsSync(n);if(!t&&!r)return"skipped";let o=r?pe.readFileSync(n,"utf8"):"";if(o.split(/\r?\n/).some(i=>/^\/?\.canopy\/?$/.test(i.trim())))return"already";let s=/\r\n/.test(o)?`\r
47
+ `);let s=Object.fromEntries(Object.entries(process.env).filter(([r])=>!/^GIT_/i.test(r)||r.toUpperCase()==="GIT_EXEC_PATH")),o=ff(process.execPath,[pf,"sync",Oe.resolve(e)],{detached:!0,stdio:["ignore",n,n],windowsHide:!0,env:s});return o.unref(),pe.closeSync(n),o.pid}function ba(e){let t=Yt(e),n=Jn(e),s=0,o=0;for(let r of wt){let i=Oe.join(t,r);if(!pe.existsSync(i))continue;let a=pe.readFileSync(i,"utf8").replace(/\r\n/g,`
48
+ `);a.includes(Xt)&&(s++,a.includes(n)&&o++)}return s<wt.length?"absent":o===wt.length?"current":"outdated"}Yo();De();De();import St from"node:fs";import Jf from"node:http";import Ce from"node:path";import{spawn as Kf}from"node:child_process";De();import gf from"node:fs";import yf from"node:http";import xf from"node:https";import Qo from"node:path";import{spawn as vf,spawnSync as $a}from"node:child_process";var ts="https://registry.npmjs.org/canopy-engine/latest",Zo="npm install -g canopy-engine@latest",_a=1e4,wf=256*1024,es=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,Sf=e=>typeof e=="string"&&e.length<=64&&es.test(e);function kf(e,t){let n=es.exec(e),s=es.exec(t);for(let o=1;o<=3;o++){let r=Number(n[o])-Number(s[o]);if(r)return r>0?1:-1}return n[4]&&!s[4]?-1:!n[4]&&s[4]?1:n[4]===s[4]?0:n[4]>s[4]?1:-1}function Nf(e=process.env){let t=e.CANOPY_REGISTRY_URL;return t&&/^http:\/\/127\.0\.0\.1:\d{1,5}(\/|$)/.test(t)?t:ts}function bf(e=process.env){let t=Nf(e),n=t.startsWith("https:")?xf:yf;return new Promise((s,o)=>{let r=!1,i=(l,c)=>{r||(r=!0,l(c))},a=n.get(t,{headers:{accept:"application/json","user-agent":"canopy-engine-update-check"}},l=>{if(l.statusCode!==200)return l.resume(),i(o,new Error(`the registry answered HTTP ${l.statusCode}`));let c=0,d=[];l.on("data",m=>{if(c+=m.length,c>wf){i(o,new Error("the registry's answer is larger than 256 KB; ignored")),a.destroy();return}d.push(m)}),l.on("end",()=>{let m;try{m=JSON.parse(Buffer.concat(d).toString("utf8"))?.version}catch{return i(o,new Error("the registry's answer is not valid JSON"))}if(!Sf(m))return i(o,new Error("the registry's answer has no valid version number"));i(s,m)}),l.on("error",m=>i(o,new Error("the connection broke: "+m.message)))});a.setTimeout(_a,()=>{i(o,new Error(`no answer from the registry within ${_a/1e3} s`)),a.destroy()}),a.on("error",l=>i(o,new Error("could not reach the registry: "+(l.code||l.message))))})}function ns(e=re,t=jt()){return e.split(Qo.sep).includes("_npx")?"npx":t?"installed":"dev"}function Ia(e=process.env){let t=e.CANOPY_NPM_BIN;return t?/\.(c|m)?js$/i.test(t)?{cmd:process.execPath,pre:[t],shell:!1}:{cmd:t,pre:[],shell:process.platform==="win32"&&/\.(cmd|bat)$/i.test(t)}:{cmd:process.platform==="win32"?"npm.cmd":"npm",pre:[],shell:process.platform==="win32"}}var Qt=(e,t)=>t&&/[\s"]/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e;function _f(e,t){let{cmd:n,pre:s,shell:o}=Ia(t);return new Promise(r=>{let i=vf(Qt(n,o),[...s,...e].map(a=>Qt(a,o)),{stdio:"inherit",shell:o,env:t});i.on("error",()=>r(1)),i.on("close",a=>r(a??1))})}function $f(e,t){let{cmd:n,pre:s,shell:o}=Ia(t),r=$a(Qt(n,o),[...s,...e].map(i=>Qt(i,o)),{encoding:"utf8",shell:o,env:t,timeout:3e4});return r.status===0?r.stdout.trim():null}function If(e){let t=$f(["prefix","-g"],e),n=["canopy","canopy-engine"],s=[];if(t)for(let o of n)s.push(process.platform==="win32"?Qo.join(t,o+".cmd"):Qo.join(t,"bin",o));for(let o of s){if(!gf.existsSync(o))continue;let r=process.platform==="win32"&&/\.(cmd|bat)$/i.test(o),i=$a(Qt(o,r),["--version"],{encoding:"utf8",shell:r,env:e,timeout:3e4});if(i.status===0)return i.stdout.trim().split(/\r?\n/).pop().trim()}return null}async function Fa({check:e,version:t,root:n=re,installed:s=jt(),env:o=process.env,out:r=console.log,err:i=console.error}){let a=ns(n,s);if(a==="dev")return r("dev checkout: update disabled"),0;if(a==="npx")return r("You are running via npx; npx canopy-engine@latest always uses the newest version"),0;let l;try{l=await bf(o)}catch(m){return i(`could not check for updates: ${m.message}`),i(" you can look it up yourself: npm view canopy-engine version"),1}if(kf(l,t)<=0)return r(`up to date (${t})`),0;if(e)return r(`${l} available (you have ${t}). Run: canopy update`),0;r(`Updating canopy-engine ${t} -> ${l}`),r(` running: ${Zo}`);let c=await _f(["install","-g","canopy-engine@latest"],o);if(c!==0)return i(`The update did not finish (npm exited with ${c}). Run it yourself: ${Zo}`),1;let d=If(o);return d!==l?(i(`npm finished, but the installed canopy reports ${d??"no version"} instead of ${l}. Run it yourself: ${Zo}`),1):(r(`Updated: canopy ${d} is installed.`),0)}import je from"node:fs";import Fe from"node:path";import os from"node:vm";import Ea from"node:crypto";import Ff from"node:zlib";var ja=30,Ht=400,Ca=2*1024*1024,jf="x-canopy-token",Pa=()=>Ea.randomBytes(24).toString("hex"),Cf=/^(\.env($|[.\-_])|\.npmrc$|\.netrc$|\.pgpass$|\.htpasswd$|id_(rsa|dsa|ecdsa|ed25519)|credentials(\.|$)|.*\.(pem|key|crt|cer|der|p12|pfx|jks|keystore|ppk|gpg|asc|kdbx)$)/i,Vn=e=>Cf.test(e);function Ef(e){let t=Fe.join(e,"workflows.json"),n=Fe.join(e,"workflows.js");if(je.existsSync(t))return{mtime:je.statSync(t).mtimeMs,data:JSON.parse(je.readFileSync(t,"utf8"))};if(je.existsSync(n)){let s=os.createContext({});return os.runInContext(je.readFileSync(n,"utf8"),s,{timeout:1e4}),{mtime:je.statSync(n).mtimeMs,data:os.runInContext("workflows",s,{timeout:1e4})}}return null}var La=e=>Fe.join(Fe.resolve(e),".canopy","history");function ss(e){try{let t=JSON.parse(je.readFileSync(Fe.join(La(e),"index.json"),"utf8"));return Array.isArray(t.versions)?t:null}catch{return null}}function rs(e,t){try{if(!t||typeof t.file!="string"||!/^[0-9A-Za-z][0-9A-Za-z._-]*$/.test(t.file))return null;let n=je.readFileSync(Fe.join(La(e),t.file));return JSON.parse((t.gzip?Ff.gunzipSync(n):n).toString("utf8"))}catch{return null}}function Pf(e){let t=ss(e),n=t?.versions[t.versions.length-1],s=n?rs(e,n):null;return s?{version:n.version,nodes:Array.isArray(s.nodes)?s.nodes:[]}:null}function Lf(e,t=null){let n=new Map;for(let s of e??[])for(let o of s.steps??[]){if(n.has(o.nodeId))continue;let r=o.nodeId.lastIndexOf("::"),i=r===-1?o.nodeId:o.nodeId.slice(0,r),a=o.source&&o.source.available?o.source:null;n.set(o.nodeId,{file:i,startLine:a?.startLine??null,endLine:a?.endLine??null,text:a?.text??null})}for(let s of t??[]){if(typeof s?.id!="string"||n.has(s.id))continue;let o=s.id.lastIndexOf("::");n.set(s.id,{file:typeof s.filePath=="string"?s.filePath:o===-1?s.id:s.id.slice(0,o),startLine:Number.isInteger(s.startLine)&&s.startLine>0?s.startLine:null,endLine:Number.isInteger(s.endLine)?s.endLine:null,text:null})}return n}function Ta({outDir:e,repoRoot:t}){let n=null,s=()=>{try{return je.realpathSync(t)}catch{return null}};function o(){let a=["workflows.json","workflows.js"].map(c=>Fe.join(e,c)).concat(t?[Fe.join(t,".canopy","history","index.json")]:[]),l=0;for(let c of a)try{l=Math.max(l,je.statSync(c).mtimeMs)}catch{}if(!n||n.stamp!==l){let c=Ef(e),d=t?Pf(t):null;n={stamp:l,index:Lf(c?.data??[],d?.nodes),all:d}}return n.index}function r(){o();let a=n?.all;if(!a)return{status:200,body:{ok:!0,available:!1,nodes:[]}};let l=6e4,c=a.nodes.slice(0,l).map(d=>[d.id,d.name,d.kind,d.service,d.startLine??null,d.endLine??null]);return{status:200,body:{ok:!0,available:!0,version:a.version,total:a.nodes.length,truncated:a.nodes.length>l,nodes:c}}}function i(a){try{if(typeof a!="string"||!a||a.length>2e3)return{status:400,body:{ok:!1,code:"bad-request",message:"node must be a node id"}};let l=o().get(a);if(!l)return{status:404,body:{ok:!1,code:"unknown-node",message:"no such node in the analysed graph"}};if(l.startLine==null)return{status:404,body:{ok:!1,code:"no-range",message:"no source range was recorded for this node"}};let c=s();if(!c)return{status:410,body:{ok:!1,code:"changed",message:"file changed since analysis (the project folder is gone)"}};let d=l.file.split(/[\\/]/);if(!l.file||Fe.isAbsolute(l.file)||/^[A-Za-z]:/.test(l.file)||d.includes(".."))return{status:403,body:{ok:!1,code:"outside-repo",message:"refused: not a path inside the analysed project"}};let m=Fe.resolve(c,l.file),f;try{f=je.realpathSync(m)}catch{return{status:410,body:{ok:!1,code:"changed",message:"file changed since analysis (the file no longer exists)",file:l.file}}}if(f!==c&&!f.startsWith(c+Fe.sep))return{status:403,body:{ok:!1,code:"outside-repo",message:"refused: the file resolves outside the analysed project"}};let u=Fe.basename(f);if(Vn(Fe.basename(m))||Vn(u))return{status:403,body:{ok:!1,code:"refused",message:"refused: environment, key and certificate files are never served"}};let p=je.statSync(f);if(!p.isFile())return{status:403,body:{ok:!1,code:"refused",message:"refused: not a regular file"}};if(p.size>Ca)return{status:403,body:{ok:!1,code:"too-large",message:`refused: the file is larger than ${Ca/1024/1024} MB`}};let h=je.readFileSync(f);if(h.subarray(0,8e3).includes(0))return{status:403,body:{ok:!1,code:"binary",message:"refused: binary file"}};let v=h.toString("utf8").replace(/\r\n/g,`
49
+ `).split(`
50
+ `);v.length>1&&v[v.length-1]===""&&v.pop();let g=v.length,{startLine:w,endLine:S}=l;if(l.text!=null){let b=v.slice(w-1,S).join(`
51
+ `).replace(/\s+$/gm,""),N=l.text.replace(/\r\n/g,`
52
+ `).replace(/\s+$/gm,"");if(b.trim()!==N.trim())return{status:409,body:{ok:!1,code:"changed",message:"file changed since analysis",file:l.file,startLine:w,endLine:S}}}else if(S>g)return{status:409,body:{ok:!1,code:"changed",message:"file changed since analysis",file:l.file,startLine:w,endLine:S}};let k=Math.max(1,w-ja),y=Math.min(g,S+ja),x=!1;if(y-k+1>Ht)if(x=!0,S-w+1>=Ht)k=w,y=w+Ht-1;else{let b=Ht-(S-w+1);k=Math.max(1,w-Math.floor(b/2)),y=Math.min(g,k+Ht-1),k=Math.max(1,y-Ht+1)}return{status:200,body:{ok:!0,nodeId:a,file:l.file,startLine:w,endLine:S,from:k,to:y,total:g,truncated:x,lines:v.slice(k-1,y)}}}catch{return{status:500,body:{ok:!1,code:"error",message:"the source could not be read"}}}}return{read:i,graph:o,allNodes:r}}var Tf=(e,t)=>{let n=Buffer.from(String(e??"")),s=Buffer.from(String(t??""));return n.length===s.length&&n.length>0&&Ea.timingSafeEqual(n,s)};function Ra(e,t){if(!new Set([`127.0.0.1:${t}`,`localhost:${t}`]).has(String(e.headers.host??"").toLowerCase()))return!1;let s=e.headers.origin;return!(s!==void 0&&!(s===`http://127.0.0.1:${t}`||s===`http://localhost:${t}`))}function Xn(e,t){return e.method!=="GET"?{status:405,body:{ok:!1,code:"method",message:"GET only"}}:Tf(e.headers[jf],t)?null:{status:403,body:{ok:!1,code:"token",message:"missing or wrong session token"}}}function Aa(e,t,{token:n,service:s}){let o=Xn(e,n);return o||([...t.searchParams.keys()].length?{status:400,body:{ok:!1,code:"bad-request",message:"this request takes no parameters"}}:s.allNodes())}function Oa(e,t,{port:n,token:s,service:o}){let r=Xn(e,s);if(r)return r;let i=[...t.searchParams.keys()];return i.length!==1||i[0]!=="node"||t.searchParams.getAll("node").length!==1?{status:400,body:{ok:!1,code:"bad-request",message:"send exactly one parameter: node=<node id>"}}:o.read(t.searchParams.get("node"))}import Mf from"node:path";import{execFile as Hf}from"node:child_process";function Rf(e,t,n){let s=e.length,o=t.length,r=Math.min(s+o,n),i=r+1,a=new Int32Array(2*r+3),l=[];for(let c=0;c<=r;c++){l.push(a.slice());for(let d=-c;d<=c;d+=2){let m=d===-c||d!==c&&a[i+d-1]<a[i+d+1]?a[i+d+1]:a[i+d-1]+1,f=m-d;for(;m<s&&f<o&&e[m]===t[f];)m++,f++;if(a[i+d]=m,m>=s&&f>=o)return Af(l,s,o,c,i,e,t)}}return null}function Af(e,t,n,s,o){let r=t,i=n,a=[];for(let l=s;l>0;l--){let c=e[l],d=r-i,m=d===-l||d!==l&&c[o+d-1]<c[o+d+1]?d+1:d-1,f=c[o+m],u=f-m;for(;r>f&&i>u;)a.push(["=",r-1,i-1]),r--,i--;r===f?a.push(["+",-1,i-1]):a.push(["-",r-1,-1]),r=f,i=u}for(;r>0&&i>0;)a.push(["=",r-1,i-1]),r--,i--;return a.reverse()}function Of(e,t,{maxD:n=1500}={}){let s=0;for(;s<e.length&&s<t.length&&e[s]===t[s];)s++;let o=0;for(;o<e.length-s&&o<t.length-s&&e[e.length-1-o]===t[t.length-1-o];)o++;let r=e.slice(s,e.length-o),i=t.slice(s,t.length-o),a,l=!1;r.length?i.length?(a=Rf(r,i,n),a||(l=!0,a=[...r.map((d,m)=>["-",m,-1]),...i.map((d,m)=>["+",-1,m])])):a=r.map((d,m)=>["-",m,-1]):a=i.map((d,m)=>["+",-1,m]);let c=[];for(let d=0;d<s;d++)c.push(["=",d,d]);for(let[d,m,f]of a)c.push([d,m<0?-1:m+s,f<0?-1:f+s]);for(let d=0;d<o;d++)c.push(["=",e.length-o+d,t.length-o+d]);return{ops:c,coarse:l}}function Ma(e,t,{aBase:n=1,bBase:s=1,context:o=3,maxD:r}={}){let{ops:i,coarse:a}=Of(e,t,r?{maxD:r}:{}),l=[];i.forEach((f,u)=>{f[0]!=="="&&l.push(u)});let c={added:i.filter(f=>f[0]==="+").length,removed:i.filter(f=>f[0]==="-").length};if(!l.length)return{rows:[],stats:c,coarse:a};let d=[];for(let f of l){let u=Math.max(0,f-o),p=Math.min(i.length-1,f+o),h=d[d.length-1];h&&u<=h[1]+1?h[1]=Math.max(h[1],p):d.push([u,p])}let m=[];for(let[f,u]of d){let p=null,h=null,v=0,g=0,w=[];for(let k=f;k<=u;k++){let[y,x,b]=i[k];y!=="+"&&(p==null&&(p=x+1),v++),y!=="-"&&(h==null&&(h=b+1),g++),y==="="?w.push({t:" ",o:n+x,n:s+b,text:e[x]}):y==="-"?w.push({t:"-",o:n+x,n:null,text:e[x]}):w.push({t:"+",o:null,n:s+b,text:t[b]})}p==null&&(p=i.slice(0,f).filter(k=>k[0]!=="+").length),h==null&&(h=i.slice(0,f).filter(k=>k[0]!=="-").length);let S=(k,y)=>y===0?`${k},0`:y===1?`${k}`:`${k},${y}`;m.push({t:"@",header:`@@ -${S(p,v)} +${S(h,g)} @@`,oldStart:p,oldLen:v,newStart:h,newLen:g}),m.push(...w)}return{rows:m,stats:c,coarse:a}}function is(e,t,n=1){let s=e.map((r,i)=>t==="+"?{t:"+",o:null,n:n+i,text:r}:{t:"-",o:n+i,n:null,text:r}),o=t==="+"?`@@ -0,0 +1${e.length===1?"":","+e.length} @@`:`@@ -1${e.length===1?"":","+e.length} +0,0 @@`;return{rows:e.length?[{t:"@",header:o,oldStart:t==="+"?0:1,oldLen:t==="+"?0:e.length,newStart:t==="+"?1:0,newLen:t==="+"?e.length:0},...s]:[],stats:t==="+"?{added:e.length,removed:0}:{added:0,removed:e.length}}}var Df=5e3,Bf=3*1024*1024,Uf="line-level changes need git history",zf=/^[0-9a-f]{40}$/,Ha=/^[1-9][0-9]{0,5}$/,Wf=2e3;function qf(e=process.env){let t=["PATH","Path","SystemRoot","SYSTEMROOT","windir","TEMP","TMP","TMPDIR","HOME","USERPROFILE","HOMEDRIVE","HOMEPATH","APPDATA","LOCALAPPDATA","COMSPEC","PATHEXT"],n={};for(let s of t)e[s]!==void 0&&(n[s]=e[s]);return{...n,GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0",GIT_ASKPASS:"",LC_ALL:"C"}}function Gf(e){return typeof e!="string"||!e||e.length>1e3?"not a path":/[\u0000-\u001f\u007f]/.test(e)?"control characters in the path":e.startsWith("-")?"path starts with a dash":Mf.isAbsolute(e)||/^[A-Za-z]:/.test(e)||e.startsWith("/")||e.startsWith("\\")||e.split(/[\\/]/).includes("..")?"not a path inside the project":e.split(/[\\/]/).some(t=>Vn(t))?"environment, key and certificate files are never served":null}function Da({repoRoot:e,gitFile:t="git",gitPre:n=[],timeoutMs:s=Df,maxBlob:o=Bf,env:r=qf()}){let i=new Map;function a(p){if(i.has(p.file))return i.get(p.file);let h=rs(e,p),v=new Map;for(let g of h?.nodes??[])v.has(g.id)||v.set(g.id,g);return i.set(p.file,v),i.size>4&&i.delete(i.keys().next().value),v}let l=new Map;function c(p,h){let v=p+":"+h;return l.has(v)?Promise.resolve({ok:!0,buf:l.get(v)}):d(p,h).then(g=>(g.ok&&(l.set(v,g.buf),l.size>24&&l.delete(l.keys().next().value)),g))}function d(p,h){return new Promise(v=>{Hf(t,[...n,"--no-pager","cat-file","blob",`${p}:${h}`],{cwd:e,env:r,timeout:s,maxBuffer:o,encoding:"buffer",windowsHide:!0},(g,w)=>{if(!g)return v({ok:!0,buf:w});if(g.killed||g.signal==="SIGTERM"||g.code==="ETIMEDOUT")return v({ok:!1,why:"timeout"});if(String(g.code).includes("MAXBUFFER"))return v({ok:!1,why:"too-large"});v({ok:!1,why:"missing"})})})}function m(p,h,v){let g=p.get(v),w=h.get(v);if(g&&w)return{status:g.bodyHash===w.bodyHash?"unchanged":"modified",oldN:g,newN:w};let S=(k,y)=>k.kind===y.kind&&k.name===y.name&&k.bodyHash===y.bodyHash&&k.filePath!==y.filePath;if(w){let k=[...p.values()].filter(y=>!h.has(y.id)&&S(y,w)).sort((y,x)=>y.id<x.id?-1:1)[0];return k?{status:"moved",oldN:k,newN:w}:{status:"added",oldN:null,newN:w}}if(g){let k=[...h.values()].filter(y=>!p.has(y.id)&&S(g,y)).sort((y,x)=>y.id<x.id?-1:1)[0];return k?{status:"moved",oldN:g,newN:k}:{status:"removed",oldN:g,newN:null}}return null}let f=p=>p&&Number.isInteger(p.startLine)&&p.startLine>0&&Number.isInteger(p.endLine)&&p.endLine>=p.startLine?[p.startLine,p.endLine]:null;async function u(p,h,v){try{if(typeof p!="string"||!p||p.length>Wf)return{status:400,body:{ok:!1,code:"bad-request",message:"node must be a node id"}};if(!Ha.test(String(h))||!Ha.test(String(v)))return{status:400,body:{ok:!1,code:"bad-request",message:"from and to must be version numbers"}};let g=ss(e),w=g?.versions?.find(C=>String(C.version)===String(h)),S=g?.versions?.find(C=>String(C.version)===String(v));if(!w||!S)return{status:404,body:{ok:!1,code:"unknown-version",message:"no such stored version"}};let k=a(w),y=a(S),x=m(k,y,p);if(!x)return{status:404,body:{ok:!1,code:"unknown-node",message:"no such node in these versions"}};let{status:b,oldN:N,newN:$}=x;for(let C of[N,$]){let B=C&&Gf(C.filePath);if(B)return{status:403,body:{ok:!1,code:"refused",message:"refused: "+B}}}let F={nodeId:p,status:b,from:w.version,to:S.version,oldFile:N?.filePath??null,newFile:$?.filePath??null,oldRange:f(N),newRange:f($),name:($??N).name},H=[];N&&w.dirty&&H.push(w.version),$&&S.dirty&&!H.includes(S.version)&&H.push(S.version);let P=H.length?"approximate: taken with uncommitted changes":null,K=(C,B="")=>({status:200,body:{ok:!0,mode:"node-only",reason:C,message:Uf+B,approximate:P,...F}});if(b==="unchanged")return{status:200,body:{ok:!0,mode:"lines",rows:[],stats:{added:0,removed:0},formattingOnly:!1,approximate:P,message:"this function did not change between these versions",...F}};let U=[];N&&U.push(["old",w.headSha,N.filePath]),$&&U.push(["new",S.headSha,$.filePath]);for(let[,C]of U)if(typeof C!="string"||!zf.test(C))return K("no-git");let D=await Promise.all(U.map(([,C,B])=>c(C,B))),R={};for(let C=0;C<U.length;C++){let B=D[C];if(!B.ok)return B.why==="too-large"?{status:200,body:{ok:!0,mode:"node-only",reason:"too-large",message:"this file is too large to diff here",approximate:P,...F}}:K(B.why==="timeout"?"timeout":"missing-commit");if(B.buf.subarray(0,8e3).includes(0))return{status:403,body:{ok:!1,code:"binary",message:"refused: binary file"}};R[U[C][0]]=B.buf.toString("utf8")}let G=C=>{let B=C.replace(/\r\n/g,`
53
+ `).split(`
54
+ `);return B.length>1&&B[B.length-1]===""&&B.pop(),B},ee=(C,B)=>{let be=G(C);if(!B)return{lines:be,base:1,clamped:!1};let I=B[1]>be.length;return{lines:be.slice(B[0]-1,B[1]),base:B[0],clamped:I}},ne=R.old!=null?ee(R.old,F.oldRange):{lines:[],base:1,clamped:!1},ye=R.new!=null?ee(R.new,F.newRange):{lines:[],base:1,clamped:!1},Ee=R.old!=null&&R.new!=null&&R.old!==R.new&&G(R.old).join(`
55
+ `)===G(R.new).join(`
56
+ `)&&/\r\n/.test(R.old)!==/\r\n/.test(R.new),ct={...F,approximate:P??(ne.clamped||ye.clamped?"approximate: the stored line range no longer fits the file":null)};if(ne.lines.length>5e3||ye.lines.length>5e3)return{status:200,body:{ok:!0,mode:"node-only",reason:"too-large",message:`too large to diff here (more than ${5e3} lines on one side)`,...ct}};let xe;b==="added"?xe=is(ye.lines,"+",ye.base):b==="removed"?xe=is(ne.lines,"-",ne.base):xe=Ma(ne.lines,ye.lines,{aBase:ne.base,bBase:ye.base});let _=C=>C.join(`
57
+ `).replace(/\s+/g,""),E=b!=="added"&&b!=="removed"&&xe.stats.added+xe.stats.removed>0&&_(ne.lines)===_(ye.lines);return{status:200,body:{ok:!0,mode:"lines",rows:xe.rows,stats:xe.stats,coarse:!!xe.coarse,formattingOnly:E,eolOnly:Ee,...ct,message:Ee?"line endings changed":b==="moved"&&!xe.rows.length?"moved to another file, the code is the same":E?"formatting only":null}}}catch{return{status:500,body:{ok:!1,code:"error",message:"the diff could not be computed"}}}}return{diff:u}}async function Ba(e,t,{token:n,service:s}){let o=Xn(e,n);if(o)return o;let r=[...t.searchParams.keys()],i=["node","from","to"].every(a=>t.searchParams.getAll(a).length===1);return r.length!==3||!i?{status:400,body:{ok:!1,code:"bad-request",message:"send exactly three parameters: node=<node id>&from=<version>&to=<version>"}}:s.diff(t.searchParams.get("node"),t.searchParams.get("from"),t.searchParams.get("to"))}var za={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".json":"application/json",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".woff2":"font/woff2",".map":"application/json"};function Ua(e,t,n){let s=Ce.join(e,Ce.normalize(t).replace(/^([/\\]|\.\.[/\\])+/,""));if(!s.startsWith(e+Ce.sep)&&s!==e){n.writeHead(403).end("forbidden");return}St.readFile(s,(o,r)=>{if(o){n.writeHead(404,{"content-type":"text/plain"}).end("not found: "+t);return}n.writeHead(200,{"content-type":za[Ce.extname(s).toLowerCase()]??"application/octet-stream","cache-control":"no-store"}).end(r)})}var Vf=(()=>{try{return JSON.parse(St.readFileSync(Ce.join(re,"package.json"),"utf8")).version}catch{return null}})();function Xf({env:e=process.env,version:t=Vf,kind:n=ns()}={}){return e.CANOPY_NO_UPDATE_CHECK==="1"||e.CANOPY_NO_UPDATE_CHECK==="true"||n!=="installed"||!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(String(t))?"":`<meta name="canopy-update-check" content="${ts}" data-current="${t}">`}function Yf(e,t,n){St.readFile(Ce.join(e,"index.html"),"utf8",(s,o)=>{if(s){t.writeHead(404,{"content-type":"text/plain"}).end("not found: index.html");return}t.writeHead(200,{"content-type":za[".html"],"cache-control":"no-store"}).end(n?o.replace("</head>",n+`
58
+ </head>`):o)})}var Yn=()=>{let e=Ce.join(re,"ui-react");return!St.existsSync(Ce.join(e,"index.html"))||!St.existsSync(Ce.join(e,"dist"))?`this install has no built viewer (ui-react/dist is missing)
59
+ fix: reinstall canopy from a build that includes the viewer`:null};function Zf(){try{let e=JSON.parse(St.readFileSync(Ce.join(re,"package.json"),"utf8")).canopyFeedbackUrl;return typeof e=="string"&&/^https:\/\/[^\s"<>]+$/.test(e)?e:null}catch{return null}}function Qf(e,t){if(t)return t;try{return JSON.parse(St.readFileSync(Ce.join(e,"meta.json"),"utf8")).repoRoot??null}catch{return null}}async function Zn(e,t=0,{updateTag:n=Xf(),repoRoot:s=null,token:o=Pa(),diffOptions:r={}}={}){e=Ce.resolve(e);let i=Ce.join(re,"ui-react"),a=Qf(e,s)??"",l=Ta({outDir:e,repoRoot:a}),c=Da({repoRoot:a,...r}),d=(h,v)=>h.writeHead(v.status,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}).end(JSON.stringify(v.body)),m=Zf(),f=`<meta name="canopy-session" content="${o}">`+(m?`
60
+ <meta name="canopy-feedback" content="${m}">`:""),u=0,p=Jf.createServer((h,v)=>{if(!Ra(h,u)){v.writeHead(403,{"content-type":"text/plain","cache-control":"no-store"}).end("forbidden");return}let g;try{g=new URL(h.url??"/","http://127.0.0.1")}catch{v.writeHead(400).end("bad request");return}let w;try{w=decodeURIComponent(g.pathname)}catch{v.writeHead(400).end("bad request");return}if(w==="/api/source"){let S=Oa(h,g,{port:u,token:o,service:l});d(v,S);return}if(w==="/api/nodes"){d(v,Aa(h,g,{token:o,service:l}));return}if(w==="/api/diff"){Ba(h,g,{token:o,service:c}).then(S=>d(v,S),()=>d(v,{status:500,body:{ok:!1,code:"error",message:"the diff could not be computed"}}));return}if(w==="/"||w==="/index.html"){v.writeHead(302,{location:"/ui-react/index.html"}).end();return}if(w==="/ui-react/index.html")return Yf(i,v,f+(n?`
61
+ `+n:""));if(w.startsWith("/ui-react/"))return Ua(i,w.slice(10),v);if(w.startsWith("/output/"))return Ua(e,w.slice(8),v);v.writeHead(404).end("not found")});return await new Promise((h,v)=>{p.once("error",v),p.listen(t,"127.0.0.1",h)}),u=p.address().port,{server:p,port:u,url:`http://127.0.0.1:${u}/`,token:o}}function Wa(e){if(process.env.CANOPY_NO_BROWSER)return!1;try{let t,n;if(process.platform==="win32")t="cmd.exe",n=["/c","start","",e];else if(process.platform==="darwin")t="open",n=[e];else if(process.env.DISPLAY||process.env.WAYLAND_DISPLAY)t="xdg-open",n=[e];else return!1;let s=Kf(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return s.on("error",()=>{}),s.unref(),!0}catch{return!1}}De();yt();import Je from"node:fs";import et from"node:path";import{execFileSync as qa}from"node:child_process";function Qn(e){let t=[],n=(s,o,r,i)=>{let a=!1,l="";try{let c=r();a=c===!0||!!(c&&c.ok),l=c&&c.detail?c.detail:""}catch(c){l=String(c.message??c).split(`
62
+ `)[0]}t.push({name:s,critical:o,ok:a,detail:l,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])=>!Je.existsSync(et.join(Ae(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=[et.join(re,"src","stage2_parse","queries"),et.join(re,"dist","queries")].find(r=>Je.existsSync(r))??et.join(re,"dist","queries"),o=Je.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=ae(e).root;Je.mkdirSync(s,{recursive:!0});let o=et.join(s,`.doctor-${process.pid}`);return Je.writeFileSync(o,"x"),Je.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:!!qa("git",["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}),detail:qa("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:Je.existsSync(et.join(re,"ui-react","index.html"))&&Je.existsSync(et.join(re,"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(!Ie(e,["rev-parse","--git-dir"]))return{ok:!1,detail:"not a git repository"};let s=Yt(e),o=wt.every(r=>Je.existsSync(et.join(s,r))&&Je.readFileSync(et.join(s,r),"utf8").includes(Xt));return{ok:o,detail:o?"post-commit, post-merge":""}},`canopy hook install "${e}"`),t}function Ga(e,t,n,s=console.log){s(`canopy ${n} doctor (${t})
63
+ `);for(let r of e)s(`${r.ok?"OK ":"FAIL"} ${r.name}${r.detail?" - "+r.detail:""}${r.ok?"":`
64
+ fix: ${r.fix}`}${!r.ok&&!r.critical?" (not critical)":""}`);let o=e.filter(r=>r.critical&&!r.ok);return s(`
65
+ ${o.length?`${o.length} critical problem(s) - fix them and run canopy doctor again`:"all critical checks passed"}`),o.length}import me from"node:fs";import eu from"node:net";import tu from"node:os";import at from"node:path";import nu from"node:readline";yt();var Ja=Number(process.env.CANOPY_MIN_FREE_MB)||300,ou=".js .jsx .mjs .cjs .ts .tsx .mts .cts",eo=class extends Error{constructor(t,n){super(n),this.code=t,this.line=n}},Le=(e,t)=>{throw new eo(e,t)};function su(e){let t=!!Ie(e,["rev-parse","--git-dir"]),n=at.join(e,".gitignore"),s=me.existsSync(n);if(!t&&!s)return"skipped";let o=s?me.readFileSync(n,"utf8"):"";if(o.split(/\r?\n/).some(i=>/^\/?\.canopy\/?$/.test(i.trim())))return"already";let r=/\r\n/.test(o)?`\r
55
66
  `:`
56
- `;return pe.appendFileSync(n,(o&&!/\r?\n$/.test(o)?s:"")+"# Canopy (code map output)"+s+".canopy/"+s),r?"added":"created"}var _a=e=>ot.join(se(e).root,"prefs.json"),$a=e=>{try{return JSON.parse(pe.readFileSync(_a(e),"utf8"))}catch{return{}}};function Yn(e,t){let n={...$a(e),...t};for(let r of Object.keys(n))n[r]===void 0&&delete n[r];pe.mkdirSync(se(e).root,{recursive:!0}),pe.writeFileSync(_a(e),JSON.stringify(n,null,2))}function hf(e){return new Promise(t=>{let n=df.createServer();n.once("error",r=>t({ok:!1,code:r.code,message:r.message})),n.listen(e,"127.0.0.1",()=>{let r=n.address().port;n.close(()=>t({ok:!0,port:r}))})})}function gf(e){try{let t=pe.statfsSync(e);return Math.floor(t.bavail*t.bsize/1048576)}catch{return null}}var yf=()=>!!(process.stdin.isTTY&&process.stdout.isTTY)||!!process.env.CANOPY_ASSUME_TTY;function xf(e,t){return new Promise(n=>{let r=uf.createInterface({input:process.stdin,output:process.stdout,terminal:!1}),o=!1,s=i=>{o||(o=!0,r.close(),n(i))};r.question(e,i=>s(i.trim())),r.once("close",()=>s(""))}).then(n=>n===""?t:n)}function vf(e){try{return JSON.parse(pe.readFileSync(ot.join(e,"meta.json"),"utf8"))}catch{return null}}function wf(e){try{return JSON.parse(pe.readFileSync(ot.join(e,"services.js"),"utf8").replace(/^\s*const services\s*=\s*/,"").replace(/;\s*$/,""))}catch{return[]}}var Sf=e=>`How did it go? ${e.canopyFeedbackUrl||"see FEEDBACK.md in the README (about 20 minutes)"}`;async function Fa(e){let t=e.say??console.log,{pkg:n}=e,r=null;try{return await o()}catch(c){if(c instanceof Vn){if(t(c.line),r)try{pe.rmdirSync(r)}catch{}return c.code}return t(`Canopy stopped because of an unexpected problem: ${String(c.message??c).split(`
67
+ `;return me.appendFileSync(n,(o&&!/\r?\n$/.test(o)?r:"")+"# Canopy (code map output)"+r+".canopy/"+r),s?"added":"created"}var Ka=e=>at.join(ae(e).root,"prefs.json"),Va=e=>{try{return JSON.parse(me.readFileSync(Ka(e),"utf8"))}catch{return{}}};function to(e,t){let n={...Va(e),...t};for(let s of Object.keys(n))n[s]===void 0&&delete n[s];me.mkdirSync(ae(e).root,{recursive:!0}),me.writeFileSync(Ka(e),JSON.stringify(n,null,2))}function ru(e){return new Promise(t=>{let n=eu.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 iu(e){try{let t=me.statfsSync(e);return Math.floor(t.bavail*t.bsize/1048576)}catch{return null}}var au=()=>!!(process.stdin.isTTY&&process.stdout.isTTY)||!!process.env.CANOPY_ASSUME_TTY;function cu(e,t){return new Promise(n=>{let s=nu.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 lu(e){try{return JSON.parse(me.readFileSync(at.join(e,"meta.json"),"utf8"))}catch{return null}}function du(e){try{return JSON.parse(me.readFileSync(at.join(e,"services.js"),"utf8").replace(/^\s*const services\s*=\s*/,"").replace(/;\s*$/,""))}catch{return[]}}var fu=e=>`How did it go? ${e.canopyFeedbackUrl||"see FEEDBACK.md in the README (about 20 minutes)"}`;async function Xa(e){let t=e.say??console.log,{pkg:n}=e,s=null;try{return await o()}catch(c){if(c instanceof eo){if(t(c.line),s)try{me.rmdirSync(s)}catch{}return c.code}return t(`Canopy stopped because of an unexpected problem: ${String(c.message??c).split(`
57
68
  `)[0]}
58
- Run "canopy doctor", then send its output and .canopy/sync.log to whoever gave you Canopy.`),process.env.CANOPY_DEBUG&&t(c.stack),1}async function o(){let c=ot.resolve(e.target??process.cwd());t(`Canopy ${n.version} - a map of what your JavaScript / TypeScript code does`),t(`Folder: ${c}
59
- `),t("[1/6] Checking this computer..."),Number(process.versions.node.split(".")[0])<18&&$e(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 d=pe.existsSync(c)&&pe.statSync(c).isDirectory();pe.existsSync(c)||$e(1,`That folder does not exist: ${c}. Check the spelling, or run canopy inside your project folder.`),d||$e(1,`${c} is a file, not a folder. Run canopy on the folder that contains it: canopy "${ot.dirname(c)}"`);let p=pe.existsSync(se(c).root),f=Kn(c);p||(r=se(c).root);let u=f.find(L=>L.critical&&!L.ok);u&&$e(1,`${u.name} failed${u.detail?" ("+u.detail+")":""}. ${u.fix}.`.replace(/\.\.$/,"."));let m=!!be(c,["rev-parse","--git-dir"]),h=f.find(L=>L.name==="git available")?.ok,v=Gn();v&&!e.noOpen&&$e(1,`Canopy cannot show the map: ${v.replace(/\n\s*/g,". ")}.`);let g=gf(c);if(g!==null&&g<ba&&$e(1,`Only ${g} MB free on the disk holding ${c}; Canopy needs about ${ba} MB. Free some space and run canopy again.`),!e.noOpen){let L=await hf(e.port??0);L.ok||$e(1,L.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 (${L.code||L.message}). Check your firewall or security software and run canopy again.`)}t(` Node ${process.versions.node}, ${h?"git found":"git not found (no version history or commit hook)"}, ${g===null?"disk space not checked":g+" MB free"}${e.noOpen?"":", a local port is free"}.`),t("[2/6] Looking at your project..."),pe.readdirSync(c).filter(L=>L!==".git"&&L!==".canopy").length===0&&$e(1,`${c} is empty. Add some JavaScript or TypeScript code and run canopy again.`);let S=an(c);S.length===0&&$e(3,`No JavaScript or TypeScript files found in ${c}. Canopy currently supports JavaScript and TypeScript (${pf}); other languages are not read yet.`);let N=m&&be(c,["rev-parse","--verify","-q","HEAD"])!==null;t(` ${S.length.toLocaleString("en-US")} JavaScript / TypeScript file${S.length===1?"":"s"}. ${m?N?"Git repository.":"Git repository with no commits yet (that is fine).":"Not a git repository (that is fine; version-aware features are limited)."}`),t("[3/6] Preparing the output folder..."),pe.mkdirSync(se(c).root,{recursive:!0}),Dn(c);let y=mf(c),x={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"}[y];t(` Map output goes to ${ot.join(c,".canopy")} (${x}).`),t("[4/6] Commit hook..."),await s(c,m);let b=He(c).versions.length>0;t(`[5/6] ${b?"Checking what changed since last time":"Building your map for the first time (a big project can take a few minutes)"}...`);let k=await i(c,S.length);a(c,k);let $=ht(c);if(e.noOpen)return t("[6/6] Not opening the map (--no-open). To view it later: canopy open"),l(),0;t("[6/6] Opening the map...");let j;try{j=await Jn($,e.port??0)}catch(L){$e(1,`Canopy cannot start the viewer: ${L.code||L.message}. ${L.code==="EADDRINUSE"?"Pick another port with --port=NUMBER.":"Check your firewall or security software."}`)}t(` ${j.url}`);let D=Sa(j.url);return t(D?" Your browser should open now. If it does not, paste that address into one.":" Open that address in your browser."),l(),e.forSeconds?(await new Promise(L=>setTimeout(L,e.forSeconds*1e3)),j.server.close(),0):(t("Press Ctrl+C to stop."),await new Promise(()=>{}),0)}async function s(c,d){if(!d){t(" No git repository here, so there is no commit hook to set up.");return}if(!kf()){t(" git is not installed, so the commit hook is skipped.");return}let p;try{p=ma(c)}catch(u){t(" Could not look at the git hooks ("+String(u.message).split(`
60
- `)[0]+"); skipping the commit hook.");return}if(p==="current"){t(" The map already updates on every commit.");return}if(p==="outdated"){try{Jt(c),t(" Refreshed the commit hook (it now matches this Canopy).")}catch(u){t(" Could not refresh the commit hook: "+String(u.message).split(`
61
- `)[0])}return}if($a(c).hook==="declined"&&!e.yes){t(" The commit hook is off (you chose that earlier). Turn it on with: canopy hook install");return}let f=!0;if(e.yes)t(" Update the map on every commit? [Y/n] Y (--yes)");else if(!yf())t(" Update the map on every commit? [Y/n] Y (default; no terminal to ask)");else{let u=await xf(" Update the map on every commit? [Y/n] ","Y");f=/^y(es)?$/i.test(u)}if(!f){Yn(c,{hook:"declined"}),t(" Okay, no hook. Turn it on any time with: canopy hook install");return}try{Jt(c),Yn(c,{hook:void 0}),t(" 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(u){t(" Could not install the commit hook: "+String(u.message).split(`
62
- `)[0]+". Continuing without it.")}}async function i(c,d){let p=Date.now(),f=h=>{let v=/parsing: (\d+)\/(\d+) files/.exec(String(h));v&&t(` reading files: ${v[1]} of ${v[2]}`)};t(` Reading ${d.toLocaleString("en-US")} file${d===1?"":"s"}, linking calls, finding entry points, tracing workflows...`);let u;for(let h=0;h<2&&(u=await zn(c,{say:v=>f(v),onProgress:f}).catch(v=>$e(1,`The analysis failed: ${String(v.message??v).split(`
69
+ Run "canopy doctor", then send its output and .canopy/sync.log to whoever gave you Canopy.`),process.env.CANOPY_DEBUG&&t(c.stack),1}async function o(){let c=at.resolve(e.target??process.cwd());t(`Canopy ${n.version} - a map of what your JavaScript / TypeScript code does`),t(`Folder: ${c}
70
+ `),t("[1/6] Checking this computer..."),Number(process.versions.node.split(".")[0])<18&&Le(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 d=me.existsSync(c)&&me.statSync(c).isDirectory();me.existsSync(c)||Le(1,`That folder does not exist: ${c}. Check the spelling, or run canopy inside your project folder.`),d||Le(1,`${c} is a file, not a folder. Run canopy on the folder that contains it: canopy "${at.dirname(c)}"`);let m=me.existsSync(ae(c).root),f=Qn(c);m||(s=ae(c).root);let u=f.find(P=>P.critical&&!P.ok);u&&Le(1,`${u.name} failed${u.detail?" ("+u.detail+")":""}. ${u.fix}.`.replace(/\.\.$/,"."));let p=!!Ie(c,["rev-parse","--git-dir"]),h=f.find(P=>P.name==="git available")?.ok,v=Yn();v&&!e.noOpen&&Le(1,`Canopy cannot show the map: ${v.replace(/\n\s*/g,". ")}.`);let g=iu(c);if(g!==null&&g<Ja&&Le(1,`Only ${g} MB free on the disk holding ${c}; Canopy needs about ${Ja} MB. Free some space and run canopy again.`),!e.noOpen){let P=await ru(e.port??0);P.ok||Le(1,P.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 (${P.code||P.message}). Check your firewall or security software and run canopy again.`)}t(` Node ${process.versions.node}, ${h?"git found":"git not found (no version history or commit hook)"}, ${g===null?"disk space not checked":g+" MB free"}${e.noOpen?"":", a local port is free"}.`),t("[2/6] Looking at your project..."),me.readdirSync(c).filter(P=>P!==".git"&&P!==".canopy").length===0&&Le(1,`${c} is empty. Add some JavaScript or TypeScript code and run canopy again.`);let S=dn(c);S.length===0&&Le(3,`No JavaScript or TypeScript files found in ${c}. Canopy currently supports JavaScript and TypeScript (${ou}); other languages are not read yet.`);let k=p&&Ie(c,["rev-parse","--verify","-q","HEAD"])!==null;t(` ${S.length.toLocaleString("en-US")} JavaScript / TypeScript file${S.length===1?"":"s"}. ${p?k?"Git repository.":"Git repository with no commits yet (that is fine).":"Not a git repository (that is fine; version-aware features are limited)."}`),t("[3/6] Preparing the output folder..."),me.mkdirSync(ae(c).root,{recursive:!0}),zn(c);let y=su(c),x={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"}[y];t(` Map output goes to ${at.join(c,".canopy")} (${x}).`),t("[4/6] Commit hook..."),await r(c,p);let b=Ge(c).versions.length>0;t(`[5/6] ${b?"Checking what changed since last time":"Building your map for the first time (a big project can take a few minutes)"}...`);let N=await i(c,S.length);a(c,N);let $=vt(c);if(e.noOpen)return t("[6/6] Not opening the map (--no-open). To view it later: canopy open"),l(),0;t("[6/6] Opening the map...");let F;try{F=await Zn($,e.port??0)}catch(P){Le(1,`Canopy cannot start the viewer: ${P.code||P.message}. ${P.code==="EADDRINUSE"?"Pick another port with --port=NUMBER.":"Check your firewall or security software."}`)}t(` ${F.url}`);let H=Wa(F.url);return t(H?" Your browser should open now. If it does not, paste that address into one.":" Open that address in your browser."),l(),e.forSeconds?(await new Promise(P=>setTimeout(P,e.forSeconds*1e3)),F.server.close(),0):(t("Press Ctrl+C to stop."),await new Promise(()=>{}),0)}async function r(c,d){if(!d){t(" No git repository here, so there is no commit hook to set up.");return}if(!uu()){t(" git is not installed, so the commit hook is skipped.");return}let m;try{m=ba(c)}catch(u){t(" Could not look at the git hooks ("+String(u.message).split(`
71
+ `)[0]+"); skipping the commit hook.");return}if(m==="current"){t(" The map already updates on every commit.");return}if(m==="outdated"){try{Zt(c),t(" Refreshed the commit hook (it now matches this Canopy).")}catch(u){t(" Could not refresh the commit hook: "+String(u.message).split(`
72
+ `)[0])}return}if(Va(c).hook==="declined"&&!e.yes){t(" The commit hook is off (you chose that earlier). Turn it on with: canopy hook install");return}let f=!0;if(e.yes)t(" Update the map on every commit? [Y/n] Y (--yes)");else if(!au())t(" Update the map on every commit? [Y/n] Y (default; no terminal to ask)");else{let u=await cu(" Update the map on every commit? [Y/n] ","Y");f=/^y(es)?$/i.test(u)}if(!f){to(c,{hook:"declined"}),t(" Okay, no hook. Turn it on any time with: canopy hook install");return}try{Zt(c),to(c,{hook:void 0}),t(" 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(u){t(" Could not install the commit hook: "+String(u.message).split(`
73
+ `)[0]+". Continuing without it.")}}async function i(c,d){let m=Date.now(),f=h=>{let v=/parsing: (\d+)\/(\d+) files/.exec(String(h));v&&t(` reading files: ${v[1]} of ${v[2]}`)};t(` Reading ${d.toLocaleString("en-US")} file${d===1?"":"s"}, linking calls, finding entry points, tracing workflows...`);let u;for(let h=0;h<2&&(u=await Gn(c,{say:v=>f(v),onProgress:f}).catch(v=>Le(1,`The analysis failed: ${String(v.message??v).split(`
63
74
  `)[0]}
64
- Run "canopy doctor" and send its output with ${ot.join(c,".canopy","sync.log")} to whoever gave you Canopy.`)),u.status==="queued");h++){t(" Another update is already running; waiting for it to finish...");for(let v=0;v<1200&&pe.existsSync(se(c).lock);v++)await new Promise(g=>setTimeout(g,500))}u.status==="queued"&&$e(1,"Another Canopy update is still running. Wait for it to finish and run canopy again.");let m=((Date.now()-p)/1e3).toFixed(1);return t(u.status==="no-changes"?` Nothing changed since version ${u.version.version} (${m} s).`:` Saved version ${u.version.version} (${m} s).`),u}function a(c,d){let p=ht(c),f=d.coverage??vf(p)?.coverage,u=wf(p),m=d.version.counts??{};if(t(`
65
- Your map`),t(` services: ${u.length}${u.length?" ("+u.map(h=>h.id??h.name).slice(0,8).join(", ")+(u.length>8?", ...":"")+")":""}`),t(` workflows: ${m.workflows??"?"}${m.physicalWorkflows!==void 0?` (${m.physicalWorkflows} traced from real code, ${m.workflows-m.physicalWorkflows} guessed)`:""}`),f){let h=f.analyzed?Math.round(f.inService/f.analyzed*100):0;t(` files inside a service: ${f.inService} of ${f.analyzed} (${h}%)`),t(` files with parse errors: ${f.parseErrors}${f.parseErrors?" ("+f.parseErrorFiles.slice(0,3).join(", ")+(f.parseErrorFiles.length>3?", ...":"")+")":""}`),f.notAnalyzedTotal&&t(` not read yet: ${f.notAnalyzedTotal} files in languages Canopy does not support (${Object.entries(f.notAnalyzed).map(([v,g])=>`${g} ${v}`).join(", ")})`)}u.length||t(" The map is empty: Canopy found no entry points (routes, listeners, a main file) it recognises in this project."),t("")}function l(){t("Next time just run `canopy`."),t(Sf(n))}}function kf(){return!!be(ff.tmpdir(),["--version"])}var Zt=JSON.parse(Zo.readFileSync(Yt.join(re,"package.json"),"utf8")),Nf={"-y":"--yes","-h":"--help","-v":"--version"},Ia=process.argv.slice(2).map(e=>Nf[e]??e),de=Object.fromEntries(Ia.filter(e=>e.startsWith("--")).map(e=>{let[t,n]=e.slice(2).split("=");return[t,n??!0]})),Fe=Ia.filter(e=>!e.startsWith("--")),Ee=Fe.shift(),bf=e=>/^v?\d+$/.test(e??""),yt=()=>Yt.resolve(Fe[0]&&!bf(Fe[0])?Fe.shift():process.cwd()),ja=`canopy ${Zt.version} - a map of what your JavaScript / TypeScript code does
75
+ Run "canopy doctor" and send its output with ${at.join(c,".canopy","sync.log")} to whoever gave you Canopy.`)),u.status==="queued");h++){t(" Another update is already running; waiting for it to finish...");for(let v=0;v<1200&&me.existsSync(ae(c).lock);v++)await new Promise(g=>setTimeout(g,500))}u.status==="queued"&&Le(1,"Another Canopy update is still running. Wait for it to finish and run canopy again.");let p=((Date.now()-m)/1e3).toFixed(1);return t(u.status==="no-changes"?` Nothing changed since version ${u.version.version} (${p} s).`:` Saved version ${u.version.version} (${p} s).`),u}function a(c,d){let m=vt(c),f=d.coverage??lu(m)?.coverage,u=du(m),p=d.version.counts??{};if(t(`
76
+ Your map`),t(` services: ${u.length}${u.length?" ("+u.map(h=>h.id??h.name).slice(0,8).join(", ")+(u.length>8?", ...":"")+")":""}`),t(` workflows: ${p.workflows??"?"}${p.physicalWorkflows!==void 0?` (${p.physicalWorkflows} traced from real code, ${p.workflows-p.physicalWorkflows} guessed)`:""}`),f){let h=f.analyzed?Math.round(f.inService/f.analyzed*100):0;t(` files inside a service: ${f.inService} of ${f.analyzed} (${h}%)`),t(` files with parse errors: ${f.parseErrors}${f.parseErrors?" ("+f.parseErrorFiles.slice(0,3).join(", ")+(f.parseErrorFiles.length>3?", ...":"")+")":""}`),f.notAnalyzedTotal&&t(` not read yet: ${f.notAnalyzedTotal} files in languages Canopy does not support (${Object.entries(f.notAnalyzed).map(([v,g])=>`${g} ${v}`).join(", ")})`)}u.length||t(" The map is empty: Canopy found no entry points (routes, listeners, a main file) it recognises in this project."),t("")}function l(){t("Next time just run `canopy`."),t(fu(n))}}function uu(){return!!Ie(tu.tmpdir(),["--version"])}var nn=JSON.parse(cs.readFileSync(en.join(re,"package.json"),"utf8")),pu={"-y":"--yes","-h":"--help","-v":"--version"},Ya=process.argv.slice(2).map(e=>pu[e]??e),fe=Object.fromEntries(Ya.filter(e=>e.startsWith("--")).map(e=>{let[t,n]=e.slice(2).split("=");return[t,n??!0]})),Te=Ya.filter(e=>!e.startsWith("--")),Me=Te.shift(),mu=e=>/^v?\d+$/.test(e??""),kt=()=>en.resolve(Te[0]&&!mu(Te[0])?Te.shift():process.cwd()),Za=`canopy ${nn.version} - a map of what your JavaScript / TypeScript code does
66
77
 
67
78
  usage: canopy [path] [-y] [--no-open] do everything in order: check this computer, look at the project, prepare .canopy/,
68
79
  offer the commit hook, build the map, open it in your browser (default path: current folder)
@@ -80,8 +91,8 @@ usage: canopy [path] [-y] [--no-open] do everything in order: check this com
80
91
  options for the one-command path: -y / --yes (do not ask; install the hook), --no-open (build the map but do not start the viewer),
81
92
  --port=N, --for=SECONDS (stop the viewer by itself after that time)
82
93
  Exit codes: 0 ok, 1 a problem (the message says what to do), 3 no JavaScript / TypeScript files found.
83
- Node >= 18 required. Output lives in <path>/.canopy/ (kept out of git automatically).`;async function _f(){let e=yt(),t=ht(e);Zo.existsSync(Yt.join(t,"workflows.js"))||(console.error(`no map yet for ${e}
84
- fix: canopy sync "${e}"`),process.exit(1));let n=Gn();n&&(console.error(n),process.exit(1));let{server:r,url:o}=await Jn(t,de.port?Number(de.port):0);if(console.log(`canopy map for ${e}
85
- ${o}`),de.for){console.log(`serving for ${Number(de.for)} s`),await new Promise(s=>setTimeout(s,Number(de.for)*1e3)),r.close();return}console.log("press Ctrl+C to stop"),await new Promise(()=>{})}function $f(){let e=yt();process.exit(Na(Kn(e),e,Zt.version)?1:0)}var Xt={async sync(){let e=yt();if(de.background){let n=pa(e);n?console.log(`sync started in the background (pid ${n}); log: .canopy/sync.log`):console.error(`not a directory, nothing to sync: ${e}`);return}let t=de.keep?Number(de.keep):Wt;await zn(e,{keep:t})},open:_f,async doctor(){$f()},async update(){process.exit(await xa({check:!!de.check,version:Zt.version}))},async diff(){let e=yt(),t=He(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 a=Number(String(i).replace(/^v/,"")),l=t.versions.find(c=>c.version===a);if(!l)throw new Error(`no such version: ${i} (have ${t.versions.map(c=>"v"+c.version).join(", ")})`);return l},r=Fe[1]!==void 0?n(Fe[1]):t.versions[t.versions.length-1],o=Fe[0]!==void 0?n(Fe[0]):t.versions[t.versions.indexOf(r)-1];if(!o)throw new Error("no earlier version to compare against");let s=Un(Lt(e,o),Lt(e,r));console.log(de.json?ta(s):na(s,r,o))},async"install-hook"(){let e=yt(),t=Jt(e);Yn(e,{hook:void 0}),console.log("installed canopy block in: "+t.join(", "))},async"uninstall-hook"(){let e=ua(yt());console.log(e.length?"removed canopy block from: "+e.join(", "):"no canopy hook block found")},async hook(){let e=Fe.shift();if(e==="install")return Xt["install-hook"]();if(e==="uninstall")return Xt["uninstall-hook"]();console.error("usage: canopy hook install|uninstall [path]"),process.exit(2)},async history(){let e=yt(),t=He(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":""}`)}};(de.version||Ee==="version")&&(console.log(Zt.version),process.exit(0));(de.help||Ee==="help")&&(console.log(ja),process.exit(0));if(Ee===void 0||!Xt[Ee]&&(Zo.existsSync(Yt.resolve(Ee))||/^[.~]|[\\/]/.test(Ee))){Ee!==void 0&&Fe.unshift(Ee);let e=await Fa({target:Fe[0]?Yt.resolve(Fe[0]):process.cwd(),yes:!!de.yes,noOpen:!!de["no-open"],port:de.port?Number(de.port):void 0,forSeconds:de.for?Number(de.for):void 0,pkg:Zt});process.exit(e)}Xt[Ee]||(console.error(`unknown command: ${Ee}
94
+ Node >= 18 required. Output lives in <path>/.canopy/ (kept out of git automatically).`;async function hu(){let e=kt(),t=vt(e);cs.existsSync(en.join(t,"workflows.js"))||(console.error(`no map yet for ${e}
95
+ fix: canopy sync "${e}"`),process.exit(1));let n=Yn();n&&(console.error(n),process.exit(1));let{server:s,url:o}=await Zn(t,fe.port?Number(fe.port):0);if(console.log(`canopy map for ${e}
96
+ ${o}`),fe.for){console.log(`serving for ${Number(fe.for)} s`),await new Promise(r=>setTimeout(r,Number(fe.for)*1e3)),s.close();return}console.log("press Ctrl+C to stop"),await new Promise(()=>{})}function gu(){let e=kt();process.exit(Ga(Qn(e),e,nn.version)?1:0)}var tn={async sync(){let e=kt();if(fe.background){let n=Na(e);n?console.log(`sync started in the background (pid ${n}); log: .canopy/sync.log`):console.error(`not a directory, nothing to sync: ${e}`);return}let t=fe.keep?Number(fe.keep):Vt;await Gn(e,{keep:t})},open:hu,async doctor(){gu()},async update(){process.exit(await Fa({check:!!fe.check,version:nn.version}))},async diff(){let e=kt(),t=Ge(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 a=Number(String(i).replace(/^v/,"")),l=t.versions.find(c=>c.version===a);if(!l)throw new Error(`no such version: ${i} (have ${t.versions.map(c=>"v"+c.version).join(", ")})`);return l},s=Te[1]!==void 0?n(Te[1]):t.versions[t.versions.length-1],o=Te[0]!==void 0?n(Te[0]):t.versions[t.versions.indexOf(s)-1];if(!o)throw new Error("no earlier version to compare against");let r=Wn(Mt(e,o),Mt(e,s));console.log(fe.json?fa(r):ua(r,s,o))},async"install-hook"(){let e=kt(),t=Zt(e);to(e,{hook:void 0}),console.log("installed canopy block in: "+t.join(", "))},async"uninstall-hook"(){let e=ka(kt());console.log(e.length?"removed canopy block from: "+e.join(", "):"no canopy hook block found")},async hook(){let e=Te.shift();if(e==="install")return tn["install-hook"]();if(e==="uninstall")return tn["uninstall-hook"]();console.error("usage: canopy hook install|uninstall [path]"),process.exit(2)},async history(){let e=kt(),t=Ge(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":""}`)}};(fe.version||Me==="version")&&(console.log(nn.version),process.exit(0));(fe.help||Me==="help")&&(console.log(Za),process.exit(0));if(Me===void 0||!tn[Me]&&(cs.existsSync(en.resolve(Me))||/^[.~]|[\\/]/.test(Me))){Me!==void 0&&Te.unshift(Me);let e=await Xa({target:Te[0]?en.resolve(Te[0]):process.cwd(),yes:!!fe.yes,noOpen:!!fe["no-open"],port:fe.port?Number(fe.port):void 0,forSeconds:fe.for?Number(fe.for):void 0,pkg:nn});process.exit(e)}tn[Me]||(console.error(`unknown command: ${Me}
86
97
 
87
- ${ja}`),process.exit(2));Xt[Ee]().catch(e=>{console.error(e.stack||e.message),process.exit(1)});
98
+ ${Za}`),process.exit(2));tn[Me]().catch(e=>{console.error(e.stack||e.message),process.exit(1)});