canopy-engine 0.1.3 → 0.1.5

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
@@ -1,79 +1,101 @@
1
1
  #!/usr/bin/env node
2
2
  import{fileURLToPath as __cf,pathToFileURL as __cu}from"node:url";import{dirname as __cd,join as __cj}from"node:path";import{createRequire as __cr}from"node:module";
3
3
  const require=__cr(import.meta.url);
4
- globalThis.__canopyBundle=__cf(import.meta.url);
5
- globalThis.__canopyUrl=(r)=>__cu(__cj(__cd(__cd(globalThis.__canopyBundle)),r)).href;
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
- `)?`
9
- `:"")+`.canopy/
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(`
4
+ globalThis.__canopyBundle??=__cj(__cd(__cf(import.meta.url)),"canopy.js");
5
+ globalThis.__canopyUrl??=(r)=>__cu(__cj(__cd(__cd(globalThis.__canopyBundle)),r)).href;
6
+ import{a as mo,b as ho,d as go,e as yo,g as vo}from"./chunk-AF33YUHF.js";import{a as Lo,b as Po,c as Mo,d as To,f as Oo,g as Ao,h as Fo,i as Bo,j as Do,k as Ho,l as zo,m as Uo,o as Wo,p as qo}from"./chunk-3NY67ODS.js";import{s as _o,t as Co}from"./chunk-KGDTP5LR.js";import{a as wo,b as At,c as Ft,d as pe,e as Ie,f as Bt,g as nt,h as $n,i as xo,j as So,k as ko,l as $o,m as bo,n as No,o as Io,p as jo,q as Eo,r as Ro}from"./chunk-5KSCMRFH.js";import{b as bn,d as Go}from"./chunk-NW4RXPYG.js";import{a as Ni,b as Ii,c as Pe,d as Ot}from"./chunk-DVXET5T4.js";var ns=Ni((Nl,zt)=>{function Xo(e){return Array.isArray(e)?e:[e]}var Ei=void 0,In="",Yo=" ",Nn="\\",Ri=/^\s+$/,_i=/(?:[^\\]|^)\\$/,Ci=/^\\!/,Li=/^\\#/,Pi=/\r?\n/g,Mi=/^\.{0,2}\/|^\.{1,2}$/,Ti=/\/$/,ht="/",Ko="node-ignore";typeof Symbol<"u"&&(Ko=Symbol.for("node-ignore"));var Zo=Ko,gt=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),Oi=/([0-z])-([0-z])/g,Qo=()=>!1,Ai=e=>e.replace(Oi,(t,n,s)=>n.charCodeAt(0)<=s.charCodeAt(0)?t:In),Fi=e=>e.startsWith("!")||e.startsWith("\\^")?`^${e.slice(e[0]==="!"?1:2)}`:e,Bi=e=>{let{length:t}=e;return e.slice(0,t-t%2)},Di=[[/^\uFEFF/,()=>In],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?Yo:In)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+Yo}],[/[\\$.|*+(){^]/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,()=>Nn],[/\\\\/g,()=>Nn],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,s,o)=>t===Nn?`\\[${n}${Bi(s)}${o}`:o==="]"&&s.length%2===0?`[${Fi(Ai(n))}${s}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],Hi=/(^|\\\/)?\\\*$/,$t="regex",Dt="checkRegex",Vo="_",zi={[$t](e,t){return`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Dt](e,t){return`${t?`${t}[^/]*`:"[^/]*"}(?=$|\\/$)`}},Ui=e=>Di.reduce((t,[n,s])=>t.replace(n,s.bind(e)),e),Ht=e=>typeof e=="string",Wi=e=>e&&Ht(e)&&!Ri.test(e)&&!_i.test(e)&&e.indexOf("#")!==0,qi=e=>e.split(Pi).filter(Boolean),jn=class{constructor(t,n,s,o,r,i){this.pattern=t,this.mark=n,this.negative=r,gt(this,"body",s),gt(this,"ignoreCase",o),gt(this,"regexPrefix",i)}get regex(){let t=Vo+$t;return this[t]?this[t]:this._make($t,t)}get checkRegex(){let t=Vo+Dt;return this[t]?this[t]:this._make(Dt,t)}_make(t,n){let s=this.regexPrefix.replace(Hi,zi[t]),o=this.ignoreCase?new RegExp(s,"i"):new RegExp(s);return gt(this,n,o)}},Gi=({pattern:e,mark:t},n)=>{let s=!1,o=e;o.indexOf("!")===0&&(s=!0,o=o.substr(1)),o=o.replace(Ci,"!").replace(Li,"#");let r=Ui(o);return new jn(e,t,o,n,s,r)},En=class{constructor(t){this._ignoreCase=t,this._rules=[]}_add(t){if(t&&t[Zo]){this._rules=this._rules.concat(t._rules._rules),this._added=!0;return}if(Ht(t)&&(t={pattern:t}),Wi(t.pattern)){let n=Gi(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,Xo(Ht(t)?qi(t):t).forEach(this._add,this),this._added}test(t,n,s){let o=!1,r=!1,i;this._rules.forEach(a=>{let{negative:l}=a;r===l&&o!==r||l&&!o&&!r&&!n||!a[s].test(t)||(o=!l,r=l,i=l?Ei:a)});let c={ignored:o,unignored:r};return i&&(c.rule=i),c}},Ji=(e,t)=>{throw new t(e)},He=(e,t,n)=>Ht(e)?e?He.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),es=e=>Mi.test(e);He.isNotRelative=es;He.convert=e=>e;var Rn=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:s=!1}={}){gt(this,Zo,!0),this._rules=new En(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&&He.convert(t);return He(r,t,this._strictPathCheck?Ji:Qo),this._t(r,n,s,o)}checkIgnore(t){if(!Ti.test(t))return this.test(t);let n=t.split(ht).filter(Boolean);if(n.pop(),n.length){let s=this._t(n.join(ht)+ht,this._testCache,!0,n);if(s.ignored)return s}return this._rules.test(t,!1,Dt)}_t(t,n,s,o){if(t in n)return n[t];if(o||(o=t.split(ht).filter(Boolean)),o.pop(),!o.length)return n[t]=this._rules.test(t,s,$t);let r=this._t(o.join(ht)+ht,n,s,o);return n[t]=r.ignored?r:this._rules.test(t,s,$t)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return Xo(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},_n=e=>new Rn(e),Yi=e=>He(e&&He.convert(e),e,Qo),ts=()=>{let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");He.convert=e;let t=/^[a-z]:\//i;He.isNotRelative=n=>t.test(n)||es(n)};typeof process<"u"&&process.platform==="win32"&&ts();zt.exports=_n;_n.default=_n;zt.exports.isPathValid=Yi;gt(zt.exports,Symbol.for("setupWindows"),ts)});import{isMainThread as Jo,workerData as ji}from"node:worker_threads";Jo&&!process.env.UV_THREADPOOL_SIZE&&(process.env.UV_THREADPOOL_SIZE="16");if(!Jo&&ji?.canopyParseWorker===!0){let{runParseWorker:e}=await import("./chunk-67UE7CV6.js");await e(),await new Promise(()=>{})}import lo from"node:fs";import Ct from"node:path";import Ke from"node:fs";import Ca from"node:os";import fe from"node:path";import{fileURLToPath as Xr}from"node:url";import K from"node:path";import he from"node:fs";import{fileURLToPath as ja,pathToFileURL as Ea}from"node:url";var Pn=Ii(ns(),1);import yt from"node:fs";import Se from"node:path";var Cn={javascript:[".js",".jsx",".mjs",".cjs"],typescript:[".ts",".tsx"]},os=[".ts",".tsx",".mts",".cts"],Vi={javascript:["index.js","index.jsx"],typescript:["index.ts","index.tsx"]};function ss(){return Object.values(Cn).flat()}function rs(){return Object.values(Vi).flat()}var is=["log","logger","console","debug","trace"];var as=[".yarn",".pnp","vendor","dist","build","out","coverage",".next",".nuxt",".turbo",".cache","bower_components"],Mn=["node_modules",".git",".canopy",".canopy-cache"],cs=[".vue",".svelte"],Xi=1024*1024,Ln=1e4;function Ki(e,t=null){let n=[];function s(o,r){let i=Se.join(o,".gitignore"),c=(0,Pn.default)().add(r);yt.existsSync(i)&&c.add(yt.readFileSync(i,"utf-8"));let a=yt.readdirSync(o,{withFileTypes:!0});for(let l of a){let f=Se.join(o,l.name),h=Se.relative(e,f).split(Se.sep).join("/");if(!c.ignores(h)&&!(l.isDirectory()&&Mn.includes(l.name))){if(l.isDirectory()&&as.includes(l.name)){t&&t.excludedDirs.push(f);continue}l.isDirectory()?s(f,c):l.isFile()&&n.push(f)}}}return s(e,(0,Pn.default)()),n}function Zi(e,t,n=null){return e.filter(s=>!(n?Se.relative(n,s):s).split(Se.sep).some(r=>t.includes(r)))}function ls(e,t){let n=0,s;try{s=yt.readdirSync(e,{withFileTypes:!0})}catch{return 0}for(let o of s)o.isDirectory()?Mn.includes(o.name)||(n+=ls(Se.join(e,o.name),t)):o.isFile()&&t.has(Se.extname(o.name))&&n++;return n}var Qi=e=>/\.d\.(ts|mts|cts)$/.test(e);function ec(e){let t=Se.basename(e);if(/\.min\.js$/.test(t))return{kind:"minified",reason:"minified (*.min.js)"};if(/\.bundle\.js$/.test(t))return{kind:"bundled",reason:"bundled (*.bundle.js)"};let n;try{n=yt.statSync(e).size}catch{return null}if(n>Xi)return{kind:"oversized",reason:`oversized (${(n/1048576).toFixed(1)} MB, limit 1 MB)`};if(n>Ln){let s=yt.readFileSync(e,"utf8"),o=0,r=0;for(;;){let i=s.indexOf(`
7
+ `,o),c=(i<0?s.length:i)-o;if(c>r&&(r=c),i<0)break;o=i+1}if(r>Ln)return{kind:"minified",reason:`line of ${r.toLocaleString("en-US")} characters (limit ${Ln.toLocaleString("en-US")}; minified/bundled)`}}return null}function bt(e,t=["javascript","typescript"]){let n=t.flatMap(h=>(h==="typescript"?os:Cn[h])||[]),s={excludedDirs:[]},o=Zi(Ki(e,s),[...as,...Mn],e),r=h=>Se.relative(e,h).split(Se.sep).join("/"),i=[],c=[],a={};for(let h of o){let u=Se.extname(h);if(n.includes(u)){if(Qi(h)){c.push({file:r(h),kind:"declaration",reason:"declaration file"});continue}let v=ec(h);v?c.push({file:r(h),kind:v.kind,reason:v.reason}):i.push(h)}else cs.includes(u)&&(a[u]=(a[u]??0)+1)}let l=new Set([...n,...cs]),f={};for(let h of s.excludedDirs){let u=Se.basename(h),v=f[u]??={dirs:0,files:0};v.dirs++,v.files+=ls(h,l)}return{files:i,skipped:c,unsupported:a,excludedDirs:f}}function Tn(e,t=["javascript","typescript"]){return bt(e,t).files}import tc from"node:path";var ot=e=>e.toLocaleString("en-US"),Ut=(e,t,n=t+"s")=>`${ot(e)} ${e===1?t:n}`,nc={".vue":"Vue",".svelte":"Svelte"},oc=[".vue",".svelte"],sc=new Set([".ts",".tsx",".mts",".cts"]);function fs({discovered:e,parseResults:t,scopeFiles:n,rel:s,rootService:o=null}){let r=(t.budgetSkips??[]).map(d=>({path:s(d.filePath),kind:"timeout",reason:d.reason})),i=new Set((t.budgetSkips??[]).map(d=>d.filePath)),c=[...e.skipped.map(d=>({path:d.file,kind:d.kind,reason:d.reason})),...r].sort((d,k)=>d.path<k.path?-1:d.path>k.path?1:0),a=e.files.filter(d=>!i.has(d)),l=a.filter(d=>t.get(d)?.hadErrors).map(s).sort(),f=a.flatMap(d=>(t.get(d)?.warnings??[]).map(k=>({path:s(d),extractor:k.extractor,message:k.message}))).sort((d,k)=>d.path<k.path?-1:d.path>k.path?1:0),h=a.filter(d=>sc.has(tc.extname(d))).length,u={};for(let d of oc)e.unsupported[d]&&(u[d]=e.unsupported[d]);let v={};for(let d of c)v[d.kind]=(v[d.kind]??0)+1;return{analyzed:a.length,analyzedJs:a.length-h,analyzedTs:h,inService:a.filter(d=>n.has(d)).length,notAnalyzed:u,notAnalyzedTotal:Object.values(u).reduce((d,k)=>d+k,0),skipped:c,skippedByKind:v,parseErrors:l.length,parseErrorFiles:l.slice(0,50),parseWarnings:f.length,parseWarningList:f.slice(0,50),excludedDirs:e.excludedDirs,rootService:o}}function Wt(e){let t=["Coverage"],n=[],s=new Map;for(let[c,a]of Object.entries(e.notAnalyzed)){let l=nc[c];s.has(l)||s.set(l,[]),s.get(l).push(`${ot(a)} ${c}`)}for(let[c,a]of s)n.push(`${a.join(", ")} files (${c} not supported yet)`);if(e.skipped.length){let c=Object.entries(e.skippedByKind).map(([a,l])=>`${a}: ${l}`).join(", ");n.push(`${ot(e.skipped.length)} skipped (${c})`)}e.parseErrors&&n.push(`${ot(e.parseErrors)} with parse errors`),e.parseWarnings&&n.push(`${ot(e.parseWarnings)} extractor warnings (a construct skipped; the rest of its file was analyzed)`);let o=e.analyzedTs?`${Ut(e.analyzedJs,"JS file")} and ${Ut(e.analyzedTs,"TS file")}`:Ut(e.analyzed,"JS file");t.push(` Analyzed ${o}, ${ot(e.inService)} of them inside a service${e.analyzed?` (${Math.round(100*e.inService/e.analyzed)}%)`:""}.`),t.push(` Not analyzed: ${n.length?n.join(", "):"nothing"}.`);let r=e.skipped.filter(c=>c.kind!=="declaration");for(let c of r.slice(0,5))t.push(` skipped ${c.path}: ${c.reason}`);r.length>5&&t.push(` ... and ${ot(r.length-5)} more (full list: meta.coverage.skipped)`);let i=Object.entries(e.excludedDirs);return i.length&&t.push(` Excluded directories: ${i.map(([c,a])=>`${c}/ x${a.dirs} (${Ut(a.files,"source file")})`).join(", ")}.`),e.rootService&&t.push(` Root service: ${e.rootService.reason}.`),t.join(`
8
+ `)}function qt(e,t){return`${e}::${t}`}var us=[{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 Gt(e){let t=e.toLowerCase().replace(/\\/g,"/");for(let{category:n,patterns:s}of us)for(let o of s)if(t.includes(o))return n;return"unknown"}import On from"node:fs";import ve from"node:path";import Jt from"node:fs";import ze from"node:path";var rc=["index.html","public/index.html","src/index.html"],ic=/^(build|esbuild|vite\.config|webpack\.config|rollup\.config|bundle)[\w.-]*\.(mjs|cjs|js|ts)$/i;function cc(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 ac(e){let t=[],n=[];try{n=Jt.readdirSync(e).filter(s=>ic.test(s)).sort()}catch{return t}for(let s of n){let o;try{o=Jt.readFileSync(ze.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 Yt(e,t,n=new Set(t.map(s=>ze.resolve(s)))){for(let s of rc){let o=ze.join(e,s);if(!Jt.existsSync(o))continue;let r;try{r=Jt.readFileSync(o,"utf8")}catch{continue}let i=ze.dirname(o),c=f=>{let h=f.split(/[?#]/)[0];return!h||/^([a-z]+:)?\/\//i.test(h)?null:ze.resolve(h.startsWith("/")?ze.join(e,h):ze.join(i,h))},a=cc(r).map(f=>({s:f,p:c(f)})).filter(f=>f.p);for(let{s:f,p:h}of a)if(n.has(h))return{indexHtml:o,script:f,entry:h,via:"script"};let l=ac(e);for(let{s:f,p:h}of a)for(let u of l){if(!u.outfile||ze.resolve(e,u.outfile)!==h)continue;let v=ze.resolve(e,u.entry);if(n.has(v))return{indexHtml:o,script:f,entry:v,via:`${u.config} (outfile ${u.outfile})`}}}return null}var lc=new Set(["test","tests","__tests__","fixtures","__fixtures__","__mocks__","e2e","cypress"]);function vt(e){let t=String(e).replace(/\\/g,"/").split("/").filter(Boolean);if(!t.length)return!1;for(let n of t.slice(0,-1))if(lc.has(n.toLowerCase()))return!0;return/\.(test|spec)\.[^./]+$/i.test(t[t.length-1])}function fc(e){let t=ve.join(e,"package.json");if(!On.existsSync(t))return null;try{return JSON.parse(On.readFileSync(t,"utf-8"))}catch{return null}}function uc(e){return[...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{})]}function dc(e){let t=!!e.workspaces,n=Object.keys(e.dependencies??{}).length>0,s=!!(e.scripts&&e.scripts.start);return t&&!n&&!s}var pc=["react","vue","svelte","next","vite","webpack","parcel"],mc=["express","fastify","koa","hapi","socket.io","ws"],hc=[{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 gc(e){let t=e.some(s=>pc.includes(s)),n=e.some(s=>mc.includes(s));return t&&!n?"client":n&&!t||n&&t?"server":"unknown"}function yc(e){let t=[];for(let{deps:n,label:s}of hc)n.some(o=>e.includes(o))&&!t.includes(s)&&t.push(s);return t}function ds(e){let t=new Set(["node_modules",".git","dist","build",".next","coverage"]);try{return On.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 ps(e,t=null){let n=[e];for(let o of ds(e)){n.push(o);for(let r of ds(o))n.push(r)}let s=[];for(let o of n){let r=fc(o);if(!r||dc(r))continue;let i=uc(r);s.push({name:r.name||ve.basename(o),rootPath:o,isRepoRoot:ve.resolve(o)===ve.resolve(e),kind:gc(i),datastores:yc(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))||vt(ve.relative(e,i)+"/x")||Yt(i,t,o)&&s.push({name:ve.basename(i),rootPath:i,isRepoRoot:!1,kind:"client",datastores:[],webRoot:!0})}return s}function st(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 vc=5,wc=.1;function ms(e,t,n){let s=ve.basename(ve.resolve(n)),o=a=>({name:a,rootPath:n,isRepoRoot:!0,ownsLeftovers:!0,kind:"unknown",datastores:[]});if(!t.length)return{services:e,added:null};if(!e.length)return{services:[o(s)],added:{name:s,reason:"no package.json found: the repo root is the one service",leftover:t.length}};let r=t.filter(a=>!st(a,e)).length;if(r<vc||r<wc*t.length)return{services:e,added:null,leftover:r};let i=e.find(a=>a.isRepoRoot);if(i)return i.ownsLeftovers=!0,{services:e,added:{name:i.name,reason:`${r} of ${t.length} files sit outside every nested package: owned by the root package ${i.name}`,leftover:r}};let c=s;return e.some(a=>a.name.toLowerCase()===c.toLowerCase())&&(c=`${s} (root)`),{services:[...e,o(c)],added:{name:c,reason:`${r} of ${t.length} files sit outside every nested package: owned by a service named after the repo folder`,leftover:r}}}function hs(e,t=[]){let n=[];for(let[s,o]of e){let r=Gt(s),i=st(s,t);n.push({id:`${s}::__module_root__`,name:"module root",filePath:s,startLine:0,endLine:Number.MAX_SAFE_INTEGER,category:r,serviceName:i,type:"moduleRoot",bodyHash:o.moduleBodyHash??null});for(let c of o.functions)n.push({id:qt(s,c.name),name:c.name,filePath:s,startLine:c.startLine,endLine:c.endLine,params:c.params,returns:c.returns,category:r,serviceName:i,bodyHash:c.bodyHash??null,type:"function"});for(let c of o.arrowFunctions)n.push({id:qt(s,c.name),name:c.name,filePath:s,startLine:c.startLine,endLine:c.endLine,params:c.params,returns:c.returns,category:r,serviceName:i,bodyHash:c.bodyHash??null,type:"arrowFunction"});for(let c of o.classMethods)n.push({id:qt(s,`${c.className}.${c.methodName}`),name:c.methodName,className:c.className,filePath:s,startLine:c.startLine,endLine:c.endLine,params:c.params,returns:c.returns,category:r,serviceName:i,bodyHash:c.bodyHash??null,type:"classMethod"})}return n}function Me(e,t){let n=[];for(let r of t.routes??[])r.isInlineHandler&&n.push({item:r,line:r.startLine,key:`route:${String(r.method).toUpperCase()} ${r.path}`});for(let r of t.listeners??[])r.isInlineHandler&&n.push({item:r,line:r.startLine,key:`listener:${r.targetName??"unknown"}.${r.eventName}`});for(let r of t.socketListeners??[])r.isInlineHandler&&n.push({item:r,line:r.startLine,key:`socket:${r.eventName}`});n.sort((r,i)=>r.line-i.line);let s=new Map,o=new Map;for(let{item:r,key:i}of n){let c=(s.get(i)??0)+1;s.set(i,c),o.set(r,`${e}::${i}${c>1?`#${c}`:""}`)}return o}function gs(e,t=[]){let n=[];for(let[s,o]of e){let r=Gt(s),i=st(s,t),c=t.find(l=>l.name===i),a=Me(s,o);for(let l of o.routes??[]){if(!l.isInlineHandler)continue;let f=`${l.method.toUpperCase()} ${l.path}`;n.push({id:a.get(l),name:`${f} (inline handler)`,filePath:s,startLine:l.handlerStartLine??l.startLine,endLine:l.handlerEndLine??l.startLine,category:r,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:l.handlerBodyHash??null,trigger:{type:"route",label:f,resolvedVia:"inline"}})}for(let l of o.listeners??[])l.isInlineHandler&&n.push({id:a.get(l),name:`${l.eventName} (inline handler)`,filePath:s,startLine:l.handlerStartLine??l.startLine,endLine:l.handlerEndLine??l.startLine,category:r,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:l.handlerBodyHash??null,trigger:{type:"listener",label:l.eventName,resolvedVia:"inline"}});if(c?.kind==="server")for(let l of o.socketListeners??[])l.isInlineHandler&&n.push({id:a.get(l),name:`${l.eventName} (inline handler)`,filePath:s,startLine:l.handlerStartLine??l.startLine,endLine:l.handlerEndLine??l.startLine,category:r,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:l.handlerBodyHash??null,trigger:{type:"socketListener",label:l.eventName,resolvedVia:"inline"}})}return n}import xc from"node:fs";import Sc from"node:crypto";var ys=e=>Sc.createHash("sha256").update(e).digest("hex");function vs(e,t){return e.map(n=>[t(n),ys(xc.readFileSync(n))]).sort((n,s)=>n[0]<s[0]?-1:n[0]>s[0]?1:0)}function Vt(e){return ys(e.map(([t,n])=>`${t}\0${n}`).join(`
9
+ `))}import An from"node:path";function Xt(e){let t=An.resolve(e),n=t.split(An.sep).join("/"),s=[[t.toLowerCase(),t.length,An.sep],[n.toLowerCase(),n.length,"/"]],o=Math.max(s[0][1],s[1][1])+1,r=i=>{if(typeof i!="string")return i;let c=i.length>o?i.slice(0,o).toLowerCase():i.toLowerCase();if(c===s[0][0]||c===s[1][0])return".";for(let[a,l,f]of s)if(c.startsWith(a+f)){let h=i.slice(l+1),u=h.indexOf("::");return(u<0?h:h.slice(0,u)).split("\\").join("/")+(u<0?"":h.slice(u))}return i};return{rel:r,repoRoot:n,replacer:(i,c)=>typeof c=="string"?r(c):c,json:(i,c)=>JSON.stringify(i,(a,l)=>typeof l=="string"?r(l):l,c),clone:i=>JSON.parse(JSON.stringify(i,(c,a)=>typeof a=="string"?r(a):a))}}function ws(e){let t=e.map((s,o)=>({e:s,i:o})).sort((s,o)=>String(s.e.fromNodeId).localeCompare(String(o.e.fromNodeId))||(s.e.line??0)-(o.e.line??0)||(s.e.column??0)-(o.e.column??0)||s.i-o.i),n=new Map;for(let{e:s}of t){let o=s.calleeNameRaw??s.eventName??s.url??"",r=`${s.fromNodeId??"\u2205"} | ${s.callKind??s.type} | ${o}`,i=(n.get(r)??0)+1;n.set(r,i),s.id=`${r} | #${i}`}return e}function xs(e){let t=new Map;for(let n of e)t.has(n.id)||t.set(n.id,[]),t.get(n.id).push(n);for(let[n,s]of t)s.length<2||(s.sort((o,r)=>o.startLine-r.startLine||o.endLine-r.endLine),s.forEach((o,r)=>{r>0&&(o.id=`${n}#${r+1}`)}));return e}function ie(e,t){let n=null;for(let s of t)s.type!=="moduleRoot"&&e>=s.startLine&&e<=s.endLine&&(!n||s.endLine-s.startLine<n.endLine-n.startLine)&&(n=s);return n||t.find(s=>s.type==="moduleRoot")}function Ss(e,t){let n=[];for(let[o,r]of e){let i=t.filter(c=>c.filePath===o);for(let c of r.calls){let a=ie(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,calleeNameRaw:c.calleeName,line:c.startLine,column:c.startColumn,branchPath:c.branchPath??[],firstArgText:c.firstArgText??null,deferred:c.deferred??!1,type:"call",callKind:c.callKind??"call",resolved:!1})}for(let c of r.methodCalls){let a=ie(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,calleeNameRaw:c.methodName,objectNameRaw:c.objectName,line:c.startLine,column:c.startColumn,branchPath:c.branchPath??[],firstArgText:c.firstArgText??null,deferred:c.deferred??!1,type:"methodCall",callKind:c.callKind??"methodCall",resolved:!1})}for(let c of r.returnEntries??[]){let a=ie(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,calleeNameRaw:c.label,line:c.startLine,column:c.startColumn,branchPath:c.branchPath??[],deferred:c.deferred??!1,type:"returnValue",resolved:!1})}for(let c of r.jsxElements){let a=ie(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,calleeNameRaw:c.calleeName,line:c.startLine,type:"call",callKind:"jsx",resolved:!1})}for(let c of r.callSites??[]){let a=ie(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,calleeNameRaw:c.calleeName,line:c.startLine,column:c.startColumn,branchPath:c.branchPath??[],firstArgText:c.firstArgText??null,deferred:c.deferred??!1,type:"callSite",callKind:c.callKind,chainHead:c.chainHead??null,chainHeadCalled:c.chainHeadCalled??!1,ctorName:c.ctorName??null,...c.thisProp?{thisProp:c.thisProp,thisMethod:c.thisMethod}:{},resolved:!1})}for(let c of r.socketEmits){let a=ie(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,eventName:c.eventName,line:c.startLine,type:"socketEmit",resolved:!1})}for(let c of r.rawSocketSends??[]){let a=ie(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,eventName:c.eventName,line:c.startLine,type:"rawSocketSend",resolved:!1})}for(let c of r.apiCalls){let a=ie(c.startLine,i);n.push({fromFileId:o,fromNodeId:a?.id??null,url:c.url,httpMethod:c.method,scope:c.scope,line:c.startLine,type:"apiCall",resolved:!1})}}let s=n.filter(o=>o.type==="apiCall").length;return n}function ae(e,t){let n=new Map;for(let s of t)s.filePath===e&&n.set(s.name,s.id);return n}function Nt(e,t,n,s,o=null){if(n.has(e.calleeNameRaw))return{...e,targetNodeId:n.get(e.calleeNameRaw),confidence:.95,matchType:"local",resolved:!0};let r=[...s],i=s.legacySize??r.length,c=([,l])=>{let f=o?o.scopeOf(l):ae(l,t);return f.has(e.calleeNameRaw)?{...e,targetNodeId:f.get(e.calleeNameRaw),confidence:.85,matchType:"import",resolved:!0}:null};for(let l=0;l<i;l++){let f=c(r[l]);if(f)return f}let a=o?.bind?.resolveName(e.fromFileId,e.calleeNameRaw);if(a)return{...e,targetNodeId:a.id,confidence:.85,matchType:"import",resolved:!0};for(let l=i;l<r.length;l++){let f=c(r[l]);if(f)return f}return{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function ks(e,t,n=null){let s=n?n.method(e.objectNameRaw,e.calleeNameRaw):t.find(r=>r.type==="classMethod"&&r.className===e.objectNameRaw&&r.name===e.calleeNameRaw);if(s)return{...e,targetNodeId:s.id,confidence:.6,matchType:"methodHeuristic",resolved:!0};let o=n?.bind?.resolveMember(e.fromFileId,e.objectNameRaw,e.calleeNameRaw);return o?{...e,targetNodeId:o.id,confidence:.85,matchType:"import",resolved:!0}:{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function $s(e){return{...e,targetNodeId:null,confidence:0,matchType:"unresolvedExternal",resolved:!1}}function bs(e,t,n,s,o=null){if(e.callKind==="new"&&e.ctorName){let r=Nt({...e,calleeNameRaw:e.ctorName},t,n,s,o);if(r.resolved)return{...r,calleeNameRaw:e.calleeNameRaw,matchType:r.matchType+"New"};let i=new Set([e.fromFileId,...s.values()]),c=o?o.ctorsOf(e.ctorName).find(a=>i.has(a.filePath)):t.find(a=>a.type==="classMethod"&&a.className===e.ctorName&&a.name==="constructor"&&i.has(a.filePath));return c?{...e,targetNodeId:c.id,confidence:c.filePath===e.fromFileId?.9:.8,matchType:(c.filePath===e.fromFileId?"local":"import")+"New",resolved:!0}:$s(e)}if(e.callKind==="chainedCall"&&e.chainHead&&e.chainHeadCalled){let r=Nt({...e,calleeNameRaw:e.chainHead},t,n,s,o);if(r.resolved)return{...e,targetNodeId:r.targetNodeId,confidence:r.confidence*.8,matchType:"chainHead",resolved:!0}}return $s(e)}import Bn from"node:path";import Ue from"node:fs";import G from"node:path";var Es=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],kc=["index.ts","index.tsx","index.mts","index.cts","index.js","index.jsx","index.mjs","index.cjs"],$c={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]};var Rs=null,_s=e=>{Rs=e},Cs=()=>Rs,Ns=e=>G.resolve(e);function It(e,t){e=G.resolve(e);let n=()=>{try{let i=G.join(e,"package.json");if(!Ue.existsSync(i))return null;let c=JSON.parse(Ue.readFileSync(i,"utf8")).main;if(typeof c!="string")return null;let a=G.resolve(e,c);return t.has(a)?a:bc(a,t)}catch{return null}},s=G.extname(e);if(s&&t.has(e))return e;let o=$c[s];if(o)for(let i of o){let c=e.slice(0,-s.length)+i;if(t.has(c))return c}for(let i of Es)if(t.has(e+i))return e+i;let r=n();if(r)return r;for(let i of kc){let c=G.join(e,i);if(t.has(c))return c}return null}function bc(e,t){if(G.extname(e)&&t.has(e))return e;for(let s of Es)if(t.has(e+s))return e+s;return null}var Fn=e=>{try{let n=Ue.readFileSync(e,"utf8").replace(/^/,"").replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,(s,o)=>o??"");return JSON.parse(n.replace(/,(\s*[}\]])/g,"$1"))}catch{return null}};function Ls(e,t=new Set){if(t.has(e))return{baseUrl:null,paths:null};t.add(e);let n=Fn(e);if(!n)return{baseUrl:null,paths:null};let s=null,o=null,r=n.extends?Array.isArray(n.extends)?n.extends:[n.extends]:[];for(let c of r){if(typeof c!="string"||!c.startsWith("."))continue;let a=G.resolve(G.dirname(e),c);(!Ue.existsSync(a)||Ue.statSync(a).isDirectory())&&(a=Ue.existsSync(a+".json")?a+".json":G.join(a,"tsconfig.json"));let l=Ls(a,t);l.baseUrl&&(s=l.baseUrl),l.paths&&(o=l.paths)}let i=n.compilerOptions??{};if(typeof i.baseUrl=="string"&&(s=G.resolve(G.dirname(e),i.baseUrl)),i.paths&&typeof i.paths=="object"){let c=s??G.dirname(e);o=Object.entries(i.paths).map(([a,l])=>{let f=a.indexOf("*");return{prefix:f<0?a:a.slice(0,f),suffix:f<0?"":a.slice(f+1),wildcard:f>=0,targets:(Array.isArray(l)?l:[]).filter(h=>typeof h=="string").map(h=>G.resolve(c,h))}}).sort((a,l)=>l.prefix.length-a.prefix.length)}return{baseUrl:s,paths:o}}function Nc(e,t){if(t=t.replace(/^\.\//,"").replace(/\/+$/,""),t.startsWith("!"))return[];let n=[],s=o=>{try{return Ue.readdirSync(o,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="node_modules"&&!r.name.startsWith(".")).map(r=>G.join(o,r.name))}catch{return[]}};if(t.endsWith("/**")){let o=G.join(e,t.slice(0,-3)),r=i=>{for(let c of s(i))n.push(c),r(c)};r(o)}else t.endsWith("/*")?n.push(...s(G.join(e,t.slice(0,-2)))):t.includes("*")||n.push(G.join(e,t));return n}function Ic(e){let t=[],s=Fn(G.join(e,"package.json"))?.workspaces;Array.isArray(s)?t.push(...s):Array.isArray(s?.packages)&&t.push(...s.packages);try{let o=Ue.readFileSync(G.join(e,"pnpm-workspace.yaml"),"utf8"),r=!1;for(let i of o.split(/\r?\n/)){if(/^packages\s*:/.test(i)){r=!0;continue}if(r){let c=/^\s*-\s*['"]?([^'"#\s]+)['"]?/.exec(i);c?t.push(c[1]):/^\S/.test(i)&&(r=!1)}}}catch{}return t}function Is(e,t){if(e==null)return null;let n=o=>{if(typeof o=="string")return o;if(Array.isArray(o)){for(let r of o){let i=n(r);if(i)return i}return null}if(o&&typeof o=="object"){for(let r of["source","import","module","default","require","node"])if(r in o){let i=n(o[r]);if(i)return i}}return null};if(typeof e=="string"||Array.isArray(e))return t==="."?n(e):null;let s=Object.keys(e);if(!s.some(o=>o.startsWith(".")))return t==="."?n(e):null;if(e[t]!=null)return n(e[t]);for(let o of s){let r=o.indexOf("*");if(r>0&&t.startsWith(o.slice(0,r))&&t.endsWith(o.slice(r+1))){let i=n(e[o]);if(i)return i.replace("*",t.slice(r,t.length-(o.length-r-1)))}}return null}function Ps(e,t,n={}){let s=Ns(e),o=new Set(t),r=new Map,i=u=>{if(r.has(u))return r.get(u);let v=null,d=G.join(u,"tsconfig.json");return Ue.existsSync(d)?v=Ls(d):u!==s&&G.dirname(u)!==u&&u.startsWith(s)&&(v=i(G.dirname(u))),r.set(u,v),v},c=new Map;for(let u of Ic(s))for(let v of Nc(s,u)){let d=Fn(G.join(v,"package.json"));d?.name&&!c.has(d.name)&&c.set(d.name,{dir:Ns(v),pkg:d})}let a=[...c.keys()].sort((u,v)=>v.length-u.length),l=(u,v,d)=>{let{dir:k,pkg:j}=c.get(u),p=[],S=$=>{if(!$)return;let w=G.resolve(k,$);p.push(w);let y=G.relative(k,w).split(G.sep);["dist","build","lib","out","esm","cjs"].includes(y[0])&&p.push(G.join(k,"src",...y.slice(1)))};if(v==="."){S(Is(j.exports,"."));for(let $ of["source","module","main"])typeof j[$]=="string"&&S(j[$]);p.push(G.join(k,"src","index"),G.join(k,"index"))}else S(Is(j.exports,v)),p.push(G.join(k,v),G.join(k,"src",v));for(let $ of p){let w=It($,d);if(w)return w}return null},f=u=>a.find(v=>u===v||u.startsWith(v+"/"))??null,h=(u,v)=>v?.paths?.some(d=>d.wildcard?u.startsWith(d.prefix)&&u.endsWith(d.suffix)&&u.length>=d.prefix.length+d.suffix.length:u===d.prefix)??!1;return{root:s,files:o,packages:c,isInternal(u,v){if(u.startsWith(".")||f(u))return!0;let d=i(G.dirname(v));return!!(h(u,d)||d?.baseUrl&&!u.startsWith("@")&&It(G.join(d.baseUrl,u),o))},resolve(u,v,d){if(u.startsWith("."))return It(G.resolve(G.dirname(v),u),d);let k=i(G.dirname(v));if(k?.paths&&n.paths!==!1)for(let p of k.paths){let S=null;if(p.wildcard?u.startsWith(p.prefix)&&u.endsWith(p.suffix)&&u.length>=p.prefix.length+p.suffix.length&&(S=u.slice(p.prefix.length,u.length-p.suffix.length)):u===p.prefix&&(S=""),S!=null){for(let $ of p.targets){let w=It($.replace("*",S),d);if(w)return w}break}}let j=n.workspaces===!1?null:f(u);if(j){let p=l(j,u===j?".":"./"+u.slice(j.length+1),d);if(p)return p}if(k?.baseUrl&&n.paths!==!1){let p=It(G.join(k.baseUrl,u),d);if(p)return p}return null}}}var js=new WeakMap;function Ms(e){if(e instanceof Set)return e;let t=js.get(e);return t||js.set(e,t=new Set(e)),t}var Ts=new WeakMap;function jc(e){let t=Ts.get(e);return(!t||t.n!==e.length)&&(t={n:e.length,set:new Set(e)},Ts.set(e,t)),t.set}function Dn(e,t,n){if(!e.startsWith("."))return null;let s=Bn.dirname(t),o=Bn.resolve(s,e),r=[o,...ss().map(i=>`${o}${i}`),...rs().map(i=>Bn.join(o,i))];for(let i of r)if(jc(n).has(i))return i;return null}function me(e,t,n){let s=Dn(e,t,n);if(s)return s;let o=Cs();return o?o.resolve(e,t,Ms(n)):null}function wt(e,t,n){let s=new Map;for(let o of t){let r=Dn(o.source,e,n);r&&s.set(o.source,r)}s.legacySize=s.size;for(let o of t){if(s.has(o.source))continue;let r=me(o.source,e,n);r&&s.set(o.source,r)}return s}function Os(e){let t=new Map,n=new Map,s=new Map;for(let o of e){if(o.type!=="classMethod")continue;let r=o.className+"\0"+o.name;n.has(r)||n.set(r,o),o.name==="constructor"&&(s.has(o.className)||s.set(o.className,[]),s.get(o.className).push(o))}return{scopeOf:o=>{let r=t.get(o);return r||(r=ae(o,e),t.set(o,r)),r},method:(o,r)=>n.get(o+"\0"+r),ctorsOf:o=>s.get(o)??[]}}function xt(e){return e?e.split("?")[0].split("/").map(t=>t.startsWith(":")||/^\d+$/.test(t)?"*":t).join("/"):""}var Ec=new Set(["function","arrowFunction"]);function As(e,t,n,s){let o=new Map;for(let l of t){let f=o.get(l.filePath);f||o.set(l.filePath,f=[]),f.push(l)}let r=new Set;for(let l of s)l.resolved&&l.fromNodeId&&l.targetNodeId&&r.add(l.fromNodeId+"\0"+l.targetNodeId);let i=(l,f)=>(o.get(l)??[]).find(h=>Ec.has(h.type)&&f(h))??null,c=[];c.argBindings=[];let a=(l,f,h,u,v,d,k)=>{!f||!h||f.id===h.id||r.has(f.id+"\0"+h.id)||c.push({fromFileId:l,fromNodeId:f.id,calleeNameRaw:u,line:v,column:d,branchPath:[],firstArgText:null,deferred:!1,type:"reference",callKind:"reference",targetNodeId:h.id,confidence:k==="local"?.95:.85,matchType:k,resolved:!0})};for(let[l,f]of e){let h=o.get(l);if(h){for(let u of f.refArgs??[]){let v=null,d="local";if(u.b==="fn"?v=i(l,j=>j.name===u.name&&j.startLine===u.declLine):u.b==="import"&&(d="import",(u.ik==="default"||u.ik==="named"||u.ik==="cjs")&&(v=n.nodeForImport(l,u.src,u.ik,u.imp))),!v)continue;let k=ie(u.line,h);a(l,k,v,u.name,u.line,u.column,d),u.callLine!=null&&k&&k.id!==v.id&&c.argBindings.push({file:l,line:u.callLine,column:u.callColumn,targetNodeId:v.id,matchType:d,direct:u.via==="arg"})}for(let u of h){if(u.type!=="inlineHandler")continue;let v=null;for(let d of h)d===u||d.type==="moduleRoot"||d.startLine<=u.startLine&&d.endLine>=u.endLine&&!(d.startLine===u.startLine&&d.endLine===u.endLine)&&(!v||d.endLine-d.startLine<v.endLine-v.startLine)&&(v=d);v??=h.find(d=>d.type==="moduleRoot"),a(l,v,u,u.name,u.startLine,0,"local")}}}return c}function Fs(e,t,n,s){let o=new Map,r=new Map;for(let c of e){if(r.set(c.id,c),c.type!=="classMethod")continue;let a=c.filePath+"\0"+c.className+"\0"+c.name,l=o.get(a);l?l.push(c):o.set(a,[c])}let i=(c,a)=>{for(let l of o.keys())if(l.startsWith(c+"\0"+a+"\0"))return!0;return!1};return function(a){let l=r.get(a.fromNodeId);if(!l||l.type!=="classMethod")return null;let f=t.get(a.fromFileId),h=(f?.classProps??[]).find(j=>j.className===l.className&&j.prop===a.thisProp);if(!h)return null;let u=null,v=null,d=(f.importBindings??[]).find(j=>j.local===h.type);if(d){let j=d.kind==="default"||d.kind==="named"?s.resolveImport(a.fromFileId,d.source,d.kind,d.imported):null;j?.local&&j.local!=="default"&&(u=j.file,v=j.local)}else i(a.fromFileId,h.type)&&(u=a.fromFileId,v=h.type);if(!u)return null;let k=o.get(u+"\0"+v+"\0"+a.thisMethod);return!k||k.length!==1?null:{...a,targetNodeId:k[0].id,confidence:.9,matchType:"typedProperty",resolved:!0}}}var Rc=new Set(["function","arrowFunction"]);function Kt(e,t,n){let s=new Map;for(let f of e){if(!Rc.has(f.type))continue;let h=f.filePath+"\0"+f.name;s.has(h)||s.set(h,f)}let o=new Map,r=(f,h)=>{let u=o.get(f);if(!u){u=new Map;for(let v of t.get(f)?.importBindings??[])u.has(v.local)||u.set(v.local,v);o.set(f,u)}return u.get(h)??null},i=(f,h)=>n(f).get(h)??null;function c(f,h,u=new Set){let v=f+"\0"+h;if(u.has(v))return null;u.add(v);let d=t.get(f)?.exportBindings;if(!d)return null;if(h==="default"){if(d.default)return{file:f,local:d.default==="<anon>"?"default":d.default}}else if(d.named?.[h])return{file:f,local:d.named[h]};for(let k of d.reexports??[]){if(k.exported!==h)continue;let j=i(f,k.source);if(j)return c(j,k.imported,u)}for(let k of d.nsReexports??[]){if(k.exported!==h)continue;let j=i(f,k.source);if(j)return{moduleFile:j}}if(h!=="default")for(let k of d.stars??[]){let j=i(f,k),p=j?c(j,h,u):null;if(p)return p}return null}let a=f=>f?.local?s.get(f.file+"\0"+f.local)??null:null;function l(f,h,u,v){let d=i(f,h);return d?u==="default"?c(d,"default"):u==="named"?c(d,v):{moduleFile:d,cjs:u==="cjs"}:null}return{lookupExport:c,resolveImport:l,nodeForImport(f,h,u,v){let d=l(f,h,u,v);return d?.moduleFile&&d.cjs?a(c(d.moduleFile,"default")):a(d)},resolveName(f,h){let u=r(f,h);return u?this.nodeForImport(f,u.source,u.kind,u.imported):null},resolveMember(f,h,u){let v=r(f,h);if(!v)return null;let d=l(f,v.source,v.kind,v.imported);return d?.moduleFile?a(c(d.moduleFile,u)):null},classForImport(f,h){let u=r(f,h);if(!u)return null;let v=l(f,u.source,u.kind,u.imported);return v?.local?{file:v.file,className:v.local==="default"?null:v.local}:null},bindingFor:r}}function Bs(e,t,n,s,o,r,i){let c=[],a=Os(t),l=new Map,f=p=>l.get(p)??wt(p,n.get(p)?.imports??[],s);a.bind=Kt(t,n,f);let h=Fs(t,n,f,a.bind),u=new Map;for(let p of e)u.has(p.fromFileId)||u.set(p.fromFileId,[]),u.get(p.fromFileId).push(p);for(let[p,S]of u){let $=n.get(p),w=ae(p,t),y=wt(p,$.imports,s);l.set(p,y);for(let m of S)if(m.type==="call")c.push(Nt(m,t,w,y,a));else if(m.type==="methodCall")c.push(ks(m,t,a));else if(m.type==="callSite")c.push((m.thisProp?h(m):null)??bs(m,t,w,y,a));else if(m.type==="returnValue")c.push({...m,targetNodeId:null,confidence:0,matchType:"returnValue",resolved:!1});else if(m.type==="apiCall")if(m.scope==="external")c.push({...m,targetNodeId:null,confidence:null,matchType:"externalService",resolved:!1});else{let b=xt(m.url),g=o.get(b);g?c.push({...m,targetNodeId:g,confidence:.5,matchType:"crossLayer",resolved:!0}):c.push({...m,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(m.type==="socketEmit"){let b=r.get(m.eventName);b?c.push({...m,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):c.push({...m,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(m.type==="rawSocketSend"){let b=i?.get(m.eventName);b?c.push({...m,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):c.push({...m,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}}let v=As(n,t,a.bind,c);for(let p of v)c.push(p);let d=new Map;for(let p of c){if(p.resolved||p.line==null||p.type!=="call"&&p.type!=="methodCall"&&p.type!=="callSite")continue;let S=p.fromFileId+" "+p.line+" "+p.column;(d.get(S)??d.set(S,[]).get(S)).push(p)}let k=[...v.argBindings].sort((p,S)=>S.direct-p.direct),j=new Set;for(let p of k){let S=p.file+" "+p.line+" "+p.column;if(j.has(S))continue;let $=(d.get(S)??[]).find(w=>w.fromNodeId!==p.targetNodeId);$&&(j.add(S),Object.assign($,{targetNodeId:p.targetNodeId,confidence:p.matchType==="local"?.95:.85,matchType:"argument",resolved:!0,viaArgument:!0}))}return c}function Ds(e){let t=new Map,n=new WeakMap,s=a=>{if(typeof a=="string")return a.length>=20?"s"+a:null;if(a&&typeof a=="object"){let l=n.get(a);if(l===void 0){let f=JSON.stringify(a);l=f.length>=40?"j"+f:"",n.set(a,l)}return l||null}return null};(function a(l){let f=s(l);if(f){let h=t.get(f)??0;if(t.set(f,h+1),h>0)return}if(Array.isArray(l))for(let h of l)a(h);else if(l&&typeof l=="object")for(let h of Object.values(l))a(h)})(e);let o=[],r=new Map,i=a=>{let l=s(a),f=l&&t.get(l)>1;if(f&&r.has(l))return r.get(l);let h;if(typeof a=="string"?h=JSON.stringify(a):Array.isArray(a)?h="["+a.map(i).join(",")+"]":a&&typeof a=="object"?h="{"+Object.entries(a).map(([v,d])=>JSON.stringify(v)+":"+i(d)).join(",")+"}":h=JSON.stringify(a),!f)return h;let u="$"+o.length.toString(36);return o.push(`const ${u}=${h};`),r.set(l,u),u},c=i(e);return`(() => {${o.join(`
19
10
  `)}
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(`
11
+ return ${c};})()`}function Hn(e,t,n,s){if(!e)return{targetId:null,via:null};if(n.has(e))return{targetId:n.get(e),via:"in-file"};if(s)for(let[,o]of s){let r=ae(o,t);if(r.has(e))return{targetId:r.get(e),via:"cross-file"}}return{targetId:null,via:null}}function Hs(e,t,n,s,o,r=[],i=null){if(!n.some(a=>!a.isInlineHandler)&&!s.some(a=>!a.isInlineHandler)&&!r.some(a=>!a.isInlineHandler))return e;let c=e.map(a=>({...a}));for(let a of n){if(a.isInlineHandler)continue;let l=a.nest?e.find(u=>u.type==="classMethod"&&u.filePath===t&&u.className===a.nest.className&&u.name===a.nest.methodName):null,{targetId:f,via:h}=a.nest?{targetId:l?.id??null,via:"in-file"}:Hn(a.handlerName,e,o,i);if(f){let u=c.find(v=>v.id===f);u&&(u.isEntryPoint=!0,u.trigger={type:"route",label:`${a.method.toUpperCase()} ${a.path}`,resolvedVia:h})}}for(let a of s){if(a.isInlineHandler)continue;let{targetId:l,via:f}=Hn(a.handlerName,e,o,i);if(l){let h=c.find(u=>u.id===l);h&&(h.isEntryPoint=!0,h.trigger={type:"listener",label:a.eventName,resolvedVia:f})}}for(let a of r){if(a.isInlineHandler)continue;let{targetId:l,via:f}=Hn(a.handlerName,e,o,i);if(l){let h=c.find(u=>u.id===l);h&&(h.isEntryPoint=!0,h.trigger={type:"socketListener",label:a.eventName,resolvedVia:f})}}return c}function zn(e){let t=new Map,n=new Map;for(let s of e)s.resolved&&(t.set(s.fromNodeId,(t.get(s.fromNodeId)??0)+1),n.set(s.targetNodeId,(n.get(s.targetNodeId)??0)+1));return{outgoing:t,incoming:n}}function zs(e,t,n=zn(t)){if(e.type==="moduleRoot")return 0;let s=n.outgoing.get(e.id)??0,o=n.incoming.get(e.id)??0,r=e.exported?1.5:1;return s/(o+1)*r}function Us(e,t){let n=zn(t),s=new Set;for(let i of e)n.incoming.has(i.id)&&s.add(i.filePath);let r=e.filter(i=>!(i.isEntryPoint||i.type==="moduleRoot"||!n.incoming.has(i.id)&&s.has(i.filePath))).map(i=>({...i,fallbackScore:zs(i,t,n)}));return r.sort((i,c)=>c.fallbackScore-i.fallbackScore),r.slice(0,15)}function Un(e){let t=new Map;for(let n of e)!n.resolved||!n.fromNodeId||!n.targetNodeId||(t.has(n.fromNodeId)||t.set(n.fromNodeId,[]),t.get(n.fromNodeId).push({targetNodeId:n.targetNodeId,line:n.line??null,column:n.column??null,branchPath:n.branchPath??[],edgeType:n.type}));return t}function Wn(e,t,n,s=8){let o=new Set([e]),r=a=>n.find(l=>l.id===a)?.category??"unknown",i=[{nodeId:e,depth:0,parentNodeId:null,category:r(e)}],c=[{nodeId:e,depth:0}];for(;c.length>0;){let a=c.shift();if(a.depth>=s)continue;let l=t.get(a.nodeId)||[];for(let f of l){let h=f.targetNodeId;if(o.has(h))continue;o.add(h);let u={nodeId:h,depth:a.depth+1,parentNodeId:a.nodeId,category:r(h),callLine:f.line,callColumn:f.column,branchPath:f.branchPath,edgeType:f.edgeType};i.push(u),c.push(u)}}return i}function Ws(e,t,n,s=null){return t.filter(r=>r.filePath===e.filePath&&r.id!==e.id&&r.type!=="moduleRoot").filter(r=>!(s?s.has(r.id):n.some(c=>c.resolved&&c.targetNodeId===r.id)))}var qs=new WeakMap,Gs=new WeakMap;function _c(e){let t=qs.get(e);if(t&&t.length===e.length)return t;let n=new Set,s=new Set,o=new Map;for(let r of e)r.resolved&&(r.targetNodeId===void 0||r.targetNodeId===null||(s.add(r.targetNodeId),r.matchType==="crossLayer"&&n.add(r.targetNodeId)),o.set(r.fromNodeId,(o.get(r.fromNodeId)??0)+1));return t={length:e.length,crossLayerTargets:n,incoming:s,outgoing:o},qs.set(e,t),t}function Cc(e,t,n){let s=Gs.get(e);if(s&&s.length===e.length&&s.edgesRef===n)return s.calledByFile;let o=new Map;for(let r of e){if(r.type==="moduleRoot"||!n.incoming.has(r.id))continue;let i=o.get(r.filePath);i||o.set(r.filePath,i=new Set),i.add(r.id)}return Gs.set(e,{length:e.length,edgesRef:n,calledByFile:o}),o}function Js(e,t,n){if(e.type==="moduleRoot")return!1;let s=_c(t);if(s.crossLayerTargets.has(e.id)||(s.outgoing.get(e.id)??0)>=4||new Set((e.returns||[]).map(a=>a.condition).filter(a=>a!==null)).size>=3)return!0;if(s.incoming.has(e.id)){let a=Cc(n,t,s).get(e.filePath);if(!(!!a&&a.size-(a.has(e.id)?1:0)>0)){let f=Ws(e,n,t,s.incoming);if(f.length>0)return e.lexicalSiblings=f.map(h=>h.id),!0}}return!1}function Ys(e,t,n,s,o=8,r=null){let i=[],c=new Set(e.map(f=>f.id)),a=[...e],l=new Map;for(let f of n)l.has(f.id)||l.set(f.id,f);for(;a.length>0;){let f=a.shift(),h=Wn(f.id,t,n,o);i.push({entryPointId:f.id,entryPointName:f.name,trigger:f.trigger??null,steps:h});let u=r?new Set(Wn(f.id,r,n,o).map(v=>v.nodeId)):null;for(let v of h){if(u&&!u.has(v.nodeId)||v.nodeId===f.id||c.has(v.nodeId))continue;let d=l.get(v.nodeId);d&&Js(d,s,n)&&(c.add(d.id),v.hasOwnSubTrace=!0,d.lexicalSiblings&&(v.lexicalSiblings=d.lexicalSiblings),a.push({id:d.id,name:d.name,trigger:null}))}}return i}function Vs(e,t,n=is){return e.filter((s,o)=>{if(o===0)return!0;let r=t.find(i=>i.id===s.nodeId);return r?!n.some(i=>r.name.toLowerCase().includes(i)):!0})}function Xs(e){return e.steps.filter(n=>n.depth>0).map(n=>n.nodeId).sort().join(" | ")}function Ks(e){let t=new Map;for(let n of e){let s=Xs(n),o=s===""?`__no_calls__${n.entryPointName}`:s;t.has(o)||t.set(o,[]),t.get(o).push(n)}return t}function Zs(e){let t=e[0];return{steps:t.steps,entryPointNames:e.map(n=>n.entryPointName),occurrences:e.length,name:t.entryPointName,trigger:t.trigger,tier:e.some(n=>n.origin==="physical")?"physical":"guessed",tierOrigin:e.some(n=>n.origin==="physical")?"physical":t.origin}}import Zt from"node:path";function Qs(e){if(!e.trigger)return null;if(e.trigger.type==="route")return`${e.trigger.label.split(" ")[1].split("/").filter(Boolean).join(" ").replace(/[-_]/g," ").split(" ").map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")} Flow`;if(e.trigger.type==="listener"){let t=e.trigger.label;return`${t.charAt(0).toUpperCase()+t.slice(1)} Flow`}return null}function er(e){return e.name.replace(/([A-Z])/g," $1").trim().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}var tr=60,Lc=24;function nr(e,t=null){let n=e.map(s=>{let o=Qs(s),r=s.trigger?.workflowName??o??er(s);return{...s,name:r}});return t?.nodes?Oc(n,t.nodes):n}var qn=(e,t)=>e.length>t?e.slice(0,t-1)+"\u2026":e,Pc=new Set(["function","arrowFunction","classMethod"]);function Mc(e){let t=new Map(e.map(o=>[o.id,o])),n=new Map,s=o=>{let r=n.get(o);return r||(r=e.filter(i=>i.filePath===o&&Pc.has(i.type)),n.set(o,r)),r};return o=>{let r=t.get(o.steps[0].nodeId);if(!r)return[null,null,null];let i=null;if(r.type==="classMethod")i=r.className;else{let l=null;for(let f of s(r.filePath))f===r||!(f.startLine<=r.startLine&&f.endLine>=r.endLine)||f.startLine===r.startLine&&f.endLine===r.endLine||(!l||f.endLine-f.startLine<l.endLine-l.startLine)&&(l=f);l&&(i=l.type==="classMethod"?l.className:l.name)}let c=null;if(o.trigger?.type==="route")c=String(o.trigger.label).split(" ")[0];else if(o.trigger?.type==="listener"){let l=/::listener:([^.#]+)\./.exec(r.id);l&&(c=l[1])}let a=Zt.basename(r.filePath,Zt.extname(r.filePath));return a==="index"&&(a=Zt.basename(Zt.dirname(r.filePath))),[i||null,c||null,a||null]}}var Tc=(e,t)=>{let n=t.map(s=>qn(s,Lc)).join(", ");return e.endsWith(")")?e.slice(0,-1)+", "+n+")":e+" ("+n+")"};function Oc(e,t){let n=Mc(t),s=e.map(i=>({w:i,base:i.name,parts:[],used:new Set,stuck:!1,q:null})),o=i=>i.parts.length?Tc(i.base,i.parts):i.base,r=()=>{let i=new Map;for(let c of s){let a=o(c);(i.get(a)??i.set(a,[]).get(a)).push(c)}return[...i.values()].filter(c=>c.length>1)};for(let i=0;i<4;i++){let c=!1;for(let a of r()){if(a.some(u=>u.stuck))continue;for(let u of a)u.q??=n(u.w);let l=[0,1,2].filter(u=>a.every(v=>!v.used.has(u))),f=l.find(u=>new Set(a.map(v=>v.q[u]??"")).size>1),h=f!==void 0;if(h||(f=l.find(u=>a.every(v=>v.q[u]))),f===void 0){for(let u of a)u.stuck=!0;continue}for(let u of a)u.used.add(f),u.q[f]&&u.parts.push(u.q[f]),h||(u.stuck=!0);c=!0}if(!c)break}for(let i of r())i.sort((c,a)=>c.w.steps[0].nodeId<a.w.steps[0].nodeId?-1:c.w.steps[0].nodeId>a.w.steps[0].nodeId?1:0),i.forEach((c,a)=>{a>0&&(c.suffix=` (${a+1})`)});return s.map(i=>{let c=o(i);return i.suffix&&(c=qn(c,tr-i.suffix.length)+i.suffix),{...i.w,name:qn(c,tr)}})}var Ac=e=>e;function or(e,t){let n=new Map;for(let[s,o]of e){let r=t.filter(l=>l.filePath===s);if(r[0]?.category!=="backend")continue;let i=o.routes??[],c=Me(s,o),a=ae(s,t);for(let l of i){let f=xt(l.path);if(l.isInlineHandler){let u=c.get(l);n.set(f,u);continue}if(l.nest){let u=Ac(r).find(v=>v.type==="classMethod"&&v.className===l.nest.className&&v.name===l.nest.methodName);u&&n.set(f,u.id);continue}if(!l.handlerName||!a.has(l.handlerName))continue;let h=a.get(l.handlerName);n.set(f,h)}}return n}import rt from"node:fs";import Q from"node:path";var Qt=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Fc=/(^|\/)(dist|build|out|built|compiled|esm|cjs|lib|output)(\/|$)/,sr=/(^|\/)(dist|build|out|built|compiled|esm|cjs|output)(\/|$)/,Bc=/\b(esbuild|tsup|tsdown|tsc|rollup|webpack|ncc|swc|babel|vite|parcel|bun\s+build|pkg|unbuild|microbundle|rspack)\b/,Dc=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild|rspack)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Te=e=>{try{return rt.statSync(e).isFile()}catch{return!1}},Gn=e=>e.split(Q.sep).join("/"),Jn=e=>{if(Te(e)&&Qt.includes(Q.extname(e))&&!/\.d\.ts$/.test(e))return e;let t=e.replace(/\.(m|c)?js$/,"");for(let n of Qt)if(Te(t+n)&&!/\.d\.ts$/.test(t+n))return t+n;return null},en=(e,t)=>{let n=Q.relative(e,t);return n&&!n.startsWith("..")&&!Q.isAbsolute(n)&&!/(^|[\\/])node_modules([\\/]|$)/.test(n)};function Hc(e,t){let n=Te(t+".map")?t+".map":null;if(!n&&Te(t))try{let c=rt.readFileSync(t,"utf8").slice(-400),a=/sourceMappingURL=([^\s*]+)/.exec(c);if(a&&!a[1].startsWith("data:")){let l=Q.resolve(Q.dirname(t),a[1]);Te(l)&&(n=l)}}catch{}if(!n)return null;let s;try{s=JSON.parse(rt.readFileSync(n,"utf8"))}catch{return null}let o=Q.resolve(Q.dirname(n),s.sourceRoot??""),r=(s.sources??[]).map(c=>Q.resolve(o,c)).filter(c=>en(e,c)&&Te(c)&&Qt.includes(Q.extname(c)));if(r.length===1)return r[0];let i=Q.basename(t).replace(/\.(m|c)?js$/,"");return r.find(c=>Q.basename(c).replace(/\.[^.]+$/,"")===i)??null}function zc(e){try{return JSON.parse(rt.readFileSync(e,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,"").replace(/,(\s*[}\]])/g,"$1"))}catch{return null}}function Uc(e,t){for(let n of["tsconfig.build.json","tsconfig.json"]){let o=zc(Q.join(e,n))?.compilerOptions;if(!o?.outDir)continue;let r=Gn(Q.normalize(o.outDir)).replace(/^\.\//,"").replace(/\/$/,"");if(!(t===r||t.startsWith(r+"/")))continue;let i=t.slice(r.length+1),c=o.rootDir?o.rootDir:rt.existsSync(Q.join(e,"src"))?"src":".",a=Jn(Q.resolve(e,c,i));if(a)return a}return null}function Wc(e,t){let n=t.split("/"),s=n.findIndex(r=>/^(dist|build|out|built|compiled|esm|cjs|lib|output)$/.test(r));if(s<0)return null;let o=n.slice(s+1).join("/");for(let r of["src","source","sources"]){let i=Jn(Q.resolve(e,...n.slice(0,s),r,o));if(i&&en(e,i))return i}return null}function qc(e,t,n){let s=Q.basename(n).replace(/\.(m|c)?js$/,"");for(let o of["build","compile","bundle","prepare","prepublishOnly","prepack","postinstall"]){let r=t.scripts?.[o];if(!r||!Bc.test(r))continue;let i=[];for(let l of r.split(/\s+/).map(f=>f.replace(/^["']|["']$/g,"").replace(/^--?[\w-]+=/,""))){if(!Qt.includes(Q.extname(l))||/\.d\.ts$/.test(l))continue;let f=Q.resolve(e,l);Te(f)&&en(e,f)&&!sr.test(Gn(Q.relative(e,f)))&&i.push(f)}let c=[...new Set(i)];if(c.length===1)return c[0];let a=c.filter(l=>Q.basename(l).replace(/\.[^.]+$/,"")===s);if(a.length===1)return a[0];if(c.length)return c[0]}return null}function Gc(e,t){let n=[];try{n=rt.readdirSync(e).filter(i=>Dc.test(i)).sort()}catch{return null}let s=Q.basename(t).replace(/\.(m|c)?js$/,""),o=[];for(let i of n){let c;try{c=rt.readFileSync(Q.join(e,i),"utf8")}catch{continue}for(let a of c.matchAll(/\bentry(?:Points)?\s*:\s*[[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/g)){let l=Jn(Q.resolve(e,a[1]));l&&en(e,l)&&o.push(l)}}let r=[...new Set(o)];return r.length===1?r[0]:r.find(i=>Q.basename(i).replace(/\.[^.]+$/,"")===s)??null}function tn(e,t,n){if(typeof t!="string"||!t)return null;let s=Gn(Q.normalize(t)).replace(/^\.\//,""),o=Q.resolve(e,s);if(!Fc.test(s)||Te(o)&&!sr.test(s)||Te(o)&&/\.ts$/.test(o))return null;let i=[["sourcemap",()=>Hc(e,o)],["tsconfig outDir",()=>Uc(e,s)],["convention",()=>Te(o)?null:Wc(e,s)],["build script",()=>qc(e,n??{},s)],["build config",()=>Gc(e,s)]];for(let[c,a]of i){let l=null;try{l=a()}catch{}if(l&&l!==o)return{file:l,how:c}}return null}function rr(e,t){let n=new Map;for(let[s,o]of e){let r=o.socketListeners??[],i=Me(s,o),c=ae(s,t);for(let a of r){if(a.isInlineHandler){let f=i.get(a);n.set(a.eventName,f);continue}if(!a.handlerName||!c.has(a.handlerName))continue;let l=c.get(a.handlerName);n.set(a.eventName,l)}}return n}import Yn from"node:fs";import W from"node:path";var ke=e=>String(e??"").trim().replace(/^["']|["']$/g,""),nn=e=>e.replace(/^\s*#.*$/,"").replace(/\s+#.*$/,"");function ir(e){let t=/^(\/[A-Za-z0-9_\-./]*?)\/?(?=$|[:(*{[])/.exec(String(e).trim()),n=t?t[1]:"";return n==="/"?"":n.replace(/\/+$/,"")}function cr(e,t){let n=e.split(/\r?\n/).map(nn),s=v=>v.length-v.trimStart().length,o=[],r=null,i=!1,c=null,a=!1,l=0,f=null,h=()=>{f?.key&&f.fromService&&f.fromService!=="?"&&r.hostRefs.push({name:f.key,service:f.fromService,property:f.property}),f=null},u=(v,d,k)=>{d==="name"?v.name=ke(k):d==="rootDir"?v.rootDir=ke(k):d==="startCommand"&&(v.startCommand=ke(k))};for(let v of n){if(!v.trim())continue;let d=s(v),k=v.trim();if(d===0){h(),r=null,a=!1,i=/^services\s*:/.test(k),c=null;continue}if(!i)continue;let j=k.startsWith("-");if(j&&(c==null||d===c)){c=d,h(),r={name:null,rootDir:null,startCommand:null,kept:[],hostRefs:[]},o.push(r),a=!1;let S=/^-\s*([A-Za-z]+)\s*:\s*(.*)$/.exec(k);S&&u(r,S[1],S[2]);continue}if(!r)continue;let p=/^(?:-\s*)?([A-Za-z]+)\s*:\s*(.*)$/.exec(k);if(p){if(p[1]==="envVars"){h(),a=!0,l=d;continue}if(a&&d>l){if(j&&(h(),f={key:null,fromService:null,property:null}),!f)continue;if(p[1]==="key")f.key=ke(p[2]);else if(p[1]==="value"&&f.key){let S=We(f.key,ke(p[2]),t);S&&r.kept.push(S)}else p[1]==="fromService"?f.fromService="?":p[1]==="name"&&f.fromService==="?"?f.fromService=ke(p[2]):p[1]==="property"&&(f.property=ke(p[2]));continue}a&&(h(),a=!1),u(r,p[1],p[2])}}return h(),o.filter(v=>v.name)}function ar(e,t){let n={app:null,ports:[],kept:[]},s="";for(let o of e.split(/\r?\n/)){let r=nn(o).trim();if(!r)continue;let i=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(r);if(i){s=i[1];continue}let c=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(r);if(!c)continue;let[,a,l]=c;if(s===""&&a==="app"){let f=ke(l);/^[a-z0-9][a-z0-9-]*$/i.test(f)&&(n.app=f)}else if(a==="internal_port"){let f=Number(ke(l));Number.isInteger(f)&&f>=1&&f<=65535&&n.ports.push(f)}else if(s==="env"){let f=We(a,ke(l),t);f&&n.kept.push(f)}}return n}function lr(e,t){let n={ports:[],kept:[]},s=e.replace(/\\\r?\n/g," ");for(let o of s.split(/\r?\n/)){let r=o.trim(),i=/^EXPOSE\s+(.+)$/i.exec(r);if(i){for(let a of i[1].split(/\s+/)){let l=Number(a.replace(/\/\w+$/,""));Number.isInteger(l)&&l>=1&&l<=65535&&n.ports.push(l)}continue}if(i=/^(?:ENV|ARG)\s+(.+)$/i.exec(r),!i)continue;let c=i[1];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(c)){let a=/([A-Za-z_][A-Za-z0-9_]*)=("([^"]*)"|'([^']*)'|\S*)/g,l;for(;l=a.exec(c);){let f=We(l[1],l[3]??l[4]??l[2],t);f&&n.kept.push(f)}}else{let a=/^([A-Za-z_][A-Za-z0-9_]*)\s+(.*)$/.exec(c);if(a){let l=We(a[1],ke(a[2]),t);l&&n.kept.push(l)}}}return n}function fr(e){let t;try{t=JSON.parse(e)}catch{return[]}let n=[];for(let s of["rewrites","redirects"])for(let o of Array.isArray(t?.[s])?t[s]:[]){let r=typeof o?.destination=="string"?o.destination:"",i=/\/:[A-Za-z_]+\*?$/.test(r)?qe(r.replace(/\/:[A-Za-z_]+\*?$/,"")):null;i&&typeof o.source=="string"&&n.push({prefix:ir(o.source),target:i,kind:`vercel.json ${s}`,strip:!0})}return n}function ur(e){let t=[],n=!1,s=null,o=()=>{if(s?.from&&s.to&&/\/:[A-Za-z_]+\*?$/.test(s.to)){let r=qe(s.to.replace(/\/:[A-Za-z_]+\*?$/,""));r&&t.push({prefix:ir(s.from),target:r,kind:"netlify.toml redirects",strip:!0})}s=null};for(let r of e.split(/\r?\n/)){let i=nn(r).trim();if(!i)continue;let c=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(c){o(),n=c[1]==="redirects",s=n?{}:null;continue}if(!n||!s)continue;let a=/^(from|to)\s*=\s*(.*)$/.exec(i);a&&(s[a[1]]=ke(a[2]))}return o(),t}function dr(e,t){let n;try{n=JSON.parse(e)}catch{return[]}let s=[],o=n&&typeof n=="object"?n.env:null;if(o&&typeof o=="object")for(let r of Object.keys(o).sort()){let i=o[r],c=typeof i=="string"?i:typeof i?.value=="string"?i.value:null,a=We(r,c,t);a&&s.push(a)}return s}function pr(e,t,n){let s=[];if(n){let o;try{o=JSON.parse(e)}catch{return s}let r=(i,c)=>{if(!(!i||typeof i!="object"||c>4))for(let a of Object.keys(i).sort()){let l=i[a];if(/^(env|envVars|variables|environment)$/i.test(a)&&l&&typeof l=="object"&&!Array.isArray(l))for(let f of Object.keys(l).sort()){let h=typeof l[f]=="string"?l[f]:typeof l[f]?.value=="string"?l[f].value:null,u=We(f,h,t);u&&s.push(u)}else r(l,c+1)}};r(o,0)}else{let o="";for(let r of e.split(/\r?\n/)){let i=nn(r).trim();if(!i)continue;let c=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(c){o=c[1];continue}let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(i);if(a&&/(^|\.)(env|variables|environment)$/i.test(o)){let l=We(a[1],ke(a[2]),t);l&&s.push(l)}}}return s}var Jc=[".env.local",".env",".env.development",".env.production",".env.example"],Yc=/^(PORT|HTTP_PORT|HTTPS_PORT|SERVER_PORT|API_PORT|APP_PORT|WS_PORT|WSS_PORT|WEBSOCKET_PORT|LISTEN_PORT)$/,Vc=/^PUBLIC_(?:[A-Z0-9]+_)*(?:ORIGIN|URL|HOST|BASE_URL)$/,Xc=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","host.docker.internal"]),Kc=512*1024,mr=e=>e.split(W.sep).join("/");function it(e){try{let t=Yn.lstatSync(e);return!t.isFile()||t.isSymbolicLink()||t.size>Kc?null:Yn.readFileSync(e,"utf8")}catch{return null}}function qe(e){let t=String(e).trim().replace(/^["']|["']$/g,"");if(!/^(https?|wss?):\/\//i.test(t))return null;try{let n=new URL(t);if(!n.hostname)return null;let s=n.protocol.replace(":",""),o=n.hostname.toLowerCase(),r=n.port?Number(n.port):null,i=n.pathname.replace(/\/+$/,"");return{scheme:s,host:o,port:r,origin:`${s}://${o}${r?":"+r:""}`,path:i}}catch{return null}}function Zc(e){let t=String(e).trim().replace(/^["']|["']$/g,"");return!/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:\d{1,5})?(\/[^\s?#]*)?$/i.test(t)||!/[a-z]/i.test(t.split(/[/:]/)[0])?null:qe("http://"+t)}var Vn=e=>{let t=String(e).trim().replace(/^["']|["']$/g,"");if(!/^\d{1,5}$/.test(t))return null;let n=Number(t);return n>=1&&n<=65535?n:null};function Qc(e){let t=new Map;for(let n of e.split(/\r?\n/)){let s=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(n);if(!s)continue;let o=s[2];if(/^["']/.test(o)){let r=o[0],i=o.indexOf(r,1);o=i>0?o.slice(1,i):o.slice(1)}else o=o.replace(/\s+#.*$/,"");t.set(s[1],o)}return t}function yr(e,t,n=0,s=new Set){let o=e.get(t);return o==null||n>5||s.has(t)||(s.add(t),o=o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}]*))?\}/g,(r,i,c)=>{let a=e.has(i)?yr(e,i,n+1,s):void 0;return a!=null&&a!==""?a:c??""}),s.delete(t)),o}function We(e,t,n){if(t==null)return null;if(Yc.test(e)){let o=Vn(t);return o?{name:e,kind:"port",file:n,port:o}:null}let s=qe(t)??(/(_URL|_URI|_HOST|_HOSTNAME|_ORIGIN|_ADDR|_ENDPOINT)$/i.test(e)?Zc(t):null);return s?{name:e,kind:"url",file:n,...s}:null}function hr(e,t){let n=[];for(let s of[...e.keys()].sort()){let o=yr(e,s);if(o==null)continue;let r=We(s,o,t);r&&n.push(r)}return n}function ea(e){let t=e.split(/\r?\n/).map(l=>l.replace(/\s+#.*$/,"").replace(/\t/g," ")),n=l=>l.length-l.trimStart().length,s=[],o=t.findIndex(l=>/^services\s*:\s*$/.test(l));if(o<0)return s;let r=null,i=null,c=null,a=0;for(o=o+1;o<t.length;o++){let l=t[o];if(!l.trim())continue;let f=n(l),h=l.trim();if(f===0)break;if(r==null&&(r=f),f===r){let u=/^([A-Za-z0-9_.-]+)\s*:\s*$/.exec(h);u&&(i={name:u[1],ports:[],env:new Map,build:null},s.push(i),c=null);continue}if(i){if(f<=r+4&&/^[A-Za-z_]+\s*:/.test(h)&&!h.startsWith("-")){let u=/^([A-Za-z_]+)\s*:\s*(.*)$/.exec(h);c=u[1],a=f,c==="build"&&u[2]&&(i.build=u[2].replace(/^["']|["']$/g,""));continue}if(c==="build"&&/^context\s*:/.test(h)){i.build=h.replace(/^context\s*:\s*/,"").replace(/^["']|["']$/g,"");continue}if(c==="ports"&&h.startsWith("-")){let v=h.slice(1).trim().replace(/^["']|["']$/g,"").replace(/\/\w+$/,"").split(":"),d=v.slice(-2).map(k=>Vn(k));v.length===1&&d[0]?i.ports.push({host:null,container:d[0]}):v.length>=2&&d[0]&&d[1]&&i.ports.push({host:d[0],container:d[1]});continue}if(c==="environment"&&f>a){let u=h.startsWith("-")?/^-\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(h):/^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/.exec(h);u&&i.env.set(u[1],u[2].replace(/^["']|["']$/g,""))}}}return s}function gr(e,t){let n=[];if(t==="vite"){let s=e.search(/\bproxy\s*:/);if(s<0)return n;let o=e.slice(s,s+2500),r=/["'`](\/[^"'`]*)["'`]\s*:\s*(?:["'`](https?:\/\/[^"'`]+)["'`]|\{[^{}]*?target\s*:\s*["'`](https?:\/\/[^"'`]+)["'`])/g,i;for(;i=r.exec(o);){let c=qe(i[2]??i[3]);c&&n.push({prefix:i[1].replace(/\/+$/,""),target:c,kind:"vite.config proxy"})}}else if(t==="next"){let s=/source\s*:\s*["'`](\/[^"'`:*]*)[^"'`]*["'`]\s*,\s*destination\s*:\s*["'`](https?:\/\/[^"'`]+?)(?:\/:[^"'`]*)?["'`]/g,o;for(;o=s.exec(e);){let r=qe(o[2]);r&&n.push({prefix:o[1].replace(/\/+$/,""),target:r,kind:"next.config rewrites"})}}return n}function vr(e,t,n){let s=p=>mr(W.relative(e,p)),o=new Map,r=new Map,i=new Map,c=(p,S,$)=>{(p.get(S)??p.set(S,new Set).get(S)).add($)},a=(p,S,$)=>{let w=i.get(p)??i.set(p,[]).get(p);w.some(y=>y.service===S&&y.via===$)||w.push({service:S,via:$})},l=p=>{let S=[],$=W.resolve(p),w=W.resolve(e);for(let y=0;y<8&&(S.push($),!($===w||W.dirname($)===$||($=W.dirname($),!$.startsWith(w))));y++);return S},f=new Map,h=new Map,u=(p,S)=>{let $=p.env.get(S.name)??p.env.set(S.name,[]).get(S.name);$.some(w=>w.file===S.file)||$.push(S),S.kind==="port"&&p.ports.add(S.port)};function v(p,S,$){let w=m=>s(W.join($,m)),y=m=>it(W.join($,m));for(let m of on($))if(m==="fly.toml"){let b=y(m);if(b){let g=ar(b,w(m));for(let x of g.ports)S.ports.add(x);for(let x of g.kept)u(S,x);g.app&&(a(`${g.app.toLowerCase()}.internal`,p.name,"fly.toml app name"),a(`${g.app.toLowerCase()}.fly.dev`,p.name,"fly.toml app name"))}}else if(/^Dockerfile(\..+)?$/.test(m)){let b=y(m);if(b){let g=lr(b,w(m));for(let x of g.ports)S.weakPorts.add(x);for(let x of g.kept)u(S,x)}}else if(m==="railway.json"||m==="railway.toml"){let b=y(m);if(b)for(let g of pr(b,w(m),m.endsWith(".json")))u(S,g)}else if(m==="app.json"){let b=y(m);if(b)for(let g of dr(b,w(m)))u(S,g)}else if(m==="vercel.json"){let b=y(m);if(b)for(let g of fr(b))S.proxies.push({...g,file:w(m)})}else if(m==="netlify.toml"){let b=y(m);if(b)for(let g of ur(b))S.proxies.push({...g,file:w(m)})}}for(let p of t){let S={env:new Map,ports:new Set,weakPorts:new Set,proxies:[],isServer:!1};o.set(p.name,S);for(let $ of l(p.rootPath)){for(let w of Jc){let y=it(W.join($,w));if(y!=null)for(let m of hr(Qc(y),s(W.join($,w)))){let b=S.env.get(m.name)??S.env.set(m.name,[]).get(m.name);b.some(g=>g.file===m.file)||b.push(m),m.kind==="port"&&$===W.resolve(p.rootPath)&&/(^|\/)\.env/.test(m.file)&&!/\.example$/.test(m.file)&&S.ports.add(m.port),m.kind==="port"&&$===W.resolve(p.rootPath)&&/\.example$/.test(m.file)&&S.ports.add(m.port)}}if($===W.resolve(p.rootPath)){try{let w=JSON.parse(it(W.join($,"package.json"))??"null"),y=typeof w?.proxy=="string"?qe(w.proxy):null;y&&S.proxies.push({prefix:"",target:y,kind:'package.json "proxy"',file:s(W.join($,"package.json"))})}catch{}for(let w of on($)){if(/^vite\.config\.(js|mjs|cjs|ts|mts)$/.test(w)){let y=it(W.join($,w));if(y)for(let m of gr(y,"vite"))S.proxies.push({...m,file:s(W.join($,w))})}if(/^next\.config\.(js|mjs|cjs|ts)$/.test(w)){let y=it(W.join($,w));if(y)for(let m of gr(y,"next"))S.proxies.push({...m,file:s(W.join($,w))})}}}$===W.resolve(p.rootPath)&&v(p,S,$);for(let w of on($))if(/^render\.ya?ml$/.test(w)&&!h.has(W.join($,w))){let y=it(W.join($,w));y&&h.set(W.join($,w),cr(y,s(W.join($,w))))}for(let w of on($)){if(!/^docker-compose.*\.ya?ml$/.test(w)||f.has(W.join($,w)))continue;let y=it(W.join($,w));y&&f.set(W.join($,w),ea(y))}}}for(let[p,S]of[...f].sort(($,w)=>$[0]<w[0]?-1:1)){let $=W.dirname(p);for(let w of S){let y=w.build?W.resolve($,w.build):null,m=t.find(g=>y&&W.resolve(g.rootPath)===y)??t.find(g=>g.name===w.name||W.basename(g.rootPath)===w.name);if(!m)continue;let b=o.get(m.name);for(let g of w.ports)b.ports.add(g.container),g.host&&b.ports.add(g.host);for(let g of hr(w.env,s(p)))(b.env.get(g.name)??b.env.set(g.name,[]).get(g.name)).push(g);a(w.name.toLowerCase(),m.name,"docker-compose service name")}}for(let[p,S]of[...h].sort(($,w)=>$[0]<w[0]?-1:1)){let $=W.dirname(p),w=new Map;for(let y of S){let m=W.resolve($,y.rootDir||"."),b=y.rootDir?t.find(x=>W.resolve(x.rootPath)===m):null;if(!b&&y.startCommand)for(let x of y.startCommand.split(/\s+/)){if(!/\.(c|m)?[jt]sx?$/.test(x)&&!/^[\w./-]+\/[\w.-]+$/.test(x))continue;let I=W.resolve(m,x),E=t.filter(M=>I.startsWith(W.resolve(M.rootPath)+W.sep)).sort((M,O)=>O.rootPath.length-M.rootPath.length)[0];if(E){b=E;break}}if(b=b??t.find(x=>x.name===y.name||W.basename(x.rootPath)===y.name),!b)continue;w.set(y.name,{target:b,c:y});let g=o.get(b.name);for(let x of y.kept)u(g,{...x,scoped:!0});a(y.name.toLowerCase(),b.name,"render.yaml service name"),a(`${y.name.toLowerCase()}.onrender.com`,b.name,"render.yaml service name (Render's default public address)")}for(let{target:y,c:m}of w.values())for(let b of m.hostRefs){let g=w.get(b.service);if(!g)continue;let x=[...g.c.kept].find(M=>M.kind==="port")?.port??null,I=b.property==="hostport"&&x,E=b.service.toLowerCase();u(o.get(y.name),{name:b.name,kind:"url",file:s(p),scheme:"http",host:E,port:I?x:null,origin:`http://${E}${I?":"+x:""}`,path:""})}}let d=p=>[...n.get(p.name)?.parseResults?.values()??[]].some(S=>(S.routes??[]).length>0);for(let p of t){let S=o.get(p.name);if(S.isServer=d(p),S.isServer){for(let[$,w]of S.env)if(Vc.test($))for(let y of w)y.kind==="url"&&y.file&&(y.scoped||W.posix.dirname(y.file)===(mr(W.relative(e,p.rootPath))||"."))&&a(y.host,p.name,`${$} in ${y.file} (the server's own public address)`)}}for(let p of t){let S=o.get(p.name);for(let[,$]of n.get(p.name)?.parseResults??[])for(let w of $.httpClients?.listens??[])for(let y of k(S,w.parts)){let m=Vn(y.text);m&&S.ports.add(m)}}for(let p of t)for(let S of o.get(p.name).ports)c(r,S,p.name);for(let p of t)for(let S of o.get(p.name).weakPorts)t.some($=>o.get($.name).ports.has(S))||c(r,S,p.name);function k(p,S){let $=[{text:"",evidence:[]}];for(let w of S){let y;if(w.t==="lit")y=[{text:w.v,evidence:[]}];else if(w.t==="env"){let b=p.env.get(w.name)??[];y=[];for(let g of b)y.push({text:g.kind==="port"?String(g.port):g.origin+g.path,evidence:[{env:w.name,file:g.file}]});!y.length&&w.fallback&&(y=k(p,w.fallback).map(x=>({text:x.text,evidence:[{env:w.name,file:null,fallback:!0},...x.evidence]})))}else y=[];if(!y.length)return[];let m=[];for(let b of $)for(let g of y)if(m.push({text:b.text+g.text,evidence:[...b.evidence,...g.evidence]}),m.length>=8)break;$=m.slice(0,8)}return $}let j=(p,S)=>{let $=[],w=p.host,y=i.get(w)??[];for(let m of y)$.push(m);if(Xc.has(w)||y.length&&y.some(m=>m.via==="docker-compose service name")){let m=p.port??(p.scheme==="https"||p.scheme==="wss",null);if(m)for(let b of r.get(m)??[])$.some(g=>g.service===b)||$.push({service:b,via:`port ${m} (a service listening there)`})}return $.filter(m=>m.service!==S)};return{resolveBase(p,S){let $=o.get(p);if(!$||!S.length)return{status:"unknown"};let w=k($,S);if(!w.length)return{status:"unknown"};let y=[],m=new Set;for(let x of w){let I=qe(x.text)??(x.text.startsWith("//"),null);if(I){m.add(I.origin);for(let E of j(I,p))y.push({...E,u:I,evidence:x.evidence})}}if(!m.size)return{status:"unknown"};let b=[...new Set(y.map(x=>x.service))];if(b.length===0)return{status:"external",origins:[...m].sort()};if(b.length>1)return{status:"ambiguous",services:b.sort()};let g=y[0];return{status:"service",service:g.service,via:g.via,origin:g.u.origin,basePath:g.u.path,evidence:g.evidence.filter((x,I,E)=>E.findIndex(M=>M.env===x.env&&M.file===x.file)===I)}},resolveProxy(p,S){let $=o.get(p);for(let w of $?.proxies??[]){if(w.prefix&&S!==w.prefix&&!S.startsWith(w.prefix+"/"))continue;let y=j(w.target,p),m=[...new Set(y.map(b=>b.service))];if(m.length===1)return{status:"service",service:m[0],via:`${w.kind} ${w.prefix||"/"} -> ${w.target.origin}`,origin:w.target.origin,basePath:w.target.path,strip:w.strip?w.prefix.split("/").filter(Boolean).length:0,evidence:[{env:null,file:w.file}]}}return{status:"unknown"}},portsOf:p=>[...o.get(p)?.ports??[]].sort((S,$)=>S-$),hostClaims:()=>[...i].sort((p,S)=>p[0]<S[0]?-1:1)}}function on(e){try{return Yn.readdirSync(e).sort()}catch{return[]}}var sn=e=>String(e).toLowerCase();function rn(e){let t=[];for(let n of e)n.t==="lit"&&t.length&&t[t.length-1].t==="lit"?t[t.length-1]={t:"lit",v:t[t.length-1].v+n.v}:t.push(n);return t}function wr(e,t){let n=[];for(let s of e){if(s.t!=="param"){n.push(s);continue}let o=t?.get(s.index);o?n.push(...o):n.push({t:"ref",name:s.name})}return rn(n)}function Xn(e){if(!e.length)return null;let t=e.slice(),n="none",s=null,o=t[0];if(o.t==="lit"){let l=/^(https?:)\/\/([^/?#]*)(.*)$/.exec(o.v);if(l){n="abs",s=l[2];let f=l[3];if(t=f?[{t:"lit",v:f},...t.slice(1)]:t.slice(1),/^(www\.)?(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)(:\d+)?$/.test(s)===!1&&!/\.(local|internal|svc)$/.test(s)&&!/^[a-z0-9-]+(:\d+)?$/.test(s))return null}else if(!o.v.startsWith("/"))return null}else{for(n="var";t.length&&t[0].t!=="lit";)t.shift();if(!t.length||!t[0].v.startsWith("/"))return null}let r="",i=0,c=!1;for(let l of t){if(c)break;if(l.t==="lit"){let f=l.v.search(/[?#]/);f>=0?(r+=l.v.slice(0,f),c=!0):r+=l.v}else r+="",i++}if(!r.startsWith("/")&&!(r===""&&n==="abs"))return null;r===""&&(r="/");let a=r.split("/").slice(1).map(l=>l.includes("")?":p":l);for(;a.length>1&&a[a.length-1]==="";)a.pop();return{base:n,host:s,segments:a,placeholders:i,literal:n==="none"&&i===0}}function xr(e){if(!e.length)return[];let t=e[0];if(t.t==="lit"){let s=/^((?:https?|wss?):\/\/[^/?#]*)/.exec(t.v);return s?[{t:"lit",v:s[1]}]:[]}let n=[];for(let s of e){if(s.t==="lit"&&s.v.startsWith("/"))break;n.push(s)}return n}var ta=e=>String(e||"").split("/").filter(Boolean),Sr=e=>[...new Set(e)];function kr(e){let t=e.evidence??[];return{env:Sr(t.filter(n=>n.env).map(n=>n.env)),files:Sr(t.filter(n=>n.file).map(n=>n.file)),origin:e.origin,via:e.via,...t.some(n=>n.fallback)?{usedFallback:!0}:{}}}var $r=(e,t)=>"base URL "+(e.env.length?e.env.join(", ")+(e.files.length?" in "+e.files.join(", "):"")+" = ":e.files.length?"(from "+e.files.join(", ")+") ":"")+e.origin+" belongs to "+t+" ("+e.via+")",na=e=>{let t=String(e).split(/[?#]/)[0].split("/").slice(1).map(n=>n.startsWith(":")||/^\{.*\}$/.test(n)||n==="*"?":p":n);for(;t.length>1&&t[t.length-1]==="";)t.pop();return t};function br(e,t){if(e.length===t.length){let n=!0,s=!0;for(let o=0;o<e.length;o++){let r=e[o],i=t[o];if(r!==i&&(n=!1),!(r===i||r===":p"||i===":p")){s=!1;break}}if(n)return 3;if(s)return 2}if(e[0]==="api"&&e.length>1){let n=e.slice(1);if(/^v\d+$/.test(n[0])&&n.length>1&&(n=n.slice(1)),n.length===t.length&&n.every((s,o)=>s===t[o]||s===":p"||t[o]===":p"))return 1}return 0}function oa(e,t,n,s,o){let r=(n.importBindings??[]).find(h=>h.local===s);if(!r)return null;let i=me(r.source,t,o);if(!i)return null;let c=e.parseResults.get(i),a=h=>e.nodes.find(u=>u.filePath===i&&u.name===h&&u.type!=="moduleRoot")?.id??null;if(r.kind==="named"&&r.imported)return a(r.imported);let l=c?.exportBindings;if(l?.default&&l.default!=="<anon>")return a(l.default);let f=Object.keys(l?.named??{});return f.length===1?a(f[0]):null}function sa(e){let t=[],n=[...e.parseResults.keys()];for(let[s,o]of e.parseResults){let r=e.nodes.filter(a=>a.filePath===s);if(r[0]?.category!=="backend")continue;let i=Me(s,o),c=ae(s,e.nodes);for(let a of o.routes??[]){let l=null;a.isInlineHandler?l=i.get(a):a.nest?l=r.find(h=>h.type==="classMethod"&&h.className===a.nest.className&&h.name===a.nest.methodName)?.id??null:a.handlerName&&c.has(a.handlerName)?l=c.get(a.handlerName):a.handlerName&&(l=oa(e,s,o,a.handlerName,n));let f=!1;l||(l=ie(a.startLine,r)?.id??null,f=!0),l&&t.push({method:sn(a.method),path:a.path,segments:na(a.path),literal:!/[:*{]/.test(a.path),nodeId:l,file:s,line:a.startLine,fallback:f})}}return t}var ra=/^(ws|uws|websocket|@nestjs\/platform-ws|@fastify\/websocket|fastify-websocket|express-ws)$/,ia=/^(socket\.io|@nestjs\/platform-socket\.io|socket\.io-client)$/;function Nr(e){let t=[...e].some(s=>ia.test(s)),n=[...e].some(s=>ra.test(s));return t&&n?"unknown":t?"socketio":n?"ws":null}function ca(e){let t=[],n=new Set;for(let[,s]of e.parseResults)for(let o of s.imports??[])n.add(o.source);for(let[s,o]of e.parseResults){let r=o.socketListeners??[],i=r.find(k=>k.eventName==="connection");if(!i)continue;let c=Me(s,o),a=ae(s,e.nodes),l=k=>k.isInlineHandler?c.get(k):k.handlerName&&a.has(k.handlerName)?a.get(k.handlerName):null,f=l(i);if(!f)continue;let h=k=>i.handlerStartLine!=null&&k.startLine>=i.handlerStartLine&&k.startLine<=i.handlerEndLine,u=r.find(k=>k.eventName==="message"&&h(k))??r.find(k=>k.eventName==="message"),v=o.httpClients?.wsServers??[],d=Nr(new Set((o.imports??[]).map(k=>k.source)))??Nr(n)??"unknown";t.push({filePath:s,nodeId:f,line:i.startLine,messageNodeId:u?l(u):null,messageLine:u?.startLine??null,pathParts:v.find(k=>k.path)?.path??null,kind:d})}return t}function Ir(e,t,n={}){let s=n.repoRoot?vr(n.repoRoot,e,t):null,o=[],r=new Set,i={restCalls:0,restLinked:0,wsClients:0,wsLinked:0,wsSends:0,wsSendsLinked:0},c=l=>{let f=[l.fromService,l.fromNodeId,l.toService,l.toNodeId,l.via,l.key].join("\0");r.has(f)||(r.add(f),o.push(l))},a=new Map;for(let l of e){let f=t.get(l.name);f&&a.set(l.name,{routes:sa(f),wsServers:ca(f)})}for(let l of e){let f=t.get(l.name);if(!f)continue;let h=[...f.parseResults.keys()],u=new Map,v=new Map;for(let[y,m]of f.parseResults){let b=m.httpClients;if(b){for(let g of b.httpInstances??[])(u.get(g.name)??u.set(g.name,[]).get(g.name)).push(g);for(let g of b.httpCalls??[])(g.parts.some(I=>I.t==="param")||g.method&&typeof g.method=="object")&&g.fn?.name&&(v.get(g.fn.name)??v.set(g.fn.name,[]).get(g.fn.name)).push({filePath:y,call:g})}}let d=y=>{if(!y.startsWith("inst:")&&!y.startsWith("obj:"))return[];let m=u.get(y.slice(y.indexOf(":")+1));return m&&m.length===1?m[0].parts:y.startsWith("obj:")?null:[{t:"ref",name:"?"}]},k=[],j=(y,m)=>ie(m,f.nodes.filter(b=>b.filePath===y)),p=new Set,S=y=>y.parts.some(m=>m.t==="param")||y.method&&typeof y.method=="object";for(let[y,m]of f.parseResults){let b=m.httpClients;if(b){for(let g of b.httpCalls??[]){if(S(g))continue;let x=d(g.client);if(x===null)continue;let I=j(y,g.line);I&&k.push({filePath:y,line:g.line,nodeId:I.id,method:g.method,parts:rn([...x,...g.parts]),via:g.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let g of b.pathCallsites??[]){let x=v.get(g.callee);if(x)for(let I of x){let E=I.filePath===y;if(!E){let B=(m.importBindings??[]).find(_=>_.local===g.callee||_.imported===g.callee);B&&me(B.source,y,h)===I.filePath&&(E=!0)}if(!E)continue;let M=new Map(g.args.map(B=>[B.i,B.parts])),O=typeof I.call.method=="object"&&I.call.method?(()=>{let B=M.get(I.call.method.param);return B&&B.length===1&&B[0].t==="lit"?B[0].v.toUpperCase():"?"})():I.call.method,L=j(y,g.line);L&&(p.add(I.call),k.push({filePath:y,line:g.line,nodeId:L.id,method:O,parts:wr([...d(I.call.client),...I.call.parts],M),via:I.call.client,wrapper:g.callee}))}}}}for(let[y,m]of f.parseResults)for(let b of m.httpClients?.httpCalls??[]){if(!S(b)||p.has(b))continue;let g=d(b.client);if(g===null)continue;let x=j(y,b.line);x&&k.push({filePath:y,line:b.line,nodeId:x.id,method:typeof b.method=="object"&&b.method?"?":b.method,parts:wr([...g,...b.parts],null),via:b.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let y of k){let m=Xn(y.parts);if(!m)continue;i.restCalls++;let b=0,g=[];for(let L of e){if(L.name===l.name)continue;let B=a.get(L.name);if(B)for(let _ of B.routes){if(!(y.method==="?"||y.method==null||_.method===sn(y.method)||_.method==="all"||_.method==="use"))continue;let V=br(m.segments,_.segments);V&&(V>b&&(b=V,g.length=0),V===b&&g.push({service:L.name,route:_}))}}let x={status:"unknown"};if(s){let L=rn(y.parts);if(m.base==="none"?x=s.resolveProxy(l.name,"/"+m.segments.join("/")):x=s.resolveBase(l.name,xr(L)),x.status==="service"){let B=ta(x.basePath);if(B.length||x.strip){let _=[...B,...m.segments.slice(x.strip||0)];for(let U of a.get(x.service)?.routes??[])(y.method==="?"||y.method==null||U.method===sn(y.method)||U.method==="all"||U.method==="use")&&br(_,U.segments)&&!g.some(R=>R.service===x.service&&R.route.nodeId===U.nodeId)&&g.push({service:x.service,route:U,viaBasePath:!0})}}}if(!g.length)continue;let I=new Set(g.map(L=>L.service+"\0"+L.route.nodeId)),E=typeof y.method=="string"&&y.method!=="?",M=b===3&&m.literal&&E&&I.size===1&&g[0].route.literal&&!g[0].route.fallback&&g[0].route.method===sn(y.method),O=[];m.base==="var"&&O.push("base URL is a variable, so the target service is guessed from the path"),m.base==="abs"&&O.push("absolute URL"),m.placeholders&&O.push("path has parameters"),b===1&&O.push("leading /api removed from the client path"),b===2&&O.push("route parameters matched fuzzily"),E||O.push("method not known"),I.size>1&&O.push(I.size+" candidate routes"),g.some(L=>L.route.fallback)&&O.push("route handler not resolved: linked to the function that registers the route"),x.status==="external"&&O.push("base URL is "+x.origins.join(" / ")+", which no service of this repo owns"),x.status==="ambiguous"&&O.push("base URL could belong to "+x.services.join(" or "));for(let L of g){i.restLinked++;let B=!M&&x.status==="service"&&x.service===L.service&&!L.route.fallback,_=B?kr(x):null,U=M?"exact":B?"resolved":"inferred",V=!M&&x.status==="service"&&x.service!==L.service?["base URL belongs to "+x.service+", not this service"]:[];c({fromService:l.name,fromNodeId:y.nodeId,toService:L.service,toNodeId:L.route.nodeId,via:"httpCall",key:`${E?y.method:"ANY"} ${"/"+m.segments.join("/")}`,confidence:U,method:E?y.method:null,url:"/"+m.segments.join("/"),client:y.via,...y.wrapper?{wrapper:y.wrapper}:{},line:y.line,...M?{}:B?{reason:$r(_,L.service)+(E?"":"; method not known"),resolvedFrom:_}:{reason:[...O,...V].join("; ")||"path-only match"}})}}let $=[];for(let[y,m]of f.parseResults)for(let b of m.httpClients?.wsClients??[])$.push({filePath:y,w:b});let w=y=>y.client==="io"?"socketio":"ws";for(let{filePath:y,w:m}of $){let b=j(y,m.line);if(!b)continue;i.wsClients++;let g=rn(m.parts),x=/^wss?:\/\//.test(g[0]?.v??"")?Xn([{t:"lit",v:g[0].v.replace(/^ws(s?):/,"http$1:")},...g.slice(1)]):Xn(g),I=s&&x?s.resolveBase(l.name,xr(g)):{status:"unknown"};for(let E of e)if(E.name!==l.name)for(let M of a.get(E.name)?.wsServers??[]){if(M.kind!=="unknown"&&M.kind!==w(m))continue;let O=M.pathParts&&M.pathParts.every(V=>V.t==="lit")?"/"+M.pathParts.map(V=>V.v).join("").replace(/^\//,""):null,L=x?"/"+x.segments.join("/"):null;if(O&&L&&O!==L&&O!=="/"&&L!=="/")continue;let B=!!(x&&x.literal&&O&&L===O&&M.kind!=="unknown"),_=!B&&I.status==="service"&&I.service===E.name,U=_?kr(I):null;i.wsLinked++,c({fromService:l.name,fromNodeId:b.id,toService:E.name,toNodeId:M.nodeId,via:"webSocket",key:L??"(url unknown)",confidence:B?"exact":_?"resolved":"inferred",url:L,client:m.client,line:m.line,...B?{}:_?{reason:$r(U,E.name),resolvedFrom:U}:{reason:"WebSocket connection matched to a WebSocket server of another service ("+(x?.base==="var"?"URL base is a variable":"no path on the server to compare")+(I.status==="external"?"; base URL is "+I.origins.join(" / ")+", which no service of this repo owns":"")+")"}})}}if($.length){let y=new Set($.map(({w:m})=>w(m)));for(let[m,b]of f.parseResults)for(let g of b.httpClients?.wsSends??[]){let x=j(m,g.line);if(x){i.wsSends++;for(let I of e)if(I.name!==l.name)for(let E of a.get(I.name)?.wsServers??[])!E.messageNodeId||E.kind!=="unknown"&&!y.has(E.kind)||(i.wsSendsLinked++,c({fromService:l.name,fromNodeId:x.id,toService:I.name,toNodeId:E.messageNodeId,via:"webSocketMessage",key:"message",eventName:"message",confidence:"inferred",client:g.recv,line:g.line,reason:"a message sent over a socket whose payload is built at run time; delivered to the message listener of a WebSocket server of another service"}))}}}}if(n.serverPush!==!1){let l=new Map;for(let h of o)if(h.via==="webSocket"){let u=h.fromService+"\0"+h.toService;(l.get(u)??l.set(u,[]).get(u)).push(h)}let f=new Map;for(let h of l.values())(f.get(h[0].toService)??f.set(h[0].toService,new Set).get(h[0].toService)).add(h[0].fromService);for(let[,h]of[...l].sort((u,v)=>u[0]<v[0]?-1:1)){let u=h[0].fromService,v=h[0].toService,d=t.get(u),k=t.get(v);if(!d||!k||!(a.get(v)?.wsServers??[]).length)continue;let j=new Set(h.map(w=>w.fromNodeId.split("::")[0])),p=[];for(let[w,y]of d.parseResults){if(!j.has(w))continue;let m=ae(w,d.nodes),b=Me(w,y),g=d.nodes.filter(x=>x.filePath===w);for(let x of y.httpClients?.wsReceivers??[]){let I=x.handlerName&&m.get(x.handlerName)||ie(x.line,g)?.id;I&&p.push({id:I,line:x.line})}for(let x of y.socketListeners??[]){if(x.eventName!=="message")continue;let I=x.isInlineHandler?b.get(x):x.handlerName&&m.get(x.handlerName)||null;I&&p.push({id:I,line:x.startLine})}}let S=new Set(d.resolvedEdges.filter(w=>w.resolved&&w.targetNodeId&&w.type!=="returnValue").map(w=>w.fromNodeId));for(let w=p.length-1;w>=0;w--)S.has(p[w].id)||p.splice(w,1);if(!p.length)continue;let $=f.get(v)?.size??1;for(let[w,y]of k.parseResults){let m=k.nodes.filter(b=>b.filePath===w);for(let b of[...y.httpClients?.wsSends??[],...y.httpClients?.wsServerSends??[]]){let g=ie(b.line,m);if(g)for(let x of p)i.wsPushLinked=(i.wsPushLinked??0)+1,c({fromService:v,fromNodeId:g.id,toService:u,toNodeId:x.id,via:"webSocketDelivery",key:"message",eventName:"message",confidence:"inferred",client:b.recv,line:b.line,receiverLine:x.line,reason:"a message the server sends over a WebSocket (payload built at run time) is taken in by the message handler of "+u+", which connects to this server"+($>1?"; "+$+" services connect to this server, so it may be meant for another one":""),...$>1?{candidates:$}:{}})}}}}return o.sort((l,f)=>l.fromService+l.fromNodeId+l.via+l.key+l.toService+l.toNodeId<f.fromService+f.fromNodeId+f.via+f.key+f.toService+f.toNodeId?-1:1),{edges:o,stats:i}}import jr from"node:fs";var aa=/\b(?:Queue|Bull|Worker|Processor|InjectQueue|WorkerHost)\b|\.process\s*\(/,le="[A-Za-z_$][\\w$]*",la=1024*1024;function Er(e){let t="",n=0,s=null;for(;n<e.length;){let o=e[n],r=e[n+1];if(s){if(t+=o,o==="\\"){t+=e[n+1]??"",n+=2;continue}o===s&&(s=null),n++}else if(o==="/"&&r==="/")for(;n<e.length&&e[n]!==`
12
+ `;)t+=" ",n++;else if(o==="/"&&r==="*"){for(t+=" ",n+=2;n<e.length&&!(e[n]==="*"&&e[n+1]==="/");)t+=e[n]===`
13
+ `?`
14
+ `:" ",n++;t+=" ",n+=2}else(o==='"'||o==="'"||o==="`")&&(s=o),t+=o,n++}return t}function Zn(e,t){let n={"(":")","[":"]","{":"}"},s=[],o=null;for(let r=t;r<e.length;r++){let i=e[r];if(o){i==="\\"?r++:i===o&&(o=null);continue}if(i==='"'||i==="'"||i==="`"){o=i;continue}if(n[i])s.push(n[i]);else if(i===")"||i==="]"||i==="}"){if(s.pop()!==i)return-1;if(!s.length)return r}}return-1}function ct(e,t){let n=Zn(e,t);if(n<0)return null;let s=[],o=0,r=null,i=t+1;for(let c=t+1;c<n;c++){let a=e[c];if(r){a==="\\"?c++:a===r&&(r=null);continue}if(a==='"'||a==="'"||a==="`"){r=a;continue}a==="("||a==="["||a==="{"?o++:a===")"||a==="]"||a==="}"?o--:a===","&&o===0&&(s.push({text:e.slice(i,c),start:i}),i=c+1)}return e.slice(i,n).trim()&&s.push({text:e.slice(i,n),start:i}),{args:s,close:n}}function fa(e){let t=[0];for(let n=0;n<e.length;n++)e[n]===`
15
+ `&&t.push(n+1);return n=>{let s=0,o=t.length-1;for(;s<o;){let r=s+o+1>>1;t[r]<=n?s=r:o=r-1}return s+1}}var ua=e=>{let t=e.trim(),n=/^(['"])([^'"\\\n]*)\1$/.exec(t);return n?n[2]:(n=/^`([^`$\\]*)`$/.exec(t),n?n[1]:null)},Rr=e=>new RegExp(`(?:const|let|var|readonly|static)\\s+${e.replace(/\$/g,"\\$")}\\s*(?::[^=;{]+)?=\\s*(['"\`])([^'"\`$\\\\\\n]*)\\1`);function Kn(e,t){let n=t.exec(e);if(!n)return null;let s=e.indexOf("{",n.index+n[0].length-1);if(s<0)return null;let o=Zn(e,s);return o<0?null:e.slice(s+1,o)}function _r(e,t,n){let s=t.replace(/\$/g,"\\$"),o=n.replace(/\$/g,"\\$"),r=Kn(e,new RegExp(`\\benum\\s+${s}\\s*\\{`));if(r){let i=new RegExp(`(?:^|[,{\\s])${o}\\s*=\\s*(['"\`])([^'"\`$\\\\\\n]*)\\1`).exec(r);return i?i[2]:null}if(r=Kn(e,new RegExp(`(?:const|let|var)\\s+${s}\\s*(?::[^=]+)?=\\s*\\{`))??Kn(e,new RegExp(`\\bclass\\s+${s}\\b[^{]*\\{`)),r){let i=new RegExp(`(?:^|[,{\\s])(?:static\\s+(?:readonly\\s+)?)?${o}\\s*[:=]\\s*(['"\`])([^'"\`$\\\\\\n]*)\\1`).exec(r);return i?i[2]:null}return null}function da(e){let t=new Map,n=/import\s+(?:type\s+)?([^'";]*?)\s+from\s*['"]([^'"]+)['"]/g,s;for(;s=n.exec(e);){let o=s[1].trim(),r=s[2],i=/\{([^}]*)\}/.exec(o);if(i)for(let l of i[1].split(",")){let f=l.trim().replace(/^type\s+/,"");if(!f)continue;let h=/^(\S+)\s+as\s+(\S+)$/.exec(f);h?t.set(h[2],{spec:r,imported:h[1]}):t.set(f,{spec:r,imported:f})}let c=/\*\s*as\s+(\S+)/.exec(o);c&&t.set(c[1],{spec:r,imported:"*"});let a=/^([A-Za-z_$][\w$]*)\s*(?:,|$)/.exec(o);a&&!o.startsWith("{")&&!o.startsWith("*")&&t.set(a[1],{spec:r,imported:"default"})}return t}function Cr(e){let t=[],n,s=/export\s*\*\s*from\s*['"]([^'"]+)['"]/g;for(;n=s.exec(e);)t.push({spec:n[1],all:!0});let o=/export\s*\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g;for(;n=o.exec(e);){let r=new Map;for(let i of n[1].split(",")){let c=i.trim();if(!c)continue;let a=/^(\S+)\s+as\s+(\S+)$/.exec(c);a?r.set(a[2],a[1]):r.set(c,c)}t.push({spec:n[2],names:r})}return t}function Lr(e,t,{readFile:n=s=>jr.statSync(s).size>la?null:jr.readFileSync(s,"utf8")}={}){let s=[],o=new Map,r=new Map;for(let g of e){let x=t.get(g.name);if(x){for(let I of x.files??[])s.push(I),r.has(I)||r.set(I,g.name);for(let I of x.nodes){let E=g.name+"\0"+I.filePath;o.has(E)||o.set(E,[]),o.get(E).push(I)}}}let i=new Map,c=g=>{if(i.has(g))return i.get(g);let x=null;try{x=Er(n(g)??"")}catch{x=null}return i.size>400&&i.clear(),i.set(g,x),x},a=new Map,l=(g,x)=>{let I=a.get(g);return I||(I=da(x),a.set(g,I)),I};function f(g,x,I){let E=c(g);if(E==null||I>3)return null;let M=Rr(x).exec(E);if(M)return{value:M[2],how:"constant"};for(let O of Cr(E)){let L=O.all?x:O.names?.get(x);if(!L)continue;let B=me(O.spec,g,s);if(B){let _=f(B,L,I+1);if(_)return _}}return null}function h(g,x,I,E){let M=c(g);if(M==null||E>3)return null;let O=_r(M,x,I);if(O!=null)return{value:O,how:"enum or object member"};for(let L of Cr(M)){let B=L.all?x:L.names?.get(x);if(!B)continue;let _=me(L.spec,g,s);if(_){let U=h(_,B,I,E+1);if(U)return U}}return null}function u(g,x,I){let E=String(g).trim().replace(/\s+as\s+[\w.<>[\]| ]+$/,"").replace(/!$/,"").trim(),M=/^\{\s*name\s*:\s*([\s\S]+?)\s*[,}]?\s*\}?$/.exec(E);M&&!/^['"`]/.test(E)&&(E=M[1].trim());let O=ua(E);if(O!==null)return O?{name:O,how:"literal"}:null;let L=new RegExp(`^(${le})$`).exec(E);if(L){let B=Rr(L[1]).exec(I);if(B)return{name:B[2],how:"constant in the same file"};let _=l(x,I).get(L[1]);if(_&&_.imported!=="*"){let U=me(_.spec,x,s);if(U){let V=f(U,_.imported==="default"?L[1]:_.imported,0);if(V)return{name:V.value,how:"imported constant"}}}return null}if(L=new RegExp(`^(${le})\\.(${le})$`).exec(E),L){let B=_r(I,L[1],L[2]);if(B!=null)return{name:B,how:"enum or object member in the same file"};let _=l(x,I).get(L[1]);if(_){let U=me(_.spec,x,s);if(U){let V=_.imported==="*"?f(U,L[2],0):h(U,_.imported==="default"?L[1]:_.imported,L[2],0);if(V)return{name:V.value,how:_.imported==="*"?"imported constant":"imported enum or object member"}}}}return null}let v=[];for(let g of s){let x=r.get(g);if(!x)continue;let I=null;try{I=n(g)}catch{I=null}if(I==null||!aa.test(I))continue;let E=Er(I);v.push({file:g,service:x,t:E,line:fa(E)})}let d=new Map,k=new Map,j=g=>{let x=[],I=new RegExp(`\\bclass\\s+(${le})(?:\\s+extends\\s+(${le}))?[^{]*\\{`,"g"),E;for(;E=I.exec(g);){let M=E.index+E[0].length-1,O=Zn(g,M);O>0&&x.push({name:E[1],base:E[2]??null,open:M,close:O,start:E.index})}return x};for(let g of v)g.classes=j(g.t);for(let g of v)for(let x of g.classes){let I=g.t.slice(x.open,x.close),E=/\bconstructor\s*\(/.exec(I);if(!E)continue;let M=ct(I,E.index+E[0].length-1);if(!M)continue;let O=M.args.map(B=>{let _=new RegExp(`(${le})\\s*[?:=]`).exec(B.text.replace(/^\s*(?:@\w+\([^)]*\)\s*)*(?:(?:private|public|protected|readonly)\s+)*/,""))??new RegExp(`(${le})\\s*$`).exec(B.text);return _?_[1]:null}),L=new RegExp(`new\\s+(?:Queue|Bull|BullQueue)\\s*(?:<[^>]*>)?\\s*\\(\\s*(${le})\\s*[,)]`).exec(I);L&&O.includes(L[1])&&d.set(x.name,{file:g.file,paramIndex:O.indexOf(L[1])})}for(let g of v)for(let x of g.classes){if(!x.base||!d.has(x.base))continue;let I=g.t.slice(x.open,x.close),E=/\bsuper\s*\(/.exec(I);if(!E)continue;let O=ct(I,E.index+E[0].length-1)?.args[d.get(x.base).paramIndex];if(!O)continue;let L=u(O.text,g.file,g.t);L&&k.set(x.name,{...L,how:L.how+" passed to the base class"})}let p=[],S=[],$=0,w=0;for(let g of v){let{file:x,service:I,t:E}=g,M=o.get(I+"\0"+x)??[],O=H=>ie(g.line(H),M),L=new Map,B=(H,te)=>{(!L.has(H)||L.get(H)===null&&te)&&L.set(H,te)},_,U=new RegExp("new\\s+(?:Queue|Bull|BullQueue)\\s*(?:<[^>]*>)?\\s*\\(","g");for(;_=U.exec(E);){let H=E.slice(Math.max(0,_.index-160),_.index),te=new RegExp(`(${le})\\s*(?::[^=;]+)?=\\s*$`).exec(H),J=ct(E,_.index+_[0].length-1);!te||!J||!J.args[0]||B(te[1],u(J.args[0].text,x,E))}let V=new RegExp("@InjectQueue\\s*\\(","g");for(;_=V.exec(E);){let H=ct(E,_.index+_[0].length-1);if(!H)continue;let te=E.slice(H.close+1,H.close+200),J=new RegExp(`^\\s*(?:(?:private|public|protected|readonly)\\s+)*(${le})`).exec(te);J&&B(J[1],H.args[0]?u(H.args[0].text,x,E):null)}let R=new RegExp(`(?:private|public|protected)\\s+(?:readonly\\s+)?(${le})\\s*:\\s*(${le})`,"g");for(;_=R.exec(E);)k.has(_[2])&&B(_[1],k.get(_[2]));let z=new RegExp(`(${le})\\s*\\.\\s*(add|addBulk)\\s*\\(`,"g");for(;_=z.exec(E);){let H=L.get(_[1]);if(H===void 0)continue;let te=O(_.index);if(!H){$++;continue}te&&p.push({queue:H.name,how:H.how,service:I,nodeId:te.id,line:g.line(_.index)})}let X=(H,te)=>{let J=H.trim();if(/^(?:async\s+)?(?:function\b|\([^)]*\)\s*(?::[^=]+)?=>|[\w$]+\s*=>)/.test(J))return{node:O(te+H.indexOf(J)),how:"inline handler"};let be=new RegExp(`^this\\.(${le})(?:\\.bind\\(this\\))?$`).exec(J),Ce=be?be[1]:new RegExp(`^(${le})$`).exec(J)?.[1];if(!Ce)return null;let dt=M.filter(ge=>ge.type!=="moduleRoot"&&(ge.name===Ce||String(ge.name).endsWith("."+Ce)));if(dt.length===1)return{node:dt[0],how:"named handler"};let Be=l(x,E).get(Ce);if(Be){let ge=me(Be.spec,x,s);if(ge){let Qe=(o.get(r.get(ge)+"\0"+ge)??[]).filter(ye=>ye.type!=="moduleRoot"&&ye.name===(Be.imported==="default"?Ce:Be.imported));if(Qe.length===1)return{node:Qe[0],how:"imported handler",service:r.get(ge)}}}return null},se=new RegExp("new\\s+Worker\\s*(?:<[^>]*>)?\\s*\\(","g");for(;_=se.exec(E);){let H=ct(E,_.index+_[0].length-1);if(!H||H.args.length<2)continue;let te=u(H.args[0].text,x,E);if(!te){w++;continue}let J=X(H.args[1].text,H.args[1].start);J?.node&&S.push({queue:te.name,how:te.how+", "+J.how,service:J.service??I,nodeId:J.node.id,line:g.line(_.index)})}let re=new RegExp(`(${le})\\s*\\.\\s*process\\s*\\(`,"g");for(;_=re.exec(E);){let H=L.get(_[1]);if(H===void 0)continue;if(!H){w++;continue}let J=ct(E,_.index+_[0].length-1)?.args.at(-1);if(!J)continue;let be=X(J.text,J.start);be?.node&&S.push({queue:H.name,how:H.how+", "+be.how,service:be.service??I,nodeId:be.node.id,line:g.line(_.index)})}let ut=new RegExp("@Processor\\s*\\(","g");for(;_=ut.exec(E);){let H=ct(E,_.index+_[0].length-1);if(!H||!H.args[0])continue;let te=u(H.args[0].text,x,E),J=g.classes.find(ye=>ye.start>H.close&&ye.start-H.close<400);if(!J)continue;if(!te){w++;continue}let be=g.line(J.open),Ce=g.line(J.close),dt=E.slice(J.open,J.close),Be=new Set(["process"]),ge=new RegExp(`@Process\\s*\\([^)]*\\)\\s*(?:(?:public|private|protected|async)\\s+)*(${le})\\s*\\(`,"g"),Qe;for(;Qe=ge.exec(dt);)Be.add(Qe[1]);for(let ye of M){if(ye.type==="moduleRoot"||ye.startLine<be||ye.endLine>Ce)continue;let N=String(ye.name).split(".").pop();Be.has(N)&&S.push({queue:te.name,how:te.how+", @Processor class method",service:I,nodeId:ye.id,line:ye.startLine})}}}let y=new Map;for(let g of S)y.has(g.queue)||y.set(g.queue,new Map),y.get(g.queue).set(g.nodeId,g);let m=[],b=new Set;for(let g of p.sort((x,I)=>x.queue<I.queue?-1:x.queue>I.queue?1:x.nodeId<I.nodeId?-1:x.nodeId>I.nodeId?1:x.line-I.line)){let x=y.get(g.queue);if(x)for(let I of[...x.values()].sort((E,M)=>E.nodeId<M.nodeId?-1:E.nodeId>M.nodeId?1:0)){if(I.nodeId===g.nodeId)continue;let E=[g.service,g.nodeId,I.service,I.nodeId,g.queue,g.line].join("\0");b.has(E)||(b.add(E),m.push({fromService:g.service,fromNodeId:g.nodeId,toService:I.service,toNodeId:I.nodeId,via:"queue",key:g.queue,queueName:g.queue,confidence:"inferred",reason:`queue "${g.queue}" (name from ${g.how}; consumer: ${I.how})`,line:g.line}))}}return{edges:m,stats:{producers:p.length,consumers:S.length,unresolvedProducers:$,unresolvedConsumers:w,files:v.length}}}function Pr(e,t){let n=new Map;for(let[s,o]of e){let r=t.filter(c=>c.filePath===s),i=o.rawSocketTypeChecks??[];for(let c of i){let a=ie(c.startLine,r);a&&n.set(c.eventName,a.id)}}return n}import pa from"node:fs";import ma from"node:path";function Mr(e){let t=["index.html","public/index.html","client/index.html","frontend/index.html","src/index.html"];for(let n of t){let s=ma.join(e,n);if(pa.existsSync(s))return s}return null}import cn from"node:fs";import an from"node:path";var ha=new Set(["node","tsx","ts-node","nodemon","bun","deno","ts-node-esm"]),ga=new Set(["watch","run","start","dev"]),ya=/\.[cm]?[jt]sx?$/,va=["start","dev","serve","run"];function wa(e){for(let t of String(e).split(/&&|\|\||;|\|/)){let n=t.trim().split(/\s+/).filter(Boolean).map(o=>o.replace(/^["']|["']$/g,"")),s=n.findIndex(o=>ha.has(an.basename(o).replace(/\.cmd$/,"")));if(!(s<0)){for(let o of n.slice(s+1))if(!(o.startsWith("-")||ga.has(o)||o.includes("="))){if(ya.test(o))return o;break}}}return null}var xa=e=>String(e).replace(/^@[^/]+\//,"");function Tr(e){let t;try{t=JSON.parse(cn.readFileSync(an.join(e,"package.json"),"utf8"))}catch{return[]}let n=[],s=(o,r,i={})=>{if(typeof o!="string"||!o)return;let c=r==="script"?null:tn(e,o,t);c?n.push({file:c.file,kind:r,...i,mappedFrom:o,mappedBy:c.how}):n.push({file:an.resolve(e,o),kind:r,...i})};if(typeof t.bin=="string")s(t.bin,"bin",{binName:xa(t.name??an.basename(e))});else if(t.bin&&typeof t.bin=="object")for(let[o,r]of Object.entries(t.bin))s(r,"bin",{binName:o});for(let o of va){let r=t.scripts?.[o]&&wa(t.scripts[o]);r&&s(r,"script")}return s(t.main,"main"),n}function Or(e){try{let t=cn.openSync(e,"r"),n=Buffer.alloc(120),s=cn.readSync(t,n,0,120,0);return cn.closeSync(t),/^#!.*\b(node|tsx|ts-node|bun)\b/.test(n.toString("utf8",0,s).split(/\r?\n/)[0])}catch{return!1}}import ln from"node:fs";import at from"node:path";var Sa=50,ka=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Ar=["",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts","/index.js","/index.ts","/index.mjs","/index.cjs","/index.tsx","/index.jsx"];function Qn(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=Qn(t);if(n)return n}return null}if(e&&typeof e=="object")for(let t of["import","node","require","default"]){let n=Qn(e[t]);if(n)return n}return null}function Fr(e,t){let n;try{n=JSON.parse(ln.readFileSync(at.join(e,"package.json"),"utf8"))}catch{return null}let s=n.exports,o=typeof s=="string"||Array.isArray(s)?s:s&&typeof s=="object"?s["."]??(Object.keys(s).some(l=>l.startsWith("."))?null:s):null,r=Qn(o)??(typeof n.module=="string"?n.module:null)??(typeof n.main=="string"?n.main:null);if(!r)return null;let i=new Set(t.map(l=>at.resolve(l))),c=at.resolve(e,r);for(let l of Ar)if(i.has(c+l))return t.find(f=>at.resolve(f)===c+l);let a=[];try{a=ln.readdirSync(e).filter(l=>ka.test(l)).sort()}catch{}for(let l of a){let f;try{f=ln.readFileSync(at.join(e,l),"utf8")}catch{continue}let h=/\bentry(?:Points)?\s*:\s*[\[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/.exec(f);if(!h)continue;let u=at.resolve(e,h[1]);for(let v of Ar)if(i.has(u+v))return t.find(d=>at.resolve(d)===u+v)}return null}function Br(e,t,n,s,o=null){let r=new Map;for(let k of n){let j=r.get(k.filePath);j||r.set(k.filePath,j=[]),j.push(k)}let i=new Map,c=(k,j)=>{j&&(!i.has(j.id)||k<i.get(j.id))&&i.set(j.id,k)},a=new Map,l=(k,j)=>{let p=a.get(k);if(!p){p=new Map;let S="";try{S=ln.readFileSync(k,"utf8")}catch{}for(let $ of S.matchAll(/^[ \t]*(?:export\s+)?const\s+([\w$]+)\s*(?::[^=\n]+)?=\s*([\w$]+)\s*(?:as\s+[^;\n]+)?;?[ \t]*$/gm))$[1]!==$[2]&&p.set($[1],$[2]);a.set(k,p)}return p.get(j)??null},f=(k,j)=>(r.get(k)??[]).find(p=>(p.type==="function"||p.type==="arrowFunction")&&p.name===j),h=(k,j)=>(r.get(k)??[]).filter(p=>p.type==="classMethod"&&p.className===j&&p.name!=="constructor"&&!/^[_#]/.test(p.name)),u=new Set;function v(k,j,p,S=0){let $=f(k,p);if($){c(j,$);return}let w=h(k,p);for(let I of w)c(`${j}.${I.name}`,I);if(w.length||!o)return;let y=o.resolveName(k,p);if(y){c(j,y);return}let m=o.bindingFor(k,p),b=m&&S<3?o.resolveImport(k,m.source,m.kind,m.imported):null;if(b?.file&&b.local&&b.local!=="default"&&l(b.file,b.local)){v(b.file,j,b.local,S+1);return}let g=o.classForImport(k,p);if(g?.className)for(let I of h(g.file,g.className))c(`${j}.${I.name}`,I);if(g?.className)return;let x=l(k,p);x&&S<3&&v(k,j,x,S+1)}function d(k,j,p){let S=k+"|"+(p?[...p.keys()].sort().join(","):"*");if(u.has(S)||j>3)return;u.add(S);let $=t.get(k)?.exportBindings;if(!$)return;let w=y=>!p||p.has(y);for(let[y,m]of Object.entries($.named??{}))w(y)&&v(k,p?.get(y)??y,m);$.default&&w("default")&&$.default!=="<anon>"&&v(k,p?.get("default")??$.default,$.default);for(let y of $.reexports??[]){if(!w(y.exported))continue;let m=me(y.source,k,s);m&&d(m,j+1,new Map([[y.imported,p?.get(y.exported)??y.exported]]))}for(let y of $.stars??[]){let m=me(y,k,s);m&&(p?d(m,j+1,p):d(m,j+1,null))}}return d(e,0,null),[...i].map(([k,j])=>({name:j,nodeId:k})).sort((k,j)=>k.name<j.name?-1:k.name>j.name?1:k.nodeId<j.nodeId?-1:1).slice(0,Sa)}import fn from"node:fs";import jt from"node:path";var eo=null,to=null,Dr=()=>eo?jt.join(eo,".canopy","last-stage.txt"):null,Hr=e=>{eo=e?jt.resolve(e):null},un=()=>to;function $a(){let e=process.memoryUsage(),t=n=>Math.round(n/1048576);return{rssMB:t(e.rss),heapUsedMB:t(e.heapUsed),externalMB:t(e.external),arrayBuffersMB:t(e.arrayBuffers)}}var ba=()=>process.env.CANOPY_DEBUG_MEM==="1"||process.env.CANOPY_DEBUG_MEM==="true";function Ge(e){to=e;let t=Dr();if(t)try{fn.mkdirSync(jt.dirname(t),{recursive:!0}),fn.writeFileSync(t,e)}catch{}if(ba()){let n=$a();process.stderr.write(`[mem] ${e}: rss ${n.rssMB} MB, heapUsed ${n.heapUsedMB} MB, external ${n.externalMB} MB, arrayBuffers ${n.arrayBuffersMB} MB
16
+ `)}}function zr(){to=null;let e=Dr();if(e)try{fn.rmSync(e,{force:!0})}catch{}}function Ur(e){try{return fn.readFileSync(jt.join(jt.resolve(e),".canopy","last-stage.txt"),"utf8").trim().slice(0,120)||null}catch{return null}}import qr from"node:path";import{fileURLToPath as Na}from"node:url";import{Parser as Wr,Language as Ia}from"web-tree-sitter";var id=qr.dirname(Na(globalThis.__canopyUrl("src/stage2_parse/initHtmlParser.js")));async function Gr(){await Wr.init();let e=new Wr,t=qr.join(Ot("tree-sitter-html"),"tree-sitter-html.wasm"),n=await Ia.load(t);return e.setLanguage(n),{parser:e,language:n}}function Jr(e,t){let s=go(t,"htmlScriptRoot.scm").matches(e.rootNode);for(let o of s){let r=o.captures.find(c=>c.name==="attr_name"),i=o.captures.find(c=>c.name==="script_src");if(r&&r.node.text==="src"&&i)return i.node.text}return null}function Yr(e,t,n){let s=[];e.forEach((a,l)=>{a.steps.forEach(f=>{if(!f.hasOwnSubTrace)return;let h=e.findIndex((u,v)=>v!==l&&u.steps[0]?.nodeId===f.nodeId);h!==-1&&s.push({fromWorkflowIndex:l,toWorkflowIndex:h,atNodeId:f.nodeId})})});let o=new Map;for(let a of t)o.set(a.id,a.serviceName??null);let r=new Map;function i(a,l,f,h){if(!a||!l||a===l)return;let u=`${a} -> ${l} -> ${f}`;r.has(u)?r.get(u).count+=1:r.set(u,{fromService:a,toService:l,viaMatchType:f,count:1});let v=r.get(u);h==="exact"?v.exact=(v.exact??0)+1:h==="inferred"?v.inferred=(v.inferred??0)+1:h==="resolved"&&(v.resolved=(v.resolved??0)+1)}for(let a of n){if(!a.resolved||!a.fromNodeId||!a.targetNodeId)continue;let l=o.get(a.fromNodeId)??null,f=o.get(a.targetNodeId)??null;i(l,f,a.matchType,a.confidence)}let c=Array.from(r.values());return{workflowLinks:s,serviceLinks:c}}var Ra=K.dirname(ja(globalThis.__canopyUrl("src/index.js"))),Vr=24*1e3*1e3;async function no(e,t={}){e=K.resolve(e),console.log(`
21
17
  Analyzing: ${e}
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(`
18
+ `);let n=Date.now(),s=()=>{let N=Math.round((Date.now()-n)/1e3);return N>=60?`${Math.floor(N/60)} min ${N%60} s`:`${N} s`},o=N=>{try{t.onProgress?.(N)}catch{}};Ge("finding source files"),console.log("Stage 1: finding source files...");let r=t.discovered??bt(e),i=r.files;_s(Ps(e,i)),console.log(` found ${i.length} files`);let{parser:c,language:a,grammars:l}=await ho();await mo({grammars:l},i),console.log(`
19
+ Stage 1b: partitioning files by service...`);let f=ps(e,i),h=ms(f,i,e);f=h.services,h.added&&console.log(` note: ${h.added.reason} (service "${h.added.name}")`),console.log(` detected ${f.length} services: ${f.map(N=>`${N.name} (${N.kind})`).join(", ")}`);let u=new Map(f.map(N=>[N.name,[]])),v=[];for(let N of i){let P=st(N,f);P?u.get(P).push(N):v.push(N)}console.log(" file partition:");for(let N of f)console.log(` ${N.name}: ${u.get(N.name).length} files`);console.log(` unassigned (shared/root-level): ${v.length} files`),v.length&&(console.log(" rule: these don't get their own Stage 5-7 run (no service of their own to have routes/listeners for) \u2014"),console.log(" each one is added to a service's parse scope ONLY if a file already in that"),console.log(" service actually imports it, so intra-service calls into shared code still resolve.")),console.log(`
20
+ Stage 2: parsing (all files, once \u2014 see note above)...`),Ge("reading files");let d=await vo(i,c,a,{onProgress:t.onProgress,grammars:l,noCache:!!t.noCache,say:o});function k(N){let P=new Set;for(let A of N){let C=d.get(A);if(C)for(let F of C.imports){let ce=me(F.source,A,i);ce&&v.includes(ce)&&P.add(ce)}}return[...P]}let j=new Map;for(let N of f){let P=u.get(N.name),A=k(P);j.set(N.name,[...P,...A]),console.log(` ${N.name}: ${P.length} own + ${A.length} shared file(s) pulled in by real imports = ${P.length+A.length} total scope`)}let p=f.filter(N=>!j.get(N.name)?.length);p.length&&(console.log(` excluding ${p.length} service(s) with 0 files: ${p.map(N=>N.name).join(", ")}`),f=f.filter(N=>j.get(N.name)?.length));let S=null,$=Mr(e);if($){let{parser:N,language:P}=await Gr(),A=he.readFileSync($,"utf-8"),C=N.parse(A),F=Jr(C,P);if(F){let ce=K.dirname($),D=K.join(ce,F);i.includes(D)&&(S=D,console.log(` found HTML root: ${F} -> ${D}`))}}let w=new Map,y=0,m=0,b=0;for(let N of f){let P=j.get(N.name);if(y++,Ge(`linking calls: service ${y} of ${f.length}`),o(`linking calls: service ${y} of ${f.length} (${s()})`),console.log(`
21
+ --- Service: ${N.name} (${N.kind}) \u2014 ${P.length} files in scope ---`),!P.length){console.log(" 0 files \u2014 nothing to trace for this service."),w.set(N.name,{nodes:[],resolvedEdges:[],workflows:[],routeIndex:new Map,eventIndex:new Map,rawEventIndex:new Map,parseResults:new Map});continue}let A=yo(new Map(P.map(T=>[T,d.get(T)]))),C=hs(A,f),F=gs(A,f);C=xs(C.concat(F)),console.log(` Stage 3: materialized ${F.length} inline-handler nodes before edge construction`);let ce=Ss(A,C),D=or(A,C),we=rr(A,C),Z=Pr(A,C);for(let T of P){let ee=new Set(A.get(T)?.exportedNames??[]);for(let Y of C.filter(q=>q.filePath===T))Y.exported=ee.has(Y.name)}let xe=Bs(ce,C,A,P,D,we,Z),Ne=xe.filter(T=>T.resolved).length;console.log(` Stage 4 (scoped): resolved ${Ne}/${xe.length} edges`);for(let T of P){let ee=A.get(T),Y=ee?.routes??[],q=ee?.listeners??[],oe=ae(T,C),Le=wt(T,ee?.imports??[],P),Tt=[];N.kind==="server"&&(Tt=ee?.socketListeners??[]),C=Hs(C,T,Y,q,oe,Tt,Le)}let Ee=C.filter(T=>T.isEntryPoint),et=Ee.filter(T=>T.trigger?.resolvedVia==="in-file").length,Xe=Ee.filter(T=>T.trigger?.resolvedVia==="cross-file").length,De=Ee.filter(T=>T.trigger?.resolvedVia==="inline").length;console.log(` Stage 5 entry points by resolution: in-file named ${et}, cross-file named (BUG A) ${Xe}, inline (BUG B) ${De}`);let Pt=xe.filter(T=>T.type!=="reference"&&!T.viaArgument),Mt=Us(C,Pt),tt=[];if(N.kind==="client"&&S&&P.includes(S)&&tt.push({id:`${S}::__module_root__`,name:"main",trigger:{type:"htmlRoot",label:"index.html script"}}),!tt.length){let T=Yt(N.rootPath,i),ee=T&&P.find(Y=>K.resolve(Y)===T.entry);ee&&(console.log(` found HTML root for ${N.name}: ${K.relative(e,T.indexHtml)} -> ${K.relative(e,ee)} (${T.via})`),tt.push({id:`${ee}::__module_root__`,name:"main",trigger:{type:"htmlRoot",label:"index.html script"}}))}let pt=[];if(N.kind==="server"){let T=K.join(N.rootPath,"package.json");if(he.existsSync(T))try{let ee=JSON.parse(he.readFileSync(T,"utf-8")),Y=ee.main;if(!Y&&ee.scripts?.start){let q=ee.scripts.start.match(/([\w./-]+\.(?:js|mjs|cjs|ts))/);q&&(Y=q[1])}if(Y){let q=K.resolve(N.rootPath,Y),oe=P.find(Le=>K.resolve(Le)===q);if(!oe){let Le=tn(N.rootPath,Y,ee);Le&&(oe=P.find(Tt=>K.resolve(Tt)===Le.file))}oe?pt.push({id:`${oe}::__module_root__`,name:"main",trigger:{type:"processBootstrap",label:`${Y} (package.json main)`}}):console.log(` note: ${N.name}'s package.json names "${Y}" as its entry, but that file isn't in this service's own traced scope \u2014 no bootstrap workflow added.`)}}catch{}}if(!tt.length){let T=new Set(pt.map(q=>q.id.split("::")[0])),ee=new Set;for(let q of xe)q.resolved&&q.fromNodeId.endsWith("::__module_root__")&&ee.add(q.fromNodeId);let Y=Tr(N.rootPath).map(q=>({...q,file:P.find(oe=>K.resolve(oe)===q.file)})).filter(q=>q.file);for(let q of P)Or(q)&&!Y.some(oe=>oe.file===q)&&Y.push({file:q,kind:"shebang"});for(let q of Y){if(T.has(q.file)||vt(K.relative(e,q.file))||!ee.has(`${q.file}::__module_root__`))continue;T.add(q.file);let oe=K.relative(N.rootPath,q.file).split(K.sep).join("/"),Le=q.kind==="bin"?`CLI: ${q.binName}`:`Start: ${oe}`;pt.push({id:`${q.file}::__module_root__`,name:"main",trigger:{type:"processBootstrap",label:`${oe} (${q.kind==="bin"?"package.json bin":q.kind==="script"?"package.json script":q.kind==="main"?"package.json main":"#! shebang"}${q.mappedFrom?`, built to ${q.mappedFrom}`:""})`,workflowName:Le}})}}let kt=[];if(tt.length+pt.length+Ee.filter(T=>!vt(K.relative(e,T.filePath))).length===0){let T=Fr(N.rootPath,P);if(T){let ee=K.relative(N.rootPath,T).split(K.sep).join("/"),q=Kt(C,A,oe=>wt(oe,A.get(oe)?.imports??[],P));for(let oe of Br(T,A,C,P,q))kt.push({id:oe.nodeId,name:C.find(Le=>Le.id===oe.nodeId)?.name??oe.name,trigger:{type:"publicApi",label:`${oe.name} (exported from ${ee})`,workflowName:`API: ${oe.name}`}});kt.length&&console.log(` public API of ${N.name}: ${kt.length} exported function(s)/method(s) from ${ee}`)}}let fo=new Set(kt.map(T=>T.id)),vi=fo.size?Mt.filter(T=>!fo.has(T.id)):Mt,kn=[...tt,...pt,...Ee,...kt,...vi];console.log(` Stage 5 total entry points: ${kn.length} (${tt.length} HTML root, ${pt.length} process bootstrap, ${Ee.length} pattern-matched, ${Mt.length} fallback)`);let wi=Un(xe),xi=Ys(kn,wi,C,Pt,8,Pt.length===xe.length?null:Un(Pt)),Si=new Set(Mt.map(T=>T.id)),ki=T=>T.trigger?"physical":Si.has(T.entryPointId)?"fallback":"hub",$i=xi.map(T=>({...T,origin:ki(T),steps:Vs(T.steps,C)})),bi=Ks($i),uo=Array.from(bi.values()).map(Zs),po=uo.filter(T=>!vt(K.relative(e,String(T.steps[0]?.nodeId??"").split("::")[0])));b+=uo.length-po.length;let mt=nr(po,{nodes:C});if(mt.some(T=>T.trigger)){let T=new Set(xe.filter(Y=>Y.type!=="returnValue"&&Y.type!=="reference").map(Y=>Y.fromNodeId)),ee=new Set(mt.filter(Y=>!Y.trigger&&Y.steps.length===1&&!T.has(Y.steps[0].nodeId)).map(Y=>Y.steps[0].nodeId));ee.size&&(mt=mt.filter(Y=>Y.trigger||!ee.has(Y.steps[0].nodeId)||Y.steps.length>1),m+=ee.size)}console.log(` Stage 6-7: -> ${mt.length} named workflows for ${N.name}`),w.set(N.name,{nodes:C,resolvedEdges:xe,routeIndex:D,eventIndex:we,rawEventIndex:Z,workflows:mt,parseResults:A,files:P,entryPointCount:kn.length})}console.log(`
22
+ --- Stage 5 (stitch): cross-service edge resolution ---`),Ge("linking services together"),o(`linking services together (${s()})`);let g=[],x=0,I=0;for(let N of f){let P=w.get(N.name);if(!P||!P.resolvedEdges.length)continue;let A=P.resolvedEdges.filter(C=>!C.resolved&&(C.type==="apiCall"||C.type==="socketEmit"||C.type==="rawSocketSend"));for(let C of A){let F=null,ce=null;for(let D of f){if(D.name===N.name)continue;let we=w.get(D.name);if(!we)continue;let Z=null;if(C.type==="apiCall"&&C.scope!=="external"?Z=we.routeIndex.get(xt(C.url)):C.type==="socketEmit"?Z=we.eventIndex.get(C.eventName):C.type==="rawSocketSend"&&(Z=we.rawEventIndex.get(C.eventName)),Z){F=Z,ce=D.name;break}}F?(g.push({fromService:N.name,fromNodeId:C.fromNodeId,toService:ce,toNodeId:F,via:C.type,key:C.url||C.eventName,confidence:"inferred",reason:"name-only match",...C.type==="apiCall"?{url:C.url}:{eventName:C.eventName}}),x++):I++}}console.log(` stitched ${x} cross-service edges`);let E=Ir(f,w,{repoRoot:e});for(let N of E.edges)g.push(N);console.log(` + ${E.edges.length} links from HTTP clients / WebSockets (${E.edges.filter(N=>N.confidence==="exact").length} exact, ${E.edges.filter(N=>N.confidence==="resolved").length} resolved)`),console.log(` ${I} unresolved calls remain unresolved even after checking every other service`);try{let N=Lr(f,w);for(let P of N.edges)g.push(P);console.log(` + ${N.edges.length} queue links (${N.stats.producers} producers, ${N.stats.consumers} consumers with a known queue name; ${N.stats.unresolvedProducers+N.stats.unresolvedConsumers} left unlinked because the queue name could not be known for sure)`)}catch(N){console.log(` queue links skipped: ${N?.message??N}`)}if(t.lowMemory)for(let N of d.values())for(let P of Object.keys(N))P!=="hadErrors"&&P!=="warnings"&&P!=="failed"&&P!=="skipped"&&P!=="errorMessage"&&delete N[P];let M=new Map;function O(N,P,A){if(!N||P==null||A==null)return{available:!1,reason:"no line range recorded for this node"};try{M.has(N)||(M.set(N,he.readFileSync(N,"utf-8").split(/\r\n|\n/)),M.size>256&&M.delete(M.keys().next().value));let C=M.get(N),F=Math.max(P,1),ce=Math.min(A,C.length);if(F>C.length)return{available:!1,reason:"recorded line range is past the end of the current file \u2014 source has likely moved"};let D=C.slice(F-1,ce).join(`
23
+ `);return{available:!0,filePath:N,startLine:F,endLine:ce,text:D}}catch(C){return{available:!1,reason:`source unavailable: ${C.code==="ENOENT"?"file not found (deleted or moved)":C.message}`}}}let L=/^(addEventListener|removeEventListener|on|once|postMessage|onmessage|subscribe)$/i,B=new Set(["call","methodCall","callSite"]),_=new WeakMap;function U(N,P){let A=_.get(N);if(!A||A.n!==N.length){A={n:N.length,by:new Map};for(let C of N){let F=A.by.get(C.fromNodeId);F||A.by.set(C.fromNodeId,F=[]),F.push(C)}_.set(N,A)}return A.by.get(P)??[]}function V(N,P,A,C,F=null){let ce=D=>!!(F&&!C&&!D.deferred&&D.resolved&&D.targetNodeId&&B.has(D.type)&&D.targetNodeId!==N&&F.inWorkflow.has(D.targetNodeId)&&!F.children.has(D.targetNodeId));return U(P,N).filter(D=>D.type!=="apiCall").filter(D=>D.resolved&&D.targetNodeId?ce(D):!!D.deferred===C).map(D=>{let we=D.type==="returnValue",Z=!we&&L.test(D.calleeNameRaw||""),xe=(D.branchPath??[]).map(Xe=>({...Xe,source:A?O(A,Xe.conditionLine,Xe.conditionLine):{available:!1,reason:"owning function's node not found"}})),Ne=D.objectNameRaw?`${D.objectNameRaw}.${D.calleeNameRaw}`:D.calleeNameRaw,Ee=we?Ne:D.firstArgText?`${Ne}(${D.firstArgText})`:Ne,et=ce(D);return{label:Ee,line:D.line??null,column:D.column??null,branchPath:xe,source:A?O(A,D.line,D.line):{available:!1,reason:"owning function's node not found"},tag:et?"called-elsewhere":we?"return-value":Z?"runtime-dispatched":"unresolvable-call-site",...et?{targetNodeId:D.targetNodeId}:{},reason:et?"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":Z?`registered via ${D.calleeNameRaw}(...) \u2014 the handler runs later, outside this function's own execution`:C?"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 R(N,P,A){return V(N,P,A,!0)}function z(N,P,A,C){return V(N,P,A,!1,C)}let X=[];for(let N of f){let P=w.get(N.name);if(!P)continue;let A=new Map(P.nodes.map(C=>[C.id,C]));for(let C of P.workflows){let F=new Set([N.name]),ce=new Set(C.steps.map(Z=>Z.nodeId)),D=new Map;for(let Z of C.steps)Z.parentNodeId!=null&&(D.get(Z.parentNodeId)??D.set(Z.parentNodeId,new Set).get(Z.parentNodeId)).add(Z.nodeId);let we=C.steps.map(Z=>{let xe=g.find(De=>De.via!=="queue"&&De.fromService===N.name&&De.fromNodeId===Z.nodeId),Ne=A.get(Z.nodeId),Ee=Z.parentNodeId?A.get(Z.parentNodeId):null,et=(Z.branchPath??[]).map(De=>({...De,source:Ee?O(Ee.filePath,De.conditionLine,De.conditionLine):{available:!1,reason:"owning function's node not found"}})),Xe={...Z,branchPath:et,source:Ne?O(Ne.filePath,Ne.startLine,Ne.endLine):{available:!1,reason:"node not found in this service's own graph"},alsoCallsRuntime:R(Z.nodeId,P.resolvedEdges,Ne?.filePath),inlineCalls:z(Z.nodeId,P.resolvedEdges,Ne?.filePath,{inWorkflow:ce,children:D.get(Z.nodeId)??new Set})};return xe&&(F.add(xe.toService),Xe.crossesInto=xe.toService),Xe});X.push({...C,steps:we,serviceId:N.name,servicesTouched:[...F]})}}console.log(`
24
+ Done: ${X.length} named workflows across all services
25
+ `),X.forEach(N=>console.log(` - [${N.serviceId}] ${N.name} (${N.steps.length} steps, ${N.occurrences} entry point(s))`)),Ge("writing the map"),o(`writing the map (${s()})`);let se=t.outputDir??process.env.CANOPY_OUTPUT_DIR??K.join(Ra,"..","output");he.existsSync(se)||he.mkdirSync(se,{recursive:!0});let re=Xt(e),ut=new Set(f.flatMap(N=>j.get(N.name)??[])),H=fs({discovered:r,parseResults:d,scopeFiles:ut,rel:re.rel,rootService:h.added});H.testWorkflowsExcluded=b,H.guessedWorkflowsDropped=m;let te={repoRoot:re.repoRoot,coverage:H};he.writeFileSync(K.join(se,"meta.js"),`const meta = ${JSON.stringify(te,null,2)};`),he.writeFileSync(K.join(se,"meta.json"),JSON.stringify(te,null,2)),console.log(`
26
+ `+Wt(H)),he.existsSync(K.join(se,"history.js"))||he.writeFileSync(K.join(se,"history.js"),"const canopyHistory = null;");let J=re.json(X,2),be=J.length>Vr;if(be&&(J=re.json(X)),be&&J.length>Vr){let N=Ds(JSON.parse(J));he.writeFileSync(K.join(se,"workflows.js"),`const workflows = ${N};`),he.rmSync(K.join(se,"workflows.json"),{force:!0}),console.log(`
27
+ workflows.json omitted (${(J.length/1e6).toFixed(1)} MB plain); workflows.js written with shared sub-structures (${(N.length/1e6).toFixed(1)} MB)`)}else he.writeFileSync(K.join(se,"workflows.json"),J),console.log(`
28
+ Saved to output/workflows.json`),he.writeFileSync(K.join(se,"workflows.js"),`const workflows = ${J};`),console.log("Saved to output/workflows.js (for the viewer)");let Ce=f.flatMap(N=>w.get(N.name)?.nodes??[]),dt=g.filter(N=>N.via!=="queue").map(N=>({fromNodeId:N.fromNodeId,targetNodeId:N.toNodeId,resolved:!0,matchType:"crossLayer",confidence:N.confidence})),Be=[...f.flatMap(N=>w.get(N.name)?.resolvedEdges??[]),...dt],ge=Yr(X,Ce,Be);ge.crossServiceEdges=g,he.writeFileSync(K.join(se,"systemGraph.js"),`const systemGraph = ${re.json(ge,2)};`);let Qe=f.map(({isRepoRoot:N,ownsLeftovers:P,...A})=>({...A,nodeCount:Ce.filter(C=>C.serviceName===A.name).length,workflowCount:X.filter(C=>C.serviceId===A.name).length}));he.writeFileSync(K.join(se,"services.js"),`const services = ${re.json(Qe,2)};`),console.log(`Saved to output/systemGraph.js (${ge.workflowLinks.length} workflow links, ${ge.serviceLinks.length} service links)`),console.log("Saved to output/services.js"),console.log(`
29
+ Note on output shape: workflows.json entries gained two additive fields (serviceId, servicesTouched) \u2014 every field the old shape had (steps, name, trigger, occurrences, ...) is unchanged, so the existing viewer keeps working without modification.`);let ye=new Map;for(let N of f){let P=w.get(N.name);if(!P)continue;let A=re.clone(P.nodes.map(F=>({id:F.id,name:F.name,type:F.type,filePath:F.filePath,bodyHash:F.bodyHash??null,startLine:F.startLine===0?0:F.startLine,endLine:F.endLine===Number.MAX_SAFE_INTEGER?null:F.endLine,serviceName:F.serviceName,isEntryPoint:!!F.isEntryPoint}))),C=ws(re.clone(P.resolvedEdges.map(F=>({fromNodeId:F.fromNodeId,targetNodeId:F.targetNodeId??null,type:F.type,callKind:F.callKind,calleeNameRaw:F.calleeNameRaw,eventName:F.eventName,url:F.url,line:F.line??null,column:F.column??null,resolved:!!F.resolved,matchType:F.matchType??null}))));ye.set(N.name,{nodes:A,edges:C})}return{workflows:X,perService:w,crossServiceEdges:g,services:f,publicGraph:ye,publicWorkflows:re.clone(X),publicCrossServiceEdges:re.clone(g),fingerprint:Vt(vs(i,re.rel)),analyzedFileCount:i.length,repoRoot:re.repoRoot,coverage:H}}var _a=process.argv[1]&&globalThis.__canopyUrl("src/index.js")===Ea(K.resolve(process.argv[1])).href;_a&&no(process.argv[2]||process.cwd()).catch(e=>{console.error("Pipeline failed:",e),process.exit(1)});var La=fe.join(fe.dirname(Xr(globalThis.__canopyUrl("src/history/sync.js"))),"..","..","output"),Pa=["workflows.json","workflows.js","systemGraph.js","services.js","meta.js","meta.json","history.js"],Ma=fe.dirname(Xr(globalThis.__canopyUrl("src/history/sync.js"))).split(fe.sep).includes("node_modules"),Je=e=>process.env.CANOPY_OUTPUT_DIR||(Ma&&e?fe.join(fe.resolve(e),".canopy","output"):La);async function Ta(e,t){let n=console.log;console.log=()=>{};try{return await no(e,t)}finally{console.log=n}}function Oa(e){try{let t=JSON.parse(Ke.readFileSync(fe.join(Je(e),"meta.json"),"utf8"));return t.coverage&&fe.resolve(t.repoRoot)===fe.resolve(e)?t.coverage:null}catch{return null}}async function Aa(e,{full:t=!1}={}){let n=fe.resolve(e),s=Xt(n),o=bt(n),r=await Fo(n,o.files,s.rel,{full:t});return{fingerprint:Vt(r.hashes),reused:r.reused,rehashed:r.rehashed,discovered:o}}async function Fa(e,{keep:t,say:n=()=>{},full:s=!1}){let o=Date.now(),r=nt(e),i=r.versions[r.versions.length-1],c=await Aa(e,{full:s}),a=c.fingerprint,l=!!i&&i.fingerprint===a&&(s||i.engineVersion!==At()||i.outputFormat!==wo);if(i&&i.fingerprint===a&&!l&&!s){try{Co(e,Je(e))}catch{}return{status:"no-changes",version:i,ms:Date.now()-o,coverage:Oa(e),fast:c}}let f=Ke.mkdtempSync(fe.join(Ca.tmpdir(),"canopy-sync-"));try{let h=await Ta(e,{outputDir:f,onProgress:n,lowMemory:!0,noCache:s,discovered:c.discovered});Ge("storing the version"),n(`storing the version (${Math.round((Date.now()-o)/1e3)} s)`);let u=Do(h),v=Bo(u),d={nodes:u.nodes.length,edges:u.edges.length,workflows:u.workflows.length,physicalWorkflows:u.workflows.filter(m=>m.tier==="physical").length,crossServiceEdges:u.crossServiceEdges.length},k=To(e),j=So(e,v,u,d,t,{refresh:l,protect:k?[k.version]:[]}),p=xo();p&&n("history: "+p);let S=Ie(e,["rev-parse","--abbrev-ref","HEAD"]),$=Ie(e,["rev-parse","HEAD^{tree}"]);Mo(e,{engineFingerprint:At(),projectRoot:fe.resolve(e),lastAnalysed:{version:j.version,fingerprint:j.fingerprint,headSha:j.headSha,treeHash:$,branch:S}});let w=await import("./chunk-SR4HILUN.js").catch(()=>null);w&&w.writeHistoryJs(e,f);let y=Je(e);Ke.mkdirSync(y,{recursive:!0});for(let m of Pa)Ke.existsSync(fe.join(f,m))?Ke.copyFileSync(fe.join(f,m),fe.join(y,m)):Ke.rmSync(fe.join(y,m),{force:!0});try{Ge("building the search index"),n(`building the search index (${Math.round((Date.now()-o)/1e3)} s)`),_o(e,y)}catch(m){n("the search index could not be built: "+String(m.message).split(`
30
+ `)[0]+" (the map is fine; search falls back to the traced nodes)")}return{status:"new-version",version:j,ms:Date.now()-o,coverage:h.coverage}}finally{Ke.rmSync(f,{recursive:!0,force:!0})}}function Ba(e,t=()=>{}){let n=Oo(e);if(!n.ok){let s=Ao(e);t(`The saved history in .canopy was damaged (${n.problems[0]}). It was moved to .canopy/${s} and Canopy is starting a fresh one; this run rebuilds everything.`)}Po(e,At())}async function dn(e,{keep:t=Ft,say:n=console.log,full:s=!1}={}){if(e=fe.resolve(e),Bt(e),Ke.mkdirSync(pe(e).root,{recursive:!0}),Ba(e,n),!Io(e,process.env.CANOPY_VERSION??null,n))return Eo(e),n("sync already running - one rerun queued"),{status:"queued"};let o;try{do o=await Fa(e,{keep:t,say:n,full:s}),s=!1,o.status==="no-changes"?n(`no changes (v${o.version.version} ${o.version.fingerprint.slice(0,7)}) [${o.ms} ms]`):n(`v${o.version.version} ${o.version.fingerprint.slice(0,7)} stored: ${o.version.counts.nodes} nodes, ${o.version.counts.edges} edges, ${o.version.counts.workflows} workflows, ${(o.version.bytes/1024/1024).toFixed(2)} MB${o.version.gzip?" (gzip)":""} [${o.ms} ms]`),o.coverage&&n(`
31
+ `+Wt(o.coverage));while(Ro(e))}finally{jo(e)}return o}import ue from"node:fs";import Re from"node:path";import{spawn as Da}from"node:child_process";import{fileURLToPath as Ha}from"node:url";var Et="# >>> canopy sync (managed block - do not edit) >>>",Qr="# <<< canopy sync <<<",lt=["post-commit","post-merge"],za=globalThis.__canopyBundle??Re.join(Re.dirname(Ha(globalThis.__canopyUrl("src/history/hooks.js"))),"..","cli.js"),Ua=e=>Re.resolve(e).split(Re.sep).join("/");function Rt(e){let t=Ie(e,["rev-parse","--git-path","hooks"]);if(!t)throw new Error(`not a git repository: ${e}`);return Re.resolve(e,t)}var Kr=JSON.parse(ue.readFileSync(Re.join(Pe,"package.json"),"utf8")),Wa=Kr.name+"@"+Kr.version,Zr=e=>Ua(e).replace(/(["$`\\])/g,"\\$1");function pn(e){return[Et,"(",` if command -v canopy >/dev/null 2>&1; then canopy sync --background "${Zr(e)}" >/dev/null 2>&1 </dev/null`,` elif command -v npx >/dev/null 2>&1; then ( npx --yes ${Wa} sync --background "${Zr(e)}" >/dev/null 2>&1 </dev/null & )`,' else echo "canopy not found; skipping map update"'," fi",") || true",Qr].join(`
35
32
  `)+`
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(`
33
+ `}var mn=()=>new RegExp(`\\n?${Et.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}[\\s\\S]*?${Qr.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\n?`);function _t(e){let t=Rt(e);ue.mkdirSync(t,{recursive:!0});let n=[];for(let s of lt){let o=Re.join(t,s),r=ue.existsSync(o)?ue.readFileSync(o,"utf8"):null,i;r===null?i=`#!/bin/sh
34
+ `+pn(e):mn().test(r)?i=r.replace(mn(),()=>`
35
+ `+pn(e)):i=r+(r.endsWith(`
39
36
  `)?"":`
40
37
  `)+`
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,`
38
+ `+pn(e),ue.writeFileSync(o,i.replace(/\r\n/g,`
39
+ `));try{ue.chmodSync(o,493)}catch{}n.push(o)}return n}function ei(e){let t=Rt(e),n=[];for(let s of lt){let o=Re.join(t,s);if(!ue.existsSync(o))continue;let r=ue.readFileSync(o,"utf8");if(!mn().test(r))continue;let i=r.replace(mn(),`
40
+ `);i.replace(/^#!.*\n?/,"").trim()===""?ue.rmSync(o,{force:!0}):ue.writeFileSync(o,i.replace(/\n{3,}/g,`
44
41
 
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,`
42
+ `)),n.push(o)}return n}function ti(e){if(!ue.existsSync(Re.resolve(e)))return null;let t=pe(e);ue.mkdirSync(t.root,{recursive:!0});let n=ue.openSync(t.log,"a");ue.writeSync(n,`
46
43
  --- ${new Date().toISOString()} sync requested (pid ${process.pid})
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})
44
+ `);let s=Object.fromEntries(Object.entries(process.env).filter(([r])=>!/^GIT_/i.test(r)||r.toUpperCase()==="GIT_EXEC_PATH")),o=Da(process.execPath,[za,"sync",Re.resolve(e)],{detached:!0,stdio:["ignore",n,n],windowsHide:!0,env:s});return o.unref(),ue.closeSync(n),o.pid}function ni(e){let t=Rt(e),n=pn(e),s=0,o=0;for(let r of lt){let i=Re.join(t,r);if(!ue.existsSync(i))continue;let c=ue.readFileSync(i,"utf8").replace(/\r\n/g,`
45
+ `);c.includes(Et)&&(s++,c.includes(n)&&o++)}return s<lt.length?"absent":o===lt.length?"current":"outdated"}import Oe from"node:fs";import Ye from"node:path";import{execFileSync as oi}from"node:child_process";function hn(e){let t=[],n=(s,o,r,i)=>{let c=!1,a="";try{let l=r();c=l===!0||!!(l&&l.ok),a=l&&l.detail?l.detail:""}catch(l){a=String(l.message??l).split(`
46
+ `)[0]}t.push({name:s,critical:o,ok:c,detail:a,fix:i})};return n("Node version >= 18",!0,()=>({ok:Number(process.versions.node.split(".")[0])>=18,detail:"v"+process.versions.node}),"install Node 18 or newer from https://nodejs.org and run canopy again"),n("tree-sitter grammars (wasm)",!0,()=>{let s=[["web-tree-sitter","web-tree-sitter.wasm"],["tree-sitter-javascript","tree-sitter-javascript.wasm"],["tree-sitter-typescript","tree-sitter-typescript.wasm"],["tree-sitter-typescript","tree-sitter-tsx.wasm"],["tree-sitter-html","tree-sitter-html.wasm"]],o=s.filter(([r,i])=>!Oe.existsSync(Ye.join(Ot(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=[Ye.join(Pe,"src","stage2_parse","queries"),Ye.join(Pe,"dist","queries")].find(r=>Oe.existsSync(r))??Ye.join(Pe,"dist","queries"),o=Oe.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=pe(e).root;Oe.mkdirSync(s,{recursive:!0});let o=Ye.join(s,`.doctor-${process.pid}`);return Oe.writeFileSync(o,"x"),Oe.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:!!oi("git",["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}),detail:oi("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:Oe.existsSync(Ye.join(Pe,"ui-react","index.html"))&&Oe.existsSync(Ye.join(Pe,"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=Rt(e),o=lt.every(r=>Oe.existsSync(Ye.join(s,r))&&Oe.readFileSync(Ye.join(s,r),"utf8").includes(Et));return{ok:o,detail:o?"post-commit, post-merge":""}},`canopy hook install "${e}"`),t}function si(e,t,n,s=console.log){s(`canopy ${n} doctor (${t})
63
47
  `);for(let r of e)s(`${r.ok?"OK ":"FAIL"} ${r.name}${r.detail?" - "+r.detail:""}${r.ok?"":`
64
48
  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
49
+ ${o.length?`${o.length} critical problem(s) - fix them and run canopy doctor again`:"all critical checks passed"}`),o.length}import de from"node:fs";import Za from"node:net";import Qa from"node:os";import Ve from"node:path";import el from"node:readline";function so({stream:e=process.stdout,env:t=process.env,flags:n={},platform:s=process.platform}={}){let o=!!e.isTTY,r="NO_COLOR"in t&&t.NO_COLOR!==""||!!n["no-color"]||n.color===!1||t.TERM==="dumb",i=o&&!r&&!n.quiet,c=i&&t.TERM!=="linux"&&(s!=="win32"||!!(t.WT_SESSION||t.TERM_PROGRAM||t.ConEmuANSI==="ON"||t.ANSICON)||/UTF-?8/i.test(`${t.LC_ALL??""}${t.LC_CTYPE??""}${t.LANG??""}`));return{tty:o,color:i,rich:i,unicode:c,columns:Math.max(40,Math.min(e.columns||80,200)),quiet:!!n.quiet}}var oo={unicode:{ok:"\u2714",fail:"\u2716",line:"\u2502",top:"\u250C",cap:"\u2514",done:"\u25CF",bad:"\u25A0",spin:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],full:"\u2588",empty:"\u2591",arrow:"\u2192",dot:"\xB7"},ascii:{ok:"[ok]",fail:"[x]",line:"|",top:"+",cap:"+",done:"*",bad:"x",spin:["|","/","-","\\"],full:"#",empty:"-",arrow:"->",dot:"-"}},qa=(e,t,n)=>e?`\x1B[${t}m${n}\x1B[0m`:n,ri=e=>e<59500?`${(e/1e3).toFixed(1)} s`:`${Math.floor(e/6e4)} min ${String(Math.round(e%6e4/1e3)).padStart(2,"0")} s`,Ga=e=>!Number.isFinite(e)||e<0?"":e<1?"< 1 s":e<60?`${Math.round(e)} s`:`${Math.floor(e/60)} min ${Math.round(e%60)} s`;function Ja({done:e,total:t,unit:n="files",elapsedMs:s,width:o=24,sym:r=oo.ascii}){let i=t>0?Math.min(1,e/t):0,c=Math.round(i*o),a=s>500?e/(s/1e3):0,l=a>0?(t-e)/a:NaN,f=r.full.repeat(c)+r.empty.repeat(o-c),h=String(Math.floor(i*100)).padStart(3)+"%";return`[${f}] ${h} ${e.toLocaleString("en-US")}/${t.toLocaleString("en-US")} ${n}${a?` ${Math.round(a).toLocaleString("en-US")} ${n}/s`:""}${l===l&&i<1?` ETA ${Ga(l)}`:""}`}function ii({stream:e=process.stdout,caps:t=so({stream:e}),now:n=()=>Date.now(),interval:s=80,onExitHook:o=!0}={}){let r=t.unicode?oo.unicode:oo.ascii,i=(R,z)=>qa(t.color,R,z),c=R=>i("2",R),a=R=>i("32",R),l=R=>i("31",R),f=R=>i("1",R),h=R=>i("36",R),u=null,v=!0,d=!1,k=null,j=0,p=null,S=!1,$=!1,w=-1,y="",m=R=>{try{e.write(R)}catch{}},b=()=>{t.rich&&!$&&(m("\x1B[?25l"),$=!0)},g=()=>{$&&(m("\x1B[?25h"),$=!1)},x=()=>{S&&(m("\r\x1B[2K"),S=!1)},I=R=>R.replace(/\u001b\[[0-9;?]*[A-Za-z]/g,"").length;function E(R){let z=u.title,X=R(z),se=t.columns-1;I(X)>se&&(z=z.replace(/\s*\(.*\)\s*$/,""),X=R(z));let re=I(X)-se;if(re>0){let ut=t.unicode?"\u2026":"...";z=z.slice(0,Math.max(6,z.length-re-ut.length))+ut,X=R(z)}return X}function M(){let R=i("36",r.spin[j%r.spin.length]);return E(k?z=>` ${R} ${z} ${Ja({done:k.done,total:k.total,unit:k.unit,elapsedMs:n()-k.started,width:Math.max(8,Math.min(24,t.columns-66)),sym:r})}`:z=>` ${R} ${z}${y?c(" "+y):""} ${c(ri(n()-u.started))}`)}function O(){!t.rich||!u||(b(),m(`\r\x1B[2K${M()}`),S=!0)}let L=()=>{j++,O()},B=()=>{t.rich&&s>0&&!p&&(p=setInterval(L,s),p.unref?.())},_=()=>{p&&(clearInterval(p),p=null)};function U(R=!0){if(!u)return;_();let z=ri(n()-u.started);t.rich&&(x(),m(` ${R?a(r.done):l(r.bad)} ${u.title} ${c(z)}
50
+ `)),v=v&&R,u=null,k=null,y="",w=-1,g()}let V={caps:t,line(R=""){t.quiet||(t.rich&&S?(x(),m(R+`
51
+ `),O()):m(R+`
52
+ `))},say(R){if(t.quiet)return;let z=/^\[(\d+)\/(\d+)\] (.*?)\.\.\.$/.exec(R);if(!t.rich){let X=String(R);z?(d=!0,m(`${r.line}
53
+ ${r.done} ${X}
54
+ `)):/^\s{6}\S/.test(X)?m(`${r.line}${X.slice(1)}
55
+ `):m(X+`
56
+ `);return}if(z){U(!0),d||(m(` ${a(r.top)}
57
+ `),d=!0),m(` ${v?a(r.line):l(r.line)}
58
+ `),u={n:+z[1],total:+z[2],title:z[3],started:n()},j=0,O(),B();return}if(/^\s{6}\S/.test(R)){V.line(` ${c(r.line)} ${c(String(R).trim())}`);return}V.line(String(R))},important(R){t.rich&&S?(x(),m(R+`
59
+ `),O()):m(String(R)+`
60
+ `)},banner(R,z,X){if(!t.quiet){if(!t.rich){m(`${R} ${z} - ${X}
61
+ `);return}m(`
62
+ ${f(h(R))} ${c("v"+z)} ${c(r.dot)} ${X}
63
+
64
+ `)}},progress(R,z,X="files",se="reading files"){if(t.quiet)return;if(t.rich){k=k??{started:n()},Object.assign(k,{done:R,total:z,unit:X}),p||O();return}let re=z>0?Math.floor(R/z*10):0;re!==w&&(w=re,m(`${r.line} ${se}: ${R} of ${z}
65
+ `))},endProgress(){k=null,w=-1},status(R){t.quiet||(t.rich?(k=null,y=R,O()):m(`${r.line} ${R}
66
+ `))},endStep:U,tick:L,close(){!d||t.quiet||(U(!0),d=!1,t.rich?m(` ${v?a(r.line):l(r.line)}
67
+ ${v?a(r.cap):l(r.cap)}
68
+ `):m(`${r.line}
69
+ ${r.cap}
70
+ `))},final({url:R,changes:z=null,update:X=null,hint:se="press Ctrl+C to stop"}){if(U(!0),t.quiet){m(R+`
71
+ `);return}if(!t.rich){V.close();return}V.close(),m(`
72
+ ${a(r.ok)} ${f("Canopy is ready")}
73
+
74
+ ${c("Local:")} ${h(R)}
75
+ `),z&&m(` ${c("Since last visit:")} ${z}
76
+ `),X&&m(` ${c("Update:")} ${X}
77
+ `),m(`
78
+ ${c(se)}
79
+ `)},restore(){_(),S&&x(),g()}};if(o&&t.rich){let R=()=>V.restore();process.once("exit",R);for(let z of["SIGINT","SIGTERM"])process.once(z,()=>{R(),process.exit(z==="SIGINT"?130:143)})}return V}import St from"node:fs";import Ya from"node:http";import ro from"node:path";var ft=e=>ro.join(pe(e).root,"server.json"),ci=e=>ro.join(pe(e).root,"server.lock");function Va(e,{timeoutMs:t=1500}={}){return new Promise(n=>{let s=Ya.get({host:"127.0.0.1",port:e,path:"/api/health",headers:{host:`127.0.0.1:${e}`},timeout:t},o=>{let r="";o.on("data",i=>{r+=i}),o.on("end",()=>{try{let i=JSON.parse(r);n(o.statusCode===200&&i.ok&&i.app==="canopy"?i:null)}catch{n(null)}})});s.on("timeout",()=>{s.destroy(),n(null)}),s.on("error",()=>n(null))})}var Xa=e=>{try{return Lo(e)?.projectId??null}catch{return null}};async function Ka(e){let t=null;try{t=JSON.parse(St.readFileSync(ft(e),"utf8"))}catch{return null}let s=t&&Number.isInteger(t.pid)&&t.pid!==process.pid&&ko(t.pid)&&Number.isInteger(t.port)?await Va(t.port):null;if(!(s&&(!t.projectId||!s.projectId||t.projectId===s.projectId))){try{St.rmSync(ft(e),{force:!0})}catch{}return null}return{...t,url:`http://127.0.0.1:${t.port}/`}}async function gn(e,t,{waitMs:n=6e3}={}){let s=Date.now()+n;for(;;){let o=await Ka(e);if(o)return{ok:!1,running:o};if(bo(ci(e),{},t).ok)return{ok:!0};if(Date.now()>s)return{ok:!1,running:null,busy:!0};await new Promise(i=>setTimeout(i,150))}}function yn(e,{port:t,version:n,navToken:s=null}){let o={pid:process.pid,port:t,startedAt:new Date().toISOString(),version:n,projectId:Xa(e),...s?{navToken:s}:{}},r=ft(e)+"."+process.pid+".tmp";St.mkdirSync(ro.dirname(ft(e)),{recursive:!0}),St.writeFileSync(r,JSON.stringify(o,null,2),{mode:384}),St.renameSync(r,ft(e));let i=()=>{try{$o(ft(e))?.pid===process.pid&&St.rmSync(ft(e),{force:!0})}catch{}No(ci(e))};return process.once("exit",i),{unregister:i}}var ai=Number(process.env.CANOPY_MIN_FREE_MB)||300,tl=".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 nl(e){let t=!!Ie(e,["rev-parse","--git-dir"]),n=Ve.join(e,".gitignore"),s=de.existsSync(n);if(!t&&!s)return"skipped";let o=s?de.readFileSync(n,"utf8"):"";if(o.split(/\r?\n/).some(i=>/^\/?\.canopy\/?$/.test(i.trim())))return"already";let r=/\r\n/.test(o)?`\r
66
80
  `:`
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(`
81
+ `;return de.appendFileSync(n,(o&&!/\r?\n$/.test(o)?r:"")+"# Canopy (code map output)"+r+".canopy/"+r),s?"added":"created"}var li=e=>Ve.join(pe(e).root,"prefs.json"),fi=e=>{try{return JSON.parse(de.readFileSync(li(e),"utf8"))}catch{return{}}};function wn(e,t){let n={...fi(e),...t};for(let s of Object.keys(n))n[s]===void 0&&delete n[s];de.mkdirSync(pe(e).root,{recursive:!0}),de.writeFileSync(li(e),JSON.stringify(n,null,2))}function ol(e){return new Promise(t=>{let n=Za.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 sl(e){try{let t=de.statfsSync(e);return Math.floor(t.bavail*t.bsize/1048576)}catch{return null}}var rl=()=>!!(process.stdin.isTTY&&process.stdout.isTTY)||!!process.env.CANOPY_ASSUME_TTY;function il(e,t){return new Promise(n=>{let s=el.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 cl(e){try{return JSON.parse(de.readFileSync(Ve.join(e,"meta.json"),"utf8"))}catch{return null}}function al(e){try{return JSON.parse(de.readFileSync(Ve.join(e,"services.js"),"utf8").replace(/^\s*const services\s*=\s*/,"").replace(/;\s*$/,""))}catch{return[]}}var ll=e=>`How did it go? ${e.canopyFeedbackUrl||"see FEEDBACK.md in the README (about 20 minutes)"}`;async function ui(e){let{startViewer:t,openBrowser:n,viewerProblem:s}=await import("./chunk-LLZJOZFY.js"),o=e.say?null:ii({caps:so({flags:{quiet:e.quiet,"no-color":e.noColor}})}),r=e.say??(d=>o.say(d)),i=d=>o?o.important(d):r(d),{pkg:c}=e,a=null;try{return await l()}catch(d){if(o?.endStep(!1),o?.restore(),d instanceof vn){if(i(d.line),a)try{de.rmdirSync(a)}catch{}return d.code}return i(`Canopy stopped because of an unexpected problem: ${String(d.message??d).split(`
68
82
  `)[0]}
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(`
83
+ Run "canopy doctor", then send its output and .canopy/sync.log to whoever gave you Canopy.`),process.env.CANOPY_DEBUG&&r(d.stack),1}async function l(){let d=Ve.resolve(e.target??process.cwd());o?o.banner("Canopy",c.version,"a map of what your JavaScript / TypeScript code does"):r(`Canopy ${c.version} - a map of what your JavaScript / TypeScript code does`),r(`Folder: ${Ve.basename(d)||d}
84
+ `),r("[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 k=de.existsSync(d)&&de.statSync(d).isDirectory();de.existsSync(d)||$e(1,`That folder does not exist: ${d}. Check the spelling, or run canopy inside your project folder.`),k||$e(1,`${d} is a file, not a folder. Run canopy on the folder that contains it: canopy "${Ve.dirname(d)}"`);let j=de.existsSync(pe(d).root),p=hn(d);j||(a=pe(d).root);let S=p.find(R=>R.critical&&!R.ok);S&&$e(1,`${S.name} failed${S.detail?" ("+S.detail+")":""}. ${S.fix}.`.replace(/\.\.$/,"."));let $=!!Ie(d,["rev-parse","--git-dir"]),w=p.find(R=>R.name==="git available")?.ok,y=s();y&&!e.noOpen&&$e(1,`Canopy cannot show the map: ${y.replace(/\n\s*/g,". ")}.`);let m=sl(d);if(m!==null&&m<ai&&$e(1,`Only ${m} MB free on the disk holding ${d}; Canopy needs about ${ai} MB. Free some space and run canopy again.`),!e.noOpen){let R=await ol(e.port??0);R.ok||$e(1,R.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 (${R.code||R.message}). Check your firewall or security software and run canopy again.`)}r(` Node ${process.versions.node}, ${w?"git found":"git not found (no version history or commit hook)"}, ${m===null?"disk space not checked":m+" MB free"}${e.noOpen?"":", a local port is free"}.`),r("[2/6] Looking at your project..."),de.readdirSync(d).filter(R=>R!==".git"&&R!==".canopy").length===0&&$e(1,`${d} is empty. Add some JavaScript or TypeScript code and run canopy again.`);let g=Tn(d);g.length===0&&$e(3,`No JavaScript or TypeScript files found in ${d}. Canopy currently supports JavaScript and TypeScript (${tl}); other languages are not read yet.
85
+ What to try next: run canopy inside the folder that holds your .js / .ts code (for a monorepo, the folder of one package), or pass it: canopy <folder>.`);let x=$&&Ie(d,["rev-parse","--verify","-q","HEAD"])!==null;r(` ${g.length.toLocaleString("en-US")} JavaScript / TypeScript file${g.length===1?"":"s"}. ${$?x?"Git repository.":"Git repository with no commits yet (that is fine).":"Not a git repository (that is fine; version-aware features are limited)."}`),r("[3/6] Preparing the output folder..."),de.mkdirSync(pe(d).root,{recursive:!0}),Bt(d);let I=nl(d),E={added:"added .canopy/ to .gitignore",created:"created .gitignore with .canopy/ in it",already:".canopy/ is already in .gitignore",skipped:"no git repository, so no .gitignore change"}[I];r(` Map output goes to ${Ve.join(d,".canopy")} (${E}).`),r("[4/6] Commit hook..."),await f(d,$);let M=nt(d).versions.length>0;r(`[5/6] ${M?"Checking what changed since last time":"Building your map for the first time (a big project can take a few minutes)"}...`);let O=await h(d,g.length);u(d,O);let L=null;try{L=qo(Wo(d))}catch{L=null}L&&!(o&&o.caps.rich)&&r(` ${L}.
86
+ `);let B=Je(d);if(e.noOpen)return r("[6/6] Not opening the map (--no-open). To view it later: canopy open"),v(),0;r("[6/6] Opening the map...");let _=await gn(d,c.version);if(!_.ok&&_.running){let R=_.running.url,z=n(R);return o&&o.caps.quiet?(o.final({url:R}),0):(r(` Canopy is already running for this project (started ${_.running.startedAt?.replace("T"," ").slice(0,16)??"earlier"}): ${R}`),r(z?" Opened it in your browser. Nothing else was started.":" Open that address in your browser. Nothing else was started."),(!o||!o.caps.rich)&&v(),0)}_.ok||$e(1,"Another Canopy is just starting for this project. Wait a few seconds and run canopy again, or open the address it printed.");let U;try{U=await t(B,e.port??0,{repoRoot:d}),yn(d,{port:U.port,version:c.version,navToken:U.navToken})}catch(R){$e(1,`Canopy cannot start the viewer: ${R.code||R.message}. ${R.code==="EADDRINUSE"?"Pick another port with --port=NUMBER.":"Check your firewall or security software."}`)}let V=n(U.url);return o&&o.caps.rich?o.final({url:U.url,changes:L,update:bn(c.version),hint:V?"your browser should open now; press Ctrl+C to stop":"open that address in your browser; press Ctrl+C to stop"}):o&&o.caps.quiet?o.final({url:U.url}):(r(` ${U.url}`),r(V?" Your browser should open now. If it does not, paste that address into one.":" Open that address in your browser."),v()),e.forSeconds?(await new Promise(R=>setTimeout(R,e.forSeconds*1e3)),U.server.close(),o?.restore(),0):((!o||!o.caps.rich)&&r("Press Ctrl+C to stop."),await new Promise(()=>{}),0)}async function f(d,k){if(e.noHook){r(" Commit hook skipped (--no-hook).");return}if(!k){r(" No git repository here, so there is no commit hook to set up.");return}if(!fl()){r(" git is not installed, so the commit hook is skipped.");return}let j;try{j=ni(d)}catch(S){r(" Could not look at the git hooks ("+String(S.message).split(`
87
+ `)[0]+"); skipping the commit hook.");return}if(j==="current"){r(" The map already updates on every commit.");return}if(j==="outdated"){try{_t(d),r(" Refreshed the commit hook (it now matches this Canopy).")}catch(S){r(" Could not refresh the commit hook: "+String(S.message).split(`
88
+ `)[0])}return}if(fi(d).hook==="declined"&&!e.yes){r(" The commit hook is off (you chose that earlier). Turn it on with: canopy hook install");return}let p=!0;if(e.yes)r(" Update the map on every commit? [Y/n] Y (--yes)");else if(!rl())r(" Update the map on every commit? [Y/n] Y (default; no terminal to ask)");else{let S=await il(" Update the map on every commit? [Y/n] ","Y");p=/^y(es)?$/i.test(S)}if(!p){wn(d,{hook:"declined"}),r(" Okay, no hook. Turn it on any time with: canopy hook install");return}try{_t(d),wn(d,{hook:void 0}),r(" Done: after every commit and merge the map updates itself in the background (it never blocks or fails a commit). Remove it with: canopy hook uninstall")}catch(S){r(" Could not install the commit hook: "+String(S.message).split(`
89
+ `)[0]+". Continuing without it.")}}async function h(d,k){let j=Date.now(),p=w=>{let y=String(w),m=/parsing: (\d+)\/(\d+) files/.exec(y);if(m){let b=Number(m[1]);o?o.progress(b,Number(m[2])):r(` reading files: ${m[1]} of ${m[2]}`);return}/^(linking calls|linking services|writing the map|storing the version|building the search index)/.test(y)&&(o?(o.endProgress(),o.status(y)):r(` ${y}`))};r(` Reading ${k.toLocaleString("en-US")} file${k===1?"":"s"}, linking calls, finding entry points, tracing workflows...`);let S;for(let w=0;w<2&&(S=await dn(d,{say:y=>p(y),onProgress:p,full:!!e.full}).catch(y=>$e(1,`The analysis failed: ${String(y.message??y).split(`
74
90
  `)[0]}
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
91
+ Run "canopy doctor" and send its output with ${Ve.join(d,".canopy","sync.log")} to whoever gave you Canopy.`)),S.status==="queued");w++){r(" Another update is already running; waiting for it to finish...");for(let y=0;y<1200&&de.existsSync(pe(d).lock);y++)await new Promise(m=>setTimeout(m,500))}S.status==="queued"&&$e(1,"Another Canopy update is still running. Wait for it to finish and run canopy again."),o?.endProgress();let $=((Date.now()-j)/1e3).toFixed(1);return r(S.status==="no-changes"?` Nothing changed since version ${S.version.version} (${$} s).`:` Saved version ${S.version.version} (${$} s).`),S}function u(d,k){let j=Je(d),p=k.coverage??cl(j)?.coverage,S=al(j),$=k.version.counts??{};if(r(`
92
+ Your map`),r(` services: ${S.length}${S.length?" ("+S.map(w=>w.id??w.name).slice(0,8).join(", ")+(S.length>8?", ...":"")+")":""}`),r(` workflows: ${$.workflows??"?"}${$.physicalWorkflows!==void 0?` (${$.physicalWorkflows} traced from real code, ${$.workflows-$.physicalWorkflows} guessed)`:""}`),p){let w=p.analyzed?Math.round(p.inService/p.analyzed*100):0;r(` files inside a service: ${p.inService} of ${p.analyzed} (${w}%)`),r(` files with parse errors: ${p.parseErrors}${p.parseErrors?" ("+p.parseErrorFiles.slice(0,3).join(", ")+(p.parseErrorFiles.length>3?", ...":"")+")":""}`),p.notAnalyzedTotal&&r(` not read yet: ${p.notAnalyzedTotal} files in languages Canopy does not support (${Object.entries(p.notAnalyzed).map(([y,m])=>`${m} ${y}`).join(", ")})`)}S.length||r(" The map is empty: Canopy found no entry points (routes, listeners, a main file) it recognises in this project."),r("")}function v(){o&&o.close(),r("Next time just run `canopy`.");let d=bn(c.version);d&&r(d),r(ll(c))}}function fl(){return!!Ie(Qa.tmpdir(),["--version"])}import xn from"node:fs";import di from"node:os";import Ze from"node:path";import{spawn as ul}from"node:child_process";var io="CANOPY_CHILD",dl=2048,pl=8192,pi=1024*1024;function ml({env:e=process.env,nodeOptions:t=e.NODE_OPTIONS??"",totalmem:n=di.totalmem()}={}){let s=Number(e.CANOPY_MAX_MEMORY_MB);if(Number.isFinite(s)&&s>=256)return{mb:Math.floor(s),source:"CANOPY_MAX_MEMORY_MB"};let o=/--max-old-space-size[= ](\d+)/.exec(t);return o?{mb:null,userMb:Number(o[1]),source:"NODE_OPTIONS"}:{mb:Math.max(dl,Math.min(pl,Math.floor(n*.75/pi))),source:"75% of this computer's memory"}}var hl=new Set(["version","help","update","hook","install-hook","uninstall-hook","doctor","history","diff","open","mcp","install","uninstall"]);function co(e){if(e.some(s=>s==="--version"||s==="--help"||s==="-v"||s==="-h"))return!1;let n=e.filter(s=>!s.startsWith("-"))[0];return n===void 0?!0:hl.has(n)?!1:n==="sync"?!e.includes("--background"):xn.existsSync(Ze.resolve(n))||/^[.~]|[\\/]/.test(n)}function Sn(e,t=process.cwd()){let n=e.filter(s=>!s.startsWith("-"));return n[0]==="sync"?Ze.resolve(n[1]??t):Ze.resolve(n[0]??t)}var gl=/heap out of memory|Allocation failed|JavaScript heap|FatalProcessOutOfMemory|out of memory/i;function yl({code:e,signal:t,stderrTail:n="",platform:s=process.platform}){if(gl.test(n))return{kind:"memory",why:"Node reported that it ran out of memory"};if(t==="SIGINT"||t==="SIGTERM"||t==="SIGHUP")return null;if(t==="SIGABRT")return{kind:"memory",why:"the process aborted (usually out of memory)"};if(t==="SIGKILL")return{kind:"killed",why:"the system stopped the process (usually because the computer ran out of memory)"};if(t==="SIGSEGV"||t==="SIGBUS")return{kind:"crash",why:"the process crashed"};if(e==null)return t?{kind:"crash",why:`the process ended on signal ${t}`}:{kind:"crash",why:"the process ended without an exit code"};let o=e>>>0;if(s==="win32"){if(o>=3221225472)return{kind:o===3221226505?"memory":"crash",why:`Windows reported error 0x${o.toString(16).toUpperCase()} (a fatal stop, usually out of memory)`};if(o>255)return{kind:"crash",why:`the process ended with the unusual code ${o}`}}return e===134?{kind:"memory",why:"the process aborted (exit code 134, usually out of memory)"}:e===137?{kind:"killed",why:"the system stopped the process (exit code 137, usually out of memory)"}:e===139||e===135?{kind:"crash",why:`the process crashed (exit code ${e})`}:null}function vl(e,{projectRoot:t,stage:n,memory:s}){let o=[],r=e.kind==="memory"?"Canopy ran out of memory":e.kind==="killed"?"Canopy was stopped by the system, most likely because the computer ran out of memory":"Canopy stopped unexpectedly";return o.push(`${r}${n?` while it was working on: ${n}`:""}.`),o.push(` (${e.why}.)`),o.push(""),o.push("What to try next:"),o.push(" 1. Analyse one part of the project at a time: canopy <folder of a package or app>"),o.push(` 2. Give Canopy more memory: set CANOPY_MAX_MEMORY_MB (it used ${s?.mb??s?.userMb??"the default"} MB), for example CANOPY_MAX_MEMORY_MB=${Math.min(16384,Math.max(4096,(s?.mb??4096)*2))} canopy`),o.push(" 3. Close other programs, then run it again: the files already read are remembered, so the second run is faster."),t&&o.push("",`Details for a bug report (no code or secrets): ${Ze.join(".canopy","last-error.txt")} in the project folder.`),o.join(`
93
+ `)}function ao(e,{version:t,stage:n,code:s,signal:o,memory:r,totalmem:i=di.totalmem()}){try{let c=Ze.join(e,".canopy");xn.mkdirSync(c,{recursive:!0});let a=[`time: ${new Date().toISOString()}`,`engine version: ${t}`,`stage: ${n??"unknown"}`,`exit: ${o?"signal "+o:s}`,`memory ceiling: ${r?.mb??"left to NODE_OPTIONS"+(r?.userMb?" ("+r.userMb+" MB)":"")} MB (${r?.source??"?"}); computer memory ${Math.round(i/pi)} MB`,""].join(`
94
+ `);return xn.writeFileSync(Ze.join(c,"last-error.txt"),a),Ze.join(c,"last-error.txt")}catch{return null}}function mi(e){let{args:t,scriptPath:n,version:s="?",env:o=process.env,projectRoot:r=Sn(t),execPath:i=process.execPath,execArgv:c=process.execArgv,spawnFn:a=ul,platform:l=process.platform,err:f=process.stderr,onChild:h=null}=e,u=e.memory??ml({env:o}),v=[...u.mb?[`--max-old-space-size=${u.mb}`]:[],...c.filter(d=>!d.startsWith("--max-old-space-size")),n,...t];return new Promise(d=>{let k="",j=a(i,v,{env:{...o,[io]:"1"},stdio:["inherit","inherit","pipe"],windowsHide:!1});h?.(j),j.stderr?.on("data",m=>{try{f.write(m)}catch{}k=(k+m.toString("utf8")).slice(-4e3)});let p=m=>()=>{try{j.kill(m)}catch{}},S=p("SIGTERM");process.on("SIGTERM",S);let $=process.stdin.isTTY?()=>{}:p("SIGINT");process.on("SIGINT",$);let w=!1,y=(m,b)=>{if(w)return;w=!0,process.off("SIGTERM",S),process.off("SIGINT",$);let g=yl({code:m,signal:b,stderrTail:k,platform:l});if(!g){d(m??(b?1:0));return}let x=Ur(r);ao(r,{version:s,stage:x,code:m,signal:b,memory:u});try{xn.rmSync(Ze.join(r,".canopy","last-stage.txt"),{force:!0})}catch{}try{f.write(`
95
+ `+vl(g,{projectRoot:r,stage:x,memory:u})+`
96
+ `)}catch{}d(1)};j.on("error",m=>{try{f.write(`Canopy could not start its worker process: ${String(m.message).split(`
97
+ `)[0]}
98
+ `)}catch{}y(1,null)}),j.on("close",(m,b)=>y(m,b))})}var Fe=JSON.parse(lo.readFileSync(Ct.join(Pe,"package.json"),"utf8")),wl={"-y":"--yes","-h":"--help","-v":"--version"},hi=process.argv.slice(2).map(e=>wl[e]??e),ne=Object.fromEntries(hi.filter(e=>e.startsWith("--")).map(e=>{let[t,n]=e.slice(2).split("=");return[t,n??!0]})),je=hi.filter(e=>!e.startsWith("--")),_e=je.shift(),xl=e=>/^v?\d+$/.test(e??""),Ae=()=>Ct.resolve(je[0]&&!xl(je[0])?je.shift():process.cwd()),gi=`canopy ${Fe.version} - a map of what your JavaScript / TypeScript code does
77
99
 
78
100
  usage: canopy [path] [-y] [--no-open] do everything in order: check this computer, look at the project, prepare .canopy/,
79
101
  offer the commit hook, build the map, open it in your browser (default path: current folder)
@@ -85,14 +107,29 @@ usage: canopy [path] [-y] [--no-open] do everything in order: check this com
85
107
  diff [path] [from] [to] what changed between two versions [--json]
86
108
  hook install [path] run "canopy sync" in the background after every commit and merge (safe to repeat)
87
109
  hook uninstall [path] remove it again
110
+ mcp [path] a read-only MCP server (stdio) that lets your own AI tool search and read the map; Canopy never calls an AI service
111
+ install [path] [--yes] connect Claude Code / Cursor / Gemini CLI to it: shows the project files it will write, then asks [Y/n]; "uninstall" removes them
88
112
  update [--check] look up the newest version on npm (the only command that uses the network); "update" installs it with npm
89
113
  --version, --help
90
114
 
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),
92
- --port=N, --for=SECONDS (stop the viewer by itself after that time)
115
+ options for the one-command path: -y / --yes (do not ask; install the hook), --no-hook (do not install the hook, do not ask),
116
+ --no-open (build the map but do not start the viewer), --port=N, --for=SECONDS (stop the viewer by itself after that time),
117
+ --full (ignore everything remembered and analyse from scratch), --quiet (only problems and the address), --no-color (also: NO_COLOR=1)
118
+ Memory: a whole analysis gets about 75% of this computer's memory (2-8 GB). CANOPY_MAX_MEMORY_MB=<number> sets it; CANOPY_DEBUG_MEM=1 prints the memory at each stage.
93
119
  Exit codes: 0 ok, 1 a problem (the message says what to do), 3 no JavaScript / TypeScript files found.
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}
120
+ Node >= 18 required. Output lives in <path>/.canopy/ (kept out of git automatically).`;async function Sl(){let e=Ae(),t=Je(e);lo.existsSync(Ct.join(t,"workflows.js"))||(console.error(`no map yet for ${e}
121
+ fix: canopy sync "${e}"`),process.exit(1));let{startViewer:n,viewerProblem:s}=await import("./chunk-LLZJOZFY.js"),o=s();o&&(console.error(o),process.exit(1));let r=await gn(e,Fe.version);if(!r.ok&&r.running){console.log(`canopy map for ${e}
122
+ ${r.running.url}
123
+ already running for this project (started ${r.running.startedAt??"earlier"}); nothing else was started`);return}r.ok||(console.error("another canopy is just starting for this project; wait a few seconds and try again"),process.exit(1));let{server:i,url:c,port:a,navToken:l}=await n(t,ne.port?Number(ne.port):0,{repoRoot:e});if(yn(e,{port:a,version:Fe.version,navToken:l}),console.log(`canopy map for ${e}
124
+ ${c}`),ne.for){console.log(`serving for ${Number(ne.for)} s`),await new Promise(f=>setTimeout(f,Number(ne.for)*1e3)),i.close();return}console.log("press Ctrl+C to stop"),await new Promise(()=>{})}function kl(){let e=Ae();process.exit(si(hn(e),e,Fe.version)?1:0)}var Lt={async sync(){let e=Ae();if(ne.background){let n=ti(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=ne.keep?Number(ne.keep):Ft;await dn(e,{keep:t,full:!!ne.full})},open:Sl,async doctor(){kl()},async mcp(){let e=Ae(),{runMcp:t}=await import("./chunk-WCTNLSYC.js");await t({repoRoot:e,outDir:Je(e),version:Fe.version})},async install(){let{installCommand:e}=await import("./chunk-JZZ4VDNH.js");process.exit(await e(Ae(),{yes:!!ne.yes}))},async uninstall(){let{uninstallCommand:e}=await import("./chunk-JZZ4VDNH.js");process.exit(await e(Ae()))},async update(){process.exit(await Go({check:!!ne.check,version:Fe.version}))},async diff(){let e=Ae(),t=nt(e);if(t.versions.length<2){console.log(t.versions.length?"only one version so far - nothing to diff yet":"no versions yet - run: canopy sync");return}let n=i=>{let c=Number(String(i).replace(/^v/,"")),a=t.versions.find(l=>l.version===c);if(!a)throw new Error(`no such version: ${i} (have ${t.versions.map(l=>"v"+l.version).join(", ")})`);return a},s=je[1]!==void 0?n(je[1]):t.versions[t.versions.length-1],o=je[0]!==void 0?n(je[0]):t.versions[t.versions.indexOf(s)-1];if(!o)throw new Error("no earlier version to compare against");let r=Ho($n(e,o),$n(e,s));console.log(ne.json?zo(r):Uo(r,s,o))},async"install-hook"(){let e=Ae(),t=_t(e);wn(e,{hook:void 0}),console.log("installed canopy block in: "+t.join(", "))},async"uninstall-hook"(){let e=ei(Ae());console.log(e.length?"removed canopy block from: "+e.join(", "):"no canopy hook block found")},async hook(){let e=je.shift();if(e==="install")return Lt["install-hook"]();if(e==="uninstall")return Lt["uninstall-hook"]();console.error("usage: canopy hook install|uninstall [path]"),process.exit(2)},async history(){let e=Ae(),t=nt(e);if(!t.versions.length)return console.log("no versions yet - run: canopy sync");for(let n of t.versions)console.log(`v${n.version} ${n.fingerprint.slice(0,7)} ${n.createdAt} ${n.headSha?n.headSha.slice(0,7):"-------"}${n.dirty?"*":" "} ${n.headMessage?JSON.stringify(n.headMessage):""} nodes ${n.counts.nodes} edges ${n.counts.edges} workflows ${n.counts.workflows} ${(n.bytes/1024).toFixed(0)} KB${n.gzip?" gz":""}`)}};Number(process.versions.node.split(".")[0])<18&&(console.error(`Canopy needs Node 18 or newer, and this is Node ${process.versions.node}.
125
+ What to try next: install the current LTS from https://nodejs.org (or run: nvm install --lts), open a new terminal, and run canopy again.`),process.exit(1));process.env[io]!=="1"&&process.env.CANOPY_NO_RESPAWN!=="1"&&co(process.argv.slice(2))&&process.exit(await mi({args:process.argv.slice(2),scriptPath:process.argv[1],version:Fe.version}));var yi=e=>{let t=String(e?.message??e).split(`
126
+ `)[0].slice(0,200),n=Sn(process.argv.slice(2));ao(n,{version:Fe.version,stage:un(),code:1,memory:{mb:null,source:"this run"}}),console.error(`Canopy stopped unexpectedly${un()?" while it was working on: "+un():""}.
127
+ (${t})
128
+
129
+ What to try next:
130
+ 1. canopy doctor checks Node, the grammars and write access
131
+ 2. canopy <folder> try one package or app at a time
132
+ 3. run it again: the files already read are remembered
133
+ Details for a bug report (no code or secrets): .canopy/last-error.txt in the project folder.`),process.exit(1)};process.on("uncaughtException",yi);process.on("unhandledRejection",yi);co(process.argv.slice(2))&&Hr(Sn(process.argv.slice(2)));process.on("exit",()=>zr());(ne.version||_e==="version")&&(console.log(Fe.version),process.exit(0));(ne.help||_e==="help")&&(console.log(gi),process.exit(0));if(_e===void 0||!Lt[_e]&&(lo.existsSync(Ct.resolve(_e))||/^[.~]|[\\/]/.test(_e))){_e!==void 0&&je.unshift(_e);let e=await ui({target:je[0]?Ct.resolve(je[0]):process.cwd(),yes:!!ne.yes,noOpen:!!ne["no-open"],quiet:!!ne.quiet,noColor:!!ne["no-color"],noHook:!!ne["no-hook"],full:!!ne.full,port:ne.port?Number(ne.port):void 0,forSeconds:ne.for?Number(ne.for):void 0,pkg:Fe});process.exit(e)}Lt[_e]||(console.error(`unknown command: ${_e}
97
134
 
98
- ${Za}`),process.exit(2));tn[Me]().catch(e=>{console.error(e.stack||e.message),process.exit(1)});
135
+ ${gi}`),process.exit(2));Lt[_e]().catch(e=>{console.error(e.stack||e.message),process.exit(1)});