canopy-engine 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/FEEDBACK.md +46 -0
  2. package/LICENSE +24 -0
  3. package/README.md +171 -2
  4. package/dist/canopy.js +87 -0
  5. package/dist/queries/arrowFunctions.scm +5 -0
  6. package/dist/queries/callExpressions.scm +2 -0
  7. package/dist/queries/classMethods.scm +6 -0
  8. package/dist/queries/exports.scm +9 -0
  9. package/dist/queries/fetchApiCalls.scm +15 -0
  10. package/dist/queries/functionDeclarations.scm +4 -0
  11. package/dist/queries/htmlScriptRoot.scm +5 -0
  12. package/dist/queries/imports.scm +3 -0
  13. package/dist/queries/jsxElements.scm +5 -0
  14. package/dist/queries/matchExtensionListeners.scm +62 -0
  15. package/dist/queries/matchFastifyRoutes.scm +28 -0
  16. package/dist/queries/methodCalls.scm +4 -0
  17. package/dist/queries/rawSocketSend.scm +26 -0
  18. package/dist/queries/rawSocketTypeCheck.scm +20 -0
  19. package/dist/queries/returns.scm +2 -0
  20. package/dist/queries/socketEmit.scm +8 -0
  21. package/dist/queries/socketOn.scm +19 -0
  22. package/dist/queries/typescript/arrowFunctions.scm +15 -0
  23. package/dist/queries/typescript/classMethods.scm +65 -0
  24. package/dist/queries/typescript/defaultExports.scm +6 -0
  25. package/dist/queries/typescript/exports.scm +16 -0
  26. package/dist/queries/typescript/imports.scm +8 -0
  27. package/package.json +91 -4
  28. package/ui-react/dist/bundle.css +2 -0
  29. package/ui-react/dist/bundle.js +108 -0
  30. package/ui-react/index.html +19 -0
  31. package/vendor/tree-sitter-html/package.json +6 -0
  32. package/vendor/tree-sitter-html/tree-sitter-html.wasm +0 -0
  33. package/vendor/tree-sitter-javascript/package.json +6 -0
  34. package/vendor/tree-sitter-javascript/tree-sitter-javascript.wasm +0 -0
  35. package/vendor/tree-sitter-typescript/package.json +6 -0
  36. package/vendor/tree-sitter-typescript/tree-sitter-tsx.wasm +0 -0
  37. package/vendor/tree-sitter-typescript/tree-sitter-typescript.wasm +0 -0
