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