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