package/dist/canopy.js ADDED
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
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
+ 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 Oa=Object.create;var Zn=Object.defineProperty;var Ma=Object.getOwnPropertyDescriptor;var Ha=Object.getOwnPropertyNames;var Da=Object.getPrototypeOf,Ua=Object.prototype.hasOwnProperty;var wt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Ba=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},za=(e,t)=>{for(var n in t)Zn(e,n,{get:t[n],enumerable:!0})},Wa=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ha(t))!Ua.call(e,o)&&o!==n&&Zn(e,o,{get:()=>t[o],enumerable:!(r=Ma(t,o))||r.enumerable});return e};var qa=(e,t,n)=>(n=e!=null?Oa(Da(e)):{},Wa(t||!e||!e.__esModule?Zn(n,"default",{value:e,enumerable:!0}):n,e));var dr=Ba((jf,sn)=>{function rr(e){return Array.isArray(e)?e:[e]}var Ga=void 0,eo="",nr=" ",Qn="\\",Ja=/^\s+$/,Ka=/(?:[^\\]|^)\\$/,Va=/^\\!/,Ya=/^\\#/,Xa=/\r?\n/g,Za=/^\.{0,2}\/|^\.{1,2}$/,Qa=/\/$/,St="/",sr="node-ignore";typeof Symbol<"u"&&(sr=Symbol.for("node-ignore"));var ir=sr,kt=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),ec=/([0-z])-([0-z])/g,ar=()=>!1,tc=e=>e.replace(ec,(t,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?t:eo),nc=e=>e.startsWith("!")||e.startsWith("\\^")?`^${e.slice(e[0]==="!"?1:2)}`:e,oc=e=>{let{length:t}=e;return e.slice(0,t-t%2)},rc=[[/^\uFEFF/,()=>eo],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?nr:eo)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+nr}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*(?:\\\*\\\*\\\/)+/,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>{let r=n.replace(/\\\*/g,"[^\\/]*");return t+r}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Qn],[/\\\\/g,()=>Qn],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,o)=>t===Qn?`\\[${n}${oc(r)}${o}`:o==="]"&&r.length%2===0?`[${nc(tc(n))}${r}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],sc=/(^|\\\/)?\\\*$/,At="regex",on="checkRegex",or="_",ic={[At](e,t){return`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`},[on](e,t){return`${t?`${t}[^/]*`:"[^/]*"}(?=$|\\/$)`}},ac=e=>rc.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),rn=e=>typeof e=="string",cc=e=>e&&rn(e)&&!Ja.test(e)&&!Ka.test(e)&&e.indexOf("#")!==0,lc=e=>e.split(Xa).filter(Boolean),to=class{constructor(t,n,r,o,s,i){this.pattern=t,this.mark=n,this.negative=s,kt(this,"body",r),kt(this,"ignoreCase",o),kt(this,"regexPrefix",i)}get regex(){let t=or+At;return this[t]?this[t]:this._make(At,t)}get checkRegex(){let t=or+on;return this[t]?this[t]:this._make(on,t)}_make(t,n){let r=this.regexPrefix.replace(sc,ic[t]),o=this.ignoreCase?new RegExp(r,"i"):new RegExp(r);return kt(this,n,o)}},dc=({pattern:e,mark:t},n)=>{let r=!1,o=e;o.indexOf("!")===0&&(r=!0,o=o.substr(1)),o=o.replace(Va,"!").replace(Ya,"#");let s=ac(o);return new to(e,t,o,n,r,s)},no=class{constructor(t){this._ignoreCase=t,this._rules=[]}_add(t){if(t&&t[ir]){this._rules=this._rules.concat(t._rules._rules),this._added=!0;return}if(rn(t)&&(t={pattern:t}),cc(t.pattern)){let n=dc(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,rr(rn(t)?lc(t):t).forEach(this._add,this),this._added}test(t,n,r){let o=!1,s=!1,i;this._rules.forEach(l=>{let{negative:c}=l;s===c&&o!==s||c&&!o&&!s&&!n||!l[r].test(t)||(o=!c,s=c,i=c?Ga:l)});let a={ignored:o,unignored:s};return i&&(a.rule=i),a}},fc=(e,t)=>{throw new t(e)},We=(e,t,n)=>rn(e)?e?We.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${t}\``,TypeError),cr=e=>Za.test(e);We.isNotRelative=cr;We.convert=e=>e;var oo=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:r=!1}={}){kt(this,ir,!0),this._rules=new no(n),this._strictPathCheck=!r,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(t){return this._rules.add(t)&&this._initCache(),this}addPattern(t){return this.add(t)}_test(t,n,r,o){let s=t&&We.convert(t);return We(s,t,this._strictPathCheck?fc:ar),this._t(s,n,r,o)}checkIgnore(t){if(!Qa.test(t))return this.test(t);let n=t.split(St).filter(Boolean);if(n.pop(),n.length){let r=this._t(n.join(St)+St,this._testCache,!0,n);if(r.ignored)return r}return this._rules.test(t,!1,on)}_t(t,n,r,o){if(t in n)return n[t];if(o||(o=t.split(St).filter(Boolean)),o.pop(),!o.length)return n[t]=this._rules.test(t,r,At);let s=this._t(o.join(St)+St,n,r,o);return n[t]=s.ignored?s:this._rules.test(t,r,At)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return rr(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},ro=e=>new oo(e),uc=e=>We(e&&We.convert(e),e,ar),lr=()=>{let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");We.convert=e;let t=/^[a-z]:\//i;We.isNotRelative=n=>t.test(n)||cr(n)};typeof process<"u"&&process.platform==="win32"&&lr();sn.exports=ro;ro.default=ro;sn.exports.isPathValid=uc;kt(sn.exports,Symbol.for("setupWindows"),lr)});import vr from"node:fs";import Qe from"node:path";import{fileURLToPath as Nc}from"node:url";function je(e){let t=Qe.join(re,"vendor",e);if(bt()&&vr.existsSync(t))return t;for(let n=re;;n=Qe.dirname(n)){let r=Qe.join(n,"node_modules",e);if(vr.existsSync(r))return r;if(Qe.dirname(n)===n)break}return Qe.join(re,"node_modules",e)}var re,bt,Le=wt(()=>{re=Qe.join(Qe.dirname(Nc(globalThis.__canopyUrl("src/utils/pkgPath.js"))),"..","..");bt=()=>re.split(Qe.sep).includes("node_modules")});import Et from"node:fs";import Me from"node:path";import wd from"node:crypto";import{fileURLToPath as Sd}from"node:url";function Bo(e){let t=[];for(let n of Et.readdirSync(e,{withFileTypes:!0}).sort((r,o)=>r.name<o.name?-1:1)){let r=Me.join(e,n.name);n.isDirectory()?t.push(...Bo(r)):/\.(js|scm)$/.test(n.name)&&t.push(r)}return t}function On(){if(Uo)return Uo;let e=wd.createHash("sha256");if(!Et.existsSync(Do)&&globalThis.__canopyBundle){let t=globalThis.__canopyBundle;e.update("bundle\0").update(Et.readFileSync(t));let n=Me.join(Me.dirname(t),"queries");if(Et.existsSync(n))for(let r of Bo(n))e.update(Me.relative(n,r).split(Me.sep).join("/")).update("\0").update(Gi(r)).update("\0")}else for(let t of Bo(Do))e.update(Me.relative(Do,t).split(Me.sep).join("/")).update("\0").update(Gi(t)).update("\0");for(let t of["web-tree-sitter","tree-sitter-javascript","tree-sitter-typescript","tree-sitter-html"])try{e.update(t+"@"+JSON.parse(Et.readFileSync(Me.join(je(t),"package.json"),"utf8")).version)}catch{e.update(t+"@?")}return Uo=e.digest("hex").slice(0,16)}var An,Do,Gi,Uo,zo=wt(()=>{Le();An=1,Do=Me.join(Me.dirname(Sd(globalThis.__canopyUrl("src/history/engineVersion.js"))),"..");Gi=e=>Et.readFileSync(e).toString("utf8").replace(/\r\n/g,`
7
+ `),Uo=null});function Pt(e){let t=n=>Array.isArray(n)?n.map(t):n&&typeof n=="object"?Object.fromEntries(Object.keys(n).sort().map(r=>[r,t(n[r])])):n;return JSON.stringify(t(e))}function Ji(e){let t=[],n=[],r=[];for(let[i,a]of e.publicGraph){for(let l of a.nodes)t.push({id:l.id,service:i,kind:l.type,name:l.name,filePath:l.filePath,startLine:l.startLine,endLine:l.endLine,bodyHash:l.bodyHash});for(let l of a.edges)n.push({id:l.id,service:i,from:l.fromNodeId,callKind:l.callKind??l.type,calleeNameRaw:l.calleeNameRaw??l.eventName??l.url??null,resolvedTo:l.targetNodeId??null})}let o=new Map;for(let i of e.publicWorkflows){let a=i.steps[0]?.nodeId??null,l=`${i.serviceId} | ${a} | ${i.name}`,c=(o.get(l)??0)+1;o.set(l,c),r.push({id:c>1?`${l} #${c}`:l,service:i.serviceId,tier:i.tier,tierOrigin:i.tierOrigin,entry:a,steps:i.steps.map(d=>d.nodeId)})}t.sort(Mn(i=>i.service+"\0"+i.id)),n.sort(Mn(i=>i.service+"\0"+i.id)),r.sort(Mn(i=>i.id));let s=e.publicCrossServiceEdges.map(i=>({fromService:i.fromService,fromNodeId:i.fromNodeId,toService:i.toService,toNodeId:i.toNodeId,via:i.via,key:i.key??null,confidence:i.confidence??null})).sort(Mn(i=>[i.fromService,i.fromNodeId,i.toService,i.toNodeId,i.via,i.key].join("\0")));return{schema:1,fingerprint:e.fingerprint,nodes:t,edges:n,workflows:r,crossServiceEdges:s}}var Mn,Hn=wt(()=>{Mn=e=>(t,n)=>{let r=e(t),o=e(n);return r<o?-1:r>o?1:0}});import X from"node:fs";import we from"node:path";import Ki from"node:zlib";import{execFileSync as kd}from"node:child_process";function be(e,t){try{return kd("git",["-C",we.resolve(e),...t],{stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim()}catch{return null}}function Dn(e){let t=be(e,["rev-parse","--git-path","info/exclude"]);if(!t)return!1;let n=we.resolve(e,t);X.mkdirSync(we.dirname(n),{recursive:!0});let r=X.existsSync(n)?X.readFileSync(n,"utf8"):"";return r.split(/\r?\n/).some(o=>o.trim()===".canopy/")||X.appendFileSync(n,(r&&!r.endsWith(`
8
+ `)?`
9
+ `:"")+`.canopy/
10
+ `),!0}function He(e){let t=se(e);try{return JSON.parse(X.readFileSync(t.index,"utf8"))}catch{return{schema:1,nextVersion:1,versions:[]}}}function Fd(e,t){let n=se(e);X.mkdirSync(n.history,{recursive:!0});let r=n.index+"."+process.pid+".tmp";X.writeFileSync(r,JSON.stringify(t,null,2)),X.renameSync(r,n.index)}function Lt(e,t){let n=X.readFileSync(we.join(se(e).history,t.file));return JSON.parse((t.gzip?Ki.gunzipSync(n):n).toString("utf8"))}function Vi(e,t,n,r,o=Wt,{refresh:s=!1}={}){let i=se(e);X.mkdirSync(i.history,{recursive:!0});let a=He(e),l=!0,c=n.fingerprint+(l?".json.gz":".json"),d=we.join(i.history,c);(s||!X.existsSync(d))&&X.writeFileSync(d,l?Ki.gzipSync(t):t);let p=(be(e,["status","--porcelain"])||"").split(`
11
+ `).some(w=>w.trim()&&!/\.canopy(\/|$)/.test(w)),f=s?a.versions.pop():null,u={version:f?f.version:a.nextVersion,fingerprint:n.fingerprint,createdAt:new Date().toISOString(),headSha:be(e,["rev-parse","HEAD"]),headMessage:be(e,["log","-1","--format=%s"]),dirty:p,counts:r,file:c,gzip:l,bytes:X.statSync(d).size,engineVersion:On(),outputFormat:An};for(a.versions.push(u),f||a.nextVersion++;a.versions.length>o;)a.versions.shift();let m=_d(),h=w=>{try{return X.statSync(we.join(i.history,w.file)).size}catch{return w.bytes??0}},v=a.versions.reduce((w,S)=>w+h(S),0);for(;v>m&&a.versions.length>bd;)v-=h(a.versions.shift());let g=new Set(a.versions.map(w=>w.file));for(let w of X.readdirSync(i.history))/\.json(\.gz)?$/.test(w)&&w!=="index.json"&&!g.has(w)&&X.rmSync(we.join(i.history,w),{force:!0});return Fd(e,a),u}function Yi(e){let t=se(e);X.mkdirSync(t.root,{recursive:!0});for(let n=0;n<2;n++)try{let r=X.openSync(t.lock,"wx");return X.writeSync(r,JSON.stringify({pid:process.pid,startedAt:Date.now()})),X.closeSync(r),!0}catch(r){if(r.code!=="EEXIST")throw r;let o=1/0;try{o=Date.now()-X.statSync(t.lock).mtimeMs}catch{continue}if(o<$d)return!1;X.rmSync(t.lock,{force:!0})}return!1}var Nd,bd,_d,$d,Wt,se,Xi,Zi,Qi,pt=wt(()=>{zo();Nd=200,bd=2,_d=()=>{let e=Number(process.env.CANOPY_SNAPSHOT_MAX_MB);return(Number.isFinite(e)&&e>0?e:Nd)*1024*1024},$d=600*1e3,Wt=50,se=e=>{let t=we.join(we.resolve(e),".canopy");return{root:t,history:we.join(t,"history"),index:we.join(t,"history","index.json"),lock:we.join(t,"sync.lock"),pending:we.join(t,"sync.pending"),log:we.join(t,"sync.log")}};Xi=e=>X.rmSync(se(e).lock,{force:!0}),Zi=e=>{let t=se(e);X.mkdirSync(t.root,{recursive:!0}),X.writeFileSync(t.pending,String(Date.now()))},Qi=e=>{let t=se(e);return X.existsSync(t.pending)?(X.rmSync(t.pending,{force:!0}),!0):!1}});function ea(e){let t=new Map;for(let n of e.nodes){let r=t.get(n.id);r?r.services.push(n.service):t.set(n.id,{id:n.id,services:[n.service],kind:n.kind,name:n.name,filePath:n.filePath,bodyHash:n.bodyHash})}for(let n of t.values())n.services.sort();return t}function jd(e){return t=>{if(t==null)return t;if(e.has(t))return e.get(t);for(let[n,r]of e)if(t.startsWith(n+" | "))return r+t.slice(n.length);return t}}function qo(e,t){let n=a=>a.reduce((l,c)=>l.set(c,(l.get(c)??0)+1),new Map),r=n(e),o=n(t),s=[],i=[];for(let[a,l]of o)for(let c=0;c<l-(r.get(a)??0);c++)s.push(a);for(let[a,l]of r)for(let c=0;c<l-(o.get(a)??0);c++)i.push(a);return{added:s.sort(),removed:i.sort()}}function Un(e,t){let n=ea(e),r=ea(t),o=[...r.values()].filter(_=>!n.has(_.id)),s=[...n.values()].filter(_=>!r.has(_.id)),i=[];for(let[_,C]of r){let M=n.get(_);M&&M.bodyHash!==C.bodyHash&&i.push({...Wo(C),from:M.bodyHash,to:C.bodyHash})}let a=[],l=new Map,c=_=>[_.kind,_.name,_.bodyHash].join("\0"),d=new Map;for(let _ of Se(o,C=>C.id)){let C=c(_);d.has(C)||d.set(C,[]),d.get(C).push(_)}let p=[],f=new Set;for(let _ of Se(s,C=>C.id)){let M=(d.get(c(_))??[]).find(ie=>!f.has(ie.id)&&ie.filePath!==_.filePath&&ie.id.split("::").pop()===_.id.split("::").pop());M?(f.add(M.id),a.push({kind:_.kind,name:_.name,services:M.services,fromId:_.id,toId:M.id,fromPath:_.filePath,toPath:M.filePath}),l.set(_.id,M.id)):p.push(_)}o=Se(o.filter(_=>!f.has(_.id)),_=>_.id),s=Se(p,_=>_.id);let u=jd(l),m=_=>_.service+"\0"+_.id,h=new Map(e.edges.map(_=>[m({service:_.service,id:u(_.id)}),{..._,id:u(_.id),from:u(_.from),resolvedTo:u(_.resolvedTo)}])),v=new Map(t.edges.map(_=>[m(_),_])),g=_=>({id:_.id,service:_.service,from:_.from,callKind:_.callKind,calleeNameRaw:_.calleeNameRaw,resolvedTo:_.resolvedTo}),w=[],S=[],N=[];for(let[_,C]of v){let M=h.get(_);M?M.resolvedTo!==C.resolvedTo&&N.push({id:C.id,service:C.service,from:C.from,calleeNameRaw:C.calleeNameRaw,fromTarget:M.resolvedTo,toTarget:C.resolvedTo}):w.push(g(C))}for(let[_,C]of h)v.has(_)||S.push(g(C));let y=_=>_.service+"\0"+_.id,x=_=>({..._,id:_.id.replace(_.entry??"\0",u(_.entry)),entry:u(_.entry),steps:_.steps.map(u)}),b=new Map(e.workflows.map(_=>{let C=x(_);return[C.id,C]})),k=new Map(t.workflows.map(_=>[_.id,_])),$={added:[],removed:[],changed:[]},j={added:[],removed:[],changed:[]},D=_=>({id:_.id,service:_.service,tier:_.tier,steps:_.steps.length});for(let[_,C]of k){let M=b.get(_);if(!M){(C.tier==="physical"?$:j).added.push(D(C));continue}let ie=qo(M.steps,C.steps),ze=!ie.added.length&&!ie.removed.length&&M.steps.join(`
12
+ `)!==C.steps.join(`
13
+ `),F=M.tier!==C.tier?`${M.tier} -> ${C.tier}`:null;if(!ie.added.length&&!ie.removed.length&&!ze&&!F)continue;let P={id:_,service:C.service,tier:C.tier,stepsAdded:ie.added,stepsRemoved:ie.removed,reordered:ze,tierChange:F};(M.tier==="physical"||C.tier==="physical"?$:j).changed.push(P)}for(let[_,C]of b)k.has(_)||(C.tier==="physical"?$:j).removed.push(D(C));for(let _ of[$,j])for(let C of["added","removed","changed"])_[C]=Se(_[C],M=>M.id);let L=_=>[_.fromService,_.fromNodeId,_.toService,_.toNodeId,_.via,_.key].join(" | "),K=new Map(e.crossServiceEdges.map(_=>[L({..._,fromNodeId:u(_.fromNodeId),toNodeId:u(_.toNodeId)}),{..._,fromNodeId:u(_.fromNodeId),toNodeId:u(_.toNodeId)}])),z=new Map(t.crossServiceEdges.map(_=>[L(_),_])),O=Se([...z].filter(([_])=>!K.has(_)).map(([,_])=>_),L),W=Se([...K].filter(([_])=>!z.has(_)).map(([,_])=>_),L),G=new Map,te=new Map,ge=(_,C,M)=>{_.has(C)||_.set(C,new Set),_.get(C).add(M)};for(let _ of s)ge(G,_.id,"removed");for(let _ of o)ge(te,_.id,"added");for(let _ of i)ge(G,_.id,"modified"),ge(te,_.id,"modified");for(let _ of a)ge(G,_.fromId,"moved"),ge(te,_.toId,"moved");let rt=[],Be=new Set([...b.keys(),...k.keys()]);for(let _ of Be){let C=b.get(_),M=k.get(_);if(!(C&&C.tier==="physical"||M&&M.tier==="physical"))continue;let ie=new Map;for(let[F,P]of[[C,G],[M,te]])if(F)for(let R of new Set(F.steps))for(let I of P.get(Qt(R,F===C,l))??[])ie.set(R+"\0"+I,{node:R,why:I});let ze=C&&M&&(qo(C.steps,M.steps).added.length||qo(C.steps,M.steps).removed.length);ie.size&&rt.push({workflow:_,service:(M??C).service,status:C?M?"changed":"removed":"new",stepsChanged:!!ze,reasons:Se([...ie.values()],F=>F.node+"\0"+F.why)})}function Qt(_,C,M){if(!C)return _;for(let[ie,ze]of M)if(ze===_)return ie;return _}let Rt={schema:1,from:e.fingerprint,to:t.fingerprint,nodes:{added:o.map(Wo),removed:s.map(Wo),modified:Se(i,_=>_.id),moved:Se(a,_=>_.toId)},edges:{added:Se(w,y),removed:Se(S,y),retargeted:Se(N,y)},workflows:{physical:$,guessed:j},crossServiceEdges:{added:O,removed:W},touched:Se(rt,_=>_.workflow)};return Rt.counts={nodes:{added:o.length,removed:s.length,modified:i.length,moved:a.length},edges:{added:w.length,removed:S.length,retargeted:N.length},physicalWorkflows:{added:$.added.length,removed:$.removed.length,changed:$.changed.length},guessedWorkflows:{added:j.added.length,removed:j.removed.length,changed:j.changed.length},crossServiceEdges:{added:O.length,removed:W.length},touched:rt.length,touchedNew:rt.filter(_=>_.status==="new").length},Rt}function na(e,t,n,{limit:r=40}={}){let o=e.counts,s=t?`v${t.version} (${(t.headSha??t.fingerprint).slice(0,7)}${t.headMessage?` ${JSON.stringify(t.headMessage)}`:""})`:"to",i=[];i.push(`${s} \u2190 ${n?"v"+n.version:"from"}: nodes +${o.nodes.added} \u2212${o.nodes.removed} ~${o.nodes.modified} \u21A6${o.nodes.moved} | edges +${o.edges.added} \u2212${o.edges.removed}${o.edges.retargeted?` ~${o.edges.retargeted}`:""} | physical workflows touched: ${o.touched} (${o.touchedNew} new)`);let a=(c,d,p)=>{if(d.length){i.push("",`${c} (${d.length})`);for(let f of d.slice(0,r))i.push(" "+p(f));d.length>r&&i.push(` ... ${d.length-r} more`)}};a("Touched physical workflows",e.touched,c=>`[${c.service}] ${c.workflow.split(" | ").slice(2).join(" | ")} <${c.status}> because: ${c.reasons.slice(0,4).map(d=>`${d.why} ${mt(d.node)}`).join(", ")}${c.reasons.length>4?`, +${c.reasons.length-4}`:""}`),a("Nodes added",e.nodes.added,c=>`+ ${c.id}`),a("Nodes removed",e.nodes.removed,c=>`- ${c.id}`),a("Nodes modified",e.nodes.modified,c=>`~ ${c.id}`),a("Nodes moved",e.nodes.moved,c=>`\u21A6 ${c.name}: ${c.fromPath} \u2192 ${c.toPath}`),a("Edges added",e.edges.added,c=>`+ [${c.service}] ${mt(c.from)} \u2192 ${c.calleeNameRaw}${c.resolvedTo?` (resolved to ${mt(c.resolvedTo)})`:""}`),a("Edges removed",e.edges.removed,c=>`- [${c.service}] ${mt(c.from)} \u2192 ${c.calleeNameRaw}`),a("Edges retargeted",e.edges.retargeted,c=>`~ [${c.service}] ${mt(c.from)} \u2192 ${c.calleeNameRaw}: ${mt(c.fromTarget)||"unresolved"} \u2192 ${mt(c.toTarget)||"unresolved"}`),a("Physical workflows changed",e.workflows.physical.changed,c=>`~ ${c.id.split(" | ").slice(2).join(" | ")} +${c.stepsAdded.length} \u2212${c.stepsRemoved.length} steps${c.tierChange?`, tier ${c.tierChange}`:""}${c.reordered?", reordered":""}`),a("Physical workflows added",e.workflows.physical.added,c=>`+ ${c.id.split(" | ").slice(2).join(" | ")} (${c.steps} steps)`),a("Physical workflows removed",e.workflows.physical.removed,c=>`- ${c.id.split(" | ").slice(2).join(" | ")}`),a("Cross-service edges added",e.crossServiceEdges.added,c=>`+ ${c.fromService} \u2192 ${c.toService} via ${c.via} ${c.key??""}`),a("Cross-service edges removed",e.crossServiceEdges.removed,c=>`- ${c.fromService} \u2192 ${c.toService} via ${c.via} ${c.key??""}`);let l=o.guessedWorkflows;return l.added+l.removed+l.changed&&i.push("",`Informational (guessed workflows, never counted as changes): +${l.added} \u2212${l.removed} ~${l.changed}`),i.join(`
14
+ `)}var Id,Se,Wo,ta,mt,Go=wt(()=>{Hn();Id=(e,t)=>e<t?-1:e>t?1:0,Se=(e,t)=>e.slice().sort((n,r)=>Id(t(n),t(r)));Wo=e=>({id:e.id,services:e.services,kind:e.kind,name:e.name,filePath:e.filePath});ta=e=>Pt(e),mt=e=>(e??"").split("::").slice(-2).join("::")});var ia={};za(ia,{UI_VERSIONS:()=>ra,buildUiHistory:()=>sa,writeHistoryJs:()=>Pd});import oa from"node:fs";import Cd from"node:path";function Ed(e){let t=JSON.parse(JSON.stringify(e));t.truncated={};let n=(r,o)=>{for(let[s,i]of Object.entries(r))Array.isArray(i)&&i.length>Bn&&(t.truncated[`${o}.${s}`]=i.length,r[s]=i.slice(0,Bn))};return n(t.nodes,"nodes"),n(t.edges,"edges"),n(t.workflows.physical,"workflows.physical"),n(t.crossServiceEdges,"crossServiceEdges"),t.touched.length>Bn&&(t.truncated.touched=t.touched.length,t.touched=t.touched.slice(0,Bn)),t}function sa(e){let n=He(e).versions.slice(-ra),r={};for(let o=1;o<n.length;o++)r[n[o].version]=Ed(Un(Lt(e,n[o-1]),Lt(e,n[o])));return{schema:1,versions:n.map(o=>({version:o.version,fingerprint:o.fingerprint,createdAt:o.createdAt,headSha:o.headSha,headMessage:o.headMessage,dirty:o.dirty,counts:o.counts})),diffs:r}}function Pd(e,t){oa.mkdirSync(t,{recursive:!0}),oa.writeFileSync(Cd.join(t,"history.js"),`const canopyHistory = ${Pt(sa(e))};`)}var ra,Bn,aa=wt(()=>{pt();Go();Hn();ra=20,Bn=200});import Zo from"node:fs";import Yt from"node:path";import nt from"node:fs";import Ld from"node:os";import he from"node:path";import{fileURLToPath as ca}from"node:url";import J from"node:path";import me from"node:fs";import{fileURLToPath as gd,pathToFileURL as yd}from"node:url";var ao=qa(dr(),1);import Nt from"node:fs";import ke from"node:path";var so={javascript:[".js",".jsx",".mjs",".cjs"],typescript:[".ts",".tsx"]},fr=[".ts",".tsx",".mts",".cts"],pc={javascript:["index.js","index.jsx"],typescript:["index.ts","index.tsx"]};function ur(){return Object.values(so).flat()}function pr(){return Object.values(pc).flat()}var mr=["log","logger","console","debug","trace"];var gr=[".yarn",".pnp","vendor","dist","build","out","coverage",".next",".nuxt",".turbo",".cache","bower_components"],co=["node_modules",".git",".canopy",".canopy-cache"],hr=[".vue",".svelte"],mc=1024*1024,io=1e4;function hc(e,t=null){let n=[];function r(o,s){let i=ke.join(o,".gitignore"),a=(0,ao.default)().add(s);Nt.existsSync(i)&&a.add(Nt.readFileSync(i,"utf-8"));let l=Nt.readdirSync(o,{withFileTypes:!0});for(let c of l){let d=ke.join(o,c.name),p=ke.relative(e,d).split(ke.sep).join("/");if(!a.ignores(p)&&!(c.isDirectory()&&co.includes(c.name))){if(c.isDirectory()&&gr.includes(c.name)){t&&t.excludedDirs.push(d);continue}c.isDirectory()?r(d,a):c.isFile()&&n.push(d)}}}return r(e,(0,ao.default)()),n}function gc(e,t,n=null){return e.filter(r=>!(n?ke.relative(n,r):r).split(ke.sep).some(s=>t.includes(s)))}function yr(e,t){let n=0,r;try{r=Nt.readdirSync(e,{withFileTypes:!0})}catch{return 0}for(let o of r)o.isDirectory()?co.includes(o.name)||(n+=yr(ke.join(e,o.name),t)):o.isFile()&&t.has(ke.extname(o.name))&&n++;return n}var yc=e=>/\.d\.(ts|mts|cts)$/.test(e);function xc(e){let t=ke.basename(e);if(/\.min\.js$/.test(t))return{kind:"minified",reason:"minified (*.min.js)"};if(/\.bundle\.js$/.test(t))return{kind:"bundled",reason:"bundled (*.bundle.js)"};let n;try{n=Nt.statSync(e).size}catch{return null}if(n>mc)return{kind:"oversized",reason:`oversized (${(n/1048576).toFixed(1)} MB, limit 1 MB)`};if(n>io){let r=Nt.readFileSync(e,"utf8"),o=0,s=0;for(;;){let i=r.indexOf(`
15
+ `,o),a=(i<0?r.length:i)-o;if(a>s&&(s=a),i<0)break;o=i+1}if(s>io)return{kind:"minified",reason:`line of ${s.toLocaleString("en-US")} characters (limit ${io.toLocaleString("en-US")}; minified/bundled)`}}return null}function lo(e,t=["javascript","typescript"]){let n=t.flatMap(p=>(p==="typescript"?fr:so[p])||[]),r={excludedDirs:[]},o=gc(hc(e,r),[...gr,...co],e),s=p=>ke.relative(e,p).split(ke.sep).join("/"),i=[],a=[],l={};for(let p of o){let f=ke.extname(p);if(n.includes(f)){if(yc(p)){a.push({file:s(p),kind:"declaration",reason:"declaration file"});continue}let u=xc(p);u?a.push({file:s(p),kind:u.kind,reason:u.reason}):i.push(p)}else hr.includes(f)&&(l[f]=(l[f]??0)+1)}let c=new Set([...n,...hr]),d={};for(let p of r.excludedDirs){let f=ke.basename(p),u=d[f]??={dirs:0,files:0};u.dirs++,u.files+=yr(p,c)}return{files:i,skipped:a,unsupported:l,excludedDirs:d}}function an(e,t=["javascript","typescript"]){return lo(e,t).files}import vc from"node:path";var at=e=>e.toLocaleString("en-US"),cn=(e,t,n=t+"s")=>`${at(e)} ${e===1?t:n}`,wc={".vue":"Vue",".svelte":"Svelte"},Sc=[".vue",".svelte"],kc=new Set([".ts",".tsx",".mts",".cts"]);function xr({discovered:e,parseResults:t,scopeFiles:n,rel:r,rootService:o=null}){let s=(t.budgetSkips??[]).map(m=>({path:r(m.filePath),kind:"timeout",reason:m.reason})),i=new Set((t.budgetSkips??[]).map(m=>m.filePath)),a=[...e.skipped.map(m=>({path:m.file,kind:m.kind,reason:m.reason})),...s].sort((m,h)=>m.path<h.path?-1:m.path>h.path?1:0),l=e.files.filter(m=>!i.has(m)),c=l.filter(m=>t.get(m)?.hadErrors).map(r).sort(),d=l.flatMap(m=>(t.get(m)?.warnings??[]).map(h=>({path:r(m),extractor:h.extractor,message:h.message}))).sort((m,h)=>m.path<h.path?-1:m.path>h.path?1:0),p=l.filter(m=>kc.has(vc.extname(m))).length,f={};for(let m of Sc)e.unsupported[m]&&(f[m]=e.unsupported[m]);let u={};for(let m of a)u[m.kind]=(u[m.kind]??0)+1;return{analyzed:l.length,analyzedJs:l.length-p,analyzedTs:p,inService:l.filter(m=>n.has(m)).length,notAnalyzed:f,notAnalyzedTotal:Object.values(f).reduce((m,h)=>m+h,0),skipped:a,skippedByKind:u,parseErrors:c.length,parseErrorFiles:c.slice(0,50),parseWarnings:d.length,parseWarningList:d.slice(0,50),excludedDirs:e.excludedDirs,rootService:o}}function ln(e){let t=["Coverage"],n=[],r=new Map;for(let[a,l]of Object.entries(e.notAnalyzed)){let c=wc[a];r.has(c)||r.set(c,[]),r.get(c).push(`${at(l)} ${a}`)}for(let[a,l]of r)n.push(`${l.join(", ")} files (${a} not supported yet)`);if(e.skipped.length){let a=Object.entries(e.skippedByKind).map(([l,c])=>`${l}: ${c}`).join(", ");n.push(`${at(e.skipped.length)} skipped (${a})`)}e.parseErrors&&n.push(`${at(e.parseErrors)} with parse errors`),e.parseWarnings&&n.push(`${at(e.parseWarnings)} extractor warnings (a construct skipped; the rest of its file was analyzed)`);let o=e.analyzedTs?`${cn(e.analyzedJs,"JS file")} and ${cn(e.analyzedTs,"TS file")}`:cn(e.analyzed,"JS file");t.push(` Analyzed ${o}, ${at(e.inService)} of them inside a service${e.analyzed?` (${Math.round(100*e.inService/e.analyzed)}%)`:""}.`),t.push(` Not analyzed: ${n.length?n.join(", "):"nothing"}.`);let s=e.skipped.filter(a=>a.kind!=="declaration");for(let a of s.slice(0,5))t.push(` skipped ${a.path}: ${a.reason}`);s.length>5&&t.push(` ... and ${at(s.length-5)} more (full list: meta.coverage.skipped)`);let i=Object.entries(e.excludedDirs);return i.length&&t.push(` Excluded directories: ${i.map(([a,l])=>`${a}/ x${l.dirs} (${cn(l.files,"source file")})`).join(", ")}.`),e.rootService&&t.push(` Root service: ${e.rootService.reason}.`),t.join(`
16
+ `)}Le();import{Parser as fo,Language as wr}from"web-tree-sitter";import dn from"node:path";import{fileURLToPath as bc}from"node:url";var qf=dn.dirname(bc(globalThis.__canopyUrl("src/stage2_parse/initParser.js")));var uo=new WeakMap,Ot=e=>uo.get(e)??"javascript",et=e=>Ot(e)!=="javascript";function po(e){let t=dn.extname(e);return t===".tsx"?"tsx":t===".ts"||t===".mts"||t===".cts"?"typescript":"javascript"}var _c={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm"};async function Sr(e,t){for(let n of new Set(t.map(po))){if(e.grammars.has(n))continue;let r=dn.join(je("tree-sitter-typescript"),_c[n]),o=await wr.load(r);uo.set(o,n);let s=new fo;s.setLanguage(o),e.grammars.set(n,{parser:s,language:o})}return e}async function kr(){await fo.init();let e=new fo,t=dn.join(je("tree-sitter-javascript"),"tree-sitter-javascript.wasm"),n=await wr.load(t);return e.setLanguage(n),uo.set(n,"javascript"),{parser:e,language:n,grammars:new Map([["javascript",{parser:e,language:n}]])}}import $c from"node:fs";function $r(e,t){let n=$c.readFileSync(t,"utf-8"),r=e.parse(n);if(mo(r)||n.includes("\0")){let o=n,s=_r(r);for(let i of Fc){let a=i.apply(o);if(a===o)continue;let l=e.parse(a),c=_r(l);(c<s||i.always)&&(o=a,r=l,s=c)}o!==n&&(r.canopyOriginalSource=n)}return{tree:r,source:n,filePath:t}}var Fr=e=>e.replace(/[^\n]/g," "),Nr=e=>"any"+Fr(e).slice(3),br=/(?<![&])&(?![&=])/g,Fc=[{name:"NUL byte",always:!0,apply:e=>e.replace(/\0/g," ")},{name:"export type * from",apply:e=>e.replace(/\bexport\s+type\s+\*\s*(?:as\s+[\w$]+\s+)?from\s*(["'])[^"'\n]*\1\s*;?/g,Fr)},{name:"typeof import()",apply:e=>e.replace(/typeof\s+import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)*/g,Nr)},{name:"import().Type",apply:e=>e.replace(/(?<=[:<,|&?]\s*|\breadonly\s+|\bkeyof\s+|\bextends\s+|\bas\s+)import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)+(?!\s*\()/g,Nr)},{name:"generic call signature after a member",apply:e=>e.replace(/(?<=\n[ \t]*)[ ](?=<\s*[A-Za-z_$][\w$]*\s*(?:extends\b|=|,|>\s*\())/g,";")},{name:"& in JSX text",apply:e=>e.replace(/>[^<>{}"'`]*&[^<>{}"'`]*</g,t=>t.replace(br,"+"))},{name:"& in JSX attribute",apply:e=>e.replace(/(\s[\w:-]+=)"([^"\n]*)"/g,(t,n,r)=>n+'"'+r.replace(br,"+")+'"')}];function _r(e){let t=0;return(function n(r){if(r.type==="ERROR"){t++;return}for(let o=0;o<r.childCount;o++)n(r.child(o))})(e.rootNode),t}function mo(e){let t=!1;function n(r){if(r.type==="ERROR"){t=!0;return}for(let o=0;o<r.childCount;o++)n(r.child(o))}return n(e.rootNode),t}import ho from"node:fs";import Mt from"node:path";import{fileURLToPath as Ic}from"node:url";import{Query as jc}from"web-tree-sitter";var Ir=Mt.dirname(Ic(globalThis.__canopyUrl("src/utils/loadQuery.js"))),jr=new WeakMap;function ee(e,t){let n=jr.get(e);if(n||jr.set(e,n=new Map),n.has(t))return n.get(t);let r=Mt.join(Ir,"..","stage2_parse","queries"),o=ho.existsSync(r)?r:Mt.join(Ir,"..","..","dist","queries"),s=Ot(e),l=(s==="javascript"?[]:s==="tsx"?["tsx","typescript"]:[s]).map(p=>Mt.join(o,p,t)).find(p=>ho.existsSync(p))??Mt.join(o,t),c=ho.readFileSync(l,"utf-8"),d=new jc(e,c);return n.set(t,d),d}var Cr="javascript",Er=e=>{Cr=e};var fn=()=>Cr!=="javascript";var Cc=new Set(["non_null_expression","as_expression","satisfies_expression","type_assertion"]);function ce(e){for(;e;)if(Cc.has(e.type))e=e.type==="type_assertion"?e.namedChild(e.namedChildCount-1):e.namedChild(0);else if(e.type==="parenthesized_expression"&&e.namedChildCount===1){let t=ce(e.namedChild(0));if(t===e.namedChild(0))break;e=t}else break;return e}function Ec(e){let t=e;for(;t;){t=ce(t);for(let n=0;n<t.childCount;n++)if(t.child(n).type==="optional_chain")return!0;if(t.type==="member_expression"||t.type==="subscript_expression")t=t.childForFieldName("object");else if(t.type==="call_expression")t=t.childForFieldName("function");else break}return!1}function tt(e){let t=e.childForFieldName("function"),n=e.childForFieldName("arguments");if(!t)return{kind:"callOfCall",oldShape:!1,nameNode:e};let r=t.type==="identifier",o=t.type==="member_expression"?t.childForFieldName("property"):null,s=t.type==="member_expression"?ce(t.childForFieldName("object")):null,i=r||s?.type==="identifier"&&o?.type==="property_identifier",a=o??t;if(fn()&&e.parent?.type==="decorator")return{kind:"decorator",oldShape:i,nameNode:a};if(n&&n.type==="template_string")return{kind:"taggedTemplate",oldShape:i,nameNode:a};if(Ec(e))return{kind:"optionalCall",oldShape:i,nameNode:a};if(r)return{kind:"call",oldShape:i,nameNode:a};if(t.type==="subscript_expression")return{kind:"computed",oldShape:!1,nameNode:t};if(t.type==="member_expression")return s.type==="super"?{kind:"super",oldShape:!1,nameNode:a}:s.type==="this"?{kind:"thisCall",oldShape:!1,nameNode:a}:i?{kind:"methodCall",oldShape:!0,nameNode:a}:{kind:"chainedCall",oldShape:!1,nameNode:a};if(t.type==="import")return{kind:"dynamicImport",oldShape:!1,nameNode:t};if(t.type==="super")return{kind:"super",oldShape:!1,nameNode:t};let l=t;for(;l.type==="parenthesized_expression"&&l.namedChildCount===1;)l=l.namedChild(0);return l.type==="arrow_function"||l.type==="function_expression"||l.type==="function"||l.type==="generator_function"?{kind:"iife",oldShape:!1,nameNode:t}:{kind:"callOfCall",oldShape:!1,nameNode:t}}function Pr(e){let t=e.childForFieldName("name");return t?t.type==="identifier"?/^[A-Z]/.test(t.text)?{kind:"jsx",oldShape:!0,nameNode:t}:null:t.type==="member_expression"||t.type==="nested_identifier"?{kind:"jsxMember",oldShape:!1,nameNode:t}:null:null}function un(e){let t=e;for(;t&&t.type!=="call_expression";)t=t.parent;return t}function Lr(e){let t=e.childForFieldName("function"),n=!1;for(;t;)if(t=ce(t),t.type==="member_expression"||t.type==="subscript_expression")t=t.childForFieldName("object");else if(t.type==="call_expression")n=!0,t=t.childForFieldName("function");else if(t.type==="await_expression"||t.type==="parenthesized_expression"||t.type==="non_null_expression")t=t.namedChild(0);else break;return t&&t.type==="identifier"?{head:t.text,called:n}:{head:null,called:!1}}function Rr(e){let t=e.text.replace(/\s+/g," ");return t.length>120?t.slice(0,117)+"...":t}function Ar(e,t){let o=ee(t,"functionDeclarations.scm").matches(e.rootNode).map(s=>{let i=s.captures.find(c=>c.name==="func_name"),a=s.captures.find(c=>c.name==="func_params"),l=s.captures.find(c=>c.name==="func_declaration");return{name:i.node.text,params:a.node.text,startLine:l.node.startPosition.row+1,endLine:l.node.endPosition.row+1,startIndex:l.node.startIndex,endIndex:l.node.endIndex,node:i.node}});return et(t)&&o.push(...Pc(e,t)),o}function Pc(e,t){return ee(t,"defaultExports.scm").matches(e.rootNode).map(n=>{let r=n.captures.find(s=>s.name==="func_declaration").node;return{name:"default",params:n.captures.find(s=>s.name==="func_params").node.text,startLine:r.startPosition.row+1,endLine:r.endPosition.row+1,startIndex:r.startIndex,endIndex:r.endIndex,node:r}})}function Or(e,t){return ee(t,"arrowFunctions.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(l=>l.name==="func_name"),i=o.captures.find(l=>l.name==="func_params"),a=o.captures.find(l=>l.name==="func_declaration");return{name:s.node.text,params:i.node.text,startLine:a.node.startPosition.row+1,endLine:a.node.endPosition.row+1,startIndex:a.node.startIndex,endIndex:a.node.endIndex,node:s.node}})}function Mr(e,t){let r=ee(t,"classMethods.scm").matches(e.rootNode),o=et(t);return r.map(s=>{let i=s.captures.find(p=>p.name==="class_name"),a=s.captures.find(p=>p.name==="method_name"),l=s.captures.find(p=>p.name==="method_params"),c=s.captures.find(p=>p.name==="method_declaration"),d=c.node;if(o)for(let p=d.previousNamedSibling;p&&p.type==="decorator";p=p.previousNamedSibling)d=p;return{className:i?i.node.text:"default",methodName:a.node.text,params:l.node.text,startLine:d.startPosition.row+1,endLine:c.node.endPosition.row+1,startIndex:d.startIndex,endIndex:c.node.endIndex,node:a.node}})}function Hr(e,t){let r=ee(t,"imports.scm").matches(e.rootNode),o=et(t);return r.filter(s=>!(o&&Lc(s.captures[0].node))).map(s=>{let i=s.captures[0].node;return{source:i.text,startLine:i.startPosition.row+1}})}function Lc(e){let t=e;for(;t&&t.type!=="import_statement";)t=t.parent;if(!t)return!1;if(t.children.some(s=>s.type==="type"))return!0;let n=t.namedChildren.find(s=>s.type==="import_clause");if(!n)return!1;let r=n.namedChildren;if(r.length!==1||r[0].type!=="named_imports")return!1;let o=r[0].namedChildren.filter(s=>s.type==="import_specifier");return o.length>0&&o.every(s=>s.children.some(i=>i.type==="type"))}function Ht(e){let t=e;for(;t&&t.type!=="call_expression"&&t.type!=="new_expression";)t=t.parent;if(!t)return null;let n=t.childForFieldName("arguments");if(!n)return null;let r=n.namedChildren?.[0];return!r||r.type==="arrow_function"||r.type==="function_expression"?null:r.text}var Rc=/^(addEventListener|removeEventListener|on|once|postMessage|onmessage|subscribe)$/i;function _t(e){let t=e;for(;t.parent;){let n=t.parent;if(n.type==="arrow_function"||n.type==="function_expression"){let r=n.parent;if(r&&(r.type==="variable_declarator"||r.type==="public_field_definition"))break;if(r&&r.type==="return_statement")return!0;if(r&&r.type==="arguments"&&r.parent?.type==="call_expression"){let o=r.parent.childForFieldName("function"),s=o?.type==="member_expression"?o.childForFieldName("property")?.text:o?.text;if(s&&Rc.test(s))return!0}}else if(n.type==="function_declaration"||n.type==="method_definition")break;t=n}return!1}function Dr(e,t){return ee(t,"callExpressions.scm").matches(e.rootNode).map(o=>{let s=o.captures[0].node;return{calleeName:s.text,startLine:s.startPosition.row+1,startColumn:s.startPosition.column,branchPath:$t(s),firstArgText:Ht(s),deferred:_t(s),callKind:tt(un(s)).kind}})}function Ur(e,t){return et(t)?Tc(e):ee(t,"methodCalls.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(a=>a.name==="object_name"),i=o.captures.find(a=>a.name==="method_name");return{objectName:s.node.text,methodName:i.node.text,startLine:i.node.startPosition.row+1,startColumn:i.node.startPosition.column,firstArgText:Ht(i.node),branchPath:$t(i.node),deferred:_t(i.node),callKind:tt(un(i.node)).kind}})}function Tc(e){let t=[];for(let n of e.rootNode.descendantsOfType("call_expression")){let r=n.childForFieldName("function");if(!r||r.type!=="member_expression")continue;let o=ce(r.childForFieldName("object")),s=r.childForFieldName("property");!o||o.type!=="identifier"||!s||s.type!=="property_identifier"||t.push({objectName:o.text,methodName:s.text,startLine:s.startPosition.row+1,startColumn:s.startPosition.column,firstArgText:Ht(s),branchPath:$t(s),deferred:_t(s),callKind:tt(un(s)).kind})}return t}function Ac(e){if(!e)return"return";if(e.type==="object"){let t=e.namedChildren.filter(r=>r.type==="pair"),n=t.find(r=>r.childForFieldName("key")?.text?.replace(/^['"]|['"]$/g,"")==="type")??t.find(r=>r.childForFieldName("key")?.text?.replace(/^['"]|['"]$/g,"")==="entity");if(n){let r=n.childForFieldName("key"),o=n.childForFieldName("value");return`return { ${r.text}: ${o.text} }`}}return"return "+e.text.split(/\r?\n/)[0].trim()}function Br(e,t){return ee(t,"returns.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(l=>l.name==="return_statement"),i=o.captures.find(l=>l.name==="return_value"),a=s.node;return{label:Ac(i?.node),startLine:a.startPosition.row+1,startColumn:a.startPosition.column,branchPath:$t(a),deferred:_t(a)}})}var Oc=new Set(["function_declaration","arrow_function","function_expression","method_definition"]);function pn(e,t){return!(!t||e.row<t.startPosition.row||e.row>t.endPosition.row||e.row===t.startPosition.row&&e.column<t.startPosition.column||e.row===t.endPosition.row&&e.column>t.endPosition.column)}function $t(e){let t=[],n=e,r=e.startPosition;for(;n.parent;){let o=n.parent;if(Oc.has(o.type))break;if(o.type==="if_statement"){let s=o.childForFieldName("condition"),i=o.childForFieldName("consequence"),a=o.childForFieldName("alternative");pn(r,i)?t.push({type:"if",conditionText:s?s.text:"",conditionLine:(s??o).startPosition.row+1,outcome:"true"}):pn(r,a)&&t.push({type:"if",conditionText:s?s.text:"",conditionLine:(s??o).startPosition.row+1,outcome:"false"})}else if(o.type==="switch_case"||o.type==="switch_default"){let s=o.parent,i=s&&s.type==="switch_body"?s.parent:null;if(i){let a=i.childForFieldName("value"),l=o.childForFieldName("value");t.push({type:"switch",conditionText:a?a.text:"",conditionLine:(a??i).startPosition.row+1,outcome:o.type==="switch_default"?"default":l?l.text:"case"})}}else if(o.type==="try_statement"){let s=o.childForFieldName("handler"),i=o.childForFieldName("finalizer"),a="try";pn(r,s)?a="catch":pn(r,i)&&(a="finally"),t.push({type:"try",conditionText:"try / catch",conditionLine:o.startPosition.row+1,outcome:a})}n=o}return t.reverse()}function zr(e,t){return ee(t,"exports.scm").matches(e.rootNode).map(r=>r.captures[0].node.text)}var Tr=new WeakMap;function Mc(e,t){let n=Tr.get(e);return n||(n=ee(t,"returns.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(a=>a.name==="return_statement"),i=o.captures.find(a=>a.name==="return_value");return{stmtNode:s.node,valueNode:i?.node}}),Tr.set(e,n)),n}function Wr(e,t,n){return Mc(e,t).filter(r=>r.stmtNode.startPosition.row+1>=n.startLine&&r.stmtNode.endPosition.row+1<=n.endLine).map(r=>({shape:Hc(r.valueNode),condition:Dc(r.stmtNode,n),line:r.stmtNode.startPosition.row+1}))}function Hc(e){if(!e)return"nothing";switch(e.type){case"true":case"false":return"boolean";case"number":return"number";case"string":return"string";case"null":return"null";case"identifier":return`variable (${e.text})`;case"object":return"object";case"array":return"array";case"call_expression":return`result of ${e.text.split("(")[0]}()`;case"binary_expression":return"boolean (comparison)";case"ternary_expression":return"conditional value";default:return"expression"}}function Dc(e,t){let n=e.parent;for(;n;){if(n.type==="if_statement"){let r=n.childForFieldName("condition");if(r)return r.text}n=n.parent}return null}function qr(e,t){return Ot(t)==="typescript"?[]:ee(t,"jsxElements.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(i=>i.name==="jsx_tag");return{calleeName:s.node.text,startLine:s.node.startPosition.row+1}}).filter(o=>/^[A-Z]/.test(o.calleeName))}function Gr(e,t){return ee(t,"fetchApiCalls.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(c=>c.name==="url"),i=o.captures.find(c=>c.name==="http_method"),a=s.node.text,l=/^https?:\/\//.test(a)?"external":"internal";return{url:a,method:i?.node.text??"get",startLine:s.node.startPosition.row+1,scope:l}})}function Jr(e,t){return ee(t,"socketEmit.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(i=>i.name==="event_name");return{eventName:s.node.text,startLine:s.node.startPosition.row+1}})}function Kr(e,t){return ee(t,"rawSocketSend.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(i=>i.name==="event_name");return{eventName:s.node.text,startLine:s.node.startPosition.row+1}})}function Vr(e,t){return ee(t,"rawSocketTypeCheck.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(i=>i.name==="event_name");return{eventName:s.node.text,startLine:s.node.startPosition.row+1}})}function Yr(e,t){return ee(t,"socketOn.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(l=>l.name==="event_name"),i=o.captures.find(l=>l.name==="handler_ref"),a=o.captures.find(l=>l.name==="handler_inline");return{eventName:s.node.text,startLine:s.node.startPosition.row+1,handlerName:i?i.node.text:null,isInlineHandler:!!a,handlerStartLine:a?a.node.startPosition.row+1:null,handlerEndLine:a?a.node.endPosition.row+1:null,handlerStartIndex:a?a.node.startIndex:null,handlerEndIndex:a?a.node.endIndex:null}})}function Xr(e){let t=e.rootNode.descendantsOfType(["call_expression","new_expression","jsx_opening_element","jsx_self_closing_element",...fn()?["decorator"]:[]]),n=[];for(let r of t){let o,s,i,a=null,l=null,c=!1,d=null,p=null;if(r.type==="new_expression"){if(i=r.childForFieldName("constructor"),!i)continue;o="new",s=i,a=i.type==="identifier"?i.text:null;let u=r.childForFieldName("arguments")?.namedChildren?.[0];d=u&&u.type!=="arrow_function"&&u.type!=="function_expression"?u.text:null}else if(r.type==="decorator"){let f=r.namedChild(0);if(!f||f.type==="call_expression")continue;o="decorator",s=f.type==="member_expression"?f.childForFieldName("property")??f:f,i=f}else if(r.type==="call_expression"){let f=tt(r);if(f.oldShape)continue;if(o=f.kind,s=f.nameNode,i=r.childForFieldName("function")??r,o==="chainedCall"){let u=Lr(r);l=u.head,c=u.called;let m=r.childForFieldName("function"),h=m?.type==="member_expression"?ce(m.childForFieldName("object")):null;h?.type==="member_expression"&&ce(h.childForFieldName("object"))?.type==="this"&&h.childForFieldName("property")?.type==="property_identifier"&&m.childForFieldName("property")&&(p={thisProp:h.childForFieldName("property").text,thisMethod:m.childForFieldName("property").text})}d=Ht(s)}else{let f=Pr(r);if(!f||f.oldShape)continue;o=f.kind,s=f.nameNode,i=f.nameNode}n.push({callKind:o,calleeName:Rr(i),startLine:s.startPosition.row+1,startColumn:s.startPosition.column,branchPath:$t(s),firstArgText:d,deferred:_t(s),chainHead:l,chainHeadCalled:c,ctorName:a,...p??{}})}return n.sort((r,o)=>r.startLine-o.startLine||r.startColumn-o.startColumn)}var go=new Set(["get","post","put","patch","delete","head","options"]),yo=new Set(["axios","ky","got","superagent","$http"]),Uc=new Set(["function_declaration","function_expression","function","arrow_function","method_definition","generator_function_declaration","generator_function"]),Bc=new Set(["WebSocket","ReconnectingWebSocket","SockJS","W3CWebSocket"]),xo=/^(ws|socket|sock|websocket|webSocket|wsClient|socketRef|wsRef|[A-Za-z]+Socket|[A-Za-z]+Ws|[A-Za-z]+WebSocket)$/,Z=e=>{for(;e&&(e.type==="parenthesized_expression"||e.type==="as_expression"||e.type==="non_null_expression"||e.type==="await_expression"||e.type==="satisfies_expression"||e.type==="type_assertion")&&(e=e.namedChildren.find(t=>t.type!=="type_annotation"&&t.type!=="predefined_type"&&!/_type$/.test(t.type))??e.namedChildren[0],!!e););return e},Dt=e=>e.namedChildren.length?e.namedChildren.filter(t=>t.type==="string_fragment"||t.type==="escape_sequence").map(t=>t.text).join(""):e.text.slice(1,-1);function Ft(e){for(let t=e.parent;t;t=t.parent)if(Uc.has(t.type))return t;return null}function Zr(e){if(!e)return null;let t=e.childForFieldName("name")?.text??null;if(!t&&e.parent){let o=e.parent;o.type==="variable_declarator"?t=o.childForFieldName("name")?.text??null:o.type==="assignment_expression"?t=o.childForFieldName("left")?.text??null:o.type==="pair"&&(t=o.childForFieldName("key")?.text??null)}let n=[],r=e.childForFieldName("parameters");if(r)r.namedChildren.forEach((o,s)=>{let i=o.type==="identifier"?o:o.type==="assignment_pattern"?o.childForFieldName("left"):o.type==="required_parameter"||o.type==="optional_parameter"?o.childForFieldName("pattern")??o.namedChildren[0]:null;n[s]=i&&i.type==="identifier"?i.text:null});else{let o=e.childForFieldName("parameter");o&&o.type==="identifier"&&(n[0]=o.text)}return{name:t,params:n}}function Qr(e){let t=e.rootNode,n={httpCalls:[],pathCallsites:[],httpInstances:[],wsClients:[],wsServers:[],wsSends:[],wsServerSends:[],listens:[],wsReceivers:[]},r=new Map;for(let u of t.descendantsOfType("variable_declarator")){let m=u.childForFieldName("name"),h=u.childForFieldName("value");if(!m||m.type!=="identifier"||!h)continue;(r.get(m.text)??r.set(m.text,[]).get(m.text)).push({value:h,fn:Ft(u)})}let o=(u,m)=>{let h=r.get(u);if(!h)return null;for(let g=Ft(m);g;g=Ft(g)){let w=h.filter(S=>S.fn&&S.fn.id===g.id);if(w.length===1)return w[0].value}let v=h.filter(g=>!g.fn);return v.length===1?v[0].value:h.length===1?h[0].value:null},s=(u,m)=>{for(let h=Ft(m);h;h=Ft(h)){let g=Zr(h).params.indexOf(u);if(g>=0)return g}return-1};function i(u,m=0){if(u=Z(u),!u)return[{t:"ref",name:""}];switch(u.type){case"string":return[{t:"lit",v:Dt(u)}];case"template_string":{let h=[];for(let v of u.namedChildren)v.type==="string_fragment"||v.type==="escape_sequence"?h.push({t:"lit",v:v.text}):v.type==="template_substitution"&&h.push(...i(v.namedChildren[0],m+1));return h.length?h:[{t:"lit",v:""}]}case"number":return[{t:"lit",v:u.text}];case"binary_expression":{let h=u.childForFieldName("operator")?.text;if(h==="||"||h==="??"){let v=i(u.childForFieldName("left"),m+1);if(v.length===1&&v[0].t==="env")return[{...v[0],fallback:i(u.childForFieldName("right"),m+1)}]}return h!=="+"?[{t:"ref",name:u.text.slice(0,60)}]:[...i(u.childForFieldName("left"),m+1),...i(u.childForFieldName("right"),m+1)]}case"shorthand_property_identifier":case"identifier":{let h=u.text,v=s(h,u);if(v>=0)return[{t:"param",name:h,index:v}];if(m<4){let g=o(h,u);if(g&&g.id!==u.id)return i(g,m+1)}return[{t:"ref",name:h}]}case"member_expression":{let h=u.text,v=/^(?:process\.env|import\.meta\.env)\.([A-Za-z0-9_$]+)$/.exec(h)??/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(h);return v?[{t:"env",name:v[1]}]:[{t:"ref",name:h.slice(0,60)}]}case"subscript_expression":{let h=/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(u.text);return h?[{t:"env",name:h[1]}]:[{t:"ref",name:u.text.slice(0,60)}]}case"call_expression":{let h=u.childForFieldName("function")?.text,v=u.childForFieldName("arguments")?.namedChildren[0];if(v&&(h==="encodeURIComponent"||h==="String"||h==="encodeURI"))return i(v,m+1);let g=Z(u.childForFieldName("function"));if(g&&g.type==="member_expression"&&/^(replace|replaceAll|trim|trimEnd|trimStart|toString|toLowerCase)$/.test(g.childForFieldName("property")?.text??"")){let w=g.childForFieldName("object");if(w){let S=i(w,m+1);if(S.length&&S.every(N=>N.t!=="ref"))return S}}return[{t:"ref",name:u.text.slice(0,60)}]}default:return[{t:"ref",name:u.text.slice(0,60)}]}}let a=(u,m)=>{if(u=Z(u),!(!u||u.type!=="object")){for(let h of u.namedChildren)if(h.type==="pair"){let v=h.childForFieldName("key");if((v?v.type==="string"?Dt(v):v.text:null)===m)return h.childForFieldName("value")}else if(h.type==="shorthand_property_identifier"&&h.text===m)return h}},l=u=>u.childForFieldName("arguments")?.namedChildren.filter(m=>m.type!=="comment")??[],c=u=>{if(!u)return null;let m=i(u);return m.length===1&&m[0].t==="lit"?m[0].v.toUpperCase():m.length===1&&m[0].t==="param"?{param:m[0].index}:"?"},d=(u,m,h,v)=>({client:u,method:m,parts:h,line:v.startPosition.row+1,fn:Zr(Ft(v))});for(let u of t.descendantsOfType("variable_declarator")){let m=u.childForFieldName("name"),h=Z(u.childForFieldName("value"));if(!m||m.type!=="identifier"||!h||h.type!=="call_expression")continue;let v=Z(h.childForFieldName("function"));if(!v||v.type!=="member_expression")continue;let g=v.childForFieldName("object")?.text,w=v.childForFieldName("property")?.text;if(!(yo.has(g)&&(w==="create"||w==="extend")))continue;let S=l(h)[0],N=a(S,"baseURL")??a(S,"baseUrl")??a(S,"prefixUrl")??a(S,"prefix_url");n.httpInstances.push({name:m.text,parts:N?i(N):[],line:u.startPosition.row+1})}let p=new Set(n.httpInstances.map(u=>u.name));for(let u of t.descendantsOfType("call_expression")){let m=Z(u.childForFieldName("function"));if(!m)continue;let h=l(u),v=!1;if(m.type==="identifier"){let g=m.text;if(g==="fetch"&&h[0]){let w=Z(h[0]);if(w&&w.type==="new_expression")continue;let S=a(h[1],"method");n.httpCalls.push(d("fetch",S?c(S):h[1]&&Z(h[1])?.type!=="object"?"?":"GET",i(h[0]),u)),v=!0}else if((yo.has(g)||p.has(g))&&h[0]){let w=Z(h[0]);if(w&&w.type==="object"){let S=a(w,"url");if(S){let N=a(w,"baseURL");n.httpCalls.push(d(p.has(g)?"inst:"+g:g,c(a(w,"method"))??"GET",[...N?i(N):[],...i(S)],u)),v=!0}}else n.httpCalls.push(d(p.has(g)?"inst:"+g:g,h[1]&&a(h[1],"method")?c(a(h[1],"method")):"GET",i(h[0]),u)),v=!0}else g==="io"&&h[0]&&(n.wsClients.push({client:"io",parts:i(h[0]),line:u.startPosition.row+1}),v=!0)}else if(m.type==="member_expression"){let w=m.childForFieldName("object")?.text??"",S=m.childForFieldName("property")?.text??"",N=yo.has(w)||p.has(w);if(N&&go.has(S)&&h[0])n.httpCalls.push(d(p.has(w)?"inst:"+w:w,S.toUpperCase(),i(h[0]),u)),v=!0;else if(!N&&go.has(S)&&/^[A-Za-z_$][\w$]*$/.test(w)&&h[0]&&(Z(h[0])?.type==="string"||Z(h[0])?.type==="template_string")){let y=i(h[0]);y[0]?.t==="lit"&&(y[0].v.startsWith("/")||/^https?:\/\//.test(y[0].v))&&(n.httpCalls.push(d("obj:"+w,S.toUpperCase(),y,u)),v=!0)}else if(N&&S==="request"&&h[0]){let y=a(h[0],"url");if(y){let x=a(h[0],"baseURL");n.httpCalls.push(d(p.has(w)?"inst:"+w:w,c(a(h[0],"method"))??"GET",[...x?i(x):[],...i(y)],u)),v=!0}}else if(S==="open"&&h.length>=2&&Z(h[0])?.type==="string"&&/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/i.test(Dt(Z(h[0]))))n.httpCalls.push(d("xhr",Dt(Z(h[0])).toUpperCase(),i(h[1]),u)),v=!0;else if(w==="io"&&S==="connect"&&h[0])n.wsClients.push({client:"io",parts:i(h[0]),line:u.startPosition.row+1}),v=!0;else if(S==="listen"&&h[0]){let y=Z(h[0]),x=y&&y.type==="object"?a(y,"port"):y;x&&n.listens.push({parts:i(x),line:u.startPosition.row+1}),v=!0}else if(S==="send"&&/^(client|conn|connection|peer)$/.test(w.replace(/^this./,"").split(".").pop())&&h[0]){let y=Z(h[0]),x=!1;if(y&&y.type==="call_expression"&&y.childForFieldName("function")?.text==="JSON.stringify"){let b=l(y)[0];x=!!(b&&(a(b,"type")||a(b,"event"))&&Z(a(b,"type")??a(b,"event"))?.type==="string")}x||n.wsServerSends.push({recv:w,line:u.startPosition.row+1}),v=!0}else if(S==="send"&&xo.test(w.replace(/^this\./,"").replace(/\.current$/,"").split(".").pop())){let y=h[0]?Z(h[0]):null,x=!1;if(y&&y.type==="call_expression"&&y.childForFieldName("function")?.text==="JSON.stringify"){let b=l(y)[0];x=!!(b&&(a(b,"type")||a(b,"event"))&&Z(a(b,"type")??a(b,"event"))?.type==="string")}x||n.wsSends.push({recv:w,line:u.startPosition.row+1}),v=!0}}if(!v){let g=null;if(m.type==="identifier"?g=m.text:m.type==="member_expression"&&(g=m.childForFieldName("property")?.text??null),!g||go.has(g)||h.length===0||h.length>6)continue;let w=[],S=!1;h.slice(0,5).forEach((N,y)=>{let x=Z(N);if(!x||x.type!=="string"&&x.type!=="template_string")return;let b=i(x);w.push({i:y,parts:b});let k=b[0];k&&k.t==="lit"&&(k.v.startsWith("/")||/^https?:\/\//.test(k.v))&&k.v.length>1&&(S=!0)}),S&&n.pathCallsites.push({callee:g,args:w,line:u.startPosition.row+1})}}let f=u=>u.replace(/^this./,"").replace(/.current$/,"").split(".").pop();for(let u of t.descendantsOfType("assignment_expression")){let m=u.childForFieldName("left");if(!m||m.type!=="member_expression"||m.childForFieldName("property")?.text!=="onmessage"||!xo.test(f(m.childForFieldName("object")?.text??"")))continue;let h=Z(u.childForFieldName("right"));n.wsReceivers.push({line:u.startPosition.row+1,handlerName:h&&h.type==="identifier"?h.text:null})}for(let u of t.descendantsOfType("call_expression")){let m=Z(u.childForFieldName("function"));if(!m||m.type!=="member_expression"||m.childForFieldName("property")?.text!=="addEventListener")continue;let h=l(u),v=h[0]&&Z(h[0]);if(!v||v.type!=="string"||Dt(v)!=="message"||!xo.test(f(m.childForFieldName("object")?.text??"")))continue;let g=h[1]&&Z(h[1]);n.wsReceivers.push({line:u.startPosition.row+1,handlerName:g&&g.type==="identifier"?g.text:null})}for(let u of t.descendantsOfType("new_expression")){let m=Z(u.childForFieldName("constructor"));if(!m)continue;let h=m.text,v=l(u);if(Bc.has(h)&&v[0])n.wsClients.push({client:h,parts:i(v[0]),line:u.startPosition.row+1});else if(/^(WebSocketServer|WebSocket\.Server|WebSocket\.WebSocketServer|ws\.Server|ws\.WebSocketServer|Server)$/.test(h)){if(h==="Server"&&!/socket\.io|socketio/i.test(e.rootNode.text.slice(0,4e3)+""))continue;let g=a(v.find(w=>Z(w)?.type==="object"),"path");n.wsServers.push({path:g?i(g):null,line:u.startPosition.row+1})}}return n}var zc=new Set(["function_declaration","generator_function_declaration","function_expression","generator_function","arrow_function","method_definition"]),Wc=new Set(["arrow_function","function_expression","generator_function"]);function qe(e,t){if(e)switch(e.type){case"identifier":case"shorthand_property_identifier_pattern":t.push(e.text);return;case"assignment_pattern":qe(e.childForFieldName("left"),t);return;case"rest_pattern":case"object_pattern":case"array_pattern":case"pair_pattern":case"required_parameter":case"optional_parameter":for(let n of e.namedChildren)qe(e.type==="pair_pattern"?e.childForFieldName("value"):n,t);return;default:if(e.type==="pattern"||e.namedChildCount){let n=e.childForFieldName?.("pattern");n&&qe(n,t)}}}function qc(e,t){let n=e;if(n.type==="export_statement"&&(n=n.childForFieldName("declaration")),!n)return null;if(n.type==="function_declaration"||n.type==="generator_function_declaration")return n.childForFieldName("name")?.text===t?{kind:"fn",declLine:n.startPosition.row+1}:null;if(n.type==="lexical_declaration"||n.type==="variable_declaration"){for(let r of n.namedChildren){if(r.type!=="variable_declarator")continue;let o=r.childForFieldName("name");if(o?.type==="identifier"){if(o.text!==t)continue;let i=ce(r.childForFieldName("value"));return i&&Wc.has(i.type)?{kind:"fn",declLine:r.startPosition.row+1}:{kind:"other"}}let s=[];if(qe(o,s),s.includes(t))return{kind:"other"}}return null}return(n.type==="class_declaration"||n.type==="abstract_class_declaration"||n.type==="enum_declaration")&&n.childForFieldName("name")?.text===t?{kind:"other"}:null}function Gc(e){let t=e.namedChildren.find(o=>o.type==="string")?.text.slice(1,-1)??null,n=e.namedChildren.find(o=>o.type==="import_clause"),r=[];if(!n||t==null)return{src:t,out:r};for(let o of n.namedChildren)if(o.type==="identifier")r.push({kind:"default",local:o.text,imported:null});else if(o.type==="namespace_import"){let s=o.namedChildren.find(i=>i.type==="identifier");s&&r.push({kind:"ns",local:s.text,imported:null})}else if(o.type==="named_imports")for(let s of o.namedChildren){if(s.type!=="import_specifier")continue;let i=s.childForFieldName("name"),a=s.childForFieldName("alias");i&&r.push({kind:"named",local:(a??i).text,imported:i.text})}return{src:t,out:r}}function es(e){let t=[];for(let n of e.rootNode.namedChildren)if(n.type==="import_statement"){if(n.children.some(i=>i.type==="type"))continue;let r=n.namedChildren.find(i=>i.type==="import_require_clause");if(r){let i=r.namedChildren.find(l=>l.type==="identifier"),a=r.namedChildren.find(l=>l.type==="string");i&&a&&t.push({source:Ut(a),kind:"cjs",local:i.text,imported:null});continue}let{src:o,out:s}=Gc(n);for(let i of s)t.push({source:o,...i})}else if(n.type==="lexical_declaration"||n.type==="variable_declaration")for(let r of n.namedChildren){if(r.type!=="variable_declarator")continue;let o=ce(r.childForFieldName("value")),s=null;o?.type==="member_expression"&&(s=o.childForFieldName("property")?.text??null,o=ce(o.childForFieldName("object")));let i=mn(o);if(i==null)continue;let a=r.childForFieldName("name");if(a?.type==="identifier")t.push({source:i,kind:s?"named":"cjs",local:a.text,imported:s});else if(a?.type==="object_pattern"&&!s){for(let l of a.namedChildren)if(l.type==="shorthand_property_identifier_pattern")t.push({source:i,kind:"named",local:l.text,imported:l.text});else if(l.type==="pair_pattern"){let c=l.childForFieldName("key"),d=l.childForFieldName("value");c&&d?.type==="identifier"&&t.push({source:i,kind:"named",local:d.text,imported:c.text})}}}return t}var Ut=e=>e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("");function mn(e){if(e?.type!=="call_expression")return null;let t=e.childForFieldName("function"),n=e.childForFieldName("arguments");if(t?.type!=="identifier"||t.text!=="require"||!n||n.namedChildCount!==1)return null;let r=n.namedChildren[0];return r.type==="string"?Ut(r):null}function ts(e){let t=[];return(function n(r){if(r.type==="export_statement"){let o=r.childForFieldName("source");o&&!r.children.some(s=>s.type==="type")&&t.push({source:Ut(o),startLine:o.startPosition.row+1})}else if(r.type==="import_require_clause"){let o=r.namedChildren.find(s=>s.type==="string");o&&t.push({source:Ut(o),startLine:o.startPosition.row+1})}else if(r.type==="call_expression"){let o=mn(r);o!=null&&t.push({source:o,startLine:r.startPosition.row+1})}for(let o of r.namedChildren)n(o)})(e.rootNode),t}function ns(e){let t={default:null,named:{},reexports:[],stars:[],nsReexports:[]};for(let n of e.rootNode.namedChildren){if(n.type!=="export_statement")continue;let r=n.children.some(i=>i.type==="default"),o=n.childForFieldName("declaration"),s=n.childForFieldName("source")!=null;if(r){if(o){let i=o.childForFieldName("name");t.default=i&&(o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"||o.type==="abstract_class_declaration")?i.text:"<anon>"}else{let i=ce(n.childForFieldName("value"));t.default=i?.type==="identifier"?i.text:"<anon>"}continue}if(o){if(o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"||o.type==="abstract_class_declaration"){let i=o.childForFieldName("name")?.text;i&&(t.named[i]=i)}else if(o.type==="lexical_declaration"||o.type==="variable_declaration")for(let i of o.namedChildren){let a=i.type==="variable_declarator"?i.childForFieldName("name"):null;a?.type==="identifier"&&(t.named[a.text]=a.text)}continue}if(s){if(n.children.some(c=>c.type==="type"))continue;let i=Ut(n.childForFieldName("source")),a=n.namedChildren.find(c=>c.type==="export_clause"),l=n.namedChildren.find(c=>c.type==="namespace_export");if(a)for(let c of a.namedChildren){if(c.type!=="export_specifier")continue;let d=c.childForFieldName("name")?.text,p=c.childForFieldName("alias")?.text;d&&t.reexports.push({exported:p??d,imported:d,source:i})}else if(l){let c=l.namedChildren.find(d=>d.type==="identifier");c&&t.nsReexports.push({exported:c.text,source:i})}else t.stars.push(i);continue}for(let i of n.namedChildren)if(i.type==="export_clause")for(let a of i.namedChildren){if(a.type!=="export_specifier")continue;let l=a.childForFieldName("name")?.text,c=a.childForFieldName("alias")?.text;l&&(c==="default"?t.default=l:t.named[c??l]=l)}}for(let n of e.rootNode.namedChildren){let r=n.type==="expression_statement"?n.namedChildren[0]:null;if(r?.type!=="assignment_expression")continue;let o=r.childForFieldName("left"),s=ce(r.childForFieldName("right"));if(o?.type!=="member_expression")continue;let i=o.childForFieldName("object"),a=o.childForFieldName("property")?.text,l=c=>c?.type==="member_expression"&&c.childForFieldName("object")?.text==="module"&&c.childForFieldName("property")?.text==="exports";if(l(o))if(s?.type==="identifier")t.default=s.text;else if(s?.type==="object"){for(let c of s.namedChildren)if(c.type==="shorthand_property_identifier")t.named[c.text]=c.text;else if(c.type==="pair"){let d=c.childForFieldName("key"),p=ce(c.childForFieldName("value"));d&&p?.type==="identifier"&&(t.named[d.text.replace(/^['"]|['"]$/g,"")]=p.text)}t.default??="<object>"}else mn(s)!=null?t.stars.push(mn(s)):t.default="<anon>";else a&&(i?.type==="identifier"&&i.text==="exports"||l(i))&&s?.type==="identifier"&&(t.named[a]=s.text)}return t}function Jc(e,t,n){for(let r=e.parent;r;r=r.parent)if(zc.has(r.type)){let o=[],s=r.childForFieldName("parameters");if(s)for(let a of s.namedChildren)qe(a,o);let i=r.childForFieldName("parameter");if(i&&qe(i,o),r.type==="function_expression"||r.type==="generator_function"){let a=r.childForFieldName("name");a&&o.push(a.text)}if(o.includes(t))return{kind:"other"}}else if(r.type==="catch_clause"){let o=[];if(qe(r.childForFieldName("parameter"),o),o.includes(t))return{kind:"other"}}else if(r.type==="for_in_statement"||r.type==="for_statement"){let o=[],s=r.type==="for_statement"?r.childForFieldName("initializer"):r.childForFieldName("left");if(s)if(s.type==="lexical_declaration"||s.type==="variable_declaration")for(let i of s.namedChildren)qe(i.childForFieldName?.("name"),o);else qe(s,o);if(o.includes(t))return{kind:"other"}}else if(r.type==="statement_block"||r.type==="program"||r.type==="switch_body"){if(r.type==="program"&&n.has(t))return{kind:"import",imp:n.get(t)};for(let o of r.namedChildren){let s=qc(o,t);if(s)return s}if(r.type==="program"&&n.has(t))return{kind:"import",imp:n.get(t)}}return null}var Kc=e=>(e.childForFieldName("function")?.text??"").replace(/\s+/g," ").slice(0,40);function os(e,t){let n=new Map(t.map(s=>[s.local,s])),r=[],o=(s,i,a)=>{let l=ce(s);if(!l||l.type!=="identifier"&&l.type!=="shorthand_property_identifier")return;let c=l.text,d=Jc(l,c,n);if(!d||d.kind==="other")return;let p=tt(a).nameNode,f={name:c,line:l.startPosition.row+1,column:l.startPosition.column,via:i,callee:Kc(a),callLine:p.startPosition.row+1,callColumn:p.startPosition.column,b:d.kind};d.kind==="fn"?f.declLine=d.declLine:(f.src=d.imp.source,f.ik=d.imp.kind,f.imp=d.imp.imported),r.push(f)};return(function s(i){if(i.type==="call_expression"){let a=i.childForFieldName("arguments");for(let l of a?.namedChildren??[]){let c=ce(l);if(c)if(c.type==="array")for(let d of c.namedChildren)o(d,"array",i);else if(c.type==="object")for(let d of c.namedChildren)d.type==="pair"?o(d.childForFieldName("value"),"object",i):d.type==="shorthand_property_identifier"&&o(d,"object",i);else o(c,"arg",i)}}for(let a of i.namedChildren)s(a)})(e.rootNode),r}function rs(e){let t=[],n=o=>{let s=o?.namedChildren.find(i=>i.type!=="comment");return s?.type==="type_identifier"?s.text:null},r=o=>{let s=o.childForFieldName("name")?.text,i=o.childForFieldName("body");if(!(!s||!i)){for(let a of i.namedChildren)if(a.type==="public_field_definition"){let l=a.childForFieldName("name"),c=n(a.childForFieldName("type"));l?.type==="property_identifier"&&c&&t.push({className:s,prop:l.text,type:c})}else if(a.type==="method_definition"&&a.childForFieldName("name")?.text==="constructor")for(let l of a.childForFieldName("parameters")?.namedChildren??[]){if(l.type!=="required_parameter"&&l.type!=="optional_parameter"||!l.namedChildren.some(p=>p.type==="accessibility_modifier")&&!l.children.some(p=>p.type==="readonly"))continue;let c=l.childForFieldName("pattern"),d=n(l.childForFieldName("type"));c?.type==="identifier"&&d&&t.push({className:s,prop:c.text,type:d})}}};for(let o of e.rootNode.namedChildren){let s=o.type==="export_statement"?o.childForFieldName("declaration"):o;s&&(s.type==="class_declaration"||s.type==="abstract_class_declaration")&&r(s)}return t}var Vc={Get:"get",Post:"post",Put:"put",Patch:"patch",Delete:"delete",All:"all"};function ss(e){let t=e.namedChildren[0];if(!t)return null;if(t.type==="call_expression"){let n=t.childForFieldName("function"),r=n?.type==="identifier"?n.text:null;return r?{name:r,args:t.childForFieldName("arguments")}:null}return t.type==="identifier"?{name:t.text,args:null}:null}var ct=e=>e?e.type==="string"?e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join(""):e.type==="template_string"&&!e.namedChildren.some(t=>t.type==="template_substitution")?e.text.slice(1,-1):null:null;function is(e){let t=e?.namedChildren.find(n=>n.type!=="comment");if(!t)return"";if(t.type==="array")return ct(t.namedChildren.find(n=>n.type!=="comment"))??"";if(t.type==="object"){for(let n of t.namedChildren){if(n.type!=="pair")continue;let r=n.childForFieldName("key");if(r?.text==="path"||r?.text==="'path'"||r?.text==='"path"'){let o=n.childForFieldName("value");return(o?.type==="array"?ct(o.namedChildren[0]):ct(o))??""}}return""}return ct(t)??""}var hn=(...e)=>"/"+e.map(n=>String(n??"").replace(/^\/+|\/+$/g,"")).filter(Boolean).join("/");function as(e){let t=[],n=(r,o)=>{let s=r.childForFieldName("name")?.text,i=r.childForFieldName("body");if(!s||!i)return;let l=[...o,...r.namedChildren.filter(p=>p.type==="decorator")].map(ss).filter(Boolean).find(p=>p.name==="Controller");if(!l)return;let c=is(l.args),d=[];for(let p of i.namedChildren)if(p.type!=="comment"){if(p.type==="decorator"){d.push(p);continue}if(p.type==="method_definition"){let f=p.childForFieldName("name")?.text;for(let u of d.map(ss).filter(Boolean)){let m=Vc[u.name];!m||!f||t.push({method:m,path:hn(c,is(u.args)),startLine:p.startPosition.row+1,handlerName:null,isInlineHandler:!1,handlerStartLine:null,handlerEndLine:null,handlerStartIndex:null,handlerEndIndex:null,nest:{className:s,methodName:f}})}}d=[]}};for(let r of e.rootNode.namedChildren)if(r.type==="export_statement"){let o=r.childForFieldName("declaration");o&&(o.type==="class_declaration"||o.type==="abstract_class_declaration")&&n(o,r.namedChildren.filter(s=>s.type==="decorator"))}else(r.type==="class_declaration"||r.type==="abstract_class_declaration")&&n(r,[]);return t}function cs(e){let t=[];return(function n(r){if(r.type==="call_expression"){let o=r.childForFieldName("function");if(o?.type==="member_expression"&&o.childForFieldName("property")?.text==="setGlobalPrefix"){let s=(r.childForFieldName("arguments")?.namedChildren??[]).filter(c=>c.type!=="comment"),i=s[0]?ct(s[0]):null,a=[],l=s[1];if(l?.type==="object")for(let c of l.namedChildren){if(c.type!=="pair"||c.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")!=="exclude")continue;let d=c.childForFieldName("value");for(let p of d?.type==="array"?d.namedChildren:[])if(p.type==="object"){for(let f of p.namedChildren)if(f.type==="pair"&&f.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")==="path"){let u=ct(f.childForFieldName("value"));u!=null&&a.push(u)}}else{let f=ct(p);f!=null&&a.push(f)}}t.push({prefix:i||null,exclude:a})}}for(let o of r.namedChildren)n(o)})(e.rootNode),t}function ls(e){let t=[];for(let s of e.values())for(let i of s?.globalPrefix??[])t.push(i);if(!t.length||t.some(s=>!s.prefix||s.prefix!==t[0].prefix))return e;let n=t[0].prefix,r=new Set(t.flatMap(s=>s.exclude).map(s=>hn(s))),o=new Map;for(let[s,i]of e){if(!i?.routes?.some(a=>a.nest)){o.set(s,i);continue}o.set(s,{...i,routes:i.routes.map(a=>a.nest&&!r.has(hn(a.path))?{...a,path:hn(n,a.path)}:a)})}return o}import Yc from"node:crypto";var ds=e=>Yc.createHash("sha256").update(e).digest("hex");function Xc(e,t=null){let n=[],r=o=>{if(o.childCount===0){if(o.type==="comment")return;let s=t?t.slice(o.startIndex,o.endIndex):o.text,i=o.type==="jsx_text"?s.replace(/\s+/g," ").trim():s;if(i==="")return;n.push({s:o.startIndex,e:o.endIndex,t:i});return}for(let s=0;s<o.childCount;s++)r(o.child(s))};return r(e),n}function fs(e,t){let n=[];for(let s of[t.functions,t.arrowFunctions,t.classMethods])for(let i of s??[])i.startIndex!=null&&n.push({s:i.startIndex,e:i.endIndex,item:i,field:"bodyHash"});for(let s of[t.routes,t.listeners,t.socketListeners])for(let i of s??[])i.isInlineHandler&&i.handlerStartIndex!=null&&n.push({s:i.handlerStartIndex,e:i.handlerEndIndex,item:i,field:"handlerBodyHash"});let r=new Map(n.map(s=>[s,[]])),o=[];for(let s of Xc(e.rootNode,e.canopyOriginalSource??null)){let i=null,a=1/0;for(let l of n)s.s>=l.s&&s.e<=l.e&&l.e-l.s<a&&(i=l,a=l.e-l.s);(i?r.get(i):o).push(s.t)}for(let s of n)s.item[s.field]=ds(r.get(s).join(" "));t.moduleBodyHash=ds(o.join(" "))}function us(e,t){return ee(t,"matchFastifyRoutes.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(c=>c.name==="http_method"),i=o.captures.find(c=>c.name==="route_path"),a=o.captures.find(c=>c.name==="handler_ref"),l=o.captures.find(c=>c.name==="handler_inline");return{method:s.node.text,path:i.node.text,startLine:s.node.startPosition.row+1,handlerName:a?a.node.text:null,isInlineHandler:!!l,handlerStartLine:l?l.node.startPosition.row+1:null,handlerEndLine:l?l.node.endPosition.row+1:null,handlerStartIndex:l?l.node.startIndex:null,handlerEndIndex:l?l.node.endIndex:null}})}function ps(e,t){return ee(t,"matchExtensionListeners.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(m=>m.name==="event_type"),i=o.captures.find(m=>m.name==="event_name"),a=o.captures.find(m=>m.name==="method_name"||m.name==="listener_method"),l=o.captures.find(m=>m.name==="handler_ref"),c=o.captures.find(m=>m.name==="target"),d=o.captures.find(m=>m.name==="root_object"),p=o.captures.find(m=>m.name==="sub_object"),f=c?c.node.text:d?d.node.text+(p?"."+p.node.text:""):null,u=o.captures.find(m=>m.name==="handler_inline");return{eventName:s?.node.text??i?.node.text??"unknown",targetName:f,startLine:a.node.startPosition.row+1,handlerName:l?l.node.text:null,isInlineHandler:!!u,handlerStartLine:u?u.node.startPosition.row+1:null,handlerEndLine:u?u.node.endPosition.row+1:null,handlerStartIndex:u?u.node.startIndex:null,handlerEndIndex:u?u.node.endIndex:null}})}import nl from"node:fs";Le();import Re from"node:fs";import oe from"node:path";import Zc from"node:os";import hs from"node:crypto";import{fileURLToPath as Qc}from"node:url";var el=oe.dirname(Qc(globalThis.__canopyUrl("src/stage2_parse/parseCache.js"))),gs=oe.join(el,"..",".."),vo=process.env.CANOPY_CACHE_DIR||(bt()?oe.join(Zc.homedir(),".canopy-cache"):oe.join(gs,".canopy-cache")),ms=e=>hs.createHash("sha256").update(e).digest("hex");function gn(e,t){return Re.readdirSync(e,{withFileTypes:!0}).flatMap(n=>n.isDirectory()?gn(oe.join(e,n.name),t):t.some(r=>n.name.endsWith(r))?[oe.join(e,n.name)]:[]).sort()}var wo=null;function tl(){if(wo)return wo;let e=oe.join(gs,"src"),t=!Re.existsSync(e)&&globalThis.__canopyBundle,n=t?[t,...gn(oe.join(oe.dirname(t),"queries"),[".scm"])]:[...gn(oe.join(e,"stage2_parse"),[".js",".scm"]),...gn(oe.join(e,"stage5_entrypoints"),[".js"]).filter(o=>/match/i.test(oe.basename(o))),oe.join(e,"utils","loadQuery.js")],r=hs.createHash("sha256");for(let o of n)r.update(oe.relative(t?oe.dirname(t):e,o).split(oe.sep).join("/")).update("\0").update(Re.readFileSync(o).toString("utf8").replace(/\r\n/g,`
17
+ `)).update("\0");for(let o of["web-tree-sitter","tree-sitter-javascript","tree-sitter-typescript"])try{r.update(o+"@"+JSON.parse(Re.readFileSync(oe.join(je(o),"package.json"),"utf8")).version)}catch{r.update(o+"@?")}return wo=r.digest("hex").slice(0,16)}function ys(){let e=tl(),t=oe.join(vo,e);Re.mkdirSync(t,{recursive:!0});for(let n of Re.readdirSync(vo,{withFileTypes:!0}))n.isDirectory()&&n.name!==e&&Re.rmSync(oe.join(vo,n.name),{recursive:!0,force:!0});return{version:e,keyFor:(n,r="javascript")=>ms(r==="javascript"?n:Buffer.concat([Buffer.from(r+"\0"),n])),get(n){try{return JSON.parse(Re.readFileSync(oe.join(t,n+".json"),"utf8"))}catch{return null}},set(n,r){let o=oe.join(t,`${n}.${process.pid}.tmp`);Re.writeFileSync(o,JSON.stringify(r)),Re.renameSync(o,oe.join(t,n+".json"))}}}function xs(e){return JSON.parse(JSON.stringify(e,(t,n)=>n&&typeof n=="object"&&n.startPosition&&n.endPosition&&"type"in n&&"tree"in n?void 0:n))}var vs=Number(process.env.CANOPY_PARSE_BUDGET_MS)||3e4,ko=class extends Error{constructor(t){super(`parse time budget exceeded (limit ${vs/1e3} s; stopped after ${(t/1e3).toFixed(1)} s)`),this.name="ParseBudgetError"}},ol=100;function So(e,t,n){return e.map(r=>({...r,returns:Wr(t,n,r)}))}function ws(e,t,n,{cache:r=!0,onProgress:o=console.log,grammars:s=null}={}){let i=new Map,a=0,l=0,c=0,d=r?ys():null,p=[],f=0;for(let u of e){f>0&&f%ol===0&&o(` parsing: ${f}/${e.length} files (${c} from cache)`),f++;try{let m=nl.readFileSync(u),h=po(u),v=d?.keyFor(m,h),g=d?d.get(v):null;if(g){i.set(u,g),c++;continue}l++;let w=performance.now(),S=()=>{let O=performance.now()-w;if(O>vs)throw new ko(O)},N=h==="javascript"?{parser:t,language:n}:s?.get(h);if(!N)throw new Error(`no ${h} grammar loaded`);let y=N.language;Er(h);let{tree:x}=$r(N.parser,u);S();let b=[],k=(O,W,G=[])=>{try{return W()}catch(te){if(te.name==="ParseBudgetError")throw te;return b.push({extractor:O,message:String(te.message).slice(0,160)}),G}},$=k("functionDeclarations",()=>So(Ar(x,y),x,y));S();let j=k("arrowFunctions",()=>So(Or(x,y),x,y));S();let D=k("classMethods",()=>So(Mr(x,y),x,y));S();let L=k("importBindings",()=>es(x)),K={functions:$,arrowFunctions:j,classMethods:D,imports:k("imports",()=>[...Hr(x,y),...ts(x)]),calls:(S(),k("calls",()=>Dr(x,y))),methodCalls:(S(),k("methodCalls",()=>Ur(x,y))),returnEntries:k("returnEntries",()=>Br(x,y)),jsxElements:k("jsxElements",()=>qr(x,y)),callSites:(S(),k("callSites",()=>Xr(x))),apiCalls:(S(),k("apiCalls",()=>Gr(x,y))),socketEmits:k("socketEmits",()=>Jr(x,y)),socketListeners:k("socketListeners",()=>Yr(x,y)),rawSocketSends:k("rawSocketSends",()=>Kr(x,y)),rawSocketTypeChecks:k("rawSocketTypeChecks",()=>Vr(x,y)),routes:k("routes",()=>[...us(x,y),...et(y)?as(x):[]]),listeners:k("listeners",()=>ps(x,y)),refArgs:k("refArgs",()=>os(x,L)),globalPrefix:k("globalPrefix",()=>cs(x)),importBindings:L,classProps:k("classProps",()=>et(y)?rs(x):[]),httpClients:k("httpClients",()=>Qr(x),null),exportBindings:k("exportBindings",()=>ns(x),null),hadErrors:mo(x),exportedNames:k("exports",()=>zr(x,y)),failed:!1,warnings:b};k("bodyHash",()=>fs(x,K),null);let z=xs(K);d&&d.set(v,z),i.set(u,z)}catch(m){if(m.name==="ParseBudgetError"){p.push({filePath:u,reason:m.message}),i.set(u,{functions:[],arrowFunctions:[],classMethods:[],imports:[],calls:[],methodCalls:[],returnEntries:[],jsxElements:[],callSites:[],apiCalls:[],socketEmits:[],socketListeners:[],rawSocketSends:[],rawSocketTypeChecks:[],routes:[],listeners:[],hadErrors:!1,failed:!1,skipped:m.message}),console.warn(` ! Skipped ${u}: ${m.message}`);continue}a++,i.set(u,{functions:[],arrowFunctions:[],classMethods:[],imports:[],calls:[],methodCalls:[],returnEntries:[],jsxElements:[],callSites:[],apiCalls:[],socketEmits:[],socketListeners:[],rawSocketSends:[],rawSocketTypeChecks:[],routes:[],listeners:[],hadErrors:!0,failed:!0,errorMessage:m.message}),console.warn(` ! Failed to parse ${u}: ${m.message}`)}}return console.log(`Parsed ${i.size} files (${a} failed)`),console.log(` parse cache: ${l} file(s) parsed, ${c} served from cache`),i.cacheStats={parsed:l,cacheHits:c},i.budgetSkips=p,i}function yn(e,t){return`${e}::${t}`}var Ss=[{category:"frontend",patterns:["frontend","client","src/components","ui","src/pages","public"]},{category:"backend",patterns:["backend","server","api","realtime-backend"]},{category:"transport",patterns:["websocket","socket","realtime"]},{category:"data",patterns:["redis","database","models","db"]}];function xn(e){let t=e.toLowerCase().replace(/\\/g,"/");for(let{category:n,patterns:r}of Ss)for(let o of r)if(t.includes(o))return n;return"unknown"}import No from"node:fs";import ye from"node:path";import vn from"node:fs";import Ge from"node:path";var rl=["index.html","public/index.html","src/index.html"],sl=/^(build|esbuild|vite\.config|webpack\.config|rollup\.config|bundle)[\w.-]*\.(mjs|cjs|js|ts)$/i;function il(e){let t=e.replace(/<!--[\s\S]*?-->/g,""),n=[];for(let r of t.matchAll(/<script\b[^>]*?\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)')/gi))n.push(r[1]??r[2]);return n}function al(e){let t=[],n=[];try{n=vn.readdirSync(e).filter(r=>sl.test(r)).sort()}catch{return t}for(let r of n){let o;try{o=vn.readFileSync(Ge.join(e,r),"utf8")}catch{continue}let s=/\boutfile\s*:\s*["'`]([^"'`]+)["'`]/.exec(o)?.[1]??null,i=/\b(?:entryPoints|entry|input)\s*:\s*\[?\s*["'`]([^"'`]+)["'`]/.exec(o)?.[1]??null;i&&t.push({config:r,outfile:s,entry:i})}return t}function wn(e,t,n=new Set(t.map(r=>Ge.resolve(r)))){for(let r of rl){let o=Ge.join(e,r);if(!vn.existsSync(o))continue;let s;try{s=vn.readFileSync(o,"utf8")}catch{continue}let i=Ge.dirname(o),a=d=>{let p=d.split(/[?#]/)[0];return!p||/^([a-z]+:)?\/\//i.test(p)?null:Ge.resolve(p.startsWith("/")?Ge.join(e,p):Ge.join(i,p))},l=il(s).map(d=>({s:d,p:a(d)})).filter(d=>d.p);for(let{s:d,p}of l)if(n.has(p))return{indexHtml:o,script:d,entry:p,via:"script"};let c=al(e);for(let{s:d,p}of l)for(let f of c){if(!f.outfile||Ge.resolve(e,f.outfile)!==p)continue;let u=Ge.resolve(e,f.entry);if(n.has(u))return{indexHtml:o,script:d,entry:u,via:`${f.config} (outfile ${f.outfile})`}}}return null}var cl=new Set(["test","tests","__tests__","fixtures","__fixtures__","__mocks__","e2e","cypress"]);function It(e){let t=String(e).replace(/\\/g,"/").split("/").filter(Boolean);if(!t.length)return!1;for(let n of t.slice(0,-1))if(cl.has(n.toLowerCase()))return!0;return/\.(test|spec)\.[^./]+$/i.test(t[t.length-1])}function ll(e){let t=ye.join(e,"package.json");if(!No.existsSync(t))return null;try{return JSON.parse(No.readFileSync(t,"utf-8"))}catch{return null}}function dl(e){return[...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{})]}function fl(e){let t=!!e.workspaces,n=Object.keys(e.dependencies??{}).length>0,r=!!(e.scripts&&e.scripts.start);return t&&!n&&!r}var ul=["react","vue","svelte","next","vite","webpack","parcel"],pl=["express","fastify","koa","hapi","socket.io","ws"],ml=[{deps:["mongodb","mongoose"],label:"MongoDB"},{deps:["redis","ioredis"],label:"Redis"},{deps:["pg","postgres"],label:"PostgreSQL"},{deps:["mysql","mysql2"],label:"MySQL"},{deps:["sqlite3","better-sqlite3"],label:"SQLite"},{deps:["@prisma/client"],label:"Prisma"},{deps:["drizzle-orm"],label:"Drizzle"}];function hl(e){let t=e.some(r=>ul.includes(r)),n=e.some(r=>pl.includes(r));return t&&!n?"client":n&&!t||n&&t?"server":"unknown"}function gl(e){let t=[];for(let{deps:n,label:r}of ml)n.some(o=>e.includes(o))&&!t.includes(r)&&t.push(r);return t}function ks(e){let t=new Set(["node_modules",".git","dist","build",".next","coverage"]);try{return No.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!t.has(n.name)&&!n.name.startsWith(".")).map(n=>ye.join(e,n.name))}catch{return[]}}function Ns(e,t=null){let n=[e];for(let o of ks(e)){n.push(o);for(let s of ks(o))n.push(s)}let r=[];for(let o of n){let s=ll(o);if(!s||fl(s))continue;let i=dl(s);r.push({name:s.name||ye.basename(o),rootPath:o,isRepoRoot:ye.resolve(o)===ye.resolve(e),kind:hl(i),datastores:gl(i)})}if(t){let o=new Set(t.map(i=>ye.resolve(i))),s=new Set(r.map(i=>ye.resolve(i.rootPath)));for(let i of n)ye.resolve(i)===ye.resolve(e)||s.has(ye.resolve(i))||It(ye.relative(e,i)+"/x")||wn(i,t,o)&&r.push({name:ye.basename(i),rootPath:i,isRepoRoot:!1,kind:"client",datastores:[],webRoot:!0})}return r}function lt(e,t){let n=null,r=-1;for(let o of t)o.isRepoRoot&&t.length>1&&!o.ownsLeftovers||(e===o.rootPath||e.startsWith(o.rootPath+ye.sep))&&o.rootPath.length>r&&(n=o.name,r=o.rootPath.length);return n}var yl=5,xl=.1;function bs(e,t,n){let r=ye.basename(ye.resolve(n)),o=l=>({name:l,rootPath:n,isRepoRoot:!0,ownsLeftovers:!0,kind:"unknown",datastores:[]});if(!t.length)return{services:e,added:null};if(!e.length)return{services:[o(r)],added:{name:r,reason:"no package.json found: the repo root is the one service",leftover:t.length}};let s=t.filter(l=>!lt(l,e)).length;if(s<yl||s<xl*t.length)return{services:e,added:null,leftover:s};let i=e.find(l=>l.isRepoRoot);if(i)return i.ownsLeftovers=!0,{services:e,added:{name:i.name,reason:`${s} of ${t.length} files sit outside every nested package: owned by the root package ${i.name}`,leftover:s}};let a=r;return e.some(l=>l.name.toLowerCase()===a.toLowerCase())&&(a=`${r} (root)`),{services:[...e,o(a)],added:{name:a,reason:`${s} of ${t.length} files sit outside every nested package: owned by a service named after the repo folder`,leftover:s}}}function _s(e,t=[]){let n=[];for(let[r,o]of e){let s=xn(r),i=lt(r,t);n.push({id:`${r}::__module_root__`,name:"module root",filePath:r,startLine:0,endLine:Number.MAX_SAFE_INTEGER,category:s,serviceName:i,type:"moduleRoot",bodyHash:o.moduleBodyHash??null});for(let a of o.functions)n.push({id:yn(r,a.name),name:a.name,filePath:r,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:s,serviceName:i,bodyHash:a.bodyHash??null,type:"function"});for(let a of o.arrowFunctions)n.push({id:yn(r,a.name),name:a.name,filePath:r,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:s,serviceName:i,bodyHash:a.bodyHash??null,type:"arrowFunction"});for(let a of o.classMethods)n.push({id:yn(r,`${a.className}.${a.methodName}`),name:a.methodName,className:a.className,filePath:r,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:s,serviceName:i,bodyHash:a.bodyHash??null,type:"classMethod"})}return n}function Te(e,t){let n=[];for(let s of t.routes??[])s.isInlineHandler&&n.push({item:s,line:s.startLine,key:`route:${String(s.method).toUpperCase()} ${s.path}`});for(let s of t.listeners??[])s.isInlineHandler&&n.push({item:s,line:s.startLine,key:`listener:${s.targetName??"unknown"}.${s.eventName}`});for(let s of t.socketListeners??[])s.isInlineHandler&&n.push({item:s,line:s.startLine,key:`socket:${s.eventName}`});n.sort((s,i)=>s.line-i.line);let r=new Map,o=new Map;for(let{item:s,key:i}of n){let a=(r.get(i)??0)+1;r.set(i,a),o.set(s,`${e}::${i}${a>1?`#${a}`:""}`)}return o}function $s(e,t=[]){let n=[];for(let[r,o]of e){let s=xn(r),i=lt(r,t),a=t.find(c=>c.name===i),l=Te(r,o);for(let c of o.routes??[]){if(!c.isInlineHandler)continue;let d=`${c.method.toUpperCase()} ${c.path}`;n.push({id:l.get(c),name:`${d} (inline handler)`,filePath:r,startLine:c.handlerStartLine??c.startLine,endLine:c.handlerEndLine??c.startLine,category:s,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:c.handlerBodyHash??null,trigger:{type:"route",label:d,resolvedVia:"inline"}})}for(let c of o.listeners??[])c.isInlineHandler&&n.push({id:l.get(c),name:`${c.eventName} (inline handler)`,filePath:r,startLine:c.handlerStartLine??c.startLine,endLine:c.handlerEndLine??c.startLine,category:s,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:c.handlerBodyHash??null,trigger:{type:"listener",label:c.eventName,resolvedVia:"inline"}});if(a?.kind==="server")for(let c of o.socketListeners??[])c.isInlineHandler&&n.push({id:l.get(c),name:`${c.eventName} (inline handler)`,filePath:r,startLine:c.handlerStartLine??c.startLine,endLine:c.handlerEndLine??c.startLine,category:s,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:c.handlerBodyHash??null,trigger:{type:"socketListener",label:c.eventName,resolvedVia:"inline"}})}return n}import vl from"node:fs";import wl from"node:crypto";var Fs=e=>wl.createHash("sha256").update(e).digest("hex");function Sn(e,t){return e.map(n=>[t(n),Fs(vl.readFileSync(n))]).sort((n,r)=>n[0]<r[0]?-1:n[0]>r[0]?1:0)}function kn(e){return Fs(e.map(([t,n])=>`${t}\0${n}`).join(`
18
+ `))}import bo from"node:path";function Nn(e){let t=bo.resolve(e),n=t.split(bo.sep).join("/"),r=[[t.toLowerCase(),t.length,bo.sep],[n.toLowerCase(),n.length,"/"]],o=s=>{if(typeof s!="string")return s;let i=s.toLowerCase();if(i===r[0][0]||i===r[1][0])return".";for(let[a,l,c]of r)if(i.startsWith(a+c)){let d=s.slice(l+1),p=d.indexOf("::");return(p<0?d:d.slice(0,p)).split("\\").join("/")+(p<0?"":d.slice(p))}return s};return{rel:o,repoRoot:n,replacer:(s,i)=>typeof i=="string"?o(i):i,json:(s,i)=>JSON.stringify(s,(a,l)=>typeof l=="string"?o(l):l,i),clone:s=>JSON.parse(JSON.stringify(s,(i,a)=>typeof a=="string"?o(a):a))}}function Is(e){let t=e.map((r,o)=>({e:r,i:o})).sort((r,o)=>String(r.e.fromNodeId).localeCompare(String(o.e.fromNodeId))||(r.e.line??0)-(o.e.line??0)||(r.e.column??0)-(o.e.column??0)||r.i-o.i),n=new Map;for(let{e:r}of t){let o=r.calleeNameRaw??r.eventName??r.url??"",s=`${r.fromNodeId??"\u2205"} | ${r.callKind??r.type} | ${o}`,i=(n.get(s)??0)+1;n.set(s,i),r.id=`${s} | #${i}`}return e}function js(e){let t=new Map;for(let n of e)t.has(n.id)||t.set(n.id,[]),t.get(n.id).push(n);for(let[n,r]of t)r.length<2||(r.sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine),r.forEach((o,s)=>{s>0&&(o.id=`${n}#${s+1}`)}));return e}function fe(e,t){let n=null;for(let r of t)r.type!=="moduleRoot"&&e>=r.startLine&&e<=r.endLine&&(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r);return n||t.find(r=>r.type==="moduleRoot")}function Cs(e,t){let n=[];for(let[o,s]of e){let i=t.filter(a=>a.filePath===o);for(let a of s.calls){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"call",callKind:a.callKind??"call",resolved:!1})}for(let a of s.methodCalls){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.methodName,objectNameRaw:a.objectName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"methodCall",callKind:a.callKind??"methodCall",resolved:!1})}for(let a of s.returnEntries??[]){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.label,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],deferred:a.deferred??!1,type:"returnValue",resolved:!1})}for(let a of s.jsxElements){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,type:"call",callKind:"jsx",resolved:!1})}for(let a of s.callSites??[]){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"callSite",callKind:a.callKind,chainHead:a.chainHead??null,chainHeadCalled:a.chainHeadCalled??!1,ctorName:a.ctorName??null,...a.thisProp?{thisProp:a.thisProp,thisMethod:a.thisMethod}:{},resolved:!1})}for(let a of s.socketEmits){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,eventName:a.eventName,line:a.startLine,type:"socketEmit",resolved:!1})}for(let a of s.rawSocketSends??[]){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,eventName:a.eventName,line:a.startLine,type:"rawSocketSend",resolved:!1})}for(let a of s.apiCalls){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,url:a.url,httpMethod:a.method,scope:a.scope,line:a.startLine,type:"apiCall",resolved:!1})}}let r=n.filter(o=>o.type==="apiCall").length;return n}function le(e,t){let n=new Map;for(let r of t)r.filePath===e&&n.set(r.name,r.id);return n}function Bt(e,t,n,r,o=null){if(n.has(e.calleeNameRaw))return{...e,targetNodeId:n.get(e.calleeNameRaw),confidence:.95,matchType:"local",resolved:!0};let s=[...r],i=r.legacySize??s.length,a=([,c])=>{let d=o?o.scopeOf(c):le(c,t);return d.has(e.calleeNameRaw)?{...e,targetNodeId:d.get(e.calleeNameRaw),confidence:.85,matchType:"import",resolved:!0}:null};for(let c=0;c<i;c++){let d=a(s[c]);if(d)return d}let l=o?.bind?.resolveName(e.fromFileId,e.calleeNameRaw);if(l)return{...e,targetNodeId:l.id,confidence:.85,matchType:"import",resolved:!0};for(let c=i;c<s.length;c++){let d=a(s[c]);if(d)return d}return{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function Es(e,t,n=null){let r=n?n.method(e.objectNameRaw,e.calleeNameRaw):t.find(s=>s.type==="classMethod"&&s.className===e.objectNameRaw&&s.name===e.calleeNameRaw);if(r)return{...e,targetNodeId:r.id,confidence:.6,matchType:"methodHeuristic",resolved:!0};let o=n?.bind?.resolveMember(e.fromFileId,e.objectNameRaw,e.calleeNameRaw);return o?{...e,targetNodeId:o.id,confidence:.85,matchType:"import",resolved:!0}:{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function Ps(e){return{...e,targetNodeId:null,confidence:0,matchType:"unresolvedExternal",resolved:!1}}function Ls(e,t,n,r,o=null){if(e.callKind==="new"&&e.ctorName){let s=Bt({...e,calleeNameRaw:e.ctorName},t,n,r,o);if(s.resolved)return{...s,calleeNameRaw:e.calleeNameRaw,matchType:s.matchType+"New"};let i=new Set([e.fromFileId,...r.values()]),a=o?o.ctorsOf(e.ctorName).find(l=>i.has(l.filePath)):t.find(l=>l.type==="classMethod"&&l.className===e.ctorName&&l.name==="constructor"&&i.has(l.filePath));return a?{...e,targetNodeId:a.id,confidence:a.filePath===e.fromFileId?.9:.8,matchType:(a.filePath===e.fromFileId?"local":"import")+"New",resolved:!0}:Ps(e)}if(e.callKind==="chainedCall"&&e.chainHead&&e.chainHeadCalled){let s=Bt({...e,calleeNameRaw:e.chainHead},t,n,r,o);if(s.resolved)return{...e,targetNodeId:s.targetNodeId,confidence:s.confidence*.8,matchType:"chainHead",resolved:!0}}return Ps(e)}import $o from"node:path";import Je from"node:fs";import B from"node:path";var Os=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Sl=["index.ts","index.tsx","index.mts","index.cts","index.js","index.jsx","index.mjs","index.cjs"],kl={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]};var Ms=null,Hs=e=>{Ms=e},Ds=()=>Ms,Rs=e=>B.resolve(e);function zt(e,t){e=B.resolve(e);let n=()=>{try{let i=B.join(e,"package.json");if(!Je.existsSync(i))return null;let a=JSON.parse(Je.readFileSync(i,"utf8")).main;if(typeof a!="string")return null;let l=B.resolve(e,a);return t.has(l)?l:Nl(l,t)}catch{return null}},r=B.extname(e);if(r&&t.has(e))return e;let o=kl[r];if(o)for(let i of o){let a=e.slice(0,-r.length)+i;if(t.has(a))return a}for(let i of Os)if(t.has(e+i))return e+i;let s=n();if(s)return s;for(let i of Sl){let a=B.join(e,i);if(t.has(a))return a}return null}function Nl(e,t){if(B.extname(e)&&t.has(e))return e;for(let r of Os)if(t.has(e+r))return e+r;return null}var _o=e=>{try{let n=Je.readFileSync(e,"utf8").replace(/^/,"").replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,(r,o)=>o??"");return JSON.parse(n.replace(/,(\s*[}\]])/g,"$1"))}catch{return null}};function Us(e,t=new Set){if(t.has(e))return{baseUrl:null,paths:null};t.add(e);let n=_o(e);if(!n)return{baseUrl:null,paths:null};let r=null,o=null,s=n.extends?Array.isArray(n.extends)?n.extends:[n.extends]:[];for(let a of s){if(typeof a!="string"||!a.startsWith("."))continue;let l=B.resolve(B.dirname(e),a);(!Je.existsSync(l)||Je.statSync(l).isDirectory())&&(l=Je.existsSync(l+".json")?l+".json":B.join(l,"tsconfig.json"));let c=Us(l,t);c.baseUrl&&(r=c.baseUrl),c.paths&&(o=c.paths)}let i=n.compilerOptions??{};if(typeof i.baseUrl=="string"&&(r=B.resolve(B.dirname(e),i.baseUrl)),i.paths&&typeof i.paths=="object"){let a=r??B.dirname(e);o=Object.entries(i.paths).map(([l,c])=>{let d=l.indexOf("*");return{prefix:d<0?l:l.slice(0,d),suffix:d<0?"":l.slice(d+1),wildcard:d>=0,targets:(Array.isArray(c)?c:[]).filter(p=>typeof p=="string").map(p=>B.resolve(a,p))}}).sort((l,c)=>c.prefix.length-l.prefix.length)}return{baseUrl:r,paths:o}}function bl(e,t){if(t=t.replace(/^\.\//,"").replace(/\/+$/,""),t.startsWith("!"))return[];let n=[],r=o=>{try{return Je.readdirSync(o,{withFileTypes:!0}).filter(s=>s.isDirectory()&&s.name!=="node_modules"&&!s.name.startsWith(".")).map(s=>B.join(o,s.name))}catch{return[]}};if(t.endsWith("/**")){let o=B.join(e,t.slice(0,-3)),s=i=>{for(let a of r(i))n.push(a),s(a)};s(o)}else t.endsWith("/*")?n.push(...r(B.join(e,t.slice(0,-2)))):t.includes("*")||n.push(B.join(e,t));return n}function _l(e){let t=[],r=_o(B.join(e,"package.json"))?.workspaces;Array.isArray(r)?t.push(...r):Array.isArray(r?.packages)&&t.push(...r.packages);try{let o=Je.readFileSync(B.join(e,"pnpm-workspace.yaml"),"utf8"),s=!1;for(let i of o.split(/\r?\n/)){if(/^packages\s*:/.test(i)){s=!0;continue}if(s){let a=/^\s*-\s*['"]?([^'"#\s]+)['"]?/.exec(i);a?t.push(a[1]):/^\S/.test(i)&&(s=!1)}}}catch{}return t}function Ts(e,t){if(e==null)return null;let n=o=>{if(typeof o=="string")return o;if(Array.isArray(o)){for(let s of o){let i=n(s);if(i)return i}return null}if(o&&typeof o=="object"){for(let s of["source","import","module","default","require","node"])if(s in o){let i=n(o[s]);if(i)return i}}return null};if(typeof e=="string"||Array.isArray(e))return t==="."?n(e):null;let r=Object.keys(e);if(!r.some(o=>o.startsWith(".")))return t==="."?n(e):null;if(e[t]!=null)return n(e[t]);for(let o of r){let s=o.indexOf("*");if(s>0&&t.startsWith(o.slice(0,s))&&t.endsWith(o.slice(s+1))){let i=n(e[o]);if(i)return i.replace("*",t.slice(s,t.length-(o.length-s-1)))}}return null}function Bs(e,t,n={}){let r=Rs(e),o=new Set(t),s=new Map,i=f=>{if(s.has(f))return s.get(f);let u=null,m=B.join(f,"tsconfig.json");return Je.existsSync(m)?u=Us(m):f!==r&&B.dirname(f)!==f&&f.startsWith(r)&&(u=i(B.dirname(f))),s.set(f,u),u},a=new Map;for(let f of _l(r))for(let u of bl(r,f)){let m=_o(B.join(u,"package.json"));m?.name&&!a.has(m.name)&&a.set(m.name,{dir:Rs(u),pkg:m})}let l=[...a.keys()].sort((f,u)=>u.length-f.length),c=(f,u,m)=>{let{dir:h,pkg:v}=a.get(f),g=[],w=S=>{if(!S)return;let N=B.resolve(h,S);g.push(N);let y=B.relative(h,N).split(B.sep);["dist","build","lib","out","esm","cjs"].includes(y[0])&&g.push(B.join(h,"src",...y.slice(1)))};if(u==="."){w(Ts(v.exports,"."));for(let S of["source","module","main"])typeof v[S]=="string"&&w(v[S]);g.push(B.join(h,"src","index"),B.join(h,"index"))}else w(Ts(v.exports,u)),g.push(B.join(h,u),B.join(h,"src",u));for(let S of g){let N=zt(S,m);if(N)return N}return null},d=f=>l.find(u=>f===u||f.startsWith(u+"/"))??null,p=(f,u)=>u?.paths?.some(m=>m.wildcard?f.startsWith(m.prefix)&&f.endsWith(m.suffix)&&f.length>=m.prefix.length+m.suffix.length:f===m.prefix)??!1;return{root:r,files:o,packages:a,isInternal(f,u){if(f.startsWith(".")||d(f))return!0;let m=i(B.dirname(u));return!!(p(f,m)||m?.baseUrl&&!f.startsWith("@")&&zt(B.join(m.baseUrl,f),o))},resolve(f,u,m){if(f.startsWith("."))return zt(B.resolve(B.dirname(u),f),m);let h=i(B.dirname(u));if(h?.paths&&n.paths!==!1)for(let g of h.paths){let w=null;if(g.wildcard?f.startsWith(g.prefix)&&f.endsWith(g.suffix)&&f.length>=g.prefix.length+g.suffix.length&&(w=f.slice(g.prefix.length,f.length-g.suffix.length)):f===g.prefix&&(w=""),w!=null){for(let S of g.targets){let N=zt(S.replace("*",w),m);if(N)return N}break}}let v=n.workspaces===!1?null:d(f);if(v){let g=c(v,f===v?".":"./"+f.slice(v.length+1),m);if(g)return g}if(h?.baseUrl&&n.paths!==!1){let g=zt(B.join(h.baseUrl,f),m);if(g)return g}return null}}}var As=new WeakMap;function zs(e){if(e instanceof Set)return e;let t=As.get(e);return t||As.set(e,t=new Set(e)),t}function Fo(e,t,n){if(!e.startsWith("."))return null;let r=$o.dirname(t),o=$o.resolve(r,e),s=[o,...ur().map(i=>`${o}${i}`),...pr().map(i=>$o.join(o,i))];for(let i of s)if(n.includes(i))return i;return null}function Ae(e,t,n){let r=Fo(e,t,n);if(r)return r;let o=Ds();return o?o.resolve(e,t,zs(n)):null}function jt(e,t,n){let r=new Map;for(let o of t){let s=Fo(o.source,e,n);s&&r.set(o.source,s)}r.legacySize=r.size;for(let o of t){if(r.has(o.source))continue;let s=Ae(o.source,e,n);s&&r.set(o.source,s)}return r}function Ws(e){let t=new Map,n=new Map,r=new Map;for(let o of e){if(o.type!=="classMethod")continue;let s=o.className+"\0"+o.name;n.has(s)||n.set(s,o),o.name==="constructor"&&(r.has(o.className)||r.set(o.className,[]),r.get(o.className).push(o))}return{scopeOf:o=>{let s=t.get(o);return s||(s=le(o,e),t.set(o,s)),s},method:(o,s)=>n.get(o+"\0"+s),ctorsOf:o=>r.get(o)??[]}}function Ct(e){return e?e.split("?")[0].split("/").map(t=>t.startsWith(":")||/^\d+$/.test(t)?"*":t).join("/"):""}var $l=new Set(["function","arrowFunction"]);function qs(e,t,n,r){let o=new Map;for(let c of t){let d=o.get(c.filePath);d||o.set(c.filePath,d=[]),d.push(c)}let s=new Set;for(let c of r)c.resolved&&c.fromNodeId&&c.targetNodeId&&s.add(c.fromNodeId+"\0"+c.targetNodeId);let i=(c,d)=>(o.get(c)??[]).find(p=>$l.has(p.type)&&d(p))??null,a=[];a.argBindings=[];let l=(c,d,p,f,u,m,h)=>{!d||!p||d.id===p.id||s.has(d.id+"\0"+p.id)||a.push({fromFileId:c,fromNodeId:d.id,calleeNameRaw:f,line:u,column:m,branchPath:[],firstArgText:null,deferred:!1,type:"reference",callKind:"reference",targetNodeId:p.id,confidence:h==="local"?.95:.85,matchType:h,resolved:!0})};for(let[c,d]of e){let p=o.get(c);if(p){for(let f of d.refArgs??[]){let u=null,m="local";if(f.b==="fn"?u=i(c,v=>v.name===f.name&&v.startLine===f.declLine):f.b==="import"&&(m="import",(f.ik==="default"||f.ik==="named"||f.ik==="cjs")&&(u=n.nodeForImport(c,f.src,f.ik,f.imp))),!u)continue;let h=fe(f.line,p);l(c,h,u,f.name,f.line,f.column,m),f.callLine!=null&&h&&h.id!==u.id&&a.argBindings.push({file:c,line:f.callLine,column:f.callColumn,targetNodeId:u.id,matchType:m,direct:f.via==="arg"})}for(let f of p){if(f.type!=="inlineHandler")continue;let u=null;for(let m of p)m===f||m.type==="moduleRoot"||m.startLine<=f.startLine&&m.endLine>=f.endLine&&!(m.startLine===f.startLine&&m.endLine===f.endLine)&&(!u||m.endLine-m.startLine<u.endLine-u.startLine)&&(u=m);u??=p.find(m=>m.type==="moduleRoot"),l(c,u,f,f.name,f.startLine,0,"local")}}}return a}function Gs(e,t,n,r){let o=new Map,s=new Map;for(let a of e){if(s.set(a.id,a),a.type!=="classMethod")continue;let l=a.filePath+"\0"+a.className+"\0"+a.name,c=o.get(l);c?c.push(a):o.set(l,[a])}let i=(a,l)=>{for(let c of o.keys())if(c.startsWith(a+"\0"+l+"\0"))return!0;return!1};return function(l){let c=s.get(l.fromNodeId);if(!c||c.type!=="classMethod")return null;let d=t.get(l.fromFileId),p=(d?.classProps??[]).find(v=>v.className===c.className&&v.prop===l.thisProp);if(!p)return null;let f=null,u=null,m=(d.importBindings??[]).find(v=>v.local===p.type);if(m){let v=m.kind==="default"||m.kind==="named"?r.resolveImport(l.fromFileId,m.source,m.kind,m.imported):null;v?.local&&v.local!=="default"&&(f=v.file,u=v.local)}else i(l.fromFileId,p.type)&&(f=l.fromFileId,u=p.type);if(!f)return null;let h=o.get(f+"\0"+u+"\0"+l.thisMethod);return!h||h.length!==1?null:{...l,targetNodeId:h[0].id,confidence:.9,matchType:"typedProperty",resolved:!0}}}var Fl=new Set(["function","arrowFunction"]);function bn(e,t,n){let r=new Map;for(let d of e){if(!Fl.has(d.type))continue;let p=d.filePath+"\0"+d.name;r.has(p)||r.set(p,d)}let o=new Map,s=(d,p)=>{let f=o.get(d);if(!f){f=new Map;for(let u of t.get(d)?.importBindings??[])f.has(u.local)||f.set(u.local,u);o.set(d,f)}return f.get(p)??null},i=(d,p)=>n(d).get(p)??null;function a(d,p,f=new Set){let u=d+"\0"+p;if(f.has(u))return null;f.add(u);let m=t.get(d)?.exportBindings;if(!m)return null;if(p==="default"){if(m.default)return{file:d,local:m.default==="<anon>"?"default":m.default}}else if(m.named?.[p])return{file:d,local:m.named[p]};for(let h of m.reexports??[]){if(h.exported!==p)continue;let v=i(d,h.source);if(v)return a(v,h.imported,f)}for(let h of m.nsReexports??[]){if(h.exported!==p)continue;let v=i(d,h.source);if(v)return{moduleFile:v}}if(p!=="default")for(let h of m.stars??[]){let v=i(d,h),g=v?a(v,p,f):null;if(g)return g}return null}let l=d=>d?.local?r.get(d.file+"\0"+d.local)??null:null;function c(d,p,f,u){let m=i(d,p);return m?f==="default"?a(m,"default"):f==="named"?a(m,u):{moduleFile:m,cjs:f==="cjs"}:null}return{lookupExport:a,resolveImport:c,nodeForImport(d,p,f,u){let m=c(d,p,f,u);return m?.moduleFile&&m.cjs?l(a(m.moduleFile,"default")):l(m)},resolveName(d,p){let f=s(d,p);return f?this.nodeForImport(d,f.source,f.kind,f.imported):null},resolveMember(d,p,f){let u=s(d,p);if(!u)return null;let m=c(d,u.source,u.kind,u.imported);return m?.moduleFile?l(a(m.moduleFile,f)):null},classForImport(d,p){let f=s(d,p);if(!f)return null;let u=c(d,f.source,f.kind,f.imported);return u?.local?{file:u.file,className:u.local==="default"?null:u.local}:null},bindingFor:s}}function Js(e,t,n,r,o,s,i){let a=[],l=Ws(t),c=new Map,d=g=>c.get(g)??jt(g,n.get(g)?.imports??[],r);l.bind=bn(t,n,d);let p=Gs(t,n,d,l.bind),f=new Map;for(let g of e)f.has(g.fromFileId)||f.set(g.fromFileId,[]),f.get(g.fromFileId).push(g);for(let[g,w]of f){let S=n.get(g),N=le(g,t),y=jt(g,S.imports,r);c.set(g,y);for(let x of w)if(x.type==="call")a.push(Bt(x,t,N,y,l));else if(x.type==="methodCall")a.push(Es(x,t,l));else if(x.type==="callSite")a.push((x.thisProp?p(x):null)??Ls(x,t,N,y,l));else if(x.type==="returnValue")a.push({...x,targetNodeId:null,confidence:0,matchType:"returnValue",resolved:!1});else if(x.type==="apiCall")if(x.scope==="external")a.push({...x,targetNodeId:null,confidence:null,matchType:"externalService",resolved:!1});else{let b=Ct(x.url),k=o.get(b);k?a.push({...x,targetNodeId:k,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...x,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(x.type==="socketEmit"){let b=s.get(x.eventName);b?a.push({...x,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...x,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(x.type==="rawSocketSend"){let b=i?.get(x.eventName);b?a.push({...x,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...x,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}}let u=qs(n,t,l.bind,a);for(let g of u)a.push(g);let m=new Map;for(let g of a){if(g.resolved||g.line==null||g.type!=="call"&&g.type!=="methodCall"&&g.type!=="callSite")continue;let w=g.fromFileId+" "+g.line+" "+g.column;(m.get(w)??m.set(w,[]).get(w)).push(g)}let h=[...u.argBindings].sort((g,w)=>w.direct-g.direct),v=new Set;for(let g of h){let w=g.file+" "+g.line+" "+g.column;if(v.has(w))continue;let S=(m.get(w)??[]).find(N=>N.fromNodeId!==g.targetNodeId);S&&(v.add(w),Object.assign(S,{targetNodeId:g.targetNodeId,confidence:g.matchType==="local"?.95:.85,matchType:"argument",resolved:!0,viaArgument:!0}))}return a}function Ks(e){let t=new Map,n=new WeakMap,r=l=>{if(typeof l=="string")return l.length>=20?"s"+l:null;if(l&&typeof l=="object"){let c=n.get(l);if(c===void 0){let d=JSON.stringify(l);c=d.length>=40?"j"+d:"",n.set(l,c)}return c||null}return null};(function l(c){let d=r(c);if(d){let p=t.get(d)??0;if(t.set(d,p+1),p>0)return}if(Array.isArray(c))for(let p of c)l(p);else if(c&&typeof c=="object")for(let p of Object.values(c))l(p)})(e);let o=[],s=new Map,i=l=>{let c=r(l),d=c&&t.get(c)>1;if(d&&s.has(c))return s.get(c);let p;if(typeof l=="string"?p=JSON.stringify(l):Array.isArray(l)?p="["+l.map(i).join(",")+"]":l&&typeof l=="object"?p="{"+Object.entries(l).map(([u,m])=>JSON.stringify(u)+":"+i(m)).join(",")+"}":p=JSON.stringify(l),!d)return p;let f="$"+o.length.toString(36);return o.push(`const ${f}=${p};`),s.set(c,f),f},a=i(e);return`(() => {${o.join(`
19
+ `)}
20
+ return ${a};})()`}function Io(e,t,n,r){if(!e)return{targetId:null,via:null};if(n.has(e))return{targetId:n.get(e),via:"in-file"};if(r)for(let[,o]of r){let s=le(o,t);if(s.has(e))return{targetId:s.get(e),via:"cross-file"}}return{targetId:null,via:null}}function Vs(e,t,n,r,o,s=[],i=null){if(!n.some(l=>!l.isInlineHandler)&&!r.some(l=>!l.isInlineHandler)&&!s.some(l=>!l.isInlineHandler))return e;let a=e.map(l=>({...l}));for(let l of n){if(l.isInlineHandler)continue;let c=l.nest?e.find(f=>f.type==="classMethod"&&f.filePath===t&&f.className===l.nest.className&&f.name===l.nest.methodName):null,{targetId:d,via:p}=l.nest?{targetId:c?.id??null,via:"in-file"}:Io(l.handlerName,e,o,i);if(d){let f=a.find(u=>u.id===d);f&&(f.isEntryPoint=!0,f.trigger={type:"route",label:`${l.method.toUpperCase()} ${l.path}`,resolvedVia:p})}}for(let l of r){if(l.isInlineHandler)continue;let{targetId:c,via:d}=Io(l.handlerName,e,o,i);if(c){let p=a.find(f=>f.id===c);p&&(p.isEntryPoint=!0,p.trigger={type:"listener",label:l.eventName,resolvedVia:d})}}for(let l of s){if(l.isInlineHandler)continue;let{targetId:c,via:d}=Io(l.handlerName,e,o,i);if(c){let p=a.find(f=>f.id===c);p&&(p.isEntryPoint=!0,p.trigger={type:"socketListener",label:l.eventName,resolvedVia:d})}}return a}function jo(e){let t=new Map,n=new Map;for(let r of e)r.resolved&&(t.set(r.fromNodeId,(t.get(r.fromNodeId)??0)+1),n.set(r.targetNodeId,(n.get(r.targetNodeId)??0)+1));return{outgoing:t,incoming:n}}function Ys(e,t,n=jo(t)){if(e.type==="moduleRoot")return 0;let r=n.outgoing.get(e.id)??0,o=n.incoming.get(e.id)??0,s=e.exported?1.5:1;return r/(o+1)*s}function Xs(e,t){let n=jo(t),r=new Set;for(let i of e)n.incoming.has(i.id)&&r.add(i.filePath);let s=e.filter(i=>!(i.isEntryPoint||i.type==="moduleRoot"||!n.incoming.has(i.id)&&r.has(i.filePath))).map(i=>({...i,fallbackScore:Ys(i,t,n)}));return s.sort((i,a)=>a.fallbackScore-i.fallbackScore),s.slice(0,15)}function Co(e){let t=new Map;for(let n of e)!n.resolved||!n.fromNodeId||!n.targetNodeId||(t.has(n.fromNodeId)||t.set(n.fromNodeId,[]),t.get(n.fromNodeId).push({targetNodeId:n.targetNodeId,line:n.line??null,column:n.column??null,branchPath:n.branchPath??[],edgeType:n.type}));return t}function Eo(e,t,n,r=8){let o=new Set([e]),s=l=>n.find(c=>c.id===l)?.category??"unknown",i=[{nodeId:e,depth:0,parentNodeId:null,category:s(e)}],a=[{nodeId:e,depth:0}];for(;a.length>0;){let l=a.shift();if(l.depth>=r)continue;let c=t.get(l.nodeId)||[];for(let d of c){let p=d.targetNodeId;if(o.has(p))continue;o.add(p);let f={nodeId:p,depth:l.depth+1,parentNodeId:l.nodeId,category:s(p),callLine:d.line,callColumn:d.column,branchPath:d.branchPath,edgeType:d.edgeType};i.push(f),a.push(f)}}return i}function Zs(e,t,n){return t.filter(o=>o.filePath===e.filePath&&o.id!==e.id&&o.type!=="moduleRoot").filter(o=>!n.some(i=>i.resolved&&i.targetNodeId===o.id))}function Qs(e,t,n){if(e.type==="moduleRoot")return!1;if(t.some(a=>a.resolved&&a.targetNodeId===e.id&&a.matchType==="crossLayer")||t.filter(a=>a.resolved&&a.fromNodeId===e.id).length>=4||new Set((e.returns||[]).map(a=>a.condition).filter(a=>a!==null)).size>=3)return!0;if(t.some(a=>a.resolved&&a.targetNodeId===e.id)&&!n.some(l=>l.filePath===e.filePath&&l.id!==e.id&&l.type!=="moduleRoot"&&t.some(c=>c.resolved&&c.targetNodeId===l.id))){let l=Zs(e,n,t);if(l.length>0)return e.lexicalSiblings=l.map(c=>c.id),!0}return!1}function ei(e,t,n,r,o=8,s=null){let i=[],a=new Set(e.map(c=>c.id)),l=[...e];for(;l.length>0;){let c=l.shift(),d=Eo(c.id,t,n,o);i.push({entryPointId:c.id,entryPointName:c.name,trigger:c.trigger??null,steps:d});let p=s?new Set(Eo(c.id,s,n,o).map(f=>f.nodeId)):null;for(let f of d){if(p&&!p.has(f.nodeId)||f.nodeId===c.id||a.has(f.nodeId))continue;let u=n.find(m=>m.id===f.nodeId);u&&Qs(u,r,n)&&(a.add(u.id),f.hasOwnSubTrace=!0,u.lexicalSiblings&&(f.lexicalSiblings=u.lexicalSiblings),l.push({id:u.id,name:u.name,trigger:null}))}}return i}function ti(e,t,n=mr){return e.filter((r,o)=>{if(o===0)return!0;let s=t.find(i=>i.id===r.nodeId);return s?!n.some(i=>s.name.toLowerCase().includes(i)):!0})}function ni(e){return e.steps.filter(n=>n.depth>0).map(n=>n.nodeId).sort().join(" | ")}function oi(e){let t=new Map;for(let n of e){let r=ni(n),o=r===""?`__no_calls__${n.entryPointName}`:r;t.has(o)||t.set(o,[]),t.get(o).push(n)}return t}function ri(e){let t=e[0];return{steps:t.steps,entryPointNames:e.map(n=>n.entryPointName),occurrences:e.length,name:t.entryPointName,trigger:t.trigger,tier:e.some(n=>n.origin==="physical")?"physical":"guessed",tierOrigin:e.some(n=>n.origin==="physical")?"physical":t.origin}}import _n from"node:path";function si(e){if(!e.trigger)return null;if(e.trigger.type==="route")return`${e.trigger.label.split(" ")[1].split("/").filter(Boolean).join(" ").replace(/[-_]/g," ").split(" ").map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")} Flow`;if(e.trigger.type==="listener"){let t=e.trigger.label;return`${t.charAt(0).toUpperCase()+t.slice(1)} Flow`}return null}function ii(e){return e.name.replace(/([A-Z])/g," $1").trim().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}var ai=60,Il=24;function ci(e,t=null){let n=e.map(r=>{let o=si(r),s=r.trigger?.workflowName??o??ii(r);return{...r,name:s}});return t?.nodes?Pl(n,t.nodes):n}var Po=(e,t)=>e.length>t?e.slice(0,t-1)+"\u2026":e,jl=new Set(["function","arrowFunction","classMethod"]);function Cl(e){let t=new Map(e.map(o=>[o.id,o])),n=new Map,r=o=>{let s=n.get(o);return s||(s=e.filter(i=>i.filePath===o&&jl.has(i.type)),n.set(o,s)),s};return o=>{let s=t.get(o.steps[0].nodeId);if(!s)return[null,null,null];let i=null;if(s.type==="classMethod")i=s.className;else{let c=null;for(let d of r(s.filePath))d===s||!(d.startLine<=s.startLine&&d.endLine>=s.endLine)||d.startLine===s.startLine&&d.endLine===s.endLine||(!c||d.endLine-d.startLine<c.endLine-c.startLine)&&(c=d);c&&(i=c.type==="classMethod"?c.className:c.name)}let a=null;if(o.trigger?.type==="route")a=String(o.trigger.label).split(" ")[0];else if(o.trigger?.type==="listener"){let c=/::listener:([^.#]+)\./.exec(s.id);c&&(a=c[1])}let l=_n.basename(s.filePath,_n.extname(s.filePath));return l==="index"&&(l=_n.basename(_n.dirname(s.filePath))),[i||null,a||null,l||null]}}var El=(e,t)=>{let n=t.map(r=>Po(r,Il)).join(", ");return e.endsWith(")")?e.slice(0,-1)+", "+n+")":e+" ("+n+")"};function Pl(e,t){let n=Cl(t),r=e.map(i=>({w:i,base:i.name,parts:[],used:new Set,stuck:!1,q:null})),o=i=>i.parts.length?El(i.base,i.parts):i.base,s=()=>{let i=new Map;for(let a of r){let l=o(a);(i.get(l)??i.set(l,[]).get(l)).push(a)}return[...i.values()].filter(a=>a.length>1)};for(let i=0;i<4;i++){let a=!1;for(let l of s()){if(l.some(f=>f.stuck))continue;for(let f of l)f.q??=n(f.w);let c=[0,1,2].filter(f=>l.every(u=>!u.used.has(f))),d=c.find(f=>new Set(l.map(u=>u.q[f]??"")).size>1),p=d!==void 0;if(p||(d=c.find(f=>l.every(u=>u.q[f]))),d===void 0){for(let f of l)f.stuck=!0;continue}for(let f of l)f.used.add(d),f.q[d]&&f.parts.push(f.q[d]),p||(f.stuck=!0);a=!0}if(!a)break}for(let i of s())i.sort((a,l)=>a.w.steps[0].nodeId<l.w.steps[0].nodeId?-1:a.w.steps[0].nodeId>l.w.steps[0].nodeId?1:0),i.forEach((a,l)=>{l>0&&(a.suffix=` (${l+1})`)});return r.map(i=>{let a=o(i);return i.suffix&&(a=Po(a,ai-i.suffix.length)+i.suffix),{...i.w,name:Po(a,ai)}})}var Ll=e=>e;function li(e,t){let n=new Map;for(let[r,o]of e){let s=t.filter(c=>c.filePath===r);if(s[0]?.category!=="backend")continue;let i=o.routes??[],a=Te(r,o),l=le(r,t);for(let c of i){let d=Ct(c.path);if(c.isInlineHandler){let f=a.get(c);n.set(d,f);continue}if(c.nest){let f=Ll(s).find(u=>u.type==="classMethod"&&u.className===c.nest.className&&u.name===c.nest.methodName);f&&n.set(d,f.id);continue}if(!c.handlerName||!l.has(c.handlerName))continue;let p=l.get(c.handlerName);n.set(d,p)}}return n}import dt from"node:fs";import Y from"node:path";var $n=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Rl=/(^|\/)(dist|build|out|built|compiled|esm|cjs|lib|output)(\/|$)/,di=/(^|\/)(dist|build|out|built|compiled|esm|cjs|output)(\/|$)/,Tl=/\b(esbuild|tsup|tsdown|tsc|rollup|webpack|ncc|swc|babel|vite|parcel|bun\s+build|pkg|unbuild|microbundle|rspack)\b/,Al=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild|rspack)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Oe=e=>{try{return dt.statSync(e).isFile()}catch{return!1}},Lo=e=>e.split(Y.sep).join("/"),Ro=e=>{if(Oe(e)&&$n.includes(Y.extname(e))&&!/\.d\.ts$/.test(e))return e;let t=e.replace(/\.(m|c)?js$/,"");for(let n of $n)if(Oe(t+n)&&!/\.d\.ts$/.test(t+n))return t+n;return null},Fn=(e,t)=>{let n=Y.relative(e,t);return n&&!n.startsWith("..")&&!Y.isAbsolute(n)&&!/(^|[\\/])node_modules([\\/]|$)/.test(n)};function Ol(e,t){let n=Oe(t+".map")?t+".map":null;if(!n&&Oe(t))try{let a=dt.readFileSync(t,"utf8").slice(-400),l=/sourceMappingURL=([^\s*]+)/.exec(a);if(l&&!l[1].startsWith("data:")){let c=Y.resolve(Y.dirname(t),l[1]);Oe(c)&&(n=c)}}catch{}if(!n)return null;let r;try{r=JSON.parse(dt.readFileSync(n,"utf8"))}catch{return null}let o=Y.resolve(Y.dirname(n),r.sourceRoot??""),s=(r.sources??[]).map(a=>Y.resolve(o,a)).filter(a=>Fn(e,a)&&Oe(a)&&$n.includes(Y.extname(a)));if(s.length===1)return s[0];let i=Y.basename(t).replace(/\.(m|c)?js$/,"");return s.find(a=>Y.basename(a).replace(/\.[^.]+$/,"")===i)??null}function Ml(e){try{return JSON.parse(dt.readFileSync(e,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,"").replace(/,(\s*[}\]])/g,"$1"))}catch{return null}}function Hl(e,t){for(let n of["tsconfig.build.json","tsconfig.json"]){let o=Ml(Y.join(e,n))?.compilerOptions;if(!o?.outDir)continue;let s=Lo(Y.normalize(o.outDir)).replace(/^\.\//,"").replace(/\/$/,"");if(!(t===s||t.startsWith(s+"/")))continue;let i=t.slice(s.length+1),a=o.rootDir?o.rootDir:dt.existsSync(Y.join(e,"src"))?"src":".",l=Ro(Y.resolve(e,a,i));if(l)return l}return null}function Dl(e,t){let n=t.split("/"),r=n.findIndex(s=>/^(dist|build|out|built|compiled|esm|cjs|lib|output)$/.test(s));if(r<0)return null;let o=n.slice(r+1).join("/");for(let s of["src","source","sources"]){let i=Ro(Y.resolve(e,...n.slice(0,r),s,o));if(i&&Fn(e,i))return i}return null}function Ul(e,t,n){let r=Y.basename(n).replace(/\.(m|c)?js$/,"");for(let o of["build","compile","bundle","prepare","prepublishOnly","prepack","postinstall"]){let s=t.scripts?.[o];if(!s||!Tl.test(s))continue;let i=[];for(let c of s.split(/\s+/).map(d=>d.replace(/^["']|["']$/g,"").replace(/^--?[\w-]+=/,""))){if(!$n.includes(Y.extname(c))||/\.d\.ts$/.test(c))continue;let d=Y.resolve(e,c);Oe(d)&&Fn(e,d)&&!di.test(Lo(Y.relative(e,d)))&&i.push(d)}let a=[...new Set(i)];if(a.length===1)return a[0];let l=a.filter(c=>Y.basename(c).replace(/\.[^.]+$/,"")===r);if(l.length===1)return l[0];if(a.length)return a[0]}return null}function Bl(e,t){let n=[];try{n=dt.readdirSync(e).filter(i=>Al.test(i)).sort()}catch{return null}let r=Y.basename(t).replace(/\.(m|c)?js$/,""),o=[];for(let i of n){let a;try{a=dt.readFileSync(Y.join(e,i),"utf8")}catch{continue}for(let l of a.matchAll(/\bentry(?:Points)?\s*:\s*[[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/g)){let c=Ro(Y.resolve(e,l[1]));c&&Fn(e,c)&&o.push(c)}}let s=[...new Set(o)];return s.length===1?s[0]:s.find(i=>Y.basename(i).replace(/\.[^.]+$/,"")===r)??null}function In(e,t,n){if(typeof t!="string"||!t)return null;let r=Lo(Y.normalize(t)).replace(/^\.\//,""),o=Y.resolve(e,r);if(!Rl.test(r)||Oe(o)&&!di.test(r)||Oe(o)&&/\.ts$/.test(o))return null;let i=[["sourcemap",()=>Ol(e,o)],["tsconfig outDir",()=>Hl(e,r)],["convention",()=>Oe(o)?null:Dl(e,r)],["build script",()=>Ul(e,n??{},r)],["build config",()=>Bl(e,r)]];for(let[a,l]of i){let c=null;try{c=l()}catch{}if(c&&c!==o)return{file:c,how:a}}return null}function fi(e,t){let n=new Map;for(let[r,o]of e){let s=o.socketListeners??[],i=Te(r,o),a=le(r,t);for(let l of s){if(l.isInlineHandler){let d=i.get(l);n.set(l.eventName,d);continue}if(!l.handlerName||!a.has(l.handlerName))continue;let c=a.get(l.handlerName);n.set(l.eventName,c)}}return n}import To from"node:fs";import H from"node:path";var Ne=e=>String(e??"").trim().replace(/^["']|["']$/g,""),jn=e=>e.replace(/^\s*#.*$/,"").replace(/\s+#.*$/,"");function ui(e){let t=/^(\/[A-Za-z0-9_\-./]*?)\/?(?=$|[:(*{[])/.exec(String(e).trim()),n=t?t[1]:"";return n==="/"?"":n.replace(/\/+$/,"")}function pi(e,t){let n=e.split(/\r?\n/).map(jn),r=u=>u.length-u.trimStart().length,o=[],s=null,i=!1,a=null,l=!1,c=0,d=null,p=()=>{d?.key&&d.fromService&&d.fromService!=="?"&&s.hostRefs.push({name:d.key,service:d.fromService,property:d.property}),d=null},f=(u,m,h)=>{m==="name"?u.name=Ne(h):m==="rootDir"?u.rootDir=Ne(h):m==="startCommand"&&(u.startCommand=Ne(h))};for(let u of n){if(!u.trim())continue;let m=r(u),h=u.trim();if(m===0){p(),s=null,l=!1,i=/^services\s*:/.test(h),a=null;continue}if(!i)continue;let v=h.startsWith("-");if(v&&(a==null||m===a)){a=m,p(),s={name:null,rootDir:null,startCommand:null,kept:[],hostRefs:[]},o.push(s),l=!1;let w=/^-\s*([A-Za-z]+)\s*:\s*(.*)$/.exec(h);w&&f(s,w[1],w[2]);continue}if(!s)continue;let g=/^(?:-\s*)?([A-Za-z]+)\s*:\s*(.*)$/.exec(h);if(g){if(g[1]==="envVars"){p(),l=!0,c=m;continue}if(l&&m>c){if(v&&(p(),d={key:null,fromService:null,property:null}),!d)continue;if(g[1]==="key")d.key=Ne(g[2]);else if(g[1]==="value"&&d.key){let w=Ke(d.key,Ne(g[2]),t);w&&s.kept.push(w)}else g[1]==="fromService"?d.fromService="?":g[1]==="name"&&d.fromService==="?"?d.fromService=Ne(g[2]):g[1]==="property"&&(d.property=Ne(g[2]));continue}l&&(p(),l=!1),f(s,g[1],g[2])}}return p(),o.filter(u=>u.name)}function mi(e,t){let n={app:null,ports:[],kept:[]},r="";for(let o of e.split(/\r?\n/)){let s=jn(o).trim();if(!s)continue;let i=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(s);if(i){r=i[1];continue}let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(s);if(!a)continue;let[,l,c]=a;if(r===""&&l==="app"){let d=Ne(c);/^[a-z0-9][a-z0-9-]*$/i.test(d)&&(n.app=d)}else if(l==="internal_port"){let d=Number(Ne(c));Number.isInteger(d)&&d>=1&&d<=65535&&n.ports.push(d)}else if(r==="env"){let d=Ke(l,Ne(c),t);d&&n.kept.push(d)}}return n}function hi(e,t){let n={ports:[],kept:[]},r=e.replace(/\\\r?\n/g," ");for(let o of r.split(/\r?\n/)){let s=o.trim(),i=/^EXPOSE\s+(.+)$/i.exec(s);if(i){for(let l of i[1].split(/\s+/)){let c=Number(l.replace(/\/\w+$/,""));Number.isInteger(c)&&c>=1&&c<=65535&&n.ports.push(c)}continue}if(i=/^(?:ENV|ARG)\s+(.+)$/i.exec(s),!i)continue;let a=i[1];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(a)){let l=/([A-Za-z_][A-Za-z0-9_]*)=("([^"]*)"|'([^']*)'|\S*)/g,c;for(;c=l.exec(a);){let d=Ke(c[1],c[3]??c[4]??c[2],t);d&&n.kept.push(d)}}else{let l=/^([A-Za-z_][A-Za-z0-9_]*)\s+(.*)$/.exec(a);if(l){let c=Ke(l[1],Ne(l[2]),t);c&&n.kept.push(c)}}}return n}function gi(e){let t;try{t=JSON.parse(e)}catch{return[]}let n=[];for(let r of["rewrites","redirects"])for(let o of Array.isArray(t?.[r])?t[r]:[]){let s=typeof o?.destination=="string"?o.destination:"",i=/\/:[A-Za-z_]+\*?$/.test(s)?Ve(s.replace(/\/:[A-Za-z_]+\*?$/,"")):null;i&&typeof o.source=="string"&&n.push({prefix:ui(o.source),target:i,kind:`vercel.json ${r}`,strip:!0})}return n}function yi(e){let t=[],n=!1,r=null,o=()=>{if(r?.from&&r.to&&/\/:[A-Za-z_]+\*?$/.test(r.to)){let s=Ve(r.to.replace(/\/:[A-Za-z_]+\*?$/,""));s&&t.push({prefix:ui(r.from),target:s,kind:"netlify.toml redirects",strip:!0})}r=null};for(let s of e.split(/\r?\n/)){let i=jn(s).trim();if(!i)continue;let a=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(a){o(),n=a[1]==="redirects",r=n?{}:null;continue}if(!n||!r)continue;let l=/^(from|to)\s*=\s*(.*)$/.exec(i);l&&(r[l[1]]=Ne(l[2]))}return o(),t}function xi(e,t){let n;try{n=JSON.parse(e)}catch{return[]}let r=[],o=n&&typeof n=="object"?n.env:null;if(o&&typeof o=="object")for(let s of Object.keys(o).sort()){let i=o[s],a=typeof i=="string"?i:typeof i?.value=="string"?i.value:null,l=Ke(s,a,t);l&&r.push(l)}return r}function vi(e,t,n){let r=[];if(n){let o;try{o=JSON.parse(e)}catch{return r}let s=(i,a)=>{if(!(!i||typeof i!="object"||a>4))for(let l of Object.keys(i).sort()){let c=i[l];if(/^(env|envVars|variables|environment)$/i.test(l)&&c&&typeof c=="object"&&!Array.isArray(c))for(let d of Object.keys(c).sort()){let p=typeof c[d]=="string"?c[d]:typeof c[d]?.value=="string"?c[d].value:null,f=Ke(d,p,t);f&&r.push(f)}else s(c,a+1)}};s(o,0)}else{let o="";for(let s of e.split(/\r?\n/)){let i=jn(s).trim();if(!i)continue;let a=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(a){o=a[1];continue}let l=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(i);if(l&&/(^|\.)(env|variables|environment)$/i.test(o)){let c=Ke(l[1],Ne(l[2]),t);c&&r.push(c)}}}return r}var zl=[".env.local",".env",".env.development",".env.production",".env.example"],Wl=/^(PORT|HTTP_PORT|HTTPS_PORT|SERVER_PORT|API_PORT|APP_PORT|WS_PORT|WSS_PORT|WEBSOCKET_PORT|LISTEN_PORT)$/,ql=/^PUBLIC_(?:[A-Z0-9]+_)*(?:ORIGIN|URL|HOST|BASE_URL)$/,Gl=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","host.docker.internal"]),Jl=512*1024,wi=e=>e.split(H.sep).join("/");function ft(e){try{let t=To.lstatSync(e);return!t.isFile()||t.isSymbolicLink()||t.size>Jl?null:To.readFileSync(e,"utf8")}catch{return null}}function Ve(e){let t=String(e).trim().replace(/^["']|["']$/g,"");if(!/^(https?|wss?):\/\//i.test(t))return null;try{let n=new URL(t);if(!n.hostname)return null;let r=n.protocol.replace(":",""),o=n.hostname.toLowerCase(),s=n.port?Number(n.port):null,i=n.pathname.replace(/\/+$/,"");return{scheme:r,host:o,port:s,origin:`${r}://${o}${s?":"+s:""}`,path:i}}catch{return null}}function Kl(e){let t=String(e).trim().replace(/^["']|["']$/g,"");return!/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:\d{1,5})?(\/[^\s?#]*)?$/i.test(t)||!/[a-z]/i.test(t.split(/[/:]/)[0])?null:Ve("http://"+t)}var Ao=e=>{let t=String(e).trim().replace(/^["']|["']$/g,"");if(!/^\d{1,5}$/.test(t))return null;let n=Number(t);return n>=1&&n<=65535?n:null};function Vl(e){let t=new Map;for(let n of e.split(/\r?\n/)){let r=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(n);if(!r)continue;let o=r[2];if(/^["']/.test(o)){let s=o[0],i=o.indexOf(s,1);o=i>0?o.slice(1,i):o.slice(1)}else o=o.replace(/\s+#.*$/,"");t.set(r[1],o)}return t}function Ni(e,t,n=0,r=new Set){let o=e.get(t);return o==null||n>5||r.has(t)||(r.add(t),o=o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}]*))?\}/g,(s,i,a)=>{let l=e.has(i)?Ni(e,i,n+1,r):void 0;return l!=null&&l!==""?l:a??""}),r.delete(t)),o}function Ke(e,t,n){if(t==null)return null;if(Wl.test(e)){let o=Ao(t);return o?{name:e,kind:"port",file:n,port:o}:null}let r=Ve(t)??(/(_URL|_URI|_HOST|_HOSTNAME|_ORIGIN|_ADDR|_ENDPOINT)$/i.test(e)?Kl(t):null);return r?{name:e,kind:"url",file:n,...r}:null}function Si(e,t){let n=[];for(let r of[...e.keys()].sort()){let o=Ni(e,r);if(o==null)continue;let s=Ke(r,o,t);s&&n.push(s)}return n}function Yl(e){let t=e.split(/\r?\n/).map(c=>c.replace(/\s+#.*$/,"").replace(/\t/g," ")),n=c=>c.length-c.trimStart().length,r=[],o=t.findIndex(c=>/^services\s*:\s*$/.test(c));if(o<0)return r;let s=null,i=null,a=null,l=0;for(o=o+1;o<t.length;o++){let c=t[o];if(!c.trim())continue;let d=n(c),p=c.trim();if(d===0)break;if(s==null&&(s=d),d===s){let f=/^([A-Za-z0-9_.-]+)\s*:\s*$/.exec(p);f&&(i={name:f[1],ports:[],env:new Map,build:null},r.push(i),a=null);continue}if(i){if(d<=s+4&&/^[A-Za-z_]+\s*:/.test(p)&&!p.startsWith("-")){let f=/^([A-Za-z_]+)\s*:\s*(.*)$/.exec(p);a=f[1],l=d,a==="build"&&f[2]&&(i.build=f[2].replace(/^["']|["']$/g,""));continue}if(a==="build"&&/^context\s*:/.test(p)){i.build=p.replace(/^context\s*:\s*/,"").replace(/^["']|["']$/g,"");continue}if(a==="ports"&&p.startsWith("-")){let u=p.slice(1).trim().replace(/^["']|["']$/g,"").replace(/\/\w+$/,"").split(":"),m=u.slice(-2).map(h=>Ao(h));u.length===1&&m[0]?i.ports.push({host:null,container:m[0]}):u.length>=2&&m[0]&&m[1]&&i.ports.push({host:m[0],container:m[1]});continue}if(a==="environment"&&d>l){let f=p.startsWith("-")?/^-\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(p):/^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/.exec(p);f&&i.env.set(f[1],f[2].replace(/^["']|["']$/g,""))}}}return r}function ki(e,t){let n=[];if(t==="vite"){let r=e.search(/\bproxy\s*:/);if(r<0)return n;let o=e.slice(r,r+2500),s=/["'`](\/[^"'`]*)["'`]\s*:\s*(?:["'`](https?:\/\/[^"'`]+)["'`]|\{[^{}]*?target\s*:\s*["'`](https?:\/\/[^"'`]+)["'`])/g,i;for(;i=s.exec(o);){let a=Ve(i[2]??i[3]);a&&n.push({prefix:i[1].replace(/\/+$/,""),target:a,kind:"vite.config proxy"})}}else if(t==="next"){let r=/source\s*:\s*["'`](\/[^"'`:*]*)[^"'`]*["'`]\s*,\s*destination\s*:\s*["'`](https?:\/\/[^"'`]+?)(?:\/:[^"'`]*)?["'`]/g,o;for(;o=r.exec(e);){let s=Ve(o[2]);s&&n.push({prefix:o[1].replace(/\/+$/,""),target:s,kind:"next.config rewrites"})}}return n}function bi(e,t,n){let r=g=>wi(H.relative(e,g)),o=new Map,s=new Map,i=new Map,a=(g,w,S)=>{(g.get(w)??g.set(w,new Set).get(w)).add(S)},l=(g,w,S)=>{let N=i.get(g)??i.set(g,[]).get(g);N.some(y=>y.service===w&&y.via===S)||N.push({service:w,via:S})},c=g=>{let w=[],S=H.resolve(g),N=H.resolve(e);for(let y=0;y<8&&(w.push(S),!(S===N||H.dirname(S)===S||(S=H.dirname(S),!S.startsWith(N))));y++);return w},d=new Map,p=new Map,f=(g,w)=>{let S=g.env.get(w.name)??g.env.set(w.name,[]).get(w.name);S.some(N=>N.file===w.file)||S.push(w),w.kind==="port"&&g.ports.add(w.port)};function u(g,w,S){let N=x=>r(H.join(S,x)),y=x=>ft(H.join(S,x));for(let x of Cn(S))if(x==="fly.toml"){let b=y(x);if(b){let k=mi(b,N(x));for(let $ of k.ports)w.ports.add($);for(let $ of k.kept)f(w,$);k.app&&(l(`${k.app.toLowerCase()}.internal`,g.name,"fly.toml app name"),l(`${k.app.toLowerCase()}.fly.dev`,g.name,"fly.toml app name"))}}else if(/^Dockerfile(\..+)?$/.test(x)){let b=y(x);if(b){let k=hi(b,N(x));for(let $ of k.ports)w.weakPorts.add($);for(let $ of k.kept)f(w,$)}}else if(x==="railway.json"||x==="railway.toml"){let b=y(x);if(b)for(let k of vi(b,N(x),x.endsWith(".json")))f(w,k)}else if(x==="app.json"){let b=y(x);if(b)for(let k of xi(b,N(x)))f(w,k)}else if(x==="vercel.json"){let b=y(x);if(b)for(let k of gi(b))w.proxies.push({...k,file:N(x)})}else if(x==="netlify.toml"){let b=y(x);if(b)for(let k of yi(b))w.proxies.push({...k,file:N(x)})}}for(let g of t){let w={env:new Map,ports:new Set,weakPorts:new Set,proxies:[],isServer:!1};o.set(g.name,w);for(let S of c(g.rootPath)){for(let N of zl){let y=ft(H.join(S,N));if(y!=null)for(let x of Si(Vl(y),r(H.join(S,N)))){let b=w.env.get(x.name)??w.env.set(x.name,[]).get(x.name);b.some(k=>k.file===x.file)||b.push(x),x.kind==="port"&&S===H.resolve(g.rootPath)&&/(^|\/)\.env/.test(x.file)&&!/\.example$/.test(x.file)&&w.ports.add(x.port),x.kind==="port"&&S===H.resolve(g.rootPath)&&/\.example$/.test(x.file)&&w.ports.add(x.port)}}if(S===H.resolve(g.rootPath)){try{let N=JSON.parse(ft(H.join(S,"package.json"))??"null"),y=typeof N?.proxy=="string"?Ve(N.proxy):null;y&&w.proxies.push({prefix:"",target:y,kind:'package.json "proxy"',file:r(H.join(S,"package.json"))})}catch{}for(let N of Cn(S)){if(/^vite\.config\.(js|mjs|cjs|ts|mts)$/.test(N)){let y=ft(H.join(S,N));if(y)for(let x of ki(y,"vite"))w.proxies.push({...x,file:r(H.join(S,N))})}if(/^next\.config\.(js|mjs|cjs|ts)$/.test(N)){let y=ft(H.join(S,N));if(y)for(let x of ki(y,"next"))w.proxies.push({...x,file:r(H.join(S,N))})}}}S===H.resolve(g.rootPath)&&u(g,w,S);for(let N of Cn(S))if(/^render\.ya?ml$/.test(N)&&!p.has(H.join(S,N))){let y=ft(H.join(S,N));y&&p.set(H.join(S,N),pi(y,r(H.join(S,N))))}for(let N of Cn(S)){if(!/^docker-compose.*\.ya?ml$/.test(N)||d.has(H.join(S,N)))continue;let y=ft(H.join(S,N));y&&d.set(H.join(S,N),Yl(y))}}}for(let[g,w]of[...d].sort((S,N)=>S[0]<N[0]?-1:1)){let S=H.dirname(g);for(let N of w){let y=N.build?H.resolve(S,N.build):null,x=t.find(k=>y&&H.resolve(k.rootPath)===y)??t.find(k=>k.name===N.name||H.basename(k.rootPath)===N.name);if(!x)continue;let b=o.get(x.name);for(let k of N.ports)b.ports.add(k.container),k.host&&b.ports.add(k.host);for(let k of Si(N.env,r(g)))(b.env.get(k.name)??b.env.set(k.name,[]).get(k.name)).push(k);l(N.name.toLowerCase(),x.name,"docker-compose service name")}}for(let[g,w]of[...p].sort((S,N)=>S[0]<N[0]?-1:1)){let S=H.dirname(g),N=new Map;for(let y of w){let x=H.resolve(S,y.rootDir||"."),b=y.rootDir?t.find($=>H.resolve($.rootPath)===x):null;if(!b&&y.startCommand)for(let $ of y.startCommand.split(/\s+/)){if(!/\.(c|m)?[jt]sx?$/.test($)&&!/^[\w./-]+\/[\w.-]+$/.test($))continue;let j=H.resolve(x,$),D=t.filter(L=>j.startsWith(H.resolve(L.rootPath)+H.sep)).sort((L,K)=>K.rootPath.length-L.rootPath.length)[0];if(D){b=D;break}}if(b=b??t.find($=>$.name===y.name||H.basename($.rootPath)===y.name),!b)continue;N.set(y.name,{target:b,c:y});let k=o.get(b.name);for(let $ of y.kept)f(k,{...$,scoped:!0});l(y.name.toLowerCase(),b.name,"render.yaml service name"),l(`${y.name.toLowerCase()}.onrender.com`,b.name,"render.yaml service name (Render's default public address)")}for(let{target:y,c:x}of N.values())for(let b of x.hostRefs){let k=N.get(b.service);if(!k)continue;let $=[...k.c.kept].find(L=>L.kind==="port")?.port??null,j=b.property==="hostport"&&$,D=b.service.toLowerCase();f(o.get(y.name),{name:b.name,kind:"url",file:r(g),scheme:"http",host:D,port:j?$:null,origin:`http://${D}${j?":"+$:""}`,path:""})}}let m=g=>[...n.get(g.name)?.parseResults?.values()??[]].some(w=>(w.routes??[]).length>0);for(let g of t){let w=o.get(g.name);if(w.isServer=m(g),w.isServer){for(let[S,N]of w.env)if(ql.test(S))for(let y of N)y.kind==="url"&&y.file&&(y.scoped||H.posix.dirname(y.file)===(wi(H.relative(e,g.rootPath))||"."))&&l(y.host,g.name,`${S} in ${y.file} (the server's own public address)`)}}for(let g of t){let w=o.get(g.name);for(let[,S]of n.get(g.name)?.parseResults??[])for(let N of S.httpClients?.listens??[])for(let y of h(w,N.parts)){let x=Ao(y.text);x&&w.ports.add(x)}}for(let g of t)for(let w of o.get(g.name).ports)a(s,w,g.name);for(let g of t)for(let w of o.get(g.name).weakPorts)t.some(S=>o.get(S.name).ports.has(w))||a(s,w,g.name);function h(g,w){let S=[{text:"",evidence:[]}];for(let N of w){let y;if(N.t==="lit")y=[{text:N.v,evidence:[]}];else if(N.t==="env"){let b=g.env.get(N.name)??[];y=[];for(let k of b)y.push({text:k.kind==="port"?String(k.port):k.origin+k.path,evidence:[{env:N.name,file:k.file}]});!y.length&&N.fallback&&(y=h(g,N.fallback).map($=>({text:$.text,evidence:[{env:N.name,file:null,fallback:!0},...$.evidence]})))}else y=[];if(!y.length)return[];let x=[];for(let b of S)for(let k of y)if(x.push({text:b.text+k.text,evidence:[...b.evidence,...k.evidence]}),x.length>=8)break;S=x.slice(0,8)}return S}let v=(g,w)=>{let S=[],N=g.host,y=i.get(N)??[];for(let x of y)S.push(x);if(Gl.has(N)||y.length&&y.some(x=>x.via==="docker-compose service name")){let x=g.port??(g.scheme==="https"||g.scheme==="wss",null);if(x)for(let b of s.get(x)??[])S.some(k=>k.service===b)||S.push({service:b,via:`port ${x} (a service listening there)`})}return S.filter(x=>x.service!==w)};return{resolveBase(g,w){let S=o.get(g);if(!S||!w.length)return{status:"unknown"};let N=h(S,w);if(!N.length)return{status:"unknown"};let y=[],x=new Set;for(let $ of N){let j=Ve($.text)??($.text.startsWith("//"),null);if(j){x.add(j.origin);for(let D of v(j,g))y.push({...D,u:j,evidence:$.evidence})}}if(!x.size)return{status:"unknown"};let b=[...new Set(y.map($=>$.service))];if(b.length===0)return{status:"external",origins:[...x].sort()};if(b.length>1)return{status:"ambiguous",services:b.sort()};let k=y[0];return{status:"service",service:k.service,via:k.via,origin:k.u.origin,basePath:k.u.path,evidence:k.evidence.filter(($,j,D)=>D.findIndex(L=>L.env===$.env&&L.file===$.file)===j)}},resolveProxy(g,w){let S=o.get(g);for(let N of S?.proxies??[]){if(N.prefix&&w!==N.prefix&&!w.startsWith(N.prefix+"/"))continue;let y=v(N.target,g),x=[...new Set(y.map(b=>b.service))];if(x.length===1)return{status:"service",service:x[0],via:`${N.kind} ${N.prefix||"/"} -> ${N.target.origin}`,origin:N.target.origin,basePath:N.target.path,strip:N.strip?N.prefix.split("/").filter(Boolean).length:0,evidence:[{env:null,file:N.file}]}}return{status:"unknown"}},portsOf:g=>[...o.get(g)?.ports??[]].sort((w,S)=>w-S),hostClaims:()=>[...i].sort((g,w)=>g[0]<w[0]?-1:1)}}function Cn(e){try{return To.readdirSync(e).sort()}catch{return[]}}var En=e=>String(e).toLowerCase();function Pn(e){let t=[];for(let n of e)n.t==="lit"&&t.length&&t[t.length-1].t==="lit"?t[t.length-1]={t:"lit",v:t[t.length-1].v+n.v}:t.push(n);return t}function _i(e,t){let n=[];for(let r of e){if(r.t!=="param"){n.push(r);continue}let o=t?.get(r.index);o?n.push(...o):n.push({t:"ref",name:r.name})}return Pn(n)}function Oo(e){if(!e.length)return null;let t=e.slice(),n="none",r=null,o=t[0];if(o.t==="lit"){let c=/^(https?:)\/\/([^/?#]*)(.*)$/.exec(o.v);if(c){n="abs",r=c[2];let d=c[3];if(t=d?[{t:"lit",v:d},...t.slice(1)]:t.slice(1),/^(www\.)?(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)(:\d+)?$/.test(r)===!1&&!/\.(local|internal|svc)$/.test(r)&&!/^[a-z0-9-]+(:\d+)?$/.test(r))return null}else if(!o.v.startsWith("/"))return null}else{for(n="var";t.length&&t[0].t!=="lit";)t.shift();if(!t.length||!t[0].v.startsWith("/"))return null}let s="",i=0,a=!1;for(let c of t){if(a)break;if(c.t==="lit"){let d=c.v.search(/[?#]/);d>=0?(s+=c.v.slice(0,d),a=!0):s+=c.v}else s+="",i++}if(!s.startsWith("/")&&!(s===""&&n==="abs"))return null;s===""&&(s="/");let l=s.split("/").slice(1).map(c=>c.includes("")?":p":c);for(;l.length>1&&l[l.length-1]==="";)l.pop();return{base:n,host:r,segments:l,placeholders:i,literal:n==="none"&&i===0}}function $i(e){if(!e.length)return[];let t=e[0];if(t.t==="lit"){let r=/^((?:https?|wss?):\/\/[^/?#]*)/.exec(t.v);return r?[{t:"lit",v:r[1]}]:[]}let n=[];for(let r of e){if(r.t==="lit"&&r.v.startsWith("/"))break;n.push(r)}return n}var Xl=e=>String(e||"").split("/").filter(Boolean),Fi=e=>[...new Set(e)];function Ii(e){let t=e.evidence??[];return{env:Fi(t.filter(n=>n.env).map(n=>n.env)),files:Fi(t.filter(n=>n.file).map(n=>n.file)),origin:e.origin,via:e.via,...t.some(n=>n.fallback)?{usedFallback:!0}:{}}}var ji=(e,t)=>"base URL "+(e.env.length?e.env.join(", ")+(e.files.length?" in "+e.files.join(", "):"")+" = ":e.files.length?"(from "+e.files.join(", ")+") ":"")+e.origin+" belongs to "+t+" ("+e.via+")",Zl=e=>{let t=String(e).split(/[?#]/)[0].split("/").slice(1).map(n=>n.startsWith(":")||/^\{.*\}$/.test(n)||n==="*"?":p":n);for(;t.length>1&&t[t.length-1]==="";)t.pop();return t};function Ci(e,t){if(e.length===t.length){let n=!0,r=!0;for(let o=0;o<e.length;o++){let s=e[o],i=t[o];if(s!==i&&(n=!1),!(s===i||s===":p"||i===":p")){r=!1;break}}if(n)return 3;if(r)return 2}if(e[0]==="api"&&e.length>1){let n=e.slice(1);if(/^v\d+$/.test(n[0])&&n.length>1&&(n=n.slice(1)),n.length===t.length&&n.every((r,o)=>r===t[o]||r===":p"||t[o]===":p"))return 1}return 0}function Ql(e,t,n,r,o){let s=(n.importBindings??[]).find(p=>p.local===r);if(!s)return null;let i=Ae(s.source,t,o);if(!i)return null;let a=e.parseResults.get(i),l=p=>e.nodes.find(f=>f.filePath===i&&f.name===p&&f.type!=="moduleRoot")?.id??null;if(s.kind==="named"&&s.imported)return l(s.imported);let c=a?.exportBindings;if(c?.default&&c.default!=="<anon>")return l(c.default);let d=Object.keys(c?.named??{});return d.length===1?l(d[0]):null}function ed(e){let t=[],n=[...e.parseResults.keys()];for(let[r,o]of e.parseResults){let s=e.nodes.filter(l=>l.filePath===r);if(s[0]?.category!=="backend")continue;let i=Te(r,o),a=le(r,e.nodes);for(let l of o.routes??[]){let c=null;l.isInlineHandler?c=i.get(l):l.nest?c=s.find(p=>p.type==="classMethod"&&p.className===l.nest.className&&p.name===l.nest.methodName)?.id??null:l.handlerName&&a.has(l.handlerName)?c=a.get(l.handlerName):l.handlerName&&(c=Ql(e,r,o,l.handlerName,n));let d=!1;c||(c=fe(l.startLine,s)?.id??null,d=!0),c&&t.push({method:En(l.method),path:l.path,segments:Zl(l.path),literal:!/[:*{]/.test(l.path),nodeId:c,file:r,line:l.startLine,fallback:d})}}return t}var td=/^(ws|uws|websocket|@nestjs\/platform-ws|@fastify\/websocket|fastify-websocket|express-ws)$/,nd=/^(socket\.io|@nestjs\/platform-socket\.io|socket\.io-client)$/;function Ei(e){let t=[...e].some(r=>nd.test(r)),n=[...e].some(r=>td.test(r));return t&&n?"unknown":t?"socketio":n?"ws":null}function od(e){let t=[],n=new Set;for(let[,r]of e.parseResults)for(let o of r.imports??[])n.add(o.source);for(let[r,o]of e.parseResults){let s=o.socketListeners??[],i=s.find(h=>h.eventName==="connection");if(!i)continue;let a=Te(r,o),l=le(r,e.nodes),c=h=>h.isInlineHandler?a.get(h):h.handlerName&&l.has(h.handlerName)?l.get(h.handlerName):null,d=c(i);if(!d)continue;let p=h=>i.handlerStartLine!=null&&h.startLine>=i.handlerStartLine&&h.startLine<=i.handlerEndLine,f=s.find(h=>h.eventName==="message"&&p(h))??s.find(h=>h.eventName==="message"),u=o.httpClients?.wsServers??[],m=Ei(new Set((o.imports??[]).map(h=>h.source)))??Ei(n)??"unknown";t.push({filePath:r,nodeId:d,line:i.startLine,messageNodeId:f?c(f):null,messageLine:f?.startLine??null,pathParts:u.find(h=>h.path)?.path??null,kind:m})}return t}function Pi(e,t,n={}){let r=n.repoRoot?bi(n.repoRoot,e,t):null,o=[],s=new Set,i={restCalls:0,restLinked:0,wsClients:0,wsLinked:0,wsSends:0,wsSendsLinked:0},a=c=>{let d=[c.fromService,c.fromNodeId,c.toService,c.toNodeId,c.via,c.key].join("\0");s.has(d)||(s.add(d),o.push(c))},l=new Map;for(let c of e){let d=t.get(c.name);d&&l.set(c.name,{routes:ed(d),wsServers:od(d)})}for(let c of e){let d=t.get(c.name);if(!d)continue;let p=[...d.parseResults.keys()],f=new Map,u=new Map;for(let[y,x]of d.parseResults){let b=x.httpClients;if(b){for(let k of b.httpInstances??[])(f.get(k.name)??f.set(k.name,[]).get(k.name)).push(k);for(let k of b.httpCalls??[])(k.parts.some(j=>j.t==="param")||k.method&&typeof k.method=="object")&&k.fn?.name&&(u.get(k.fn.name)??u.set(k.fn.name,[]).get(k.fn.name)).push({filePath:y,call:k})}}let m=y=>{if(!y.startsWith("inst:")&&!y.startsWith("obj:"))return[];let x=f.get(y.slice(y.indexOf(":")+1));return x&&x.length===1?x[0].parts:y.startsWith("obj:")?null:[{t:"ref",name:"?"}]},h=[],v=(y,x)=>fe(x,d.nodes.filter(b=>b.filePath===y)),g=new Set,w=y=>y.parts.some(x=>x.t==="param")||y.method&&typeof y.method=="object";for(let[y,x]of d.parseResults){let b=x.httpClients;if(b){for(let k of b.httpCalls??[]){if(w(k))continue;let $=m(k.client);if($===null)continue;let j=v(y,k.line);j&&h.push({filePath:y,line:k.line,nodeId:j.id,method:k.method,parts:Pn([...$,...k.parts]),via:k.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let k of b.pathCallsites??[]){let $=u.get(k.callee);if($)for(let j of $){let D=j.filePath===y;if(!D){let O=(x.importBindings??[]).find(W=>W.local===k.callee||W.imported===k.callee);O&&Ae(O.source,y,p)===j.filePath&&(D=!0)}if(!D)continue;let L=new Map(k.args.map(O=>[O.i,O.parts])),K=typeof j.call.method=="object"&&j.call.method?(()=>{let O=L.get(j.call.method.param);return O&&O.length===1&&O[0].t==="lit"?O[0].v.toUpperCase():"?"})():j.call.method,z=v(y,k.line);z&&(g.add(j.call),h.push({filePath:y,line:k.line,nodeId:z.id,method:K,parts:_i([...m(j.call.client),...j.call.parts],L),via:j.call.client,wrapper:k.callee}))}}}}for(let[y,x]of d.parseResults)for(let b of x.httpClients?.httpCalls??[]){if(!w(b)||g.has(b))continue;let k=m(b.client);if(k===null)continue;let $=v(y,b.line);$&&h.push({filePath:y,line:b.line,nodeId:$.id,method:typeof b.method=="object"&&b.method?"?":b.method,parts:_i([...k,...b.parts],null),via:b.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let y of h){let x=Oo(y.parts);if(!x)continue;i.restCalls++;let b=0,k=[];for(let z of e){if(z.name===c.name)continue;let O=l.get(z.name);if(O)for(let W of O.routes){if(!(y.method==="?"||y.method==null||W.method===En(y.method)||W.method==="all"||W.method==="use"))continue;let te=Ci(x.segments,W.segments);te&&(te>b&&(b=te,k.length=0),te===b&&k.push({service:z.name,route:W}))}}let $={status:"unknown"};if(r){let z=Pn(y.parts);if(x.base==="none"?$=r.resolveProxy(c.name,"/"+x.segments.join("/")):$=r.resolveBase(c.name,$i(z)),$.status==="service"){let O=Xl($.basePath);if(O.length||$.strip){let W=[...O,...x.segments.slice($.strip||0)];for(let G of l.get($.service)?.routes??[])(y.method==="?"||y.method==null||G.method===En(y.method)||G.method==="all"||G.method==="use")&&Ci(W,G.segments)&&!k.some(ge=>ge.service===$.service&&ge.route.nodeId===G.nodeId)&&k.push({service:$.service,route:G,viaBasePath:!0})}}}if(!k.length)continue;let j=new Set(k.map(z=>z.service+"\0"+z.route.nodeId)),D=typeof y.method=="string"&&y.method!=="?",L=b===3&&x.literal&&D&&j.size===1&&k[0].route.literal&&!k[0].route.fallback&&k[0].route.method===En(y.method),K=[];x.base==="var"&&K.push("base URL is a variable, so the target service is guessed from the path"),x.base==="abs"&&K.push("absolute URL"),x.placeholders&&K.push("path has parameters"),b===1&&K.push("leading /api removed from the client path"),b===2&&K.push("route parameters matched fuzzily"),D||K.push("method not known"),j.size>1&&K.push(j.size+" candidate routes"),k.some(z=>z.route.fallback)&&K.push("route handler not resolved: linked to the function that registers the route"),$.status==="external"&&K.push("base URL is "+$.origins.join(" / ")+", which no service of this repo owns"),$.status==="ambiguous"&&K.push("base URL could belong to "+$.services.join(" or "));for(let z of k){i.restLinked++;let O=!L&&$.status==="service"&&$.service===z.service&&!z.route.fallback,W=O?Ii($):null,G=L?"exact":O?"resolved":"inferred",te=!L&&$.status==="service"&&$.service!==z.service?["base URL belongs to "+$.service+", not this service"]:[];a({fromService:c.name,fromNodeId:y.nodeId,toService:z.service,toNodeId:z.route.nodeId,via:"httpCall",key:`${D?y.method:"ANY"} ${"/"+x.segments.join("/")}`,confidence:G,method:D?y.method:null,url:"/"+x.segments.join("/"),client:y.via,...y.wrapper?{wrapper:y.wrapper}:{},line:y.line,...L?{}:O?{reason:ji(W,z.service)+(D?"":"; method not known"),resolvedFrom:W}:{reason:[...K,...te].join("; ")||"path-only match"}})}}let S=[];for(let[y,x]of d.parseResults)for(let b of x.httpClients?.wsClients??[])S.push({filePath:y,w:b});let N=y=>y.client==="io"?"socketio":"ws";for(let{filePath:y,w:x}of S){let b=v(y,x.line);if(!b)continue;i.wsClients++;let k=Pn(x.parts),$=/^wss?:\/\//.test(k[0]?.v??"")?Oo([{t:"lit",v:k[0].v.replace(/^ws(s?):/,"http$1:")},...k.slice(1)]):Oo(k),j=r&&$?r.resolveBase(c.name,$i(k)):{status:"unknown"};for(let D of e)if(D.name!==c.name)for(let L of l.get(D.name)?.wsServers??[]){if(L.kind!=="unknown"&&L.kind!==N(x))continue;let K=L.pathParts&&L.pathParts.every(te=>te.t==="lit")?"/"+L.pathParts.map(te=>te.v).join("").replace(/^\//,""):null,z=$?"/"+$.segments.join("/"):null;if(K&&z&&K!==z&&K!=="/"&&z!=="/")continue;let O=!!($&&$.literal&&K&&z===K&&L.kind!=="unknown"),W=!O&&j.status==="service"&&j.service===D.name,G=W?Ii(j):null;i.wsLinked++,a({fromService:c.name,fromNodeId:b.id,toService:D.name,toNodeId:L.nodeId,via:"webSocket",key:z??"(url unknown)",confidence:O?"exact":W?"resolved":"inferred",url:z,client:x.client,line:x.line,...O?{}:W?{reason:ji(G,D.name),resolvedFrom:G}:{reason:"WebSocket connection matched to a WebSocket server of another service ("+($?.base==="var"?"URL base is a variable":"no path on the server to compare")+(j.status==="external"?"; base URL is "+j.origins.join(" / ")+", which no service of this repo owns":"")+")"}})}}if(S.length){let y=new Set(S.map(({w:x})=>N(x)));for(let[x,b]of d.parseResults)for(let k of b.httpClients?.wsSends??[]){let $=v(x,k.line);if($){i.wsSends++;for(let j of e)if(j.name!==c.name)for(let D of l.get(j.name)?.wsServers??[])!D.messageNodeId||D.kind!=="unknown"&&!y.has(D.kind)||(i.wsSendsLinked++,a({fromService:c.name,fromNodeId:$.id,toService:j.name,toNodeId:D.messageNodeId,via:"webSocketMessage",key:"message",eventName:"message",confidence:"inferred",client:k.recv,line:k.line,reason:"a message sent over a socket whose payload is built at run time; delivered to the message listener of a WebSocket server of another service"}))}}}}if(n.serverPush!==!1){let c=new Map;for(let p of o)if(p.via==="webSocket"){let f=p.fromService+"\0"+p.toService;(c.get(f)??c.set(f,[]).get(f)).push(p)}let d=new Map;for(let p of c.values())(d.get(p[0].toService)??d.set(p[0].toService,new Set).get(p[0].toService)).add(p[0].fromService);for(let[,p]of[...c].sort((f,u)=>f[0]<u[0]?-1:1)){let f=p[0].fromService,u=p[0].toService,m=t.get(f),h=t.get(u);if(!m||!h||!(l.get(u)?.wsServers??[]).length)continue;let v=new Set(p.map(N=>N.fromNodeId.split("::")[0])),g=[];for(let[N,y]of m.parseResults){if(!v.has(N))continue;let x=le(N,m.nodes),b=Te(N,y),k=m.nodes.filter($=>$.filePath===N);for(let $ of y.httpClients?.wsReceivers??[]){let j=$.handlerName&&x.get($.handlerName)||fe($.line,k)?.id;j&&g.push({id:j,line:$.line})}for(let $ of y.socketListeners??[]){if($.eventName!=="message")continue;let j=$.isInlineHandler?b.get($):$.handlerName&&x.get($.handlerName)||null;j&&g.push({id:j,line:$.startLine})}}let w=new Set(m.resolvedEdges.filter(N=>N.resolved&&N.targetNodeId&&N.type!=="returnValue").map(N=>N.fromNodeId));for(let N=g.length-1;N>=0;N--)w.has(g[N].id)||g.splice(N,1);if(!g.length)continue;let S=d.get(u)?.size??1;for(let[N,y]of h.parseResults){let x=h.nodes.filter(b=>b.filePath===N);for(let b of[...y.httpClients?.wsSends??[],...y.httpClients?.wsServerSends??[]]){let k=fe(b.line,x);if(k)for(let $ of g)i.wsPushLinked=(i.wsPushLinked??0)+1,a({fromService:u,fromNodeId:k.id,toService:f,toNodeId:$.id,via:"webSocketDelivery",key:"message",eventName:"message",confidence:"inferred",client:b.recv,line:b.line,receiverLine:$.line,reason:"a message the server sends over a WebSocket (payload built at run time) is taken in by the message handler of "+f+", which connects to this server"+(S>1?"; "+S+" services connect to this server, so it may be meant for another one":""),...S>1?{candidates:S}:{}})}}}}return o.sort((c,d)=>c.fromService+c.fromNodeId+c.via+c.key+c.toService+c.toNodeId<d.fromService+d.fromNodeId+d.via+d.key+d.toService+d.toNodeId?-1:1),{edges:o,stats:i}}function Li(e,t){let n=new Map;for(let[r,o]of e){let s=t.filter(a=>a.filePath===r),i=o.rawSocketTypeChecks??[];for(let a of i){let l=fe(a.startLine,s);l&&n.set(a.eventName,l.id)}}return n}import rd from"node:fs";import sd from"node:path";function Ri(e){let t=["index.html","public/index.html","client/index.html","frontend/index.html","src/index.html"];for(let n of t){let r=sd.join(e,n);if(rd.existsSync(r))return r}return null}import Ln from"node:fs";import Rn from"node:path";var id=new Set(["node","tsx","ts-node","nodemon","bun","deno","ts-node-esm"]),ad=new Set(["watch","run","start","dev"]),cd=/\.[cm]?[jt]sx?$/,ld=["start","dev","serve","run"];function dd(e){for(let t of String(e).split(/&&|\|\||;|\|/)){let n=t.trim().split(/\s+/).filter(Boolean).map(o=>o.replace(/^["']|["']$/g,"")),r=n.findIndex(o=>id.has(Rn.basename(o).replace(/\.cmd$/,"")));if(!(r<0)){for(let o of n.slice(r+1))if(!(o.startsWith("-")||ad.has(o)||o.includes("="))){if(cd.test(o))return o;break}}}return null}var fd=e=>String(e).replace(/^@[^/]+\//,"");function Ti(e){let t;try{t=JSON.parse(Ln.readFileSync(Rn.join(e,"package.json"),"utf8"))}catch{return[]}let n=[],r=(o,s,i={})=>{if(typeof o!="string"||!o)return;let a=s==="script"?null:In(e,o,t);a?n.push({file:a.file,kind:s,...i,mappedFrom:o,mappedBy:a.how}):n.push({file:Rn.resolve(e,o),kind:s,...i})};if(typeof t.bin=="string")r(t.bin,"bin",{binName:fd(t.name??Rn.basename(e))});else if(t.bin&&typeof t.bin=="object")for(let[o,s]of Object.entries(t.bin))r(s,"bin",{binName:o});for(let o of ld){let s=t.scripts?.[o]&&dd(t.scripts[o]);s&&r(s,"script")}return r(t.main,"main"),n}function Ai(e){try{let t=Ln.openSync(e,"r"),n=Buffer.alloc(120),r=Ln.readSync(t,n,0,120,0);return Ln.closeSync(t),/^#!.*\b(node|tsx|ts-node|bun)\b/.test(n.toString("utf8",0,r).split(/\r?\n/)[0])}catch{return!1}}import Tn from"node:fs";import ut from"node:path";var ud=50,pd=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Oi=["",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts","/index.js","/index.ts","/index.mjs","/index.cjs","/index.tsx","/index.jsx"];function Mo(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=Mo(t);if(n)return n}return null}if(e&&typeof e=="object")for(let t of["import","node","require","default"]){let n=Mo(e[t]);if(n)return n}return null}function Mi(e,t){let n;try{n=JSON.parse(Tn.readFileSync(ut.join(e,"package.json"),"utf8"))}catch{return null}let r=n.exports,o=typeof r=="string"||Array.isArray(r)?r:r&&typeof r=="object"?r["."]??(Object.keys(r).some(c=>c.startsWith("."))?null:r):null,s=Mo(o)??(typeof n.module=="string"?n.module:null)??(typeof n.main=="string"?n.main:null);if(!s)return null;let i=new Set(t.map(c=>ut.resolve(c))),a=ut.resolve(e,s);for(let c of Oi)if(i.has(a+c))return t.find(d=>ut.resolve(d)===a+c);let l=[];try{l=Tn.readdirSync(e).filter(c=>pd.test(c)).sort()}catch{}for(let c of l){let d;try{d=Tn.readFileSync(ut.join(e,c),"utf8")}catch{continue}let p=/\bentry(?:Points)?\s*:\s*[\[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/.exec(d);if(!p)continue;let f=ut.resolve(e,p[1]);for(let u of Oi)if(i.has(f+u))return t.find(m=>ut.resolve(m)===f+u)}return null}function Hi(e,t,n,r,o=null){let s=new Map;for(let h of n){let v=s.get(h.filePath);v||s.set(h.filePath,v=[]),v.push(h)}let i=new Map,a=(h,v)=>{v&&(!i.has(v.id)||h<i.get(v.id))&&i.set(v.id,h)},l=new Map,c=(h,v)=>{let g=l.get(h);if(!g){g=new Map;let w="";try{w=Tn.readFileSync(h,"utf8")}catch{}for(let S of w.matchAll(/^[ \t]*(?:export\s+)?const\s+([\w$]+)\s*(?::[^=\n]+)?=\s*([\w$]+)\s*(?:as\s+[^;\n]+)?;?[ \t]*$/gm))S[1]!==S[2]&&g.set(S[1],S[2]);l.set(h,g)}return g.get(v)??null},d=(h,v)=>(s.get(h)??[]).find(g=>(g.type==="function"||g.type==="arrowFunction")&&g.name===v),p=(h,v)=>(s.get(h)??[]).filter(g=>g.type==="classMethod"&&g.className===v&&g.name!=="constructor"&&!/^[_#]/.test(g.name)),f=new Set;function u(h,v,g,w=0){let S=d(h,g);if(S){a(v,S);return}let N=p(h,g);for(let j of N)a(`${v}.${j.name}`,j);if(N.length||!o)return;let y=o.resolveName(h,g);if(y){a(v,y);return}let x=o.bindingFor(h,g),b=x&&w<3?o.resolveImport(h,x.source,x.kind,x.imported):null;if(b?.file&&b.local&&b.local!=="default"&&c(b.file,b.local)){u(b.file,v,b.local,w+1);return}let k=o.classForImport(h,g);if(k?.className)for(let j of p(k.file,k.className))a(`${v}.${j.name}`,j);if(k?.className)return;let $=c(h,g);$&&w<3&&u(h,v,$,w+1)}function m(h,v,g){let w=h+"|"+(g?[...g.keys()].sort().join(","):"*");if(f.has(w)||v>3)return;f.add(w);let S=t.get(h)?.exportBindings;if(!S)return;let N=y=>!g||g.has(y);for(let[y,x]of Object.entries(S.named??{}))N(y)&&u(h,g?.get(y)??y,x);S.default&&N("default")&&S.default!=="<anon>"&&u(h,g?.get("default")??S.default,S.default);for(let y of S.reexports??[]){if(!N(y.exported))continue;let x=Ae(y.source,h,r);x&&m(x,v+1,new Map([[y.imported,g?.get(y.exported)??y.exported]]))}for(let y of S.stars??[]){let x=Ae(y,h,r);x&&(g?m(x,v+1,g):m(x,v+1,null))}}return m(e,0,null),[...i].map(([h,v])=>({name:v,nodeId:h})).sort((h,v)=>h.name<v.name?-1:h.name>v.name?1:h.nodeId<v.nodeId?-1:1).slice(0,ud)}Le();import Ui from"node:path";import{fileURLToPath as md}from"node:url";import{Parser as Di,Language as hd}from"web-tree-sitter";var lh=Ui.dirname(md(globalThis.__canopyUrl("src/stage2_parse/initHtmlParser.js")));async function Bi(){await Di.init();let e=new Di,t=Ui.join(je("tree-sitter-html"),"tree-sitter-html.wasm"),n=await hd.load(t);return e.setLanguage(n),{parser:e,language:n}}function zi(e,t){let r=ee(t,"htmlScriptRoot.scm").matches(e.rootNode);for(let o of r){let s=o.captures.find(a=>a.name==="attr_name"),i=o.captures.find(a=>a.name==="script_src");if(s&&s.node.text==="src"&&i)return i.node.text}return null}function Wi(e,t,n){let r=[];e.forEach((l,c)=>{l.steps.forEach(d=>{if(!d.hasOwnSubTrace)return;let p=e.findIndex((f,u)=>u!==c&&f.steps[0]?.nodeId===d.nodeId);p!==-1&&r.push({fromWorkflowIndex:c,toWorkflowIndex:p,atNodeId:d.nodeId})})});let o=new Map;for(let l of t)o.set(l.id,l.serviceName??null);let s=new Map;function i(l,c,d,p){if(!l||!c||l===c)return;let f=`${l} -> ${c} -> ${d}`;s.has(f)?s.get(f).count+=1:s.set(f,{fromService:l,toService:c,viaMatchType:d,count:1});let u=s.get(f);p==="exact"?u.exact=(u.exact??0)+1:p==="inferred"?u.inferred=(u.inferred??0)+1:p==="resolved"&&(u.resolved=(u.resolved??0)+1)}for(let l of n){if(!l.resolved||!l.fromNodeId||!l.targetNodeId)continue;let c=o.get(l.fromNodeId)??null,d=o.get(l.targetNodeId)??null;i(c,d,l.matchType,l.confidence)}let a=Array.from(s.values());return{workflowLinks:r,serviceLinks:a}}var xd=J.dirname(gd(globalThis.__canopyUrl("src/index.js"))),qi=24*1e3*1e3;async function Ho(e,t={}){e=J.resolve(e),console.log(`
21
+ Analyzing: ${e}
22
+ `),console.log("Stage 1: finding source files...");let n=lo(e),r=n.files;Hs(Bs(e,r)),console.log(` found ${r.length} files`);let{parser:o,language:s,grammars:i}=await kr();await Sr({grammars:i},r),console.log(`
23
+ Stage 1b: partitioning files by service...`);let a=Ns(e,r),l=bs(a,r,e);a=l.services,l.added&&console.log(` note: ${l.added.reason} (service "${l.added.name}")`),console.log(` detected ${a.length} services: ${a.map(F=>`${F.name} (${F.kind})`).join(", ")}`);let c=new Map(a.map(F=>[F.name,[]])),d=[];for(let F of r){let P=lt(F,a);P?c.get(P).push(F):d.push(F)}console.log(" file partition:");for(let F of a)console.log(` ${F.name}: ${c.get(F.name).length} files`);console.log(` unassigned (shared/root-level): ${d.length} files`),d.length&&(console.log(" rule: these don't get their own Stage 5-7 run (no service of their own to have routes/listeners for) \u2014"),console.log(" each one is added to a service's parse scope ONLY if a file already in that"),console.log(" service actually imports it, so intra-service calls into shared code still resolve.")),console.log(`
24
+ Stage 2: parsing (all files, once \u2014 see note above)...`);let p=await ws(r,o,s,{onProgress:t.onProgress,grammars:i});function f(F){let P=new Set;for(let R of F){let I=p.get(R);if(I)for(let A of I.imports){let ae=Ae(A.source,R,r);ae&&d.includes(ae)&&P.add(ae)}}return[...P]}let u=new Map;for(let F of a){let P=c.get(F.name),R=f(P);u.set(F.name,[...P,...R]),console.log(` ${F.name}: ${P.length} own + ${R.length} shared file(s) pulled in by real imports = ${P.length+R.length} total scope`)}let m=a.filter(F=>!u.get(F.name)?.length);m.length&&(console.log(` excluding ${m.length} service(s) with 0 files: ${m.map(F=>F.name).join(", ")}`),a=a.filter(F=>u.get(F.name)?.length));let h=null,v=Ri(e);if(v){let{parser:F,language:P}=await Bi(),R=me.readFileSync(v,"utf-8"),I=F.parse(R),A=zi(I,P);if(A){let ae=J.dirname(v),T=J.join(ae,A);r.includes(T)&&(h=T,console.log(` found HTML root: ${A} -> ${T}`))}}let g=new Map,w=0,S=0;for(let F of a){let P=u.get(F.name);if(console.log(`
25
+ --- Service: ${F.name} (${F.kind}) \u2014 ${P.length} files in scope ---`),!P.length){console.log(" 0 files \u2014 nothing to trace for this service."),g.set(F.name,{nodes:[],resolvedEdges:[],workflows:[],routeIndex:new Map,eventIndex:new Map,rawEventIndex:new Map,parseResults:new Map});continue}let R=ls(new Map(P.map(E=>[E,p.get(E)]))),I=_s(R,a),A=$s(R,a);I=js(I.concat(A)),console.log(` Stage 3: materialized ${A.length} inline-handler nodes before edge construction`);let ae=Cs(R,I),T=li(R,I),xe=fi(R,I),V=Li(R,I);for(let E of P){let Q=new Set(R.get(E)?.exportedNames??[]);for(let q of I.filter(U=>U.filePath===E))q.exported=Q.has(q.name)}let ve=Js(ae,I,R,P,T,xe,V),_e=ve.filter(E=>E.resolved).length;console.log(` Stage 4 (scoped): resolved ${_e}/${ve.length} edges`);for(let E of P){let Q=R.get(E),q=Q?.routes??[],U=Q?.listeners??[],ne=le(E,I),Pe=jt(E,Q?.imports??[],P),nn=[];F.kind==="server"&&(nn=Q?.socketListeners??[]),I=Vs(I,E,q,U,ne,nn,Pe)}let Ie=I.filter(E=>E.isEntryPoint),st=Ie.filter(E=>E.trigger?.resolvedVia==="in-file").length,Xe=Ie.filter(E=>E.trigger?.resolvedVia==="cross-file").length,Ze=Ie.filter(E=>E.trigger?.resolvedVia==="inline").length;console.log(` Stage 5 entry points by resolution: in-file named ${st}, cross-file named (BUG A) ${Xe}, inline (BUG B) ${Ze}`);let en=ve.filter(E=>E.type!=="reference"&&!E.viaArgument),tn=Xs(I,en),it=[];if(F.kind==="client"&&h&&P.includes(h)&&it.push({id:`${h}::__module_root__`,name:"main",trigger:{type:"htmlRoot",label:"index.html script"}}),!it.length){let E=wn(F.rootPath,r),Q=E&&P.find(q=>J.resolve(q)===E.entry);Q&&(console.log(` found HTML root for ${F.name}: ${J.relative(e,E.indexHtml)} -> ${J.relative(e,Q)} (${E.via})`),it.push({id:`${Q}::__module_root__`,name:"main",trigger:{type:"htmlRoot",label:"index.html script"}}))}let xt=[];if(F.kind==="server"){let E=J.join(F.rootPath,"package.json");if(me.existsSync(E))try{let Q=JSON.parse(me.readFileSync(E,"utf-8")),q=Q.main;if(!q&&Q.scripts?.start){let U=Q.scripts.start.match(/([\w./-]+\.(?:js|mjs|cjs|ts))/);U&&(q=U[1])}if(q){let U=J.resolve(F.rootPath,q),ne=P.find(Pe=>J.resolve(Pe)===U);if(!ne){let Pe=In(F.rootPath,q,Q);Pe&&(ne=P.find(nn=>J.resolve(nn)===Pe.file))}ne?xt.push({id:`${ne}::__module_root__`,name:"main",trigger:{type:"processBootstrap",label:`${q} (package.json main)`}}):console.log(` note: ${F.name}'s package.json names "${q}" as its entry, but that file isn't in this service's own traced scope \u2014 no bootstrap workflow added.`)}}catch{}}if(!it.length){let E=new Set(xt.map(U=>U.id.split("::")[0])),Q=new Set;for(let U of ve)U.resolved&&U.fromNodeId.endsWith("::__module_root__")&&Q.add(U.fromNodeId);let q=Ti(F.rootPath).map(U=>({...U,file:P.find(ne=>J.resolve(ne)===U.file)})).filter(U=>U.file);for(let U of P)Ai(U)&&!q.some(ne=>ne.file===U)&&q.push({file:U,kind:"shebang"});for(let U of q){if(E.has(U.file)||It(J.relative(e,U.file))||!Q.has(`${U.file}::__module_root__`))continue;E.add(U.file);let ne=J.relative(F.rootPath,U.file).split(J.sep).join("/"),Pe=U.kind==="bin"?`CLI: ${U.binName}`:`Start: ${ne}`;xt.push({id:`${U.file}::__module_root__`,name:"main",trigger:{type:"processBootstrap",label:`${ne} (${U.kind==="bin"?"package.json bin":U.kind==="script"?"package.json script":U.kind==="main"?"package.json main":"#! shebang"}${U.mappedFrom?`, built to ${U.mappedFrom}`:""})`,workflowName:Pe}})}}let Tt=[];if(it.length+xt.length+Ie.filter(E=>!It(J.relative(e,E.filePath))).length===0){let E=Mi(F.rootPath,P);if(E){let Q=J.relative(F.rootPath,E).split(J.sep).join("/"),U=bn(I,R,ne=>jt(ne,R.get(ne)?.imports??[],P));for(let ne of Hi(E,R,I,P,U))Tt.push({id:ne.nodeId,name:I.find(Pe=>Pe.id===ne.nodeId)?.name??ne.name,trigger:{type:"publicApi",label:`${ne.name} (exported from ${Q})`,workflowName:`API: ${ne.name}`}});Tt.length&&console.log(` public API of ${F.name}: ${Tt.length} exported function(s)/method(s) from ${Q}`)}}let Qo=new Set(Tt.map(E=>E.id)),Ca=Qo.size?tn.filter(E=>!Qo.has(E.id)):tn,Xn=[...it,...xt,...Ie,...Tt,...Ca];console.log(` Stage 5 total entry points: ${Xn.length} (${it.length} HTML root, ${xt.length} process bootstrap, ${Ie.length} pattern-matched, ${tn.length} fallback)`);let Ea=Co(ve),Pa=ei(Xn,Ea,I,en,8,en.length===ve.length?null:Co(en)),La=new Set(tn.map(E=>E.id)),Ra=E=>E.trigger?"physical":La.has(E.entryPointId)?"fallback":"hub",Ta=Pa.map(E=>({...E,origin:Ra(E),steps:ti(E.steps,I)})),Aa=oi(Ta),er=Array.from(Aa.values()).map(ri),tr=er.filter(E=>!It(J.relative(e,String(E.steps[0]?.nodeId??"").split("::")[0])));S+=er.length-tr.length;let vt=ci(tr,{nodes:I});if(vt.some(E=>E.trigger)){let E=new Set(ve.filter(q=>q.type!=="returnValue"&&q.type!=="reference").map(q=>q.fromNodeId)),Q=new Set(vt.filter(q=>!q.trigger&&q.steps.length===1&&!E.has(q.steps[0].nodeId)).map(q=>q.steps[0].nodeId));Q.size&&(vt=vt.filter(q=>q.trigger||!Q.has(q.steps[0].nodeId)||q.steps.length>1),w+=Q.size)}console.log(` Stage 6-7: -> ${vt.length} named workflows for ${F.name}`),g.set(F.name,{nodes:I,resolvedEdges:ve,routeIndex:T,eventIndex:xe,rawEventIndex:V,workflows:vt,parseResults:R,files:P,entryPointCount:Xn.length})}console.log(`
26
+ --- Stage 5 (stitch): cross-service edge resolution ---`);let N=[],y=0,x=0;for(let F of a){let P=g.get(F.name);if(!P||!P.resolvedEdges.length)continue;let R=P.resolvedEdges.filter(I=>!I.resolved&&(I.type==="apiCall"||I.type==="socketEmit"||I.type==="rawSocketSend"));for(let I of R){let A=null,ae=null;for(let T of a){if(T.name===F.name)continue;let xe=g.get(T.name);if(!xe)continue;let V=null;if(I.type==="apiCall"&&I.scope!=="external"?V=xe.routeIndex.get(Ct(I.url)):I.type==="socketEmit"?V=xe.eventIndex.get(I.eventName):I.type==="rawSocketSend"&&(V=xe.rawEventIndex.get(I.eventName)),V){A=V,ae=T.name;break}}A?(N.push({fromService:F.name,fromNodeId:I.fromNodeId,toService:ae,toNodeId:A,via:I.type,key:I.url||I.eventName,confidence:"inferred",reason:"name-only match",...I.type==="apiCall"?{url:I.url}:{eventName:I.eventName}}),y++):x++}}console.log(` stitched ${y} cross-service edges`);let b=Pi(a,g,{repoRoot:e});for(let F of b.edges)N.push(F);console.log(` + ${b.edges.length} links from HTTP clients / WebSockets (${b.edges.filter(F=>F.confidence==="exact").length} exact, ${b.edges.filter(F=>F.confidence==="resolved").length} resolved)`),console.log(` ${x} unresolved calls remain unresolved even after checking every other service`);let k=new Map;function $(F,P,R){if(!F||P==null||R==null)return{available:!1,reason:"no line range recorded for this node"};try{k.has(F)||k.set(F,me.readFileSync(F,"utf-8").split(/\r\n|\n/));let I=k.get(F),A=Math.max(P,1),ae=Math.min(R,I.length);if(A>I.length)return{available:!1,reason:"recorded line range is past the end of the current file \u2014 source has likely moved"};let T=I.slice(A-1,ae).join(`
27
+ `);return{available:!0,filePath:F,startLine:A,endLine:ae,text:T}}catch(I){return{available:!1,reason:`source unavailable: ${I.code==="ENOENT"?"file not found (deleted or moved)":I.message}`}}}let j=/^(addEventListener|removeEventListener|on|once|postMessage|onmessage|subscribe)$/i,D=new Set(["call","methodCall","callSite"]);function L(F,P,R,I,A=null){let ae=T=>!!(A&&!I&&!T.deferred&&T.resolved&&T.targetNodeId&&D.has(T.type)&&T.targetNodeId!==F&&A.inWorkflow.has(T.targetNodeId)&&!A.children.has(T.targetNodeId));return P.filter(T=>T.fromNodeId===F&&T.type!=="apiCall").filter(T=>T.resolved&&T.targetNodeId?ae(T):!!T.deferred===I).map(T=>{let xe=T.type==="returnValue",V=!xe&&j.test(T.calleeNameRaw||""),ve=(T.branchPath??[]).map(Xe=>({...Xe,source:R?$(R,Xe.conditionLine,Xe.conditionLine):{available:!1,reason:"owning function's node not found"}})),_e=T.objectNameRaw?`${T.objectNameRaw}.${T.calleeNameRaw}`:T.calleeNameRaw,Ie=xe?_e:T.firstArgText?`${_e}(${T.firstArgText})`:_e,st=ae(T);return{label:Ie,line:T.line??null,column:T.column??null,branchPath:ve,source:R?$(R,T.line,T.line):{available:!1,reason:"owning function's node not found"},tag:st?"called-elsewhere":xe?"return-value":V?"runtime-dispatched":"unresolvable-call-site",...st?{targetNodeId:T.targetNodeId}:{},reason:st?"a call to a function this workflow shows under another step (a function is placed once, under the first step that reaches it); it runs here, at this line, in this order":xe?"the value this branch returns \u2014 not a function call, just what this path produces":V?`registered via ${T.calleeNameRaw}(...) \u2014 the handler runs later, outside this function's own execution`:I?"runs later, outside this function's own execution (an effect cleanup, a deferred callback)":"call target could not be statically resolved to a declared function (dynamic dispatch, external/browser API, or computed member access) \u2014 but it still runs here, in this order"}})}function K(F,P,R){return L(F,P,R,!0)}function z(F,P,R,I){return L(F,P,R,!1,I)}let O=[];for(let F of a){let P=g.get(F.name);if(!P)continue;let R=new Map(P.nodes.map(I=>[I.id,I]));for(let I of P.workflows){let A=new Set([F.name]),ae=new Set(I.steps.map(V=>V.nodeId)),T=new Map;for(let V of I.steps)V.parentNodeId!=null&&(T.get(V.parentNodeId)??T.set(V.parentNodeId,new Set).get(V.parentNodeId)).add(V.nodeId);let xe=I.steps.map(V=>{let ve=N.find(Ze=>Ze.fromService===F.name&&Ze.fromNodeId===V.nodeId),_e=R.get(V.nodeId),Ie=V.parentNodeId?R.get(V.parentNodeId):null,st=(V.branchPath??[]).map(Ze=>({...Ze,source:Ie?$(Ie.filePath,Ze.conditionLine,Ze.conditionLine):{available:!1,reason:"owning function's node not found"}})),Xe={...V,branchPath:st,source:_e?$(_e.filePath,_e.startLine,_e.endLine):{available:!1,reason:"node not found in this service's own graph"},alsoCallsRuntime:K(V.nodeId,P.resolvedEdges,_e?.filePath),inlineCalls:z(V.nodeId,P.resolvedEdges,_e?.filePath,{inWorkflow:ae,children:T.get(V.nodeId)??new Set})};return ve&&(A.add(ve.toService),Xe.crossesInto=ve.toService),Xe});O.push({...I,steps:xe,serviceId:F.name,servicesTouched:[...A]})}}console.log(`
28
+ Done: ${O.length} named workflows across all services
29
+ `),O.forEach(F=>console.log(` - [${F.serviceId}] ${F.name} (${F.steps.length} steps, ${F.occurrences} entry point(s))`));let W=t.outputDir??process.env.CANOPY_OUTPUT_DIR??J.join(xd,"..","output");me.existsSync(W)||me.mkdirSync(W,{recursive:!0});let G=Nn(e),te=new Set(a.flatMap(F=>u.get(F.name)??[])),ge=xr({discovered:n,parseResults:p,scopeFiles:te,rel:G.rel,rootService:l.added});ge.testWorkflowsExcluded=S,ge.guessedWorkflowsDropped=w;let rt={repoRoot:G.repoRoot,coverage:ge};me.writeFileSync(J.join(W,"meta.js"),`const meta = ${JSON.stringify(rt,null,2)};`),me.writeFileSync(J.join(W,"meta.json"),JSON.stringify(rt,null,2)),console.log(`
30
+ `+ln(ge)),me.existsSync(J.join(W,"history.js"))||me.writeFileSync(J.join(W,"history.js"),"const canopyHistory = null;");let Be=G.json(O,2),Qt=Be.length>qi;if(Qt&&(Be=G.json(O)),Qt&&Be.length>qi){let F=Ks(JSON.parse(Be));me.writeFileSync(J.join(W,"workflows.js"),`const workflows = ${F};`),me.rmSync(J.join(W,"workflows.json"),{force:!0}),console.log(`
31
+ workflows.json omitted (${(Be.length/1e6).toFixed(1)} MB plain); workflows.js written with shared sub-structures (${(F.length/1e6).toFixed(1)} MB)`)}else me.writeFileSync(J.join(W,"workflows.json"),Be),console.log(`
32
+ Saved to output/workflows.json`),me.writeFileSync(J.join(W,"workflows.js"),`const workflows = ${Be};`),console.log("Saved to output/workflows.js (for the viewer)");let Rt=a.flatMap(F=>g.get(F.name)?.nodes??[]),_=N.map(F=>({fromNodeId:F.fromNodeId,targetNodeId:F.toNodeId,resolved:!0,matchType:"crossLayer",confidence:F.confidence})),C=[...a.flatMap(F=>g.get(F.name)?.resolvedEdges??[]),..._],M=Wi(O,Rt,C);M.crossServiceEdges=N,me.writeFileSync(J.join(W,"systemGraph.js"),`const systemGraph = ${G.json(M,2)};`);let ie=a.map(({isRepoRoot:F,ownsLeftovers:P,...R})=>({...R,nodeCount:Rt.filter(I=>I.serviceName===R.name).length,workflowCount:O.filter(I=>I.serviceId===R.name).length}));me.writeFileSync(J.join(W,"services.js"),`const services = ${G.json(ie,2)};`),console.log(`Saved to output/systemGraph.js (${M.workflowLinks.length} workflow links, ${M.serviceLinks.length} service links)`),console.log("Saved to output/services.js"),console.log(`
33
+ Note on output shape: workflows.json entries gained two additive fields (serviceId, servicesTouched) \u2014 every field the old shape had (steps, name, trigger, occurrences, ...) is unchanged, so the existing viewer keeps working without modification.`);let ze=new Map;for(let F of a){let P=g.get(F.name);if(!P)continue;let R=G.clone(P.nodes.map(A=>({id:A.id,name:A.name,type:A.type,filePath:A.filePath,bodyHash:A.bodyHash??null,startLine:A.startLine===0?0:A.startLine,endLine:A.endLine===Number.MAX_SAFE_INTEGER?null:A.endLine,serviceName:A.serviceName,isEntryPoint:!!A.isEntryPoint}))),I=Is(G.clone(P.resolvedEdges.map(A=>({fromNodeId:A.fromNodeId,targetNodeId:A.targetNodeId??null,type:A.type,callKind:A.callKind,calleeNameRaw:A.calleeNameRaw,eventName:A.eventName,url:A.url,line:A.line??null,column:A.column??null,resolved:!!A.resolved,matchType:A.matchType??null}))));ze.set(F.name,{nodes:R,edges:I})}return{workflows:O,perService:g,crossServiceEdges:N,services:a,publicGraph:ze,publicWorkflows:G.clone(O),publicCrossServiceEdges:G.clone(N),fingerprint:kn(Sn(r,G.rel)),analyzedFileCount:r.length,repoRoot:G.repoRoot,coverage:ge}}var vd=process.argv[1]&&globalThis.__canopyUrl("src/index.js")===yd(J.resolve(process.argv[1])).href;vd&&Ho(process.argv[2]||process.cwd()).catch(e=>{console.error("Pipeline failed:",e),process.exit(1)});zo();Hn();pt();var Rd=he.join(he.dirname(ca(globalThis.__canopyUrl("src/history/sync.js"))),"..","..","output"),Td=["workflows.json","workflows.js","systemGraph.js","services.js","meta.js","meta.json","history.js"],Ad=he.dirname(ca(globalThis.__canopyUrl("src/history/sync.js"))).split(he.sep).includes("node_modules"),ht=e=>process.env.CANOPY_OUTPUT_DIR||(Ad&&e?he.join(he.resolve(e),".canopy","output"):Rd);async function Od(e,t){let n=console.log;console.log=()=>{};try{return await Ho(e,t)}finally{console.log=n}}function Md(e){let t=he.resolve(e),n=Nn(t);return kn(Sn(an(t),n.rel))}function Hd(e){try{let t=JSON.parse(nt.readFileSync(he.join(ht(e),"meta.json"),"utf8"));return t.coverage&&he.resolve(t.repoRoot)===he.resolve(e)?t.coverage:null}catch{return null}}async function Dd(e,{keep:t,say:n=()=>{}}){let r=Date.now(),o=He(e),s=o.versions[o.versions.length-1],i=Md(e),a=!!s&&s.fingerprint===i&&(s.engineVersion!==On()||s.outputFormat!==An);if(s&&s.fingerprint===i&&!a)return{status:"no-changes",version:s,ms:Date.now()-r,coverage:Hd(e)};let l=nt.mkdtempSync(he.join(Ld.tmpdir(),"canopy-sync-"));try{let c=await Od(e,{outputDir:l,onProgress:n}),d=Ji(c),p=Pt(d),f={nodes:d.nodes.length,edges:d.edges.length,workflows:d.workflows.length,physicalWorkflows:d.workflows.filter(v=>v.tier==="physical").length,crossServiceEdges:d.crossServiceEdges.length},u=Vi(e,p,d,f,t,{refresh:a}),m=await Promise.resolve().then(()=>(aa(),ia)).catch(()=>null);m&&m.writeHistoryJs(e,l);let h=ht(e);nt.mkdirSync(h,{recursive:!0});for(let v of Td)nt.existsSync(he.join(l,v))?nt.copyFileSync(he.join(l,v),he.join(h,v)):nt.rmSync(he.join(h,v),{force:!0});return{status:"new-version",version:u,ms:Date.now()-r,coverage:c.coverage}}finally{nt.rmSync(l,{recursive:!0,force:!0})}}async function zn(e,{keep:t=Wt,say:n=console.log}={}){if(e=he.resolve(e),Dn(e),nt.mkdirSync(se(e).root,{recursive:!0}),!Yi(e))return Zi(e),n("sync already running - one rerun queued"),{status:"queued"};let r;try{do r=await Dd(e,{keep:t,say:n}),r.status==="no-changes"?n(`no changes (v${r.version.version} ${r.version.fingerprint.slice(0,7)}) [${r.ms} ms]`):n(`v${r.version.version} ${r.version.fingerprint.slice(0,7)} stored: ${r.version.counts.nodes} nodes, ${r.version.counts.edges} edges, ${r.version.counts.workflows} workflows, ${(r.version.bytes/1024/1024).toFixed(2)} MB${r.version.gzip?" (gzip)":""} [${r.ms} ms]`),r.coverage&&n(`
34
+ `+ln(r.coverage));while(Qi(e))}finally{Xi(e)}return r}pt();pt();Le();import ue from"node:fs";import Ce from"node:path";import{spawn as Ud}from"node:child_process";import{fileURLToPath as Bd}from"node:url";var qt="# >>> canopy sync (managed block - do not edit) >>>",fa="# <<< canopy sync <<<",gt=["post-commit","post-merge"],zd=globalThis.__canopyBundle??Ce.join(Ce.dirname(Bd(globalThis.__canopyUrl("src/history/hooks.js"))),"..","cli.js"),Wd=e=>Ce.resolve(e).split(Ce.sep).join("/");function Gt(e){let t=be(e,["rev-parse","--git-path","hooks"]);if(!t)throw new Error(`not a git repository: ${e}`);return Ce.resolve(e,t)}var la=JSON.parse(ue.readFileSync(Ce.join(re,"package.json"),"utf8")),qd=la.name+"@"+la.version,da=e=>Wd(e).replace(/(["$`\\])/g,"\\$1");function Wn(e){return[qt,"(",` if command -v canopy >/dev/null 2>&1; then canopy sync --background "${da(e)}" >/dev/null 2>&1 </dev/null`,` elif command -v npx >/dev/null 2>&1; then ( npx --yes ${qd} sync --background "${da(e)}" >/dev/null 2>&1 </dev/null & )`,' else echo "canopy not found; skipping map update"'," fi",") || true",fa].join(`
35
+ `)+`
36
+ `}var qn=()=>new RegExp(`\\n?${qt.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}[\\s\\S]*?${fa.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\n?`);function Jt(e){let t=Gt(e);ue.mkdirSync(t,{recursive:!0});let n=[];for(let r of gt){let o=Ce.join(t,r),s=ue.existsSync(o)?ue.readFileSync(o,"utf8"):null,i;s===null?i=`#!/bin/sh
37
+ `+Wn(e):qn().test(s)?i=s.replace(qn(),()=>`
38
+ `+Wn(e)):i=s+(s.endsWith(`
39
+ `)?"":`
40
+ `)+`
41
+ `+Wn(e),ue.writeFileSync(o,i.replace(/\r\n/g,`
42
+ `));try{ue.chmodSync(o,493)}catch{}n.push(o)}return n}function ua(e){let t=Gt(e),n=[];for(let r of gt){let o=Ce.join(t,r);if(!ue.existsSync(o))continue;let s=ue.readFileSync(o,"utf8");if(!qn().test(s))continue;let i=s.replace(qn(),`
43
+ `);i.replace(/^#!.*\n?/,"").trim()===""?ue.rmSync(o,{force:!0}):ue.writeFileSync(o,i.replace(/\n{3,}/g,`
44
+
45
+ `)),n.push(o)}return n}function pa(e){if(!ue.existsSync(Ce.resolve(e)))return null;let t=se(e);ue.mkdirSync(t.root,{recursive:!0});let n=ue.openSync(t.log,"a");ue.writeSync(n,`
46
+ --- ${new Date().toISOString()} sync requested (pid ${process.pid})
47
+ `);let r=Object.fromEntries(Object.entries(process.env).filter(([s])=>!/^GIT_/i.test(s)||s.toUpperCase()==="GIT_EXEC_PATH")),o=Ud(process.execPath,[zd,"sync",Ce.resolve(e)],{detached:!0,stdio:["ignore",n,n],windowsHide:!0,env:r});return o.unref(),ue.closeSync(n),o.pid}function ma(e){let t=Gt(e),n=Wn(e),r=0,o=0;for(let s of gt){let i=Ce.join(t,s);if(!ue.existsSync(i))continue;let a=ue.readFileSync(i,"utf8").replace(/\r\n/g,`
48
+ `);a.includes(qt)&&(r++,a.includes(n)&&o++)}return r<gt.length?"absent":o===gt.length?"current":"outdated"}Go();Le();Le();import Vt from"node:fs";import rf from"node:http";import De from"node:path";import{spawn as sf}from"node:child_process";Le();import Gd from"node:fs";import Jd from"node:http";import Kd from"node:https";import Ko from"node:path";import{spawn as Vd,spawnSync as ga}from"node:child_process";var Yo="https://registry.npmjs.org/canopy-engine/latest",Jo="npm install -g canopy-engine@latest",ha=1e4,Yd=256*1024,Vo=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,Xd=e=>typeof e=="string"&&e.length<=64&&Vo.test(e);function Zd(e,t){let n=Vo.exec(e),r=Vo.exec(t);for(let o=1;o<=3;o++){let s=Number(n[o])-Number(r[o]);if(s)return s>0?1:-1}return n[4]&&!r[4]?-1:!n[4]&&r[4]?1:n[4]===r[4]?0:n[4]>r[4]?1:-1}function Qd(e=process.env){let t=e.CANOPY_REGISTRY_URL;return t&&/^http:\/\/127\.0\.0\.1:\d{1,5}(\/|$)/.test(t)?t:Yo}function ef(e=process.env){let t=Qd(e),n=t.startsWith("https:")?Kd:Jd;return new Promise((r,o)=>{let s=!1,i=(l,c)=>{s||(s=!0,l(c))},a=n.get(t,{headers:{accept:"application/json","user-agent":"canopy-engine-update-check"}},l=>{if(l.statusCode!==200)return l.resume(),i(o,new Error(`the registry answered HTTP ${l.statusCode}`));let c=0,d=[];l.on("data",p=>{if(c+=p.length,c>Yd){i(o,new Error("the registry's answer is larger than 256 KB; ignored")),a.destroy();return}d.push(p)}),l.on("end",()=>{let p;try{p=JSON.parse(Buffer.concat(d).toString("utf8"))?.version}catch{return i(o,new Error("the registry's answer is not valid JSON"))}if(!Xd(p))return i(o,new Error("the registry's answer has no valid version number"));i(r,p)}),l.on("error",p=>i(o,new Error("the connection broke: "+p.message)))});a.setTimeout(ha,()=>{i(o,new Error(`no answer from the registry within ${ha/1e3} s`)),a.destroy()}),a.on("error",l=>i(o,new Error("could not reach the registry: "+(l.code||l.message))))})}function Xo(e=re,t=bt()){return e.split(Ko.sep).includes("_npx")?"npx":t?"installed":"dev"}function ya(e=process.env){let t=e.CANOPY_NPM_BIN;return t?/\.(c|m)?js$/i.test(t)?{cmd:process.execPath,pre:[t],shell:!1}:{cmd:t,pre:[],shell:process.platform==="win32"&&/\.(cmd|bat)$/i.test(t)}:{cmd:process.platform==="win32"?"npm.cmd":"npm",pre:[],shell:process.platform==="win32"}}var Kt=(e,t)=>t&&/[\s"]/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e;function tf(e,t){let{cmd:n,pre:r,shell:o}=ya(t);return new Promise(s=>{let i=Vd(Kt(n,o),[...r,...e].map(a=>Kt(a,o)),{stdio:"inherit",shell:o,env:t});i.on("error",()=>s(1)),i.on("close",a=>s(a??1))})}function nf(e,t){let{cmd:n,pre:r,shell:o}=ya(t),s=ga(Kt(n,o),[...r,...e].map(i=>Kt(i,o)),{encoding:"utf8",shell:o,env:t,timeout:3e4});return s.status===0?s.stdout.trim():null}function of(e){let t=nf(["prefix","-g"],e),n=["canopy","canopy-engine"],r=[];if(t)for(let o of n)r.push(process.platform==="win32"?Ko.join(t,o+".cmd"):Ko.join(t,"bin",o));for(let o of r){if(!Gd.existsSync(o))continue;let s=process.platform==="win32"&&/\.(cmd|bat)$/i.test(o),i=ga(Kt(o,s),["--version"],{encoding:"utf8",shell:s,env:e,timeout:3e4});if(i.status===0)return i.stdout.trim().split(/\r?\n/).pop().trim()}return null}async function xa({check:e,version:t,root:n=re,installed:r=bt(),env:o=process.env,out:s=console.log,err:i=console.error}){let a=Xo(n,r);if(a==="dev")return s("dev checkout: update disabled"),0;if(a==="npx")return s("You are running via npx; npx canopy-engine@latest always uses the newest version"),0;let l;try{l=await ef(o)}catch(p){return i(`could not check for updates: ${p.message}`),i(" you can look it up yourself: npm view canopy-engine version"),1}if(Zd(l,t)<=0)return s(`up to date (${t})`),0;if(e)return s(`${l} available (you have ${t}). Run: canopy update`),0;s(`Updating canopy-engine ${t} -> ${l}`),s(` running: ${Jo}`);let c=await tf(["install","-g","canopy-engine@latest"],o);if(c!==0)return i(`The update did not finish (npm exited with ${c}). Run it yourself: ${Jo}`),1;let d=of(o);return d!==l?(i(`npm finished, but the installed canopy reports ${d??"no version"} instead of ${l}. Run it yourself: ${Jo}`),1):(s(`Updated: canopy ${d} is installed.`),0)}var wa={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".json":"application/json",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".woff2":"font/woff2",".map":"application/json"};function va(e,t,n){let r=De.join(e,De.normalize(t).replace(/^([/\\]|\.\.[/\\])+/,""));if(!r.startsWith(e+De.sep)&&r!==e){n.writeHead(403).end("forbidden");return}Vt.readFile(r,(o,s)=>{if(o){n.writeHead(404,{"content-type":"text/plain"}).end("not found: "+t);return}n.writeHead(200,{"content-type":wa[De.extname(r).toLowerCase()]??"application/octet-stream","cache-control":"no-store"}).end(s)})}var af=(()=>{try{return JSON.parse(Vt.readFileSync(De.join(re,"package.json"),"utf8")).version}catch{return null}})();function cf({env:e=process.env,version:t=af,kind:n=Xo()}={}){return e.CANOPY_NO_UPDATE_CHECK==="1"||e.CANOPY_NO_UPDATE_CHECK==="true"||n!=="installed"||!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(String(t))?"":`<meta name="canopy-update-check" content="${Yo}" data-current="${t}">`}function lf(e,t,n){Vt.readFile(De.join(e,"index.html"),"utf8",(r,o)=>{if(r){t.writeHead(404,{"content-type":"text/plain"}).end("not found: index.html");return}t.writeHead(200,{"content-type":wa[".html"],"cache-control":"no-store"}).end(n?o.replace("</head>",n+`
49
+ </head>`):o)})}var Gn=()=>{let e=De.join(re,"ui-react");return!Vt.existsSync(De.join(e,"index.html"))||!Vt.existsSync(De.join(e,"dist"))?`this install has no built viewer (ui-react/dist is missing)
50
+ fix: reinstall canopy from a build that includes the viewer`:null};async function Jn(e,t=0,{updateTag:n=cf()}={}){let r=De.join(re,"ui-react"),o=rf.createServer((i,a)=>{let l;try{l=decodeURIComponent((i.url??"/").split("?")[0])}catch{a.writeHead(400).end("bad request");return}if(l==="/"||l==="/index.html"){a.writeHead(302,{location:"/ui-react/index.html"}).end();return}if(l==="/ui-react/index.html")return lf(r,a,n);if(l.startsWith("/ui-react/"))return va(r,l.slice(10),a);if(l.startsWith("/output/"))return va(e,l.slice(8),a);a.writeHead(404).end("not found")});await new Promise((i,a)=>{o.once("error",a),o.listen(t,"127.0.0.1",i)});let s=o.address().port;return{server:o,port:s,url:`http://127.0.0.1:${s}/`}}function Sa(e){if(process.env.CANOPY_NO_BROWSER)return!1;try{let t,n;if(process.platform==="win32")t="cmd.exe",n=["/c","start","",e];else if(process.platform==="darwin")t="open",n=[e];else if(process.env.DISPLAY||process.env.WAYLAND_DISPLAY)t="xdg-open",n=[e];else return!1;let r=sf(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),!0}catch{return!1}}Le();pt();import Ue from"node:fs";import Ye from"node:path";import{execFileSync as ka}from"node:child_process";function Kn(e){let t=[],n=(r,o,s,i)=>{let a=!1,l="";try{let c=s();a=c===!0||!!(c&&c.ok),l=c&&c.detail?c.detail:""}catch(c){l=String(c.message??c).split(`
51
+ `)[0]}t.push({name:r,critical:o,ok:a,detail:l,fix:i})};return n("Node version >= 18",!0,()=>({ok:Number(process.versions.node.split(".")[0])>=18,detail:"v"+process.versions.node}),"install Node 18 or newer from https://nodejs.org and run canopy again"),n("tree-sitter grammars (wasm)",!0,()=>{let r=[["web-tree-sitter","web-tree-sitter.wasm"],["tree-sitter-javascript","tree-sitter-javascript.wasm"],["tree-sitter-typescript","tree-sitter-typescript.wasm"],["tree-sitter-typescript","tree-sitter-tsx.wasm"],["tree-sitter-html","tree-sitter-html.wasm"]],o=r.filter(([s,i])=>!Ue.existsSync(Ye.join(je(s),i))).map(([,s])=>s);return{ok:o.length===0,detail:o.length?"missing "+o.join(", "):r.length+" files"}},"reinstall canopy: npm install -g canopy-engine (or, in a checkout, npm install in the canopy-engine folder)"),n("query files (.scm)",!0,()=>{let r=[Ye.join(re,"src","stage2_parse","queries"),Ye.join(re,"dist","queries")].find(s=>Ue.existsSync(s))??Ye.join(re,"dist","queries"),o=Ue.readdirSync(r).filter(s=>s.endsWith(".scm")).length;return{ok:o>=10,detail:o+" files"}},"reinstall canopy: the package is missing its query files (dist/queries)"),n("write access to <path>/.canopy",!0,()=>{let r=se(e).root;Ue.mkdirSync(r,{recursive:!0});let o=Ye.join(r,`.doctor-${process.pid}`);return Ue.writeFileSync(o,"x"),Ue.rmSync(o),{ok:!0,detail:r}},`make ${e} writable for your user, or run canopy on a folder you own`),n("git available",!1,()=>({ok:!!ka("git",["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}),detail:ka("git",["--version"],{encoding:"utf8"}).trim()}),"install git (https://git-scm.com); without it version history and the hook are limited"),n("map viewer present",!1,()=>({ok:Ue.existsSync(Ye.join(re,"ui-react","index.html"))&&Ue.existsSync(Ye.join(re,"ui-react","dist"))}),"canopy open needs the built viewer (ui-react/dist); reinstall from a build that includes it"),n("post-commit hook installed",!1,()=>{if(!be(e,["rev-parse","--git-dir"]))return{ok:!1,detail:"not a git repository"};let r=Gt(e),o=gt.every(s=>Ue.existsSync(Ye.join(r,s))&&Ue.readFileSync(Ye.join(r,s),"utf8").includes(qt));return{ok:o,detail:o?"post-commit, post-merge":""}},`canopy hook install "${e}"`),t}function Na(e,t,n,r=console.log){r(`canopy ${n} doctor (${t})
52
+ `);for(let s of e)r(`${s.ok?"OK ":"FAIL"} ${s.name}${s.detail?" - "+s.detail:""}${s.ok?"":`
53
+ fix: ${s.fix}`}${!s.ok&&!s.critical?" (not critical)":""}`);let o=e.filter(s=>s.critical&&!s.ok);return r(`
54
+ ${o.length?`${o.length} critical problem(s) - fix them and run canopy doctor again`:"all critical checks passed"}`),o.length}import pe from"node:fs";import df from"node:net";import ff from"node:os";import ot from"node:path";import uf from"node:readline";pt();var ba=Number(process.env.CANOPY_MIN_FREE_MB)||300,pf=".js .jsx .mjs .cjs .ts .tsx .mts .cts",Vn=class extends Error{constructor(t,n){super(n),this.code=t,this.line=n}},$e=(e,t)=>{throw new Vn(e,t)};function mf(e){let t=!!be(e,["rev-parse","--git-dir"]),n=ot.join(e,".gitignore"),r=pe.existsSync(n);if(!t&&!r)return"skipped";let o=r?pe.readFileSync(n,"utf8"):"";if(o.split(/\r?\n/).some(i=>/^\/?\.canopy\/?$/.test(i.trim())))return"already";let s=/\r\n/.test(o)?`\r
55
+ `:`
56
+ `;return pe.appendFileSync(n,(o&&!/\r?\n$/.test(o)?s:"")+"# Canopy (code map output)"+s+".canopy/"+s),r?"added":"created"}var _a=e=>ot.join(se(e).root,"prefs.json"),$a=e=>{try{return JSON.parse(pe.readFileSync(_a(e),"utf8"))}catch{return{}}};function Yn(e,t){let n={...$a(e),...t};for(let r of Object.keys(n))n[r]===void 0&&delete n[r];pe.mkdirSync(se(e).root,{recursive:!0}),pe.writeFileSync(_a(e),JSON.stringify(n,null,2))}function hf(e){return new Promise(t=>{let n=df.createServer();n.once("error",r=>t({ok:!1,code:r.code,message:r.message})),n.listen(e,"127.0.0.1",()=>{let r=n.address().port;n.close(()=>t({ok:!0,port:r}))})})}function gf(e){try{let t=pe.statfsSync(e);return Math.floor(t.bavail*t.bsize/1048576)}catch{return null}}var yf=()=>!!(process.stdin.isTTY&&process.stdout.isTTY)||!!process.env.CANOPY_ASSUME_TTY;function xf(e,t){return new Promise(n=>{let r=uf.createInterface({input:process.stdin,output:process.stdout,terminal:!1}),o=!1,s=i=>{o||(o=!0,r.close(),n(i))};r.question(e,i=>s(i.trim())),r.once("close",()=>s(""))}).then(n=>n===""?t:n)}function vf(e){try{return JSON.parse(pe.readFileSync(ot.join(e,"meta.json"),"utf8"))}catch{return null}}function wf(e){try{return JSON.parse(pe.readFileSync(ot.join(e,"services.js"),"utf8").replace(/^\s*const services\s*=\s*/,"").replace(/;\s*$/,""))}catch{return[]}}var Sf=e=>`How did it go? ${e.canopyFeedbackUrl||"see FEEDBACK.md in the README (about 20 minutes)"}`;async function Fa(e){let t=e.say??console.log,{pkg:n}=e,r=null;try{return await o()}catch(c){if(c instanceof Vn){if(t(c.line),r)try{pe.rmdirSync(r)}catch{}return c.code}return t(`Canopy stopped because of an unexpected problem: ${String(c.message??c).split(`
57
+ `)[0]}
58
+ Run "canopy doctor", then send its output and .canopy/sync.log to whoever gave you Canopy.`),process.env.CANOPY_DEBUG&&t(c.stack),1}async function o(){let c=ot.resolve(e.target??process.cwd());t(`Canopy ${n.version} - a map of what your JavaScript / TypeScript code does`),t(`Folder: ${c}
59
+ `),t("[1/6] Checking this computer..."),Number(process.versions.node.split(".")[0])<18&&$e(1,`Canopy needs Node 18 or newer and this is Node ${process.versions.node}. Install the current LTS from https://nodejs.org and run canopy again.`);let d=pe.existsSync(c)&&pe.statSync(c).isDirectory();pe.existsSync(c)||$e(1,`That folder does not exist: ${c}. Check the spelling, or run canopy inside your project folder.`),d||$e(1,`${c} is a file, not a folder. Run canopy on the folder that contains it: canopy "${ot.dirname(c)}"`);let p=pe.existsSync(se(c).root),f=Kn(c);p||(r=se(c).root);let u=f.find(L=>L.critical&&!L.ok);u&&$e(1,`${u.name} failed${u.detail?" ("+u.detail+")":""}. ${u.fix}.`.replace(/\.\.$/,"."));let m=!!be(c,["rev-parse","--git-dir"]),h=f.find(L=>L.name==="git available")?.ok,v=Gn();v&&!e.noOpen&&$e(1,`Canopy cannot show the map: ${v.replace(/\n\s*/g,". ")}.`);let g=gf(c);if(g!==null&&g<ba&&$e(1,`Only ${g} MB free on the disk holding ${c}; Canopy needs about ${ba} MB. Free some space and run canopy again.`),!e.noOpen){let L=await hf(e.port??0);L.ok||$e(1,L.code==="EADDRINUSE"?`Port ${e.port} is already in use. Pick another with --port=NUMBER, or leave --port out and Canopy picks a free one.`:`Canopy cannot open a local port on 127.0.0.1 (${L.code||L.message}). Check your firewall or security software and run canopy again.`)}t(` Node ${process.versions.node}, ${h?"git found":"git not found (no version history or commit hook)"}, ${g===null?"disk space not checked":g+" MB free"}${e.noOpen?"":", a local port is free"}.`),t("[2/6] Looking at your project..."),pe.readdirSync(c).filter(L=>L!==".git"&&L!==".canopy").length===0&&$e(1,`${c} is empty. Add some JavaScript or TypeScript code and run canopy again.`);let S=an(c);S.length===0&&$e(3,`No JavaScript or TypeScript files found in ${c}. Canopy currently supports JavaScript and TypeScript (${pf}); other languages are not read yet.`);let N=m&&be(c,["rev-parse","--verify","-q","HEAD"])!==null;t(` ${S.length.toLocaleString("en-US")} JavaScript / TypeScript file${S.length===1?"":"s"}. ${m?N?"Git repository.":"Git repository with no commits yet (that is fine).":"Not a git repository (that is fine; version-aware features are limited)."}`),t("[3/6] Preparing the output folder..."),pe.mkdirSync(se(c).root,{recursive:!0}),Dn(c);let y=mf(c),x={added:"added .canopy/ to .gitignore",created:"created .gitignore with .canopy/ in it",already:".canopy/ is already in .gitignore",skipped:"no git repository, so no .gitignore change"}[y];t(` Map output goes to ${ot.join(c,".canopy")} (${x}).`),t("[4/6] Commit hook..."),await s(c,m);let b=He(c).versions.length>0;t(`[5/6] ${b?"Checking what changed since last time":"Building your map for the first time (a big project can take a few minutes)"}...`);let k=await i(c,S.length);a(c,k);let $=ht(c);if(e.noOpen)return t("[6/6] Not opening the map (--no-open). To view it later: canopy open"),l(),0;t("[6/6] Opening the map...");let j;try{j=await Jn($,e.port??0)}catch(L){$e(1,`Canopy cannot start the viewer: ${L.code||L.message}. ${L.code==="EADDRINUSE"?"Pick another port with --port=NUMBER.":"Check your firewall or security software."}`)}t(` ${j.url}`);let D=Sa(j.url);return t(D?" Your browser should open now. If it does not, paste that address into one.":" Open that address in your browser."),l(),e.forSeconds?(await new Promise(L=>setTimeout(L,e.forSeconds*1e3)),j.server.close(),0):(t("Press Ctrl+C to stop."),await new Promise(()=>{}),0)}async function s(c,d){if(!d){t(" No git repository here, so there is no commit hook to set up.");return}if(!kf()){t(" git is not installed, so the commit hook is skipped.");return}let p;try{p=ma(c)}catch(u){t(" Could not look at the git hooks ("+String(u.message).split(`
60
+ `)[0]+"); skipping the commit hook.");return}if(p==="current"){t(" The map already updates on every commit.");return}if(p==="outdated"){try{Jt(c),t(" Refreshed the commit hook (it now matches this Canopy).")}catch(u){t(" Could not refresh the commit hook: "+String(u.message).split(`
61
+ `)[0])}return}if($a(c).hook==="declined"&&!e.yes){t(" The commit hook is off (you chose that earlier). Turn it on with: canopy hook install");return}let f=!0;if(e.yes)t(" Update the map on every commit? [Y/n] Y (--yes)");else if(!yf())t(" Update the map on every commit? [Y/n] Y (default; no terminal to ask)");else{let u=await xf(" Update the map on every commit? [Y/n] ","Y");f=/^y(es)?$/i.test(u)}if(!f){Yn(c,{hook:"declined"}),t(" Okay, no hook. Turn it on any time with: canopy hook install");return}try{Jt(c),Yn(c,{hook:void 0}),t(" Done: after every commit and merge the map updates itself in the background (it never blocks or fails a commit). Remove it with: canopy hook uninstall")}catch(u){t(" Could not install the commit hook: "+String(u.message).split(`
62
+ `)[0]+". Continuing without it.")}}async function i(c,d){let p=Date.now(),f=h=>{let v=/parsing: (\d+)\/(\d+) files/.exec(String(h));v&&t(` reading files: ${v[1]} of ${v[2]}`)};t(` Reading ${d.toLocaleString("en-US")} file${d===1?"":"s"}, linking calls, finding entry points, tracing workflows...`);let u;for(let h=0;h<2&&(u=await zn(c,{say:v=>f(v),onProgress:f}).catch(v=>$e(1,`The analysis failed: ${String(v.message??v).split(`
63
+ `)[0]}
64
+ Run "canopy doctor" and send its output with ${ot.join(c,".canopy","sync.log")} to whoever gave you Canopy.`)),u.status==="queued");h++){t(" Another update is already running; waiting for it to finish...");for(let v=0;v<1200&&pe.existsSync(se(c).lock);v++)await new Promise(g=>setTimeout(g,500))}u.status==="queued"&&$e(1,"Another Canopy update is still running. Wait for it to finish and run canopy again.");let m=((Date.now()-p)/1e3).toFixed(1);return t(u.status==="no-changes"?` Nothing changed since version ${u.version.version} (${m} s).`:` Saved version ${u.version.version} (${m} s).`),u}function a(c,d){let p=ht(c),f=d.coverage??vf(p)?.coverage,u=wf(p),m=d.version.counts??{};if(t(`
65
+ Your map`),t(` services: ${u.length}${u.length?" ("+u.map(h=>h.id??h.name).slice(0,8).join(", ")+(u.length>8?", ...":"")+")":""}`),t(` workflows: ${m.workflows??"?"}${m.physicalWorkflows!==void 0?` (${m.physicalWorkflows} traced from real code, ${m.workflows-m.physicalWorkflows} guessed)`:""}`),f){let h=f.analyzed?Math.round(f.inService/f.analyzed*100):0;t(` files inside a service: ${f.inService} of ${f.analyzed} (${h}%)`),t(` files with parse errors: ${f.parseErrors}${f.parseErrors?" ("+f.parseErrorFiles.slice(0,3).join(", ")+(f.parseErrorFiles.length>3?", ...":"")+")":""}`),f.notAnalyzedTotal&&t(` not read yet: ${f.notAnalyzedTotal} files in languages Canopy does not support (${Object.entries(f.notAnalyzed).map(([v,g])=>`${g} ${v}`).join(", ")})`)}u.length||t(" The map is empty: Canopy found no entry points (routes, listeners, a main file) it recognises in this project."),t("")}function l(){t("Next time just run `canopy`."),t(Sf(n))}}function kf(){return!!be(ff.tmpdir(),["--version"])}var Zt=JSON.parse(Zo.readFileSync(Yt.join(re,"package.json"),"utf8")),Nf={"-y":"--yes","-h":"--help","-v":"--version"},Ia=process.argv.slice(2).map(e=>Nf[e]??e),de=Object.fromEntries(Ia.filter(e=>e.startsWith("--")).map(e=>{let[t,n]=e.slice(2).split("=");return[t,n??!0]})),Fe=Ia.filter(e=>!e.startsWith("--")),Ee=Fe.shift(),bf=e=>/^v?\d+$/.test(e??""),yt=()=>Yt.resolve(Fe[0]&&!bf(Fe[0])?Fe.shift():process.cwd()),ja=`canopy ${Zt.version} - a map of what your JavaScript / TypeScript code does
66
+
67
+ usage: canopy [path] [-y] [--no-open] do everything in order: check this computer, look at the project, prepare .canopy/,
68
+ offer the commit hook, build the map, open it in your browser (default path: current folder)
69
+ canopy <command> [path]
70
+ sync [path] analyze the repo (default: current folder); stores a new version if the code changed
71
+ open [path] serve the map on the latest output and print the URL (Ctrl+C stops it) [--port=N] [--for=SECONDS]
72
+ doctor [path] check Node, grammars, queries, write access, git and the hook; says how to fix each problem
73
+ history [path] list the stored versions
74
+ diff [path] [from] [to] what changed between two versions [--json]
75
+ hook install [path] run "canopy sync" in the background after every commit and merge (safe to repeat)
76
+ hook uninstall [path] remove it again
77
+ update [--check] look up the newest version on npm (the only command that uses the network); "update" installs it with npm
78
+ --version, --help
79
+
80
+ options for the one-command path: -y / --yes (do not ask; install the hook), --no-open (build the map but do not start the viewer),
81
+ --port=N, --for=SECONDS (stop the viewer by itself after that time)
82
+ Exit codes: 0 ok, 1 a problem (the message says what to do), 3 no JavaScript / TypeScript files found.
83
+ Node >= 18 required. Output lives in <path>/.canopy/ (kept out of git automatically).`;async function _f(){let e=yt(),t=ht(e);Zo.existsSync(Yt.join(t,"workflows.js"))||(console.error(`no map yet for ${e}
84
+ fix: canopy sync "${e}"`),process.exit(1));let n=Gn();n&&(console.error(n),process.exit(1));let{server:r,url:o}=await Jn(t,de.port?Number(de.port):0);if(console.log(`canopy map for ${e}
85
+ ${o}`),de.for){console.log(`serving for ${Number(de.for)} s`),await new Promise(s=>setTimeout(s,Number(de.for)*1e3)),r.close();return}console.log("press Ctrl+C to stop"),await new Promise(()=>{})}function $f(){let e=yt();process.exit(Na(Kn(e),e,Zt.version)?1:0)}var Xt={async sync(){let e=yt();if(de.background){let n=pa(e);n?console.log(`sync started in the background (pid ${n}); log: .canopy/sync.log`):console.error(`not a directory, nothing to sync: ${e}`);return}let t=de.keep?Number(de.keep):Wt;await zn(e,{keep:t})},open:_f,async doctor(){$f()},async update(){process.exit(await xa({check:!!de.check,version:Zt.version}))},async diff(){let e=yt(),t=He(e);if(t.versions.length<2){console.log(t.versions.length?"only one version so far - nothing to diff yet":"no versions yet - run: canopy sync");return}let n=i=>{let a=Number(String(i).replace(/^v/,"")),l=t.versions.find(c=>c.version===a);if(!l)throw new Error(`no such version: ${i} (have ${t.versions.map(c=>"v"+c.version).join(", ")})`);return l},r=Fe[1]!==void 0?n(Fe[1]):t.versions[t.versions.length-1],o=Fe[0]!==void 0?n(Fe[0]):t.versions[t.versions.indexOf(r)-1];if(!o)throw new Error("no earlier version to compare against");let s=Un(Lt(e,o),Lt(e,r));console.log(de.json?ta(s):na(s,r,o))},async"install-hook"(){let e=yt(),t=Jt(e);Yn(e,{hook:void 0}),console.log("installed canopy block in: "+t.join(", "))},async"uninstall-hook"(){let e=ua(yt());console.log(e.length?"removed canopy block from: "+e.join(", "):"no canopy hook block found")},async hook(){let e=Fe.shift();if(e==="install")return Xt["install-hook"]();if(e==="uninstall")return Xt["uninstall-hook"]();console.error("usage: canopy hook install|uninstall [path]"),process.exit(2)},async history(){let e=yt(),t=He(e);if(!t.versions.length)return console.log("no versions yet - run: canopy sync");for(let n of t.versions)console.log(`v${n.version} ${n.fingerprint.slice(0,7)} ${n.createdAt} ${n.headSha?n.headSha.slice(0,7):"-------"}${n.dirty?"*":" "} ${n.headMessage?JSON.stringify(n.headMessage):""} nodes ${n.counts.nodes} edges ${n.counts.edges} workflows ${n.counts.workflows} ${(n.bytes/1024).toFixed(0)} KB${n.gzip?" gz":""}`)}};(de.version||Ee==="version")&&(console.log(Zt.version),process.exit(0));(de.help||Ee==="help")&&(console.log(ja),process.exit(0));if(Ee===void 0||!Xt[Ee]&&(Zo.existsSync(Yt.resolve(Ee))||/^[.~]|[\\/]/.test(Ee))){Ee!==void 0&&Fe.unshift(Ee);let e=await Fa({target:Fe[0]?Yt.resolve(Fe[0]):process.cwd(),yes:!!de.yes,noOpen:!!de["no-open"],port:de.port?Number(de.port):void 0,forSeconds:de.for?Number(de.for):void 0,pkg:Zt});process.exit(e)}Xt[Ee]||(console.error(`unknown command: ${Ee}
86
+
87
+ ${ja}`),process.exit(2));Xt[Ee]().catch(e=>{console.error(e.stack||e.message),process.exit(1)});