canopy-engine 0.1.3 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -7
- package/dist/canopy.js +106 -63
- package/package.json +5 -2
- package/ui-react/dist/bundle.css +1 -1
- package/ui-react/dist/bundle.js +25 -25
package/dist/canopy.js
CHANGED
|
@@ -3,77 +3,107 @@ import{fileURLToPath as __cf,pathToFileURL as __cu}from"node:url";import{dirname
|
|
|
3
3
|
const require=__cr(import.meta.url);
|
|
4
4
|
globalThis.__canopyBundle=__cf(import.meta.url);
|
|
5
5
|
globalThis.__canopyUrl=(r)=>__cu(__cj(__cd(__cd(globalThis.__canopyBundle)),r)).href;
|
|
6
|
-
var
|
|
7
|
-
`),
|
|
6
|
+
var kl=Object.create;var jo=Object.defineProperty;var Nl=Object.getOwnPropertyDescriptor;var bl=Object.getOwnPropertyNames;var _l=Object.getPrototypeOf,$l=Object.prototype.hasOwnProperty;var kt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Il=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},jl=(e,t)=>{for(var n in t)jo(e,n,{get:t[n],enumerable:!0})},Cl=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of bl(t))!$l.call(e,o)&&o!==n&&jo(e,o,{get:()=>t[o],enumerable:!(r=Nl(t,o))||r.enumerable});return e};var Fl=(e,t,n)=>(n=e!=null?kl(_l(e)):{},Cl(t||!e||!e.__esModule?jo(n,"default",{value:e,enumerable:!0}):n,e));var us=Il((Qp,_n)=>{function is(e){return Array.isArray(e)?e:[e]}var El=void 0,Fo="",rs=" ",Co="\\",Pl=/^\s+$/,Ll=/(?:[^\\]|^)\\$/,Tl=/^\\!/,Rl=/^\\#/,Al=/\r?\n/g,Ol=/^\.{0,2}\/|^\.{1,2}$/,Ml=/\/$/,Ot="/",as="node-ignore";typeof Symbol<"u"&&(as=Symbol.for("node-ignore"));var cs=as,Mt=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),Hl=/([0-z])-([0-z])/g,ls=()=>!1,Dl=e=>e.replace(Hl,(t,n,r)=>n.charCodeAt(0)<=r.charCodeAt(0)?t:Fo),Bl=e=>e.startsWith("!")||e.startsWith("\\^")?`^${e.slice(e[0]==="!"?1:2)}`:e,Ul=e=>{let{length:t}=e;return e.slice(0,t-t%2)},zl=[[/^\uFEFF/,()=>Fo],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf("\\")===0?rs:Fo)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+rs}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*(?:\\\*\\\*\\\/)+/,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?"(?:\\/[^\\/]+)*":"\\/.+"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>{let r=n.replace(/\\\*/g,"[^\\/]*");return t+r}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Co],[/\\\\/g,()=>Co],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,o)=>t===Co?`\\[${n}${Ul(r)}${o}`:o==="]"&&r.length%2===0?`[${Bl(Dl(n))}${r}]`:"[]"],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],Wl=/(^|\\\/)?\\\*$/,tn="regex",Nn="checkRegex",ss="_",Gl={[tn](e,t){return`${t?`${t}[^/]+`:"[^/]*"}(?=$|\\/$)`},[Nn](e,t){return`${t?`${t}[^/]*`:"[^/]*"}(?=$|\\/$)`}},ql=e=>zl.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),bn=e=>typeof e=="string",Jl=e=>e&&bn(e)&&!Pl.test(e)&&!Ll.test(e)&&e.indexOf("#")!==0,Vl=e=>e.split(Al).filter(Boolean),Eo=class{constructor(t,n,r,o,s,i){this.pattern=t,this.mark=n,this.negative=s,Mt(this,"body",r),Mt(this,"ignoreCase",o),Mt(this,"regexPrefix",i)}get regex(){let t=ss+tn;return this[t]?this[t]:this._make(tn,t)}get checkRegex(){let t=ss+Nn;return this[t]?this[t]:this._make(Nn,t)}_make(t,n){let r=this.regexPrefix.replace(Wl,Gl[t]),o=this.ignoreCase?new RegExp(r,"i"):new RegExp(r);return Mt(this,n,o)}},Yl=({pattern:e,mark:t},n)=>{let r=!1,o=e;o.indexOf("!")===0&&(r=!0,o=o.substr(1)),o=o.replace(Tl,"!").replace(Rl,"#");let s=ql(o);return new Eo(e,t,o,n,r,s)},Po=class{constructor(t){this._ignoreCase=t,this._rules=[]}_add(t){if(t&&t[cs]){this._rules=this._rules.concat(t._rules._rules),this._added=!0;return}if(bn(t)&&(t={pattern:t}),Jl(t.pattern)){let n=Yl(t,this._ignoreCase);this._added=!0,this._rules.push(n)}}add(t){return this._added=!1,is(bn(t)?Vl(t):t).forEach(this._add,this),this._added}test(t,n,r){let o=!1,s=!1,i;this._rules.forEach(c=>{let{negative:l}=c;s===l&&o!==s||l&&!o&&!s&&!n||!c[r].test(t)||(o=!l,s=l,i=l?El:c)});let a={ignored:o,unignored:s};return i&&(a.rule=i),a}},Kl=(e,t)=>{throw new t(e)},Ze=(e,t,n)=>bn(e)?e?Ze.isNotRelative(e)?n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):!0:n("path must not be empty",TypeError):n(`path must be a string, but got \`${t}\``,TypeError),ds=e=>Ol.test(e);Ze.isNotRelative=ds;Ze.convert=e=>e;var Lo=class{constructor({ignorecase:t=!0,ignoreCase:n=t,allowRelativePaths:r=!1}={}){Mt(this,cs,!0),this._rules=new Po(n),this._strictPathCheck=!r,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(t){return this._rules.add(t)&&this._initCache(),this}addPattern(t){return this.add(t)}_test(t,n,r,o){let s=t&&Ze.convert(t);return Ze(s,t,this._strictPathCheck?Kl:ls),this._t(s,n,r,o)}checkIgnore(t){if(!Ml.test(t))return this.test(t);let n=t.split(Ot).filter(Boolean);if(n.pop(),n.length){let r=this._t(n.join(Ot)+Ot,this._testCache,!0,n);if(r.ignored)return r}return this._rules.test(t,!1,Nn)}_t(t,n,r,o){if(t in n)return n[t];if(o||(o=t.split(Ot).filter(Boolean)),o.pop(),!o.length)return n[t]=this._rules.test(t,r,tn);let s=this._t(o.join(Ot)+Ot,n,r,o);return n[t]=s.ignored?s:this._rules.test(t,r,tn)}ignores(t){return this._test(t,this._ignoreCache,!1).ignored}createFilter(){return t=>!this.ignores(t)}filter(t){return is(t).filter(this.createFilter())}test(t){return this._test(t,this._testCache,!0)}},To=e=>new Lo(e),Xl=e=>Ze(e&&Ze.convert(e),e,ls),fs=()=>{let e=n=>/^\\\\\?\\/.test(n)||/["<>|\u0000-\u001F]+/u.test(n)?n:n.replace(/\\/g,"/");Ze.convert=e;let t=/^[a-z]:\//i;Ze.isNotRelative=n=>t.test(n)||ds(n)};typeof process<"u"&&process.platform==="win32"&&fs();_n.exports=To;To.default=To;_n.exports.isPathValid=Xl;Mt(_n.exports,Symbol.for("setupWindows"),fs)});import Ss from"node:fs";import ft from"node:path";import{fileURLToPath as cd}from"node:url";function He(e){let t=ft.join(le,"vendor",e);if(Dt()&&Ss.existsSync(t))return t;for(let n=le;;n=ft.dirname(n)){let r=ft.join(n,"node_modules",e);if(Ss.existsSync(r))return r;if(ft.dirname(n)===n)break}return ft.join(le,"node_modules",e)}var le,Dt,We=kt(()=>{le=ft.join(ft.dirname(cd(globalThis.__canopyUrl("src/utils/pkgPath.js"))),"..","..");Dt=()=>le.split(ft.sep).includes("node_modules")});import Jt from"node:fs";import Ye from"node:path";import cu from"node:crypto";import{fileURLToPath as lu}from"node:url";function xr(e){let t=[];for(let n of Jt.readdirSync(e,{withFileTypes:!0}).sort((r,o)=>r.name<o.name?-1:1)){let r=Ye.join(e,n.name);n.isDirectory()?t.push(...xr(r)):/\.(js|scm)$/.test(n.name)&&t.push(r)}return t}function Vt(){if(vr)return vr;let e=cu.createHash("sha256");if(!Jt.existsSync(yr)&&globalThis.__canopyBundle){let t=globalThis.__canopyBundle;e.update("bundle\0").update(Jt.readFileSync(t));let n=Ye.join(Ye.dirname(t),"queries");if(Jt.existsSync(n))for(let r of xr(n))e.update(Ye.relative(n,r).split(Ye.sep).join("/")).update("\0").update(Qa(r)).update("\0")}else for(let t of xr(yr))e.update(Ye.relative(yr,t).split(Ye.sep).join("/")).update("\0").update(Qa(t)).update("\0");for(let t of["web-tree-sitter","tree-sitter-javascript","tree-sitter-typescript","tree-sitter-html"])try{e.update(t+"@"+JSON.parse(Jt.readFileSync(Ye.join(He(t),"package.json"),"utf8")).version)}catch{e.update(t+"@?")}return vr=e.digest("hex").slice(0,16)}var no,yr,Qa,vr,wr=kt(()=>{We();no=1,yr=Ye.join(Ye.dirname(lu(globalThis.__canopyUrl("src/history/engineVersion.js"))),"..");Qa=e=>Jt.readFileSync(e).toString("utf8").replace(/\r\n/g,`
|
|
7
|
+
`),vr=null});import Q from"node:fs";import ke from"node:path";import nc from"node:zlib";import du from"node:crypto";import{execFileSync as fu}from"node:child_process";function fe(e,t){try{return fu("git",["-C",ke.resolve(e),...t],{stdio:["ignore","pipe","ignore"],encoding:"utf8"}).trim()}catch{return null}}function ro(e){let t=fe(e,["rev-parse","--git-path","info/exclude"]);if(!t)return!1;let n=ke.resolve(e,t);Q.mkdirSync(ke.dirname(n),{recursive:!0});let r=Q.existsSync(n)?Q.readFileSync(n,"utf8"):"";return r.split(/\r?\n/).some(o=>o.trim()===".canopy/")||Q.appendFileSync(n,(r&&!r.endsWith(`
|
|
8
8
|
`)?`
|
|
9
9
|
`:"")+`.canopy/
|
|
10
|
-
`),!0}function
|
|
11
|
-
`).some(w=>w.trim()&&!/\.canopy(\/|$)/.test(w)),f=r?a.versions.pop():null,u={version:f?f.version:a.nextVersion,fingerprint:n.fingerprint,createdAt:new Date().toISOString(),headSha:Ie(e,["rev-parse","HEAD"]),headMessage:Ie(e,["log","-1","--format=%s"]),dirty:m,counts:s,file:c,gzip:l,bytes:Z.statSync(d).size,engineVersion:Dn(),outputFormat:Hn};for(a.versions.push(u),f||a.nextVersion++;a.versions.length>o;)a.versions.shift();let p=Kd(),h=w=>{try{return Z.statSync(ke.join(i.history,w.file)).size}catch{return w.bytes??0}},v=a.versions.reduce((w,S)=>w+h(S),0);for(;v>p&&a.versions.length>Jd;)v-=h(a.versions.shift());let g=new Set(a.versions.map(w=>w.file));for(let w of Z.readdirSync(i.history))/\.json(\.gz)?$/.test(w)&&w!=="index.json"&&!g.has(w)&&Z.rmSync(ke.join(i.history,w),{force:!0});return Xd(e,a),u}function ia(e){let t=ae(e);Z.mkdirSync(t.root,{recursive:!0});for(let n=0;n<2;n++)try{let s=Z.openSync(t.lock,"wx");return Z.writeSync(s,JSON.stringify({pid:process.pid,startedAt:Date.now()})),Z.closeSync(s),!0}catch(s){if(s.code!=="EEXIST")throw s;let o=1/0;try{o=Date.now()-Z.statSync(t.lock).mtimeMs}catch{continue}if(o<Vd)return!1;Z.rmSync(t.lock,{force:!0})}return!1}var Gd,Jd,Kd,Vd,Vt,ae,aa,ca,la,yt=_t(()=>{Ko();Gd=200,Jd=2,Kd=()=>{let e=Number(process.env.CANOPY_SNAPSHOT_MAX_MB);return(Number.isFinite(e)&&e>0?e:Gd)*1024*1024},Vd=600*1e3,Vt=50,ae=e=>{let t=ke.join(ke.resolve(e),".canopy");return{root:t,history:ke.join(t,"history"),index:ke.join(t,"history","index.json"),lock:ke.join(t,"sync.lock"),pending:ke.join(t,"sync.pending"),log:ke.join(t,"sync.log")}};aa=e=>Z.rmSync(ae(e).lock,{force:!0}),ca=e=>{let t=ae(e);Z.mkdirSync(t.root,{recursive:!0}),Z.writeFileSync(t.pending,String(Date.now()))},la=e=>{let t=ae(e);return Z.existsSync(t.pending)?(Z.rmSync(t.pending,{force:!0}),!0):!1}});function da(e){let t=new Map;for(let n of e.nodes){let s=t.get(n.id);s?s.services.push(n.service):t.set(n.id,{id:n.id,services:[n.service],kind:n.kind,name:n.name,filePath:n.filePath,bodyHash:n.bodyHash})}for(let n of t.values())n.services.sort();return t}function Zd(e){return t=>{if(t==null)return t;if(e.has(t))return e.get(t);for(let[n,s]of e)if(t.startsWith(n+" | "))return s+t.slice(n.length);return t}}function Xo(e,t){let n=a=>a.reduce((l,c)=>l.set(c,(l.get(c)??0)+1),new Map),s=n(e),o=n(t),r=[],i=[];for(let[a,l]of o)for(let c=0;c<l-(s.get(a)??0);c++)r.push(a);for(let[a,l]of s)for(let c=0;c<l-(o.get(a)??0);c++)i.push(a);return{added:r.sort(),removed:i.sort()}}function Wn(e,t){let n=da(e),s=da(t),o=[...s.values()].filter(_=>!n.has(_.id)),r=[...n.values()].filter(_=>!s.has(_.id)),i=[];for(let[_,E]of s){let C=n.get(_);C&&C.bodyHash!==E.bodyHash&&i.push({...Vo(E),from:C.bodyHash,to:E.bodyHash})}let a=[],l=new Map,c=_=>[_.kind,_.name,_.bodyHash].join("\0"),d=new Map;for(let _ of Ne(o,E=>E.id)){let E=c(_);d.has(E)||d.set(E,[]),d.get(E).push(_)}let m=[],f=new Set;for(let _ of Ne(r,E=>E.id)){let C=(d.get(c(_))??[]).find(B=>!f.has(B.id)&&B.filePath!==_.filePath&&B.id.split("::").pop()===_.id.split("::").pop());C?(f.add(C.id),a.push({kind:_.kind,name:_.name,services:C.services,fromId:_.id,toId:C.id,fromPath:_.filePath,toPath:C.filePath}),l.set(_.id,C.id)):m.push(_)}o=Ne(o.filter(_=>!f.has(_.id)),_=>_.id),r=Ne(m,_=>_.id);let u=Zd(l),p=_=>_.service+"\0"+_.id,h=new Map(e.edges.map(_=>[p({service:_.service,id:u(_.id)}),{..._,id:u(_.id),from:u(_.from),resolvedTo:u(_.resolvedTo)}])),v=new Map(t.edges.map(_=>[p(_),_])),g=_=>({id:_.id,service:_.service,from:_.from,callKind:_.callKind,calleeNameRaw:_.calleeNameRaw,resolvedTo:_.resolvedTo}),w=[],S=[],k=[];for(let[_,E]of v){let C=h.get(_);C?C.resolvedTo!==E.resolvedTo&&k.push({id:E.id,service:E.service,from:E.from,calleeNameRaw:E.calleeNameRaw,fromTarget:C.resolvedTo,toTarget:E.resolvedTo}):w.push(g(E))}for(let[_,E]of h)v.has(_)||S.push(g(E));let y=_=>_.service+"\0"+_.id,x=_=>({..._,id:_.id.replace(_.entry??"\0",u(_.entry)),entry:u(_.entry),steps:_.steps.map(u)}),b=new Map(e.workflows.map(_=>{let E=x(_);return[E.id,E]})),N=new Map(t.workflows.map(_=>[_.id,_])),$={added:[],removed:[],changed:[]},F={added:[],removed:[],changed:[]},H=_=>({id:_.id,service:_.service,tier:_.tier,steps:_.steps.length});for(let[_,E]of N){let C=b.get(_);if(!C){(E.tier==="physical"?$:F).added.push(H(E));continue}let B=Xo(C.steps,E.steps),be=!B.added.length&&!B.removed.length&&C.steps.join(`
|
|
12
|
-
`)!==
|
|
13
|
-
`),
|
|
14
|
-
`)}var
|
|
15
|
-
`,o),a=(i<0?
|
|
16
|
-
`)}De();import{Parser as go,Language as Cs}from"web-tree-sitter";import pn from"node:path";import{fileURLToPath as Jc}from"node:url";var Ru=pn.dirname(Jc(globalThis.__canopyUrl("src/stage2_parse/initParser.js")));var yo=new WeakMap,Ut=e=>yo.get(e)??"javascript",st=e=>Ut(e)!=="javascript";function xo(e){let t=pn.extname(e);return t===".tsx"?"tsx":t===".ts"||t===".mts"||t===".cts"?"typescript":"javascript"}var Kc={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm"};async function Es(e,t){for(let n of new Set(t.map(xo))){if(e.grammars.has(n))continue;let s=pn.join(Ae("tree-sitter-typescript"),Kc[n]),o=await Cs.load(s);yo.set(o,n);let r=new go;r.setLanguage(o),e.grammars.set(n,{parser:r,language:o})}return e}async function Ps(){await go.init();let e=new go,t=pn.join(Ae("tree-sitter-javascript"),"tree-sitter-javascript.wasm"),n=await Cs.load(t);return e.setLanguage(n),yo.set(n,"javascript"),{parser:e,language:n,grammars:new Map([["javascript",{parser:e,language:n}]])}}import Vc from"node:fs";function As(e,t){let n=Vc.readFileSync(t,"utf-8"),s=e.parse(n);if(vo(s)||n.includes("\0")){let o=n,r=Rs(s);for(let i of Xc){let a=i.apply(o);if(a===o)continue;let l=e.parse(a),c=Rs(l);(c<r||i.always)&&(o=a,s=l,r=c)}o!==n&&(s.canopyOriginalSource=n)}return{tree:s,source:n,filePath:t}}var Os=e=>e.replace(/[^\n]/g," "),Ls=e=>"any"+Os(e).slice(3),Ts=/(?<![&])&(?![&=])/g,Xc=[{name:"NUL byte",always:!0,apply:e=>e.replace(/\0/g," ")},{name:"export type * from",apply:e=>e.replace(/\bexport\s+type\s+\*\s*(?:as\s+[\w$]+\s+)?from\s*(["'])[^"'\n]*\1\s*;?/g,Os)},{name:"typeof import()",apply:e=>e.replace(/typeof\s+import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)*/g,Ls)},{name:"import().Type",apply:e=>e.replace(/(?<=[:<,|&?]\s*|\breadonly\s+|\bkeyof\s+|\bextends\s+|\bas\s+)import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)+(?!\s*\()/g,Ls)},{name:"generic call signature after a member",apply:e=>e.replace(/(?<=\n[ \t]*)[ ](?=<\s*[A-Za-z_$][\w$]*\s*(?:extends\b|=|,|>\s*\())/g,";")},{name:"& in JSX text",apply:e=>e.replace(/>[^<>{}"'`]*&[^<>{}"'`]*</g,t=>t.replace(Ts,"+"))},{name:"& in JSX attribute",apply:e=>e.replace(/(\s[\w:-]+=)"([^"\n]*)"/g,(t,n,s)=>n+'"'+s.replace(Ts,"+")+'"')}];function Rs(e){let t=0;return(function n(s){if(s.type==="ERROR"){t++;return}for(let o=0;o<s.childCount;o++)n(s.child(o))})(e.rootNode),t}function vo(e){let t=!1;function n(s){if(s.type==="ERROR"){t=!0;return}for(let o=0;o<s.childCount;o++)n(s.child(o))}return n(e.rootNode),t}import wo from"node:fs";import zt from"node:path";import{fileURLToPath as Yc}from"node:url";import{Query as Zc}from"web-tree-sitter";var Ms=zt.dirname(Yc(globalThis.__canopyUrl("src/utils/loadQuery.js"))),Hs=new WeakMap;function oe(e,t){let n=Hs.get(e);if(n||Hs.set(e,n=new Map),n.has(t))return n.get(t);let s=zt.join(Ms,"..","stage2_parse","queries"),o=wo.existsSync(s)?s:zt.join(Ms,"..","..","dist","queries"),r=Ut(e),l=(r==="javascript"?[]:r==="tsx"?["tsx","typescript"]:[r]).map(m=>zt.join(o,m,t)).find(m=>wo.existsSync(m))??zt.join(o,t),c=wo.readFileSync(l,"utf-8"),d=new Zc(e,c);return n.set(t,d),d}var Ds="javascript",Bs=e=>{Ds=e};var mn=()=>Ds!=="javascript";var Qc=new Set(["non_null_expression","as_expression","satisfies_expression","type_assertion"]);function le(e){for(;e;)if(Qc.has(e.type))e=e.type==="type_assertion"?e.namedChild(e.namedChildCount-1):e.namedChild(0);else if(e.type==="parenthesized_expression"&&e.namedChildCount===1){let t=le(e.namedChild(0));if(t===e.namedChild(0))break;e=t}else break;return e}function el(e){let t=e;for(;t;){t=le(t);for(let n=0;n<t.childCount;n++)if(t.child(n).type==="optional_chain")return!0;if(t.type==="member_expression"||t.type==="subscript_expression")t=t.childForFieldName("object");else if(t.type==="call_expression")t=t.childForFieldName("function");else break}return!1}function rt(e){let t=e.childForFieldName("function"),n=e.childForFieldName("arguments");if(!t)return{kind:"callOfCall",oldShape:!1,nameNode:e};let s=t.type==="identifier",o=t.type==="member_expression"?t.childForFieldName("property"):null,r=t.type==="member_expression"?le(t.childForFieldName("object")):null,i=s||r?.type==="identifier"&&o?.type==="property_identifier",a=o??t;if(mn()&&e.parent?.type==="decorator")return{kind:"decorator",oldShape:i,nameNode:a};if(n&&n.type==="template_string")return{kind:"taggedTemplate",oldShape:i,nameNode:a};if(el(e))return{kind:"optionalCall",oldShape:i,nameNode:a};if(s)return{kind:"call",oldShape:i,nameNode:a};if(t.type==="subscript_expression")return{kind:"computed",oldShape:!1,nameNode:t};if(t.type==="member_expression")return r.type==="super"?{kind:"super",oldShape:!1,nameNode:a}:r.type==="this"?{kind:"thisCall",oldShape:!1,nameNode:a}:i?{kind:"methodCall",oldShape:!0,nameNode:a}:{kind:"chainedCall",oldShape:!1,nameNode:a};if(t.type==="import")return{kind:"dynamicImport",oldShape:!1,nameNode:t};if(t.type==="super")return{kind:"super",oldShape:!1,nameNode:t};let l=t;for(;l.type==="parenthesized_expression"&&l.namedChildCount===1;)l=l.namedChild(0);return l.type==="arrow_function"||l.type==="function_expression"||l.type==="function"||l.type==="generator_function"?{kind:"iife",oldShape:!1,nameNode:t}:{kind:"callOfCall",oldShape:!1,nameNode:t}}function Us(e){let t=e.childForFieldName("name");return t?t.type==="identifier"?/^[A-Z]/.test(t.text)?{kind:"jsx",oldShape:!0,nameNode:t}:null:t.type==="member_expression"||t.type==="nested_identifier"?{kind:"jsxMember",oldShape:!1,nameNode:t}:null:null}function hn(e){let t=e;for(;t&&t.type!=="call_expression";)t=t.parent;return t}function zs(e){let t=e.childForFieldName("function"),n=!1;for(;t;)if(t=le(t),t.type==="member_expression"||t.type==="subscript_expression")t=t.childForFieldName("object");else if(t.type==="call_expression")n=!0,t=t.childForFieldName("function");else if(t.type==="await_expression"||t.type==="parenthesized_expression"||t.type==="non_null_expression")t=t.namedChild(0);else break;return t&&t.type==="identifier"?{head:t.text,called:n}:{head:null,called:!1}}function Ws(e){let t=e.text.replace(/\s+/g," ");return t.length>120?t.slice(0,117)+"...":t}function Gs(e,t){let o=oe(t,"functionDeclarations.scm").matches(e.rootNode).map(r=>{let i=r.captures.find(c=>c.name==="func_name"),a=r.captures.find(c=>c.name==="func_params"),l=r.captures.find(c=>c.name==="func_declaration");return{name:i.node.text,params:a.node.text,startLine:l.node.startPosition.row+1,endLine:l.node.endPosition.row+1,startIndex:l.node.startIndex,endIndex:l.node.endIndex,node:i.node}});return st(t)&&o.push(...tl(e,t)),o}function tl(e,t){return oe(t,"defaultExports.scm").matches(e.rootNode).map(n=>{let s=n.captures.find(r=>r.name==="func_declaration").node;return{name:"default",params:n.captures.find(r=>r.name==="func_params").node.text,startLine:s.startPosition.row+1,endLine:s.endPosition.row+1,startIndex:s.startIndex,endIndex:s.endIndex,node:s}})}function Js(e,t){return oe(t,"arrowFunctions.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(l=>l.name==="func_name"),i=o.captures.find(l=>l.name==="func_params"),a=o.captures.find(l=>l.name==="func_declaration");return{name:r.node.text,params:i.node.text,startLine:a.node.startPosition.row+1,endLine:a.node.endPosition.row+1,startIndex:a.node.startIndex,endIndex:a.node.endIndex,node:r.node}})}function Ks(e,t){let s=oe(t,"classMethods.scm").matches(e.rootNode),o=st(t);return s.map(r=>{let i=r.captures.find(m=>m.name==="class_name"),a=r.captures.find(m=>m.name==="method_name"),l=r.captures.find(m=>m.name==="method_params"),c=r.captures.find(m=>m.name==="method_declaration"),d=c.node;if(o)for(let m=d.previousNamedSibling;m&&m.type==="decorator";m=m.previousNamedSibling)d=m;return{className:i?i.node.text:"default",methodName:a.node.text,params:l.node.text,startLine:d.startPosition.row+1,endLine:c.node.endPosition.row+1,startIndex:d.startIndex,endIndex:c.node.endIndex,node:a.node}})}function Vs(e,t){let s=oe(t,"imports.scm").matches(e.rootNode),o=st(t);return s.filter(r=>!(o&&nl(r.captures[0].node))).map(r=>{let i=r.captures[0].node;return{source:i.text,startLine:i.startPosition.row+1}})}function nl(e){let t=e;for(;t&&t.type!=="import_statement";)t=t.parent;if(!t)return!1;if(t.children.some(r=>r.type==="type"))return!0;let n=t.namedChildren.find(r=>r.type==="import_clause");if(!n)return!1;let s=n.namedChildren;if(s.length!==1||s[0].type!=="named_imports")return!1;let o=s[0].namedChildren.filter(r=>r.type==="import_specifier");return o.length>0&&o.every(r=>r.children.some(i=>i.type==="type"))}function Wt(e){let t=e;for(;t&&t.type!=="call_expression"&&t.type!=="new_expression";)t=t.parent;if(!t)return null;let n=t.childForFieldName("arguments");if(!n)return null;let s=n.namedChildren?.[0];return!s||s.type==="arrow_function"||s.type==="function_expression"?null:s.text}var ol=/^(addEventListener|removeEventListener|on|once|postMessage|onmessage|subscribe)$/i;function Ct(e){let t=e;for(;t.parent;){let n=t.parent;if(n.type==="arrow_function"||n.type==="function_expression"){let s=n.parent;if(s&&(s.type==="variable_declarator"||s.type==="public_field_definition"))break;if(s&&s.type==="return_statement")return!0;if(s&&s.type==="arguments"&&s.parent?.type==="call_expression"){let o=s.parent.childForFieldName("function"),r=o?.type==="member_expression"?o.childForFieldName("property")?.text:o?.text;if(r&&ol.test(r))return!0}}else if(n.type==="function_declaration"||n.type==="method_definition")break;t=n}return!1}function Xs(e,t){return oe(t,"callExpressions.scm").matches(e.rootNode).map(o=>{let r=o.captures[0].node;return{calleeName:r.text,startLine:r.startPosition.row+1,startColumn:r.startPosition.column,branchPath:Et(r),firstArgText:Wt(r),deferred:Ct(r),callKind:rt(hn(r)).kind}})}function Ys(e,t){return st(t)?sl(e):oe(t,"methodCalls.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(a=>a.name==="object_name"),i=o.captures.find(a=>a.name==="method_name");return{objectName:r.node.text,methodName:i.node.text,startLine:i.node.startPosition.row+1,startColumn:i.node.startPosition.column,firstArgText:Wt(i.node),branchPath:Et(i.node),deferred:Ct(i.node),callKind:rt(hn(i.node)).kind}})}function sl(e){let t=[];for(let n of e.rootNode.descendantsOfType("call_expression")){let s=n.childForFieldName("function");if(!s||s.type!=="member_expression")continue;let o=le(s.childForFieldName("object")),r=s.childForFieldName("property");!o||o.type!=="identifier"||!r||r.type!=="property_identifier"||t.push({objectName:o.text,methodName:r.text,startLine:r.startPosition.row+1,startColumn:r.startPosition.column,firstArgText:Wt(r),branchPath:Et(r),deferred:Ct(r),callKind:rt(hn(r)).kind})}return t}function rl(e){if(!e)return"return";if(e.type==="object"){let t=e.namedChildren.filter(s=>s.type==="pair"),n=t.find(s=>s.childForFieldName("key")?.text?.replace(/^['"]|['"]$/g,"")==="type")??t.find(s=>s.childForFieldName("key")?.text?.replace(/^['"]|['"]$/g,"")==="entity");if(n){let s=n.childForFieldName("key"),o=n.childForFieldName("value");return`return { ${s.text}: ${o.text} }`}}return"return "+e.text.split(/\r?\n/)[0].trim()}function Zs(e,t){return oe(t,"returns.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(l=>l.name==="return_statement"),i=o.captures.find(l=>l.name==="return_value"),a=r.node;return{label:rl(i?.node),startLine:a.startPosition.row+1,startColumn:a.startPosition.column,branchPath:Et(a),deferred:Ct(a)}})}var il=new Set(["function_declaration","arrow_function","function_expression","method_definition"]);function gn(e,t){return!(!t||e.row<t.startPosition.row||e.row>t.endPosition.row||e.row===t.startPosition.row&&e.column<t.startPosition.column||e.row===t.endPosition.row&&e.column>t.endPosition.column)}function Et(e){let t=[],n=e,s=e.startPosition;for(;n.parent;){let o=n.parent;if(il.has(o.type))break;if(o.type==="if_statement"){let r=o.childForFieldName("condition"),i=o.childForFieldName("consequence"),a=o.childForFieldName("alternative");gn(s,i)?t.push({type:"if",conditionText:r?r.text:"",conditionLine:(r??o).startPosition.row+1,outcome:"true"}):gn(s,a)&&t.push({type:"if",conditionText:r?r.text:"",conditionLine:(r??o).startPosition.row+1,outcome:"false"})}else if(o.type==="switch_case"||o.type==="switch_default"){let r=o.parent,i=r&&r.type==="switch_body"?r.parent:null;if(i){let a=i.childForFieldName("value"),l=o.childForFieldName("value");t.push({type:"switch",conditionText:a?a.text:"",conditionLine:(a??i).startPosition.row+1,outcome:o.type==="switch_default"?"default":l?l.text:"case"})}}else if(o.type==="try_statement"){let r=o.childForFieldName("handler"),i=o.childForFieldName("finalizer"),a="try";gn(s,r)?a="catch":gn(s,i)&&(a="finally"),t.push({type:"try",conditionText:"try / catch",conditionLine:o.startPosition.row+1,outcome:a})}n=o}return t.reverse()}function Qs(e,t){return oe(t,"exports.scm").matches(e.rootNode).map(s=>s.captures[0].node.text)}var qs=new WeakMap;function al(e,t){let n=qs.get(e);return n||(n=oe(t,"returns.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(a=>a.name==="return_statement"),i=o.captures.find(a=>a.name==="return_value");return{stmtNode:r.node,valueNode:i?.node}}),qs.set(e,n)),n}function er(e,t,n){return al(e,t).filter(s=>s.stmtNode.startPosition.row+1>=n.startLine&&s.stmtNode.endPosition.row+1<=n.endLine).map(s=>({shape:cl(s.valueNode),condition:ll(s.stmtNode,n),line:s.stmtNode.startPosition.row+1}))}function cl(e){if(!e)return"nothing";switch(e.type){case"true":case"false":return"boolean";case"number":return"number";case"string":return"string";case"null":return"null";case"identifier":return`variable (${e.text})`;case"object":return"object";case"array":return"array";case"call_expression":return`result of ${e.text.split("(")[0]}()`;case"binary_expression":return"boolean (comparison)";case"ternary_expression":return"conditional value";default:return"expression"}}function ll(e,t){let n=e.parent;for(;n;){if(n.type==="if_statement"){let s=n.childForFieldName("condition");if(s)return s.text}n=n.parent}return null}function tr(e,t){return Ut(t)==="typescript"?[]:oe(t,"jsxElements.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(i=>i.name==="jsx_tag");return{calleeName:r.node.text,startLine:r.node.startPosition.row+1}}).filter(o=>/^[A-Z]/.test(o.calleeName))}function nr(e,t){return oe(t,"fetchApiCalls.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(c=>c.name==="url"),i=o.captures.find(c=>c.name==="http_method"),a=r.node.text,l=/^https?:\/\//.test(a)?"external":"internal";return{url:a,method:i?.node.text??"get",startLine:r.node.startPosition.row+1,scope:l}})}function or(e,t){return oe(t,"socketEmit.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(i=>i.name==="event_name");return{eventName:r.node.text,startLine:r.node.startPosition.row+1}})}function sr(e,t){return oe(t,"rawSocketSend.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(i=>i.name==="event_name");return{eventName:r.node.text,startLine:r.node.startPosition.row+1}})}function rr(e,t){return oe(t,"rawSocketTypeCheck.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(i=>i.name==="event_name");return{eventName:r.node.text,startLine:r.node.startPosition.row+1}})}function ir(e,t){return oe(t,"socketOn.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(l=>l.name==="event_name"),i=o.captures.find(l=>l.name==="handler_ref"),a=o.captures.find(l=>l.name==="handler_inline");return{eventName:r.node.text,startLine:r.node.startPosition.row+1,handlerName:i?i.node.text:null,isInlineHandler:!!a,handlerStartLine:a?a.node.startPosition.row+1:null,handlerEndLine:a?a.node.endPosition.row+1:null,handlerStartIndex:a?a.node.startIndex:null,handlerEndIndex:a?a.node.endIndex:null}})}function ar(e){let t=e.rootNode.descendantsOfType(["call_expression","new_expression","jsx_opening_element","jsx_self_closing_element",...mn()?["decorator"]:[]]),n=[];for(let s of t){let o,r,i,a=null,l=null,c=!1,d=null,m=null;if(s.type==="new_expression"){if(i=s.childForFieldName("constructor"),!i)continue;o="new",r=i,a=i.type==="identifier"?i.text:null;let u=s.childForFieldName("arguments")?.namedChildren?.[0];d=u&&u.type!=="arrow_function"&&u.type!=="function_expression"?u.text:null}else if(s.type==="decorator"){let f=s.namedChild(0);if(!f||f.type==="call_expression")continue;o="decorator",r=f.type==="member_expression"?f.childForFieldName("property")??f:f,i=f}else if(s.type==="call_expression"){let f=rt(s);if(f.oldShape)continue;if(o=f.kind,r=f.nameNode,i=s.childForFieldName("function")??s,o==="chainedCall"){let u=zs(s);l=u.head,c=u.called;let p=s.childForFieldName("function"),h=p?.type==="member_expression"?le(p.childForFieldName("object")):null;h?.type==="member_expression"&&le(h.childForFieldName("object"))?.type==="this"&&h.childForFieldName("property")?.type==="property_identifier"&&p.childForFieldName("property")&&(m={thisProp:h.childForFieldName("property").text,thisMethod:p.childForFieldName("property").text})}d=Wt(r)}else{let f=Us(s);if(!f||f.oldShape)continue;o=f.kind,r=f.nameNode,i=f.nameNode}n.push({callKind:o,calleeName:Ws(i),startLine:r.startPosition.row+1,startColumn:r.startPosition.column,branchPath:Et(r),firstArgText:d,deferred:Ct(r),chainHead:l,chainHeadCalled:c,ctorName:a,...m??{}})}return n.sort((s,o)=>s.startLine-o.startLine||s.startColumn-o.startColumn)}var So=new Set(["get","post","put","patch","delete","head","options"]),ko=new Set(["axios","ky","got","superagent","$http"]),dl=new Set(["function_declaration","function_expression","function","arrow_function","method_definition","generator_function_declaration","generator_function"]),fl=new Set(["WebSocket","ReconnectingWebSocket","SockJS","W3CWebSocket"]),No=/^(ws|socket|sock|websocket|webSocket|wsClient|socketRef|wsRef|[A-Za-z]+Socket|[A-Za-z]+Ws|[A-Za-z]+WebSocket)$/,Q=e=>{for(;e&&(e.type==="parenthesized_expression"||e.type==="as_expression"||e.type==="non_null_expression"||e.type==="await_expression"||e.type==="satisfies_expression"||e.type==="type_assertion")&&(e=e.namedChildren.find(t=>t.type!=="type_annotation"&&t.type!=="predefined_type"&&!/_type$/.test(t.type))??e.namedChildren[0],!!e););return e},qt=e=>e.namedChildren.length?e.namedChildren.filter(t=>t.type==="string_fragment"||t.type==="escape_sequence").map(t=>t.text).join(""):e.text.slice(1,-1);function Pt(e){for(let t=e.parent;t;t=t.parent)if(dl.has(t.type))return t;return null}function cr(e){if(!e)return null;let t=e.childForFieldName("name")?.text??null;if(!t&&e.parent){let o=e.parent;o.type==="variable_declarator"?t=o.childForFieldName("name")?.text??null:o.type==="assignment_expression"?t=o.childForFieldName("left")?.text??null:o.type==="pair"&&(t=o.childForFieldName("key")?.text??null)}let n=[],s=e.childForFieldName("parameters");if(s)s.namedChildren.forEach((o,r)=>{let i=o.type==="identifier"?o:o.type==="assignment_pattern"?o.childForFieldName("left"):o.type==="required_parameter"||o.type==="optional_parameter"?o.childForFieldName("pattern")??o.namedChildren[0]:null;n[r]=i&&i.type==="identifier"?i.text:null});else{let o=e.childForFieldName("parameter");o&&o.type==="identifier"&&(n[0]=o.text)}return{name:t,params:n}}function lr(e){let t=e.rootNode,n={httpCalls:[],pathCallsites:[],httpInstances:[],wsClients:[],wsServers:[],wsSends:[],wsServerSends:[],listens:[],wsReceivers:[]},s=new Map;for(let u of t.descendantsOfType("variable_declarator")){let p=u.childForFieldName("name"),h=u.childForFieldName("value");if(!p||p.type!=="identifier"||!h)continue;(s.get(p.text)??s.set(p.text,[]).get(p.text)).push({value:h,fn:Pt(u)})}let o=(u,p)=>{let h=s.get(u);if(!h)return null;for(let g=Pt(p);g;g=Pt(g)){let w=h.filter(S=>S.fn&&S.fn.id===g.id);if(w.length===1)return w[0].value}let v=h.filter(g=>!g.fn);return v.length===1?v[0].value:h.length===1?h[0].value:null},r=(u,p)=>{for(let h=Pt(p);h;h=Pt(h)){let g=cr(h).params.indexOf(u);if(g>=0)return g}return-1};function i(u,p=0){if(u=Q(u),!u)return[{t:"ref",name:""}];switch(u.type){case"string":return[{t:"lit",v:qt(u)}];case"template_string":{let h=[];for(let v of u.namedChildren)v.type==="string_fragment"||v.type==="escape_sequence"?h.push({t:"lit",v:v.text}):v.type==="template_substitution"&&h.push(...i(v.namedChildren[0],p+1));return h.length?h:[{t:"lit",v:""}]}case"number":return[{t:"lit",v:u.text}];case"binary_expression":{let h=u.childForFieldName("operator")?.text;if(h==="||"||h==="??"){let v=i(u.childForFieldName("left"),p+1);if(v.length===1&&v[0].t==="env")return[{...v[0],fallback:i(u.childForFieldName("right"),p+1)}]}return h!=="+"?[{t:"ref",name:u.text.slice(0,60)}]:[...i(u.childForFieldName("left"),p+1),...i(u.childForFieldName("right"),p+1)]}case"shorthand_property_identifier":case"identifier":{let h=u.text,v=r(h,u);if(v>=0)return[{t:"param",name:h,index:v}];if(p<4){let g=o(h,u);if(g&&g.id!==u.id)return i(g,p+1)}return[{t:"ref",name:h}]}case"member_expression":{let h=u.text,v=/^(?:process\.env|import\.meta\.env)\.([A-Za-z0-9_$]+)$/.exec(h)??/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(h);return v?[{t:"env",name:v[1]}]:[{t:"ref",name:h.slice(0,60)}]}case"subscript_expression":{let h=/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(u.text);return h?[{t:"env",name:h[1]}]:[{t:"ref",name:u.text.slice(0,60)}]}case"call_expression":{let h=u.childForFieldName("function")?.text,v=u.childForFieldName("arguments")?.namedChildren[0];if(v&&(h==="encodeURIComponent"||h==="String"||h==="encodeURI"))return i(v,p+1);let g=Q(u.childForFieldName("function"));if(g&&g.type==="member_expression"&&/^(replace|replaceAll|trim|trimEnd|trimStart|toString|toLowerCase)$/.test(g.childForFieldName("property")?.text??"")){let w=g.childForFieldName("object");if(w){let S=i(w,p+1);if(S.length&&S.every(k=>k.t!=="ref"))return S}}return[{t:"ref",name:u.text.slice(0,60)}]}default:return[{t:"ref",name:u.text.slice(0,60)}]}}let a=(u,p)=>{if(u=Q(u),!(!u||u.type!=="object")){for(let h of u.namedChildren)if(h.type==="pair"){let v=h.childForFieldName("key");if((v?v.type==="string"?qt(v):v.text:null)===p)return h.childForFieldName("value")}else if(h.type==="shorthand_property_identifier"&&h.text===p)return h}},l=u=>u.childForFieldName("arguments")?.namedChildren.filter(p=>p.type!=="comment")??[],c=u=>{if(!u)return null;let p=i(u);return p.length===1&&p[0].t==="lit"?p[0].v.toUpperCase():p.length===1&&p[0].t==="param"?{param:p[0].index}:"?"},d=(u,p,h,v)=>({client:u,method:p,parts:h,line:v.startPosition.row+1,fn:cr(Pt(v))});for(let u of t.descendantsOfType("variable_declarator")){let p=u.childForFieldName("name"),h=Q(u.childForFieldName("value"));if(!p||p.type!=="identifier"||!h||h.type!=="call_expression")continue;let v=Q(h.childForFieldName("function"));if(!v||v.type!=="member_expression")continue;let g=v.childForFieldName("object")?.text,w=v.childForFieldName("property")?.text;if(!(ko.has(g)&&(w==="create"||w==="extend")))continue;let S=l(h)[0],k=a(S,"baseURL")??a(S,"baseUrl")??a(S,"prefixUrl")??a(S,"prefix_url");n.httpInstances.push({name:p.text,parts:k?i(k):[],line:u.startPosition.row+1})}let m=new Set(n.httpInstances.map(u=>u.name));for(let u of t.descendantsOfType("call_expression")){let p=Q(u.childForFieldName("function"));if(!p)continue;let h=l(u),v=!1;if(p.type==="identifier"){let g=p.text;if(g==="fetch"&&h[0]){let w=Q(h[0]);if(w&&w.type==="new_expression")continue;let S=a(h[1],"method");n.httpCalls.push(d("fetch",S?c(S):h[1]&&Q(h[1])?.type!=="object"?"?":"GET",i(h[0]),u)),v=!0}else if((ko.has(g)||m.has(g))&&h[0]){let w=Q(h[0]);if(w&&w.type==="object"){let S=a(w,"url");if(S){let k=a(w,"baseURL");n.httpCalls.push(d(m.has(g)?"inst:"+g:g,c(a(w,"method"))??"GET",[...k?i(k):[],...i(S)],u)),v=!0}}else n.httpCalls.push(d(m.has(g)?"inst:"+g:g,h[1]&&a(h[1],"method")?c(a(h[1],"method")):"GET",i(h[0]),u)),v=!0}else g==="io"&&h[0]&&(n.wsClients.push({client:"io",parts:i(h[0]),line:u.startPosition.row+1}),v=!0)}else if(p.type==="member_expression"){let w=p.childForFieldName("object")?.text??"",S=p.childForFieldName("property")?.text??"",k=ko.has(w)||m.has(w);if(k&&So.has(S)&&h[0])n.httpCalls.push(d(m.has(w)?"inst:"+w:w,S.toUpperCase(),i(h[0]),u)),v=!0;else if(!k&&So.has(S)&&/^[A-Za-z_$][\w$]*$/.test(w)&&h[0]&&(Q(h[0])?.type==="string"||Q(h[0])?.type==="template_string")){let y=i(h[0]);y[0]?.t==="lit"&&(y[0].v.startsWith("/")||/^https?:\/\//.test(y[0].v))&&(n.httpCalls.push(d("obj:"+w,S.toUpperCase(),y,u)),v=!0)}else if(k&&S==="request"&&h[0]){let y=a(h[0],"url");if(y){let x=a(h[0],"baseURL");n.httpCalls.push(d(m.has(w)?"inst:"+w:w,c(a(h[0],"method"))??"GET",[...x?i(x):[],...i(y)],u)),v=!0}}else if(S==="open"&&h.length>=2&&Q(h[0])?.type==="string"&&/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/i.test(qt(Q(h[0]))))n.httpCalls.push(d("xhr",qt(Q(h[0])).toUpperCase(),i(h[1]),u)),v=!0;else if(w==="io"&&S==="connect"&&h[0])n.wsClients.push({client:"io",parts:i(h[0]),line:u.startPosition.row+1}),v=!0;else if(S==="listen"&&h[0]){let y=Q(h[0]),x=y&&y.type==="object"?a(y,"port"):y;x&&n.listens.push({parts:i(x),line:u.startPosition.row+1}),v=!0}else if(S==="send"&&/^(client|conn|connection|peer)$/.test(w.replace(/^this./,"").split(".").pop())&&h[0]){let y=Q(h[0]),x=!1;if(y&&y.type==="call_expression"&&y.childForFieldName("function")?.text==="JSON.stringify"){let b=l(y)[0];x=!!(b&&(a(b,"type")||a(b,"event"))&&Q(a(b,"type")??a(b,"event"))?.type==="string")}x||n.wsServerSends.push({recv:w,line:u.startPosition.row+1}),v=!0}else if(S==="send"&&No.test(w.replace(/^this\./,"").replace(/\.current$/,"").split(".").pop())){let y=h[0]?Q(h[0]):null,x=!1;if(y&&y.type==="call_expression"&&y.childForFieldName("function")?.text==="JSON.stringify"){let b=l(y)[0];x=!!(b&&(a(b,"type")||a(b,"event"))&&Q(a(b,"type")??a(b,"event"))?.type==="string")}x||n.wsSends.push({recv:w,line:u.startPosition.row+1}),v=!0}}if(!v){let g=null;if(p.type==="identifier"?g=p.text:p.type==="member_expression"&&(g=p.childForFieldName("property")?.text??null),!g||So.has(g)||h.length===0||h.length>6)continue;let w=[],S=!1;h.slice(0,5).forEach((k,y)=>{let x=Q(k);if(!x||x.type!=="string"&&x.type!=="template_string")return;let b=i(x);w.push({i:y,parts:b});let N=b[0];N&&N.t==="lit"&&(N.v.startsWith("/")||/^https?:\/\//.test(N.v))&&N.v.length>1&&(S=!0)}),S&&n.pathCallsites.push({callee:g,args:w,line:u.startPosition.row+1})}}let f=u=>u.replace(/^this./,"").replace(/.current$/,"").split(".").pop();for(let u of t.descendantsOfType("assignment_expression")){let p=u.childForFieldName("left");if(!p||p.type!=="member_expression"||p.childForFieldName("property")?.text!=="onmessage"||!No.test(f(p.childForFieldName("object")?.text??"")))continue;let h=Q(u.childForFieldName("right"));n.wsReceivers.push({line:u.startPosition.row+1,handlerName:h&&h.type==="identifier"?h.text:null})}for(let u of t.descendantsOfType("call_expression")){let p=Q(u.childForFieldName("function"));if(!p||p.type!=="member_expression"||p.childForFieldName("property")?.text!=="addEventListener")continue;let h=l(u),v=h[0]&&Q(h[0]);if(!v||v.type!=="string"||qt(v)!=="message"||!No.test(f(p.childForFieldName("object")?.text??"")))continue;let g=h[1]&&Q(h[1]);n.wsReceivers.push({line:u.startPosition.row+1,handlerName:g&&g.type==="identifier"?g.text:null})}for(let u of t.descendantsOfType("new_expression")){let p=Q(u.childForFieldName("constructor"));if(!p)continue;let h=p.text,v=l(u);if(fl.has(h)&&v[0])n.wsClients.push({client:h,parts:i(v[0]),line:u.startPosition.row+1});else if(/^(WebSocketServer|WebSocket\.Server|WebSocket\.WebSocketServer|ws\.Server|ws\.WebSocketServer|Server)$/.test(h)){if(h==="Server"&&!/socket\.io|socketio/i.test(e.rootNode.text.slice(0,4e3)+""))continue;let g=a(v.find(w=>Q(w)?.type==="object"),"path");n.wsServers.push({path:g?i(g):null,line:u.startPosition.row+1})}}return n}var ul=new Set(["function_declaration","generator_function_declaration","function_expression","generator_function","arrow_function","method_definition"]),pl=new Set(["arrow_function","function_expression","generator_function"]);function Ve(e,t){if(e)switch(e.type){case"identifier":case"shorthand_property_identifier_pattern":t.push(e.text);return;case"assignment_pattern":Ve(e.childForFieldName("left"),t);return;case"rest_pattern":case"object_pattern":case"array_pattern":case"pair_pattern":case"required_parameter":case"optional_parameter":for(let n of e.namedChildren)Ve(e.type==="pair_pattern"?e.childForFieldName("value"):n,t);return;default:if(e.type==="pattern"||e.namedChildCount){let n=e.childForFieldName?.("pattern");n&&Ve(n,t)}}}function ml(e,t){let n=e;if(n.type==="export_statement"&&(n=n.childForFieldName("declaration")),!n)return null;if(n.type==="function_declaration"||n.type==="generator_function_declaration")return n.childForFieldName("name")?.text===t?{kind:"fn",declLine:n.startPosition.row+1}:null;if(n.type==="lexical_declaration"||n.type==="variable_declaration"){for(let s of n.namedChildren){if(s.type!=="variable_declarator")continue;let o=s.childForFieldName("name");if(o?.type==="identifier"){if(o.text!==t)continue;let i=le(s.childForFieldName("value"));return i&&pl.has(i.type)?{kind:"fn",declLine:s.startPosition.row+1}:{kind:"other"}}let r=[];if(Ve(o,r),r.includes(t))return{kind:"other"}}return null}return(n.type==="class_declaration"||n.type==="abstract_class_declaration"||n.type==="enum_declaration")&&n.childForFieldName("name")?.text===t?{kind:"other"}:null}function hl(e){let t=e.namedChildren.find(o=>o.type==="string")?.text.slice(1,-1)??null,n=e.namedChildren.find(o=>o.type==="import_clause"),s=[];if(!n||t==null)return{src:t,out:s};for(let o of n.namedChildren)if(o.type==="identifier")s.push({kind:"default",local:o.text,imported:null});else if(o.type==="namespace_import"){let r=o.namedChildren.find(i=>i.type==="identifier");r&&s.push({kind:"ns",local:r.text,imported:null})}else if(o.type==="named_imports")for(let r of o.namedChildren){if(r.type!=="import_specifier")continue;let i=r.childForFieldName("name"),a=r.childForFieldName("alias");i&&s.push({kind:"named",local:(a??i).text,imported:i.text})}return{src:t,out:s}}function dr(e){let t=[];for(let n of e.rootNode.namedChildren)if(n.type==="import_statement"){if(n.children.some(i=>i.type==="type"))continue;let s=n.namedChildren.find(i=>i.type==="import_require_clause");if(s){let i=s.namedChildren.find(l=>l.type==="identifier"),a=s.namedChildren.find(l=>l.type==="string");i&&a&&t.push({source:Gt(a),kind:"cjs",local:i.text,imported:null});continue}let{src:o,out:r}=hl(n);for(let i of r)t.push({source:o,...i})}else if(n.type==="lexical_declaration"||n.type==="variable_declaration")for(let s of n.namedChildren){if(s.type!=="variable_declarator")continue;let o=le(s.childForFieldName("value")),r=null;o?.type==="member_expression"&&(r=o.childForFieldName("property")?.text??null,o=le(o.childForFieldName("object")));let i=yn(o);if(i==null)continue;let a=s.childForFieldName("name");if(a?.type==="identifier")t.push({source:i,kind:r?"named":"cjs",local:a.text,imported:r});else if(a?.type==="object_pattern"&&!r){for(let l of a.namedChildren)if(l.type==="shorthand_property_identifier_pattern")t.push({source:i,kind:"named",local:l.text,imported:l.text});else if(l.type==="pair_pattern"){let c=l.childForFieldName("key"),d=l.childForFieldName("value");c&&d?.type==="identifier"&&t.push({source:i,kind:"named",local:d.text,imported:c.text})}}}return t}var Gt=e=>e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("");function yn(e){if(e?.type!=="call_expression")return null;let t=e.childForFieldName("function"),n=e.childForFieldName("arguments");if(t?.type!=="identifier"||t.text!=="require"||!n||n.namedChildCount!==1)return null;let s=n.namedChildren[0];return s.type==="string"?Gt(s):null}function fr(e){let t=[];return(function n(s){if(s.type==="export_statement"){let o=s.childForFieldName("source");o&&!s.children.some(r=>r.type==="type")&&t.push({source:Gt(o),startLine:o.startPosition.row+1})}else if(s.type==="import_require_clause"){let o=s.namedChildren.find(r=>r.type==="string");o&&t.push({source:Gt(o),startLine:o.startPosition.row+1})}else if(s.type==="call_expression"){let o=yn(s);o!=null&&t.push({source:o,startLine:s.startPosition.row+1})}for(let o of s.namedChildren)n(o)})(e.rootNode),t}function ur(e){let t={default:null,named:{},reexports:[],stars:[],nsReexports:[]};for(let n of e.rootNode.namedChildren){if(n.type!=="export_statement")continue;let s=n.children.some(i=>i.type==="default"),o=n.childForFieldName("declaration"),r=n.childForFieldName("source")!=null;if(s){if(o){let i=o.childForFieldName("name");t.default=i&&(o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"||o.type==="abstract_class_declaration")?i.text:"<anon>"}else{let i=le(n.childForFieldName("value"));t.default=i?.type==="identifier"?i.text:"<anon>"}continue}if(o){if(o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"||o.type==="abstract_class_declaration"){let i=o.childForFieldName("name")?.text;i&&(t.named[i]=i)}else if(o.type==="lexical_declaration"||o.type==="variable_declaration")for(let i of o.namedChildren){let a=i.type==="variable_declarator"?i.childForFieldName("name"):null;a?.type==="identifier"&&(t.named[a.text]=a.text)}continue}if(r){if(n.children.some(c=>c.type==="type"))continue;let i=Gt(n.childForFieldName("source")),a=n.namedChildren.find(c=>c.type==="export_clause"),l=n.namedChildren.find(c=>c.type==="namespace_export");if(a)for(let c of a.namedChildren){if(c.type!=="export_specifier")continue;let d=c.childForFieldName("name")?.text,m=c.childForFieldName("alias")?.text;d&&t.reexports.push({exported:m??d,imported:d,source:i})}else if(l){let c=l.namedChildren.find(d=>d.type==="identifier");c&&t.nsReexports.push({exported:c.text,source:i})}else t.stars.push(i);continue}for(let i of n.namedChildren)if(i.type==="export_clause")for(let a of i.namedChildren){if(a.type!=="export_specifier")continue;let l=a.childForFieldName("name")?.text,c=a.childForFieldName("alias")?.text;l&&(c==="default"?t.default=l:t.named[c??l]=l)}}for(let n of e.rootNode.namedChildren){let s=n.type==="expression_statement"?n.namedChildren[0]:null;if(s?.type!=="assignment_expression")continue;let o=s.childForFieldName("left"),r=le(s.childForFieldName("right"));if(o?.type!=="member_expression")continue;let i=o.childForFieldName("object"),a=o.childForFieldName("property")?.text,l=c=>c?.type==="member_expression"&&c.childForFieldName("object")?.text==="module"&&c.childForFieldName("property")?.text==="exports";if(l(o))if(r?.type==="identifier")t.default=r.text;else if(r?.type==="object"){for(let c of r.namedChildren)if(c.type==="shorthand_property_identifier")t.named[c.text]=c.text;else if(c.type==="pair"){let d=c.childForFieldName("key"),m=le(c.childForFieldName("value"));d&&m?.type==="identifier"&&(t.named[d.text.replace(/^['"]|['"]$/g,"")]=m.text)}t.default??="<object>"}else yn(r)!=null?t.stars.push(yn(r)):t.default="<anon>";else a&&(i?.type==="identifier"&&i.text==="exports"||l(i))&&r?.type==="identifier"&&(t.named[a]=r.text)}return t}function gl(e,t,n){for(let s=e.parent;s;s=s.parent)if(ul.has(s.type)){let o=[],r=s.childForFieldName("parameters");if(r)for(let a of r.namedChildren)Ve(a,o);let i=s.childForFieldName("parameter");if(i&&Ve(i,o),s.type==="function_expression"||s.type==="generator_function"){let a=s.childForFieldName("name");a&&o.push(a.text)}if(o.includes(t))return{kind:"other"}}else if(s.type==="catch_clause"){let o=[];if(Ve(s.childForFieldName("parameter"),o),o.includes(t))return{kind:"other"}}else if(s.type==="for_in_statement"||s.type==="for_statement"){let o=[],r=s.type==="for_statement"?s.childForFieldName("initializer"):s.childForFieldName("left");if(r)if(r.type==="lexical_declaration"||r.type==="variable_declaration")for(let i of r.namedChildren)Ve(i.childForFieldName?.("name"),o);else Ve(r,o);if(o.includes(t))return{kind:"other"}}else if(s.type==="statement_block"||s.type==="program"||s.type==="switch_body"){if(s.type==="program"&&n.has(t))return{kind:"import",imp:n.get(t)};for(let o of s.namedChildren){let r=ml(o,t);if(r)return r}if(s.type==="program"&&n.has(t))return{kind:"import",imp:n.get(t)}}return null}var yl=e=>(e.childForFieldName("function")?.text??"").replace(/\s+/g," ").slice(0,40);function pr(e,t){let n=new Map(t.map(r=>[r.local,r])),s=[],o=(r,i,a)=>{let l=le(r);if(!l||l.type!=="identifier"&&l.type!=="shorthand_property_identifier")return;let c=l.text,d=gl(l,c,n);if(!d||d.kind==="other")return;let m=rt(a).nameNode,f={name:c,line:l.startPosition.row+1,column:l.startPosition.column,via:i,callee:yl(a),callLine:m.startPosition.row+1,callColumn:m.startPosition.column,b:d.kind};d.kind==="fn"?f.declLine=d.declLine:(f.src=d.imp.source,f.ik=d.imp.kind,f.imp=d.imp.imported),s.push(f)};return(function r(i){if(i.type==="call_expression"){let a=i.childForFieldName("arguments");for(let l of a?.namedChildren??[]){let c=le(l);if(c)if(c.type==="array")for(let d of c.namedChildren)o(d,"array",i);else if(c.type==="object")for(let d of c.namedChildren)d.type==="pair"?o(d.childForFieldName("value"),"object",i):d.type==="shorthand_property_identifier"&&o(d,"object",i);else o(c,"arg",i)}}for(let a of i.namedChildren)r(a)})(e.rootNode),s}function mr(e){let t=[],n=o=>{let r=o?.namedChildren.find(i=>i.type!=="comment");return r?.type==="type_identifier"?r.text:null},s=o=>{let r=o.childForFieldName("name")?.text,i=o.childForFieldName("body");if(!(!r||!i)){for(let a of i.namedChildren)if(a.type==="public_field_definition"){let l=a.childForFieldName("name"),c=n(a.childForFieldName("type"));l?.type==="property_identifier"&&c&&t.push({className:r,prop:l.text,type:c})}else if(a.type==="method_definition"&&a.childForFieldName("name")?.text==="constructor")for(let l of a.childForFieldName("parameters")?.namedChildren??[]){if(l.type!=="required_parameter"&&l.type!=="optional_parameter"||!l.namedChildren.some(m=>m.type==="accessibility_modifier")&&!l.children.some(m=>m.type==="readonly"))continue;let c=l.childForFieldName("pattern"),d=n(l.childForFieldName("type"));c?.type==="identifier"&&d&&t.push({className:r,prop:c.text,type:d})}}};for(let o of e.rootNode.namedChildren){let r=o.type==="export_statement"?o.childForFieldName("declaration"):o;r&&(r.type==="class_declaration"||r.type==="abstract_class_declaration")&&s(r)}return t}var xl={Get:"get",Post:"post",Put:"put",Patch:"patch",Delete:"delete",All:"all"};function hr(e){let t=e.namedChildren[0];if(!t)return null;if(t.type==="call_expression"){let n=t.childForFieldName("function"),s=n?.type==="identifier"?n.text:null;return s?{name:s,args:t.childForFieldName("arguments")}:null}return t.type==="identifier"?{name:t.text,args:null}:null}var ut=e=>e?e.type==="string"?e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join(""):e.type==="template_string"&&!e.namedChildren.some(t=>t.type==="template_substitution")?e.text.slice(1,-1):null:null;function gr(e){let t=e?.namedChildren.find(n=>n.type!=="comment");if(!t)return"";if(t.type==="array")return ut(t.namedChildren.find(n=>n.type!=="comment"))??"";if(t.type==="object"){for(let n of t.namedChildren){if(n.type!=="pair")continue;let s=n.childForFieldName("key");if(s?.text==="path"||s?.text==="'path'"||s?.text==='"path"'){let o=n.childForFieldName("value");return(o?.type==="array"?ut(o.namedChildren[0]):ut(o))??""}}return""}return ut(t)??""}var xn=(...e)=>"/"+e.map(n=>String(n??"").replace(/^\/+|\/+$/g,"")).filter(Boolean).join("/");function yr(e){let t=[],n=(s,o)=>{let r=s.childForFieldName("name")?.text,i=s.childForFieldName("body");if(!r||!i)return;let l=[...o,...s.namedChildren.filter(m=>m.type==="decorator")].map(hr).filter(Boolean).find(m=>m.name==="Controller");if(!l)return;let c=gr(l.args),d=[];for(let m of i.namedChildren)if(m.type!=="comment"){if(m.type==="decorator"){d.push(m);continue}if(m.type==="method_definition"){let f=m.childForFieldName("name")?.text;for(let u of d.map(hr).filter(Boolean)){let p=xl[u.name];!p||!f||t.push({method:p,path:xn(c,gr(u.args)),startLine:m.startPosition.row+1,handlerName:null,isInlineHandler:!1,handlerStartLine:null,handlerEndLine:null,handlerStartIndex:null,handlerEndIndex:null,nest:{className:r,methodName:f}})}}d=[]}};for(let s of e.rootNode.namedChildren)if(s.type==="export_statement"){let o=s.childForFieldName("declaration");o&&(o.type==="class_declaration"||o.type==="abstract_class_declaration")&&n(o,s.namedChildren.filter(r=>r.type==="decorator"))}else(s.type==="class_declaration"||s.type==="abstract_class_declaration")&&n(s,[]);return t}function xr(e){let t=[];return(function n(s){if(s.type==="call_expression"){let o=s.childForFieldName("function");if(o?.type==="member_expression"&&o.childForFieldName("property")?.text==="setGlobalPrefix"){let r=(s.childForFieldName("arguments")?.namedChildren??[]).filter(c=>c.type!=="comment"),i=r[0]?ut(r[0]):null,a=[],l=r[1];if(l?.type==="object")for(let c of l.namedChildren){if(c.type!=="pair"||c.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")!=="exclude")continue;let d=c.childForFieldName("value");for(let m of d?.type==="array"?d.namedChildren:[])if(m.type==="object"){for(let f of m.namedChildren)if(f.type==="pair"&&f.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")==="path"){let u=ut(f.childForFieldName("value"));u!=null&&a.push(u)}}else{let f=ut(m);f!=null&&a.push(f)}}t.push({prefix:i||null,exclude:a})}}for(let o of s.namedChildren)n(o)})(e.rootNode),t}function vr(e){let t=[];for(let r of e.values())for(let i of r?.globalPrefix??[])t.push(i);if(!t.length||t.some(r=>!r.prefix||r.prefix!==t[0].prefix))return e;let n=t[0].prefix,s=new Set(t.flatMap(r=>r.exclude).map(r=>xn(r))),o=new Map;for(let[r,i]of e){if(!i?.routes?.some(a=>a.nest)){o.set(r,i);continue}o.set(r,{...i,routes:i.routes.map(a=>a.nest&&!s.has(xn(a.path))?{...a,path:xn(n,a.path)}:a)})}return o}import vl from"node:crypto";var wr=e=>vl.createHash("sha256").update(e).digest("hex");function wl(e,t=null){let n=[],s=o=>{if(o.childCount===0){if(o.type==="comment")return;let r=t?t.slice(o.startIndex,o.endIndex):o.text,i=o.type==="jsx_text"?r.replace(/\s+/g," ").trim():r;if(i==="")return;n.push({s:o.startIndex,e:o.endIndex,t:i});return}for(let r=0;r<o.childCount;r++)s(o.child(r))};return s(e),n}function Sr(e,t){let n=[];for(let r of[t.functions,t.arrowFunctions,t.classMethods])for(let i of r??[])i.startIndex!=null&&n.push({s:i.startIndex,e:i.endIndex,item:i,field:"bodyHash"});for(let r of[t.routes,t.listeners,t.socketListeners])for(let i of r??[])i.isInlineHandler&&i.handlerStartIndex!=null&&n.push({s:i.handlerStartIndex,e:i.handlerEndIndex,item:i,field:"handlerBodyHash"});let s=new Map(n.map(r=>[r,[]])),o=[];for(let r of wl(e.rootNode,e.canopyOriginalSource??null)){let i=null,a=1/0;for(let l of n)r.s>=l.s&&r.e<=l.e&&l.e-l.s<a&&(i=l,a=l.e-l.s);(i?s.get(i):o).push(r.t)}for(let r of n)r.item[r.field]=wr(s.get(r).join(" "));t.moduleBodyHash=wr(o.join(" "))}function kr(e,t){return oe(t,"matchFastifyRoutes.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(c=>c.name==="http_method"),i=o.captures.find(c=>c.name==="route_path"),a=o.captures.find(c=>c.name==="handler_ref"),l=o.captures.find(c=>c.name==="handler_inline");return{method:r.node.text,path:i.node.text,startLine:r.node.startPosition.row+1,handlerName:a?a.node.text:null,isInlineHandler:!!l,handlerStartLine:l?l.node.startPosition.row+1:null,handlerEndLine:l?l.node.endPosition.row+1:null,handlerStartIndex:l?l.node.startIndex:null,handlerEndIndex:l?l.node.endIndex:null}})}function Nr(e,t){return oe(t,"matchExtensionListeners.scm").matches(e.rootNode).map(o=>{let r=o.captures.find(p=>p.name==="event_type"),i=o.captures.find(p=>p.name==="event_name"),a=o.captures.find(p=>p.name==="method_name"||p.name==="listener_method"),l=o.captures.find(p=>p.name==="handler_ref"),c=o.captures.find(p=>p.name==="target"),d=o.captures.find(p=>p.name==="root_object"),m=o.captures.find(p=>p.name==="sub_object"),f=c?c.node.text:d?d.node.text+(m?"."+m.node.text:""):null,u=o.captures.find(p=>p.name==="handler_inline");return{eventName:r?.node.text??i?.node.text??"unknown",targetName:f,startLine:a.node.startPosition.row+1,handlerName:l?l.node.text:null,isInlineHandler:!!u,handlerStartLine:u?u.node.startPosition.row+1:null,handlerEndLine:u?u.node.endPosition.row+1:null,handlerStartIndex:u?u.node.startIndex:null,handlerEndIndex:u?u.node.endIndex:null}})}import _l from"node:fs";De();import Be from"node:fs";import ie from"node:path";import Sl from"node:os";import _r from"node:crypto";import{fileURLToPath as kl}from"node:url";var Nl=ie.dirname(kl(globalThis.__canopyUrl("src/stage2_parse/parseCache.js"))),$r=ie.join(Nl,"..",".."),bo=process.env.CANOPY_CACHE_DIR||(jt()?ie.join(Sl.homedir(),".canopy-cache"):ie.join($r,".canopy-cache")),br=e=>_r.createHash("sha256").update(e).digest("hex");function vn(e,t){return Be.readdirSync(e,{withFileTypes:!0}).flatMap(n=>n.isDirectory()?vn(ie.join(e,n.name),t):t.some(s=>n.name.endsWith(s))?[ie.join(e,n.name)]:[]).sort()}var _o=null;function bl(){if(_o)return _o;let e=ie.join($r,"src"),t=!Be.existsSync(e)&&globalThis.__canopyBundle,n=t?[t,...vn(ie.join(ie.dirname(t),"queries"),[".scm"])]:[...vn(ie.join(e,"stage2_parse"),[".js",".scm"]),...vn(ie.join(e,"stage5_entrypoints"),[".js"]).filter(o=>/match/i.test(ie.basename(o))),ie.join(e,"utils","loadQuery.js")],s=_r.createHash("sha256");for(let o of n)s.update(ie.relative(t?ie.dirname(t):e,o).split(ie.sep).join("/")).update("\0").update(Be.readFileSync(o).toString("utf8").replace(/\r\n/g,`
|
|
17
|
-
`)).update("\0");for(let o of["web-tree-sitter","tree-sitter-javascript","tree-sitter-typescript"])try{s.update(o+"@"+JSON.parse(Be.readFileSync(ie.join(Ae(o),"package.json"),"utf8")).version)}catch{s.update(o+"@?")}return _o=s.digest("hex").slice(0,16)}function Ir(){let e=bl(),t=ie.join(bo,e);Be.mkdirSync(t,{recursive:!0});for(let n of Be.readdirSync(bo,{withFileTypes:!0}))n.isDirectory()&&n.name!==e&&Be.rmSync(ie.join(bo,n.name),{recursive:!0,force:!0});return{version:e,keyFor:(n,s="javascript")=>br(s==="javascript"?n:Buffer.concat([Buffer.from(s+"\0"),n])),get(n){try{return JSON.parse(Be.readFileSync(ie.join(t,n+".json"),"utf8"))}catch{return null}},set(n,s){let o=ie.join(t,`${n}.${process.pid}.tmp`);Be.writeFileSync(o,JSON.stringify(s)),Be.renameSync(o,ie.join(t,n+".json"))}}}function Fr(e){return JSON.parse(JSON.stringify(e,(t,n)=>n&&typeof n=="object"&&n.startPosition&&n.endPosition&&"type"in n&&"tree"in n?void 0:n))}var jr=Number(process.env.CANOPY_PARSE_BUDGET_MS)||3e4,Io=class extends Error{constructor(t){super(`parse time budget exceeded (limit ${jr/1e3} s; stopped after ${(t/1e3).toFixed(1)} s)`),this.name="ParseBudgetError"}},$l=100;function $o(e,t,n){return e.map(s=>({...s,returns:er(t,n,s)}))}function Cr(e,t,n,{cache:s=!0,onProgress:o=console.log,grammars:r=null}={}){let i=new Map,a=0,l=0,c=0,d=s?Ir():null,m=[],f=0;for(let u of e){f>0&&f%$l===0&&o(` parsing: ${f}/${e.length} files (${c} from cache)`),f++;try{let p=_l.readFileSync(u),h=xo(u),v=d?.keyFor(p,h),g=d?d.get(v):null;if(g){i.set(u,g),c++;continue}l++;let w=performance.now(),S=()=>{let D=performance.now()-w;if(D>jr)throw new Io(D)},k=h==="javascript"?{parser:t,language:n}:r?.get(h);if(!k)throw new Error(`no ${h} grammar loaded`);let y=k.language;Bs(h);let{tree:x}=As(k.parser,u);S();let b=[],N=(D,R,G=[])=>{try{return R()}catch(ee){if(ee.name==="ParseBudgetError")throw ee;return b.push({extractor:D,message:String(ee.message).slice(0,160)}),G}},$=N("functionDeclarations",()=>$o(Gs(x,y),x,y));S();let F=N("arrowFunctions",()=>$o(Js(x,y),x,y));S();let H=N("classMethods",()=>$o(Ks(x,y),x,y));S();let P=N("importBindings",()=>dr(x)),K={functions:$,arrowFunctions:F,classMethods:H,imports:N("imports",()=>[...Vs(x,y),...fr(x)]),calls:(S(),N("calls",()=>Xs(x,y))),methodCalls:(S(),N("methodCalls",()=>Ys(x,y))),returnEntries:N("returnEntries",()=>Zs(x,y)),jsxElements:N("jsxElements",()=>tr(x,y)),callSites:(S(),N("callSites",()=>ar(x))),apiCalls:(S(),N("apiCalls",()=>nr(x,y))),socketEmits:N("socketEmits",()=>or(x,y)),socketListeners:N("socketListeners",()=>ir(x,y)),rawSocketSends:N("rawSocketSends",()=>sr(x,y)),rawSocketTypeChecks:N("rawSocketTypeChecks",()=>rr(x,y)),routes:N("routes",()=>[...kr(x,y),...st(y)?yr(x):[]]),listeners:N("listeners",()=>Nr(x,y)),refArgs:N("refArgs",()=>pr(x,P)),globalPrefix:N("globalPrefix",()=>xr(x)),importBindings:P,classProps:N("classProps",()=>st(y)?mr(x):[]),httpClients:N("httpClients",()=>lr(x),null),exportBindings:N("exportBindings",()=>ur(x),null),hadErrors:vo(x),exportedNames:N("exports",()=>Qs(x,y)),failed:!1,warnings:b};N("bodyHash",()=>Sr(x,K),null);let U=Fr(K);d&&d.set(v,U),i.set(u,U)}catch(p){if(p.name==="ParseBudgetError"){m.push({filePath:u,reason:p.message}),i.set(u,{functions:[],arrowFunctions:[],classMethods:[],imports:[],calls:[],methodCalls:[],returnEntries:[],jsxElements:[],callSites:[],apiCalls:[],socketEmits:[],socketListeners:[],rawSocketSends:[],rawSocketTypeChecks:[],routes:[],listeners:[],hadErrors:!1,failed:!1,skipped:p.message}),console.warn(` ! Skipped ${u}: ${p.message}`);continue}a++,i.set(u,{functions:[],arrowFunctions:[],classMethods:[],imports:[],calls:[],methodCalls:[],returnEntries:[],jsxElements:[],callSites:[],apiCalls:[],socketEmits:[],socketListeners:[],rawSocketSends:[],rawSocketTypeChecks:[],routes:[],listeners:[],hadErrors:!0,failed:!0,errorMessage:p.message}),console.warn(` ! Failed to parse ${u}: ${p.message}`)}}return console.log(`Parsed ${i.size} files (${a} failed)`),console.log(` parse cache: ${l} file(s) parsed, ${c} served from cache`),i.cacheStats={parsed:l,cacheHits:c},i.budgetSkips=m,i}function wn(e,t){return`${e}::${t}`}var Er=[{category:"frontend",patterns:["frontend","client","src/components","ui","src/pages","public"]},{category:"backend",patterns:["backend","server","api","realtime-backend"]},{category:"transport",patterns:["websocket","socket","realtime"]},{category:"data",patterns:["redis","database","models","db"]}];function Sn(e){let t=e.toLowerCase().replace(/\\/g,"/");for(let{category:n,patterns:s}of Er)for(let o of s)if(t.includes(o))return n;return"unknown"}import Fo from"node:fs";import ve from"node:path";import kn from"node:fs";import Xe from"node:path";var Il=["index.html","public/index.html","src/index.html"],Fl=/^(build|esbuild|vite\.config|webpack\.config|rollup\.config|bundle)[\w.-]*\.(mjs|cjs|js|ts)$/i;function jl(e){let t=e.replace(/<!--[\s\S]*?-->/g,""),n=[];for(let s of t.matchAll(/<script\b[^>]*?\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)')/gi))n.push(s[1]??s[2]);return n}function Cl(e){let t=[],n=[];try{n=kn.readdirSync(e).filter(s=>Fl.test(s)).sort()}catch{return t}for(let s of n){let o;try{o=kn.readFileSync(Xe.join(e,s),"utf8")}catch{continue}let r=/\boutfile\s*:\s*["'`]([^"'`]+)["'`]/.exec(o)?.[1]??null,i=/\b(?:entryPoints|entry|input)\s*:\s*\[?\s*["'`]([^"'`]+)["'`]/.exec(o)?.[1]??null;i&&t.push({config:s,outfile:r,entry:i})}return t}function Nn(e,t,n=new Set(t.map(s=>Xe.resolve(s)))){for(let s of Il){let o=Xe.join(e,s);if(!kn.existsSync(o))continue;let r;try{r=kn.readFileSync(o,"utf8")}catch{continue}let i=Xe.dirname(o),a=d=>{let m=d.split(/[?#]/)[0];return!m||/^([a-z]+:)?\/\//i.test(m)?null:Xe.resolve(m.startsWith("/")?Xe.join(e,m):Xe.join(i,m))},l=jl(r).map(d=>({s:d,p:a(d)})).filter(d=>d.p);for(let{s:d,p:m}of l)if(n.has(m))return{indexHtml:o,script:d,entry:m,via:"script"};let c=Cl(e);for(let{s:d,p:m}of l)for(let f of c){if(!f.outfile||Xe.resolve(e,f.outfile)!==m)continue;let u=Xe.resolve(e,f.entry);if(n.has(u))return{indexHtml:o,script:d,entry:u,via:`${f.config} (outfile ${f.outfile})`}}}return null}var El=new Set(["test","tests","__tests__","fixtures","__fixtures__","__mocks__","e2e","cypress"]);function Lt(e){let t=String(e).replace(/\\/g,"/").split("/").filter(Boolean);if(!t.length)return!1;for(let n of t.slice(0,-1))if(El.has(n.toLowerCase()))return!0;return/\.(test|spec)\.[^./]+$/i.test(t[t.length-1])}function Pl(e){let t=ve.join(e,"package.json");if(!Fo.existsSync(t))return null;try{return JSON.parse(Fo.readFileSync(t,"utf-8"))}catch{return null}}function Ll(e){return[...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{})]}function Tl(e){let t=!!e.workspaces,n=Object.keys(e.dependencies??{}).length>0,s=!!(e.scripts&&e.scripts.start);return t&&!n&&!s}var Rl=["react","vue","svelte","next","vite","webpack","parcel"],Al=["express","fastify","koa","hapi","socket.io","ws"],Ol=[{deps:["mongodb","mongoose"],label:"MongoDB"},{deps:["redis","ioredis"],label:"Redis"},{deps:["pg","postgres"],label:"PostgreSQL"},{deps:["mysql","mysql2"],label:"MySQL"},{deps:["sqlite3","better-sqlite3"],label:"SQLite"},{deps:["@prisma/client"],label:"Prisma"},{deps:["drizzle-orm"],label:"Drizzle"}];function Ml(e){let t=e.some(s=>Rl.includes(s)),n=e.some(s=>Al.includes(s));return t&&!n?"client":n&&!t||n&&t?"server":"unknown"}function Hl(e){let t=[];for(let{deps:n,label:s}of Ol)n.some(o=>e.includes(o))&&!t.includes(s)&&t.push(s);return t}function Pr(e){let t=new Set(["node_modules",".git","dist","build",".next","coverage"]);try{return Fo.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!t.has(n.name)&&!n.name.startsWith(".")).map(n=>ve.join(e,n.name))}catch{return[]}}function Lr(e,t=null){let n=[e];for(let o of Pr(e)){n.push(o);for(let r of Pr(o))n.push(r)}let s=[];for(let o of n){let r=Pl(o);if(!r||Tl(r))continue;let i=Ll(r);s.push({name:r.name||ve.basename(o),rootPath:o,isRepoRoot:ve.resolve(o)===ve.resolve(e),kind:Ml(i),datastores:Hl(i)})}if(t){let o=new Set(t.map(i=>ve.resolve(i))),r=new Set(s.map(i=>ve.resolve(i.rootPath)));for(let i of n)ve.resolve(i)===ve.resolve(e)||r.has(ve.resolve(i))||Lt(ve.relative(e,i)+"/x")||Nn(i,t,o)&&s.push({name:ve.basename(i),rootPath:i,isRepoRoot:!1,kind:"client",datastores:[],webRoot:!0})}return s}function pt(e,t){let n=null,s=-1;for(let o of t)o.isRepoRoot&&t.length>1&&!o.ownsLeftovers||(e===o.rootPath||e.startsWith(o.rootPath+ve.sep))&&o.rootPath.length>s&&(n=o.name,s=o.rootPath.length);return n}var Dl=5,Bl=.1;function Tr(e,t,n){let s=ve.basename(ve.resolve(n)),o=l=>({name:l,rootPath:n,isRepoRoot:!0,ownsLeftovers:!0,kind:"unknown",datastores:[]});if(!t.length)return{services:e,added:null};if(!e.length)return{services:[o(s)],added:{name:s,reason:"no package.json found: the repo root is the one service",leftover:t.length}};let r=t.filter(l=>!pt(l,e)).length;if(r<Dl||r<Bl*t.length)return{services:e,added:null,leftover:r};let i=e.find(l=>l.isRepoRoot);if(i)return i.ownsLeftovers=!0,{services:e,added:{name:i.name,reason:`${r} of ${t.length} files sit outside every nested package: owned by the root package ${i.name}`,leftover:r}};let a=s;return e.some(l=>l.name.toLowerCase()===a.toLowerCase())&&(a=`${s} (root)`),{services:[...e,o(a)],added:{name:a,reason:`${r} of ${t.length} files sit outside every nested package: owned by a service named after the repo folder`,leftover:r}}}function Rr(e,t=[]){let n=[];for(let[s,o]of e){let r=Sn(s),i=pt(s,t);n.push({id:`${s}::__module_root__`,name:"module root",filePath:s,startLine:0,endLine:Number.MAX_SAFE_INTEGER,category:r,serviceName:i,type:"moduleRoot",bodyHash:o.moduleBodyHash??null});for(let a of o.functions)n.push({id:wn(s,a.name),name:a.name,filePath:s,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:r,serviceName:i,bodyHash:a.bodyHash??null,type:"function"});for(let a of o.arrowFunctions)n.push({id:wn(s,a.name),name:a.name,filePath:s,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:r,serviceName:i,bodyHash:a.bodyHash??null,type:"arrowFunction"});for(let a of o.classMethods)n.push({id:wn(s,`${a.className}.${a.methodName}`),name:a.methodName,className:a.className,filePath:s,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:r,serviceName:i,bodyHash:a.bodyHash??null,type:"classMethod"})}return n}function Ue(e,t){let n=[];for(let r of t.routes??[])r.isInlineHandler&&n.push({item:r,line:r.startLine,key:`route:${String(r.method).toUpperCase()} ${r.path}`});for(let r of t.listeners??[])r.isInlineHandler&&n.push({item:r,line:r.startLine,key:`listener:${r.targetName??"unknown"}.${r.eventName}`});for(let r of t.socketListeners??[])r.isInlineHandler&&n.push({item:r,line:r.startLine,key:`socket:${r.eventName}`});n.sort((r,i)=>r.line-i.line);let s=new Map,o=new Map;for(let{item:r,key:i}of n){let a=(s.get(i)??0)+1;s.set(i,a),o.set(r,`${e}::${i}${a>1?`#${a}`:""}`)}return o}function Ar(e,t=[]){let n=[];for(let[s,o]of e){let r=Sn(s),i=pt(s,t),a=t.find(c=>c.name===i),l=Ue(s,o);for(let c of o.routes??[]){if(!c.isInlineHandler)continue;let d=`${c.method.toUpperCase()} ${c.path}`;n.push({id:l.get(c),name:`${d} (inline handler)`,filePath:s,startLine:c.handlerStartLine??c.startLine,endLine:c.handlerEndLine??c.startLine,category:r,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:c.handlerBodyHash??null,trigger:{type:"route",label:d,resolvedVia:"inline"}})}for(let c of o.listeners??[])c.isInlineHandler&&n.push({id:l.get(c),name:`${c.eventName} (inline handler)`,filePath:s,startLine:c.handlerStartLine??c.startLine,endLine:c.handlerEndLine??c.startLine,category:r,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:c.handlerBodyHash??null,trigger:{type:"listener",label:c.eventName,resolvedVia:"inline"}});if(a?.kind==="server")for(let c of o.socketListeners??[])c.isInlineHandler&&n.push({id:l.get(c),name:`${c.eventName} (inline handler)`,filePath:s,startLine:c.handlerStartLine??c.startLine,endLine:c.handlerEndLine??c.startLine,category:r,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:c.handlerBodyHash??null,trigger:{type:"socketListener",label:c.eventName,resolvedVia:"inline"}})}return n}import Ul from"node:fs";import zl from"node:crypto";var Or=e=>zl.createHash("sha256").update(e).digest("hex");function bn(e,t){return e.map(n=>[t(n),Or(Ul.readFileSync(n))]).sort((n,s)=>n[0]<s[0]?-1:n[0]>s[0]?1:0)}function _n(e){return Or(e.map(([t,n])=>`${t}\0${n}`).join(`
|
|
18
|
-
`))}import jo from"node:path";function $n(e){let t=jo.resolve(e),n=t.split(jo.sep).join("/"),s=[[t.toLowerCase(),t.length,jo.sep],[n.toLowerCase(),n.length,"/"]],o=r=>{if(typeof r!="string")return r;let i=r.toLowerCase();if(i===s[0][0]||i===s[1][0])return".";for(let[a,l,c]of s)if(i.startsWith(a+c)){let d=r.slice(l+1),m=d.indexOf("::");return(m<0?d:d.slice(0,m)).split("\\").join("/")+(m<0?"":d.slice(m))}return r};return{rel:o,repoRoot:n,replacer:(r,i)=>typeof i=="string"?o(i):i,json:(r,i)=>JSON.stringify(r,(a,l)=>typeof l=="string"?o(l):l,i),clone:r=>JSON.parse(JSON.stringify(r,(i,a)=>typeof a=="string"?o(a):a))}}function Mr(e){let t=e.map((s,o)=>({e:s,i:o})).sort((s,o)=>String(s.e.fromNodeId).localeCompare(String(o.e.fromNodeId))||(s.e.line??0)-(o.e.line??0)||(s.e.column??0)-(o.e.column??0)||s.i-o.i),n=new Map;for(let{e:s}of t){let o=s.calleeNameRaw??s.eventName??s.url??"",r=`${s.fromNodeId??"\u2205"} | ${s.callKind??s.type} | ${o}`,i=(n.get(r)??0)+1;n.set(r,i),s.id=`${r} | #${i}`}return e}function Hr(e){let t=new Map;for(let n of e)t.has(n.id)||t.set(n.id,[]),t.get(n.id).push(n);for(let[n,s]of t)s.length<2||(s.sort((o,r)=>o.startLine-r.startLine||o.endLine-r.endLine),s.forEach((o,r)=>{r>0&&(o.id=`${n}#${r+1}`)}));return e}function ue(e,t){let n=null;for(let s of t)s.type!=="moduleRoot"&&e>=s.startLine&&e<=s.endLine&&(!n||s.endLine-s.startLine<n.endLine-n.startLine)&&(n=s);return n||t.find(s=>s.type==="moduleRoot")}function Dr(e,t){let n=[];for(let[o,r]of e){let i=t.filter(a=>a.filePath===o);for(let a of r.calls){let l=ue(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"call",callKind:a.callKind??"call",resolved:!1})}for(let a of r.methodCalls){let l=ue(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.methodName,objectNameRaw:a.objectName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"methodCall",callKind:a.callKind??"methodCall",resolved:!1})}for(let a of r.returnEntries??[]){let l=ue(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.label,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],deferred:a.deferred??!1,type:"returnValue",resolved:!1})}for(let a of r.jsxElements){let l=ue(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,type:"call",callKind:"jsx",resolved:!1})}for(let a of r.callSites??[]){let l=ue(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"callSite",callKind:a.callKind,chainHead:a.chainHead??null,chainHeadCalled:a.chainHeadCalled??!1,ctorName:a.ctorName??null,...a.thisProp?{thisProp:a.thisProp,thisMethod:a.thisMethod}:{},resolved:!1})}for(let a of r.socketEmits){let l=ue(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,eventName:a.eventName,line:a.startLine,type:"socketEmit",resolved:!1})}for(let a of r.rawSocketSends??[]){let l=ue(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,eventName:a.eventName,line:a.startLine,type:"rawSocketSend",resolved:!1})}for(let a of r.apiCalls){let l=ue(a.startLine,i);n.push({fromFileId:o,fromNodeId:l?.id??null,url:a.url,httpMethod:a.method,scope:a.scope,line:a.startLine,type:"apiCall",resolved:!1})}}let s=n.filter(o=>o.type==="apiCall").length;return n}function de(e,t){let n=new Map;for(let s of t)s.filePath===e&&n.set(s.name,s.id);return n}function Jt(e,t,n,s,o=null){if(n.has(e.calleeNameRaw))return{...e,targetNodeId:n.get(e.calleeNameRaw),confidence:.95,matchType:"local",resolved:!0};let r=[...s],i=s.legacySize??r.length,a=([,c])=>{let d=o?o.scopeOf(c):de(c,t);return d.has(e.calleeNameRaw)?{...e,targetNodeId:d.get(e.calleeNameRaw),confidence:.85,matchType:"import",resolved:!0}:null};for(let c=0;c<i;c++){let d=a(r[c]);if(d)return d}let l=o?.bind?.resolveName(e.fromFileId,e.calleeNameRaw);if(l)return{...e,targetNodeId:l.id,confidence:.85,matchType:"import",resolved:!0};for(let c=i;c<r.length;c++){let d=a(r[c]);if(d)return d}return{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function Br(e,t,n=null){let s=n?n.method(e.objectNameRaw,e.calleeNameRaw):t.find(r=>r.type==="classMethod"&&r.className===e.objectNameRaw&&r.name===e.calleeNameRaw);if(s)return{...e,targetNodeId:s.id,confidence:.6,matchType:"methodHeuristic",resolved:!0};let o=n?.bind?.resolveMember(e.fromFileId,e.objectNameRaw,e.calleeNameRaw);return o?{...e,targetNodeId:o.id,confidence:.85,matchType:"import",resolved:!0}:{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function Ur(e){return{...e,targetNodeId:null,confidence:0,matchType:"unresolvedExternal",resolved:!1}}function zr(e,t,n,s,o=null){if(e.callKind==="new"&&e.ctorName){let r=Jt({...e,calleeNameRaw:e.ctorName},t,n,s,o);if(r.resolved)return{...r,calleeNameRaw:e.calleeNameRaw,matchType:r.matchType+"New"};let i=new Set([e.fromFileId,...s.values()]),a=o?o.ctorsOf(e.ctorName).find(l=>i.has(l.filePath)):t.find(l=>l.type==="classMethod"&&l.className===e.ctorName&&l.name==="constructor"&&i.has(l.filePath));return a?{...e,targetNodeId:a.id,confidence:a.filePath===e.fromFileId?.9:.8,matchType:(a.filePath===e.fromFileId?"local":"import")+"New",resolved:!0}:Ur(e)}if(e.callKind==="chainedCall"&&e.chainHead&&e.chainHeadCalled){let r=Jt({...e,calleeNameRaw:e.chainHead},t,n,s,o);if(r.resolved)return{...e,targetNodeId:r.targetNodeId,confidence:r.confidence*.8,matchType:"chainHead",resolved:!0}}return Ur(e)}import Eo from"node:path";import Ye from"node:fs";import q from"node:path";var Jr=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Wl=["index.ts","index.tsx","index.mts","index.cts","index.js","index.jsx","index.mjs","index.cjs"],ql={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]};var Kr=null,Vr=e=>{Kr=e},Xr=()=>Kr,Wr=e=>q.resolve(e);function Kt(e,t){e=q.resolve(e);let n=()=>{try{let i=q.join(e,"package.json");if(!Ye.existsSync(i))return null;let a=JSON.parse(Ye.readFileSync(i,"utf8")).main;if(typeof a!="string")return null;let l=q.resolve(e,a);return t.has(l)?l:Gl(l,t)}catch{return null}},s=q.extname(e);if(s&&t.has(e))return e;let o=ql[s];if(o)for(let i of o){let a=e.slice(0,-s.length)+i;if(t.has(a))return a}for(let i of Jr)if(t.has(e+i))return e+i;let r=n();if(r)return r;for(let i of Wl){let a=q.join(e,i);if(t.has(a))return a}return null}function Gl(e,t){if(q.extname(e)&&t.has(e))return e;for(let s of Jr)if(t.has(e+s))return e+s;return null}var Co=e=>{try{let n=Ye.readFileSync(e,"utf8").replace(/^/,"").replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,(s,o)=>o??"");return JSON.parse(n.replace(/,(\s*[}\]])/g,"$1"))}catch{return null}};function Yr(e,t=new Set){if(t.has(e))return{baseUrl:null,paths:null};t.add(e);let n=Co(e);if(!n)return{baseUrl:null,paths:null};let s=null,o=null,r=n.extends?Array.isArray(n.extends)?n.extends:[n.extends]:[];for(let a of r){if(typeof a!="string"||!a.startsWith("."))continue;let l=q.resolve(q.dirname(e),a);(!Ye.existsSync(l)||Ye.statSync(l).isDirectory())&&(l=Ye.existsSync(l+".json")?l+".json":q.join(l,"tsconfig.json"));let c=Yr(l,t);c.baseUrl&&(s=c.baseUrl),c.paths&&(o=c.paths)}let i=n.compilerOptions??{};if(typeof i.baseUrl=="string"&&(s=q.resolve(q.dirname(e),i.baseUrl)),i.paths&&typeof i.paths=="object"){let a=s??q.dirname(e);o=Object.entries(i.paths).map(([l,c])=>{let d=l.indexOf("*");return{prefix:d<0?l:l.slice(0,d),suffix:d<0?"":l.slice(d+1),wildcard:d>=0,targets:(Array.isArray(c)?c:[]).filter(m=>typeof m=="string").map(m=>q.resolve(a,m))}}).sort((l,c)=>c.prefix.length-l.prefix.length)}return{baseUrl:s,paths:o}}function Jl(e,t){if(t=t.replace(/^\.\//,"").replace(/\/+$/,""),t.startsWith("!"))return[];let n=[],s=o=>{try{return Ye.readdirSync(o,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="node_modules"&&!r.name.startsWith(".")).map(r=>q.join(o,r.name))}catch{return[]}};if(t.endsWith("/**")){let o=q.join(e,t.slice(0,-3)),r=i=>{for(let a of s(i))n.push(a),r(a)};r(o)}else t.endsWith("/*")?n.push(...s(q.join(e,t.slice(0,-2)))):t.includes("*")||n.push(q.join(e,t));return n}function Kl(e){let t=[],s=Co(q.join(e,"package.json"))?.workspaces;Array.isArray(s)?t.push(...s):Array.isArray(s?.packages)&&t.push(...s.packages);try{let o=Ye.readFileSync(q.join(e,"pnpm-workspace.yaml"),"utf8"),r=!1;for(let i of o.split(/\r?\n/)){if(/^packages\s*:/.test(i)){r=!0;continue}if(r){let a=/^\s*-\s*['"]?([^'"#\s]+)['"]?/.exec(i);a?t.push(a[1]):/^\S/.test(i)&&(r=!1)}}}catch{}return t}function qr(e,t){if(e==null)return null;let n=o=>{if(typeof o=="string")return o;if(Array.isArray(o)){for(let r of o){let i=n(r);if(i)return i}return null}if(o&&typeof o=="object"){for(let r of["source","import","module","default","require","node"])if(r in o){let i=n(o[r]);if(i)return i}}return null};if(typeof e=="string"||Array.isArray(e))return t==="."?n(e):null;let s=Object.keys(e);if(!s.some(o=>o.startsWith(".")))return t==="."?n(e):null;if(e[t]!=null)return n(e[t]);for(let o of s){let r=o.indexOf("*");if(r>0&&t.startsWith(o.slice(0,r))&&t.endsWith(o.slice(r+1))){let i=n(e[o]);if(i)return i.replace("*",t.slice(r,t.length-(o.length-r-1)))}}return null}function Zr(e,t,n={}){let s=Wr(e),o=new Set(t),r=new Map,i=f=>{if(r.has(f))return r.get(f);let u=null,p=q.join(f,"tsconfig.json");return Ye.existsSync(p)?u=Yr(p):f!==s&&q.dirname(f)!==f&&f.startsWith(s)&&(u=i(q.dirname(f))),r.set(f,u),u},a=new Map;for(let f of Kl(s))for(let u of Jl(s,f)){let p=Co(q.join(u,"package.json"));p?.name&&!a.has(p.name)&&a.set(p.name,{dir:Wr(u),pkg:p})}let l=[...a.keys()].sort((f,u)=>u.length-f.length),c=(f,u,p)=>{let{dir:h,pkg:v}=a.get(f),g=[],w=S=>{if(!S)return;let k=q.resolve(h,S);g.push(k);let y=q.relative(h,k).split(q.sep);["dist","build","lib","out","esm","cjs"].includes(y[0])&&g.push(q.join(h,"src",...y.slice(1)))};if(u==="."){w(qr(v.exports,"."));for(let S of["source","module","main"])typeof v[S]=="string"&&w(v[S]);g.push(q.join(h,"src","index"),q.join(h,"index"))}else w(qr(v.exports,u)),g.push(q.join(h,u),q.join(h,"src",u));for(let S of g){let k=Kt(S,p);if(k)return k}return null},d=f=>l.find(u=>f===u||f.startsWith(u+"/"))??null,m=(f,u)=>u?.paths?.some(p=>p.wildcard?f.startsWith(p.prefix)&&f.endsWith(p.suffix)&&f.length>=p.prefix.length+p.suffix.length:f===p.prefix)??!1;return{root:s,files:o,packages:a,isInternal(f,u){if(f.startsWith(".")||d(f))return!0;let p=i(q.dirname(u));return!!(m(f,p)||p?.baseUrl&&!f.startsWith("@")&&Kt(q.join(p.baseUrl,f),o))},resolve(f,u,p){if(f.startsWith("."))return Kt(q.resolve(q.dirname(u),f),p);let h=i(q.dirname(u));if(h?.paths&&n.paths!==!1)for(let g of h.paths){let w=null;if(g.wildcard?f.startsWith(g.prefix)&&f.endsWith(g.suffix)&&f.length>=g.prefix.length+g.suffix.length&&(w=f.slice(g.prefix.length,f.length-g.suffix.length)):f===g.prefix&&(w=""),w!=null){for(let S of g.targets){let k=Kt(S.replace("*",w),p);if(k)return k}break}}let v=n.workspaces===!1?null:d(f);if(v){let g=c(v,f===v?".":"./"+f.slice(v.length+1),p);if(g)return g}if(h?.baseUrl&&n.paths!==!1){let g=Kt(q.join(h.baseUrl,f),p);if(g)return g}return null}}}var Gr=new WeakMap;function Qr(e){if(e instanceof Set)return e;let t=Gr.get(e);return t||Gr.set(e,t=new Set(e)),t}function Po(e,t,n){if(!e.startsWith("."))return null;let s=Eo.dirname(t),o=Eo.resolve(s,e),r=[o,...ks().map(i=>`${o}${i}`),...Ns().map(i=>Eo.join(o,i))];for(let i of r)if(n.includes(i))return i;return null}function ze(e,t,n){let s=Po(e,t,n);if(s)return s;let o=Xr();return o?o.resolve(e,t,Qr(n)):null}function Tt(e,t,n){let s=new Map;for(let o of t){let r=Po(o.source,e,n);r&&s.set(o.source,r)}s.legacySize=s.size;for(let o of t){if(s.has(o.source))continue;let r=ze(o.source,e,n);r&&s.set(o.source,r)}return s}function ei(e){let t=new Map,n=new Map,s=new Map;for(let o of e){if(o.type!=="classMethod")continue;let r=o.className+"\0"+o.name;n.has(r)||n.set(r,o),o.name==="constructor"&&(s.has(o.className)||s.set(o.className,[]),s.get(o.className).push(o))}return{scopeOf:o=>{let r=t.get(o);return r||(r=de(o,e),t.set(o,r)),r},method:(o,r)=>n.get(o+"\0"+r),ctorsOf:o=>s.get(o)??[]}}function Rt(e){return e?e.split("?")[0].split("/").map(t=>t.startsWith(":")||/^\d+$/.test(t)?"*":t).join("/"):""}var Vl=new Set(["function","arrowFunction"]);function ti(e,t,n,s){let o=new Map;for(let c of t){let d=o.get(c.filePath);d||o.set(c.filePath,d=[]),d.push(c)}let r=new Set;for(let c of s)c.resolved&&c.fromNodeId&&c.targetNodeId&&r.add(c.fromNodeId+"\0"+c.targetNodeId);let i=(c,d)=>(o.get(c)??[]).find(m=>Vl.has(m.type)&&d(m))??null,a=[];a.argBindings=[];let l=(c,d,m,f,u,p,h)=>{!d||!m||d.id===m.id||r.has(d.id+"\0"+m.id)||a.push({fromFileId:c,fromNodeId:d.id,calleeNameRaw:f,line:u,column:p,branchPath:[],firstArgText:null,deferred:!1,type:"reference",callKind:"reference",targetNodeId:m.id,confidence:h==="local"?.95:.85,matchType:h,resolved:!0})};for(let[c,d]of e){let m=o.get(c);if(m){for(let f of d.refArgs??[]){let u=null,p="local";if(f.b==="fn"?u=i(c,v=>v.name===f.name&&v.startLine===f.declLine):f.b==="import"&&(p="import",(f.ik==="default"||f.ik==="named"||f.ik==="cjs")&&(u=n.nodeForImport(c,f.src,f.ik,f.imp))),!u)continue;let h=ue(f.line,m);l(c,h,u,f.name,f.line,f.column,p),f.callLine!=null&&h&&h.id!==u.id&&a.argBindings.push({file:c,line:f.callLine,column:f.callColumn,targetNodeId:u.id,matchType:p,direct:f.via==="arg"})}for(let f of m){if(f.type!=="inlineHandler")continue;let u=null;for(let p of m)p===f||p.type==="moduleRoot"||p.startLine<=f.startLine&&p.endLine>=f.endLine&&!(p.startLine===f.startLine&&p.endLine===f.endLine)&&(!u||p.endLine-p.startLine<u.endLine-u.startLine)&&(u=p);u??=m.find(p=>p.type==="moduleRoot"),l(c,u,f,f.name,f.startLine,0,"local")}}}return a}function ni(e,t,n,s){let o=new Map,r=new Map;for(let a of e){if(r.set(a.id,a),a.type!=="classMethod")continue;let l=a.filePath+"\0"+a.className+"\0"+a.name,c=o.get(l);c?c.push(a):o.set(l,[a])}let i=(a,l)=>{for(let c of o.keys())if(c.startsWith(a+"\0"+l+"\0"))return!0;return!1};return function(l){let c=r.get(l.fromNodeId);if(!c||c.type!=="classMethod")return null;let d=t.get(l.fromFileId),m=(d?.classProps??[]).find(v=>v.className===c.className&&v.prop===l.thisProp);if(!m)return null;let f=null,u=null,p=(d.importBindings??[]).find(v=>v.local===m.type);if(p){let v=p.kind==="default"||p.kind==="named"?s.resolveImport(l.fromFileId,p.source,p.kind,p.imported):null;v?.local&&v.local!=="default"&&(f=v.file,u=v.local)}else i(l.fromFileId,m.type)&&(f=l.fromFileId,u=m.type);if(!f)return null;let h=o.get(f+"\0"+u+"\0"+l.thisMethod);return!h||h.length!==1?null:{...l,targetNodeId:h[0].id,confidence:.9,matchType:"typedProperty",resolved:!0}}}var Xl=new Set(["function","arrowFunction"]);function In(e,t,n){let s=new Map;for(let d of e){if(!Xl.has(d.type))continue;let m=d.filePath+"\0"+d.name;s.has(m)||s.set(m,d)}let o=new Map,r=(d,m)=>{let f=o.get(d);if(!f){f=new Map;for(let u of t.get(d)?.importBindings??[])f.has(u.local)||f.set(u.local,u);o.set(d,f)}return f.get(m)??null},i=(d,m)=>n(d).get(m)??null;function a(d,m,f=new Set){let u=d+"\0"+m;if(f.has(u))return null;f.add(u);let p=t.get(d)?.exportBindings;if(!p)return null;if(m==="default"){if(p.default)return{file:d,local:p.default==="<anon>"?"default":p.default}}else if(p.named?.[m])return{file:d,local:p.named[m]};for(let h of p.reexports??[]){if(h.exported!==m)continue;let v=i(d,h.source);if(v)return a(v,h.imported,f)}for(let h of p.nsReexports??[]){if(h.exported!==m)continue;let v=i(d,h.source);if(v)return{moduleFile:v}}if(m!=="default")for(let h of p.stars??[]){let v=i(d,h),g=v?a(v,m,f):null;if(g)return g}return null}let l=d=>d?.local?s.get(d.file+"\0"+d.local)??null:null;function c(d,m,f,u){let p=i(d,m);return p?f==="default"?a(p,"default"):f==="named"?a(p,u):{moduleFile:p,cjs:f==="cjs"}:null}return{lookupExport:a,resolveImport:c,nodeForImport(d,m,f,u){let p=c(d,m,f,u);return p?.moduleFile&&p.cjs?l(a(p.moduleFile,"default")):l(p)},resolveName(d,m){let f=r(d,m);return f?this.nodeForImport(d,f.source,f.kind,f.imported):null},resolveMember(d,m,f){let u=r(d,m);if(!u)return null;let p=c(d,u.source,u.kind,u.imported);return p?.moduleFile?l(a(p.moduleFile,f)):null},classForImport(d,m){let f=r(d,m);if(!f)return null;let u=c(d,f.source,f.kind,f.imported);return u?.local?{file:u.file,className:u.local==="default"?null:u.local}:null},bindingFor:r}}function oi(e,t,n,s,o,r,i){let a=[],l=ei(t),c=new Map,d=g=>c.get(g)??Tt(g,n.get(g)?.imports??[],s);l.bind=In(t,n,d);let m=ni(t,n,d,l.bind),f=new Map;for(let g of e)f.has(g.fromFileId)||f.set(g.fromFileId,[]),f.get(g.fromFileId).push(g);for(let[g,w]of f){let S=n.get(g),k=de(g,t),y=Tt(g,S.imports,s);c.set(g,y);for(let x of w)if(x.type==="call")a.push(Jt(x,t,k,y,l));else if(x.type==="methodCall")a.push(Br(x,t,l));else if(x.type==="callSite")a.push((x.thisProp?m(x):null)??zr(x,t,k,y,l));else if(x.type==="returnValue")a.push({...x,targetNodeId:null,confidence:0,matchType:"returnValue",resolved:!1});else if(x.type==="apiCall")if(x.scope==="external")a.push({...x,targetNodeId:null,confidence:null,matchType:"externalService",resolved:!1});else{let b=Rt(x.url),N=o.get(b);N?a.push({...x,targetNodeId:N,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...x,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(x.type==="socketEmit"){let b=r.get(x.eventName);b?a.push({...x,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...x,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(x.type==="rawSocketSend"){let b=i?.get(x.eventName);b?a.push({...x,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...x,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}}let u=ti(n,t,l.bind,a);for(let g of u)a.push(g);let p=new Map;for(let g of a){if(g.resolved||g.line==null||g.type!=="call"&&g.type!=="methodCall"&&g.type!=="callSite")continue;let w=g.fromFileId+" "+g.line+" "+g.column;(p.get(w)??p.set(w,[]).get(w)).push(g)}let h=[...u.argBindings].sort((g,w)=>w.direct-g.direct),v=new Set;for(let g of h){let w=g.file+" "+g.line+" "+g.column;if(v.has(w))continue;let S=(p.get(w)??[]).find(k=>k.fromNodeId!==g.targetNodeId);S&&(v.add(w),Object.assign(S,{targetNodeId:g.targetNodeId,confidence:g.matchType==="local"?.95:.85,matchType:"argument",resolved:!0,viaArgument:!0}))}return a}function si(e){let t=new Map,n=new WeakMap,s=l=>{if(typeof l=="string")return l.length>=20?"s"+l:null;if(l&&typeof l=="object"){let c=n.get(l);if(c===void 0){let d=JSON.stringify(l);c=d.length>=40?"j"+d:"",n.set(l,c)}return c||null}return null};(function l(c){let d=s(c);if(d){let m=t.get(d)??0;if(t.set(d,m+1),m>0)return}if(Array.isArray(c))for(let m of c)l(m);else if(c&&typeof c=="object")for(let m of Object.values(c))l(m)})(e);let o=[],r=new Map,i=l=>{let c=s(l),d=c&&t.get(c)>1;if(d&&r.has(c))return r.get(c);let m;if(typeof l=="string"?m=JSON.stringify(l):Array.isArray(l)?m="["+l.map(i).join(",")+"]":l&&typeof l=="object"?m="{"+Object.entries(l).map(([u,p])=>JSON.stringify(u)+":"+i(p)).join(",")+"}":m=JSON.stringify(l),!d)return m;let f="$"+o.length.toString(36);return o.push(`const ${f}=${m};`),r.set(c,f),f},a=i(e);return`(() => {${o.join(`
|
|
10
|
+
`),!0}function Ee(e){let t=te(e);try{return JSON.parse(Q.readFileSync(t.index,"utf8"))}catch{return{schema:1,nextVersion:1,versions:[]}}}function hu(e,t){let n=te(e);Q.mkdirSync(n.history,{recursive:!0});let r=n.index+"."+process.pid+".tmp";Q.writeFileSync(r,JSON.stringify(t,null,2)),Q.renameSync(r,n.index)}function ht(e,t){let n=Q.readFileSync(ke.join(te(e).history,t.file));return JSON.parse((t.gzip?nc.gunzipSync(n):n).toString("utf8"))}function rc(e,t,n,r,o=fn,{refresh:s=!1,protect:i=[]}={}){Sr=null;let a=te(e);Q.mkdirSync(a.history,{recursive:!0});let c=Ee(e),l=!0,d=n.fingerprint+(l?".json.gz":".json"),f=ke.join(a.history,d);(s||!Q.existsSync(f))&&Q.writeFileSync(f,l?nc.gzipSync(t):t);let u=(fe(e,["status","--porcelain"])||"").split(`
|
|
11
|
+
`).some(N=>N.trim()&&!/\.canopy(\/|$)/.test(N)),h=s?c.versions.pop():null,p={version:h?h.version:c.nextVersion,fingerprint:n.fingerprint,createdAt:new Date().toISOString(),headSha:fe(e,["rev-parse","HEAD"]),headMessage:fe(e,["log","-1","--format=%s"]),dirty:u,counts:r,file:d,gzip:l,bytes:Q.statSync(f).size,sha256:du.createHash("sha256").update(Q.readFileSync(f)).digest("hex"),engineVersion:Vt(),outputFormat:no};c.versions.push(p),h||c.nextVersion++;let m=c.versions[0]?.version,y=N=>N.version===m||i.includes(N.version),g=0,x=0,S=()=>{let N=c.versions.findIndex(($,j)=>!y($)&&j<c.versions.length-1);return N<0?null:c.versions.splice(N,1)[0]};for(;c.versions.length>o&&S();)g++;let k=mu(),v=N=>{try{return Q.statSync(ke.join(a.history,N.file)).size}catch{return N.bytes??0}},w=c.versions.reduce((N,$)=>N+v($),0);for(;w>k&&c.versions.length>pu;){let N=S();if(!N)break;w-=v(N),x++}if(g||x){let N=[];g&&N.push(`${g} old version${g===1?"":"s"} removed (the store keeps the first version, the one you last saw and the newest ${o})`),x&&N.push(`${x} more removed to stay under the size limit of ${Math.round(k/1048576)} MB`),Sr=N.join("; ")}let b=new Set(c.versions.map(N=>N.file));for(let N of Q.readdirSync(a.history))/\.json(\.gz)?$/.test(N)&&N!=="index.json"&&!b.has(N)&&Q.rmSync(ke.join(a.history,N),{force:!0});return hu(e,c),p}function tc(){for(let e of oo)try{Q.rmSync(e,{force:!0})}catch{}oo.clear()}function gu(){if(!ec){ec=!0,process.once("exit",tc);for(let e of["SIGINT","SIGTERM"])process.on(e,()=>{tc(),process.exit(e==="SIGINT"?130:143)})}}function kr(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Nr(e){try{return JSON.parse(Q.readFileSync(e,"utf8"))}catch{return null}}function br(e,t={},n=null){Q.mkdirSync(ke.dirname(e),{recursive:!0});let r=null;for(let o=0;o<3;o++)try{let s=Q.openSync(e,"wx");return Q.writeSync(s,JSON.stringify({pid:process.pid,startedAt:Date.now(),version:n,...t})),Q.closeSync(s),oo.add(e),gu(),r?{ok:!0,removedStale:r}:{ok:!0}}catch(s){if(s.code!=="EEXIST")throw s;let i=Nr(e);if(i&&kr(i.pid)&&i.pid!==process.pid)return{ok:!1,owner:i};let a=0;try{a=Date.now()-Q.statSync(e).mtimeMs}catch{continue}if(!i&&a<2e3)return{ok:!1,owner:null};r={pid:i?.pid??null},Q.rmSync(e,{force:!0})}return{ok:!1,owner:null}}function _r(e){oo.delete(e);try{Q.rmSync(e,{force:!0})}catch{}}function sc(e,t=null,n=null){let r=br(te(e).lock,{},t);return r.ok&&r.removedStale&&n&&n(`removed a stale lock left by a run that stopped (process ${r.removedStale.pid??"unknown"})`),r.ok}var uu,pu,mu,Gv,fn,te,Sr,oc,oo,ec,ic,ac,cc,De=kt(()=>{wr();uu=200,pu=2,mu=()=>{let e=Number(process.env.CANOPY_SNAPSHOT_MAX_MB);return(Number.isFinite(e)&&e>0?e:uu)*1024*1024},Gv=600*1e3,fn=50,te=e=>{let t=ke.join(ke.resolve(e),".canopy");return{root:t,history:ke.join(t,"history"),index:ke.join(t,"history","index.json"),lock:ke.join(t,"sync.lock"),pending:ke.join(t,"sync.pending"),log:ke.join(t,"sync.log")}};Sr=null,oc=()=>Sr;oo=new Set,ec=!1;ic=e=>_r(te(e).lock),ac=e=>{let t=te(e);Q.mkdirSync(t.root,{recursive:!0}),Q.writeFileSync(t.pending,String(Date.now()))},cc=e=>{let t=te(e);return Q.existsSync(t.pending)?(Q.rmSync(t.pending,{force:!0}),!0):!1}});import _e from"node:fs";import rt from"node:path";import dc from"node:crypto";import yu from"node:zlib";function pc(e,t){_e.mkdirSync(rt.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;_e.writeFileSync(n,t),_e.renameSync(n,e)}function gt(e){let t;try{t=_e.readFileSync(uc(e),"utf8")}catch{return null}let n;try{n=JSON.parse(t)}catch{throw new Error("corrupt")}if(!n||typeof n!="object"||n.schemaVersion!==fc||n.checksum!==mc(n))throw new Error("corrupt");return n}function hc(e,t){let n={...t,schemaVersion:fc};return n.checksum=mc(n),pc(uc(e),JSON.stringify(n,null,2)),n}function Ir(e,t){let n=null;try{n=gt(e)}catch{n=null}return n||hc(e,{projectId:dc.randomBytes(8).toString("hex"),firstInstalledAt:new Date().toISOString(),engineFingerprint:t,lastAnalysed:null,lastSeen:null,projectRoot:rt.resolve(e)})}function jr(e,t){let n=gt(e)??Ir(e,t.engineFingerprint??null);return hc(e,{...n,...t})}function so(e){try{return gt(e)?.lastSeen??null}catch{return null}}function gc(e,t,{branch:n=null,engineFingerprint:r=null,now:o=new Date}={}){return t?jr(e,{lastSeen:{version:t.version,fingerprint:t.fingerprint,headSha:t.headSha??null,at:o.toISOString(),branch:n,engineFingerprint:r??t.engineVersion??null}}).lastSeen:null}function yc(e){let t=[];try{gt(e)}catch{t.push("meta.json is damaged")}let n=te(e);if(_e.existsSync(n.index)){let r=null;try{r=JSON.parse(_e.readFileSync(n.index,"utf8"))}catch{t.push("history/index.json is damaged")}r&&!Array.isArray(r.versions)&&t.push("history/index.json has no version list");for(let o of r?.versions??[]){let s=rt.join(n.history,String(o.file??""));if(!o.file||/[\\/]/.test(o.file)||!_e.existsSync(s)){t.push(`snapshot of version ${o.version} is missing`);continue}let i=_e.readFileSync(s);if(o.sha256&&$r(i)!==o.sha256){t.push(`snapshot of version ${o.version} does not match its checksum`);continue}try{JSON.parse((o.gzip?yu.gunzipSync(i):i).toString("utf8"))}catch{t.push(`snapshot of version ${o.version} cannot be read`)}}}return{ok:t.length===0,problems:t}}function vc(e,t=new Date){let n=te(e).root,r=rt.join(n,"state.corrupt-"+t.toISOString().replace(/[:.]/g,"-"));_e.mkdirSync(r,{recursive:!0});for(let o of["meta.json","files.json","history"]){let s=rt.join(n,o);_e.existsSync(s)&&_e.renameSync(s,rt.join(r,o))}return rt.basename(r)}function xc(e,t,n,{full:r=!1}={}){let o={};if(!r)try{let l=JSON.parse(_e.readFileSync(lc(e),"utf8"));l.schema===1&&l.files&&(o=l.files)}catch{o={}}let s={},i=0,a=0,c=t.map(l=>{let d=n(l),f;try{f=_e.statSync(l)}catch{f=null}let u=o[d];if(f&&u&&u[0]===f.size&&u[1]===Math.round(f.mtimeMs)&&typeof u[2]=="string")return s[d]=u,i++,[d,u[2]];let h=$r(_e.readFileSync(l));return a++,f&&(s[d]=[f.size,Math.round(f.mtimeMs),h]),[d,h]}).sort((l,d)=>l[0]<d[0]?-1:l[0]>d[0]?1:0);try{pc(lc(e),JSON.stringify({schema:1,files:s}))}catch{}return{hashes:c,reused:i,rehashed:a}}var fc,$r,uc,lc,mc,un=kt(()=>{De();fc=1,$r=e=>dc.createHash("sha256").update(e).digest("hex"),uc=e=>rt.join(te(e).root,"meta.json"),lc=e=>rt.join(te(e).root,"files.json");mc=e=>{let{checksum:t,...n}=e;return $r(JSON.stringify(n))}});function Ct(e){let t=n=>Array.isArray(n)?n.map(t):n&&typeof n=="object"?Object.fromEntries(Object.keys(n).sort().map(r=>[r,t(n[r])])):n;return JSON.stringify(t(e))}function wc(e){let t=[],n=[],r=[];for(let[i,a]of e.publicGraph){for(let c of a.nodes)t.push({id:c.id,service:i,kind:c.type,name:c.name,filePath:c.filePath,startLine:c.startLine,endLine:c.endLine,bodyHash:c.bodyHash});for(let c of a.edges)n.push({id:c.id,service:i,from:c.fromNodeId,callKind:c.callKind??c.type,calleeNameRaw:c.calleeNameRaw??c.eventName??c.url??null,resolvedTo:c.targetNodeId??null})}let o=new Map;for(let i of e.publicWorkflows){let a=i.steps[0]?.nodeId??null,c=`${i.serviceId} | ${a} | ${i.name}`,l=(o.get(c)??0)+1;o.set(c,l),r.push({id:l>1?`${c} #${l}`:c,service:i.serviceId,tier:i.tier,tierOrigin:i.tierOrigin,entry:a,steps:i.steps.map(d=>d.nodeId)})}t.sort(io(i=>i.service+"\0"+i.id)),n.sort(io(i=>i.service+"\0"+i.id)),r.sort(io(i=>i.id));let s=e.publicCrossServiceEdges.map(i=>({fromService:i.fromService,fromNodeId:i.fromNodeId,toService:i.toService,toNodeId:i.toNodeId,via:i.via,key:i.key??null,confidence:i.confidence??null})).sort(io(i=>[i.fromService,i.fromNodeId,i.toService,i.toNodeId,i.via,i.key].join("\0")));return{schema:1,fingerprint:e.fingerprint,nodes:t,edges:n,workflows:r,crossServiceEdges:s}}var io,ao=kt(()=>{io=e=>(t,n)=>{let r=e(t),o=e(n);return r<o?-1:r>o?1:0}});function Sc(e){let t=new Map;for(let n of e.nodes){let r=t.get(n.id);r?r.services.push(n.service):t.set(n.id,{id:n.id,services:[n.service],kind:n.kind,name:n.name,filePath:n.filePath,bodyHash:n.bodyHash})}for(let n of t.values())n.services.sort();return t}function xu(e){return t=>{if(t==null)return t;if(e.has(t))return e.get(t);for(let[n,r]of e)if(t.startsWith(n+" | "))return r+t.slice(n.length);return t}}function Fr(e,t){let n=a=>a.reduce((c,l)=>c.set(l,(c.get(l)??0)+1),new Map),r=n(e),o=n(t),s=[],i=[];for(let[a,c]of o)for(let l=0;l<c-(r.get(a)??0);l++)s.push(a);for(let[a,c]of r)for(let l=0;l<c-(o.get(a)??0);l++)i.push(a);return{added:s.sort(),removed:i.sort()}}function pn(e,t){let n=Sc(e),r=Sc(t),o=[...r.values()].filter(_=>!n.has(_.id)),s=[...n.values()].filter(_=>!r.has(_.id)),i=[];for(let[_,P]of r){let L=n.get(_);L&&L.bodyHash!==P.bodyHash&&i.push({...Cr(P),from:L.bodyHash,to:P.bodyHash})}let a=[],c=new Map,l=_=>[_.kind,_.name,_.bodyHash].join("\0"),d=new Map;for(let _ of $e(o,P=>P.id)){let P=l(_);d.has(P)||d.set(P,[]),d.get(P).push(_)}let f=[],u=new Set;for(let _ of $e(s,P=>P.id)){let L=(d.get(l(_))??[]).find(z=>!u.has(z.id)&&z.filePath!==_.filePath&&z.id.split("::").pop()===_.id.split("::").pop());L?(u.add(L.id),a.push({kind:_.kind,name:_.name,services:L.services,fromId:_.id,toId:L.id,fromPath:_.filePath,toPath:L.filePath}),c.set(_.id,L.id)):f.push(_)}o=$e(o.filter(_=>!u.has(_.id)),_=>_.id),s=$e(f,_=>_.id);let h=xu(c),p=_=>_.service+"\0"+_.id,m=new Map(e.edges.map(_=>[p({service:_.service,id:h(_.id)}),{..._,id:h(_.id),from:h(_.from),resolvedTo:h(_.resolvedTo)}])),y=new Map(t.edges.map(_=>[p(_),_])),g=_=>({id:_.id,service:_.service,from:_.from,callKind:_.callKind,calleeNameRaw:_.calleeNameRaw,resolvedTo:_.resolvedTo}),x=[],S=[],k=[];for(let[_,P]of y){let L=m.get(_);L?L.resolvedTo!==P.resolvedTo&&k.push({id:P.id,service:P.service,from:P.from,calleeNameRaw:P.calleeNameRaw,fromTarget:L.resolvedTo,toTarget:P.resolvedTo}):x.push(g(P))}for(let[_,P]of m)y.has(_)||S.push(g(P));let v=_=>_.service+"\0"+_.id,w=_=>({..._,id:_.id.replace(_.entry??"\0",h(_.entry)),entry:h(_.entry),steps:_.steps.map(h)}),b=new Map(e.workflows.map(_=>{let P=w(_);return[P.id,P]})),N=new Map(t.workflows.map(_=>[_.id,_])),$={added:[],removed:[],changed:[]},j={added:[],removed:[],changed:[]},O=_=>({id:_.id,service:_.service,tier:_.tier,steps:_.steps.length});for(let[_,P]of N){let L=b.get(_);if(!L){(P.tier==="physical"?$:j).added.push(O(P));continue}let z=Fr(L.steps,P.steps),Re=!z.added.length&&!z.removed.length&&L.steps.join(`
|
|
12
|
+
`)!==P.steps.join(`
|
|
13
|
+
`),je=L.tier!==P.tier?`${L.tier} -> ${P.tier}`:null;if(!z.added.length&&!z.removed.length&&!Re&&!je)continue;let ct={id:_,service:P.service,tier:P.tier,stepsAdded:z.added,stepsRemoved:z.removed,reordered:Re,tierChange:je};(L.tier==="physical"||P.tier==="physical"?$:j).changed.push(ct)}for(let[_,P]of b)N.has(_)||(P.tier==="physical"?$:j).removed.push(O(P));for(let _ of[$,j])for(let P of["added","removed","changed"])_[P]=$e(_[P],L=>L.id);let D=_=>[_.fromService,_.fromNodeId,_.toService,_.toNodeId,_.via,_.key].join(" | "),G=new Map(e.crossServiceEdges.map(_=>[D({..._,fromNodeId:h(_.fromNodeId),toNodeId:h(_.toNodeId)}),{..._,fromNodeId:h(_.fromNodeId),toNodeId:h(_.toNodeId)}])),M=new Map(t.crossServiceEdges.map(_=>[D(_),_])),q=$e([...M].filter(([_])=>!G.has(_)).map(([,_])=>_),D),E=$e([...G].filter(([_])=>!M.has(_)).map(([,_])=>_),D),C=new Map,R=new Map,W=(_,P,L)=>{_.has(P)||_.set(P,new Set),_.get(P).add(L)};for(let _ of s)W(C,_.id,"removed");for(let _ of o)W(R,_.id,"added");for(let _ of i)W(C,_.id,"modified"),W(R,_.id,"modified");for(let _ of a)W(C,_.fromId,"moved"),W(R,_.toId,"moved");let K=[],se=new Set([...b.keys(),...N.keys()]);for(let _ of se){let P=b.get(_),L=N.get(_);if(!(P&&P.tier==="physical"||L&&L.tier==="physical"))continue;let z=new Map;for(let[je,ct]of[[P,C],[L,R]])if(je)for(let Zt of new Set(je.steps))for(let Qt of ct.get(Xe(Zt,je===P,c))??[])z.set(Zt+"\0"+Qt,{node:Zt,why:Qt});let Re=P&&L&&(Fr(P.steps,L.steps).added.length||Fr(P.steps,L.steps).removed.length);z.size&&K.push({workflow:_,service:(L??P).service,status:P?L?"changed":"removed":"new",stepsChanged:!!Re,reasons:$e([...z.values()],je=>je.node+"\0"+je.why)})}function Xe(_,P,L){if(!P)return _;for(let[z,Re]of L)if(Re===_)return z;return _}let ue={schema:1,from:e.fingerprint,to:t.fingerprint,nodes:{added:o.map(Cr),removed:s.map(Cr),modified:$e(i,_=>_.id),moved:$e(a,_=>_.toId)},edges:{added:$e(x,v),removed:$e(S,v),retargeted:$e(k,v)},workflows:{physical:$,guessed:j},crossServiceEdges:{added:q,removed:E},touched:$e(K,_=>_.workflow)};return ue.counts={nodes:{added:o.length,removed:s.length,modified:i.length,moved:a.length},edges:{added:x.length,removed:S.length,retargeted:k.length},physicalWorkflows:{added:$.added.length,removed:$.removed.length,changed:$.changed.length},guessedWorkflows:{added:j.added.length,removed:j.removed.length,changed:j.changed.length},crossServiceEdges:{added:q.length,removed:E.length},touched:K.length,touchedNew:K.filter(_=>_.status==="new").length},ue}function Nc(e,t,n,{limit:r=40}={}){let o=e.counts,s=t?`v${t.version} (${(t.headSha??t.fingerprint).slice(0,7)}${t.headMessage?` ${JSON.stringify(t.headMessage)}`:""})`:"to",i=[];i.push(`${s} \u2190 ${n?"v"+n.version:"from"}: nodes +${o.nodes.added} \u2212${o.nodes.removed} ~${o.nodes.modified} \u21A6${o.nodes.moved} | edges +${o.edges.added} \u2212${o.edges.removed}${o.edges.retargeted?` ~${o.edges.retargeted}`:""} | physical workflows touched: ${o.touched} (${o.touchedNew} new)`);let a=(l,d,f)=>{if(d.length){i.push("",`${l} (${d.length})`);for(let u of d.slice(0,r))i.push(" "+f(u));d.length>r&&i.push(` ... ${d.length-r} more`)}};a("Touched physical workflows",e.touched,l=>`[${l.service}] ${l.workflow.split(" | ").slice(2).join(" | ")} <${l.status}> because: ${l.reasons.slice(0,4).map(d=>`${d.why} ${Ft(d.node)}`).join(", ")}${l.reasons.length>4?`, +${l.reasons.length-4}`:""}`),a("Nodes added",e.nodes.added,l=>`+ ${l.id}`),a("Nodes removed",e.nodes.removed,l=>`- ${l.id}`),a("Nodes modified",e.nodes.modified,l=>`~ ${l.id}`),a("Nodes moved",e.nodes.moved,l=>`\u21A6 ${l.name}: ${l.fromPath} \u2192 ${l.toPath}`),a("Edges added",e.edges.added,l=>`+ [${l.service}] ${Ft(l.from)} \u2192 ${l.calleeNameRaw}${l.resolvedTo?` (resolved to ${Ft(l.resolvedTo)})`:""}`),a("Edges removed",e.edges.removed,l=>`- [${l.service}] ${Ft(l.from)} \u2192 ${l.calleeNameRaw}`),a("Edges retargeted",e.edges.retargeted,l=>`~ [${l.service}] ${Ft(l.from)} \u2192 ${l.calleeNameRaw}: ${Ft(l.fromTarget)||"unresolved"} \u2192 ${Ft(l.toTarget)||"unresolved"}`),a("Physical workflows changed",e.workflows.physical.changed,l=>`~ ${l.id.split(" | ").slice(2).join(" | ")} +${l.stepsAdded.length} \u2212${l.stepsRemoved.length} steps${l.tierChange?`, tier ${l.tierChange}`:""}${l.reordered?", reordered":""}`),a("Physical workflows added",e.workflows.physical.added,l=>`+ ${l.id.split(" | ").slice(2).join(" | ")} (${l.steps} steps)`),a("Physical workflows removed",e.workflows.physical.removed,l=>`- ${l.id.split(" | ").slice(2).join(" | ")}`),a("Cross-service edges added",e.crossServiceEdges.added,l=>`+ ${l.fromService} \u2192 ${l.toService} via ${l.via} ${l.key??""}`),a("Cross-service edges removed",e.crossServiceEdges.removed,l=>`- ${l.fromService} \u2192 ${l.toService} via ${l.via} ${l.key??""}`);let c=o.guessedWorkflows;return c.added+c.removed+c.changed&&i.push("",`Informational (guessed workflows, never counted as changes): +${c.added} \u2212${c.removed} ~${c.changed}`),i.join(`
|
|
14
|
+
`)}var vu,$e,Cr,kc,Ft,Er=kt(()=>{ao();vu=(e,t)=>e<t?-1:e>t?1:0,$e=(e,t)=>e.slice().sort((n,r)=>vu(t(n),t(r)));Cr=e=>({id:e.id,services:e.services,kind:e.kind,name:e.name,filePath:e.filePath});kc=e=>Ct(e),Ft=e=>(e??"").split("::").slice(-2).join("::")});var $c={};jl($c,{UI_VERSIONS:()=>bc,buildSince:()=>uo,buildUiHistory:()=>Tr,describeSince:()=>Lr,historyScript:()=>Rr,writeHistoryJs:()=>Su});import Pr from"node:fs";import fo from"node:path";function _c(e){let t=JSON.parse(JSON.stringify(e));t.truncated={};let n=(r,o)=>{for(let[s,i]of Object.entries(r))Array.isArray(i)&&i.length>co&&(t.truncated[`${o}.${s}`]=i.length,r[s]=i.slice(0,co))};return n(t.nodes,"nodes"),n(t.edges,"edges"),n(t.workflows.physical,"workflows.physical"),n(t.crossServiceEdges,"crossServiceEdges"),t.touched.length>co&&(t.truncated.touched=t.touched.length,t.touched=t.touched.slice(0,co)),t}function uo(e,{cache:t=null}={}){let r=Ee(e).versions;if(!r.length)return null;let o=r[r.length-1],s=so(e),i=s?r.find(u=>u.version===s.version):null,a=!i,c=i??r[0],l={fromVersion:c.version,toVersion:o.version,firstVisit:a,noChanges:!1,at:s?.at??null,commits:null,versionsBetween:r.filter(u=>u.version>c.version&&u.version<=o.version).length,branchNote:null,engineNote:!1,diff:null,baselineGone:!!s&&!i},d=fe(e,["rev-parse","--abbrev-ref","HEAD"]);if(s?.branch&&d&&s.branch!==d&&(l.branchNote=`branch changed from ${s.branch} to ${d}`),c.engineVersion&&o.engineVersion&&c.engineVersion!==o.engineVersion&&(l.engineNote=!0),c.version===o.version)return l.noChanges=!a,l;if(c.headSha&&o.headSha&&c.headSha!==o.headSha){let u=fe(e,["rev-list","--count",`${c.headSha}..${o.headSha}`]);u!==null&&/^\d+$/.test(u)&&(l.commits=Number(u))}let f=`${c.version}:${o.version}:${c.fingerprint}:${o.fingerprint}`;return t&&t.has(f)?l.diff=t.get(f):(l.diff=_c(pn(ht(e,c),ht(e,o))),t&&(t.clear(),t.set(f,l.diff))),l}function Lr(e,t=Date.now()){if(!e)return null;if(e.firstVisit)return e.baselineGone?"Your last visit is no longer stored, so this compares with the first saved version":"First visit: nothing to compare with yet";let n=wu(e.at,t);if(e.noChanges)return`No changes since you last opened Canopy${n?", "+n:""}`;let r=e.commits!=null?` (${e.commits} commit${e.commits===1?"":"s"})`:e.versionsBetween?` (${e.versionsBetween} saved version${e.versionsBetween===1?"":"s"})`:"",o=e.diff?.counts?.touched;return`Since you last opened Canopy${n?", "+n:""}${r}${o!==void 0?`: ${o} workflow${o===1?"":"s"} touched`:""}`}function Tr(e,{sinceCache:t=null,memo:n=!1}={}){let o=Ee(e).versions.slice(-bc),s=null;if(n)try{let a=Pr.statSync(fo.join(fo.resolve(e),".canopy","history","index.json"));s=`${fo.resolve(e)}|${a.mtimeMs}|${a.size}`}catch{s=null}let i;if(s&&lo.key===s)i=lo.value;else{i={};for(let a=1;a<o.length;a++)i[o[a].version]=_c(pn(ht(e,o[a-1]),ht(e,o[a])));s&&(lo.key=s,lo.value=i)}return{schema:1,versions:o.map(a=>({version:a.version,fingerprint:a.fingerprint,createdAt:a.createdAt,headSha:a.headSha,headMessage:a.headMessage,dirty:a.dirty,counts:a.counts})),diffs:i,since:uo(e,{cache:t})}}function Rr(e,t={}){return`const canopyHistory = ${Ct(Tr(e,{memo:!0,...t}))};`}function Su(e,t){Pr.mkdirSync(t,{recursive:!0}),Pr.writeFileSync(fo.join(t,"history.js"),`const canopyHistory = ${Ct(Tr(e))};`)}var bc,co,wu,lo,po=kt(()=>{De();un();Er();ao();bc=20,co=200;wu=(e,t=Date.now())=>{if(!e)return null;let n=Math.max(0,Math.round((t-Date.parse(e))/6e4));if(n<2)return"a moment ago";if(n<90)return`${n} minutes ago`;let r=Math.round(n/60);if(r<24)return`${r} hours ago`;let o=Math.round(r/24);return o===1?"yesterday":`${o} days ago`};lo={key:null,value:null}});import es from"node:fs";import vn from"node:path";import yt from"node:fs";import ku from"node:os";import ye from"node:path";import{fileURLToPath as Ic}from"node:url";import Z from"node:path";import we from"node:fs";import{fileURLToPath as ru,pathToFileURL as su}from"node:url";var Oo=Fl(us(),1);import Ht from"node:fs";import Ce from"node:path";var Ro={javascript:[".js",".jsx",".mjs",".cjs"],typescript:[".ts",".tsx"]},ps=[".ts",".tsx",".mts",".cts"],Zl={javascript:["index.js","index.jsx"],typescript:["index.ts","index.tsx"]};function ms(){return Object.values(Ro).flat()}function hs(){return Object.values(Zl).flat()}var gs=["log","logger","console","debug","trace"];var vs=[".yarn",".pnp","vendor","dist","build","out","coverage",".next",".nuxt",".turbo",".cache","bower_components"],Mo=["node_modules",".git",".canopy",".canopy-cache"],ys=[".vue",".svelte"],Ql=1024*1024,Ao=1e4;function ed(e,t=null){let n=[];function r(o,s){let i=Ce.join(o,".gitignore"),a=(0,Oo.default)().add(s);Ht.existsSync(i)&&a.add(Ht.readFileSync(i,"utf-8"));let c=Ht.readdirSync(o,{withFileTypes:!0});for(let l of c){let d=Ce.join(o,l.name),f=Ce.relative(e,d).split(Ce.sep).join("/");if(!a.ignores(f)&&!(l.isDirectory()&&Mo.includes(l.name))){if(l.isDirectory()&&vs.includes(l.name)){t&&t.excludedDirs.push(d);continue}l.isDirectory()?r(d,a):l.isFile()&&n.push(d)}}}return r(e,(0,Oo.default)()),n}function td(e,t,n=null){return e.filter(r=>!(n?Ce.relative(n,r):r).split(Ce.sep).some(s=>t.includes(s)))}function xs(e,t){let n=0,r;try{r=Ht.readdirSync(e,{withFileTypes:!0})}catch{return 0}for(let o of r)o.isDirectory()?Mo.includes(o.name)||(n+=xs(Ce.join(e,o.name),t)):o.isFile()&&t.has(Ce.extname(o.name))&&n++;return n}var nd=e=>/\.d\.(ts|mts|cts)$/.test(e);function od(e){let t=Ce.basename(e);if(/\.min\.js$/.test(t))return{kind:"minified",reason:"minified (*.min.js)"};if(/\.bundle\.js$/.test(t))return{kind:"bundled",reason:"bundled (*.bundle.js)"};let n;try{n=Ht.statSync(e).size}catch{return null}if(n>Ql)return{kind:"oversized",reason:`oversized (${(n/1048576).toFixed(1)} MB, limit 1 MB)`};if(n>Ao){let r=Ht.readFileSync(e,"utf8"),o=0,s=0;for(;;){let i=r.indexOf(`
|
|
15
|
+
`,o),a=(i<0?r.length:i)-o;if(a>s&&(s=a),i<0)break;o=i+1}if(s>Ao)return{kind:"minified",reason:`line of ${s.toLocaleString("en-US")} characters (limit ${Ao.toLocaleString("en-US")}; minified/bundled)`}}return null}function Ho(e,t=["javascript","typescript"]){let n=t.flatMap(f=>(f==="typescript"?ps:Ro[f])||[]),r={excludedDirs:[]},o=td(ed(e,r),[...vs,...Mo],e),s=f=>Ce.relative(e,f).split(Ce.sep).join("/"),i=[],a=[],c={};for(let f of o){let u=Ce.extname(f);if(n.includes(u)){if(nd(f)){a.push({file:s(f),kind:"declaration",reason:"declaration file"});continue}let h=od(f);h?a.push({file:s(f),kind:h.kind,reason:h.reason}):i.push(f)}else ys.includes(u)&&(c[u]=(c[u]??0)+1)}let l=new Set([...n,...ys]),d={};for(let f of r.excludedDirs){let u=Ce.basename(f),h=d[u]??={dirs:0,files:0};h.dirs++,h.files+=xs(f,l)}return{files:i,skipped:a,unsupported:c,excludedDirs:d}}function $n(e,t=["javascript","typescript"]){return Ho(e,t).files}import rd from"node:path";var Nt=e=>e.toLocaleString("en-US"),In=(e,t,n=t+"s")=>`${Nt(e)} ${e===1?t:n}`,sd={".vue":"Vue",".svelte":"Svelte"},id=[".vue",".svelte"],ad=new Set([".ts",".tsx",".mts",".cts"]);function ws({discovered:e,parseResults:t,scopeFiles:n,rel:r,rootService:o=null}){let s=(t.budgetSkips??[]).map(p=>({path:r(p.filePath),kind:"timeout",reason:p.reason})),i=new Set((t.budgetSkips??[]).map(p=>p.filePath)),a=[...e.skipped.map(p=>({path:p.file,kind:p.kind,reason:p.reason})),...s].sort((p,m)=>p.path<m.path?-1:p.path>m.path?1:0),c=e.files.filter(p=>!i.has(p)),l=c.filter(p=>t.get(p)?.hadErrors).map(r).sort(),d=c.flatMap(p=>(t.get(p)?.warnings??[]).map(m=>({path:r(p),extractor:m.extractor,message:m.message}))).sort((p,m)=>p.path<m.path?-1:p.path>m.path?1:0),f=c.filter(p=>ad.has(rd.extname(p))).length,u={};for(let p of id)e.unsupported[p]&&(u[p]=e.unsupported[p]);let h={};for(let p of a)h[p.kind]=(h[p.kind]??0)+1;return{analyzed:c.length,analyzedJs:c.length-f,analyzedTs:f,inService:c.filter(p=>n.has(p)).length,notAnalyzed:u,notAnalyzedTotal:Object.values(u).reduce((p,m)=>p+m,0),skipped:a,skippedByKind:h,parseErrors:l.length,parseErrorFiles:l.slice(0,50),parseWarnings:d.length,parseWarningList:d.slice(0,50),excludedDirs:e.excludedDirs,rootService:o}}function jn(e){let t=["Coverage"],n=[],r=new Map;for(let[a,c]of Object.entries(e.notAnalyzed)){let l=sd[a];r.has(l)||r.set(l,[]),r.get(l).push(`${Nt(c)} ${a}`)}for(let[a,c]of r)n.push(`${c.join(", ")} files (${a} not supported yet)`);if(e.skipped.length){let a=Object.entries(e.skippedByKind).map(([c,l])=>`${c}: ${l}`).join(", ");n.push(`${Nt(e.skipped.length)} skipped (${a})`)}e.parseErrors&&n.push(`${Nt(e.parseErrors)} with parse errors`),e.parseWarnings&&n.push(`${Nt(e.parseWarnings)} extractor warnings (a construct skipped; the rest of its file was analyzed)`);let o=e.analyzedTs?`${In(e.analyzedJs,"JS file")} and ${In(e.analyzedTs,"TS file")}`:In(e.analyzed,"JS file");t.push(` Analyzed ${o}, ${Nt(e.inService)} of them inside a service${e.analyzed?` (${Math.round(100*e.inService/e.analyzed)}%)`:""}.`),t.push(` Not analyzed: ${n.length?n.join(", "):"nothing"}.`);let s=e.skipped.filter(a=>a.kind!=="declaration");for(let a of s.slice(0,5))t.push(` skipped ${a.path}: ${a.reason}`);s.length>5&&t.push(` ... and ${Nt(s.length-5)} more (full list: meta.coverage.skipped)`);let i=Object.entries(e.excludedDirs);return i.length&&t.push(` Excluded directories: ${i.map(([a,c])=>`${a}/ x${c.dirs} (${In(c.files,"source file")})`).join(", ")}.`),e.rootService&&t.push(` Root service: ${e.rootService.reason}.`),t.join(`
|
|
16
|
+
`)}We();import{Parser as Do,Language as ks}from"web-tree-sitter";import Cn from"node:path";import{fileURLToPath as ld}from"node:url";var hm=Cn.dirname(ld(globalThis.__canopyUrl("src/stage2_parse/initParser.js")));var Bo=new WeakMap,nn=e=>Bo.get(e)??"javascript",ut=e=>nn(e)!=="javascript";function Uo(e){let t=Cn.extname(e);return t===".tsx"?"tsx":t===".ts"||t===".mts"||t===".cts"?"typescript":"javascript"}var dd={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm"};async function Ns(e,t){for(let n of new Set(t.map(Uo))){if(e.grammars.has(n))continue;let r=Cn.join(He("tree-sitter-typescript"),dd[n]),o=await ks.load(r);Bo.set(o,n);let s=new Do;s.setLanguage(o),e.grammars.set(n,{parser:s,language:o})}return e}async function bs(){await Do.init();let e=new Do,t=Cn.join(He("tree-sitter-javascript"),"tree-sitter-javascript.wasm"),n=await ks.load(t);return e.setLanguage(n),Bo.set(n,"javascript"),{parser:e,language:n,grammars:new Map([["javascript",{parser:e,language:n}]])}}import fd from"node:fs";function js(e,t){let n=fd.readFileSync(t,"utf-8"),r=e.parse(n);if(zo(r)||n.includes("\0")){let o=n,s=Is(r);for(let i of ud){let a=i.apply(o);if(a===o)continue;let c=e.parse(a),l=Is(c);if(l<s||i.always){try{r.delete()}catch{}o=a,r=c,s=l}else try{c.delete()}catch{}}o!==n&&(r.canopyOriginalSource=n)}return{tree:r,source:n,filePath:t}}var Cs=e=>e.replace(/[^\n]/g," "),_s=e=>"any"+Cs(e).slice(3),$s=/(?<![&])&(?![&=])/g,ud=[{name:"NUL byte",always:!0,apply:e=>e.replace(/\0/g," ")},{name:"export type * from",apply:e=>e.replace(/\bexport\s+type\s+\*\s*(?:as\s+[\w$]+\s+)?from\s*(["'])[^"'\n]*\1\s*;?/g,Cs)},{name:"typeof import()",apply:e=>e.replace(/typeof\s+import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)*/g,_s)},{name:"import().Type",apply:e=>e.replace(/(?<=[:<,|&?]\s*|\breadonly\s+|\bkeyof\s+|\bextends\s+|\bas\s+)import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)+(?!\s*\()/g,_s)},{name:"generic call signature after a member",apply:e=>e.replace(/(?<=\n[ \t]*)[ ](?=<\s*[A-Za-z_$][\w$]*\s*(?:extends\b|=|,|>\s*\())/g,";")},{name:"& in JSX text",apply:e=>e.replace(/>[^<>{}"'`]*&[^<>{}"'`]*</g,t=>t.replace($s,"+"))},{name:"& in JSX attribute",apply:e=>e.replace(/(\s[\w:-]+=)"([^"\n]*)"/g,(t,n,r)=>n+'"'+r.replace($s,"+")+'"')}];function Is(e){let t=0;return(function n(r){if(r.type==="ERROR"){t++;return}for(let o=0;o<r.childCount;o++)n(r.child(o))})(e.rootNode),t}function zo(e){let t=!1;function n(r){if(r.type==="ERROR"){t=!0;return}for(let o=0;o<r.childCount;o++)n(r.child(o))}return n(e.rootNode),t}import Wo from"node:fs";import on from"node:path";import{fileURLToPath as pd}from"node:url";import{Query as md}from"web-tree-sitter";var Fs=on.dirname(pd(globalThis.__canopyUrl("src/utils/loadQuery.js"))),Es=new WeakMap;function ie(e,t){let n=Es.get(e);if(n||Es.set(e,n=new Map),n.has(t))return n.get(t);let r=on.join(Fs,"..","stage2_parse","queries"),o=Wo.existsSync(r)?r:on.join(Fs,"..","..","dist","queries"),s=nn(e),c=(s==="javascript"?[]:s==="tsx"?["tsx","typescript"]:[s]).map(f=>on.join(o,f,t)).find(f=>Wo.existsSync(f))??on.join(o,t),l=Wo.readFileSync(c,"utf-8"),d=new md(e,l);return n.set(t,d),d}var Ps="javascript",Ls=e=>{Ps=e};var Fn=()=>Ps!=="javascript";var hd=new Set(["non_null_expression","as_expression","satisfies_expression","type_assertion"]);function me(e){for(;e;)if(hd.has(e.type))e=e.type==="type_assertion"?e.namedChild(e.namedChildCount-1):e.namedChild(0);else if(e.type==="parenthesized_expression"&&e.namedChildCount===1){let t=me(e.namedChild(0));if(t===e.namedChild(0))break;e=t}else break;return e}function gd(e){let t=e;for(;t;){t=me(t);for(let n=0;n<t.childCount;n++)if(t.child(n).type==="optional_chain")return!0;if(t.type==="member_expression"||t.type==="subscript_expression")t=t.childForFieldName("object");else if(t.type==="call_expression")t=t.childForFieldName("function");else break}return!1}function pt(e){let t=e.childForFieldName("function"),n=e.childForFieldName("arguments");if(!t)return{kind:"callOfCall",oldShape:!1,nameNode:e};let r=t.type==="identifier",o=t.type==="member_expression"?t.childForFieldName("property"):null,s=t.type==="member_expression"?me(t.childForFieldName("object")):null,i=r||s?.type==="identifier"&&o?.type==="property_identifier",a=o??t;if(Fn()&&e.parent?.type==="decorator")return{kind:"decorator",oldShape:i,nameNode:a};if(n&&n.type==="template_string")return{kind:"taggedTemplate",oldShape:i,nameNode:a};if(gd(e))return{kind:"optionalCall",oldShape:i,nameNode:a};if(r)return{kind:"call",oldShape:i,nameNode:a};if(t.type==="subscript_expression")return{kind:"computed",oldShape:!1,nameNode:t};if(t.type==="member_expression")return s.type==="super"?{kind:"super",oldShape:!1,nameNode:a}:s.type==="this"?{kind:"thisCall",oldShape:!1,nameNode:a}:i?{kind:"methodCall",oldShape:!0,nameNode:a}:{kind:"chainedCall",oldShape:!1,nameNode:a};if(t.type==="import")return{kind:"dynamicImport",oldShape:!1,nameNode:t};if(t.type==="super")return{kind:"super",oldShape:!1,nameNode:t};let c=t;for(;c.type==="parenthesized_expression"&&c.namedChildCount===1;)c=c.namedChild(0);return c.type==="arrow_function"||c.type==="function_expression"||c.type==="function"||c.type==="generator_function"?{kind:"iife",oldShape:!1,nameNode:t}:{kind:"callOfCall",oldShape:!1,nameNode:t}}function Ts(e){let t=e.childForFieldName("name");return t?t.type==="identifier"?/^[A-Z]/.test(t.text)?{kind:"jsx",oldShape:!0,nameNode:t}:null:t.type==="member_expression"||t.type==="nested_identifier"?{kind:"jsxMember",oldShape:!1,nameNode:t}:null:null}function En(e){let t=e;for(;t&&t.type!=="call_expression";)t=t.parent;return t}function Rs(e){let t=e.childForFieldName("function"),n=!1;for(;t;)if(t=me(t),t.type==="member_expression"||t.type==="subscript_expression")t=t.childForFieldName("object");else if(t.type==="call_expression")n=!0,t=t.childForFieldName("function");else if(t.type==="await_expression"||t.type==="parenthesized_expression"||t.type==="non_null_expression")t=t.namedChild(0);else break;return t&&t.type==="identifier"?{head:t.text,called:n}:{head:null,called:!1}}function As(e){let t=e.text.replace(/\s+/g," ");return t.length>120?t.slice(0,117)+"...":t}function Ms(e,t){let o=ie(t,"functionDeclarations.scm").matches(e.rootNode).map(s=>{let i=s.captures.find(l=>l.name==="func_name"),a=s.captures.find(l=>l.name==="func_params"),c=s.captures.find(l=>l.name==="func_declaration");return{name:i.node.text,params:a.node.text,startLine:c.node.startPosition.row+1,endLine:c.node.endPosition.row+1,startIndex:c.node.startIndex,endIndex:c.node.endIndex,node:i.node}});return ut(t)&&o.push(...yd(e,t)),o}function yd(e,t){return ie(t,"defaultExports.scm").matches(e.rootNode).map(n=>{let r=n.captures.find(s=>s.name==="func_declaration").node;return{name:"default",params:n.captures.find(s=>s.name==="func_params").node.text,startLine:r.startPosition.row+1,endLine:r.endPosition.row+1,startIndex:r.startIndex,endIndex:r.endIndex,node:r}})}function Hs(e,t){return ie(t,"arrowFunctions.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(c=>c.name==="func_name"),i=o.captures.find(c=>c.name==="func_params"),a=o.captures.find(c=>c.name==="func_declaration");return{name:s.node.text,params:i.node.text,startLine:a.node.startPosition.row+1,endLine:a.node.endPosition.row+1,startIndex:a.node.startIndex,endIndex:a.node.endIndex,node:s.node}})}function Ds(e,t){let r=ie(t,"classMethods.scm").matches(e.rootNode),o=ut(t);return r.map(s=>{let i=s.captures.find(f=>f.name==="class_name"),a=s.captures.find(f=>f.name==="method_name"),c=s.captures.find(f=>f.name==="method_params"),l=s.captures.find(f=>f.name==="method_declaration"),d=l.node;if(o)for(let f=d.previousNamedSibling;f&&f.type==="decorator";f=f.previousNamedSibling)d=f;return{className:i?i.node.text:"default",methodName:a.node.text,params:c.node.text,startLine:d.startPosition.row+1,endLine:l.node.endPosition.row+1,startIndex:d.startIndex,endIndex:l.node.endIndex,node:a.node}})}function Bs(e,t){let r=ie(t,"imports.scm").matches(e.rootNode),o=ut(t);return r.filter(s=>!(o&&vd(s.captures[0].node))).map(s=>{let i=s.captures[0].node;return{source:i.text,startLine:i.startPosition.row+1}})}function vd(e){let t=e;for(;t&&t.type!=="import_statement";)t=t.parent;if(!t)return!1;if(t.children.some(s=>s.type==="type"))return!0;let n=t.namedChildren.find(s=>s.type==="import_clause");if(!n)return!1;let r=n.namedChildren;if(r.length!==1||r[0].type!=="named_imports")return!1;let o=r[0].namedChildren.filter(s=>s.type==="import_specifier");return o.length>0&&o.every(s=>s.children.some(i=>i.type==="type"))}function rn(e){let t=e;for(;t&&t.type!=="call_expression"&&t.type!=="new_expression";)t=t.parent;if(!t)return null;let n=t.childForFieldName("arguments");if(!n)return null;let r=n.namedChildren?.[0];return!r||r.type==="arrow_function"||r.type==="function_expression"?null:r.text}var xd=/^(addEventListener|removeEventListener|on|once|postMessage|onmessage|subscribe)$/i;function Bt(e){let t=e;for(;t.parent;){let n=t.parent;if(n.type==="arrow_function"||n.type==="function_expression"){let r=n.parent;if(r&&(r.type==="variable_declarator"||r.type==="public_field_definition"))break;if(r&&r.type==="return_statement")return!0;if(r&&r.type==="arguments"&&r.parent?.type==="call_expression"){let o=r.parent.childForFieldName("function"),s=o?.type==="member_expression"?o.childForFieldName("property")?.text:o?.text;if(s&&xd.test(s))return!0}}else if(n.type==="function_declaration"||n.type==="method_definition")break;t=n}return!1}function Us(e,t){return ie(t,"callExpressions.scm").matches(e.rootNode).map(o=>{let s=o.captures[0].node;return{calleeName:s.text,startLine:s.startPosition.row+1,startColumn:s.startPosition.column,branchPath:Ut(s),firstArgText:rn(s),deferred:Bt(s),callKind:pt(En(s)).kind}})}function zs(e,t){return ut(t)?wd(e):ie(t,"methodCalls.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(a=>a.name==="object_name"),i=o.captures.find(a=>a.name==="method_name");return{objectName:s.node.text,methodName:i.node.text,startLine:i.node.startPosition.row+1,startColumn:i.node.startPosition.column,firstArgText:rn(i.node),branchPath:Ut(i.node),deferred:Bt(i.node),callKind:pt(En(i.node)).kind}})}function wd(e){let t=[];for(let n of e.rootNode.descendantsOfType("call_expression")){let r=n.childForFieldName("function");if(!r||r.type!=="member_expression")continue;let o=me(r.childForFieldName("object")),s=r.childForFieldName("property");!o||o.type!=="identifier"||!s||s.type!=="property_identifier"||t.push({objectName:o.text,methodName:s.text,startLine:s.startPosition.row+1,startColumn:s.startPosition.column,firstArgText:rn(s),branchPath:Ut(s),deferred:Bt(s),callKind:pt(En(s)).kind})}return t}function Sd(e){if(!e)return"return";if(e.type==="object"){let t=e.namedChildren.filter(r=>r.type==="pair"),n=t.find(r=>r.childForFieldName("key")?.text?.replace(/^['"]|['"]$/g,"")==="type")??t.find(r=>r.childForFieldName("key")?.text?.replace(/^['"]|['"]$/g,"")==="entity");if(n){let r=n.childForFieldName("key"),o=n.childForFieldName("value");return`return { ${r.text}: ${o.text} }`}}return"return "+e.text.split(/\r?\n/)[0].trim()}function Ws(e,t){return ie(t,"returns.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(c=>c.name==="return_statement"),i=o.captures.find(c=>c.name==="return_value"),a=s.node;return{label:Sd(i?.node),startLine:a.startPosition.row+1,startColumn:a.startPosition.column,branchPath:Ut(a),deferred:Bt(a)}})}var kd=new Set(["function_declaration","arrow_function","function_expression","method_definition"]);function Pn(e,t){return!(!t||e.row<t.startPosition.row||e.row>t.endPosition.row||e.row===t.startPosition.row&&e.column<t.startPosition.column||e.row===t.endPosition.row&&e.column>t.endPosition.column)}function Ut(e){let t=[],n=e,r=e.startPosition;for(;n.parent;){let o=n.parent;if(kd.has(o.type))break;if(o.type==="if_statement"){let s=o.childForFieldName("condition"),i=o.childForFieldName("consequence"),a=o.childForFieldName("alternative");Pn(r,i)?t.push({type:"if",conditionText:s?s.text:"",conditionLine:(s??o).startPosition.row+1,outcome:"true"}):Pn(r,a)&&t.push({type:"if",conditionText:s?s.text:"",conditionLine:(s??o).startPosition.row+1,outcome:"false"})}else if(o.type==="switch_case"||o.type==="switch_default"){let s=o.parent,i=s&&s.type==="switch_body"?s.parent:null;if(i){let a=i.childForFieldName("value"),c=o.childForFieldName("value");t.push({type:"switch",conditionText:a?a.text:"",conditionLine:(a??i).startPosition.row+1,outcome:o.type==="switch_default"?"default":c?c.text:"case"})}}else if(o.type==="try_statement"){let s=o.childForFieldName("handler"),i=o.childForFieldName("finalizer"),a="try";Pn(r,s)?a="catch":Pn(r,i)&&(a="finally"),t.push({type:"try",conditionText:"try / catch",conditionLine:o.startPosition.row+1,outcome:a})}n=o}return t.reverse()}function Gs(e,t){return ie(t,"exports.scm").matches(e.rootNode).map(r=>r.captures[0].node.text)}var Os=new WeakMap;function Nd(e,t){let n=Os.get(e);return n||(n=ie(t,"returns.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(a=>a.name==="return_statement"),i=o.captures.find(a=>a.name==="return_value");return{stmtNode:s.node,valueNode:i?.node}}),Os.set(e,n)),n}function qs(e,t,n){return Nd(e,t).filter(r=>r.stmtNode.startPosition.row+1>=n.startLine&&r.stmtNode.endPosition.row+1<=n.endLine).map(r=>({shape:bd(r.valueNode),condition:_d(r.stmtNode,n),line:r.stmtNode.startPosition.row+1}))}function bd(e){if(!e)return"nothing";switch(e.type){case"true":case"false":return"boolean";case"number":return"number";case"string":return"string";case"null":return"null";case"identifier":return`variable (${e.text})`;case"object":return"object";case"array":return"array";case"call_expression":return`result of ${e.text.split("(")[0]}()`;case"binary_expression":return"boolean (comparison)";case"ternary_expression":return"conditional value";default:return"expression"}}function _d(e,t){let n=e.parent;for(;n;){if(n.type==="if_statement"){let r=n.childForFieldName("condition");if(r)return r.text}n=n.parent}return null}function Js(e,t){return nn(t)==="typescript"?[]:ie(t,"jsxElements.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(i=>i.name==="jsx_tag");return{calleeName:s.node.text,startLine:s.node.startPosition.row+1}}).filter(o=>/^[A-Z]/.test(o.calleeName))}function Vs(e,t){return ie(t,"fetchApiCalls.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(l=>l.name==="url"),i=o.captures.find(l=>l.name==="http_method"),a=s.node.text,c=/^https?:\/\//.test(a)?"external":"internal";return{url:a,method:i?.node.text??"get",startLine:s.node.startPosition.row+1,scope:c}})}function Ys(e,t){return ie(t,"socketEmit.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(i=>i.name==="event_name");return{eventName:s.node.text,startLine:s.node.startPosition.row+1}})}function Ks(e,t){return ie(t,"rawSocketSend.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(i=>i.name==="event_name");return{eventName:s.node.text,startLine:s.node.startPosition.row+1}})}function Xs(e,t){return ie(t,"rawSocketTypeCheck.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(i=>i.name==="event_name");return{eventName:s.node.text,startLine:s.node.startPosition.row+1}})}function Zs(e,t){return ie(t,"socketOn.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(c=>c.name==="event_name"),i=o.captures.find(c=>c.name==="handler_ref"),a=o.captures.find(c=>c.name==="handler_inline");return{eventName:s.node.text,startLine:s.node.startPosition.row+1,handlerName:i?i.node.text:null,isInlineHandler:!!a,handlerStartLine:a?a.node.startPosition.row+1:null,handlerEndLine:a?a.node.endPosition.row+1:null,handlerStartIndex:a?a.node.startIndex:null,handlerEndIndex:a?a.node.endIndex:null}})}function Qs(e){let t=e.rootNode.descendantsOfType(["call_expression","new_expression","jsx_opening_element","jsx_self_closing_element",...Fn()?["decorator"]:[]]),n=[];for(let r of t){let o,s,i,a=null,c=null,l=!1,d=null,f=null;if(r.type==="new_expression"){if(i=r.childForFieldName("constructor"),!i)continue;o="new",s=i,a=i.type==="identifier"?i.text:null;let h=r.childForFieldName("arguments")?.namedChildren?.[0];d=h&&h.type!=="arrow_function"&&h.type!=="function_expression"?h.text:null}else if(r.type==="decorator"){let u=r.namedChild(0);if(!u||u.type==="call_expression")continue;o="decorator",s=u.type==="member_expression"?u.childForFieldName("property")??u:u,i=u}else if(r.type==="call_expression"){let u=pt(r);if(u.oldShape)continue;if(o=u.kind,s=u.nameNode,i=r.childForFieldName("function")??r,o==="chainedCall"){let h=Rs(r);c=h.head,l=h.called;let p=r.childForFieldName("function"),m=p?.type==="member_expression"?me(p.childForFieldName("object")):null;m?.type==="member_expression"&&me(m.childForFieldName("object"))?.type==="this"&&m.childForFieldName("property")?.type==="property_identifier"&&p.childForFieldName("property")&&(f={thisProp:m.childForFieldName("property").text,thisMethod:p.childForFieldName("property").text})}d=rn(s)}else{let u=Ts(r);if(!u||u.oldShape)continue;o=u.kind,s=u.nameNode,i=u.nameNode}n.push({callKind:o,calleeName:As(i),startLine:s.startPosition.row+1,startColumn:s.startPosition.column,branchPath:Ut(s),firstArgText:d,deferred:Bt(s),chainHead:c,chainHeadCalled:l,ctorName:a,...f??{}})}return n.sort((r,o)=>r.startLine-o.startLine||r.startColumn-o.startColumn)}var Go=new Set(["get","post","put","patch","delete","head","options"]),qo=new Set(["axios","ky","got","superagent","$http"]),$d=new Set(["function_declaration","function_expression","function","arrow_function","method_definition","generator_function_declaration","generator_function"]),Id=new Set(["WebSocket","ReconnectingWebSocket","SockJS","W3CWebSocket"]),Jo=/^(ws|socket|sock|websocket|webSocket|wsClient|socketRef|wsRef|[A-Za-z]+Socket|[A-Za-z]+Ws|[A-Za-z]+WebSocket)$/,oe=e=>{for(;e&&(e.type==="parenthesized_expression"||e.type==="as_expression"||e.type==="non_null_expression"||e.type==="await_expression"||e.type==="satisfies_expression"||e.type==="type_assertion")&&(e=e.namedChildren.find(t=>t.type!=="type_annotation"&&t.type!=="predefined_type"&&!/_type$/.test(t.type))??e.namedChildren[0],!!e););return e},sn=e=>e.namedChildren.length?e.namedChildren.filter(t=>t.type==="string_fragment"||t.type==="escape_sequence").map(t=>t.text).join(""):e.text.slice(1,-1);function zt(e){for(let t=e.parent;t;t=t.parent)if($d.has(t.type))return t;return null}function ei(e){if(!e)return null;let t=e.childForFieldName("name")?.text??null;if(!t&&e.parent){let o=e.parent;o.type==="variable_declarator"?t=o.childForFieldName("name")?.text??null:o.type==="assignment_expression"?t=o.childForFieldName("left")?.text??null:o.type==="pair"&&(t=o.childForFieldName("key")?.text??null)}let n=[],r=e.childForFieldName("parameters");if(r)r.namedChildren.forEach((o,s)=>{let i=o.type==="identifier"?o:o.type==="assignment_pattern"?o.childForFieldName("left"):o.type==="required_parameter"||o.type==="optional_parameter"?o.childForFieldName("pattern")??o.namedChildren[0]:null;n[s]=i&&i.type==="identifier"?i.text:null});else{let o=e.childForFieldName("parameter");o&&o.type==="identifier"&&(n[0]=o.text)}return{name:t,params:n}}function ti(e){let t=e.rootNode,n={httpCalls:[],pathCallsites:[],httpInstances:[],wsClients:[],wsServers:[],wsSends:[],wsServerSends:[],listens:[],wsReceivers:[]},r=new Map;for(let h of t.descendantsOfType("variable_declarator")){let p=h.childForFieldName("name"),m=h.childForFieldName("value");if(!p||p.type!=="identifier"||!m)continue;(r.get(p.text)??r.set(p.text,[]).get(p.text)).push({value:m,fn:zt(h)})}let o=(h,p)=>{let m=r.get(h);if(!m)return null;for(let g=zt(p);g;g=zt(g)){let x=m.filter(S=>S.fn&&S.fn.id===g.id);if(x.length===1)return x[0].value}let y=m.filter(g=>!g.fn);return y.length===1?y[0].value:m.length===1?m[0].value:null},s=(h,p)=>{for(let m=zt(p);m;m=zt(m)){let g=ei(m).params.indexOf(h);if(g>=0)return g}return-1};function i(h,p=0){if(h=oe(h),!h)return[{t:"ref",name:""}];switch(h.type){case"string":return[{t:"lit",v:sn(h)}];case"template_string":{let m=[];for(let y of h.namedChildren)y.type==="string_fragment"||y.type==="escape_sequence"?m.push({t:"lit",v:y.text}):y.type==="template_substitution"&&m.push(...i(y.namedChildren[0],p+1));return m.length?m:[{t:"lit",v:""}]}case"number":return[{t:"lit",v:h.text}];case"binary_expression":{let m=h.childForFieldName("operator")?.text;if(m==="||"||m==="??"){let y=i(h.childForFieldName("left"),p+1);if(y.length===1&&y[0].t==="env")return[{...y[0],fallback:i(h.childForFieldName("right"),p+1)}]}return m!=="+"?[{t:"ref",name:h.text.slice(0,60)}]:[...i(h.childForFieldName("left"),p+1),...i(h.childForFieldName("right"),p+1)]}case"shorthand_property_identifier":case"identifier":{let m=h.text,y=s(m,h);if(y>=0)return[{t:"param",name:m,index:y}];if(p<4){let g=o(m,h);if(g&&g.id!==h.id)return i(g,p+1)}return[{t:"ref",name:m}]}case"member_expression":{let m=h.text,y=/^(?:process\.env|import\.meta\.env)\.([A-Za-z0-9_$]+)$/.exec(m)??/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(m);return y?[{t:"env",name:y[1]}]:[{t:"ref",name:m.slice(0,60)}]}case"subscript_expression":{let m=/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(h.text);return m?[{t:"env",name:m[1]}]:[{t:"ref",name:h.text.slice(0,60)}]}case"call_expression":{let m=h.childForFieldName("function")?.text,y=h.childForFieldName("arguments")?.namedChildren[0];if(y&&(m==="encodeURIComponent"||m==="String"||m==="encodeURI"))return i(y,p+1);let g=oe(h.childForFieldName("function"));if(g&&g.type==="member_expression"&&/^(replace|replaceAll|trim|trimEnd|trimStart|toString|toLowerCase)$/.test(g.childForFieldName("property")?.text??"")){let x=g.childForFieldName("object");if(x){let S=i(x,p+1);if(S.length&&S.every(k=>k.t!=="ref"))return S}}return[{t:"ref",name:h.text.slice(0,60)}]}default:return[{t:"ref",name:h.text.slice(0,60)}]}}let a=(h,p)=>{if(h=oe(h),!(!h||h.type!=="object")){for(let m of h.namedChildren)if(m.type==="pair"){let y=m.childForFieldName("key");if((y?y.type==="string"?sn(y):y.text:null)===p)return m.childForFieldName("value")}else if(m.type==="shorthand_property_identifier"&&m.text===p)return m}},c=h=>h.childForFieldName("arguments")?.namedChildren.filter(p=>p.type!=="comment")??[],l=h=>{if(!h)return null;let p=i(h);return p.length===1&&p[0].t==="lit"?p[0].v.toUpperCase():p.length===1&&p[0].t==="param"?{param:p[0].index}:"?"},d=(h,p,m,y)=>({client:h,method:p,parts:m,line:y.startPosition.row+1,fn:ei(zt(y))});for(let h of t.descendantsOfType("variable_declarator")){let p=h.childForFieldName("name"),m=oe(h.childForFieldName("value"));if(!p||p.type!=="identifier"||!m||m.type!=="call_expression")continue;let y=oe(m.childForFieldName("function"));if(!y||y.type!=="member_expression")continue;let g=y.childForFieldName("object")?.text,x=y.childForFieldName("property")?.text;if(!(qo.has(g)&&(x==="create"||x==="extend")))continue;let S=c(m)[0],k=a(S,"baseURL")??a(S,"baseUrl")??a(S,"prefixUrl")??a(S,"prefix_url");n.httpInstances.push({name:p.text,parts:k?i(k):[],line:h.startPosition.row+1})}let f=new Set(n.httpInstances.map(h=>h.name));for(let h of t.descendantsOfType("call_expression")){let p=oe(h.childForFieldName("function"));if(!p)continue;let m=c(h),y=!1;if(p.type==="identifier"){let g=p.text;if(g==="fetch"&&m[0]){let x=oe(m[0]);if(x&&x.type==="new_expression")continue;let S=a(m[1],"method");n.httpCalls.push(d("fetch",S?l(S):m[1]&&oe(m[1])?.type!=="object"?"?":"GET",i(m[0]),h)),y=!0}else if((qo.has(g)||f.has(g))&&m[0]){let x=oe(m[0]);if(x&&x.type==="object"){let S=a(x,"url");if(S){let k=a(x,"baseURL");n.httpCalls.push(d(f.has(g)?"inst:"+g:g,l(a(x,"method"))??"GET",[...k?i(k):[],...i(S)],h)),y=!0}}else n.httpCalls.push(d(f.has(g)?"inst:"+g:g,m[1]&&a(m[1],"method")?l(a(m[1],"method")):"GET",i(m[0]),h)),y=!0}else g==="io"&&m[0]&&(n.wsClients.push({client:"io",parts:i(m[0]),line:h.startPosition.row+1}),y=!0)}else if(p.type==="member_expression"){let x=p.childForFieldName("object")?.text??"",S=p.childForFieldName("property")?.text??"",k=qo.has(x)||f.has(x);if(k&&Go.has(S)&&m[0])n.httpCalls.push(d(f.has(x)?"inst:"+x:x,S.toUpperCase(),i(m[0]),h)),y=!0;else if(!k&&Go.has(S)&&/^[A-Za-z_$][\w$]*$/.test(x)&&m[0]&&(oe(m[0])?.type==="string"||oe(m[0])?.type==="template_string")){let v=i(m[0]);v[0]?.t==="lit"&&(v[0].v.startsWith("/")||/^https?:\/\//.test(v[0].v))&&(n.httpCalls.push(d("obj:"+x,S.toUpperCase(),v,h)),y=!0)}else if(k&&S==="request"&&m[0]){let v=a(m[0],"url");if(v){let w=a(m[0],"baseURL");n.httpCalls.push(d(f.has(x)?"inst:"+x:x,l(a(m[0],"method"))??"GET",[...w?i(w):[],...i(v)],h)),y=!0}}else if(S==="open"&&m.length>=2&&oe(m[0])?.type==="string"&&/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/i.test(sn(oe(m[0]))))n.httpCalls.push(d("xhr",sn(oe(m[0])).toUpperCase(),i(m[1]),h)),y=!0;else if(x==="io"&&S==="connect"&&m[0])n.wsClients.push({client:"io",parts:i(m[0]),line:h.startPosition.row+1}),y=!0;else if(S==="listen"&&m[0]){let v=oe(m[0]),w=v&&v.type==="object"?a(v,"port"):v;w&&n.listens.push({parts:i(w),line:h.startPosition.row+1}),y=!0}else if(S==="send"&&/^(client|conn|connection|peer)$/.test(x.replace(/^this./,"").split(".").pop())&&m[0]){let v=oe(m[0]),w=!1;if(v&&v.type==="call_expression"&&v.childForFieldName("function")?.text==="JSON.stringify"){let b=c(v)[0];w=!!(b&&(a(b,"type")||a(b,"event"))&&oe(a(b,"type")??a(b,"event"))?.type==="string")}w||n.wsServerSends.push({recv:x,line:h.startPosition.row+1}),y=!0}else if(S==="send"&&Jo.test(x.replace(/^this\./,"").replace(/\.current$/,"").split(".").pop())){let v=m[0]?oe(m[0]):null,w=!1;if(v&&v.type==="call_expression"&&v.childForFieldName("function")?.text==="JSON.stringify"){let b=c(v)[0];w=!!(b&&(a(b,"type")||a(b,"event"))&&oe(a(b,"type")??a(b,"event"))?.type==="string")}w||n.wsSends.push({recv:x,line:h.startPosition.row+1}),y=!0}}if(!y){let g=null;if(p.type==="identifier"?g=p.text:p.type==="member_expression"&&(g=p.childForFieldName("property")?.text??null),!g||Go.has(g)||m.length===0||m.length>6)continue;let x=[],S=!1;m.slice(0,5).forEach((k,v)=>{let w=oe(k);if(!w||w.type!=="string"&&w.type!=="template_string")return;let b=i(w);x.push({i:v,parts:b});let N=b[0];N&&N.t==="lit"&&(N.v.startsWith("/")||/^https?:\/\//.test(N.v))&&N.v.length>1&&(S=!0)}),S&&n.pathCallsites.push({callee:g,args:x,line:h.startPosition.row+1})}}let u=h=>h.replace(/^this./,"").replace(/.current$/,"").split(".").pop();for(let h of t.descendantsOfType("assignment_expression")){let p=h.childForFieldName("left");if(!p||p.type!=="member_expression"||p.childForFieldName("property")?.text!=="onmessage"||!Jo.test(u(p.childForFieldName("object")?.text??"")))continue;let m=oe(h.childForFieldName("right"));n.wsReceivers.push({line:h.startPosition.row+1,handlerName:m&&m.type==="identifier"?m.text:null})}for(let h of t.descendantsOfType("call_expression")){let p=oe(h.childForFieldName("function"));if(!p||p.type!=="member_expression"||p.childForFieldName("property")?.text!=="addEventListener")continue;let m=c(h),y=m[0]&&oe(m[0]);if(!y||y.type!=="string"||sn(y)!=="message"||!Jo.test(u(p.childForFieldName("object")?.text??"")))continue;let g=m[1]&&oe(m[1]);n.wsReceivers.push({line:h.startPosition.row+1,handlerName:g&&g.type==="identifier"?g.text:null})}for(let h of t.descendantsOfType("new_expression")){let p=oe(h.childForFieldName("constructor"));if(!p)continue;let m=p.text,y=c(h);if(Id.has(m)&&y[0])n.wsClients.push({client:m,parts:i(y[0]),line:h.startPosition.row+1});else if(/^(WebSocketServer|WebSocket\.Server|WebSocket\.WebSocketServer|ws\.Server|ws\.WebSocketServer|Server)$/.test(m)){if(m==="Server"&&!/socket\.io|socketio/i.test(e.rootNode.text.slice(0,4e3)+""))continue;let g=a(y.find(x=>oe(x)?.type==="object"),"path");n.wsServers.push({path:g?i(g):null,line:h.startPosition.row+1})}}return n}var jd=new Set(["function_declaration","generator_function_declaration","function_expression","generator_function","arrow_function","method_definition"]),Cd=new Set(["arrow_function","function_expression","generator_function"]);function Qe(e,t){if(e)switch(e.type){case"identifier":case"shorthand_property_identifier_pattern":t.push(e.text);return;case"assignment_pattern":Qe(e.childForFieldName("left"),t);return;case"rest_pattern":case"object_pattern":case"array_pattern":case"pair_pattern":case"required_parameter":case"optional_parameter":for(let n of e.namedChildren)Qe(e.type==="pair_pattern"?e.childForFieldName("value"):n,t);return;default:if(e.type==="pattern"||e.namedChildCount){let n=e.childForFieldName?.("pattern");n&&Qe(n,t)}}}function Fd(e,t){let n=e;if(n.type==="export_statement"&&(n=n.childForFieldName("declaration")),!n)return null;if(n.type==="function_declaration"||n.type==="generator_function_declaration")return n.childForFieldName("name")?.text===t?{kind:"fn",declLine:n.startPosition.row+1}:null;if(n.type==="lexical_declaration"||n.type==="variable_declaration"){for(let r of n.namedChildren){if(r.type!=="variable_declarator")continue;let o=r.childForFieldName("name");if(o?.type==="identifier"){if(o.text!==t)continue;let i=me(r.childForFieldName("value"));return i&&Cd.has(i.type)?{kind:"fn",declLine:r.startPosition.row+1}:{kind:"other"}}let s=[];if(Qe(o,s),s.includes(t))return{kind:"other"}}return null}return(n.type==="class_declaration"||n.type==="abstract_class_declaration"||n.type==="enum_declaration")&&n.childForFieldName("name")?.text===t?{kind:"other"}:null}function Ed(e){let t=e.namedChildren.find(o=>o.type==="string")?.text.slice(1,-1)??null,n=e.namedChildren.find(o=>o.type==="import_clause"),r=[];if(!n||t==null)return{src:t,out:r};for(let o of n.namedChildren)if(o.type==="identifier")r.push({kind:"default",local:o.text,imported:null});else if(o.type==="namespace_import"){let s=o.namedChildren.find(i=>i.type==="identifier");s&&r.push({kind:"ns",local:s.text,imported:null})}else if(o.type==="named_imports")for(let s of o.namedChildren){if(s.type!=="import_specifier")continue;let i=s.childForFieldName("name"),a=s.childForFieldName("alias");i&&r.push({kind:"named",local:(a??i).text,imported:i.text})}return{src:t,out:r}}function ni(e){let t=[];for(let n of e.rootNode.namedChildren)if(n.type==="import_statement"){if(n.children.some(i=>i.type==="type"))continue;let r=n.namedChildren.find(i=>i.type==="import_require_clause");if(r){let i=r.namedChildren.find(c=>c.type==="identifier"),a=r.namedChildren.find(c=>c.type==="string");i&&a&&t.push({source:an(a),kind:"cjs",local:i.text,imported:null});continue}let{src:o,out:s}=Ed(n);for(let i of s)t.push({source:o,...i})}else if(n.type==="lexical_declaration"||n.type==="variable_declaration")for(let r of n.namedChildren){if(r.type!=="variable_declarator")continue;let o=me(r.childForFieldName("value")),s=null;o?.type==="member_expression"&&(s=o.childForFieldName("property")?.text??null,o=me(o.childForFieldName("object")));let i=Ln(o);if(i==null)continue;let a=r.childForFieldName("name");if(a?.type==="identifier")t.push({source:i,kind:s?"named":"cjs",local:a.text,imported:s});else if(a?.type==="object_pattern"&&!s){for(let c of a.namedChildren)if(c.type==="shorthand_property_identifier_pattern")t.push({source:i,kind:"named",local:c.text,imported:c.text});else if(c.type==="pair_pattern"){let l=c.childForFieldName("key"),d=c.childForFieldName("value");l&&d?.type==="identifier"&&t.push({source:i,kind:"named",local:d.text,imported:l.text})}}}return t}var an=e=>e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join("");function Ln(e){if(e?.type!=="call_expression")return null;let t=e.childForFieldName("function"),n=e.childForFieldName("arguments");if(t?.type!=="identifier"||t.text!=="require"||!n||n.namedChildCount!==1)return null;let r=n.namedChildren[0];return r.type==="string"?an(r):null}function oi(e){let t=[];return(function n(r){if(r.type==="export_statement"){let o=r.childForFieldName("source");o&&!r.children.some(s=>s.type==="type")&&t.push({source:an(o),startLine:o.startPosition.row+1})}else if(r.type==="import_require_clause"){let o=r.namedChildren.find(s=>s.type==="string");o&&t.push({source:an(o),startLine:o.startPosition.row+1})}else if(r.type==="call_expression"){let o=Ln(r);o!=null&&t.push({source:o,startLine:r.startPosition.row+1})}for(let o of r.namedChildren)n(o)})(e.rootNode),t}function ri(e){let t={default:null,named:{},reexports:[],stars:[],nsReexports:[]};for(let n of e.rootNode.namedChildren){if(n.type!=="export_statement")continue;let r=n.children.some(i=>i.type==="default"),o=n.childForFieldName("declaration"),s=n.childForFieldName("source")!=null;if(r){if(o){let i=o.childForFieldName("name");t.default=i&&(o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"||o.type==="abstract_class_declaration")?i.text:"<anon>"}else{let i=me(n.childForFieldName("value"));t.default=i?.type==="identifier"?i.text:"<anon>"}continue}if(o){if(o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"||o.type==="abstract_class_declaration"){let i=o.childForFieldName("name")?.text;i&&(t.named[i]=i)}else if(o.type==="lexical_declaration"||o.type==="variable_declaration")for(let i of o.namedChildren){let a=i.type==="variable_declarator"?i.childForFieldName("name"):null;a?.type==="identifier"&&(t.named[a.text]=a.text)}continue}if(s){if(n.children.some(l=>l.type==="type"))continue;let i=an(n.childForFieldName("source")),a=n.namedChildren.find(l=>l.type==="export_clause"),c=n.namedChildren.find(l=>l.type==="namespace_export");if(a)for(let l of a.namedChildren){if(l.type!=="export_specifier")continue;let d=l.childForFieldName("name")?.text,f=l.childForFieldName("alias")?.text;d&&t.reexports.push({exported:f??d,imported:d,source:i})}else if(c){let l=c.namedChildren.find(d=>d.type==="identifier");l&&t.nsReexports.push({exported:l.text,source:i})}else t.stars.push(i);continue}for(let i of n.namedChildren)if(i.type==="export_clause")for(let a of i.namedChildren){if(a.type!=="export_specifier")continue;let c=a.childForFieldName("name")?.text,l=a.childForFieldName("alias")?.text;c&&(l==="default"?t.default=c:t.named[l??c]=c)}}for(let n of e.rootNode.namedChildren){let r=n.type==="expression_statement"?n.namedChildren[0]:null;if(r?.type!=="assignment_expression")continue;let o=r.childForFieldName("left"),s=me(r.childForFieldName("right"));if(o?.type!=="member_expression")continue;let i=o.childForFieldName("object"),a=o.childForFieldName("property")?.text,c=l=>l?.type==="member_expression"&&l.childForFieldName("object")?.text==="module"&&l.childForFieldName("property")?.text==="exports";if(c(o))if(s?.type==="identifier")t.default=s.text;else if(s?.type==="object"){for(let l of s.namedChildren)if(l.type==="shorthand_property_identifier")t.named[l.text]=l.text;else if(l.type==="pair"){let d=l.childForFieldName("key"),f=me(l.childForFieldName("value"));d&&f?.type==="identifier"&&(t.named[d.text.replace(/^['"]|['"]$/g,"")]=f.text)}t.default??="<object>"}else Ln(s)!=null?t.stars.push(Ln(s)):t.default="<anon>";else a&&(i?.type==="identifier"&&i.text==="exports"||c(i))&&s?.type==="identifier"&&(t.named[a]=s.text)}return t}function Pd(e,t,n){for(let r=e.parent;r;r=r.parent)if(jd.has(r.type)){let o=[],s=r.childForFieldName("parameters");if(s)for(let a of s.namedChildren)Qe(a,o);let i=r.childForFieldName("parameter");if(i&&Qe(i,o),r.type==="function_expression"||r.type==="generator_function"){let a=r.childForFieldName("name");a&&o.push(a.text)}if(o.includes(t))return{kind:"other"}}else if(r.type==="catch_clause"){let o=[];if(Qe(r.childForFieldName("parameter"),o),o.includes(t))return{kind:"other"}}else if(r.type==="for_in_statement"||r.type==="for_statement"){let o=[],s=r.type==="for_statement"?r.childForFieldName("initializer"):r.childForFieldName("left");if(s)if(s.type==="lexical_declaration"||s.type==="variable_declaration")for(let i of s.namedChildren)Qe(i.childForFieldName?.("name"),o);else Qe(s,o);if(o.includes(t))return{kind:"other"}}else if(r.type==="statement_block"||r.type==="program"||r.type==="switch_body"){if(r.type==="program"&&n.has(t))return{kind:"import",imp:n.get(t)};for(let o of r.namedChildren){let s=Fd(o,t);if(s)return s}if(r.type==="program"&&n.has(t))return{kind:"import",imp:n.get(t)}}return null}var Ld=e=>(e.childForFieldName("function")?.text??"").replace(/\s+/g," ").slice(0,40);function si(e,t){let n=new Map(t.map(s=>[s.local,s])),r=[],o=(s,i,a)=>{let c=me(s);if(!c||c.type!=="identifier"&&c.type!=="shorthand_property_identifier")return;let l=c.text,d=Pd(c,l,n);if(!d||d.kind==="other")return;let f=pt(a).nameNode,u={name:l,line:c.startPosition.row+1,column:c.startPosition.column,via:i,callee:Ld(a),callLine:f.startPosition.row+1,callColumn:f.startPosition.column,b:d.kind};d.kind==="fn"?u.declLine=d.declLine:(u.src=d.imp.source,u.ik=d.imp.kind,u.imp=d.imp.imported),r.push(u)};return(function s(i){if(i.type==="call_expression"){let a=i.childForFieldName("arguments");for(let c of a?.namedChildren??[]){let l=me(c);if(l)if(l.type==="array")for(let d of l.namedChildren)o(d,"array",i);else if(l.type==="object")for(let d of l.namedChildren)d.type==="pair"?o(d.childForFieldName("value"),"object",i):d.type==="shorthand_property_identifier"&&o(d,"object",i);else o(l,"arg",i)}}for(let a of i.namedChildren)s(a)})(e.rootNode),r}function ii(e){let t=[],n=o=>{let s=o?.namedChildren.find(i=>i.type!=="comment");return s?.type==="type_identifier"?s.text:null},r=o=>{let s=o.childForFieldName("name")?.text,i=o.childForFieldName("body");if(!(!s||!i)){for(let a of i.namedChildren)if(a.type==="public_field_definition"){let c=a.childForFieldName("name"),l=n(a.childForFieldName("type"));c?.type==="property_identifier"&&l&&t.push({className:s,prop:c.text,type:l})}else if(a.type==="method_definition"&&a.childForFieldName("name")?.text==="constructor")for(let c of a.childForFieldName("parameters")?.namedChildren??[]){if(c.type!=="required_parameter"&&c.type!=="optional_parameter"||!c.namedChildren.some(f=>f.type==="accessibility_modifier")&&!c.children.some(f=>f.type==="readonly"))continue;let l=c.childForFieldName("pattern"),d=n(c.childForFieldName("type"));l?.type==="identifier"&&d&&t.push({className:s,prop:l.text,type:d})}}};for(let o of e.rootNode.namedChildren){let s=o.type==="export_statement"?o.childForFieldName("declaration"):o;s&&(s.type==="class_declaration"||s.type==="abstract_class_declaration")&&r(s)}return t}var Td={Get:"get",Post:"post",Put:"put",Patch:"patch",Delete:"delete",All:"all"};function ai(e){let t=e.namedChildren[0];if(!t)return null;if(t.type==="call_expression"){let n=t.childForFieldName("function"),r=n?.type==="identifier"?n.text:null;return r?{name:r,args:t.childForFieldName("arguments")}:null}return t.type==="identifier"?{name:t.text,args:null}:null}var bt=e=>e?e.type==="string"?e.namedChildren.filter(t=>t.type==="string_fragment").map(t=>t.text).join(""):e.type==="template_string"&&!e.namedChildren.some(t=>t.type==="template_substitution")?e.text.slice(1,-1):null:null;function ci(e){let t=e?.namedChildren.find(n=>n.type!=="comment");if(!t)return"";if(t.type==="array")return bt(t.namedChildren.find(n=>n.type!=="comment"))??"";if(t.type==="object"){for(let n of t.namedChildren){if(n.type!=="pair")continue;let r=n.childForFieldName("key");if(r?.text==="path"||r?.text==="'path'"||r?.text==='"path"'){let o=n.childForFieldName("value");return(o?.type==="array"?bt(o.namedChildren[0]):bt(o))??""}}return""}return bt(t)??""}var Tn=(...e)=>"/"+e.map(n=>String(n??"").replace(/^\/+|\/+$/g,"")).filter(Boolean).join("/");function li(e){let t=[],n=(r,o)=>{let s=r.childForFieldName("name")?.text,i=r.childForFieldName("body");if(!s||!i)return;let c=[...o,...r.namedChildren.filter(f=>f.type==="decorator")].map(ai).filter(Boolean).find(f=>f.name==="Controller");if(!c)return;let l=ci(c.args),d=[];for(let f of i.namedChildren)if(f.type!=="comment"){if(f.type==="decorator"){d.push(f);continue}if(f.type==="method_definition"){let u=f.childForFieldName("name")?.text;for(let h of d.map(ai).filter(Boolean)){let p=Td[h.name];!p||!u||t.push({method:p,path:Tn(l,ci(h.args)),startLine:f.startPosition.row+1,handlerName:null,isInlineHandler:!1,handlerStartLine:null,handlerEndLine:null,handlerStartIndex:null,handlerEndIndex:null,nest:{className:s,methodName:u}})}}d=[]}};for(let r of e.rootNode.namedChildren)if(r.type==="export_statement"){let o=r.childForFieldName("declaration");o&&(o.type==="class_declaration"||o.type==="abstract_class_declaration")&&n(o,r.namedChildren.filter(s=>s.type==="decorator"))}else(r.type==="class_declaration"||r.type==="abstract_class_declaration")&&n(r,[]);return t}function di(e){let t=[];return(function n(r){if(r.type==="call_expression"){let o=r.childForFieldName("function");if(o?.type==="member_expression"&&o.childForFieldName("property")?.text==="setGlobalPrefix"){let s=(r.childForFieldName("arguments")?.namedChildren??[]).filter(l=>l.type!=="comment"),i=s[0]?bt(s[0]):null,a=[],c=s[1];if(c?.type==="object")for(let l of c.namedChildren){if(l.type!=="pair"||l.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")!=="exclude")continue;let d=l.childForFieldName("value");for(let f of d?.type==="array"?d.namedChildren:[])if(f.type==="object"){for(let u of f.namedChildren)if(u.type==="pair"&&u.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")==="path"){let h=bt(u.childForFieldName("value"));h!=null&&a.push(h)}}else{let u=bt(f);u!=null&&a.push(u)}}t.push({prefix:i||null,exclude:a})}}for(let o of r.namedChildren)n(o)})(e.rootNode),t}function fi(e){let t=[];for(let s of e.values())for(let i of s?.globalPrefix??[])t.push(i);if(!t.length||t.some(s=>!s.prefix||s.prefix!==t[0].prefix))return e;let n=t[0].prefix,r=new Set(t.flatMap(s=>s.exclude).map(s=>Tn(s))),o=new Map;for(let[s,i]of e){if(!i?.routes?.some(a=>a.nest)){o.set(s,i);continue}o.set(s,{...i,routes:i.routes.map(a=>a.nest&&!r.has(Tn(a.path))?{...a,path:Tn(n,a.path)}:a)})}return o}import Rd from"node:crypto";var ui=e=>Rd.createHash("sha256").update(e).digest("hex");function Ad(e,t=null){let n=[],r=o=>{if(o.childCount===0){if(o.type==="comment")return;let s=t?t.slice(o.startIndex,o.endIndex):o.text,i=o.type==="jsx_text"?s.replace(/\s+/g," ").trim():s;if(i==="")return;n.push({s:o.startIndex,e:o.endIndex,t:i});return}for(let s=0;s<o.childCount;s++)r(o.child(s))};return r(e),n}function pi(e,t){let n=[];for(let s of[t.functions,t.arrowFunctions,t.classMethods])for(let i of s??[])i.startIndex!=null&&n.push({s:i.startIndex,e:i.endIndex,item:i,field:"bodyHash"});for(let s of[t.routes,t.listeners,t.socketListeners])for(let i of s??[])i.isInlineHandler&&i.handlerStartIndex!=null&&n.push({s:i.handlerStartIndex,e:i.handlerEndIndex,item:i,field:"handlerBodyHash"});let r=new Map(n.map(s=>[s,[]])),o=[];for(let s of Ad(e.rootNode,e.canopyOriginalSource??null)){let i=null,a=1/0;for(let c of n)s.s>=c.s&&s.e<=c.e&&c.e-c.s<a&&(i=c,a=c.e-c.s);(i?r.get(i):o).push(s.t)}for(let s of n)s.item[s.field]=ui(r.get(s).join(" "));t.moduleBodyHash=ui(o.join(" "))}function mi(e,t){return ie(t,"matchFastifyRoutes.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(l=>l.name==="http_method"),i=o.captures.find(l=>l.name==="route_path"),a=o.captures.find(l=>l.name==="handler_ref"),c=o.captures.find(l=>l.name==="handler_inline");return{method:s.node.text,path:i.node.text,startLine:s.node.startPosition.row+1,handlerName:a?a.node.text:null,isInlineHandler:!!c,handlerStartLine:c?c.node.startPosition.row+1:null,handlerEndLine:c?c.node.endPosition.row+1:null,handlerStartIndex:c?c.node.startIndex:null,handlerEndIndex:c?c.node.endIndex:null}})}function hi(e,t){return ie(t,"matchExtensionListeners.scm").matches(e.rootNode).map(o=>{let s=o.captures.find(p=>p.name==="event_type"),i=o.captures.find(p=>p.name==="event_name"),a=o.captures.find(p=>p.name==="method_name"||p.name==="listener_method"),c=o.captures.find(p=>p.name==="handler_ref"),l=o.captures.find(p=>p.name==="target"),d=o.captures.find(p=>p.name==="root_object"),f=o.captures.find(p=>p.name==="sub_object"),u=l?l.node.text:d?d.node.text+(f?"."+f.node.text:""):null,h=o.captures.find(p=>p.name==="handler_inline");return{eventName:s?.node.text??i?.node.text??"unknown",targetName:u,startLine:a.node.startPosition.row+1,handlerName:c?c.node.text:null,isInlineHandler:!!h,handlerStartLine:h?h.node.startPosition.row+1:null,handlerEndLine:h?h.node.endPosition.row+1:null,handlerStartIndex:h?h.node.startIndex:null,handlerEndIndex:h?h.node.endIndex:null}})}import Bd from"node:fs";We();import Ge from"node:fs";import de from"node:path";import Od from"node:os";import yi from"node:crypto";import{fileURLToPath as Md}from"node:url";var Hd=de.dirname(Md(globalThis.__canopyUrl("src/stage2_parse/parseCache.js"))),vi=de.join(Hd,"..",".."),Vo=process.env.CANOPY_CACHE_DIR||(Dt()?de.join(Od.homedir(),".canopy-cache"):de.join(vi,".canopy-cache")),gi=e=>yi.createHash("sha256").update(e).digest("hex");function Rn(e,t){return Ge.readdirSync(e,{withFileTypes:!0}).flatMap(n=>n.isDirectory()?Rn(de.join(e,n.name),t):t.some(r=>n.name.endsWith(r))?[de.join(e,n.name)]:[]).sort()}var Yo=null;function Dd(){if(Yo)return Yo;let e=de.join(vi,"src"),t=!Ge.existsSync(e)&&globalThis.__canopyBundle,n=t?[t,...Rn(de.join(de.dirname(t),"queries"),[".scm"])]:[...Rn(de.join(e,"stage2_parse"),[".js",".scm"]),...Rn(de.join(e,"stage5_entrypoints"),[".js"]).filter(o=>/match/i.test(de.basename(o))),de.join(e,"utils","loadQuery.js")],r=yi.createHash("sha256");for(let o of n)r.update(de.relative(t?de.dirname(t):e,o).split(de.sep).join("/")).update("\0").update(Ge.readFileSync(o).toString("utf8").replace(/\r\n/g,`
|
|
17
|
+
`)).update("\0");for(let o of["web-tree-sitter","tree-sitter-javascript","tree-sitter-typescript"])try{r.update(o+"@"+JSON.parse(Ge.readFileSync(de.join(He(o),"package.json"),"utf8")).version)}catch{r.update(o+"@?")}return Yo=r.digest("hex").slice(0,16)}function xi(){let e=Dd(),t=de.join(Vo,e);Ge.mkdirSync(t,{recursive:!0});for(let n of Ge.readdirSync(Vo,{withFileTypes:!0}))n.isDirectory()&&n.name!==e&&Ge.rmSync(de.join(Vo,n.name),{recursive:!0,force:!0});return{version:e,keyFor:(n,r="javascript")=>gi(r==="javascript"?n:Buffer.concat([Buffer.from(r+"\0"),n])),get(n){try{return JSON.parse(Ge.readFileSync(de.join(t,n+".json"),"utf8"))}catch{return null}},set(n,r){let o=de.join(t,`${n}.${process.pid}.tmp`);Ge.writeFileSync(o,JSON.stringify(r)),Ge.renameSync(o,de.join(t,n+".json"))}}}function wi(e){return JSON.parse(JSON.stringify(e,(t,n)=>n&&typeof n=="object"&&n.startPosition&&n.endPosition&&"type"in n&&"tree"in n?void 0:n))}var Si=Number(process.env.CANOPY_PARSE_BUDGET_MS)||3e4,Xo=class extends Error{constructor(t){super(`parse time budget exceeded (limit ${Si/1e3} s; stopped after ${(t/1e3).toFixed(1)} s)`),this.name="ParseBudgetError"}},Ud=100;function Ko(e,t,n){return e.map(r=>({...r,returns:qs(t,n,r)}))}function ki(e,t,n,{cache:r=!0,onProgress:o=console.log,grammars:s=null,noCache:i=!1}={}){let a=new Map,c=0,l=0,d=0,f=r?xi():null,u=!i,h=[],p=0;for(let m of e){p>0&&p%Ud===0&&o(` parsing: ${p}/${e.length} files (${d} from cache)`),p++;let y=null;try{let g=Bd.readFileSync(m),x=Uo(m),S=f?.keyFor(g,x),k=f&&u?f.get(S):null;if(k){a.set(m,k),d++;continue}l++;let v=performance.now(),w=()=>{let C=performance.now()-v;if(C>Si)throw new Xo(C)},b=x==="javascript"?{parser:t,language:n}:s?.get(x);if(!b)throw new Error(`no ${x} grammar loaded`);let N=b.language;Ls(x),y=js(b.parser,m).tree,w();let $=[],j=(C,R,W=[])=>{try{return R()}catch(K){if(K.name==="ParseBudgetError")throw K;return $.push({extractor:C,message:String(K.message).slice(0,160)}),W}},O=j("functionDeclarations",()=>Ko(Ms(y,N),y,N));w();let D=j("arrowFunctions",()=>Ko(Hs(y,N),y,N));w();let G=j("classMethods",()=>Ko(Ds(y,N),y,N));w();let M=j("importBindings",()=>ni(y)),q={functions:O,arrowFunctions:D,classMethods:G,imports:j("imports",()=>[...Bs(y,N),...oi(y)]),calls:(w(),j("calls",()=>Us(y,N))),methodCalls:(w(),j("methodCalls",()=>zs(y,N))),returnEntries:j("returnEntries",()=>Ws(y,N)),jsxElements:j("jsxElements",()=>Js(y,N)),callSites:(w(),j("callSites",()=>Qs(y))),apiCalls:(w(),j("apiCalls",()=>Vs(y,N))),socketEmits:j("socketEmits",()=>Ys(y,N)),socketListeners:j("socketListeners",()=>Zs(y,N)),rawSocketSends:j("rawSocketSends",()=>Ks(y,N)),rawSocketTypeChecks:j("rawSocketTypeChecks",()=>Xs(y,N)),routes:j("routes",()=>[...mi(y,N),...ut(N)?li(y):[]]),listeners:j("listeners",()=>hi(y,N)),refArgs:j("refArgs",()=>si(y,M)),globalPrefix:j("globalPrefix",()=>di(y)),importBindings:M,classProps:j("classProps",()=>ut(N)?ii(y):[]),httpClients:j("httpClients",()=>ti(y),null),exportBindings:j("exportBindings",()=>ri(y),null),hadErrors:zo(y),exportedNames:j("exports",()=>Gs(y,N)),failed:!1,warnings:$};j("bodyHash",()=>pi(y,q),null);let E=wi(q);f&&f.set(S,E),a.set(m,E)}catch(g){if(g.name==="ParseBudgetError"){h.push({filePath:m,reason:g.message}),a.set(m,{functions:[],arrowFunctions:[],classMethods:[],imports:[],calls:[],methodCalls:[],returnEntries:[],jsxElements:[],callSites:[],apiCalls:[],socketEmits:[],socketListeners:[],rawSocketSends:[],rawSocketTypeChecks:[],routes:[],listeners:[],hadErrors:!1,failed:!1,skipped:g.message}),console.warn(` ! Skipped ${m}: ${g.message}`);continue}c++,a.set(m,{functions:[],arrowFunctions:[],classMethods:[],imports:[],calls:[],methodCalls:[],returnEntries:[],jsxElements:[],callSites:[],apiCalls:[],socketEmits:[],socketListeners:[],rawSocketSends:[],rawSocketTypeChecks:[],routes:[],listeners:[],hadErrors:!0,failed:!0,errorMessage:g.message}),console.warn(` ! Failed to parse ${m}: ${g.message}`)}finally{if(y){try{y.delete()}catch{}y=null}}}return console.log(`Parsed ${a.size} files (${c} failed)`),console.log(` parse cache: ${l} file(s) parsed, ${d} served from cache`),a.cacheStats={parsed:l,cacheHits:d},a.budgetSkips=h,a}function An(e,t){return`${e}::${t}`}var Ni=[{category:"frontend",patterns:["frontend","client","src/components","ui","src/pages","public"]},{category:"backend",patterns:["backend","server","api","realtime-backend"]},{category:"transport",patterns:["websocket","socket","realtime"]},{category:"data",patterns:["redis","database","models","db"]}];function On(e){let t=e.toLowerCase().replace(/\\/g,"/");for(let{category:n,patterns:r}of Ni)for(let o of r)if(t.includes(o))return n;return"unknown"}import Zo from"node:fs";import Se from"node:path";import Mn from"node:fs";import et from"node:path";var zd=["index.html","public/index.html","src/index.html"],Wd=/^(build|esbuild|vite\.config|webpack\.config|rollup\.config|bundle)[\w.-]*\.(mjs|cjs|js|ts)$/i;function Gd(e){let t=e.replace(/<!--[\s\S]*?-->/g,""),n=[];for(let r of t.matchAll(/<script\b[^>]*?\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)')/gi))n.push(r[1]??r[2]);return n}function qd(e){let t=[],n=[];try{n=Mn.readdirSync(e).filter(r=>Wd.test(r)).sort()}catch{return t}for(let r of n){let o;try{o=Mn.readFileSync(et.join(e,r),"utf8")}catch{continue}let s=/\boutfile\s*:\s*["'`]([^"'`]+)["'`]/.exec(o)?.[1]??null,i=/\b(?:entryPoints|entry|input)\s*:\s*\[?\s*["'`]([^"'`]+)["'`]/.exec(o)?.[1]??null;i&&t.push({config:r,outfile:s,entry:i})}return t}function Hn(e,t,n=new Set(t.map(r=>et.resolve(r)))){for(let r of zd){let o=et.join(e,r);if(!Mn.existsSync(o))continue;let s;try{s=Mn.readFileSync(o,"utf8")}catch{continue}let i=et.dirname(o),a=d=>{let f=d.split(/[?#]/)[0];return!f||/^([a-z]+:)?\/\//i.test(f)?null:et.resolve(f.startsWith("/")?et.join(e,f):et.join(i,f))},c=Gd(s).map(d=>({s:d,p:a(d)})).filter(d=>d.p);for(let{s:d,p:f}of c)if(n.has(f))return{indexHtml:o,script:d,entry:f,via:"script"};let l=qd(e);for(let{s:d,p:f}of c)for(let u of l){if(!u.outfile||et.resolve(e,u.outfile)!==f)continue;let h=et.resolve(e,u.entry);if(n.has(h))return{indexHtml:o,script:d,entry:h,via:`${u.config} (outfile ${u.outfile})`}}}return null}var Jd=new Set(["test","tests","__tests__","fixtures","__fixtures__","__mocks__","e2e","cypress"]);function Wt(e){let t=String(e).replace(/\\/g,"/").split("/").filter(Boolean);if(!t.length)return!1;for(let n of t.slice(0,-1))if(Jd.has(n.toLowerCase()))return!0;return/\.(test|spec)\.[^./]+$/i.test(t[t.length-1])}function Vd(e){let t=Se.join(e,"package.json");if(!Zo.existsSync(t))return null;try{return JSON.parse(Zo.readFileSync(t,"utf-8"))}catch{return null}}function Yd(e){return[...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{})]}function Kd(e){let t=!!e.workspaces,n=Object.keys(e.dependencies??{}).length>0,r=!!(e.scripts&&e.scripts.start);return t&&!n&&!r}var Xd=["react","vue","svelte","next","vite","webpack","parcel"],Zd=["express","fastify","koa","hapi","socket.io","ws"],Qd=[{deps:["mongodb","mongoose"],label:"MongoDB"},{deps:["redis","ioredis"],label:"Redis"},{deps:["pg","postgres"],label:"PostgreSQL"},{deps:["mysql","mysql2"],label:"MySQL"},{deps:["sqlite3","better-sqlite3"],label:"SQLite"},{deps:["@prisma/client"],label:"Prisma"},{deps:["drizzle-orm"],label:"Drizzle"}];function ef(e){let t=e.some(r=>Xd.includes(r)),n=e.some(r=>Zd.includes(r));return t&&!n?"client":n&&!t||n&&t?"server":"unknown"}function tf(e){let t=[];for(let{deps:n,label:r}of Qd)n.some(o=>e.includes(o))&&!t.includes(r)&&t.push(r);return t}function bi(e){let t=new Set(["node_modules",".git","dist","build",".next","coverage"]);try{return Zo.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!t.has(n.name)&&!n.name.startsWith(".")).map(n=>Se.join(e,n.name))}catch{return[]}}function _i(e,t=null){let n=[e];for(let o of bi(e)){n.push(o);for(let s of bi(o))n.push(s)}let r=[];for(let o of n){let s=Vd(o);if(!s||Kd(s))continue;let i=Yd(s);r.push({name:s.name||Se.basename(o),rootPath:o,isRepoRoot:Se.resolve(o)===Se.resolve(e),kind:ef(i),datastores:tf(i)})}if(t){let o=new Set(t.map(i=>Se.resolve(i))),s=new Set(r.map(i=>Se.resolve(i.rootPath)));for(let i of n)Se.resolve(i)===Se.resolve(e)||s.has(Se.resolve(i))||Wt(Se.relative(e,i)+"/x")||Hn(i,t,o)&&r.push({name:Se.basename(i),rootPath:i,isRepoRoot:!1,kind:"client",datastores:[],webRoot:!0})}return r}function _t(e,t){let n=null,r=-1;for(let o of t)o.isRepoRoot&&t.length>1&&!o.ownsLeftovers||(e===o.rootPath||e.startsWith(o.rootPath+Se.sep))&&o.rootPath.length>r&&(n=o.name,r=o.rootPath.length);return n}var nf=5,of=.1;function $i(e,t,n){let r=Se.basename(Se.resolve(n)),o=c=>({name:c,rootPath:n,isRepoRoot:!0,ownsLeftovers:!0,kind:"unknown",datastores:[]});if(!t.length)return{services:e,added:null};if(!e.length)return{services:[o(r)],added:{name:r,reason:"no package.json found: the repo root is the one service",leftover:t.length}};let s=t.filter(c=>!_t(c,e)).length;if(s<nf||s<of*t.length)return{services:e,added:null,leftover:s};let i=e.find(c=>c.isRepoRoot);if(i)return i.ownsLeftovers=!0,{services:e,added:{name:i.name,reason:`${s} of ${t.length} files sit outside every nested package: owned by the root package ${i.name}`,leftover:s}};let a=r;return e.some(c=>c.name.toLowerCase()===a.toLowerCase())&&(a=`${r} (root)`),{services:[...e,o(a)],added:{name:a,reason:`${s} of ${t.length} files sit outside every nested package: owned by a service named after the repo folder`,leftover:s}}}function Ii(e,t=[]){let n=[];for(let[r,o]of e){let s=On(r),i=_t(r,t);n.push({id:`${r}::__module_root__`,name:"module root",filePath:r,startLine:0,endLine:Number.MAX_SAFE_INTEGER,category:s,serviceName:i,type:"moduleRoot",bodyHash:o.moduleBodyHash??null});for(let a of o.functions)n.push({id:An(r,a.name),name:a.name,filePath:r,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:s,serviceName:i,bodyHash:a.bodyHash??null,type:"function"});for(let a of o.arrowFunctions)n.push({id:An(r,a.name),name:a.name,filePath:r,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:s,serviceName:i,bodyHash:a.bodyHash??null,type:"arrowFunction"});for(let a of o.classMethods)n.push({id:An(r,`${a.className}.${a.methodName}`),name:a.methodName,className:a.className,filePath:r,startLine:a.startLine,endLine:a.endLine,params:a.params,returns:a.returns,category:s,serviceName:i,bodyHash:a.bodyHash??null,type:"classMethod"})}return n}function qe(e,t){let n=[];for(let s of t.routes??[])s.isInlineHandler&&n.push({item:s,line:s.startLine,key:`route:${String(s.method).toUpperCase()} ${s.path}`});for(let s of t.listeners??[])s.isInlineHandler&&n.push({item:s,line:s.startLine,key:`listener:${s.targetName??"unknown"}.${s.eventName}`});for(let s of t.socketListeners??[])s.isInlineHandler&&n.push({item:s,line:s.startLine,key:`socket:${s.eventName}`});n.sort((s,i)=>s.line-i.line);let r=new Map,o=new Map;for(let{item:s,key:i}of n){let a=(r.get(i)??0)+1;r.set(i,a),o.set(s,`${e}::${i}${a>1?`#${a}`:""}`)}return o}function ji(e,t=[]){let n=[];for(let[r,o]of e){let s=On(r),i=_t(r,t),a=t.find(l=>l.name===i),c=qe(r,o);for(let l of o.routes??[]){if(!l.isInlineHandler)continue;let d=`${l.method.toUpperCase()} ${l.path}`;n.push({id:c.get(l),name:`${d} (inline handler)`,filePath:r,startLine:l.handlerStartLine??l.startLine,endLine:l.handlerEndLine??l.startLine,category:s,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:l.handlerBodyHash??null,trigger:{type:"route",label:d,resolvedVia:"inline"}})}for(let l of o.listeners??[])l.isInlineHandler&&n.push({id:c.get(l),name:`${l.eventName} (inline handler)`,filePath:r,startLine:l.handlerStartLine??l.startLine,endLine:l.handlerEndLine??l.startLine,category:s,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:l.handlerBodyHash??null,trigger:{type:"listener",label:l.eventName,resolvedVia:"inline"}});if(a?.kind==="server")for(let l of o.socketListeners??[])l.isInlineHandler&&n.push({id:c.get(l),name:`${l.eventName} (inline handler)`,filePath:r,startLine:l.handlerStartLine??l.startLine,endLine:l.handlerEndLine??l.startLine,category:s,serviceName:i,type:"inlineHandler",isEntryPoint:!0,bodyHash:l.handlerBodyHash??null,trigger:{type:"socketListener",label:l.eventName,resolvedVia:"inline"}})}return n}import rf from"node:fs";import sf from"node:crypto";var Ci=e=>sf.createHash("sha256").update(e).digest("hex");function Fi(e,t){return e.map(n=>[t(n),Ci(rf.readFileSync(n))]).sort((n,r)=>n[0]<r[0]?-1:n[0]>r[0]?1:0)}function Dn(e){return Ci(e.map(([t,n])=>`${t}\0${n}`).join(`
|
|
18
|
+
`))}import Qo from"node:path";function Bn(e){let t=Qo.resolve(e),n=t.split(Qo.sep).join("/"),r=[[t.toLowerCase(),t.length,Qo.sep],[n.toLowerCase(),n.length,"/"]],o=s=>{if(typeof s!="string")return s;let i=s.toLowerCase();if(i===r[0][0]||i===r[1][0])return".";for(let[a,c,l]of r)if(i.startsWith(a+l)){let d=s.slice(c+1),f=d.indexOf("::");return(f<0?d:d.slice(0,f)).split("\\").join("/")+(f<0?"":d.slice(f))}return s};return{rel:o,repoRoot:n,replacer:(s,i)=>typeof i=="string"?o(i):i,json:(s,i)=>JSON.stringify(s,(a,c)=>typeof c=="string"?o(c):c,i),clone:s=>JSON.parse(JSON.stringify(s,(i,a)=>typeof a=="string"?o(a):a))}}function Ei(e){let t=e.map((r,o)=>({e:r,i:o})).sort((r,o)=>String(r.e.fromNodeId).localeCompare(String(o.e.fromNodeId))||(r.e.line??0)-(o.e.line??0)||(r.e.column??0)-(o.e.column??0)||r.i-o.i),n=new Map;for(let{e:r}of t){let o=r.calleeNameRaw??r.eventName??r.url??"",s=`${r.fromNodeId??"\u2205"} | ${r.callKind??r.type} | ${o}`,i=(n.get(s)??0)+1;n.set(s,i),r.id=`${s} | #${i}`}return e}function Pi(e){let t=new Map;for(let n of e)t.has(n.id)||t.set(n.id,[]),t.get(n.id).push(n);for(let[n,r]of t)r.length<2||(r.sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine),r.forEach((o,s)=>{s>0&&(o.id=`${n}#${s+1}`)}));return e}function ge(e,t){let n=null;for(let r of t)r.type!=="moduleRoot"&&e>=r.startLine&&e<=r.endLine&&(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r);return n||t.find(r=>r.type==="moduleRoot")}function Li(e,t){let n=[];for(let[o,s]of e){let i=t.filter(a=>a.filePath===o);for(let a of s.calls){let c=ge(a.startLine,i);n.push({fromFileId:o,fromNodeId:c?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"call",callKind:a.callKind??"call",resolved:!1})}for(let a of s.methodCalls){let c=ge(a.startLine,i);n.push({fromFileId:o,fromNodeId:c?.id??null,calleeNameRaw:a.methodName,objectNameRaw:a.objectName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"methodCall",callKind:a.callKind??"methodCall",resolved:!1})}for(let a of s.returnEntries??[]){let c=ge(a.startLine,i);n.push({fromFileId:o,fromNodeId:c?.id??null,calleeNameRaw:a.label,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],deferred:a.deferred??!1,type:"returnValue",resolved:!1})}for(let a of s.jsxElements){let c=ge(a.startLine,i);n.push({fromFileId:o,fromNodeId:c?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,type:"call",callKind:"jsx",resolved:!1})}for(let a of s.callSites??[]){let c=ge(a.startLine,i);n.push({fromFileId:o,fromNodeId:c?.id??null,calleeNameRaw:a.calleeName,line:a.startLine,column:a.startColumn,branchPath:a.branchPath??[],firstArgText:a.firstArgText??null,deferred:a.deferred??!1,type:"callSite",callKind:a.callKind,chainHead:a.chainHead??null,chainHeadCalled:a.chainHeadCalled??!1,ctorName:a.ctorName??null,...a.thisProp?{thisProp:a.thisProp,thisMethod:a.thisMethod}:{},resolved:!1})}for(let a of s.socketEmits){let c=ge(a.startLine,i);n.push({fromFileId:o,fromNodeId:c?.id??null,eventName:a.eventName,line:a.startLine,type:"socketEmit",resolved:!1})}for(let a of s.rawSocketSends??[]){let c=ge(a.startLine,i);n.push({fromFileId:o,fromNodeId:c?.id??null,eventName:a.eventName,line:a.startLine,type:"rawSocketSend",resolved:!1})}for(let a of s.apiCalls){let c=ge(a.startLine,i);n.push({fromFileId:o,fromNodeId:c?.id??null,url:a.url,httpMethod:a.method,scope:a.scope,line:a.startLine,type:"apiCall",resolved:!1})}}let r=n.filter(o=>o.type==="apiCall").length;return n}function he(e,t){let n=new Map;for(let r of t)r.filePath===e&&n.set(r.name,r.id);return n}function cn(e,t,n,r,o=null){if(n.has(e.calleeNameRaw))return{...e,targetNodeId:n.get(e.calleeNameRaw),confidence:.95,matchType:"local",resolved:!0};let s=[...r],i=r.legacySize??s.length,a=([,l])=>{let d=o?o.scopeOf(l):he(l,t);return d.has(e.calleeNameRaw)?{...e,targetNodeId:d.get(e.calleeNameRaw),confidence:.85,matchType:"import",resolved:!0}:null};for(let l=0;l<i;l++){let d=a(s[l]);if(d)return d}let c=o?.bind?.resolveName(e.fromFileId,e.calleeNameRaw);if(c)return{...e,targetNodeId:c.id,confidence:.85,matchType:"import",resolved:!0};for(let l=i;l<s.length;l++){let d=a(s[l]);if(d)return d}return{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function Ti(e,t,n=null){let r=n?n.method(e.objectNameRaw,e.calleeNameRaw):t.find(s=>s.type==="classMethod"&&s.className===e.objectNameRaw&&s.name===e.calleeNameRaw);if(r)return{...e,targetNodeId:r.id,confidence:.6,matchType:"methodHeuristic",resolved:!0};let o=n?.bind?.resolveMember(e.fromFileId,e.objectNameRaw,e.calleeNameRaw);return o?{...e,targetNodeId:o.id,confidence:.85,matchType:"import",resolved:!0}:{...e,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1}}function Ri(e){return{...e,targetNodeId:null,confidence:0,matchType:"unresolvedExternal",resolved:!1}}function Ai(e,t,n,r,o=null){if(e.callKind==="new"&&e.ctorName){let s=cn({...e,calleeNameRaw:e.ctorName},t,n,r,o);if(s.resolved)return{...s,calleeNameRaw:e.calleeNameRaw,matchType:s.matchType+"New"};let i=new Set([e.fromFileId,...r.values()]),a=o?o.ctorsOf(e.ctorName).find(c=>i.has(c.filePath)):t.find(c=>c.type==="classMethod"&&c.className===e.ctorName&&c.name==="constructor"&&i.has(c.filePath));return a?{...e,targetNodeId:a.id,confidence:a.filePath===e.fromFileId?.9:.8,matchType:(a.filePath===e.fromFileId?"local":"import")+"New",resolved:!0}:Ri(e)}if(e.callKind==="chainedCall"&&e.chainHead&&e.chainHeadCalled){let s=cn({...e,calleeNameRaw:e.chainHead},t,n,r,o);if(s.resolved)return{...e,targetNodeId:s.targetNodeId,confidence:s.confidence*.8,matchType:"chainHead",resolved:!0}}return Ri(e)}import tr from"node:path";import tt from"node:fs";import Y from"node:path";var Di=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],af=["index.ts","index.tsx","index.mts","index.cts","index.js","index.jsx","index.mjs","index.cjs"],cf={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]};var Bi=null,Ui=e=>{Bi=e},zi=()=>Bi,Oi=e=>Y.resolve(e);function ln(e,t){e=Y.resolve(e);let n=()=>{try{let i=Y.join(e,"package.json");if(!tt.existsSync(i))return null;let a=JSON.parse(tt.readFileSync(i,"utf8")).main;if(typeof a!="string")return null;let c=Y.resolve(e,a);return t.has(c)?c:lf(c,t)}catch{return null}},r=Y.extname(e);if(r&&t.has(e))return e;let o=cf[r];if(o)for(let i of o){let a=e.slice(0,-r.length)+i;if(t.has(a))return a}for(let i of Di)if(t.has(e+i))return e+i;let s=n();if(s)return s;for(let i of af){let a=Y.join(e,i);if(t.has(a))return a}return null}function lf(e,t){if(Y.extname(e)&&t.has(e))return e;for(let r of Di)if(t.has(e+r))return e+r;return null}var er=e=>{try{let n=tt.readFileSync(e,"utf8").replace(/^/,"").replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g,(r,o)=>o??"");return JSON.parse(n.replace(/,(\s*[}\]])/g,"$1"))}catch{return null}};function Wi(e,t=new Set){if(t.has(e))return{baseUrl:null,paths:null};t.add(e);let n=er(e);if(!n)return{baseUrl:null,paths:null};let r=null,o=null,s=n.extends?Array.isArray(n.extends)?n.extends:[n.extends]:[];for(let a of s){if(typeof a!="string"||!a.startsWith("."))continue;let c=Y.resolve(Y.dirname(e),a);(!tt.existsSync(c)||tt.statSync(c).isDirectory())&&(c=tt.existsSync(c+".json")?c+".json":Y.join(c,"tsconfig.json"));let l=Wi(c,t);l.baseUrl&&(r=l.baseUrl),l.paths&&(o=l.paths)}let i=n.compilerOptions??{};if(typeof i.baseUrl=="string"&&(r=Y.resolve(Y.dirname(e),i.baseUrl)),i.paths&&typeof i.paths=="object"){let a=r??Y.dirname(e);o=Object.entries(i.paths).map(([c,l])=>{let d=c.indexOf("*");return{prefix:d<0?c:c.slice(0,d),suffix:d<0?"":c.slice(d+1),wildcard:d>=0,targets:(Array.isArray(l)?l:[]).filter(f=>typeof f=="string").map(f=>Y.resolve(a,f))}}).sort((c,l)=>l.prefix.length-c.prefix.length)}return{baseUrl:r,paths:o}}function df(e,t){if(t=t.replace(/^\.\//,"").replace(/\/+$/,""),t.startsWith("!"))return[];let n=[],r=o=>{try{return tt.readdirSync(o,{withFileTypes:!0}).filter(s=>s.isDirectory()&&s.name!=="node_modules"&&!s.name.startsWith(".")).map(s=>Y.join(o,s.name))}catch{return[]}};if(t.endsWith("/**")){let o=Y.join(e,t.slice(0,-3)),s=i=>{for(let a of r(i))n.push(a),s(a)};s(o)}else t.endsWith("/*")?n.push(...r(Y.join(e,t.slice(0,-2)))):t.includes("*")||n.push(Y.join(e,t));return n}function ff(e){let t=[],r=er(Y.join(e,"package.json"))?.workspaces;Array.isArray(r)?t.push(...r):Array.isArray(r?.packages)&&t.push(...r.packages);try{let o=tt.readFileSync(Y.join(e,"pnpm-workspace.yaml"),"utf8"),s=!1;for(let i of o.split(/\r?\n/)){if(/^packages\s*:/.test(i)){s=!0;continue}if(s){let a=/^\s*-\s*['"]?([^'"#\s]+)['"]?/.exec(i);a?t.push(a[1]):/^\S/.test(i)&&(s=!1)}}}catch{}return t}function Mi(e,t){if(e==null)return null;let n=o=>{if(typeof o=="string")return o;if(Array.isArray(o)){for(let s of o){let i=n(s);if(i)return i}return null}if(o&&typeof o=="object"){for(let s of["source","import","module","default","require","node"])if(s in o){let i=n(o[s]);if(i)return i}}return null};if(typeof e=="string"||Array.isArray(e))return t==="."?n(e):null;let r=Object.keys(e);if(!r.some(o=>o.startsWith(".")))return t==="."?n(e):null;if(e[t]!=null)return n(e[t]);for(let o of r){let s=o.indexOf("*");if(s>0&&t.startsWith(o.slice(0,s))&&t.endsWith(o.slice(s+1))){let i=n(e[o]);if(i)return i.replace("*",t.slice(s,t.length-(o.length-s-1)))}}return null}function Gi(e,t,n={}){let r=Oi(e),o=new Set(t),s=new Map,i=u=>{if(s.has(u))return s.get(u);let h=null,p=Y.join(u,"tsconfig.json");return tt.existsSync(p)?h=Wi(p):u!==r&&Y.dirname(u)!==u&&u.startsWith(r)&&(h=i(Y.dirname(u))),s.set(u,h),h},a=new Map;for(let u of ff(r))for(let h of df(r,u)){let p=er(Y.join(h,"package.json"));p?.name&&!a.has(p.name)&&a.set(p.name,{dir:Oi(h),pkg:p})}let c=[...a.keys()].sort((u,h)=>h.length-u.length),l=(u,h,p)=>{let{dir:m,pkg:y}=a.get(u),g=[],x=S=>{if(!S)return;let k=Y.resolve(m,S);g.push(k);let v=Y.relative(m,k).split(Y.sep);["dist","build","lib","out","esm","cjs"].includes(v[0])&&g.push(Y.join(m,"src",...v.slice(1)))};if(h==="."){x(Mi(y.exports,"."));for(let S of["source","module","main"])typeof y[S]=="string"&&x(y[S]);g.push(Y.join(m,"src","index"),Y.join(m,"index"))}else x(Mi(y.exports,h)),g.push(Y.join(m,h),Y.join(m,"src",h));for(let S of g){let k=ln(S,p);if(k)return k}return null},d=u=>c.find(h=>u===h||u.startsWith(h+"/"))??null,f=(u,h)=>h?.paths?.some(p=>p.wildcard?u.startsWith(p.prefix)&&u.endsWith(p.suffix)&&u.length>=p.prefix.length+p.suffix.length:u===p.prefix)??!1;return{root:r,files:o,packages:a,isInternal(u,h){if(u.startsWith(".")||d(u))return!0;let p=i(Y.dirname(h));return!!(f(u,p)||p?.baseUrl&&!u.startsWith("@")&&ln(Y.join(p.baseUrl,u),o))},resolve(u,h,p){if(u.startsWith("."))return ln(Y.resolve(Y.dirname(h),u),p);let m=i(Y.dirname(h));if(m?.paths&&n.paths!==!1)for(let g of m.paths){let x=null;if(g.wildcard?u.startsWith(g.prefix)&&u.endsWith(g.suffix)&&u.length>=g.prefix.length+g.suffix.length&&(x=u.slice(g.prefix.length,u.length-g.suffix.length)):u===g.prefix&&(x=""),x!=null){for(let S of g.targets){let k=ln(S.replace("*",x),p);if(k)return k}break}}let y=n.workspaces===!1?null:d(u);if(y){let g=l(y,u===y?".":"./"+u.slice(y.length+1),p);if(g)return g}if(m?.baseUrl&&n.paths!==!1){let g=ln(Y.join(m.baseUrl,u),p);if(g)return g}return null}}}var Hi=new WeakMap;function qi(e){if(e instanceof Set)return e;let t=Hi.get(e);return t||Hi.set(e,t=new Set(e)),t}function nr(e,t,n){if(!e.startsWith("."))return null;let r=tr.dirname(t),o=tr.resolve(r,e),s=[o,...ms().map(i=>`${o}${i}`),...hs().map(i=>tr.join(o,i))];for(let i of s)if(n.includes(i))return i;return null}function Je(e,t,n){let r=nr(e,t,n);if(r)return r;let o=zi();return o?o.resolve(e,t,qi(n)):null}function Gt(e,t,n){let r=new Map;for(let o of t){let s=nr(o.source,e,n);s&&r.set(o.source,s)}r.legacySize=r.size;for(let o of t){if(r.has(o.source))continue;let s=Je(o.source,e,n);s&&r.set(o.source,s)}return r}function Ji(e){let t=new Map,n=new Map,r=new Map;for(let o of e){if(o.type!=="classMethod")continue;let s=o.className+"\0"+o.name;n.has(s)||n.set(s,o),o.name==="constructor"&&(r.has(o.className)||r.set(o.className,[]),r.get(o.className).push(o))}return{scopeOf:o=>{let s=t.get(o);return s||(s=he(o,e),t.set(o,s)),s},method:(o,s)=>n.get(o+"\0"+s),ctorsOf:o=>r.get(o)??[]}}function qt(e){return e?e.split("?")[0].split("/").map(t=>t.startsWith(":")||/^\d+$/.test(t)?"*":t).join("/"):""}var uf=new Set(["function","arrowFunction"]);function Vi(e,t,n,r){let o=new Map;for(let l of t){let d=o.get(l.filePath);d||o.set(l.filePath,d=[]),d.push(l)}let s=new Set;for(let l of r)l.resolved&&l.fromNodeId&&l.targetNodeId&&s.add(l.fromNodeId+"\0"+l.targetNodeId);let i=(l,d)=>(o.get(l)??[]).find(f=>uf.has(f.type)&&d(f))??null,a=[];a.argBindings=[];let c=(l,d,f,u,h,p,m)=>{!d||!f||d.id===f.id||s.has(d.id+"\0"+f.id)||a.push({fromFileId:l,fromNodeId:d.id,calleeNameRaw:u,line:h,column:p,branchPath:[],firstArgText:null,deferred:!1,type:"reference",callKind:"reference",targetNodeId:f.id,confidence:m==="local"?.95:.85,matchType:m,resolved:!0})};for(let[l,d]of e){let f=o.get(l);if(f){for(let u of d.refArgs??[]){let h=null,p="local";if(u.b==="fn"?h=i(l,y=>y.name===u.name&&y.startLine===u.declLine):u.b==="import"&&(p="import",(u.ik==="default"||u.ik==="named"||u.ik==="cjs")&&(h=n.nodeForImport(l,u.src,u.ik,u.imp))),!h)continue;let m=ge(u.line,f);c(l,m,h,u.name,u.line,u.column,p),u.callLine!=null&&m&&m.id!==h.id&&a.argBindings.push({file:l,line:u.callLine,column:u.callColumn,targetNodeId:h.id,matchType:p,direct:u.via==="arg"})}for(let u of f){if(u.type!=="inlineHandler")continue;let h=null;for(let p of f)p===u||p.type==="moduleRoot"||p.startLine<=u.startLine&&p.endLine>=u.endLine&&!(p.startLine===u.startLine&&p.endLine===u.endLine)&&(!h||p.endLine-p.startLine<h.endLine-h.startLine)&&(h=p);h??=f.find(p=>p.type==="moduleRoot"),c(l,h,u,u.name,u.startLine,0,"local")}}}return a}function Yi(e,t,n,r){let o=new Map,s=new Map;for(let a of e){if(s.set(a.id,a),a.type!=="classMethod")continue;let c=a.filePath+"\0"+a.className+"\0"+a.name,l=o.get(c);l?l.push(a):o.set(c,[a])}let i=(a,c)=>{for(let l of o.keys())if(l.startsWith(a+"\0"+c+"\0"))return!0;return!1};return function(c){let l=s.get(c.fromNodeId);if(!l||l.type!=="classMethod")return null;let d=t.get(c.fromFileId),f=(d?.classProps??[]).find(y=>y.className===l.className&&y.prop===c.thisProp);if(!f)return null;let u=null,h=null,p=(d.importBindings??[]).find(y=>y.local===f.type);if(p){let y=p.kind==="default"||p.kind==="named"?r.resolveImport(c.fromFileId,p.source,p.kind,p.imported):null;y?.local&&y.local!=="default"&&(u=y.file,h=y.local)}else i(c.fromFileId,f.type)&&(u=c.fromFileId,h=f.type);if(!u)return null;let m=o.get(u+"\0"+h+"\0"+c.thisMethod);return!m||m.length!==1?null:{...c,targetNodeId:m[0].id,confidence:.9,matchType:"typedProperty",resolved:!0}}}var pf=new Set(["function","arrowFunction"]);function Un(e,t,n){let r=new Map;for(let d of e){if(!pf.has(d.type))continue;let f=d.filePath+"\0"+d.name;r.has(f)||r.set(f,d)}let o=new Map,s=(d,f)=>{let u=o.get(d);if(!u){u=new Map;for(let h of t.get(d)?.importBindings??[])u.has(h.local)||u.set(h.local,h);o.set(d,u)}return u.get(f)??null},i=(d,f)=>n(d).get(f)??null;function a(d,f,u=new Set){let h=d+"\0"+f;if(u.has(h))return null;u.add(h);let p=t.get(d)?.exportBindings;if(!p)return null;if(f==="default"){if(p.default)return{file:d,local:p.default==="<anon>"?"default":p.default}}else if(p.named?.[f])return{file:d,local:p.named[f]};for(let m of p.reexports??[]){if(m.exported!==f)continue;let y=i(d,m.source);if(y)return a(y,m.imported,u)}for(let m of p.nsReexports??[]){if(m.exported!==f)continue;let y=i(d,m.source);if(y)return{moduleFile:y}}if(f!=="default")for(let m of p.stars??[]){let y=i(d,m),g=y?a(y,f,u):null;if(g)return g}return null}let c=d=>d?.local?r.get(d.file+"\0"+d.local)??null:null;function l(d,f,u,h){let p=i(d,f);return p?u==="default"?a(p,"default"):u==="named"?a(p,h):{moduleFile:p,cjs:u==="cjs"}:null}return{lookupExport:a,resolveImport:l,nodeForImport(d,f,u,h){let p=l(d,f,u,h);return p?.moduleFile&&p.cjs?c(a(p.moduleFile,"default")):c(p)},resolveName(d,f){let u=s(d,f);return u?this.nodeForImport(d,u.source,u.kind,u.imported):null},resolveMember(d,f,u){let h=s(d,f);if(!h)return null;let p=l(d,h.source,h.kind,h.imported);return p?.moduleFile?c(a(p.moduleFile,u)):null},classForImport(d,f){let u=s(d,f);if(!u)return null;let h=l(d,u.source,u.kind,u.imported);return h?.local?{file:h.file,className:h.local==="default"?null:h.local}:null},bindingFor:s}}function Ki(e,t,n,r,o,s,i){let a=[],c=Ji(t),l=new Map,d=g=>l.get(g)??Gt(g,n.get(g)?.imports??[],r);c.bind=Un(t,n,d);let f=Yi(t,n,d,c.bind),u=new Map;for(let g of e)u.has(g.fromFileId)||u.set(g.fromFileId,[]),u.get(g.fromFileId).push(g);for(let[g,x]of u){let S=n.get(g),k=he(g,t),v=Gt(g,S.imports,r);l.set(g,v);for(let w of x)if(w.type==="call")a.push(cn(w,t,k,v,c));else if(w.type==="methodCall")a.push(Ti(w,t,c));else if(w.type==="callSite")a.push((w.thisProp?f(w):null)??Ai(w,t,k,v,c));else if(w.type==="returnValue")a.push({...w,targetNodeId:null,confidence:0,matchType:"returnValue",resolved:!1});else if(w.type==="apiCall")if(w.scope==="external")a.push({...w,targetNodeId:null,confidence:null,matchType:"externalService",resolved:!1});else{let b=qt(w.url),N=o.get(b);N?a.push({...w,targetNodeId:N,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...w,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(w.type==="socketEmit"){let b=s.get(w.eventName);b?a.push({...w,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...w,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}else if(w.type==="rawSocketSend"){let b=i?.get(w.eventName);b?a.push({...w,targetNodeId:b,confidence:.5,matchType:"crossLayer",resolved:!0}):a.push({...w,targetNodeId:null,confidence:0,matchType:"unresolved",resolved:!1})}}let h=Vi(n,t,c.bind,a);for(let g of h)a.push(g);let p=new Map;for(let g of a){if(g.resolved||g.line==null||g.type!=="call"&&g.type!=="methodCall"&&g.type!=="callSite")continue;let x=g.fromFileId+" "+g.line+" "+g.column;(p.get(x)??p.set(x,[]).get(x)).push(g)}let m=[...h.argBindings].sort((g,x)=>x.direct-g.direct),y=new Set;for(let g of m){let x=g.file+" "+g.line+" "+g.column;if(y.has(x))continue;let S=(p.get(x)??[]).find(k=>k.fromNodeId!==g.targetNodeId);S&&(y.add(x),Object.assign(S,{targetNodeId:g.targetNodeId,confidence:g.matchType==="local"?.95:.85,matchType:"argument",resolved:!0,viaArgument:!0}))}return a}function Xi(e){let t=new Map,n=new WeakMap,r=c=>{if(typeof c=="string")return c.length>=20?"s"+c:null;if(c&&typeof c=="object"){let l=n.get(c);if(l===void 0){let d=JSON.stringify(c);l=d.length>=40?"j"+d:"",n.set(c,l)}return l||null}return null};(function c(l){let d=r(l);if(d){let f=t.get(d)??0;if(t.set(d,f+1),f>0)return}if(Array.isArray(l))for(let f of l)c(f);else if(l&&typeof l=="object")for(let f of Object.values(l))c(f)})(e);let o=[],s=new Map,i=c=>{let l=r(c),d=l&&t.get(l)>1;if(d&&s.has(l))return s.get(l);let f;if(typeof c=="string"?f=JSON.stringify(c):Array.isArray(c)?f="["+c.map(i).join(",")+"]":c&&typeof c=="object"?f="{"+Object.entries(c).map(([h,p])=>JSON.stringify(h)+":"+i(p)).join(",")+"}":f=JSON.stringify(c),!d)return f;let u="$"+o.length.toString(36);return o.push(`const ${u}=${f};`),s.set(l,u),u},a=i(e);return`(() => {${o.join(`
|
|
19
19
|
`)}
|
|
20
|
-
return ${a};})()`}function Lo(e,t,n,s){if(!e)return{targetId:null,via:null};if(n.has(e))return{targetId:n.get(e),via:"in-file"};if(s)for(let[,o]of s){let r=de(o,t);if(r.has(e))return{targetId:r.get(e),via:"cross-file"}}return{targetId:null,via:null}}function ri(e,t,n,s,o,r=[],i=null){if(!n.some(l=>!l.isInlineHandler)&&!s.some(l=>!l.isInlineHandler)&&!r.some(l=>!l.isInlineHandler))return e;let a=e.map(l=>({...l}));for(let l of n){if(l.isInlineHandler)continue;let c=l.nest?e.find(f=>f.type==="classMethod"&&f.filePath===t&&f.className===l.nest.className&&f.name===l.nest.methodName):null,{targetId:d,via:m}=l.nest?{targetId:c?.id??null,via:"in-file"}:Lo(l.handlerName,e,o,i);if(d){let f=a.find(u=>u.id===d);f&&(f.isEntryPoint=!0,f.trigger={type:"route",label:`${l.method.toUpperCase()} ${l.path}`,resolvedVia:m})}}for(let l of s){if(l.isInlineHandler)continue;let{targetId:c,via:d}=Lo(l.handlerName,e,o,i);if(c){let m=a.find(f=>f.id===c);m&&(m.isEntryPoint=!0,m.trigger={type:"listener",label:l.eventName,resolvedVia:d})}}for(let l of r){if(l.isInlineHandler)continue;let{targetId:c,via:d}=Lo(l.handlerName,e,o,i);if(c){let m=a.find(f=>f.id===c);m&&(m.isEntryPoint=!0,m.trigger={type:"socketListener",label:l.eventName,resolvedVia:d})}}return a}function To(e){let t=new Map,n=new Map;for(let s of e)s.resolved&&(t.set(s.fromNodeId,(t.get(s.fromNodeId)??0)+1),n.set(s.targetNodeId,(n.get(s.targetNodeId)??0)+1));return{outgoing:t,incoming:n}}function ii(e,t,n=To(t)){if(e.type==="moduleRoot")return 0;let s=n.outgoing.get(e.id)??0,o=n.incoming.get(e.id)??0,r=e.exported?1.5:1;return s/(o+1)*r}function ai(e,t){let n=To(t),s=new Set;for(let i of e)n.incoming.has(i.id)&&s.add(i.filePath);let r=e.filter(i=>!(i.isEntryPoint||i.type==="moduleRoot"||!n.incoming.has(i.id)&&s.has(i.filePath))).map(i=>({...i,fallbackScore:ii(i,t,n)}));return r.sort((i,a)=>a.fallbackScore-i.fallbackScore),r.slice(0,15)}function Ro(e){let t=new Map;for(let n of e)!n.resolved||!n.fromNodeId||!n.targetNodeId||(t.has(n.fromNodeId)||t.set(n.fromNodeId,[]),t.get(n.fromNodeId).push({targetNodeId:n.targetNodeId,line:n.line??null,column:n.column??null,branchPath:n.branchPath??[],edgeType:n.type}));return t}function Ao(e,t,n,s=8){let o=new Set([e]),r=l=>n.find(c=>c.id===l)?.category??"unknown",i=[{nodeId:e,depth:0,parentNodeId:null,category:r(e)}],a=[{nodeId:e,depth:0}];for(;a.length>0;){let l=a.shift();if(l.depth>=s)continue;let c=t.get(l.nodeId)||[];for(let d of c){let m=d.targetNodeId;if(o.has(m))continue;o.add(m);let f={nodeId:m,depth:l.depth+1,parentNodeId:l.nodeId,category:r(m),callLine:d.line,callColumn:d.column,branchPath:d.branchPath,edgeType:d.edgeType};i.push(f),a.push(f)}}return i}function ci(e,t,n){return t.filter(o=>o.filePath===e.filePath&&o.id!==e.id&&o.type!=="moduleRoot").filter(o=>!n.some(i=>i.resolved&&i.targetNodeId===o.id))}function li(e,t,n){if(e.type==="moduleRoot")return!1;if(t.some(a=>a.resolved&&a.targetNodeId===e.id&&a.matchType==="crossLayer")||t.filter(a=>a.resolved&&a.fromNodeId===e.id).length>=4||new Set((e.returns||[]).map(a=>a.condition).filter(a=>a!==null)).size>=3)return!0;if(t.some(a=>a.resolved&&a.targetNodeId===e.id)&&!n.some(l=>l.filePath===e.filePath&&l.id!==e.id&&l.type!=="moduleRoot"&&t.some(c=>c.resolved&&c.targetNodeId===l.id))){let l=ci(e,n,t);if(l.length>0)return e.lexicalSiblings=l.map(c=>c.id),!0}return!1}function di(e,t,n,s,o=8,r=null){let i=[],a=new Set(e.map(c=>c.id)),l=[...e];for(;l.length>0;){let c=l.shift(),d=Ao(c.id,t,n,o);i.push({entryPointId:c.id,entryPointName:c.name,trigger:c.trigger??null,steps:d});let m=r?new Set(Ao(c.id,r,n,o).map(f=>f.nodeId)):null;for(let f of d){if(m&&!m.has(f.nodeId)||f.nodeId===c.id||a.has(f.nodeId))continue;let u=n.find(p=>p.id===f.nodeId);u&&li(u,s,n)&&(a.add(u.id),f.hasOwnSubTrace=!0,u.lexicalSiblings&&(f.lexicalSiblings=u.lexicalSiblings),l.push({id:u.id,name:u.name,trigger:null}))}}return i}function fi(e,t,n=bs){return e.filter((s,o)=>{if(o===0)return!0;let r=t.find(i=>i.id===s.nodeId);return r?!n.some(i=>r.name.toLowerCase().includes(i)):!0})}function ui(e){return e.steps.filter(n=>n.depth>0).map(n=>n.nodeId).sort().join(" | ")}function pi(e){let t=new Map;for(let n of e){let s=ui(n),o=s===""?`__no_calls__${n.entryPointName}`:s;t.has(o)||t.set(o,[]),t.get(o).push(n)}return t}function mi(e){let t=e[0];return{steps:t.steps,entryPointNames:e.map(n=>n.entryPointName),occurrences:e.length,name:t.entryPointName,trigger:t.trigger,tier:e.some(n=>n.origin==="physical")?"physical":"guessed",tierOrigin:e.some(n=>n.origin==="physical")?"physical":t.origin}}import Fn from"node:path";function hi(e){if(!e.trigger)return null;if(e.trigger.type==="route")return`${e.trigger.label.split(" ")[1].split("/").filter(Boolean).join(" ").replace(/[-_]/g," ").split(" ").map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")} Flow`;if(e.trigger.type==="listener"){let t=e.trigger.label;return`${t.charAt(0).toUpperCase()+t.slice(1)} Flow`}return null}function gi(e){return e.name.replace(/([A-Z])/g," $1").trim().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}var yi=60,Yl=24;function xi(e,t=null){let n=e.map(s=>{let o=hi(s),r=s.trigger?.workflowName??o??gi(s);return{...s,name:r}});return t?.nodes?td(n,t.nodes):n}var Oo=(e,t)=>e.length>t?e.slice(0,t-1)+"\u2026":e,Zl=new Set(["function","arrowFunction","classMethod"]);function Ql(e){let t=new Map(e.map(o=>[o.id,o])),n=new Map,s=o=>{let r=n.get(o);return r||(r=e.filter(i=>i.filePath===o&&Zl.has(i.type)),n.set(o,r)),r};return o=>{let r=t.get(o.steps[0].nodeId);if(!r)return[null,null,null];let i=null;if(r.type==="classMethod")i=r.className;else{let c=null;for(let d of s(r.filePath))d===r||!(d.startLine<=r.startLine&&d.endLine>=r.endLine)||d.startLine===r.startLine&&d.endLine===r.endLine||(!c||d.endLine-d.startLine<c.endLine-c.startLine)&&(c=d);c&&(i=c.type==="classMethod"?c.className:c.name)}let a=null;if(o.trigger?.type==="route")a=String(o.trigger.label).split(" ")[0];else if(o.trigger?.type==="listener"){let c=/::listener:([^.#]+)\./.exec(r.id);c&&(a=c[1])}let l=Fn.basename(r.filePath,Fn.extname(r.filePath));return l==="index"&&(l=Fn.basename(Fn.dirname(r.filePath))),[i||null,a||null,l||null]}}var ed=(e,t)=>{let n=t.map(s=>Oo(s,Yl)).join(", ");return e.endsWith(")")?e.slice(0,-1)+", "+n+")":e+" ("+n+")"};function td(e,t){let n=Ql(t),s=e.map(i=>({w:i,base:i.name,parts:[],used:new Set,stuck:!1,q:null})),o=i=>i.parts.length?ed(i.base,i.parts):i.base,r=()=>{let i=new Map;for(let a of s){let l=o(a);(i.get(l)??i.set(l,[]).get(l)).push(a)}return[...i.values()].filter(a=>a.length>1)};for(let i=0;i<4;i++){let a=!1;for(let l of r()){if(l.some(f=>f.stuck))continue;for(let f of l)f.q??=n(f.w);let c=[0,1,2].filter(f=>l.every(u=>!u.used.has(f))),d=c.find(f=>new Set(l.map(u=>u.q[f]??"")).size>1),m=d!==void 0;if(m||(d=c.find(f=>l.every(u=>u.q[f]))),d===void 0){for(let f of l)f.stuck=!0;continue}for(let f of l)f.used.add(d),f.q[d]&&f.parts.push(f.q[d]),m||(f.stuck=!0);a=!0}if(!a)break}for(let i of r())i.sort((a,l)=>a.w.steps[0].nodeId<l.w.steps[0].nodeId?-1:a.w.steps[0].nodeId>l.w.steps[0].nodeId?1:0),i.forEach((a,l)=>{l>0&&(a.suffix=` (${l+1})`)});return s.map(i=>{let a=o(i);return i.suffix&&(a=Oo(a,yi-i.suffix.length)+i.suffix),{...i.w,name:Oo(a,yi)}})}var nd=e=>e;function vi(e,t){let n=new Map;for(let[s,o]of e){let r=t.filter(c=>c.filePath===s);if(r[0]?.category!=="backend")continue;let i=o.routes??[],a=Ue(s,o),l=de(s,t);for(let c of i){let d=Rt(c.path);if(c.isInlineHandler){let f=a.get(c);n.set(d,f);continue}if(c.nest){let f=nd(r).find(u=>u.type==="classMethod"&&u.className===c.nest.className&&u.name===c.nest.methodName);f&&n.set(d,f.id);continue}if(!c.handlerName||!l.has(c.handlerName))continue;let m=l.get(c.handlerName);n.set(d,m)}}return n}import mt from"node:fs";import Y from"node:path";var jn=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],od=/(^|\/)(dist|build|out|built|compiled|esm|cjs|lib|output)(\/|$)/,wi=/(^|\/)(dist|build|out|built|compiled|esm|cjs|output)(\/|$)/,sd=/\b(esbuild|tsup|tsdown|tsc|rollup|webpack|ncc|swc|babel|vite|parcel|bun\s+build|pkg|unbuild|microbundle|rspack)\b/,rd=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild|rspack)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,We=e=>{try{return mt.statSync(e).isFile()}catch{return!1}},Mo=e=>e.split(Y.sep).join("/"),Ho=e=>{if(We(e)&&jn.includes(Y.extname(e))&&!/\.d\.ts$/.test(e))return e;let t=e.replace(/\.(m|c)?js$/,"");for(let n of jn)if(We(t+n)&&!/\.d\.ts$/.test(t+n))return t+n;return null},Cn=(e,t)=>{let n=Y.relative(e,t);return n&&!n.startsWith("..")&&!Y.isAbsolute(n)&&!/(^|[\\/])node_modules([\\/]|$)/.test(n)};function id(e,t){let n=We(t+".map")?t+".map":null;if(!n&&We(t))try{let a=mt.readFileSync(t,"utf8").slice(-400),l=/sourceMappingURL=([^\s*]+)/.exec(a);if(l&&!l[1].startsWith("data:")){let c=Y.resolve(Y.dirname(t),l[1]);We(c)&&(n=c)}}catch{}if(!n)return null;let s;try{s=JSON.parse(mt.readFileSync(n,"utf8"))}catch{return null}let o=Y.resolve(Y.dirname(n),s.sourceRoot??""),r=(s.sources??[]).map(a=>Y.resolve(o,a)).filter(a=>Cn(e,a)&&We(a)&&jn.includes(Y.extname(a)));if(r.length===1)return r[0];let i=Y.basename(t).replace(/\.(m|c)?js$/,"");return r.find(a=>Y.basename(a).replace(/\.[^.]+$/,"")===i)??null}function ad(e){try{return JSON.parse(mt.readFileSync(e,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,"").replace(/,(\s*[}\]])/g,"$1"))}catch{return null}}function cd(e,t){for(let n of["tsconfig.build.json","tsconfig.json"]){let o=ad(Y.join(e,n))?.compilerOptions;if(!o?.outDir)continue;let r=Mo(Y.normalize(o.outDir)).replace(/^\.\//,"").replace(/\/$/,"");if(!(t===r||t.startsWith(r+"/")))continue;let i=t.slice(r.length+1),a=o.rootDir?o.rootDir:mt.existsSync(Y.join(e,"src"))?"src":".",l=Ho(Y.resolve(e,a,i));if(l)return l}return null}function ld(e,t){let n=t.split("/"),s=n.findIndex(r=>/^(dist|build|out|built|compiled|esm|cjs|lib|output)$/.test(r));if(s<0)return null;let o=n.slice(s+1).join("/");for(let r of["src","source","sources"]){let i=Ho(Y.resolve(e,...n.slice(0,s),r,o));if(i&&Cn(e,i))return i}return null}function dd(e,t,n){let s=Y.basename(n).replace(/\.(m|c)?js$/,"");for(let o of["build","compile","bundle","prepare","prepublishOnly","prepack","postinstall"]){let r=t.scripts?.[o];if(!r||!sd.test(r))continue;let i=[];for(let c of r.split(/\s+/).map(d=>d.replace(/^["']|["']$/g,"").replace(/^--?[\w-]+=/,""))){if(!jn.includes(Y.extname(c))||/\.d\.ts$/.test(c))continue;let d=Y.resolve(e,c);We(d)&&Cn(e,d)&&!wi.test(Mo(Y.relative(e,d)))&&i.push(d)}let a=[...new Set(i)];if(a.length===1)return a[0];let l=a.filter(c=>Y.basename(c).replace(/\.[^.]+$/,"")===s);if(l.length===1)return l[0];if(a.length)return a[0]}return null}function fd(e,t){let n=[];try{n=mt.readdirSync(e).filter(i=>rd.test(i)).sort()}catch{return null}let s=Y.basename(t).replace(/\.(m|c)?js$/,""),o=[];for(let i of n){let a;try{a=mt.readFileSync(Y.join(e,i),"utf8")}catch{continue}for(let l of a.matchAll(/\bentry(?:Points)?\s*:\s*[[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/g)){let c=Ho(Y.resolve(e,l[1]));c&&Cn(e,c)&&o.push(c)}}let r=[...new Set(o)];return r.length===1?r[0]:r.find(i=>Y.basename(i).replace(/\.[^.]+$/,"")===s)??null}function En(e,t,n){if(typeof t!="string"||!t)return null;let s=Mo(Y.normalize(t)).replace(/^\.\//,""),o=Y.resolve(e,s);if(!od.test(s)||We(o)&&!wi.test(s)||We(o)&&/\.ts$/.test(o))return null;let i=[["sourcemap",()=>id(e,o)],["tsconfig outDir",()=>cd(e,s)],["convention",()=>We(o)?null:ld(e,s)],["build script",()=>dd(e,n??{},s)],["build config",()=>fd(e,s)]];for(let[a,l]of i){let c=null;try{c=l()}catch{}if(c&&c!==o)return{file:c,how:a}}return null}function Si(e,t){let n=new Map;for(let[s,o]of e){let r=o.socketListeners??[],i=Ue(s,o),a=de(s,t);for(let l of r){if(l.isInlineHandler){let d=i.get(l);n.set(l.eventName,d);continue}if(!l.handlerName||!a.has(l.handlerName))continue;let c=a.get(l.handlerName);n.set(l.eventName,c)}}return n}import Do from"node:fs";import z from"node:path";var $e=e=>String(e??"").trim().replace(/^["']|["']$/g,""),Pn=e=>e.replace(/^\s*#.*$/,"").replace(/\s+#.*$/,"");function ki(e){let t=/^(\/[A-Za-z0-9_\-./]*?)\/?(?=$|[:(*{[])/.exec(String(e).trim()),n=t?t[1]:"";return n==="/"?"":n.replace(/\/+$/,"")}function Ni(e,t){let n=e.split(/\r?\n/).map(Pn),s=u=>u.length-u.trimStart().length,o=[],r=null,i=!1,a=null,l=!1,c=0,d=null,m=()=>{d?.key&&d.fromService&&d.fromService!=="?"&&r.hostRefs.push({name:d.key,service:d.fromService,property:d.property}),d=null},f=(u,p,h)=>{p==="name"?u.name=$e(h):p==="rootDir"?u.rootDir=$e(h):p==="startCommand"&&(u.startCommand=$e(h))};for(let u of n){if(!u.trim())continue;let p=s(u),h=u.trim();if(p===0){m(),r=null,l=!1,i=/^services\s*:/.test(h),a=null;continue}if(!i)continue;let v=h.startsWith("-");if(v&&(a==null||p===a)){a=p,m(),r={name:null,rootDir:null,startCommand:null,kept:[],hostRefs:[]},o.push(r),l=!1;let w=/^-\s*([A-Za-z]+)\s*:\s*(.*)$/.exec(h);w&&f(r,w[1],w[2]);continue}if(!r)continue;let g=/^(?:-\s*)?([A-Za-z]+)\s*:\s*(.*)$/.exec(h);if(g){if(g[1]==="envVars"){m(),l=!0,c=p;continue}if(l&&p>c){if(v&&(m(),d={key:null,fromService:null,property:null}),!d)continue;if(g[1]==="key")d.key=$e(g[2]);else if(g[1]==="value"&&d.key){let w=Ze(d.key,$e(g[2]),t);w&&r.kept.push(w)}else g[1]==="fromService"?d.fromService="?":g[1]==="name"&&d.fromService==="?"?d.fromService=$e(g[2]):g[1]==="property"&&(d.property=$e(g[2]));continue}l&&(m(),l=!1),f(r,g[1],g[2])}}return m(),o.filter(u=>u.name)}function bi(e,t){let n={app:null,ports:[],kept:[]},s="";for(let o of e.split(/\r?\n/)){let r=Pn(o).trim();if(!r)continue;let i=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(r);if(i){s=i[1];continue}let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(r);if(!a)continue;let[,l,c]=a;if(s===""&&l==="app"){let d=$e(c);/^[a-z0-9][a-z0-9-]*$/i.test(d)&&(n.app=d)}else if(l==="internal_port"){let d=Number($e(c));Number.isInteger(d)&&d>=1&&d<=65535&&n.ports.push(d)}else if(s==="env"){let d=Ze(l,$e(c),t);d&&n.kept.push(d)}}return n}function _i(e,t){let n={ports:[],kept:[]},s=e.replace(/\\\r?\n/g," ");for(let o of s.split(/\r?\n/)){let r=o.trim(),i=/^EXPOSE\s+(.+)$/i.exec(r);if(i){for(let l of i[1].split(/\s+/)){let c=Number(l.replace(/\/\w+$/,""));Number.isInteger(c)&&c>=1&&c<=65535&&n.ports.push(c)}continue}if(i=/^(?:ENV|ARG)\s+(.+)$/i.exec(r),!i)continue;let a=i[1];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(a)){let l=/([A-Za-z_][A-Za-z0-9_]*)=("([^"]*)"|'([^']*)'|\S*)/g,c;for(;c=l.exec(a);){let d=Ze(c[1],c[3]??c[4]??c[2],t);d&&n.kept.push(d)}}else{let l=/^([A-Za-z_][A-Za-z0-9_]*)\s+(.*)$/.exec(a);if(l){let c=Ze(l[1],$e(l[2]),t);c&&n.kept.push(c)}}}return n}function $i(e){let t;try{t=JSON.parse(e)}catch{return[]}let n=[];for(let s of["rewrites","redirects"])for(let o of Array.isArray(t?.[s])?t[s]:[]){let r=typeof o?.destination=="string"?o.destination:"",i=/\/:[A-Za-z_]+\*?$/.test(r)?Qe(r.replace(/\/:[A-Za-z_]+\*?$/,"")):null;i&&typeof o.source=="string"&&n.push({prefix:ki(o.source),target:i,kind:`vercel.json ${s}`,strip:!0})}return n}function Ii(e){let t=[],n=!1,s=null,o=()=>{if(s?.from&&s.to&&/\/:[A-Za-z_]+\*?$/.test(s.to)){let r=Qe(s.to.replace(/\/:[A-Za-z_]+\*?$/,""));r&&t.push({prefix:ki(s.from),target:r,kind:"netlify.toml redirects",strip:!0})}s=null};for(let r of e.split(/\r?\n/)){let i=Pn(r).trim();if(!i)continue;let a=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(a){o(),n=a[1]==="redirects",s=n?{}:null;continue}if(!n||!s)continue;let l=/^(from|to)\s*=\s*(.*)$/.exec(i);l&&(s[l[1]]=$e(l[2]))}return o(),t}function Fi(e,t){let n;try{n=JSON.parse(e)}catch{return[]}let s=[],o=n&&typeof n=="object"?n.env:null;if(o&&typeof o=="object")for(let r of Object.keys(o).sort()){let i=o[r],a=typeof i=="string"?i:typeof i?.value=="string"?i.value:null,l=Ze(r,a,t);l&&s.push(l)}return s}function ji(e,t,n){let s=[];if(n){let o;try{o=JSON.parse(e)}catch{return s}let r=(i,a)=>{if(!(!i||typeof i!="object"||a>4))for(let l of Object.keys(i).sort()){let c=i[l];if(/^(env|envVars|variables|environment)$/i.test(l)&&c&&typeof c=="object"&&!Array.isArray(c))for(let d of Object.keys(c).sort()){let m=typeof c[d]=="string"?c[d]:typeof c[d]?.value=="string"?c[d].value:null,f=Ze(d,m,t);f&&s.push(f)}else r(c,a+1)}};r(o,0)}else{let o="";for(let r of e.split(/\r?\n/)){let i=Pn(r).trim();if(!i)continue;let a=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(a){o=a[1];continue}let l=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(i);if(l&&/(^|\.)(env|variables|environment)$/i.test(o)){let c=Ze(l[1],$e(l[2]),t);c&&s.push(c)}}}return s}var ud=[".env.local",".env",".env.development",".env.production",".env.example"],pd=/^(PORT|HTTP_PORT|HTTPS_PORT|SERVER_PORT|API_PORT|APP_PORT|WS_PORT|WSS_PORT|WEBSOCKET_PORT|LISTEN_PORT)$/,md=/^PUBLIC_(?:[A-Z0-9]+_)*(?:ORIGIN|URL|HOST|BASE_URL)$/,hd=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","host.docker.internal"]),gd=512*1024,Ci=e=>e.split(z.sep).join("/");function ht(e){try{let t=Do.lstatSync(e);return!t.isFile()||t.isSymbolicLink()||t.size>gd?null:Do.readFileSync(e,"utf8")}catch{return null}}function Qe(e){let t=String(e).trim().replace(/^["']|["']$/g,"");if(!/^(https?|wss?):\/\//i.test(t))return null;try{let n=new URL(t);if(!n.hostname)return null;let s=n.protocol.replace(":",""),o=n.hostname.toLowerCase(),r=n.port?Number(n.port):null,i=n.pathname.replace(/\/+$/,"");return{scheme:s,host:o,port:r,origin:`${s}://${o}${r?":"+r:""}`,path:i}}catch{return null}}function yd(e){let t=String(e).trim().replace(/^["']|["']$/g,"");return!/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:\d{1,5})?(\/[^\s?#]*)?$/i.test(t)||!/[a-z]/i.test(t.split(/[/:]/)[0])?null:Qe("http://"+t)}var Bo=e=>{let t=String(e).trim().replace(/^["']|["']$/g,"");if(!/^\d{1,5}$/.test(t))return null;let n=Number(t);return n>=1&&n<=65535?n:null};function xd(e){let t=new Map;for(let n of e.split(/\r?\n/)){let s=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(n);if(!s)continue;let o=s[2];if(/^["']/.test(o)){let r=o[0],i=o.indexOf(r,1);o=i>0?o.slice(1,i):o.slice(1)}else o=o.replace(/\s+#.*$/,"");t.set(s[1],o)}return t}function Li(e,t,n=0,s=new Set){let o=e.get(t);return o==null||n>5||s.has(t)||(s.add(t),o=o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}]*))?\}/g,(r,i,a)=>{let l=e.has(i)?Li(e,i,n+1,s):void 0;return l!=null&&l!==""?l:a??""}),s.delete(t)),o}function Ze(e,t,n){if(t==null)return null;if(pd.test(e)){let o=Bo(t);return o?{name:e,kind:"port",file:n,port:o}:null}let s=Qe(t)??(/(_URL|_URI|_HOST|_HOSTNAME|_ORIGIN|_ADDR|_ENDPOINT)$/i.test(e)?yd(t):null);return s?{name:e,kind:"url",file:n,...s}:null}function Ei(e,t){let n=[];for(let s of[...e.keys()].sort()){let o=Li(e,s);if(o==null)continue;let r=Ze(s,o,t);r&&n.push(r)}return n}function vd(e){let t=e.split(/\r?\n/).map(c=>c.replace(/\s+#.*$/,"").replace(/\t/g," ")),n=c=>c.length-c.trimStart().length,s=[],o=t.findIndex(c=>/^services\s*:\s*$/.test(c));if(o<0)return s;let r=null,i=null,a=null,l=0;for(o=o+1;o<t.length;o++){let c=t[o];if(!c.trim())continue;let d=n(c),m=c.trim();if(d===0)break;if(r==null&&(r=d),d===r){let f=/^([A-Za-z0-9_.-]+)\s*:\s*$/.exec(m);f&&(i={name:f[1],ports:[],env:new Map,build:null},s.push(i),a=null);continue}if(i){if(d<=r+4&&/^[A-Za-z_]+\s*:/.test(m)&&!m.startsWith("-")){let f=/^([A-Za-z_]+)\s*:\s*(.*)$/.exec(m);a=f[1],l=d,a==="build"&&f[2]&&(i.build=f[2].replace(/^["']|["']$/g,""));continue}if(a==="build"&&/^context\s*:/.test(m)){i.build=m.replace(/^context\s*:\s*/,"").replace(/^["']|["']$/g,"");continue}if(a==="ports"&&m.startsWith("-")){let u=m.slice(1).trim().replace(/^["']|["']$/g,"").replace(/\/\w+$/,"").split(":"),p=u.slice(-2).map(h=>Bo(h));u.length===1&&p[0]?i.ports.push({host:null,container:p[0]}):u.length>=2&&p[0]&&p[1]&&i.ports.push({host:p[0],container:p[1]});continue}if(a==="environment"&&d>l){let f=m.startsWith("-")?/^-\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(m):/^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/.exec(m);f&&i.env.set(f[1],f[2].replace(/^["']|["']$/g,""))}}}return s}function Pi(e,t){let n=[];if(t==="vite"){let s=e.search(/\bproxy\s*:/);if(s<0)return n;let o=e.slice(s,s+2500),r=/["'`](\/[^"'`]*)["'`]\s*:\s*(?:["'`](https?:\/\/[^"'`]+)["'`]|\{[^{}]*?target\s*:\s*["'`](https?:\/\/[^"'`]+)["'`])/g,i;for(;i=r.exec(o);){let a=Qe(i[2]??i[3]);a&&n.push({prefix:i[1].replace(/\/+$/,""),target:a,kind:"vite.config proxy"})}}else if(t==="next"){let s=/source\s*:\s*["'`](\/[^"'`:*]*)[^"'`]*["'`]\s*,\s*destination\s*:\s*["'`](https?:\/\/[^"'`]+?)(?:\/:[^"'`]*)?["'`]/g,o;for(;o=s.exec(e);){let r=Qe(o[2]);r&&n.push({prefix:o[1].replace(/\/+$/,""),target:r,kind:"next.config rewrites"})}}return n}function Ti(e,t,n){let s=g=>Ci(z.relative(e,g)),o=new Map,r=new Map,i=new Map,a=(g,w,S)=>{(g.get(w)??g.set(w,new Set).get(w)).add(S)},l=(g,w,S)=>{let k=i.get(g)??i.set(g,[]).get(g);k.some(y=>y.service===w&&y.via===S)||k.push({service:w,via:S})},c=g=>{let w=[],S=z.resolve(g),k=z.resolve(e);for(let y=0;y<8&&(w.push(S),!(S===k||z.dirname(S)===S||(S=z.dirname(S),!S.startsWith(k))));y++);return w},d=new Map,m=new Map,f=(g,w)=>{let S=g.env.get(w.name)??g.env.set(w.name,[]).get(w.name);S.some(k=>k.file===w.file)||S.push(w),w.kind==="port"&&g.ports.add(w.port)};function u(g,w,S){let k=x=>s(z.join(S,x)),y=x=>ht(z.join(S,x));for(let x of Ln(S))if(x==="fly.toml"){let b=y(x);if(b){let N=bi(b,k(x));for(let $ of N.ports)w.ports.add($);for(let $ of N.kept)f(w,$);N.app&&(l(`${N.app.toLowerCase()}.internal`,g.name,"fly.toml app name"),l(`${N.app.toLowerCase()}.fly.dev`,g.name,"fly.toml app name"))}}else if(/^Dockerfile(\..+)?$/.test(x)){let b=y(x);if(b){let N=_i(b,k(x));for(let $ of N.ports)w.weakPorts.add($);for(let $ of N.kept)f(w,$)}}else if(x==="railway.json"||x==="railway.toml"){let b=y(x);if(b)for(let N of ji(b,k(x),x.endsWith(".json")))f(w,N)}else if(x==="app.json"){let b=y(x);if(b)for(let N of Fi(b,k(x)))f(w,N)}else if(x==="vercel.json"){let b=y(x);if(b)for(let N of $i(b))w.proxies.push({...N,file:k(x)})}else if(x==="netlify.toml"){let b=y(x);if(b)for(let N of Ii(b))w.proxies.push({...N,file:k(x)})}}for(let g of t){let w={env:new Map,ports:new Set,weakPorts:new Set,proxies:[],isServer:!1};o.set(g.name,w);for(let S of c(g.rootPath)){for(let k of ud){let y=ht(z.join(S,k));if(y!=null)for(let x of Ei(xd(y),s(z.join(S,k)))){let b=w.env.get(x.name)??w.env.set(x.name,[]).get(x.name);b.some(N=>N.file===x.file)||b.push(x),x.kind==="port"&&S===z.resolve(g.rootPath)&&/(^|\/)\.env/.test(x.file)&&!/\.example$/.test(x.file)&&w.ports.add(x.port),x.kind==="port"&&S===z.resolve(g.rootPath)&&/\.example$/.test(x.file)&&w.ports.add(x.port)}}if(S===z.resolve(g.rootPath)){try{let k=JSON.parse(ht(z.join(S,"package.json"))??"null"),y=typeof k?.proxy=="string"?Qe(k.proxy):null;y&&w.proxies.push({prefix:"",target:y,kind:'package.json "proxy"',file:s(z.join(S,"package.json"))})}catch{}for(let k of Ln(S)){if(/^vite\.config\.(js|mjs|cjs|ts|mts)$/.test(k)){let y=ht(z.join(S,k));if(y)for(let x of Pi(y,"vite"))w.proxies.push({...x,file:s(z.join(S,k))})}if(/^next\.config\.(js|mjs|cjs|ts)$/.test(k)){let y=ht(z.join(S,k));if(y)for(let x of Pi(y,"next"))w.proxies.push({...x,file:s(z.join(S,k))})}}}S===z.resolve(g.rootPath)&&u(g,w,S);for(let k of Ln(S))if(/^render\.ya?ml$/.test(k)&&!m.has(z.join(S,k))){let y=ht(z.join(S,k));y&&m.set(z.join(S,k),Ni(y,s(z.join(S,k))))}for(let k of Ln(S)){if(!/^docker-compose.*\.ya?ml$/.test(k)||d.has(z.join(S,k)))continue;let y=ht(z.join(S,k));y&&d.set(z.join(S,k),vd(y))}}}for(let[g,w]of[...d].sort((S,k)=>S[0]<k[0]?-1:1)){let S=z.dirname(g);for(let k of w){let y=k.build?z.resolve(S,k.build):null,x=t.find(N=>y&&z.resolve(N.rootPath)===y)??t.find(N=>N.name===k.name||z.basename(N.rootPath)===k.name);if(!x)continue;let b=o.get(x.name);for(let N of k.ports)b.ports.add(N.container),N.host&&b.ports.add(N.host);for(let N of Ei(k.env,s(g)))(b.env.get(N.name)??b.env.set(N.name,[]).get(N.name)).push(N);l(k.name.toLowerCase(),x.name,"docker-compose service name")}}for(let[g,w]of[...m].sort((S,k)=>S[0]<k[0]?-1:1)){let S=z.dirname(g),k=new Map;for(let y of w){let x=z.resolve(S,y.rootDir||"."),b=y.rootDir?t.find($=>z.resolve($.rootPath)===x):null;if(!b&&y.startCommand)for(let $ of y.startCommand.split(/\s+/)){if(!/\.(c|m)?[jt]sx?$/.test($)&&!/^[\w./-]+\/[\w.-]+$/.test($))continue;let F=z.resolve(x,$),H=t.filter(P=>F.startsWith(z.resolve(P.rootPath)+z.sep)).sort((P,K)=>K.rootPath.length-P.rootPath.length)[0];if(H){b=H;break}}if(b=b??t.find($=>$.name===y.name||z.basename($.rootPath)===y.name),!b)continue;k.set(y.name,{target:b,c:y});let N=o.get(b.name);for(let $ of y.kept)f(N,{...$,scoped:!0});l(y.name.toLowerCase(),b.name,"render.yaml service name"),l(`${y.name.toLowerCase()}.onrender.com`,b.name,"render.yaml service name (Render's default public address)")}for(let{target:y,c:x}of k.values())for(let b of x.hostRefs){let N=k.get(b.service);if(!N)continue;let $=[...N.c.kept].find(P=>P.kind==="port")?.port??null,F=b.property==="hostport"&&$,H=b.service.toLowerCase();f(o.get(y.name),{name:b.name,kind:"url",file:s(g),scheme:"http",host:H,port:F?$:null,origin:`http://${H}${F?":"+$:""}`,path:""})}}let p=g=>[...n.get(g.name)?.parseResults?.values()??[]].some(w=>(w.routes??[]).length>0);for(let g of t){let w=o.get(g.name);if(w.isServer=p(g),w.isServer){for(let[S,k]of w.env)if(md.test(S))for(let y of k)y.kind==="url"&&y.file&&(y.scoped||z.posix.dirname(y.file)===(Ci(z.relative(e,g.rootPath))||"."))&&l(y.host,g.name,`${S} in ${y.file} (the server's own public address)`)}}for(let g of t){let w=o.get(g.name);for(let[,S]of n.get(g.name)?.parseResults??[])for(let k of S.httpClients?.listens??[])for(let y of h(w,k.parts)){let x=Bo(y.text);x&&w.ports.add(x)}}for(let g of t)for(let w of o.get(g.name).ports)a(r,w,g.name);for(let g of t)for(let w of o.get(g.name).weakPorts)t.some(S=>o.get(S.name).ports.has(w))||a(r,w,g.name);function h(g,w){let S=[{text:"",evidence:[]}];for(let k of w){let y;if(k.t==="lit")y=[{text:k.v,evidence:[]}];else if(k.t==="env"){let b=g.env.get(k.name)??[];y=[];for(let N of b)y.push({text:N.kind==="port"?String(N.port):N.origin+N.path,evidence:[{env:k.name,file:N.file}]});!y.length&&k.fallback&&(y=h(g,k.fallback).map($=>({text:$.text,evidence:[{env:k.name,file:null,fallback:!0},...$.evidence]})))}else y=[];if(!y.length)return[];let x=[];for(let b of S)for(let N of y)if(x.push({text:b.text+N.text,evidence:[...b.evidence,...N.evidence]}),x.length>=8)break;S=x.slice(0,8)}return S}let v=(g,w)=>{let S=[],k=g.host,y=i.get(k)??[];for(let x of y)S.push(x);if(hd.has(k)||y.length&&y.some(x=>x.via==="docker-compose service name")){let x=g.port??(g.scheme==="https"||g.scheme==="wss",null);if(x)for(let b of r.get(x)??[])S.some(N=>N.service===b)||S.push({service:b,via:`port ${x} (a service listening there)`})}return S.filter(x=>x.service!==w)};return{resolveBase(g,w){let S=o.get(g);if(!S||!w.length)return{status:"unknown"};let k=h(S,w);if(!k.length)return{status:"unknown"};let y=[],x=new Set;for(let $ of k){let F=Qe($.text)??($.text.startsWith("//"),null);if(F){x.add(F.origin);for(let H of v(F,g))y.push({...H,u:F,evidence:$.evidence})}}if(!x.size)return{status:"unknown"};let b=[...new Set(y.map($=>$.service))];if(b.length===0)return{status:"external",origins:[...x].sort()};if(b.length>1)return{status:"ambiguous",services:b.sort()};let N=y[0];return{status:"service",service:N.service,via:N.via,origin:N.u.origin,basePath:N.u.path,evidence:N.evidence.filter(($,F,H)=>H.findIndex(P=>P.env===$.env&&P.file===$.file)===F)}},resolveProxy(g,w){let S=o.get(g);for(let k of S?.proxies??[]){if(k.prefix&&w!==k.prefix&&!w.startsWith(k.prefix+"/"))continue;let y=v(k.target,g),x=[...new Set(y.map(b=>b.service))];if(x.length===1)return{status:"service",service:x[0],via:`${k.kind} ${k.prefix||"/"} -> ${k.target.origin}`,origin:k.target.origin,basePath:k.target.path,strip:k.strip?k.prefix.split("/").filter(Boolean).length:0,evidence:[{env:null,file:k.file}]}}return{status:"unknown"}},portsOf:g=>[...o.get(g)?.ports??[]].sort((w,S)=>w-S),hostClaims:()=>[...i].sort((g,w)=>g[0]<w[0]?-1:1)}}function Ln(e){try{return Do.readdirSync(e).sort()}catch{return[]}}var Tn=e=>String(e).toLowerCase();function Rn(e){let t=[];for(let n of e)n.t==="lit"&&t.length&&t[t.length-1].t==="lit"?t[t.length-1]={t:"lit",v:t[t.length-1].v+n.v}:t.push(n);return t}function Ri(e,t){let n=[];for(let s of e){if(s.t!=="param"){n.push(s);continue}let o=t?.get(s.index);o?n.push(...o):n.push({t:"ref",name:s.name})}return Rn(n)}function Uo(e){if(!e.length)return null;let t=e.slice(),n="none",s=null,o=t[0];if(o.t==="lit"){let c=/^(https?:)\/\/([^/?#]*)(.*)$/.exec(o.v);if(c){n="abs",s=c[2];let d=c[3];if(t=d?[{t:"lit",v:d},...t.slice(1)]:t.slice(1),/^(www\.)?(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)(:\d+)?$/.test(s)===!1&&!/\.(local|internal|svc)$/.test(s)&&!/^[a-z0-9-]+(:\d+)?$/.test(s))return null}else if(!o.v.startsWith("/"))return null}else{for(n="var";t.length&&t[0].t!=="lit";)t.shift();if(!t.length||!t[0].v.startsWith("/"))return null}let r="",i=0,a=!1;for(let c of t){if(a)break;if(c.t==="lit"){let d=c.v.search(/[?#]/);d>=0?(r+=c.v.slice(0,d),a=!0):r+=c.v}else r+="",i++}if(!r.startsWith("/")&&!(r===""&&n==="abs"))return null;r===""&&(r="/");let l=r.split("/").slice(1).map(c=>c.includes("")?":p":c);for(;l.length>1&&l[l.length-1]==="";)l.pop();return{base:n,host:s,segments:l,placeholders:i,literal:n==="none"&&i===0}}function Ai(e){if(!e.length)return[];let t=e[0];if(t.t==="lit"){let s=/^((?:https?|wss?):\/\/[^/?#]*)/.exec(t.v);return s?[{t:"lit",v:s[1]}]:[]}let n=[];for(let s of e){if(s.t==="lit"&&s.v.startsWith("/"))break;n.push(s)}return n}var wd=e=>String(e||"").split("/").filter(Boolean),Oi=e=>[...new Set(e)];function Mi(e){let t=e.evidence??[];return{env:Oi(t.filter(n=>n.env).map(n=>n.env)),files:Oi(t.filter(n=>n.file).map(n=>n.file)),origin:e.origin,via:e.via,...t.some(n=>n.fallback)?{usedFallback:!0}:{}}}var Hi=(e,t)=>"base URL "+(e.env.length?e.env.join(", ")+(e.files.length?" in "+e.files.join(", "):"")+" = ":e.files.length?"(from "+e.files.join(", ")+") ":"")+e.origin+" belongs to "+t+" ("+e.via+")",Sd=e=>{let t=String(e).split(/[?#]/)[0].split("/").slice(1).map(n=>n.startsWith(":")||/^\{.*\}$/.test(n)||n==="*"?":p":n);for(;t.length>1&&t[t.length-1]==="";)t.pop();return t};function Di(e,t){if(e.length===t.length){let n=!0,s=!0;for(let o=0;o<e.length;o++){let r=e[o],i=t[o];if(r!==i&&(n=!1),!(r===i||r===":p"||i===":p")){s=!1;break}}if(n)return 3;if(s)return 2}if(e[0]==="api"&&e.length>1){let n=e.slice(1);if(/^v\d+$/.test(n[0])&&n.length>1&&(n=n.slice(1)),n.length===t.length&&n.every((s,o)=>s===t[o]||s===":p"||t[o]===":p"))return 1}return 0}function kd(e,t,n,s,o){let r=(n.importBindings??[]).find(m=>m.local===s);if(!r)return null;let i=ze(r.source,t,o);if(!i)return null;let a=e.parseResults.get(i),l=m=>e.nodes.find(f=>f.filePath===i&&f.name===m&&f.type!=="moduleRoot")?.id??null;if(r.kind==="named"&&r.imported)return l(r.imported);let c=a?.exportBindings;if(c?.default&&c.default!=="<anon>")return l(c.default);let d=Object.keys(c?.named??{});return d.length===1?l(d[0]):null}function Nd(e){let t=[],n=[...e.parseResults.keys()];for(let[s,o]of e.parseResults){let r=e.nodes.filter(l=>l.filePath===s);if(r[0]?.category!=="backend")continue;let i=Ue(s,o),a=de(s,e.nodes);for(let l of o.routes??[]){let c=null;l.isInlineHandler?c=i.get(l):l.nest?c=r.find(m=>m.type==="classMethod"&&m.className===l.nest.className&&m.name===l.nest.methodName)?.id??null:l.handlerName&&a.has(l.handlerName)?c=a.get(l.handlerName):l.handlerName&&(c=kd(e,s,o,l.handlerName,n));let d=!1;c||(c=ue(l.startLine,r)?.id??null,d=!0),c&&t.push({method:Tn(l.method),path:l.path,segments:Sd(l.path),literal:!/[:*{]/.test(l.path),nodeId:c,file:s,line:l.startLine,fallback:d})}}return t}var bd=/^(ws|uws|websocket|@nestjs\/platform-ws|@fastify\/websocket|fastify-websocket|express-ws)$/,_d=/^(socket\.io|@nestjs\/platform-socket\.io|socket\.io-client)$/;function Bi(e){let t=[...e].some(s=>_d.test(s)),n=[...e].some(s=>bd.test(s));return t&&n?"unknown":t?"socketio":n?"ws":null}function $d(e){let t=[],n=new Set;for(let[,s]of e.parseResults)for(let o of s.imports??[])n.add(o.source);for(let[s,o]of e.parseResults){let r=o.socketListeners??[],i=r.find(h=>h.eventName==="connection");if(!i)continue;let a=Ue(s,o),l=de(s,e.nodes),c=h=>h.isInlineHandler?a.get(h):h.handlerName&&l.has(h.handlerName)?l.get(h.handlerName):null,d=c(i);if(!d)continue;let m=h=>i.handlerStartLine!=null&&h.startLine>=i.handlerStartLine&&h.startLine<=i.handlerEndLine,f=r.find(h=>h.eventName==="message"&&m(h))??r.find(h=>h.eventName==="message"),u=o.httpClients?.wsServers??[],p=Bi(new Set((o.imports??[]).map(h=>h.source)))??Bi(n)??"unknown";t.push({filePath:s,nodeId:d,line:i.startLine,messageNodeId:f?c(f):null,messageLine:f?.startLine??null,pathParts:u.find(h=>h.path)?.path??null,kind:p})}return t}function Ui(e,t,n={}){let s=n.repoRoot?Ti(n.repoRoot,e,t):null,o=[],r=new Set,i={restCalls:0,restLinked:0,wsClients:0,wsLinked:0,wsSends:0,wsSendsLinked:0},a=c=>{let d=[c.fromService,c.fromNodeId,c.toService,c.toNodeId,c.via,c.key].join("\0");r.has(d)||(r.add(d),o.push(c))},l=new Map;for(let c of e){let d=t.get(c.name);d&&l.set(c.name,{routes:Nd(d),wsServers:$d(d)})}for(let c of e){let d=t.get(c.name);if(!d)continue;let m=[...d.parseResults.keys()],f=new Map,u=new Map;for(let[y,x]of d.parseResults){let b=x.httpClients;if(b){for(let N of b.httpInstances??[])(f.get(N.name)??f.set(N.name,[]).get(N.name)).push(N);for(let N of b.httpCalls??[])(N.parts.some(F=>F.t==="param")||N.method&&typeof N.method=="object")&&N.fn?.name&&(u.get(N.fn.name)??u.set(N.fn.name,[]).get(N.fn.name)).push({filePath:y,call:N})}}let p=y=>{if(!y.startsWith("inst:")&&!y.startsWith("obj:"))return[];let x=f.get(y.slice(y.indexOf(":")+1));return x&&x.length===1?x[0].parts:y.startsWith("obj:")?null:[{t:"ref",name:"?"}]},h=[],v=(y,x)=>ue(x,d.nodes.filter(b=>b.filePath===y)),g=new Set,w=y=>y.parts.some(x=>x.t==="param")||y.method&&typeof y.method=="object";for(let[y,x]of d.parseResults){let b=x.httpClients;if(b){for(let N of b.httpCalls??[]){if(w(N))continue;let $=p(N.client);if($===null)continue;let F=v(y,N.line);F&&h.push({filePath:y,line:N.line,nodeId:F.id,method:N.method,parts:Rn([...$,...N.parts]),via:N.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let N of b.pathCallsites??[]){let $=u.get(N.callee);if($)for(let F of $){let H=F.filePath===y;if(!H){let D=(x.importBindings??[]).find(R=>R.local===N.callee||R.imported===N.callee);D&&ze(D.source,y,m)===F.filePath&&(H=!0)}if(!H)continue;let P=new Map(N.args.map(D=>[D.i,D.parts])),K=typeof F.call.method=="object"&&F.call.method?(()=>{let D=P.get(F.call.method.param);return D&&D.length===1&&D[0].t==="lit"?D[0].v.toUpperCase():"?"})():F.call.method,U=v(y,N.line);U&&(g.add(F.call),h.push({filePath:y,line:N.line,nodeId:U.id,method:K,parts:Ri([...p(F.call.client),...F.call.parts],P),via:F.call.client,wrapper:N.callee}))}}}}for(let[y,x]of d.parseResults)for(let b of x.httpClients?.httpCalls??[]){if(!w(b)||g.has(b))continue;let N=p(b.client);if(N===null)continue;let $=v(y,b.line);$&&h.push({filePath:y,line:b.line,nodeId:$.id,method:typeof b.method=="object"&&b.method?"?":b.method,parts:Ri([...N,...b.parts],null),via:b.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let y of h){let x=Uo(y.parts);if(!x)continue;i.restCalls++;let b=0,N=[];for(let U of e){if(U.name===c.name)continue;let D=l.get(U.name);if(D)for(let R of D.routes){if(!(y.method==="?"||y.method==null||R.method===Tn(y.method)||R.method==="all"||R.method==="use"))continue;let ee=Di(x.segments,R.segments);ee&&(ee>b&&(b=ee,N.length=0),ee===b&&N.push({service:U.name,route:R}))}}let $={status:"unknown"};if(s){let U=Rn(y.parts);if(x.base==="none"?$=s.resolveProxy(c.name,"/"+x.segments.join("/")):$=s.resolveBase(c.name,Ai(U)),$.status==="service"){let D=wd($.basePath);if(D.length||$.strip){let R=[...D,...x.segments.slice($.strip||0)];for(let G of l.get($.service)?.routes??[])(y.method==="?"||y.method==null||G.method===Tn(y.method)||G.method==="all"||G.method==="use")&&Di(R,G.segments)&&!N.some(ne=>ne.service===$.service&&ne.route.nodeId===G.nodeId)&&N.push({service:$.service,route:G,viaBasePath:!0})}}}if(!N.length)continue;let F=new Set(N.map(U=>U.service+"\0"+U.route.nodeId)),H=typeof y.method=="string"&&y.method!=="?",P=b===3&&x.literal&&H&&F.size===1&&N[0].route.literal&&!N[0].route.fallback&&N[0].route.method===Tn(y.method),K=[];x.base==="var"&&K.push("base URL is a variable, so the target service is guessed from the path"),x.base==="abs"&&K.push("absolute URL"),x.placeholders&&K.push("path has parameters"),b===1&&K.push("leading /api removed from the client path"),b===2&&K.push("route parameters matched fuzzily"),H||K.push("method not known"),F.size>1&&K.push(F.size+" candidate routes"),N.some(U=>U.route.fallback)&&K.push("route handler not resolved: linked to the function that registers the route"),$.status==="external"&&K.push("base URL is "+$.origins.join(" / ")+", which no service of this repo owns"),$.status==="ambiguous"&&K.push("base URL could belong to "+$.services.join(" or "));for(let U of N){i.restLinked++;let D=!P&&$.status==="service"&&$.service===U.service&&!U.route.fallback,R=D?Mi($):null,G=P?"exact":D?"resolved":"inferred",ee=!P&&$.status==="service"&&$.service!==U.service?["base URL belongs to "+$.service+", not this service"]:[];a({fromService:c.name,fromNodeId:y.nodeId,toService:U.service,toNodeId:U.route.nodeId,via:"httpCall",key:`${H?y.method:"ANY"} ${"/"+x.segments.join("/")}`,confidence:G,method:H?y.method:null,url:"/"+x.segments.join("/"),client:y.via,...y.wrapper?{wrapper:y.wrapper}:{},line:y.line,...P?{}:D?{reason:Hi(R,U.service)+(H?"":"; method not known"),resolvedFrom:R}:{reason:[...K,...ee].join("; ")||"path-only match"}})}}let S=[];for(let[y,x]of d.parseResults)for(let b of x.httpClients?.wsClients??[])S.push({filePath:y,w:b});let k=y=>y.client==="io"?"socketio":"ws";for(let{filePath:y,w:x}of S){let b=v(y,x.line);if(!b)continue;i.wsClients++;let N=Rn(x.parts),$=/^wss?:\/\//.test(N[0]?.v??"")?Uo([{t:"lit",v:N[0].v.replace(/^ws(s?):/,"http$1:")},...N.slice(1)]):Uo(N),F=s&&$?s.resolveBase(c.name,Ai(N)):{status:"unknown"};for(let H of e)if(H.name!==c.name)for(let P of l.get(H.name)?.wsServers??[]){if(P.kind!=="unknown"&&P.kind!==k(x))continue;let K=P.pathParts&&P.pathParts.every(ee=>ee.t==="lit")?"/"+P.pathParts.map(ee=>ee.v).join("").replace(/^\//,""):null,U=$?"/"+$.segments.join("/"):null;if(K&&U&&K!==U&&K!=="/"&&U!=="/")continue;let D=!!($&&$.literal&&K&&U===K&&P.kind!=="unknown"),R=!D&&F.status==="service"&&F.service===H.name,G=R?Mi(F):null;i.wsLinked++,a({fromService:c.name,fromNodeId:b.id,toService:H.name,toNodeId:P.nodeId,via:"webSocket",key:U??"(url unknown)",confidence:D?"exact":R?"resolved":"inferred",url:U,client:x.client,line:x.line,...D?{}:R?{reason:Hi(G,H.name),resolvedFrom:G}:{reason:"WebSocket connection matched to a WebSocket server of another service ("+($?.base==="var"?"URL base is a variable":"no path on the server to compare")+(F.status==="external"?"; base URL is "+F.origins.join(" / ")+", which no service of this repo owns":"")+")"}})}}if(S.length){let y=new Set(S.map(({w:x})=>k(x)));for(let[x,b]of d.parseResults)for(let N of b.httpClients?.wsSends??[]){let $=v(x,N.line);if($){i.wsSends++;for(let F of e)if(F.name!==c.name)for(let H of l.get(F.name)?.wsServers??[])!H.messageNodeId||H.kind!=="unknown"&&!y.has(H.kind)||(i.wsSendsLinked++,a({fromService:c.name,fromNodeId:$.id,toService:F.name,toNodeId:H.messageNodeId,via:"webSocketMessage",key:"message",eventName:"message",confidence:"inferred",client:N.recv,line:N.line,reason:"a message sent over a socket whose payload is built at run time; delivered to the message listener of a WebSocket server of another service"}))}}}}if(n.serverPush!==!1){let c=new Map;for(let m of o)if(m.via==="webSocket"){let f=m.fromService+"\0"+m.toService;(c.get(f)??c.set(f,[]).get(f)).push(m)}let d=new Map;for(let m of c.values())(d.get(m[0].toService)??d.set(m[0].toService,new Set).get(m[0].toService)).add(m[0].fromService);for(let[,m]of[...c].sort((f,u)=>f[0]<u[0]?-1:1)){let f=m[0].fromService,u=m[0].toService,p=t.get(f),h=t.get(u);if(!p||!h||!(l.get(u)?.wsServers??[]).length)continue;let v=new Set(m.map(k=>k.fromNodeId.split("::")[0])),g=[];for(let[k,y]of p.parseResults){if(!v.has(k))continue;let x=de(k,p.nodes),b=Ue(k,y),N=p.nodes.filter($=>$.filePath===k);for(let $ of y.httpClients?.wsReceivers??[]){let F=$.handlerName&&x.get($.handlerName)||ue($.line,N)?.id;F&&g.push({id:F,line:$.line})}for(let $ of y.socketListeners??[]){if($.eventName!=="message")continue;let F=$.isInlineHandler?b.get($):$.handlerName&&x.get($.handlerName)||null;F&&g.push({id:F,line:$.startLine})}}let w=new Set(p.resolvedEdges.filter(k=>k.resolved&&k.targetNodeId&&k.type!=="returnValue").map(k=>k.fromNodeId));for(let k=g.length-1;k>=0;k--)w.has(g[k].id)||g.splice(k,1);if(!g.length)continue;let S=d.get(u)?.size??1;for(let[k,y]of h.parseResults){let x=h.nodes.filter(b=>b.filePath===k);for(let b of[...y.httpClients?.wsSends??[],...y.httpClients?.wsServerSends??[]]){let N=ue(b.line,x);if(N)for(let $ of g)i.wsPushLinked=(i.wsPushLinked??0)+1,a({fromService:u,fromNodeId:N.id,toService:f,toNodeId:$.id,via:"webSocketDelivery",key:"message",eventName:"message",confidence:"inferred",client:b.recv,line:b.line,receiverLine:$.line,reason:"a message the server sends over a WebSocket (payload built at run time) is taken in by the message handler of "+f+", which connects to this server"+(S>1?"; "+S+" services connect to this server, so it may be meant for another one":""),...S>1?{candidates:S}:{}})}}}}return o.sort((c,d)=>c.fromService+c.fromNodeId+c.via+c.key+c.toService+c.toNodeId<d.fromService+d.fromNodeId+d.via+d.key+d.toService+d.toNodeId?-1:1),{edges:o,stats:i}}function zi(e,t){let n=new Map;for(let[s,o]of e){let r=t.filter(a=>a.filePath===s),i=o.rawSocketTypeChecks??[];for(let a of i){let l=ue(a.startLine,r);l&&n.set(a.eventName,l.id)}}return n}import Id from"node:fs";import Fd from"node:path";function Wi(e){let t=["index.html","public/index.html","client/index.html","frontend/index.html","src/index.html"];for(let n of t){let s=Fd.join(e,n);if(Id.existsSync(s))return s}return null}import An from"node:fs";import On from"node:path";var jd=new Set(["node","tsx","ts-node","nodemon","bun","deno","ts-node-esm"]),Cd=new Set(["watch","run","start","dev"]),Ed=/\.[cm]?[jt]sx?$/,Pd=["start","dev","serve","run"];function Ld(e){for(let t of String(e).split(/&&|\|\||;|\|/)){let n=t.trim().split(/\s+/).filter(Boolean).map(o=>o.replace(/^["']|["']$/g,"")),s=n.findIndex(o=>jd.has(On.basename(o).replace(/\.cmd$/,"")));if(!(s<0)){for(let o of n.slice(s+1))if(!(o.startsWith("-")||Cd.has(o)||o.includes("="))){if(Ed.test(o))return o;break}}}return null}var Td=e=>String(e).replace(/^@[^/]+\//,"");function qi(e){let t;try{t=JSON.parse(An.readFileSync(On.join(e,"package.json"),"utf8"))}catch{return[]}let n=[],s=(o,r,i={})=>{if(typeof o!="string"||!o)return;let a=r==="script"?null:En(e,o,t);a?n.push({file:a.file,kind:r,...i,mappedFrom:o,mappedBy:a.how}):n.push({file:On.resolve(e,o),kind:r,...i})};if(typeof t.bin=="string")s(t.bin,"bin",{binName:Td(t.name??On.basename(e))});else if(t.bin&&typeof t.bin=="object")for(let[o,r]of Object.entries(t.bin))s(r,"bin",{binName:o});for(let o of Pd){let r=t.scripts?.[o]&&Ld(t.scripts[o]);r&&s(r,"script")}return s(t.main,"main"),n}function Gi(e){try{let t=An.openSync(e,"r"),n=Buffer.alloc(120),s=An.readSync(t,n,0,120,0);return An.closeSync(t),/^#!.*\b(node|tsx|ts-node|bun)\b/.test(n.toString("utf8",0,s).split(/\r?\n/)[0])}catch{return!1}}import Mn from"node:fs";import gt from"node:path";var Rd=50,Ad=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Ji=["",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts","/index.js","/index.ts","/index.mjs","/index.cjs","/index.tsx","/index.jsx"];function zo(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=zo(t);if(n)return n}return null}if(e&&typeof e=="object")for(let t of["import","node","require","default"]){let n=zo(e[t]);if(n)return n}return null}function Ki(e,t){let n;try{n=JSON.parse(Mn.readFileSync(gt.join(e,"package.json"),"utf8"))}catch{return null}let s=n.exports,o=typeof s=="string"||Array.isArray(s)?s:s&&typeof s=="object"?s["."]??(Object.keys(s).some(c=>c.startsWith("."))?null:s):null,r=zo(o)??(typeof n.module=="string"?n.module:null)??(typeof n.main=="string"?n.main:null);if(!r)return null;let i=new Set(t.map(c=>gt.resolve(c))),a=gt.resolve(e,r);for(let c of Ji)if(i.has(a+c))return t.find(d=>gt.resolve(d)===a+c);let l=[];try{l=Mn.readdirSync(e).filter(c=>Ad.test(c)).sort()}catch{}for(let c of l){let d;try{d=Mn.readFileSync(gt.join(e,c),"utf8")}catch{continue}let m=/\bentry(?:Points)?\s*:\s*[\[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/.exec(d);if(!m)continue;let f=gt.resolve(e,m[1]);for(let u of Ji)if(i.has(f+u))return t.find(p=>gt.resolve(p)===f+u)}return null}function Vi(e,t,n,s,o=null){let r=new Map;for(let h of n){let v=r.get(h.filePath);v||r.set(h.filePath,v=[]),v.push(h)}let i=new Map,a=(h,v)=>{v&&(!i.has(v.id)||h<i.get(v.id))&&i.set(v.id,h)},l=new Map,c=(h,v)=>{let g=l.get(h);if(!g){g=new Map;let w="";try{w=Mn.readFileSync(h,"utf8")}catch{}for(let S of w.matchAll(/^[ \t]*(?:export\s+)?const\s+([\w$]+)\s*(?::[^=\n]+)?=\s*([\w$]+)\s*(?:as\s+[^;\n]+)?;?[ \t]*$/gm))S[1]!==S[2]&&g.set(S[1],S[2]);l.set(h,g)}return g.get(v)??null},d=(h,v)=>(r.get(h)??[]).find(g=>(g.type==="function"||g.type==="arrowFunction")&&g.name===v),m=(h,v)=>(r.get(h)??[]).filter(g=>g.type==="classMethod"&&g.className===v&&g.name!=="constructor"&&!/^[_#]/.test(g.name)),f=new Set;function u(h,v,g,w=0){let S=d(h,g);if(S){a(v,S);return}let k=m(h,g);for(let F of k)a(`${v}.${F.name}`,F);if(k.length||!o)return;let y=o.resolveName(h,g);if(y){a(v,y);return}let x=o.bindingFor(h,g),b=x&&w<3?o.resolveImport(h,x.source,x.kind,x.imported):null;if(b?.file&&b.local&&b.local!=="default"&&c(b.file,b.local)){u(b.file,v,b.local,w+1);return}let N=o.classForImport(h,g);if(N?.className)for(let F of m(N.file,N.className))a(`${v}.${F.name}`,F);if(N?.className)return;let $=c(h,g);$&&w<3&&u(h,v,$,w+1)}function p(h,v,g){let w=h+"|"+(g?[...g.keys()].sort().join(","):"*");if(f.has(w)||v>3)return;f.add(w);let S=t.get(h)?.exportBindings;if(!S)return;let k=y=>!g||g.has(y);for(let[y,x]of Object.entries(S.named??{}))k(y)&&u(h,g?.get(y)??y,x);S.default&&k("default")&&S.default!=="<anon>"&&u(h,g?.get("default")??S.default,S.default);for(let y of S.reexports??[]){if(!k(y.exported))continue;let x=ze(y.source,h,s);x&&p(x,v+1,new Map([[y.imported,g?.get(y.exported)??y.exported]]))}for(let y of S.stars??[]){let x=ze(y,h,s);x&&(g?p(x,v+1,g):p(x,v+1,null))}}return p(e,0,null),[...i].map(([h,v])=>({name:v,nodeId:h})).sort((h,v)=>h.name<v.name?-1:h.name>v.name?1:h.nodeId<v.nodeId?-1:1).slice(0,Rd)}De();import Yi from"node:path";import{fileURLToPath as Od}from"node:url";import{Parser as Xi,Language as Md}from"web-tree-sitter";var Qh=Yi.dirname(Od(globalThis.__canopyUrl("src/stage2_parse/initHtmlParser.js")));async function Zi(){await Xi.init();let e=new Xi,t=Yi.join(Ae("tree-sitter-html"),"tree-sitter-html.wasm"),n=await Md.load(t);return e.setLanguage(n),{parser:e,language:n}}function Qi(e,t){let s=oe(t,"htmlScriptRoot.scm").matches(e.rootNode);for(let o of s){let r=o.captures.find(a=>a.name==="attr_name"),i=o.captures.find(a=>a.name==="script_src");if(r&&r.node.text==="src"&&i)return i.node.text}return null}function ea(e,t,n){let s=[];e.forEach((l,c)=>{l.steps.forEach(d=>{if(!d.hasOwnSubTrace)return;let m=e.findIndex((f,u)=>u!==c&&f.steps[0]?.nodeId===d.nodeId);m!==-1&&s.push({fromWorkflowIndex:c,toWorkflowIndex:m,atNodeId:d.nodeId})})});let o=new Map;for(let l of t)o.set(l.id,l.serviceName??null);let r=new Map;function i(l,c,d,m){if(!l||!c||l===c)return;let f=`${l} -> ${c} -> ${d}`;r.has(f)?r.get(f).count+=1:r.set(f,{fromService:l,toService:c,viaMatchType:d,count:1});let u=r.get(f);m==="exact"?u.exact=(u.exact??0)+1:m==="inferred"?u.inferred=(u.inferred??0)+1:m==="resolved"&&(u.resolved=(u.resolved??0)+1)}for(let l of n){if(!l.resolved||!l.fromNodeId||!l.targetNodeId)continue;let c=o.get(l.fromNodeId)??null,d=o.get(l.targetNodeId)??null;i(c,d,l.matchType,l.confidence)}let a=Array.from(r.values());return{workflowLinks:s,serviceLinks:a}}var Bd=V.dirname(Hd(globalThis.__canopyUrl("src/index.js"))),ta=24*1e3*1e3;async function Wo(e,t={}){e=V.resolve(e),console.log(`
|
|
20
|
+
return ${a};})()`}function or(e,t,n,r){if(!e)return{targetId:null,via:null};if(n.has(e))return{targetId:n.get(e),via:"in-file"};if(r)for(let[,o]of r){let s=he(o,t);if(s.has(e))return{targetId:s.get(e),via:"cross-file"}}return{targetId:null,via:null}}function Zi(e,t,n,r,o,s=[],i=null){if(!n.some(c=>!c.isInlineHandler)&&!r.some(c=>!c.isInlineHandler)&&!s.some(c=>!c.isInlineHandler))return e;let a=e.map(c=>({...c}));for(let c of n){if(c.isInlineHandler)continue;let l=c.nest?e.find(u=>u.type==="classMethod"&&u.filePath===t&&u.className===c.nest.className&&u.name===c.nest.methodName):null,{targetId:d,via:f}=c.nest?{targetId:l?.id??null,via:"in-file"}:or(c.handlerName,e,o,i);if(d){let u=a.find(h=>h.id===d);u&&(u.isEntryPoint=!0,u.trigger={type:"route",label:`${c.method.toUpperCase()} ${c.path}`,resolvedVia:f})}}for(let c of r){if(c.isInlineHandler)continue;let{targetId:l,via:d}=or(c.handlerName,e,o,i);if(l){let f=a.find(u=>u.id===l);f&&(f.isEntryPoint=!0,f.trigger={type:"listener",label:c.eventName,resolvedVia:d})}}for(let c of s){if(c.isInlineHandler)continue;let{targetId:l,via:d}=or(c.handlerName,e,o,i);if(l){let f=a.find(u=>u.id===l);f&&(f.isEntryPoint=!0,f.trigger={type:"socketListener",label:c.eventName,resolvedVia:d})}}return a}function rr(e){let t=new Map,n=new Map;for(let r of e)r.resolved&&(t.set(r.fromNodeId,(t.get(r.fromNodeId)??0)+1),n.set(r.targetNodeId,(n.get(r.targetNodeId)??0)+1));return{outgoing:t,incoming:n}}function Qi(e,t,n=rr(t)){if(e.type==="moduleRoot")return 0;let r=n.outgoing.get(e.id)??0,o=n.incoming.get(e.id)??0,s=e.exported?1.5:1;return r/(o+1)*s}function ea(e,t){let n=rr(t),r=new Set;for(let i of e)n.incoming.has(i.id)&&r.add(i.filePath);let s=e.filter(i=>!(i.isEntryPoint||i.type==="moduleRoot"||!n.incoming.has(i.id)&&r.has(i.filePath))).map(i=>({...i,fallbackScore:Qi(i,t,n)}));return s.sort((i,a)=>a.fallbackScore-i.fallbackScore),s.slice(0,15)}function sr(e){let t=new Map;for(let n of e)!n.resolved||!n.fromNodeId||!n.targetNodeId||(t.has(n.fromNodeId)||t.set(n.fromNodeId,[]),t.get(n.fromNodeId).push({targetNodeId:n.targetNodeId,line:n.line??null,column:n.column??null,branchPath:n.branchPath??[],edgeType:n.type}));return t}function ir(e,t,n,r=8){let o=new Set([e]),s=c=>n.find(l=>l.id===c)?.category??"unknown",i=[{nodeId:e,depth:0,parentNodeId:null,category:s(e)}],a=[{nodeId:e,depth:0}];for(;a.length>0;){let c=a.shift();if(c.depth>=r)continue;let l=t.get(c.nodeId)||[];for(let d of l){let f=d.targetNodeId;if(o.has(f))continue;o.add(f);let u={nodeId:f,depth:c.depth+1,parentNodeId:c.nodeId,category:s(f),callLine:d.line,callColumn:d.column,branchPath:d.branchPath,edgeType:d.edgeType};i.push(u),a.push(u)}}return i}function ta(e,t,n){return t.filter(o=>o.filePath===e.filePath&&o.id!==e.id&&o.type!=="moduleRoot").filter(o=>!n.some(i=>i.resolved&&i.targetNodeId===o.id))}function na(e,t,n){if(e.type==="moduleRoot")return!1;if(t.some(a=>a.resolved&&a.targetNodeId===e.id&&a.matchType==="crossLayer")||t.filter(a=>a.resolved&&a.fromNodeId===e.id).length>=4||new Set((e.returns||[]).map(a=>a.condition).filter(a=>a!==null)).size>=3)return!0;if(t.some(a=>a.resolved&&a.targetNodeId===e.id)&&!n.some(c=>c.filePath===e.filePath&&c.id!==e.id&&c.type!=="moduleRoot"&&t.some(l=>l.resolved&&l.targetNodeId===c.id))){let c=ta(e,n,t);if(c.length>0)return e.lexicalSiblings=c.map(l=>l.id),!0}return!1}function oa(e,t,n,r,o=8,s=null){let i=[],a=new Set(e.map(l=>l.id)),c=[...e];for(;c.length>0;){let l=c.shift(),d=ir(l.id,t,n,o);i.push({entryPointId:l.id,entryPointName:l.name,trigger:l.trigger??null,steps:d});let f=s?new Set(ir(l.id,s,n,o).map(u=>u.nodeId)):null;for(let u of d){if(f&&!f.has(u.nodeId)||u.nodeId===l.id||a.has(u.nodeId))continue;let h=n.find(p=>p.id===u.nodeId);h&&na(h,r,n)&&(a.add(h.id),u.hasOwnSubTrace=!0,h.lexicalSiblings&&(u.lexicalSiblings=h.lexicalSiblings),c.push({id:h.id,name:h.name,trigger:null}))}}return i}function ra(e,t,n=gs){return e.filter((r,o)=>{if(o===0)return!0;let s=t.find(i=>i.id===r.nodeId);return s?!n.some(i=>s.name.toLowerCase().includes(i)):!0})}function sa(e){return e.steps.filter(n=>n.depth>0).map(n=>n.nodeId).sort().join(" | ")}function ia(e){let t=new Map;for(let n of e){let r=sa(n),o=r===""?`__no_calls__${n.entryPointName}`:r;t.has(o)||t.set(o,[]),t.get(o).push(n)}return t}function aa(e){let t=e[0];return{steps:t.steps,entryPointNames:e.map(n=>n.entryPointName),occurrences:e.length,name:t.entryPointName,trigger:t.trigger,tier:e.some(n=>n.origin==="physical")?"physical":"guessed",tierOrigin:e.some(n=>n.origin==="physical")?"physical":t.origin}}import zn from"node:path";function ca(e){if(!e.trigger)return null;if(e.trigger.type==="route")return`${e.trigger.label.split(" ")[1].split("/").filter(Boolean).join(" ").replace(/[-_]/g," ").split(" ").map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")} Flow`;if(e.trigger.type==="listener"){let t=e.trigger.label;return`${t.charAt(0).toUpperCase()+t.slice(1)} Flow`}return null}function la(e){return e.name.replace(/([A-Z])/g," $1").trim().split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}var da=60,mf=24;function fa(e,t=null){let n=e.map(r=>{let o=ca(r),s=r.trigger?.workflowName??o??la(r);return{...r,name:s}});return t?.nodes?vf(n,t.nodes):n}var ar=(e,t)=>e.length>t?e.slice(0,t-1)+"\u2026":e,hf=new Set(["function","arrowFunction","classMethod"]);function gf(e){let t=new Map(e.map(o=>[o.id,o])),n=new Map,r=o=>{let s=n.get(o);return s||(s=e.filter(i=>i.filePath===o&&hf.has(i.type)),n.set(o,s)),s};return o=>{let s=t.get(o.steps[0].nodeId);if(!s)return[null,null,null];let i=null;if(s.type==="classMethod")i=s.className;else{let l=null;for(let d of r(s.filePath))d===s||!(d.startLine<=s.startLine&&d.endLine>=s.endLine)||d.startLine===s.startLine&&d.endLine===s.endLine||(!l||d.endLine-d.startLine<l.endLine-l.startLine)&&(l=d);l&&(i=l.type==="classMethod"?l.className:l.name)}let a=null;if(o.trigger?.type==="route")a=String(o.trigger.label).split(" ")[0];else if(o.trigger?.type==="listener"){let l=/::listener:([^.#]+)\./.exec(s.id);l&&(a=l[1])}let c=zn.basename(s.filePath,zn.extname(s.filePath));return c==="index"&&(c=zn.basename(zn.dirname(s.filePath))),[i||null,a||null,c||null]}}var yf=(e,t)=>{let n=t.map(r=>ar(r,mf)).join(", ");return e.endsWith(")")?e.slice(0,-1)+", "+n+")":e+" ("+n+")"};function vf(e,t){let n=gf(t),r=e.map(i=>({w:i,base:i.name,parts:[],used:new Set,stuck:!1,q:null})),o=i=>i.parts.length?yf(i.base,i.parts):i.base,s=()=>{let i=new Map;for(let a of r){let c=o(a);(i.get(c)??i.set(c,[]).get(c)).push(a)}return[...i.values()].filter(a=>a.length>1)};for(let i=0;i<4;i++){let a=!1;for(let c of s()){if(c.some(u=>u.stuck))continue;for(let u of c)u.q??=n(u.w);let l=[0,1,2].filter(u=>c.every(h=>!h.used.has(u))),d=l.find(u=>new Set(c.map(h=>h.q[u]??"")).size>1),f=d!==void 0;if(f||(d=l.find(u=>c.every(h=>h.q[u]))),d===void 0){for(let u of c)u.stuck=!0;continue}for(let u of c)u.used.add(d),u.q[d]&&u.parts.push(u.q[d]),f||(u.stuck=!0);a=!0}if(!a)break}for(let i of s())i.sort((a,c)=>a.w.steps[0].nodeId<c.w.steps[0].nodeId?-1:a.w.steps[0].nodeId>c.w.steps[0].nodeId?1:0),i.forEach((a,c)=>{c>0&&(a.suffix=` (${c+1})`)});return r.map(i=>{let a=o(i);return i.suffix&&(a=ar(a,da-i.suffix.length)+i.suffix),{...i.w,name:ar(a,da)}})}var xf=e=>e;function ua(e,t){let n=new Map;for(let[r,o]of e){let s=t.filter(l=>l.filePath===r);if(s[0]?.category!=="backend")continue;let i=o.routes??[],a=qe(r,o),c=he(r,t);for(let l of i){let d=qt(l.path);if(l.isInlineHandler){let u=a.get(l);n.set(d,u);continue}if(l.nest){let u=xf(s).find(h=>h.type==="classMethod"&&h.className===l.nest.className&&h.name===l.nest.methodName);u&&n.set(d,u.id);continue}if(!l.handlerName||!c.has(l.handlerName))continue;let f=c.get(l.handlerName);n.set(d,f)}}return n}import $t from"node:fs";import ne from"node:path";var Wn=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],wf=/(^|\/)(dist|build|out|built|compiled|esm|cjs|lib|output)(\/|$)/,pa=/(^|\/)(dist|build|out|built|compiled|esm|cjs|output)(\/|$)/,Sf=/\b(esbuild|tsup|tsdown|tsc|rollup|webpack|ncc|swc|babel|vite|parcel|bun\s+build|pkg|unbuild|microbundle|rspack)\b/,kf=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild|rspack)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Ve=e=>{try{return $t.statSync(e).isFile()}catch{return!1}},cr=e=>e.split(ne.sep).join("/"),lr=e=>{if(Ve(e)&&Wn.includes(ne.extname(e))&&!/\.d\.ts$/.test(e))return e;let t=e.replace(/\.(m|c)?js$/,"");for(let n of Wn)if(Ve(t+n)&&!/\.d\.ts$/.test(t+n))return t+n;return null},Gn=(e,t)=>{let n=ne.relative(e,t);return n&&!n.startsWith("..")&&!ne.isAbsolute(n)&&!/(^|[\\/])node_modules([\\/]|$)/.test(n)};function Nf(e,t){let n=Ve(t+".map")?t+".map":null;if(!n&&Ve(t))try{let a=$t.readFileSync(t,"utf8").slice(-400),c=/sourceMappingURL=([^\s*]+)/.exec(a);if(c&&!c[1].startsWith("data:")){let l=ne.resolve(ne.dirname(t),c[1]);Ve(l)&&(n=l)}}catch{}if(!n)return null;let r;try{r=JSON.parse($t.readFileSync(n,"utf8"))}catch{return null}let o=ne.resolve(ne.dirname(n),r.sourceRoot??""),s=(r.sources??[]).map(a=>ne.resolve(o,a)).filter(a=>Gn(e,a)&&Ve(a)&&Wn.includes(ne.extname(a)));if(s.length===1)return s[0];let i=ne.basename(t).replace(/\.(m|c)?js$/,"");return s.find(a=>ne.basename(a).replace(/\.[^.]+$/,"")===i)??null}function bf(e){try{return JSON.parse($t.readFileSync(e,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,"").replace(/,(\s*[}\]])/g,"$1"))}catch{return null}}function _f(e,t){for(let n of["tsconfig.build.json","tsconfig.json"]){let o=bf(ne.join(e,n))?.compilerOptions;if(!o?.outDir)continue;let s=cr(ne.normalize(o.outDir)).replace(/^\.\//,"").replace(/\/$/,"");if(!(t===s||t.startsWith(s+"/")))continue;let i=t.slice(s.length+1),a=o.rootDir?o.rootDir:$t.existsSync(ne.join(e,"src"))?"src":".",c=lr(ne.resolve(e,a,i));if(c)return c}return null}function $f(e,t){let n=t.split("/"),r=n.findIndex(s=>/^(dist|build|out|built|compiled|esm|cjs|lib|output)$/.test(s));if(r<0)return null;let o=n.slice(r+1).join("/");for(let s of["src","source","sources"]){let i=lr(ne.resolve(e,...n.slice(0,r),s,o));if(i&&Gn(e,i))return i}return null}function If(e,t,n){let r=ne.basename(n).replace(/\.(m|c)?js$/,"");for(let o of["build","compile","bundle","prepare","prepublishOnly","prepack","postinstall"]){let s=t.scripts?.[o];if(!s||!Sf.test(s))continue;let i=[];for(let l of s.split(/\s+/).map(d=>d.replace(/^["']|["']$/g,"").replace(/^--?[\w-]+=/,""))){if(!Wn.includes(ne.extname(l))||/\.d\.ts$/.test(l))continue;let d=ne.resolve(e,l);Ve(d)&&Gn(e,d)&&!pa.test(cr(ne.relative(e,d)))&&i.push(d)}let a=[...new Set(i)];if(a.length===1)return a[0];let c=a.filter(l=>ne.basename(l).replace(/\.[^.]+$/,"")===r);if(c.length===1)return c[0];if(a.length)return a[0]}return null}function jf(e,t){let n=[];try{n=$t.readdirSync(e).filter(i=>kf.test(i)).sort()}catch{return null}let r=ne.basename(t).replace(/\.(m|c)?js$/,""),o=[];for(let i of n){let a;try{a=$t.readFileSync(ne.join(e,i),"utf8")}catch{continue}for(let c of a.matchAll(/\bentry(?:Points)?\s*:\s*[[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/g)){let l=lr(ne.resolve(e,c[1]));l&&Gn(e,l)&&o.push(l)}}let s=[...new Set(o)];return s.length===1?s[0]:s.find(i=>ne.basename(i).replace(/\.[^.]+$/,"")===r)??null}function qn(e,t,n){if(typeof t!="string"||!t)return null;let r=cr(ne.normalize(t)).replace(/^\.\//,""),o=ne.resolve(e,r);if(!wf.test(r)||Ve(o)&&!pa.test(r)||Ve(o)&&/\.ts$/.test(o))return null;let i=[["sourcemap",()=>Nf(e,o)],["tsconfig outDir",()=>_f(e,r)],["convention",()=>Ve(o)?null:$f(e,r)],["build script",()=>If(e,n??{},r)],["build config",()=>jf(e,r)]];for(let[a,c]of i){let l=null;try{l=c()}catch{}if(l&&l!==o)return{file:l,how:a}}return null}function ma(e,t){let n=new Map;for(let[r,o]of e){let s=o.socketListeners??[],i=qe(r,o),a=he(r,t);for(let c of s){if(c.isInlineHandler){let d=i.get(c);n.set(c.eventName,d);continue}if(!c.handlerName||!a.has(c.handlerName))continue;let l=a.get(c.handlerName);n.set(c.eventName,l)}}return n}import dr from"node:fs";import J from"node:path";var Fe=e=>String(e??"").trim().replace(/^["']|["']$/g,""),Jn=e=>e.replace(/^\s*#.*$/,"").replace(/\s+#.*$/,"");function ha(e){let t=/^(\/[A-Za-z0-9_\-./]*?)\/?(?=$|[:(*{[])/.exec(String(e).trim()),n=t?t[1]:"";return n==="/"?"":n.replace(/\/+$/,"")}function ga(e,t){let n=e.split(/\r?\n/).map(Jn),r=h=>h.length-h.trimStart().length,o=[],s=null,i=!1,a=null,c=!1,l=0,d=null,f=()=>{d?.key&&d.fromService&&d.fromService!=="?"&&s.hostRefs.push({name:d.key,service:d.fromService,property:d.property}),d=null},u=(h,p,m)=>{p==="name"?h.name=Fe(m):p==="rootDir"?h.rootDir=Fe(m):p==="startCommand"&&(h.startCommand=Fe(m))};for(let h of n){if(!h.trim())continue;let p=r(h),m=h.trim();if(p===0){f(),s=null,c=!1,i=/^services\s*:/.test(m),a=null;continue}if(!i)continue;let y=m.startsWith("-");if(y&&(a==null||p===a)){a=p,f(),s={name:null,rootDir:null,startCommand:null,kept:[],hostRefs:[]},o.push(s),c=!1;let x=/^-\s*([A-Za-z]+)\s*:\s*(.*)$/.exec(m);x&&u(s,x[1],x[2]);continue}if(!s)continue;let g=/^(?:-\s*)?([A-Za-z]+)\s*:\s*(.*)$/.exec(m);if(g){if(g[1]==="envVars"){f(),c=!0,l=p;continue}if(c&&p>l){if(y&&(f(),d={key:null,fromService:null,property:null}),!d)continue;if(g[1]==="key")d.key=Fe(g[2]);else if(g[1]==="value"&&d.key){let x=nt(d.key,Fe(g[2]),t);x&&s.kept.push(x)}else g[1]==="fromService"?d.fromService="?":g[1]==="name"&&d.fromService==="?"?d.fromService=Fe(g[2]):g[1]==="property"&&(d.property=Fe(g[2]));continue}c&&(f(),c=!1),u(s,g[1],g[2])}}return f(),o.filter(h=>h.name)}function ya(e,t){let n={app:null,ports:[],kept:[]},r="";for(let o of e.split(/\r?\n/)){let s=Jn(o).trim();if(!s)continue;let i=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(s);if(i){r=i[1];continue}let a=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(s);if(!a)continue;let[,c,l]=a;if(r===""&&c==="app"){let d=Fe(l);/^[a-z0-9][a-z0-9-]*$/i.test(d)&&(n.app=d)}else if(c==="internal_port"){let d=Number(Fe(l));Number.isInteger(d)&&d>=1&&d<=65535&&n.ports.push(d)}else if(r==="env"){let d=nt(c,Fe(l),t);d&&n.kept.push(d)}}return n}function va(e,t){let n={ports:[],kept:[]},r=e.replace(/\\\r?\n/g," ");for(let o of r.split(/\r?\n/)){let s=o.trim(),i=/^EXPOSE\s+(.+)$/i.exec(s);if(i){for(let c of i[1].split(/\s+/)){let l=Number(c.replace(/\/\w+$/,""));Number.isInteger(l)&&l>=1&&l<=65535&&n.ports.push(l)}continue}if(i=/^(?:ENV|ARG)\s+(.+)$/i.exec(s),!i)continue;let a=i[1];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(a)){let c=/([A-Za-z_][A-Za-z0-9_]*)=("([^"]*)"|'([^']*)'|\S*)/g,l;for(;l=c.exec(a);){let d=nt(l[1],l[3]??l[4]??l[2],t);d&&n.kept.push(d)}}else{let c=/^([A-Za-z_][A-Za-z0-9_]*)\s+(.*)$/.exec(a);if(c){let l=nt(c[1],Fe(c[2]),t);l&&n.kept.push(l)}}}return n}function xa(e){let t;try{t=JSON.parse(e)}catch{return[]}let n=[];for(let r of["rewrites","redirects"])for(let o of Array.isArray(t?.[r])?t[r]:[]){let s=typeof o?.destination=="string"?o.destination:"",i=/\/:[A-Za-z_]+\*?$/.test(s)?ot(s.replace(/\/:[A-Za-z_]+\*?$/,"")):null;i&&typeof o.source=="string"&&n.push({prefix:ha(o.source),target:i,kind:`vercel.json ${r}`,strip:!0})}return n}function wa(e){let t=[],n=!1,r=null,o=()=>{if(r?.from&&r.to&&/\/:[A-Za-z_]+\*?$/.test(r.to)){let s=ot(r.to.replace(/\/:[A-Za-z_]+\*?$/,""));s&&t.push({prefix:ha(r.from),target:s,kind:"netlify.toml redirects",strip:!0})}r=null};for(let s of e.split(/\r?\n/)){let i=Jn(s).trim();if(!i)continue;let a=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(a){o(),n=a[1]==="redirects",r=n?{}:null;continue}if(!n||!r)continue;let c=/^(from|to)\s*=\s*(.*)$/.exec(i);c&&(r[c[1]]=Fe(c[2]))}return o(),t}function Sa(e,t){let n;try{n=JSON.parse(e)}catch{return[]}let r=[],o=n&&typeof n=="object"?n.env:null;if(o&&typeof o=="object")for(let s of Object.keys(o).sort()){let i=o[s],a=typeof i=="string"?i:typeof i?.value=="string"?i.value:null,c=nt(s,a,t);c&&r.push(c)}return r}function ka(e,t,n){let r=[];if(n){let o;try{o=JSON.parse(e)}catch{return r}let s=(i,a)=>{if(!(!i||typeof i!="object"||a>4))for(let c of Object.keys(i).sort()){let l=i[c];if(/^(env|envVars|variables|environment)$/i.test(c)&&l&&typeof l=="object"&&!Array.isArray(l))for(let d of Object.keys(l).sort()){let f=typeof l[d]=="string"?l[d]:typeof l[d]?.value=="string"?l[d].value:null,u=nt(d,f,t);u&&r.push(u)}else s(l,a+1)}};s(o,0)}else{let o="";for(let s of e.split(/\r?\n/)){let i=Jn(s).trim();if(!i)continue;let a=/^\[\[?\s*([A-Za-z0-9_.]+)\s*\]\]?$/.exec(i);if(a){o=a[1];continue}let c=/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(i);if(c&&/(^|\.)(env|variables|environment)$/i.test(o)){let l=nt(c[1],Fe(c[2]),t);l&&r.push(l)}}}return r}var Cf=[".env.local",".env",".env.development",".env.production",".env.example"],Ff=/^(PORT|HTTP_PORT|HTTPS_PORT|SERVER_PORT|API_PORT|APP_PORT|WS_PORT|WSS_PORT|WEBSOCKET_PORT|LISTEN_PORT)$/,Ef=/^PUBLIC_(?:[A-Z0-9]+_)*(?:ORIGIN|URL|HOST|BASE_URL)$/,Pf=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","host.docker.internal"]),Lf=512*1024,Na=e=>e.split(J.sep).join("/");function It(e){try{let t=dr.lstatSync(e);return!t.isFile()||t.isSymbolicLink()||t.size>Lf?null:dr.readFileSync(e,"utf8")}catch{return null}}function ot(e){let t=String(e).trim().replace(/^["']|["']$/g,"");if(!/^(https?|wss?):\/\//i.test(t))return null;try{let n=new URL(t);if(!n.hostname)return null;let r=n.protocol.replace(":",""),o=n.hostname.toLowerCase(),s=n.port?Number(n.port):null,i=n.pathname.replace(/\/+$/,"");return{scheme:r,host:o,port:s,origin:`${r}://${o}${s?":"+s:""}`,path:i}}catch{return null}}function Tf(e){let t=String(e).trim().replace(/^["']|["']$/g,"");return!/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:\d{1,5})?(\/[^\s?#]*)?$/i.test(t)||!/[a-z]/i.test(t.split(/[/:]/)[0])?null:ot("http://"+t)}var fr=e=>{let t=String(e).trim().replace(/^["']|["']$/g,"");if(!/^\d{1,5}$/.test(t))return null;let n=Number(t);return n>=1&&n<=65535?n:null};function Rf(e){let t=new Map;for(let n of e.split(/\r?\n/)){let r=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(n);if(!r)continue;let o=r[2];if(/^["']/.test(o)){let s=o[0],i=o.indexOf(s,1);o=i>0?o.slice(1,i):o.slice(1)}else o=o.replace(/\s+#.*$/,"");t.set(r[1],o)}return t}function $a(e,t,n=0,r=new Set){let o=e.get(t);return o==null||n>5||r.has(t)||(r.add(t),o=o.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}]*))?\}/g,(s,i,a)=>{let c=e.has(i)?$a(e,i,n+1,r):void 0;return c!=null&&c!==""?c:a??""}),r.delete(t)),o}function nt(e,t,n){if(t==null)return null;if(Ff.test(e)){let o=fr(t);return o?{name:e,kind:"port",file:n,port:o}:null}let r=ot(t)??(/(_URL|_URI|_HOST|_HOSTNAME|_ORIGIN|_ADDR|_ENDPOINT)$/i.test(e)?Tf(t):null);return r?{name:e,kind:"url",file:n,...r}:null}function ba(e,t){let n=[];for(let r of[...e.keys()].sort()){let o=$a(e,r);if(o==null)continue;let s=nt(r,o,t);s&&n.push(s)}return n}function Af(e){let t=e.split(/\r?\n/).map(l=>l.replace(/\s+#.*$/,"").replace(/\t/g," ")),n=l=>l.length-l.trimStart().length,r=[],o=t.findIndex(l=>/^services\s*:\s*$/.test(l));if(o<0)return r;let s=null,i=null,a=null,c=0;for(o=o+1;o<t.length;o++){let l=t[o];if(!l.trim())continue;let d=n(l),f=l.trim();if(d===0)break;if(s==null&&(s=d),d===s){let u=/^([A-Za-z0-9_.-]+)\s*:\s*$/.exec(f);u&&(i={name:u[1],ports:[],env:new Map,build:null},r.push(i),a=null);continue}if(i){if(d<=s+4&&/^[A-Za-z_]+\s*:/.test(f)&&!f.startsWith("-")){let u=/^([A-Za-z_]+)\s*:\s*(.*)$/.exec(f);a=u[1],c=d,a==="build"&&u[2]&&(i.build=u[2].replace(/^["']|["']$/g,""));continue}if(a==="build"&&/^context\s*:/.test(f)){i.build=f.replace(/^context\s*:\s*/,"").replace(/^["']|["']$/g,"");continue}if(a==="ports"&&f.startsWith("-")){let h=f.slice(1).trim().replace(/^["']|["']$/g,"").replace(/\/\w+$/,"").split(":"),p=h.slice(-2).map(m=>fr(m));h.length===1&&p[0]?i.ports.push({host:null,container:p[0]}):h.length>=2&&p[0]&&p[1]&&i.ports.push({host:p[0],container:p[1]});continue}if(a==="environment"&&d>c){let u=f.startsWith("-")?/^-\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(f):/^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/.exec(f);u&&i.env.set(u[1],u[2].replace(/^["']|["']$/g,""))}}}return r}function _a(e,t){let n=[];if(t==="vite"){let r=e.search(/\bproxy\s*:/);if(r<0)return n;let o=e.slice(r,r+2500),s=/["'`](\/[^"'`]*)["'`]\s*:\s*(?:["'`](https?:\/\/[^"'`]+)["'`]|\{[^{}]*?target\s*:\s*["'`](https?:\/\/[^"'`]+)["'`])/g,i;for(;i=s.exec(o);){let a=ot(i[2]??i[3]);a&&n.push({prefix:i[1].replace(/\/+$/,""),target:a,kind:"vite.config proxy"})}}else if(t==="next"){let r=/source\s*:\s*["'`](\/[^"'`:*]*)[^"'`]*["'`]\s*,\s*destination\s*:\s*["'`](https?:\/\/[^"'`]+?)(?:\/:[^"'`]*)?["'`]/g,o;for(;o=r.exec(e);){let s=ot(o[2]);s&&n.push({prefix:o[1].replace(/\/+$/,""),target:s,kind:"next.config rewrites"})}}return n}function Ia(e,t,n){let r=g=>Na(J.relative(e,g)),o=new Map,s=new Map,i=new Map,a=(g,x,S)=>{(g.get(x)??g.set(x,new Set).get(x)).add(S)},c=(g,x,S)=>{let k=i.get(g)??i.set(g,[]).get(g);k.some(v=>v.service===x&&v.via===S)||k.push({service:x,via:S})},l=g=>{let x=[],S=J.resolve(g),k=J.resolve(e);for(let v=0;v<8&&(x.push(S),!(S===k||J.dirname(S)===S||(S=J.dirname(S),!S.startsWith(k))));v++);return x},d=new Map,f=new Map,u=(g,x)=>{let S=g.env.get(x.name)??g.env.set(x.name,[]).get(x.name);S.some(k=>k.file===x.file)||S.push(x),x.kind==="port"&&g.ports.add(x.port)};function h(g,x,S){let k=w=>r(J.join(S,w)),v=w=>It(J.join(S,w));for(let w of Vn(S))if(w==="fly.toml"){let b=v(w);if(b){let N=ya(b,k(w));for(let $ of N.ports)x.ports.add($);for(let $ of N.kept)u(x,$);N.app&&(c(`${N.app.toLowerCase()}.internal`,g.name,"fly.toml app name"),c(`${N.app.toLowerCase()}.fly.dev`,g.name,"fly.toml app name"))}}else if(/^Dockerfile(\..+)?$/.test(w)){let b=v(w);if(b){let N=va(b,k(w));for(let $ of N.ports)x.weakPorts.add($);for(let $ of N.kept)u(x,$)}}else if(w==="railway.json"||w==="railway.toml"){let b=v(w);if(b)for(let N of ka(b,k(w),w.endsWith(".json")))u(x,N)}else if(w==="app.json"){let b=v(w);if(b)for(let N of Sa(b,k(w)))u(x,N)}else if(w==="vercel.json"){let b=v(w);if(b)for(let N of xa(b))x.proxies.push({...N,file:k(w)})}else if(w==="netlify.toml"){let b=v(w);if(b)for(let N of wa(b))x.proxies.push({...N,file:k(w)})}}for(let g of t){let x={env:new Map,ports:new Set,weakPorts:new Set,proxies:[],isServer:!1};o.set(g.name,x);for(let S of l(g.rootPath)){for(let k of Cf){let v=It(J.join(S,k));if(v!=null)for(let w of ba(Rf(v),r(J.join(S,k)))){let b=x.env.get(w.name)??x.env.set(w.name,[]).get(w.name);b.some(N=>N.file===w.file)||b.push(w),w.kind==="port"&&S===J.resolve(g.rootPath)&&/(^|\/)\.env/.test(w.file)&&!/\.example$/.test(w.file)&&x.ports.add(w.port),w.kind==="port"&&S===J.resolve(g.rootPath)&&/\.example$/.test(w.file)&&x.ports.add(w.port)}}if(S===J.resolve(g.rootPath)){try{let k=JSON.parse(It(J.join(S,"package.json"))??"null"),v=typeof k?.proxy=="string"?ot(k.proxy):null;v&&x.proxies.push({prefix:"",target:v,kind:'package.json "proxy"',file:r(J.join(S,"package.json"))})}catch{}for(let k of Vn(S)){if(/^vite\.config\.(js|mjs|cjs|ts|mts)$/.test(k)){let v=It(J.join(S,k));if(v)for(let w of _a(v,"vite"))x.proxies.push({...w,file:r(J.join(S,k))})}if(/^next\.config\.(js|mjs|cjs|ts)$/.test(k)){let v=It(J.join(S,k));if(v)for(let w of _a(v,"next"))x.proxies.push({...w,file:r(J.join(S,k))})}}}S===J.resolve(g.rootPath)&&h(g,x,S);for(let k of Vn(S))if(/^render\.ya?ml$/.test(k)&&!f.has(J.join(S,k))){let v=It(J.join(S,k));v&&f.set(J.join(S,k),ga(v,r(J.join(S,k))))}for(let k of Vn(S)){if(!/^docker-compose.*\.ya?ml$/.test(k)||d.has(J.join(S,k)))continue;let v=It(J.join(S,k));v&&d.set(J.join(S,k),Af(v))}}}for(let[g,x]of[...d].sort((S,k)=>S[0]<k[0]?-1:1)){let S=J.dirname(g);for(let k of x){let v=k.build?J.resolve(S,k.build):null,w=t.find(N=>v&&J.resolve(N.rootPath)===v)??t.find(N=>N.name===k.name||J.basename(N.rootPath)===k.name);if(!w)continue;let b=o.get(w.name);for(let N of k.ports)b.ports.add(N.container),N.host&&b.ports.add(N.host);for(let N of ba(k.env,r(g)))(b.env.get(N.name)??b.env.set(N.name,[]).get(N.name)).push(N);c(k.name.toLowerCase(),w.name,"docker-compose service name")}}for(let[g,x]of[...f].sort((S,k)=>S[0]<k[0]?-1:1)){let S=J.dirname(g),k=new Map;for(let v of x){let w=J.resolve(S,v.rootDir||"."),b=v.rootDir?t.find($=>J.resolve($.rootPath)===w):null;if(!b&&v.startCommand)for(let $ of v.startCommand.split(/\s+/)){if(!/\.(c|m)?[jt]sx?$/.test($)&&!/^[\w./-]+\/[\w.-]+$/.test($))continue;let j=J.resolve(w,$),O=t.filter(D=>j.startsWith(J.resolve(D.rootPath)+J.sep)).sort((D,G)=>G.rootPath.length-D.rootPath.length)[0];if(O){b=O;break}}if(b=b??t.find($=>$.name===v.name||J.basename($.rootPath)===v.name),!b)continue;k.set(v.name,{target:b,c:v});let N=o.get(b.name);for(let $ of v.kept)u(N,{...$,scoped:!0});c(v.name.toLowerCase(),b.name,"render.yaml service name"),c(`${v.name.toLowerCase()}.onrender.com`,b.name,"render.yaml service name (Render's default public address)")}for(let{target:v,c:w}of k.values())for(let b of w.hostRefs){let N=k.get(b.service);if(!N)continue;let $=[...N.c.kept].find(D=>D.kind==="port")?.port??null,j=b.property==="hostport"&&$,O=b.service.toLowerCase();u(o.get(v.name),{name:b.name,kind:"url",file:r(g),scheme:"http",host:O,port:j?$:null,origin:`http://${O}${j?":"+$:""}`,path:""})}}let p=g=>[...n.get(g.name)?.parseResults?.values()??[]].some(x=>(x.routes??[]).length>0);for(let g of t){let x=o.get(g.name);if(x.isServer=p(g),x.isServer){for(let[S,k]of x.env)if(Ef.test(S))for(let v of k)v.kind==="url"&&v.file&&(v.scoped||J.posix.dirname(v.file)===(Na(J.relative(e,g.rootPath))||"."))&&c(v.host,g.name,`${S} in ${v.file} (the server's own public address)`)}}for(let g of t){let x=o.get(g.name);for(let[,S]of n.get(g.name)?.parseResults??[])for(let k of S.httpClients?.listens??[])for(let v of m(x,k.parts)){let w=fr(v.text);w&&x.ports.add(w)}}for(let g of t)for(let x of o.get(g.name).ports)a(s,x,g.name);for(let g of t)for(let x of o.get(g.name).weakPorts)t.some(S=>o.get(S.name).ports.has(x))||a(s,x,g.name);function m(g,x){let S=[{text:"",evidence:[]}];for(let k of x){let v;if(k.t==="lit")v=[{text:k.v,evidence:[]}];else if(k.t==="env"){let b=g.env.get(k.name)??[];v=[];for(let N of b)v.push({text:N.kind==="port"?String(N.port):N.origin+N.path,evidence:[{env:k.name,file:N.file}]});!v.length&&k.fallback&&(v=m(g,k.fallback).map($=>({text:$.text,evidence:[{env:k.name,file:null,fallback:!0},...$.evidence]})))}else v=[];if(!v.length)return[];let w=[];for(let b of S)for(let N of v)if(w.push({text:b.text+N.text,evidence:[...b.evidence,...N.evidence]}),w.length>=8)break;S=w.slice(0,8)}return S}let y=(g,x)=>{let S=[],k=g.host,v=i.get(k)??[];for(let w of v)S.push(w);if(Pf.has(k)||v.length&&v.some(w=>w.via==="docker-compose service name")){let w=g.port??(g.scheme==="https"||g.scheme==="wss",null);if(w)for(let b of s.get(w)??[])S.some(N=>N.service===b)||S.push({service:b,via:`port ${w} (a service listening there)`})}return S.filter(w=>w.service!==x)};return{resolveBase(g,x){let S=o.get(g);if(!S||!x.length)return{status:"unknown"};let k=m(S,x);if(!k.length)return{status:"unknown"};let v=[],w=new Set;for(let $ of k){let j=ot($.text)??($.text.startsWith("//"),null);if(j){w.add(j.origin);for(let O of y(j,g))v.push({...O,u:j,evidence:$.evidence})}}if(!w.size)return{status:"unknown"};let b=[...new Set(v.map($=>$.service))];if(b.length===0)return{status:"external",origins:[...w].sort()};if(b.length>1)return{status:"ambiguous",services:b.sort()};let N=v[0];return{status:"service",service:N.service,via:N.via,origin:N.u.origin,basePath:N.u.path,evidence:N.evidence.filter(($,j,O)=>O.findIndex(D=>D.env===$.env&&D.file===$.file)===j)}},resolveProxy(g,x){let S=o.get(g);for(let k of S?.proxies??[]){if(k.prefix&&x!==k.prefix&&!x.startsWith(k.prefix+"/"))continue;let v=y(k.target,g),w=[...new Set(v.map(b=>b.service))];if(w.length===1)return{status:"service",service:w[0],via:`${k.kind} ${k.prefix||"/"} -> ${k.target.origin}`,origin:k.target.origin,basePath:k.target.path,strip:k.strip?k.prefix.split("/").filter(Boolean).length:0,evidence:[{env:null,file:k.file}]}}return{status:"unknown"}},portsOf:g=>[...o.get(g)?.ports??[]].sort((x,S)=>x-S),hostClaims:()=>[...i].sort((g,x)=>g[0]<x[0]?-1:1)}}function Vn(e){try{return dr.readdirSync(e).sort()}catch{return[]}}var Yn=e=>String(e).toLowerCase();function Kn(e){let t=[];for(let n of e)n.t==="lit"&&t.length&&t[t.length-1].t==="lit"?t[t.length-1]={t:"lit",v:t[t.length-1].v+n.v}:t.push(n);return t}function ja(e,t){let n=[];for(let r of e){if(r.t!=="param"){n.push(r);continue}let o=t?.get(r.index);o?n.push(...o):n.push({t:"ref",name:r.name})}return Kn(n)}function ur(e){if(!e.length)return null;let t=e.slice(),n="none",r=null,o=t[0];if(o.t==="lit"){let l=/^(https?:)\/\/([^/?#]*)(.*)$/.exec(o.v);if(l){n="abs",r=l[2];let d=l[3];if(t=d?[{t:"lit",v:d},...t.slice(1)]:t.slice(1),/^(www\.)?(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0)(:\d+)?$/.test(r)===!1&&!/\.(local|internal|svc)$/.test(r)&&!/^[a-z0-9-]+(:\d+)?$/.test(r))return null}else if(!o.v.startsWith("/"))return null}else{for(n="var";t.length&&t[0].t!=="lit";)t.shift();if(!t.length||!t[0].v.startsWith("/"))return null}let s="",i=0,a=!1;for(let l of t){if(a)break;if(l.t==="lit"){let d=l.v.search(/[?#]/);d>=0?(s+=l.v.slice(0,d),a=!0):s+=l.v}else s+="",i++}if(!s.startsWith("/")&&!(s===""&&n==="abs"))return null;s===""&&(s="/");let c=s.split("/").slice(1).map(l=>l.includes("")?":p":l);for(;c.length>1&&c[c.length-1]==="";)c.pop();return{base:n,host:r,segments:c,placeholders:i,literal:n==="none"&&i===0}}function Ca(e){if(!e.length)return[];let t=e[0];if(t.t==="lit"){let r=/^((?:https?|wss?):\/\/[^/?#]*)/.exec(t.v);return r?[{t:"lit",v:r[1]}]:[]}let n=[];for(let r of e){if(r.t==="lit"&&r.v.startsWith("/"))break;n.push(r)}return n}var Of=e=>String(e||"").split("/").filter(Boolean),Fa=e=>[...new Set(e)];function Ea(e){let t=e.evidence??[];return{env:Fa(t.filter(n=>n.env).map(n=>n.env)),files:Fa(t.filter(n=>n.file).map(n=>n.file)),origin:e.origin,via:e.via,...t.some(n=>n.fallback)?{usedFallback:!0}:{}}}var Pa=(e,t)=>"base URL "+(e.env.length?e.env.join(", ")+(e.files.length?" in "+e.files.join(", "):"")+" = ":e.files.length?"(from "+e.files.join(", ")+") ":"")+e.origin+" belongs to "+t+" ("+e.via+")",Mf=e=>{let t=String(e).split(/[?#]/)[0].split("/").slice(1).map(n=>n.startsWith(":")||/^\{.*\}$/.test(n)||n==="*"?":p":n);for(;t.length>1&&t[t.length-1]==="";)t.pop();return t};function La(e,t){if(e.length===t.length){let n=!0,r=!0;for(let o=0;o<e.length;o++){let s=e[o],i=t[o];if(s!==i&&(n=!1),!(s===i||s===":p"||i===":p")){r=!1;break}}if(n)return 3;if(r)return 2}if(e[0]==="api"&&e.length>1){let n=e.slice(1);if(/^v\d+$/.test(n[0])&&n.length>1&&(n=n.slice(1)),n.length===t.length&&n.every((r,o)=>r===t[o]||r===":p"||t[o]===":p"))return 1}return 0}function Hf(e,t,n,r,o){let s=(n.importBindings??[]).find(f=>f.local===r);if(!s)return null;let i=Je(s.source,t,o);if(!i)return null;let a=e.parseResults.get(i),c=f=>e.nodes.find(u=>u.filePath===i&&u.name===f&&u.type!=="moduleRoot")?.id??null;if(s.kind==="named"&&s.imported)return c(s.imported);let l=a?.exportBindings;if(l?.default&&l.default!=="<anon>")return c(l.default);let d=Object.keys(l?.named??{});return d.length===1?c(d[0]):null}function Df(e){let t=[],n=[...e.parseResults.keys()];for(let[r,o]of e.parseResults){let s=e.nodes.filter(c=>c.filePath===r);if(s[0]?.category!=="backend")continue;let i=qe(r,o),a=he(r,e.nodes);for(let c of o.routes??[]){let l=null;c.isInlineHandler?l=i.get(c):c.nest?l=s.find(f=>f.type==="classMethod"&&f.className===c.nest.className&&f.name===c.nest.methodName)?.id??null:c.handlerName&&a.has(c.handlerName)?l=a.get(c.handlerName):c.handlerName&&(l=Hf(e,r,o,c.handlerName,n));let d=!1;l||(l=ge(c.startLine,s)?.id??null,d=!0),l&&t.push({method:Yn(c.method),path:c.path,segments:Mf(c.path),literal:!/[:*{]/.test(c.path),nodeId:l,file:r,line:c.startLine,fallback:d})}}return t}var Bf=/^(ws|uws|websocket|@nestjs\/platform-ws|@fastify\/websocket|fastify-websocket|express-ws)$/,Uf=/^(socket\.io|@nestjs\/platform-socket\.io|socket\.io-client)$/;function Ta(e){let t=[...e].some(r=>Uf.test(r)),n=[...e].some(r=>Bf.test(r));return t&&n?"unknown":t?"socketio":n?"ws":null}function zf(e){let t=[],n=new Set;for(let[,r]of e.parseResults)for(let o of r.imports??[])n.add(o.source);for(let[r,o]of e.parseResults){let s=o.socketListeners??[],i=s.find(m=>m.eventName==="connection");if(!i)continue;let a=qe(r,o),c=he(r,e.nodes),l=m=>m.isInlineHandler?a.get(m):m.handlerName&&c.has(m.handlerName)?c.get(m.handlerName):null,d=l(i);if(!d)continue;let f=m=>i.handlerStartLine!=null&&m.startLine>=i.handlerStartLine&&m.startLine<=i.handlerEndLine,u=s.find(m=>m.eventName==="message"&&f(m))??s.find(m=>m.eventName==="message"),h=o.httpClients?.wsServers??[],p=Ta(new Set((o.imports??[]).map(m=>m.source)))??Ta(n)??"unknown";t.push({filePath:r,nodeId:d,line:i.startLine,messageNodeId:u?l(u):null,messageLine:u?.startLine??null,pathParts:h.find(m=>m.path)?.path??null,kind:p})}return t}function Ra(e,t,n={}){let r=n.repoRoot?Ia(n.repoRoot,e,t):null,o=[],s=new Set,i={restCalls:0,restLinked:0,wsClients:0,wsLinked:0,wsSends:0,wsSendsLinked:0},a=l=>{let d=[l.fromService,l.fromNodeId,l.toService,l.toNodeId,l.via,l.key].join("\0");s.has(d)||(s.add(d),o.push(l))},c=new Map;for(let l of e){let d=t.get(l.name);d&&c.set(l.name,{routes:Df(d),wsServers:zf(d)})}for(let l of e){let d=t.get(l.name);if(!d)continue;let f=[...d.parseResults.keys()],u=new Map,h=new Map;for(let[v,w]of d.parseResults){let b=w.httpClients;if(b){for(let N of b.httpInstances??[])(u.get(N.name)??u.set(N.name,[]).get(N.name)).push(N);for(let N of b.httpCalls??[])(N.parts.some(j=>j.t==="param")||N.method&&typeof N.method=="object")&&N.fn?.name&&(h.get(N.fn.name)??h.set(N.fn.name,[]).get(N.fn.name)).push({filePath:v,call:N})}}let p=v=>{if(!v.startsWith("inst:")&&!v.startsWith("obj:"))return[];let w=u.get(v.slice(v.indexOf(":")+1));return w&&w.length===1?w[0].parts:v.startsWith("obj:")?null:[{t:"ref",name:"?"}]},m=[],y=(v,w)=>ge(w,d.nodes.filter(b=>b.filePath===v)),g=new Set,x=v=>v.parts.some(w=>w.t==="param")||v.method&&typeof v.method=="object";for(let[v,w]of d.parseResults){let b=w.httpClients;if(b){for(let N of b.httpCalls??[]){if(x(N))continue;let $=p(N.client);if($===null)continue;let j=y(v,N.line);j&&m.push({filePath:v,line:N.line,nodeId:j.id,method:N.method,parts:Kn([...$,...N.parts]),via:N.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let N of b.pathCallsites??[]){let $=h.get(N.callee);if($)for(let j of $){let O=j.filePath===v;if(!O){let q=(w.importBindings??[]).find(E=>E.local===N.callee||E.imported===N.callee);q&&Je(q.source,v,f)===j.filePath&&(O=!0)}if(!O)continue;let D=new Map(N.args.map(q=>[q.i,q.parts])),G=typeof j.call.method=="object"&&j.call.method?(()=>{let q=D.get(j.call.method.param);return q&&q.length===1&&q[0].t==="lit"?q[0].v.toUpperCase():"?"})():j.call.method,M=y(v,N.line);M&&(g.add(j.call),m.push({filePath:v,line:N.line,nodeId:M.id,method:G,parts:ja([...p(j.call.client),...j.call.parts],D),via:j.call.client,wrapper:N.callee}))}}}}for(let[v,w]of d.parseResults)for(let b of w.httpClients?.httpCalls??[]){if(!x(b)||g.has(b))continue;let N=p(b.client);if(N===null)continue;let $=y(v,b.line);$&&m.push({filePath:v,line:b.line,nodeId:$.id,method:typeof b.method=="object"&&b.method?"?":b.method,parts:ja([...N,...b.parts],null),via:b.client.replace(/^obj:/,"inst:"),wrapper:null})}for(let v of m){let w=ur(v.parts);if(!w)continue;i.restCalls++;let b=0,N=[];for(let M of e){if(M.name===l.name)continue;let q=c.get(M.name);if(q)for(let E of q.routes){if(!(v.method==="?"||v.method==null||E.method===Yn(v.method)||E.method==="all"||E.method==="use"))continue;let R=La(w.segments,E.segments);R&&(R>b&&(b=R,N.length=0),R===b&&N.push({service:M.name,route:E}))}}let $={status:"unknown"};if(r){let M=Kn(v.parts);if(w.base==="none"?$=r.resolveProxy(l.name,"/"+w.segments.join("/")):$=r.resolveBase(l.name,Ca(M)),$.status==="service"){let q=Of($.basePath);if(q.length||$.strip){let E=[...q,...w.segments.slice($.strip||0)];for(let C of c.get($.service)?.routes??[])(v.method==="?"||v.method==null||C.method===Yn(v.method)||C.method==="all"||C.method==="use")&&La(E,C.segments)&&!N.some(W=>W.service===$.service&&W.route.nodeId===C.nodeId)&&N.push({service:$.service,route:C,viaBasePath:!0})}}}if(!N.length)continue;let j=new Set(N.map(M=>M.service+"\0"+M.route.nodeId)),O=typeof v.method=="string"&&v.method!=="?",D=b===3&&w.literal&&O&&j.size===1&&N[0].route.literal&&!N[0].route.fallback&&N[0].route.method===Yn(v.method),G=[];w.base==="var"&&G.push("base URL is a variable, so the target service is guessed from the path"),w.base==="abs"&&G.push("absolute URL"),w.placeholders&&G.push("path has parameters"),b===1&&G.push("leading /api removed from the client path"),b===2&&G.push("route parameters matched fuzzily"),O||G.push("method not known"),j.size>1&&G.push(j.size+" candidate routes"),N.some(M=>M.route.fallback)&&G.push("route handler not resolved: linked to the function that registers the route"),$.status==="external"&&G.push("base URL is "+$.origins.join(" / ")+", which no service of this repo owns"),$.status==="ambiguous"&&G.push("base URL could belong to "+$.services.join(" or "));for(let M of N){i.restLinked++;let q=!D&&$.status==="service"&&$.service===M.service&&!M.route.fallback,E=q?Ea($):null,C=D?"exact":q?"resolved":"inferred",R=!D&&$.status==="service"&&$.service!==M.service?["base URL belongs to "+$.service+", not this service"]:[];a({fromService:l.name,fromNodeId:v.nodeId,toService:M.service,toNodeId:M.route.nodeId,via:"httpCall",key:`${O?v.method:"ANY"} ${"/"+w.segments.join("/")}`,confidence:C,method:O?v.method:null,url:"/"+w.segments.join("/"),client:v.via,...v.wrapper?{wrapper:v.wrapper}:{},line:v.line,...D?{}:q?{reason:Pa(E,M.service)+(O?"":"; method not known"),resolvedFrom:E}:{reason:[...G,...R].join("; ")||"path-only match"}})}}let S=[];for(let[v,w]of d.parseResults)for(let b of w.httpClients?.wsClients??[])S.push({filePath:v,w:b});let k=v=>v.client==="io"?"socketio":"ws";for(let{filePath:v,w}of S){let b=y(v,w.line);if(!b)continue;i.wsClients++;let N=Kn(w.parts),$=/^wss?:\/\//.test(N[0]?.v??"")?ur([{t:"lit",v:N[0].v.replace(/^ws(s?):/,"http$1:")},...N.slice(1)]):ur(N),j=r&&$?r.resolveBase(l.name,Ca(N)):{status:"unknown"};for(let O of e)if(O.name!==l.name)for(let D of c.get(O.name)?.wsServers??[]){if(D.kind!=="unknown"&&D.kind!==k(w))continue;let G=D.pathParts&&D.pathParts.every(R=>R.t==="lit")?"/"+D.pathParts.map(R=>R.v).join("").replace(/^\//,""):null,M=$?"/"+$.segments.join("/"):null;if(G&&M&&G!==M&&G!=="/"&&M!=="/")continue;let q=!!($&&$.literal&&G&&M===G&&D.kind!=="unknown"),E=!q&&j.status==="service"&&j.service===O.name,C=E?Ea(j):null;i.wsLinked++,a({fromService:l.name,fromNodeId:b.id,toService:O.name,toNodeId:D.nodeId,via:"webSocket",key:M??"(url unknown)",confidence:q?"exact":E?"resolved":"inferred",url:M,client:w.client,line:w.line,...q?{}:E?{reason:Pa(C,O.name),resolvedFrom:C}:{reason:"WebSocket connection matched to a WebSocket server of another service ("+($?.base==="var"?"URL base is a variable":"no path on the server to compare")+(j.status==="external"?"; base URL is "+j.origins.join(" / ")+", which no service of this repo owns":"")+")"}})}}if(S.length){let v=new Set(S.map(({w})=>k(w)));for(let[w,b]of d.parseResults)for(let N of b.httpClients?.wsSends??[]){let $=y(w,N.line);if($){i.wsSends++;for(let j of e)if(j.name!==l.name)for(let O of c.get(j.name)?.wsServers??[])!O.messageNodeId||O.kind!=="unknown"&&!v.has(O.kind)||(i.wsSendsLinked++,a({fromService:l.name,fromNodeId:$.id,toService:j.name,toNodeId:O.messageNodeId,via:"webSocketMessage",key:"message",eventName:"message",confidence:"inferred",client:N.recv,line:N.line,reason:"a message sent over a socket whose payload is built at run time; delivered to the message listener of a WebSocket server of another service"}))}}}}if(n.serverPush!==!1){let l=new Map;for(let f of o)if(f.via==="webSocket"){let u=f.fromService+"\0"+f.toService;(l.get(u)??l.set(u,[]).get(u)).push(f)}let d=new Map;for(let f of l.values())(d.get(f[0].toService)??d.set(f[0].toService,new Set).get(f[0].toService)).add(f[0].fromService);for(let[,f]of[...l].sort((u,h)=>u[0]<h[0]?-1:1)){let u=f[0].fromService,h=f[0].toService,p=t.get(u),m=t.get(h);if(!p||!m||!(c.get(h)?.wsServers??[]).length)continue;let y=new Set(f.map(k=>k.fromNodeId.split("::")[0])),g=[];for(let[k,v]of p.parseResults){if(!y.has(k))continue;let w=he(k,p.nodes),b=qe(k,v),N=p.nodes.filter($=>$.filePath===k);for(let $ of v.httpClients?.wsReceivers??[]){let j=$.handlerName&&w.get($.handlerName)||ge($.line,N)?.id;j&&g.push({id:j,line:$.line})}for(let $ of v.socketListeners??[]){if($.eventName!=="message")continue;let j=$.isInlineHandler?b.get($):$.handlerName&&w.get($.handlerName)||null;j&&g.push({id:j,line:$.startLine})}}let x=new Set(p.resolvedEdges.filter(k=>k.resolved&&k.targetNodeId&&k.type!=="returnValue").map(k=>k.fromNodeId));for(let k=g.length-1;k>=0;k--)x.has(g[k].id)||g.splice(k,1);if(!g.length)continue;let S=d.get(h)?.size??1;for(let[k,v]of m.parseResults){let w=m.nodes.filter(b=>b.filePath===k);for(let b of[...v.httpClients?.wsSends??[],...v.httpClients?.wsServerSends??[]]){let N=ge(b.line,w);if(N)for(let $ of g)i.wsPushLinked=(i.wsPushLinked??0)+1,a({fromService:h,fromNodeId:N.id,toService:u,toNodeId:$.id,via:"webSocketDelivery",key:"message",eventName:"message",confidence:"inferred",client:b.recv,line:b.line,receiverLine:$.line,reason:"a message the server sends over a WebSocket (payload built at run time) is taken in by the message handler of "+u+", which connects to this server"+(S>1?"; "+S+" services connect to this server, so it may be meant for another one":""),...S>1?{candidates:S}:{}})}}}}return o.sort((l,d)=>l.fromService+l.fromNodeId+l.via+l.key+l.toService+l.toNodeId<d.fromService+d.fromNodeId+d.via+d.key+d.toService+d.toNodeId?-1:1),{edges:o,stats:i}}function Aa(e,t){let n=new Map;for(let[r,o]of e){let s=t.filter(a=>a.filePath===r),i=o.rawSocketTypeChecks??[];for(let a of i){let c=ge(a.startLine,s);c&&n.set(a.eventName,c.id)}}return n}import Wf from"node:fs";import Gf from"node:path";function Oa(e){let t=["index.html","public/index.html","client/index.html","frontend/index.html","src/index.html"];for(let n of t){let r=Gf.join(e,n);if(Wf.existsSync(r))return r}return null}import Xn from"node:fs";import Zn from"node:path";var qf=new Set(["node","tsx","ts-node","nodemon","bun","deno","ts-node-esm"]),Jf=new Set(["watch","run","start","dev"]),Vf=/\.[cm]?[jt]sx?$/,Yf=["start","dev","serve","run"];function Kf(e){for(let t of String(e).split(/&&|\|\||;|\|/)){let n=t.trim().split(/\s+/).filter(Boolean).map(o=>o.replace(/^["']|["']$/g,"")),r=n.findIndex(o=>qf.has(Zn.basename(o).replace(/\.cmd$/,"")));if(!(r<0)){for(let o of n.slice(r+1))if(!(o.startsWith("-")||Jf.has(o)||o.includes("="))){if(Vf.test(o))return o;break}}}return null}var Xf=e=>String(e).replace(/^@[^/]+\//,"");function Ma(e){let t;try{t=JSON.parse(Xn.readFileSync(Zn.join(e,"package.json"),"utf8"))}catch{return[]}let n=[],r=(o,s,i={})=>{if(typeof o!="string"||!o)return;let a=s==="script"?null:qn(e,o,t);a?n.push({file:a.file,kind:s,...i,mappedFrom:o,mappedBy:a.how}):n.push({file:Zn.resolve(e,o),kind:s,...i})};if(typeof t.bin=="string")r(t.bin,"bin",{binName:Xf(t.name??Zn.basename(e))});else if(t.bin&&typeof t.bin=="object")for(let[o,s]of Object.entries(t.bin))r(s,"bin",{binName:o});for(let o of Yf){let s=t.scripts?.[o]&&Kf(t.scripts[o]);s&&r(s,"script")}return r(t.main,"main"),n}function Ha(e){try{let t=Xn.openSync(e,"r"),n=Buffer.alloc(120),r=Xn.readSync(t,n,0,120,0);return Xn.closeSync(t),/^#!.*\b(node|tsx|ts-node|bun)\b/.test(n.toString("utf8",0,r).split(/\r?\n/)[0])}catch{return!1}}import Qn from"node:fs";import jt from"node:path";var Zf=50,Qf=/^(tsup|tsdown|unbuild|build|rollup|vite|webpack|esbuild)[\w.-]*\.(mts|cts|mjs|cjs|js|ts)$/i,Da=["",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts","/index.js","/index.ts","/index.mjs","/index.cjs","/index.tsx","/index.jsx"];function pr(e){if(typeof e=="string")return e;if(Array.isArray(e)){for(let t of e){let n=pr(t);if(n)return n}return null}if(e&&typeof e=="object")for(let t of["import","node","require","default"]){let n=pr(e[t]);if(n)return n}return null}function Ba(e,t){let n;try{n=JSON.parse(Qn.readFileSync(jt.join(e,"package.json"),"utf8"))}catch{return null}let r=n.exports,o=typeof r=="string"||Array.isArray(r)?r:r&&typeof r=="object"?r["."]??(Object.keys(r).some(l=>l.startsWith("."))?null:r):null,s=pr(o)??(typeof n.module=="string"?n.module:null)??(typeof n.main=="string"?n.main:null);if(!s)return null;let i=new Set(t.map(l=>jt.resolve(l))),a=jt.resolve(e,s);for(let l of Da)if(i.has(a+l))return t.find(d=>jt.resolve(d)===a+l);let c=[];try{c=Qn.readdirSync(e).filter(l=>Qf.test(l)).sort()}catch{}for(let l of c){let d;try{d=Qn.readFileSync(jt.join(e,l),"utf8")}catch{continue}let f=/\bentry(?:Points)?\s*:\s*[\[{]?\s*(?:["'\w-]+\s*:\s*)?["'`]([^"'`]+)["'`]/.exec(d);if(!f)continue;let u=jt.resolve(e,f[1]);for(let h of Da)if(i.has(u+h))return t.find(p=>jt.resolve(p)===u+h)}return null}function Ua(e,t,n,r,o=null){let s=new Map;for(let m of n){let y=s.get(m.filePath);y||s.set(m.filePath,y=[]),y.push(m)}let i=new Map,a=(m,y)=>{y&&(!i.has(y.id)||m<i.get(y.id))&&i.set(y.id,m)},c=new Map,l=(m,y)=>{let g=c.get(m);if(!g){g=new Map;let x="";try{x=Qn.readFileSync(m,"utf8")}catch{}for(let S of x.matchAll(/^[ \t]*(?:export\s+)?const\s+([\w$]+)\s*(?::[^=\n]+)?=\s*([\w$]+)\s*(?:as\s+[^;\n]+)?;?[ \t]*$/gm))S[1]!==S[2]&&g.set(S[1],S[2]);c.set(m,g)}return g.get(y)??null},d=(m,y)=>(s.get(m)??[]).find(g=>(g.type==="function"||g.type==="arrowFunction")&&g.name===y),f=(m,y)=>(s.get(m)??[]).filter(g=>g.type==="classMethod"&&g.className===y&&g.name!=="constructor"&&!/^[_#]/.test(g.name)),u=new Set;function h(m,y,g,x=0){let S=d(m,g);if(S){a(y,S);return}let k=f(m,g);for(let j of k)a(`${y}.${j.name}`,j);if(k.length||!o)return;let v=o.resolveName(m,g);if(v){a(y,v);return}let w=o.bindingFor(m,g),b=w&&x<3?o.resolveImport(m,w.source,w.kind,w.imported):null;if(b?.file&&b.local&&b.local!=="default"&&l(b.file,b.local)){h(b.file,y,b.local,x+1);return}let N=o.classForImport(m,g);if(N?.className)for(let j of f(N.file,N.className))a(`${y}.${j.name}`,j);if(N?.className)return;let $=l(m,g);$&&x<3&&h(m,y,$,x+1)}function p(m,y,g){let x=m+"|"+(g?[...g.keys()].sort().join(","):"*");if(u.has(x)||y>3)return;u.add(x);let S=t.get(m)?.exportBindings;if(!S)return;let k=v=>!g||g.has(v);for(let[v,w]of Object.entries(S.named??{}))k(v)&&h(m,g?.get(v)??v,w);S.default&&k("default")&&S.default!=="<anon>"&&h(m,g?.get("default")??S.default,S.default);for(let v of S.reexports??[]){if(!k(v.exported))continue;let w=Je(v.source,m,r);w&&p(w,y+1,new Map([[v.imported,g?.get(v.exported)??v.exported]]))}for(let v of S.stars??[]){let w=Je(v,m,r);w&&(g?p(w,y+1,g):p(w,y+1,null))}}return p(e,0,null),[...i].map(([m,y])=>({name:y,nodeId:m})).sort((m,y)=>m.name<y.name?-1:m.name>y.name?1:m.nodeId<y.nodeId?-1:1).slice(0,Zf)}import eo from"node:fs";import dn from"node:path";var mr=null,hr=null,za=()=>mr?dn.join(mr,".canopy","last-stage.txt"):null,Wa=e=>{mr=e?dn.resolve(e):null},to=()=>hr;function eu(){let e=process.memoryUsage(),t=n=>Math.round(n/1048576);return{rssMB:t(e.rss),heapUsedMB:t(e.heapUsed),externalMB:t(e.external),arrayBuffersMB:t(e.arrayBuffers)}}var tu=()=>process.env.CANOPY_DEBUG_MEM==="1"||process.env.CANOPY_DEBUG_MEM==="true";function mt(e){hr=e;let t=za();if(t)try{eo.mkdirSync(dn.dirname(t),{recursive:!0}),eo.writeFileSync(t,e)}catch{}if(tu()){let n=eu();process.stderr.write(`[mem] ${e}: rss ${n.rssMB} MB, heapUsed ${n.heapUsedMB} MB, external ${n.externalMB} MB, arrayBuffers ${n.arrayBuffersMB} MB
|
|
21
|
+
`)}}function Ga(){hr=null;let e=za();if(e)try{eo.rmSync(e,{force:!0})}catch{}}function qa(e){try{return eo.readFileSync(dn.join(dn.resolve(e),".canopy","last-stage.txt"),"utf8").trim().slice(0,120)||null}catch{return null}}We();import Va from"node:path";import{fileURLToPath as nu}from"node:url";import{Parser as Ja,Language as ou}from"web-tree-sitter";var Ay=Va.dirname(nu(globalThis.__canopyUrl("src/stage2_parse/initHtmlParser.js")));async function Ya(){await Ja.init();let e=new Ja,t=Va.join(He("tree-sitter-html"),"tree-sitter-html.wasm"),n=await ou.load(t);return e.setLanguage(n),{parser:e,language:n}}function Ka(e,t){let r=ie(t,"htmlScriptRoot.scm").matches(e.rootNode);for(let o of r){let s=o.captures.find(a=>a.name==="attr_name"),i=o.captures.find(a=>a.name==="script_src");if(s&&s.node.text==="src"&&i)return i.node.text}return null}function Xa(e,t,n){let r=[];e.forEach((c,l)=>{c.steps.forEach(d=>{if(!d.hasOwnSubTrace)return;let f=e.findIndex((u,h)=>h!==l&&u.steps[0]?.nodeId===d.nodeId);f!==-1&&r.push({fromWorkflowIndex:l,toWorkflowIndex:f,atNodeId:d.nodeId})})});let o=new Map;for(let c of t)o.set(c.id,c.serviceName??null);let s=new Map;function i(c,l,d,f){if(!c||!l||c===l)return;let u=`${c} -> ${l} -> ${d}`;s.has(u)?s.get(u).count+=1:s.set(u,{fromService:c,toService:l,viaMatchType:d,count:1});let h=s.get(u);f==="exact"?h.exact=(h.exact??0)+1:f==="inferred"?h.inferred=(h.inferred??0)+1:f==="resolved"&&(h.resolved=(h.resolved??0)+1)}for(let c of n){if(!c.resolved||!c.fromNodeId||!c.targetNodeId)continue;let l=o.get(c.fromNodeId)??null,d=o.get(c.targetNodeId)??null;i(l,d,c.matchType,c.confidence)}let a=Array.from(s.values());return{workflowLinks:r,serviceLinks:a}}var iu=Z.dirname(ru(globalThis.__canopyUrl("src/index.js"))),Za=24*1e3*1e3;async function gr(e,t={}){e=Z.resolve(e),console.log(`
|
|
21
22
|
Analyzing: ${e}
|
|
22
|
-
`),console.log("Stage 1: finding source files...");let
|
|
23
|
-
Stage 1b: partitioning files by service...`);let
|
|
24
|
-
Stage 2: parsing (all files, once \u2014 see note above)...`);let
|
|
25
|
-
--- Service: ${I.name} (${I.kind}) \u2014 ${T.length} files in scope ---`),!T.length){console.log(" 0 files \u2014 nothing to trace for this service."),
|
|
26
|
-
--- Stage 5 (stitch): cross-service edge resolution ---`);let
|
|
27
|
-
`);return{available:!0,filePath:I,startLine:
|
|
28
|
-
Done: ${
|
|
29
|
-
`),
|
|
30
|
-
`+
|
|
31
|
-
workflows.json omitted (${(
|
|
32
|
-
Saved to output/workflows.json`),
|
|
33
|
-
Note on output shape: workflows.json entries gained two additive fields (serviceId, servicesTouched) \u2014 every field the old shape had (steps, name, trigger, occurrences, ...) is unchanged, so the existing viewer keeps working without modification.`);let
|
|
34
|
-
`+
|
|
23
|
+
`);let n=Date.now(),r=()=>{let I=Math.round((Date.now()-n)/1e3);return I>=60?`${Math.floor(I/60)} min ${I%60} s`:`${I} s`},o=I=>{try{t.onProgress?.(I)}catch{}};mt("finding source files"),console.log("Stage 1: finding source files...");let s=Ho(e),i=s.files;Ui(Gi(e,i)),console.log(` found ${i.length} files`);let{parser:a,language:c,grammars:l}=await bs();await Ns({grammars:l},i),console.log(`
|
|
24
|
+
Stage 1b: partitioning files by service...`);let d=_i(e,i),f=$i(d,i,e);d=f.services,f.added&&console.log(` note: ${f.added.reason} (service "${f.added.name}")`),console.log(` detected ${d.length} services: ${d.map(I=>`${I.name} (${I.kind})`).join(", ")}`);let u=new Map(d.map(I=>[I.name,[]])),h=[];for(let I of i){let T=_t(I,d);T?u.get(T).push(I):h.push(I)}console.log(" file partition:");for(let I of d)console.log(` ${I.name}: ${u.get(I.name).length} files`);console.log(` unassigned (shared/root-level): ${h.length} files`),h.length&&(console.log(" rule: these don't get their own Stage 5-7 run (no service of their own to have routes/listeners for) \u2014"),console.log(" each one is added to a service's parse scope ONLY if a file already in that"),console.log(" service actually imports it, so intra-service calls into shared code still resolve.")),console.log(`
|
|
25
|
+
Stage 2: parsing (all files, once \u2014 see note above)...`),mt("reading files");let p=await ki(i,a,c,{onProgress:t.onProgress,grammars:l,noCache:!!t.noCache});function m(I){let T=new Set;for(let U of I){let F=p.get(U);if(F)for(let B of F.imports){let pe=Je(B.source,U,i);pe&&h.includes(pe)&&T.add(pe)}}return[...T]}let y=new Map;for(let I of d){let T=u.get(I.name),U=m(T);y.set(I.name,[...T,...U]),console.log(` ${I.name}: ${T.length} own + ${U.length} shared file(s) pulled in by real imports = ${T.length+U.length} total scope`)}let g=d.filter(I=>!y.get(I.name)?.length);g.length&&(console.log(` excluding ${g.length} service(s) with 0 files: ${g.map(I=>I.name).join(", ")}`),d=d.filter(I=>y.get(I.name)?.length));let x=null,S=Oa(e);if(S){let{parser:I,language:T}=await Ya(),U=we.readFileSync(S,"utf-8"),F=I.parse(U),B=Ka(F,T);if(B){let pe=Z.dirname(S),H=Z.join(pe,B);i.includes(H)&&(x=H,console.log(` found HTML root: ${B} -> ${H}`))}}let k=new Map,v=0,w=0,b=0;for(let I of d){let T=y.get(I.name);if(v++,mt(`linking calls: service ${v} of ${d.length}`),o(`linking calls: service ${v} of ${d.length} (${r()})`),console.log(`
|
|
26
|
+
--- Service: ${I.name} (${I.kind}) \u2014 ${T.length} files in scope ---`),!T.length){console.log(" 0 files \u2014 nothing to trace for this service."),k.set(I.name,{nodes:[],resolvedEdges:[],workflows:[],routeIndex:new Map,eventIndex:new Map,rawEventIndex:new Map,parseResults:new Map});continue}let U=fi(new Map(T.map(A=>[A,p.get(A)]))),F=Ii(U,d),B=ji(U,d);F=Pi(F.concat(B)),console.log(` Stage 3: materialized ${B.length} inline-handler nodes before edge construction`);let pe=Li(U,F),H=ua(U,F),Ne=ma(U,F),ee=Aa(U,F);for(let A of T){let re=new Set(U.get(A)?.exportedNames??[]);for(let X of F.filter(V=>V.filePath===A))X.exported=re.has(X.name)}let be=Ki(pe,F,U,T,H,Ne,ee),Ae=be.filter(A=>A.resolved).length;console.log(` Stage 4 (scoped): resolved ${Ae}/${be.length} edges`);for(let A of T){let re=U.get(A),X=re?.routes??[],V=re?.listeners??[],ce=he(A,F),ze=Gt(A,re?.imports??[],T),kn=[];I.kind==="server"&&(kn=re?.socketListeners??[]),F=Zi(F,A,X,V,ce,kn,ze)}let Me=F.filter(A=>A.isEntryPoint),wt=Me.filter(A=>A.trigger?.resolvedVia==="in-file").length,lt=Me.filter(A=>A.trigger?.resolvedVia==="cross-file").length,dt=Me.filter(A=>A.trigger?.resolvedVia==="inline").length;console.log(` Stage 5 entry points by resolution: in-file named ${wt}, cross-file named (BUG A) ${lt}, inline (BUG B) ${dt}`);let wn=be.filter(A=>A.type!=="reference"&&!A.viaArgument),Sn=ea(F,wn),St=[];if(I.kind==="client"&&x&&T.includes(x)&&St.push({id:`${x}::__module_root__`,name:"main",trigger:{type:"htmlRoot",label:"index.html script"}}),!St.length){let A=Hn(I.rootPath,i),re=A&&T.find(X=>Z.resolve(X)===A.entry);re&&(console.log(` found HTML root for ${I.name}: ${Z.relative(e,A.indexHtml)} -> ${Z.relative(e,re)} (${A.via})`),St.push({id:`${re}::__module_root__`,name:"main",trigger:{type:"htmlRoot",label:"index.html script"}}))}let Rt=[];if(I.kind==="server"){let A=Z.join(I.rootPath,"package.json");if(we.existsSync(A))try{let re=JSON.parse(we.readFileSync(A,"utf-8")),X=re.main;if(!X&&re.scripts?.start){let V=re.scripts.start.match(/([\w./-]+\.(?:js|mjs|cjs|ts))/);V&&(X=V[1])}if(X){let V=Z.resolve(I.rootPath,X),ce=T.find(ze=>Z.resolve(ze)===V);if(!ce){let ze=qn(I.rootPath,X,re);ze&&(ce=T.find(kn=>Z.resolve(kn)===ze.file))}ce?Rt.push({id:`${ce}::__module_root__`,name:"main",trigger:{type:"processBootstrap",label:`${X} (package.json main)`}}):console.log(` note: ${I.name}'s package.json names "${X}" as its entry, but that file isn't in this service's own traced scope \u2014 no bootstrap workflow added.`)}}catch{}}if(!St.length){let A=new Set(Rt.map(V=>V.id.split("::")[0])),re=new Set;for(let V of be)V.resolved&&V.fromNodeId.endsWith("::__module_root__")&&re.add(V.fromNodeId);let X=Ma(I.rootPath).map(V=>({...V,file:T.find(ce=>Z.resolve(ce)===V.file)})).filter(V=>V.file);for(let V of T)Ha(V)&&!X.some(ce=>ce.file===V)&&X.push({file:V,kind:"shebang"});for(let V of X){if(A.has(V.file)||Wt(Z.relative(e,V.file))||!re.has(`${V.file}::__module_root__`))continue;A.add(V.file);let ce=Z.relative(I.rootPath,V.file).split(Z.sep).join("/"),ze=V.kind==="bin"?`CLI: ${V.binName}`:`Start: ${ce}`;Rt.push({id:`${V.file}::__module_root__`,name:"main",trigger:{type:"processBootstrap",label:`${ce} (${V.kind==="bin"?"package.json bin":V.kind==="script"?"package.json script":V.kind==="main"?"package.json main":"#! shebang"}${V.mappedFrom?`, built to ${V.mappedFrom}`:""})`,workflowName:ze}})}}let en=[];if(St.length+Rt.length+Me.filter(A=>!Wt(Z.relative(e,A.filePath))).length===0){let A=Ba(I.rootPath,T);if(A){let re=Z.relative(I.rootPath,A).split(Z.sep).join("/"),V=Un(F,U,ce=>Gt(ce,U.get(ce)?.imports??[],T));for(let ce of Ua(A,U,F,T,V))en.push({id:ce.nodeId,name:F.find(ze=>ze.id===ce.nodeId)?.name??ce.name,trigger:{type:"publicApi",label:`${ce.name} (exported from ${re})`,workflowName:`API: ${ce.name}`}});en.length&&console.log(` public API of ${I.name}: ${en.length} exported function(s)/method(s) from ${re}`)}}let ts=new Set(en.map(A=>A.id)),hl=ts.size?Sn.filter(A=>!ts.has(A.id)):Sn,Io=[...St,...Rt,...Me,...en,...hl];console.log(` Stage 5 total entry points: ${Io.length} (${St.length} HTML root, ${Rt.length} process bootstrap, ${Me.length} pattern-matched, ${Sn.length} fallback)`);let gl=sr(be),yl=oa(Io,gl,F,wn,8,wn.length===be.length?null:sr(wn)),vl=new Set(Sn.map(A=>A.id)),xl=A=>A.trigger?"physical":vl.has(A.entryPointId)?"fallback":"hub",wl=yl.map(A=>({...A,origin:xl(A),steps:ra(A.steps,F)})),Sl=ia(wl),ns=Array.from(Sl.values()).map(aa),os=ns.filter(A=>!Wt(Z.relative(e,String(A.steps[0]?.nodeId??"").split("::")[0])));b+=ns.length-os.length;let At=fa(os,{nodes:F});if(At.some(A=>A.trigger)){let A=new Set(be.filter(X=>X.type!=="returnValue"&&X.type!=="reference").map(X=>X.fromNodeId)),re=new Set(At.filter(X=>!X.trigger&&X.steps.length===1&&!A.has(X.steps[0].nodeId)).map(X=>X.steps[0].nodeId));re.size&&(At=At.filter(X=>X.trigger||!re.has(X.steps[0].nodeId)||X.steps.length>1),w+=re.size)}console.log(` Stage 6-7: -> ${At.length} named workflows for ${I.name}`),k.set(I.name,{nodes:F,resolvedEdges:be,routeIndex:H,eventIndex:Ne,rawEventIndex:ee,workflows:At,parseResults:U,files:T,entryPointCount:Io.length})}console.log(`
|
|
27
|
+
--- Stage 5 (stitch): cross-service edge resolution ---`),mt("linking services together"),o(`linking services together (${r()})`);let N=[],$=0,j=0;for(let I of d){let T=k.get(I.name);if(!T||!T.resolvedEdges.length)continue;let U=T.resolvedEdges.filter(F=>!F.resolved&&(F.type==="apiCall"||F.type==="socketEmit"||F.type==="rawSocketSend"));for(let F of U){let B=null,pe=null;for(let H of d){if(H.name===I.name)continue;let Ne=k.get(H.name);if(!Ne)continue;let ee=null;if(F.type==="apiCall"&&F.scope!=="external"?ee=Ne.routeIndex.get(qt(F.url)):F.type==="socketEmit"?ee=Ne.eventIndex.get(F.eventName):F.type==="rawSocketSend"&&(ee=Ne.rawEventIndex.get(F.eventName)),ee){B=ee,pe=H.name;break}}B?(N.push({fromService:I.name,fromNodeId:F.fromNodeId,toService:pe,toNodeId:B,via:F.type,key:F.url||F.eventName,confidence:"inferred",reason:"name-only match",...F.type==="apiCall"?{url:F.url}:{eventName:F.eventName}}),$++):j++}}console.log(` stitched ${$} cross-service edges`);let O=Ra(d,k,{repoRoot:e});for(let I of O.edges)N.push(I);if(console.log(` + ${O.edges.length} links from HTTP clients / WebSockets (${O.edges.filter(I=>I.confidence==="exact").length} exact, ${O.edges.filter(I=>I.confidence==="resolved").length} resolved)`),console.log(` ${j} unresolved calls remain unresolved even after checking every other service`),t.lowMemory)for(let I of p.values())for(let T of Object.keys(I))T!=="hadErrors"&&T!=="warnings"&&T!=="failed"&&T!=="skipped"&&T!=="errorMessage"&&delete I[T];let D=new Map;function G(I,T,U){if(!I||T==null||U==null)return{available:!1,reason:"no line range recorded for this node"};try{D.has(I)||(D.set(I,we.readFileSync(I,"utf-8").split(/\r\n|\n/)),D.size>256&&D.delete(D.keys().next().value));let F=D.get(I),B=Math.max(T,1),pe=Math.min(U,F.length);if(B>F.length)return{available:!1,reason:"recorded line range is past the end of the current file \u2014 source has likely moved"};let H=F.slice(B-1,pe).join(`
|
|
28
|
+
`);return{available:!0,filePath:I,startLine:B,endLine:pe,text:H}}catch(F){return{available:!1,reason:`source unavailable: ${F.code==="ENOENT"?"file not found (deleted or moved)":F.message}`}}}let M=/^(addEventListener|removeEventListener|on|once|postMessage|onmessage|subscribe)$/i,q=new Set(["call","methodCall","callSite"]);function E(I,T,U,F,B=null){let pe=H=>!!(B&&!F&&!H.deferred&&H.resolved&&H.targetNodeId&&q.has(H.type)&&H.targetNodeId!==I&&B.inWorkflow.has(H.targetNodeId)&&!B.children.has(H.targetNodeId));return T.filter(H=>H.fromNodeId===I&&H.type!=="apiCall").filter(H=>H.resolved&&H.targetNodeId?pe(H):!!H.deferred===F).map(H=>{let Ne=H.type==="returnValue",ee=!Ne&&M.test(H.calleeNameRaw||""),be=(H.branchPath??[]).map(lt=>({...lt,source:U?G(U,lt.conditionLine,lt.conditionLine):{available:!1,reason:"owning function's node not found"}})),Ae=H.objectNameRaw?`${H.objectNameRaw}.${H.calleeNameRaw}`:H.calleeNameRaw,Me=Ne?Ae:H.firstArgText?`${Ae}(${H.firstArgText})`:Ae,wt=pe(H);return{label:Me,line:H.line??null,column:H.column??null,branchPath:be,source:U?G(U,H.line,H.line):{available:!1,reason:"owning function's node not found"},tag:wt?"called-elsewhere":Ne?"return-value":ee?"runtime-dispatched":"unresolvable-call-site",...wt?{targetNodeId:H.targetNodeId}:{},reason:wt?"a call to a function this workflow shows under another step (a function is placed once, under the first step that reaches it); it runs here, at this line, in this order":Ne?"the value this branch returns \u2014 not a function call, just what this path produces":ee?`registered via ${H.calleeNameRaw}(...) \u2014 the handler runs later, outside this function's own execution`:F?"runs later, outside this function's own execution (an effect cleanup, a deferred callback)":"call target could not be statically resolved to a declared function (dynamic dispatch, external/browser API, or computed member access) \u2014 but it still runs here, in this order"}})}function C(I,T,U){return E(I,T,U,!0)}function R(I,T,U,F){return E(I,T,U,!1,F)}let W=[];for(let I of d){let T=k.get(I.name);if(!T)continue;let U=new Map(T.nodes.map(F=>[F.id,F]));for(let F of T.workflows){let B=new Set([I.name]),pe=new Set(F.steps.map(ee=>ee.nodeId)),H=new Map;for(let ee of F.steps)ee.parentNodeId!=null&&(H.get(ee.parentNodeId)??H.set(ee.parentNodeId,new Set).get(ee.parentNodeId)).add(ee.nodeId);let Ne=F.steps.map(ee=>{let be=N.find(dt=>dt.fromService===I.name&&dt.fromNodeId===ee.nodeId),Ae=U.get(ee.nodeId),Me=ee.parentNodeId?U.get(ee.parentNodeId):null,wt=(ee.branchPath??[]).map(dt=>({...dt,source:Me?G(Me.filePath,dt.conditionLine,dt.conditionLine):{available:!1,reason:"owning function's node not found"}})),lt={...ee,branchPath:wt,source:Ae?G(Ae.filePath,Ae.startLine,Ae.endLine):{available:!1,reason:"node not found in this service's own graph"},alsoCallsRuntime:C(ee.nodeId,T.resolvedEdges,Ae?.filePath),inlineCalls:R(ee.nodeId,T.resolvedEdges,Ae?.filePath,{inWorkflow:pe,children:H.get(ee.nodeId)??new Set})};return be&&(B.add(be.toService),lt.crossesInto=be.toService),lt});W.push({...F,steps:Ne,serviceId:I.name,servicesTouched:[...B]})}}console.log(`
|
|
29
|
+
Done: ${W.length} named workflows across all services
|
|
30
|
+
`),W.forEach(I=>console.log(` - [${I.serviceId}] ${I.name} (${I.steps.length} steps, ${I.occurrences} entry point(s))`)),mt("writing the map"),o(`writing the map (${r()})`);let K=t.outputDir??process.env.CANOPY_OUTPUT_DIR??Z.join(iu,"..","output");we.existsSync(K)||we.mkdirSync(K,{recursive:!0});let se=Bn(e),Xe=new Set(d.flatMap(I=>y.get(I.name)??[])),ue=ws({discovered:s,parseResults:p,scopeFiles:Xe,rel:se.rel,rootService:f.added});ue.testWorkflowsExcluded=b,ue.guessedWorkflowsDropped=w;let _={repoRoot:se.repoRoot,coverage:ue};we.writeFileSync(Z.join(K,"meta.js"),`const meta = ${JSON.stringify(_,null,2)};`),we.writeFileSync(Z.join(K,"meta.json"),JSON.stringify(_,null,2)),console.log(`
|
|
31
|
+
`+jn(ue)),we.existsSync(Z.join(K,"history.js"))||we.writeFileSync(Z.join(K,"history.js"),"const canopyHistory = null;");let P=se.json(W,2),L=P.length>Za;if(L&&(P=se.json(W)),L&&P.length>Za){let I=Xi(JSON.parse(P));we.writeFileSync(Z.join(K,"workflows.js"),`const workflows = ${I};`),we.rmSync(Z.join(K,"workflows.json"),{force:!0}),console.log(`
|
|
32
|
+
workflows.json omitted (${(P.length/1e6).toFixed(1)} MB plain); workflows.js written with shared sub-structures (${(I.length/1e6).toFixed(1)} MB)`)}else we.writeFileSync(Z.join(K,"workflows.json"),P),console.log(`
|
|
33
|
+
Saved to output/workflows.json`),we.writeFileSync(Z.join(K,"workflows.js"),`const workflows = ${P};`),console.log("Saved to output/workflows.js (for the viewer)");let z=d.flatMap(I=>k.get(I.name)?.nodes??[]),Re=N.map(I=>({fromNodeId:I.fromNodeId,targetNodeId:I.toNodeId,resolved:!0,matchType:"crossLayer",confidence:I.confidence})),je=[...d.flatMap(I=>k.get(I.name)?.resolvedEdges??[]),...Re],ct=Xa(W,z,je);ct.crossServiceEdges=N,we.writeFileSync(Z.join(K,"systemGraph.js"),`const systemGraph = ${se.json(ct,2)};`);let Zt=d.map(({isRepoRoot:I,ownsLeftovers:T,...U})=>({...U,nodeCount:z.filter(F=>F.serviceName===U.name).length,workflowCount:W.filter(F=>F.serviceId===U.name).length}));we.writeFileSync(Z.join(K,"services.js"),`const services = ${se.json(Zt,2)};`),console.log(`Saved to output/systemGraph.js (${ct.workflowLinks.length} workflow links, ${ct.serviceLinks.length} service links)`),console.log("Saved to output/services.js"),console.log(`
|
|
34
|
+
Note on output shape: workflows.json entries gained two additive fields (serviceId, servicesTouched) \u2014 every field the old shape had (steps, name, trigger, occurrences, ...) is unchanged, so the existing viewer keeps working without modification.`);let Qt=new Map;for(let I of d){let T=k.get(I.name);if(!T)continue;let U=se.clone(T.nodes.map(B=>({id:B.id,name:B.name,type:B.type,filePath:B.filePath,bodyHash:B.bodyHash??null,startLine:B.startLine===0?0:B.startLine,endLine:B.endLine===Number.MAX_SAFE_INTEGER?null:B.endLine,serviceName:B.serviceName,isEntryPoint:!!B.isEntryPoint}))),F=Ei(se.clone(T.resolvedEdges.map(B=>({fromNodeId:B.fromNodeId,targetNodeId:B.targetNodeId??null,type:B.type,callKind:B.callKind,calleeNameRaw:B.calleeNameRaw,eventName:B.eventName,url:B.url,line:B.line??null,column:B.column??null,resolved:!!B.resolved,matchType:B.matchType??null}))));Qt.set(I.name,{nodes:U,edges:F})}return{workflows:W,perService:k,crossServiceEdges:N,services:d,publicGraph:Qt,publicWorkflows:se.clone(W),publicCrossServiceEdges:se.clone(N),fingerprint:Dn(Fi(i,se.rel)),analyzedFileCount:i.length,repoRoot:se.repoRoot,coverage:ue}}var au=process.argv[1]&&globalThis.__canopyUrl("src/index.js")===su(Z.resolve(process.argv[1])).href;au&&gr(process.argv[2]||process.cwd()).catch(e=>{console.error("Pipeline failed:",e),process.exit(1)});un();wr();ao();De();var Nu=ye.join(ye.dirname(Ic(globalThis.__canopyUrl("src/history/sync.js"))),"..","..","output"),bu=["workflows.json","workflows.js","systemGraph.js","services.js","meta.js","meta.json","history.js"],_u=ye.dirname(Ic(globalThis.__canopyUrl("src/history/sync.js"))).split(ye.sep).includes("node_modules"),Et=e=>process.env.CANOPY_OUTPUT_DIR||(_u&&e?ye.join(ye.resolve(e),".canopy","output"):Nu);async function $u(e,t){let n=console.log;console.log=()=>{};try{return await gr(e,t)}finally{console.log=n}}function Iu(e,{full:t=!1}={}){let n=ye.resolve(e),r=Bn(n),o=xc(n,$n(n),r.rel,{full:t});return{fingerprint:Dn(o.hashes),reused:o.reused,rehashed:o.rehashed}}function ju(e){try{let t=JSON.parse(yt.readFileSync(ye.join(Et(e),"meta.json"),"utf8"));return t.coverage&&ye.resolve(t.repoRoot)===ye.resolve(e)?t.coverage:null}catch{return null}}async function Cu(e,{keep:t,say:n=()=>{},full:r=!1}){let o=Date.now(),s=Ee(e),i=s.versions[s.versions.length-1],a=Iu(e,{full:r}),c=a.fingerprint,l=!!i&&i.fingerprint===c&&(r||i.engineVersion!==Vt()||i.outputFormat!==no);if(i&&i.fingerprint===c&&!l&&!r)return{status:"no-changes",version:i,ms:Date.now()-o,coverage:ju(e),fast:a};let d=yt.mkdtempSync(ye.join(ku.tmpdir(),"canopy-sync-"));try{let f=await $u(e,{outputDir:d,onProgress:n,lowMemory:!0,noCache:r});mt("storing the version"),n(`storing the version (${Math.round((Date.now()-o)/1e3)} s)`);let u=wc(f),h=Ct(u),p={nodes:u.nodes.length,edges:u.edges.length,workflows:u.workflows.length,physicalWorkflows:u.workflows.filter(w=>w.tier==="physical").length,crossServiceEdges:u.crossServiceEdges.length},m=so(e),y=rc(e,h,u,p,t,{refresh:l,protect:m?[m.version]:[]}),g=oc();g&&n("history: "+g);let x=fe(e,["rev-parse","--abbrev-ref","HEAD"]),S=fe(e,["rev-parse","HEAD^{tree}"]);jr(e,{engineFingerprint:Vt(),projectRoot:ye.resolve(e),lastAnalysed:{version:y.version,fingerprint:y.fingerprint,headSha:y.headSha,treeHash:S,branch:x}});let k=await Promise.resolve().then(()=>(po(),$c)).catch(()=>null);k&&k.writeHistoryJs(e,d);let v=Et(e);yt.mkdirSync(v,{recursive:!0});for(let w of bu)yt.existsSync(ye.join(d,w))?yt.copyFileSync(ye.join(d,w),ye.join(v,w)):yt.rmSync(ye.join(v,w),{force:!0});return{status:"new-version",version:y,ms:Date.now()-o,coverage:f.coverage}}finally{yt.rmSync(d,{recursive:!0,force:!0})}}function Fu(e,t=()=>{}){let n=yc(e);if(!n.ok){let r=vc(e);t(`The saved history in .canopy was damaged (${n.problems[0]}). It was moved to .canopy/${r} and Canopy is starting a fresh one; this run rebuilds everything.`)}Ir(e,Vt())}async function mo(e,{keep:t=fn,say:n=console.log,full:r=!1}={}){if(e=ye.resolve(e),ro(e),yt.mkdirSync(te(e).root,{recursive:!0}),Fu(e,n),!sc(e,process.env.CANOPY_VERSION??null,n))return ac(e),n("sync already running - one rerun queued"),{status:"queued"};let o;try{do o=await Cu(e,{keep:t,say:n,full:r}),r=!1,o.status==="no-changes"?n(`no changes (v${o.version.version} ${o.version.fingerprint.slice(0,7)}) [${o.ms} ms]`):n(`v${o.version.version} ${o.version.fingerprint.slice(0,7)} stored: ${o.version.counts.nodes} nodes, ${o.version.counts.edges} edges, ${o.version.counts.workflows} workflows, ${(o.version.bytes/1024/1024).toFixed(2)} MB${o.version.gzip?" (gzip)":""} [${o.ms} ms]`),o.coverage&&n(`
|
|
35
|
+
`+jn(o.coverage));while(cc(e))}finally{ic(e)}return o}De();De();We();import ve from"node:fs";import Be from"node:path";import{spawn as Eu}from"node:child_process";import{fileURLToPath as Pu}from"node:url";var mn="# >>> canopy sync (managed block - do not edit) >>>",Fc="# <<< canopy sync <<<",Pt=["post-commit","post-merge"],Lu=globalThis.__canopyBundle??Be.join(Be.dirname(Pu(globalThis.__canopyUrl("src/history/hooks.js"))),"..","cli.js"),Tu=e=>Be.resolve(e).split(Be.sep).join("/");function hn(e){let t=fe(e,["rev-parse","--git-path","hooks"]);if(!t)throw new Error(`not a git repository: ${e}`);return Be.resolve(e,t)}var jc=JSON.parse(ve.readFileSync(Be.join(le,"package.json"),"utf8")),Ru=jc.name+"@"+jc.version,Cc=e=>Tu(e).replace(/(["$`\\])/g,"\\$1");function ho(e){return[mn,"(",` if command -v canopy >/dev/null 2>&1; then canopy sync --background "${Cc(e)}" >/dev/null 2>&1 </dev/null`,` elif command -v npx >/dev/null 2>&1; then ( npx --yes ${Ru} sync --background "${Cc(e)}" >/dev/null 2>&1 </dev/null & )`,' else echo "canopy not found; skipping map update"'," fi",") || true",Fc].join(`
|
|
35
36
|
`)+`
|
|
36
|
-
`}var
|
|
37
|
-
`+
|
|
38
|
-
`+
|
|
37
|
+
`}var go=()=>new RegExp(`\\n?${mn.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}[\\s\\S]*?${Fc.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\n?`);function gn(e){let t=hn(e);ve.mkdirSync(t,{recursive:!0});let n=[];for(let r of Pt){let o=Be.join(t,r),s=ve.existsSync(o)?ve.readFileSync(o,"utf8"):null,i;s===null?i=`#!/bin/sh
|
|
38
|
+
`+ho(e):go().test(s)?i=s.replace(go(),()=>`
|
|
39
|
+
`+ho(e)):i=s+(s.endsWith(`
|
|
39
40
|
`)?"":`
|
|
40
41
|
`)+`
|
|
41
|
-
`+
|
|
42
|
-
`));try{
|
|
43
|
-
`);i.replace(/^#!.*\n?/,"").trim()===""?
|
|
42
|
+
`+ho(e),ve.writeFileSync(o,i.replace(/\r\n/g,`
|
|
43
|
+
`));try{ve.chmodSync(o,493)}catch{}n.push(o)}return n}function Ec(e){let t=hn(e),n=[];for(let r of Pt){let o=Be.join(t,r);if(!ve.existsSync(o))continue;let s=ve.readFileSync(o,"utf8");if(!go().test(s))continue;let i=s.replace(go(),`
|
|
44
|
+
`);i.replace(/^#!.*\n?/,"").trim()===""?ve.rmSync(o,{force:!0}):ve.writeFileSync(o,i.replace(/\n{3,}/g,`
|
|
44
45
|
|
|
45
|
-
`)),n.push(o)}return n}function
|
|
46
|
+
`)),n.push(o)}return n}function Pc(e){if(!ve.existsSync(Be.resolve(e)))return null;let t=te(e);ve.mkdirSync(t.root,{recursive:!0});let n=ve.openSync(t.log,"a");ve.writeSync(n,`
|
|
46
47
|
--- ${new Date().toISOString()} sync requested (pid ${process.pid})
|
|
47
|
-
`);let
|
|
48
|
-
`);a.includes(
|
|
48
|
+
`);let r=Object.fromEntries(Object.entries(process.env).filter(([s])=>!/^GIT_/i.test(s)||s.toUpperCase()==="GIT_EXEC_PATH")),o=Eu(process.execPath,[Lu,"sync",Be.resolve(e)],{detached:!0,stdio:["ignore",n,n],windowsHide:!0,env:r});return o.unref(),ve.closeSync(n),o.pid}function Lc(e){let t=hn(e),n=ho(e),r=0,o=0;for(let s of Pt){let i=Be.join(t,s);if(!ve.existsSync(i))continue;let a=ve.readFileSync(i,"utf8").replace(/\r\n/g,`
|
|
49
|
+
`);a.includes(mn)&&(r++,a.includes(n)&&o++)}return r<Pt.length?"absent":o===Pt.length?"current":"outdated"}Er();We();We();import vt from"node:fs";import pp from"node:http";import Ie from"node:path";import{spawn as mp}from"node:child_process";We();import Au from"node:fs";import Ou from"node:http";import Mu from"node:https";import Or from"node:path";import{spawn as Hu,spawnSync as Rc}from"node:child_process";var Hr="https://registry.npmjs.org/canopy-engine/latest",Ar="npm install -g canopy-engine@latest",Tc=1e4,Du=256*1024,Mr=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/,Bu=e=>typeof e=="string"&&e.length<=64&&Mr.test(e);function Uu(e,t){let n=Mr.exec(e),r=Mr.exec(t);for(let o=1;o<=3;o++){let s=Number(n[o])-Number(r[o]);if(s)return s>0?1:-1}return n[4]&&!r[4]?-1:!n[4]&&r[4]?1:n[4]===r[4]?0:n[4]>r[4]?1:-1}function zu(e=process.env){let t=e.CANOPY_REGISTRY_URL;return t&&/^http:\/\/127\.0\.0\.1:\d{1,5}(\/|$)/.test(t)?t:Hr}function Wu(e=process.env){let t=zu(e),n=t.startsWith("https:")?Mu:Ou;return new Promise((r,o)=>{let s=!1,i=(c,l)=>{s||(s=!0,c(l))},a=n.get(t,{headers:{accept:"application/json","user-agent":"canopy-engine-update-check"}},c=>{if(c.statusCode!==200)return c.resume(),i(o,new Error(`the registry answered HTTP ${c.statusCode}`));let l=0,d=[];c.on("data",f=>{if(l+=f.length,l>Du){i(o,new Error("the registry's answer is larger than 256 KB; ignored")),a.destroy();return}d.push(f)}),c.on("end",()=>{let f;try{f=JSON.parse(Buffer.concat(d).toString("utf8"))?.version}catch{return i(o,new Error("the registry's answer is not valid JSON"))}if(!Bu(f))return i(o,new Error("the registry's answer has no valid version number"));i(r,f)}),c.on("error",f=>i(o,new Error("the connection broke: "+f.message)))});a.setTimeout(Tc,()=>{i(o,new Error(`no answer from the registry within ${Tc/1e3} s`)),a.destroy()}),a.on("error",c=>i(o,new Error("could not reach the registry: "+(c.code||c.message))))})}function Dr(e=le,t=Dt()){return e.split(Or.sep).includes("_npx")?"npx":t?"installed":"dev"}function Ac(e=process.env){let t=e.CANOPY_NPM_BIN;return t?/\.(c|m)?js$/i.test(t)?{cmd:process.execPath,pre:[t],shell:!1}:{cmd:t,pre:[],shell:process.platform==="win32"&&/\.(cmd|bat)$/i.test(t)}:{cmd:process.platform==="win32"?"npm.cmd":"npm",pre:[],shell:process.platform==="win32"}}var yn=(e,t)=>t&&/[\s"]/.test(e)?`"${e.replace(/"/g,'\\"')}"`:e;function Gu(e,t){let{cmd:n,pre:r,shell:o}=Ac(t);return new Promise(s=>{let i=Hu(yn(n,o),[...r,...e].map(a=>yn(a,o)),{stdio:"inherit",shell:o,env:t});i.on("error",()=>s(1)),i.on("close",a=>s(a??1))})}function qu(e,t){let{cmd:n,pre:r,shell:o}=Ac(t),s=Rc(yn(n,o),[...r,...e].map(i=>yn(i,o)),{encoding:"utf8",shell:o,env:t,timeout:3e4});return s.status===0?s.stdout.trim():null}function Ju(e){let t=qu(["prefix","-g"],e),n=["canopy","canopy-engine"],r=[];if(t)for(let o of n)r.push(process.platform==="win32"?Or.join(t,o+".cmd"):Or.join(t,"bin",o));for(let o of r){if(!Au.existsSync(o))continue;let s=process.platform==="win32"&&/\.(cmd|bat)$/i.test(o),i=Rc(yn(o,s),["--version"],{encoding:"utf8",shell:s,env:e,timeout:3e4});if(i.status===0)return i.stdout.trim().split(/\r?\n/).pop().trim()}return null}async function Oc({check:e,version:t,root:n=le,installed:r=Dt(),env:o=process.env,out:s=console.log,err:i=console.error}){let a=Dr(n,r);if(a==="dev")return s("dev checkout: update disabled"),0;if(a==="npx")return s("You are running via npx; npx canopy-engine@latest always uses the newest version"),0;let c;try{c=await Wu(o)}catch(f){return i(`could not check for updates: ${f.message}`),i(" you can look it up yourself: npm view canopy-engine version"),1}if(Uu(c,t)<=0)return s(`up to date (${t})`),0;if(e)return s(`${c} available (you have ${t}). Run: canopy update`),0;s(`Updating canopy-engine ${t} -> ${c}`),s(` running: ${Ar}`);let l=await Gu(["install","-g","canopy-engine@latest"],o);if(l!==0)return i(`The update did not finish (npm exited with ${l}). Run it yourself: ${Ar}`),1;let d=Ju(o);return d!==c?(i(`npm finished, but the installed canopy reports ${d??"no version"} instead of ${c}. Run it yourself: ${Ar}`),1):(s(`Updated: canopy ${d} is installed.`),0)}import Le from"node:fs";import Pe from"node:path";import Br from"node:vm";import Dc from"node:crypto";import Vu from"node:zlib";var Mc=30,Yt=400,Hc=2*1024*1024,Yu="x-canopy-token",Bc=()=>Dc.randomBytes(24).toString("hex"),Ku=/^(\.env($|[.\-_])|\.npmrc$|\.netrc$|\.pgpass$|\.htpasswd$|id_(rsa|dsa|ecdsa|ed25519)|credentials(\.|$)|.*\.(pem|key|crt|cer|der|p12|pfx|jks|keystore|ppk|gpg|asc|kdbx)$)/i,yo=e=>Ku.test(e);function Xu(e){let t=Pe.join(e,"workflows.json"),n=Pe.join(e,"workflows.js");if(Le.existsSync(t))return{mtime:Le.statSync(t).mtimeMs,data:JSON.parse(Le.readFileSync(t,"utf8"))};if(Le.existsSync(n)){let r=Br.createContext({});return Br.runInContext(Le.readFileSync(n,"utf8"),r,{timeout:1e4}),{mtime:Le.statSync(n).mtimeMs,data:Br.runInContext("workflows",r,{timeout:1e4})}}return null}var Uc=e=>Pe.join(Pe.resolve(e),".canopy","history");function Ur(e){try{let t=JSON.parse(Le.readFileSync(Pe.join(Uc(e),"index.json"),"utf8"));return Array.isArray(t.versions)?t:null}catch{return null}}function zr(e,t){try{if(!t||typeof t.file!="string"||!/^[0-9A-Za-z][0-9A-Za-z._-]*$/.test(t.file))return null;let n=Le.readFileSync(Pe.join(Uc(e),t.file));return JSON.parse((t.gzip?Vu.gunzipSync(n):n).toString("utf8"))}catch{return null}}function Zu(e){let t=Ur(e),n=t?.versions[t.versions.length-1],r=n?zr(e,n):null;return r?{version:n.version,nodes:Array.isArray(r.nodes)?r.nodes:[]}:null}function Qu(e,t=null){let n=new Map;for(let r of e??[])for(let o of r.steps??[]){if(n.has(o.nodeId))continue;let s=o.nodeId.lastIndexOf("::"),i=s===-1?o.nodeId:o.nodeId.slice(0,s),a=o.source&&o.source.available?o.source:null;n.set(o.nodeId,{file:i,startLine:a?.startLine??null,endLine:a?.endLine??null,text:a?.text??null})}for(let r of t??[]){if(typeof r?.id!="string"||n.has(r.id))continue;let o=r.id.lastIndexOf("::");n.set(r.id,{file:typeof r.filePath=="string"?r.filePath:o===-1?r.id:r.id.slice(0,o),startLine:Number.isInteger(r.startLine)&&r.startLine>0?r.startLine:null,endLine:Number.isInteger(r.endLine)?r.endLine:null,text:null})}return n}function zc({outDir:e,repoRoot:t}){let n=null,r=()=>{try{return Le.realpathSync(t)}catch{return null}};function o(){let a=["workflows.json","workflows.js"].map(l=>Pe.join(e,l)).concat(t?[Pe.join(t,".canopy","history","index.json")]:[]),c=0;for(let l of a)try{c=Math.max(c,Le.statSync(l).mtimeMs)}catch{}if(!n||n.stamp!==c){let l=Xu(e),d=t?Zu(t):null;n={stamp:c,index:Qu(l?.data??[],d?.nodes),all:d}}return n.index}function s(){o();let a=n?.all;if(!a)return{status:200,body:{ok:!0,available:!1,nodes:[]}};let c=6e4,l=a.nodes.slice(0,c).map(d=>[d.id,d.name,d.kind,d.service,d.startLine??null,d.endLine??null]);return{status:200,body:{ok:!0,available:!0,version:a.version,total:a.nodes.length,truncated:a.nodes.length>c,nodes:l}}}function i(a){try{if(typeof a!="string"||!a||a.length>2e3)return{status:400,body:{ok:!1,code:"bad-request",message:"node must be a node id"}};let c=o().get(a);if(!c)return{status:404,body:{ok:!1,code:"unknown-node",message:"no such node in the analysed graph"}};if(c.startLine==null)return{status:404,body:{ok:!1,code:"no-range",message:"no source range was recorded for this node"}};let l=r();if(!l)return{status:410,body:{ok:!1,code:"changed",message:"file changed since analysis (the project folder is gone)"}};let d=c.file.split(/[\\/]/);if(!c.file||Pe.isAbsolute(c.file)||/^[A-Za-z]:/.test(c.file)||d.includes(".."))return{status:403,body:{ok:!1,code:"outside-repo",message:"refused: not a path inside the analysed project"}};let f=Pe.resolve(l,c.file),u;try{u=Le.realpathSync(f)}catch{return{status:410,body:{ok:!1,code:"changed",message:"file changed since analysis (the file no longer exists)",file:c.file}}}if(u!==l&&!u.startsWith(l+Pe.sep))return{status:403,body:{ok:!1,code:"outside-repo",message:"refused: the file resolves outside the analysed project"}};let h=Pe.basename(u);if(yo(Pe.basename(f))||yo(h))return{status:403,body:{ok:!1,code:"refused",message:"refused: environment, key and certificate files are never served"}};let p=Le.statSync(u);if(!p.isFile())return{status:403,body:{ok:!1,code:"refused",message:"refused: not a regular file"}};if(p.size>Hc)return{status:403,body:{ok:!1,code:"too-large",message:`refused: the file is larger than ${Hc/1024/1024} MB`}};let m=Le.readFileSync(u);if(m.subarray(0,8e3).includes(0))return{status:403,body:{ok:!1,code:"binary",message:"refused: binary file"}};let y=m.toString("utf8").replace(/\r\n/g,`
|
|
49
50
|
`).split(`
|
|
50
|
-
`);
|
|
51
|
-
`).replace(/\s+$/gm,""),N=
|
|
52
|
-
`).replace(/\s+$/gm,"");if(b.trim()!==N.trim())return{status:409,body:{ok:!1,code:"changed",message:"file changed since analysis",file:
|
|
51
|
+
`);y.length>1&&y[y.length-1]===""&&y.pop();let g=y.length,{startLine:x,endLine:S}=c;if(c.text!=null){let b=y.slice(x-1,S).join(`
|
|
52
|
+
`).replace(/\s+$/gm,""),N=c.text.replace(/\r\n/g,`
|
|
53
|
+
`).replace(/\s+$/gm,"");if(b.trim()!==N.trim())return{status:409,body:{ok:!1,code:"changed",message:"file changed since analysis",file:c.file,startLine:x,endLine:S}}}else if(S>g)return{status:409,body:{ok:!1,code:"changed",message:"file changed since analysis",file:c.file,startLine:x,endLine:S}};let k=Math.max(1,x-Mc),v=Math.min(g,S+Mc),w=!1;if(v-k+1>Yt)if(w=!0,S-x+1>=Yt)k=x,v=x+Yt-1;else{let b=Yt-(S-x+1);k=Math.max(1,x-Math.floor(b/2)),v=Math.min(g,k+Yt-1),k=Math.max(1,v-Yt+1)}return{status:200,body:{ok:!0,nodeId:a,file:c.file,startLine:x,endLine:S,from:k,to:v,total:g,truncated:w,lines:y.slice(k-1,v)}}}catch{return{status:500,body:{ok:!1,code:"error",message:"the source could not be read"}}}}return{read:i,graph:o,allNodes:s}}var ep=(e,t)=>{let n=Buffer.from(String(e??"")),r=Buffer.from(String(t??""));return n.length===r.length&&n.length>0&&Dc.timingSafeEqual(n,r)};function Wc(e,t){if(!new Set([`127.0.0.1:${t}`,`localhost:${t}`]).has(String(e.headers.host??"").toLowerCase()))return!1;let r=e.headers.origin;return!(r!==void 0&&!(r===`http://127.0.0.1:${t}`||r===`http://localhost:${t}`))}function Kt(e,t,n="GET"){return e.method!==n?{status:405,body:{ok:!1,code:"method",message:n+" only"}}:ep(e.headers[Yu],t)?null:{status:403,body:{ok:!1,code:"token",message:"missing or wrong session token"}}}function Gc(e,t,{token:n,service:r}){let o=Kt(e,n);return o||([...t.searchParams.keys()].length?{status:400,body:{ok:!1,code:"bad-request",message:"this request takes no parameters"}}:r.allNodes())}function qc(e,t,{port:n,token:r,service:o}){let s=Kt(e,r);if(s)return s;let i=[...t.searchParams.keys()];return i.length!==1||i[0]!=="node"||t.searchParams.getAll("node").length!==1?{status:400,body:{ok:!1,code:"bad-request",message:"send exactly one parameter: node=<node id>"}}:o.read(t.searchParams.get("node"))}import rp from"node:path";import{execFile as sp}from"node:child_process";function tp(e,t,n){let r=e.length,o=t.length,s=Math.min(r+o,n),i=s+1,a=new Int32Array(2*s+3),c=[];for(let l=0;l<=s;l++){c.push(a.slice());for(let d=-l;d<=l;d+=2){let f=d===-l||d!==l&&a[i+d-1]<a[i+d+1]?a[i+d+1]:a[i+d-1]+1,u=f-d;for(;f<r&&u<o&&e[f]===t[u];)f++,u++;if(a[i+d]=f,f>=r&&u>=o)return np(c,r,o,l,i,e,t)}}return null}function np(e,t,n,r,o){let s=t,i=n,a=[];for(let c=r;c>0;c--){let l=e[c],d=s-i,f=d===-c||d!==c&&l[o+d-1]<l[o+d+1]?d+1:d-1,u=l[o+f],h=u-f;for(;s>u&&i>h;)a.push(["=",s-1,i-1]),s--,i--;s===u?a.push(["+",-1,i-1]):a.push(["-",s-1,-1]),s=u,i=h}for(;s>0&&i>0;)a.push(["=",s-1,i-1]),s--,i--;return a.reverse()}function op(e,t,{maxD:n=1500}={}){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;let o=0;for(;o<e.length-r&&o<t.length-r&&e[e.length-1-o]===t[t.length-1-o];)o++;let s=e.slice(r,e.length-o),i=t.slice(r,t.length-o),a,c=!1;s.length?i.length?(a=tp(s,i,n),a||(c=!0,a=[...s.map((d,f)=>["-",f,-1]),...i.map((d,f)=>["+",-1,f])])):a=s.map((d,f)=>["-",f,-1]):a=i.map((d,f)=>["+",-1,f]);let l=[];for(let d=0;d<r;d++)l.push(["=",d,d]);for(let[d,f,u]of a)l.push([d,f<0?-1:f+r,u<0?-1:u+r]);for(let d=0;d<o;d++)l.push(["=",e.length-o+d,t.length-o+d]);return{ops:l,coarse:c}}function Jc(e,t,{aBase:n=1,bBase:r=1,context:o=3,maxD:s}={}){let{ops:i,coarse:a}=op(e,t,s?{maxD:s}:{}),c=[];i.forEach((u,h)=>{u[0]!=="="&&c.push(h)});let l={added:i.filter(u=>u[0]==="+").length,removed:i.filter(u=>u[0]==="-").length};if(!c.length)return{rows:[],stats:l,coarse:a};let d=[];for(let u of c){let h=Math.max(0,u-o),p=Math.min(i.length-1,u+o),m=d[d.length-1];m&&h<=m[1]+1?m[1]=Math.max(m[1],p):d.push([h,p])}let f=[];for(let[u,h]of d){let p=null,m=null,y=0,g=0,x=[];for(let k=u;k<=h;k++){let[v,w,b]=i[k];v!=="+"&&(p==null&&(p=w+1),y++),v!=="-"&&(m==null&&(m=b+1),g++),v==="="?x.push({t:" ",o:n+w,n:r+b,text:e[w]}):v==="-"?x.push({t:"-",o:n+w,n:null,text:e[w]}):x.push({t:"+",o:null,n:r+b,text:t[b]})}p==null&&(p=i.slice(0,u).filter(k=>k[0]!=="+").length),m==null&&(m=i.slice(0,u).filter(k=>k[0]!=="-").length);let S=(k,v)=>v===0?`${k},0`:v===1?`${k}`:`${k},${v}`;f.push({t:"@",header:`@@ -${S(p,y)} +${S(m,g)} @@`,oldStart:p,oldLen:y,newStart:m,newLen:g}),f.push(...x)}return{rows:f,stats:l,coarse:a}}function Wr(e,t,n=1){let r=e.map((s,i)=>t==="+"?{t:"+",o:null,n:n+i,text:s}:{t:"-",o:n+i,n:null,text:s}),o=t==="+"?`@@ -0,0 +1${e.length===1?"":","+e.length} @@`:`@@ -1${e.length===1?"":","+e.length} +0,0 @@`;return{rows:e.length?[{t:"@",header:o,oldStart:t==="+"?0:1,oldLen:t==="+"?0:e.length,newStart:t==="+"?1:0,newLen:t==="+"?e.length:0},...r]:[],stats:t==="+"?{added:e.length,removed:0}:{added:0,removed:e.length}}}var ip=5e3,ap=3*1024*1024,cp="line-level changes need git history",lp=/^[0-9a-f]{40}$/,Vc=/^[1-9][0-9]{0,5}$/,dp=2e3;function fp(e=process.env){let t=["PATH","Path","SystemRoot","SYSTEMROOT","windir","TEMP","TMP","TMPDIR","HOME","USERPROFILE","HOMEDRIVE","HOMEPATH","APPDATA","LOCALAPPDATA","COMSPEC","PATHEXT"],n={};for(let r of t)e[r]!==void 0&&(n[r]=e[r]);return{...n,GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0",GIT_ASKPASS:"",LC_ALL:"C"}}function up(e){return typeof e!="string"||!e||e.length>1e3?"not a path":/[\u0000-\u001f\u007f]/.test(e)?"control characters in the path":e.startsWith("-")?"path starts with a dash":rp.isAbsolute(e)||/^[A-Za-z]:/.test(e)||e.startsWith("/")||e.startsWith("\\")||e.split(/[\\/]/).includes("..")?"not a path inside the project":e.split(/[\\/]/).some(t=>yo(t))?"environment, key and certificate files are never served":null}function Yc({repoRoot:e,gitFile:t="git",gitPre:n=[],timeoutMs:r=ip,maxBlob:o=ap,env:s=fp()}){let i=new Map;function a(p){if(i.has(p.file))return i.get(p.file);let m=zr(e,p),y=new Map;for(let g of m?.nodes??[])y.has(g.id)||y.set(g.id,g);return i.set(p.file,y),i.size>4&&i.delete(i.keys().next().value),y}let c=new Map;function l(p,m){let y=p+":"+m;return c.has(y)?Promise.resolve({ok:!0,buf:c.get(y)}):d(p,m).then(g=>(g.ok&&(c.set(y,g.buf),c.size>24&&c.delete(c.keys().next().value)),g))}function d(p,m){return new Promise(y=>{sp(t,[...n,"--no-pager","cat-file","blob",`${p}:${m}`],{cwd:e,env:s,timeout:r,maxBuffer:o,encoding:"buffer",windowsHide:!0},(g,x)=>{if(!g)return y({ok:!0,buf:x});if(g.killed||g.signal==="SIGTERM"||g.code==="ETIMEDOUT")return y({ok:!1,why:"timeout"});if(String(g.code).includes("MAXBUFFER"))return y({ok:!1,why:"too-large"});y({ok:!1,why:"missing"})})})}function f(p,m,y){let g=p.get(y),x=m.get(y);if(g&&x)return{status:g.bodyHash===x.bodyHash?"unchanged":"modified",oldN:g,newN:x};let S=(k,v)=>k.kind===v.kind&&k.name===v.name&&k.bodyHash===v.bodyHash&&k.filePath!==v.filePath;if(x){let k=[...p.values()].filter(v=>!m.has(v.id)&&S(v,x)).sort((v,w)=>v.id<w.id?-1:1)[0];return k?{status:"moved",oldN:k,newN:x}:{status:"added",oldN:null,newN:x}}if(g){let k=[...m.values()].filter(v=>!p.has(v.id)&&S(g,v)).sort((v,w)=>v.id<w.id?-1:1)[0];return k?{status:"moved",oldN:g,newN:k}:{status:"removed",oldN:g,newN:null}}return null}let u=p=>p&&Number.isInteger(p.startLine)&&p.startLine>0&&Number.isInteger(p.endLine)&&p.endLine>=p.startLine?[p.startLine,p.endLine]:null;async function h(p,m,y){try{if(typeof p!="string"||!p||p.length>dp)return{status:400,body:{ok:!1,code:"bad-request",message:"node must be a node id"}};if(!Vc.test(String(m))||!Vc.test(String(y)))return{status:400,body:{ok:!1,code:"bad-request",message:"from and to must be version numbers"}};let g=Ur(e),x=g?.versions?.find(L=>String(L.version)===String(m)),S=g?.versions?.find(L=>String(L.version)===String(y));if(!x||!S)return{status:404,body:{ok:!1,code:"unknown-version",message:"no such stored version"}};let k=a(x),v=a(S),w=f(k,v,p);if(!w)return{status:404,body:{ok:!1,code:"unknown-node",message:"no such node in these versions"}};let{status:b,oldN:N,newN:$}=w;for(let L of[N,$]){let z=L&&up(L.filePath);if(z)return{status:403,body:{ok:!1,code:"refused",message:"refused: "+z}}}let j={nodeId:p,status:b,from:x.version,to:S.version,oldFile:N?.filePath??null,newFile:$?.filePath??null,oldRange:u(N),newRange:u($),name:($??N).name},O=[];N&&x.dirty&&O.push(x.version),$&&S.dirty&&!O.includes(S.version)&&O.push(S.version);let D=O.length?"approximate: taken with uncommitted changes":null,G=(L,z="")=>({status:200,body:{ok:!0,mode:"node-only",reason:L,message:cp+z,approximate:D,...j}});if(b==="unchanged")return{status:200,body:{ok:!0,mode:"lines",rows:[],stats:{added:0,removed:0},formattingOnly:!1,approximate:D,message:"this function did not change between these versions",...j}};let M=[];N&&M.push(["old",x.headSha,N.filePath]),$&&M.push(["new",S.headSha,$.filePath]);for(let[,L]of M)if(typeof L!="string"||!lp.test(L))return G("no-git");let q=await Promise.all(M.map(([,L,z])=>l(L,z))),E={};for(let L=0;L<M.length;L++){let z=q[L];if(!z.ok)return z.why==="too-large"?{status:200,body:{ok:!0,mode:"node-only",reason:"too-large",message:"this file is too large to diff here",approximate:D,...j}}:G(z.why==="timeout"?"timeout":"missing-commit");if(z.buf.subarray(0,8e3).includes(0))return{status:403,body:{ok:!1,code:"binary",message:"refused: binary file"}};E[M[L][0]]=z.buf.toString("utf8")}let C=L=>{let z=L.replace(/\r\n/g,`
|
|
53
54
|
`).split(`
|
|
54
|
-
`);return
|
|
55
|
-
`)===
|
|
56
|
-
`)&&/\r\n/.test(
|
|
57
|
-
`).replace(/\s+/g,""),
|
|
58
|
-
</head>`):o)})}var
|
|
59
|
-
fix: reinstall canopy from a build that includes the viewer`:null};function
|
|
60
|
-
<meta name="canopy-feedback" content="${
|
|
61
|
-
`+n:""));if(
|
|
62
|
-
`)[0]}t.push({name:
|
|
63
|
-
`);for(let
|
|
64
|
-
fix: ${
|
|
65
|
-
${o.length?`${o.length} critical problem(s) - fix them and run canopy doctor again`:"all critical checks passed"}`),o.length}import
|
|
55
|
+
`);return z.length>1&&z[z.length-1]===""&&z.pop(),z},R=(L,z)=>{let Re=C(L);if(!z)return{lines:Re,base:1,clamped:!1};let je=z[1]>Re.length;return{lines:Re.slice(z[0]-1,z[1]),base:z[0],clamped:je}},W=E.old!=null?R(E.old,j.oldRange):{lines:[],base:1,clamped:!1},K=E.new!=null?R(E.new,j.newRange):{lines:[],base:1,clamped:!1},se=E.old!=null&&E.new!=null&&E.old!==E.new&&C(E.old).join(`
|
|
56
|
+
`)===C(E.new).join(`
|
|
57
|
+
`)&&/\r\n/.test(E.old)!==/\r\n/.test(E.new),Xe={...j,approximate:D??(W.clamped||K.clamped?"approximate: the stored line range no longer fits the file":null)};if(W.lines.length>5e3||K.lines.length>5e3)return{status:200,body:{ok:!0,mode:"node-only",reason:"too-large",message:`too large to diff here (more than ${5e3} lines on one side)`,...Xe}};let ue;b==="added"?ue=Wr(K.lines,"+",K.base):b==="removed"?ue=Wr(W.lines,"-",W.base):ue=Jc(W.lines,K.lines,{aBase:W.base,bBase:K.base});let _=L=>L.join(`
|
|
58
|
+
`).replace(/\s+/g,""),P=b!=="added"&&b!=="removed"&&ue.stats.added+ue.stats.removed>0&&_(W.lines)===_(K.lines);return{status:200,body:{ok:!0,mode:"lines",rows:ue.rows,stats:ue.stats,coarse:!!ue.coarse,formattingOnly:P,eolOnly:se,...Xe,message:se?"line endings changed":b==="moved"&&!ue.rows.length?"moved to another file, the code is the same":P?"formatting only":null}}}catch{return{status:500,body:{ok:!1,code:"error",message:"the diff could not be computed"}}}}return{diff:h}}async function Kc(e,t,{token:n,service:r}){let o=Kt(e,n);if(o)return o;let s=[...t.searchParams.keys()],i=["node","from","to"].every(a=>t.searchParams.getAll(a).length===1);return s.length!==3||!i?{status:400,body:{ok:!1,code:"bad-request",message:"send exactly three parameters: node=<node id>&from=<version>&to=<version>"}}:r.diff(t.searchParams.get("node"),t.searchParams.get("from"),t.searchParams.get("to"))}function Xc({now:e=Date.now,holdMs:t=Number(process.env.CANOPY_SEEN_HOLD_MS)||6e4,staleMs:n=null,commit:r}){let o=n??Math.max(t*.75,2e3),s=null,i=null,a=!1;return{ping(){let c=e();s===null&&(s=c),i=c},check(){if(a||s===null)return!1;let c=e();return c-s>=t&&c-i<=o?(a=!0,r(),!0):!1},flush(){return a||s===null?!1:(a=!0,r(),!0)},get acknowledged(){return s!==null},get committed(){return a}}}De();po();un();De();var qr={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".json":"application/json",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".woff2":"font/woff2",".map":"application/json"};function Zc(e,t,n){let r=Ie.join(e,Ie.normalize(t).replace(/^([/\\]|\.\.[/\\])+/,""));if(!r.startsWith(e+Ie.sep)&&r!==e){n.writeHead(403).end("forbidden");return}vt.readFile(r,(o,s)=>{if(o){n.writeHead(404,{"content-type":"text/plain"}).end("not found: "+t);return}n.writeHead(200,{"content-type":qr[Ie.extname(r).toLowerCase()]??"application/octet-stream","cache-control":"no-store"}).end(s)})}var Qc=(()=>{try{return JSON.parse(vt.readFileSync(Ie.join(le,"package.json"),"utf8")).version}catch{return null}})();function hp({env:e=process.env,version:t=Qc,kind:n=Dr()}={}){return e.CANOPY_NO_UPDATE_CHECK==="1"||e.CANOPY_NO_UPDATE_CHECK==="true"||n!=="installed"||!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(String(t))?"":`<meta name="canopy-update-check" content="${Hr}" data-current="${t}">`}function gp(e,t,n){vt.readFile(Ie.join(e,"index.html"),"utf8",(r,o)=>{if(r){t.writeHead(404,{"content-type":"text/plain"}).end("not found: index.html");return}t.writeHead(200,{"content-type":qr[".html"],"cache-control":"no-store"}).end(n?o.replace("</head>",n+`
|
|
59
|
+
</head>`):o)})}var vo=()=>{let e=Ie.join(le,"ui-react");return!vt.existsSync(Ie.join(e,"index.html"))||!vt.existsSync(Ie.join(e,"dist"))?`this install has no built viewer (ui-react/dist is missing)
|
|
60
|
+
fix: reinstall canopy from a build that includes the viewer`:null};function yp(){try{let e=JSON.parse(vt.readFileSync(Ie.join(le,"package.json"),"utf8")).canopyFeedbackUrl;return typeof e=="string"&&/^https:\/\/[^\s"<>]+$/.test(e)?e:null}catch{return null}}function vp(e,t){if(t)return t;try{return JSON.parse(vt.readFileSync(Ie.join(e,"meta.json"),"utf8")).repoRoot??null}catch{return null}}async function xo(e,t=0,{updateTag:n=hp(),repoRoot:r=null,token:o=Bc(),diffOptions:s={}}={}){e=Ie.resolve(e);let i=Ie.join(le,"ui-react"),a=vp(e,r)??"",c=zc({outDir:e,repoRoot:a}),l=Yc({repoRoot:a,...s}),d=(x,S)=>x.writeHead(S.status,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}).end(JSON.stringify(S.body)),f=yp(),u=`<meta name="canopy-session" content="${o}">`+(f?`
|
|
61
|
+
<meta name="canopy-feedback" content="${f}">`:""),h=new Map,p=a?Xc({commit:()=>{try{let x=Ee(a),S=x.versions[x.versions.length-1];S&&gc(a,S,{branch:fe(a,["rev-parse","--abbrev-ref","HEAD"])})}catch{}}}):null,m=0,y=pp.createServer((x,S)=>{if(!Wc(x,m)){S.writeHead(403,{"content-type":"text/plain","cache-control":"no-store"}).end("forbidden");return}let k;try{k=new URL(x.url??"/","http://127.0.0.1")}catch{S.writeHead(400).end("bad request");return}let v;try{v=decodeURIComponent(k.pathname)}catch{S.writeHead(400).end("bad request");return}if(v==="/api/source"){let w=qc(x,k,{port:m,token:o,service:c});d(S,w);return}if(v==="/api/health"){let w=null;try{w=a?gt(a)?.projectId??null:null}catch{}d(S,{status:200,body:{ok:!0,app:"canopy",version:Qc,pid:process.pid,projectId:w}});return}if(v==="/api/seen"){let w=Kt(x,o,"POST");if(w){d(S,w);return}p?.ping(),d(S,{status:200,body:{ok:!0}});return}if(v==="/output/history.js"&&a&&vt.existsSync(Ie.join(a,".canopy","history","index.json"))){let w=null;try{w=Rr(a,{sinceCache:h})}catch{w=null}if(w){S.writeHead(200,{"content-type":qr[".js"],"cache-control":"no-store"}).end(w);return}}if(v==="/api/nodes"){d(S,Gc(x,k,{token:o,service:c}));return}if(v==="/api/diff"){Kc(x,k,{token:o,service:l}).then(w=>d(S,w),()=>d(S,{status:500,body:{ok:!1,code:"error",message:"the diff could not be computed"}}));return}if(v==="/"||v==="/index.html"){S.writeHead(302,{location:"/ui-react/index.html"}).end();return}if(v==="/ui-react/index.html")return gp(i,S,u+(n?`
|
|
62
|
+
`+n:""));if(v.startsWith("/ui-react/"))return Zc(i,v.slice(10),S);if(v.startsWith("/output/"))return Zc(e,v.slice(8),S);S.writeHead(404).end("not found")});await new Promise((x,S)=>{y.once("error",S),y.listen(t,"127.0.0.1",x)}),m=y.address().port;let g=null;if(p){g=setInterval(()=>{try{p.check()}catch{}},2e3),g.unref?.();let x=y.close.bind(y);y.close=S=>{clearInterval(g);try{p.flush()}catch{}return x(S)},process.once("exit",S=>{if(S===0||S===130||S===143)try{p.flush()}catch{}})}return{server:y,port:m,url:`http://127.0.0.1:${m}/`,token:o,seen:p}}function Jr(e){if(process.env.CANOPY_NO_BROWSER)return!1;try{let t,n;if(process.platform==="win32")t="cmd.exe",n=["/c","start","",e];else if(process.platform==="darwin")t="open",n=[e];else if(process.env.DISPLAY||process.env.WAYLAND_DISPLAY)t="xdg-open",n=[e];else return!1;let r=mp(t,n,{detached:!0,stdio:"ignore",windowsHide:!0});return r.on("error",()=>{}),r.unref(),!0}catch{return!1}}We();De();import Ke from"node:fs";import st from"node:path";import{execFileSync as el}from"node:child_process";function wo(e){let t=[],n=(r,o,s,i)=>{let a=!1,c="";try{let l=s();a=l===!0||!!(l&&l.ok),c=l&&l.detail?l.detail:""}catch(l){c=String(l.message??l).split(`
|
|
63
|
+
`)[0]}t.push({name:r,critical:o,ok:a,detail:c,fix:i})};return n("Node version >= 18",!0,()=>({ok:Number(process.versions.node.split(".")[0])>=18,detail:"v"+process.versions.node}),"install Node 18 or newer from https://nodejs.org and run canopy again"),n("tree-sitter grammars (wasm)",!0,()=>{let r=[["web-tree-sitter","web-tree-sitter.wasm"],["tree-sitter-javascript","tree-sitter-javascript.wasm"],["tree-sitter-typescript","tree-sitter-typescript.wasm"],["tree-sitter-typescript","tree-sitter-tsx.wasm"],["tree-sitter-html","tree-sitter-html.wasm"]],o=r.filter(([s,i])=>!Ke.existsSync(st.join(He(s),i))).map(([,s])=>s);return{ok:o.length===0,detail:o.length?"missing "+o.join(", "):r.length+" files"}},"reinstall canopy: npm install -g canopy-engine (or, in a checkout, npm install in the canopy-engine folder)"),n("query files (.scm)",!0,()=>{let r=[st.join(le,"src","stage2_parse","queries"),st.join(le,"dist","queries")].find(s=>Ke.existsSync(s))??st.join(le,"dist","queries"),o=Ke.readdirSync(r).filter(s=>s.endsWith(".scm")).length;return{ok:o>=10,detail:o+" files"}},"reinstall canopy: the package is missing its query files (dist/queries)"),n("write access to <path>/.canopy",!0,()=>{let r=te(e).root;Ke.mkdirSync(r,{recursive:!0});let o=st.join(r,`.doctor-${process.pid}`);return Ke.writeFileSync(o,"x"),Ke.rmSync(o),{ok:!0,detail:r}},`make ${e} writable for your user, or run canopy on a folder you own`),n("git available",!1,()=>({ok:!!el("git",["--version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}),detail:el("git",["--version"],{encoding:"utf8"}).trim()}),"install git (https://git-scm.com); without it version history and the hook are limited"),n("map viewer present",!1,()=>({ok:Ke.existsSync(st.join(le,"ui-react","index.html"))&&Ke.existsSync(st.join(le,"ui-react","dist"))}),"canopy open needs the built viewer (ui-react/dist); reinstall from a build that includes it"),n("post-commit hook installed",!1,()=>{if(!fe(e,["rev-parse","--git-dir"]))return{ok:!1,detail:"not a git repository"};let r=hn(e),o=Pt.every(s=>Ke.existsSync(st.join(r,s))&&Ke.readFileSync(st.join(r,s),"utf8").includes(mn));return{ok:o,detail:o?"post-commit, post-merge":""}},`canopy hook install "${e}"`),t}function tl(e,t,n,r=console.log){r(`canopy ${n} doctor (${t})
|
|
64
|
+
`);for(let s of e)r(`${s.ok?"OK ":"FAIL"} ${s.name}${s.detail?" - "+s.detail:""}${s.ok?"":`
|
|
65
|
+
fix: ${s.fix}`}${!s.ok&&!s.critical?" (not critical)":""}`);let o=e.filter(s=>s.critical&&!s.ok);return r(`
|
|
66
|
+
${o.length?`${o.length} critical problem(s) - fix them and run canopy doctor again`:"all critical checks passed"}`),o.length}import xe from"node:fs";import $p from"node:net";import Ip from"node:os";import it from"node:path";import jp from"node:readline";De();function Yr({stream:e=process.stdout,env:t=process.env,flags:n={},platform:r=process.platform}={}){let o=!!e.isTTY,s="NO_COLOR"in t&&t.NO_COLOR!==""||!!n["no-color"]||n.color===!1||t.TERM==="dumb",i=o&&!s&&!n.quiet,a=i&&t.TERM!=="linux"&&(r!=="win32"||!!(t.WT_SESSION||t.TERM_PROGRAM||t.ConEmuANSI==="ON"||t.ANSICON)||/UTF-?8/i.test(`${t.LC_ALL??""}${t.LC_CTYPE??""}${t.LANG??""}`));return{tty:o,color:i,rich:i,unicode:a,columns:Math.max(40,Math.min(e.columns||80,200)),quiet:!!n.quiet}}var Vr={unicode:{ok:"\u2714",fail:"\u2716",spin:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],full:"\u2588",empty:"\u2591",arrow:"\u2192",dot:"\xB7"},ascii:{ok:"[ok]",fail:"[x]",spin:["|","/","-","\\"],full:"#",empty:"-",arrow:"->",dot:"-"}},xp=(e,t,n)=>e?`\x1B[${t}m${n}\x1B[0m`:n,nl=e=>e<59500?`${(e/1e3).toFixed(1)} s`:`${Math.floor(e/6e4)} min ${String(Math.round(e%6e4/1e3)).padStart(2,"0")} s`,wp=e=>!Number.isFinite(e)||e<0?"":e<1?"< 1 s":e<60?`${Math.round(e)} s`:`${Math.floor(e/60)} min ${Math.round(e%60)} s`;function Sp({done:e,total:t,unit:n="files",elapsedMs:r,width:o=24,sym:s=Vr.ascii}){let i=t>0?Math.min(1,e/t):0,a=Math.round(i*o),c=r>500?e/(r/1e3):0,l=c>0?(t-e)/c:NaN,d=s.full.repeat(a)+s.empty.repeat(o-a),f=String(Math.floor(i*100)).padStart(3)+"%";return`[${d}] ${f} ${e.toLocaleString("en-US")}/${t.toLocaleString("en-US")} ${n}${c?` ${Math.round(c).toLocaleString("en-US")} ${n}/s`:""}${l===l&&i<1?` ETA ${wp(l)}`:""}`}function ol({stream:e=process.stdout,caps:t=Yr({stream:e}),now:n=()=>Date.now(),interval:r=80,onExitHook:o=!0}={}){let s=t.unicode?Vr.unicode:Vr.ascii,i=(C,R)=>xp(t.color,C,R),a=C=>i("2",C),c=C=>i("32",C),l=C=>i("31",C),d=C=>i("1",C),f=C=>i("36",C),u=null,h=null,p=0,m=null,y=!1,g=!1,x=-1,S="",k=C=>{try{e.write(C)}catch{}},v=()=>{t.rich&&!g&&(k("\x1B[?25l"),g=!0)},w=()=>{g&&(k("\x1B[?25h"),g=!1)},b=()=>{y&&(k("\r\x1B[2K"),y=!1)},N=C=>C.replace(/\u001b\[[0-9;?]*[A-Za-z]/g,"").length;function $(C){let R=u.title,W=C(R),K=t.columns-1;N(W)>K&&(R=R.replace(/\s*\(.*\)\s*$/,""),W=C(R));let se=N(W)-K;if(se>0){let Xe=t.unicode?"\u2026":"...";R=R.slice(0,Math.max(6,R.length-se-Xe.length))+Xe,W=C(R)}return W}function j(){let C=i("36",s.spin[p%s.spin.length]);return $(h?R=>`${C} ${R} ${Sp({done:h.done,total:h.total,unit:h.unit,elapsedMs:n()-h.started,width:Math.max(8,Math.min(24,t.columns-66)),sym:s})}`:R=>`${C} ${R}${S?a(" "+S):""} ${a(nl(n()-u.started))}`)}function O(){!t.rich||!u||(v(),k(`\r\x1B[2K${j()}`),y=!0)}let D=()=>{p++,O()},G=()=>{t.rich&&r>0&&!m&&(m=setInterval(D,r),m.unref?.())},M=()=>{m&&(clearInterval(m),m=null)};function q(C=!0){if(!u)return;M();let R=nl(n()-u.started);t.rich&&(b(),k(`${C?c(s.ok):l(s.fail)} ${u.title} ${a(R)}
|
|
67
|
+
`)),u=null,h=null,S="",x=-1,w()}let E={caps:t,line(C=""){t.quiet||(t.rich&&y?(b(),k(C+`
|
|
68
|
+
`),O()):k(C+`
|
|
69
|
+
`))},say(C){if(t.quiet)return;if(!t.rich){k(String(C)+`
|
|
70
|
+
`);return}let R=/^\[(\d+)\/(\d+)\] (.*?)\.\.\.$/.exec(C);if(R){q(!0),u={n:+R[1],total:+R[2],title:R[3],started:n()},p=0,O(),G();return}if(/^\s{6}\S/.test(C)){E.line(" "+a(String(C).trim()));return}E.line(String(C))},important(C){t.rich&&y?(b(),k(C+`
|
|
71
|
+
`),O()):k(String(C)+`
|
|
72
|
+
`)},banner(C,R,W){if(!t.quiet){if(!t.rich){k(`${C} ${R} - ${W}
|
|
73
|
+
`);return}k(`
|
|
74
|
+
${d(f(C))} ${a("v"+R)} ${a(s.dot)} ${W}
|
|
75
|
+
|
|
76
|
+
`)}},progress(C,R,W="files",K="reading files"){if(t.quiet)return;if(t.rich){h=h??{started:n()},Object.assign(h,{done:C,total:R,unit:W}),m||O();return}let se=R>0?Math.floor(C/R*10):0;se!==x&&(x=se,k(` ${K}: ${C} of ${R}
|
|
77
|
+
`))},endProgress(){h=null,x=-1},status(C){t.quiet||(t.rich?(h=null,S=C,O()):k(` ${C}
|
|
78
|
+
`))},endStep:q,tick:D,final({url:C,changes:R=null,update:W=null,hint:K="press Ctrl+C to stop"}){if(q(!0),t.quiet){k(C+`
|
|
79
|
+
`);return}t.rich&&(k(`
|
|
80
|
+
${c(s.ok)} ${d("Canopy is ready")}
|
|
81
|
+
|
|
82
|
+
${a("Local:")} ${f(C)}
|
|
83
|
+
`),R&&k(` ${a("Since last visit:")} ${R}
|
|
84
|
+
`),W&&k(` ${a("Update:")} ${W}
|
|
85
|
+
`),k(`
|
|
86
|
+
${a(K)}
|
|
87
|
+
`))},restore(){M(),y&&b(),w()}};if(o&&t.rich){let C=()=>E.restore();process.once("exit",C);for(let R of["SIGINT","SIGTERM"])process.once(R,()=>{C(),process.exit(R==="SIGINT"?130:143)})}return E}De();un();import Xt from"node:fs";import kp from"node:http";import Kr from"node:path";var Lt=e=>Kr.join(te(e).root,"server.json"),rl=e=>Kr.join(te(e).root,"server.lock");function Np(e,{timeoutMs:t=1500}={}){return new Promise(n=>{let r=kp.get({host:"127.0.0.1",port:e,path:"/api/health",headers:{host:`127.0.0.1:${e}`},timeout:t},o=>{let s="";o.on("data",i=>{s+=i}),o.on("end",()=>{try{let i=JSON.parse(s);n(o.statusCode===200&&i.ok&&i.app==="canopy"?i:null)}catch{n(null)}})});r.on("timeout",()=>{r.destroy(),n(null)}),r.on("error",()=>n(null))})}var bp=e=>{try{return gt(e)?.projectId??null}catch{return null}};async function _p(e){let t=null;try{t=JSON.parse(Xt.readFileSync(Lt(e),"utf8"))}catch{return null}let r=t&&Number.isInteger(t.pid)&&t.pid!==process.pid&&kr(t.pid)&&Number.isInteger(t.port)?await Np(t.port):null;if(!(r&&(!t.projectId||!r.projectId||t.projectId===r.projectId))){try{Xt.rmSync(Lt(e),{force:!0})}catch{}return null}return{...t,url:`http://127.0.0.1:${t.port}/`}}async function So(e,t,{waitMs:n=6e3}={}){let r=Date.now()+n;for(;;){let o=await _p(e);if(o)return{ok:!1,running:o};if(br(rl(e),{},t).ok)return{ok:!0};if(Date.now()>r)return{ok:!1,running:null,busy:!0};await new Promise(i=>setTimeout(i,150))}}function ko(e,{port:t,version:n}){let r={pid:process.pid,port:t,startedAt:new Date().toISOString(),version:n,projectId:bp(e)},o=Lt(e)+"."+process.pid+".tmp";Xt.mkdirSync(Kr.dirname(Lt(e)),{recursive:!0}),Xt.writeFileSync(o,JSON.stringify(r,null,2)),Xt.renameSync(o,Lt(e));let s=()=>{try{Nr(Lt(e))?.pid===process.pid&&Xt.rmSync(Lt(e),{force:!0})}catch{}_r(rl(e))};return process.once("exit",s),{unregister:s}}po();var sl=Number(process.env.CANOPY_MIN_FREE_MB)||300,Cp=".js .jsx .mjs .cjs .ts .tsx .mts .cts",No=class extends Error{constructor(t,n){super(n),this.code=t,this.line=n}},Te=(e,t)=>{throw new No(e,t)};function Fp(e){let t=!!fe(e,["rev-parse","--git-dir"]),n=it.join(e,".gitignore"),r=xe.existsSync(n);if(!t&&!r)return"skipped";let o=r?xe.readFileSync(n,"utf8"):"";if(o.split(/\r?\n/).some(i=>/^\/?\.canopy\/?$/.test(i.trim())))return"already";let s=/\r\n/.test(o)?`\r
|
|
66
88
|
`:`
|
|
67
|
-
`;return
|
|
89
|
+
`;return xe.appendFileSync(n,(o&&!/\r?\n$/.test(o)?s:"")+"# Canopy (code map output)"+s+".canopy/"+s),r?"added":"created"}var il=e=>it.join(te(e).root,"prefs.json"),al=e=>{try{return JSON.parse(xe.readFileSync(il(e),"utf8"))}catch{return{}}};function bo(e,t){let n={...al(e),...t};for(let r of Object.keys(n))n[r]===void 0&&delete n[r];xe.mkdirSync(te(e).root,{recursive:!0}),xe.writeFileSync(il(e),JSON.stringify(n,null,2))}function Ep(e){return new Promise(t=>{let n=$p.createServer();n.once("error",r=>t({ok:!1,code:r.code,message:r.message})),n.listen(e,"127.0.0.1",()=>{let r=n.address().port;n.close(()=>t({ok:!0,port:r}))})})}function Pp(e){try{let t=xe.statfsSync(e);return Math.floor(t.bavail*t.bsize/1048576)}catch{return null}}var Lp=()=>!!(process.stdin.isTTY&&process.stdout.isTTY)||!!process.env.CANOPY_ASSUME_TTY;function Tp(e,t){return new Promise(n=>{let r=jp.createInterface({input:process.stdin,output:process.stdout,terminal:!1}),o=!1,s=i=>{o||(o=!0,r.close(),n(i))};r.question(e,i=>s(i.trim())),r.once("close",()=>s(""))}).then(n=>n===""?t:n)}function Rp(e){try{return JSON.parse(xe.readFileSync(it.join(e,"meta.json"),"utf8"))}catch{return null}}function Ap(e){try{return JSON.parse(xe.readFileSync(it.join(e,"services.js"),"utf8").replace(/^\s*const services\s*=\s*/,"").replace(/;\s*$/,""))}catch{return[]}}var Op=e=>`How did it go? ${e.canopyFeedbackUrl||"see FEEDBACK.md in the README (about 20 minutes)"}`;async function cl(e){let t=e.say?null:ol({caps:Yr({flags:{quiet:e.quiet,"no-color":e.noColor}})}),n=e.say??(f=>t.say(f)),r=f=>t?t.important(f):n(f),{pkg:o}=e,s=null;try{return await i()}catch(f){if(t?.endStep(!1),t?.restore(),f instanceof No){if(r(f.line),s)try{xe.rmdirSync(s)}catch{}return f.code}return r(`Canopy stopped because of an unexpected problem: ${String(f.message??f).split(`
|
|
68
90
|
`)[0]}
|
|
69
|
-
Run "canopy doctor", then send its output and .canopy/sync.log to whoever gave you Canopy.`),process.env.CANOPY_DEBUG&&
|
|
70
|
-
`),
|
|
71
|
-
|
|
72
|
-
`)
|
|
73
|
-
`)[0]+"
|
|
91
|
+
Run "canopy doctor", then send its output and .canopy/sync.log to whoever gave you Canopy.`),process.env.CANOPY_DEBUG&&n(f.stack),1}async function i(){let f=it.resolve(e.target??process.cwd());t?t.banner("Canopy",o.version,"a map of what your JavaScript / TypeScript code does"):n(`Canopy ${o.version} - a map of what your JavaScript / TypeScript code does`),n(`Folder: ${it.basename(f)||f}
|
|
92
|
+
`),n("[1/6] Checking this computer..."),Number(process.versions.node.split(".")[0])<18&&Te(1,`Canopy needs Node 18 or newer and this is Node ${process.versions.node}. Install the current LTS from https://nodejs.org and run canopy again.`);let u=xe.existsSync(f)&&xe.statSync(f).isDirectory();xe.existsSync(f)||Te(1,`That folder does not exist: ${f}. Check the spelling, or run canopy inside your project folder.`),u||Te(1,`${f} is a file, not a folder. Run canopy on the folder that contains it: canopy "${it.dirname(f)}"`);let h=xe.existsSync(te(f).root),p=wo(f);h||(s=te(f).root);let m=p.find(E=>E.critical&&!E.ok);m&&Te(1,`${m.name} failed${m.detail?" ("+m.detail+")":""}. ${m.fix}.`.replace(/\.\.$/,"."));let y=!!fe(f,["rev-parse","--git-dir"]),g=p.find(E=>E.name==="git available")?.ok,x=vo();x&&!e.noOpen&&Te(1,`Canopy cannot show the map: ${x.replace(/\n\s*/g,". ")}.`);let S=Pp(f);if(S!==null&&S<sl&&Te(1,`Only ${S} MB free on the disk holding ${f}; Canopy needs about ${sl} MB. Free some space and run canopy again.`),!e.noOpen){let E=await Ep(e.port??0);E.ok||Te(1,E.code==="EADDRINUSE"?`Port ${e.port} is already in use. Pick another with --port=NUMBER, or leave --port out and Canopy picks a free one.`:`Canopy cannot open a local port on 127.0.0.1 (${E.code||E.message}). Check your firewall or security software and run canopy again.`)}n(` Node ${process.versions.node}, ${g?"git found":"git not found (no version history or commit hook)"}, ${S===null?"disk space not checked":S+" MB free"}${e.noOpen?"":", a local port is free"}.`),n("[2/6] Looking at your project..."),xe.readdirSync(f).filter(E=>E!==".git"&&E!==".canopy").length===0&&Te(1,`${f} is empty. Add some JavaScript or TypeScript code and run canopy again.`);let v=$n(f);v.length===0&&Te(3,`No JavaScript or TypeScript files found in ${f}. Canopy currently supports JavaScript and TypeScript (${Cp}); other languages are not read yet.
|
|
93
|
+
What to try next: run canopy inside the folder that holds your .js / .ts code (for a monorepo, the folder of one package), or pass it: canopy <folder>.`);let w=y&&fe(f,["rev-parse","--verify","-q","HEAD"])!==null;n(` ${v.length.toLocaleString("en-US")} JavaScript / TypeScript file${v.length===1?"":"s"}. ${y?w?"Git repository.":"Git repository with no commits yet (that is fine).":"Not a git repository (that is fine; version-aware features are limited)."}`),n("[3/6] Preparing the output folder..."),xe.mkdirSync(te(f).root,{recursive:!0}),ro(f);let b=Fp(f),N={added:"added .canopy/ to .gitignore",created:"created .gitignore with .canopy/ in it",already:".canopy/ is already in .gitignore",skipped:"no git repository, so no .gitignore change"}[b];n(` Map output goes to ${it.join(f,".canopy")} (${N}).`),n("[4/6] Commit hook..."),await a(f,y);let $=Ee(f).versions.length>0;n(`[5/6] ${$?"Checking what changed since last time":"Building your map for the first time (a big project can take a few minutes)"}...`);let j=await c(f,v.length);l(f,j);let O=null;try{O=Lr(uo(f))}catch{O=null}O&&!(t&&t.caps.rich)&&n(` ${O}.
|
|
94
|
+
`);let D=Et(f);if(e.noOpen)return n("[6/6] Not opening the map (--no-open). To view it later: canopy open"),d(),0;n("[6/6] Opening the map...");let G=await So(f,o.version);if(!G.ok&&G.running){let E=G.running.url,C=Jr(E);return t&&t.caps.quiet?(t.final({url:E}),0):(n(` Canopy is already running for this project (started ${G.running.startedAt?.replace("T"," ").slice(0,16)??"earlier"}): ${E}`),n(C?" Opened it in your browser. Nothing else was started.":" Open that address in your browser. Nothing else was started."),(!t||!t.caps.rich)&&d(),0)}G.ok||Te(1,"Another Canopy is just starting for this project. Wait a few seconds and run canopy again, or open the address it printed.");let M;try{M=await xo(D,e.port??0,{repoRoot:f}),ko(f,{port:M.port,version:o.version})}catch(E){Te(1,`Canopy cannot start the viewer: ${E.code||E.message}. ${E.code==="EADDRINUSE"?"Pick another port with --port=NUMBER.":"Check your firewall or security software."}`)}let q=Jr(M.url);return t&&t.caps.rich?t.final({url:M.url,changes:O,hint:q?"your browser should open now; press Ctrl+C to stop":"open that address in your browser; press Ctrl+C to stop"}):t&&t.caps.quiet?t.final({url:M.url}):(n(` ${M.url}`),n(q?" Your browser should open now. If it does not, paste that address into one.":" Open that address in your browser."),d()),e.forSeconds?(await new Promise(E=>setTimeout(E,e.forSeconds*1e3)),M.server.close(),t?.restore(),0):((!t||!t.caps.rich)&&n("Press Ctrl+C to stop."),await new Promise(()=>{}),0)}async function a(f,u){if(e.noHook){n(" Commit hook skipped (--no-hook).");return}if(!u){n(" No git repository here, so there is no commit hook to set up.");return}if(!Mp()){n(" git is not installed, so the commit hook is skipped.");return}let h;try{h=Lc(f)}catch(m){n(" Could not look at the git hooks ("+String(m.message).split(`
|
|
95
|
+
`)[0]+"); skipping the commit hook.");return}if(h==="current"){n(" The map already updates on every commit.");return}if(h==="outdated"){try{gn(f),n(" Refreshed the commit hook (it now matches this Canopy).")}catch(m){n(" Could not refresh the commit hook: "+String(m.message).split(`
|
|
96
|
+
`)[0])}return}if(al(f).hook==="declined"&&!e.yes){n(" The commit hook is off (you chose that earlier). Turn it on with: canopy hook install");return}let p=!0;if(e.yes)n(" Update the map on every commit? [Y/n] Y (--yes)");else if(!Lp())n(" Update the map on every commit? [Y/n] Y (default; no terminal to ask)");else{let m=await Tp(" Update the map on every commit? [Y/n] ","Y");p=/^y(es)?$/i.test(m)}if(!p){bo(f,{hook:"declined"}),n(" Okay, no hook. Turn it on any time with: canopy hook install");return}try{gn(f),bo(f,{hook:void 0}),n(" Done: after every commit and merge the map updates itself in the background (it never blocks or fails a commit). Remove it with: canopy hook uninstall")}catch(m){n(" Could not install the commit hook: "+String(m.message).split(`
|
|
97
|
+
`)[0]+". Continuing without it.")}}async function c(f,u){let h=Date.now(),p=g=>{let x=String(g),S=/parsing: (\d+)\/(\d+) files/.exec(x);if(S){let k=Number(S[1]);t?t.progress(k,Number(S[2])):n(` reading files: ${S[1]} of ${S[2]}`);return}/^(linking calls|linking services|writing the map|storing the version)/.test(x)&&(t?(t.endProgress(),t.status(x)):n(` ${x}`))};n(` Reading ${u.toLocaleString("en-US")} file${u===1?"":"s"}, linking calls, finding entry points, tracing workflows...`);let m;for(let g=0;g<2&&(m=await mo(f,{say:x=>p(x),onProgress:p,full:!!e.full}).catch(x=>Te(1,`The analysis failed: ${String(x.message??x).split(`
|
|
74
98
|
`)[0]}
|
|
75
|
-
Run "canopy doctor" and send its output with ${
|
|
76
|
-
Your map`),
|
|
99
|
+
Run "canopy doctor" and send its output with ${it.join(f,".canopy","sync.log")} to whoever gave you Canopy.`)),m.status==="queued");g++){n(" Another update is already running; waiting for it to finish...");for(let x=0;x<1200&&xe.existsSync(te(f).lock);x++)await new Promise(S=>setTimeout(S,500))}m.status==="queued"&&Te(1,"Another Canopy update is still running. Wait for it to finish and run canopy again."),t?.endProgress();let y=((Date.now()-h)/1e3).toFixed(1);return n(m.status==="no-changes"?` Nothing changed since version ${m.version.version} (${y} s).`:` Saved version ${m.version.version} (${y} s).`),m}function l(f,u){let h=Et(f),p=u.coverage??Rp(h)?.coverage,m=Ap(h),y=u.version.counts??{};if(n(`
|
|
100
|
+
Your map`),n(` services: ${m.length}${m.length?" ("+m.map(g=>g.id??g.name).slice(0,8).join(", ")+(m.length>8?", ...":"")+")":""}`),n(` workflows: ${y.workflows??"?"}${y.physicalWorkflows!==void 0?` (${y.physicalWorkflows} traced from real code, ${y.workflows-y.physicalWorkflows} guessed)`:""}`),p){let g=p.analyzed?Math.round(p.inService/p.analyzed*100):0;n(` files inside a service: ${p.inService} of ${p.analyzed} (${g}%)`),n(` files with parse errors: ${p.parseErrors}${p.parseErrors?" ("+p.parseErrorFiles.slice(0,3).join(", ")+(p.parseErrorFiles.length>3?", ...":"")+")":""}`),p.notAnalyzedTotal&&n(` not read yet: ${p.notAnalyzedTotal} files in languages Canopy does not support (${Object.entries(p.notAnalyzed).map(([x,S])=>`${S} ${x}`).join(", ")})`)}m.length||n(" The map is empty: Canopy found no entry points (routes, listeners, a main file) it recognises in this project."),n("")}function d(){n("Next time just run `canopy`."),n(Op(o))}}function Mp(){return!!fe(Ip.tmpdir(),["--version"])}import _o from"node:fs";import ll from"node:os";import xt from"node:path";import{spawn as Hp}from"node:child_process";var Xr="CANOPY_CHILD",Dp=2048,Bp=8192,dl=1024*1024;function Up({env:e=process.env,nodeOptions:t=e.NODE_OPTIONS??"",totalmem:n=ll.totalmem()}={}){let r=Number(e.CANOPY_MAX_MEMORY_MB);if(Number.isFinite(r)&&r>=256)return{mb:Math.floor(r),source:"CANOPY_MAX_MEMORY_MB"};let o=/--max-old-space-size[= ](\d+)/.exec(t);return o?{mb:null,userMb:Number(o[1]),source:"NODE_OPTIONS"}:{mb:Math.max(Dp,Math.min(Bp,Math.floor(n*.75/dl))),source:"75% of this computer's memory"}}var zp=new Set(["version","help","update","hook","install-hook","uninstall-hook","doctor","history","diff","open"]);function Zr(e){if(e.some(r=>r==="--version"||r==="--help"||r==="-v"||r==="-h"))return!1;let n=e.filter(r=>!r.startsWith("-"))[0];return n===void 0?!0:zp.has(n)?!1:n==="sync"?!e.includes("--background"):_o.existsSync(xt.resolve(n))||/^[.~]|[\\/]/.test(n)}function $o(e,t=process.cwd()){let n=e.filter(r=>!r.startsWith("-"));return n[0]==="sync"?xt.resolve(n[1]??t):xt.resolve(n[0]??t)}var Wp=/heap out of memory|Allocation failed|JavaScript heap|FatalProcessOutOfMemory|out of memory/i;function Gp({code:e,signal:t,stderrTail:n="",platform:r=process.platform}){if(Wp.test(n))return{kind:"memory",why:"Node reported that it ran out of memory"};if(t==="SIGINT"||t==="SIGTERM"||t==="SIGHUP")return null;if(t==="SIGABRT")return{kind:"memory",why:"the process aborted (usually out of memory)"};if(t==="SIGKILL")return{kind:"killed",why:"the system stopped the process (usually because the computer ran out of memory)"};if(t==="SIGSEGV"||t==="SIGBUS")return{kind:"crash",why:"the process crashed"};if(e==null)return t?{kind:"crash",why:`the process ended on signal ${t}`}:{kind:"crash",why:"the process ended without an exit code"};let o=e>>>0;if(r==="win32"){if(o>=3221225472)return{kind:o===3221226505?"memory":"crash",why:`Windows reported error 0x${o.toString(16).toUpperCase()} (a fatal stop, usually out of memory)`};if(o>255)return{kind:"crash",why:`the process ended with the unusual code ${o}`}}return e===134?{kind:"memory",why:"the process aborted (exit code 134, usually out of memory)"}:e===137?{kind:"killed",why:"the system stopped the process (exit code 137, usually out of memory)"}:e===139||e===135?{kind:"crash",why:`the process crashed (exit code ${e})`}:null}function qp(e,{projectRoot:t,stage:n,memory:r}){let o=[],s=e.kind==="memory"?"Canopy ran out of memory":e.kind==="killed"?"Canopy was stopped by the system, most likely because the computer ran out of memory":"Canopy stopped unexpectedly";return o.push(`${s}${n?` while it was working on: ${n}`:""}.`),o.push(` (${e.why}.)`),o.push(""),o.push("What to try next:"),o.push(" 1. Analyse one part of the project at a time: canopy <folder of a package or app>"),o.push(` 2. Give Canopy more memory: set CANOPY_MAX_MEMORY_MB (it used ${r?.mb??r?.userMb??"the default"} MB), for example CANOPY_MAX_MEMORY_MB=${Math.min(16384,Math.max(4096,(r?.mb??4096)*2))} canopy`),o.push(" 3. Close other programs, then run it again: the files already read are remembered, so the second run is faster."),t&&o.push("",`Details for a bug report (no code or secrets): ${xt.join(".canopy","last-error.txt")} in the project folder.`),o.join(`
|
|
101
|
+
`)}function Qr(e,{version:t,stage:n,code:r,signal:o,memory:s,totalmem:i=ll.totalmem()}){try{let a=xt.join(e,".canopy");_o.mkdirSync(a,{recursive:!0});let c=[`time: ${new Date().toISOString()}`,`engine version: ${t}`,`stage: ${n??"unknown"}`,`exit: ${o?"signal "+o:r}`,`memory ceiling: ${s?.mb??"left to NODE_OPTIONS"+(s?.userMb?" ("+s.userMb+" MB)":"")} MB (${s?.source??"?"}); computer memory ${Math.round(i/dl)} MB`,""].join(`
|
|
102
|
+
`);return _o.writeFileSync(xt.join(a,"last-error.txt"),c),xt.join(a,"last-error.txt")}catch{return null}}function fl(e){let{args:t,scriptPath:n,version:r="?",env:o=process.env,projectRoot:s=$o(t),execPath:i=process.execPath,execArgv:a=process.execArgv,spawnFn:c=Hp,platform:l=process.platform,err:d=process.stderr,onChild:f=null}=e,u=e.memory??Up({env:o}),h=[...u.mb?[`--max-old-space-size=${u.mb}`]:[],...a.filter(p=>!p.startsWith("--max-old-space-size")),n,...t];return new Promise(p=>{let m="",y=c(i,h,{env:{...o,[Xr]:"1"},stdio:["inherit","inherit","pipe"],windowsHide:!1});f?.(y),y.stderr?.on("data",w=>{try{d.write(w)}catch{}m=(m+w.toString("utf8")).slice(-4e3)});let g=w=>()=>{try{y.kill(w)}catch{}},x=g("SIGTERM");process.on("SIGTERM",x);let S=process.stdin.isTTY?()=>{}:g("SIGINT");process.on("SIGINT",S);let k=!1,v=(w,b)=>{if(k)return;k=!0,process.off("SIGTERM",x),process.off("SIGINT",S);let N=Gp({code:w,signal:b,stderrTail:m,platform:l});if(!N){p(w??(b?1:0));return}let $=qa(s);Qr(s,{version:r,stage:$,code:w,signal:b,memory:u});try{_o.rmSync(xt.join(s,".canopy","last-stage.txt"),{force:!0})}catch{}try{d.write(`
|
|
103
|
+
`+qp(N,{projectRoot:s,stage:$,memory:u})+`
|
|
104
|
+
`)}catch{}p(1)};y.on("error",w=>{try{d.write(`Canopy could not start its worker process: ${String(w.message).split(`
|
|
105
|
+
`)[0]}
|
|
106
|
+
`)}catch{}v(1,null)}),y.on("close",(w,b)=>v(w,b))})}var at=JSON.parse(es.readFileSync(vn.join(le,"package.json"),"utf8")),Jp={"-y":"--yes","-h":"--help","-v":"--version"},ul=process.argv.slice(2).map(e=>Jp[e]??e),ae=Object.fromEntries(ul.filter(e=>e.startsWith("--")).map(e=>{let[t,n]=e.slice(2).split("=");return[t,n??!0]})),Oe=ul.filter(e=>!e.startsWith("--")),Ue=Oe.shift(),Vp=e=>/^v?\d+$/.test(e??""),Tt=()=>vn.resolve(Oe[0]&&!Vp(Oe[0])?Oe.shift():process.cwd()),pl=`canopy ${at.version} - a map of what your JavaScript / TypeScript code does
|
|
77
107
|
|
|
78
108
|
usage: canopy [path] [-y] [--no-open] do everything in order: check this computer, look at the project, prepare .canopy/,
|
|
79
109
|
offer the commit hook, build the map, open it in your browser (default path: current folder)
|
|
@@ -88,11 +118,24 @@ usage: canopy [path] [-y] [--no-open] do everything in order: check this com
|
|
|
88
118
|
update [--check] look up the newest version on npm (the only command that uses the network); "update" installs it with npm
|
|
89
119
|
--version, --help
|
|
90
120
|
|
|
91
|
-
options for the one-command path: -y / --yes (do not ask; install the hook), --no-
|
|
92
|
-
--port=N, --for=SECONDS (stop the viewer by itself after that time)
|
|
121
|
+
options for the one-command path: -y / --yes (do not ask; install the hook), --no-hook (do not install the hook, do not ask),
|
|
122
|
+
--no-open (build the map but do not start the viewer), --port=N, --for=SECONDS (stop the viewer by itself after that time),
|
|
123
|
+
--full (ignore everything remembered and analyse from scratch), --quiet (only problems and the address), --no-color (also: NO_COLOR=1)
|
|
124
|
+
Memory: a whole analysis gets about 75% of this computer's memory (2-8 GB). CANOPY_MAX_MEMORY_MB=<number> sets it; CANOPY_DEBUG_MEM=1 prints the memory at each stage.
|
|
93
125
|
Exit codes: 0 ok, 1 a problem (the message says what to do), 3 no JavaScript / TypeScript files found.
|
|
94
|
-
Node >= 18 required. Output lives in <path>/.canopy/ (kept out of git automatically).`;async function
|
|
95
|
-
fix: canopy sync "${e}"`),process.exit(1));let n=
|
|
96
|
-
${
|
|
126
|
+
Node >= 18 required. Output lives in <path>/.canopy/ (kept out of git automatically).`;async function Yp(){let e=Tt(),t=Et(e);es.existsSync(vn.join(t,"workflows.js"))||(console.error(`no map yet for ${e}
|
|
127
|
+
fix: canopy sync "${e}"`),process.exit(1));let n=vo();n&&(console.error(n),process.exit(1));let r=await So(e,at.version);if(!r.ok&&r.running){console.log(`canopy map for ${e}
|
|
128
|
+
${r.running.url}
|
|
129
|
+
already running for this project (started ${r.running.startedAt??"earlier"}); nothing else was started`);return}r.ok||(console.error("another canopy is just starting for this project; wait a few seconds and try again"),process.exit(1));let{server:o,url:s,port:i}=await xo(t,ae.port?Number(ae.port):0,{repoRoot:e});if(ko(e,{port:i,version:at.version}),console.log(`canopy map for ${e}
|
|
130
|
+
${s}`),ae.for){console.log(`serving for ${Number(ae.for)} s`),await new Promise(a=>setTimeout(a,Number(ae.for)*1e3)),o.close();return}console.log("press Ctrl+C to stop"),await new Promise(()=>{})}function Kp(){let e=Tt();process.exit(tl(wo(e),e,at.version)?1:0)}var xn={async sync(){let e=Tt();if(ae.background){let n=Pc(e);n?console.log(`sync started in the background (pid ${n}); log: .canopy/sync.log`):console.error(`not a directory, nothing to sync: ${e}`);return}let t=ae.keep?Number(ae.keep):fn;await mo(e,{keep:t,full:!!ae.full})},open:Yp,async doctor(){Kp()},async update(){process.exit(await Oc({check:!!ae.check,version:at.version}))},async diff(){let e=Tt(),t=Ee(e);if(t.versions.length<2){console.log(t.versions.length?"only one version so far - nothing to diff yet":"no versions yet - run: canopy sync");return}let n=i=>{let a=Number(String(i).replace(/^v/,"")),c=t.versions.find(l=>l.version===a);if(!c)throw new Error(`no such version: ${i} (have ${t.versions.map(l=>"v"+l.version).join(", ")})`);return c},r=Oe[1]!==void 0?n(Oe[1]):t.versions[t.versions.length-1],o=Oe[0]!==void 0?n(Oe[0]):t.versions[t.versions.indexOf(r)-1];if(!o)throw new Error("no earlier version to compare against");let s=pn(ht(e,o),ht(e,r));console.log(ae.json?kc(s):Nc(s,r,o))},async"install-hook"(){let e=Tt(),t=gn(e);bo(e,{hook:void 0}),console.log("installed canopy block in: "+t.join(", "))},async"uninstall-hook"(){let e=Ec(Tt());console.log(e.length?"removed canopy block from: "+e.join(", "):"no canopy hook block found")},async hook(){let e=Oe.shift();if(e==="install")return xn["install-hook"]();if(e==="uninstall")return xn["uninstall-hook"]();console.error("usage: canopy hook install|uninstall [path]"),process.exit(2)},async history(){let e=Tt(),t=Ee(e);if(!t.versions.length)return console.log("no versions yet - run: canopy sync");for(let n of t.versions)console.log(`v${n.version} ${n.fingerprint.slice(0,7)} ${n.createdAt} ${n.headSha?n.headSha.slice(0,7):"-------"}${n.dirty?"*":" "} ${n.headMessage?JSON.stringify(n.headMessage):""} nodes ${n.counts.nodes} edges ${n.counts.edges} workflows ${n.counts.workflows} ${(n.bytes/1024).toFixed(0)} KB${n.gzip?" gz":""}`)}};Number(process.versions.node.split(".")[0])<18&&(console.error(`Canopy needs Node 18 or newer, and this is Node ${process.versions.node}.
|
|
131
|
+
What to try next: install the current LTS from https://nodejs.org (or run: nvm install --lts), open a new terminal, and run canopy again.`),process.exit(1));process.env[Xr]!=="1"&&process.env.CANOPY_NO_RESPAWN!=="1"&&Zr(process.argv.slice(2))&&process.exit(await fl({args:process.argv.slice(2),scriptPath:process.argv[1],version:at.version}));var ml=e=>{let t=String(e?.message??e).split(`
|
|
132
|
+
`)[0].slice(0,200),n=$o(process.argv.slice(2));Qr(n,{version:at.version,stage:to(),code:1,memory:{mb:null,source:"this run"}}),console.error(`Canopy stopped unexpectedly${to()?" while it was working on: "+to():""}.
|
|
133
|
+
(${t})
|
|
134
|
+
|
|
135
|
+
What to try next:
|
|
136
|
+
1. canopy doctor checks Node, the grammars and write access
|
|
137
|
+
2. canopy <folder> try one package or app at a time
|
|
138
|
+
3. run it again: the files already read are remembered
|
|
139
|
+
Details for a bug report (no code or secrets): .canopy/last-error.txt in the project folder.`),process.exit(1)};process.on("uncaughtException",ml);process.on("unhandledRejection",ml);Zr(process.argv.slice(2))&&Wa($o(process.argv.slice(2)));process.on("exit",()=>Ga());(ae.version||Ue==="version")&&(console.log(at.version),process.exit(0));(ae.help||Ue==="help")&&(console.log(pl),process.exit(0));if(Ue===void 0||!xn[Ue]&&(es.existsSync(vn.resolve(Ue))||/^[.~]|[\\/]/.test(Ue))){Ue!==void 0&&Oe.unshift(Ue);let e=await cl({target:Oe[0]?vn.resolve(Oe[0]):process.cwd(),yes:!!ae.yes,noOpen:!!ae["no-open"],quiet:!!ae.quiet,noColor:!!ae["no-color"],noHook:!!ae["no-hook"],full:!!ae.full,port:ae.port?Number(ae.port):void 0,forSeconds:ae.for?Number(ae.for):void 0,pkg:at});process.exit(e)}xn[Ue]||(console.error(`unknown command: ${Ue}
|
|
97
140
|
|
|
98
|
-
${
|
|
141
|
+
${pl}`),process.exit(2));xn[Ue]().catch(e=>{console.error(e.stack||e.message),process.exit(1)});
|