canopy-engine 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/canopy.js CHANGED
@@ -3,66 +3,107 @@ import{fileURLToPath as __cf,pathToFileURL as __cu}from"node:url";import{dirname
3
3
  const require=__cr(import.meta.url);
4
4
  globalThis.__canopyBundle=__cf(import.meta.url);
5
5
  globalThis.__canopyUrl=(r)=>__cu(__cj(__cd(__cd(globalThis.__canopyBundle)),r)).href;
6
- var Oa=Object.create;var Zn=Object.defineProperty;var Ma=Object.getOwnPropertyDescriptor;var Ha=Object.getOwnPropertyNames;var Da=Object.getPrototypeOf,Ua=Object.prototype.hasOwnProperty;var wt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Ba=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},za=(e,t)=>{for(var n in t)Zn(e,n,{get:t[n],enumerable:!0})},Wa=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ha(t))!Ua.call(e,o)&&o!==n&&Zn(e,o,{get:()=>t[o],enumerable:!(r=Ma(t,o))||r.enumerable});return e};var qa=(e,t,n)=>(n=e!=null?Oa(Da(e)):{},Wa(t||!e||!e.__esModule?Zn(n,"default",{value:e,enumerable:!0}):n,e));var dr=Ba((jf,sn)=>{function rr(e){return Array.isArray(e)?e:[e]}var Ga=void 0,eo="",nr=" ",Qn="\\",Ja=/^\s+$/,Ka=/(?:[^\\]|^)\\$/,Va=/^\\!/,Ya=/^\\#/,Xa=/\r?\n/g,Za=/^\.{0,2}\/|^\.{1,2}$/,Qa=/\/$/,St="/",sr="node-ignore";typeof Symbol<"u"&&(sr=Symbol.for("node-ignore"));var ir=sr,kt=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),ec=/([0-z])-([0-z])/g,ar=()=>!1,tc=e=>e.replace(ec,(t,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?t:eo),nc=e=>e.startsWith("!")||e.startsWith("\\^")?`^${e.slice(e[0]==="!"?1:2)}`:e,oc=e=>{let{length:t}=e;return e.slice(0,t-t%2)},rc=[[/^\uFEFF/,()=>eo],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?nr:eo)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+nr}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*(?:\\\*\\\*\\\/)+/,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>{let r=n.replace(/\\\*/g,"[^\\/]*");return t+r}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Qn],[/\\\\/g,()=>Qn],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,o)=>t===Qn?`\\[${n}${oc(r)}${o}`:o==="]"&&r.length%2===0?`[${nc(tc(n))}${r}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],sc=/(^|\\\/)?\\\*$/,At="regex",on="checkRegex",or="_",ic={[At](e,t){return`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`},[on](e,t){return`${t?`${t}[^/]*`:"[^/]*"}(?=$|\\/$)`}},ac=e=>rc.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),rn=e=>typeof e=="string",cc=e=>e&&rn(e)&&!Ja.test(e)&&!Ka.test(e)&&e.indexOf("#")!==0,lc=e=>e.split(Xa).filter(Boolean),to=class{constructor(t,n,r,o,s,i){this.pattern=t,this.mark=n,this.negative=s,kt(this,"body",r),kt(this,"ignoreCase",o),kt(this,"regexPrefix",i)}get regex(){let t=or+At;return this[t]?this[t]:this._make(At,t)}get checkRegex(){let t=or+on;return this[t]?this[t]:this._make(on,t)}_make(t,n){let r=this.regexPrefix.replace(sc,ic[t]),o=this.ignoreCase?new RegExp(r,"i"):new RegExp(r);return kt(this,n,o)}},dc=({pattern:e,mark:t},n)=>{let r=!1,o=e;o.indexOf("!")===0&&(r=!0,o=o.substr(1)),o=o.replace(Va,"!").replace(Ya,"#");let s=ac(o);return new to(e,t,o,n,r,s)},no=class{constructor(t){this._ignoreCase=t,this._rules=[]}_add(t){if(t&&t[ir]){this._rules=this._rules.concat(t._rules._rules),this._added=!0;return}if(rn(t)&&(t={pattern:t}),cc(t.pattern)){let n=dc(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,rr(rn(t)?lc(t):t).forEach(this._add,this),this._added}test(t,n,r){let o=!1,s=!1,i;this._rules.forEach(l=>{let{negative:c}=l;s===c&&o!==s||c&&!o&&!s&&!n||!l[r].test(t)||(o=!c,s=c,i=c?Ga:l)});let a={ignored:o,unignored:s};return i&&(a.rule=i),a}},fc=(e,t)=>{throw new t(e)},We=(e,t,n)=>rn(e)?e?We.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${t}\``,TypeError),cr=e=>Za.test(e);We.isNotRelative=cr;We.convert=e=>e;var oo=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:r=!1}={}){kt(this,ir,!0),this._rules=new no(n),this._strictPathCheck=!r,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(t){return this._rules.add(t)&&this._initCache(),this}addPattern(t){return this.add(t)}_test(t,n,r,o){let s=t&&We.convert(t);return We(s,t,this._strictPathCheck?fc:ar),this._t(s,n,r,o)}checkIgnore(t){if(!Qa.test(t))return this.test(t);let n=t.split(St).filter(Boolean);if(n.pop(),n.length){let r=this._t(n.join(St)+St,this._testCache,!0,n);if(r.ignored)return r}return this._rules.test(t,!1,on)}_t(t,n,r,o){if(t in n)return n[t];if(o||(o=t.split(St).filter(Boolean)),o.pop(),!o.length)return n[t]=this._rules.test(t,r,At);let s=this._t(o.join(St)+St,n,r,o);return n[t]=s.ignored?s:this._rules.test(t,r,At)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return rr(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},ro=e=>new oo(e),uc=e=>We(e&&We.convert(e),e,ar),lr=()=>{let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");We.convert=e;let t=/^[a-z]:\//i;We.isNotRelative=n=>t.test(n)||cr(n)};typeof process<"u"&&process.platform==="win32"&&lr();sn.exports=ro;ro.default=ro;sn.exports.isPathValid=uc;kt(sn.exports,Symbol.for("setupWindows"),lr)});import vr from"node:fs";import Qe from"node:path";import{fileURLToPath as Nc}from"node:url";function je(e){let t=Qe.join(re,"vendor",e);if(bt()&&vr.existsSync(t))return t;for(let n=re;;n=Qe.dirname(n)){let r=Qe.join(n,"node_modules",e);if(vr.existsSync(r))return r;if(Qe.dirname(n)===n)break}return Qe.join(re,"node_modules",e)}var re,bt,Le=wt(()=>{re=Qe.join(Qe.dirname(Nc(globalThis.__canopyUrl("src/utils/pkgPath.js"))),"..","..");bt=()=>re.split(Qe.sep).includes("node_modules")});import Et from"node:fs";import Me from"node:path";import wd from"node:crypto";import{fileURLToPath as Sd}from"node:url";function Bo(e){let t=[];for(let n of Et.readdirSync(e,{withFileTypes:!0}).sort((r,o)=>r.name<o.name?-1:1)){let r=Me.join(e,n.name);n.isDirectory()?t.push(...Bo(r)):/\.(js|scm)$/.test(n.name)&&t.push(r)}return t}function On(){if(Uo)return Uo;let e=wd.createHash("sha256");if(!Et.existsSync(Do)&&globalThis.__canopyBundle){let t=globalThis.__canopyBundle;e.update("bundle\0").update(Et.readFileSync(t));let n=Me.join(Me.dirname(t),"queries");if(Et.existsSync(n))for(let r of Bo(n))e.update(Me.relative(n,r).split(Me.sep).join("/")).update("\0").update(Gi(r)).update("\0")}else for(let t of Bo(Do))e.update(Me.relative(Do,t).split(Me.sep).join("/")).update("\0").update(Gi(t)).update("\0");for(let t of["web-tree-sitter","tree-sitter-javascript","tree-sitter-typescript","tree-sitter-html"])try{e.update(t+"@"+JSON.parse(Et.readFileSync(Me.join(je(t),"package.json"),"utf8")).version)}catch{e.update(t+"@?")}return Uo=e.digest("hex").slice(0,16)}var An,Do,Gi,Uo,zo=wt(()=>{Le();An=1,Do=Me.join(Me.dirname(Sd(globalThis.__canopyUrl("src/history/engineVersion.js"))),"..");Gi=e=>Et.readFileSync(e).toString("utf8").replace(/\r\n/g,`
7
- `),Uo=null});function Pt(e){let t=n=>Array.isArray(n)?n.map(t):n&&typeof n=="object"?Object.fromEntries(Object.keys(n).sort().map(r=>[r,t(n[r])])):n;return JSON.stringify(t(e))}function Ji(e){let t=[],n=[],r=[];for(let[i,a]of e.publicGraph){for(let l of a.nodes)t.push({id:l.id,service:i,kind:l.type,name:l.name,filePath:l.filePath,startLine:l.startLine,endLine:l.endLine,bodyHash:l.bodyHash});for(let l of a.edges)n.push({id:l.id,service:i,from:l.fromNodeId,callKind:l.callKind??l.type,calleeNameRaw:l.calleeNameRaw??l.eventName??l.url??null,resolvedTo:l.targetNodeId??null})}let o=new Map;for(let i of e.publicWorkflows){let a=i.steps[0]?.nodeId??null,l=`${i.serviceId} | ${a} | ${i.name}`,c=(o.get(l)??0)+1;o.set(l,c),r.push({id:c>1?`${l} #${c}`:l,service:i.serviceId,tier:i.tier,tierOrigin:i.tierOrigin,entry:a,steps:i.steps.map(d=>d.nodeId)})}t.sort(Mn(i=>i.service+"\0"+i.id)),n.sort(Mn(i=>i.service+"\0"+i.id)),r.sort(Mn(i=>i.id));let s=e.publicCrossServiceEdges.map(i=>({fromService:i.fromService,fromNodeId:i.fromNodeId,toService:i.toService,toNodeId:i.toNodeId,via:i.via,key:i.key??null,confidence:i.confidence??null})).sort(Mn(i=>[i.fromService,i.fromNodeId,i.toService,i.toNodeId,i.via,i.key].join("\0")));return{schema:1,fingerprint:e.fingerprint,nodes:t,edges:n,workflows:r,crossServiceEdges:s}}var Mn,Hn=wt(()=>{Mn=e=>(t,n)=>{let r=e(t),o=e(n);return r<o?-1:r>o?1:0}});import X from"node:fs";import we from"node:path";import Ki from"node:zlib";import{execFileSync as kd}from"node:child_process";function be(e,t){try{return kd("git",["-C",we.resolve(e),...t],{stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim()}catch{return null}}function Dn(e){let t=be(e,["rev-parse","--git-path","info/exclude"]);if(!t)return!1;let n=we.resolve(e,t);X.mkdirSync(we.dirname(n),{recursive:!0});let r=X.existsSync(n)?X.readFileSync(n,"utf8"):"";return r.split(/\r?\n/).some(o=>o.trim()===".canopy/")||X.appendFileSync(n,(r&&!r.endsWith(`
6
+ var kl=Object.create;var jo=Object.defineProperty;var Nl=Object.getOwnPropertyDescriptor;var bl=Object.getOwnPropertyNames;var _l=Object.getPrototypeOf,$l=Object.prototype.hasOwnProperty;var kt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Il=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},jl=(e,t)=>{for(var n in t)jo(e,n,{get:t[n],enumerable:!0})},Cl=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of bl(t))!$l.call(e,o)&&o!==n&&jo(e,o,{get:()=>t[o],enumerable:!(r=Nl(t,o))||r.enumerable});return e};var Fl=(e,t,n)=>(n=e!=null?kl(_l(e)):{},Cl(t||!e||!e.__esModule?jo(n,"default",{value:e,enumerable:!0}):n,e));var us=Il((Qp,_n)=>{function is(e){return Array.isArray(e)?e:[e]}var El=void 0,Fo="",rs=" ",Co="\\",Pl=/^\s+$/,Ll=/(?:[^\\]|^)\\$/,Tl=/^\\!/,Rl=/^\\#/,Al=/\r?\n/g,Ol=/^\.{0,2}\/|^\.{1,2}$/,Ml=/\/$/,Ot="/",as="node-ignore";typeof Symbol<"u"&&(as=Symbol.for("node-ignore"));var cs=as,Mt=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),Hl=/([0-z])-([0-z])/g,ls=()=>!1,Dl=e=>e.replace(Hl,(t,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?t:Fo),Bl=e=>e.startsWith("!")||e.startsWith("\\^")?`^${e.slice(e[0]==="!"?1:2)}`:e,Ul=e=>{let{length:t}=e;return e.slice(0,t-t%2)},zl=[[/^\uFEFF/,()=>Fo],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?rs:Fo)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+rs}],[/[\\$.|*+(){^]/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,()=>Co],[/\\\\/g,()=>Co],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,o)=>t===Co?`\\[${n}${Ul(r)}${o}`:o==="]"&&r.length%2===0?`[${Bl(Dl(n))}${r}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],Wl=/(^|\\\/)?\\\*$/,tn="regex",Nn="checkRegex",ss="_",Gl={[tn](e,t){return`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Nn](e,t){return`${t?`${t}[^/]*`:"[^/]*"}(?=$|\\/$)`}},ql=e=>zl.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),bn=e=>typeof e=="string",Jl=e=>e&&bn(e)&&!Pl.test(e)&&!Ll.test(e)&&e.indexOf("#")!==0,Vl=e=>e.split(Al).filter(Boolean),Eo=class{constructor(t,n,r,o,s,i){this.pattern=t,this.mark=n,this.negative=s,Mt(this,"body",r),Mt(this,"ignoreCase",o),Mt(this,"regexPrefix",i)}get regex(){let t=ss+tn;return this[t]?this[t]:this._make(tn,t)}get checkRegex(){let t=ss+Nn;return this[t]?this[t]:this._make(Nn,t)}_make(t,n){let r=this.regexPrefix.replace(Wl,Gl[t]),o=this.ignoreCase?new RegExp(r,"i"):new RegExp(r);return Mt(this,n,o)}},Yl=({pattern:e,mark:t},n)=>{let r=!1,o=e;o.indexOf("!")===0&&(r=!0,o=o.substr(1)),o=o.replace(Tl,"!").replace(Rl,"#");let s=ql(o);return new Eo(e,t,o,n,r,s)},Po=class{constructor(t){this._ignoreCase=t,this._rules=[]}_add(t){if(t&&t[cs]){this._rules=this._rules.concat(t._rules._rules),this._added=!0;return}if(bn(t)&&(t={pattern:t}),Jl(t.pattern)){let n=Yl(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,is(bn(t)?Vl(t):t).forEach(this._add,this),this._added}test(t,n,r){let o=!1,s=!1,i;this._rules.forEach(c=>{let{negative:l}=c;s===l&&o!==s||l&&!o&&!s&&!n||!c[r].test(t)||(o=!l,s=l,i=l?El:c)});let a={ignored:o,unignored:s};return i&&(a.rule=i),a}},Kl=(e,t)=>{throw new t(e)},Ze=(e,t,n)=>bn(e)?e?Ze.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${t}\``,TypeError),ds=e=>Ol.test(e);Ze.isNotRelative=ds;Ze.convert=e=>e;var Lo=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:r=!1}={}){Mt(this,cs,!0),this._rules=new Po(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&&Ze.convert(t);return Ze(s,t,this._strictPathCheck?Kl:ls),this._t(s,n,r,o)}checkIgnore(t){if(!Ml.test(t))return this.test(t);let n=t.split(Ot).filter(Boolean);if(n.pop(),n.length){let r=this._t(n.join(Ot)+Ot,this._testCache,!0,n);if(r.ignored)return r}return this._rules.test(t,!1,Nn)}_t(t,n,r,o){if(t in n)return n[t];if(o||(o=t.split(Ot).filter(Boolean)),o.pop(),!o.length)return n[t]=this._rules.test(t,r,tn);let s=this._t(o.join(Ot)+Ot,n,r,o);return n[t]=s.ignored?s:this._rules.test(t,r,tn)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return is(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},To=e=>new Lo(e),Xl=e=>Ze(e&&Ze.convert(e),e,ls),fs=()=>{let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");Ze.convert=e;let t=/^[a-z]:\//i;Ze.isNotRelative=n=>t.test(n)||ds(n)};typeof process<"u"&&process.platform==="win32"&&fs();_n.exports=To;To.default=To;_n.exports.isPathValid=Xl;Mt(_n.exports,Symbol.for("setupWindows"),fs)});import Ss from"node:fs";import ft from"node:path";import{fileURLToPath as cd}from"node:url";function He(e){let t=ft.join(le,"vendor",e);if(Dt()&&Ss.existsSync(t))return t;for(let n=le;;n=ft.dirname(n)){let r=ft.join(n,"node_modules",e);if(Ss.existsSync(r))return r;if(ft.dirname(n)===n)break}return ft.join(le,"node_modules",e)}var le,Dt,We=kt(()=>{le=ft.join(ft.dirname(cd(globalThis.__canopyUrl("src/utils/pkgPath.js"))),"..","..");Dt=()=>le.split(ft.sep).includes("node_modules")});import Jt from"node:fs";import Ye from"node:path";import cu from"node:crypto";import{fileURLToPath as lu}from"node:url";function xr(e){let t=[];for(let n of Jt.readdirSync(e,{withFileTypes:!0}).sort((r,o)=>r.name<o.name?-1:1)){let r=Ye.join(e,n.name);n.isDirectory()?t.push(...xr(r)):/\.(js|scm)$/.test(n.name)&&t.push(r)}return t}function Vt(){if(vr)return vr;let e=cu.createHash("sha256");if(!Jt.existsSync(yr)&&globalThis.__canopyBundle){let t=globalThis.__canopyBundle;e.update("bundle\0").update(Jt.readFileSync(t));let n=Ye.join(Ye.dirname(t),"queries");if(Jt.existsSync(n))for(let r of xr(n))e.update(Ye.relative(n,r).split(Ye.sep).join("/")).update("\0").update(Qa(r)).update("\0")}else for(let t of xr(yr))e.update(Ye.relative(yr,t).split(Ye.sep).join("/")).update("\0").update(Qa(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(Jt.readFileSync(Ye.join(He(t),"package.json"),"utf8")).version)}catch{e.update(t+"@?")}return vr=e.digest("hex").slice(0,16)}var no,yr,Qa,vr,wr=kt(()=>{We();no=1,yr=Ye.join(Ye.dirname(lu(globalThis.__canopyUrl("src/history/engineVersion.js"))),"..");Qa=e=>Jt.readFileSync(e).toString("utf8").replace(/\r\n/g,`
7
+ `),vr=null});import Q from"node:fs";import ke from"node:path";import nc from"node:zlib";import du from"node:crypto";import{execFileSync as fu}from"node:child_process";function fe(e,t){try{return fu("git",["-C",ke.resolve(e),...t],{stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim()}catch{return null}}function ro(e){let t=fe(e,["rev-parse","--git-path","info/exclude"]);if(!t)return!1;let n=ke.resolve(e,t);Q.mkdirSync(ke.dirname(n),{recursive:!0});let r=Q.existsSync(n)?Q.readFileSync(n,"utf8"):"";return r.split(/\r?\n/).some(o=>o.trim()===".canopy/")||Q.appendFileSync(n,(r&&!r.endsWith(`
8
8
  `)?`
9
9
  `:"")+`.canopy/
10
- `),!0}function He(e){let t=se(e);try{return JSON.parse(X.readFileSync(t.index,"utf8"))}catch{return{schema:1,nextVersion:1,versions:[]}}}function Fd(e,t){let n=se(e);X.mkdirSync(n.history,{recursive:!0});let r=n.index+"."+process.pid+".tmp";X.writeFileSync(r,JSON.stringify(t,null,2)),X.renameSync(r,n.index)}function Lt(e,t){let n=X.readFileSync(we.join(se(e).history,t.file));return JSON.parse((t.gzip?Ki.gunzipSync(n):n).toString("utf8"))}function Vi(e,t,n,r,o=Wt,{refresh:s=!1}={}){let i=se(e);X.mkdirSync(i.history,{recursive:!0});let a=He(e),l=!0,c=n.fingerprint+(l?".json.gz":".json"),d=we.join(i.history,c);(s||!X.existsSync(d))&&X.writeFileSync(d,l?Ki.gzipSync(t):t);let p=(be(e,["status","--porcelain"])||"").split(`
11
- `).some(w=>w.trim()&&!/\.canopy(\/|$)/.test(w)),f=s?a.versions.pop():null,u={version:f?f.version:a.nextVersion,fingerprint:n.fingerprint,createdAt:new Date().toISOString(),headSha:be(e,["rev-parse","HEAD"]),headMessage:be(e,["log","-1","--format=%s"]),dirty:p,counts:r,file:c,gzip:l,bytes:X.statSync(d).size,engineVersion:On(),outputFormat:An};for(a.versions.push(u),f||a.nextVersion++;a.versions.length>o;)a.versions.shift();let m=_d(),h=w=>{try{return X.statSync(we.join(i.history,w.file)).size}catch{return w.bytes??0}},v=a.versions.reduce((w,S)=>w+h(S),0);for(;v>m&&a.versions.length>bd;)v-=h(a.versions.shift());let g=new Set(a.versions.map(w=>w.file));for(let w of X.readdirSync(i.history))/\.json(\.gz)?$/.test(w)&&w!=="index.json"&&!g.has(w)&&X.rmSync(we.join(i.history,w),{force:!0});return Fd(e,a),u}function Yi(e){let t=se(e);X.mkdirSync(t.root,{recursive:!0});for(let n=0;n<2;n++)try{let r=X.openSync(t.lock,"wx");return X.writeSync(r,JSON.stringify({pid:process.pid,startedAt:Date.now()})),X.closeSync(r),!0}catch(r){if(r.code!=="EEXIST")throw r;let o=1/0;try{o=Date.now()-X.statSync(t.lock).mtimeMs}catch{continue}if(o<$d)return!1;X.rmSync(t.lock,{force:!0})}return!1}var Nd,bd,_d,$d,Wt,se,Xi,Zi,Qi,pt=wt(()=>{zo();Nd=200,bd=2,_d=()=>{let e=Number(process.env.CANOPY_SNAPSHOT_MAX_MB);return(Number.isFinite(e)&&e>0?e:Nd)*1024*1024},$d=600*1e3,Wt=50,se=e=>{let t=we.join(we.resolve(e),".canopy");return{root:t,history:we.join(t,"history"),index:we.join(t,"history","index.json"),lock:we.join(t,"sync.lock"),pending:we.join(t,"sync.pending"),log:we.join(t,"sync.log")}};Xi=e=>X.rmSync(se(e).lock,{force:!0}),Zi=e=>{let t=se(e);X.mkdirSync(t.root,{recursive:!0}),X.writeFileSync(t.pending,String(Date.now()))},Qi=e=>{let t=se(e);return X.existsSync(t.pending)?(X.rmSync(t.pending,{force:!0}),!0):!1}});function ea(e){let t=new Map;for(let n of e.nodes){let r=t.get(n.id);r?r.services.push(n.service):t.set(n.id,{id:n.id,services:[n.service],kind:n.kind,name:n.name,filePath:n.filePath,bodyHash:n.bodyHash})}for(let n of t.values())n.services.sort();return t}function jd(e){return t=>{if(t==null)return t;if(e.has(t))return e.get(t);for(let[n,r]of e)if(t.startsWith(n+" | "))return r+t.slice(n.length);return t}}function qo(e,t){let n=a=>a.reduce((l,c)=>l.set(c,(l.get(c)??0)+1),new Map),r=n(e),o=n(t),s=[],i=[];for(let[a,l]of o)for(let c=0;c<l-(r.get(a)??0);c++)s.push(a);for(let[a,l]of r)for(let c=0;c<l-(o.get(a)??0);c++)i.push(a);return{added:s.sort(),removed:i.sort()}}function Un(e,t){let n=ea(e),r=ea(t),o=[...r.values()].filter(_=>!n.has(_.id)),s=[...n.values()].filter(_=>!r.has(_.id)),i=[];for(let[_,C]of r){let M=n.get(_);M&&M.bodyHash!==C.bodyHash&&i.push({...Wo(C),from:M.bodyHash,to:C.bodyHash})}let a=[],l=new Map,c=_=>[_.kind,_.name,_.bodyHash].join("\0"),d=new Map;for(let _ of Se(o,C=>C.id)){let C=c(_);d.has(C)||d.set(C,[]),d.get(C).push(_)}let p=[],f=new Set;for(let _ of Se(s,C=>C.id)){let M=(d.get(c(_))??[]).find(ie=>!f.has(ie.id)&&ie.filePath!==_.filePath&&ie.id.split("::").pop()===_.id.split("::").pop());M?(f.add(M.id),a.push({kind:_.kind,name:_.name,services:M.services,fromId:_.id,toId:M.id,fromPath:_.filePath,toPath:M.filePath}),l.set(_.id,M.id)):p.push(_)}o=Se(o.filter(_=>!f.has(_.id)),_=>_.id),s=Se(p,_=>_.id);let u=jd(l),m=_=>_.service+"\0"+_.id,h=new Map(e.edges.map(_=>[m({service:_.service,id:u(_.id)}),{..._,id:u(_.id),from:u(_.from),resolvedTo:u(_.resolvedTo)}])),v=new Map(t.edges.map(_=>[m(_),_])),g=_=>({id:_.id,service:_.service,from:_.from,callKind:_.callKind,calleeNameRaw:_.calleeNameRaw,resolvedTo:_.resolvedTo}),w=[],S=[],N=[];for(let[_,C]of v){let M=h.get(_);M?M.resolvedTo!==C.resolvedTo&&N.push({id:C.id,service:C.service,from:C.from,calleeNameRaw:C.calleeNameRaw,fromTarget:M.resolvedTo,toTarget:C.resolvedTo}):w.push(g(C))}for(let[_,C]of h)v.has(_)||S.push(g(C));let y=_=>_.service+"\0"+_.id,x=_=>({..._,id:_.id.replace(_.entry??"\0",u(_.entry)),entry:u(_.entry),steps:_.steps.map(u)}),b=new Map(e.workflows.map(_=>{let C=x(_);return[C.id,C]})),k=new Map(t.workflows.map(_=>[_.id,_])),$={added:[],removed:[],changed:[]},j={added:[],removed:[],changed:[]},D=_=>({id:_.id,service:_.service,tier:_.tier,steps:_.steps.length});for(let[_,C]of k){let M=b.get(_);if(!M){(C.tier==="physical"?$:j).added.push(D(C));continue}let ie=qo(M.steps,C.steps),ze=!ie.added.length&&!ie.removed.length&&M.steps.join(`
12
- `)!==C.steps.join(`
13
- `),F=M.tier!==C.tier?`${M.tier} -> ${C.tier}`:null;if(!ie.added.length&&!ie.removed.length&&!ze&&!F)continue;let P={id:_,service:C.service,tier:C.tier,stepsAdded:ie.added,stepsRemoved:ie.removed,reordered:ze,tierChange:F};(M.tier==="physical"||C.tier==="physical"?$:j).changed.push(P)}for(let[_,C]of b)k.has(_)||(C.tier==="physical"?$:j).removed.push(D(C));for(let _ of[$,j])for(let C of["added","removed","changed"])_[C]=Se(_[C],M=>M.id);let L=_=>[_.fromService,_.fromNodeId,_.toService,_.toNodeId,_.via,_.key].join(" | "),K=new Map(e.crossServiceEdges.map(_=>[L({..._,fromNodeId:u(_.fromNodeId),toNodeId:u(_.toNodeId)}),{..._,fromNodeId:u(_.fromNodeId),toNodeId:u(_.toNodeId)}])),z=new Map(t.crossServiceEdges.map(_=>[L(_),_])),O=Se([...z].filter(([_])=>!K.has(_)).map(([,_])=>_),L),W=Se([...K].filter(([_])=>!z.has(_)).map(([,_])=>_),L),G=new Map,te=new Map,ge=(_,C,M)=>{_.has(C)||_.set(C,new Set),_.get(C).add(M)};for(let _ of s)ge(G,_.id,"removed");for(let _ of o)ge(te,_.id,"added");for(let _ of i)ge(G,_.id,"modified"),ge(te,_.id,"modified");for(let _ of a)ge(G,_.fromId,"moved"),ge(te,_.toId,"moved");let rt=[],Be=new Set([...b.keys(),...k.keys()]);for(let _ of Be){let C=b.get(_),M=k.get(_);if(!(C&&C.tier==="physical"||M&&M.tier==="physical"))continue;let ie=new Map;for(let[F,P]of[[C,G],[M,te]])if(F)for(let R of new Set(F.steps))for(let I of P.get(Qt(R,F===C,l))??[])ie.set(R+"\0"+I,{node:R,why:I});let ze=C&&M&&(qo(C.steps,M.steps).added.length||qo(C.steps,M.steps).removed.length);ie.size&&rt.push({workflow:_,service:(M??C).service,status:C?M?"changed":"removed":"new",stepsChanged:!!ze,reasons:Se([...ie.values()],F=>F.node+"\0"+F.why)})}function Qt(_,C,M){if(!C)return _;for(let[ie,ze]of M)if(ze===_)return ie;return _}let Rt={schema:1,from:e.fingerprint,to:t.fingerprint,nodes:{added:o.map(Wo),removed:s.map(Wo),modified:Se(i,_=>_.id),moved:Se(a,_=>_.toId)},edges:{added:Se(w,y),removed:Se(S,y),retargeted:Se(N,y)},workflows:{physical:$,guessed:j},crossServiceEdges:{added:O,removed:W},touched:Se(rt,_=>_.workflow)};return Rt.counts={nodes:{added:o.length,removed:s.length,modified:i.length,moved:a.length},edges:{added:w.length,removed:S.length,retargeted:N.length},physicalWorkflows:{added:$.added.length,removed:$.removed.length,changed:$.changed.length},guessedWorkflows:{added:j.added.length,removed:j.removed.length,changed:j.changed.length},crossServiceEdges:{added:O.length,removed:W.length},touched:rt.length,touchedNew:rt.filter(_=>_.status==="new").length},Rt}function na(e,t,n,{limit:r=40}={}){let o=e.counts,s=t?`v${t.version} (${(t.headSha??t.fingerprint).slice(0,7)}${t.headMessage?` ${JSON.stringify(t.headMessage)}`:""})`:"to",i=[];i.push(`${s} \u2190 ${n?"v"+n.version:"from"}: nodes +${o.nodes.added} \u2212${o.nodes.removed} ~${o.nodes.modified} \u21A6${o.nodes.moved} | edges +${o.edges.added} \u2212${o.edges.removed}${o.edges.retargeted?` ~${o.edges.retargeted}`:""} | physical workflows touched: ${o.touched} (${o.touchedNew} new)`);let a=(c,d,p)=>{if(d.length){i.push("",`${c} (${d.length})`);for(let f of d.slice(0,r))i.push(" "+p(f));d.length>r&&i.push(` ... ${d.length-r} more`)}};a("Touched physical workflows",e.touched,c=>`[${c.service}] ${c.workflow.split(" | ").slice(2).join(" | ")} <${c.status}> because: ${c.reasons.slice(0,4).map(d=>`${d.why} ${mt(d.node)}`).join(", ")}${c.reasons.length>4?`, +${c.reasons.length-4}`:""}`),a("Nodes added",e.nodes.added,c=>`+ ${c.id}`),a("Nodes removed",e.nodes.removed,c=>`- ${c.id}`),a("Nodes modified",e.nodes.modified,c=>`~ ${c.id}`),a("Nodes moved",e.nodes.moved,c=>`\u21A6 ${c.name}: ${c.fromPath} \u2192 ${c.toPath}`),a("Edges added",e.edges.added,c=>`+ [${c.service}] ${mt(c.from)} \u2192 ${c.calleeNameRaw}${c.resolvedTo?` (resolved to ${mt(c.resolvedTo)})`:""}`),a("Edges removed",e.edges.removed,c=>`- [${c.service}] ${mt(c.from)} \u2192 ${c.calleeNameRaw}`),a("Edges retargeted",e.edges.retargeted,c=>`~ [${c.service}] ${mt(c.from)} \u2192 ${c.calleeNameRaw}: ${mt(c.fromTarget)||"unresolved"} \u2192 ${mt(c.toTarget)||"unresolved"}`),a("Physical workflows changed",e.workflows.physical.changed,c=>`~ ${c.id.split(" | ").slice(2).join(" | ")} +${c.stepsAdded.length} \u2212${c.stepsRemoved.length} steps${c.tierChange?`, tier ${c.tierChange}`:""}${c.reordered?", reordered":""}`),a("Physical workflows added",e.workflows.physical.added,c=>`+ ${c.id.split(" | ").slice(2).join(" | ")} (${c.steps} steps)`),a("Physical workflows removed",e.workflows.physical.removed,c=>`- ${c.id.split(" | ").slice(2).join(" | ")}`),a("Cross-service edges added",e.crossServiceEdges.added,c=>`+ ${c.fromService} \u2192 ${c.toService} via ${c.via} ${c.key??""}`),a("Cross-service edges removed",e.crossServiceEdges.removed,c=>`- ${c.fromService} \u2192 ${c.toService} via ${c.via} ${c.key??""}`);let l=o.guessedWorkflows;return l.added+l.removed+l.changed&&i.push("",`Informational (guessed workflows, never counted as changes): +${l.added} \u2212${l.removed} ~${l.changed}`),i.join(`
14
- `)}var Id,Se,Wo,ta,mt,Go=wt(()=>{Hn();Id=(e,t)=>e<t?-1:e>t?1:0,Se=(e,t)=>e.slice().sort((n,r)=>Id(t(n),t(r)));Wo=e=>({id:e.id,services:e.services,kind:e.kind,name:e.name,filePath:e.filePath});ta=e=>Pt(e),mt=e=>(e??"").split("::").slice(-2).join("::")});var ia={};za(ia,{UI_VERSIONS:()=>ra,buildUiHistory:()=>sa,writeHistoryJs:()=>Pd});import oa from"node:fs";import Cd from"node:path";function Ed(e){let t=JSON.parse(JSON.stringify(e));t.truncated={};let n=(r,o)=>{for(let[s,i]of Object.entries(r))Array.isArray(i)&&i.length>Bn&&(t.truncated[`${o}.${s}`]=i.length,r[s]=i.slice(0,Bn))};return n(t.nodes,"nodes"),n(t.edges,"edges"),n(t.workflows.physical,"workflows.physical"),n(t.crossServiceEdges,"crossServiceEdges"),t.touched.length>Bn&&(t.truncated.touched=t.touched.length,t.touched=t.touched.slice(0,Bn)),t}function sa(e){let n=He(e).versions.slice(-ra),r={};for(let o=1;o<n.length;o++)r[n[o].version]=Ed(Un(Lt(e,n[o-1]),Lt(e,n[o])));return{schema:1,versions:n.map(o=>({version:o.version,fingerprint:o.fingerprint,createdAt:o.createdAt,headSha:o.headSha,headMessage:o.headMessage,dirty:o.dirty,counts:o.counts})),diffs:r}}function Pd(e,t){oa.mkdirSync(t,{recursive:!0}),oa.writeFileSync(Cd.join(t,"history.js"),`const canopyHistory = ${Pt(sa(e))};`)}var ra,Bn,aa=wt(()=>{pt();Go();Hn();ra=20,Bn=200});import Zo from"node:fs";import Yt from"node:path";import nt from"node:fs";import Ld from"node:os";import he from"node:path";import{fileURLToPath as ca}from"node:url";import J from"node:path";import me from"node:fs";import{fileURLToPath as gd,pathToFileURL as yd}from"node:url";var ao=qa(dr(),1);import Nt from"node:fs";import ke from"node:path";var so={javascript:[".js",".jsx",".mjs",".cjs"],typescript:[".ts",".tsx"]},fr=[".ts",".tsx",".mts",".cts"],pc={javascript:["index.js","index.jsx"],typescript:["index.ts","index.tsx"]};function ur(){return Object.values(so).flat()}function pr(){return Object.values(pc).flat()}var mr=["log","logger","console","debug","trace"];var gr=[".yarn",".pnp","vendor","dist","build","out","coverage",".next",".nuxt",".turbo",".cache","bower_components"],co=["node_modules",".git",".canopy",".canopy-cache"],hr=[".vue",".svelte"],mc=1024*1024,io=1e4;function hc(e,t=null){let n=[];function r(o,s){let i=ke.join(o,".gitignore"),a=(0,ao.default)().add(s);Nt.existsSync(i)&&a.add(Nt.readFileSync(i,"utf-8"));let l=Nt.readdirSync(o,{withFileTypes:!0});for(let c of l){let d=ke.join(o,c.name),p=ke.relative(e,d).split(ke.sep).join("/");if(!a.ignores(p)&&!(c.isDirectory()&&co.includes(c.name))){if(c.isDirectory()&&gr.includes(c.name)){t&&t.excludedDirs.push(d);continue}c.isDirectory()?r(d,a):c.isFile()&&n.push(d)}}}return r(e,(0,ao.default)()),n}function gc(e,t,n=null){return e.filter(r=>!(n?ke.relative(n,r):r).split(ke.sep).some(s=>t.includes(s)))}function yr(e,t){let n=0,r;try{r=Nt.readdirSync(e,{withFileTypes:!0})}catch{return 0}for(let o of r)o.isDirectory()?co.includes(o.name)||(n+=yr(ke.join(e,o.name),t)):o.isFile()&&t.has(ke.extname(o.name))&&n++;return n}var yc=e=>/\.d\.(ts|mts|cts)$/.test(e);function xc(e){let t=ke.basename(e);if(/\.min\.js$/.test(t))return{kind:"minified",reason:"minified (*.min.js)"};if(/\.bundle\.js$/.test(t))return{kind:"bundled",reason:"bundled (*.bundle.js)"};let n;try{n=Nt.statSync(e).size}catch{return null}if(n>mc)return{kind:"oversized",reason:`oversized (${(n/1048576).toFixed(1)} MB, limit 1 MB)`};if(n>io){let r=Nt.readFileSync(e,"utf8"),o=0,s=0;for(;;){let i=r.indexOf(`
15
- `,o),a=(i<0?r.length:i)-o;if(a>s&&(s=a),i<0)break;o=i+1}if(s>io)return{kind:"minified",reason:`line of ${s.toLocaleString("en-US")} characters (limit ${io.toLocaleString("en-US")}; minified/bundled)`}}return null}function lo(e,t=["javascript","typescript"]){let n=t.flatMap(p=>(p==="typescript"?fr:so[p])||[]),r={excludedDirs:[]},o=gc(hc(e,r),[...gr,...co],e),s=p=>ke.relative(e,p).split(ke.sep).join("/"),i=[],a=[],l={};for(let p of o){let f=ke.extname(p);if(n.includes(f)){if(yc(p)){a.push({file:s(p),kind:"declaration",reason:"declaration file"});continue}let u=xc(p);u?a.push({file:s(p),kind:u.kind,reason:u.reason}):i.push(p)}else hr.includes(f)&&(l[f]=(l[f]??0)+1)}let c=new Set([...n,...hr]),d={};for(let p of r.excludedDirs){let f=ke.basename(p),u=d[f]??={dirs:0,files:0};u.dirs++,u.files+=yr(p,c)}return{files:i,skipped:a,unsupported:l,excludedDirs:d}}function an(e,t=["javascript","typescript"]){return lo(e,t).files}import vc from"node:path";var at=e=>e.toLocaleString("en-US"),cn=(e,t,n=t+"s")=>`${at(e)} ${e===1?t:n}`,wc={".vue":"Vue",".svelte":"Svelte"},Sc=[".vue",".svelte"],kc=new Set([".ts",".tsx",".mts",".cts"]);function xr({discovered:e,parseResults:t,scopeFiles:n,rel:r,rootService:o=null}){let s=(t.budgetSkips??[]).map(m=>({path:r(m.filePath),kind:"timeout",reason:m.reason})),i=new Set((t.budgetSkips??[]).map(m=>m.filePath)),a=[...e.skipped.map(m=>({path:m.file,kind:m.kind,reason:m.reason})),...s].sort((m,h)=>m.path<h.path?-1:m.path>h.path?1:0),l=e.files.filter(m=>!i.has(m)),c=l.filter(m=>t.get(m)?.hadErrors).map(r).sort(),d=l.flatMap(m=>(t.get(m)?.warnings??[]).map(h=>({path:r(m),extractor:h.extractor,message:h.message}))).sort((m,h)=>m.path<h.path?-1:m.path>h.path?1:0),p=l.filter(m=>kc.has(vc.extname(m))).length,f={};for(let m of Sc)e.unsupported[m]&&(f[m]=e.unsupported[m]);let u={};for(let m of a)u[m.kind]=(u[m.kind]??0)+1;return{analyzed:l.length,analyzedJs:l.length-p,analyzedTs:p,inService:l.filter(m=>n.has(m)).length,notAnalyzed:f,notAnalyzedTotal:Object.values(f).reduce((m,h)=>m+h,0),skipped:a,skippedByKind:u,parseErrors:c.length,parseErrorFiles:c.slice(0,50),parseWarnings:d.length,parseWarningList:d.slice(0,50),excludedDirs:e.excludedDirs,rootService:o}}function ln(e){let t=["Coverage"],n=[],r=new Map;for(let[a,l]of Object.entries(e.notAnalyzed)){let c=wc[a];r.has(c)||r.set(c,[]),r.get(c).push(`${at(l)} ${a}`)}for(let[a,l]of r)n.push(`${l.join(", ")} files (${a} not supported yet)`);if(e.skipped.length){let a=Object.entries(e.skippedByKind).map(([l,c])=>`${l}: ${c}`).join(", ");n.push(`${at(e.skipped.length)} skipped (${a})`)}e.parseErrors&&n.push(`${at(e.parseErrors)} with parse errors`),e.parseWarnings&&n.push(`${at(e.parseWarnings)} extractor warnings (a construct skipped; the rest of its file was analyzed)`);let o=e.analyzedTs?`${cn(e.analyzedJs,"JS file")} and ${cn(e.analyzedTs,"TS file")}`:cn(e.analyzed,"JS file");t.push(` Analyzed ${o}, ${at(e.inService)} of them inside a service${e.analyzed?` (${Math.round(100*e.inService/e.analyzed)}%)`:""}.`),t.push(` Not analyzed: ${n.length?n.join(", "):"nothing"}.`);let s=e.skipped.filter(a=>a.kind!=="declaration");for(let a of s.slice(0,5))t.push(` skipped ${a.path}: ${a.reason}`);s.length>5&&t.push(` ... and ${at(s.length-5)} more (full list: meta.coverage.skipped)`);let i=Object.entries(e.excludedDirs);return i.length&&t.push(` Excluded directories: ${i.map(([a,l])=>`${a}/ x${l.dirs} (${cn(l.files,"source file")})`).join(", ")}.`),e.rootService&&t.push(` Root service: ${e.rootService.reason}.`),t.join(`
16
- `)}Le();import{Parser as fo,Language as wr}from"web-tree-sitter";import dn from"node:path";import{fileURLToPath as bc}from"node:url";var qf=dn.dirname(bc(globalThis.__canopyUrl("src/stage2_parse/initParser.js")));var uo=new WeakMap,Ot=e=>uo.get(e)??"javascript",et=e=>Ot(e)!=="javascript";function po(e){let t=dn.extname(e);return t===".tsx"?"tsx":t===".ts"||t===".mts"||t===".cts"?"typescript":"javascript"}var _c={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm"};async function Sr(e,t){for(let n of new Set(t.map(po))){if(e.grammars.has(n))continue;let r=dn.join(je("tree-sitter-typescript"),_c[n]),o=await wr.load(r);uo.set(o,n);let s=new fo;s.setLanguage(o),e.grammars.set(n,{parser:s,language:o})}return e}async function kr(){await fo.init();let e=new fo,t=dn.join(je("tree-sitter-javascript"),"tree-sitter-javascript.wasm"),n=await wr.load(t);return e.setLanguage(n),uo.set(n,"javascript"),{parser:e,language:n,grammars:new Map([["javascript",{parser:e,language:n}]])}}import $c from"node:fs";function $r(e,t){let n=$c.readFileSync(t,"utf-8"),r=e.parse(n);if(mo(r)||n.includes("\0")){let o=n,s=_r(r);for(let i of Fc){let a=i.apply(o);if(a===o)continue;let l=e.parse(a),c=_r(l);(c<s||i.always)&&(o=a,r=l,s=c)}o!==n&&(r.canopyOriginalSource=n)}return{tree:r,source:n,filePath:t}}var Fr=e=>e.replace(/[^\n]/g," "),Nr=e=>"any"+Fr(e).slice(3),br=/(?<![&])&(?![&=])/g,Fc=[{name:"NUL byte",always:!0,apply:e=>e.replace(/\0/g," ")},{name:"export type * from",apply:e=>e.replace(/\bexport\s+type\s+\*\s*(?:as\s+[\w$]+\s+)?from\s*(["'])[^"'\n]*\1\s*;?/g,Fr)},{name:"typeof import()",apply:e=>e.replace(/typeof\s+import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)*/g,Nr)},{name:"import().Type",apply:e=>e.replace(/(?<=[:<,|&?]\s*|\breadonly\s+|\bkeyof\s+|\bextends\s+|\bas\s+)import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)+(?!\s*\()/g,Nr)},{name:"generic call signature after a member",apply:e=>e.replace(/(?<=\n[ \t]*)[ ](?=<\s*[A-Za-z_$][\w$]*\s*(?:extends\b|=|,|>\s*\())/g,";")},{name:"& in JSX text",apply:e=>e.replace(/>[^<>{}"'`]*&[^<>{}"'`]*</g,t=>t.replace(br,"+"))},{name:"& in JSX attribute",apply:e=>e.replace(/(\s[\w:-]+=)"([^"\n]*)"/g,(t,n,r)=>n+'"'+r.replace(br,"+")+'"')}];function _r(e){let t=0;return(function n(r){if(r.type==="ERROR"){t++;return}for(let o=0;o<r.childCount;o++)n(r.child(o))})(e.rootNode),t}function mo(e){let t=!1;function n(r){if(r.type==="ERROR"){t=!0;return}for(let o=0;o<r.childCount;o++)n(r.child(o))}return n(e.rootNode),t}import ho from"node:fs";import Mt from"node:path";import{fileURLToPath as Ic}from"node:url";import{Query as jc}from"web-tree-sitter";var Ir=Mt.dirname(Ic(globalThis.__canopyUrl("src/utils/loadQuery.js"))),jr=new WeakMap;function ee(e,t){let n=jr.get(e);if(n||jr.set(e,n=new Map),n.has(t))return n.get(t);let r=Mt.join(Ir,"..","stage2_parse","queries"),o=ho.existsSync(r)?r:Mt.join(Ir,"..","..","dist","queries"),s=Ot(e),l=(s==="javascript"?[]:s==="tsx"?["tsx","typescript"]:[s]).map(p=>Mt.join(o,p,t)).find(p=>ho.existsSync(p))??Mt.join(o,t),c=ho.readFileSync(l,"utf-8"),d=new jc(e,c);return n.set(t,d),d}var Cr="javascript",Er=e=>{Cr=e};var fn=()=>Cr!=="javascript";var Cc=new Set(["non_null_expression","as_expression","satisfies_expression","type_assertion"]);function ce(e){for(;e;)if(Cc.has(e.type))e=e.type==="type_assertion"?e.namedChild(e.namedChildCount-1):e.namedChild(0);else if(e.type==="parenthesized_expression"&&e.namedChildCount===1){let t=ce(e.namedChild(0));if(t===e.namedChild(0))break;e=t}else break;return e}function Ec(e){let t=e;for(;t;){t=ce(t);for(let n=0;n<t.childCount;n++)if(t.child(n).type==="optional_chain")return!0;if(t.type==="member_expression"||t.type==="subscript_expression")t=t.childForFieldName("object");else if(t.type==="call_expression")t=t.childForFieldName("function");else break}return!1}function tt(e){let t=e.childForFieldName("function"),n=e.childForFieldName("arguments");if(!t)return{kind:"callOfCall",oldShape:!1,nameNode:e};let r=t.type==="identifier",o=t.type==="member_expression"?t.childForFieldName("property"):null,s=t.type==="member_expression"?ce(t.childForFieldName("object")):null,i=r||s?.type==="identifier"&&o?.type==="property_identifier",a=o??t;if(fn()&&e.parent?.type==="decorator")return{kind:"decorator",oldShape:i,nameNode:a};if(n&&n.type==="template_string")return{kind:"taggedTemplate",oldShape:i,nameNode:a};if(Ec(e))return{kind:"optionalCall",oldShape:i,nameNode:a};if(r)return{kind:"call",oldShape:i,nameNode:a};if(t.type==="subscript_expression")return{kind:"computed",oldShape:!1,nameNode:t};if(t.type==="member_expression")return s.type==="super"?{kind:"super",oldShape:!1,nameNode:a}:s.type==="this"?{kind:"thisCall",oldShape:!1,nameNode:a}:i?{kind:"methodCall",oldShape:!0,nameNode:a}:{kind:"chainedCall",oldShape:!1,nameNode:a};if(t.type==="import")return{kind:"dynamicImport",oldShape:!1,nameNode:t};if(t.type==="super")return{kind:"super",oldShape:!1,nameNode:t};let l=t;for(;l.type==="parenthesized_expression"&&l.namedChildCount===1;)l=l.namedChild(0);return l.type==="arrow_function"||l.type==="function_expression"||l.type==="function"||l.type==="generator_function"?{kind:"iife",oldShape:!1,nameNode:t}:{kind:"callOfCall",oldShape:!1,nameNode:t}}function Pr(e){let t=e.childForFieldName("name");return t?t.type==="identifier"?/^[A-Z]/.test(t.text)?{kind:"jsx",oldShape:!0,nameNode:t}:null:t.type==="member_expression"||t.type==="nested_identifier"?{kind:"jsxMember",oldShape:!1,nameNode:t}:null:null}function un(e){let t=e;for(;t&&t.type!=="call_expression";)t=t.parent;return t}function Lr(e){let t=e.childForFieldName("function"),n=!1;for(;t;)if(t=ce(t),t.type==="member_expression"||t.type==="subscript_expression")t=t.childForFieldName("object");else if(t.type==="call_expression")n=!0,t=t.childForFieldName("function");else if(t.type==="await_expression"||t.type==="parenthesized_expression"||t.type==="non_null_expression")t=t.namedChild(0);else break;return t&&t.type==="identifier"?{head:t.text,called:n}:{head:null,called:!1}}function Rr(e){let t=e.text.replace(/\s+/g," ");return t.length>120?t.slice(0,117)+"...":t}function Ar(e,t){let o=ee(t,"functionDeclarations.scm").matches(e.rootNode).map(s=>{let i=s.captures.find(c=>c.name==="func_name"),a=s.captures.find(c=>c.name==="func_params"),l=s.captures.find(c=>c.name==="func_declaration");return{name:i.node.text,params:a.node.text,startLine:l.node.startPosition.row+1,endLine:l.node.endPosition.row+1,startIndex:l.node.startIndex,endIndex:l.node.endIndex,node:i.node}});return et(t)&&o.push(...Pc(e,t)),o}function Pc(e,t){return ee(t,"defaultExports.scm").matches(e.rootNode).map(n=>{let r=n.captures.find(s=>s.name==="func_declaration").node;return{name:"default",params:n.captures.find(s=>s.name==="func_params").node.text,startLine:r.startPosition.row+1,endLine:r.endPosition.row+1,startIndex:r.startIndex,endIndex:r.endIndex,node:r}})}function Or(e,t){return ee(t,"arrowFunctions.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(l=>l.name==="func_name"),i=o.captures.find(l=>l.name==="func_params"),a=o.captures.find(l=>l.name==="func_declaration");return{name:s.node.text,params:i.node.text,startLine:a.node.startPosition.row+1,endLine:a.node.endPosition.row+1,startIndex:a.node.startIndex,endIndex:a.node.endIndex,node:s.node}})}function Mr(e,t){let r=ee(t,"classMethods.scm").matches(e.rootNode),o=et(t);return r.map(s=>{let i=s.captures.find(p=>p.name==="class_name"),a=s.captures.find(p=>p.name==="method_name"),l=s.captures.find(p=>p.name==="method_params"),c=s.captures.find(p=>p.name==="method_declaration"),d=c.node;if(o)for(let p=d.previousNamedSibling;p&&p.type==="decorator";p=p.previousNamedSibling)d=p;return{className:i?i.node.text:"default",methodName:a.node.text,params:l.node.text,startLine:d.startPosition.row+1,endLine:c.node.endPosition.row+1,startIndex:d.startIndex,endIndex:c.node.endIndex,node:a.node}})}function Hr(e,t){let r=ee(t,"imports.scm").matches(e.rootNode),o=et(t);return r.filter(s=>!(o&&Lc(s.captures[0].node))).map(s=>{let i=s.captures[0].node;return{source:i.text,startLine:i.startPosition.row+1}})}function Lc(e){let t=e;for(;t&&t.type!=="import_statement";)t=t.parent;if(!t)return!1;if(t.children.some(s=>s.type==="type"))return!0;let n=t.namedChildren.find(s=>s.type==="import_clause");if(!n)return!1;let r=n.namedChildren;if(r.length!==1||r[0].type!=="named_imports")return!1;let o=r[0].namedChildren.filter(s=>s.type==="import_specifier");return o.length>0&&o.every(s=>s.children.some(i=>i.type==="type"))}function Ht(e){let t=e;for(;t&&t.type!=="call_expression"&&t.type!=="new_expression";)t=t.parent;if(!t)return null;let n=t.childForFieldName("arguments");if(!n)return null;let r=n.namedChildren?.[0];return!r||r.type==="arrow_function"||r.type==="function_expression"?null:r.text}var Rc=/^(addEventListener|removeEventListener|on|once|postMessage|onmessage|subscribe)$/i;function _t(e){let t=e;for(;t.parent;){let n=t.parent;if(n.type==="arrow_function"||n.type==="function_expression"){let r=n.parent;if(r&&(r.type==="variable_declarator"||r.type==="public_field_definition"))break;if(r&&r.type==="return_statement")return!0;if(r&&r.type==="arguments"&&r.parent?.type==="call_expression"){let o=r.parent.childForFieldName("function"),s=o?.type==="member_expression"?o.childForFieldName("property")?.text:o?.text;if(s&&Rc.test(s))return!0}}else if(n.type==="function_declaration"||n.type==="method_definition")break;t=n}return!1}function Dr(e,t){return ee(t,"callExpressions.scm").matches(e.rootNode).map(o=>{let s=o.captures[0].node;return{calleeName:s.text,startLine:s.startPosition.row+1,startColumn:s.startPosition.column,branchPath:$t(s),firstArgText:Ht(s),deferred:_t(s),callKind:tt(un(s)).kind}})}function Ur(e,t){return et(t)?Tc(e):ee(t,"methodCalls.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(a=>a.name==="object_name"),i=o.captures.find(a=>a.name==="method_name");return{objectName:s.node.text,methodName:i.node.text,startLine:i.node.startPosition.row+1,startColumn:i.node.startPosition.column,firstArgText:Ht(i.node),branchPath:$t(i.node),deferred:_t(i.node),callKind:tt(un(i.node)).kind}})}function Tc(e){let t=[];for(let n of e.rootNode.descendantsOfType("call_expression")){let r=n.childForFieldName("function");if(!r||r.type!=="member_expression")continue;let o=ce(r.childForFieldName("object")),s=r.childForFieldName("property");!o||o.type!=="identifier"||!s||s.type!=="property_identifier"||t.push({objectName:o.text,methodName:s.text,startLine:s.startPosition.row+1,startColumn:s.startPosition.column,firstArgText:Ht(s),branchPath:$t(s),deferred:_t(s),callKind:tt(un(s)).kind})}return t}function Ac(e){if(!e)return"return";if(e.type==="object"){let t=e.namedChildren.filter(r=>r.type==="pair"),n=t.find(r=>r.childForFieldName("key")?.text?.replace(/^['"]|['"]$/g,"")==="type")??t.find(r=>r.childForFieldName("key")?.text?.replace(/^['"]|['"]$/g,"")==="entity");if(n){let r=n.childForFieldName("key"),o=n.childForFieldName("value");return`return { ${r.text}: ${o.text} }`}}return"return "+e.text.split(/\r?\n/)[0].trim()}function Br(e,t){return ee(t,"returns.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(l=>l.name==="return_statement"),i=o.captures.find(l=>l.name==="return_value"),a=s.node;return{label:Ac(i?.node),startLine:a.startPosition.row+1,startColumn:a.startPosition.column,branchPath:$t(a),deferred:_t(a)}})}var Oc=new Set(["function_declaration","arrow_function","function_expression","method_definition"]);function pn(e,t){return!(!t||e.row<t.startPosition.row||e.row>t.endPosition.row||e.row===t.startPosition.row&&e.column<t.startPosition.column||e.row===t.endPosition.row&&e.column>t.endPosition.column)}function $t(e){let t=[],n=e,r=e.startPosition;for(;n.parent;){let o=n.parent;if(Oc.has(o.type))break;if(o.type==="if_statement"){let s=o.childForFieldName("condition"),i=o.childForFieldName("consequence"),a=o.childForFieldName("alternative");pn(r,i)?t.push({type:"if",conditionText:s?s.text:"",conditionLine:(s??o).startPosition.row+1,outcome:"true"}):pn(r,a)&&t.push({type:"if",conditionText:s?s.text:"",conditionLine:(s??o).startPosition.row+1,outcome:"false"})}else if(o.type==="switch_case"||o.type==="switch_default"){let s=o.parent,i=s&&s.type==="switch_body"?s.parent:null;if(i){let a=i.childForFieldName("value"),l=o.childForFieldName("value");t.push({type:"switch",conditionText:a?a.text:"",conditionLine:(a??i).startPosition.row+1,outcome:o.type==="switch_default"?"default":l?l.text:"case"})}}else if(o.type==="try_statement"){let s=o.childForFieldName("handler"),i=o.childForFieldName("finalizer"),a="try";pn(r,s)?a="catch":pn(r,i)&&(a="finally"),t.push({type:"try",conditionText:"try / catch",conditionLine:o.startPosition.row+1,outcome:a})}n=o}return t.reverse()}function zr(e,t){return ee(t,"exports.scm").matches(e.rootNode).map(r=>r.captures[0].node.text)}var Tr=new WeakMap;function Mc(e,t){let n=Tr.get(e);return n||(n=ee(t,"returns.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(a=>a.name==="return_statement"),i=o.captures.find(a=>a.name==="return_value");return{stmtNode:s.node,valueNode:i?.node}}),Tr.set(e,n)),n}function Wr(e,t,n){return Mc(e,t).filter(r=>r.stmtNode.startPosition.row+1>=n.startLine&&r.stmtNode.endPosition.row+1<=n.endLine).map(r=>({shape:Hc(r.valueNode),condition:Dc(r.stmtNode,n),line:r.stmtNode.startPosition.row+1}))}function Hc(e){if(!e)return"nothing";switch(e.type){case"true":case"false":return"boolean";case"number":return"number";case"string":return"string";case"null":return"null";case"identifier":return`variable (${e.text})`;case"object":return"object";case"array":return"array";case"call_expression":return`result of ${e.text.split("(")[0]}()`;case"binary_expression":return"boolean (comparison)";case"ternary_expression":return"conditional value";default:return"expression"}}function Dc(e,t){let n=e.parent;for(;n;){if(n.type==="if_statement"){let r=n.childForFieldName("condition");if(r)return r.text}n=n.parent}return null}function qr(e,t){return Ot(t)==="typescript"?[]:ee(t,"jsxElements.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(i=>i.name==="jsx_tag");return{calleeName:s.node.text,startLine:s.node.startPosition.row+1}}).filter(o=>/^[A-Z]/.test(o.calleeName))}function Gr(e,t){return ee(t,"fetchApiCalls.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(c=>c.name==="url"),i=o.captures.find(c=>c.name==="http_method"),a=s.node.text,l=/^https?:\/\//.test(a)?"external":"internal";return{url:a,method:i?.node.text??"get",startLine:s.node.startPosition.row+1,scope:l}})}function Jr(e,t){return ee(t,"socketEmit.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(i=>i.name==="event_name");return{eventName:s.node.text,startLine:s.node.startPosition.row+1}})}function Kr(e,t){return ee(t,"rawSocketSend.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(i=>i.name==="event_name");return{eventName:s.node.text,startLine:s.node.startPosition.row+1}})}function Vr(e,t){return ee(t,"rawSocketTypeCheck.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(i=>i.name==="event_name");return{eventName:s.node.text,startLine:s.node.startPosition.row+1}})}function Yr(e,t){return ee(t,"socketOn.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(l=>l.name==="event_name"),i=o.captures.find(l=>l.name==="handler_ref"),a=o.captures.find(l=>l.name==="handler_inline");return{eventName:s.node.text,startLine:s.node.startPosition.row+1,handlerName:i?i.node.text:null,isInlineHandler:!!a,handlerStartLine:a?a.node.startPosition.row+1:null,handlerEndLine:a?a.node.endPosition.row+1:null,handlerStartIndex:a?a.node.startIndex:null,handlerEndIndex:a?a.node.endIndex:null}})}function Xr(e){let t=e.rootNode.descendantsOfType(["call_expression","new_expression","jsx_opening_element","jsx_self_closing_element",...fn()?["decorator"]:[]]),n=[];for(let r of t){let o,s,i,a=null,l=null,c=!1,d=null,p=null;if(r.type==="new_expression"){if(i=r.childForFieldName("constructor"),!i)continue;o="new",s=i,a=i.type==="identifier"?i.text:null;let u=r.childForFieldName("arguments")?.namedChildren?.[0];d=u&&u.type!=="arrow_function"&&u.type!=="function_expression"?u.text:null}else if(r.type==="decorator"){let f=r.namedChild(0);if(!f||f.type==="call_expression")continue;o="decorator",s=f.type==="member_expression"?f.childForFieldName("property")??f:f,i=f}else if(r.type==="call_expression"){let f=tt(r);if(f.oldShape)continue;if(o=f.kind,s=f.nameNode,i=r.childForFieldName("function")??r,o==="chainedCall"){let u=Lr(r);l=u.head,c=u.called;let m=r.childForFieldName("function"),h=m?.type==="member_expression"?ce(m.childForFieldName("object")):null;h?.type==="member_expression"&&ce(h.childForFieldName("object"))?.type==="this"&&h.childForFieldName("property")?.type==="property_identifier"&&m.childForFieldName("property")&&(p={thisProp:h.childForFieldName("property").text,thisMethod:m.childForFieldName("property").text})}d=Ht(s)}else{let f=Pr(r);if(!f||f.oldShape)continue;o=f.kind,s=f.nameNode,i=f.nameNode}n.push({callKind:o,calleeName:Rr(i),startLine:s.startPosition.row+1,startColumn:s.startPosition.column,branchPath:$t(s),firstArgText:d,deferred:_t(s),chainHead:l,chainHeadCalled:c,ctorName:a,...p??{}})}return n.sort((r,o)=>r.startLine-o.startLine||r.startColumn-o.startColumn)}var go=new Set(["get","post","put","patch","delete","head","options"]),yo=new Set(["axios","ky","got","superagent","$http"]),Uc=new Set(["function_declaration","function_expression","function","arrow_function","method_definition","generator_function_declaration","generator_function"]),Bc=new Set(["WebSocket","ReconnectingWebSocket","SockJS","W3CWebSocket"]),xo=/^(ws|socket|sock|websocket|webSocket|wsClient|socketRef|wsRef|[A-Za-z]+Socket|[A-Za-z]+Ws|[A-Za-z]+WebSocket)$/,Z=e=>{for(;e&&(e.type==="parenthesized_expression"||e.type==="as_expression"||e.type==="non_null_expression"||e.type==="await_expression"||e.type==="satisfies_expression"||e.type==="type_assertion")&&(e=e.namedChildren.find(t=>t.type!=="type_annotation"&&t.type!=="predefined_type"&&!/_type$/.test(t.type))??e.namedChildren[0],!!e););return e},Dt=e=>e.namedChildren.length?e.namedChildren.filter(t=>t.type==="string_fragment"||t.type==="escape_sequence").map(t=>t.text).join(""):e.text.slice(1,-1);function Ft(e){for(let t=e.parent;t;t=t.parent)if(Uc.has(t.type))return t;return null}function Zr(e){if(!e)return null;let t=e.childForFieldName("name")?.text??null;if(!t&&e.parent){let o=e.parent;o.type==="variable_declarator"?t=o.childForFieldName("name")?.text??null:o.type==="assignment_expression"?t=o.childForFieldName("left")?.text??null:o.type==="pair"&&(t=o.childForFieldName("key")?.text??null)}let n=[],r=e.childForFieldName("parameters");if(r)r.namedChildren.forEach((o,s)=>{let i=o.type==="identifier"?o:o.type==="assignment_pattern"?o.childForFieldName("left"):o.type==="required_parameter"||o.type==="optional_parameter"?o.childForFieldName("pattern")??o.namedChildren[0]:null;n[s]=i&&i.type==="identifier"?i.text:null});else{let o=e.childForFieldName("parameter");o&&o.type==="identifier"&&(n[0]=o.text)}return{name:t,params:n}}function Qr(e){let t=e.rootNode,n={httpCalls:[],pathCallsites:[],httpInstances:[],wsClients:[],wsServers:[],wsSends:[],wsServerSends:[],listens:[],wsReceivers:[]},r=new Map;for(let u of t.descendantsOfType("variable_declarator")){let m=u.childForFieldName("name"),h=u.childForFieldName("value");if(!m||m.type!=="identifier"||!h)continue;(r.get(m.text)??r.set(m.text,[]).get(m.text)).push({value:h,fn:Ft(u)})}let o=(u,m)=>{let h=r.get(u);if(!h)return null;for(let g=Ft(m);g;g=Ft(g)){let w=h.filter(S=>S.fn&&S.fn.id===g.id);if(w.length===1)return w[0].value}let v=h.filter(g=>!g.fn);return v.length===1?v[0].value:h.length===1?h[0].value:null},s=(u,m)=>{for(let h=Ft(m);h;h=Ft(h)){let g=Zr(h).params.indexOf(u);if(g>=0)return g}return-1};function i(u,m=0){if(u=Z(u),!u)return[{t:"ref",name:""}];switch(u.type){case"string":return[{t:"lit",v:Dt(u)}];case"template_string":{let h=[];for(let v of u.namedChildren)v.type==="string_fragment"||v.type==="escape_sequence"?h.push({t:"lit",v:v.text}):v.type==="template_substitution"&&h.push(...i(v.namedChildren[0],m+1));return h.length?h:[{t:"lit",v:""}]}case"number":return[{t:"lit",v:u.text}];case"binary_expression":{let h=u.childForFieldName("operator")?.text;if(h==="||"||h==="??"){let v=i(u.childForFieldName("left"),m+1);if(v.length===1&&v[0].t==="env")return[{...v[0],fallback:i(u.childForFieldName("right"),m+1)}]}return h!=="+"?[{t:"ref",name:u.text.slice(0,60)}]:[...i(u.childForFieldName("left"),m+1),...i(u.childForFieldName("right"),m+1)]}case"shorthand_property_identifier":case"identifier":{let h=u.text,v=s(h,u);if(v>=0)return[{t:"param",name:h,index:v}];if(m<4){let g=o(h,u);if(g&&g.id!==u.id)return i(g,m+1)}return[{t:"ref",name:h}]}case"member_expression":{let h=u.text,v=/^(?:process\.env|import\.meta\.env)\.([A-Za-z0-9_$]+)$/.exec(h)??/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(h);return v?[{t:"env",name:v[1]}]:[{t:"ref",name:h.slice(0,60)}]}case"subscript_expression":{let h=/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(u.text);return h?[{t:"env",name:h[1]}]:[{t:"ref",name:u.text.slice(0,60)}]}case"call_expression":{let h=u.childForFieldName("function")?.text,v=u.childForFieldName("arguments")?.namedChildren[0];if(v&&(h==="encodeURIComponent"||h==="String"||h==="encodeURI"))return i(v,m+1);let g=Z(u.childForFieldName("function"));if(g&&g.type==="member_expression"&&/^(replace|replaceAll|trim|trimEnd|trimStart|toString|toLowerCase)$/.test(g.childForFieldName("property")?.text??"")){let w=g.childForFieldName("object");if(w){let S=i(w,m+1);if(S.length&&S.every(N=>N.t!=="ref"))return S}}return[{t:"ref",name:u.text.slice(0,60)}]}default:return[{t:"ref",name:u.text.slice(0,60)}]}}let a=(u,m)=>{if(u=Z(u),!(!u||u.type!=="object")){for(let h of u.namedChildren)if(h.type==="pair"){let v=h.childForFieldName("key");if((v?v.type==="string"?Dt(v):v.text:null)===m)return h.childForFieldName("value")}else if(h.type==="shorthand_property_identifier"&&h.text===m)return h}},l=u=>u.childForFieldName("arguments")?.namedChildren.filter(m=>m.type!=="comment")??[],c=u=>{if(!u)return null;let m=i(u);return m.length===1&&m[0].t==="lit"?m[0].v.toUpperCase():m.length===1&&m[0].t==="param"?{param:m[0].index}:"?"},d=(u,m,h,v)=>({client:u,method:m,parts:h,line:v.startPosition.row+1,fn:Zr(Ft(v))});for(let u of t.descendantsOfType("variable_declarator")){let m=u.childForFieldName("name"),h=Z(u.childForFieldName("value"));if(!m||m.type!=="identifier"||!h||h.type!=="call_expression")continue;let v=Z(h.childForFieldName("function"));if(!v||v.type!=="member_expression")continue;let g=v.childForFieldName("object")?.text,w=v.childForFieldName("property")?.text;if(!(yo.has(g)&&(w==="create"||w==="extend")))continue;let S=l(h)[0],N=a(S,"baseURL")??a(S,"baseUrl")??a(S,"prefixUrl")??a(S,"prefix_url");n.httpInstances.push({name:m.text,parts:N?i(N):[],line:u.startPosition.row+1})}let p=new Set(n.httpInstances.map(u=>u.name));for(let u of t.descendantsOfType("call_expression")){let m=Z(u.childForFieldName("function"));if(!m)continue;let h=l(u),v=!1;if(m.type==="identifier"){let g=m.text;if(g==="fetch"&&h[0]){let w=Z(h[0]);if(w&&w.type==="new_expression")continue;let S=a(h[1],"method");n.httpCalls.push(d("fetch",S?c(S):h[1]&&Z(h[1])?.type!=="object"?"?":"GET",i(h[0]),u)),v=!0}else if((yo.has(g)||p.has(g))&&h[0]){let w=Z(h[0]);if(w&&w.type==="object"){let S=a(w,"url");if(S){let N=a(w,"baseURL");n.httpCalls.push(d(p.has(g)?"inst:"+g:g,c(a(w,"method"))??"GET",[...N?i(N):[],...i(S)],u)),v=!0}}else n.httpCalls.push(d(p.has(g)?"inst:"+g:g,h[1]&&a(h[1],"method")?c(a(h[1],"method")):"GET",i(h[0]),u)),v=!0}else g==="io"&&h[0]&&(n.wsClients.push({client:"io",parts:i(h[0]),line:u.startPosition.row+1}),v=!0)}else if(m.type==="member_expression"){let w=m.childForFieldName("object")?.text??"",S=m.childForFieldName("property")?.text??"",N=yo.has(w)||p.has(w);if(N&&go.has(S)&&h[0])n.httpCalls.push(d(p.has(w)?"inst:"+w:w,S.toUpperCase(),i(h[0]),u)),v=!0;else if(!N&&go.has(S)&&/^[A-Za-z_$][\w$]*$/.test(w)&&h[0]&&(Z(h[0])?.type==="string"||Z(h[0])?.type==="template_string")){let y=i(h[0]);y[0]?.t==="lit"&&(y[0].v.startsWith("/")||/^https?:\/\//.test(y[0].v))&&(n.httpCalls.push(d("obj:"+w,S.toUpperCase(),y,u)),v=!0)}else if(N&&S==="request"&&h[0]){let y=a(h[0],"url");if(y){let x=a(h[0],"baseURL");n.httpCalls.push(d(p.has(w)?"inst:"+w:w,c(a(h[0],"method"))??"GET",[...x?i(x):[],...i(y)],u)),v=!0}}else if(S==="open"&&h.length>=2&&Z(h[0])?.type==="string"&&/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/i.test(Dt(Z(h[0]))))n.httpCalls.push(d("xhr",Dt(Z(h[0])).toUpperCase(),i(h[1]),u)),v=!0;else if(w==="io"&&S==="connect"&&h[0])n.wsClients.push({client:"io",parts:i(h[0]),line:u.startPosition.row+1}),v=!0;else if(S==="listen"&&h[0]){let y=Z(h[0]),x=y&&y.type==="object"?a(y,"port"):y;x&&n.listens.push({parts:i(x),line:u.startPosition.row+1}),v=!0}else if(S==="send"&&/^(client|conn|connection|peer)$/.test(w.replace(/^this./,"").split(".").pop())&&h[0]){let y=Z(h[0]),x=!1;if(y&&y.type==="call_expression"&&y.childForFieldName("function")?.text==="JSON.stringify"){let b=l(y)[0];x=!!(b&&(a(b,"type")||a(b,"event"))&&Z(a(b,"type")??a(b,"event"))?.type==="string")}x||n.wsServerSends.push({recv:w,line:u.startPosition.row+1}),v=!0}else if(S==="send"&&xo.test(w.replace(/^this\./,"").replace(/\.current$/,"").split(".").pop())){let y=h[0]?Z(h[0]):null,x=!1;if(y&&y.type==="call_expression"&&y.childForFieldName("function")?.text==="JSON.stringify"){let b=l(y)[0];x=!!(b&&(a(b,"type")||a(b,"event"))&&Z(a(b,"type")??a(b,"event"))?.type==="string")}x||n.wsSends.push({recv:w,line:u.startPosition.row+1}),v=!0}}if(!v){let g=null;if(m.type==="identifier"?g=m.text:m.type==="member_expression"&&(g=m.childForFieldName("property")?.text??null),!g||go.has(g)||h.length===0||h.length>6)continue;let w=[],S=!1;h.slice(0,5).forEach((N,y)=>{let x=Z(N);if(!x||x.type!=="string"&&x.type!=="template_string")return;let b=i(x);w.push({i:y,parts:b});let k=b[0];k&&k.t==="lit"&&(k.v.startsWith("/")||/^https?:\/\//.test(k.v))&&k.v.length>1&&(S=!0)}),S&&n.pathCallsites.push({callee:g,args:w,line:u.startPosition.row+1})}}let f=u=>u.replace(/^this./,"").replace(/.current$/,"").split(".").pop();for(let u of t.descendantsOfType("assignment_expression")){let m=u.childForFieldName("left");if(!m||m.type!=="member_expression"||m.childForFieldName("property")?.text!=="onmessage"||!xo.test(f(m.childForFieldName("object")?.text??"")))continue;let h=Z(u.childForFieldName("right"));n.wsReceivers.push({line:u.startPosition.row+1,handlerName:h&&h.type==="identifier"?h.text:null})}for(let u of t.descendantsOfType("call_expression")){let m=Z(u.childForFieldName("function"));if(!m||m.type!=="member_expression"||m.childForFieldName("property")?.text!=="addEventListener")continue;let h=l(u),v=h[0]&&Z(h[0]);if(!v||v.type!=="string"||Dt(v)!=="message"||!xo.test(f(m.childForFieldName("object")?.text??"")))continue;let g=h[1]&&Z(h[1]);n.wsReceivers.push({line:u.startPosition.row+1,handlerName:g&&g.type==="identifier"?g.text:null})}for(let u of t.descendantsOfType("new_expression")){let m=Z(u.childForFieldName("constructor"));if(!m)continue;let h=m.text,v=l(u);if(Bc.has(h)&&v[0])n.wsClients.push({client:h,parts:i(v[0]),line:u.startPosition.row+1});else if(/^(WebSocketServer|WebSocket\.Server|WebSocket\.WebSocketServer|ws\.Server|ws\.WebSocketServer|Server)$/.test(h)){if(h==="Server"&&!/socket\.io|socketio/i.test(e.rootNode.text.slice(0,4e3)+""))continue;let g=a(v.find(w=>Z(w)?.type==="object"),"path");n.wsServers.push({path:g?i(g):null,line:u.startPosition.row+1})}}return n}var zc=new Set(["function_declaration","generator_function_declaration","function_expression","generator_function","arrow_function","method_definition"]),Wc=new Set(["arrow_function","function_expression","generator_function"]);function qe(e,t){if(e)switch(e.type){case"identifier":case"shorthand_property_identifier_pattern":t.push(e.text);return;case"assignment_pattern":qe(e.childForFieldName("left"),t);return;case"rest_pattern":case"object_pattern":case"array_pattern":case"pair_pattern":case"required_parameter":case"optional_parameter":for(let n of e.namedChildren)qe(e.type==="pair_pattern"?e.childForFieldName("value"):n,t);return;default:if(e.type==="pattern"||e.namedChildCount){let n=e.childForFieldName?.("pattern");n&&qe(n,t)}}}function qc(e,t){let n=e;if(n.type==="export_statement"&&(n=n.childForFieldName("declaration")),!n)return null;if(n.type==="function_declaration"||n.type==="generator_function_declaration")return n.childForFieldName("name")?.text===t?{kind:"fn",declLine:n.startPosition.row+1}:null;if(n.type==="lexical_declaration"||n.type==="variable_declaration"){for(let r of n.namedChildren){if(r.type!=="variable_declarator")continue;let o=r.childForFieldName("name");if(o?.type==="identifier"){if(o.text!==t)continue;let i=ce(r.childForFieldName("value"));return i&&Wc.has(i.type)?{kind:"fn",declLine:r.startPosition.row+1}:{kind:"other"}}let s=[];if(qe(o,s),s.includes(t))return{kind:"other"}}return null}return(n.type==="class_declaration"||n.type==="abstract_class_declaration"||n.type==="enum_declaration")&&n.childForFieldName("name")?.text===t?{kind:"other"}:null}function Gc(e){let t=e.namedChildren.find(o=>o.type==="string")?.text.slice(1,-1)??null,n=e.namedChildren.find(o=>o.type==="import_clause"),r=[];if(!n||t==null)return{src:t,out:r};for(let o of n.namedChildren)if(o.type==="identifier")r.push({kind:"default",local:o.text,imported:null});else if(o.type==="namespace_import"){let s=o.namedChildren.find(i=>i.type==="identifier");s&&r.push({kind:"ns",local:s.text,imported:null})}else if(o.type==="named_imports")for(let s of o.namedChildren){if(s.type!=="import_specifier")continue;let i=s.childForFieldName("name"),a=s.childForFieldName("alias");i&&r.push({kind:"named",local:(a??i).text,imported:i.text})}return{src:t,out:r}}function es(e){let t=[];for(let n of e.rootNode.namedChildren)if(n.type==="import_statement"){if(n.children.some(i=>i.type==="type"))continue;let r=n.namedChildren.find(i=>i.type==="import_require_clause");if(r){let i=r.namedChildren.find(l=>l.type==="identifier"),a=r.namedChildren.find(l=>l.type==="string");i&&a&&t.push({source:Ut(a),kind:"cjs",local:i.text,imported:null});continue}let{src:o,out:s}=Gc(n);for(let i of s)t.push({source:o,...i})}else if(n.type==="lexical_declaration"||n.type==="variable_declaration")for(let r of n.namedChildren){if(r.type!=="variable_declarator")continue;let o=ce(r.childForFieldName("value")),s=null;o?.type==="member_expression"&&(s=o.childForFieldName("property")?.text??null,o=ce(o.childForFieldName("object")));let i=mn(o);if(i==null)continue;let a=r.childForFieldName("name");if(a?.type==="identifier")t.push({source:i,kind:s?"named":"cjs",local:a.text,imported:s});else if(a?.type==="object_pattern"&&!s){for(let l of a.namedChildren)if(l.type==="shorthand_property_identifier_pattern")t.push({source:i,kind:"named",local:l.text,imported:l.text});else if(l.type==="pair_pattern"){let c=l.childForFieldName("key"),d=l.childForFieldName("value");c&&d?.type==="identifier"&&t.push({source:i,kind:"named",local:d.text,imported:c.text})}}}return t}var Ut=e=>e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("");function mn(e){if(e?.type!=="call_expression")return null;let t=e.childForFieldName("function"),n=e.childForFieldName("arguments");if(t?.type!=="identifier"||t.text!=="require"||!n||n.namedChildCount!==1)return null;let r=n.namedChildren[0];return r.type==="string"?Ut(r):null}function ts(e){let t=[];return(function n(r){if(r.type==="export_statement"){let o=r.childForFieldName("source");o&&!r.children.some(s=>s.type==="type")&&t.push({source:Ut(o),startLine:o.startPosition.row+1})}else if(r.type==="import_require_clause"){let o=r.namedChildren.find(s=>s.type==="string");o&&t.push({source:Ut(o),startLine:o.startPosition.row+1})}else if(r.type==="call_expression"){let o=mn(r);o!=null&&t.push({source:o,startLine:r.startPosition.row+1})}for(let o of r.namedChildren)n(o)})(e.rootNode),t}function ns(e){let t={default:null,named:{},reexports:[],stars:[],nsReexports:[]};for(let n of e.rootNode.namedChildren){if(n.type!=="export_statement")continue;let r=n.children.some(i=>i.type==="default"),o=n.childForFieldName("declaration"),s=n.childForFieldName("source")!=null;if(r){if(o){let i=o.childForFieldName("name");t.default=i&&(o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"||o.type==="abstract_class_declaration")?i.text:"<anon>"}else{let i=ce(n.childForFieldName("value"));t.default=i?.type==="identifier"?i.text:"<anon>"}continue}if(o){if(o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"||o.type==="abstract_class_declaration"){let i=o.childForFieldName("name")?.text;i&&(t.named[i]=i)}else if(o.type==="lexical_declaration"||o.type==="variable_declaration")for(let i of o.namedChildren){let a=i.type==="variable_declarator"?i.childForFieldName("name"):null;a?.type==="identifier"&&(t.named[a.text]=a.text)}continue}if(s){if(n.children.some(c=>c.type==="type"))continue;let i=Ut(n.childForFieldName("source")),a=n.namedChildren.find(c=>c.type==="export_clause"),l=n.namedChildren.find(c=>c.type==="namespace_export");if(a)for(let c of a.namedChildren){if(c.type!=="export_specifier")continue;let d=c.childForFieldName("name")?.text,p=c.childForFieldName("alias")?.text;d&&t.reexports.push({exported:p??d,imported:d,source:i})}else if(l){let c=l.namedChildren.find(d=>d.type==="identifier");c&&t.nsReexports.push({exported:c.text,source:i})}else t.stars.push(i);continue}for(let i of n.namedChildren)if(i.type==="export_clause")for(let a of i.namedChildren){if(a.type!=="export_specifier")continue;let l=a.childForFieldName("name")?.text,c=a.childForFieldName("alias")?.text;l&&(c==="default"?t.default=l:t.named[c??l]=l)}}for(let n of e.rootNode.namedChildren){let r=n.type==="expression_statement"?n.namedChildren[0]:null;if(r?.type!=="assignment_expression")continue;let o=r.childForFieldName("left"),s=ce(r.childForFieldName("right"));if(o?.type!=="member_expression")continue;let i=o.childForFieldName("object"),a=o.childForFieldName("property")?.text,l=c=>c?.type==="member_expression"&&c.childForFieldName("object")?.text==="module"&&c.childForFieldName("property")?.text==="exports";if(l(o))if(s?.type==="identifier")t.default=s.text;else if(s?.type==="object"){for(let c of s.namedChildren)if(c.type==="shorthand_property_identifier")t.named[c.text]=c.text;else if(c.type==="pair"){let d=c.childForFieldName("key"),p=ce(c.childForFieldName("value"));d&&p?.type==="identifier"&&(t.named[d.text.replace(/^['"]|['"]$/g,"")]=p.text)}t.default??="<object>"}else mn(s)!=null?t.stars.push(mn(s)):t.default="<anon>";else a&&(i?.type==="identifier"&&i.text==="exports"||l(i))&&s?.type==="identifier"&&(t.named[a]=s.text)}return t}function Jc(e,t,n){for(let r=e.parent;r;r=r.parent)if(zc.has(r.type)){let o=[],s=r.childForFieldName("parameters");if(s)for(let a of s.namedChildren)qe(a,o);let i=r.childForFieldName("parameter");if(i&&qe(i,o),r.type==="function_expression"||r.type==="generator_function"){let a=r.childForFieldName("name");a&&o.push(a.text)}if(o.includes(t))return{kind:"other"}}else if(r.type==="catch_clause"){let o=[];if(qe(r.childForFieldName("parameter"),o),o.includes(t))return{kind:"other"}}else if(r.type==="for_in_statement"||r.type==="for_statement"){let o=[],s=r.type==="for_statement"?r.childForFieldName("initializer"):r.childForFieldName("left");if(s)if(s.type==="lexical_declaration"||s.type==="variable_declaration")for(let i of s.namedChildren)qe(i.childForFieldName?.("name"),o);else qe(s,o);if(o.includes(t))return{kind:"other"}}else if(r.type==="statement_block"||r.type==="program"||r.type==="switch_body"){if(r.type==="program"&&n.has(t))return{kind:"import",imp:n.get(t)};for(let o of r.namedChildren){let s=qc(o,t);if(s)return s}if(r.type==="program"&&n.has(t))return{kind:"import",imp:n.get(t)}}return null}var Kc=e=>(e.childForFieldName("function")?.text??"").replace(/\s+/g," ").slice(0,40);function os(e,t){let n=new Map(t.map(s=>[s.local,s])),r=[],o=(s,i,a)=>{let l=ce(s);if(!l||l.type!=="identifier"&&l.type!=="shorthand_property_identifier")return;let c=l.text,d=Jc(l,c,n);if(!d||d.kind==="other")return;let p=tt(a).nameNode,f={name:c,line:l.startPosition.row+1,column:l.startPosition.column,via:i,callee:Kc(a),callLine:p.startPosition.row+1,callColumn:p.startPosition.column,b:d.kind};d.kind==="fn"?f.declLine=d.declLine:(f.src=d.imp.source,f.ik=d.imp.kind,f.imp=d.imp.imported),r.push(f)};return(function s(i){if(i.type==="call_expression"){let a=i.childForFieldName("arguments");for(let l of a?.namedChildren??[]){let c=ce(l);if(c)if(c.type==="array")for(let d of c.namedChildren)o(d,"array",i);else if(c.type==="object")for(let d of c.namedChildren)d.type==="pair"?o(d.childForFieldName("value"),"object",i):d.type==="shorthand_property_identifier"&&o(d,"object",i);else o(c,"arg",i)}}for(let a of i.namedChildren)s(a)})(e.rootNode),r}function rs(e){let t=[],n=o=>{let s=o?.namedChildren.find(i=>i.type!=="comment");return s?.type==="type_identifier"?s.text:null},r=o=>{let s=o.childForFieldName("name")?.text,i=o.childForFieldName("body");if(!(!s||!i)){for(let a of i.namedChildren)if(a.type==="public_field_definition"){let l=a.childForFieldName("name"),c=n(a.childForFieldName("type"));l?.type==="property_identifier"&&c&&t.push({className:s,prop:l.text,type:c})}else if(a.type==="method_definition"&&a.childForFieldName("name")?.text==="constructor")for(let l of a.childForFieldName("parameters")?.namedChildren??[]){if(l.type!=="required_parameter"&&l.type!=="optional_parameter"||!l.namedChildren.some(p=>p.type==="accessibility_modifier")&&!l.children.some(p=>p.type==="readonly"))continue;let c=l.childForFieldName("pattern"),d=n(l.childForFieldName("type"));c?.type==="identifier"&&d&&t.push({className:s,prop:c.text,type:d})}}};for(let o of e.rootNode.namedChildren){let s=o.type==="export_statement"?o.childForFieldName("declaration"):o;s&&(s.type==="class_declaration"||s.type==="abstract_class_declaration")&&r(s)}return t}var Vc={Get:"get",Post:"post",Put:"put",Patch:"patch",Delete:"delete",All:"all"};function ss(e){let t=e.namedChildren[0];if(!t)return null;if(t.type==="call_expression"){let n=t.childForFieldName("function"),r=n?.type==="identifier"?n.text:null;return r?{name:r,args:t.childForFieldName("arguments")}:null}return t.type==="identifier"?{name:t.text,args:null}:null}var ct=e=>e?e.type==="string"?e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join(""):e.type==="template_string"&&!e.namedChildren.some(t=>t.type==="template_substitution")?e.text.slice(1,-1):null:null;function is(e){let t=e?.namedChildren.find(n=>n.type!=="comment");if(!t)return"";if(t.type==="array")return ct(t.namedChildren.find(n=>n.type!=="comment"))??"";if(t.type==="object"){for(let n of t.namedChildren){if(n.type!=="pair")continue;let r=n.childForFieldName("key");if(r?.text==="path"||r?.text==="'path'"||r?.text==='"path"'){let o=n.childForFieldName("value");return(o?.type==="array"?ct(o.namedChildren[0]):ct(o))??""}}return""}return ct(t)??""}var hn=(...e)=>"/"+e.map(n=>String(n??"").replace(/^\/+|\/+$/g,"")).filter(Boolean).join("/");function as(e){let t=[],n=(r,o)=>{let s=r.childForFieldName("name")?.text,i=r.childForFieldName("body");if(!s||!i)return;let l=[...o,...r.namedChildren.filter(p=>p.type==="decorator")].map(ss).filter(Boolean).find(p=>p.name==="Controller");if(!l)return;let c=is(l.args),d=[];for(let p of i.namedChildren)if(p.type!=="comment"){if(p.type==="decorator"){d.push(p);continue}if(p.type==="method_definition"){let f=p.childForFieldName("name")?.text;for(let u of d.map(ss).filter(Boolean)){let m=Vc[u.name];!m||!f||t.push({method:m,path:hn(c,is(u.args)),startLine:p.startPosition.row+1,handlerName:null,isInlineHandler:!1,handlerStartLine:null,handlerEndLine:null,handlerStartIndex:null,handlerEndIndex:null,nest:{className:s,methodName:f}})}}d=[]}};for(let r of e.rootNode.namedChildren)if(r.type==="export_statement"){let o=r.childForFieldName("declaration");o&&(o.type==="class_declaration"||o.type==="abstract_class_declaration")&&n(o,r.namedChildren.filter(s=>s.type==="decorator"))}else(r.type==="class_declaration"||r.type==="abstract_class_declaration")&&n(r,[]);return t}function cs(e){let t=[];return(function n(r){if(r.type==="call_expression"){let o=r.childForFieldName("function");if(o?.type==="member_expression"&&o.childForFieldName("property")?.text==="setGlobalPrefix"){let s=(r.childForFieldName("arguments")?.namedChildren??[]).filter(c=>c.type!=="comment"),i=s[0]?ct(s[0]):null,a=[],l=s[1];if(l?.type==="object")for(let c of l.namedChildren){if(c.type!=="pair"||c.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")!=="exclude")continue;let d=c.childForFieldName("value");for(let p of d?.type==="array"?d.namedChildren:[])if(p.type==="object"){for(let f of p.namedChildren)if(f.type==="pair"&&f.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")==="path"){let u=ct(f.childForFieldName("value"));u!=null&&a.push(u)}}else{let f=ct(p);f!=null&&a.push(f)}}t.push({prefix:i||null,exclude:a})}}for(let o of r.namedChildren)n(o)})(e.rootNode),t}function ls(e){let t=[];for(let s of e.values())for(let i of s?.globalPrefix??[])t.push(i);if(!t.length||t.some(s=>!s.prefix||s.prefix!==t[0].prefix))return e;let n=t[0].prefix,r=new Set(t.flatMap(s=>s.exclude).map(s=>hn(s))),o=new Map;for(let[s,i]of e){if(!i?.routes?.some(a=>a.nest)){o.set(s,i);continue}o.set(s,{...i,routes:i.routes.map(a=>a.nest&&!r.has(hn(a.path))?{...a,path:hn(n,a.path)}:a)})}return o}import Yc from"node:crypto";var ds=e=>Yc.createHash("sha256").update(e).digest("hex");function Xc(e,t=null){let n=[],r=o=>{if(o.childCount===0){if(o.type==="comment")return;let s=t?t.slice(o.startIndex,o.endIndex):o.text,i=o.type==="jsx_text"?s.replace(/\s+/g," ").trim():s;if(i==="")return;n.push({s:o.startIndex,e:o.endIndex,t:i});return}for(let s=0;s<o.childCount;s++)r(o.child(s))};return r(e),n}function fs(e,t){let n=[];for(let s of[t.functions,t.arrowFunctions,t.classMethods])for(let i of s??[])i.startIndex!=null&&n.push({s:i.startIndex,e:i.endIndex,item:i,field:"bodyHash"});for(let s of[t.routes,t.listeners,t.socketListeners])for(let i of s??[])i.isInlineHandler&&i.handlerStartIndex!=null&&n.push({s:i.handlerStartIndex,e:i.handlerEndIndex,item:i,field:"handlerBodyHash"});let r=new Map(n.map(s=>[s,[]])),o=[];for(let s of Xc(e.rootNode,e.canopyOriginalSource??null)){let i=null,a=1/0;for(let l of n)s.s>=l.s&&s.e<=l.e&&l.e-l.s<a&&(i=l,a=l.e-l.s);(i?r.get(i):o).push(s.t)}for(let s of n)s.item[s.field]=ds(r.get(s).join(" "));t.moduleBodyHash=ds(o.join(" "))}function us(e,t){return ee(t,"matchFastifyRoutes.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(c=>c.name==="http_method"),i=o.captures.find(c=>c.name==="route_path"),a=o.captures.find(c=>c.name==="handler_ref"),l=o.captures.find(c=>c.name==="handler_inline");return{method:s.node.text,path:i.node.text,startLine:s.node.startPosition.row+1,handlerName:a?a.node.text:null,isInlineHandler:!!l,handlerStartLine:l?l.node.startPosition.row+1:null,handlerEndLine:l?l.node.endPosition.row+1:null,handlerStartIndex:l?l.node.startIndex:null,handlerEndIndex:l?l.node.endIndex:null}})}function ps(e,t){return ee(t,"matchExtensionListeners.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(m=>m.name==="event_type"),i=o.captures.find(m=>m.name==="event_name"),a=o.captures.find(m=>m.name==="method_name"||m.name==="listener_method"),l=o.captures.find(m=>m.name==="handler_ref"),c=o.captures.find(m=>m.name==="target"),d=o.captures.find(m=>m.name==="root_object"),p=o.captures.find(m=>m.name==="sub_object"),f=c?c.node.text:d?d.node.text+(p?"."+p.node.text:""):null,u=o.captures.find(m=>m.name==="handler_inline");return{eventName:s?.node.text??i?.node.text??"unknown",targetName:f,startLine:a.node.startPosition.row+1,handlerName:l?l.node.text:null,isInlineHandler:!!u,handlerStartLine:u?u.node.startPosition.row+1:null,handlerEndLine:u?u.node.endPosition.row+1:null,handlerStartIndex:u?u.node.startIndex:null,handlerEndIndex:u?u.node.endIndex:null}})}import nl from"node:fs";Le();import Re from"node:fs";import oe from"node:path";import Zc from"node:os";import hs from"node:crypto";import{fileURLToPath as Qc}from"node:url";var el=oe.dirname(Qc(globalThis.__canopyUrl("src/stage2_parse/parseCache.js"))),gs=oe.join(el,"..",".."),vo=process.env.CANOPY_CACHE_DIR||(bt()?oe.join(Zc.homedir(),".canopy-cache"):oe.join(gs,".canopy-cache")),ms=e=>hs.createHash("sha256").update(e).digest("hex");function gn(e,t){return Re.readdirSync(e,{withFileTypes:!0}).flatMap(n=>n.isDirectory()?gn(oe.join(e,n.name),t):t.some(r=>n.name.endsWith(r))?[oe.join(e,n.name)]:[]).sort()}var wo=null;function tl(){if(wo)return wo;let e=oe.join(gs,"src"),t=!Re.existsSync(e)&&globalThis.__canopyBundle,n=t?[t,...gn(oe.join(oe.dirname(t),"queries"),[".scm"])]:[...gn(oe.join(e,"stage2_parse"),[".js",".scm"]),...gn(oe.join(e,"stage5_entrypoints"),[".js"]).filter(o=>/match/i.test(oe.basename(o))),oe.join(e,"utils","loadQuery.js")],r=hs.createHash("sha256");for(let o of n)r.update(oe.relative(t?oe.dirname(t):e,o).split(oe.sep).join("/")).update("\0").update(Re.readFileSync(o).toString("utf8").replace(/\r\n/g,`
17
- `)).update("\0");for(let o of["web-tree-sitter","tree-sitter-javascript","tree-sitter-typescript"])try{r.update(o+"@"+JSON.parse(Re.readFileSync(oe.join(je(o),"package.json"),"utf8")).version)}catch{r.update(o+"@?")}return wo=r.digest("hex").slice(0,16)}function ys(){let e=tl(),t=oe.join(vo,e);Re.mkdirSync(t,{recursive:!0});for(let n of Re.readdirSync(vo,{withFileTypes:!0}))n.isDirectory()&&n.name!==e&&Re.rmSync(oe.join(vo,n.name),{recursive:!0,force:!0});return{version:e,keyFor:(n,r="javascript")=>ms(r==="javascript"?n:Buffer.concat([Buffer.from(r+"\0"),n])),get(n){try{return JSON.parse(Re.readFileSync(oe.join(t,n+".json"),"utf8"))}catch{return null}},set(n,r){let o=oe.join(t,`${n}.${process.pid}.tmp`);Re.writeFileSync(o,JSON.stringify(r)),Re.renameSync(o,oe.join(t,n+".json"))}}}function xs(e){return JSON.parse(JSON.stringify(e,(t,n)=>n&&typeof n=="object"&&n.startPosition&&n.endPosition&&"type"in n&&"tree"in n?void 0:n))}var vs=Number(process.env.CANOPY_PARSE_BUDGET_MS)||3e4,ko=class extends Error{constructor(t){super(`parse time budget exceeded (limit ${vs/1e3} s; stopped after ${(t/1e3).toFixed(1)} s)`),this.name="ParseBudgetError"}},ol=100;function So(e,t,n){return e.map(r=>({...r,returns:Wr(t,n,r)}))}function ws(e,t,n,{cache:r=!0,onProgress:o=console.log,grammars:s=null}={}){let i=new Map,a=0,l=0,c=0,d=r?ys():null,p=[],f=0;for(let u of e){f>0&&f%ol===0&&o(` parsing: ${f}/${e.length} files (${c} from cache)`),f++;try{let m=nl.readFileSync(u),h=po(u),v=d?.keyFor(m,h),g=d?d.get(v):null;if(g){i.set(u,g),c++;continue}l++;let w=performance.now(),S=()=>{let O=performance.now()-w;if(O>vs)throw new ko(O)},N=h==="javascript"?{parser:t,language:n}:s?.get(h);if(!N)throw new Error(`no ${h} grammar loaded`);let y=N.language;Er(h);let{tree:x}=$r(N.parser,u);S();let b=[],k=(O,W,G=[])=>{try{return W()}catch(te){if(te.name==="ParseBudgetError")throw te;return b.push({extractor:O,message:String(te.message).slice(0,160)}),G}},$=k("functionDeclarations",()=>So(Ar(x,y),x,y));S();let j=k("arrowFunctions",()=>So(Or(x,y),x,y));S();let D=k("classMethods",()=>So(Mr(x,y),x,y));S();let L=k("importBindings",()=>es(x)),K={functions:$,arrowFunctions:j,classMethods:D,imports:k("imports",()=>[...Hr(x,y),...ts(x)]),calls:(S(),k("calls",()=>Dr(x,y))),methodCalls:(S(),k("methodCalls",()=>Ur(x,y))),returnEntries:k("returnEntries",()=>Br(x,y)),jsxElements:k("jsxElements",()=>qr(x,y)),callSites:(S(),k("callSites",()=>Xr(x))),apiCalls:(S(),k("apiCalls",()=>Gr(x,y))),socketEmits:k("socketEmits",()=>Jr(x,y)),socketListeners:k("socketListeners",()=>Yr(x,y)),rawSocketSends:k("rawSocketSends",()=>Kr(x,y)),rawSocketTypeChecks:k("rawSocketTypeChecks",()=>Vr(x,y)),routes:k("routes",()=>[...us(x,y),...et(y)?as(x):[]]),listeners:k("listeners",()=>ps(x,y)),refArgs:k("refArgs",()=>os(x,L)),globalPrefix:k("globalPrefix",()=>cs(x)),importBindings:L,classProps:k("classProps",()=>et(y)?rs(x):[]),httpClients:k("httpClients",()=>Qr(x),null),exportBindings:k("exportBindings",()=>ns(x),null),hadErrors:mo(x),exportedNames:k("exports",()=>zr(x,y)),failed:!1,warnings:b};k("bodyHash",()=>fs(x,K),null);let z=xs(K);d&&d.set(v,z),i.set(u,z)}catch(m){if(m.name==="ParseBudgetError"){p.push({filePath:u,reason:m.message}),i.set(u,{functions:[],arrowFunctions:[],classMethods:[],imports:[],calls:[],methodCalls:[],returnEntries:[],jsxElements:[],callSites:[],apiCalls:[],socketEmits:[],socketListeners:[],rawSocketSends:[],rawSocketTypeChecks:[],routes:[],listeners:[],hadErrors:!1,failed:!1,skipped:m.message}),console.warn(` ! Skipped ${u}: ${m.message}`);continue}a++,i.set(u,{functions:[],arrowFunctions:[],classMethods:[],imports:[],calls:[],methodCalls:[],returnEntries:[],jsxElements:[],callSites:[],apiCalls:[],socketEmits:[],socketListeners:[],rawSocketSends:[],rawSocketTypeChecks:[],routes:[],listeners:[],hadErrors:!0,failed:!0,errorMessage:m.message}),console.warn(` ! Failed to parse ${u}: ${m.message}`)}}return console.log(`Parsed ${i.size} files (${a} failed)`),console.log(` parse cache: ${l} file(s) parsed, ${c} served from cache`),i.cacheStats={parsed:l,cacheHits:c},i.budgetSkips=p,i}function yn(e,t){return`${e}::${t}`}var Ss=[{category:"frontend",patterns:["frontend","client","src/components","ui","src/pages","public"]},{category:"backend",patterns:["backend","server","api","realtime-backend"]},{category:"transport",patterns:["websocket","socket","realtime"]},{category:"data",patterns:["redis","database","models","db"]}];function xn(e){let t=e.toLowerCase().replace(/\\/g,"/");for(let{category:n,patterns:r}of Ss)for(let o of r)if(t.includes(o))return n;return"unknown"}import No from"node:fs";import ye from"node:path";import vn from"node:fs";import Ge from"node:path";var rl=["index.html","public/index.html","src/index.html"],sl=/^(build|esbuild|vite\.config|webpack\.config|rollup\.config|bundle)[\w.-]*\.(mjs|cjs|js|ts)$/i;function il(e){let t=e.replace(/<!--[\s\S]*?-->/g,""),n=[];for(let r of t.matchAll(/<script\b[^>]*?\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)')/gi))n.push(r[1]??r[2]);return n}function al(e){let t=[],n=[];try{n=vn.readdirSync(e).filter(r=>sl.test(r)).sort()}catch{return t}for(let r of n){let o;try{o=vn.readFileSync(Ge.join(e,r),"utf8")}catch{continue}let s=/\boutfile\s*:\s*["'`]([^"'`]+)["'`]/.exec(o)?.[1]??null,i=/\b(?:entryPoints|entry|input)\s*:\s*\[?\s*["'`]([^"'`]+)["'`]/.exec(o)?.[1]??null;i&&t.push({config:r,outfile:s,entry:i})}return t}function wn(e,t,n=new Set(t.map(r=>Ge.resolve(r)))){for(let r of rl){let o=Ge.join(e,r);if(!vn.existsSync(o))continue;let s;try{s=vn.readFileSync(o,"utf8")}catch{continue}let i=Ge.dirname(o),a=d=>{let p=d.split(/[?#]/)[0];return!p||/^([a-z]+:)?\/\//i.test(p)?null:Ge.resolve(p.startsWith("/")?Ge.join(e,p):Ge.join(i,p))},l=il(s).map(d=>({s:d,p:a(d)})).filter(d=>d.p);for(let{s:d,p}of l)if(n.has(p))return{indexHtml:o,script:d,entry:p,via:"script"};let c=al(e);for(let{s:d,p}of l)for(let f of c){if(!f.outfile||Ge.resolve(e,f.outfile)!==p)continue;let u=Ge.resolve(e,f.entry);if(n.has(u))return{indexHtml:o,script:d,entry:u,via:`${f.config} (outfile ${f.outfile})`}}}return null}var cl=new Set(["test","tests","__tests__","fixtures","__fixtures__","__mocks__","e2e","cypress"]);function It(e){let t=String(e).replace(/\\/g,"/").split("/").filter(Boolean);if(!t.length)return!1;for(let n of t.slice(0,-1))if(cl.has(n.toLowerCase()))return!0;return/\.(test|spec)\.[^./]+$/i.test(t[t.length-1])}function ll(e){let t=ye.join(e,"package.json");if(!No.existsSync(t))return null;try{return JSON.parse(No.readFileSync(t,"utf-8"))}catch{return null}}function dl(e){return[...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{})]}function fl(e){let t=!!e.workspaces,n=Object.keys(e.dependencies??{}).length>0,r=!!(e.scripts&&e.scripts.start);return t&&!n&&!r}var ul=["react","vue","svelte","next","vite","webpack","parcel"],pl=["express","fastify","koa","hapi","socket.io","ws"],ml=[{deps:["mongodb","mongoose"],label:"MongoDB"},{deps:["redis","ioredis"],label:"Redis"},{deps:["pg","postgres"],label:"PostgreSQL"},{deps:["mysql","mysql2"],label:"MySQL"},{deps:["sqlite3","better-sqlite3"],label:"SQLite"},{deps:["@prisma/client"],label:"Prisma"},{deps:["drizzle-orm"],label:"Drizzle"}];function hl(e){let t=e.some(r=>ul.includes(r)),n=e.some(r=>pl.includes(r));return t&&!n?"client":n&&!t||n&&t?"server":"unknown"}function gl(e){let t=[];for(let{deps:n,label:r}of ml)n.some(o=>e.includes(o))&&!t.includes(r)&&t.push(r);return t}function ks(e){let t=new Set(["node_modules",".git","dist","build",".next","coverage"]);try{return No.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!t.has(n.name)&&!n.name.startsWith(".")).map(n=>ye.join(e,n.name))}catch{return[]}}function Ns(e,t=null){let n=[e];for(let o of ks(e)){n.push(o);for(let s of ks(o))n.push(s)}let r=[];for(let o of n){let s=ll(o);if(!s||fl(s))continue;let i=dl(s);r.push({name:s.name||ye.basename(o),rootPath:o,isRepoRoot:ye.resolve(o)===ye.resolve(e),kind:hl(i),datastores:gl(i)})}if(t){let o=new Set(t.map(i=>ye.resolve(i))),s=new Set(r.map(i=>ye.resolve(i.rootPath)));for(let i of n)ye.resolve(i)===ye.resolve(e)||s.has(ye.resolve(i))||It(ye.relative(e,i)+"/x")||wn(i,t,o)&&r.push({name:ye.basename(i),rootPath:i,isRepoRoot:!1,kind:"client",datastores:[],webRoot:!0})}return r}function lt(e,t){let n=null,r=-1;for(let o of t)o.isRepoRoot&&t.length>1&&!o.ownsLeftovers||(e===o.rootPath||e.startsWith(o.rootPath+ye.sep))&&o.rootPath.length>r&&(n=o.name,r=o.rootPath.length);return n}var yl=5,xl=.1;function bs(e,t,n){let r=ye.basename(ye.resolve(n)),o=l=>({name:l,rootPath:n,isRepoRoot:!0,ownsLeftovers:!0,kind:"unknown",datastores:[]});if(!t.length)return{services:e,added:null};if(!e.length)return{services:[o(r)],added:{name:r,reason:"no package.json found: the repo root is the one service",leftover:t.length}};let s=t.filter(l=>!lt(l,e)).length;if(s<yl||s<xl*t.length)return{services:e,added:null,leftover:s};let i=e.find(l=>l.isRepoRoot);if(i)return i.ownsLeftovers=!0,{services:e,added:{name:i.name,reason:`${s} of ${t.length} files sit outside every nested package: owned by the root package ${i.name}`,leftover:s}};let a=r;return e.some(l=>l.name.toLowerCase()===a.toLowerCase())&&(a=`${r} (root)`),{services:[...e,o(a)],added:{name:a,reason:`${s} of ${t.length} files sit outside every nested package: owned by a service named after the repo folder`,leftover:s}}}function _s(e,t=[]){let n=[];for(let[r,o]of e){let s=xn(r),i=lt(r,t);n.push({id:`${r}::__module_root__`,name:"module root",filePath:r,startLine:0,endLine:Number.MAX_SAFE_INTEGER,category:s,serviceName:i,type:"moduleRoot",bodyHash:o.moduleBodyHash??null});for(let a of o.functions)n.push({id:yn(r,a.name),name:a.name,filePath:r,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:s,serviceName:i,bodyHash:a.bodyHash??null,type:"function"});for(let a of o.arrowFunctions)n.push({id:yn(r,a.name),name:a.name,filePath:r,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:s,serviceName:i,bodyHash:a.bodyHash??null,type:"arrowFunction"});for(let a of o.classMethods)n.push({id:yn(r,`${a.className}.${a.methodName}`),name:a.methodName,className:a.className,filePath:r,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:s,serviceName:i,bodyHash:a.bodyHash??null,type:"classMethod"})}return n}function Te(e,t){let n=[];for(let s of t.routes??[])s.isInlineHandler&&n.push({item:s,line:s.startLine,key:`route:${String(s.method).toUpperCase()} ${s.path}`});for(let s of t.listeners??[])s.isInlineHandler&&n.push({item:s,line:s.startLine,key:`listener:${s.targetName??"unknown"}.${s.eventName}`});for(let s of t.socketListeners??[])s.isInlineHandler&&n.push({item:s,line:s.startLine,key:`socket:${s.eventName}`});n.sort((s,i)=>s.line-i.line);let r=new Map,o=new Map;for(let{item:s,key:i}of n){let a=(r.get(i)??0)+1;r.set(i,a),o.set(s,`${e}::${i}${a>1?`#${a}`:""}`)}return o}function $s(e,t=[]){let n=[];for(let[r,o]of e){let s=xn(r),i=lt(r,t),a=t.find(c=>c.name===i),l=Te(r,o);for(let c of o.routes??[]){if(!c.isInlineHandler)continue;let d=`${c.method.toUpperCase()} ${c.path}`;n.push({id:l.get(c),name:`${d} (inline handler)`,filePath:r,startLine:c.handlerStartLine??c.startLine,endLine:c.handlerEndLine??c.startLine,category:s,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:c.handlerBodyHash??null,trigger:{type:"route",label:d,resolvedVia:"inline"}})}for(let c of o.listeners??[])c.isInlineHandler&&n.push({id:l.get(c),name:`${c.eventName} (inline handler)`,filePath:r,startLine:c.handlerStartLine??c.startLine,endLine:c.handlerEndLine??c.startLine,category:s,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:c.handlerBodyHash??null,trigger:{type:"listener",label:c.eventName,resolvedVia:"inline"}});if(a?.kind==="server")for(let c of o.socketListeners??[])c.isInlineHandler&&n.push({id:l.get(c),name:`${c.eventName} (inline handler)`,filePath:r,startLine:c.handlerStartLine??c.startLine,endLine:c.handlerEndLine??c.startLine,category:s,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:c.handlerBodyHash??null,trigger:{type:"socketListener",label:c.eventName,resolvedVia:"inline"}})}return n}import vl from"node:fs";import wl from"node:crypto";var Fs=e=>wl.createHash("sha256").update(e).digest("hex");function Sn(e,t){return e.map(n=>[t(n),Fs(vl.readFileSync(n))]).sort((n,r)=>n[0]<r[0]?-1:n[0]>r[0]?1:0)}function kn(e){return Fs(e.map(([t,n])=>`${t}\0${n}`).join(`
18
- `))}import bo from"node:path";function Nn(e){let t=bo.resolve(e),n=t.split(bo.sep).join("/"),r=[[t.toLowerCase(),t.length,bo.sep],[n.toLowerCase(),n.length,"/"]],o=s=>{if(typeof s!="string")return s;let i=s.toLowerCase();if(i===r[0][0]||i===r[1][0])return".";for(let[a,l,c]of r)if(i.startsWith(a+c)){let d=s.slice(l+1),p=d.indexOf("::");return(p<0?d:d.slice(0,p)).split("\\").join("/")+(p<0?"":d.slice(p))}return s};return{rel:o,repoRoot:n,replacer:(s,i)=>typeof i=="string"?o(i):i,json:(s,i)=>JSON.stringify(s,(a,l)=>typeof l=="string"?o(l):l,i),clone:s=>JSON.parse(JSON.stringify(s,(i,a)=>typeof a=="string"?o(a):a))}}function Is(e){let t=e.map((r,o)=>({e:r,i:o})).sort((r,o)=>String(r.e.fromNodeId).localeCompare(String(o.e.fromNodeId))||(r.e.line??0)-(o.e.line??0)||(r.e.column??0)-(o.e.column??0)||r.i-o.i),n=new Map;for(let{e:r}of t){let o=r.calleeNameRaw??r.eventName??r.url??"",s=`${r.fromNodeId??"\u2205"} | ${r.callKind??r.type} | ${o}`,i=(n.get(s)??0)+1;n.set(s,i),r.id=`${s} | #${i}`}return e}function js(e){let t=new Map;for(let n of e)t.has(n.id)||t.set(n.id,[]),t.get(n.id).push(n);for(let[n,r]of t)r.length<2||(r.sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine),r.forEach((o,s)=>{s>0&&(o.id=`${n}#${s+1}`)}));return e}function fe(e,t){let n=null;for(let r of t)r.type!=="moduleRoot"&&e>=r.startLine&&e<=r.endLine&&(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r);return n||t.find(r=>r.type==="moduleRoot")}function Cs(e,t){let n=[];for(let[o,s]of e){let i=t.filter(a=>a.filePath===o);for(let a of s.calls){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"call",callKind:a.callKind??"call",resolved:!1})}for(let a of s.methodCalls){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.methodName,objectNameRaw:a.objectName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"methodCall",callKind:a.callKind??"methodCall",resolved:!1})}for(let a of s.returnEntries??[]){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.label,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],deferred:a.deferred??!1,type:"returnValue",resolved:!1})}for(let a of s.jsxElements){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,type:"call",callKind:"jsx",resolved:!1})}for(let a of s.callSites??[]){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"callSite",callKind:a.callKind,chainHead:a.chainHead??null,chainHeadCalled:a.chainHeadCalled??!1,ctorName:a.ctorName??null,...a.thisProp?{thisProp:a.thisProp,thisMethod:a.thisMethod}:{},resolved:!1})}for(let a of s.socketEmits){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,eventName:a.eventName,line:a.startLine,type:"socketEmit",resolved:!1})}for(let a of s.rawSocketSends??[]){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,eventName:a.eventName,line:a.startLine,type:"rawSocketSend",resolved:!1})}for(let a of s.apiCalls){let l=fe(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,url:a.url,httpMethod:a.method,scope:a.scope,line:a.startLine,type:"apiCall",resolved:!1})}}let r=n.filter(o=>o.type==="apiCall").length;return n}function le(e,t){let n=new Map;for(let r of t)r.filePath===e&&n.set(r.name,r.id);return n}function Bt(e,t,n,r,o=null){if(n.has(e.calleeNameRaw))return{...e,targetNodeId:n.get(e.calleeNameRaw),confidence:.95,matchType:"local",resolved:!0};let s=[...r],i=r.legacySize??s.length,a=([,c])=>{let d=o?o.scopeOf(c):le(c,t);return d.has(e.calleeNameRaw)?{...e,targetNodeId:d.get(e.calleeNameRaw),confidence:.85,matchType:"import",resolved:!0}:null};for(let c=0;c<i;c++){let d=a(s[c]);if(d)return d}let l=o?.bind?.resolveName(e.fromFileId,e.calleeNameRaw);if(l)return{...e,targetNodeId:l.id,confidence:.85,matchType:"import",resolved:!0};for(let c=i;c<s.length;c++){let d=a(s[c]);if(d)return d}return{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function Es(e,t,n=null){let r=n?n.method(e.objectNameRaw,e.calleeNameRaw):t.find(s=>s.type==="classMethod"&&s.className===e.objectNameRaw&&s.name===e.calleeNameRaw);if(r)return{...e,targetNodeId:r.id,confidence:.6,matchType:"methodHeuristic",resolved:!0};let o=n?.bind?.resolveMember(e.fromFileId,e.objectNameRaw,e.calleeNameRaw);return o?{...e,targetNodeId:o.id,confidence:.85,matchType:"import",resolved:!0}:{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function Ps(e){return{...e,targetNodeId:null,confidence:0,matchType:"unresolvedExternal",resolved:!1}}function Ls(e,t,n,r,o=null){if(e.callKind==="new"&&e.ctorName){let s=Bt({...e,calleeNameRaw:e.ctorName},t,n,r,o);if(s.resolved)return{...s,calleeNameRaw:e.calleeNameRaw,matchType:s.matchType+"New"};let i=new Set([e.fromFileId,...r.values()]),a=o?o.ctorsOf(e.ctorName).find(l=>i.has(l.filePath)):t.find(l=>l.type==="classMethod"&&l.className===e.ctorName&&l.name==="constructor"&&i.has(l.filePath));return a?{...e,targetNodeId:a.id,confidence:a.filePath===e.fromFileId?.9:.8,matchType:(a.filePath===e.fromFileId?"local":"import")+"New",resolved:!0}:Ps(e)}if(e.callKind==="chainedCall"&&e.chainHead&&e.chainHeadCalled){let s=Bt({...e,calleeNameRaw:e.chainHead},t,n,r,o);if(s.resolved)return{...e,targetNodeId:s.targetNodeId,confidence:s.confidence*.8,matchType:"chainHead",resolved:!0}}return Ps(e)}import $o from"node:path";import Je from"node:fs";import B from"node:path";var Os=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Sl=["index.ts","index.tsx","index.mts","index.cts","index.js","index.jsx","index.mjs","index.cjs"],kl={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]};var Ms=null,Hs=e=>{Ms=e},Ds=()=>Ms,Rs=e=>B.resolve(e);function zt(e,t){e=B.resolve(e);let n=()=>{try{let i=B.join(e,"package.json");if(!Je.existsSync(i))return null;let a=JSON.parse(Je.readFileSync(i,"utf8")).main;if(typeof a!="string")return null;let l=B.resolve(e,a);return t.has(l)?l:Nl(l,t)}catch{return null}},r=B.extname(e);if(r&&t.has(e))return e;let o=kl[r];if(o)for(let i of o){let a=e.slice(0,-r.length)+i;if(t.has(a))return a}for(let i of Os)if(t.has(e+i))return e+i;let s=n();if(s)return s;for(let i of Sl){let a=B.join(e,i);if(t.has(a))return a}return null}function Nl(e,t){if(B.extname(e)&&t.has(e))return e;for(let r of Os)if(t.has(e+r))return e+r;return null}var _o=e=>{try{let n=Je.readFileSync(e,"utf8").replace(/^/,"").replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,(r,o)=>o??"");return JSON.parse(n.replace(/,(\s*[}\]])/g,"$1"))}catch{return null}};function Us(e,t=new Set){if(t.has(e))return{baseUrl:null,paths:null};t.add(e);let n=_o(e);if(!n)return{baseUrl:null,paths:null};let r=null,o=null,s=n.extends?Array.isArray(n.extends)?n.extends:[n.extends]:[];for(let a of s){if(typeof a!="string"||!a.startsWith("."))continue;let l=B.resolve(B.dirname(e),a);(!Je.existsSync(l)||Je.statSync(l).isDirectory())&&(l=Je.existsSync(l+".json")?l+".json":B.join(l,"tsconfig.json"));let c=Us(l,t);c.baseUrl&&(r=c.baseUrl),c.paths&&(o=c.paths)}let i=n.compilerOptions??{};if(typeof i.baseUrl=="string"&&(r=B.resolve(B.dirname(e),i.baseUrl)),i.paths&&typeof i.paths=="object"){let a=r??B.dirname(e);o=Object.entries(i.paths).map(([l,c])=>{let d=l.indexOf("*");return{prefix:d<0?l:l.slice(0,d),suffix:d<0?"":l.slice(d+1),wildcard:d>=0,targets:(Array.isArray(c)?c:[]).filter(p=>typeof p=="string").map(p=>B.resolve(a,p))}}).sort((l,c)=>c.prefix.length-l.prefix.length)}return{baseUrl:r,paths:o}}function bl(e,t){if(t=t.replace(/^\.\//,"").replace(/\/+$/,""),t.startsWith("!"))return[];let n=[],r=o=>{try{return Je.readdirSync(o,{withFileTypes:!0}).filter(s=>s.isDirectory()&&s.name!=="node_modules"&&!s.name.startsWith(".")).map(s=>B.join(o,s.name))}catch{return[]}};if(t.endsWith("/**")){let o=B.join(e,t.slice(0,-3)),s=i=>{for(let a of r(i))n.push(a),s(a)};s(o)}else t.endsWith("/*")?n.push(...r(B.join(e,t.slice(0,-2)))):t.includes("*")||n.push(B.join(e,t));return n}function _l(e){let t=[],r=_o(B.join(e,"package.json"))?.workspaces;Array.isArray(r)?t.push(...r):Array.isArray(r?.packages)&&t.push(...r.packages);try{let o=Je.readFileSync(B.join(e,"pnpm-workspace.yaml"),"utf8"),s=!1;for(let i of o.split(/\r?\n/)){if(/^packages\s*:/.test(i)){s=!0;continue}if(s){let a=/^\s*-\s*['"]?([^'"#\s]+)['"]?/.exec(i);a?t.push(a[1]):/^\S/.test(i)&&(s=!1)}}}catch{}return t}function Ts(e,t){if(e==null)return null;let n=o=>{if(typeof o=="string")return o;if(Array.isArray(o)){for(let s of o){let i=n(s);if(i)return i}return null}if(o&&typeof o=="object"){for(let s of["source","import","module","default","require","node"])if(s in o){let i=n(o[s]);if(i)return i}}return null};if(typeof e=="string"||Array.isArray(e))return t==="."?n(e):null;let r=Object.keys(e);if(!r.some(o=>o.startsWith(".")))return t==="."?n(e):null;if(e[t]!=null)return n(e[t]);for(let o of r){let s=o.indexOf("*");if(s>0&&t.startsWith(o.slice(0,s))&&t.endsWith(o.slice(s+1))){let i=n(e[o]);if(i)return i.replace("*",t.slice(s,t.length-(o.length-s-1)))}}return null}function Bs(e,t,n={}){let r=Rs(e),o=new Set(t),s=new Map,i=f=>{if(s.has(f))return s.get(f);let u=null,m=B.join(f,"tsconfig.json");return Je.existsSync(m)?u=Us(m):f!==r&&B.dirname(f)!==f&&f.startsWith(r)&&(u=i(B.dirname(f))),s.set(f,u),u},a=new Map;for(let f of _l(r))for(let u of bl(r,f)){let m=_o(B.join(u,"package.json"));m?.name&&!a.has(m.name)&&a.set(m.name,{dir:Rs(u),pkg:m})}let l=[...a.keys()].sort((f,u)=>u.length-f.length),c=(f,u,m)=>{let{dir:h,pkg:v}=a.get(f),g=[],w=S=>{if(!S)return;let N=B.resolve(h,S);g.push(N);let y=B.relative(h,N).split(B.sep);["dist","build","lib","out","esm","cjs"].includes(y[0])&&g.push(B.join(h,"src",...y.slice(1)))};if(u==="."){w(Ts(v.exports,"."));for(let S of["source","module","main"])typeof v[S]=="string"&&w(v[S]);g.push(B.join(h,"src","index"),B.join(h,"index"))}else w(Ts(v.exports,u)),g.push(B.join(h,u),B.join(h,"src",u));for(let S of g){let N=zt(S,m);if(N)return N}return null},d=f=>l.find(u=>f===u||f.startsWith(u+"/"))??null,p=(f,u)=>u?.paths?.some(m=>m.wildcard?f.startsWith(m.prefix)&&f.endsWith(m.suffix)&&f.length>=m.prefix.length+m.suffix.length:f===m.prefix)??!1;return{root:r,files:o,packages:a,isInternal(f,u){if(f.startsWith(".")||d(f))return!0;let m=i(B.dirname(u));return!!(p(f,m)||m?.baseUrl&&!f.startsWith("@")&&zt(B.join(m.baseUrl,f),o))},resolve(f,u,m){if(f.startsWith("."))return zt(B.resolve(B.dirname(u),f),m);let h=i(B.dirname(u));if(h?.paths&&n.paths!==!1)for(let g of h.paths){let w=null;if(g.wildcard?f.startsWith(g.prefix)&&f.endsWith(g.suffix)&&f.length>=g.prefix.length+g.suffix.length&&(w=f.slice(g.prefix.length,f.length-g.suffix.length)):f===g.prefix&&(w=""),w!=null){for(let S of g.targets){let N=zt(S.replace("*",w),m);if(N)return N}break}}let v=n.workspaces===!1?null:d(f);if(v){let g=c(v,f===v?".":"./"+f.slice(v.length+1),m);if(g)return g}if(h?.baseUrl&&n.paths!==!1){let g=zt(B.join(h.baseUrl,f),m);if(g)return g}return null}}}var As=new WeakMap;function zs(e){if(e instanceof Set)return e;let t=As.get(e);return t||As.set(e,t=new Set(e)),t}function Fo(e,t,n){if(!e.startsWith("."))return null;let r=$o.dirname(t),o=$o.resolve(r,e),s=[o,...ur().map(i=>`${o}${i}`),...pr().map(i=>$o.join(o,i))];for(let i of s)if(n.includes(i))return i;return null}function Ae(e,t,n){let r=Fo(e,t,n);if(r)return r;let o=Ds();return o?o.resolve(e,t,zs(n)):null}function jt(e,t,n){let r=new Map;for(let o of t){let s=Fo(o.source,e,n);s&&r.set(o.source,s)}r.legacySize=r.size;for(let o of t){if(r.has(o.source))continue;let s=Ae(o.source,e,n);s&&r.set(o.source,s)}return r}function Ws(e){let t=new Map,n=new Map,r=new Map;for(let o of e){if(o.type!=="classMethod")continue;let s=o.className+"\0"+o.name;n.has(s)||n.set(s,o),o.name==="constructor"&&(r.has(o.className)||r.set(o.className,[]),r.get(o.className).push(o))}return{scopeOf:o=>{let s=t.get(o);return s||(s=le(o,e),t.set(o,s)),s},method:(o,s)=>n.get(o+"\0"+s),ctorsOf:o=>r.get(o)??[]}}function Ct(e){return e?e.split("?")[0].split("/").map(t=>t.startsWith(":")||/^\d+$/.test(t)?"*":t).join("/"):""}var $l=new Set(["function","arrowFunction"]);function qs(e,t,n,r){let o=new Map;for(let c of t){let d=o.get(c.filePath);d||o.set(c.filePath,d=[]),d.push(c)}let s=new Set;for(let c of r)c.resolved&&c.fromNodeId&&c.targetNodeId&&s.add(c.fromNodeId+"\0"+c.targetNodeId);let i=(c,d)=>(o.get(c)??[]).find(p=>$l.has(p.type)&&d(p))??null,a=[];a.argBindings=[];let l=(c,d,p,f,u,m,h)=>{!d||!p||d.id===p.id||s.has(d.id+"\0"+p.id)||a.push({fromFileId:c,fromNodeId:d.id,calleeNameRaw:f,line:u,column:m,branchPath:[],firstArgText:null,deferred:!1,type:"reference",callKind:"reference",targetNodeId:p.id,confidence:h==="local"?.95:.85,matchType:h,resolved:!0})};for(let[c,d]of e){let p=o.get(c);if(p){for(let f of d.refArgs??[]){let u=null,m="local";if(f.b==="fn"?u=i(c,v=>v.name===f.name&&v.startLine===f.declLine):f.b==="import"&&(m="import",(f.ik==="default"||f.ik==="named"||f.ik==="cjs")&&(u=n.nodeForImport(c,f.src,f.ik,f.imp))),!u)continue;let h=fe(f.line,p);l(c,h,u,f.name,f.line,f.column,m),f.callLine!=null&&h&&h.id!==u.id&&a.argBindings.push({file:c,line:f.callLine,column:f.callColumn,targetNodeId:u.id,matchType:m,direct:f.via==="arg"})}for(let f of p){if(f.type!=="inlineHandler")continue;let u=null;for(let m of p)m===f||m.type==="moduleRoot"||m.startLine<=f.startLine&&m.endLine>=f.endLine&&!(m.startLine===f.startLine&&m.endLine===f.endLine)&&(!u||m.endLine-m.startLine<u.endLine-u.startLine)&&(u=m);u??=p.find(m=>m.type==="moduleRoot"),l(c,u,f,f.name,f.startLine,0,"local")}}}return a}function Gs(e,t,n,r){let o=new Map,s=new Map;for(let a of e){if(s.set(a.id,a),a.type!=="classMethod")continue;let l=a.filePath+"\0"+a.className+"\0"+a.name,c=o.get(l);c?c.push(a):o.set(l,[a])}let i=(a,l)=>{for(let c of o.keys())if(c.startsWith(a+"\0"+l+"\0"))return!0;return!1};return function(l){let c=s.get(l.fromNodeId);if(!c||c.type!=="classMethod")return null;let d=t.get(l.fromFileId),p=(d?.classProps??[]).find(v=>v.className===c.className&&v.prop===l.thisProp);if(!p)return null;let f=null,u=null,m=(d.importBindings??[]).find(v=>v.local===p.type);if(m){let v=m.kind==="default"||m.kind==="named"?r.resolveImport(l.fromFileId,m.source,m.kind,m.imported):null;v?.local&&v.local!=="default"&&(f=v.file,u=v.local)}else i(l.fromFileId,p.type)&&(f=l.fromFileId,u=p.type);if(!f)return null;let h=o.get(f+"\0"+u+"\0"+l.thisMethod);return!h||h.length!==1?null:{...l,targetNodeId:h[0].id,confidence:.9,matchType:"typedProperty",resolved:!0}}}var Fl=new Set(["function","arrowFunction"]);function bn(e,t,n){let r=new Map;for(let d of e){if(!Fl.has(d.type))continue;let p=d.filePath+"\0"+d.name;r.has(p)||r.set(p,d)}let o=new Map,s=(d,p)=>{let f=o.get(d);if(!f){f=new Map;for(let u of t.get(d)?.importBindings??[])f.has(u.local)||f.set(u.local,u);o.set(d,f)}return f.get(p)??null},i=(d,p)=>n(d).get(p)??null;function a(d,p,f=new Set){let u=d+"\0"+p;if(f.has(u))return null;f.add(u);let m=t.get(d)?.exportBindings;if(!m)return null;if(p==="default"){if(m.default)return{file:d,local:m.default==="<anon>"?"default":m.default}}else if(m.named?.[p])return{file:d,local:m.named[p]};for(let h of m.reexports??[]){if(h.exported!==p)continue;let v=i(d,h.source);if(v)return a(v,h.imported,f)}for(let h of m.nsReexports??[]){if(h.exported!==p)continue;let v=i(d,h.source);if(v)return{moduleFile:v}}if(p!=="default")for(let h of m.stars??[]){let v=i(d,h),g=v?a(v,p,f):null;if(g)return g}return null}let l=d=>d?.local?r.get(d.file+"\0"+d.local)??null:null;function c(d,p,f,u){let m=i(d,p);return m?f==="default"?a(m,"default"):f==="named"?a(m,u):{moduleFile:m,cjs:f==="cjs"}:null}return{lookupExport:a,resolveImport:c,nodeForImport(d,p,f,u){let m=c(d,p,f,u);return m?.moduleFile&&m.cjs?l(a(m.moduleFile,"default")):l(m)},resolveName(d,p){let f=s(d,p);return f?this.nodeForImport(d,f.source,f.kind,f.imported):null},resolveMember(d,p,f){let u=s(d,p);if(!u)return null;let m=c(d,u.source,u.kind,u.imported);return m?.moduleFile?l(a(m.moduleFile,f)):null},classForImport(d,p){let f=s(d,p);if(!f)return null;let u=c(d,f.source,f.kind,f.imported);return u?.local?{file:u.file,className:u.local==="default"?null:u.local}:null},bindingFor:s}}function Js(e,t,n,r,o,s,i){let a=[],l=Ws(t),c=new Map,d=g=>c.get(g)??jt(g,n.get(g)?.imports??[],r);l.bind=bn(t,n,d);let p=Gs(t,n,d,l.bind),f=new Map;for(let g of e)f.has(g.fromFileId)||f.set(g.fromFileId,[]),f.get(g.fromFileId).push(g);for(let[g,w]of f){let S=n.get(g),N=le(g,t),y=jt(g,S.imports,r);c.set(g,y);for(let x of w)if(x.type==="call")a.push(Bt(x,t,N,y,l));else if(x.type==="methodCall")a.push(Es(x,t,l));else if(x.type==="callSite")a.push((x.thisProp?p(x):null)??Ls(x,t,N,y,l));else if(x.type==="returnValue")a.push({...x,targetNodeId:null,confidence:0,matchType:"returnValue",resolved:!1});else if(x.type==="apiCall")if(x.scope==="external")a.push({...x,targetNodeId:null,confidence:null,matchType:"externalService",resolved:!1});else{let b=Ct(x.url),k=o.get(b);k?a.push({...x,targetNodeId:k,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...x,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(x.type==="socketEmit"){let b=s.get(x.eventName);b?a.push({...x,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...x,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(x.type==="rawSocketSend"){let b=i?.get(x.eventName);b?a.push({...x,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...x,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}}let u=qs(n,t,l.bind,a);for(let g of u)a.push(g);let m=new Map;for(let g of a){if(g.resolved||g.line==null||g.type!=="call"&&g.type!=="methodCall"&&g.type!=="callSite")continue;let w=g.fromFileId+" "+g.line+" "+g.column;(m.get(w)??m.set(w,[]).get(w)).push(g)}let h=[...u.argBindings].sort((g,w)=>w.direct-g.direct),v=new Set;for(let g of h){let w=g.file+" "+g.line+" "+g.column;if(v.has(w))continue;let S=(m.get(w)??[]).find(N=>N.fromNodeId!==g.targetNodeId);S&&(v.add(w),Object.assign(S,{targetNodeId:g.targetNodeId,confidence:g.matchType==="local"?.95:.85,matchType:"argument",resolved:!0,viaArgument:!0}))}return a}function Ks(e){let t=new Map,n=new WeakMap,r=l=>{if(typeof l=="string")return l.length>=20?"s"+l:null;if(l&&typeof l=="object"){let c=n.get(l);if(c===void 0){let d=JSON.stringify(l);c=d.length>=40?"j"+d:"",n.set(l,c)}return c||null}return null};(function l(c){let d=r(c);if(d){let p=t.get(d)??0;if(t.set(d,p+1),p>0)return}if(Array.isArray(c))for(let p of c)l(p);else if(c&&typeof c=="object")for(let p of Object.values(c))l(p)})(e);let o=[],s=new Map,i=l=>{let c=r(l),d=c&&t.get(c)>1;if(d&&s.has(c))return s.get(c);let p;if(typeof l=="string"?p=JSON.stringify(l):Array.isArray(l)?p="["+l.map(i).join(",")+"]":l&&typeof l=="object"?p="{"+Object.entries(l).map(([u,m])=>JSON.stringify(u)+":"+i(m)).join(",")+"}":p=JSON.stringify(l),!d)return p;let f="$"+o.length.toString(36);return o.push(`const ${f}=${p};`),s.set(c,f),f},a=i(e);return`(() => {${o.join(`
10
+ `),!0}function Ee(e){let t=te(e);try{return JSON.parse(Q.readFileSync(t.index,"utf8"))}catch{return{schema:1,nextVersion:1,versions:[]}}}function hu(e,t){let n=te(e);Q.mkdirSync(n.history,{recursive:!0});let r=n.index+"."+process.pid+".tmp";Q.writeFileSync(r,JSON.stringify(t,null,2)),Q.renameSync(r,n.index)}function ht(e,t){let n=Q.readFileSync(ke.join(te(e).history,t.file));return JSON.parse((t.gzip?nc.gunzipSync(n):n).toString("utf8"))}function rc(e,t,n,r,o=fn,{refresh:s=!1,protect:i=[]}={}){Sr=null;let a=te(e);Q.mkdirSync(a.history,{recursive:!0});let c=Ee(e),l=!0,d=n.fingerprint+(l?".json.gz":".json"),f=ke.join(a.history,d);(s||!Q.existsSync(f))&&Q.writeFileSync(f,l?nc.gzipSync(t):t);let u=(fe(e,["status","--porcelain"])||"").split(`
11
+ `).some(N=>N.trim()&&!/\.canopy(\/|$)/.test(N)),h=s?c.versions.pop():null,p={version:h?h.version:c.nextVersion,fingerprint:n.fingerprint,createdAt:new Date().toISOString(),headSha:fe(e,["rev-parse","HEAD"]),headMessage:fe(e,["log","-1","--format=%s"]),dirty:u,counts:r,file:d,gzip:l,bytes:Q.statSync(f).size,sha256:du.createHash("sha256").update(Q.readFileSync(f)).digest("hex"),engineVersion:Vt(),outputFormat:no};c.versions.push(p),h||c.nextVersion++;let m=c.versions[0]?.version,y=N=>N.version===m||i.includes(N.version),g=0,x=0,S=()=>{let N=c.versions.findIndex(($,j)=>!y($)&&j<c.versions.length-1);return N<0?null:c.versions.splice(N,1)[0]};for(;c.versions.length>o&&S();)g++;let k=mu(),v=N=>{try{return Q.statSync(ke.join(a.history,N.file)).size}catch{return N.bytes??0}},w=c.versions.reduce((N,$)=>N+v($),0);for(;w>k&&c.versions.length>pu;){let N=S();if(!N)break;w-=v(N),x++}if(g||x){let N=[];g&&N.push(`${g} old version${g===1?"":"s"} removed (the store keeps the first version, the one you last saw and the newest ${o})`),x&&N.push(`${x} more removed to stay under the size limit of ${Math.round(k/1048576)} MB`),Sr=N.join("; ")}let b=new Set(c.versions.map(N=>N.file));for(let N of Q.readdirSync(a.history))/\.json(\.gz)?$/.test(N)&&N!=="index.json"&&!b.has(N)&&Q.rmSync(ke.join(a.history,N),{force:!0});return hu(e,c),p}function tc(){for(let e of oo)try{Q.rmSync(e,{force:!0})}catch{}oo.clear()}function gu(){if(!ec){ec=!0,process.once("exit",tc);for(let e of["SIGINT","SIGTERM"])process.on(e,()=>{tc(),process.exit(e==="SIGINT"?130:143)})}}function kr(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Nr(e){try{return JSON.parse(Q.readFileSync(e,"utf8"))}catch{return null}}function br(e,t={},n=null){Q.mkdirSync(ke.dirname(e),{recursive:!0});let r=null;for(let o=0;o<3;o++)try{let s=Q.openSync(e,"wx");return Q.writeSync(s,JSON.stringify({pid:process.pid,startedAt:Date.now(),version:n,...t})),Q.closeSync(s),oo.add(e),gu(),r?{ok:!0,removedStale:r}:{ok:!0}}catch(s){if(s.code!=="EEXIST")throw s;let i=Nr(e);if(i&&kr(i.pid)&&i.pid!==process.pid)return{ok:!1,owner:i};let a=0;try{a=Date.now()-Q.statSync(e).mtimeMs}catch{continue}if(!i&&a<2e3)return{ok:!1,owner:null};r={pid:i?.pid??null},Q.rmSync(e,{force:!0})}return{ok:!1,owner:null}}function _r(e){oo.delete(e);try{Q.rmSync(e,{force:!0})}catch{}}function sc(e,t=null,n=null){let r=br(te(e).lock,{},t);return r.ok&&r.removedStale&&n&&n(`removed a stale lock left by a run that stopped (process ${r.removedStale.pid??"unknown"})`),r.ok}var uu,pu,mu,Gv,fn,te,Sr,oc,oo,ec,ic,ac,cc,De=kt(()=>{wr();uu=200,pu=2,mu=()=>{let e=Number(process.env.CANOPY_SNAPSHOT_MAX_MB);return(Number.isFinite(e)&&e>0?e:uu)*1024*1024},Gv=600*1e3,fn=50,te=e=>{let t=ke.join(ke.resolve(e),".canopy");return{root:t,history:ke.join(t,"history"),index:ke.join(t,"history","index.json"),lock:ke.join(t,"sync.lock"),pending:ke.join(t,"sync.pending"),log:ke.join(t,"sync.log")}};Sr=null,oc=()=>Sr;oo=new Set,ec=!1;ic=e=>_r(te(e).lock),ac=e=>{let t=te(e);Q.mkdirSync(t.root,{recursive:!0}),Q.writeFileSync(t.pending,String(Date.now()))},cc=e=>{let t=te(e);return Q.existsSync(t.pending)?(Q.rmSync(t.pending,{force:!0}),!0):!1}});import _e from"node:fs";import rt from"node:path";import dc from"node:crypto";import yu from"node:zlib";function pc(e,t){_e.mkdirSync(rt.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;_e.writeFileSync(n,t),_e.renameSync(n,e)}function gt(e){let t;try{t=_e.readFileSync(uc(e),"utf8")}catch{return null}let n;try{n=JSON.parse(t)}catch{throw new Error("corrupt")}if(!n||typeof n!="object"||n.schemaVersion!==fc||n.checksum!==mc(n))throw new Error("corrupt");return n}function hc(e,t){let n={...t,schemaVersion:fc};return n.checksum=mc(n),pc(uc(e),JSON.stringify(n,null,2)),n}function Ir(e,t){let n=null;try{n=gt(e)}catch{n=null}return n||hc(e,{projectId:dc.randomBytes(8).toString("hex"),firstInstalledAt:new Date().toISOString(),engineFingerprint:t,lastAnalysed:null,lastSeen:null,projectRoot:rt.resolve(e)})}function jr(e,t){let n=gt(e)??Ir(e,t.engineFingerprint??null);return hc(e,{...n,...t})}function so(e){try{return gt(e)?.lastSeen??null}catch{return null}}function gc(e,t,{branch:n=null,engineFingerprint:r=null,now:o=new Date}={}){return t?jr(e,{lastSeen:{version:t.version,fingerprint:t.fingerprint,headSha:t.headSha??null,at:o.toISOString(),branch:n,engineFingerprint:r??t.engineVersion??null}}).lastSeen:null}function yc(e){let t=[];try{gt(e)}catch{t.push("meta.json is damaged")}let n=te(e);if(_e.existsSync(n.index)){let r=null;try{r=JSON.parse(_e.readFileSync(n.index,"utf8"))}catch{t.push("history/index.json is damaged")}r&&!Array.isArray(r.versions)&&t.push("history/index.json has no version list");for(let o of r?.versions??[]){let s=rt.join(n.history,String(o.file??""));if(!o.file||/[\\/]/.test(o.file)||!_e.existsSync(s)){t.push(`snapshot of version ${o.version} is missing`);continue}let i=_e.readFileSync(s);if(o.sha256&&$r(i)!==o.sha256){t.push(`snapshot of version ${o.version} does not match its checksum`);continue}try{JSON.parse((o.gzip?yu.gunzipSync(i):i).toString("utf8"))}catch{t.push(`snapshot of version ${o.version} cannot be read`)}}}return{ok:t.length===0,problems:t}}function vc(e,t=new Date){let n=te(e).root,r=rt.join(n,"state.corrupt-"+t.toISOString().replace(/[:.]/g,"-"));_e.mkdirSync(r,{recursive:!0});for(let o of["meta.json","files.json","history"]){let s=rt.join(n,o);_e.existsSync(s)&&_e.renameSync(s,rt.join(r,o))}return rt.basename(r)}function xc(e,t,n,{full:r=!1}={}){let o={};if(!r)try{let l=JSON.parse(_e.readFileSync(lc(e),"utf8"));l.schema===1&&l.files&&(o=l.files)}catch{o={}}let s={},i=0,a=0,c=t.map(l=>{let d=n(l),f;try{f=_e.statSync(l)}catch{f=null}let u=o[d];if(f&&u&&u[0]===f.size&&u[1]===Math.round(f.mtimeMs)&&typeof u[2]=="string")return s[d]=u,i++,[d,u[2]];let h=$r(_e.readFileSync(l));return a++,f&&(s[d]=[f.size,Math.round(f.mtimeMs),h]),[d,h]}).sort((l,d)=>l[0]<d[0]?-1:l[0]>d[0]?1:0);try{pc(lc(e),JSON.stringify({schema:1,files:s}))}catch{}return{hashes:c,reused:i,rehashed:a}}var fc,$r,uc,lc,mc,un=kt(()=>{De();fc=1,$r=e=>dc.createHash("sha256").update(e).digest("hex"),uc=e=>rt.join(te(e).root,"meta.json"),lc=e=>rt.join(te(e).root,"files.json");mc=e=>{let{checksum:t,...n}=e;return $r(JSON.stringify(n))}});function Ct(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 wc(e){let t=[],n=[],r=[];for(let[i,a]of e.publicGraph){for(let c of a.nodes)t.push({id:c.id,service:i,kind:c.type,name:c.name,filePath:c.filePath,startLine:c.startLine,endLine:c.endLine,bodyHash:c.bodyHash});for(let c of a.edges)n.push({id:c.id,service:i,from:c.fromNodeId,callKind:c.callKind??c.type,calleeNameRaw:c.calleeNameRaw??c.eventName??c.url??null,resolvedTo:c.targetNodeId??null})}let o=new Map;for(let i of e.publicWorkflows){let a=i.steps[0]?.nodeId??null,c=`${i.serviceId} | ${a} | ${i.name}`,l=(o.get(c)??0)+1;o.set(c,l),r.push({id:l>1?`${c} #${l}`:c,service:i.serviceId,tier:i.tier,tierOrigin:i.tierOrigin,entry:a,steps:i.steps.map(d=>d.nodeId)})}t.sort(io(i=>i.service+"\0"+i.id)),n.sort(io(i=>i.service+"\0"+i.id)),r.sort(io(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(io(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 io,ao=kt(()=>{io=e=>(t,n)=>{let r=e(t),o=e(n);return r<o?-1:r>o?1:0}});function Sc(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 xu(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 Fr(e,t){let n=a=>a.reduce((c,l)=>c.set(l,(c.get(l)??0)+1),new Map),r=n(e),o=n(t),s=[],i=[];for(let[a,c]of o)for(let l=0;l<c-(r.get(a)??0);l++)s.push(a);for(let[a,c]of r)for(let l=0;l<c-(o.get(a)??0);l++)i.push(a);return{added:s.sort(),removed:i.sort()}}function pn(e,t){let n=Sc(e),r=Sc(t),o=[...r.values()].filter(_=>!n.has(_.id)),s=[...n.values()].filter(_=>!r.has(_.id)),i=[];for(let[_,P]of r){let L=n.get(_);L&&L.bodyHash!==P.bodyHash&&i.push({...Cr(P),from:L.bodyHash,to:P.bodyHash})}let a=[],c=new Map,l=_=>[_.kind,_.name,_.bodyHash].join("\0"),d=new Map;for(let _ of $e(o,P=>P.id)){let P=l(_);d.has(P)||d.set(P,[]),d.get(P).push(_)}let f=[],u=new Set;for(let _ of $e(s,P=>P.id)){let L=(d.get(l(_))??[]).find(z=>!u.has(z.id)&&z.filePath!==_.filePath&&z.id.split("::").pop()===_.id.split("::").pop());L?(u.add(L.id),a.push({kind:_.kind,name:_.name,services:L.services,fromId:_.id,toId:L.id,fromPath:_.filePath,toPath:L.filePath}),c.set(_.id,L.id)):f.push(_)}o=$e(o.filter(_=>!u.has(_.id)),_=>_.id),s=$e(f,_=>_.id);let h=xu(c),p=_=>_.service+"\0"+_.id,m=new Map(e.edges.map(_=>[p({service:_.service,id:h(_.id)}),{..._,id:h(_.id),from:h(_.from),resolvedTo:h(_.resolvedTo)}])),y=new Map(t.edges.map(_=>[p(_),_])),g=_=>({id:_.id,service:_.service,from:_.from,callKind:_.callKind,calleeNameRaw:_.calleeNameRaw,resolvedTo:_.resolvedTo}),x=[],S=[],k=[];for(let[_,P]of y){let L=m.get(_);L?L.resolvedTo!==P.resolvedTo&&k.push({id:P.id,service:P.service,from:P.from,calleeNameRaw:P.calleeNameRaw,fromTarget:L.resolvedTo,toTarget:P.resolvedTo}):x.push(g(P))}for(let[_,P]of m)y.has(_)||S.push(g(P));let v=_=>_.service+"\0"+_.id,w=_=>({..._,id:_.id.replace(_.entry??"\0",h(_.entry)),entry:h(_.entry),steps:_.steps.map(h)}),b=new Map(e.workflows.map(_=>{let P=w(_);return[P.id,P]})),N=new Map(t.workflows.map(_=>[_.id,_])),$={added:[],removed:[],changed:[]},j={added:[],removed:[],changed:[]},O=_=>({id:_.id,service:_.service,tier:_.tier,steps:_.steps.length});for(let[_,P]of N){let L=b.get(_);if(!L){(P.tier==="physical"?$:j).added.push(O(P));continue}let z=Fr(L.steps,P.steps),Re=!z.added.length&&!z.removed.length&&L.steps.join(`
12
+ `)!==P.steps.join(`
13
+ `),je=L.tier!==P.tier?`${L.tier} -> ${P.tier}`:null;if(!z.added.length&&!z.removed.length&&!Re&&!je)continue;let ct={id:_,service:P.service,tier:P.tier,stepsAdded:z.added,stepsRemoved:z.removed,reordered:Re,tierChange:je};(L.tier==="physical"||P.tier==="physical"?$:j).changed.push(ct)}for(let[_,P]of b)N.has(_)||(P.tier==="physical"?$:j).removed.push(O(P));for(let _ of[$,j])for(let P of["added","removed","changed"])_[P]=$e(_[P],L=>L.id);let D=_=>[_.fromService,_.fromNodeId,_.toService,_.toNodeId,_.via,_.key].join(" | "),G=new Map(e.crossServiceEdges.map(_=>[D({..._,fromNodeId:h(_.fromNodeId),toNodeId:h(_.toNodeId)}),{..._,fromNodeId:h(_.fromNodeId),toNodeId:h(_.toNodeId)}])),M=new Map(t.crossServiceEdges.map(_=>[D(_),_])),q=$e([...M].filter(([_])=>!G.has(_)).map(([,_])=>_),D),E=$e([...G].filter(([_])=>!M.has(_)).map(([,_])=>_),D),C=new Map,R=new Map,W=(_,P,L)=>{_.has(P)||_.set(P,new Set),_.get(P).add(L)};for(let _ of s)W(C,_.id,"removed");for(let _ of o)W(R,_.id,"added");for(let _ of i)W(C,_.id,"modified"),W(R,_.id,"modified");for(let _ of a)W(C,_.fromId,"moved"),W(R,_.toId,"moved");let K=[],se=new Set([...b.keys(),...N.keys()]);for(let _ of se){let P=b.get(_),L=N.get(_);if(!(P&&P.tier==="physical"||L&&L.tier==="physical"))continue;let z=new Map;for(let[je,ct]of[[P,C],[L,R]])if(je)for(let Zt of new Set(je.steps))for(let Qt of ct.get(Xe(Zt,je===P,c))??[])z.set(Zt+"\0"+Qt,{node:Zt,why:Qt});let Re=P&&L&&(Fr(P.steps,L.steps).added.length||Fr(P.steps,L.steps).removed.length);z.size&&K.push({workflow:_,service:(L??P).service,status:P?L?"changed":"removed":"new",stepsChanged:!!Re,reasons:$e([...z.values()],je=>je.node+"\0"+je.why)})}function Xe(_,P,L){if(!P)return _;for(let[z,Re]of L)if(Re===_)return z;return _}let ue={schema:1,from:e.fingerprint,to:t.fingerprint,nodes:{added:o.map(Cr),removed:s.map(Cr),modified:$e(i,_=>_.id),moved:$e(a,_=>_.toId)},edges:{added:$e(x,v),removed:$e(S,v),retargeted:$e(k,v)},workflows:{physical:$,guessed:j},crossServiceEdges:{added:q,removed:E},touched:$e(K,_=>_.workflow)};return ue.counts={nodes:{added:o.length,removed:s.length,modified:i.length,moved:a.length},edges:{added:x.length,removed:S.length,retargeted:k.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:q.length,removed:E.length},touched:K.length,touchedNew:K.filter(_=>_.status==="new").length},ue}function Nc(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=(l,d,f)=>{if(d.length){i.push("",`${l} (${d.length})`);for(let u of d.slice(0,r))i.push(" "+f(u));d.length>r&&i.push(` ... ${d.length-r} more`)}};a("Touched physical workflows",e.touched,l=>`[${l.service}] ${l.workflow.split(" | ").slice(2).join(" | ")} <${l.status}> because: ${l.reasons.slice(0,4).map(d=>`${d.why} ${Ft(d.node)}`).join(", ")}${l.reasons.length>4?`, +${l.reasons.length-4}`:""}`),a("Nodes added",e.nodes.added,l=>`+ ${l.id}`),a("Nodes removed",e.nodes.removed,l=>`- ${l.id}`),a("Nodes modified",e.nodes.modified,l=>`~ ${l.id}`),a("Nodes moved",e.nodes.moved,l=>`\u21A6 ${l.name}: ${l.fromPath} \u2192 ${l.toPath}`),a("Edges added",e.edges.added,l=>`+ [${l.service}] ${Ft(l.from)} \u2192 ${l.calleeNameRaw}${l.resolvedTo?` (resolved to ${Ft(l.resolvedTo)})`:""}`),a("Edges removed",e.edges.removed,l=>`- [${l.service}] ${Ft(l.from)} \u2192 ${l.calleeNameRaw}`),a("Edges retargeted",e.edges.retargeted,l=>`~ [${l.service}] ${Ft(l.from)} \u2192 ${l.calleeNameRaw}: ${Ft(l.fromTarget)||"unresolved"} \u2192 ${Ft(l.toTarget)||"unresolved"}`),a("Physical workflows changed",e.workflows.physical.changed,l=>`~ ${l.id.split(" | ").slice(2).join(" | ")} +${l.stepsAdded.length} \u2212${l.stepsRemoved.length} steps${l.tierChange?`, tier ${l.tierChange}`:""}${l.reordered?", reordered":""}`),a("Physical workflows added",e.workflows.physical.added,l=>`+ ${l.id.split(" | ").slice(2).join(" | ")} (${l.steps} steps)`),a("Physical workflows removed",e.workflows.physical.removed,l=>`- ${l.id.split(" | ").slice(2).join(" | ")}`),a("Cross-service edges added",e.crossServiceEdges.added,l=>`+ ${l.fromService} \u2192 ${l.toService} via ${l.via} ${l.key??""}`),a("Cross-service edges removed",e.crossServiceEdges.removed,l=>`- ${l.fromService} \u2192 ${l.toService} via ${l.via} ${l.key??""}`);let c=o.guessedWorkflows;return c.added+c.removed+c.changed&&i.push("",`Informational (guessed workflows, never counted as changes): +${c.added} \u2212${c.removed} ~${c.changed}`),i.join(`
14
+ `)}var vu,$e,Cr,kc,Ft,Er=kt(()=>{ao();vu=(e,t)=>e<t?-1:e>t?1:0,$e=(e,t)=>e.slice().sort((n,r)=>vu(t(n),t(r)));Cr=e=>({id:e.id,services:e.services,kind:e.kind,name:e.name,filePath:e.filePath});kc=e=>Ct(e),Ft=e=>(e??"").split("::").slice(-2).join("::")});var $c={};jl($c,{UI_VERSIONS:()=>bc,buildSince:()=>uo,buildUiHistory:()=>Tr,describeSince:()=>Lr,historyScript:()=>Rr,writeHistoryJs:()=>Su});import Pr from"node:fs";import fo from"node:path";function _c(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>co&&(t.truncated[`${o}.${s}`]=i.length,r[s]=i.slice(0,co))};return n(t.nodes,"nodes"),n(t.edges,"edges"),n(t.workflows.physical,"workflows.physical"),n(t.crossServiceEdges,"crossServiceEdges"),t.touched.length>co&&(t.truncated.touched=t.touched.length,t.touched=t.touched.slice(0,co)),t}function uo(e,{cache:t=null}={}){let r=Ee(e).versions;if(!r.length)return null;let o=r[r.length-1],s=so(e),i=s?r.find(u=>u.version===s.version):null,a=!i,c=i??r[0],l={fromVersion:c.version,toVersion:o.version,firstVisit:a,noChanges:!1,at:s?.at??null,commits:null,versionsBetween:r.filter(u=>u.version>c.version&&u.version<=o.version).length,branchNote:null,engineNote:!1,diff:null,baselineGone:!!s&&!i},d=fe(e,["rev-parse","--abbrev-ref","HEAD"]);if(s?.branch&&d&&s.branch!==d&&(l.branchNote=`branch changed from ${s.branch} to ${d}`),c.engineVersion&&o.engineVersion&&c.engineVersion!==o.engineVersion&&(l.engineNote=!0),c.version===o.version)return l.noChanges=!a,l;if(c.headSha&&o.headSha&&c.headSha!==o.headSha){let u=fe(e,["rev-list","--count",`${c.headSha}..${o.headSha}`]);u!==null&&/^\d+$/.test(u)&&(l.commits=Number(u))}let f=`${c.version}:${o.version}:${c.fingerprint}:${o.fingerprint}`;return t&&t.has(f)?l.diff=t.get(f):(l.diff=_c(pn(ht(e,c),ht(e,o))),t&&(t.clear(),t.set(f,l.diff))),l}function Lr(e,t=Date.now()){if(!e)return null;if(e.firstVisit)return e.baselineGone?"Your last visit is no longer stored, so this compares with the first saved version":"First visit: nothing to compare with yet";let n=wu(e.at,t);if(e.noChanges)return`No changes since you last opened Canopy${n?", "+n:""}`;let r=e.commits!=null?` (${e.commits} commit${e.commits===1?"":"s"})`:e.versionsBetween?` (${e.versionsBetween} saved version${e.versionsBetween===1?"":"s"})`:"",o=e.diff?.counts?.touched;return`Since you last opened Canopy${n?", "+n:""}${r}${o!==void 0?`: ${o} workflow${o===1?"":"s"} touched`:""}`}function Tr(e,{sinceCache:t=null,memo:n=!1}={}){let o=Ee(e).versions.slice(-bc),s=null;if(n)try{let a=Pr.statSync(fo.join(fo.resolve(e),".canopy","history","index.json"));s=`${fo.resolve(e)}|${a.mtimeMs}|${a.size}`}catch{s=null}let i;if(s&&lo.key===s)i=lo.value;else{i={};for(let a=1;a<o.length;a++)i[o[a].version]=_c(pn(ht(e,o[a-1]),ht(e,o[a])));s&&(lo.key=s,lo.value=i)}return{schema:1,versions:o.map(a=>({version:a.version,fingerprint:a.fingerprint,createdAt:a.createdAt,headSha:a.headSha,headMessage:a.headMessage,dirty:a.dirty,counts:a.counts})),diffs:i,since:uo(e,{cache:t})}}function Rr(e,t={}){return`const canopyHistory = ${Ct(Tr(e,{memo:!0,...t}))};`}function Su(e,t){Pr.mkdirSync(t,{recursive:!0}),Pr.writeFileSync(fo.join(t,"history.js"),`const canopyHistory = ${Ct(Tr(e))};`)}var bc,co,wu,lo,po=kt(()=>{De();un();Er();ao();bc=20,co=200;wu=(e,t=Date.now())=>{if(!e)return null;let n=Math.max(0,Math.round((t-Date.parse(e))/6e4));if(n<2)return"a moment ago";if(n<90)return`${n} minutes ago`;let r=Math.round(n/60);if(r<24)return`${r} hours ago`;let o=Math.round(r/24);return o===1?"yesterday":`${o} days ago`};lo={key:null,value:null}});import es from"node:fs";import vn from"node:path";import yt from"node:fs";import ku from"node:os";import ye from"node:path";import{fileURLToPath as Ic}from"node:url";import Z from"node:path";import we from"node:fs";import{fileURLToPath as ru,pathToFileURL as su}from"node:url";var Oo=Fl(us(),1);import Ht from"node:fs";import Ce from"node:path";var Ro={javascript:[".js",".jsx",".mjs",".cjs"],typescript:[".ts",".tsx"]},ps=[".ts",".tsx",".mts",".cts"],Zl={javascript:["index.js","index.jsx"],typescript:["index.ts","index.tsx"]};function ms(){return Object.values(Ro).flat()}function hs(){return Object.values(Zl).flat()}var gs=["log","logger","console","debug","trace"];var vs=[".yarn",".pnp","vendor","dist","build","out","coverage",".next",".nuxt",".turbo",".cache","bower_components"],Mo=["node_modules",".git",".canopy",".canopy-cache"],ys=[".vue",".svelte"],Ql=1024*1024,Ao=1e4;function ed(e,t=null){let n=[];function r(o,s){let i=Ce.join(o,".gitignore"),a=(0,Oo.default)().add(s);Ht.existsSync(i)&&a.add(Ht.readFileSync(i,"utf-8"));let c=Ht.readdirSync(o,{withFileTypes:!0});for(let l of c){let d=Ce.join(o,l.name),f=Ce.relative(e,d).split(Ce.sep).join("/");if(!a.ignores(f)&&!(l.isDirectory()&&Mo.includes(l.name))){if(l.isDirectory()&&vs.includes(l.name)){t&&t.excludedDirs.push(d);continue}l.isDirectory()?r(d,a):l.isFile()&&n.push(d)}}}return r(e,(0,Oo.default)()),n}function td(e,t,n=null){return e.filter(r=>!(n?Ce.relative(n,r):r).split(Ce.sep).some(s=>t.includes(s)))}function xs(e,t){let n=0,r;try{r=Ht.readdirSync(e,{withFileTypes:!0})}catch{return 0}for(let o of r)o.isDirectory()?Mo.includes(o.name)||(n+=xs(Ce.join(e,o.name),t)):o.isFile()&&t.has(Ce.extname(o.name))&&n++;return n}var nd=e=>/\.d\.(ts|mts|cts)$/.test(e);function od(e){let t=Ce.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=Ht.statSync(e).size}catch{return null}if(n>Ql)return{kind:"oversized",reason:`oversized (${(n/1048576).toFixed(1)} MB, limit 1 MB)`};if(n>Ao){let r=Ht.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>Ao)return{kind:"minified",reason:`line of ${s.toLocaleString("en-US")} characters (limit ${Ao.toLocaleString("en-US")}; minified/bundled)`}}return null}function Ho(e,t=["javascript","typescript"]){let n=t.flatMap(f=>(f==="typescript"?ps:Ro[f])||[]),r={excludedDirs:[]},o=td(ed(e,r),[...vs,...Mo],e),s=f=>Ce.relative(e,f).split(Ce.sep).join("/"),i=[],a=[],c={};for(let f of o){let u=Ce.extname(f);if(n.includes(u)){if(nd(f)){a.push({file:s(f),kind:"declaration",reason:"declaration file"});continue}let h=od(f);h?a.push({file:s(f),kind:h.kind,reason:h.reason}):i.push(f)}else ys.includes(u)&&(c[u]=(c[u]??0)+1)}let l=new Set([...n,...ys]),d={};for(let f of r.excludedDirs){let u=Ce.basename(f),h=d[u]??={dirs:0,files:0};h.dirs++,h.files+=xs(f,l)}return{files:i,skipped:a,unsupported:c,excludedDirs:d}}function $n(e,t=["javascript","typescript"]){return Ho(e,t).files}import rd from"node:path";var Nt=e=>e.toLocaleString("en-US"),In=(e,t,n=t+"s")=>`${Nt(e)} ${e===1?t:n}`,sd={".vue":"Vue",".svelte":"Svelte"},id=[".vue",".svelte"],ad=new Set([".ts",".tsx",".mts",".cts"]);function ws({discovered:e,parseResults:t,scopeFiles:n,rel:r,rootService:o=null}){let s=(t.budgetSkips??[]).map(p=>({path:r(p.filePath),kind:"timeout",reason:p.reason})),i=new Set((t.budgetSkips??[]).map(p=>p.filePath)),a=[...e.skipped.map(p=>({path:p.file,kind:p.kind,reason:p.reason})),...s].sort((p,m)=>p.path<m.path?-1:p.path>m.path?1:0),c=e.files.filter(p=>!i.has(p)),l=c.filter(p=>t.get(p)?.hadErrors).map(r).sort(),d=c.flatMap(p=>(t.get(p)?.warnings??[]).map(m=>({path:r(p),extractor:m.extractor,message:m.message}))).sort((p,m)=>p.path<m.path?-1:p.path>m.path?1:0),f=c.filter(p=>ad.has(rd.extname(p))).length,u={};for(let p of id)e.unsupported[p]&&(u[p]=e.unsupported[p]);let h={};for(let p of a)h[p.kind]=(h[p.kind]??0)+1;return{analyzed:c.length,analyzedJs:c.length-f,analyzedTs:f,inService:c.filter(p=>n.has(p)).length,notAnalyzed:u,notAnalyzedTotal:Object.values(u).reduce((p,m)=>p+m,0),skipped:a,skippedByKind:h,parseErrors:l.length,parseErrorFiles:l.slice(0,50),parseWarnings:d.length,parseWarningList:d.slice(0,50),excludedDirs:e.excludedDirs,rootService:o}}function jn(e){let t=["Coverage"],n=[],r=new Map;for(let[a,c]of Object.entries(e.notAnalyzed)){let l=sd[a];r.has(l)||r.set(l,[]),r.get(l).push(`${Nt(c)} ${a}`)}for(let[a,c]of r)n.push(`${c.join(", ")} files (${a} not supported yet)`);if(e.skipped.length){let a=Object.entries(e.skippedByKind).map(([c,l])=>`${c}: ${l}`).join(", ");n.push(`${Nt(e.skipped.length)} skipped (${a})`)}e.parseErrors&&n.push(`${Nt(e.parseErrors)} with parse errors`),e.parseWarnings&&n.push(`${Nt(e.parseWarnings)} extractor warnings (a construct skipped; the rest of its file was analyzed)`);let o=e.analyzedTs?`${In(e.analyzedJs,"JS file")} and ${In(e.analyzedTs,"TS file")}`:In(e.analyzed,"JS file");t.push(` Analyzed ${o}, ${Nt(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 ${Nt(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,c])=>`${a}/ x${c.dirs} (${In(c.files,"source file")})`).join(", ")}.`),e.rootService&&t.push(` Root service: ${e.rootService.reason}.`),t.join(`
16
+ `)}We();import{Parser as Do,Language as ks}from"web-tree-sitter";import Cn from"node:path";import{fileURLToPath as ld}from"node:url";var hm=Cn.dirname(ld(globalThis.__canopyUrl("src/stage2_parse/initParser.js")));var Bo=new WeakMap,nn=e=>Bo.get(e)??"javascript",ut=e=>nn(e)!=="javascript";function Uo(e){let t=Cn.extname(e);return t===".tsx"?"tsx":t===".ts"||t===".mts"||t===".cts"?"typescript":"javascript"}var dd={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm"};async function Ns(e,t){for(let n of new Set(t.map(Uo))){if(e.grammars.has(n))continue;let r=Cn.join(He("tree-sitter-typescript"),dd[n]),o=await ks.load(r);Bo.set(o,n);let s=new Do;s.setLanguage(o),e.grammars.set(n,{parser:s,language:o})}return e}async function bs(){await Do.init();let e=new Do,t=Cn.join(He("tree-sitter-javascript"),"tree-sitter-javascript.wasm"),n=await ks.load(t);return e.setLanguage(n),Bo.set(n,"javascript"),{parser:e,language:n,grammars:new Map([["javascript",{parser:e,language:n}]])}}import fd from"node:fs";function js(e,t){let n=fd.readFileSync(t,"utf-8"),r=e.parse(n);if(zo(r)||n.includes("\0")){let o=n,s=Is(r);for(let i of ud){let a=i.apply(o);if(a===o)continue;let c=e.parse(a),l=Is(c);if(l<s||i.always){try{r.delete()}catch{}o=a,r=c,s=l}else try{c.delete()}catch{}}o!==n&&(r.canopyOriginalSource=n)}return{tree:r,source:n,filePath:t}}var Cs=e=>e.replace(/[^\n]/g," "),_s=e=>"any"+Cs(e).slice(3),$s=/(?<![&])&(?![&=])/g,ud=[{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,Cs)},{name:"typeof import()",apply:e=>e.replace(/typeof\s+import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)*/g,_s)},{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,_s)},{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($s,"+"))},{name:"& in JSX attribute",apply:e=>e.replace(/(\s[\w:-]+=)"([^"\n]*)"/g,(t,n,r)=>n+'"'+r.replace($s,"+")+'"')}];function Is(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 zo(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 Wo from"node:fs";import on from"node:path";import{fileURLToPath as pd}from"node:url";import{Query as md}from"web-tree-sitter";var Fs=on.dirname(pd(globalThis.__canopyUrl("src/utils/loadQuery.js"))),Es=new WeakMap;function ie(e,t){let n=Es.get(e);if(n||Es.set(e,n=new Map),n.has(t))return n.get(t);let r=on.join(Fs,"..","stage2_parse","queries"),o=Wo.existsSync(r)?r:on.join(Fs,"..","..","dist","queries"),s=nn(e),c=(s==="javascript"?[]:s==="tsx"?["tsx","typescript"]:[s]).map(f=>on.join(o,f,t)).find(f=>Wo.existsSync(f))??on.join(o,t),l=Wo.readFileSync(c,"utf-8"),d=new md(e,l);return n.set(t,d),d}var Ps="javascript",Ls=e=>{Ps=e};var Fn=()=>Ps!=="javascript";var hd=new Set(["non_null_expression","as_expression","satisfies_expression","type_assertion"]);function me(e){for(;e;)if(hd.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=me(e.namedChild(0));if(t===e.namedChild(0))break;e=t}else break;return e}function gd(e){let t=e;for(;t;){t=me(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 pt(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"?me(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(gd(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 c=t;for(;c.type==="parenthesized_expression"&&c.namedChildCount===1;)c=c.namedChild(0);return c.type==="arrow_function"||c.type==="function_expression"||c.type==="function"||c.type==="generator_function"?{kind:"iife",oldShape:!1,nameNode:t}:{kind:"callOfCall",oldShape:!1,nameNode:t}}function Ts(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 En(e){let t=e;for(;t&&t.type!=="call_expression";)t=t.parent;return t}function Rs(e){let t=e.childForFieldName("function"),n=!1;for(;t;)if(t=me(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 As(e){let t=e.text.replace(/\s+/g," ");return t.length>120?t.slice(0,117)+"...":t}function Ms(e,t){let o=ie(t,"functionDeclarations.scm").matches(e.rootNode).map(s=>{let i=s.captures.find(l=>l.name==="func_name"),a=s.captures.find(l=>l.name==="func_params"),c=s.captures.find(l=>l.name==="func_declaration");return{name:i.node.text,params:a.node.text,startLine:c.node.startPosition.row+1,endLine:c.node.endPosition.row+1,startIndex:c.node.startIndex,endIndex:c.node.endIndex,node:i.node}});return ut(t)&&o.push(...yd(e,t)),o}function yd(e,t){return ie(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 Hs(e,t){return ie(t,"arrowFunctions.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(c=>c.name==="func_name"),i=o.captures.find(c=>c.name==="func_params"),a=o.captures.find(c=>c.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 Ds(e,t){let r=ie(t,"classMethods.scm").matches(e.rootNode),o=ut(t);return r.map(s=>{let i=s.captures.find(f=>f.name==="class_name"),a=s.captures.find(f=>f.name==="method_name"),c=s.captures.find(f=>f.name==="method_params"),l=s.captures.find(f=>f.name==="method_declaration"),d=l.node;if(o)for(let f=d.previousNamedSibling;f&&f.type==="decorator";f=f.previousNamedSibling)d=f;return{className:i?i.node.text:"default",methodName:a.node.text,params:c.node.text,startLine:d.startPosition.row+1,endLine:l.node.endPosition.row+1,startIndex:d.startIndex,endIndex:l.node.endIndex,node:a.node}})}function Bs(e,t){let r=ie(t,"imports.scm").matches(e.rootNode),o=ut(t);return r.filter(s=>!(o&&vd(s.captures[0].node))).map(s=>{let i=s.captures[0].node;return{source:i.text,startLine:i.startPosition.row+1}})}function vd(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 rn(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 xd=/^(addEventListener|removeEventListener|on|once|postMessage|onmessage|subscribe)$/i;function Bt(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&&xd.test(s))return!0}}else if(n.type==="function_declaration"||n.type==="method_definition")break;t=n}return!1}function Us(e,t){return ie(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:Ut(s),firstArgText:rn(s),deferred:Bt(s),callKind:pt(En(s)).kind}})}function zs(e,t){return ut(t)?wd(e):ie(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:rn(i.node),branchPath:Ut(i.node),deferred:Bt(i.node),callKind:pt(En(i.node)).kind}})}function wd(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=me(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:rn(s),branchPath:Ut(s),deferred:Bt(s),callKind:pt(En(s)).kind})}return t}function Sd(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 Ws(e,t){return ie(t,"returns.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(c=>c.name==="return_statement"),i=o.captures.find(c=>c.name==="return_value"),a=s.node;return{label:Sd(i?.node),startLine:a.startPosition.row+1,startColumn:a.startPosition.column,branchPath:Ut(a),deferred:Bt(a)}})}var kd=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 Ut(e){let t=[],n=e,r=e.startPosition;for(;n.parent;){let o=n.parent;if(kd.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"),c=o.childForFieldName("value");t.push({type:"switch",conditionText:a?a.text:"",conditionLine:(a??i).startPosition.row+1,outcome:o.type==="switch_default"?"default":c?c.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 Gs(e,t){return ie(t,"exports.scm").matches(e.rootNode).map(r=>r.captures[0].node.text)}var Os=new WeakMap;function Nd(e,t){let n=Os.get(e);return n||(n=ie(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}}),Os.set(e,n)),n}function qs(e,t,n){return Nd(e,t).filter(r=>r.stmtNode.startPosition.row+1>=n.startLine&&r.stmtNode.endPosition.row+1<=n.endLine).map(r=>({shape:bd(r.valueNode),condition:_d(r.stmtNode,n),line:r.stmtNode.startPosition.row+1}))}function bd(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 _d(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 Js(e,t){return nn(t)==="typescript"?[]:ie(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 Vs(e,t){return ie(t,"fetchApiCalls.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(l=>l.name==="url"),i=o.captures.find(l=>l.name==="http_method"),a=s.node.text,c=/^https?:\/\//.test(a)?"external":"internal";return{url:a,method:i?.node.text??"get",startLine:s.node.startPosition.row+1,scope:c}})}function Ys(e,t){return ie(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 Ks(e,t){return ie(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 Xs(e,t){return ie(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 Zs(e,t){return ie(t,"socketOn.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(c=>c.name==="event_name"),i=o.captures.find(c=>c.name==="handler_ref"),a=o.captures.find(c=>c.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 Qs(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,c=null,l=!1,d=null,f=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 h=r.childForFieldName("arguments")?.namedChildren?.[0];d=h&&h.type!=="arrow_function"&&h.type!=="function_expression"?h.text:null}else if(r.type==="decorator"){let u=r.namedChild(0);if(!u||u.type==="call_expression")continue;o="decorator",s=u.type==="member_expression"?u.childForFieldName("property")??u:u,i=u}else if(r.type==="call_expression"){let u=pt(r);if(u.oldShape)continue;if(o=u.kind,s=u.nameNode,i=r.childForFieldName("function")??r,o==="chainedCall"){let h=Rs(r);c=h.head,l=h.called;let p=r.childForFieldName("function"),m=p?.type==="member_expression"?me(p.childForFieldName("object")):null;m?.type==="member_expression"&&me(m.childForFieldName("object"))?.type==="this"&&m.childForFieldName("property")?.type==="property_identifier"&&p.childForFieldName("property")&&(f={thisProp:m.childForFieldName("property").text,thisMethod:p.childForFieldName("property").text})}d=rn(s)}else{let u=Ts(r);if(!u||u.oldShape)continue;o=u.kind,s=u.nameNode,i=u.nameNode}n.push({callKind:o,calleeName:As(i),startLine:s.startPosition.row+1,startColumn:s.startPosition.column,branchPath:Ut(s),firstArgText:d,deferred:Bt(s),chainHead:c,chainHeadCalled:l,ctorName:a,...f??{}})}return n.sort((r,o)=>r.startLine-o.startLine||r.startColumn-o.startColumn)}var Go=new Set(["get","post","put","patch","delete","head","options"]),qo=new Set(["axios","ky","got","superagent","$http"]),$d=new Set(["function_declaration","function_expression","function","arrow_function","method_definition","generator_function_declaration","generator_function"]),Id=new Set(["WebSocket","ReconnectingWebSocket","SockJS","W3CWebSocket"]),Jo=/^(ws|socket|sock|websocket|webSocket|wsClient|socketRef|wsRef|[A-Za-z]+Socket|[A-Za-z]+Ws|[A-Za-z]+WebSocket)$/,oe=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},sn=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 zt(e){for(let t=e.parent;t;t=t.parent)if($d.has(t.type))return t;return null}function ei(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 ti(e){let t=e.rootNode,n={httpCalls:[],pathCallsites:[],httpInstances:[],wsClients:[],wsServers:[],wsSends:[],wsServerSends:[],listens:[],wsReceivers:[]},r=new Map;for(let h of t.descendantsOfType("variable_declarator")){let p=h.childForFieldName("name"),m=h.childForFieldName("value");if(!p||p.type!=="identifier"||!m)continue;(r.get(p.text)??r.set(p.text,[]).get(p.text)).push({value:m,fn:zt(h)})}let o=(h,p)=>{let m=r.get(h);if(!m)return null;for(let g=zt(p);g;g=zt(g)){let x=m.filter(S=>S.fn&&S.fn.id===g.id);if(x.length===1)return x[0].value}let y=m.filter(g=>!g.fn);return y.length===1?y[0].value:m.length===1?m[0].value:null},s=(h,p)=>{for(let m=zt(p);m;m=zt(m)){let g=ei(m).params.indexOf(h);if(g>=0)return g}return-1};function i(h,p=0){if(h=oe(h),!h)return[{t:"ref",name:""}];switch(h.type){case"string":return[{t:"lit",v:sn(h)}];case"template_string":{let m=[];for(let y of h.namedChildren)y.type==="string_fragment"||y.type==="escape_sequence"?m.push({t:"lit",v:y.text}):y.type==="template_substitution"&&m.push(...i(y.namedChildren[0],p+1));return m.length?m:[{t:"lit",v:""}]}case"number":return[{t:"lit",v:h.text}];case"binary_expression":{let m=h.childForFieldName("operator")?.text;if(m==="||"||m==="??"){let y=i(h.childForFieldName("left"),p+1);if(y.length===1&&y[0].t==="env")return[{...y[0],fallback:i(h.childForFieldName("right"),p+1)}]}return m!=="+"?[{t:"ref",name:h.text.slice(0,60)}]:[...i(h.childForFieldName("left"),p+1),...i(h.childForFieldName("right"),p+1)]}case"shorthand_property_identifier":case"identifier":{let m=h.text,y=s(m,h);if(y>=0)return[{t:"param",name:m,index:y}];if(p<4){let g=o(m,h);if(g&&g.id!==h.id)return i(g,p+1)}return[{t:"ref",name:m}]}case"member_expression":{let m=h.text,y=/^(?:process\.env|import\.meta\.env)\.([A-Za-z0-9_$]+)$/.exec(m)??/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(m);return y?[{t:"env",name:y[1]}]:[{t:"ref",name:m.slice(0,60)}]}case"subscript_expression":{let m=/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(h.text);return m?[{t:"env",name:m[1]}]:[{t:"ref",name:h.text.slice(0,60)}]}case"call_expression":{let m=h.childForFieldName("function")?.text,y=h.childForFieldName("arguments")?.namedChildren[0];if(y&&(m==="encodeURIComponent"||m==="String"||m==="encodeURI"))return i(y,p+1);let g=oe(h.childForFieldName("function"));if(g&&g.type==="member_expression"&&/^(replace|replaceAll|trim|trimEnd|trimStart|toString|toLowerCase)$/.test(g.childForFieldName("property")?.text??"")){let x=g.childForFieldName("object");if(x){let S=i(x,p+1);if(S.length&&S.every(k=>k.t!=="ref"))return S}}return[{t:"ref",name:h.text.slice(0,60)}]}default:return[{t:"ref",name:h.text.slice(0,60)}]}}let a=(h,p)=>{if(h=oe(h),!(!h||h.type!=="object")){for(let m of h.namedChildren)if(m.type==="pair"){let y=m.childForFieldName("key");if((y?y.type==="string"?sn(y):y.text:null)===p)return m.childForFieldName("value")}else if(m.type==="shorthand_property_identifier"&&m.text===p)return m}},c=h=>h.childForFieldName("arguments")?.namedChildren.filter(p=>p.type!=="comment")??[],l=h=>{if(!h)return null;let p=i(h);return p.length===1&&p[0].t==="lit"?p[0].v.toUpperCase():p.length===1&&p[0].t==="param"?{param:p[0].index}:"?"},d=(h,p,m,y)=>({client:h,method:p,parts:m,line:y.startPosition.row+1,fn:ei(zt(y))});for(let h of t.descendantsOfType("variable_declarator")){let p=h.childForFieldName("name"),m=oe(h.childForFieldName("value"));if(!p||p.type!=="identifier"||!m||m.type!=="call_expression")continue;let y=oe(m.childForFieldName("function"));if(!y||y.type!=="member_expression")continue;let g=y.childForFieldName("object")?.text,x=y.childForFieldName("property")?.text;if(!(qo.has(g)&&(x==="create"||x==="extend")))continue;let S=c(m)[0],k=a(S,"baseURL")??a(S,"baseUrl")??a(S,"prefixUrl")??a(S,"prefix_url");n.httpInstances.push({name:p.text,parts:k?i(k):[],line:h.startPosition.row+1})}let f=new Set(n.httpInstances.map(h=>h.name));for(let h of t.descendantsOfType("call_expression")){let p=oe(h.childForFieldName("function"));if(!p)continue;let m=c(h),y=!1;if(p.type==="identifier"){let g=p.text;if(g==="fetch"&&m[0]){let x=oe(m[0]);if(x&&x.type==="new_expression")continue;let S=a(m[1],"method");n.httpCalls.push(d("fetch",S?l(S):m[1]&&oe(m[1])?.type!=="object"?"?":"GET",i(m[0]),h)),y=!0}else if((qo.has(g)||f.has(g))&&m[0]){let x=oe(m[0]);if(x&&x.type==="object"){let S=a(x,"url");if(S){let k=a(x,"baseURL");n.httpCalls.push(d(f.has(g)?"inst:"+g:g,l(a(x,"method"))??"GET",[...k?i(k):[],...i(S)],h)),y=!0}}else n.httpCalls.push(d(f.has(g)?"inst:"+g:g,m[1]&&a(m[1],"method")?l(a(m[1],"method")):"GET",i(m[0]),h)),y=!0}else g==="io"&&m[0]&&(n.wsClients.push({client:"io",parts:i(m[0]),line:h.startPosition.row+1}),y=!0)}else if(p.type==="member_expression"){let x=p.childForFieldName("object")?.text??"",S=p.childForFieldName("property")?.text??"",k=qo.has(x)||f.has(x);if(k&&Go.has(S)&&m[0])n.httpCalls.push(d(f.has(x)?"inst:"+x:x,S.toUpperCase(),i(m[0]),h)),y=!0;else if(!k&&Go.has(S)&&/^[A-Za-z_$][\w$]*$/.test(x)&&m[0]&&(oe(m[0])?.type==="string"||oe(m[0])?.type==="template_string")){let v=i(m[0]);v[0]?.t==="lit"&&(v[0].v.startsWith("/")||/^https?:\/\//.test(v[0].v))&&(n.httpCalls.push(d("obj:"+x,S.toUpperCase(),v,h)),y=!0)}else if(k&&S==="request"&&m[0]){let v=a(m[0],"url");if(v){let w=a(m[0],"baseURL");n.httpCalls.push(d(f.has(x)?"inst:"+x:x,l(a(m[0],"method"))??"GET",[...w?i(w):[],...i(v)],h)),y=!0}}else if(S==="open"&&m.length>=2&&oe(m[0])?.type==="string"&&/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/i.test(sn(oe(m[0]))))n.httpCalls.push(d("xhr",sn(oe(m[0])).toUpperCase(),i(m[1]),h)),y=!0;else if(x==="io"&&S==="connect"&&m[0])n.wsClients.push({client:"io",parts:i(m[0]),line:h.startPosition.row+1}),y=!0;else if(S==="listen"&&m[0]){let v=oe(m[0]),w=v&&v.type==="object"?a(v,"port"):v;w&&n.listens.push({parts:i(w),line:h.startPosition.row+1}),y=!0}else if(S==="send"&&/^(client|conn|connection|peer)$/.test(x.replace(/^this./,"").split(".").pop())&&m[0]){let v=oe(m[0]),w=!1;if(v&&v.type==="call_expression"&&v.childForFieldName("function")?.text==="JSON.stringify"){let b=c(v)[0];w=!!(b&&(a(b,"type")||a(b,"event"))&&oe(a(b,"type")??a(b,"event"))?.type==="string")}w||n.wsServerSends.push({recv:x,line:h.startPosition.row+1}),y=!0}else if(S==="send"&&Jo.test(x.replace(/^this\./,"").replace(/\.current$/,"").split(".").pop())){let v=m[0]?oe(m[0]):null,w=!1;if(v&&v.type==="call_expression"&&v.childForFieldName("function")?.text==="JSON.stringify"){let b=c(v)[0];w=!!(b&&(a(b,"type")||a(b,"event"))&&oe(a(b,"type")??a(b,"event"))?.type==="string")}w||n.wsSends.push({recv:x,line:h.startPosition.row+1}),y=!0}}if(!y){let g=null;if(p.type==="identifier"?g=p.text:p.type==="member_expression"&&(g=p.childForFieldName("property")?.text??null),!g||Go.has(g)||m.length===0||m.length>6)continue;let x=[],S=!1;m.slice(0,5).forEach((k,v)=>{let w=oe(k);if(!w||w.type!=="string"&&w.type!=="template_string")return;let b=i(w);x.push({i:v,parts:b});let N=b[0];N&&N.t==="lit"&&(N.v.startsWith("/")||/^https?:\/\//.test(N.v))&&N.v.length>1&&(S=!0)}),S&&n.pathCallsites.push({callee:g,args:x,line:h.startPosition.row+1})}}let u=h=>h.replace(/^this./,"").replace(/.current$/,"").split(".").pop();for(let h of t.descendantsOfType("assignment_expression")){let p=h.childForFieldName("left");if(!p||p.type!=="member_expression"||p.childForFieldName("property")?.text!=="onmessage"||!Jo.test(u(p.childForFieldName("object")?.text??"")))continue;let m=oe(h.childForFieldName("right"));n.wsReceivers.push({line:h.startPosition.row+1,handlerName:m&&m.type==="identifier"?m.text:null})}for(let h of t.descendantsOfType("call_expression")){let p=oe(h.childForFieldName("function"));if(!p||p.type!=="member_expression"||p.childForFieldName("property")?.text!=="addEventListener")continue;let m=c(h),y=m[0]&&oe(m[0]);if(!y||y.type!=="string"||sn(y)!=="message"||!Jo.test(u(p.childForFieldName("object")?.text??"")))continue;let g=m[1]&&oe(m[1]);n.wsReceivers.push({line:h.startPosition.row+1,handlerName:g&&g.type==="identifier"?g.text:null})}for(let h of t.descendantsOfType("new_expression")){let p=oe(h.childForFieldName("constructor"));if(!p)continue;let m=p.text,y=c(h);if(Id.has(m)&&y[0])n.wsClients.push({client:m,parts:i(y[0]),line:h.startPosition.row+1});else if(/^(WebSocketServer|WebSocket\.Server|WebSocket\.WebSocketServer|ws\.Server|ws\.WebSocketServer|Server)$/.test(m)){if(m==="Server"&&!/socket\.io|socketio/i.test(e.rootNode.text.slice(0,4e3)+""))continue;let g=a(y.find(x=>oe(x)?.type==="object"),"path");n.wsServers.push({path:g?i(g):null,line:h.startPosition.row+1})}}return n}var jd=new Set(["function_declaration","generator_function_declaration","function_expression","generator_function","arrow_function","method_definition"]),Cd=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 Fd(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=me(r.childForFieldName("value"));return i&&Cd.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 Ed(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 ni(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(c=>c.type==="identifier"),a=r.namedChildren.find(c=>c.type==="string");i&&a&&t.push({source:an(a),kind:"cjs",local:i.text,imported:null});continue}let{src:o,out:s}=Ed(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=me(r.childForFieldName("value")),s=null;o?.type==="member_expression"&&(s=o.childForFieldName("property")?.text??null,o=me(o.childForFieldName("object")));let i=Ln(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 c of a.namedChildren)if(c.type==="shorthand_property_identifier_pattern")t.push({source:i,kind:"named",local:c.text,imported:c.text});else if(c.type==="pair_pattern"){let l=c.childForFieldName("key"),d=c.childForFieldName("value");l&&d?.type==="identifier"&&t.push({source:i,kind:"named",local:d.text,imported:l.text})}}}return t}var an=e=>e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("");function Ln(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"?an(r):null}function oi(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:an(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:an(o),startLine:o.startPosition.row+1})}else if(r.type==="call_expression"){let o=Ln(r);o!=null&&t.push({source:o,startLine:r.startPosition.row+1})}for(let o of r.namedChildren)n(o)})(e.rootNode),t}function ri(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=me(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(l=>l.type==="type"))continue;let i=an(n.childForFieldName("source")),a=n.namedChildren.find(l=>l.type==="export_clause"),c=n.namedChildren.find(l=>l.type==="namespace_export");if(a)for(let l of a.namedChildren){if(l.type!=="export_specifier")continue;let d=l.childForFieldName("name")?.text,f=l.childForFieldName("alias")?.text;d&&t.reexports.push({exported:f??d,imported:d,source:i})}else if(c){let l=c.namedChildren.find(d=>d.type==="identifier");l&&t.nsReexports.push({exported:l.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 c=a.childForFieldName("name")?.text,l=a.childForFieldName("alias")?.text;c&&(l==="default"?t.default=c:t.named[l??c]=c)}}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=me(r.childForFieldName("right"));if(o?.type!=="member_expression")continue;let i=o.childForFieldName("object"),a=o.childForFieldName("property")?.text,c=l=>l?.type==="member_expression"&&l.childForFieldName("object")?.text==="module"&&l.childForFieldName("property")?.text==="exports";if(c(o))if(s?.type==="identifier")t.default=s.text;else if(s?.type==="object"){for(let l of s.namedChildren)if(l.type==="shorthand_property_identifier")t.named[l.text]=l.text;else if(l.type==="pair"){let d=l.childForFieldName("key"),f=me(l.childForFieldName("value"));d&&f?.type==="identifier"&&(t.named[d.text.replace(/^['"]|['"]$/g,"")]=f.text)}t.default??="<object>"}else Ln(s)!=null?t.stars.push(Ln(s)):t.default="<anon>";else a&&(i?.type==="identifier"&&i.text==="exports"||c(i))&&s?.type==="identifier"&&(t.named[a]=s.text)}return t}function Pd(e,t,n){for(let r=e.parent;r;r=r.parent)if(jd.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=Fd(o,t);if(s)return s}if(r.type==="program"&&n.has(t))return{kind:"import",imp:n.get(t)}}return null}var Ld=e=>(e.childForFieldName("function")?.text??"").replace(/\s+/g," ").slice(0,40);function si(e,t){let n=new Map(t.map(s=>[s.local,s])),r=[],o=(s,i,a)=>{let c=me(s);if(!c||c.type!=="identifier"&&c.type!=="shorthand_property_identifier")return;let l=c.text,d=Pd(c,l,n);if(!d||d.kind==="other")return;let f=pt(a).nameNode,u={name:l,line:c.startPosition.row+1,column:c.startPosition.column,via:i,callee:Ld(a),callLine:f.startPosition.row+1,callColumn:f.startPosition.column,b:d.kind};d.kind==="fn"?u.declLine=d.declLine:(u.src=d.imp.source,u.ik=d.imp.kind,u.imp=d.imp.imported),r.push(u)};return(function s(i){if(i.type==="call_expression"){let a=i.childForFieldName("arguments");for(let c of a?.namedChildren??[]){let l=me(c);if(l)if(l.type==="array")for(let d of l.namedChildren)o(d,"array",i);else if(l.type==="object")for(let d of l.namedChildren)d.type==="pair"?o(d.childForFieldName("value"),"object",i):d.type==="shorthand_property_identifier"&&o(d,"object",i);else o(l,"arg",i)}}for(let a of i.namedChildren)s(a)})(e.rootNode),r}function ii(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 c=a.childForFieldName("name"),l=n(a.childForFieldName("type"));c?.type==="property_identifier"&&l&&t.push({className:s,prop:c.text,type:l})}else if(a.type==="method_definition"&&a.childForFieldName("name")?.text==="constructor")for(let c of a.childForFieldName("parameters")?.namedChildren??[]){if(c.type!=="required_parameter"&&c.type!=="optional_parameter"||!c.namedChildren.some(f=>f.type==="accessibility_modifier")&&!c.children.some(f=>f.type==="readonly"))continue;let l=c.childForFieldName("pattern"),d=n(c.childForFieldName("type"));l?.type==="identifier"&&d&&t.push({className:s,prop:l.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 Td={Get:"get",Post:"post",Put:"put",Patch:"patch",Delete:"delete",All:"all"};function ai(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 bt=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 ci(e){let t=e?.namedChildren.find(n=>n.type!=="comment");if(!t)return"";if(t.type==="array")return bt(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"?bt(o.namedChildren[0]):bt(o))??""}}return""}return bt(t)??""}var Tn=(...e)=>"/"+e.map(n=>String(n??"").replace(/^\/+|\/+$/g,"")).filter(Boolean).join("/");function li(e){let t=[],n=(r,o)=>{let s=r.childForFieldName("name")?.text,i=r.childForFieldName("body");if(!s||!i)return;let c=[...o,...r.namedChildren.filter(f=>f.type==="decorator")].map(ai).filter(Boolean).find(f=>f.name==="Controller");if(!c)return;let l=ci(c.args),d=[];for(let f of i.namedChildren)if(f.type!=="comment"){if(f.type==="decorator"){d.push(f);continue}if(f.type==="method_definition"){let u=f.childForFieldName("name")?.text;for(let h of d.map(ai).filter(Boolean)){let p=Td[h.name];!p||!u||t.push({method:p,path:Tn(l,ci(h.args)),startLine:f.startPosition.row+1,handlerName:null,isInlineHandler:!1,handlerStartLine:null,handlerEndLine:null,handlerStartIndex:null,handlerEndIndex:null,nest:{className:s,methodName:u}})}}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 di(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(l=>l.type!=="comment"),i=s[0]?bt(s[0]):null,a=[],c=s[1];if(c?.type==="object")for(let l of c.namedChildren){if(l.type!=="pair"||l.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")!=="exclude")continue;let d=l.childForFieldName("value");for(let f of d?.type==="array"?d.namedChildren:[])if(f.type==="object"){for(let u of f.namedChildren)if(u.type==="pair"&&u.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")==="path"){let h=bt(u.childForFieldName("value"));h!=null&&a.push(h)}}else{let u=bt(f);u!=null&&a.push(u)}}t.push({prefix:i||null,exclude:a})}}for(let o of r.namedChildren)n(o)})(e.rootNode),t}function fi(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=>Tn(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(Tn(a.path))?{...a,path:Tn(n,a.path)}:a)})}return o}import Rd from"node:crypto";var ui=e=>Rd.createHash("sha256").update(e).digest("hex");function Ad(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 pi(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 Ad(e.rootNode,e.canopyOriginalSource??null)){let i=null,a=1/0;for(let c of n)s.s>=c.s&&s.e<=c.e&&c.e-c.s<a&&(i=c,a=c.e-c.s);(i?r.get(i):o).push(s.t)}for(let s of n)s.item[s.field]=ui(r.get(s).join(" "));t.moduleBodyHash=ui(o.join(" "))}function mi(e,t){return ie(t,"matchFastifyRoutes.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(l=>l.name==="http_method"),i=o.captures.find(l=>l.name==="route_path"),a=o.captures.find(l=>l.name==="handler_ref"),c=o.captures.find(l=>l.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:!!c,handlerStartLine:c?c.node.startPosition.row+1:null,handlerEndLine:c?c.node.endPosition.row+1:null,handlerStartIndex:c?c.node.startIndex:null,handlerEndIndex:c?c.node.endIndex:null}})}function hi(e,t){return ie(t,"matchExtensionListeners.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(p=>p.name==="event_type"),i=o.captures.find(p=>p.name==="event_name"),a=o.captures.find(p=>p.name==="method_name"||p.name==="listener_method"),c=o.captures.find(p=>p.name==="handler_ref"),l=o.captures.find(p=>p.name==="target"),d=o.captures.find(p=>p.name==="root_object"),f=o.captures.find(p=>p.name==="sub_object"),u=l?l.node.text:d?d.node.text+(f?"."+f.node.text:""):null,h=o.captures.find(p=>p.name==="handler_inline");return{eventName:s?.node.text??i?.node.text??"unknown",targetName:u,startLine:a.node.startPosition.row+1,handlerName:c?c.node.text:null,isInlineHandler:!!h,handlerStartLine:h?h.node.startPosition.row+1:null,handlerEndLine:h?h.node.endPosition.row+1:null,handlerStartIndex:h?h.node.startIndex:null,handlerEndIndex:h?h.node.endIndex:null}})}import Bd from"node:fs";We();import Ge from"node:fs";import de from"node:path";import Od from"node:os";import yi from"node:crypto";import{fileURLToPath as Md}from"node:url";var Hd=de.dirname(Md(globalThis.__canopyUrl("src/stage2_parse/parseCache.js"))),vi=de.join(Hd,"..",".."),Vo=process.env.CANOPY_CACHE_DIR||(Dt()?de.join(Od.homedir(),".canopy-cache"):de.join(vi,".canopy-cache")),gi=e=>yi.createHash("sha256").update(e).digest("hex");function Rn(e,t){return Ge.readdirSync(e,{withFileTypes:!0}).flatMap(n=>n.isDirectory()?Rn(de.join(e,n.name),t):t.some(r=>n.name.endsWith(r))?[de.join(e,n.name)]:[]).sort()}var Yo=null;function Dd(){if(Yo)return Yo;let e=de.join(vi,"src"),t=!Ge.existsSync(e)&&globalThis.__canopyBundle,n=t?[t,...Rn(de.join(de.dirname(t),"queries"),[".scm"])]:[...Rn(de.join(e,"stage2_parse"),[".js",".scm"]),...Rn(de.join(e,"stage5_entrypoints"),[".js"]).filter(o=>/match/i.test(de.basename(o))),de.join(e,"utils","loadQuery.js")],r=yi.createHash("sha256");for(let o of n)r.update(de.relative(t?de.dirname(t):e,o).split(de.sep).join("/")).update("\0").update(Ge.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(Ge.readFileSync(de.join(He(o),"package.json"),"utf8")).version)}catch{r.update(o+"@?")}return Yo=r.digest("hex").slice(0,16)}function xi(){let e=Dd(),t=de.join(Vo,e);Ge.mkdirSync(t,{recursive:!0});for(let n of Ge.readdirSync(Vo,{withFileTypes:!0}))n.isDirectory()&&n.name!==e&&Ge.rmSync(de.join(Vo,n.name),{recursive:!0,force:!0});return{version:e,keyFor:(n,r="javascript")=>gi(r==="javascript"?n:Buffer.concat([Buffer.from(r+"\0"),n])),get(n){try{return JSON.parse(Ge.readFileSync(de.join(t,n+".json"),"utf8"))}catch{return null}},set(n,r){let o=de.join(t,`${n}.${process.pid}.tmp`);Ge.writeFileSync(o,JSON.stringify(r)),Ge.renameSync(o,de.join(t,n+".json"))}}}function wi(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 Si=Number(process.env.CANOPY_PARSE_BUDGET_MS)||3e4,Xo=class extends Error{constructor(t){super(`parse time budget exceeded (limit ${Si/1e3} s; stopped after ${(t/1e3).toFixed(1)} s)`),this.name="ParseBudgetError"}},Ud=100;function Ko(e,t,n){return e.map(r=>({...r,returns:qs(t,n,r)}))}function ki(e,t,n,{cache:r=!0,onProgress:o=console.log,grammars:s=null,noCache:i=!1}={}){let a=new Map,c=0,l=0,d=0,f=r?xi():null,u=!i,h=[],p=0;for(let m of e){p>0&&p%Ud===0&&o(` parsing: ${p}/${e.length} files (${d} from cache)`),p++;let y=null;try{let g=Bd.readFileSync(m),x=Uo(m),S=f?.keyFor(g,x),k=f&&u?f.get(S):null;if(k){a.set(m,k),d++;continue}l++;let v=performance.now(),w=()=>{let C=performance.now()-v;if(C>Si)throw new Xo(C)},b=x==="javascript"?{parser:t,language:n}:s?.get(x);if(!b)throw new Error(`no ${x} grammar loaded`);let N=b.language;Ls(x),y=js(b.parser,m).tree,w();let $=[],j=(C,R,W=[])=>{try{return R()}catch(K){if(K.name==="ParseBudgetError")throw K;return $.push({extractor:C,message:String(K.message).slice(0,160)}),W}},O=j("functionDeclarations",()=>Ko(Ms(y,N),y,N));w();let D=j("arrowFunctions",()=>Ko(Hs(y,N),y,N));w();let G=j("classMethods",()=>Ko(Ds(y,N),y,N));w();let M=j("importBindings",()=>ni(y)),q={functions:O,arrowFunctions:D,classMethods:G,imports:j("imports",()=>[...Bs(y,N),...oi(y)]),calls:(w(),j("calls",()=>Us(y,N))),methodCalls:(w(),j("methodCalls",()=>zs(y,N))),returnEntries:j("returnEntries",()=>Ws(y,N)),jsxElements:j("jsxElements",()=>Js(y,N)),callSites:(w(),j("callSites",()=>Qs(y))),apiCalls:(w(),j("apiCalls",()=>Vs(y,N))),socketEmits:j("socketEmits",()=>Ys(y,N)),socketListeners:j("socketListeners",()=>Zs(y,N)),rawSocketSends:j("rawSocketSends",()=>Ks(y,N)),rawSocketTypeChecks:j("rawSocketTypeChecks",()=>Xs(y,N)),routes:j("routes",()=>[...mi(y,N),...ut(N)?li(y):[]]),listeners:j("listeners",()=>hi(y,N)),refArgs:j("refArgs",()=>si(y,M)),globalPrefix:j("globalPrefix",()=>di(y)),importBindings:M,classProps:j("classProps",()=>ut(N)?ii(y):[]),httpClients:j("httpClients",()=>ti(y),null),exportBindings:j("exportBindings",()=>ri(y),null),hadErrors:zo(y),exportedNames:j("exports",()=>Gs(y,N)),failed:!1,warnings:$};j("bodyHash",()=>pi(y,q),null);let E=wi(q);f&&f.set(S,E),a.set(m,E)}catch(g){if(g.name==="ParseBudgetError"){h.push({filePath:m,reason:g.message}),a.set(m,{functions:[],arrowFunctions:[],classMethods:[],imports:[],calls:[],methodCalls:[],returnEntries:[],jsxElements:[],callSites:[],apiCalls:[],socketEmits:[],socketListeners:[],rawSocketSends:[],rawSocketTypeChecks:[],routes:[],listeners:[],hadErrors:!1,failed:!1,skipped:g.message}),console.warn(` ! Skipped ${m}: ${g.message}`);continue}c++,a.set(m,{functions:[],arrowFunctions:[],classMethods:[],imports:[],calls:[],methodCalls:[],returnEntries:[],jsxElements:[],callSites:[],apiCalls:[],socketEmits:[],socketListeners:[],rawSocketSends:[],rawSocketTypeChecks:[],routes:[],listeners:[],hadErrors:!0,failed:!0,errorMessage:g.message}),console.warn(` ! Failed to parse ${m}: ${g.message}`)}finally{if(y){try{y.delete()}catch{}y=null}}}return console.log(`Parsed ${a.size} files (${c} failed)`),console.log(` parse cache: ${l} file(s) parsed, ${d} served from cache`),a.cacheStats={parsed:l,cacheHits:d},a.budgetSkips=h,a}function An(e,t){return`${e}::${t}`}var Ni=[{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 On(e){let t=e.toLowerCase().replace(/\\/g,"/");for(let{category:n,patterns:r}of Ni)for(let o of r)if(t.includes(o))return n;return"unknown"}import Zo from"node:fs";import Se from"node:path";import Mn from"node:fs";import et from"node:path";var zd=["index.html","public/index.html","src/index.html"],Wd=/^(build|esbuild|vite\.config|webpack\.config|rollup\.config|bundle)[\w.-]*\.(mjs|cjs|js|ts)$/i;function Gd(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 qd(e){let t=[],n=[];try{n=Mn.readdirSync(e).filter(r=>Wd.test(r)).sort()}catch{return t}for(let r of n){let o;try{o=Mn.readFileSync(et.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 Hn(e,t,n=new Set(t.map(r=>et.resolve(r)))){for(let r of zd){let o=et.join(e,r);if(!Mn.existsSync(o))continue;let s;try{s=Mn.readFileSync(o,"utf8")}catch{continue}let i=et.dirname(o),a=d=>{let f=d.split(/[?#]/)[0];return!f||/^([a-z]+:)?\/\//i.test(f)?null:et.resolve(f.startsWith("/")?et.join(e,f):et.join(i,f))},c=Gd(s).map(d=>({s:d,p:a(d)})).filter(d=>d.p);for(let{s:d,p:f}of c)if(n.has(f))return{indexHtml:o,script:d,entry:f,via:"script"};let l=qd(e);for(let{s:d,p:f}of c)for(let u of l){if(!u.outfile||et.resolve(e,u.outfile)!==f)continue;let h=et.resolve(e,u.entry);if(n.has(h))return{indexHtml:o,script:d,entry:h,via:`${u.config} (outfile ${u.outfile})`}}}return null}var Jd=new Set(["test","tests","__tests__","fixtures","__fixtures__","__mocks__","e2e","cypress"]);function Wt(e){let t=String(e).replace(/\\/g,"/").split("/").filter(Boolean);if(!t.length)return!1;for(let n of t.slice(0,-1))if(Jd.has(n.toLowerCase()))return!0;return/\.(test|spec)\.[^./]+$/i.test(t[t.length-1])}function Vd(e){let t=Se.join(e,"package.json");if(!Zo.existsSync(t))return null;try{return JSON.parse(Zo.readFileSync(t,"utf-8"))}catch{return null}}function Yd(e){return[...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{})]}function Kd(e){let t=!!e.workspaces,n=Object.keys(e.dependencies??{}).length>0,r=!!(e.scripts&&e.scripts.start);return t&&!n&&!r}var Xd=["react","vue","svelte","next","vite","webpack","parcel"],Zd=["express","fastify","koa","hapi","socket.io","ws"],Qd=[{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 ef(e){let t=e.some(r=>Xd.includes(r)),n=e.some(r=>Zd.includes(r));return t&&!n?"client":n&&!t||n&&t?"server":"unknown"}function tf(e){let t=[];for(let{deps:n,label:r}of Qd)n.some(o=>e.includes(o))&&!t.includes(r)&&t.push(r);return t}function bi(e){let t=new Set(["node_modules",".git","dist","build",".next","coverage"]);try{return Zo.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!t.has(n.name)&&!n.name.startsWith(".")).map(n=>Se.join(e,n.name))}catch{return[]}}function _i(e,t=null){let n=[e];for(let o of bi(e)){n.push(o);for(let s of bi(o))n.push(s)}let r=[];for(let o of n){let s=Vd(o);if(!s||Kd(s))continue;let i=Yd(s);r.push({name:s.name||Se.basename(o),rootPath:o,isRepoRoot:Se.resolve(o)===Se.resolve(e),kind:ef(i),datastores:tf(i)})}if(t){let o=new Set(t.map(i=>Se.resolve(i))),s=new Set(r.map(i=>Se.resolve(i.rootPath)));for(let i of n)Se.resolve(i)===Se.resolve(e)||s.has(Se.resolve(i))||Wt(Se.relative(e,i)+"/x")||Hn(i,t,o)&&r.push({name:Se.basename(i),rootPath:i,isRepoRoot:!1,kind:"client",datastores:[],webRoot:!0})}return r}function _t(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+Se.sep))&&o.rootPath.length>r&&(n=o.name,r=o.rootPath.length);return n}var nf=5,of=.1;function $i(e,t,n){let r=Se.basename(Se.resolve(n)),o=c=>({name:c,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(c=>!_t(c,e)).length;if(s<nf||s<of*t.length)return{services:e,added:null,leftover:s};let i=e.find(c=>c.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(c=>c.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 Ii(e,t=[]){let n=[];for(let[r,o]of e){let s=On(r),i=_t(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:An(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:An(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:An(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 qe(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 ji(e,t=[]){let n=[];for(let[r,o]of e){let s=On(r),i=_t(r,t),a=t.find(l=>l.name===i),c=qe(r,o);for(let l of o.routes??[]){if(!l.isInlineHandler)continue;let d=`${l.method.toUpperCase()} ${l.path}`;n.push({id:c.get(l),name:`${d} (inline handler)`,filePath:r,startLine:l.handlerStartLine??l.startLine,endLine:l.handlerEndLine??l.startLine,category:s,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:l.handlerBodyHash??null,trigger:{type:"route",label:d,resolvedVia:"inline"}})}for(let l of o.listeners??[])l.isInlineHandler&&n.push({id:c.get(l),name:`${l.eventName} (inline handler)`,filePath:r,startLine:l.handlerStartLine??l.startLine,endLine:l.handlerEndLine??l.startLine,category:s,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:l.handlerBodyHash??null,trigger:{type:"listener",label:l.eventName,resolvedVia:"inline"}});if(a?.kind==="server")for(let l of o.socketListeners??[])l.isInlineHandler&&n.push({id:c.get(l),name:`${l.eventName} (inline handler)`,filePath:r,startLine:l.handlerStartLine??l.startLine,endLine:l.handlerEndLine??l.startLine,category:s,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:l.handlerBodyHash??null,trigger:{type:"socketListener",label:l.eventName,resolvedVia:"inline"}})}return n}import rf from"node:fs";import sf from"node:crypto";var Ci=e=>sf.createHash("sha256").update(e).digest("hex");function Fi(e,t){return e.map(n=>[t(n),Ci(rf.readFileSync(n))]).sort((n,r)=>n[0]<r[0]?-1:n[0]>r[0]?1:0)}function Dn(e){return Ci(e.map(([t,n])=>`${t}\0${n}`).join(`
18
+ `))}import Qo from"node:path";function Bn(e){let t=Qo.resolve(e),n=t.split(Qo.sep).join("/"),r=[[t.toLowerCase(),t.length,Qo.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,c,l]of r)if(i.startsWith(a+l)){let d=s.slice(c+1),f=d.indexOf("::");return(f<0?d:d.slice(0,f)).split("\\").join("/")+(f<0?"":d.slice(f))}return s};return{rel:o,repoRoot:n,replacer:(s,i)=>typeof i=="string"?o(i):i,json:(s,i)=>JSON.stringify(s,(a,c)=>typeof c=="string"?o(c):c,i),clone:s=>JSON.parse(JSON.stringify(s,(i,a)=>typeof a=="string"?o(a):a))}}function Ei(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 Pi(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 ge(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 Li(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 c=ge(a.startLine,i);n.push({fromFileId:o,fromNodeId:c?.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 c=ge(a.startLine,i);n.push({fromFileId:o,fromNodeId:c?.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 c=ge(a.startLine,i);n.push({fromFileId:o,fromNodeId:c?.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 c=ge(a.startLine,i);n.push({fromFileId:o,fromNodeId:c?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,type:"call",callKind:"jsx",resolved:!1})}for(let a of s.callSites??[]){let c=ge(a.startLine,i);n.push({fromFileId:o,fromNodeId:c?.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 c=ge(a.startLine,i);n.push({fromFileId:o,fromNodeId:c?.id??null,eventName:a.eventName,line:a.startLine,type:"socketEmit",resolved:!1})}for(let a of s.rawSocketSends??[]){let c=ge(a.startLine,i);n.push({fromFileId:o,fromNodeId:c?.id??null,eventName:a.eventName,line:a.startLine,type:"rawSocketSend",resolved:!1})}for(let a of s.apiCalls){let c=ge(a.startLine,i);n.push({fromFileId:o,fromNodeId:c?.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 he(e,t){let n=new Map;for(let r of t)r.filePath===e&&n.set(r.name,r.id);return n}function cn(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=([,l])=>{let d=o?o.scopeOf(l):he(l,t);return d.has(e.calleeNameRaw)?{...e,targetNodeId:d.get(e.calleeNameRaw),confidence:.85,matchType:"import",resolved:!0}:null};for(let l=0;l<i;l++){let d=a(s[l]);if(d)return d}let c=o?.bind?.resolveName(e.fromFileId,e.calleeNameRaw);if(c)return{...e,targetNodeId:c.id,confidence:.85,matchType:"import",resolved:!0};for(let l=i;l<s.length;l++){let d=a(s[l]);if(d)return d}return{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function Ti(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 Ri(e){return{...e,targetNodeId:null,confidence:0,matchType:"unresolvedExternal",resolved:!1}}function Ai(e,t,n,r,o=null){if(e.callKind==="new"&&e.ctorName){let s=cn({...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(c=>i.has(c.filePath)):t.find(c=>c.type==="classMethod"&&c.className===e.ctorName&&c.name==="constructor"&&i.has(c.filePath));return a?{...e,targetNodeId:a.id,confidence:a.filePath===e.fromFileId?.9:.8,matchType:(a.filePath===e.fromFileId?"local":"import")+"New",resolved:!0}:Ri(e)}if(e.callKind==="chainedCall"&&e.chainHead&&e.chainHeadCalled){let s=cn({...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 Ri(e)}import tr from"node:path";import tt from"node:fs";import Y from"node:path";var Di=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],af=["index.ts","index.tsx","index.mts","index.cts","index.js","index.jsx","index.mjs","index.cjs"],cf={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]};var Bi=null,Ui=e=>{Bi=e},zi=()=>Bi,Oi=e=>Y.resolve(e);function ln(e,t){e=Y.resolve(e);let n=()=>{try{let i=Y.join(e,"package.json");if(!tt.existsSync(i))return null;let a=JSON.parse(tt.readFileSync(i,"utf8")).main;if(typeof a!="string")return null;let c=Y.resolve(e,a);return t.has(c)?c:lf(c,t)}catch{return null}},r=Y.extname(e);if(r&&t.has(e))return e;let o=cf[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 Di)if(t.has(e+i))return e+i;let s=n();if(s)return s;for(let i of af){let a=Y.join(e,i);if(t.has(a))return a}return null}function lf(e,t){if(Y.extname(e)&&t.has(e))return e;for(let r of Di)if(t.has(e+r))return e+r;return null}var er=e=>{try{let n=tt.readFileSync(e,"utf8").replace(/^/,"").replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,(r,o)=>o??"");return JSON.parse(n.replace(/,(\s*[}\]])/g,"$1"))}catch{return null}};function Wi(e,t=new Set){if(t.has(e))return{baseUrl:null,paths:null};t.add(e);let n=er(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 c=Y.resolve(Y.dirname(e),a);(!tt.existsSync(c)||tt.statSync(c).isDirectory())&&(c=tt.existsSync(c+".json")?c+".json":Y.join(c,"tsconfig.json"));let l=Wi(c,t);l.baseUrl&&(r=l.baseUrl),l.paths&&(o=l.paths)}let i=n.compilerOptions??{};if(typeof i.baseUrl=="string"&&(r=Y.resolve(Y.dirname(e),i.baseUrl)),i.paths&&typeof i.paths=="object"){let a=r??Y.dirname(e);o=Object.entries(i.paths).map(([c,l])=>{let d=c.indexOf("*");return{prefix:d<0?c:c.slice(0,d),suffix:d<0?"":c.slice(d+1),wildcard:d>=0,targets:(Array.isArray(l)?l:[]).filter(f=>typeof f=="string").map(f=>Y.resolve(a,f))}}).sort((c,l)=>l.prefix.length-c.prefix.length)}return{baseUrl:r,paths:o}}function df(e,t){if(t=t.replace(/^\.\//,"").replace(/\/+$/,""),t.startsWith("!"))return[];let n=[],r=o=>{try{return tt.readdirSync(o,{withFileTypes:!0}).filter(s=>s.isDirectory()&&s.name!=="node_modules"&&!s.name.startsWith(".")).map(s=>Y.join(o,s.name))}catch{return[]}};if(t.endsWith("/**")){let o=Y.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(Y.join(e,t.slice(0,-2)))):t.includes("*")||n.push(Y.join(e,t));return n}function ff(e){let t=[],r=er(Y.join(e,"package.json"))?.workspaces;Array.isArray(r)?t.push(...r):Array.isArray(r?.packages)&&t.push(...r.packages);try{let o=tt.readFileSync(Y.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 Mi(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 Gi(e,t,n={}){let r=Oi(e),o=new Set(t),s=new Map,i=u=>{if(s.has(u))return s.get(u);let h=null,p=Y.join(u,"tsconfig.json");return tt.existsSync(p)?h=Wi(p):u!==r&&Y.dirname(u)!==u&&u.startsWith(r)&&(h=i(Y.dirname(u))),s.set(u,h),h},a=new Map;for(let u of ff(r))for(let h of df(r,u)){let p=er(Y.join(h,"package.json"));p?.name&&!a.has(p.name)&&a.set(p.name,{dir:Oi(h),pkg:p})}let c=[...a.keys()].sort((u,h)=>h.length-u.length),l=(u,h,p)=>{let{dir:m,pkg:y}=a.get(u),g=[],x=S=>{if(!S)return;let k=Y.resolve(m,S);g.push(k);let v=Y.relative(m,k).split(Y.sep);["dist","build","lib","out","esm","cjs"].includes(v[0])&&g.push(Y.join(m,"src",...v.slice(1)))};if(h==="."){x(Mi(y.exports,"."));for(let S of["source","module","main"])typeof y[S]=="string"&&x(y[S]);g.push(Y.join(m,"src","index"),Y.join(m,"index"))}else x(Mi(y.exports,h)),g.push(Y.join(m,h),Y.join(m,"src",h));for(let S of g){let k=ln(S,p);if(k)return k}return null},d=u=>c.find(h=>u===h||u.startsWith(h+"/"))??null,f=(u,h)=>h?.paths?.some(p=>p.wildcard?u.startsWith(p.prefix)&&u.endsWith(p.suffix)&&u.length>=p.prefix.length+p.suffix.length:u===p.prefix)??!1;return{root:r,files:o,packages:a,isInternal(u,h){if(u.startsWith(".")||d(u))return!0;let p=i(Y.dirname(h));return!!(f(u,p)||p?.baseUrl&&!u.startsWith("@")&&ln(Y.join(p.baseUrl,u),o))},resolve(u,h,p){if(u.startsWith("."))return ln(Y.resolve(Y.dirname(h),u),p);let m=i(Y.dirname(h));if(m?.paths&&n.paths!==!1)for(let g of m.paths){let x=null;if(g.wildcard?u.startsWith(g.prefix)&&u.endsWith(g.suffix)&&u.length>=g.prefix.length+g.suffix.length&&(x=u.slice(g.prefix.length,u.length-g.suffix.length)):u===g.prefix&&(x=""),x!=null){for(let S of g.targets){let k=ln(S.replace("*",x),p);if(k)return k}break}}let y=n.workspaces===!1?null:d(u);if(y){let g=l(y,u===y?".":"./"+u.slice(y.length+1),p);if(g)return g}if(m?.baseUrl&&n.paths!==!1){let g=ln(Y.join(m.baseUrl,u),p);if(g)return g}return null}}}var Hi=new WeakMap;function qi(e){if(e instanceof Set)return e;let t=Hi.get(e);return t||Hi.set(e,t=new Set(e)),t}function nr(e,t,n){if(!e.startsWith("."))return null;let r=tr.dirname(t),o=tr.resolve(r,e),s=[o,...ms().map(i=>`${o}${i}`),...hs().map(i=>tr.join(o,i))];for(let i of s)if(n.includes(i))return i;return null}function Je(e,t,n){let r=nr(e,t,n);if(r)return r;let o=zi();return o?o.resolve(e,t,qi(n)):null}function Gt(e,t,n){let r=new Map;for(let o of t){let s=nr(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=Je(o.source,e,n);s&&r.set(o.source,s)}return r}function Ji(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=he(o,e),t.set(o,s)),s},method:(o,s)=>n.get(o+"\0"+s),ctorsOf:o=>r.get(o)??[]}}function qt(e){return e?e.split("?")[0].split("/").map(t=>t.startsWith(":")||/^\d+$/.test(t)?"*":t).join("/"):""}var uf=new Set(["function","arrowFunction"]);function Vi(e,t,n,r){let o=new Map;for(let l of t){let d=o.get(l.filePath);d||o.set(l.filePath,d=[]),d.push(l)}let s=new Set;for(let l of r)l.resolved&&l.fromNodeId&&l.targetNodeId&&s.add(l.fromNodeId+"\0"+l.targetNodeId);let i=(l,d)=>(o.get(l)??[]).find(f=>uf.has(f.type)&&d(f))??null,a=[];a.argBindings=[];let c=(l,d,f,u,h,p,m)=>{!d||!f||d.id===f.id||s.has(d.id+"\0"+f.id)||a.push({fromFileId:l,fromNodeId:d.id,calleeNameRaw:u,line:h,column:p,branchPath:[],firstArgText:null,deferred:!1,type:"reference",callKind:"reference",targetNodeId:f.id,confidence:m==="local"?.95:.85,matchType:m,resolved:!0})};for(let[l,d]of e){let f=o.get(l);if(f){for(let u of d.refArgs??[]){let h=null,p="local";if(u.b==="fn"?h=i(l,y=>y.name===u.name&&y.startLine===u.declLine):u.b==="import"&&(p="import",(u.ik==="default"||u.ik==="named"||u.ik==="cjs")&&(h=n.nodeForImport(l,u.src,u.ik,u.imp))),!h)continue;let m=ge(u.line,f);c(l,m,h,u.name,u.line,u.column,p),u.callLine!=null&&m&&m.id!==h.id&&a.argBindings.push({file:l,line:u.callLine,column:u.callColumn,targetNodeId:h.id,matchType:p,direct:u.via==="arg"})}for(let u of f){if(u.type!=="inlineHandler")continue;let h=null;for(let p of f)p===u||p.type==="moduleRoot"||p.startLine<=u.startLine&&p.endLine>=u.endLine&&!(p.startLine===u.startLine&&p.endLine===u.endLine)&&(!h||p.endLine-p.startLine<h.endLine-h.startLine)&&(h=p);h??=f.find(p=>p.type==="moduleRoot"),c(l,h,u,u.name,u.startLine,0,"local")}}}return a}function Yi(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 c=a.filePath+"\0"+a.className+"\0"+a.name,l=o.get(c);l?l.push(a):o.set(c,[a])}let i=(a,c)=>{for(let l of o.keys())if(l.startsWith(a+"\0"+c+"\0"))return!0;return!1};return function(c){let l=s.get(c.fromNodeId);if(!l||l.type!=="classMethod")return null;let d=t.get(c.fromFileId),f=(d?.classProps??[]).find(y=>y.className===l.className&&y.prop===c.thisProp);if(!f)return null;let u=null,h=null,p=(d.importBindings??[]).find(y=>y.local===f.type);if(p){let y=p.kind==="default"||p.kind==="named"?r.resolveImport(c.fromFileId,p.source,p.kind,p.imported):null;y?.local&&y.local!=="default"&&(u=y.file,h=y.local)}else i(c.fromFileId,f.type)&&(u=c.fromFileId,h=f.type);if(!u)return null;let m=o.get(u+"\0"+h+"\0"+c.thisMethod);return!m||m.length!==1?null:{...c,targetNodeId:m[0].id,confidence:.9,matchType:"typedProperty",resolved:!0}}}var pf=new Set(["function","arrowFunction"]);function Un(e,t,n){let r=new Map;for(let d of e){if(!pf.has(d.type))continue;let f=d.filePath+"\0"+d.name;r.has(f)||r.set(f,d)}let o=new Map,s=(d,f)=>{let u=o.get(d);if(!u){u=new Map;for(let h of t.get(d)?.importBindings??[])u.has(h.local)||u.set(h.local,h);o.set(d,u)}return u.get(f)??null},i=(d,f)=>n(d).get(f)??null;function a(d,f,u=new Set){let h=d+"\0"+f;if(u.has(h))return null;u.add(h);let p=t.get(d)?.exportBindings;if(!p)return null;if(f==="default"){if(p.default)return{file:d,local:p.default==="<anon>"?"default":p.default}}else if(p.named?.[f])return{file:d,local:p.named[f]};for(let m of p.reexports??[]){if(m.exported!==f)continue;let y=i(d,m.source);if(y)return a(y,m.imported,u)}for(let m of p.nsReexports??[]){if(m.exported!==f)continue;let y=i(d,m.source);if(y)return{moduleFile:y}}if(f!=="default")for(let m of p.stars??[]){let y=i(d,m),g=y?a(y,f,u):null;if(g)return g}return null}let c=d=>d?.local?r.get(d.file+"\0"+d.local)??null:null;function l(d,f,u,h){let p=i(d,f);return p?u==="default"?a(p,"default"):u==="named"?a(p,h):{moduleFile:p,cjs:u==="cjs"}:null}return{lookupExport:a,resolveImport:l,nodeForImport(d,f,u,h){let p=l(d,f,u,h);return p?.moduleFile&&p.cjs?c(a(p.moduleFile,"default")):c(p)},resolveName(d,f){let u=s(d,f);return u?this.nodeForImport(d,u.source,u.kind,u.imported):null},resolveMember(d,f,u){let h=s(d,f);if(!h)return null;let p=l(d,h.source,h.kind,h.imported);return p?.moduleFile?c(a(p.moduleFile,u)):null},classForImport(d,f){let u=s(d,f);if(!u)return null;let h=l(d,u.source,u.kind,u.imported);return h?.local?{file:h.file,className:h.local==="default"?null:h.local}:null},bindingFor:s}}function Ki(e,t,n,r,o,s,i){let a=[],c=Ji(t),l=new Map,d=g=>l.get(g)??Gt(g,n.get(g)?.imports??[],r);c.bind=Un(t,n,d);let f=Yi(t,n,d,c.bind),u=new Map;for(let g of e)u.has(g.fromFileId)||u.set(g.fromFileId,[]),u.get(g.fromFileId).push(g);for(let[g,x]of u){let S=n.get(g),k=he(g,t),v=Gt(g,S.imports,r);l.set(g,v);for(let w of x)if(w.type==="call")a.push(cn(w,t,k,v,c));else if(w.type==="methodCall")a.push(Ti(w,t,c));else if(w.type==="callSite")a.push((w.thisProp?f(w):null)??Ai(w,t,k,v,c));else if(w.type==="returnValue")a.push({...w,targetNodeId:null,confidence:0,matchType:"returnValue",resolved:!1});else if(w.type==="apiCall")if(w.scope==="external")a.push({...w,targetNodeId:null,confidence:null,matchType:"externalService",resolved:!1});else{let b=qt(w.url),N=o.get(b);N?a.push({...w,targetNodeId:N,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...w,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(w.type==="socketEmit"){let b=s.get(w.eventName);b?a.push({...w,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...w,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(w.type==="rawSocketSend"){let b=i?.get(w.eventName);b?a.push({...w,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...w,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}}let h=Vi(n,t,c.bind,a);for(let g of h)a.push(g);let p=new Map;for(let g of a){if(g.resolved||g.line==null||g.type!=="call"&&g.type!=="methodCall"&&g.type!=="callSite")continue;let x=g.fromFileId+" "+g.line+" "+g.column;(p.get(x)??p.set(x,[]).get(x)).push(g)}let m=[...h.argBindings].sort((g,x)=>x.direct-g.direct),y=new Set;for(let g of m){let x=g.file+" "+g.line+" "+g.column;if(y.has(x))continue;let S=(p.get(x)??[]).find(k=>k.fromNodeId!==g.targetNodeId);S&&(y.add(x),Object.assign(S,{targetNodeId:g.targetNodeId,confidence:g.matchType==="local"?.95:.85,matchType:"argument",resolved:!0,viaArgument:!0}))}return a}function Xi(e){let t=new Map,n=new WeakMap,r=c=>{if(typeof c=="string")return c.length>=20?"s"+c:null;if(c&&typeof c=="object"){let l=n.get(c);if(l===void 0){let d=JSON.stringify(c);l=d.length>=40?"j"+d:"",n.set(c,l)}return l||null}return null};(function c(l){let d=r(l);if(d){let f=t.get(d)??0;if(t.set(d,f+1),f>0)return}if(Array.isArray(l))for(let f of l)c(f);else if(l&&typeof l=="object")for(let f of Object.values(l))c(f)})(e);let o=[],s=new Map,i=c=>{let l=r(c),d=l&&t.get(l)>1;if(d&&s.has(l))return s.get(l);let f;if(typeof c=="string"?f=JSON.stringify(c):Array.isArray(c)?f="["+c.map(i).join(",")+"]":c&&typeof c=="object"?f="{"+Object.entries(c).map(([h,p])=>JSON.stringify(h)+":"+i(p)).join(",")+"}":f=JSON.stringify(c),!d)return f;let u="$"+o.length.toString(36);return o.push(`const ${u}=${f};`),s.set(l,u),u},a=i(e);return`(() => {${o.join(`
19
19
  `)}
20
- return ${a};})()`}function Io(e,t,n,r){if(!e)return{targetId:null,via:null};if(n.has(e))return{targetId:n.get(e),via:"in-file"};if(r)for(let[,o]of r){let s=le(o,t);if(s.has(e))return{targetId:s.get(e),via:"cross-file"}}return{targetId:null,via:null}}function Vs(e,t,n,r,o,s=[],i=null){if(!n.some(l=>!l.isInlineHandler)&&!r.some(l=>!l.isInlineHandler)&&!s.some(l=>!l.isInlineHandler))return e;let a=e.map(l=>({...l}));for(let l of n){if(l.isInlineHandler)continue;let c=l.nest?e.find(f=>f.type==="classMethod"&&f.filePath===t&&f.className===l.nest.className&&f.name===l.nest.methodName):null,{targetId:d,via:p}=l.nest?{targetId:c?.id??null,via:"in-file"}:Io(l.handlerName,e,o,i);if(d){let f=a.find(u=>u.id===d);f&&(f.isEntryPoint=!0,f.trigger={type:"route",label:`${l.method.toUpperCase()} ${l.path}`,resolvedVia:p})}}for(let l of r){if(l.isInlineHandler)continue;let{targetId:c,via:d}=Io(l.handlerName,e,o,i);if(c){let p=a.find(f=>f.id===c);p&&(p.isEntryPoint=!0,p.trigger={type:"listener",label:l.eventName,resolvedVia:d})}}for(let l of s){if(l.isInlineHandler)continue;let{targetId:c,via:d}=Io(l.handlerName,e,o,i);if(c){let p=a.find(f=>f.id===c);p&&(p.isEntryPoint=!0,p.trigger={type:"socketListener",label:l.eventName,resolvedVia:d})}}return a}function jo(e){let t=new Map,n=new Map;for(let r of e)r.resolved&&(t.set(r.fromNodeId,(t.get(r.fromNodeId)??0)+1),n.set(r.targetNodeId,(n.get(r.targetNodeId)??0)+1));return{outgoing:t,incoming:n}}function Ys(e,t,n=jo(t)){if(e.type==="moduleRoot")return 0;let r=n.outgoing.get(e.id)??0,o=n.incoming.get(e.id)??0,s=e.exported?1.5:1;return r/(o+1)*s}function Xs(e,t){let n=jo(t),r=new Set;for(let i of e)n.incoming.has(i.id)&&r.add(i.filePath);let s=e.filter(i=>!(i.isEntryPoint||i.type==="moduleRoot"||!n.incoming.has(i.id)&&r.has(i.filePath))).map(i=>({...i,fallbackScore:Ys(i,t,n)}));return s.sort((i,a)=>a.fallbackScore-i.fallbackScore),s.slice(0,15)}function Co(e){let t=new Map;for(let n of e)!n.resolved||!n.fromNodeId||!n.targetNodeId||(t.has(n.fromNodeId)||t.set(n.fromNodeId,[]),t.get(n.fromNodeId).push({targetNodeId:n.targetNodeId,line:n.line??null,column:n.column??null,branchPath:n.branchPath??[],edgeType:n.type}));return t}function Eo(e,t,n,r=8){let o=new Set([e]),s=l=>n.find(c=>c.id===l)?.category??"unknown",i=[{nodeId:e,depth:0,parentNodeId:null,category:s(e)}],a=[{nodeId:e,depth:0}];for(;a.length>0;){let l=a.shift();if(l.depth>=r)continue;let c=t.get(l.nodeId)||[];for(let d of c){let p=d.targetNodeId;if(o.has(p))continue;o.add(p);let f={nodeId:p,depth:l.depth+1,parentNodeId:l.nodeId,category:s(p),callLine:d.line,callColumn:d.column,branchPath:d.branchPath,edgeType:d.edgeType};i.push(f),a.push(f)}}return i}function Zs(e,t,n){return t.filter(o=>o.filePath===e.filePath&&o.id!==e.id&&o.type!=="moduleRoot").filter(o=>!n.some(i=>i.resolved&&i.targetNodeId===o.id))}function Qs(e,t,n){if(e.type==="moduleRoot")return!1;if(t.some(a=>a.resolved&&a.targetNodeId===e.id&&a.matchType==="crossLayer")||t.filter(a=>a.resolved&&a.fromNodeId===e.id).length>=4||new Set((e.returns||[]).map(a=>a.condition).filter(a=>a!==null)).size>=3)return!0;if(t.some(a=>a.resolved&&a.targetNodeId===e.id)&&!n.some(l=>l.filePath===e.filePath&&l.id!==e.id&&l.type!=="moduleRoot"&&t.some(c=>c.resolved&&c.targetNodeId===l.id))){let l=Zs(e,n,t);if(l.length>0)return e.lexicalSiblings=l.map(c=>c.id),!0}return!1}function ei(e,t,n,r,o=8,s=null){let i=[],a=new Set(e.map(c=>c.id)),l=[...e];for(;l.length>0;){let c=l.shift(),d=Eo(c.id,t,n,o);i.push({entryPointId:c.id,entryPointName:c.name,trigger:c.trigger??null,steps:d});let p=s?new Set(Eo(c.id,s,n,o).map(f=>f.nodeId)):null;for(let f of d){if(p&&!p.has(f.nodeId)||f.nodeId===c.id||a.has(f.nodeId))continue;let u=n.find(m=>m.id===f.nodeId);u&&Qs(u,r,n)&&(a.add(u.id),f.hasOwnSubTrace=!0,u.lexicalSiblings&&(f.lexicalSiblings=u.lexicalSiblings),l.push({id:u.id,name:u.name,trigger:null}))}}return i}function ti(e,t,n=mr){return e.filter((r,o)=>{if(o===0)return!0;let s=t.find(i=>i.id===r.nodeId);return s?!n.some(i=>s.name.toLowerCase().includes(i)):!0})}function ni(e){return e.steps.filter(n=>n.depth>0).map(n=>n.nodeId).sort().join(" | ")}function oi(e){let t=new Map;for(let n of e){let r=ni(n),o=r===""?`__no_calls__${n.entryPointName}`:r;t.has(o)||t.set(o,[]),t.get(o).push(n)}return t}function ri(e){let t=e[0];return{steps:t.steps,entryPointNames:e.map(n=>n.entryPointName),occurrences:e.length,name:t.entryPointName,trigger:t.trigger,tier:e.some(n=>n.origin==="physical")?"physical":"guessed",tierOrigin:e.some(n=>n.origin==="physical")?"physical":t.origin}}import _n from"node:path";function si(e){if(!e.trigger)return null;if(e.trigger.type==="route")return`${e.trigger.label.split(" ")[1].split("/").filter(Boolean).join(" ").replace(/[-_]/g," ").split(" ").map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")} Flow`;if(e.trigger.type==="listener"){let t=e.trigger.label;return`${t.charAt(0).toUpperCase()+t.slice(1)} Flow`}return null}function ii(e){return e.name.replace(/([A-Z])/g," $1").trim().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}var ai=60,Il=24;function ci(e,t=null){let n=e.map(r=>{let o=si(r),s=r.trigger?.workflowName??o??ii(r);return{...r,name:s}});return t?.nodes?Pl(n,t.nodes):n}var Po=(e,t)=>e.length>t?e.slice(0,t-1)+"\u2026":e,jl=new Set(["function","arrowFunction","classMethod"]);function Cl(e){let t=new Map(e.map(o=>[o.id,o])),n=new Map,r=o=>{let s=n.get(o);return s||(s=e.filter(i=>i.filePath===o&&jl.has(i.type)),n.set(o,s)),s};return o=>{let s=t.get(o.steps[0].nodeId);if(!s)return[null,null,null];let i=null;if(s.type==="classMethod")i=s.className;else{let c=null;for(let d of r(s.filePath))d===s||!(d.startLine<=s.startLine&&d.endLine>=s.endLine)||d.startLine===s.startLine&&d.endLine===s.endLine||(!c||d.endLine-d.startLine<c.endLine-c.startLine)&&(c=d);c&&(i=c.type==="classMethod"?c.className:c.name)}let a=null;if(o.trigger?.type==="route")a=String(o.trigger.label).split(" ")[0];else if(o.trigger?.type==="listener"){let c=/::listener:([^.#]+)\./.exec(s.id);c&&(a=c[1])}let l=_n.basename(s.filePath,_n.extname(s.filePath));return l==="index"&&(l=_n.basename(_n.dirname(s.filePath))),[i||null,a||null,l||null]}}var El=(e,t)=>{let n=t.map(r=>Po(r,Il)).join(", ");return e.endsWith(")")?e.slice(0,-1)+", "+n+")":e+" ("+n+")"};function Pl(e,t){let n=Cl(t),r=e.map(i=>({w:i,base:i.name,parts:[],used:new Set,stuck:!1,q:null})),o=i=>i.parts.length?El(i.base,i.parts):i.base,s=()=>{let i=new Map;for(let a of r){let l=o(a);(i.get(l)??i.set(l,[]).get(l)).push(a)}return[...i.values()].filter(a=>a.length>1)};for(let i=0;i<4;i++){let a=!1;for(let l of s()){if(l.some(f=>f.stuck))continue;for(let f of l)f.q??=n(f.w);let c=[0,1,2].filter(f=>l.every(u=>!u.used.has(f))),d=c.find(f=>new Set(l.map(u=>u.q[f]??"")).size>1),p=d!==void 0;if(p||(d=c.find(f=>l.every(u=>u.q[f]))),d===void 0){for(let f of l)f.stuck=!0;continue}for(let f of l)f.used.add(d),f.q[d]&&f.parts.push(f.q[d]),p||(f.stuck=!0);a=!0}if(!a)break}for(let i of s())i.sort((a,l)=>a.w.steps[0].nodeId<l.w.steps[0].nodeId?-1:a.w.steps[0].nodeId>l.w.steps[0].nodeId?1:0),i.forEach((a,l)=>{l>0&&(a.suffix=` (${l+1})`)});return r.map(i=>{let a=o(i);return i.suffix&&(a=Po(a,ai-i.suffix.length)+i.suffix),{...i.w,name:Po(a,ai)}})}var Ll=e=>e;function li(e,t){let n=new Map;for(let[r,o]of e){let s=t.filter(c=>c.filePath===r);if(s[0]?.category!=="backend")continue;let i=o.routes??[],a=Te(r,o),l=le(r,t);for(let c of i){let d=Ct(c.path);if(c.isInlineHandler){let f=a.get(c);n.set(d,f);continue}if(c.nest){let f=Ll(s).find(u=>u.type==="classMethod"&&u.className===c.nest.className&&u.name===c.nest.methodName);f&&n.set(d,f.id);continue}if(!c.handlerName||!l.has(c.handlerName))continue;let p=l.get(c.handlerName);n.set(d,p)}}return n}import dt from"node:fs";import Y from"node:path";var $n=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Rl=/(^|\/)(dist|build|out|built|compiled|esm|cjs|lib|output)(\/|$)/,di=/(^|\/)(dist|build|out|built|compiled|esm|cjs|output)(\/|$)/,Tl=/\b(esbuild|tsup|tsdown|tsc|rollup|webpack|ncc|swc|babel|vite|parcel|bun\s+build|pkg|unbuild|microbundle|rspack)\b/,Al=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild|rspack)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Oe=e=>{try{return dt.statSync(e).isFile()}catch{return!1}},Lo=e=>e.split(Y.sep).join("/"),Ro=e=>{if(Oe(e)&&$n.includes(Y.extname(e))&&!/\.d\.ts$/.test(e))return e;let t=e.replace(/\.(m|c)?js$/,"");for(let n of $n)if(Oe(t+n)&&!/\.d\.ts$/.test(t+n))return t+n;return null},Fn=(e,t)=>{let n=Y.relative(e,t);return n&&!n.startsWith("..")&&!Y.isAbsolute(n)&&!/(^|[\\/])node_modules([\\/]|$)/.test(n)};function Ol(e,t){let n=Oe(t+".map")?t+".map":null;if(!n&&Oe(t))try{let a=dt.readFileSync(t,"utf8").slice(-400),l=/sourceMappingURL=([^\s*]+)/.exec(a);if(l&&!l[1].startsWith("data:")){let c=Y.resolve(Y.dirname(t),l[1]);Oe(c)&&(n=c)}}catch{}if(!n)return null;let r;try{r=JSON.parse(dt.readFileSync(n,"utf8"))}catch{return null}let o=Y.resolve(Y.dirname(n),r.sourceRoot??""),s=(r.sources??[]).map(a=>Y.resolve(o,a)).filter(a=>Fn(e,a)&&Oe(a)&&$n.includes(Y.extname(a)));if(s.length===1)return s[0];let i=Y.basename(t).replace(/\.(m|c)?js$/,"");return s.find(a=>Y.basename(a).replace(/\.[^.]+$/,"")===i)??null}function Ml(e){try{return JSON.parse(dt.readFileSync(e,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,"").replace(/,(\s*[}\]])/g,"$1"))}catch{return null}}function Hl(e,t){for(let n of["tsconfig.build.json","tsconfig.json"]){let o=Ml(Y.join(e,n))?.compilerOptions;if(!o?.outDir)continue;let s=Lo(Y.normalize(o.outDir)).replace(/^\.\//,"").replace(/\/$/,"");if(!(t===s||t.startsWith(s+"/")))continue;let i=t.slice(s.length+1),a=o.rootDir?o.rootDir:dt.existsSync(Y.join(e,"src"))?"src":".",l=Ro(Y.resolve(e,a,i));if(l)return l}return null}function Dl(e,t){let n=t.split("/"),r=n.findIndex(s=>/^(dist|build|out|built|compiled|esm|cjs|lib|output)$/.test(s));if(r<0)return null;let o=n.slice(r+1).join("/");for(let s of["src","source","sources"]){let i=Ro(Y.resolve(e,...n.slice(0,r),s,o));if(i&&Fn(e,i))return i}return null}function Ul(e,t,n){let r=Y.basename(n).replace(/\.(m|c)?js$/,"");for(let o of["build","compile","bundle","prepare","prepublishOnly","prepack","postinstall"]){let s=t.scripts?.[o];if(!s||!Tl.test(s))continue;let i=[];for(let c of s.split(/\s+/).map(d=>d.replace(/^["']|["']$/g,"").replace(/^--?[\w-]+=/,""))){if(!$n.includes(Y.extname(c))||/\.d\.ts$/.test(c))continue;let d=Y.resolve(e,c);Oe(d)&&Fn(e,d)&&!di.test(Lo(Y.relative(e,d)))&&i.push(d)}let a=[...new Set(i)];if(a.length===1)return a[0];let l=a.filter(c=>Y.basename(c).replace(/\.[^.]+$/,"")===r);if(l.length===1)return l[0];if(a.length)return a[0]}return null}function Bl(e,t){let n=[];try{n=dt.readdirSync(e).filter(i=>Al.test(i)).sort()}catch{return null}let r=Y.basename(t).replace(/\.(m|c)?js$/,""),o=[];for(let i of n){let a;try{a=dt.readFileSync(Y.join(e,i),"utf8")}catch{continue}for(let l of a.matchAll(/\bentry(?:Points)?\s*:\s*[[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/g)){let c=Ro(Y.resolve(e,l[1]));c&&Fn(e,c)&&o.push(c)}}let s=[...new Set(o)];return s.length===1?s[0]:s.find(i=>Y.basename(i).replace(/\.[^.]+$/,"")===r)??null}function In(e,t,n){if(typeof t!="string"||!t)return null;let r=Lo(Y.normalize(t)).replace(/^\.\//,""),o=Y.resolve(e,r);if(!Rl.test(r)||Oe(o)&&!di.test(r)||Oe(o)&&/\.ts$/.test(o))return null;let i=[["sourcemap",()=>Ol(e,o)],["tsconfig outDir",()=>Hl(e,r)],["convention",()=>Oe(o)?null:Dl(e,r)],["build script",()=>Ul(e,n??{},r)],["build config",()=>Bl(e,r)]];for(let[a,l]of i){let c=null;try{c=l()}catch{}if(c&&c!==o)return{file:c,how:a}}return null}function fi(e,t){let n=new Map;for(let[r,o]of e){let s=o.socketListeners??[],i=Te(r,o),a=le(r,t);for(let l of s){if(l.isInlineHandler){let d=i.get(l);n.set(l.eventName,d);continue}if(!l.handlerName||!a.has(l.handlerName))continue;let c=a.get(l.handlerName);n.set(l.eventName,c)}}return n}import To from"node:fs";import H from"node:path";var Ne=e=>String(e??"").trim().replace(/^["']|["']$/g,""),jn=e=>e.replace(/^\s*#.*$/,"").replace(/\s+#.*$/,"");function ui(e){let t=/^(\/[A-Za-z0-9_\-./]*?)\/?(?=$|[:(*{[])/.exec(String(e).trim()),n=t?t[1]:"";return n==="/"?"":n.replace(/\/+$/,"")}function pi(e,t){let n=e.split(/\r?\n/).map(jn),r=u=>u.length-u.trimStart().length,o=[],s=null,i=!1,a=null,l=!1,c=0,d=null,p=()=>{d?.key&&d.fromService&&d.fromService!=="?"&&s.hostRefs.push({name:d.key,service:d.fromService,property:d.property}),d=null},f=(u,m,h)=>{m==="name"?u.name=Ne(h):m==="rootDir"?u.rootDir=Ne(h):m==="startCommand"&&(u.startCommand=Ne(h))};for(let u of n){if(!u.trim())continue;let m=r(u),h=u.trim();if(m===0){p(),s=null,l=!1,i=/^services\s*:/.test(h),a=null;continue}if(!i)continue;let v=h.startsWith("-");if(v&&(a==null||m===a)){a=m,p(),s={name:null,rootDir:null,startCommand:null,kept:[],hostRefs:[]},o.push(s),l=!1;let w=/^-\s*([A-Za-z]+)\s*:\s*(.*)$/.exec(h);w&&f(s,w[1],w[2]);continue}if(!s)continue;let g=/^(?:-\s*)?([A-Za-z]+)\s*:\s*(.*)$/.exec(h);if(g){if(g[1]==="envVars"){p(),l=!0,c=m;continue}if(l&&m>c){if(v&&(p(),d={key:null,fromService:null,property:null}),!d)continue;if(g[1]==="key")d.key=Ne(g[2]);else if(g[1]==="value"&&d.key){let w=Ke(d.key,Ne(g[2]),t);w&&s.kept.push(w)}else g[1]==="fromService"?d.fromService="?":g[1]==="name"&&d.fromService==="?"?d.fromService=Ne(g[2]):g[1]==="property"&&(d.property=Ne(g[2]));continue}l&&(p(),l=!1),f(s,g[1],g[2])}}return p(),o.filter(u=>u.name)}function mi(e,t){let n={app:null,ports:[],kept:[]},r="";for(let o of e.split(/\r?\n/)){let s=jn(o).trim();if(!s)continue;let i=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(s);if(i){r=i[1];continue}let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(s);if(!a)continue;let[,l,c]=a;if(r===""&&l==="app"){let d=Ne(c);/^[a-z0-9][a-z0-9-]*$/i.test(d)&&(n.app=d)}else if(l==="internal_port"){let d=Number(Ne(c));Number.isInteger(d)&&d>=1&&d<=65535&&n.ports.push(d)}else if(r==="env"){let d=Ke(l,Ne(c),t);d&&n.kept.push(d)}}return n}function hi(e,t){let n={ports:[],kept:[]},r=e.replace(/\\\r?\n/g," ");for(let o of r.split(/\r?\n/)){let s=o.trim(),i=/^EXPOSE\s+(.+)$/i.exec(s);if(i){for(let l of i[1].split(/\s+/)){let c=Number(l.replace(/\/\w+$/,""));Number.isInteger(c)&&c>=1&&c<=65535&&n.ports.push(c)}continue}if(i=/^(?:ENV|ARG)\s+(.+)$/i.exec(s),!i)continue;let a=i[1];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(a)){let l=/([A-Za-z_][A-Za-z0-9_]*)=("([^"]*)"|'([^']*)'|\S*)/g,c;for(;c=l.exec(a);){let d=Ke(c[1],c[3]??c[4]??c[2],t);d&&n.kept.push(d)}}else{let l=/^([A-Za-z_][A-Za-z0-9_]*)\s+(.*)$/.exec(a);if(l){let c=Ke(l[1],Ne(l[2]),t);c&&n.kept.push(c)}}}return n}function gi(e){let t;try{t=JSON.parse(e)}catch{return[]}let n=[];for(let r of["rewrites","redirects"])for(let o of Array.isArray(t?.[r])?t[r]:[]){let s=typeof o?.destination=="string"?o.destination:"",i=/\/:[A-Za-z_]+\*?$/.test(s)?Ve(s.replace(/\/:[A-Za-z_]+\*?$/,"")):null;i&&typeof o.source=="string"&&n.push({prefix:ui(o.source),target:i,kind:`vercel.json ${r}`,strip:!0})}return n}function yi(e){let t=[],n=!1,r=null,o=()=>{if(r?.from&&r.to&&/\/:[A-Za-z_]+\*?$/.test(r.to)){let s=Ve(r.to.replace(/\/:[A-Za-z_]+\*?$/,""));s&&t.push({prefix:ui(r.from),target:s,kind:"netlify.toml redirects",strip:!0})}r=null};for(let s of e.split(/\r?\n/)){let i=jn(s).trim();if(!i)continue;let a=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(a){o(),n=a[1]==="redirects",r=n?{}:null;continue}if(!n||!r)continue;let l=/^(from|to)\s*=\s*(.*)$/.exec(i);l&&(r[l[1]]=Ne(l[2]))}return o(),t}function xi(e,t){let n;try{n=JSON.parse(e)}catch{return[]}let r=[],o=n&&typeof n=="object"?n.env:null;if(o&&typeof o=="object")for(let s of Object.keys(o).sort()){let i=o[s],a=typeof i=="string"?i:typeof i?.value=="string"?i.value:null,l=Ke(s,a,t);l&&r.push(l)}return r}function vi(e,t,n){let r=[];if(n){let o;try{o=JSON.parse(e)}catch{return r}let s=(i,a)=>{if(!(!i||typeof i!="object"||a>4))for(let l of Object.keys(i).sort()){let c=i[l];if(/^(env|envVars|variables|environment)$/i.test(l)&&c&&typeof c=="object"&&!Array.isArray(c))for(let d of Object.keys(c).sort()){let p=typeof c[d]=="string"?c[d]:typeof c[d]?.value=="string"?c[d].value:null,f=Ke(d,p,t);f&&r.push(f)}else s(c,a+1)}};s(o,0)}else{let o="";for(let s of e.split(/\r?\n/)){let i=jn(s).trim();if(!i)continue;let a=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(a){o=a[1];continue}let l=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(i);if(l&&/(^|\.)(env|variables|environment)$/i.test(o)){let c=Ke(l[1],Ne(l[2]),t);c&&r.push(c)}}}return r}var zl=[".env.local",".env",".env.development",".env.production",".env.example"],Wl=/^(PORT|HTTP_PORT|HTTPS_PORT|SERVER_PORT|API_PORT|APP_PORT|WS_PORT|WSS_PORT|WEBSOCKET_PORT|LISTEN_PORT)$/,ql=/^PUBLIC_(?:[A-Z0-9]+_)*(?:ORIGIN|URL|HOST|BASE_URL)$/,Gl=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","host.docker.internal"]),Jl=512*1024,wi=e=>e.split(H.sep).join("/");function ft(e){try{let t=To.lstatSync(e);return!t.isFile()||t.isSymbolicLink()||t.size>Jl?null:To.readFileSync(e,"utf8")}catch{return null}}function Ve(e){let t=String(e).trim().replace(/^["']|["']$/g,"");if(!/^(https?|wss?):\/\//i.test(t))return null;try{let n=new URL(t);if(!n.hostname)return null;let r=n.protocol.replace(":",""),o=n.hostname.toLowerCase(),s=n.port?Number(n.port):null,i=n.pathname.replace(/\/+$/,"");return{scheme:r,host:o,port:s,origin:`${r}://${o}${s?":"+s:""}`,path:i}}catch{return null}}function Kl(e){let t=String(e).trim().replace(/^["']|["']$/g,"");return!/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:\d{1,5})?(\/[^\s?#]*)?$/i.test(t)||!/[a-z]/i.test(t.split(/[/:]/)[0])?null:Ve("http://"+t)}var Ao=e=>{let t=String(e).trim().replace(/^["']|["']$/g,"");if(!/^\d{1,5}$/.test(t))return null;let n=Number(t);return n>=1&&n<=65535?n:null};function Vl(e){let t=new Map;for(let n of e.split(/\r?\n/)){let r=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(n);if(!r)continue;let o=r[2];if(/^["']/.test(o)){let s=o[0],i=o.indexOf(s,1);o=i>0?o.slice(1,i):o.slice(1)}else o=o.replace(/\s+#.*$/,"");t.set(r[1],o)}return t}function Ni(e,t,n=0,r=new Set){let o=e.get(t);return o==null||n>5||r.has(t)||(r.add(t),o=o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}]*))?\}/g,(s,i,a)=>{let l=e.has(i)?Ni(e,i,n+1,r):void 0;return l!=null&&l!==""?l:a??""}),r.delete(t)),o}function Ke(e,t,n){if(t==null)return null;if(Wl.test(e)){let o=Ao(t);return o?{name:e,kind:"port",file:n,port:o}:null}let r=Ve(t)??(/(_URL|_URI|_HOST|_HOSTNAME|_ORIGIN|_ADDR|_ENDPOINT)$/i.test(e)?Kl(t):null);return r?{name:e,kind:"url",file:n,...r}:null}function Si(e,t){let n=[];for(let r of[...e.keys()].sort()){let o=Ni(e,r);if(o==null)continue;let s=Ke(r,o,t);s&&n.push(s)}return n}function Yl(e){let t=e.split(/\r?\n/).map(c=>c.replace(/\s+#.*$/,"").replace(/\t/g," ")),n=c=>c.length-c.trimStart().length,r=[],o=t.findIndex(c=>/^services\s*:\s*$/.test(c));if(o<0)return r;let s=null,i=null,a=null,l=0;for(o=o+1;o<t.length;o++){let c=t[o];if(!c.trim())continue;let d=n(c),p=c.trim();if(d===0)break;if(s==null&&(s=d),d===s){let f=/^([A-Za-z0-9_.-]+)\s*:\s*$/.exec(p);f&&(i={name:f[1],ports:[],env:new Map,build:null},r.push(i),a=null);continue}if(i){if(d<=s+4&&/^[A-Za-z_]+\s*:/.test(p)&&!p.startsWith("-")){let f=/^([A-Za-z_]+)\s*:\s*(.*)$/.exec(p);a=f[1],l=d,a==="build"&&f[2]&&(i.build=f[2].replace(/^["']|["']$/g,""));continue}if(a==="build"&&/^context\s*:/.test(p)){i.build=p.replace(/^context\s*:\s*/,"").replace(/^["']|["']$/g,"");continue}if(a==="ports"&&p.startsWith("-")){let u=p.slice(1).trim().replace(/^["']|["']$/g,"").replace(/\/\w+$/,"").split(":"),m=u.slice(-2).map(h=>Ao(h));u.length===1&&m[0]?i.ports.push({host:null,container:m[0]}):u.length>=2&&m[0]&&m[1]&&i.ports.push({host:m[0],container:m[1]});continue}if(a==="environment"&&d>l){let f=p.startsWith("-")?/^-\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(p):/^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/.exec(p);f&&i.env.set(f[1],f[2].replace(/^["']|["']$/g,""))}}}return r}function ki(e,t){let n=[];if(t==="vite"){let r=e.search(/\bproxy\s*:/);if(r<0)return n;let o=e.slice(r,r+2500),s=/["'`](\/[^"'`]*)["'`]\s*:\s*(?:["'`](https?:\/\/[^"'`]+)["'`]|\{[^{}]*?target\s*:\s*["'`](https?:\/\/[^"'`]+)["'`])/g,i;for(;i=s.exec(o);){let a=Ve(i[2]??i[3]);a&&n.push({prefix:i[1].replace(/\/+$/,""),target:a,kind:"vite.config proxy"})}}else if(t==="next"){let r=/source\s*:\s*["'`](\/[^"'`:*]*)[^"'`]*["'`]\s*,\s*destination\s*:\s*["'`](https?:\/\/[^"'`]+?)(?:\/:[^"'`]*)?["'`]/g,o;for(;o=r.exec(e);){let s=Ve(o[2]);s&&n.push({prefix:o[1].replace(/\/+$/,""),target:s,kind:"next.config rewrites"})}}return n}function bi(e,t,n){let r=g=>wi(H.relative(e,g)),o=new Map,s=new Map,i=new Map,a=(g,w,S)=>{(g.get(w)??g.set(w,new Set).get(w)).add(S)},l=(g,w,S)=>{let N=i.get(g)??i.set(g,[]).get(g);N.some(y=>y.service===w&&y.via===S)||N.push({service:w,via:S})},c=g=>{let w=[],S=H.resolve(g),N=H.resolve(e);for(let y=0;y<8&&(w.push(S),!(S===N||H.dirname(S)===S||(S=H.dirname(S),!S.startsWith(N))));y++);return w},d=new Map,p=new Map,f=(g,w)=>{let S=g.env.get(w.name)??g.env.set(w.name,[]).get(w.name);S.some(N=>N.file===w.file)||S.push(w),w.kind==="port"&&g.ports.add(w.port)};function u(g,w,S){let N=x=>r(H.join(S,x)),y=x=>ft(H.join(S,x));for(let x of Cn(S))if(x==="fly.toml"){let b=y(x);if(b){let k=mi(b,N(x));for(let $ of k.ports)w.ports.add($);for(let $ of k.kept)f(w,$);k.app&&(l(`${k.app.toLowerCase()}.internal`,g.name,"fly.toml app name"),l(`${k.app.toLowerCase()}.fly.dev`,g.name,"fly.toml app name"))}}else if(/^Dockerfile(\..+)?$/.test(x)){let b=y(x);if(b){let k=hi(b,N(x));for(let $ of k.ports)w.weakPorts.add($);for(let $ of k.kept)f(w,$)}}else if(x==="railway.json"||x==="railway.toml"){let b=y(x);if(b)for(let k of vi(b,N(x),x.endsWith(".json")))f(w,k)}else if(x==="app.json"){let b=y(x);if(b)for(let k of xi(b,N(x)))f(w,k)}else if(x==="vercel.json"){let b=y(x);if(b)for(let k of gi(b))w.proxies.push({...k,file:N(x)})}else if(x==="netlify.toml"){let b=y(x);if(b)for(let k of yi(b))w.proxies.push({...k,file:N(x)})}}for(let g of t){let w={env:new Map,ports:new Set,weakPorts:new Set,proxies:[],isServer:!1};o.set(g.name,w);for(let S of c(g.rootPath)){for(let N of zl){let y=ft(H.join(S,N));if(y!=null)for(let x of Si(Vl(y),r(H.join(S,N)))){let b=w.env.get(x.name)??w.env.set(x.name,[]).get(x.name);b.some(k=>k.file===x.file)||b.push(x),x.kind==="port"&&S===H.resolve(g.rootPath)&&/(^|\/)\.env/.test(x.file)&&!/\.example$/.test(x.file)&&w.ports.add(x.port),x.kind==="port"&&S===H.resolve(g.rootPath)&&/\.example$/.test(x.file)&&w.ports.add(x.port)}}if(S===H.resolve(g.rootPath)){try{let N=JSON.parse(ft(H.join(S,"package.json"))??"null"),y=typeof N?.proxy=="string"?Ve(N.proxy):null;y&&w.proxies.push({prefix:"",target:y,kind:'package.json "proxy"',file:r(H.join(S,"package.json"))})}catch{}for(let N of Cn(S)){if(/^vite\.config\.(js|mjs|cjs|ts|mts)$/.test(N)){let y=ft(H.join(S,N));if(y)for(let x of ki(y,"vite"))w.proxies.push({...x,file:r(H.join(S,N))})}if(/^next\.config\.(js|mjs|cjs|ts)$/.test(N)){let y=ft(H.join(S,N));if(y)for(let x of ki(y,"next"))w.proxies.push({...x,file:r(H.join(S,N))})}}}S===H.resolve(g.rootPath)&&u(g,w,S);for(let N of Cn(S))if(/^render\.ya?ml$/.test(N)&&!p.has(H.join(S,N))){let y=ft(H.join(S,N));y&&p.set(H.join(S,N),pi(y,r(H.join(S,N))))}for(let N of Cn(S)){if(!/^docker-compose.*\.ya?ml$/.test(N)||d.has(H.join(S,N)))continue;let y=ft(H.join(S,N));y&&d.set(H.join(S,N),Yl(y))}}}for(let[g,w]of[...d].sort((S,N)=>S[0]<N[0]?-1:1)){let S=H.dirname(g);for(let N of w){let y=N.build?H.resolve(S,N.build):null,x=t.find(k=>y&&H.resolve(k.rootPath)===y)??t.find(k=>k.name===N.name||H.basename(k.rootPath)===N.name);if(!x)continue;let b=o.get(x.name);for(let k of N.ports)b.ports.add(k.container),k.host&&b.ports.add(k.host);for(let k of Si(N.env,r(g)))(b.env.get(k.name)??b.env.set(k.name,[]).get(k.name)).push(k);l(N.name.toLowerCase(),x.name,"docker-compose service name")}}for(let[g,w]of[...p].sort((S,N)=>S[0]<N[0]?-1:1)){let S=H.dirname(g),N=new Map;for(let y of w){let x=H.resolve(S,y.rootDir||"."),b=y.rootDir?t.find($=>H.resolve($.rootPath)===x):null;if(!b&&y.startCommand)for(let $ of y.startCommand.split(/\s+/)){if(!/\.(c|m)?[jt]sx?$/.test($)&&!/^[\w./-]+\/[\w.-]+$/.test($))continue;let j=H.resolve(x,$),D=t.filter(L=>j.startsWith(H.resolve(L.rootPath)+H.sep)).sort((L,K)=>K.rootPath.length-L.rootPath.length)[0];if(D){b=D;break}}if(b=b??t.find($=>$.name===y.name||H.basename($.rootPath)===y.name),!b)continue;N.set(y.name,{target:b,c:y});let k=o.get(b.name);for(let $ of y.kept)f(k,{...$,scoped:!0});l(y.name.toLowerCase(),b.name,"render.yaml service name"),l(`${y.name.toLowerCase()}.onrender.com`,b.name,"render.yaml service name (Render's default public address)")}for(let{target:y,c:x}of N.values())for(let b of x.hostRefs){let k=N.get(b.service);if(!k)continue;let $=[...k.c.kept].find(L=>L.kind==="port")?.port??null,j=b.property==="hostport"&&$,D=b.service.toLowerCase();f(o.get(y.name),{name:b.name,kind:"url",file:r(g),scheme:"http",host:D,port:j?$:null,origin:`http://${D}${j?":"+$:""}`,path:""})}}let m=g=>[...n.get(g.name)?.parseResults?.values()??[]].some(w=>(w.routes??[]).length>0);for(let g of t){let w=o.get(g.name);if(w.isServer=m(g),w.isServer){for(let[S,N]of w.env)if(ql.test(S))for(let y of N)y.kind==="url"&&y.file&&(y.scoped||H.posix.dirname(y.file)===(wi(H.relative(e,g.rootPath))||"."))&&l(y.host,g.name,`${S} in ${y.file} (the server's own public address)`)}}for(let g of t){let w=o.get(g.name);for(let[,S]of n.get(g.name)?.parseResults??[])for(let N of S.httpClients?.listens??[])for(let y of h(w,N.parts)){let x=Ao(y.text);x&&w.ports.add(x)}}for(let g of t)for(let w of o.get(g.name).ports)a(s,w,g.name);for(let g of t)for(let w of o.get(g.name).weakPorts)t.some(S=>o.get(S.name).ports.has(w))||a(s,w,g.name);function h(g,w){let S=[{text:"",evidence:[]}];for(let N of w){let y;if(N.t==="lit")y=[{text:N.v,evidence:[]}];else if(N.t==="env"){let b=g.env.get(N.name)??[];y=[];for(let k of b)y.push({text:k.kind==="port"?String(k.port):k.origin+k.path,evidence:[{env:N.name,file:k.file}]});!y.length&&N.fallback&&(y=h(g,N.fallback).map($=>({text:$.text,evidence:[{env:N.name,file:null,fallback:!0},...$.evidence]})))}else y=[];if(!y.length)return[];let x=[];for(let b of S)for(let k of y)if(x.push({text:b.text+k.text,evidence:[...b.evidence,...k.evidence]}),x.length>=8)break;S=x.slice(0,8)}return S}let v=(g,w)=>{let S=[],N=g.host,y=i.get(N)??[];for(let x of y)S.push(x);if(Gl.has(N)||y.length&&y.some(x=>x.via==="docker-compose service name")){let x=g.port??(g.scheme==="https"||g.scheme==="wss",null);if(x)for(let b of s.get(x)??[])S.some(k=>k.service===b)||S.push({service:b,via:`port ${x} (a service listening there)`})}return S.filter(x=>x.service!==w)};return{resolveBase(g,w){let S=o.get(g);if(!S||!w.length)return{status:"unknown"};let N=h(S,w);if(!N.length)return{status:"unknown"};let y=[],x=new Set;for(let $ of N){let j=Ve($.text)??($.text.startsWith("//"),null);if(j){x.add(j.origin);for(let D of v(j,g))y.push({...D,u:j,evidence:$.evidence})}}if(!x.size)return{status:"unknown"};let b=[...new Set(y.map($=>$.service))];if(b.length===0)return{status:"external",origins:[...x].sort()};if(b.length>1)return{status:"ambiguous",services:b.sort()};let k=y[0];return{status:"service",service:k.service,via:k.via,origin:k.u.origin,basePath:k.u.path,evidence:k.evidence.filter(($,j,D)=>D.findIndex(L=>L.env===$.env&&L.file===$.file)===j)}},resolveProxy(g,w){let S=o.get(g);for(let N of S?.proxies??[]){if(N.prefix&&w!==N.prefix&&!w.startsWith(N.prefix+"/"))continue;let y=v(N.target,g),x=[...new Set(y.map(b=>b.service))];if(x.length===1)return{status:"service",service:x[0],via:`${N.kind} ${N.prefix||"/"} -> ${N.target.origin}`,origin:N.target.origin,basePath:N.target.path,strip:N.strip?N.prefix.split("/").filter(Boolean).length:0,evidence:[{env:null,file:N.file}]}}return{status:"unknown"}},portsOf:g=>[...o.get(g)?.ports??[]].sort((w,S)=>w-S),hostClaims:()=>[...i].sort((g,w)=>g[0]<w[0]?-1:1)}}function Cn(e){try{return To.readdirSync(e).sort()}catch{return[]}}var En=e=>String(e).toLowerCase();function Pn(e){let t=[];for(let n of e)n.t==="lit"&&t.length&&t[t.length-1].t==="lit"?t[t.length-1]={t:"lit",v:t[t.length-1].v+n.v}:t.push(n);return t}function _i(e,t){let n=[];for(let r of e){if(r.t!=="param"){n.push(r);continue}let o=t?.get(r.index);o?n.push(...o):n.push({t:"ref",name:r.name})}return Pn(n)}function Oo(e){if(!e.length)return null;let t=e.slice(),n="none",r=null,o=t[0];if(o.t==="lit"){let c=/^(https?:)\/\/([^/?#]*)(.*)$/.exec(o.v);if(c){n="abs",r=c[2];let d=c[3];if(t=d?[{t:"lit",v:d},...t.slice(1)]:t.slice(1),/^(www\.)?(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)(:\d+)?$/.test(r)===!1&&!/\.(local|internal|svc)$/.test(r)&&!/^[a-z0-9-]+(:\d+)?$/.test(r))return null}else if(!o.v.startsWith("/"))return null}else{for(n="var";t.length&&t[0].t!=="lit";)t.shift();if(!t.length||!t[0].v.startsWith("/"))return null}let s="",i=0,a=!1;for(let c of t){if(a)break;if(c.t==="lit"){let d=c.v.search(/[?#]/);d>=0?(s+=c.v.slice(0,d),a=!0):s+=c.v}else s+="",i++}if(!s.startsWith("/")&&!(s===""&&n==="abs"))return null;s===""&&(s="/");let l=s.split("/").slice(1).map(c=>c.includes("")?":p":c);for(;l.length>1&&l[l.length-1]==="";)l.pop();return{base:n,host:r,segments:l,placeholders:i,literal:n==="none"&&i===0}}function $i(e){if(!e.length)return[];let t=e[0];if(t.t==="lit"){let r=/^((?:https?|wss?):\/\/[^/?#]*)/.exec(t.v);return r?[{t:"lit",v:r[1]}]:[]}let n=[];for(let r of e){if(r.t==="lit"&&r.v.startsWith("/"))break;n.push(r)}return n}var Xl=e=>String(e||"").split("/").filter(Boolean),Fi=e=>[...new Set(e)];function Ii(e){let t=e.evidence??[];return{env:Fi(t.filter(n=>n.env).map(n=>n.env)),files:Fi(t.filter(n=>n.file).map(n=>n.file)),origin:e.origin,via:e.via,...t.some(n=>n.fallback)?{usedFallback:!0}:{}}}var ji=(e,t)=>"base URL "+(e.env.length?e.env.join(", ")+(e.files.length?" in "+e.files.join(", "):"")+" = ":e.files.length?"(from "+e.files.join(", ")+") ":"")+e.origin+" belongs to "+t+" ("+e.via+")",Zl=e=>{let t=String(e).split(/[?#]/)[0].split("/").slice(1).map(n=>n.startsWith(":")||/^\{.*\}$/.test(n)||n==="*"?":p":n);for(;t.length>1&&t[t.length-1]==="";)t.pop();return t};function Ci(e,t){if(e.length===t.length){let n=!0,r=!0;for(let o=0;o<e.length;o++){let s=e[o],i=t[o];if(s!==i&&(n=!1),!(s===i||s===":p"||i===":p")){r=!1;break}}if(n)return 3;if(r)return 2}if(e[0]==="api"&&e.length>1){let n=e.slice(1);if(/^v\d+$/.test(n[0])&&n.length>1&&(n=n.slice(1)),n.length===t.length&&n.every((r,o)=>r===t[o]||r===":p"||t[o]===":p"))return 1}return 0}function Ql(e,t,n,r,o){let s=(n.importBindings??[]).find(p=>p.local===r);if(!s)return null;let i=Ae(s.source,t,o);if(!i)return null;let a=e.parseResults.get(i),l=p=>e.nodes.find(f=>f.filePath===i&&f.name===p&&f.type!=="moduleRoot")?.id??null;if(s.kind==="named"&&s.imported)return l(s.imported);let c=a?.exportBindings;if(c?.default&&c.default!=="<anon>")return l(c.default);let d=Object.keys(c?.named??{});return d.length===1?l(d[0]):null}function ed(e){let t=[],n=[...e.parseResults.keys()];for(let[r,o]of e.parseResults){let s=e.nodes.filter(l=>l.filePath===r);if(s[0]?.category!=="backend")continue;let i=Te(r,o),a=le(r,e.nodes);for(let l of o.routes??[]){let c=null;l.isInlineHandler?c=i.get(l):l.nest?c=s.find(p=>p.type==="classMethod"&&p.className===l.nest.className&&p.name===l.nest.methodName)?.id??null:l.handlerName&&a.has(l.handlerName)?c=a.get(l.handlerName):l.handlerName&&(c=Ql(e,r,o,l.handlerName,n));let d=!1;c||(c=fe(l.startLine,s)?.id??null,d=!0),c&&t.push({method:En(l.method),path:l.path,segments:Zl(l.path),literal:!/[:*{]/.test(l.path),nodeId:c,file:r,line:l.startLine,fallback:d})}}return t}var td=/^(ws|uws|websocket|@nestjs\/platform-ws|@fastify\/websocket|fastify-websocket|express-ws)$/,nd=/^(socket\.io|@nestjs\/platform-socket\.io|socket\.io-client)$/;function Ei(e){let t=[...e].some(r=>nd.test(r)),n=[...e].some(r=>td.test(r));return t&&n?"unknown":t?"socketio":n?"ws":null}function od(e){let t=[],n=new Set;for(let[,r]of e.parseResults)for(let o of r.imports??[])n.add(o.source);for(let[r,o]of e.parseResults){let s=o.socketListeners??[],i=s.find(h=>h.eventName==="connection");if(!i)continue;let a=Te(r,o),l=le(r,e.nodes),c=h=>h.isInlineHandler?a.get(h):h.handlerName&&l.has(h.handlerName)?l.get(h.handlerName):null,d=c(i);if(!d)continue;let p=h=>i.handlerStartLine!=null&&h.startLine>=i.handlerStartLine&&h.startLine<=i.handlerEndLine,f=s.find(h=>h.eventName==="message"&&p(h))??s.find(h=>h.eventName==="message"),u=o.httpClients?.wsServers??[],m=Ei(new Set((o.imports??[]).map(h=>h.source)))??Ei(n)??"unknown";t.push({filePath:r,nodeId:d,line:i.startLine,messageNodeId:f?c(f):null,messageLine:f?.startLine??null,pathParts:u.find(h=>h.path)?.path??null,kind:m})}return t}function Pi(e,t,n={}){let r=n.repoRoot?bi(n.repoRoot,e,t):null,o=[],s=new Set,i={restCalls:0,restLinked:0,wsClients:0,wsLinked:0,wsSends:0,wsSendsLinked:0},a=c=>{let d=[c.fromService,c.fromNodeId,c.toService,c.toNodeId,c.via,c.key].join("\0");s.has(d)||(s.add(d),o.push(c))},l=new Map;for(let c of e){let d=t.get(c.name);d&&l.set(c.name,{routes:ed(d),wsServers:od(d)})}for(let c of e){let d=t.get(c.name);if(!d)continue;let p=[...d.parseResults.keys()],f=new Map,u=new Map;for(let[y,x]of d.parseResults){let b=x.httpClients;if(b){for(let k of b.httpInstances??[])(f.get(k.name)??f.set(k.name,[]).get(k.name)).push(k);for(let k of b.httpCalls??[])(k.parts.some(j=>j.t==="param")||k.method&&typeof k.method=="object")&&k.fn?.name&&(u.get(k.fn.name)??u.set(k.fn.name,[]).get(k.fn.name)).push({filePath:y,call:k})}}let m=y=>{if(!y.startsWith("inst:")&&!y.startsWith("obj:"))return[];let x=f.get(y.slice(y.indexOf(":")+1));return x&&x.length===1?x[0].parts:y.startsWith("obj:")?null:[{t:"ref",name:"?"}]},h=[],v=(y,x)=>fe(x,d.nodes.filter(b=>b.filePath===y)),g=new Set,w=y=>y.parts.some(x=>x.t==="param")||y.method&&typeof y.method=="object";for(let[y,x]of d.parseResults){let b=x.httpClients;if(b){for(let k of b.httpCalls??[]){if(w(k))continue;let $=m(k.client);if($===null)continue;let j=v(y,k.line);j&&h.push({filePath:y,line:k.line,nodeId:j.id,method:k.method,parts:Pn([...$,...k.parts]),via:k.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let k of b.pathCallsites??[]){let $=u.get(k.callee);if($)for(let j of $){let D=j.filePath===y;if(!D){let O=(x.importBindings??[]).find(W=>W.local===k.callee||W.imported===k.callee);O&&Ae(O.source,y,p)===j.filePath&&(D=!0)}if(!D)continue;let L=new Map(k.args.map(O=>[O.i,O.parts])),K=typeof j.call.method=="object"&&j.call.method?(()=>{let O=L.get(j.call.method.param);return O&&O.length===1&&O[0].t==="lit"?O[0].v.toUpperCase():"?"})():j.call.method,z=v(y,k.line);z&&(g.add(j.call),h.push({filePath:y,line:k.line,nodeId:z.id,method:K,parts:_i([...m(j.call.client),...j.call.parts],L),via:j.call.client,wrapper:k.callee}))}}}}for(let[y,x]of d.parseResults)for(let b of x.httpClients?.httpCalls??[]){if(!w(b)||g.has(b))continue;let k=m(b.client);if(k===null)continue;let $=v(y,b.line);$&&h.push({filePath:y,line:b.line,nodeId:$.id,method:typeof b.method=="object"&&b.method?"?":b.method,parts:_i([...k,...b.parts],null),via:b.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let y of h){let x=Oo(y.parts);if(!x)continue;i.restCalls++;let b=0,k=[];for(let z of e){if(z.name===c.name)continue;let O=l.get(z.name);if(O)for(let W of O.routes){if(!(y.method==="?"||y.method==null||W.method===En(y.method)||W.method==="all"||W.method==="use"))continue;let te=Ci(x.segments,W.segments);te&&(te>b&&(b=te,k.length=0),te===b&&k.push({service:z.name,route:W}))}}let $={status:"unknown"};if(r){let z=Pn(y.parts);if(x.base==="none"?$=r.resolveProxy(c.name,"/"+x.segments.join("/")):$=r.resolveBase(c.name,$i(z)),$.status==="service"){let O=Xl($.basePath);if(O.length||$.strip){let W=[...O,...x.segments.slice($.strip||0)];for(let G of l.get($.service)?.routes??[])(y.method==="?"||y.method==null||G.method===En(y.method)||G.method==="all"||G.method==="use")&&Ci(W,G.segments)&&!k.some(ge=>ge.service===$.service&&ge.route.nodeId===G.nodeId)&&k.push({service:$.service,route:G,viaBasePath:!0})}}}if(!k.length)continue;let j=new Set(k.map(z=>z.service+"\0"+z.route.nodeId)),D=typeof y.method=="string"&&y.method!=="?",L=b===3&&x.literal&&D&&j.size===1&&k[0].route.literal&&!k[0].route.fallback&&k[0].route.method===En(y.method),K=[];x.base==="var"&&K.push("base URL is a variable, so the target service is guessed from the path"),x.base==="abs"&&K.push("absolute URL"),x.placeholders&&K.push("path has parameters"),b===1&&K.push("leading /api removed from the client path"),b===2&&K.push("route parameters matched fuzzily"),D||K.push("method not known"),j.size>1&&K.push(j.size+" candidate routes"),k.some(z=>z.route.fallback)&&K.push("route handler not resolved: linked to the function that registers the route"),$.status==="external"&&K.push("base URL is "+$.origins.join(" / ")+", which no service of this repo owns"),$.status==="ambiguous"&&K.push("base URL could belong to "+$.services.join(" or "));for(let z of k){i.restLinked++;let O=!L&&$.status==="service"&&$.service===z.service&&!z.route.fallback,W=O?Ii($):null,G=L?"exact":O?"resolved":"inferred",te=!L&&$.status==="service"&&$.service!==z.service?["base URL belongs to "+$.service+", not this service"]:[];a({fromService:c.name,fromNodeId:y.nodeId,toService:z.service,toNodeId:z.route.nodeId,via:"httpCall",key:`${D?y.method:"ANY"} ${"/"+x.segments.join("/")}`,confidence:G,method:D?y.method:null,url:"/"+x.segments.join("/"),client:y.via,...y.wrapper?{wrapper:y.wrapper}:{},line:y.line,...L?{}:O?{reason:ji(W,z.service)+(D?"":"; method not known"),resolvedFrom:W}:{reason:[...K,...te].join("; ")||"path-only match"}})}}let S=[];for(let[y,x]of d.parseResults)for(let b of x.httpClients?.wsClients??[])S.push({filePath:y,w:b});let N=y=>y.client==="io"?"socketio":"ws";for(let{filePath:y,w:x}of S){let b=v(y,x.line);if(!b)continue;i.wsClients++;let k=Pn(x.parts),$=/^wss?:\/\//.test(k[0]?.v??"")?Oo([{t:"lit",v:k[0].v.replace(/^ws(s?):/,"http$1:")},...k.slice(1)]):Oo(k),j=r&&$?r.resolveBase(c.name,$i(k)):{status:"unknown"};for(let D of e)if(D.name!==c.name)for(let L of l.get(D.name)?.wsServers??[]){if(L.kind!=="unknown"&&L.kind!==N(x))continue;let K=L.pathParts&&L.pathParts.every(te=>te.t==="lit")?"/"+L.pathParts.map(te=>te.v).join("").replace(/^\//,""):null,z=$?"/"+$.segments.join("/"):null;if(K&&z&&K!==z&&K!=="/"&&z!=="/")continue;let O=!!($&&$.literal&&K&&z===K&&L.kind!=="unknown"),W=!O&&j.status==="service"&&j.service===D.name,G=W?Ii(j):null;i.wsLinked++,a({fromService:c.name,fromNodeId:b.id,toService:D.name,toNodeId:L.nodeId,via:"webSocket",key:z??"(url unknown)",confidence:O?"exact":W?"resolved":"inferred",url:z,client:x.client,line:x.line,...O?{}:W?{reason:ji(G,D.name),resolvedFrom:G}:{reason:"WebSocket connection matched to a WebSocket server of another service ("+($?.base==="var"?"URL base is a variable":"no path on the server to compare")+(j.status==="external"?"; base URL is "+j.origins.join(" / ")+", which no service of this repo owns":"")+")"}})}}if(S.length){let y=new Set(S.map(({w:x})=>N(x)));for(let[x,b]of d.parseResults)for(let k of b.httpClients?.wsSends??[]){let $=v(x,k.line);if($){i.wsSends++;for(let j of e)if(j.name!==c.name)for(let D of l.get(j.name)?.wsServers??[])!D.messageNodeId||D.kind!=="unknown"&&!y.has(D.kind)||(i.wsSendsLinked++,a({fromService:c.name,fromNodeId:$.id,toService:j.name,toNodeId:D.messageNodeId,via:"webSocketMessage",key:"message",eventName:"message",confidence:"inferred",client:k.recv,line:k.line,reason:"a message sent over a socket whose payload is built at run time; delivered to the message listener of a WebSocket server of another service"}))}}}}if(n.serverPush!==!1){let c=new Map;for(let p of o)if(p.via==="webSocket"){let f=p.fromService+"\0"+p.toService;(c.get(f)??c.set(f,[]).get(f)).push(p)}let d=new Map;for(let p of c.values())(d.get(p[0].toService)??d.set(p[0].toService,new Set).get(p[0].toService)).add(p[0].fromService);for(let[,p]of[...c].sort((f,u)=>f[0]<u[0]?-1:1)){let f=p[0].fromService,u=p[0].toService,m=t.get(f),h=t.get(u);if(!m||!h||!(l.get(u)?.wsServers??[]).length)continue;let v=new Set(p.map(N=>N.fromNodeId.split("::")[0])),g=[];for(let[N,y]of m.parseResults){if(!v.has(N))continue;let x=le(N,m.nodes),b=Te(N,y),k=m.nodes.filter($=>$.filePath===N);for(let $ of y.httpClients?.wsReceivers??[]){let j=$.handlerName&&x.get($.handlerName)||fe($.line,k)?.id;j&&g.push({id:j,line:$.line})}for(let $ of y.socketListeners??[]){if($.eventName!=="message")continue;let j=$.isInlineHandler?b.get($):$.handlerName&&x.get($.handlerName)||null;j&&g.push({id:j,line:$.startLine})}}let w=new Set(m.resolvedEdges.filter(N=>N.resolved&&N.targetNodeId&&N.type!=="returnValue").map(N=>N.fromNodeId));for(let N=g.length-1;N>=0;N--)w.has(g[N].id)||g.splice(N,1);if(!g.length)continue;let S=d.get(u)?.size??1;for(let[N,y]of h.parseResults){let x=h.nodes.filter(b=>b.filePath===N);for(let b of[...y.httpClients?.wsSends??[],...y.httpClients?.wsServerSends??[]]){let k=fe(b.line,x);if(k)for(let $ of g)i.wsPushLinked=(i.wsPushLinked??0)+1,a({fromService:u,fromNodeId:k.id,toService:f,toNodeId:$.id,via:"webSocketDelivery",key:"message",eventName:"message",confidence:"inferred",client:b.recv,line:b.line,receiverLine:$.line,reason:"a message the server sends over a WebSocket (payload built at run time) is taken in by the message handler of "+f+", which connects to this server"+(S>1?"; "+S+" services connect to this server, so it may be meant for another one":""),...S>1?{candidates:S}:{}})}}}}return o.sort((c,d)=>c.fromService+c.fromNodeId+c.via+c.key+c.toService+c.toNodeId<d.fromService+d.fromNodeId+d.via+d.key+d.toService+d.toNodeId?-1:1),{edges:o,stats:i}}function Li(e,t){let n=new Map;for(let[r,o]of e){let s=t.filter(a=>a.filePath===r),i=o.rawSocketTypeChecks??[];for(let a of i){let l=fe(a.startLine,s);l&&n.set(a.eventName,l.id)}}return n}import rd from"node:fs";import sd from"node:path";function Ri(e){let t=["index.html","public/index.html","client/index.html","frontend/index.html","src/index.html"];for(let n of t){let r=sd.join(e,n);if(rd.existsSync(r))return r}return null}import Ln from"node:fs";import Rn from"node:path";var id=new Set(["node","tsx","ts-node","nodemon","bun","deno","ts-node-esm"]),ad=new Set(["watch","run","start","dev"]),cd=/\.[cm]?[jt]sx?$/,ld=["start","dev","serve","run"];function dd(e){for(let t of String(e).split(/&&|\|\||;|\|/)){let n=t.trim().split(/\s+/).filter(Boolean).map(o=>o.replace(/^["']|["']$/g,"")),r=n.findIndex(o=>id.has(Rn.basename(o).replace(/\.cmd$/,"")));if(!(r<0)){for(let o of n.slice(r+1))if(!(o.startsWith("-")||ad.has(o)||o.includes("="))){if(cd.test(o))return o;break}}}return null}var fd=e=>String(e).replace(/^@[^/]+\//,"");function Ti(e){let t;try{t=JSON.parse(Ln.readFileSync(Rn.join(e,"package.json"),"utf8"))}catch{return[]}let n=[],r=(o,s,i={})=>{if(typeof o!="string"||!o)return;let a=s==="script"?null:In(e,o,t);a?n.push({file:a.file,kind:s,...i,mappedFrom:o,mappedBy:a.how}):n.push({file:Rn.resolve(e,o),kind:s,...i})};if(typeof t.bin=="string")r(t.bin,"bin",{binName:fd(t.name??Rn.basename(e))});else if(t.bin&&typeof t.bin=="object")for(let[o,s]of Object.entries(t.bin))r(s,"bin",{binName:o});for(let o of ld){let s=t.scripts?.[o]&&dd(t.scripts[o]);s&&r(s,"script")}return r(t.main,"main"),n}function Ai(e){try{let t=Ln.openSync(e,"r"),n=Buffer.alloc(120),r=Ln.readSync(t,n,0,120,0);return Ln.closeSync(t),/^#!.*\b(node|tsx|ts-node|bun)\b/.test(n.toString("utf8",0,r).split(/\r?\n/)[0])}catch{return!1}}import Tn from"node:fs";import ut from"node:path";var ud=50,pd=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Oi=["",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts","/index.js","/index.ts","/index.mjs","/index.cjs","/index.tsx","/index.jsx"];function Mo(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=Mo(t);if(n)return n}return null}if(e&&typeof e=="object")for(let t of["import","node","require","default"]){let n=Mo(e[t]);if(n)return n}return null}function Mi(e,t){let n;try{n=JSON.parse(Tn.readFileSync(ut.join(e,"package.json"),"utf8"))}catch{return null}let r=n.exports,o=typeof r=="string"||Array.isArray(r)?r:r&&typeof r=="object"?r["."]??(Object.keys(r).some(c=>c.startsWith("."))?null:r):null,s=Mo(o)??(typeof n.module=="string"?n.module:null)??(typeof n.main=="string"?n.main:null);if(!s)return null;let i=new Set(t.map(c=>ut.resolve(c))),a=ut.resolve(e,s);for(let c of Oi)if(i.has(a+c))return t.find(d=>ut.resolve(d)===a+c);let l=[];try{l=Tn.readdirSync(e).filter(c=>pd.test(c)).sort()}catch{}for(let c of l){let d;try{d=Tn.readFileSync(ut.join(e,c),"utf8")}catch{continue}let p=/\bentry(?:Points)?\s*:\s*[\[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/.exec(d);if(!p)continue;let f=ut.resolve(e,p[1]);for(let u of Oi)if(i.has(f+u))return t.find(m=>ut.resolve(m)===f+u)}return null}function Hi(e,t,n,r,o=null){let s=new Map;for(let h of n){let v=s.get(h.filePath);v||s.set(h.filePath,v=[]),v.push(h)}let i=new Map,a=(h,v)=>{v&&(!i.has(v.id)||h<i.get(v.id))&&i.set(v.id,h)},l=new Map,c=(h,v)=>{let g=l.get(h);if(!g){g=new Map;let w="";try{w=Tn.readFileSync(h,"utf8")}catch{}for(let S of w.matchAll(/^[ \t]*(?:export\s+)?const\s+([\w$]+)\s*(?::[^=\n]+)?=\s*([\w$]+)\s*(?:as\s+[^;\n]+)?;?[ \t]*$/gm))S[1]!==S[2]&&g.set(S[1],S[2]);l.set(h,g)}return g.get(v)??null},d=(h,v)=>(s.get(h)??[]).find(g=>(g.type==="function"||g.type==="arrowFunction")&&g.name===v),p=(h,v)=>(s.get(h)??[]).filter(g=>g.type==="classMethod"&&g.className===v&&g.name!=="constructor"&&!/^[_#]/.test(g.name)),f=new Set;function u(h,v,g,w=0){let S=d(h,g);if(S){a(v,S);return}let N=p(h,g);for(let j of N)a(`${v}.${j.name}`,j);if(N.length||!o)return;let y=o.resolveName(h,g);if(y){a(v,y);return}let x=o.bindingFor(h,g),b=x&&w<3?o.resolveImport(h,x.source,x.kind,x.imported):null;if(b?.file&&b.local&&b.local!=="default"&&c(b.file,b.local)){u(b.file,v,b.local,w+1);return}let k=o.classForImport(h,g);if(k?.className)for(let j of p(k.file,k.className))a(`${v}.${j.name}`,j);if(k?.className)return;let $=c(h,g);$&&w<3&&u(h,v,$,w+1)}function m(h,v,g){let w=h+"|"+(g?[...g.keys()].sort().join(","):"*");if(f.has(w)||v>3)return;f.add(w);let S=t.get(h)?.exportBindings;if(!S)return;let N=y=>!g||g.has(y);for(let[y,x]of Object.entries(S.named??{}))N(y)&&u(h,g?.get(y)??y,x);S.default&&N("default")&&S.default!=="<anon>"&&u(h,g?.get("default")??S.default,S.default);for(let y of S.reexports??[]){if(!N(y.exported))continue;let x=Ae(y.source,h,r);x&&m(x,v+1,new Map([[y.imported,g?.get(y.exported)??y.exported]]))}for(let y of S.stars??[]){let x=Ae(y,h,r);x&&(g?m(x,v+1,g):m(x,v+1,null))}}return m(e,0,null),[...i].map(([h,v])=>({name:v,nodeId:h})).sort((h,v)=>h.name<v.name?-1:h.name>v.name?1:h.nodeId<v.nodeId?-1:1).slice(0,ud)}Le();import Ui from"node:path";import{fileURLToPath as md}from"node:url";import{Parser as Di,Language as hd}from"web-tree-sitter";var lh=Ui.dirname(md(globalThis.__canopyUrl("src/stage2_parse/initHtmlParser.js")));async function Bi(){await Di.init();let e=new Di,t=Ui.join(je("tree-sitter-html"),"tree-sitter-html.wasm"),n=await hd.load(t);return e.setLanguage(n),{parser:e,language:n}}function zi(e,t){let r=ee(t,"htmlScriptRoot.scm").matches(e.rootNode);for(let o of r){let s=o.captures.find(a=>a.name==="attr_name"),i=o.captures.find(a=>a.name==="script_src");if(s&&s.node.text==="src"&&i)return i.node.text}return null}function Wi(e,t,n){let r=[];e.forEach((l,c)=>{l.steps.forEach(d=>{if(!d.hasOwnSubTrace)return;let p=e.findIndex((f,u)=>u!==c&&f.steps[0]?.nodeId===d.nodeId);p!==-1&&r.push({fromWorkflowIndex:c,toWorkflowIndex:p,atNodeId:d.nodeId})})});let o=new Map;for(let l of t)o.set(l.id,l.serviceName??null);let s=new Map;function i(l,c,d,p){if(!l||!c||l===c)return;let f=`${l} -> ${c} -> ${d}`;s.has(f)?s.get(f).count+=1:s.set(f,{fromService:l,toService:c,viaMatchType:d,count:1});let u=s.get(f);p==="exact"?u.exact=(u.exact??0)+1:p==="inferred"?u.inferred=(u.inferred??0)+1:p==="resolved"&&(u.resolved=(u.resolved??0)+1)}for(let l of n){if(!l.resolved||!l.fromNodeId||!l.targetNodeId)continue;let c=o.get(l.fromNodeId)??null,d=o.get(l.targetNodeId)??null;i(c,d,l.matchType,l.confidence)}let a=Array.from(s.values());return{workflowLinks:r,serviceLinks:a}}var xd=J.dirname(gd(globalThis.__canopyUrl("src/index.js"))),qi=24*1e3*1e3;async function Ho(e,t={}){e=J.resolve(e),console.log(`
20
+ return ${a};})()`}function or(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=he(o,t);if(s.has(e))return{targetId:s.get(e),via:"cross-file"}}return{targetId:null,via:null}}function Zi(e,t,n,r,o,s=[],i=null){if(!n.some(c=>!c.isInlineHandler)&&!r.some(c=>!c.isInlineHandler)&&!s.some(c=>!c.isInlineHandler))return e;let a=e.map(c=>({...c}));for(let c of n){if(c.isInlineHandler)continue;let l=c.nest?e.find(u=>u.type==="classMethod"&&u.filePath===t&&u.className===c.nest.className&&u.name===c.nest.methodName):null,{targetId:d,via:f}=c.nest?{targetId:l?.id??null,via:"in-file"}:or(c.handlerName,e,o,i);if(d){let u=a.find(h=>h.id===d);u&&(u.isEntryPoint=!0,u.trigger={type:"route",label:`${c.method.toUpperCase()} ${c.path}`,resolvedVia:f})}}for(let c of r){if(c.isInlineHandler)continue;let{targetId:l,via:d}=or(c.handlerName,e,o,i);if(l){let f=a.find(u=>u.id===l);f&&(f.isEntryPoint=!0,f.trigger={type:"listener",label:c.eventName,resolvedVia:d})}}for(let c of s){if(c.isInlineHandler)continue;let{targetId:l,via:d}=or(c.handlerName,e,o,i);if(l){let f=a.find(u=>u.id===l);f&&(f.isEntryPoint=!0,f.trigger={type:"socketListener",label:c.eventName,resolvedVia:d})}}return a}function rr(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 Qi(e,t,n=rr(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 ea(e,t){let n=rr(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:Qi(i,t,n)}));return s.sort((i,a)=>a.fallbackScore-i.fallbackScore),s.slice(0,15)}function sr(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 ir(e,t,n,r=8){let o=new Set([e]),s=c=>n.find(l=>l.id===c)?.category??"unknown",i=[{nodeId:e,depth:0,parentNodeId:null,category:s(e)}],a=[{nodeId:e,depth:0}];for(;a.length>0;){let c=a.shift();if(c.depth>=r)continue;let l=t.get(c.nodeId)||[];for(let d of l){let f=d.targetNodeId;if(o.has(f))continue;o.add(f);let u={nodeId:f,depth:c.depth+1,parentNodeId:c.nodeId,category:s(f),callLine:d.line,callColumn:d.column,branchPath:d.branchPath,edgeType:d.edgeType};i.push(u),a.push(u)}}return i}function ta(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 na(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(c=>c.filePath===e.filePath&&c.id!==e.id&&c.type!=="moduleRoot"&&t.some(l=>l.resolved&&l.targetNodeId===c.id))){let c=ta(e,n,t);if(c.length>0)return e.lexicalSiblings=c.map(l=>l.id),!0}return!1}function oa(e,t,n,r,o=8,s=null){let i=[],a=new Set(e.map(l=>l.id)),c=[...e];for(;c.length>0;){let l=c.shift(),d=ir(l.id,t,n,o);i.push({entryPointId:l.id,entryPointName:l.name,trigger:l.trigger??null,steps:d});let f=s?new Set(ir(l.id,s,n,o).map(u=>u.nodeId)):null;for(let u of d){if(f&&!f.has(u.nodeId)||u.nodeId===l.id||a.has(u.nodeId))continue;let h=n.find(p=>p.id===u.nodeId);h&&na(h,r,n)&&(a.add(h.id),u.hasOwnSubTrace=!0,h.lexicalSiblings&&(u.lexicalSiblings=h.lexicalSiblings),c.push({id:h.id,name:h.name,trigger:null}))}}return i}function ra(e,t,n=gs){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 sa(e){return e.steps.filter(n=>n.depth>0).map(n=>n.nodeId).sort().join(" | ")}function ia(e){let t=new Map;for(let n of e){let r=sa(n),o=r===""?`__no_calls__${n.entryPointName}`:r;t.has(o)||t.set(o,[]),t.get(o).push(n)}return t}function aa(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 zn from"node:path";function ca(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 la(e){return e.name.replace(/([A-Z])/g," $1").trim().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}var da=60,mf=24;function fa(e,t=null){let n=e.map(r=>{let o=ca(r),s=r.trigger?.workflowName??o??la(r);return{...r,name:s}});return t?.nodes?vf(n,t.nodes):n}var ar=(e,t)=>e.length>t?e.slice(0,t-1)+"\u2026":e,hf=new Set(["function","arrowFunction","classMethod"]);function gf(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&&hf.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 l=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||(!l||d.endLine-d.startLine<l.endLine-l.startLine)&&(l=d);l&&(i=l.type==="classMethod"?l.className:l.name)}let a=null;if(o.trigger?.type==="route")a=String(o.trigger.label).split(" ")[0];else if(o.trigger?.type==="listener"){let l=/::listener:([^.#]+)\./.exec(s.id);l&&(a=l[1])}let c=zn.basename(s.filePath,zn.extname(s.filePath));return c==="index"&&(c=zn.basename(zn.dirname(s.filePath))),[i||null,a||null,c||null]}}var yf=(e,t)=>{let n=t.map(r=>ar(r,mf)).join(", ");return e.endsWith(")")?e.slice(0,-1)+", "+n+")":e+" ("+n+")"};function vf(e,t){let n=gf(t),r=e.map(i=>({w:i,base:i.name,parts:[],used:new Set,stuck:!1,q:null})),o=i=>i.parts.length?yf(i.base,i.parts):i.base,s=()=>{let i=new Map;for(let a of r){let c=o(a);(i.get(c)??i.set(c,[]).get(c)).push(a)}return[...i.values()].filter(a=>a.length>1)};for(let i=0;i<4;i++){let a=!1;for(let c of s()){if(c.some(u=>u.stuck))continue;for(let u of c)u.q??=n(u.w);let l=[0,1,2].filter(u=>c.every(h=>!h.used.has(u))),d=l.find(u=>new Set(c.map(h=>h.q[u]??"")).size>1),f=d!==void 0;if(f||(d=l.find(u=>c.every(h=>h.q[u]))),d===void 0){for(let u of c)u.stuck=!0;continue}for(let u of c)u.used.add(d),u.q[d]&&u.parts.push(u.q[d]),f||(u.stuck=!0);a=!0}if(!a)break}for(let i of s())i.sort((a,c)=>a.w.steps[0].nodeId<c.w.steps[0].nodeId?-1:a.w.steps[0].nodeId>c.w.steps[0].nodeId?1:0),i.forEach((a,c)=>{c>0&&(a.suffix=` (${c+1})`)});return r.map(i=>{let a=o(i);return i.suffix&&(a=ar(a,da-i.suffix.length)+i.suffix),{...i.w,name:ar(a,da)}})}var xf=e=>e;function ua(e,t){let n=new Map;for(let[r,o]of e){let s=t.filter(l=>l.filePath===r);if(s[0]?.category!=="backend")continue;let i=o.routes??[],a=qe(r,o),c=he(r,t);for(let l of i){let d=qt(l.path);if(l.isInlineHandler){let u=a.get(l);n.set(d,u);continue}if(l.nest){let u=xf(s).find(h=>h.type==="classMethod"&&h.className===l.nest.className&&h.name===l.nest.methodName);u&&n.set(d,u.id);continue}if(!l.handlerName||!c.has(l.handlerName))continue;let f=c.get(l.handlerName);n.set(d,f)}}return n}import $t from"node:fs";import ne from"node:path";var Wn=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],wf=/(^|\/)(dist|build|out|built|compiled|esm|cjs|lib|output)(\/|$)/,pa=/(^|\/)(dist|build|out|built|compiled|esm|cjs|output)(\/|$)/,Sf=/\b(esbuild|tsup|tsdown|tsc|rollup|webpack|ncc|swc|babel|vite|parcel|bun\s+build|pkg|unbuild|microbundle|rspack)\b/,kf=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild|rspack)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Ve=e=>{try{return $t.statSync(e).isFile()}catch{return!1}},cr=e=>e.split(ne.sep).join("/"),lr=e=>{if(Ve(e)&&Wn.includes(ne.extname(e))&&!/\.d\.ts$/.test(e))return e;let t=e.replace(/\.(m|c)?js$/,"");for(let n of Wn)if(Ve(t+n)&&!/\.d\.ts$/.test(t+n))return t+n;return null},Gn=(e,t)=>{let n=ne.relative(e,t);return n&&!n.startsWith("..")&&!ne.isAbsolute(n)&&!/(^|[\\/])node_modules([\\/]|$)/.test(n)};function Nf(e,t){let n=Ve(t+".map")?t+".map":null;if(!n&&Ve(t))try{let a=$t.readFileSync(t,"utf8").slice(-400),c=/sourceMappingURL=([^\s*]+)/.exec(a);if(c&&!c[1].startsWith("data:")){let l=ne.resolve(ne.dirname(t),c[1]);Ve(l)&&(n=l)}}catch{}if(!n)return null;let r;try{r=JSON.parse($t.readFileSync(n,"utf8"))}catch{return null}let o=ne.resolve(ne.dirname(n),r.sourceRoot??""),s=(r.sources??[]).map(a=>ne.resolve(o,a)).filter(a=>Gn(e,a)&&Ve(a)&&Wn.includes(ne.extname(a)));if(s.length===1)return s[0];let i=ne.basename(t).replace(/\.(m|c)?js$/,"");return s.find(a=>ne.basename(a).replace(/\.[^.]+$/,"")===i)??null}function bf(e){try{return JSON.parse($t.readFileSync(e,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,"").replace(/,(\s*[}\]])/g,"$1"))}catch{return null}}function _f(e,t){for(let n of["tsconfig.build.json","tsconfig.json"]){let o=bf(ne.join(e,n))?.compilerOptions;if(!o?.outDir)continue;let s=cr(ne.normalize(o.outDir)).replace(/^\.\//,"").replace(/\/$/,"");if(!(t===s||t.startsWith(s+"/")))continue;let i=t.slice(s.length+1),a=o.rootDir?o.rootDir:$t.existsSync(ne.join(e,"src"))?"src":".",c=lr(ne.resolve(e,a,i));if(c)return c}return null}function $f(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=lr(ne.resolve(e,...n.slice(0,r),s,o));if(i&&Gn(e,i))return i}return null}function If(e,t,n){let r=ne.basename(n).replace(/\.(m|c)?js$/,"");for(let o of["build","compile","bundle","prepare","prepublishOnly","prepack","postinstall"]){let s=t.scripts?.[o];if(!s||!Sf.test(s))continue;let i=[];for(let l of s.split(/\s+/).map(d=>d.replace(/^["']|["']$/g,"").replace(/^--?[\w-]+=/,""))){if(!Wn.includes(ne.extname(l))||/\.d\.ts$/.test(l))continue;let d=ne.resolve(e,l);Ve(d)&&Gn(e,d)&&!pa.test(cr(ne.relative(e,d)))&&i.push(d)}let a=[...new Set(i)];if(a.length===1)return a[0];let c=a.filter(l=>ne.basename(l).replace(/\.[^.]+$/,"")===r);if(c.length===1)return c[0];if(a.length)return a[0]}return null}function jf(e,t){let n=[];try{n=$t.readdirSync(e).filter(i=>kf.test(i)).sort()}catch{return null}let r=ne.basename(t).replace(/\.(m|c)?js$/,""),o=[];for(let i of n){let a;try{a=$t.readFileSync(ne.join(e,i),"utf8")}catch{continue}for(let c of a.matchAll(/\bentry(?:Points)?\s*:\s*[[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/g)){let l=lr(ne.resolve(e,c[1]));l&&Gn(e,l)&&o.push(l)}}let s=[...new Set(o)];return s.length===1?s[0]:s.find(i=>ne.basename(i).replace(/\.[^.]+$/,"")===r)??null}function qn(e,t,n){if(typeof t!="string"||!t)return null;let r=cr(ne.normalize(t)).replace(/^\.\//,""),o=ne.resolve(e,r);if(!wf.test(r)||Ve(o)&&!pa.test(r)||Ve(o)&&/\.ts$/.test(o))return null;let i=[["sourcemap",()=>Nf(e,o)],["tsconfig outDir",()=>_f(e,r)],["convention",()=>Ve(o)?null:$f(e,r)],["build script",()=>If(e,n??{},r)],["build config",()=>jf(e,r)]];for(let[a,c]of i){let l=null;try{l=c()}catch{}if(l&&l!==o)return{file:l,how:a}}return null}function ma(e,t){let n=new Map;for(let[r,o]of e){let s=o.socketListeners??[],i=qe(r,o),a=he(r,t);for(let c of s){if(c.isInlineHandler){let d=i.get(c);n.set(c.eventName,d);continue}if(!c.handlerName||!a.has(c.handlerName))continue;let l=a.get(c.handlerName);n.set(c.eventName,l)}}return n}import dr from"node:fs";import J from"node:path";var Fe=e=>String(e??"").trim().replace(/^["']|["']$/g,""),Jn=e=>e.replace(/^\s*#.*$/,"").replace(/\s+#.*$/,"");function ha(e){let t=/^(\/[A-Za-z0-9_\-./]*?)\/?(?=$|[:(*{[])/.exec(String(e).trim()),n=t?t[1]:"";return n==="/"?"":n.replace(/\/+$/,"")}function ga(e,t){let n=e.split(/\r?\n/).map(Jn),r=h=>h.length-h.trimStart().length,o=[],s=null,i=!1,a=null,c=!1,l=0,d=null,f=()=>{d?.key&&d.fromService&&d.fromService!=="?"&&s.hostRefs.push({name:d.key,service:d.fromService,property:d.property}),d=null},u=(h,p,m)=>{p==="name"?h.name=Fe(m):p==="rootDir"?h.rootDir=Fe(m):p==="startCommand"&&(h.startCommand=Fe(m))};for(let h of n){if(!h.trim())continue;let p=r(h),m=h.trim();if(p===0){f(),s=null,c=!1,i=/^services\s*:/.test(m),a=null;continue}if(!i)continue;let y=m.startsWith("-");if(y&&(a==null||p===a)){a=p,f(),s={name:null,rootDir:null,startCommand:null,kept:[],hostRefs:[]},o.push(s),c=!1;let x=/^-\s*([A-Za-z]+)\s*:\s*(.*)$/.exec(m);x&&u(s,x[1],x[2]);continue}if(!s)continue;let g=/^(?:-\s*)?([A-Za-z]+)\s*:\s*(.*)$/.exec(m);if(g){if(g[1]==="envVars"){f(),c=!0,l=p;continue}if(c&&p>l){if(y&&(f(),d={key:null,fromService:null,property:null}),!d)continue;if(g[1]==="key")d.key=Fe(g[2]);else if(g[1]==="value"&&d.key){let x=nt(d.key,Fe(g[2]),t);x&&s.kept.push(x)}else g[1]==="fromService"?d.fromService="?":g[1]==="name"&&d.fromService==="?"?d.fromService=Fe(g[2]):g[1]==="property"&&(d.property=Fe(g[2]));continue}c&&(f(),c=!1),u(s,g[1],g[2])}}return f(),o.filter(h=>h.name)}function ya(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[,c,l]=a;if(r===""&&c==="app"){let d=Fe(l);/^[a-z0-9][a-z0-9-]*$/i.test(d)&&(n.app=d)}else if(c==="internal_port"){let d=Number(Fe(l));Number.isInteger(d)&&d>=1&&d<=65535&&n.ports.push(d)}else if(r==="env"){let d=nt(c,Fe(l),t);d&&n.kept.push(d)}}return n}function va(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 c of i[1].split(/\s+/)){let l=Number(c.replace(/\/\w+$/,""));Number.isInteger(l)&&l>=1&&l<=65535&&n.ports.push(l)}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 c=/([A-Za-z_][A-Za-z0-9_]*)=("([^"]*)"|'([^']*)'|\S*)/g,l;for(;l=c.exec(a);){let d=nt(l[1],l[3]??l[4]??l[2],t);d&&n.kept.push(d)}}else{let c=/^([A-Za-z_][A-Za-z0-9_]*)\s+(.*)$/.exec(a);if(c){let l=nt(c[1],Fe(c[2]),t);l&&n.kept.push(l)}}}return n}function xa(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)?ot(s.replace(/\/:[A-Za-z_]+\*?$/,"")):null;i&&typeof o.source=="string"&&n.push({prefix:ha(o.source),target:i,kind:`vercel.json ${r}`,strip:!0})}return n}function wa(e){let t=[],n=!1,r=null,o=()=>{if(r?.from&&r.to&&/\/:[A-Za-z_]+\*?$/.test(r.to)){let s=ot(r.to.replace(/\/:[A-Za-z_]+\*?$/,""));s&&t.push({prefix:ha(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 c=/^(from|to)\s*=\s*(.*)$/.exec(i);c&&(r[c[1]]=Fe(c[2]))}return o(),t}function Sa(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,c=nt(s,a,t);c&&r.push(c)}return r}function ka(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 c of Object.keys(i).sort()){let l=i[c];if(/^(env|envVars|variables|environment)$/i.test(c)&&l&&typeof l=="object"&&!Array.isArray(l))for(let d of Object.keys(l).sort()){let f=typeof l[d]=="string"?l[d]:typeof l[d]?.value=="string"?l[d].value:null,u=nt(d,f,t);u&&r.push(u)}else s(l,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 c=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(i);if(c&&/(^|\.)(env|variables|environment)$/i.test(o)){let l=nt(c[1],Fe(c[2]),t);l&&r.push(l)}}}return r}var Cf=[".env.local",".env",".env.development",".env.production",".env.example"],Ff=/^(PORT|HTTP_PORT|HTTPS_PORT|SERVER_PORT|API_PORT|APP_PORT|WS_PORT|WSS_PORT|WEBSOCKET_PORT|LISTEN_PORT)$/,Ef=/^PUBLIC_(?:[A-Z0-9]+_)*(?:ORIGIN|URL|HOST|BASE_URL)$/,Pf=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","host.docker.internal"]),Lf=512*1024,Na=e=>e.split(J.sep).join("/");function It(e){try{let t=dr.lstatSync(e);return!t.isFile()||t.isSymbolicLink()||t.size>Lf?null:dr.readFileSync(e,"utf8")}catch{return null}}function ot(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 Tf(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:ot("http://"+t)}var fr=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 Rf(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 $a(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 c=e.has(i)?$a(e,i,n+1,r):void 0;return c!=null&&c!==""?c:a??""}),r.delete(t)),o}function nt(e,t,n){if(t==null)return null;if(Ff.test(e)){let o=fr(t);return o?{name:e,kind:"port",file:n,port:o}:null}let r=ot(t)??(/(_URL|_URI|_HOST|_HOSTNAME|_ORIGIN|_ADDR|_ENDPOINT)$/i.test(e)?Tf(t):null);return r?{name:e,kind:"url",file:n,...r}:null}function ba(e,t){let n=[];for(let r of[...e.keys()].sort()){let o=$a(e,r);if(o==null)continue;let s=nt(r,o,t);s&&n.push(s)}return n}function Af(e){let t=e.split(/\r?\n/).map(l=>l.replace(/\s+#.*$/,"").replace(/\t/g," ")),n=l=>l.length-l.trimStart().length,r=[],o=t.findIndex(l=>/^services\s*:\s*$/.test(l));if(o<0)return r;let s=null,i=null,a=null,c=0;for(o=o+1;o<t.length;o++){let l=t[o];if(!l.trim())continue;let d=n(l),f=l.trim();if(d===0)break;if(s==null&&(s=d),d===s){let u=/^([A-Za-z0-9_.-]+)\s*:\s*$/.exec(f);u&&(i={name:u[1],ports:[],env:new Map,build:null},r.push(i),a=null);continue}if(i){if(d<=s+4&&/^[A-Za-z_]+\s*:/.test(f)&&!f.startsWith("-")){let u=/^([A-Za-z_]+)\s*:\s*(.*)$/.exec(f);a=u[1],c=d,a==="build"&&u[2]&&(i.build=u[2].replace(/^["']|["']$/g,""));continue}if(a==="build"&&/^context\s*:/.test(f)){i.build=f.replace(/^context\s*:\s*/,"").replace(/^["']|["']$/g,"");continue}if(a==="ports"&&f.startsWith("-")){let h=f.slice(1).trim().replace(/^["']|["']$/g,"").replace(/\/\w+$/,"").split(":"),p=h.slice(-2).map(m=>fr(m));h.length===1&&p[0]?i.ports.push({host:null,container:p[0]}):h.length>=2&&p[0]&&p[1]&&i.ports.push({host:p[0],container:p[1]});continue}if(a==="environment"&&d>c){let u=f.startsWith("-")?/^-\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(f):/^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/.exec(f);u&&i.env.set(u[1],u[2].replace(/^["']|["']$/g,""))}}}return r}function _a(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=ot(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=ot(o[2]);s&&n.push({prefix:o[1].replace(/\/+$/,""),target:s,kind:"next.config rewrites"})}}return n}function Ia(e,t,n){let r=g=>Na(J.relative(e,g)),o=new Map,s=new Map,i=new Map,a=(g,x,S)=>{(g.get(x)??g.set(x,new Set).get(x)).add(S)},c=(g,x,S)=>{let k=i.get(g)??i.set(g,[]).get(g);k.some(v=>v.service===x&&v.via===S)||k.push({service:x,via:S})},l=g=>{let x=[],S=J.resolve(g),k=J.resolve(e);for(let v=0;v<8&&(x.push(S),!(S===k||J.dirname(S)===S||(S=J.dirname(S),!S.startsWith(k))));v++);return x},d=new Map,f=new Map,u=(g,x)=>{let S=g.env.get(x.name)??g.env.set(x.name,[]).get(x.name);S.some(k=>k.file===x.file)||S.push(x),x.kind==="port"&&g.ports.add(x.port)};function h(g,x,S){let k=w=>r(J.join(S,w)),v=w=>It(J.join(S,w));for(let w of Vn(S))if(w==="fly.toml"){let b=v(w);if(b){let N=ya(b,k(w));for(let $ of N.ports)x.ports.add($);for(let $ of N.kept)u(x,$);N.app&&(c(`${N.app.toLowerCase()}.internal`,g.name,"fly.toml app name"),c(`${N.app.toLowerCase()}.fly.dev`,g.name,"fly.toml app name"))}}else if(/^Dockerfile(\..+)?$/.test(w)){let b=v(w);if(b){let N=va(b,k(w));for(let $ of N.ports)x.weakPorts.add($);for(let $ of N.kept)u(x,$)}}else if(w==="railway.json"||w==="railway.toml"){let b=v(w);if(b)for(let N of ka(b,k(w),w.endsWith(".json")))u(x,N)}else if(w==="app.json"){let b=v(w);if(b)for(let N of Sa(b,k(w)))u(x,N)}else if(w==="vercel.json"){let b=v(w);if(b)for(let N of xa(b))x.proxies.push({...N,file:k(w)})}else if(w==="netlify.toml"){let b=v(w);if(b)for(let N of wa(b))x.proxies.push({...N,file:k(w)})}}for(let g of t){let x={env:new Map,ports:new Set,weakPorts:new Set,proxies:[],isServer:!1};o.set(g.name,x);for(let S of l(g.rootPath)){for(let k of Cf){let v=It(J.join(S,k));if(v!=null)for(let w of ba(Rf(v),r(J.join(S,k)))){let b=x.env.get(w.name)??x.env.set(w.name,[]).get(w.name);b.some(N=>N.file===w.file)||b.push(w),w.kind==="port"&&S===J.resolve(g.rootPath)&&/(^|\/)\.env/.test(w.file)&&!/\.example$/.test(w.file)&&x.ports.add(w.port),w.kind==="port"&&S===J.resolve(g.rootPath)&&/\.example$/.test(w.file)&&x.ports.add(w.port)}}if(S===J.resolve(g.rootPath)){try{let k=JSON.parse(It(J.join(S,"package.json"))??"null"),v=typeof k?.proxy=="string"?ot(k.proxy):null;v&&x.proxies.push({prefix:"",target:v,kind:'package.json "proxy"',file:r(J.join(S,"package.json"))})}catch{}for(let k of Vn(S)){if(/^vite\.config\.(js|mjs|cjs|ts|mts)$/.test(k)){let v=It(J.join(S,k));if(v)for(let w of _a(v,"vite"))x.proxies.push({...w,file:r(J.join(S,k))})}if(/^next\.config\.(js|mjs|cjs|ts)$/.test(k)){let v=It(J.join(S,k));if(v)for(let w of _a(v,"next"))x.proxies.push({...w,file:r(J.join(S,k))})}}}S===J.resolve(g.rootPath)&&h(g,x,S);for(let k of Vn(S))if(/^render\.ya?ml$/.test(k)&&!f.has(J.join(S,k))){let v=It(J.join(S,k));v&&f.set(J.join(S,k),ga(v,r(J.join(S,k))))}for(let k of Vn(S)){if(!/^docker-compose.*\.ya?ml$/.test(k)||d.has(J.join(S,k)))continue;let v=It(J.join(S,k));v&&d.set(J.join(S,k),Af(v))}}}for(let[g,x]of[...d].sort((S,k)=>S[0]<k[0]?-1:1)){let S=J.dirname(g);for(let k of x){let v=k.build?J.resolve(S,k.build):null,w=t.find(N=>v&&J.resolve(N.rootPath)===v)??t.find(N=>N.name===k.name||J.basename(N.rootPath)===k.name);if(!w)continue;let b=o.get(w.name);for(let N of k.ports)b.ports.add(N.container),N.host&&b.ports.add(N.host);for(let N of ba(k.env,r(g)))(b.env.get(N.name)??b.env.set(N.name,[]).get(N.name)).push(N);c(k.name.toLowerCase(),w.name,"docker-compose service name")}}for(let[g,x]of[...f].sort((S,k)=>S[0]<k[0]?-1:1)){let S=J.dirname(g),k=new Map;for(let v of x){let w=J.resolve(S,v.rootDir||"."),b=v.rootDir?t.find($=>J.resolve($.rootPath)===w):null;if(!b&&v.startCommand)for(let $ of v.startCommand.split(/\s+/)){if(!/\.(c|m)?[jt]sx?$/.test($)&&!/^[\w./-]+\/[\w.-]+$/.test($))continue;let j=J.resolve(w,$),O=t.filter(D=>j.startsWith(J.resolve(D.rootPath)+J.sep)).sort((D,G)=>G.rootPath.length-D.rootPath.length)[0];if(O){b=O;break}}if(b=b??t.find($=>$.name===v.name||J.basename($.rootPath)===v.name),!b)continue;k.set(v.name,{target:b,c:v});let N=o.get(b.name);for(let $ of v.kept)u(N,{...$,scoped:!0});c(v.name.toLowerCase(),b.name,"render.yaml service name"),c(`${v.name.toLowerCase()}.onrender.com`,b.name,"render.yaml service name (Render's default public address)")}for(let{target:v,c:w}of k.values())for(let b of w.hostRefs){let N=k.get(b.service);if(!N)continue;let $=[...N.c.kept].find(D=>D.kind==="port")?.port??null,j=b.property==="hostport"&&$,O=b.service.toLowerCase();u(o.get(v.name),{name:b.name,kind:"url",file:r(g),scheme:"http",host:O,port:j?$:null,origin:`http://${O}${j?":"+$:""}`,path:""})}}let p=g=>[...n.get(g.name)?.parseResults?.values()??[]].some(x=>(x.routes??[]).length>0);for(let g of t){let x=o.get(g.name);if(x.isServer=p(g),x.isServer){for(let[S,k]of x.env)if(Ef.test(S))for(let v of k)v.kind==="url"&&v.file&&(v.scoped||J.posix.dirname(v.file)===(Na(J.relative(e,g.rootPath))||"."))&&c(v.host,g.name,`${S} in ${v.file} (the server's own public address)`)}}for(let g of t){let x=o.get(g.name);for(let[,S]of n.get(g.name)?.parseResults??[])for(let k of S.httpClients?.listens??[])for(let v of m(x,k.parts)){let w=fr(v.text);w&&x.ports.add(w)}}for(let g of t)for(let x of o.get(g.name).ports)a(s,x,g.name);for(let g of t)for(let x of o.get(g.name).weakPorts)t.some(S=>o.get(S.name).ports.has(x))||a(s,x,g.name);function m(g,x){let S=[{text:"",evidence:[]}];for(let k of x){let v;if(k.t==="lit")v=[{text:k.v,evidence:[]}];else if(k.t==="env"){let b=g.env.get(k.name)??[];v=[];for(let N of b)v.push({text:N.kind==="port"?String(N.port):N.origin+N.path,evidence:[{env:k.name,file:N.file}]});!v.length&&k.fallback&&(v=m(g,k.fallback).map($=>({text:$.text,evidence:[{env:k.name,file:null,fallback:!0},...$.evidence]})))}else v=[];if(!v.length)return[];let w=[];for(let b of S)for(let N of v)if(w.push({text:b.text+N.text,evidence:[...b.evidence,...N.evidence]}),w.length>=8)break;S=w.slice(0,8)}return S}let y=(g,x)=>{let S=[],k=g.host,v=i.get(k)??[];for(let w of v)S.push(w);if(Pf.has(k)||v.length&&v.some(w=>w.via==="docker-compose service name")){let w=g.port??(g.scheme==="https"||g.scheme==="wss",null);if(w)for(let b of s.get(w)??[])S.some(N=>N.service===b)||S.push({service:b,via:`port ${w} (a service listening there)`})}return S.filter(w=>w.service!==x)};return{resolveBase(g,x){let S=o.get(g);if(!S||!x.length)return{status:"unknown"};let k=m(S,x);if(!k.length)return{status:"unknown"};let v=[],w=new Set;for(let $ of k){let j=ot($.text)??($.text.startsWith("//"),null);if(j){w.add(j.origin);for(let O of y(j,g))v.push({...O,u:j,evidence:$.evidence})}}if(!w.size)return{status:"unknown"};let b=[...new Set(v.map($=>$.service))];if(b.length===0)return{status:"external",origins:[...w].sort()};if(b.length>1)return{status:"ambiguous",services:b.sort()};let N=v[0];return{status:"service",service:N.service,via:N.via,origin:N.u.origin,basePath:N.u.path,evidence:N.evidence.filter(($,j,O)=>O.findIndex(D=>D.env===$.env&&D.file===$.file)===j)}},resolveProxy(g,x){let S=o.get(g);for(let k of S?.proxies??[]){if(k.prefix&&x!==k.prefix&&!x.startsWith(k.prefix+"/"))continue;let v=y(k.target,g),w=[...new Set(v.map(b=>b.service))];if(w.length===1)return{status:"service",service:w[0],via:`${k.kind} ${k.prefix||"/"} -> ${k.target.origin}`,origin:k.target.origin,basePath:k.target.path,strip:k.strip?k.prefix.split("/").filter(Boolean).length:0,evidence:[{env:null,file:k.file}]}}return{status:"unknown"}},portsOf:g=>[...o.get(g)?.ports??[]].sort((x,S)=>x-S),hostClaims:()=>[...i].sort((g,x)=>g[0]<x[0]?-1:1)}}function Vn(e){try{return dr.readdirSync(e).sort()}catch{return[]}}var Yn=e=>String(e).toLowerCase();function Kn(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 ja(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 Kn(n)}function ur(e){if(!e.length)return null;let t=e.slice(),n="none",r=null,o=t[0];if(o.t==="lit"){let l=/^(https?:)\/\/([^/?#]*)(.*)$/.exec(o.v);if(l){n="abs",r=l[2];let d=l[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 l of t){if(a)break;if(l.t==="lit"){let d=l.v.search(/[?#]/);d>=0?(s+=l.v.slice(0,d),a=!0):s+=l.v}else s+="",i++}if(!s.startsWith("/")&&!(s===""&&n==="abs"))return null;s===""&&(s="/");let c=s.split("/").slice(1).map(l=>l.includes("")?":p":l);for(;c.length>1&&c[c.length-1]==="";)c.pop();return{base:n,host:r,segments:c,placeholders:i,literal:n==="none"&&i===0}}function Ca(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 Of=e=>String(e||"").split("/").filter(Boolean),Fa=e=>[...new Set(e)];function Ea(e){let t=e.evidence??[];return{env:Fa(t.filter(n=>n.env).map(n=>n.env)),files:Fa(t.filter(n=>n.file).map(n=>n.file)),origin:e.origin,via:e.via,...t.some(n=>n.fallback)?{usedFallback:!0}:{}}}var Pa=(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+")",Mf=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 La(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 Hf(e,t,n,r,o){let s=(n.importBindings??[]).find(f=>f.local===r);if(!s)return null;let i=Je(s.source,t,o);if(!i)return null;let a=e.parseResults.get(i),c=f=>e.nodes.find(u=>u.filePath===i&&u.name===f&&u.type!=="moduleRoot")?.id??null;if(s.kind==="named"&&s.imported)return c(s.imported);let l=a?.exportBindings;if(l?.default&&l.default!=="<anon>")return c(l.default);let d=Object.keys(l?.named??{});return d.length===1?c(d[0]):null}function Df(e){let t=[],n=[...e.parseResults.keys()];for(let[r,o]of e.parseResults){let s=e.nodes.filter(c=>c.filePath===r);if(s[0]?.category!=="backend")continue;let i=qe(r,o),a=he(r,e.nodes);for(let c of o.routes??[]){let l=null;c.isInlineHandler?l=i.get(c):c.nest?l=s.find(f=>f.type==="classMethod"&&f.className===c.nest.className&&f.name===c.nest.methodName)?.id??null:c.handlerName&&a.has(c.handlerName)?l=a.get(c.handlerName):c.handlerName&&(l=Hf(e,r,o,c.handlerName,n));let d=!1;l||(l=ge(c.startLine,s)?.id??null,d=!0),l&&t.push({method:Yn(c.method),path:c.path,segments:Mf(c.path),literal:!/[:*{]/.test(c.path),nodeId:l,file:r,line:c.startLine,fallback:d})}}return t}var Bf=/^(ws|uws|websocket|@nestjs\/platform-ws|@fastify\/websocket|fastify-websocket|express-ws)$/,Uf=/^(socket\.io|@nestjs\/platform-socket\.io|socket\.io-client)$/;function Ta(e){let t=[...e].some(r=>Uf.test(r)),n=[...e].some(r=>Bf.test(r));return t&&n?"unknown":t?"socketio":n?"ws":null}function zf(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(m=>m.eventName==="connection");if(!i)continue;let a=qe(r,o),c=he(r,e.nodes),l=m=>m.isInlineHandler?a.get(m):m.handlerName&&c.has(m.handlerName)?c.get(m.handlerName):null,d=l(i);if(!d)continue;let f=m=>i.handlerStartLine!=null&&m.startLine>=i.handlerStartLine&&m.startLine<=i.handlerEndLine,u=s.find(m=>m.eventName==="message"&&f(m))??s.find(m=>m.eventName==="message"),h=o.httpClients?.wsServers??[],p=Ta(new Set((o.imports??[]).map(m=>m.source)))??Ta(n)??"unknown";t.push({filePath:r,nodeId:d,line:i.startLine,messageNodeId:u?l(u):null,messageLine:u?.startLine??null,pathParts:h.find(m=>m.path)?.path??null,kind:p})}return t}function Ra(e,t,n={}){let r=n.repoRoot?Ia(n.repoRoot,e,t):null,o=[],s=new Set,i={restCalls:0,restLinked:0,wsClients:0,wsLinked:0,wsSends:0,wsSendsLinked:0},a=l=>{let d=[l.fromService,l.fromNodeId,l.toService,l.toNodeId,l.via,l.key].join("\0");s.has(d)||(s.add(d),o.push(l))},c=new Map;for(let l of e){let d=t.get(l.name);d&&c.set(l.name,{routes:Df(d),wsServers:zf(d)})}for(let l of e){let d=t.get(l.name);if(!d)continue;let f=[...d.parseResults.keys()],u=new Map,h=new Map;for(let[v,w]of d.parseResults){let b=w.httpClients;if(b){for(let N of b.httpInstances??[])(u.get(N.name)??u.set(N.name,[]).get(N.name)).push(N);for(let N of b.httpCalls??[])(N.parts.some(j=>j.t==="param")||N.method&&typeof N.method=="object")&&N.fn?.name&&(h.get(N.fn.name)??h.set(N.fn.name,[]).get(N.fn.name)).push({filePath:v,call:N})}}let p=v=>{if(!v.startsWith("inst:")&&!v.startsWith("obj:"))return[];let w=u.get(v.slice(v.indexOf(":")+1));return w&&w.length===1?w[0].parts:v.startsWith("obj:")?null:[{t:"ref",name:"?"}]},m=[],y=(v,w)=>ge(w,d.nodes.filter(b=>b.filePath===v)),g=new Set,x=v=>v.parts.some(w=>w.t==="param")||v.method&&typeof v.method=="object";for(let[v,w]of d.parseResults){let b=w.httpClients;if(b){for(let N of b.httpCalls??[]){if(x(N))continue;let $=p(N.client);if($===null)continue;let j=y(v,N.line);j&&m.push({filePath:v,line:N.line,nodeId:j.id,method:N.method,parts:Kn([...$,...N.parts]),via:N.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let N of b.pathCallsites??[]){let $=h.get(N.callee);if($)for(let j of $){let O=j.filePath===v;if(!O){let q=(w.importBindings??[]).find(E=>E.local===N.callee||E.imported===N.callee);q&&Je(q.source,v,f)===j.filePath&&(O=!0)}if(!O)continue;let D=new Map(N.args.map(q=>[q.i,q.parts])),G=typeof j.call.method=="object"&&j.call.method?(()=>{let q=D.get(j.call.method.param);return q&&q.length===1&&q[0].t==="lit"?q[0].v.toUpperCase():"?"})():j.call.method,M=y(v,N.line);M&&(g.add(j.call),m.push({filePath:v,line:N.line,nodeId:M.id,method:G,parts:ja([...p(j.call.client),...j.call.parts],D),via:j.call.client,wrapper:N.callee}))}}}}for(let[v,w]of d.parseResults)for(let b of w.httpClients?.httpCalls??[]){if(!x(b)||g.has(b))continue;let N=p(b.client);if(N===null)continue;let $=y(v,b.line);$&&m.push({filePath:v,line:b.line,nodeId:$.id,method:typeof b.method=="object"&&b.method?"?":b.method,parts:ja([...N,...b.parts],null),via:b.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let v of m){let w=ur(v.parts);if(!w)continue;i.restCalls++;let b=0,N=[];for(let M of e){if(M.name===l.name)continue;let q=c.get(M.name);if(q)for(let E of q.routes){if(!(v.method==="?"||v.method==null||E.method===Yn(v.method)||E.method==="all"||E.method==="use"))continue;let R=La(w.segments,E.segments);R&&(R>b&&(b=R,N.length=0),R===b&&N.push({service:M.name,route:E}))}}let $={status:"unknown"};if(r){let M=Kn(v.parts);if(w.base==="none"?$=r.resolveProxy(l.name,"/"+w.segments.join("/")):$=r.resolveBase(l.name,Ca(M)),$.status==="service"){let q=Of($.basePath);if(q.length||$.strip){let E=[...q,...w.segments.slice($.strip||0)];for(let C of c.get($.service)?.routes??[])(v.method==="?"||v.method==null||C.method===Yn(v.method)||C.method==="all"||C.method==="use")&&La(E,C.segments)&&!N.some(W=>W.service===$.service&&W.route.nodeId===C.nodeId)&&N.push({service:$.service,route:C,viaBasePath:!0})}}}if(!N.length)continue;let j=new Set(N.map(M=>M.service+"\0"+M.route.nodeId)),O=typeof v.method=="string"&&v.method!=="?",D=b===3&&w.literal&&O&&j.size===1&&N[0].route.literal&&!N[0].route.fallback&&N[0].route.method===Yn(v.method),G=[];w.base==="var"&&G.push("base URL is a variable, so the target service is guessed from the path"),w.base==="abs"&&G.push("absolute URL"),w.placeholders&&G.push("path has parameters"),b===1&&G.push("leading /api removed from the client path"),b===2&&G.push("route parameters matched fuzzily"),O||G.push("method not known"),j.size>1&&G.push(j.size+" candidate routes"),N.some(M=>M.route.fallback)&&G.push("route handler not resolved: linked to the function that registers the route"),$.status==="external"&&G.push("base URL is "+$.origins.join(" / ")+", which no service of this repo owns"),$.status==="ambiguous"&&G.push("base URL could belong to "+$.services.join(" or "));for(let M of N){i.restLinked++;let q=!D&&$.status==="service"&&$.service===M.service&&!M.route.fallback,E=q?Ea($):null,C=D?"exact":q?"resolved":"inferred",R=!D&&$.status==="service"&&$.service!==M.service?["base URL belongs to "+$.service+", not this service"]:[];a({fromService:l.name,fromNodeId:v.nodeId,toService:M.service,toNodeId:M.route.nodeId,via:"httpCall",key:`${O?v.method:"ANY"} ${"/"+w.segments.join("/")}`,confidence:C,method:O?v.method:null,url:"/"+w.segments.join("/"),client:v.via,...v.wrapper?{wrapper:v.wrapper}:{},line:v.line,...D?{}:q?{reason:Pa(E,M.service)+(O?"":"; method not known"),resolvedFrom:E}:{reason:[...G,...R].join("; ")||"path-only match"}})}}let S=[];for(let[v,w]of d.parseResults)for(let b of w.httpClients?.wsClients??[])S.push({filePath:v,w:b});let k=v=>v.client==="io"?"socketio":"ws";for(let{filePath:v,w}of S){let b=y(v,w.line);if(!b)continue;i.wsClients++;let N=Kn(w.parts),$=/^wss?:\/\//.test(N[0]?.v??"")?ur([{t:"lit",v:N[0].v.replace(/^ws(s?):/,"http$1:")},...N.slice(1)]):ur(N),j=r&&$?r.resolveBase(l.name,Ca(N)):{status:"unknown"};for(let O of e)if(O.name!==l.name)for(let D of c.get(O.name)?.wsServers??[]){if(D.kind!=="unknown"&&D.kind!==k(w))continue;let G=D.pathParts&&D.pathParts.every(R=>R.t==="lit")?"/"+D.pathParts.map(R=>R.v).join("").replace(/^\//,""):null,M=$?"/"+$.segments.join("/"):null;if(G&&M&&G!==M&&G!=="/"&&M!=="/")continue;let q=!!($&&$.literal&&G&&M===G&&D.kind!=="unknown"),E=!q&&j.status==="service"&&j.service===O.name,C=E?Ea(j):null;i.wsLinked++,a({fromService:l.name,fromNodeId:b.id,toService:O.name,toNodeId:D.nodeId,via:"webSocket",key:M??"(url unknown)",confidence:q?"exact":E?"resolved":"inferred",url:M,client:w.client,line:w.line,...q?{}:E?{reason:Pa(C,O.name),resolvedFrom:C}:{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 v=new Set(S.map(({w})=>k(w)));for(let[w,b]of d.parseResults)for(let N of b.httpClients?.wsSends??[]){let $=y(w,N.line);if($){i.wsSends++;for(let j of e)if(j.name!==l.name)for(let O of c.get(j.name)?.wsServers??[])!O.messageNodeId||O.kind!=="unknown"&&!v.has(O.kind)||(i.wsSendsLinked++,a({fromService:l.name,fromNodeId:$.id,toService:j.name,toNodeId:O.messageNodeId,via:"webSocketMessage",key:"message",eventName:"message",confidence:"inferred",client:N.recv,line:N.line,reason:"a message sent over a socket whose payload is built at run time; delivered to the message listener of a WebSocket server of another service"}))}}}}if(n.serverPush!==!1){let l=new Map;for(let f of o)if(f.via==="webSocket"){let u=f.fromService+"\0"+f.toService;(l.get(u)??l.set(u,[]).get(u)).push(f)}let d=new Map;for(let f of l.values())(d.get(f[0].toService)??d.set(f[0].toService,new Set).get(f[0].toService)).add(f[0].fromService);for(let[,f]of[...l].sort((u,h)=>u[0]<h[0]?-1:1)){let u=f[0].fromService,h=f[0].toService,p=t.get(u),m=t.get(h);if(!p||!m||!(c.get(h)?.wsServers??[]).length)continue;let y=new Set(f.map(k=>k.fromNodeId.split("::")[0])),g=[];for(let[k,v]of p.parseResults){if(!y.has(k))continue;let w=he(k,p.nodes),b=qe(k,v),N=p.nodes.filter($=>$.filePath===k);for(let $ of v.httpClients?.wsReceivers??[]){let j=$.handlerName&&w.get($.handlerName)||ge($.line,N)?.id;j&&g.push({id:j,line:$.line})}for(let $ of v.socketListeners??[]){if($.eventName!=="message")continue;let j=$.isInlineHandler?b.get($):$.handlerName&&w.get($.handlerName)||null;j&&g.push({id:j,line:$.startLine})}}let x=new Set(p.resolvedEdges.filter(k=>k.resolved&&k.targetNodeId&&k.type!=="returnValue").map(k=>k.fromNodeId));for(let k=g.length-1;k>=0;k--)x.has(g[k].id)||g.splice(k,1);if(!g.length)continue;let S=d.get(h)?.size??1;for(let[k,v]of m.parseResults){let w=m.nodes.filter(b=>b.filePath===k);for(let b of[...v.httpClients?.wsSends??[],...v.httpClients?.wsServerSends??[]]){let N=ge(b.line,w);if(N)for(let $ of g)i.wsPushLinked=(i.wsPushLinked??0)+1,a({fromService:h,fromNodeId:N.id,toService:u,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 "+u+", 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((l,d)=>l.fromService+l.fromNodeId+l.via+l.key+l.toService+l.toNodeId<d.fromService+d.fromNodeId+d.via+d.key+d.toService+d.toNodeId?-1:1),{edges:o,stats:i}}function Aa(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 c=ge(a.startLine,s);c&&n.set(a.eventName,c.id)}}return n}import Wf from"node:fs";import Gf from"node:path";function Oa(e){let t=["index.html","public/index.html","client/index.html","frontend/index.html","src/index.html"];for(let n of t){let r=Gf.join(e,n);if(Wf.existsSync(r))return r}return null}import Xn from"node:fs";import Zn from"node:path";var qf=new Set(["node","tsx","ts-node","nodemon","bun","deno","ts-node-esm"]),Jf=new Set(["watch","run","start","dev"]),Vf=/\.[cm]?[jt]sx?$/,Yf=["start","dev","serve","run"];function Kf(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=>qf.has(Zn.basename(o).replace(/\.cmd$/,"")));if(!(r<0)){for(let o of n.slice(r+1))if(!(o.startsWith("-")||Jf.has(o)||o.includes("="))){if(Vf.test(o))return o;break}}}return null}var Xf=e=>String(e).replace(/^@[^/]+\//,"");function Ma(e){let t;try{t=JSON.parse(Xn.readFileSync(Zn.join(e,"package.json"),"utf8"))}catch{return[]}let n=[],r=(o,s,i={})=>{if(typeof o!="string"||!o)return;let a=s==="script"?null:qn(e,o,t);a?n.push({file:a.file,kind:s,...i,mappedFrom:o,mappedBy:a.how}):n.push({file:Zn.resolve(e,o),kind:s,...i})};if(typeof t.bin=="string")r(t.bin,"bin",{binName:Xf(t.name??Zn.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 Yf){let s=t.scripts?.[o]&&Kf(t.scripts[o]);s&&r(s,"script")}return r(t.main,"main"),n}function Ha(e){try{let t=Xn.openSync(e,"r"),n=Buffer.alloc(120),r=Xn.readSync(t,n,0,120,0);return Xn.closeSync(t),/^#!.*\b(node|tsx|ts-node|bun)\b/.test(n.toString("utf8",0,r).split(/\r?\n/)[0])}catch{return!1}}import Qn from"node:fs";import jt from"node:path";var Zf=50,Qf=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Da=["",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts","/index.js","/index.ts","/index.mjs","/index.cjs","/index.tsx","/index.jsx"];function pr(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=pr(t);if(n)return n}return null}if(e&&typeof e=="object")for(let t of["import","node","require","default"]){let n=pr(e[t]);if(n)return n}return null}function Ba(e,t){let n;try{n=JSON.parse(Qn.readFileSync(jt.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(l=>l.startsWith("."))?null:r):null,s=pr(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(l=>jt.resolve(l))),a=jt.resolve(e,s);for(let l of Da)if(i.has(a+l))return t.find(d=>jt.resolve(d)===a+l);let c=[];try{c=Qn.readdirSync(e).filter(l=>Qf.test(l)).sort()}catch{}for(let l of c){let d;try{d=Qn.readFileSync(jt.join(e,l),"utf8")}catch{continue}let f=/\bentry(?:Points)?\s*:\s*[\[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/.exec(d);if(!f)continue;let u=jt.resolve(e,f[1]);for(let h of Da)if(i.has(u+h))return t.find(p=>jt.resolve(p)===u+h)}return null}function Ua(e,t,n,r,o=null){let s=new Map;for(let m of n){let y=s.get(m.filePath);y||s.set(m.filePath,y=[]),y.push(m)}let i=new Map,a=(m,y)=>{y&&(!i.has(y.id)||m<i.get(y.id))&&i.set(y.id,m)},c=new Map,l=(m,y)=>{let g=c.get(m);if(!g){g=new Map;let x="";try{x=Qn.readFileSync(m,"utf8")}catch{}for(let S of x.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]);c.set(m,g)}return g.get(y)??null},d=(m,y)=>(s.get(m)??[]).find(g=>(g.type==="function"||g.type==="arrowFunction")&&g.name===y),f=(m,y)=>(s.get(m)??[]).filter(g=>g.type==="classMethod"&&g.className===y&&g.name!=="constructor"&&!/^[_#]/.test(g.name)),u=new Set;function h(m,y,g,x=0){let S=d(m,g);if(S){a(y,S);return}let k=f(m,g);for(let j of k)a(`${y}.${j.name}`,j);if(k.length||!o)return;let v=o.resolveName(m,g);if(v){a(y,v);return}let w=o.bindingFor(m,g),b=w&&x<3?o.resolveImport(m,w.source,w.kind,w.imported):null;if(b?.file&&b.local&&b.local!=="default"&&l(b.file,b.local)){h(b.file,y,b.local,x+1);return}let N=o.classForImport(m,g);if(N?.className)for(let j of f(N.file,N.className))a(`${y}.${j.name}`,j);if(N?.className)return;let $=l(m,g);$&&x<3&&h(m,y,$,x+1)}function p(m,y,g){let x=m+"|"+(g?[...g.keys()].sort().join(","):"*");if(u.has(x)||y>3)return;u.add(x);let S=t.get(m)?.exportBindings;if(!S)return;let k=v=>!g||g.has(v);for(let[v,w]of Object.entries(S.named??{}))k(v)&&h(m,g?.get(v)??v,w);S.default&&k("default")&&S.default!=="<anon>"&&h(m,g?.get("default")??S.default,S.default);for(let v of S.reexports??[]){if(!k(v.exported))continue;let w=Je(v.source,m,r);w&&p(w,y+1,new Map([[v.imported,g?.get(v.exported)??v.exported]]))}for(let v of S.stars??[]){let w=Je(v,m,r);w&&(g?p(w,y+1,g):p(w,y+1,null))}}return p(e,0,null),[...i].map(([m,y])=>({name:y,nodeId:m})).sort((m,y)=>m.name<y.name?-1:m.name>y.name?1:m.nodeId<y.nodeId?-1:1).slice(0,Zf)}import eo from"node:fs";import dn from"node:path";var mr=null,hr=null,za=()=>mr?dn.join(mr,".canopy","last-stage.txt"):null,Wa=e=>{mr=e?dn.resolve(e):null},to=()=>hr;function eu(){let e=process.memoryUsage(),t=n=>Math.round(n/1048576);return{rssMB:t(e.rss),heapUsedMB:t(e.heapUsed),externalMB:t(e.external),arrayBuffersMB:t(e.arrayBuffers)}}var tu=()=>process.env.CANOPY_DEBUG_MEM==="1"||process.env.CANOPY_DEBUG_MEM==="true";function mt(e){hr=e;let t=za();if(t)try{eo.mkdirSync(dn.dirname(t),{recursive:!0}),eo.writeFileSync(t,e)}catch{}if(tu()){let n=eu();process.stderr.write(`[mem] ${e}: rss ${n.rssMB} MB, heapUsed ${n.heapUsedMB} MB, external ${n.externalMB} MB, arrayBuffers ${n.arrayBuffersMB} MB
21
+ `)}}function Ga(){hr=null;let e=za();if(e)try{eo.rmSync(e,{force:!0})}catch{}}function qa(e){try{return eo.readFileSync(dn.join(dn.resolve(e),".canopy","last-stage.txt"),"utf8").trim().slice(0,120)||null}catch{return null}}We();import Va from"node:path";import{fileURLToPath as nu}from"node:url";import{Parser as Ja,Language as ou}from"web-tree-sitter";var Ay=Va.dirname(nu(globalThis.__canopyUrl("src/stage2_parse/initHtmlParser.js")));async function Ya(){await Ja.init();let e=new Ja,t=Va.join(He("tree-sitter-html"),"tree-sitter-html.wasm"),n=await ou.load(t);return e.setLanguage(n),{parser:e,language:n}}function Ka(e,t){let r=ie(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 Xa(e,t,n){let r=[];e.forEach((c,l)=>{c.steps.forEach(d=>{if(!d.hasOwnSubTrace)return;let f=e.findIndex((u,h)=>h!==l&&u.steps[0]?.nodeId===d.nodeId);f!==-1&&r.push({fromWorkflowIndex:l,toWorkflowIndex:f,atNodeId:d.nodeId})})});let o=new Map;for(let c of t)o.set(c.id,c.serviceName??null);let s=new Map;function i(c,l,d,f){if(!c||!l||c===l)return;let u=`${c} -> ${l} -> ${d}`;s.has(u)?s.get(u).count+=1:s.set(u,{fromService:c,toService:l,viaMatchType:d,count:1});let h=s.get(u);f==="exact"?h.exact=(h.exact??0)+1:f==="inferred"?h.inferred=(h.inferred??0)+1:f==="resolved"&&(h.resolved=(h.resolved??0)+1)}for(let c of n){if(!c.resolved||!c.fromNodeId||!c.targetNodeId)continue;let l=o.get(c.fromNodeId)??null,d=o.get(c.targetNodeId)??null;i(l,d,c.matchType,c.confidence)}let a=Array.from(s.values());return{workflowLinks:r,serviceLinks:a}}var iu=Z.dirname(ru(globalThis.__canopyUrl("src/index.js"))),Za=24*1e3*1e3;async function gr(e,t={}){e=Z.resolve(e),console.log(`
21
22
  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(`
23
+ `);let n=Date.now(),r=()=>{let I=Math.round((Date.now()-n)/1e3);return I>=60?`${Math.floor(I/60)} min ${I%60} s`:`${I} s`},o=I=>{try{t.onProgress?.(I)}catch{}};mt("finding source files"),console.log("Stage 1: finding source files...");let s=Ho(e),i=s.files;Ui(Gi(e,i)),console.log(` found ${i.length} files`);let{parser:a,language:c,grammars:l}=await bs();await Ns({grammars:l},i),console.log(`
24
+ Stage 1b: partitioning files by service...`);let d=_i(e,i),f=$i(d,i,e);d=f.services,f.added&&console.log(` note: ${f.added.reason} (service "${f.added.name}")`),console.log(` detected ${d.length} services: ${d.map(I=>`${I.name} (${I.kind})`).join(", ")}`);let u=new Map(d.map(I=>[I.name,[]])),h=[];for(let I of i){let T=_t(I,d);T?u.get(T).push(I):h.push(I)}console.log(" file partition:");for(let I of d)console.log(` ${I.name}: ${u.get(I.name).length} files`);console.log(` unassigned (shared/root-level): ${h.length} files`),h.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(`
25
+ Stage 2: parsing (all files, once \u2014 see note above)...`),mt("reading files");let p=await ki(i,a,c,{onProgress:t.onProgress,grammars:l,noCache:!!t.noCache});function m(I){let T=new Set;for(let U of I){let F=p.get(U);if(F)for(let B of F.imports){let pe=Je(B.source,U,i);pe&&h.includes(pe)&&T.add(pe)}}return[...T]}let y=new Map;for(let I of d){let T=u.get(I.name),U=m(T);y.set(I.name,[...T,...U]),console.log(` ${I.name}: ${T.length} own + ${U.length} shared file(s) pulled in by real imports = ${T.length+U.length} total scope`)}let g=d.filter(I=>!y.get(I.name)?.length);g.length&&(console.log(` excluding ${g.length} service(s) with 0 files: ${g.map(I=>I.name).join(", ")}`),d=d.filter(I=>y.get(I.name)?.length));let x=null,S=Oa(e);if(S){let{parser:I,language:T}=await Ya(),U=we.readFileSync(S,"utf-8"),F=I.parse(U),B=Ka(F,T);if(B){let pe=Z.dirname(S),H=Z.join(pe,B);i.includes(H)&&(x=H,console.log(` found HTML root: ${B} -> ${H}`))}}let k=new Map,v=0,w=0,b=0;for(let I of d){let T=y.get(I.name);if(v++,mt(`linking calls: service ${v} of ${d.length}`),o(`linking calls: service ${v} of ${d.length} (${r()})`),console.log(`
26
+ --- Service: ${I.name} (${I.kind}) \u2014 ${T.length} files in scope ---`),!T.length){console.log(" 0 files \u2014 nothing to trace for this service."),k.set(I.name,{nodes:[],resolvedEdges:[],workflows:[],routeIndex:new Map,eventIndex:new Map,rawEventIndex:new Map,parseResults:new Map});continue}let U=fi(new Map(T.map(A=>[A,p.get(A)]))),F=Ii(U,d),B=ji(U,d);F=Pi(F.concat(B)),console.log(` Stage 3: materialized ${B.length} inline-handler nodes before edge construction`);let pe=Li(U,F),H=ua(U,F),Ne=ma(U,F),ee=Aa(U,F);for(let A of T){let re=new Set(U.get(A)?.exportedNames??[]);for(let X of F.filter(V=>V.filePath===A))X.exported=re.has(X.name)}let be=Ki(pe,F,U,T,H,Ne,ee),Ae=be.filter(A=>A.resolved).length;console.log(` Stage 4 (scoped): resolved ${Ae}/${be.length} edges`);for(let A of T){let re=U.get(A),X=re?.routes??[],V=re?.listeners??[],ce=he(A,F),ze=Gt(A,re?.imports??[],T),kn=[];I.kind==="server"&&(kn=re?.socketListeners??[]),F=Zi(F,A,X,V,ce,kn,ze)}let Me=F.filter(A=>A.isEntryPoint),wt=Me.filter(A=>A.trigger?.resolvedVia==="in-file").length,lt=Me.filter(A=>A.trigger?.resolvedVia==="cross-file").length,dt=Me.filter(A=>A.trigger?.resolvedVia==="inline").length;console.log(` Stage 5 entry points by resolution: in-file named ${wt}, cross-file named (BUG A) ${lt}, inline (BUG B) ${dt}`);let wn=be.filter(A=>A.type!=="reference"&&!A.viaArgument),Sn=ea(F,wn),St=[];if(I.kind==="client"&&x&&T.includes(x)&&St.push({id:`${x}::__module_root__`,name:"main",trigger:{type:"htmlRoot",label:"index.html script"}}),!St.length){let A=Hn(I.rootPath,i),re=A&&T.find(X=>Z.resolve(X)===A.entry);re&&(console.log(` found HTML root for ${I.name}: ${Z.relative(e,A.indexHtml)} -> ${Z.relative(e,re)} (${A.via})`),St.push({id:`${re}::__module_root__`,name:"main",trigger:{type:"htmlRoot",label:"index.html script"}}))}let Rt=[];if(I.kind==="server"){let A=Z.join(I.rootPath,"package.json");if(we.existsSync(A))try{let re=JSON.parse(we.readFileSync(A,"utf-8")),X=re.main;if(!X&&re.scripts?.start){let V=re.scripts.start.match(/([\w./-]+\.(?:js|mjs|cjs|ts))/);V&&(X=V[1])}if(X){let V=Z.resolve(I.rootPath,X),ce=T.find(ze=>Z.resolve(ze)===V);if(!ce){let ze=qn(I.rootPath,X,re);ze&&(ce=T.find(kn=>Z.resolve(kn)===ze.file))}ce?Rt.push({id:`${ce}::__module_root__`,name:"main",trigger:{type:"processBootstrap",label:`${X} (package.json main)`}}):console.log(` note: ${I.name}'s package.json names "${X}" as its entry, but that file isn't in this service's own traced scope \u2014 no bootstrap workflow added.`)}}catch{}}if(!St.length){let A=new Set(Rt.map(V=>V.id.split("::")[0])),re=new Set;for(let V of be)V.resolved&&V.fromNodeId.endsWith("::__module_root__")&&re.add(V.fromNodeId);let X=Ma(I.rootPath).map(V=>({...V,file:T.find(ce=>Z.resolve(ce)===V.file)})).filter(V=>V.file);for(let V of T)Ha(V)&&!X.some(ce=>ce.file===V)&&X.push({file:V,kind:"shebang"});for(let V of X){if(A.has(V.file)||Wt(Z.relative(e,V.file))||!re.has(`${V.file}::__module_root__`))continue;A.add(V.file);let ce=Z.relative(I.rootPath,V.file).split(Z.sep).join("/"),ze=V.kind==="bin"?`CLI: ${V.binName}`:`Start: ${ce}`;Rt.push({id:`${V.file}::__module_root__`,name:"main",trigger:{type:"processBootstrap",label:`${ce} (${V.kind==="bin"?"package.json bin":V.kind==="script"?"package.json script":V.kind==="main"?"package.json main":"#! shebang"}${V.mappedFrom?`, built to ${V.mappedFrom}`:""})`,workflowName:ze}})}}let en=[];if(St.length+Rt.length+Me.filter(A=>!Wt(Z.relative(e,A.filePath))).length===0){let A=Ba(I.rootPath,T);if(A){let re=Z.relative(I.rootPath,A).split(Z.sep).join("/"),V=Un(F,U,ce=>Gt(ce,U.get(ce)?.imports??[],T));for(let ce of Ua(A,U,F,T,V))en.push({id:ce.nodeId,name:F.find(ze=>ze.id===ce.nodeId)?.name??ce.name,trigger:{type:"publicApi",label:`${ce.name} (exported from ${re})`,workflowName:`API: ${ce.name}`}});en.length&&console.log(` public API of ${I.name}: ${en.length} exported function(s)/method(s) from ${re}`)}}let ts=new Set(en.map(A=>A.id)),hl=ts.size?Sn.filter(A=>!ts.has(A.id)):Sn,Io=[...St,...Rt,...Me,...en,...hl];console.log(` Stage 5 total entry points: ${Io.length} (${St.length} HTML root, ${Rt.length} process bootstrap, ${Me.length} pattern-matched, ${Sn.length} fallback)`);let gl=sr(be),yl=oa(Io,gl,F,wn,8,wn.length===be.length?null:sr(wn)),vl=new Set(Sn.map(A=>A.id)),xl=A=>A.trigger?"physical":vl.has(A.entryPointId)?"fallback":"hub",wl=yl.map(A=>({...A,origin:xl(A),steps:ra(A.steps,F)})),Sl=ia(wl),ns=Array.from(Sl.values()).map(aa),os=ns.filter(A=>!Wt(Z.relative(e,String(A.steps[0]?.nodeId??"").split("::")[0])));b+=ns.length-os.length;let At=fa(os,{nodes:F});if(At.some(A=>A.trigger)){let A=new Set(be.filter(X=>X.type!=="returnValue"&&X.type!=="reference").map(X=>X.fromNodeId)),re=new Set(At.filter(X=>!X.trigger&&X.steps.length===1&&!A.has(X.steps[0].nodeId)).map(X=>X.steps[0].nodeId));re.size&&(At=At.filter(X=>X.trigger||!re.has(X.steps[0].nodeId)||X.steps.length>1),w+=re.size)}console.log(` Stage 6-7: -> ${At.length} named workflows for ${I.name}`),k.set(I.name,{nodes:F,resolvedEdges:be,routeIndex:H,eventIndex:Ne,rawEventIndex:ee,workflows:At,parseResults:U,files:T,entryPointCount:Io.length})}console.log(`
27
+ --- Stage 5 (stitch): cross-service edge resolution ---`),mt("linking services together"),o(`linking services together (${r()})`);let N=[],$=0,j=0;for(let I of d){let T=k.get(I.name);if(!T||!T.resolvedEdges.length)continue;let U=T.resolvedEdges.filter(F=>!F.resolved&&(F.type==="apiCall"||F.type==="socketEmit"||F.type==="rawSocketSend"));for(let F of U){let B=null,pe=null;for(let H of d){if(H.name===I.name)continue;let Ne=k.get(H.name);if(!Ne)continue;let ee=null;if(F.type==="apiCall"&&F.scope!=="external"?ee=Ne.routeIndex.get(qt(F.url)):F.type==="socketEmit"?ee=Ne.eventIndex.get(F.eventName):F.type==="rawSocketSend"&&(ee=Ne.rawEventIndex.get(F.eventName)),ee){B=ee,pe=H.name;break}}B?(N.push({fromService:I.name,fromNodeId:F.fromNodeId,toService:pe,toNodeId:B,via:F.type,key:F.url||F.eventName,confidence:"inferred",reason:"name-only match",...F.type==="apiCall"?{url:F.url}:{eventName:F.eventName}}),$++):j++}}console.log(` stitched ${$} cross-service edges`);let O=Ra(d,k,{repoRoot:e});for(let I of O.edges)N.push(I);if(console.log(` + ${O.edges.length} links from HTTP clients / WebSockets (${O.edges.filter(I=>I.confidence==="exact").length} exact, ${O.edges.filter(I=>I.confidence==="resolved").length} resolved)`),console.log(` ${j} unresolved calls remain unresolved even after checking every other service`),t.lowMemory)for(let I of p.values())for(let T of Object.keys(I))T!=="hadErrors"&&T!=="warnings"&&T!=="failed"&&T!=="skipped"&&T!=="errorMessage"&&delete I[T];let D=new Map;function G(I,T,U){if(!I||T==null||U==null)return{available:!1,reason:"no line range recorded for this node"};try{D.has(I)||(D.set(I,we.readFileSync(I,"utf-8").split(/\r\n|\n/)),D.size>256&&D.delete(D.keys().next().value));let F=D.get(I),B=Math.max(T,1),pe=Math.min(U,F.length);if(B>F.length)return{available:!1,reason:"recorded line range is past the end of the current file \u2014 source has likely moved"};let H=F.slice(B-1,pe).join(`
28
+ `);return{available:!0,filePath:I,startLine:B,endLine:pe,text:H}}catch(F){return{available:!1,reason:`source unavailable: ${F.code==="ENOENT"?"file not found (deleted or moved)":F.message}`}}}let M=/^(addEventListener|removeEventListener|on|once|postMessage|onmessage|subscribe)$/i,q=new Set(["call","methodCall","callSite"]);function E(I,T,U,F,B=null){let pe=H=>!!(B&&!F&&!H.deferred&&H.resolved&&H.targetNodeId&&q.has(H.type)&&H.targetNodeId!==I&&B.inWorkflow.has(H.targetNodeId)&&!B.children.has(H.targetNodeId));return T.filter(H=>H.fromNodeId===I&&H.type!=="apiCall").filter(H=>H.resolved&&H.targetNodeId?pe(H):!!H.deferred===F).map(H=>{let Ne=H.type==="returnValue",ee=!Ne&&M.test(H.calleeNameRaw||""),be=(H.branchPath??[]).map(lt=>({...lt,source:U?G(U,lt.conditionLine,lt.conditionLine):{available:!1,reason:"owning function's node not found"}})),Ae=H.objectNameRaw?`${H.objectNameRaw}.${H.calleeNameRaw}`:H.calleeNameRaw,Me=Ne?Ae:H.firstArgText?`${Ae}(${H.firstArgText})`:Ae,wt=pe(H);return{label:Me,line:H.line??null,column:H.column??null,branchPath:be,source:U?G(U,H.line,H.line):{available:!1,reason:"owning function's node not found"},tag:wt?"called-elsewhere":Ne?"return-value":ee?"runtime-dispatched":"unresolvable-call-site",...wt?{targetNodeId:H.targetNodeId}:{},reason:wt?"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":Ne?"the value this branch returns \u2014 not a function call, just what this path produces":ee?`registered via ${H.calleeNameRaw}(...) \u2014 the handler runs later, outside this function's own execution`:F?"runs later, outside this function's own execution (an effect cleanup, a deferred callback)":"call target could not be statically resolved to a declared function (dynamic dispatch, external/browser API, or computed member access) \u2014 but it still runs here, in this order"}})}function C(I,T,U){return E(I,T,U,!0)}function R(I,T,U,F){return E(I,T,U,!1,F)}let W=[];for(let I of d){let T=k.get(I.name);if(!T)continue;let U=new Map(T.nodes.map(F=>[F.id,F]));for(let F of T.workflows){let B=new Set([I.name]),pe=new Set(F.steps.map(ee=>ee.nodeId)),H=new Map;for(let ee of F.steps)ee.parentNodeId!=null&&(H.get(ee.parentNodeId)??H.set(ee.parentNodeId,new Set).get(ee.parentNodeId)).add(ee.nodeId);let Ne=F.steps.map(ee=>{let be=N.find(dt=>dt.fromService===I.name&&dt.fromNodeId===ee.nodeId),Ae=U.get(ee.nodeId),Me=ee.parentNodeId?U.get(ee.parentNodeId):null,wt=(ee.branchPath??[]).map(dt=>({...dt,source:Me?G(Me.filePath,dt.conditionLine,dt.conditionLine):{available:!1,reason:"owning function's node not found"}})),lt={...ee,branchPath:wt,source:Ae?G(Ae.filePath,Ae.startLine,Ae.endLine):{available:!1,reason:"node not found in this service's own graph"},alsoCallsRuntime:C(ee.nodeId,T.resolvedEdges,Ae?.filePath),inlineCalls:R(ee.nodeId,T.resolvedEdges,Ae?.filePath,{inWorkflow:pe,children:H.get(ee.nodeId)??new Set})};return be&&(B.add(be.toService),lt.crossesInto=be.toService),lt});W.push({...F,steps:Ne,serviceId:I.name,servicesTouched:[...B]})}}console.log(`
29
+ Done: ${W.length} named workflows across all services
30
+ `),W.forEach(I=>console.log(` - [${I.serviceId}] ${I.name} (${I.steps.length} steps, ${I.occurrences} entry point(s))`)),mt("writing the map"),o(`writing the map (${r()})`);let K=t.outputDir??process.env.CANOPY_OUTPUT_DIR??Z.join(iu,"..","output");we.existsSync(K)||we.mkdirSync(K,{recursive:!0});let se=Bn(e),Xe=new Set(d.flatMap(I=>y.get(I.name)??[])),ue=ws({discovered:s,parseResults:p,scopeFiles:Xe,rel:se.rel,rootService:f.added});ue.testWorkflowsExcluded=b,ue.guessedWorkflowsDropped=w;let _={repoRoot:se.repoRoot,coverage:ue};we.writeFileSync(Z.join(K,"meta.js"),`const meta = ${JSON.stringify(_,null,2)};`),we.writeFileSync(Z.join(K,"meta.json"),JSON.stringify(_,null,2)),console.log(`
31
+ `+jn(ue)),we.existsSync(Z.join(K,"history.js"))||we.writeFileSync(Z.join(K,"history.js"),"const canopyHistory = null;");let P=se.json(W,2),L=P.length>Za;if(L&&(P=se.json(W)),L&&P.length>Za){let I=Xi(JSON.parse(P));we.writeFileSync(Z.join(K,"workflows.js"),`const workflows = ${I};`),we.rmSync(Z.join(K,"workflows.json"),{force:!0}),console.log(`
32
+ workflows.json omitted (${(P.length/1e6).toFixed(1)} MB plain); workflows.js written with shared sub-structures (${(I.length/1e6).toFixed(1)} MB)`)}else we.writeFileSync(Z.join(K,"workflows.json"),P),console.log(`
33
+ Saved to output/workflows.json`),we.writeFileSync(Z.join(K,"workflows.js"),`const workflows = ${P};`),console.log("Saved to output/workflows.js (for the viewer)");let z=d.flatMap(I=>k.get(I.name)?.nodes??[]),Re=N.map(I=>({fromNodeId:I.fromNodeId,targetNodeId:I.toNodeId,resolved:!0,matchType:"crossLayer",confidence:I.confidence})),je=[...d.flatMap(I=>k.get(I.name)?.resolvedEdges??[]),...Re],ct=Xa(W,z,je);ct.crossServiceEdges=N,we.writeFileSync(Z.join(K,"systemGraph.js"),`const systemGraph = ${se.json(ct,2)};`);let Zt=d.map(({isRepoRoot:I,ownsLeftovers:T,...U})=>({...U,nodeCount:z.filter(F=>F.serviceName===U.name).length,workflowCount:W.filter(F=>F.serviceId===U.name).length}));we.writeFileSync(Z.join(K,"services.js"),`const services = ${se.json(Zt,2)};`),console.log(`Saved to output/systemGraph.js (${ct.workflowLinks.length} workflow links, ${ct.serviceLinks.length} service links)`),console.log("Saved to output/services.js"),console.log(`
34
+ 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 Qt=new Map;for(let I of d){let T=k.get(I.name);if(!T)continue;let U=se.clone(T.nodes.map(B=>({id:B.id,name:B.name,type:B.type,filePath:B.filePath,bodyHash:B.bodyHash??null,startLine:B.startLine===0?0:B.startLine,endLine:B.endLine===Number.MAX_SAFE_INTEGER?null:B.endLine,serviceName:B.serviceName,isEntryPoint:!!B.isEntryPoint}))),F=Ei(se.clone(T.resolvedEdges.map(B=>({fromNodeId:B.fromNodeId,targetNodeId:B.targetNodeId??null,type:B.type,callKind:B.callKind,calleeNameRaw:B.calleeNameRaw,eventName:B.eventName,url:B.url,line:B.line??null,column:B.column??null,resolved:!!B.resolved,matchType:B.matchType??null}))));Qt.set(I.name,{nodes:U,edges:F})}return{workflows:W,perService:k,crossServiceEdges:N,services:d,publicGraph:Qt,publicWorkflows:se.clone(W),publicCrossServiceEdges:se.clone(N),fingerprint:Dn(Fi(i,se.rel)),analyzedFileCount:i.length,repoRoot:se.repoRoot,coverage:ue}}var au=process.argv[1]&&globalThis.__canopyUrl("src/index.js")===su(Z.resolve(process.argv[1])).href;au&&gr(process.argv[2]||process.cwd()).catch(e=>{console.error("Pipeline failed:",e),process.exit(1)});un();wr();ao();De();var Nu=ye.join(ye.dirname(Ic(globalThis.__canopyUrl("src/history/sync.js"))),"..","..","output"),bu=["workflows.json","workflows.js","systemGraph.js","services.js","meta.js","meta.json","history.js"],_u=ye.dirname(Ic(globalThis.__canopyUrl("src/history/sync.js"))).split(ye.sep).includes("node_modules"),Et=e=>process.env.CANOPY_OUTPUT_DIR||(_u&&e?ye.join(ye.resolve(e),".canopy","output"):Nu);async function $u(e,t){let n=console.log;console.log=()=>{};try{return await gr(e,t)}finally{console.log=n}}function Iu(e,{full:t=!1}={}){let n=ye.resolve(e),r=Bn(n),o=xc(n,$n(n),r.rel,{full:t});return{fingerprint:Dn(o.hashes),reused:o.reused,rehashed:o.rehashed}}function ju(e){try{let t=JSON.parse(yt.readFileSync(ye.join(Et(e),"meta.json"),"utf8"));return t.coverage&&ye.resolve(t.repoRoot)===ye.resolve(e)?t.coverage:null}catch{return null}}async function Cu(e,{keep:t,say:n=()=>{},full:r=!1}){let o=Date.now(),s=Ee(e),i=s.versions[s.versions.length-1],a=Iu(e,{full:r}),c=a.fingerprint,l=!!i&&i.fingerprint===c&&(r||i.engineVersion!==Vt()||i.outputFormat!==no);if(i&&i.fingerprint===c&&!l&&!r)return{status:"no-changes",version:i,ms:Date.now()-o,coverage:ju(e),fast:a};let d=yt.mkdtempSync(ye.join(ku.tmpdir(),"canopy-sync-"));try{let f=await $u(e,{outputDir:d,onProgress:n,lowMemory:!0,noCache:r});mt("storing the version"),n(`storing the version (${Math.round((Date.now()-o)/1e3)} s)`);let u=wc(f),h=Ct(u),p={nodes:u.nodes.length,edges:u.edges.length,workflows:u.workflows.length,physicalWorkflows:u.workflows.filter(w=>w.tier==="physical").length,crossServiceEdges:u.crossServiceEdges.length},m=so(e),y=rc(e,h,u,p,t,{refresh:l,protect:m?[m.version]:[]}),g=oc();g&&n("history: "+g);let x=fe(e,["rev-parse","--abbrev-ref","HEAD"]),S=fe(e,["rev-parse","HEAD^{tree}"]);jr(e,{engineFingerprint:Vt(),projectRoot:ye.resolve(e),lastAnalysed:{version:y.version,fingerprint:y.fingerprint,headSha:y.headSha,treeHash:S,branch:x}});let k=await Promise.resolve().then(()=>(po(),$c)).catch(()=>null);k&&k.writeHistoryJs(e,d);let v=Et(e);yt.mkdirSync(v,{recursive:!0});for(let w of bu)yt.existsSync(ye.join(d,w))?yt.copyFileSync(ye.join(d,w),ye.join(v,w)):yt.rmSync(ye.join(v,w),{force:!0});return{status:"new-version",version:y,ms:Date.now()-o,coverage:f.coverage}}finally{yt.rmSync(d,{recursive:!0,force:!0})}}function Fu(e,t=()=>{}){let n=yc(e);if(!n.ok){let r=vc(e);t(`The saved history in .canopy was damaged (${n.problems[0]}). It was moved to .canopy/${r} and Canopy is starting a fresh one; this run rebuilds everything.`)}Ir(e,Vt())}async function mo(e,{keep:t=fn,say:n=console.log,full:r=!1}={}){if(e=ye.resolve(e),ro(e),yt.mkdirSync(te(e).root,{recursive:!0}),Fu(e,n),!sc(e,process.env.CANOPY_VERSION??null,n))return ac(e),n("sync already running - one rerun queued"),{status:"queued"};let o;try{do o=await Cu(e,{keep:t,say:n,full:r}),r=!1,o.status==="no-changes"?n(`no changes (v${o.version.version} ${o.version.fingerprint.slice(0,7)}) [${o.ms} ms]`):n(`v${o.version.version} ${o.version.fingerprint.slice(0,7)} stored: ${o.version.counts.nodes} nodes, ${o.version.counts.edges} edges, ${o.version.counts.workflows} workflows, ${(o.version.bytes/1024/1024).toFixed(2)} MB${o.version.gzip?" (gzip)":""} [${o.ms} ms]`),o.coverage&&n(`
35
+ `+jn(o.coverage));while(cc(e))}finally{ic(e)}return o}De();De();We();import ve from"node:fs";import Be from"node:path";import{spawn as Eu}from"node:child_process";import{fileURLToPath as Pu}from"node:url";var mn="# >>> canopy sync (managed block - do not edit) >>>",Fc="# <<< canopy sync <<<",Pt=["post-commit","post-merge"],Lu=globalThis.__canopyBundle??Be.join(Be.dirname(Pu(globalThis.__canopyUrl("src/history/hooks.js"))),"..","cli.js"),Tu=e=>Be.resolve(e).split(Be.sep).join("/");function hn(e){let t=fe(e,["rev-parse","--git-path","hooks"]);if(!t)throw new Error(`not a git repository: ${e}`);return Be.resolve(e,t)}var jc=JSON.parse(ve.readFileSync(Be.join(le,"package.json"),"utf8")),Ru=jc.name+"@"+jc.version,Cc=e=>Tu(e).replace(/(["$`\\])/g,"\\$1");function ho(e){return[mn,"(",` if command -v canopy >/dev/null 2>&1; then canopy sync --background "${Cc(e)}" >/dev/null 2>&1 </dev/null`,` elif command -v npx >/dev/null 2>&1; then ( npx --yes ${Ru} sync --background "${Cc(e)}" >/dev/null 2>&1 </dev/null & )`,' else echo "canopy not found; skipping map update"'," fi",") || true",Fc].join(`
35
36
  `)+`
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(`
37
+ `}var go=()=>new RegExp(`\\n?${mn.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}[\\s\\S]*?${Fc.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\n?`);function gn(e){let t=hn(e);ve.mkdirSync(t,{recursive:!0});let n=[];for(let r of Pt){let o=Be.join(t,r),s=ve.existsSync(o)?ve.readFileSync(o,"utf8"):null,i;s===null?i=`#!/bin/sh
38
+ `+ho(e):go().test(s)?i=s.replace(go(),()=>`
39
+ `+ho(e)):i=s+(s.endsWith(`
39
40
  `)?"":`
40
41
  `)+`
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,`
42
+ `+ho(e),ve.writeFileSync(o,i.replace(/\r\n/g,`
43
+ `));try{ve.chmodSync(o,493)}catch{}n.push(o)}return n}function Ec(e){let t=hn(e),n=[];for(let r of Pt){let o=Be.join(t,r);if(!ve.existsSync(o))continue;let s=ve.readFileSync(o,"utf8");if(!go().test(s))continue;let i=s.replace(go(),`
44
+ `);i.replace(/^#!.*\n?/,"").trim()===""?ve.rmSync(o,{force:!0}):ve.writeFileSync(o,i.replace(/\n{3,}/g,`
44
45
 
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
+ `)),n.push(o)}return n}function Pc(e){if(!ve.existsSync(Be.resolve(e)))return null;let t=te(e);ve.mkdirSync(t.root,{recursive:!0});let n=ve.openSync(t.log,"a");ve.writeSync(n,`
46
47
  --- ${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})
48
+ `);let r=Object.fromEntries(Object.entries(process.env).filter(([s])=>!/^GIT_/i.test(s)||s.toUpperCase()==="GIT_EXEC_PATH")),o=Eu(process.execPath,[Lu,"sync",Be.resolve(e)],{detached:!0,stdio:["ignore",n,n],windowsHide:!0,env:r});return o.unref(),ve.closeSync(n),o.pid}function Lc(e){let t=hn(e),n=ho(e),r=0,o=0;for(let s of Pt){let i=Be.join(t,s);if(!ve.existsSync(i))continue;let a=ve.readFileSync(i,"utf8").replace(/\r\n/g,`
49
+ `);a.includes(mn)&&(r++,a.includes(n)&&o++)}return r<Pt.length?"absent":o===Pt.length?"current":"outdated"}Er();We();We();import vt from"node:fs";import pp from"node:http";import Ie from"node:path";import{spawn as mp}from"node:child_process";We();import Au from"node:fs";import Ou from"node:http";import Mu from"node:https";import Or from"node:path";import{spawn as Hu,spawnSync as Rc}from"node:child_process";var Hr="https://registry.npmjs.org/canopy-engine/latest",Ar="npm install -g canopy-engine@latest",Tc=1e4,Du=256*1024,Mr=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,Bu=e=>typeof e=="string"&&e.length<=64&&Mr.test(e);function Uu(e,t){let n=Mr.exec(e),r=Mr.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 zu(e=process.env){let t=e.CANOPY_REGISTRY_URL;return t&&/^http:\/\/127\.0\.0\.1:\d{1,5}(\/|$)/.test(t)?t:Hr}function Wu(e=process.env){let t=zu(e),n=t.startsWith("https:")?Mu:Ou;return new Promise((r,o)=>{let s=!1,i=(c,l)=>{s||(s=!0,c(l))},a=n.get(t,{headers:{accept:"application/json","user-agent":"canopy-engine-update-check"}},c=>{if(c.statusCode!==200)return c.resume(),i(o,new Error(`the registry answered HTTP ${c.statusCode}`));let l=0,d=[];c.on("data",f=>{if(l+=f.length,l>Du){i(o,new Error("the registry's answer is larger than 256 KB; ignored")),a.destroy();return}d.push(f)}),c.on("end",()=>{let f;try{f=JSON.parse(Buffer.concat(d).toString("utf8"))?.version}catch{return i(o,new Error("the registry's answer is not valid JSON"))}if(!Bu(f))return i(o,new Error("the registry's answer has no valid version number"));i(r,f)}),c.on("error",f=>i(o,new Error("the connection broke: "+f.message)))});a.setTimeout(Tc,()=>{i(o,new Error(`no answer from the registry within ${Tc/1e3} s`)),a.destroy()}),a.on("error",c=>i(o,new Error("could not reach the registry: "+(c.code||c.message))))})}function Dr(e=le,t=Dt()){return e.split(Or.sep).includes("_npx")?"npx":t?"installed":"dev"}function Ac(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 yn=(e,t)=>t&&/[\s"]/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e;function Gu(e,t){let{cmd:n,pre:r,shell:o}=Ac(t);return new Promise(s=>{let i=Hu(yn(n,o),[...r,...e].map(a=>yn(a,o)),{stdio:"inherit",shell:o,env:t});i.on("error",()=>s(1)),i.on("close",a=>s(a??1))})}function qu(e,t){let{cmd:n,pre:r,shell:o}=Ac(t),s=Rc(yn(n,o),[...r,...e].map(i=>yn(i,o)),{encoding:"utf8",shell:o,env:t,timeout:3e4});return s.status===0?s.stdout.trim():null}function Ju(e){let t=qu(["prefix","-g"],e),n=["canopy","canopy-engine"],r=[];if(t)for(let o of n)r.push(process.platform==="win32"?Or.join(t,o+".cmd"):Or.join(t,"bin",o));for(let o of r){if(!Au.existsSync(o))continue;let s=process.platform==="win32"&&/\.(cmd|bat)$/i.test(o),i=Rc(yn(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 Oc({check:e,version:t,root:n=le,installed:r=Dt(),env:o=process.env,out:s=console.log,err:i=console.error}){let a=Dr(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 c;try{c=await Wu(o)}catch(f){return i(`could not check for updates: ${f.message}`),i(" you can look it up yourself: npm view canopy-engine version"),1}if(Uu(c,t)<=0)return s(`up to date (${t})`),0;if(e)return s(`${c} available (you have ${t}). Run: canopy update`),0;s(`Updating canopy-engine ${t} -> ${c}`),s(` running: ${Ar}`);let l=await Gu(["install","-g","canopy-engine@latest"],o);if(l!==0)return i(`The update did not finish (npm exited with ${l}). Run it yourself: ${Ar}`),1;let d=Ju(o);return d!==c?(i(`npm finished, but the installed canopy reports ${d??"no version"} instead of ${c}. Run it yourself: ${Ar}`),1):(s(`Updated: canopy ${d} is installed.`),0)}import Le from"node:fs";import Pe from"node:path";import Br from"node:vm";import Dc from"node:crypto";import Vu from"node:zlib";var Mc=30,Yt=400,Hc=2*1024*1024,Yu="x-canopy-token",Bc=()=>Dc.randomBytes(24).toString("hex"),Ku=/^(\.env($|[.\-_])|\.npmrc$|\.netrc$|\.pgpass$|\.htpasswd$|id_(rsa|dsa|ecdsa|ed25519)|credentials(\.|$)|.*\.(pem|key|crt|cer|der|p12|pfx|jks|keystore|ppk|gpg|asc|kdbx)$)/i,yo=e=>Ku.test(e);function Xu(e){let t=Pe.join(e,"workflows.json"),n=Pe.join(e,"workflows.js");if(Le.existsSync(t))return{mtime:Le.statSync(t).mtimeMs,data:JSON.parse(Le.readFileSync(t,"utf8"))};if(Le.existsSync(n)){let r=Br.createContext({});return Br.runInContext(Le.readFileSync(n,"utf8"),r,{timeout:1e4}),{mtime:Le.statSync(n).mtimeMs,data:Br.runInContext("workflows",r,{timeout:1e4})}}return null}var Uc=e=>Pe.join(Pe.resolve(e),".canopy","history");function Ur(e){try{let t=JSON.parse(Le.readFileSync(Pe.join(Uc(e),"index.json"),"utf8"));return Array.isArray(t.versions)?t:null}catch{return null}}function zr(e,t){try{if(!t||typeof t.file!="string"||!/^[0-9A-Za-z][0-9A-Za-z._-]*$/.test(t.file))return null;let n=Le.readFileSync(Pe.join(Uc(e),t.file));return JSON.parse((t.gzip?Vu.gunzipSync(n):n).toString("utf8"))}catch{return null}}function Zu(e){let t=Ur(e),n=t?.versions[t.versions.length-1],r=n?zr(e,n):null;return r?{version:n.version,nodes:Array.isArray(r.nodes)?r.nodes:[]}:null}function Qu(e,t=null){let n=new Map;for(let r of e??[])for(let o of r.steps??[]){if(n.has(o.nodeId))continue;let s=o.nodeId.lastIndexOf("::"),i=s===-1?o.nodeId:o.nodeId.slice(0,s),a=o.source&&o.source.available?o.source:null;n.set(o.nodeId,{file:i,startLine:a?.startLine??null,endLine:a?.endLine??null,text:a?.text??null})}for(let r of t??[]){if(typeof r?.id!="string"||n.has(r.id))continue;let o=r.id.lastIndexOf("::");n.set(r.id,{file:typeof r.filePath=="string"?r.filePath:o===-1?r.id:r.id.slice(0,o),startLine:Number.isInteger(r.startLine)&&r.startLine>0?r.startLine:null,endLine:Number.isInteger(r.endLine)?r.endLine:null,text:null})}return n}function zc({outDir:e,repoRoot:t}){let n=null,r=()=>{try{return Le.realpathSync(t)}catch{return null}};function o(){let a=["workflows.json","workflows.js"].map(l=>Pe.join(e,l)).concat(t?[Pe.join(t,".canopy","history","index.json")]:[]),c=0;for(let l of a)try{c=Math.max(c,Le.statSync(l).mtimeMs)}catch{}if(!n||n.stamp!==c){let l=Xu(e),d=t?Zu(t):null;n={stamp:c,index:Qu(l?.data??[],d?.nodes),all:d}}return n.index}function s(){o();let a=n?.all;if(!a)return{status:200,body:{ok:!0,available:!1,nodes:[]}};let c=6e4,l=a.nodes.slice(0,c).map(d=>[d.id,d.name,d.kind,d.service,d.startLine??null,d.endLine??null]);return{status:200,body:{ok:!0,available:!0,version:a.version,total:a.nodes.length,truncated:a.nodes.length>c,nodes:l}}}function i(a){try{if(typeof a!="string"||!a||a.length>2e3)return{status:400,body:{ok:!1,code:"bad-request",message:"node must be a node id"}};let c=o().get(a);if(!c)return{status:404,body:{ok:!1,code:"unknown-node",message:"no such node in the analysed graph"}};if(c.startLine==null)return{status:404,body:{ok:!1,code:"no-range",message:"no source range was recorded for this node"}};let l=r();if(!l)return{status:410,body:{ok:!1,code:"changed",message:"file changed since analysis (the project folder is gone)"}};let d=c.file.split(/[\\/]/);if(!c.file||Pe.isAbsolute(c.file)||/^[A-Za-z]:/.test(c.file)||d.includes(".."))return{status:403,body:{ok:!1,code:"outside-repo",message:"refused: not a path inside the analysed project"}};let f=Pe.resolve(l,c.file),u;try{u=Le.realpathSync(f)}catch{return{status:410,body:{ok:!1,code:"changed",message:"file changed since analysis (the file no longer exists)",file:c.file}}}if(u!==l&&!u.startsWith(l+Pe.sep))return{status:403,body:{ok:!1,code:"outside-repo",message:"refused: the file resolves outside the analysed project"}};let h=Pe.basename(u);if(yo(Pe.basename(f))||yo(h))return{status:403,body:{ok:!1,code:"refused",message:"refused: environment, key and certificate files are never served"}};let p=Le.statSync(u);if(!p.isFile())return{status:403,body:{ok:!1,code:"refused",message:"refused: not a regular file"}};if(p.size>Hc)return{status:403,body:{ok:!1,code:"too-large",message:`refused: the file is larger than ${Hc/1024/1024} MB`}};let m=Le.readFileSync(u);if(m.subarray(0,8e3).includes(0))return{status:403,body:{ok:!1,code:"binary",message:"refused: binary file"}};let y=m.toString("utf8").replace(/\r\n/g,`
50
+ `).split(`
51
+ `);y.length>1&&y[y.length-1]===""&&y.pop();let g=y.length,{startLine:x,endLine:S}=c;if(c.text!=null){let b=y.slice(x-1,S).join(`
52
+ `).replace(/\s+$/gm,""),N=c.text.replace(/\r\n/g,`
53
+ `).replace(/\s+$/gm,"");if(b.trim()!==N.trim())return{status:409,body:{ok:!1,code:"changed",message:"file changed since analysis",file:c.file,startLine:x,endLine:S}}}else if(S>g)return{status:409,body:{ok:!1,code:"changed",message:"file changed since analysis",file:c.file,startLine:x,endLine:S}};let k=Math.max(1,x-Mc),v=Math.min(g,S+Mc),w=!1;if(v-k+1>Yt)if(w=!0,S-x+1>=Yt)k=x,v=x+Yt-1;else{let b=Yt-(S-x+1);k=Math.max(1,x-Math.floor(b/2)),v=Math.min(g,k+Yt-1),k=Math.max(1,v-Yt+1)}return{status:200,body:{ok:!0,nodeId:a,file:c.file,startLine:x,endLine:S,from:k,to:v,total:g,truncated:w,lines:y.slice(k-1,v)}}}catch{return{status:500,body:{ok:!1,code:"error",message:"the source could not be read"}}}}return{read:i,graph:o,allNodes:s}}var ep=(e,t)=>{let n=Buffer.from(String(e??"")),r=Buffer.from(String(t??""));return n.length===r.length&&n.length>0&&Dc.timingSafeEqual(n,r)};function Wc(e,t){if(!new Set([`127.0.0.1:${t}`,`localhost:${t}`]).has(String(e.headers.host??"").toLowerCase()))return!1;let r=e.headers.origin;return!(r!==void 0&&!(r===`http://127.0.0.1:${t}`||r===`http://localhost:${t}`))}function Kt(e,t,n="GET"){return e.method!==n?{status:405,body:{ok:!1,code:"method",message:n+" only"}}:ep(e.headers[Yu],t)?null:{status:403,body:{ok:!1,code:"token",message:"missing or wrong session token"}}}function Gc(e,t,{token:n,service:r}){let o=Kt(e,n);return o||([...t.searchParams.keys()].length?{status:400,body:{ok:!1,code:"bad-request",message:"this request takes no parameters"}}:r.allNodes())}function qc(e,t,{port:n,token:r,service:o}){let s=Kt(e,r);if(s)return s;let i=[...t.searchParams.keys()];return i.length!==1||i[0]!=="node"||t.searchParams.getAll("node").length!==1?{status:400,body:{ok:!1,code:"bad-request",message:"send exactly one parameter: node=<node id>"}}:o.read(t.searchParams.get("node"))}import rp from"node:path";import{execFile as sp}from"node:child_process";function tp(e,t,n){let r=e.length,o=t.length,s=Math.min(r+o,n),i=s+1,a=new Int32Array(2*s+3),c=[];for(let l=0;l<=s;l++){c.push(a.slice());for(let d=-l;d<=l;d+=2){let f=d===-l||d!==l&&a[i+d-1]<a[i+d+1]?a[i+d+1]:a[i+d-1]+1,u=f-d;for(;f<r&&u<o&&e[f]===t[u];)f++,u++;if(a[i+d]=f,f>=r&&u>=o)return np(c,r,o,l,i,e,t)}}return null}function np(e,t,n,r,o){let s=t,i=n,a=[];for(let c=r;c>0;c--){let l=e[c],d=s-i,f=d===-c||d!==c&&l[o+d-1]<l[o+d+1]?d+1:d-1,u=l[o+f],h=u-f;for(;s>u&&i>h;)a.push(["=",s-1,i-1]),s--,i--;s===u?a.push(["+",-1,i-1]):a.push(["-",s-1,-1]),s=u,i=h}for(;s>0&&i>0;)a.push(["=",s-1,i-1]),s--,i--;return a.reverse()}function op(e,t,{maxD:n=1500}={}){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;let o=0;for(;o<e.length-r&&o<t.length-r&&e[e.length-1-o]===t[t.length-1-o];)o++;let s=e.slice(r,e.length-o),i=t.slice(r,t.length-o),a,c=!1;s.length?i.length?(a=tp(s,i,n),a||(c=!0,a=[...s.map((d,f)=>["-",f,-1]),...i.map((d,f)=>["+",-1,f])])):a=s.map((d,f)=>["-",f,-1]):a=i.map((d,f)=>["+",-1,f]);let l=[];for(let d=0;d<r;d++)l.push(["=",d,d]);for(let[d,f,u]of a)l.push([d,f<0?-1:f+r,u<0?-1:u+r]);for(let d=0;d<o;d++)l.push(["=",e.length-o+d,t.length-o+d]);return{ops:l,coarse:c}}function Jc(e,t,{aBase:n=1,bBase:r=1,context:o=3,maxD:s}={}){let{ops:i,coarse:a}=op(e,t,s?{maxD:s}:{}),c=[];i.forEach((u,h)=>{u[0]!=="="&&c.push(h)});let l={added:i.filter(u=>u[0]==="+").length,removed:i.filter(u=>u[0]==="-").length};if(!c.length)return{rows:[],stats:l,coarse:a};let d=[];for(let u of c){let h=Math.max(0,u-o),p=Math.min(i.length-1,u+o),m=d[d.length-1];m&&h<=m[1]+1?m[1]=Math.max(m[1],p):d.push([h,p])}let f=[];for(let[u,h]of d){let p=null,m=null,y=0,g=0,x=[];for(let k=u;k<=h;k++){let[v,w,b]=i[k];v!=="+"&&(p==null&&(p=w+1),y++),v!=="-"&&(m==null&&(m=b+1),g++),v==="="?x.push({t:" ",o:n+w,n:r+b,text:e[w]}):v==="-"?x.push({t:"-",o:n+w,n:null,text:e[w]}):x.push({t:"+",o:null,n:r+b,text:t[b]})}p==null&&(p=i.slice(0,u).filter(k=>k[0]!=="+").length),m==null&&(m=i.slice(0,u).filter(k=>k[0]!=="-").length);let S=(k,v)=>v===0?`${k},0`:v===1?`${k}`:`${k},${v}`;f.push({t:"@",header:`@@ -${S(p,y)} +${S(m,g)} @@`,oldStart:p,oldLen:y,newStart:m,newLen:g}),f.push(...x)}return{rows:f,stats:l,coarse:a}}function Wr(e,t,n=1){let r=e.map((s,i)=>t==="+"?{t:"+",o:null,n:n+i,text:s}:{t:"-",o:n+i,n:null,text:s}),o=t==="+"?`@@ -0,0 +1${e.length===1?"":","+e.length} @@`:`@@ -1${e.length===1?"":","+e.length} +0,0 @@`;return{rows:e.length?[{t:"@",header:o,oldStart:t==="+"?0:1,oldLen:t==="+"?0:e.length,newStart:t==="+"?1:0,newLen:t==="+"?e.length:0},...r]:[],stats:t==="+"?{added:e.length,removed:0}:{added:0,removed:e.length}}}var ip=5e3,ap=3*1024*1024,cp="line-level changes need git history",lp=/^[0-9a-f]{40}$/,Vc=/^[1-9][0-9]{0,5}$/,dp=2e3;function fp(e=process.env){let t=["PATH","Path","SystemRoot","SYSTEMROOT","windir","TEMP","TMP","TMPDIR","HOME","USERPROFILE","HOMEDRIVE","HOMEPATH","APPDATA","LOCALAPPDATA","COMSPEC","PATHEXT"],n={};for(let r of t)e[r]!==void 0&&(n[r]=e[r]);return{...n,GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0",GIT_ASKPASS:"",LC_ALL:"C"}}function up(e){return typeof e!="string"||!e||e.length>1e3?"not a path":/[\u0000-\u001f\u007f]/.test(e)?"control characters in the path":e.startsWith("-")?"path starts with a dash":rp.isAbsolute(e)||/^[A-Za-z]:/.test(e)||e.startsWith("/")||e.startsWith("\\")||e.split(/[\\/]/).includes("..")?"not a path inside the project":e.split(/[\\/]/).some(t=>yo(t))?"environment, key and certificate files are never served":null}function Yc({repoRoot:e,gitFile:t="git",gitPre:n=[],timeoutMs:r=ip,maxBlob:o=ap,env:s=fp()}){let i=new Map;function a(p){if(i.has(p.file))return i.get(p.file);let m=zr(e,p),y=new Map;for(let g of m?.nodes??[])y.has(g.id)||y.set(g.id,g);return i.set(p.file,y),i.size>4&&i.delete(i.keys().next().value),y}let c=new Map;function l(p,m){let y=p+":"+m;return c.has(y)?Promise.resolve({ok:!0,buf:c.get(y)}):d(p,m).then(g=>(g.ok&&(c.set(y,g.buf),c.size>24&&c.delete(c.keys().next().value)),g))}function d(p,m){return new Promise(y=>{sp(t,[...n,"--no-pager","cat-file","blob",`${p}:${m}`],{cwd:e,env:s,timeout:r,maxBuffer:o,encoding:"buffer",windowsHide:!0},(g,x)=>{if(!g)return y({ok:!0,buf:x});if(g.killed||g.signal==="SIGTERM"||g.code==="ETIMEDOUT")return y({ok:!1,why:"timeout"});if(String(g.code).includes("MAXBUFFER"))return y({ok:!1,why:"too-large"});y({ok:!1,why:"missing"})})})}function f(p,m,y){let g=p.get(y),x=m.get(y);if(g&&x)return{status:g.bodyHash===x.bodyHash?"unchanged":"modified",oldN:g,newN:x};let S=(k,v)=>k.kind===v.kind&&k.name===v.name&&k.bodyHash===v.bodyHash&&k.filePath!==v.filePath;if(x){let k=[...p.values()].filter(v=>!m.has(v.id)&&S(v,x)).sort((v,w)=>v.id<w.id?-1:1)[0];return k?{status:"moved",oldN:k,newN:x}:{status:"added",oldN:null,newN:x}}if(g){let k=[...m.values()].filter(v=>!p.has(v.id)&&S(g,v)).sort((v,w)=>v.id<w.id?-1:1)[0];return k?{status:"moved",oldN:g,newN:k}:{status:"removed",oldN:g,newN:null}}return null}let u=p=>p&&Number.isInteger(p.startLine)&&p.startLine>0&&Number.isInteger(p.endLine)&&p.endLine>=p.startLine?[p.startLine,p.endLine]:null;async function h(p,m,y){try{if(typeof p!="string"||!p||p.length>dp)return{status:400,body:{ok:!1,code:"bad-request",message:"node must be a node id"}};if(!Vc.test(String(m))||!Vc.test(String(y)))return{status:400,body:{ok:!1,code:"bad-request",message:"from and to must be version numbers"}};let g=Ur(e),x=g?.versions?.find(L=>String(L.version)===String(m)),S=g?.versions?.find(L=>String(L.version)===String(y));if(!x||!S)return{status:404,body:{ok:!1,code:"unknown-version",message:"no such stored version"}};let k=a(x),v=a(S),w=f(k,v,p);if(!w)return{status:404,body:{ok:!1,code:"unknown-node",message:"no such node in these versions"}};let{status:b,oldN:N,newN:$}=w;for(let L of[N,$]){let z=L&&up(L.filePath);if(z)return{status:403,body:{ok:!1,code:"refused",message:"refused: "+z}}}let j={nodeId:p,status:b,from:x.version,to:S.version,oldFile:N?.filePath??null,newFile:$?.filePath??null,oldRange:u(N),newRange:u($),name:($??N).name},O=[];N&&x.dirty&&O.push(x.version),$&&S.dirty&&!O.includes(S.version)&&O.push(S.version);let D=O.length?"approximate: taken with uncommitted changes":null,G=(L,z="")=>({status:200,body:{ok:!0,mode:"node-only",reason:L,message:cp+z,approximate:D,...j}});if(b==="unchanged")return{status:200,body:{ok:!0,mode:"lines",rows:[],stats:{added:0,removed:0},formattingOnly:!1,approximate:D,message:"this function did not change between these versions",...j}};let M=[];N&&M.push(["old",x.headSha,N.filePath]),$&&M.push(["new",S.headSha,$.filePath]);for(let[,L]of M)if(typeof L!="string"||!lp.test(L))return G("no-git");let q=await Promise.all(M.map(([,L,z])=>l(L,z))),E={};for(let L=0;L<M.length;L++){let z=q[L];if(!z.ok)return z.why==="too-large"?{status:200,body:{ok:!0,mode:"node-only",reason:"too-large",message:"this file is too large to diff here",approximate:D,...j}}:G(z.why==="timeout"?"timeout":"missing-commit");if(z.buf.subarray(0,8e3).includes(0))return{status:403,body:{ok:!1,code:"binary",message:"refused: binary file"}};E[M[L][0]]=z.buf.toString("utf8")}let C=L=>{let z=L.replace(/\r\n/g,`
54
+ `).split(`
55
+ `);return z.length>1&&z[z.length-1]===""&&z.pop(),z},R=(L,z)=>{let Re=C(L);if(!z)return{lines:Re,base:1,clamped:!1};let je=z[1]>Re.length;return{lines:Re.slice(z[0]-1,z[1]),base:z[0],clamped:je}},W=E.old!=null?R(E.old,j.oldRange):{lines:[],base:1,clamped:!1},K=E.new!=null?R(E.new,j.newRange):{lines:[],base:1,clamped:!1},se=E.old!=null&&E.new!=null&&E.old!==E.new&&C(E.old).join(`
56
+ `)===C(E.new).join(`
57
+ `)&&/\r\n/.test(E.old)!==/\r\n/.test(E.new),Xe={...j,approximate:D??(W.clamped||K.clamped?"approximate: the stored line range no longer fits the file":null)};if(W.lines.length>5e3||K.lines.length>5e3)return{status:200,body:{ok:!0,mode:"node-only",reason:"too-large",message:`too large to diff here (more than ${5e3} lines on one side)`,...Xe}};let ue;b==="added"?ue=Wr(K.lines,"+",K.base):b==="removed"?ue=Wr(W.lines,"-",W.base):ue=Jc(W.lines,K.lines,{aBase:W.base,bBase:K.base});let _=L=>L.join(`
58
+ `).replace(/\s+/g,""),P=b!=="added"&&b!=="removed"&&ue.stats.added+ue.stats.removed>0&&_(W.lines)===_(K.lines);return{status:200,body:{ok:!0,mode:"lines",rows:ue.rows,stats:ue.stats,coarse:!!ue.coarse,formattingOnly:P,eolOnly:se,...Xe,message:se?"line endings changed":b==="moved"&&!ue.rows.length?"moved to another file, the code is the same":P?"formatting only":null}}}catch{return{status:500,body:{ok:!1,code:"error",message:"the diff could not be computed"}}}}return{diff:h}}async function Kc(e,t,{token:n,service:r}){let o=Kt(e,n);if(o)return o;let s=[...t.searchParams.keys()],i=["node","from","to"].every(a=>t.searchParams.getAll(a).length===1);return s.length!==3||!i?{status:400,body:{ok:!1,code:"bad-request",message:"send exactly three parameters: node=<node id>&from=<version>&to=<version>"}}:r.diff(t.searchParams.get("node"),t.searchParams.get("from"),t.searchParams.get("to"))}function Xc({now:e=Date.now,holdMs:t=Number(process.env.CANOPY_SEEN_HOLD_MS)||6e4,staleMs:n=null,commit:r}){let o=n??Math.max(t*.75,2e3),s=null,i=null,a=!1;return{ping(){let c=e();s===null&&(s=c),i=c},check(){if(a||s===null)return!1;let c=e();return c-s>=t&&c-i<=o?(a=!0,r(),!0):!1},flush(){return a||s===null?!1:(a=!0,r(),!0)},get acknowledged(){return s!==null},get committed(){return a}}}De();po();un();De();var qr={".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 Zc(e,t,n){let r=Ie.join(e,Ie.normalize(t).replace(/^([/\\]|\.\.[/\\])+/,""));if(!r.startsWith(e+Ie.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":qr[Ie.extname(r).toLowerCase()]??"application/octet-stream","cache-control":"no-store"}).end(s)})}var Qc=(()=>{try{return JSON.parse(vt.readFileSync(Ie.join(le,"package.json"),"utf8")).version}catch{return null}})();function hp({env:e=process.env,version:t=Qc,kind:n=Dr()}={}){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="${Hr}" data-current="${t}">`}function gp(e,t,n){vt.readFile(Ie.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":qr[".html"],"cache-control":"no-store"}).end(n?o.replace("</head>",n+`
59
+ </head>`):o)})}var vo=()=>{let e=Ie.join(le,"ui-react");return!vt.existsSync(Ie.join(e,"index.html"))||!vt.existsSync(Ie.join(e,"dist"))?`this install has no built viewer (ui-react/dist is missing)
60
+ fix: reinstall canopy from a build that includes the viewer`:null};function yp(){try{let e=JSON.parse(vt.readFileSync(Ie.join(le,"package.json"),"utf8")).canopyFeedbackUrl;return typeof e=="string"&&/^https:\/\/[^\s"<>]+$/.test(e)?e:null}catch{return null}}function vp(e,t){if(t)return t;try{return JSON.parse(vt.readFileSync(Ie.join(e,"meta.json"),"utf8")).repoRoot??null}catch{return null}}async function xo(e,t=0,{updateTag:n=hp(),repoRoot:r=null,token:o=Bc(),diffOptions:s={}}={}){e=Ie.resolve(e);let i=Ie.join(le,"ui-react"),a=vp(e,r)??"",c=zc({outDir:e,repoRoot:a}),l=Yc({repoRoot:a,...s}),d=(x,S)=>x.writeHead(S.status,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}).end(JSON.stringify(S.body)),f=yp(),u=`<meta name="canopy-session" content="${o}">`+(f?`
61
+ <meta name="canopy-feedback" content="${f}">`:""),h=new Map,p=a?Xc({commit:()=>{try{let x=Ee(a),S=x.versions[x.versions.length-1];S&&gc(a,S,{branch:fe(a,["rev-parse","--abbrev-ref","HEAD"])})}catch{}}}):null,m=0,y=pp.createServer((x,S)=>{if(!Wc(x,m)){S.writeHead(403,{"content-type":"text/plain","cache-control":"no-store"}).end("forbidden");return}let k;try{k=new URL(x.url??"/","http://127.0.0.1")}catch{S.writeHead(400).end("bad request");return}let v;try{v=decodeURIComponent(k.pathname)}catch{S.writeHead(400).end("bad request");return}if(v==="/api/source"){let w=qc(x,k,{port:m,token:o,service:c});d(S,w);return}if(v==="/api/health"){let w=null;try{w=a?gt(a)?.projectId??null:null}catch{}d(S,{status:200,body:{ok:!0,app:"canopy",version:Qc,pid:process.pid,projectId:w}});return}if(v==="/api/seen"){let w=Kt(x,o,"POST");if(w){d(S,w);return}p?.ping(),d(S,{status:200,body:{ok:!0}});return}if(v==="/output/history.js"&&a&&vt.existsSync(Ie.join(a,".canopy","history","index.json"))){let w=null;try{w=Rr(a,{sinceCache:h})}catch{w=null}if(w){S.writeHead(200,{"content-type":qr[".js"],"cache-control":"no-store"}).end(w);return}}if(v==="/api/nodes"){d(S,Gc(x,k,{token:o,service:c}));return}if(v==="/api/diff"){Kc(x,k,{token:o,service:l}).then(w=>d(S,w),()=>d(S,{status:500,body:{ok:!1,code:"error",message:"the diff could not be computed"}}));return}if(v==="/"||v==="/index.html"){S.writeHead(302,{location:"/ui-react/index.html"}).end();return}if(v==="/ui-react/index.html")return gp(i,S,u+(n?`
62
+ `+n:""));if(v.startsWith("/ui-react/"))return Zc(i,v.slice(10),S);if(v.startsWith("/output/"))return Zc(e,v.slice(8),S);S.writeHead(404).end("not found")});await new Promise((x,S)=>{y.once("error",S),y.listen(t,"127.0.0.1",x)}),m=y.address().port;let g=null;if(p){g=setInterval(()=>{try{p.check()}catch{}},2e3),g.unref?.();let x=y.close.bind(y);y.close=S=>{clearInterval(g);try{p.flush()}catch{}return x(S)},process.once("exit",S=>{if(S===0||S===130||S===143)try{p.flush()}catch{}})}return{server:y,port:m,url:`http://127.0.0.1:${m}/`,token:o,seen:p}}function Jr(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=mp(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),!0}catch{return!1}}We();De();import Ke from"node:fs";import st from"node:path";import{execFileSync as el}from"node:child_process";function wo(e){let t=[],n=(r,o,s,i)=>{let a=!1,c="";try{let l=s();a=l===!0||!!(l&&l.ok),c=l&&l.detail?l.detail:""}catch(l){c=String(l.message??l).split(`
63
+ `)[0]}t.push({name:r,critical:o,ok:a,detail:c,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])=>!Ke.existsSync(st.join(He(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=[st.join(le,"src","stage2_parse","queries"),st.join(le,"dist","queries")].find(s=>Ke.existsSync(s))??st.join(le,"dist","queries"),o=Ke.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=te(e).root;Ke.mkdirSync(r,{recursive:!0});let o=st.join(r,`.doctor-${process.pid}`);return Ke.writeFileSync(o,"x"),Ke.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:!!el("git",["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}),detail:el("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:Ke.existsSync(st.join(le,"ui-react","index.html"))&&Ke.existsSync(st.join(le,"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(!fe(e,["rev-parse","--git-dir"]))return{ok:!1,detail:"not a git repository"};let r=hn(e),o=Pt.every(s=>Ke.existsSync(st.join(r,s))&&Ke.readFileSync(st.join(r,s),"utf8").includes(mn));return{ok:o,detail:o?"post-commit, post-merge":""}},`canopy hook install "${e}"`),t}function tl(e,t,n,r=console.log){r(`canopy ${n} doctor (${t})
52
64
  `);for(let s of e)r(`${s.ok?"OK ":"FAIL"} ${s.name}${s.detail?" - "+s.detail:""}${s.ok?"":`
53
65
  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
66
+ ${o.length?`${o.length} critical problem(s) - fix them and run canopy doctor again`:"all critical checks passed"}`),o.length}import xe from"node:fs";import $p from"node:net";import Ip from"node:os";import it from"node:path";import jp from"node:readline";De();function Yr({stream:e=process.stdout,env:t=process.env,flags:n={},platform:r=process.platform}={}){let o=!!e.isTTY,s="NO_COLOR"in t&&t.NO_COLOR!==""||!!n["no-color"]||n.color===!1||t.TERM==="dumb",i=o&&!s&&!n.quiet,a=i&&t.TERM!=="linux"&&(r!=="win32"||!!(t.WT_SESSION||t.TERM_PROGRAM||t.ConEmuANSI==="ON"||t.ANSICON)||/UTF-?8/i.test(`${t.LC_ALL??""}${t.LC_CTYPE??""}${t.LANG??""}`));return{tty:o,color:i,rich:i,unicode:a,columns:Math.max(40,Math.min(e.columns||80,200)),quiet:!!n.quiet}}var Vr={unicode:{ok:"\u2714",fail:"\u2716",spin:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],full:"\u2588",empty:"\u2591",arrow:"\u2192",dot:"\xB7"},ascii:{ok:"[ok]",fail:"[x]",spin:["|","/","-","\\"],full:"#",empty:"-",arrow:"->",dot:"-"}},xp=(e,t,n)=>e?`\x1B[${t}m${n}\x1B[0m`:n,nl=e=>e<59500?`${(e/1e3).toFixed(1)} s`:`${Math.floor(e/6e4)} min ${String(Math.round(e%6e4/1e3)).padStart(2,"0")} s`,wp=e=>!Number.isFinite(e)||e<0?"":e<1?"< 1 s":e<60?`${Math.round(e)} s`:`${Math.floor(e/60)} min ${Math.round(e%60)} s`;function Sp({done:e,total:t,unit:n="files",elapsedMs:r,width:o=24,sym:s=Vr.ascii}){let i=t>0?Math.min(1,e/t):0,a=Math.round(i*o),c=r>500?e/(r/1e3):0,l=c>0?(t-e)/c:NaN,d=s.full.repeat(a)+s.empty.repeat(o-a),f=String(Math.floor(i*100)).padStart(3)+"%";return`[${d}] ${f} ${e.toLocaleString("en-US")}/${t.toLocaleString("en-US")} ${n}${c?` ${Math.round(c).toLocaleString("en-US")} ${n}/s`:""}${l===l&&i<1?` ETA ${wp(l)}`:""}`}function ol({stream:e=process.stdout,caps:t=Yr({stream:e}),now:n=()=>Date.now(),interval:r=80,onExitHook:o=!0}={}){let s=t.unicode?Vr.unicode:Vr.ascii,i=(C,R)=>xp(t.color,C,R),a=C=>i("2",C),c=C=>i("32",C),l=C=>i("31",C),d=C=>i("1",C),f=C=>i("36",C),u=null,h=null,p=0,m=null,y=!1,g=!1,x=-1,S="",k=C=>{try{e.write(C)}catch{}},v=()=>{t.rich&&!g&&(k("\x1B[?25l"),g=!0)},w=()=>{g&&(k("\x1B[?25h"),g=!1)},b=()=>{y&&(k("\r\x1B[2K"),y=!1)},N=C=>C.replace(/\u001b\[[0-9;?]*[A-Za-z]/g,"").length;function $(C){let R=u.title,W=C(R),K=t.columns-1;N(W)>K&&(R=R.replace(/\s*\(.*\)\s*$/,""),W=C(R));let se=N(W)-K;if(se>0){let Xe=t.unicode?"\u2026":"...";R=R.slice(0,Math.max(6,R.length-se-Xe.length))+Xe,W=C(R)}return W}function j(){let C=i("36",s.spin[p%s.spin.length]);return $(h?R=>`${C} ${R} ${Sp({done:h.done,total:h.total,unit:h.unit,elapsedMs:n()-h.started,width:Math.max(8,Math.min(24,t.columns-66)),sym:s})}`:R=>`${C} ${R}${S?a(" "+S):""} ${a(nl(n()-u.started))}`)}function O(){!t.rich||!u||(v(),k(`\r\x1B[2K${j()}`),y=!0)}let D=()=>{p++,O()},G=()=>{t.rich&&r>0&&!m&&(m=setInterval(D,r),m.unref?.())},M=()=>{m&&(clearInterval(m),m=null)};function q(C=!0){if(!u)return;M();let R=nl(n()-u.started);t.rich&&(b(),k(`${C?c(s.ok):l(s.fail)} ${u.title} ${a(R)}
67
+ `)),u=null,h=null,S="",x=-1,w()}let E={caps:t,line(C=""){t.quiet||(t.rich&&y?(b(),k(C+`
68
+ `),O()):k(C+`
69
+ `))},say(C){if(t.quiet)return;if(!t.rich){k(String(C)+`
70
+ `);return}let R=/^\[(\d+)\/(\d+)\] (.*?)\.\.\.$/.exec(C);if(R){q(!0),u={n:+R[1],total:+R[2],title:R[3],started:n()},p=0,O(),G();return}if(/^\s{6}\S/.test(C)){E.line(" "+a(String(C).trim()));return}E.line(String(C))},important(C){t.rich&&y?(b(),k(C+`
71
+ `),O()):k(String(C)+`
72
+ `)},banner(C,R,W){if(!t.quiet){if(!t.rich){k(`${C} ${R} - ${W}
73
+ `);return}k(`
74
+ ${d(f(C))} ${a("v"+R)} ${a(s.dot)} ${W}
75
+
76
+ `)}},progress(C,R,W="files",K="reading files"){if(t.quiet)return;if(t.rich){h=h??{started:n()},Object.assign(h,{done:C,total:R,unit:W}),m||O();return}let se=R>0?Math.floor(C/R*10):0;se!==x&&(x=se,k(` ${K}: ${C} of ${R}
77
+ `))},endProgress(){h=null,x=-1},status(C){t.quiet||(t.rich?(h=null,S=C,O()):k(` ${C}
78
+ `))},endStep:q,tick:D,final({url:C,changes:R=null,update:W=null,hint:K="press Ctrl+C to stop"}){if(q(!0),t.quiet){k(C+`
79
+ `);return}t.rich&&(k(`
80
+ ${c(s.ok)} ${d("Canopy is ready")}
81
+
82
+ ${a("Local:")} ${f(C)}
83
+ `),R&&k(` ${a("Since last visit:")} ${R}
84
+ `),W&&k(` ${a("Update:")} ${W}
85
+ `),k(`
86
+ ${a(K)}
87
+ `))},restore(){M(),y&&b(),w()}};if(o&&t.rich){let C=()=>E.restore();process.once("exit",C);for(let R of["SIGINT","SIGTERM"])process.once(R,()=>{C(),process.exit(R==="SIGINT"?130:143)})}return E}De();un();import Xt from"node:fs";import kp from"node:http";import Kr from"node:path";var Lt=e=>Kr.join(te(e).root,"server.json"),rl=e=>Kr.join(te(e).root,"server.lock");function Np(e,{timeoutMs:t=1500}={}){return new Promise(n=>{let r=kp.get({host:"127.0.0.1",port:e,path:"/api/health",headers:{host:`127.0.0.1:${e}`},timeout:t},o=>{let s="";o.on("data",i=>{s+=i}),o.on("end",()=>{try{let i=JSON.parse(s);n(o.statusCode===200&&i.ok&&i.app==="canopy"?i:null)}catch{n(null)}})});r.on("timeout",()=>{r.destroy(),n(null)}),r.on("error",()=>n(null))})}var bp=e=>{try{return gt(e)?.projectId??null}catch{return null}};async function _p(e){let t=null;try{t=JSON.parse(Xt.readFileSync(Lt(e),"utf8"))}catch{return null}let r=t&&Number.isInteger(t.pid)&&t.pid!==process.pid&&kr(t.pid)&&Number.isInteger(t.port)?await Np(t.port):null;if(!(r&&(!t.projectId||!r.projectId||t.projectId===r.projectId))){try{Xt.rmSync(Lt(e),{force:!0})}catch{}return null}return{...t,url:`http://127.0.0.1:${t.port}/`}}async function So(e,t,{waitMs:n=6e3}={}){let r=Date.now()+n;for(;;){let o=await _p(e);if(o)return{ok:!1,running:o};if(br(rl(e),{},t).ok)return{ok:!0};if(Date.now()>r)return{ok:!1,running:null,busy:!0};await new Promise(i=>setTimeout(i,150))}}function ko(e,{port:t,version:n}){let r={pid:process.pid,port:t,startedAt:new Date().toISOString(),version:n,projectId:bp(e)},o=Lt(e)+"."+process.pid+".tmp";Xt.mkdirSync(Kr.dirname(Lt(e)),{recursive:!0}),Xt.writeFileSync(o,JSON.stringify(r,null,2)),Xt.renameSync(o,Lt(e));let s=()=>{try{Nr(Lt(e))?.pid===process.pid&&Xt.rmSync(Lt(e),{force:!0})}catch{}_r(rl(e))};return process.once("exit",s),{unregister:s}}po();var sl=Number(process.env.CANOPY_MIN_FREE_MB)||300,Cp=".js .jsx .mjs .cjs .ts .tsx .mts .cts",No=class extends Error{constructor(t,n){super(n),this.code=t,this.line=n}},Te=(e,t)=>{throw new No(e,t)};function Fp(e){let t=!!fe(e,["rev-parse","--git-dir"]),n=it.join(e,".gitignore"),r=xe.existsSync(n);if(!t&&!r)return"skipped";let o=r?xe.readFileSync(n,"utf8"):"";if(o.split(/\r?\n/).some(i=>/^\/?\.canopy\/?$/.test(i.trim())))return"already";let s=/\r\n/.test(o)?`\r
55
88
  `:`
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(`
89
+ `;return xe.appendFileSync(n,(o&&!/\r?\n$/.test(o)?s:"")+"# Canopy (code map output)"+s+".canopy/"+s),r?"added":"created"}var il=e=>it.join(te(e).root,"prefs.json"),al=e=>{try{return JSON.parse(xe.readFileSync(il(e),"utf8"))}catch{return{}}};function bo(e,t){let n={...al(e),...t};for(let r of Object.keys(n))n[r]===void 0&&delete n[r];xe.mkdirSync(te(e).root,{recursive:!0}),xe.writeFileSync(il(e),JSON.stringify(n,null,2))}function Ep(e){return new Promise(t=>{let n=$p.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 Pp(e){try{let t=xe.statfsSync(e);return Math.floor(t.bavail*t.bsize/1048576)}catch{return null}}var Lp=()=>!!(process.stdin.isTTY&&process.stdout.isTTY)||!!process.env.CANOPY_ASSUME_TTY;function Tp(e,t){return new Promise(n=>{let r=jp.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 Rp(e){try{return JSON.parse(xe.readFileSync(it.join(e,"meta.json"),"utf8"))}catch{return null}}function Ap(e){try{return JSON.parse(xe.readFileSync(it.join(e,"services.js"),"utf8").replace(/^\s*const services\s*=\s*/,"").replace(/;\s*$/,""))}catch{return[]}}var Op=e=>`How did it go? ${e.canopyFeedbackUrl||"see FEEDBACK.md in the README (about 20 minutes)"}`;async function cl(e){let t=e.say?null:ol({caps:Yr({flags:{quiet:e.quiet,"no-color":e.noColor}})}),n=e.say??(f=>t.say(f)),r=f=>t?t.important(f):n(f),{pkg:o}=e,s=null;try{return await i()}catch(f){if(t?.endStep(!1),t?.restore(),f instanceof No){if(r(f.line),s)try{xe.rmdirSync(s)}catch{}return f.code}return r(`Canopy stopped because of an unexpected problem: ${String(f.message??f).split(`
57
90
  `)[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(`
91
+ Run "canopy doctor", then send its output and .canopy/sync.log to whoever gave you Canopy.`),process.env.CANOPY_DEBUG&&n(f.stack),1}async function i(){let f=it.resolve(e.target??process.cwd());t?t.banner("Canopy",o.version,"a map of what your JavaScript / TypeScript code does"):n(`Canopy ${o.version} - a map of what your JavaScript / TypeScript code does`),n(`Folder: ${it.basename(f)||f}
92
+ `),n("[1/6] Checking this computer..."),Number(process.versions.node.split(".")[0])<18&&Te(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 u=xe.existsSync(f)&&xe.statSync(f).isDirectory();xe.existsSync(f)||Te(1,`That folder does not exist: ${f}. Check the spelling, or run canopy inside your project folder.`),u||Te(1,`${f} is a file, not a folder. Run canopy on the folder that contains it: canopy "${it.dirname(f)}"`);let h=xe.existsSync(te(f).root),p=wo(f);h||(s=te(f).root);let m=p.find(E=>E.critical&&!E.ok);m&&Te(1,`${m.name} failed${m.detail?" ("+m.detail+")":""}. ${m.fix}.`.replace(/\.\.$/,"."));let y=!!fe(f,["rev-parse","--git-dir"]),g=p.find(E=>E.name==="git available")?.ok,x=vo();x&&!e.noOpen&&Te(1,`Canopy cannot show the map: ${x.replace(/\n\s*/g,". ")}.`);let S=Pp(f);if(S!==null&&S<sl&&Te(1,`Only ${S} MB free on the disk holding ${f}; Canopy needs about ${sl} MB. Free some space and run canopy again.`),!e.noOpen){let E=await Ep(e.port??0);E.ok||Te(1,E.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 (${E.code||E.message}). Check your firewall or security software and run canopy again.`)}n(` Node ${process.versions.node}, ${g?"git found":"git not found (no version history or commit hook)"}, ${S===null?"disk space not checked":S+" MB free"}${e.noOpen?"":", a local port is free"}.`),n("[2/6] Looking at your project..."),xe.readdirSync(f).filter(E=>E!==".git"&&E!==".canopy").length===0&&Te(1,`${f} is empty. Add some JavaScript or TypeScript code and run canopy again.`);let v=$n(f);v.length===0&&Te(3,`No JavaScript or TypeScript files found in ${f}. Canopy currently supports JavaScript and TypeScript (${Cp}); other languages are not read yet.
93
+ What to try next: run canopy inside the folder that holds your .js / .ts code (for a monorepo, the folder of one package), or pass it: canopy <folder>.`);let w=y&&fe(f,["rev-parse","--verify","-q","HEAD"])!==null;n(` ${v.length.toLocaleString("en-US")} JavaScript / TypeScript file${v.length===1?"":"s"}. ${y?w?"Git repository.":"Git repository with no commits yet (that is fine).":"Not a git repository (that is fine; version-aware features are limited)."}`),n("[3/6] Preparing the output folder..."),xe.mkdirSync(te(f).root,{recursive:!0}),ro(f);let b=Fp(f),N={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"}[b];n(` Map output goes to ${it.join(f,".canopy")} (${N}).`),n("[4/6] Commit hook..."),await a(f,y);let $=Ee(f).versions.length>0;n(`[5/6] ${$?"Checking what changed since last time":"Building your map for the first time (a big project can take a few minutes)"}...`);let j=await c(f,v.length);l(f,j);let O=null;try{O=Lr(uo(f))}catch{O=null}O&&!(t&&t.caps.rich)&&n(` ${O}.
94
+ `);let D=Et(f);if(e.noOpen)return n("[6/6] Not opening the map (--no-open). To view it later: canopy open"),d(),0;n("[6/6] Opening the map...");let G=await So(f,o.version);if(!G.ok&&G.running){let E=G.running.url,C=Jr(E);return t&&t.caps.quiet?(t.final({url:E}),0):(n(` Canopy is already running for this project (started ${G.running.startedAt?.replace("T"," ").slice(0,16)??"earlier"}): ${E}`),n(C?" Opened it in your browser. Nothing else was started.":" Open that address in your browser. Nothing else was started."),(!t||!t.caps.rich)&&d(),0)}G.ok||Te(1,"Another Canopy is just starting for this project. Wait a few seconds and run canopy again, or open the address it printed.");let M;try{M=await xo(D,e.port??0,{repoRoot:f}),ko(f,{port:M.port,version:o.version})}catch(E){Te(1,`Canopy cannot start the viewer: ${E.code||E.message}. ${E.code==="EADDRINUSE"?"Pick another port with --port=NUMBER.":"Check your firewall or security software."}`)}let q=Jr(M.url);return t&&t.caps.rich?t.final({url:M.url,changes:O,hint:q?"your browser should open now; press Ctrl+C to stop":"open that address in your browser; press Ctrl+C to stop"}):t&&t.caps.quiet?t.final({url:M.url}):(n(` ${M.url}`),n(q?" Your browser should open now. If it does not, paste that address into one.":" Open that address in your browser."),d()),e.forSeconds?(await new Promise(E=>setTimeout(E,e.forSeconds*1e3)),M.server.close(),t?.restore(),0):((!t||!t.caps.rich)&&n("Press Ctrl+C to stop."),await new Promise(()=>{}),0)}async function a(f,u){if(e.noHook){n(" Commit hook skipped (--no-hook).");return}if(!u){n(" No git repository here, so there is no commit hook to set up.");return}if(!Mp()){n(" git is not installed, so the commit hook is skipped.");return}let h;try{h=Lc(f)}catch(m){n(" Could not look at the git hooks ("+String(m.message).split(`
95
+ `)[0]+"); skipping the commit hook.");return}if(h==="current"){n(" The map already updates on every commit.");return}if(h==="outdated"){try{gn(f),n(" Refreshed the commit hook (it now matches this Canopy).")}catch(m){n(" Could not refresh the commit hook: "+String(m.message).split(`
96
+ `)[0])}return}if(al(f).hook==="declined"&&!e.yes){n(" The commit hook is off (you chose that earlier). Turn it on with: canopy hook install");return}let p=!0;if(e.yes)n(" Update the map on every commit? [Y/n] Y (--yes)");else if(!Lp())n(" Update the map on every commit? [Y/n] Y (default; no terminal to ask)");else{let m=await Tp(" Update the map on every commit? [Y/n] ","Y");p=/^y(es)?$/i.test(m)}if(!p){bo(f,{hook:"declined"}),n(" Okay, no hook. Turn it on any time with: canopy hook install");return}try{gn(f),bo(f,{hook:void 0}),n(" 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(m){n(" Could not install the commit hook: "+String(m.message).split(`
97
+ `)[0]+". Continuing without it.")}}async function c(f,u){let h=Date.now(),p=g=>{let x=String(g),S=/parsing: (\d+)\/(\d+) files/.exec(x);if(S){let k=Number(S[1]);t?t.progress(k,Number(S[2])):n(` reading files: ${S[1]} of ${S[2]}`);return}/^(linking calls|linking services|writing the map|storing the version)/.test(x)&&(t?(t.endProgress(),t.status(x)):n(` ${x}`))};n(` Reading ${u.toLocaleString("en-US")} file${u===1?"":"s"}, linking calls, finding entry points, tracing workflows...`);let m;for(let g=0;g<2&&(m=await mo(f,{say:x=>p(x),onProgress:p,full:!!e.full}).catch(x=>Te(1,`The analysis failed: ${String(x.message??x).split(`
63
98
  `)[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
99
+ Run "canopy doctor" and send its output with ${it.join(f,".canopy","sync.log")} to whoever gave you Canopy.`)),m.status==="queued");g++){n(" Another update is already running; waiting for it to finish...");for(let x=0;x<1200&&xe.existsSync(te(f).lock);x++)await new Promise(S=>setTimeout(S,500))}m.status==="queued"&&Te(1,"Another Canopy update is still running. Wait for it to finish and run canopy again."),t?.endProgress();let y=((Date.now()-h)/1e3).toFixed(1);return n(m.status==="no-changes"?` Nothing changed since version ${m.version.version} (${y} s).`:` Saved version ${m.version.version} (${y} s).`),m}function l(f,u){let h=Et(f),p=u.coverage??Rp(h)?.coverage,m=Ap(h),y=u.version.counts??{};if(n(`
100
+ Your map`),n(` services: ${m.length}${m.length?" ("+m.map(g=>g.id??g.name).slice(0,8).join(", ")+(m.length>8?", ...":"")+")":""}`),n(` workflows: ${y.workflows??"?"}${y.physicalWorkflows!==void 0?` (${y.physicalWorkflows} traced from real code, ${y.workflows-y.physicalWorkflows} guessed)`:""}`),p){let g=p.analyzed?Math.round(p.inService/p.analyzed*100):0;n(` files inside a service: ${p.inService} of ${p.analyzed} (${g}%)`),n(` files with parse errors: ${p.parseErrors}${p.parseErrors?" ("+p.parseErrorFiles.slice(0,3).join(", ")+(p.parseErrorFiles.length>3?", ...":"")+")":""}`),p.notAnalyzedTotal&&n(` not read yet: ${p.notAnalyzedTotal} files in languages Canopy does not support (${Object.entries(p.notAnalyzed).map(([x,S])=>`${S} ${x}`).join(", ")})`)}m.length||n(" The map is empty: Canopy found no entry points (routes, listeners, a main file) it recognises in this project."),n("")}function d(){n("Next time just run `canopy`."),n(Op(o))}}function Mp(){return!!fe(Ip.tmpdir(),["--version"])}import _o from"node:fs";import ll from"node:os";import xt from"node:path";import{spawn as Hp}from"node:child_process";var Xr="CANOPY_CHILD",Dp=2048,Bp=8192,dl=1024*1024;function Up({env:e=process.env,nodeOptions:t=e.NODE_OPTIONS??"",totalmem:n=ll.totalmem()}={}){let r=Number(e.CANOPY_MAX_MEMORY_MB);if(Number.isFinite(r)&&r>=256)return{mb:Math.floor(r),source:"CANOPY_MAX_MEMORY_MB"};let o=/--max-old-space-size[= ](\d+)/.exec(t);return o?{mb:null,userMb:Number(o[1]),source:"NODE_OPTIONS"}:{mb:Math.max(Dp,Math.min(Bp,Math.floor(n*.75/dl))),source:"75% of this computer's memory"}}var zp=new Set(["version","help","update","hook","install-hook","uninstall-hook","doctor","history","diff","open"]);function Zr(e){if(e.some(r=>r==="--version"||r==="--help"||r==="-v"||r==="-h"))return!1;let n=e.filter(r=>!r.startsWith("-"))[0];return n===void 0?!0:zp.has(n)?!1:n==="sync"?!e.includes("--background"):_o.existsSync(xt.resolve(n))||/^[.~]|[\\/]/.test(n)}function $o(e,t=process.cwd()){let n=e.filter(r=>!r.startsWith("-"));return n[0]==="sync"?xt.resolve(n[1]??t):xt.resolve(n[0]??t)}var Wp=/heap out of memory|Allocation failed|JavaScript heap|FatalProcessOutOfMemory|out of memory/i;function Gp({code:e,signal:t,stderrTail:n="",platform:r=process.platform}){if(Wp.test(n))return{kind:"memory",why:"Node reported that it ran out of memory"};if(t==="SIGINT"||t==="SIGTERM"||t==="SIGHUP")return null;if(t==="SIGABRT")return{kind:"memory",why:"the process aborted (usually out of memory)"};if(t==="SIGKILL")return{kind:"killed",why:"the system stopped the process (usually because the computer ran out of memory)"};if(t==="SIGSEGV"||t==="SIGBUS")return{kind:"crash",why:"the process crashed"};if(e==null)return t?{kind:"crash",why:`the process ended on signal ${t}`}:{kind:"crash",why:"the process ended without an exit code"};let o=e>>>0;if(r==="win32"){if(o>=3221225472)return{kind:o===3221226505?"memory":"crash",why:`Windows reported error 0x${o.toString(16).toUpperCase()} (a fatal stop, usually out of memory)`};if(o>255)return{kind:"crash",why:`the process ended with the unusual code ${o}`}}return e===134?{kind:"memory",why:"the process aborted (exit code 134, usually out of memory)"}:e===137?{kind:"killed",why:"the system stopped the process (exit code 137, usually out of memory)"}:e===139||e===135?{kind:"crash",why:`the process crashed (exit code ${e})`}:null}function qp(e,{projectRoot:t,stage:n,memory:r}){let o=[],s=e.kind==="memory"?"Canopy ran out of memory":e.kind==="killed"?"Canopy was stopped by the system, most likely because the computer ran out of memory":"Canopy stopped unexpectedly";return o.push(`${s}${n?` while it was working on: ${n}`:""}.`),o.push(` (${e.why}.)`),o.push(""),o.push("What to try next:"),o.push(" 1. Analyse one part of the project at a time: canopy <folder of a package or app>"),o.push(` 2. Give Canopy more memory: set CANOPY_MAX_MEMORY_MB (it used ${r?.mb??r?.userMb??"the default"} MB), for example CANOPY_MAX_MEMORY_MB=${Math.min(16384,Math.max(4096,(r?.mb??4096)*2))} canopy`),o.push(" 3. Close other programs, then run it again: the files already read are remembered, so the second run is faster."),t&&o.push("",`Details for a bug report (no code or secrets): ${xt.join(".canopy","last-error.txt")} in the project folder.`),o.join(`
101
+ `)}function Qr(e,{version:t,stage:n,code:r,signal:o,memory:s,totalmem:i=ll.totalmem()}){try{let a=xt.join(e,".canopy");_o.mkdirSync(a,{recursive:!0});let c=[`time: ${new Date().toISOString()}`,`engine version: ${t}`,`stage: ${n??"unknown"}`,`exit: ${o?"signal "+o:r}`,`memory ceiling: ${s?.mb??"left to NODE_OPTIONS"+(s?.userMb?" ("+s.userMb+" MB)":"")} MB (${s?.source??"?"}); computer memory ${Math.round(i/dl)} MB`,""].join(`
102
+ `);return _o.writeFileSync(xt.join(a,"last-error.txt"),c),xt.join(a,"last-error.txt")}catch{return null}}function fl(e){let{args:t,scriptPath:n,version:r="?",env:o=process.env,projectRoot:s=$o(t),execPath:i=process.execPath,execArgv:a=process.execArgv,spawnFn:c=Hp,platform:l=process.platform,err:d=process.stderr,onChild:f=null}=e,u=e.memory??Up({env:o}),h=[...u.mb?[`--max-old-space-size=${u.mb}`]:[],...a.filter(p=>!p.startsWith("--max-old-space-size")),n,...t];return new Promise(p=>{let m="",y=c(i,h,{env:{...o,[Xr]:"1"},stdio:["inherit","inherit","pipe"],windowsHide:!1});f?.(y),y.stderr?.on("data",w=>{try{d.write(w)}catch{}m=(m+w.toString("utf8")).slice(-4e3)});let g=w=>()=>{try{y.kill(w)}catch{}},x=g("SIGTERM");process.on("SIGTERM",x);let S=process.stdin.isTTY?()=>{}:g("SIGINT");process.on("SIGINT",S);let k=!1,v=(w,b)=>{if(k)return;k=!0,process.off("SIGTERM",x),process.off("SIGINT",S);let N=Gp({code:w,signal:b,stderrTail:m,platform:l});if(!N){p(w??(b?1:0));return}let $=qa(s);Qr(s,{version:r,stage:$,code:w,signal:b,memory:u});try{_o.rmSync(xt.join(s,".canopy","last-stage.txt"),{force:!0})}catch{}try{d.write(`
103
+ `+qp(N,{projectRoot:s,stage:$,memory:u})+`
104
+ `)}catch{}p(1)};y.on("error",w=>{try{d.write(`Canopy could not start its worker process: ${String(w.message).split(`
105
+ `)[0]}
106
+ `)}catch{}v(1,null)}),y.on("close",(w,b)=>v(w,b))})}var at=JSON.parse(es.readFileSync(vn.join(le,"package.json"),"utf8")),Jp={"-y":"--yes","-h":"--help","-v":"--version"},ul=process.argv.slice(2).map(e=>Jp[e]??e),ae=Object.fromEntries(ul.filter(e=>e.startsWith("--")).map(e=>{let[t,n]=e.slice(2).split("=");return[t,n??!0]})),Oe=ul.filter(e=>!e.startsWith("--")),Ue=Oe.shift(),Vp=e=>/^v?\d+$/.test(e??""),Tt=()=>vn.resolve(Oe[0]&&!Vp(Oe[0])?Oe.shift():process.cwd()),pl=`canopy ${at.version} - a map of what your JavaScript / TypeScript code does
66
107
 
67
108
  usage: canopy [path] [-y] [--no-open] do everything in order: check this computer, look at the project, prepare .canopy/,
68
109
  offer the commit hook, build the map, open it in your browser (default path: current folder)
@@ -77,11 +118,24 @@ usage: canopy [path] [-y] [--no-open] do everything in order: check this com
77
118
  update [--check] look up the newest version on npm (the only command that uses the network); "update" installs it with npm
78
119
  --version, --help
79
120
 
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)
121
+ options for the one-command path: -y / --yes (do not ask; install the hook), --no-hook (do not install the hook, do not ask),
122
+ --no-open (build the map but do not start the viewer), --port=N, --for=SECONDS (stop the viewer by itself after that time),
123
+ --full (ignore everything remembered and analyse from scratch), --quiet (only problems and the address), --no-color (also: NO_COLOR=1)
124
+ Memory: a whole analysis gets about 75% of this computer's memory (2-8 GB). CANOPY_MAX_MEMORY_MB=<number> sets it; CANOPY_DEBUG_MEM=1 prints the memory at each stage.
82
125
  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}
126
+ Node >= 18 required. Output lives in <path>/.canopy/ (kept out of git automatically).`;async function Yp(){let e=Tt(),t=Et(e);es.existsSync(vn.join(t,"workflows.js"))||(console.error(`no map yet for ${e}
127
+ fix: canopy sync "${e}"`),process.exit(1));let n=vo();n&&(console.error(n),process.exit(1));let r=await So(e,at.version);if(!r.ok&&r.running){console.log(`canopy map for ${e}
128
+ ${r.running.url}
129
+ already running for this project (started ${r.running.startedAt??"earlier"}); nothing else was started`);return}r.ok||(console.error("another canopy is just starting for this project; wait a few seconds and try again"),process.exit(1));let{server:o,url:s,port:i}=await xo(t,ae.port?Number(ae.port):0,{repoRoot:e});if(ko(e,{port:i,version:at.version}),console.log(`canopy map for ${e}
130
+ ${s}`),ae.for){console.log(`serving for ${Number(ae.for)} s`),await new Promise(a=>setTimeout(a,Number(ae.for)*1e3)),o.close();return}console.log("press Ctrl+C to stop"),await new Promise(()=>{})}function Kp(){let e=Tt();process.exit(tl(wo(e),e,at.version)?1:0)}var xn={async sync(){let e=Tt();if(ae.background){let n=Pc(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=ae.keep?Number(ae.keep):fn;await mo(e,{keep:t,full:!!ae.full})},open:Yp,async doctor(){Kp()},async update(){process.exit(await Oc({check:!!ae.check,version:at.version}))},async diff(){let e=Tt(),t=Ee(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/,"")),c=t.versions.find(l=>l.version===a);if(!c)throw new Error(`no such version: ${i} (have ${t.versions.map(l=>"v"+l.version).join(", ")})`);return c},r=Oe[1]!==void 0?n(Oe[1]):t.versions[t.versions.length-1],o=Oe[0]!==void 0?n(Oe[0]):t.versions[t.versions.indexOf(r)-1];if(!o)throw new Error("no earlier version to compare against");let s=pn(ht(e,o),ht(e,r));console.log(ae.json?kc(s):Nc(s,r,o))},async"install-hook"(){let e=Tt(),t=gn(e);bo(e,{hook:void 0}),console.log("installed canopy block in: "+t.join(", "))},async"uninstall-hook"(){let e=Ec(Tt());console.log(e.length?"removed canopy block from: "+e.join(", "):"no canopy hook block found")},async hook(){let e=Oe.shift();if(e==="install")return xn["install-hook"]();if(e==="uninstall")return xn["uninstall-hook"]();console.error("usage: canopy hook install|uninstall [path]"),process.exit(2)},async history(){let e=Tt(),t=Ee(e);if(!t.versions.length)return console.log("no versions yet - run: canopy sync");for(let n of t.versions)console.log(`v${n.version} ${n.fingerprint.slice(0,7)} ${n.createdAt} ${n.headSha?n.headSha.slice(0,7):"-------"}${n.dirty?"*":" "} ${n.headMessage?JSON.stringify(n.headMessage):""} nodes ${n.counts.nodes} edges ${n.counts.edges} workflows ${n.counts.workflows} ${(n.bytes/1024).toFixed(0)} KB${n.gzip?" gz":""}`)}};Number(process.versions.node.split(".")[0])<18&&(console.error(`Canopy needs Node 18 or newer, and this is Node ${process.versions.node}.
131
+ What to try next: install the current LTS from https://nodejs.org (or run: nvm install --lts), open a new terminal, and run canopy again.`),process.exit(1));process.env[Xr]!=="1"&&process.env.CANOPY_NO_RESPAWN!=="1"&&Zr(process.argv.slice(2))&&process.exit(await fl({args:process.argv.slice(2),scriptPath:process.argv[1],version:at.version}));var ml=e=>{let t=String(e?.message??e).split(`
132
+ `)[0].slice(0,200),n=$o(process.argv.slice(2));Qr(n,{version:at.version,stage:to(),code:1,memory:{mb:null,source:"this run"}}),console.error(`Canopy stopped unexpectedly${to()?" while it was working on: "+to():""}.
133
+ (${t})
134
+
135
+ What to try next:
136
+ 1. canopy doctor checks Node, the grammars and write access
137
+ 2. canopy <folder> try one package or app at a time
138
+ 3. run it again: the files already read are remembered
139
+ Details for a bug report (no code or secrets): .canopy/last-error.txt in the project folder.`),process.exit(1)};process.on("uncaughtException",ml);process.on("unhandledRejection",ml);Zr(process.argv.slice(2))&&Wa($o(process.argv.slice(2)));process.on("exit",()=>Ga());(ae.version||Ue==="version")&&(console.log(at.version),process.exit(0));(ae.help||Ue==="help")&&(console.log(pl),process.exit(0));if(Ue===void 0||!xn[Ue]&&(es.existsSync(vn.resolve(Ue))||/^[.~]|[\\/]/.test(Ue))){Ue!==void 0&&Oe.unshift(Ue);let e=await cl({target:Oe[0]?vn.resolve(Oe[0]):process.cwd(),yes:!!ae.yes,noOpen:!!ae["no-open"],quiet:!!ae.quiet,noColor:!!ae["no-color"],noHook:!!ae["no-hook"],full:!!ae.full,port:ae.port?Number(ae.port):void 0,forSeconds:ae.for?Number(ae.for):void 0,pkg:at});process.exit(e)}xn[Ue]||(console.error(`unknown command: ${Ue}
86
140
 
87
- ${ja}`),process.exit(2));Xt[Ee]().catch(e=>{console.error(e.stack||e.message),process.exit(1)});
141
+ ${pl}`),process.exit(2));xn[Ue]().catch(e=>{console.error(e.stack||e.message),process.exit(1)});