canopy-engine 0.1.7 → 0.1.8

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.
@@ -0,0 +1,5 @@
1
+ import{fileURLToPath as __cf,pathToFileURL as __cu}from"node:url";import{dirname as __cd,join as __cj}from"node:path";import{createRequire as __cr}from"node:module";
2
+ const require=__cr(import.meta.url);
3
+ globalThis.__canopyBundle??=__cj(__cd(__cf(import.meta.url)),"canopy.js");
4
+ globalThis.__canopyUrl??=(r)=>__cu(__cj(__cd(__cd(globalThis.__canopyBundle)),r)).href;
5
+ import w from"node:fs";import F from"node:os";import S from"node:path";import fe from"node:crypto";var $="https://eu.i.posthog.com/batch/",v="phc_Ah2MwhgAE7anjWnykv5G8waaifCEUHTnaPGzHMSgYKBK";var R={duration:["<5s","5-30s","30s-2m","2-10m","10m+"],files:["<500","500-2k","2k-10k","10k+"],services:["1","2-3","4-10","10+"],askDuration:["<10s","10-30s","30-90s","90s+"]},P=["sync_failed","memory","no_files","viewer_failed","update_failed","ai_failed","ai_not_installed","ai_not_logged_in","ai_timeout","other"],re=["ok","error"],se=["ok","error","cancelled"],oe=["vscode","path","env"],d="count",I={first_run:{},sync_completed:{duration_bucket:R.duration,files_bucket:R.files,services_bucket:R.services,result:re,error_code:P},viewer_opened:{},search_used:{count:d},workflow_opened:{count:d},ask_ai_used:{count:d,result:se,claude_source:oe,duration_bucket:R.askDuration},feedback_link_clicked:{count:d},update_toast_shown:{count:d},error:{error_code:P}},L=new Set(["search_used","workflow_opened","ask_ai_used","feedback_link_clicked","update_toast_shown"]),Y=new Set(["search_used","workflow_opened","feedback_link_clicked","update_toast_shown"]),ie=["event","distinct_id (the random install id)","timestamp (UTC)","canopy_version","os","arch","node_major","editor"],ce=["win32","darwin","linux"],ae=["x64","arm64","ia32","arm"],ue=["vscode","cursor","other","none"];function O(t,s){let n=Number(s);if(!Number.isFinite(n)||n<0)return null;switch(t){case"duration":return n<5e3?"<5s":n<3e4?"5-30s":n<12e4?"30s-2m":n<6e5?"2-10m":"10m+";case"files":return n<500?"<500":n<2e3?"500-2k":n<1e4?"2k-10k":"10k+";case"services":return n<=1?"1":n<=3?"2-3":n<=10?"4-10":"10+";case"askDuration":return n<1e4?"<10s":n<3e4?"10-30s":n<9e4?"30-90s":"90s+";default:return null}}function N(t,s){let n=Object.hasOwn(I,t)?I[t]:null;if(!n)return null;let i={};if(s&&typeof s=="object")for(let[u,a]of Object.entries(s)){if(!Object.hasOwn(n,u))continue;let b=n[u];b===d?Number.isInteger(a)&&a>=0&&a<=1e6&&(i[u]=a):typeof a=="string"&&b.includes(a)&&(i[u]=a)}return i}function V({version:t,platform:s,arch:n,nodeMajor:i,editor:u}){return{canopy_version:/^\d{1,3}\.\d{1,3}\.\d{1,3}(?:-[0-9A-Za-z.-]{1,20})?$/.test(String(t))?String(t):"unknown",os:ce.includes(s)?s:"other",arch:ae.includes(n)?n:"other",node_major:Number.isInteger(i)&&i>0&&i<1e3?i:0,editor:ue.includes(u)?u:"none"}}function K(t=process.env){return t.CURSOR_TRACE_ID||/cursor/i.test(String(t.TERM_PROGRAM??""))||t.CURSOR_AGENT?"cursor":t.VSCODE_PID||t.VSCODE_IPC_HOOK_CLI||String(t.TERM_PROGRAM??"").toLowerCase()==="vscode"?"vscode":t.TERM_PROGRAM&&/windsurf|zed|jetbrains/i.test(String(t.TERM_PROGRAM))?"other":"none"}function H(){let t=[`every event: ${ie.join(", ")}`];for(let[s,n]of Object.entries(I)){let i=Object.entries(n).map(([u,a])=>`${u}: ${a===d?"a whole number":a.join(" | ")}`);t.push(`${s}${i.length?" - "+i.join("; "):" - (no extra fields)"}`)}return t}var de=5*6e4,_e=2e3,pe=100,me=t=>t!==void 0&&t!==""&&!/^(0|false|no|off)$/i.test(String(t));function he({env:t=process.env,platform:s=process.platform,home:n=F.homedir()}={}){return s==="win32"?S.join(t.APPDATA||S.join(n,"AppData","Roaming"),"canopy","config.json"):S.join(t.XDG_CONFIG_HOME||S.join(n,".config"),"canopy","config.json")}var Ee=(t=process.env)=>t.CANOPY_TEST_RUN==="1"||!!t.NODE_TEST_CONTEXT||/^(pre|post)?(test|publish|prepublishOnly)(:|$)/.test(String(t.npm_lifecycle_event??""));function x(t=process.env){return me(t.DO_NOT_TRACK)?"DO_NOT_TRACK is set":/^(0|false|off|no)$/i.test(String(t.CANOPY_TELEMETRY??"x"))?"CANOPY_TELEMETRY=0":t.CI!==void 0&&t.CI!==""?"a CI environment variable is present":t.CANOPY_HOOK==="1"?"this is the commit hook's background sync":Ee(t)?"this is a test run":null}function ke({url:t=$,key:s=v,consentVersion:n=1,env:i=process.env,platform:u=process.platform,arch:a=process.arch,home:b=F.homedir(),version:G="unknown",fetchFn:D=globalThis.fetch,now:T=()=>Date.now(),nodeMajor:z=Number(process.versions.node.split(".")[0]),file:y=he({env:i,platform:u,home:b})}={}){let h=!!(t&&s&&/^https:\/\//.test(t)),f=new Map,_=[],p=null,A=()=>{try{let e=JSON.parse(w.readFileSync(y,"utf8"));return e&&typeof e=="object"?e:{}}catch{return{}}},B=e=>{try{return w.mkdirSync(S.dirname(y),{recursive:!0}),w.writeFileSync(y,JSON.stringify(e,null,2)),!0}catch{return!1}},m=()=>{let e=A();return{telemetry:e.telemetry==="on"?"on":e.telemetry==="off"?"off":null,choiceDate:e.choiceDate??null,consentVersion:Number.isInteger(e.consentVersion)?e.consentVersion:0,installId:/^[0-9a-f-]{36}$/.test(String(e.installId??""))?e.installId:null}},g=()=>{if(!h||x(i))return!1;let e=m();return e.telemetry==="on"&&e.consentVersion>=n&&!!e.installId},J=({isTTY:e,quiet:c=!1,background:o=!1}={})=>{if(!h||x(i)||!e||c||o)return!1;let r=m();return r.telemetry===null||r.consentVersion<n},q=e=>{let o={...A(),telemetry:e?"on":"off",choiceDate:new Date(T()).toISOString().slice(0,10),consentVersion:n};e?/^[0-9a-f-]{36}$/.test(String(o.installId??""))||(o.installId=fe.randomUUID()):delete o.installId;let r=B(o);return e&&r&&E("first_run"),r},M=()=>V({version:G,platform:u,arch:a,nodeMajor:z,editor:K(i)}),C=(e,c,o=T())=>{let r=N(e,c);if(!r)return null;let l=m();return{event:e,distinct_id:l.installId??"00000000-0000-4000-8000-000000000000",timestamp:new Date(o).toISOString(),properties:{distinct_id:l.installId??"00000000-0000-4000-8000-000000000000",...M(),...r,$process_person_profile:!1,$ip:null}}};function E(e,c={}){try{if(!g())return;let o=N(e,c);if(!o)return;if(L.has(e)){let{count:r,...l}=o,k=e+"|"+JSON.stringify(l);f.set(k,(f.get(k)??0)+(Number.isInteger(r)&&r>0?r:1))}else _.length<pe&&_.push({event:e,clean:o,ts:T()});Z()}catch{}}let W=e=>{Y.has(e)&&E(e,{})},X=({result:e,durationMs:c,source:o}={})=>E("ask_ai_used",{result:e==="ok"||e==="cancelled"?e:"error",claude_source:o==="path"||o==="env"?o:"vscode",duration_bucket:O("askDuration",c)}),Q=({ms:e,files:c,services:o,ok:r=!0,errorCode:l}={})=>E("sync_completed",{duration_bucket:O("duration",e),files_bucket:O("files",c),services_bucket:O("services",o),result:r?"ok":"error",...r?{}:{error_code:l??"sync_failed"}});function Z(){p||!globalThis.setInterval||(p=setInterval(()=>{U()},de),p.unref?.())}async function U(){try{if(!g()||!_.length&&!f.size)return _.length=0,f.clear(),!1;let e=[];for(let r of _.splice(0)){let l=C(r.event,r.clean,r.ts);l&&e.push(l)}for(let[r,l]of[...f]){let k=r.indexOf("|"),j=C(r.slice(0,k),{...JSON.parse(r.slice(k+1)),count:l});j&&e.push(j)}if(f.clear(),!e.length||typeof D!="function")return!1;let c=new AbortController,o=setTimeout(()=>c.abort(),_e);try{return await D(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({api_key:s,batch:e}),signal:c.signal,credentials:"omit",redirect:"error"}),!0}catch{return!1}finally{clearTimeout(o)}}catch{return!1}}let ee=()=>{p&&(clearInterval(p),p=null)};function te(){let e=m(),c=x(i);return{configured:h,choice:e.telemetry,choiceDate:e.choiceDate,consentVersion:e.consentVersion,currentConsentVersion:n,hasInstallId:!!e.installId,hardOff:c,active:g(),file:y}}function ne(){let e={event:"sync_completed",distinct_id:m().installId??"<random install id, created only after you say yes>",timestamp:new Date(T()).toISOString(),properties:{...M(),duration_bucket:"5-30s",files_bucket:"500-2k",services_bucket:"2-3",result:"ok",$process_person_profile:!1,$ip:null}};return{sample:{api_key:h?"<set at build time>":"<not set: this build sends nothing>",batch:[e]},fields:H()}}return{configured:h,active:g,shouldAsk:J,setConsent:q,record:E,recordBrowser:W,askAiUsed:X,syncCompleted:Q,flush:U,stop:ee,status:te,show:ne,buildEvent:C,choice:m,_counters:f,_queue:_}}var Oe=null;function De(t={}){return Oe??=ke(t)}var Se="t.gandigoutham@gmail.com";function be({version:t,platform:s=process.platform}){return`Canopy feedback (v${t}, ${s})`}function Te({version:t,platform:s=process.platform}){return`mailto:${Se}?subject=${encodeURIComponent(be({version:t,platform:s}))}`}function Me({version:t,platform:s=process.platform}){return`Feedback welcome: ${Te({version:t,platform:s})}`}export{De as a,Te as b,Me as c};
@@ -2,7 +2,7 @@ import{fileURLToPath as __cf,pathToFileURL as __cu}from"node:url";import{dirname
2
2
  const require=__cr(import.meta.url);
3
3
  globalThis.__canopyBundle??=__cj(__cd(__cf(import.meta.url)),"canopy.js");
4
4
  globalThis.__canopyUrl??=(r)=>__cu(__cj(__cd(__cd(globalThis.__canopyBundle)),r)).href;
5
- import{a as te,b as me}from"./chunk-KFBDAACV.js";import{a as de,e as pe,r as he}from"./chunk-DRLW6UU3.js";import{a as Se}from"./chunk-AGOP4Q7U.js";import{c as we,d as ke}from"./chunk-MWFO5O33.js";import{f as ne,g as oe,i as re,j as se,k as ae,l as ie,m as M,n as ce,o as le}from"./chunk-W57Z6UQP.js";import{e as ue,g as fe}from"./chunk-LAKMPJML.js";import"./chunk-SVREO35Y.js";import{a as ge,c as ye}from"./chunk-F535OXGZ.js";import{a as F}from"./chunk-ZF5SEDQB.js";import"./chunk-ZQ6F3H6X.js";import D from"node:fs";import Ze from"node:http";import E from"node:path";import{spawn as Qe}from"node:child_process";import $e from"node:path";import{execFile as Je}from"node:child_process";function Me(e,t,o){let r=e.length,s=t.length,l=Math.min(r+s,o),i=l+1,g=new Int32Array(2*l+3),m=[];for(let p=0;p<=l;p++){m.push(g.slice());for(let n=-p;n<=p;n+=2){let a=n===-p||n!==p&&g[i+n-1]<g[i+n+1]?g[i+n+1]:g[i+n-1]+1,c=a-n;for(;a<r&&c<s&&e[a]===t[c];)a++,c++;if(g[i+n]=a,a>=r&&c>=s)return Ce(m,r,s,p,i,e,t)}}return null}function Ce(e,t,o,r,s){let l=t,i=o,g=[];for(let m=r;m>0;m--){let p=e[m],n=l-i,a=n===-m||n!==m&&p[s+n-1]<p[s+n+1]?n+1:n-1,c=p[s+a],S=c-a;for(;l>c&&i>S;)g.push(["=",l-1,i-1]),l--,i--;l===c?g.push(["+",-1,i-1]):g.push(["-",l-1,-1]),l=c,i=S}for(;l>0&&i>0;)g.push(["=",l-1,i-1]),l--,i--;return g.reverse()}function De(e,t,{maxD:o=1500}={}){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;let s=0;for(;s<e.length-r&&s<t.length-r&&e[e.length-1-s]===t[t.length-1-s];)s++;let l=e.slice(r,e.length-s),i=t.slice(r,t.length-s),g,m=!1;l.length?i.length?(g=Me(l,i,o),g||(m=!0,g=[...l.map((n,a)=>["-",a,-1]),...i.map((n,a)=>["+",-1,a])])):g=l.map((n,a)=>["-",a,-1]):g=i.map((n,a)=>["+",-1,a]);let p=[];for(let n=0;n<r;n++)p.push(["=",n,n]);for(let[n,a,c]of g)p.push([n,a<0?-1:a+r,c<0?-1:c+r]);for(let n=0;n<s;n++)p.push(["=",e.length-s+n,t.length-s+n]);return{ops:p,coarse:m}}function be(e,t,{aBase:o=1,bBase:r=1,context:s=3,maxD:l}={}){let{ops:i,coarse:g}=De(e,t,l?{maxD:l}:{}),m=[];i.forEach((c,S)=>{c[0]!=="="&&m.push(S)});let p={added:i.filter(c=>c[0]==="+").length,removed:i.filter(c=>c[0]==="-").length};if(!m.length)return{rows:[],stats:p,coarse:g};let n=[];for(let c of m){let S=Math.max(0,c-s),u=Math.min(i.length-1,c+s),f=n[n.length-1];f&&S<=f[1]+1?f[1]=Math.max(f[1],u):n.push([S,u])}let a=[];for(let[c,S]of n){let u=null,f=null,h=0,y=0,v=[];for(let x=c;x<=S;x++){let[k,_,P]=i[x];k!=="+"&&(u==null&&(u=_+1),h++),k!=="-"&&(f==null&&(f=P+1),y++),k==="="?v.push({t:" ",o:o+_,n:r+P,text:e[_]}):k==="-"?v.push({t:"-",o:o+_,n:null,text:e[_]}):v.push({t:"+",o:null,n:r+P,text:t[P]})}u==null&&(u=i.slice(0,c).filter(x=>x[0]!=="+").length),f==null&&(f=i.slice(0,c).filter(x=>x[0]!=="-").length);let T=(x,k)=>k===0?`${x},0`:k===1?`${x}`:`${x},${k}`;a.push({t:"@",header:`@@ -${T(u,h)} +${T(f,y)} @@`,oldStart:u,oldLen:h,newStart:f,newLen:y}),a.push(...v)}return{rows:a,stats:p,coarse:g}}function W(e,t,o=1){let r=e.map((l,i)=>t==="+"?{t:"+",o:null,n:o+i,text:l}:{t:"-",o:o+i,n:null,text:l}),s=t==="+"?`@@ -0,0 +1${e.length===1?"":","+e.length} @@`:`@@ -1${e.length===1?"":","+e.length} +0,0 @@`;return{rows:e.length?[{t:"@",header:s,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 Ye=5e3,Fe=3*1024*1024,Be="line-level changes need git history",Ge=/^[0-9a-f]{40}$/,ve=/^[1-9][0-9]{0,5}$/,Ue=2e3;function Xe(e=process.env){let t=["PATH","Path","SystemRoot","SYSTEMROOT","windir","TEMP","TMP","TMPDIR","HOME","USERPROFILE","HOMEDRIVE","HOMEPATH","APPDATA","LOCALAPPDATA","COMSPEC","PATHEXT"],o={};for(let r of t)e[r]!==void 0&&(o[r]=e[r]);return{...o,GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0",GIT_ASKPASS:"",LC_ALL:"C"}}function We(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":$e.isAbsolute(e)||/^[A-Za-z]:/.test(e)||e.startsWith("/")||e.startsWith("\\")||e.split(/[\\/]/).includes("..")?"not a path inside the project":e.split(/[\\/]/).some(t=>oe(t))?"environment, key and certificate files are never served":null}function xe({repoRoot:e,gitFile:t="git",gitPre:o=[],timeoutMs:r=Ye,maxBlob:s=Fe,env:l=Xe()}){let i=new Map;function g(u){if(i.has(u.file))return i.get(u.file);let f=se(e,u),h=new Map;for(let y of f?.nodes??[])h.has(y.id)||h.set(y.id,y);return i.set(u.file,h),i.size>4&&i.delete(i.keys().next().value),h}let m=new Map;function p(u,f){let h=u+":"+f;return m.has(h)?Promise.resolve({ok:!0,buf:m.get(h)}):n(u,f).then(y=>(y.ok&&(m.set(h,y.buf),m.size>24&&m.delete(m.keys().next().value)),y))}function n(u,f){return new Promise(h=>{Je(t,[...o,"--no-pager","cat-file","blob",`${u}:${f}`],{cwd:e,env:l,timeout:r,maxBuffer:s,encoding:"buffer",windowsHide:!0},(y,v)=>{if(!y)return h({ok:!0,buf:v});if(y.killed||y.signal==="SIGTERM"||y.code==="ETIMEDOUT")return h({ok:!1,why:"timeout"});if(String(y.code).includes("MAXBUFFER"))return h({ok:!1,why:"too-large"});h({ok:!1,why:"missing"})})})}function a(u,f,h){let y=u.get(h),v=f.get(h);if(y&&v)return{status:y.bodyHash===v.bodyHash?"unchanged":"modified",oldN:y,newN:v};let T=(x,k)=>x.kind===k.kind&&x.name===k.name&&x.bodyHash===k.bodyHash&&x.filePath!==k.filePath;if(v){let x=[...u.values()].filter(k=>!f.has(k.id)&&T(k,v)).sort((k,_)=>k.id<_.id?-1:1)[0];return x?{status:"moved",oldN:x,newN:v}:{status:"added",oldN:null,newN:v}}if(y){let x=[...f.values()].filter(k=>!u.has(k.id)&&T(y,k)).sort((k,_)=>k.id<_.id?-1:1)[0];return x?{status:"moved",oldN:y,newN:x}:{status:"removed",oldN:y,newN:null}}return null}let c=u=>u&&Number.isInteger(u.startLine)&&u.startLine>0&&Number.isInteger(u.endLine)&&u.endLine>=u.startLine?[u.startLine,u.endLine]:null;async function S(u,f,h){try{if(typeof u!="string"||!u||u.length>Ue)return{status:400,body:{ok:!1,code:"bad-request",message:"node must be a node id"}};if(!ve.test(String(f))||!ve.test(String(h)))return{status:400,body:{ok:!1,code:"bad-request",message:"from and to must be version numbers"}};let y=re(e),v=y?.versions?.find(O=>String(O.version)===String(f)),T=y?.versions?.find(O=>String(O.version)===String(h));if(!v||!T)return{status:404,body:{ok:!1,code:"unknown-version",message:"no such stored version"}};let x=g(v),k=g(T),_=a(x,k,u);if(!_)return{status:404,body:{ok:!1,code:"unknown-node",message:"no such node in these versions"}};let{status:P,oldN:I,newN:w}=_;for(let O of[I,w]){let A=O&&We(O.filePath);if(A)return{status:403,body:{ok:!1,code:"refused",message:"refused: "+A}}}let d={nodeId:u,status:P,from:v.version,to:T.version,oldFile:I?.filePath??null,newFile:w?.filePath??null,oldRange:c(I),newRange:c(w),name:(w??I).name},H=[];I&&v.dirty&&H.push(v.version),w&&T.dirty&&!H.includes(T.version)&&H.push(T.version);let b=H.length?"approximate: taken with uncommitted changes":null,N=(O,A="")=>({status:200,body:{ok:!0,mode:"node-only",reason:O,message:Be+A,approximate:b,...d}});if(P==="unchanged")return{status:200,body:{ok:!0,mode:"lines",rows:[],stats:{added:0,removed:0},formattingOnly:!1,approximate:b,message:"this function did not change between these versions",...d}};let L=[];I&&L.push(["old",v.headSha,I.filePath]),w&&L.push(["new",T.headSha,w.filePath]);for(let[,O]of L)if(typeof O!="string"||!Ge.test(O))return N("no-git");let $=await Promise.all(L.map(([,O,A])=>p(O,A))),R={};for(let O=0;O<L.length;O++){let A=$[O];if(!A.ok)return A.why==="too-large"?{status:200,body:{ok:!0,mode:"node-only",reason:"too-large",message:"this file is too large to diff here",approximate:b,...d}}:N(A.why==="timeout"?"timeout":"missing-commit");if(A.buf.subarray(0,8e3).includes(0))return{status:403,body:{ok:!1,code:"binary",message:"refused: binary file"}};R[L[O][0]]=A.buf.toString("utf8")}let U=O=>{let A=O.replace(/\r\n/g,`
5
+ import{a as te,b as me}from"./chunk-B5D2E2HN.js";import{a as de,e as pe,r as he}from"./chunk-DRLW6UU3.js";import{a as Se}from"./chunk-AGOP4Q7U.js";import{c as we,d as ke}from"./chunk-MWFO5O33.js";import{f as ne,g as oe,i as re,j as se,k as ae,l as ie,m as M,n as ce,o as le}from"./chunk-W57Z6UQP.js";import{e as ue,g as fe}from"./chunk-LAKMPJML.js";import"./chunk-SVREO35Y.js";import{a as ge,c as ye}from"./chunk-F535OXGZ.js";import{a as F}from"./chunk-ZF5SEDQB.js";import"./chunk-ZQ6F3H6X.js";import D from"node:fs";import Ze from"node:http";import E from"node:path";import{spawn as Qe}from"node:child_process";import $e from"node:path";import{execFile as Je}from"node:child_process";function Me(e,t,o){let r=e.length,s=t.length,l=Math.min(r+s,o),i=l+1,g=new Int32Array(2*l+3),m=[];for(let p=0;p<=l;p++){m.push(g.slice());for(let n=-p;n<=p;n+=2){let a=n===-p||n!==p&&g[i+n-1]<g[i+n+1]?g[i+n+1]:g[i+n-1]+1,c=a-n;for(;a<r&&c<s&&e[a]===t[c];)a++,c++;if(g[i+n]=a,a>=r&&c>=s)return Ce(m,r,s,p,i,e,t)}}return null}function Ce(e,t,o,r,s){let l=t,i=o,g=[];for(let m=r;m>0;m--){let p=e[m],n=l-i,a=n===-m||n!==m&&p[s+n-1]<p[s+n+1]?n+1:n-1,c=p[s+a],S=c-a;for(;l>c&&i>S;)g.push(["=",l-1,i-1]),l--,i--;l===c?g.push(["+",-1,i-1]):g.push(["-",l-1,-1]),l=c,i=S}for(;l>0&&i>0;)g.push(["=",l-1,i-1]),l--,i--;return g.reverse()}function De(e,t,{maxD:o=1500}={}){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;let s=0;for(;s<e.length-r&&s<t.length-r&&e[e.length-1-s]===t[t.length-1-s];)s++;let l=e.slice(r,e.length-s),i=t.slice(r,t.length-s),g,m=!1;l.length?i.length?(g=Me(l,i,o),g||(m=!0,g=[...l.map((n,a)=>["-",a,-1]),...i.map((n,a)=>["+",-1,a])])):g=l.map((n,a)=>["-",a,-1]):g=i.map((n,a)=>["+",-1,a]);let p=[];for(let n=0;n<r;n++)p.push(["=",n,n]);for(let[n,a,c]of g)p.push([n,a<0?-1:a+r,c<0?-1:c+r]);for(let n=0;n<s;n++)p.push(["=",e.length-s+n,t.length-s+n]);return{ops:p,coarse:m}}function be(e,t,{aBase:o=1,bBase:r=1,context:s=3,maxD:l}={}){let{ops:i,coarse:g}=De(e,t,l?{maxD:l}:{}),m=[];i.forEach((c,S)=>{c[0]!=="="&&m.push(S)});let p={added:i.filter(c=>c[0]==="+").length,removed:i.filter(c=>c[0]==="-").length};if(!m.length)return{rows:[],stats:p,coarse:g};let n=[];for(let c of m){let S=Math.max(0,c-s),u=Math.min(i.length-1,c+s),f=n[n.length-1];f&&S<=f[1]+1?f[1]=Math.max(f[1],u):n.push([S,u])}let a=[];for(let[c,S]of n){let u=null,f=null,h=0,y=0,v=[];for(let x=c;x<=S;x++){let[k,_,P]=i[x];k!=="+"&&(u==null&&(u=_+1),h++),k!=="-"&&(f==null&&(f=P+1),y++),k==="="?v.push({t:" ",o:o+_,n:r+P,text:e[_]}):k==="-"?v.push({t:"-",o:o+_,n:null,text:e[_]}):v.push({t:"+",o:null,n:r+P,text:t[P]})}u==null&&(u=i.slice(0,c).filter(x=>x[0]!=="+").length),f==null&&(f=i.slice(0,c).filter(x=>x[0]!=="-").length);let T=(x,k)=>k===0?`${x},0`:k===1?`${x}`:`${x},${k}`;a.push({t:"@",header:`@@ -${T(u,h)} +${T(f,y)} @@`,oldStart:u,oldLen:h,newStart:f,newLen:y}),a.push(...v)}return{rows:a,stats:p,coarse:g}}function W(e,t,o=1){let r=e.map((l,i)=>t==="+"?{t:"+",o:null,n:o+i,text:l}:{t:"-",o:o+i,n:null,text:l}),s=t==="+"?`@@ -0,0 +1${e.length===1?"":","+e.length} @@`:`@@ -1${e.length===1?"":","+e.length} +0,0 @@`;return{rows:e.length?[{t:"@",header:s,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 Ye=5e3,Fe=3*1024*1024,Be="line-level changes need git history",Ge=/^[0-9a-f]{40}$/,ve=/^[1-9][0-9]{0,5}$/,Ue=2e3;function Xe(e=process.env){let t=["PATH","Path","SystemRoot","SYSTEMROOT","windir","TEMP","TMP","TMPDIR","HOME","USERPROFILE","HOMEDRIVE","HOMEPATH","APPDATA","LOCALAPPDATA","COMSPEC","PATHEXT"],o={};for(let r of t)e[r]!==void 0&&(o[r]=e[r]);return{...o,GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0",GIT_ASKPASS:"",LC_ALL:"C"}}function We(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":$e.isAbsolute(e)||/^[A-Za-z]:/.test(e)||e.startsWith("/")||e.startsWith("\\")||e.split(/[\\/]/).includes("..")?"not a path inside the project":e.split(/[\\/]/).some(t=>oe(t))?"environment, key and certificate files are never served":null}function xe({repoRoot:e,gitFile:t="git",gitPre:o=[],timeoutMs:r=Ye,maxBlob:s=Fe,env:l=Xe()}){let i=new Map;function g(u){if(i.has(u.file))return i.get(u.file);let f=se(e,u),h=new Map;for(let y of f?.nodes??[])h.has(y.id)||h.set(y.id,y);return i.set(u.file,h),i.size>4&&i.delete(i.keys().next().value),h}let m=new Map;function p(u,f){let h=u+":"+f;return m.has(h)?Promise.resolve({ok:!0,buf:m.get(h)}):n(u,f).then(y=>(y.ok&&(m.set(h,y.buf),m.size>24&&m.delete(m.keys().next().value)),y))}function n(u,f){return new Promise(h=>{Je(t,[...o,"--no-pager","cat-file","blob",`${u}:${f}`],{cwd:e,env:l,timeout:r,maxBuffer:s,encoding:"buffer",windowsHide:!0},(y,v)=>{if(!y)return h({ok:!0,buf:v});if(y.killed||y.signal==="SIGTERM"||y.code==="ETIMEDOUT")return h({ok:!1,why:"timeout"});if(String(y.code).includes("MAXBUFFER"))return h({ok:!1,why:"too-large"});h({ok:!1,why:"missing"})})})}function a(u,f,h){let y=u.get(h),v=f.get(h);if(y&&v)return{status:y.bodyHash===v.bodyHash?"unchanged":"modified",oldN:y,newN:v};let T=(x,k)=>x.kind===k.kind&&x.name===k.name&&x.bodyHash===k.bodyHash&&x.filePath!==k.filePath;if(v){let x=[...u.values()].filter(k=>!f.has(k.id)&&T(k,v)).sort((k,_)=>k.id<_.id?-1:1)[0];return x?{status:"moved",oldN:x,newN:v}:{status:"added",oldN:null,newN:v}}if(y){let x=[...f.values()].filter(k=>!u.has(k.id)&&T(y,k)).sort((k,_)=>k.id<_.id?-1:1)[0];return x?{status:"moved",oldN:y,newN:x}:{status:"removed",oldN:y,newN:null}}return null}let c=u=>u&&Number.isInteger(u.startLine)&&u.startLine>0&&Number.isInteger(u.endLine)&&u.endLine>=u.startLine?[u.startLine,u.endLine]:null;async function S(u,f,h){try{if(typeof u!="string"||!u||u.length>Ue)return{status:400,body:{ok:!1,code:"bad-request",message:"node must be a node id"}};if(!ve.test(String(f))||!ve.test(String(h)))return{status:400,body:{ok:!1,code:"bad-request",message:"from and to must be version numbers"}};let y=re(e),v=y?.versions?.find(O=>String(O.version)===String(f)),T=y?.versions?.find(O=>String(O.version)===String(h));if(!v||!T)return{status:404,body:{ok:!1,code:"unknown-version",message:"no such stored version"}};let x=g(v),k=g(T),_=a(x,k,u);if(!_)return{status:404,body:{ok:!1,code:"unknown-node",message:"no such node in these versions"}};let{status:P,oldN:I,newN:w}=_;for(let O of[I,w]){let A=O&&We(O.filePath);if(A)return{status:403,body:{ok:!1,code:"refused",message:"refused: "+A}}}let d={nodeId:u,status:P,from:v.version,to:T.version,oldFile:I?.filePath??null,newFile:w?.filePath??null,oldRange:c(I),newRange:c(w),name:(w??I).name},H=[];I&&v.dirty&&H.push(v.version),w&&T.dirty&&!H.includes(T.version)&&H.push(T.version);let b=H.length?"approximate: taken with uncommitted changes":null,N=(O,A="")=>({status:200,body:{ok:!0,mode:"node-only",reason:O,message:Be+A,approximate:b,...d}});if(P==="unchanged")return{status:200,body:{ok:!0,mode:"lines",rows:[],stats:{added:0,removed:0},formattingOnly:!1,approximate:b,message:"this function did not change between these versions",...d}};let L=[];I&&L.push(["old",v.headSha,I.filePath]),w&&L.push(["new",T.headSha,w.filePath]);for(let[,O]of L)if(typeof O!="string"||!Ge.test(O))return N("no-git");let $=await Promise.all(L.map(([,O,A])=>p(O,A))),R={};for(let O=0;O<L.length;O++){let A=$[O];if(!A.ok)return A.why==="too-large"?{status:200,body:{ok:!0,mode:"node-only",reason:"too-large",message:"this file is too large to diff here",approximate:b,...d}}:N(A.why==="timeout"?"timeout":"missing-commit");if(A.buf.subarray(0,8e3).includes(0))return{status:403,body:{ok:!1,code:"binary",message:"refused: binary file"}};R[L[O][0]]=A.buf.toString("utf8")}let U=O=>{let A=O.replace(/\r\n/g,`
6
6
  `).split(`
7
7
  `);return A.length>1&&A[A.length-1]===""&&A.pop(),A},z=(O,A)=>{let X=U(O);if(!A)return{lines:X,base:1,clamped:!1};let Le=A[1]>X.length;return{lines:X.slice(A[0]-1,A[1]),base:A[0],clamped:Le}},J=R.old!=null?z(R.old,d.oldRange):{lines:[],base:1,clamped:!1},Y=R.new!=null?z(R.new,d.newRange):{lines:[],base:1,clamped:!1},V=R.old!=null&&R.new!=null&&R.old!==R.new&&U(R.old).join(`
8
8
  `)===U(R.new).join(`
@@ -2,5 +2,5 @@ import{fileURLToPath as __cf,pathToFileURL as __cu}from"node:url";import{dirname
2
2
  const require=__cr(import.meta.url);
3
3
  globalThis.__canopyBundle??=__cj(__cd(__cf(import.meta.url)),"canopy.js");
4
4
  globalThis.__canopyUrl??=(r)=>__cu(__cj(__cd(__cd(globalThis.__canopyBundle)),r)).href;
5
- import{a as o,b as n,c as p,f as m}from"./chunk-4UV7T77F.js";import"./chunk-ZF5SEDQB.js";import"./chunk-ZQ6F3H6X.js";import{parentPort as t,workerData as c}from"node:worker_threads";async function P(){try{if(process.env.CANOPY_TEST_WORKER_FAIL==="1")throw new Error("test: a worker that cannot start");let{parser:e,language:i,grammars:s}=await n();await o({grammars:s},c.grammarKeys.map(r=>r==="tsx"?"x.tsx":r==="typescript"?"x.ts":"x.js"));let f={store:p({prune:!1}),readCache:!c.noCache,parser:e,language:i,grammars:s};t.on("message",r=>{if(r.type!=="batch")return;let a=[];for(let{i:g,filePath:u}of r.items)a.push({i:g,outcome:m(u,f)});t.postMessage({type:"done",results:a})}),t.postMessage({type:"ready"})}catch(e){t.postMessage({type:"fatal",message:`a worker could not start its parser (${String(e?.message??e).split(`
5
+ import{a as o,b as n,c as p,f as m}from"./chunk-Y3GNG3XL.js";import"./chunk-ZF5SEDQB.js";import"./chunk-ZQ6F3H6X.js";import{parentPort as t,workerData as c}from"node:worker_threads";async function P(){try{if(process.env.CANOPY_TEST_WORKER_FAIL==="1")throw new Error("test: a worker that cannot start");let{parser:e,language:i,grammars:s}=await n();await o({grammars:s},c.grammarKeys.map(r=>r==="tsx"?"x.tsx":r==="typescript"?"x.ts":"x.js"));let f={store:p({prune:!1}),readCache:!c.noCache,parser:e,language:i,grammars:s};t.on("message",r=>{if(r.type!=="batch")return;let a=[];for(let{i:g,filePath:u}of r.items)a.push({i:g,outcome:m(u,f)});t.postMessage({type:"done",results:a})}),t.postMessage({type:"ready"})}catch(e){t.postMessage({type:"fatal",message:`a worker could not start its parser (${String(e?.message??e).split(`
6
6
  `)[0].slice(0,160)})`})}}export{P as runParseWorker};
@@ -0,0 +1,7 @@
1
+ import{fileURLToPath as __cf,pathToFileURL as __cu}from"node:url";import{dirname as __cd,join as __cj}from"node:path";import{createRequire as __cr}from"node:module";
2
+ const require=__cr(import.meta.url);
3
+ globalThis.__canopyBundle??=__cj(__cd(__cf(import.meta.url)),"canopy.js");
4
+ globalThis.__canopyUrl??=(r)=>__cu(__cj(__cd(__cd(globalThis.__canopyBundle)),r)).href;
5
+ import{b as $,c as le}from"./chunk-ZF5SEDQB.js";import{Parser as Q,Language as de}from"web-tree-sitter";import D from"node:path";import{fileURLToPath as _t}from"node:url";var dn=D.dirname(_t(globalThis.__canopyUrl("src/stage2_parse/initParser.js")));var X=new WeakMap,M=t=>X.get(t)??"javascript",T=t=>M(t)!=="javascript";function q(t){let e=D.extname(t);return e===".tsx"?"tsx":e===".ts"||e===".mts"||e===".cts"?"typescript":"javascript"}var Ft={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm"};async function pn(t,e){for(let r of new Set(e.map(q))){if(t.grammars.has(r))continue;let o=D.join($("tree-sitter-typescript"),Ft[r]),n=await de.load(o);X.set(n,r);let i=new Q;i.setLanguage(n),t.grammars.set(r,{parser:i,language:n})}return t}async function un(){await Q.init();let t=new Q,e=D.join($("tree-sitter-javascript"),"tree-sitter-javascript.wasm"),r=await de.load(e);return t.setLanguage(r),X.set(r,"javascript"),{parser:t,language:r,grammars:new Map([["javascript",{parser:t,language:r}]])}}import E from"node:fs";import w from"node:path";import gt from"node:os";import ue from"node:crypto";import{threadId as Nt}from"node:worker_threads";import{fileURLToPath as Ct}from"node:url";var wt=w.dirname(Ct(globalThis.__canopyUrl("src/stage2_parse/parseCache.js"))),fe=w.join(wt,"..",".."),ee=process.env.CANOPY_CACHE_DIR||(le()?w.join(gt.homedir(),".canopy-cache"):w.join(fe,".canopy-cache")),pe=t=>ue.createHash("sha256").update(t).digest("hex");function G(t,e){return E.readdirSync(t,{withFileTypes:!0}).flatMap(r=>r.isDirectory()?G(w.join(t,r.name),e):e.some(o=>r.name.endsWith(o))?[w.join(t,r.name)]:[]).sort()}var te=null;function kt(){if(te)return te;let t=w.join(fe,"src"),e=!E.existsSync(t)&&globalThis.__canopyBundle,r=e?E.readdirSync(w.dirname(e)).filter(i=>i.endsWith(".js")).sort().map(i=>w.join(w.dirname(e),i)):[],o=e?[...r,...G(w.join(w.dirname(e),"queries"),[".scm"])]:[...G(w.join(t,"stage2_parse"),[".js",".scm"]),...G(w.join(t,"stage5_entrypoints"),[".js"]).filter(i=>/match/i.test(w.basename(i))),w.join(t,"utils","loadQuery.js")],n=ue.createHash("sha256");for(let i of o)n.update(w.relative(e?w.dirname(e):t,i).split(w.sep).join("/")).update("\0").update(E.readFileSync(i).toString("utf8").replace(/\r\n/g,`
6
+ `)).update("\0");for(let i of["web-tree-sitter","tree-sitter-javascript","tree-sitter-typescript"])try{n.update(i+"@"+JSON.parse(E.readFileSync(w.join($(i),"package.json"),"utf8")).version)}catch{n.update(i+"@?")}return te=n.digest("hex").slice(0,16)}function me({prune:t=!0}={}){let e=kt(),r=w.join(ee,e);if(E.mkdirSync(r,{recursive:!0}),t)for(let o of E.readdirSync(ee,{withFileTypes:!0}))o.isDirectory()&&o.name!==e&&E.rmSync(w.join(ee,o.name),{recursive:!0,force:!0});return{version:e,keyFor:(o,n="javascript")=>pe(n==="javascript"?o:Buffer.concat([Buffer.from(n+"\0"),o])),get(o){try{return JSON.parse(E.readFileSync(w.join(r,o+".json"),"utf8"))}catch{return null}},set(o,n){let i=w.join(r,`${o}.${process.pid}.${Nt}.tmp`);E.writeFileSync(i,JSON.stringify(n)),E.renameSync(i,w.join(r,o+".json"))}}}function he(t){return JSON.parse(JSON.stringify(t,(e,r)=>r&&typeof r=="object"&&r.startPosition&&r.endPosition&&"type"in r&&"tree"in r?void 0:r))}import bt from"node:fs";function Fe(t,e){let r=bt.readFileSync(e,"utf-8"),o=t.parse(r);if(ne(o)||r.includes("\0")){let n=r,i=_e(o);for(let s of St){let a=s.apply(n);if(a===n)continue;let c=t.parse(a),p=_e(c);if(p<i||s.always){try{o.delete()}catch{}n=a,o=c,i=p}else try{c.delete()}catch{}}n!==r&&(o.canopyOriginalSource=r)}return{tree:o,source:r,filePath:e}}var ge=t=>t.replace(/[^\n]/g," "),ye=t=>"any"+ge(t).slice(3),xe=/(?<![&])&(?![&=])/g,St=[{name:"NUL byte",always:!0,apply:t=>t.replace(/\0/g," ")},{name:"export type * from",apply:t=>t.replace(/\bexport\s+type\s+\*\s*(?:as\s+[\w$]+\s+)?from\s*(["'])[^"'\n]*\1\s*;?/g,ge)},{name:"typeof import()",apply:t=>t.replace(/typeof\s+import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)*/g,ye)},{name:"import().Type",apply:t=>t.replace(/(?<=[:<,|&?]\s*|\breadonly\s+|\bkeyof\s+|\bextends\s+|\bas\s+)import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)+(?!\s*\()/g,ye)},{name:"generic call signature after a member",apply:t=>t.replace(/(?<=\n[ \t]*)[ ](?=<\s*[A-Za-z_$][\w$]*\s*(?:extends\b|=|,|>\s*\())/g,";")},{name:"& in JSX text",apply:t=>t.replace(/>[^<>{}"'`]*&[^<>{}"'`]*</g,e=>e.replace(xe,"+"))},{name:"& in JSX attribute",apply:t=>t.replace(/(\s[\w:-]+=)"([^"\n]*)"/g,(e,r,o)=>r+'"'+o.replace(xe,"+")+'"')}];function _e(t){let e=0;return(function r(o){if(o.type==="ERROR"){e++;return}for(let n=0;n<o.childCount;n++)r(o.child(n))})(t.rootNode),e}function ne(t){let e=!1;function r(o){if(o.type==="ERROR"){e=!0;return}for(let n=0;n<o.childCount;n++)r(o.child(n))}return r(t.rootNode),e}import re from"node:fs";import B from"node:path";import{fileURLToPath as vt}from"node:url";import{Query as Et}from"web-tree-sitter";var Ne=B.dirname(vt(globalThis.__canopyUrl("src/utils/loadQuery.js"))),Ce=new WeakMap;function k(t,e){let r=Ce.get(t);if(r||Ce.set(t,r=new Map),r.has(e))return r.get(e);let o=B.join(Ne,"..","stage2_parse","queries"),n=re.existsSync(o)?o:B.join(Ne,"..","..","dist","queries"),i=M(t),c=(i==="javascript"?[]:i==="tsx"?["tsx","typescript"]:[i]).map(y=>B.join(n,y,e)).find(y=>re.existsSync(y))??B.join(n,e),p=re.readFileSync(c,"utf-8"),h=new Et(t,p);return r.set(e,h),h}var we="javascript",ke=t=>{we=t};var K=()=>we!=="javascript";var jt=new Set(["non_null_expression","as_expression","satisfies_expression","type_assertion"]);function S(t){for(;t;)if(jt.has(t.type))t=t.type==="type_assertion"?t.namedChild(t.namedChildCount-1):t.namedChild(0);else if(t.type==="parenthesized_expression"&&t.namedChildCount===1){let e=S(t.namedChild(0));if(e===t.namedChild(0))break;t=e}else break;return t}function Pt(t){let e=t;for(;e;){e=S(e);for(let r=0;r<e.childCount;r++)if(e.child(r).type==="optional_chain")return!0;if(e.type==="member_expression"||e.type==="subscript_expression")e=e.childForFieldName("object");else if(e.type==="call_expression")e=e.childForFieldName("function");else break}return!1}function L(t){let e=t.childForFieldName("function"),r=t.childForFieldName("arguments");if(!e)return{kind:"callOfCall",oldShape:!1,nameNode:t};let o=e.type==="identifier",n=e.type==="member_expression"?e.childForFieldName("property"):null,i=e.type==="member_expression"?S(e.childForFieldName("object")):null,s=o||i?.type==="identifier"&&n?.type==="property_identifier",a=n??e;if(K()&&t.parent?.type==="decorator")return{kind:"decorator",oldShape:s,nameNode:a};if(r&&r.type==="template_string")return{kind:"taggedTemplate",oldShape:s,nameNode:a};if(Pt(t))return{kind:"optionalCall",oldShape:s,nameNode:a};if(o)return{kind:"call",oldShape:s,nameNode:a};if(e.type==="subscript_expression")return{kind:"computed",oldShape:!1,nameNode:e};if(e.type==="member_expression")return i.type==="super"?{kind:"super",oldShape:!1,nameNode:a}:i.type==="this"?{kind:"thisCall",oldShape:!1,nameNode:a}:s?{kind:"methodCall",oldShape:!0,nameNode:a}:{kind:"chainedCall",oldShape:!1,nameNode:a};if(e.type==="import")return{kind:"dynamicImport",oldShape:!1,nameNode:e};if(e.type==="super")return{kind:"super",oldShape:!1,nameNode:e};let c=e;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:e}:{kind:"callOfCall",oldShape:!1,nameNode:e}}function be(t){let e=t.childForFieldName("name");return e?e.type==="identifier"?/^[A-Z]/.test(e.text)?{kind:"jsx",oldShape:!0,nameNode:e}:null:e.type==="member_expression"||e.type==="nested_identifier"?{kind:"jsxMember",oldShape:!1,nameNode:e}:null:null}function z(t){let e=t;for(;e&&e.type!=="call_expression";)e=e.parent;return e}function Se(t){let e=t.childForFieldName("function"),r=!1;for(;e;)if(e=S(e),e.type==="member_expression"||e.type==="subscript_expression")e=e.childForFieldName("object");else if(e.type==="call_expression")r=!0,e=e.childForFieldName("function");else if(e.type==="await_expression"||e.type==="parenthesized_expression"||e.type==="non_null_expression")e=e.namedChild(0);else break;return e&&e.type==="identifier"?{head:e.text,called:r}:{head:null,called:!1}}function ve(t){let e=t.text.replace(/\s+/g," ");return e.length>120?e.slice(0,117)+"...":e}function je(t,e){let n=k(e,"functionDeclarations.scm").matches(t.rootNode).map(i=>{let s=i.captures.find(p=>p.name==="func_name"),a=i.captures.find(p=>p.name==="func_params"),c=i.captures.find(p=>p.name==="func_declaration");return{name:s.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:s.node}});return T(e)&&n.push(...Tt(t,e)),n}function Tt(t,e){return k(e,"defaultExports.scm").matches(t.rootNode).map(r=>{let o=r.captures.find(i=>i.name==="func_declaration").node;return{name:"default",params:r.captures.find(i=>i.name==="func_params").node.text,startLine:o.startPosition.row+1,endLine:o.endPosition.row+1,startIndex:o.startIndex,endIndex:o.endIndex,node:o}})}function Pe(t,e){return k(e,"arrowFunctions.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(c=>c.name==="func_name"),s=n.captures.find(c=>c.name==="func_params"),a=n.captures.find(c=>c.name==="func_declaration");return{name:i.node.text,params:s.node.text,startLine:a.node.startPosition.row+1,endLine:a.node.endPosition.row+1,startIndex:a.node.startIndex,endIndex:a.node.endIndex,node:i.node}})}function Te(t,e){let o=k(e,"classMethods.scm").matches(t.rootNode),n=T(e);return o.map(i=>{let s=i.captures.find(y=>y.name==="class_name"),a=i.captures.find(y=>y.name==="method_name"),c=i.captures.find(y=>y.name==="method_params"),p=i.captures.find(y=>y.name==="method_declaration"),h=p.node;if(n)for(let y=h.previousNamedSibling;y&&y.type==="decorator";y=y.previousNamedSibling)h=y;return{className:s?s.node.text:"default",methodName:a.node.text,params:c.node.text,startLine:h.startPosition.row+1,endLine:p.node.endPosition.row+1,startIndex:h.startIndex,endIndex:p.node.endIndex,node:a.node}})}function Le(t,e){let o=k(e,"imports.scm").matches(t.rootNode),n=T(e);return o.filter(i=>!(n&&Lt(i.captures[0].node))).map(i=>{let s=i.captures[0].node;return{source:s.text,startLine:s.startPosition.row+1}})}function Lt(t){let e=t;for(;e&&e.type!=="import_statement";)e=e.parent;if(!e)return!1;if(e.children.some(i=>i.type==="type"))return!0;let r=e.namedChildren.find(i=>i.type==="import_clause");if(!r)return!1;let o=r.namedChildren;if(o.length!==1||o[0].type!=="named_imports")return!1;let n=o[0].namedChildren.filter(i=>i.type==="import_specifier");return n.length>0&&n.every(i=>i.children.some(s=>s.type==="type"))}function W(t){let e=t;for(;e&&e.type!=="call_expression"&&e.type!=="new_expression";)e=e.parent;if(!e)return null;let r=e.childForFieldName("arguments");if(!r)return null;let o=r.namedChildren?.[0];return!o||o.type==="arrow_function"||o.type==="function_expression"?null:o.text}var It=/^(addEventListener|removeEventListener|on|once|postMessage|onmessage|subscribe)$/i;function R(t){let e=t;for(;e.parent;){let r=e.parent;if(r.type==="arrow_function"||r.type==="function_expression"){let o=r.parent;if(o&&(o.type==="variable_declarator"||o.type==="public_field_definition"))break;if(o&&o.type==="return_statement")return!0;if(o&&o.type==="arguments"&&o.parent?.type==="call_expression"){let n=o.parent.childForFieldName("function"),i=n?.type==="member_expression"?n.childForFieldName("property")?.text:n?.text;if(i&&It.test(i))return!0}}else if(r.type==="function_declaration"||r.type==="method_definition")break;e=r}return!1}function Ie(t,e){return k(e,"callExpressions.scm").matches(t.rootNode).map(n=>{let i=n.captures[0].node;return{calleeName:i.text,startLine:i.startPosition.row+1,startColumn:i.startPosition.column,branchPath:A(i),firstArgText:W(i),deferred:R(i),callKind:L(z(i)).kind}})}function Re(t,e){return T(e)?Rt(t):k(e,"methodCalls.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(a=>a.name==="object_name"),s=n.captures.find(a=>a.name==="method_name");return{objectName:i.node.text,methodName:s.node.text,startLine:s.node.startPosition.row+1,startColumn:s.node.startPosition.column,firstArgText:W(s.node),branchPath:A(s.node),deferred:R(s.node),callKind:L(z(s.node)).kind}})}function Rt(t){let e=[];for(let r of t.rootNode.descendantsOfType("call_expression")){let o=r.childForFieldName("function");if(!o||o.type!=="member_expression")continue;let n=S(o.childForFieldName("object")),i=o.childForFieldName("property");!n||n.type!=="identifier"||!i||i.type!=="property_identifier"||e.push({objectName:n.text,methodName:i.text,startLine:i.startPosition.row+1,startColumn:i.startPosition.column,firstArgText:W(i),branchPath:A(i),deferred:R(i),callKind:L(z(i)).kind})}return e}function At(t){if(!t)return"return";if(t.type==="object"){let e=t.namedChildren.filter(o=>o.type==="pair"),r=e.find(o=>o.childForFieldName("key")?.text?.replace(/^['"]|['"]$/g,"")==="type")??e.find(o=>o.childForFieldName("key")?.text?.replace(/^['"]|['"]$/g,"")==="entity");if(r){let o=r.childForFieldName("key"),n=r.childForFieldName("value");return`return { ${o.text}: ${n.text} }`}}return"return "+t.text.split(/\r?\n/)[0].trim()}function Ae(t,e){return k(e,"returns.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(c=>c.name==="return_statement"),s=n.captures.find(c=>c.name==="return_value"),a=i.node;return{label:At(s?.node),startLine:a.startPosition.row+1,startColumn:a.startPosition.column,branchPath:A(a),deferred:R(a)}})}var Ot=new Set(["function_declaration","arrow_function","function_expression","method_definition"]);function J(t,e){return!(!e||t.row<e.startPosition.row||t.row>e.endPosition.row||t.row===e.startPosition.row&&t.column<e.startPosition.column||t.row===e.endPosition.row&&t.column>e.endPosition.column)}function A(t){let e=[],r=t,o=t.startPosition;for(;r.parent;){let n=r.parent;if(Ot.has(n.type))break;if(n.type==="if_statement"){let i=n.childForFieldName("condition"),s=n.childForFieldName("consequence"),a=n.childForFieldName("alternative");J(o,s)?e.push({type:"if",conditionText:i?i.text:"",conditionLine:(i??n).startPosition.row+1,outcome:"true"}):J(o,a)&&e.push({type:"if",conditionText:i?i.text:"",conditionLine:(i??n).startPosition.row+1,outcome:"false"})}else if(n.type==="switch_case"||n.type==="switch_default"){let i=n.parent,s=i&&i.type==="switch_body"?i.parent:null;if(s){let a=s.childForFieldName("value"),c=n.childForFieldName("value");e.push({type:"switch",conditionText:a?a.text:"",conditionLine:(a??s).startPosition.row+1,outcome:n.type==="switch_default"?"default":c?c.text:"case"})}}else if(n.type==="try_statement"){let i=n.childForFieldName("handler"),s=n.childForFieldName("finalizer"),a="try";J(o,i)?a="catch":J(o,s)&&(a="finally"),e.push({type:"try",conditionText:"try / catch",conditionLine:n.startPosition.row+1,outcome:a})}r=n}return e.reverse()}function Oe(t,e){return k(e,"exports.scm").matches(t.rootNode).map(o=>o.captures[0].node.text)}var Ee=new WeakMap;function $t(t,e){let r=Ee.get(t);return r||(r=k(e,"returns.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(a=>a.name==="return_statement"),s=n.captures.find(a=>a.name==="return_value");return{stmtNode:i.node,valueNode:s?.node}}),Ee.set(t,r)),r}function $e(t,e,r){return $t(t,e).filter(o=>o.stmtNode.startPosition.row+1>=r.startLine&&o.stmtNode.endPosition.row+1<=r.endLine).map(o=>({shape:Mt(o.valueNode),condition:qt(o.stmtNode,r),line:o.stmtNode.startPosition.row+1}))}function Mt(t){if(!t)return"nothing";switch(t.type){case"true":case"false":return"boolean";case"number":return"number";case"string":return"string";case"null":return"null";case"identifier":return`variable (${t.text})`;case"object":return"object";case"array":return"array";case"call_expression":return`result of ${t.text.split("(")[0]}()`;case"binary_expression":return"boolean (comparison)";case"ternary_expression":return"conditional value";default:return"expression"}}function qt(t,e){let r=t.parent;for(;r;){if(r.type==="if_statement"){let o=r.childForFieldName("condition");if(o)return o.text}r=r.parent}return null}function Me(t,e){return M(e)==="typescript"?[]:k(e,"jsxElements.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(s=>s.name==="jsx_tag");return{calleeName:i.node.text,startLine:i.node.startPosition.row+1}}).filter(n=>/^[A-Z]/.test(n.calleeName))}function qe(t,e){return k(e,"fetchApiCalls.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(p=>p.name==="url"),s=n.captures.find(p=>p.name==="http_method"),a=i.node.text,c=/^https?:\/\//.test(a)?"external":"internal";return{url:a,method:s?.node.text??"get",startLine:i.node.startPosition.row+1,scope:c}})}function Be(t,e){return k(e,"socketEmit.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(s=>s.name==="event_name");return{eventName:i.node.text,startLine:i.node.startPosition.row+1}})}function We(t,e){return k(e,"rawSocketSend.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(s=>s.name==="event_name");return{eventName:i.node.text,startLine:i.node.startPosition.row+1}})}function He(t,e){return k(e,"rawSocketTypeCheck.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(s=>s.name==="event_name");return{eventName:i.node.text,startLine:i.node.startPosition.row+1}})}function Ue(t,e){return k(e,"socketOn.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(c=>c.name==="event_name"),s=n.captures.find(c=>c.name==="handler_ref"),a=n.captures.find(c=>c.name==="handler_inline");return{eventName:i.node.text,startLine:i.node.startPosition.row+1,handlerName:s?s.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 De(t){let e=t.rootNode.descendantsOfType(["call_expression","new_expression","jsx_opening_element","jsx_self_closing_element",...K()?["decorator"]:[]]),r=[];for(let o of e){let n,i,s,a=null,c=null,p=!1,h=null,y=null,N=null;if(o.type==="new_expression"){if(s=o.childForFieldName("constructor"),!s)continue;n="new",i=s,a=s.type==="identifier"?s.text:null;let u=o.childForFieldName("arguments")?.namedChildren?.[0];h=u&&u.type!=="arrow_function"&&u.type!=="function_expression"?u.text:null}else if(o.type==="decorator"){let d=o.namedChild(0);if(!d||d.type==="call_expression")continue;n="decorator",i=d.type==="member_expression"?d.childForFieldName("property")??d:d,s=d}else if(o.type==="call_expression"){let d=L(o);if(d.oldShape)continue;if(n=d.kind,i=d.nameNode,s=o.childForFieldName("function")??o,n==="chainedCall"){let u=Se(o);c=u.head,p=u.called;let l=o.childForFieldName("function"),m=l?.type==="member_expression"?S(l.childForFieldName("object")):null;m?.type==="member_expression"&&S(m.childForFieldName("object"))?.type==="this"&&m.childForFieldName("property")?.type==="property_identifier"&&l.childForFieldName("property")&&(y={thisProp:m.childForFieldName("property").text,thisMethod:l.childForFieldName("property").text})}h=W(i)}else{let d=be(o);if(!d||d.oldShape)continue;n=d.kind,i=d.nameNode,s=d.nameNode}r.push({callKind:n,calleeName:ve(s),startLine:i.startPosition.row+1,startColumn:i.startPosition.column,branchPath:A(i),firstArgText:h,deferred:R(i),chainHead:c,chainHeadCalled:p,ctorName:a,...y??{}})}return r.sort((o,n)=>o.startLine-n.startLine||o.startColumn-n.startColumn)}var oe=new Set(["get","post","put","patch","delete","head","options"]),ie=new Set(["axios","ky","got","superagent","$http"]),Bt=new Set(["function_declaration","function_expression","function","arrow_function","method_definition","generator_function_declaration","generator_function"]),Wt=new Set(["WebSocket","ReconnectingWebSocket","SockJS","W3CWebSocket"]),se=/^(ws|socket|sock|websocket|webSocket|wsClient|socketRef|wsRef|[A-Za-z]+Socket|[A-Za-z]+Ws|[A-Za-z]+WebSocket)$/,C=t=>{for(;t&&(t.type==="parenthesized_expression"||t.type==="as_expression"||t.type==="non_null_expression"||t.type==="await_expression"||t.type==="satisfies_expression"||t.type==="type_assertion")&&(t=t.namedChildren.find(e=>e.type!=="type_annotation"&&e.type!=="predefined_type"&&!/_type$/.test(e.type))??t.namedChildren[0],!!t););return t},H=t=>t.namedChildren.length?t.namedChildren.filter(e=>e.type==="string_fragment"||e.type==="escape_sequence").map(e=>e.text).join(""):t.text.slice(1,-1);function O(t){for(let e=t.parent;e;e=e.parent)if(Bt.has(e.type))return e;return null}function Ge(t){if(!t)return null;let e=t.childForFieldName("name")?.text??null;if(!e&&t.parent){let n=t.parent;n.type==="variable_declarator"?e=n.childForFieldName("name")?.text??null:n.type==="assignment_expression"?e=n.childForFieldName("left")?.text??null:n.type==="pair"&&(e=n.childForFieldName("key")?.text??null)}let r=[],o=t.childForFieldName("parameters");if(o)o.namedChildren.forEach((n,i)=>{let s=n.type==="identifier"?n:n.type==="assignment_pattern"?n.childForFieldName("left"):n.type==="required_parameter"||n.type==="optional_parameter"?n.childForFieldName("pattern")??n.namedChildren[0]:null;r[i]=s&&s.type==="identifier"?s.text:null});else{let n=t.childForFieldName("parameter");n&&n.type==="identifier"&&(r[0]=n.text)}return{name:e,params:r}}function Ke(t){let e=t.rootNode,r={httpCalls:[],pathCallsites:[],httpInstances:[],wsClients:[],wsServers:[],wsSends:[],wsServerSends:[],listens:[],wsReceivers:[]},o=new Map;for(let d of e.descendantsOfType("variable_declarator")){let u=d.childForFieldName("name"),l=d.childForFieldName("value");if(!u||u.type!=="identifier"||!l)continue;(o.get(u.text)??o.set(u.text,[]).get(u.text)).push({value:l,fn:O(d)})}let n=(d,u)=>{let l=o.get(d);if(!l)return null;for(let f=O(u);f;f=O(f)){let x=l.filter(_=>_.fn&&_.fn.id===f.id);if(x.length===1)return x[0].value}let m=l.filter(f=>!f.fn);return m.length===1?m[0].value:l.length===1?l[0].value:null},i=(d,u)=>{for(let l=O(u);l;l=O(l)){let f=Ge(l).params.indexOf(d);if(f>=0)return f}return-1};function s(d,u=0){if(d=C(d),!d)return[{t:"ref",name:""}];switch(d.type){case"string":return[{t:"lit",v:H(d)}];case"template_string":{let l=[];for(let m of d.namedChildren)m.type==="string_fragment"||m.type==="escape_sequence"?l.push({t:"lit",v:m.text}):m.type==="template_substitution"&&l.push(...s(m.namedChildren[0],u+1));return l.length?l:[{t:"lit",v:""}]}case"number":return[{t:"lit",v:d.text}];case"binary_expression":{let l=d.childForFieldName("operator")?.text;if(l==="||"||l==="??"){let m=s(d.childForFieldName("left"),u+1);if(m.length===1&&m[0].t==="env")return[{...m[0],fallback:s(d.childForFieldName("right"),u+1)}]}return l!=="+"?[{t:"ref",name:d.text.slice(0,60)}]:[...s(d.childForFieldName("left"),u+1),...s(d.childForFieldName("right"),u+1)]}case"shorthand_property_identifier":case"identifier":{let l=d.text,m=i(l,d);if(m>=0)return[{t:"param",name:l,index:m}];if(u<4){let f=n(l,d);if(f&&f.id!==d.id)return s(f,u+1)}return[{t:"ref",name:l}]}case"member_expression":{let l=d.text,m=/^(?:process\.env|import\.meta\.env)\.([A-Za-z0-9_$]+)$/.exec(l)??/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(l);return m?[{t:"env",name:m[1]}]:[{t:"ref",name:l.slice(0,60)}]}case"subscript_expression":{let l=/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(d.text);return l?[{t:"env",name:l[1]}]:[{t:"ref",name:d.text.slice(0,60)}]}case"call_expression":{let l=d.childForFieldName("function")?.text,m=d.childForFieldName("arguments")?.namedChildren[0];if(m&&(l==="encodeURIComponent"||l==="String"||l==="encodeURI"))return s(m,u+1);let f=C(d.childForFieldName("function"));if(f&&f.type==="member_expression"&&/^(replace|replaceAll|trim|trimEnd|trimStart|toString|toLowerCase)$/.test(f.childForFieldName("property")?.text??"")){let x=f.childForFieldName("object");if(x){let _=s(x,u+1);if(_.length&&_.every(F=>F.t!=="ref"))return _}}return[{t:"ref",name:d.text.slice(0,60)}]}default:return[{t:"ref",name:d.text.slice(0,60)}]}}let a=(d,u)=>{if(d=C(d),!(!d||d.type!=="object")){for(let l of d.namedChildren)if(l.type==="pair"){let m=l.childForFieldName("key");if((m?m.type==="string"?H(m):m.text:null)===u)return l.childForFieldName("value")}else if(l.type==="shorthand_property_identifier"&&l.text===u)return l}},c=d=>d.childForFieldName("arguments")?.namedChildren.filter(u=>u.type!=="comment")??[],p=d=>{if(!d)return null;let u=s(d);return u.length===1&&u[0].t==="lit"?u[0].v.toUpperCase():u.length===1&&u[0].t==="param"?{param:u[0].index}:"?"},h=(d,u,l,m)=>({client:d,method:u,parts:l,line:m.startPosition.row+1,fn:Ge(O(m))});for(let d of e.descendantsOfType("variable_declarator")){let u=d.childForFieldName("name"),l=C(d.childForFieldName("value"));if(!u||u.type!=="identifier"||!l||l.type!=="call_expression")continue;let m=C(l.childForFieldName("function"));if(!m||m.type!=="member_expression")continue;let f=m.childForFieldName("object")?.text,x=m.childForFieldName("property")?.text;if(!(ie.has(f)&&(x==="create"||x==="extend")))continue;let _=c(l)[0],F=a(_,"baseURL")??a(_,"baseUrl")??a(_,"prefixUrl")??a(_,"prefix_url");r.httpInstances.push({name:u.text,parts:F?s(F):[],line:d.startPosition.row+1})}let y=new Set(r.httpInstances.map(d=>d.name));for(let d of e.descendantsOfType("call_expression")){let u=C(d.childForFieldName("function"));if(!u)continue;let l=c(d),m=!1;if(u.type==="identifier"){let f=u.text;if(f==="fetch"&&l[0]){let x=C(l[0]);if(x&&x.type==="new_expression")continue;let _=a(l[1],"method");r.httpCalls.push(h("fetch",_?p(_):l[1]&&C(l[1])?.type!=="object"?"?":"GET",s(l[0]),d)),m=!0}else if((ie.has(f)||y.has(f))&&l[0]){let x=C(l[0]);if(x&&x.type==="object"){let _=a(x,"url");if(_){let F=a(x,"baseURL");r.httpCalls.push(h(y.has(f)?"inst:"+f:f,p(a(x,"method"))??"GET",[...F?s(F):[],...s(_)],d)),m=!0}}else r.httpCalls.push(h(y.has(f)?"inst:"+f:f,l[1]&&a(l[1],"method")?p(a(l[1],"method")):"GET",s(l[0]),d)),m=!0}else f==="io"&&l[0]&&(r.wsClients.push({client:"io",parts:s(l[0]),line:d.startPosition.row+1}),m=!0)}else if(u.type==="member_expression"){let x=u.childForFieldName("object")?.text??"",_=u.childForFieldName("property")?.text??"",F=ie.has(x)||y.has(x);if(F&&oe.has(_)&&l[0])r.httpCalls.push(h(y.has(x)?"inst:"+x:x,_.toUpperCase(),s(l[0]),d)),m=!0;else if(!F&&oe.has(_)&&/^[A-Za-z_$][\w$]*$/.test(x)&&l[0]&&(C(l[0])?.type==="string"||C(l[0])?.type==="template_string")){let g=s(l[0]);g[0]?.t==="lit"&&(g[0].v.startsWith("/")||/^https?:\/\//.test(g[0].v))&&(r.httpCalls.push(h("obj:"+x,_.toUpperCase(),g,d)),m=!0)}else if(F&&_==="request"&&l[0]){let g=a(l[0],"url");if(g){let b=a(l[0],"baseURL");r.httpCalls.push(h(y.has(x)?"inst:"+x:x,p(a(l[0],"method"))??"GET",[...b?s(b):[],...s(g)],d)),m=!0}}else if(_==="open"&&l.length>=2&&C(l[0])?.type==="string"&&/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/i.test(H(C(l[0]))))r.httpCalls.push(h("xhr",H(C(l[0])).toUpperCase(),s(l[1]),d)),m=!0;else if(x==="io"&&_==="connect"&&l[0])r.wsClients.push({client:"io",parts:s(l[0]),line:d.startPosition.row+1}),m=!0;else if(_==="listen"&&l[0]){let g=C(l[0]),b=g&&g.type==="object"?a(g,"port"):g;b&&r.listens.push({parts:s(b),line:d.startPosition.row+1}),m=!0}else if(_==="send"&&/^(client|conn|connection|peer)$/.test(x.replace(/^this./,"").split(".").pop())&&l[0]){let g=C(l[0]),b=!1;if(g&&g.type==="call_expression"&&g.childForFieldName("function")?.text==="JSON.stringify"){let v=c(g)[0];b=!!(v&&(a(v,"type")||a(v,"event"))&&C(a(v,"type")??a(v,"event"))?.type==="string")}b||r.wsServerSends.push({recv:x,line:d.startPosition.row+1}),m=!0}else if(_==="send"&&se.test(x.replace(/^this\./,"").replace(/\.current$/,"").split(".").pop())){let g=l[0]?C(l[0]):null,b=!1;if(g&&g.type==="call_expression"&&g.childForFieldName("function")?.text==="JSON.stringify"){let v=c(g)[0];b=!!(v&&(a(v,"type")||a(v,"event"))&&C(a(v,"type")??a(v,"event"))?.type==="string")}b||r.wsSends.push({recv:x,line:d.startPosition.row+1}),m=!0}}if(!m){let f=null;if(u.type==="identifier"?f=u.text:u.type==="member_expression"&&(f=u.childForFieldName("property")?.text??null),!f||oe.has(f)||l.length===0||l.length>6)continue;let x=[],_=!1;l.slice(0,5).forEach((F,g)=>{let b=C(F);if(!b||b.type!=="string"&&b.type!=="template_string")return;let v=s(b);x.push({i:g,parts:v});let j=v[0];j&&j.t==="lit"&&(j.v.startsWith("/")||/^https?:\/\//.test(j.v))&&j.v.length>1&&(_=!0)}),_&&r.pathCallsites.push({callee:f,args:x,line:d.startPosition.row+1})}}let N=d=>d.replace(/^this./,"").replace(/.current$/,"").split(".").pop();for(let d of e.descendantsOfType("assignment_expression")){let u=d.childForFieldName("left");if(!u||u.type!=="member_expression"||u.childForFieldName("property")?.text!=="onmessage"||!se.test(N(u.childForFieldName("object")?.text??"")))continue;let l=C(d.childForFieldName("right"));r.wsReceivers.push({line:d.startPosition.row+1,handlerName:l&&l.type==="identifier"?l.text:null})}for(let d of e.descendantsOfType("call_expression")){let u=C(d.childForFieldName("function"));if(!u||u.type!=="member_expression"||u.childForFieldName("property")?.text!=="addEventListener")continue;let l=c(d),m=l[0]&&C(l[0]);if(!m||m.type!=="string"||H(m)!=="message"||!se.test(N(u.childForFieldName("object")?.text??"")))continue;let f=l[1]&&C(l[1]);r.wsReceivers.push({line:d.startPosition.row+1,handlerName:f&&f.type==="identifier"?f.text:null})}for(let d of e.descendantsOfType("new_expression")){let u=C(d.childForFieldName("constructor"));if(!u)continue;let l=u.text,m=c(d);if(Wt.has(l)&&m[0])r.wsClients.push({client:l,parts:s(m[0]),line:d.startPosition.row+1});else if(/^(WebSocketServer|WebSocket\.Server|WebSocket\.WebSocketServer|ws\.Server|ws\.WebSocketServer|Server)$/.test(l)){if(l==="Server"&&!/socket\.io|socketio/i.test(t.rootNode.text.slice(0,4e3)+""))continue;let f=a(m.find(x=>C(x)?.type==="object"),"path");r.wsServers.push({path:f?s(f):null,line:d.startPosition.row+1})}}return r}var Ht=new Set(["function_declaration","generator_function_declaration","function_expression","generator_function","arrow_function","method_definition"]),Ut=new Set(["arrow_function","function_expression","generator_function"]);function P(t,e){if(t)switch(t.type){case"identifier":case"shorthand_property_identifier_pattern":e.push(t.text);return;case"assignment_pattern":P(t.childForFieldName("left"),e);return;case"rest_pattern":case"object_pattern":case"array_pattern":case"pair_pattern":case"required_parameter":case"optional_parameter":for(let r of t.namedChildren)P(t.type==="pair_pattern"?t.childForFieldName("value"):r,e);return;default:if(t.type==="pattern"||t.namedChildCount){let r=t.childForFieldName?.("pattern");r&&P(r,e)}}}function Dt(t,e){let r=t;if(r.type==="export_statement"&&(r=r.childForFieldName("declaration")),!r)return null;if(r.type==="function_declaration"||r.type==="generator_function_declaration")return r.childForFieldName("name")?.text===e?{kind:"fn",declLine:r.startPosition.row+1}:null;if(r.type==="lexical_declaration"||r.type==="variable_declaration"){for(let o of r.namedChildren){if(o.type!=="variable_declarator")continue;let n=o.childForFieldName("name");if(n?.type==="identifier"){if(n.text!==e)continue;let s=S(o.childForFieldName("value"));return s&&Ut.has(s.type)?{kind:"fn",declLine:o.startPosition.row+1}:{kind:"other"}}let i=[];if(P(n,i),i.includes(e))return{kind:"other"}}return null}return(r.type==="class_declaration"||r.type==="abstract_class_declaration"||r.type==="enum_declaration")&&r.childForFieldName("name")?.text===e?{kind:"other"}:null}function Gt(t){let e=t.namedChildren.find(n=>n.type==="string")?.text.slice(1,-1)??null,r=t.namedChildren.find(n=>n.type==="import_clause"),o=[];if(!r||e==null)return{src:e,out:o};for(let n of r.namedChildren)if(n.type==="identifier")o.push({kind:"default",local:n.text,imported:null});else if(n.type==="namespace_import"){let i=n.namedChildren.find(s=>s.type==="identifier");i&&o.push({kind:"ns",local:i.text,imported:null})}else if(n.type==="named_imports")for(let i of n.namedChildren){if(i.type!=="import_specifier")continue;let s=i.childForFieldName("name"),a=i.childForFieldName("alias");s&&o.push({kind:"named",local:(a??s).text,imported:s.text})}return{src:e,out:o}}function ze(t){let e=[];for(let r of t.rootNode.namedChildren)if(r.type==="import_statement"){if(r.children.some(s=>s.type==="type"))continue;let o=r.namedChildren.find(s=>s.type==="import_require_clause");if(o){let s=o.namedChildren.find(c=>c.type==="identifier"),a=o.namedChildren.find(c=>c.type==="string");s&&a&&e.push({source:U(a),kind:"cjs",local:s.text,imported:null});continue}let{src:n,out:i}=Gt(r);for(let s of i)e.push({source:n,...s})}else if(r.type==="lexical_declaration"||r.type==="variable_declaration")for(let o of r.namedChildren){if(o.type!=="variable_declarator")continue;let n=S(o.childForFieldName("value")),i=null;n?.type==="member_expression"&&(i=n.childForFieldName("property")?.text??null,n=S(n.childForFieldName("object")));let s=Y(n);if(s==null)continue;let a=o.childForFieldName("name");if(a?.type==="identifier")e.push({source:s,kind:i?"named":"cjs",local:a.text,imported:i});else if(a?.type==="object_pattern"&&!i){for(let c of a.namedChildren)if(c.type==="shorthand_property_identifier_pattern")e.push({source:s,kind:"named",local:c.text,imported:c.text});else if(c.type==="pair_pattern"){let p=c.childForFieldName("key"),h=c.childForFieldName("value");p&&h?.type==="identifier"&&e.push({source:s,kind:"named",local:h.text,imported:p.text})}}}return e}var U=t=>t.namedChildren.filter(e=>e.type==="string_fragment").map(e=>e.text).join("");function Y(t){if(t?.type!=="call_expression")return null;let e=t.childForFieldName("function"),r=t.childForFieldName("arguments");if(e?.type!=="identifier"||e.text!=="require"||!r||r.namedChildCount!==1)return null;let o=r.namedChildren[0];return o.type==="string"?U(o):null}function Je(t){let e=[];return(function r(o){if(o.type==="export_statement"){let n=o.childForFieldName("source");n&&!o.children.some(i=>i.type==="type")&&e.push({source:U(n),startLine:n.startPosition.row+1})}else if(o.type==="import_require_clause"){let n=o.namedChildren.find(i=>i.type==="string");n&&e.push({source:U(n),startLine:n.startPosition.row+1})}else if(o.type==="call_expression"){let n=Y(o);n!=null&&e.push({source:n,startLine:o.startPosition.row+1})}for(let n of o.namedChildren)r(n)})(t.rootNode),e}function Ye(t){let e={default:null,named:{},reexports:[],stars:[],nsReexports:[]};for(let r of t.rootNode.namedChildren){if(r.type!=="export_statement")continue;let o=r.children.some(s=>s.type==="default"),n=r.childForFieldName("declaration"),i=r.childForFieldName("source")!=null;if(o){if(n){let s=n.childForFieldName("name");e.default=s&&(n.type==="function_declaration"||n.type==="generator_function_declaration"||n.type==="class_declaration"||n.type==="abstract_class_declaration")?s.text:"<anon>"}else{let s=S(r.childForFieldName("value"));e.default=s?.type==="identifier"?s.text:"<anon>"}continue}if(n){if(n.type==="function_declaration"||n.type==="generator_function_declaration"||n.type==="class_declaration"||n.type==="abstract_class_declaration"){let s=n.childForFieldName("name")?.text;s&&(e.named[s]=s)}else if(n.type==="lexical_declaration"||n.type==="variable_declaration")for(let s of n.namedChildren){let a=s.type==="variable_declarator"?s.childForFieldName("name"):null;a?.type==="identifier"&&(e.named[a.text]=a.text)}continue}if(i){if(r.children.some(p=>p.type==="type"))continue;let s=U(r.childForFieldName("source")),a=r.namedChildren.find(p=>p.type==="export_clause"),c=r.namedChildren.find(p=>p.type==="namespace_export");if(a)for(let p of a.namedChildren){if(p.type!=="export_specifier")continue;let h=p.childForFieldName("name")?.text,y=p.childForFieldName("alias")?.text;h&&e.reexports.push({exported:y??h,imported:h,source:s})}else if(c){let p=c.namedChildren.find(h=>h.type==="identifier");p&&e.nsReexports.push({exported:p.text,source:s})}else e.stars.push(s);continue}for(let s of r.namedChildren)if(s.type==="export_clause")for(let a of s.namedChildren){if(a.type!=="export_specifier")continue;let c=a.childForFieldName("name")?.text,p=a.childForFieldName("alias")?.text;c&&(p==="default"?e.default=c:e.named[p??c]=c)}}for(let r of t.rootNode.namedChildren){let o=r.type==="expression_statement"?r.namedChildren[0]:null;if(o?.type!=="assignment_expression")continue;let n=o.childForFieldName("left"),i=S(o.childForFieldName("right"));if(n?.type!=="member_expression")continue;let s=n.childForFieldName("object"),a=n.childForFieldName("property")?.text,c=p=>p?.type==="member_expression"&&p.childForFieldName("object")?.text==="module"&&p.childForFieldName("property")?.text==="exports";if(c(n))if(i?.type==="identifier")e.default=i.text;else if(i?.type==="object"){for(let p of i.namedChildren)if(p.type==="shorthand_property_identifier")e.named[p.text]=p.text;else if(p.type==="pair"){let h=p.childForFieldName("key"),y=S(p.childForFieldName("value"));h&&y?.type==="identifier"&&(e.named[h.text.replace(/^['"]|['"]$/g,"")]=y.text)}e.default??="<object>"}else Y(i)!=null?e.stars.push(Y(i)):e.default="<anon>";else a&&(s?.type==="identifier"&&s.text==="exports"||c(s))&&i?.type==="identifier"&&(e.named[a]=i.text)}return e}function Kt(t,e,r){for(let o=t.parent;o;o=o.parent)if(Ht.has(o.type)){let n=[],i=o.childForFieldName("parameters");if(i)for(let a of i.namedChildren)P(a,n);let s=o.childForFieldName("parameter");if(s&&P(s,n),o.type==="function_expression"||o.type==="generator_function"){let a=o.childForFieldName("name");a&&n.push(a.text)}if(n.includes(e))return{kind:"other"}}else if(o.type==="catch_clause"){let n=[];if(P(o.childForFieldName("parameter"),n),n.includes(e))return{kind:"other"}}else if(o.type==="for_in_statement"||o.type==="for_statement"){let n=[],i=o.type==="for_statement"?o.childForFieldName("initializer"):o.childForFieldName("left");if(i)if(i.type==="lexical_declaration"||i.type==="variable_declaration")for(let s of i.namedChildren)P(s.childForFieldName?.("name"),n);else P(i,n);if(n.includes(e))return{kind:"other"}}else if(o.type==="statement_block"||o.type==="program"||o.type==="switch_body"){if(o.type==="program"&&r.has(e))return{kind:"import",imp:r.get(e)};for(let n of o.namedChildren){let i=Dt(n,e);if(i)return i}if(o.type==="program"&&r.has(e))return{kind:"import",imp:r.get(e)}}return null}var zt=t=>(t.childForFieldName("function")?.text??"").replace(/\s+/g," ").slice(0,40);function Ve(t,e){let r=new Map(e.map(i=>[i.local,i])),o=[],n=(i,s,a)=>{let c=S(i);if(!c||c.type!=="identifier"&&c.type!=="shorthand_property_identifier")return;let p=c.text,h=Kt(c,p,r);if(!h||h.kind==="other")return;let y=L(a).nameNode,N={name:p,line:c.startPosition.row+1,column:c.startPosition.column,via:s,callee:zt(a),callLine:y.startPosition.row+1,callColumn:y.startPosition.column,b:h.kind};h.kind==="fn"?N.declLine=h.declLine:(N.src=h.imp.source,N.ik=h.imp.kind,N.imp=h.imp.imported),o.push(N)};return(function i(s){if(s.type==="call_expression"){let a=s.childForFieldName("arguments");for(let c of a?.namedChildren??[]){let p=S(c);if(p)if(p.type==="array")for(let h of p.namedChildren)n(h,"array",s);else if(p.type==="object")for(let h of p.namedChildren)h.type==="pair"?n(h.childForFieldName("value"),"object",s):h.type==="shorthand_property_identifier"&&n(h,"object",s);else n(p,"arg",s)}}for(let a of s.namedChildren)i(a)})(t.rootNode),o}function Ze(t){let e=[],r=n=>{let i=n?.namedChildren.find(s=>s.type!=="comment");return i?.type==="type_identifier"?i.text:null},o=n=>{let i=n.childForFieldName("name")?.text,s=n.childForFieldName("body");if(!(!i||!s)){for(let a of s.namedChildren)if(a.type==="public_field_definition"){let c=a.childForFieldName("name"),p=r(a.childForFieldName("type"));c?.type==="property_identifier"&&p&&e.push({className:i,prop:c.text,type:p})}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(y=>y.type==="accessibility_modifier")&&!c.children.some(y=>y.type==="readonly"))continue;let p=c.childForFieldName("pattern"),h=r(c.childForFieldName("type"));p?.type==="identifier"&&h&&e.push({className:i,prop:p.text,type:h})}}};for(let n of t.rootNode.namedChildren){let i=n.type==="export_statement"?n.childForFieldName("declaration"):n;i&&(i.type==="class_declaration"||i.type==="abstract_class_declaration")&&o(i)}return e}function Qe(t){let e=[];for(let r of t.rootNode.descendantsOfType(["class_declaration","abstract_class_declaration"])){let o=r.childForFieldName("name")?.text;if(!o)continue;let n=r.namedChildren.find(a=>a.type==="class_heritage"),i=null,s=!1;if(n){let a=n.namedChildren.find(p=>p.type==="extends_clause")??(n.namedChildren[0]?.type==="implements_clause"?null:n),c=a&&(a.type==="extends_clause"?a.childForFieldName("value")??a.namedChildren[0]:a.namedChildren[0]);c&&(c.type==="identifier"?i=c.text:s=!0)}e.push({className:o,superName:i,unknownSuper:s})}return e}var Jt={Get:"get",Post:"post",Put:"put",Patch:"patch",Delete:"delete",All:"all"};function Xe(t){let e=t.namedChildren[0];if(!e)return null;if(e.type==="call_expression"){let r=e.childForFieldName("function"),o=r?.type==="identifier"?r.text:null;return o?{name:o,args:e.childForFieldName("arguments")}:null}return e.type==="identifier"?{name:e.text,args:null}:null}var I=t=>t?t.type==="string"?t.namedChildren.filter(e=>e.type==="string_fragment").map(e=>e.text).join(""):t.type==="template_string"&&!t.namedChildren.some(e=>e.type==="template_substitution")?t.text.slice(1,-1):null:null;function et(t){let e=t?.namedChildren.find(r=>r.type!=="comment");if(!e)return"";if(e.type==="array")return I(e.namedChildren.find(r=>r.type!=="comment"))??"";if(e.type==="object"){for(let r of e.namedChildren){if(r.type!=="pair")continue;let o=r.childForFieldName("key");if(o?.text==="path"||o?.text==="'path'"||o?.text==='"path"'){let n=r.childForFieldName("value");return(n?.type==="array"?I(n.namedChildren[0]):I(n))??""}}return""}return I(e)??""}var V=(...t)=>"/"+t.map(r=>String(r??"").replace(/^\/+|\/+$/g,"")).filter(Boolean).join("/");function tt(t){let e=[],r=(o,n)=>{let i=o.childForFieldName("name")?.text,s=o.childForFieldName("body");if(!i||!s)return;let c=[...n,...o.namedChildren.filter(y=>y.type==="decorator")].map(Xe).filter(Boolean).find(y=>y.name==="Controller");if(!c)return;let p=et(c.args),h=[];for(let y of s.namedChildren)if(y.type!=="comment"){if(y.type==="decorator"){h.push(y);continue}if(y.type==="method_definition"){let N=y.childForFieldName("name")?.text;for(let d of h.map(Xe).filter(Boolean)){let u=Jt[d.name];!u||!N||e.push({method:u,path:V(p,et(d.args)),startLine:y.startPosition.row+1,handlerName:null,isInlineHandler:!1,handlerStartLine:null,handlerEndLine:null,handlerStartIndex:null,handlerEndIndex:null,nest:{className:i,methodName:N}})}}h=[]}};for(let o of t.rootNode.namedChildren)if(o.type==="export_statement"){let n=o.childForFieldName("declaration");n&&(n.type==="class_declaration"||n.type==="abstract_class_declaration")&&r(n,o.namedChildren.filter(i=>i.type==="decorator"))}else(o.type==="class_declaration"||o.type==="abstract_class_declaration")&&r(o,[]);return e}function nt(t){let e=[];return(function r(o){if(o.type==="call_expression"){let n=o.childForFieldName("function");if(n?.type==="member_expression"&&n.childForFieldName("property")?.text==="setGlobalPrefix"){let i=(o.childForFieldName("arguments")?.namedChildren??[]).filter(p=>p.type!=="comment"),s=i[0]?I(i[0]):null,a=[],c=i[1];if(c?.type==="object")for(let p of c.namedChildren){if(p.type!=="pair"||p.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")!=="exclude")continue;let h=p.childForFieldName("value");for(let y of h?.type==="array"?h.namedChildren:[])if(y.type==="object"){for(let N of y.namedChildren)if(N.type==="pair"&&N.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")==="path"){let d=I(N.childForFieldName("value"));d!=null&&a.push(d)}}else{let N=I(y);N!=null&&a.push(N)}}e.push({prefix:s||null,exclude:a})}}for(let n of o.namedChildren)r(n)})(t.rootNode),e}function Dn(t){let e=[];for(let i of t.values())for(let s of i?.globalPrefix??[])e.push(s);if(!e.length||e.some(i=>!i.prefix||i.prefix!==e[0].prefix))return t;let r=e[0].prefix,o=new Set(e.flatMap(i=>i.exclude).map(i=>V(i))),n=new Map;for(let[i,s]of t){if(!s?.routes?.some(a=>a.nest)){n.set(i,s);continue}n.set(i,{...s,routes:s.routes.map(a=>a.nest&&!o.has(V(a.path))?{...a,path:V(r,a.path)}:a)})}return n}import Yt from"node:crypto";var rt=t=>Yt.createHash("sha256").update(t).digest("hex");function Vt(t,e=null){let r=[],o=n=>{if(n.childCount===0){if(n.type==="comment")return;let i=e?e.slice(n.startIndex,n.endIndex):n.text,s=n.type==="jsx_text"?i.replace(/\s+/g," ").trim():i;if(s==="")return;r.push({s:n.startIndex,e:n.endIndex,t:s});return}for(let i=0;i<n.childCount;i++)o(n.child(i))};return o(t),r}function ot(t,e){let r=[];for(let i of[e.functions,e.arrowFunctions,e.classMethods])for(let s of i??[])s.startIndex!=null&&r.push({s:s.startIndex,e:s.endIndex,item:s,field:"bodyHash"});for(let i of[e.routes,e.listeners,e.socketListeners])for(let s of i??[])s.isInlineHandler&&s.handlerStartIndex!=null&&r.push({s:s.handlerStartIndex,e:s.handlerEndIndex,item:s,field:"handlerBodyHash"});let o=new Map(r.map(i=>[i,[]])),n=[];for(let i of Vt(t.rootNode,t.canopyOriginalSource??null)){let s=null,a=1/0;for(let c of r)i.s>=c.s&&i.e<=c.e&&c.e-c.s<a&&(s=c,a=c.e-c.s);(s?o.get(s):n).push(i.t)}for(let i of r)i.item[i.field]=rt(o.get(i).join(" "));e.moduleBodyHash=rt(n.join(" "))}function it(t,e){return k(e,"matchFastifyRoutes.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(p=>p.name==="http_method"),s=n.captures.find(p=>p.name==="route_path"),a=n.captures.find(p=>p.name==="handler_ref"),c=n.captures.find(p=>p.name==="handler_inline");return{method:i.node.text,path:s.node.text,startLine:i.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 st(t,e){return k(e,"matchExtensionListeners.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(u=>u.name==="event_type"),s=n.captures.find(u=>u.name==="event_name"),a=n.captures.find(u=>u.name==="method_name"||u.name==="listener_method"),c=n.captures.find(u=>u.name==="handler_ref"),p=n.captures.find(u=>u.name==="target"),h=n.captures.find(u=>u.name==="root_object"),y=n.captures.find(u=>u.name==="sub_object"),N=p?p.node.text:h?h.node.text+(y?"."+y.node.text:""):null,d=n.captures.find(u=>u.name==="handler_inline");return{eventName:i?.node.text??s?.node.text??"unknown",targetName:N,startLine:a.node.startPosition.row+1,handlerName:c?c.node.text:null,isInlineHandler:!!d,handlerStartLine:d?d.node.startPosition.row+1:null,handlerEndLine:d?d.node.endPosition.row+1:null,handlerStartIndex:d?d.node.startIndex:null,handlerEndIndex:d?d.node.endIndex:null}})}import rn from"node:fs";import at from"node:os";import ct from"node:path";import Zt from"node:v8";import{Worker as Qt}from"node:worker_threads";import{fileURLToPath as Xt}from"node:url";var lt=500,dt=8,en=24,tn=150;function pt({files:t,env:e=process.env,cpus:r=at.cpus().length,totalMb:o=Math.round(at.totalmem()/1048576),heapLimitMb:n=Math.round(Zt.getHeapStatistics().heap_size_limit/1048576)}={}){if(e.CANOPY_WORKERS!==void 0&&e.CANOPY_WORKERS!==""){let a=Number(e.CANOPY_WORKERS);return!Number.isInteger(a)||a<0?{workers:0,why:"CANOPY_WORKERS is not a whole number: one file at a time"}:a===0?{workers:0,why:"CANOPY_WORKERS=0: one file at a time"}:{workers:Math.min(a,dt),why:`CANOPY_WORKERS=${a}`}}if(t<tn)return{workers:0,why:"a small project: one file at a time"};let i=Math.min(Math.floor(n*.6/lt),Math.floor(o*.5/lt)),s=Math.min(r-1,dt,i);return s>=2?{workers:s,why:`${s} workers (${r} cpus, ${o} MB)`}:{workers:0,why:`not enough spare cpus or memory for threads (${r} cpus, ${o} MB)`}}function nn(){return globalThis.__canopyBundle?globalThis.__canopyBundle:ct.join(ct.dirname(Xt(globalThis.__canopyUrl("src/stage2_parse/parallelParse.js"))),"..","cli.js")}function ut(t,{workers:e,noCache:r,onBatch:o=()=>{},entry:n=nn()}){return new Promise(i=>{let s=new Array(t.length),a=[...new Set(t.map(q))],c=0,p=0,h=!1,y=null,N=e,d=[],u=[],l=()=>{if(!h){h=!0;for(let x of u)try{x.terminate()}catch{}i({outcomes:s,failed:y})}},m=x=>{if(h||y)return;if(c>=t.length){p>=t.length&&l();return}let _=[];for(;_.length<en&&c<t.length;)_.push({i:c,filePath:t[c]}),c++;x.busy=_,x.postMessage({type:"batch",items:_})},f=x=>{y||(y=x),l()};for(let x=0;x<e;x++){let _;try{_=new Qt(n,{workerData:{canopyParseWorker:!0,grammarKeys:a,noCache:r},resourceLimits:{maxOldGenerationSizeMb:1024,stackSizeMb:8},execArgv:[],env:process.env})}catch(F){f(`could not start a worker thread (${F?.message??F})`);return}_.busy=null,u.push(_),_.on("message",F=>{if(F.type==="ready"){m(_);return}if(F.type==="done"){for(let g of F.results)s[g.i]=g.outcome;p+=F.results.length,_.busy=null,o(p),p>=t.length?l():m(_);return}F.type==="fatal"&&f(F.message)}),_.on("error",F=>f(`a worker stopped (${String(F?.message??F).split(`
7
+ `)[0].slice(0,160)})`)),_.on("exit",F=>{N--,d.push(F),!h&&(_.busy?f(`a worker ended early (exit code ${F})`):N<=0&&f("every worker ended before the files were done (exit codes "+d.join(", ")+")"))})}})}var ht=Number(process.env.CANOPY_PARSE_BUDGET_MS)||3e4,ce=class extends Error{constructor(e){super(`parse time budget exceeded (limit ${ht/1e3} s; stopped after ${(e/1e3).toFixed(1)} s)`),this.name="ParseBudgetError"}},ft=100;function ae(t,e,r){return t.map(o=>({...o,returns:$e(e,r,o)}))}var mt=()=>({functions:[],arrowFunctions:[],classMethods:[],imports:[],calls:[],methodCalls:[],returnEntries:[],jsxElements:[],callSites:[],apiCalls:[],socketEmits:[],socketListeners:[],rawSocketSends:[],rawSocketTypeChecks:[],routes:[],listeners:[]});function on(t,e){let{store:r,readCache:o,parser:n,language:i,grammars:s}=e;{let a=null;try{let c=rn.readFileSync(t),p=q(t),h=r?.keyFor(c,p),y=r&&o?r.get(h):null;if(y)return{kind:"hit",plain:y};let N=performance.now(),d=()=>{let j=performance.now()-N;if(j>ht)throw new ce(j)},u=p==="javascript"?{parser:n,language:i}:s?.get(p);if(!u)throw new Error(`no ${p} grammar loaded`);let l=u.language;ke(p),a=Fe(u.parser,t).tree,d();let m=[],f=(j,yt,xt=[])=>{try{return yt()}catch(Z){if(Z.name==="ParseBudgetError")throw Z;return m.push({extractor:j,message:String(Z.message).slice(0,160)}),xt}},x=f("functionDeclarations",()=>ae(je(a,l),a,l));d();let _=f("arrowFunctions",()=>ae(Pe(a,l),a,l));d();let F=f("classMethods",()=>ae(Te(a,l),a,l));d();let g=f("importBindings",()=>ze(a)),b={functions:x,arrowFunctions:_,classMethods:F,imports:f("imports",()=>[...Le(a,l),...Je(a)]),calls:(d(),f("calls",()=>Ie(a,l))),methodCalls:(d(),f("methodCalls",()=>Re(a,l))),returnEntries:f("returnEntries",()=>Ae(a,l)),jsxElements:f("jsxElements",()=>Me(a,l)),callSites:(d(),f("callSites",()=>De(a))),apiCalls:(d(),f("apiCalls",()=>qe(a,l))),socketEmits:f("socketEmits",()=>Be(a,l)),socketListeners:f("socketListeners",()=>Ue(a,l)),rawSocketSends:f("rawSocketSends",()=>We(a,l)),rawSocketTypeChecks:f("rawSocketTypeChecks",()=>He(a,l)),routes:f("routes",()=>[...it(a,l),...T(l)?tt(a):[]]),listeners:f("listeners",()=>st(a,l)),refArgs:f("refArgs",()=>Ve(a,g)),globalPrefix:f("globalPrefix",()=>nt(a)),importBindings:g,classProps:f("classProps",()=>T(l)?Ze(a):[]),classHeritage:f("classHeritage",()=>Qe(a)),httpClients:f("httpClients",()=>Ke(a),null),exportBindings:f("exportBindings",()=>Ye(a),null),hadErrors:ne(a),exportedNames:f("exports",()=>Oe(a,l)),failed:!1,warnings:m};f("bodyHash",()=>ot(a,b),null);let v=he(b);if(r)try{r.set(h,v)}catch{}return{kind:"parsed",plain:v}}catch(c){return c.name==="ParseBudgetError"?{kind:"skipped",msg:c.message,plain:{...mt(),hadErrors:!1,failed:!1,skipped:c.message}}:{kind:"failed",msg:c.message,plain:{...mt(),hadErrors:!0,failed:!0,errorMessage:c.message}}}finally{if(a){try{a.delete()}catch{}a=null}}}}async function gr(t,e,r,{cache:o=!0,onProgress:n=console.log,grammars:i=null,noCache:s=!1,say:a=null}={}){let c=new Map,p=0,h=0,y=0,N=o?me():null,d=!s,u=[],l={store:N,readCache:d,parser:e,language:r,grammars:i},m=new Array(t.length),f=o?pt({files:t.length}):{workers:0,why:"no cache"};if(f.workers>=2){let x=a??n;x(` parsing on ${f.workers} threads`);let _=await ut(t,{workers:f.workers,noCache:s,onBatch:F=>{(F%ft<24||F===t.length)&&n(` parsing: ${F}/${t.length} files`)}});for(let F=0;F<_.outcomes.length;F++)m[F]=_.outcomes[F];_.failed&&x(` parsing on threads did not work (${_.failed}); the rest is parsed one file at a time`)}for(let x=0;x<t.length;x++)m[x]||(x>0&&x%ft===0&&n(` parsing: ${x}/${t.length} files (${y} from cache)`),m[x]=on(t[x],l));for(let x=0;x<t.length;x++){let _=m[x],F=t[x];_.kind==="hit"?y++:h++,_.kind==="skipped"?(u.push({filePath:F,reason:_.msg}),console.warn(` ! Skipped ${F}: ${_.msg}`)):_.kind==="failed"&&(p++,console.warn(` ! Failed to parse ${F}: ${_.msg}`)),c.set(F,_.plain),m[x]=null}return console.log(`Parsed ${c.size} files (${p} failed)`),console.log(` parse cache: ${h} file(s) parsed, ${y} served from cache`),c.cacheStats={parsed:h,cacheHits:y},c.budgetSkips=u,c}export{pn as a,un as b,me as c,k as d,Dn as e,on as f,gr as g};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "canopy-engine",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "type": "module",
5
5
  "description": "Canopy: a map of what a JavaScript / TypeScript codebase does - entry points, call flows and services, drawn from the code itself.",
6
6
  "keywords": [
@@ -45,7 +45,7 @@
45
45
  },
46
46
  "scripts": {
47
47
  "start": "node src/cli.js",
48
- "test": "node test/regression.js && node test/ids.js && node test/bodyhash.js",
48
+ "test": "node test/regression.js && node test/ids.js && node test/bodyhash.js && node test/this-calls.js && node test/telemetry.js",
49
49
  "build:ui": "node scripts/build-ui.js",
50
50
  "snapshot": "node test/snapshot.js",
51
51
  "audit:completeness": "node tools/auditCompleteness.js",
@@ -60,6 +60,7 @@
60
60
  "test:snapshots": "node test/snapshots.js",
61
61
  "test:readme": "node test/readme.js",
62
62
  "test:services": "node test/services.js",
63
+ "test:this-calls": "node test/this-calls.js",
63
64
  "test:dogfood": "node test/dogfood.js",
64
65
  "prepack": "node scripts/build-ui.js && node scripts/vendor-grammars.js && node scripts/build.js",
65
66
  "test:installed-ui": "node test/installed-ui.js",
@@ -1,7 +0,0 @@
1
- import{fileURLToPath as __cf,pathToFileURL as __cu}from"node:url";import{dirname as __cd,join as __cj}from"node:path";import{createRequire as __cr}from"node:module";
2
- const require=__cr(import.meta.url);
3
- globalThis.__canopyBundle??=__cj(__cd(__cf(import.meta.url)),"canopy.js");
4
- globalThis.__canopyUrl??=(r)=>__cu(__cj(__cd(__cd(globalThis.__canopyBundle)),r)).href;
5
- import{b as $,c as le}from"./chunk-ZF5SEDQB.js";import{Parser as Q,Language as de}from"web-tree-sitter";import D from"node:path";import{fileURLToPath as xt}from"node:url";var ln=D.dirname(xt(globalThis.__canopyUrl("src/stage2_parse/initParser.js")));var X=new WeakMap,M=t=>X.get(t)??"javascript",T=t=>M(t)!=="javascript";function q(t){let e=D.extname(t);return e===".tsx"?"tsx":e===".ts"||e===".mts"||e===".cts"?"typescript":"javascript"}var _t={typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm"};async function dn(t,e){for(let r of new Set(e.map(q))){if(t.grammars.has(r))continue;let o=D.join($("tree-sitter-typescript"),_t[r]),n=await de.load(o);X.set(n,r);let i=new Q;i.setLanguage(n),t.grammars.set(r,{parser:i,language:n})}return t}async function pn(){await Q.init();let t=new Q,e=D.join($("tree-sitter-javascript"),"tree-sitter-javascript.wasm"),r=await de.load(e);return t.setLanguage(r),X.set(r,"javascript"),{parser:t,language:r,grammars:new Map([["javascript",{parser:t,language:r}]])}}import E from"node:fs";import w from"node:path";import Ft from"node:os";import ue from"node:crypto";import{threadId as gt}from"node:worker_threads";import{fileURLToPath as Nt}from"node:url";var Ct=w.dirname(Nt(globalThis.__canopyUrl("src/stage2_parse/parseCache.js"))),fe=w.join(Ct,"..",".."),ee=process.env.CANOPY_CACHE_DIR||(le()?w.join(Ft.homedir(),".canopy-cache"):w.join(fe,".canopy-cache")),pe=t=>ue.createHash("sha256").update(t).digest("hex");function G(t,e){return E.readdirSync(t,{withFileTypes:!0}).flatMap(r=>r.isDirectory()?G(w.join(t,r.name),e):e.some(o=>r.name.endsWith(o))?[w.join(t,r.name)]:[]).sort()}var te=null;function wt(){if(te)return te;let t=w.join(fe,"src"),e=!E.existsSync(t)&&globalThis.__canopyBundle,r=e?E.readdirSync(w.dirname(e)).filter(i=>i.endsWith(".js")).sort().map(i=>w.join(w.dirname(e),i)):[],o=e?[...r,...G(w.join(w.dirname(e),"queries"),[".scm"])]:[...G(w.join(t,"stage2_parse"),[".js",".scm"]),...G(w.join(t,"stage5_entrypoints"),[".js"]).filter(i=>/match/i.test(w.basename(i))),w.join(t,"utils","loadQuery.js")],n=ue.createHash("sha256");for(let i of o)n.update(w.relative(e?w.dirname(e):t,i).split(w.sep).join("/")).update("\0").update(E.readFileSync(i).toString("utf8").replace(/\r\n/g,`
6
- `)).update("\0");for(let i of["web-tree-sitter","tree-sitter-javascript","tree-sitter-typescript"])try{n.update(i+"@"+JSON.parse(E.readFileSync(w.join($(i),"package.json"),"utf8")).version)}catch{n.update(i+"@?")}return te=n.digest("hex").slice(0,16)}function me({prune:t=!0}={}){let e=wt(),r=w.join(ee,e);if(E.mkdirSync(r,{recursive:!0}),t)for(let o of E.readdirSync(ee,{withFileTypes:!0}))o.isDirectory()&&o.name!==e&&E.rmSync(w.join(ee,o.name),{recursive:!0,force:!0});return{version:e,keyFor:(o,n="javascript")=>pe(n==="javascript"?o:Buffer.concat([Buffer.from(n+"\0"),o])),get(o){try{return JSON.parse(E.readFileSync(w.join(r,o+".json"),"utf8"))}catch{return null}},set(o,n){let i=w.join(r,`${o}.${process.pid}.${gt}.tmp`);E.writeFileSync(i,JSON.stringify(n)),E.renameSync(i,w.join(r,o+".json"))}}}function he(t){return JSON.parse(JSON.stringify(t,(e,r)=>r&&typeof r=="object"&&r.startPosition&&r.endPosition&&"type"in r&&"tree"in r?void 0:r))}import kt from"node:fs";function Fe(t,e){let r=kt.readFileSync(e,"utf-8"),o=t.parse(r);if(ne(o)||r.includes("\0")){let n=r,i=_e(o);for(let s of bt){let a=s.apply(n);if(a===n)continue;let c=t.parse(a),p=_e(c);if(p<i||s.always){try{o.delete()}catch{}n=a,o=c,i=p}else try{c.delete()}catch{}}n!==r&&(o.canopyOriginalSource=r)}return{tree:o,source:r,filePath:e}}var ge=t=>t.replace(/[^\n]/g," "),ye=t=>"any"+ge(t).slice(3),xe=/(?<![&])&(?![&=])/g,bt=[{name:"NUL byte",always:!0,apply:t=>t.replace(/\0/g," ")},{name:"export type * from",apply:t=>t.replace(/\bexport\s+type\s+\*\s*(?:as\s+[\w$]+\s+)?from\s*(["'])[^"'\n]*\1\s*;?/g,ge)},{name:"typeof import()",apply:t=>t.replace(/typeof\s+import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)*/g,ye)},{name:"import().Type",apply:t=>t.replace(/(?<=[:<,|&?]\s*|\breadonly\s+|\bkeyof\s+|\bextends\s+|\bas\s+)import\s*\(\s*(["'])[^"'\n]*\1\s*\)(?:\s*\.\s*[\w$]+)+(?!\s*\()/g,ye)},{name:"generic call signature after a member",apply:t=>t.replace(/(?<=\n[ \t]*)[ ](?=<\s*[A-Za-z_$][\w$]*\s*(?:extends\b|=|,|>\s*\())/g,";")},{name:"& in JSX text",apply:t=>t.replace(/>[^<>{}"'`]*&[^<>{}"'`]*</g,e=>e.replace(xe,"+"))},{name:"& in JSX attribute",apply:t=>t.replace(/(\s[\w:-]+=)"([^"\n]*)"/g,(e,r,o)=>r+'"'+o.replace(xe,"+")+'"')}];function _e(t){let e=0;return(function r(o){if(o.type==="ERROR"){e++;return}for(let n=0;n<o.childCount;n++)r(o.child(n))})(t.rootNode),e}function ne(t){let e=!1;function r(o){if(o.type==="ERROR"){e=!0;return}for(let n=0;n<o.childCount;n++)r(o.child(n))}return r(t.rootNode),e}import re from"node:fs";import B from"node:path";import{fileURLToPath as St}from"node:url";import{Query as vt}from"web-tree-sitter";var Ne=B.dirname(St(globalThis.__canopyUrl("src/utils/loadQuery.js"))),Ce=new WeakMap;function k(t,e){let r=Ce.get(t);if(r||Ce.set(t,r=new Map),r.has(e))return r.get(e);let o=B.join(Ne,"..","stage2_parse","queries"),n=re.existsSync(o)?o:B.join(Ne,"..","..","dist","queries"),i=M(t),c=(i==="javascript"?[]:i==="tsx"?["tsx","typescript"]:[i]).map(h=>B.join(n,h,e)).find(h=>re.existsSync(h))??B.join(n,e),p=re.readFileSync(c,"utf-8"),m=new vt(t,p);return r.set(e,m),m}var we="javascript",ke=t=>{we=t};var K=()=>we!=="javascript";var Et=new Set(["non_null_expression","as_expression","satisfies_expression","type_assertion"]);function S(t){for(;t;)if(Et.has(t.type))t=t.type==="type_assertion"?t.namedChild(t.namedChildCount-1):t.namedChild(0);else if(t.type==="parenthesized_expression"&&t.namedChildCount===1){let e=S(t.namedChild(0));if(e===t.namedChild(0))break;t=e}else break;return t}function jt(t){let e=t;for(;e;){e=S(e);for(let r=0;r<e.childCount;r++)if(e.child(r).type==="optional_chain")return!0;if(e.type==="member_expression"||e.type==="subscript_expression")e=e.childForFieldName("object");else if(e.type==="call_expression")e=e.childForFieldName("function");else break}return!1}function L(t){let e=t.childForFieldName("function"),r=t.childForFieldName("arguments");if(!e)return{kind:"callOfCall",oldShape:!1,nameNode:t};let o=e.type==="identifier",n=e.type==="member_expression"?e.childForFieldName("property"):null,i=e.type==="member_expression"?S(e.childForFieldName("object")):null,s=o||i?.type==="identifier"&&n?.type==="property_identifier",a=n??e;if(K()&&t.parent?.type==="decorator")return{kind:"decorator",oldShape:s,nameNode:a};if(r&&r.type==="template_string")return{kind:"taggedTemplate",oldShape:s,nameNode:a};if(jt(t))return{kind:"optionalCall",oldShape:s,nameNode:a};if(o)return{kind:"call",oldShape:s,nameNode:a};if(e.type==="subscript_expression")return{kind:"computed",oldShape:!1,nameNode:e};if(e.type==="member_expression")return i.type==="super"?{kind:"super",oldShape:!1,nameNode:a}:i.type==="this"?{kind:"thisCall",oldShape:!1,nameNode:a}:s?{kind:"methodCall",oldShape:!0,nameNode:a}:{kind:"chainedCall",oldShape:!1,nameNode:a};if(e.type==="import")return{kind:"dynamicImport",oldShape:!1,nameNode:e};if(e.type==="super")return{kind:"super",oldShape:!1,nameNode:e};let c=e;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:e}:{kind:"callOfCall",oldShape:!1,nameNode:e}}function be(t){let e=t.childForFieldName("name");return e?e.type==="identifier"?/^[A-Z]/.test(e.text)?{kind:"jsx",oldShape:!0,nameNode:e}:null:e.type==="member_expression"||e.type==="nested_identifier"?{kind:"jsxMember",oldShape:!1,nameNode:e}:null:null}function z(t){let e=t;for(;e&&e.type!=="call_expression";)e=e.parent;return e}function Se(t){let e=t.childForFieldName("function"),r=!1;for(;e;)if(e=S(e),e.type==="member_expression"||e.type==="subscript_expression")e=e.childForFieldName("object");else if(e.type==="call_expression")r=!0,e=e.childForFieldName("function");else if(e.type==="await_expression"||e.type==="parenthesized_expression"||e.type==="non_null_expression")e=e.namedChild(0);else break;return e&&e.type==="identifier"?{head:e.text,called:r}:{head:null,called:!1}}function ve(t){let e=t.text.replace(/\s+/g," ");return e.length>120?e.slice(0,117)+"...":e}function je(t,e){let n=k(e,"functionDeclarations.scm").matches(t.rootNode).map(i=>{let s=i.captures.find(p=>p.name==="func_name"),a=i.captures.find(p=>p.name==="func_params"),c=i.captures.find(p=>p.name==="func_declaration");return{name:s.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:s.node}});return T(e)&&n.push(...Pt(t,e)),n}function Pt(t,e){return k(e,"defaultExports.scm").matches(t.rootNode).map(r=>{let o=r.captures.find(i=>i.name==="func_declaration").node;return{name:"default",params:r.captures.find(i=>i.name==="func_params").node.text,startLine:o.startPosition.row+1,endLine:o.endPosition.row+1,startIndex:o.startIndex,endIndex:o.endIndex,node:o}})}function Pe(t,e){return k(e,"arrowFunctions.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(c=>c.name==="func_name"),s=n.captures.find(c=>c.name==="func_params"),a=n.captures.find(c=>c.name==="func_declaration");return{name:i.node.text,params:s.node.text,startLine:a.node.startPosition.row+1,endLine:a.node.endPosition.row+1,startIndex:a.node.startIndex,endIndex:a.node.endIndex,node:i.node}})}function Te(t,e){let o=k(e,"classMethods.scm").matches(t.rootNode),n=T(e);return o.map(i=>{let s=i.captures.find(h=>h.name==="class_name"),a=i.captures.find(h=>h.name==="method_name"),c=i.captures.find(h=>h.name==="method_params"),p=i.captures.find(h=>h.name==="method_declaration"),m=p.node;if(n)for(let h=m.previousNamedSibling;h&&h.type==="decorator";h=h.previousNamedSibling)m=h;return{className:s?s.node.text:"default",methodName:a.node.text,params:c.node.text,startLine:m.startPosition.row+1,endLine:p.node.endPosition.row+1,startIndex:m.startIndex,endIndex:p.node.endIndex,node:a.node}})}function Le(t,e){let o=k(e,"imports.scm").matches(t.rootNode),n=T(e);return o.filter(i=>!(n&&Tt(i.captures[0].node))).map(i=>{let s=i.captures[0].node;return{source:s.text,startLine:s.startPosition.row+1}})}function Tt(t){let e=t;for(;e&&e.type!=="import_statement";)e=e.parent;if(!e)return!1;if(e.children.some(i=>i.type==="type"))return!0;let r=e.namedChildren.find(i=>i.type==="import_clause");if(!r)return!1;let o=r.namedChildren;if(o.length!==1||o[0].type!=="named_imports")return!1;let n=o[0].namedChildren.filter(i=>i.type==="import_specifier");return n.length>0&&n.every(i=>i.children.some(s=>s.type==="type"))}function W(t){let e=t;for(;e&&e.type!=="call_expression"&&e.type!=="new_expression";)e=e.parent;if(!e)return null;let r=e.childForFieldName("arguments");if(!r)return null;let o=r.namedChildren?.[0];return!o||o.type==="arrow_function"||o.type==="function_expression"?null:o.text}var Lt=/^(addEventListener|removeEventListener|on|once|postMessage|onmessage|subscribe)$/i;function R(t){let e=t;for(;e.parent;){let r=e.parent;if(r.type==="arrow_function"||r.type==="function_expression"){let o=r.parent;if(o&&(o.type==="variable_declarator"||o.type==="public_field_definition"))break;if(o&&o.type==="return_statement")return!0;if(o&&o.type==="arguments"&&o.parent?.type==="call_expression"){let n=o.parent.childForFieldName("function"),i=n?.type==="member_expression"?n.childForFieldName("property")?.text:n?.text;if(i&&Lt.test(i))return!0}}else if(r.type==="function_declaration"||r.type==="method_definition")break;e=r}return!1}function Ie(t,e){return k(e,"callExpressions.scm").matches(t.rootNode).map(n=>{let i=n.captures[0].node;return{calleeName:i.text,startLine:i.startPosition.row+1,startColumn:i.startPosition.column,branchPath:A(i),firstArgText:W(i),deferred:R(i),callKind:L(z(i)).kind}})}function Re(t,e){return T(e)?It(t):k(e,"methodCalls.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(a=>a.name==="object_name"),s=n.captures.find(a=>a.name==="method_name");return{objectName:i.node.text,methodName:s.node.text,startLine:s.node.startPosition.row+1,startColumn:s.node.startPosition.column,firstArgText:W(s.node),branchPath:A(s.node),deferred:R(s.node),callKind:L(z(s.node)).kind}})}function It(t){let e=[];for(let r of t.rootNode.descendantsOfType("call_expression")){let o=r.childForFieldName("function");if(!o||o.type!=="member_expression")continue;let n=S(o.childForFieldName("object")),i=o.childForFieldName("property");!n||n.type!=="identifier"||!i||i.type!=="property_identifier"||e.push({objectName:n.text,methodName:i.text,startLine:i.startPosition.row+1,startColumn:i.startPosition.column,firstArgText:W(i),branchPath:A(i),deferred:R(i),callKind:L(z(i)).kind})}return e}function Rt(t){if(!t)return"return";if(t.type==="object"){let e=t.namedChildren.filter(o=>o.type==="pair"),r=e.find(o=>o.childForFieldName("key")?.text?.replace(/^['"]|['"]$/g,"")==="type")??e.find(o=>o.childForFieldName("key")?.text?.replace(/^['"]|['"]$/g,"")==="entity");if(r){let o=r.childForFieldName("key"),n=r.childForFieldName("value");return`return { ${o.text}: ${n.text} }`}}return"return "+t.text.split(/\r?\n/)[0].trim()}function Ae(t,e){return k(e,"returns.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(c=>c.name==="return_statement"),s=n.captures.find(c=>c.name==="return_value"),a=i.node;return{label:Rt(s?.node),startLine:a.startPosition.row+1,startColumn:a.startPosition.column,branchPath:A(a),deferred:R(a)}})}var At=new Set(["function_declaration","arrow_function","function_expression","method_definition"]);function J(t,e){return!(!e||t.row<e.startPosition.row||t.row>e.endPosition.row||t.row===e.startPosition.row&&t.column<e.startPosition.column||t.row===e.endPosition.row&&t.column>e.endPosition.column)}function A(t){let e=[],r=t,o=t.startPosition;for(;r.parent;){let n=r.parent;if(At.has(n.type))break;if(n.type==="if_statement"){let i=n.childForFieldName("condition"),s=n.childForFieldName("consequence"),a=n.childForFieldName("alternative");J(o,s)?e.push({type:"if",conditionText:i?i.text:"",conditionLine:(i??n).startPosition.row+1,outcome:"true"}):J(o,a)&&e.push({type:"if",conditionText:i?i.text:"",conditionLine:(i??n).startPosition.row+1,outcome:"false"})}else if(n.type==="switch_case"||n.type==="switch_default"){let i=n.parent,s=i&&i.type==="switch_body"?i.parent:null;if(s){let a=s.childForFieldName("value"),c=n.childForFieldName("value");e.push({type:"switch",conditionText:a?a.text:"",conditionLine:(a??s).startPosition.row+1,outcome:n.type==="switch_default"?"default":c?c.text:"case"})}}else if(n.type==="try_statement"){let i=n.childForFieldName("handler"),s=n.childForFieldName("finalizer"),a="try";J(o,i)?a="catch":J(o,s)&&(a="finally"),e.push({type:"try",conditionText:"try / catch",conditionLine:n.startPosition.row+1,outcome:a})}r=n}return e.reverse()}function Oe(t,e){return k(e,"exports.scm").matches(t.rootNode).map(o=>o.captures[0].node.text)}var Ee=new WeakMap;function Ot(t,e){let r=Ee.get(t);return r||(r=k(e,"returns.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(a=>a.name==="return_statement"),s=n.captures.find(a=>a.name==="return_value");return{stmtNode:i.node,valueNode:s?.node}}),Ee.set(t,r)),r}function $e(t,e,r){return Ot(t,e).filter(o=>o.stmtNode.startPosition.row+1>=r.startLine&&o.stmtNode.endPosition.row+1<=r.endLine).map(o=>({shape:$t(o.valueNode),condition:Mt(o.stmtNode,r),line:o.stmtNode.startPosition.row+1}))}function $t(t){if(!t)return"nothing";switch(t.type){case"true":case"false":return"boolean";case"number":return"number";case"string":return"string";case"null":return"null";case"identifier":return`variable (${t.text})`;case"object":return"object";case"array":return"array";case"call_expression":return`result of ${t.text.split("(")[0]}()`;case"binary_expression":return"boolean (comparison)";case"ternary_expression":return"conditional value";default:return"expression"}}function Mt(t,e){let r=t.parent;for(;r;){if(r.type==="if_statement"){let o=r.childForFieldName("condition");if(o)return o.text}r=r.parent}return null}function Me(t,e){return M(e)==="typescript"?[]:k(e,"jsxElements.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(s=>s.name==="jsx_tag");return{calleeName:i.node.text,startLine:i.node.startPosition.row+1}}).filter(n=>/^[A-Z]/.test(n.calleeName))}function qe(t,e){return k(e,"fetchApiCalls.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(p=>p.name==="url"),s=n.captures.find(p=>p.name==="http_method"),a=i.node.text,c=/^https?:\/\//.test(a)?"external":"internal";return{url:a,method:s?.node.text??"get",startLine:i.node.startPosition.row+1,scope:c}})}function Be(t,e){return k(e,"socketEmit.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(s=>s.name==="event_name");return{eventName:i.node.text,startLine:i.node.startPosition.row+1}})}function We(t,e){return k(e,"rawSocketSend.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(s=>s.name==="event_name");return{eventName:i.node.text,startLine:i.node.startPosition.row+1}})}function Ue(t,e){return k(e,"rawSocketTypeCheck.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(s=>s.name==="event_name");return{eventName:i.node.text,startLine:i.node.startPosition.row+1}})}function He(t,e){return k(e,"socketOn.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(c=>c.name==="event_name"),s=n.captures.find(c=>c.name==="handler_ref"),a=n.captures.find(c=>c.name==="handler_inline");return{eventName:i.node.text,startLine:i.node.startPosition.row+1,handlerName:s?s.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 De(t){let e=t.rootNode.descendantsOfType(["call_expression","new_expression","jsx_opening_element","jsx_self_closing_element",...K()?["decorator"]:[]]),r=[];for(let o of e){let n,i,s,a=null,c=null,p=!1,m=null,h=null;if(o.type==="new_expression"){if(s=o.childForFieldName("constructor"),!s)continue;n="new",i=s,a=s.type==="identifier"?s.text:null;let d=o.childForFieldName("arguments")?.namedChildren?.[0];m=d&&d.type!=="arrow_function"&&d.type!=="function_expression"?d.text:null}else if(o.type==="decorator"){let F=o.namedChild(0);if(!F||F.type==="call_expression")continue;n="decorator",i=F.type==="member_expression"?F.childForFieldName("property")??F:F,s=F}else if(o.type==="call_expression"){let F=L(o);if(F.oldShape)continue;if(n=F.kind,i=F.nameNode,s=o.childForFieldName("function")??o,n==="chainedCall"){let d=Se(o);c=d.head,p=d.called;let u=o.childForFieldName("function"),l=u?.type==="member_expression"?S(u.childForFieldName("object")):null;l?.type==="member_expression"&&S(l.childForFieldName("object"))?.type==="this"&&l.childForFieldName("property")?.type==="property_identifier"&&u.childForFieldName("property")&&(h={thisProp:l.childForFieldName("property").text,thisMethod:u.childForFieldName("property").text})}m=W(i)}else{let F=be(o);if(!F||F.oldShape)continue;n=F.kind,i=F.nameNode,s=F.nameNode}r.push({callKind:n,calleeName:ve(s),startLine:i.startPosition.row+1,startColumn:i.startPosition.column,branchPath:A(i),firstArgText:m,deferred:R(i),chainHead:c,chainHeadCalled:p,ctorName:a,...h??{}})}return r.sort((o,n)=>o.startLine-n.startLine||o.startColumn-n.startColumn)}var oe=new Set(["get","post","put","patch","delete","head","options"]),ie=new Set(["axios","ky","got","superagent","$http"]),qt=new Set(["function_declaration","function_expression","function","arrow_function","method_definition","generator_function_declaration","generator_function"]),Bt=new Set(["WebSocket","ReconnectingWebSocket","SockJS","W3CWebSocket"]),se=/^(ws|socket|sock|websocket|webSocket|wsClient|socketRef|wsRef|[A-Za-z]+Socket|[A-Za-z]+Ws|[A-Za-z]+WebSocket)$/,C=t=>{for(;t&&(t.type==="parenthesized_expression"||t.type==="as_expression"||t.type==="non_null_expression"||t.type==="await_expression"||t.type==="satisfies_expression"||t.type==="type_assertion")&&(t=t.namedChildren.find(e=>e.type!=="type_annotation"&&e.type!=="predefined_type"&&!/_type$/.test(e.type))??t.namedChildren[0],!!t););return t},U=t=>t.namedChildren.length?t.namedChildren.filter(e=>e.type==="string_fragment"||e.type==="escape_sequence").map(e=>e.text).join(""):t.text.slice(1,-1);function O(t){for(let e=t.parent;e;e=e.parent)if(qt.has(e.type))return e;return null}function Ge(t){if(!t)return null;let e=t.childForFieldName("name")?.text??null;if(!e&&t.parent){let n=t.parent;n.type==="variable_declarator"?e=n.childForFieldName("name")?.text??null:n.type==="assignment_expression"?e=n.childForFieldName("left")?.text??null:n.type==="pair"&&(e=n.childForFieldName("key")?.text??null)}let r=[],o=t.childForFieldName("parameters");if(o)o.namedChildren.forEach((n,i)=>{let s=n.type==="identifier"?n:n.type==="assignment_pattern"?n.childForFieldName("left"):n.type==="required_parameter"||n.type==="optional_parameter"?n.childForFieldName("pattern")??n.namedChildren[0]:null;r[i]=s&&s.type==="identifier"?s.text:null});else{let n=t.childForFieldName("parameter");n&&n.type==="identifier"&&(r[0]=n.text)}return{name:e,params:r}}function Ke(t){let e=t.rootNode,r={httpCalls:[],pathCallsites:[],httpInstances:[],wsClients:[],wsServers:[],wsSends:[],wsServerSends:[],listens:[],wsReceivers:[]},o=new Map;for(let d of e.descendantsOfType("variable_declarator")){let u=d.childForFieldName("name"),l=d.childForFieldName("value");if(!u||u.type!=="identifier"||!l)continue;(o.get(u.text)??o.set(u.text,[]).get(u.text)).push({value:l,fn:O(d)})}let n=(d,u)=>{let l=o.get(d);if(!l)return null;for(let f=O(u);f;f=O(f)){let x=l.filter(_=>_.fn&&_.fn.id===f.id);if(x.length===1)return x[0].value}let y=l.filter(f=>!f.fn);return y.length===1?y[0].value:l.length===1?l[0].value:null},i=(d,u)=>{for(let l=O(u);l;l=O(l)){let f=Ge(l).params.indexOf(d);if(f>=0)return f}return-1};function s(d,u=0){if(d=C(d),!d)return[{t:"ref",name:""}];switch(d.type){case"string":return[{t:"lit",v:U(d)}];case"template_string":{let l=[];for(let y of d.namedChildren)y.type==="string_fragment"||y.type==="escape_sequence"?l.push({t:"lit",v:y.text}):y.type==="template_substitution"&&l.push(...s(y.namedChildren[0],u+1));return l.length?l:[{t:"lit",v:""}]}case"number":return[{t:"lit",v:d.text}];case"binary_expression":{let l=d.childForFieldName("operator")?.text;if(l==="||"||l==="??"){let y=s(d.childForFieldName("left"),u+1);if(y.length===1&&y[0].t==="env")return[{...y[0],fallback:s(d.childForFieldName("right"),u+1)}]}return l!=="+"?[{t:"ref",name:d.text.slice(0,60)}]:[...s(d.childForFieldName("left"),u+1),...s(d.childForFieldName("right"),u+1)]}case"shorthand_property_identifier":case"identifier":{let l=d.text,y=i(l,d);if(y>=0)return[{t:"param",name:l,index:y}];if(u<4){let f=n(l,d);if(f&&f.id!==d.id)return s(f,u+1)}return[{t:"ref",name:l}]}case"member_expression":{let l=d.text,y=/^(?:process\.env|import\.meta\.env)\.([A-Za-z0-9_$]+)$/.exec(l)??/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(l);return y?[{t:"env",name:y[1]}]:[{t:"ref",name:l.slice(0,60)}]}case"subscript_expression":{let l=/^(?:process\.env|import\.meta\.env)\[["']([^"']+)["']\]$/.exec(d.text);return l?[{t:"env",name:l[1]}]:[{t:"ref",name:d.text.slice(0,60)}]}case"call_expression":{let l=d.childForFieldName("function")?.text,y=d.childForFieldName("arguments")?.namedChildren[0];if(y&&(l==="encodeURIComponent"||l==="String"||l==="encodeURI"))return s(y,u+1);let f=C(d.childForFieldName("function"));if(f&&f.type==="member_expression"&&/^(replace|replaceAll|trim|trimEnd|trimStart|toString|toLowerCase)$/.test(f.childForFieldName("property")?.text??"")){let x=f.childForFieldName("object");if(x){let _=s(x,u+1);if(_.length&&_.every(g=>g.t!=="ref"))return _}}return[{t:"ref",name:d.text.slice(0,60)}]}default:return[{t:"ref",name:d.text.slice(0,60)}]}}let a=(d,u)=>{if(d=C(d),!(!d||d.type!=="object")){for(let l of d.namedChildren)if(l.type==="pair"){let y=l.childForFieldName("key");if((y?y.type==="string"?U(y):y.text:null)===u)return l.childForFieldName("value")}else if(l.type==="shorthand_property_identifier"&&l.text===u)return l}},c=d=>d.childForFieldName("arguments")?.namedChildren.filter(u=>u.type!=="comment")??[],p=d=>{if(!d)return null;let u=s(d);return u.length===1&&u[0].t==="lit"?u[0].v.toUpperCase():u.length===1&&u[0].t==="param"?{param:u[0].index}:"?"},m=(d,u,l,y)=>({client:d,method:u,parts:l,line:y.startPosition.row+1,fn:Ge(O(y))});for(let d of e.descendantsOfType("variable_declarator")){let u=d.childForFieldName("name"),l=C(d.childForFieldName("value"));if(!u||u.type!=="identifier"||!l||l.type!=="call_expression")continue;let y=C(l.childForFieldName("function"));if(!y||y.type!=="member_expression")continue;let f=y.childForFieldName("object")?.text,x=y.childForFieldName("property")?.text;if(!(ie.has(f)&&(x==="create"||x==="extend")))continue;let _=c(l)[0],g=a(_,"baseURL")??a(_,"baseUrl")??a(_,"prefixUrl")??a(_,"prefix_url");r.httpInstances.push({name:u.text,parts:g?s(g):[],line:d.startPosition.row+1})}let h=new Set(r.httpInstances.map(d=>d.name));for(let d of e.descendantsOfType("call_expression")){let u=C(d.childForFieldName("function"));if(!u)continue;let l=c(d),y=!1;if(u.type==="identifier"){let f=u.text;if(f==="fetch"&&l[0]){let x=C(l[0]);if(x&&x.type==="new_expression")continue;let _=a(l[1],"method");r.httpCalls.push(m("fetch",_?p(_):l[1]&&C(l[1])?.type!=="object"?"?":"GET",s(l[0]),d)),y=!0}else if((ie.has(f)||h.has(f))&&l[0]){let x=C(l[0]);if(x&&x.type==="object"){let _=a(x,"url");if(_){let g=a(x,"baseURL");r.httpCalls.push(m(h.has(f)?"inst:"+f:f,p(a(x,"method"))??"GET",[...g?s(g):[],...s(_)],d)),y=!0}}else r.httpCalls.push(m(h.has(f)?"inst:"+f:f,l[1]&&a(l[1],"method")?p(a(l[1],"method")):"GET",s(l[0]),d)),y=!0}else f==="io"&&l[0]&&(r.wsClients.push({client:"io",parts:s(l[0]),line:d.startPosition.row+1}),y=!0)}else if(u.type==="member_expression"){let x=u.childForFieldName("object")?.text??"",_=u.childForFieldName("property")?.text??"",g=ie.has(x)||h.has(x);if(g&&oe.has(_)&&l[0])r.httpCalls.push(m(h.has(x)?"inst:"+x:x,_.toUpperCase(),s(l[0]),d)),y=!0;else if(!g&&oe.has(_)&&/^[A-Za-z_$][\w$]*$/.test(x)&&l[0]&&(C(l[0])?.type==="string"||C(l[0])?.type==="template_string")){let N=s(l[0]);N[0]?.t==="lit"&&(N[0].v.startsWith("/")||/^https?:\/\//.test(N[0].v))&&(r.httpCalls.push(m("obj:"+x,_.toUpperCase(),N,d)),y=!0)}else if(g&&_==="request"&&l[0]){let N=a(l[0],"url");if(N){let b=a(l[0],"baseURL");r.httpCalls.push(m(h.has(x)?"inst:"+x:x,p(a(l[0],"method"))??"GET",[...b?s(b):[],...s(N)],d)),y=!0}}else if(_==="open"&&l.length>=2&&C(l[0])?.type==="string"&&/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/i.test(U(C(l[0]))))r.httpCalls.push(m("xhr",U(C(l[0])).toUpperCase(),s(l[1]),d)),y=!0;else if(x==="io"&&_==="connect"&&l[0])r.wsClients.push({client:"io",parts:s(l[0]),line:d.startPosition.row+1}),y=!0;else if(_==="listen"&&l[0]){let N=C(l[0]),b=N&&N.type==="object"?a(N,"port"):N;b&&r.listens.push({parts:s(b),line:d.startPosition.row+1}),y=!0}else if(_==="send"&&/^(client|conn|connection|peer)$/.test(x.replace(/^this./,"").split(".").pop())&&l[0]){let N=C(l[0]),b=!1;if(N&&N.type==="call_expression"&&N.childForFieldName("function")?.text==="JSON.stringify"){let v=c(N)[0];b=!!(v&&(a(v,"type")||a(v,"event"))&&C(a(v,"type")??a(v,"event"))?.type==="string")}b||r.wsServerSends.push({recv:x,line:d.startPosition.row+1}),y=!0}else if(_==="send"&&se.test(x.replace(/^this\./,"").replace(/\.current$/,"").split(".").pop())){let N=l[0]?C(l[0]):null,b=!1;if(N&&N.type==="call_expression"&&N.childForFieldName("function")?.text==="JSON.stringify"){let v=c(N)[0];b=!!(v&&(a(v,"type")||a(v,"event"))&&C(a(v,"type")??a(v,"event"))?.type==="string")}b||r.wsSends.push({recv:x,line:d.startPosition.row+1}),y=!0}}if(!y){let f=null;if(u.type==="identifier"?f=u.text:u.type==="member_expression"&&(f=u.childForFieldName("property")?.text??null),!f||oe.has(f)||l.length===0||l.length>6)continue;let x=[],_=!1;l.slice(0,5).forEach((g,N)=>{let b=C(g);if(!b||b.type!=="string"&&b.type!=="template_string")return;let v=s(b);x.push({i:N,parts:v});let j=v[0];j&&j.t==="lit"&&(j.v.startsWith("/")||/^https?:\/\//.test(j.v))&&j.v.length>1&&(_=!0)}),_&&r.pathCallsites.push({callee:f,args:x,line:d.startPosition.row+1})}}let F=d=>d.replace(/^this./,"").replace(/.current$/,"").split(".").pop();for(let d of e.descendantsOfType("assignment_expression")){let u=d.childForFieldName("left");if(!u||u.type!=="member_expression"||u.childForFieldName("property")?.text!=="onmessage"||!se.test(F(u.childForFieldName("object")?.text??"")))continue;let l=C(d.childForFieldName("right"));r.wsReceivers.push({line:d.startPosition.row+1,handlerName:l&&l.type==="identifier"?l.text:null})}for(let d of e.descendantsOfType("call_expression")){let u=C(d.childForFieldName("function"));if(!u||u.type!=="member_expression"||u.childForFieldName("property")?.text!=="addEventListener")continue;let l=c(d),y=l[0]&&C(l[0]);if(!y||y.type!=="string"||U(y)!=="message"||!se.test(F(u.childForFieldName("object")?.text??"")))continue;let f=l[1]&&C(l[1]);r.wsReceivers.push({line:d.startPosition.row+1,handlerName:f&&f.type==="identifier"?f.text:null})}for(let d of e.descendantsOfType("new_expression")){let u=C(d.childForFieldName("constructor"));if(!u)continue;let l=u.text,y=c(d);if(Bt.has(l)&&y[0])r.wsClients.push({client:l,parts:s(y[0]),line:d.startPosition.row+1});else if(/^(WebSocketServer|WebSocket\.Server|WebSocket\.WebSocketServer|ws\.Server|ws\.WebSocketServer|Server)$/.test(l)){if(l==="Server"&&!/socket\.io|socketio/i.test(t.rootNode.text.slice(0,4e3)+""))continue;let f=a(y.find(x=>C(x)?.type==="object"),"path");r.wsServers.push({path:f?s(f):null,line:d.startPosition.row+1})}}return r}var Wt=new Set(["function_declaration","generator_function_declaration","function_expression","generator_function","arrow_function","method_definition"]),Ut=new Set(["arrow_function","function_expression","generator_function"]);function P(t,e){if(t)switch(t.type){case"identifier":case"shorthand_property_identifier_pattern":e.push(t.text);return;case"assignment_pattern":P(t.childForFieldName("left"),e);return;case"rest_pattern":case"object_pattern":case"array_pattern":case"pair_pattern":case"required_parameter":case"optional_parameter":for(let r of t.namedChildren)P(t.type==="pair_pattern"?t.childForFieldName("value"):r,e);return;default:if(t.type==="pattern"||t.namedChildCount){let r=t.childForFieldName?.("pattern");r&&P(r,e)}}}function Ht(t,e){let r=t;if(r.type==="export_statement"&&(r=r.childForFieldName("declaration")),!r)return null;if(r.type==="function_declaration"||r.type==="generator_function_declaration")return r.childForFieldName("name")?.text===e?{kind:"fn",declLine:r.startPosition.row+1}:null;if(r.type==="lexical_declaration"||r.type==="variable_declaration"){for(let o of r.namedChildren){if(o.type!=="variable_declarator")continue;let n=o.childForFieldName("name");if(n?.type==="identifier"){if(n.text!==e)continue;let s=S(o.childForFieldName("value"));return s&&Ut.has(s.type)?{kind:"fn",declLine:o.startPosition.row+1}:{kind:"other"}}let i=[];if(P(n,i),i.includes(e))return{kind:"other"}}return null}return(r.type==="class_declaration"||r.type==="abstract_class_declaration"||r.type==="enum_declaration")&&r.childForFieldName("name")?.text===e?{kind:"other"}:null}function Dt(t){let e=t.namedChildren.find(n=>n.type==="string")?.text.slice(1,-1)??null,r=t.namedChildren.find(n=>n.type==="import_clause"),o=[];if(!r||e==null)return{src:e,out:o};for(let n of r.namedChildren)if(n.type==="identifier")o.push({kind:"default",local:n.text,imported:null});else if(n.type==="namespace_import"){let i=n.namedChildren.find(s=>s.type==="identifier");i&&o.push({kind:"ns",local:i.text,imported:null})}else if(n.type==="named_imports")for(let i of n.namedChildren){if(i.type!=="import_specifier")continue;let s=i.childForFieldName("name"),a=i.childForFieldName("alias");s&&o.push({kind:"named",local:(a??s).text,imported:s.text})}return{src:e,out:o}}function ze(t){let e=[];for(let r of t.rootNode.namedChildren)if(r.type==="import_statement"){if(r.children.some(s=>s.type==="type"))continue;let o=r.namedChildren.find(s=>s.type==="import_require_clause");if(o){let s=o.namedChildren.find(c=>c.type==="identifier"),a=o.namedChildren.find(c=>c.type==="string");s&&a&&e.push({source:H(a),kind:"cjs",local:s.text,imported:null});continue}let{src:n,out:i}=Dt(r);for(let s of i)e.push({source:n,...s})}else if(r.type==="lexical_declaration"||r.type==="variable_declaration")for(let o of r.namedChildren){if(o.type!=="variable_declarator")continue;let n=S(o.childForFieldName("value")),i=null;n?.type==="member_expression"&&(i=n.childForFieldName("property")?.text??null,n=S(n.childForFieldName("object")));let s=Y(n);if(s==null)continue;let a=o.childForFieldName("name");if(a?.type==="identifier")e.push({source:s,kind:i?"named":"cjs",local:a.text,imported:i});else if(a?.type==="object_pattern"&&!i){for(let c of a.namedChildren)if(c.type==="shorthand_property_identifier_pattern")e.push({source:s,kind:"named",local:c.text,imported:c.text});else if(c.type==="pair_pattern"){let p=c.childForFieldName("key"),m=c.childForFieldName("value");p&&m?.type==="identifier"&&e.push({source:s,kind:"named",local:m.text,imported:p.text})}}}return e}var H=t=>t.namedChildren.filter(e=>e.type==="string_fragment").map(e=>e.text).join("");function Y(t){if(t?.type!=="call_expression")return null;let e=t.childForFieldName("function"),r=t.childForFieldName("arguments");if(e?.type!=="identifier"||e.text!=="require"||!r||r.namedChildCount!==1)return null;let o=r.namedChildren[0];return o.type==="string"?H(o):null}function Je(t){let e=[];return(function r(o){if(o.type==="export_statement"){let n=o.childForFieldName("source");n&&!o.children.some(i=>i.type==="type")&&e.push({source:H(n),startLine:n.startPosition.row+1})}else if(o.type==="import_require_clause"){let n=o.namedChildren.find(i=>i.type==="string");n&&e.push({source:H(n),startLine:n.startPosition.row+1})}else if(o.type==="call_expression"){let n=Y(o);n!=null&&e.push({source:n,startLine:o.startPosition.row+1})}for(let n of o.namedChildren)r(n)})(t.rootNode),e}function Ye(t){let e={default:null,named:{},reexports:[],stars:[],nsReexports:[]};for(let r of t.rootNode.namedChildren){if(r.type!=="export_statement")continue;let o=r.children.some(s=>s.type==="default"),n=r.childForFieldName("declaration"),i=r.childForFieldName("source")!=null;if(o){if(n){let s=n.childForFieldName("name");e.default=s&&(n.type==="function_declaration"||n.type==="generator_function_declaration"||n.type==="class_declaration"||n.type==="abstract_class_declaration")?s.text:"<anon>"}else{let s=S(r.childForFieldName("value"));e.default=s?.type==="identifier"?s.text:"<anon>"}continue}if(n){if(n.type==="function_declaration"||n.type==="generator_function_declaration"||n.type==="class_declaration"||n.type==="abstract_class_declaration"){let s=n.childForFieldName("name")?.text;s&&(e.named[s]=s)}else if(n.type==="lexical_declaration"||n.type==="variable_declaration")for(let s of n.namedChildren){let a=s.type==="variable_declarator"?s.childForFieldName("name"):null;a?.type==="identifier"&&(e.named[a.text]=a.text)}continue}if(i){if(r.children.some(p=>p.type==="type"))continue;let s=H(r.childForFieldName("source")),a=r.namedChildren.find(p=>p.type==="export_clause"),c=r.namedChildren.find(p=>p.type==="namespace_export");if(a)for(let p of a.namedChildren){if(p.type!=="export_specifier")continue;let m=p.childForFieldName("name")?.text,h=p.childForFieldName("alias")?.text;m&&e.reexports.push({exported:h??m,imported:m,source:s})}else if(c){let p=c.namedChildren.find(m=>m.type==="identifier");p&&e.nsReexports.push({exported:p.text,source:s})}else e.stars.push(s);continue}for(let s of r.namedChildren)if(s.type==="export_clause")for(let a of s.namedChildren){if(a.type!=="export_specifier")continue;let c=a.childForFieldName("name")?.text,p=a.childForFieldName("alias")?.text;c&&(p==="default"?e.default=c:e.named[p??c]=c)}}for(let r of t.rootNode.namedChildren){let o=r.type==="expression_statement"?r.namedChildren[0]:null;if(o?.type!=="assignment_expression")continue;let n=o.childForFieldName("left"),i=S(o.childForFieldName("right"));if(n?.type!=="member_expression")continue;let s=n.childForFieldName("object"),a=n.childForFieldName("property")?.text,c=p=>p?.type==="member_expression"&&p.childForFieldName("object")?.text==="module"&&p.childForFieldName("property")?.text==="exports";if(c(n))if(i?.type==="identifier")e.default=i.text;else if(i?.type==="object"){for(let p of i.namedChildren)if(p.type==="shorthand_property_identifier")e.named[p.text]=p.text;else if(p.type==="pair"){let m=p.childForFieldName("key"),h=S(p.childForFieldName("value"));m&&h?.type==="identifier"&&(e.named[m.text.replace(/^['"]|['"]$/g,"")]=h.text)}e.default??="<object>"}else Y(i)!=null?e.stars.push(Y(i)):e.default="<anon>";else a&&(s?.type==="identifier"&&s.text==="exports"||c(s))&&i?.type==="identifier"&&(e.named[a]=i.text)}return e}function Gt(t,e,r){for(let o=t.parent;o;o=o.parent)if(Wt.has(o.type)){let n=[],i=o.childForFieldName("parameters");if(i)for(let a of i.namedChildren)P(a,n);let s=o.childForFieldName("parameter");if(s&&P(s,n),o.type==="function_expression"||o.type==="generator_function"){let a=o.childForFieldName("name");a&&n.push(a.text)}if(n.includes(e))return{kind:"other"}}else if(o.type==="catch_clause"){let n=[];if(P(o.childForFieldName("parameter"),n),n.includes(e))return{kind:"other"}}else if(o.type==="for_in_statement"||o.type==="for_statement"){let n=[],i=o.type==="for_statement"?o.childForFieldName("initializer"):o.childForFieldName("left");if(i)if(i.type==="lexical_declaration"||i.type==="variable_declaration")for(let s of i.namedChildren)P(s.childForFieldName?.("name"),n);else P(i,n);if(n.includes(e))return{kind:"other"}}else if(o.type==="statement_block"||o.type==="program"||o.type==="switch_body"){if(o.type==="program"&&r.has(e))return{kind:"import",imp:r.get(e)};for(let n of o.namedChildren){let i=Ht(n,e);if(i)return i}if(o.type==="program"&&r.has(e))return{kind:"import",imp:r.get(e)}}return null}var Kt=t=>(t.childForFieldName("function")?.text??"").replace(/\s+/g," ").slice(0,40);function Ve(t,e){let r=new Map(e.map(i=>[i.local,i])),o=[],n=(i,s,a)=>{let c=S(i);if(!c||c.type!=="identifier"&&c.type!=="shorthand_property_identifier")return;let p=c.text,m=Gt(c,p,r);if(!m||m.kind==="other")return;let h=L(a).nameNode,F={name:p,line:c.startPosition.row+1,column:c.startPosition.column,via:s,callee:Kt(a),callLine:h.startPosition.row+1,callColumn:h.startPosition.column,b:m.kind};m.kind==="fn"?F.declLine=m.declLine:(F.src=m.imp.source,F.ik=m.imp.kind,F.imp=m.imp.imported),o.push(F)};return(function i(s){if(s.type==="call_expression"){let a=s.childForFieldName("arguments");for(let c of a?.namedChildren??[]){let p=S(c);if(p)if(p.type==="array")for(let m of p.namedChildren)n(m,"array",s);else if(p.type==="object")for(let m of p.namedChildren)m.type==="pair"?n(m.childForFieldName("value"),"object",s):m.type==="shorthand_property_identifier"&&n(m,"object",s);else n(p,"arg",s)}}for(let a of s.namedChildren)i(a)})(t.rootNode),o}function Ze(t){let e=[],r=n=>{let i=n?.namedChildren.find(s=>s.type!=="comment");return i?.type==="type_identifier"?i.text:null},o=n=>{let i=n.childForFieldName("name")?.text,s=n.childForFieldName("body");if(!(!i||!s)){for(let a of s.namedChildren)if(a.type==="public_field_definition"){let c=a.childForFieldName("name"),p=r(a.childForFieldName("type"));c?.type==="property_identifier"&&p&&e.push({className:i,prop:c.text,type:p})}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(h=>h.type==="accessibility_modifier")&&!c.children.some(h=>h.type==="readonly"))continue;let p=c.childForFieldName("pattern"),m=r(c.childForFieldName("type"));p?.type==="identifier"&&m&&e.push({className:i,prop:p.text,type:m})}}};for(let n of t.rootNode.namedChildren){let i=n.type==="export_statement"?n.childForFieldName("declaration"):n;i&&(i.type==="class_declaration"||i.type==="abstract_class_declaration")&&o(i)}return e}var zt={Get:"get",Post:"post",Put:"put",Patch:"patch",Delete:"delete",All:"all"};function Qe(t){let e=t.namedChildren[0];if(!e)return null;if(e.type==="call_expression"){let r=e.childForFieldName("function"),o=r?.type==="identifier"?r.text:null;return o?{name:o,args:e.childForFieldName("arguments")}:null}return e.type==="identifier"?{name:e.text,args:null}:null}var I=t=>t?t.type==="string"?t.namedChildren.filter(e=>e.type==="string_fragment").map(e=>e.text).join(""):t.type==="template_string"&&!t.namedChildren.some(e=>e.type==="template_substitution")?t.text.slice(1,-1):null:null;function Xe(t){let e=t?.namedChildren.find(r=>r.type!=="comment");if(!e)return"";if(e.type==="array")return I(e.namedChildren.find(r=>r.type!=="comment"))??"";if(e.type==="object"){for(let r of e.namedChildren){if(r.type!=="pair")continue;let o=r.childForFieldName("key");if(o?.text==="path"||o?.text==="'path'"||o?.text==='"path"'){let n=r.childForFieldName("value");return(n?.type==="array"?I(n.namedChildren[0]):I(n))??""}}return""}return I(e)??""}var V=(...t)=>"/"+t.map(r=>String(r??"").replace(/^\/+|\/+$/g,"")).filter(Boolean).join("/");function et(t){let e=[],r=(o,n)=>{let i=o.childForFieldName("name")?.text,s=o.childForFieldName("body");if(!i||!s)return;let c=[...n,...o.namedChildren.filter(h=>h.type==="decorator")].map(Qe).filter(Boolean).find(h=>h.name==="Controller");if(!c)return;let p=Xe(c.args),m=[];for(let h of s.namedChildren)if(h.type!=="comment"){if(h.type==="decorator"){m.push(h);continue}if(h.type==="method_definition"){let F=h.childForFieldName("name")?.text;for(let d of m.map(Qe).filter(Boolean)){let u=zt[d.name];!u||!F||e.push({method:u,path:V(p,Xe(d.args)),startLine:h.startPosition.row+1,handlerName:null,isInlineHandler:!1,handlerStartLine:null,handlerEndLine:null,handlerStartIndex:null,handlerEndIndex:null,nest:{className:i,methodName:F}})}}m=[]}};for(let o of t.rootNode.namedChildren)if(o.type==="export_statement"){let n=o.childForFieldName("declaration");n&&(n.type==="class_declaration"||n.type==="abstract_class_declaration")&&r(n,o.namedChildren.filter(i=>i.type==="decorator"))}else(o.type==="class_declaration"||o.type==="abstract_class_declaration")&&r(o,[]);return e}function tt(t){let e=[];return(function r(o){if(o.type==="call_expression"){let n=o.childForFieldName("function");if(n?.type==="member_expression"&&n.childForFieldName("property")?.text==="setGlobalPrefix"){let i=(o.childForFieldName("arguments")?.namedChildren??[]).filter(p=>p.type!=="comment"),s=i[0]?I(i[0]):null,a=[],c=i[1];if(c?.type==="object")for(let p of c.namedChildren){if(p.type!=="pair"||p.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")!=="exclude")continue;let m=p.childForFieldName("value");for(let h of m?.type==="array"?m.namedChildren:[])if(h.type==="object"){for(let F of h.namedChildren)if(F.type==="pair"&&F.childForFieldName("key")?.text.replace(/^['"]|['"]$/g,"")==="path"){let d=I(F.childForFieldName("value"));d!=null&&a.push(d)}}else{let F=I(h);F!=null&&a.push(F)}}e.push({prefix:s||null,exclude:a})}}for(let n of o.namedChildren)r(n)})(t.rootNode),e}function Hn(t){let e=[];for(let i of t.values())for(let s of i?.globalPrefix??[])e.push(s);if(!e.length||e.some(i=>!i.prefix||i.prefix!==e[0].prefix))return t;let r=e[0].prefix,o=new Set(e.flatMap(i=>i.exclude).map(i=>V(i))),n=new Map;for(let[i,s]of t){if(!s?.routes?.some(a=>a.nest)){n.set(i,s);continue}n.set(i,{...s,routes:s.routes.map(a=>a.nest&&!o.has(V(a.path))?{...a,path:V(r,a.path)}:a)})}return n}import Jt from"node:crypto";var nt=t=>Jt.createHash("sha256").update(t).digest("hex");function Yt(t,e=null){let r=[],o=n=>{if(n.childCount===0){if(n.type==="comment")return;let i=e?e.slice(n.startIndex,n.endIndex):n.text,s=n.type==="jsx_text"?i.replace(/\s+/g," ").trim():i;if(s==="")return;r.push({s:n.startIndex,e:n.endIndex,t:s});return}for(let i=0;i<n.childCount;i++)o(n.child(i))};return o(t),r}function rt(t,e){let r=[];for(let i of[e.functions,e.arrowFunctions,e.classMethods])for(let s of i??[])s.startIndex!=null&&r.push({s:s.startIndex,e:s.endIndex,item:s,field:"bodyHash"});for(let i of[e.routes,e.listeners,e.socketListeners])for(let s of i??[])s.isInlineHandler&&s.handlerStartIndex!=null&&r.push({s:s.handlerStartIndex,e:s.handlerEndIndex,item:s,field:"handlerBodyHash"});let o=new Map(r.map(i=>[i,[]])),n=[];for(let i of Yt(t.rootNode,t.canopyOriginalSource??null)){let s=null,a=1/0;for(let c of r)i.s>=c.s&&i.e<=c.e&&c.e-c.s<a&&(s=c,a=c.e-c.s);(s?o.get(s):n).push(i.t)}for(let i of r)i.item[i.field]=nt(o.get(i).join(" "));e.moduleBodyHash=nt(n.join(" "))}function ot(t,e){return k(e,"matchFastifyRoutes.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(p=>p.name==="http_method"),s=n.captures.find(p=>p.name==="route_path"),a=n.captures.find(p=>p.name==="handler_ref"),c=n.captures.find(p=>p.name==="handler_inline");return{method:i.node.text,path:s.node.text,startLine:i.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 it(t,e){return k(e,"matchExtensionListeners.scm").matches(t.rootNode).map(n=>{let i=n.captures.find(u=>u.name==="event_type"),s=n.captures.find(u=>u.name==="event_name"),a=n.captures.find(u=>u.name==="method_name"||u.name==="listener_method"),c=n.captures.find(u=>u.name==="handler_ref"),p=n.captures.find(u=>u.name==="target"),m=n.captures.find(u=>u.name==="root_object"),h=n.captures.find(u=>u.name==="sub_object"),F=p?p.node.text:m?m.node.text+(h?"."+h.node.text:""):null,d=n.captures.find(u=>u.name==="handler_inline");return{eventName:i?.node.text??s?.node.text??"unknown",targetName:F,startLine:a.node.startPosition.row+1,handlerName:c?c.node.text:null,isInlineHandler:!!d,handlerStartLine:d?d.node.startPosition.row+1:null,handlerEndLine:d?d.node.endPosition.row+1:null,handlerStartIndex:d?d.node.startIndex:null,handlerEndIndex:d?d.node.endIndex:null}})}import nn from"node:fs";import st from"node:os";import at from"node:path";import Vt from"node:v8";import{Worker as Zt}from"node:worker_threads";import{fileURLToPath as Qt}from"node:url";var ct=500,lt=8,Xt=24,en=150;function dt({files:t,env:e=process.env,cpus:r=st.cpus().length,totalMb:o=Math.round(st.totalmem()/1048576),heapLimitMb:n=Math.round(Vt.getHeapStatistics().heap_size_limit/1048576)}={}){if(e.CANOPY_WORKERS!==void 0&&e.CANOPY_WORKERS!==""){let a=Number(e.CANOPY_WORKERS);return!Number.isInteger(a)||a<0?{workers:0,why:"CANOPY_WORKERS is not a whole number: one file at a time"}:a===0?{workers:0,why:"CANOPY_WORKERS=0: one file at a time"}:{workers:Math.min(a,lt),why:`CANOPY_WORKERS=${a}`}}if(t<en)return{workers:0,why:"a small project: one file at a time"};let i=Math.min(Math.floor(n*.6/ct),Math.floor(o*.5/ct)),s=Math.min(r-1,lt,i);return s>=2?{workers:s,why:`${s} workers (${r} cpus, ${o} MB)`}:{workers:0,why:`not enough spare cpus or memory for threads (${r} cpus, ${o} MB)`}}function tn(){return globalThis.__canopyBundle?globalThis.__canopyBundle:at.join(at.dirname(Qt(globalThis.__canopyUrl("src/stage2_parse/parallelParse.js"))),"..","cli.js")}function pt(t,{workers:e,noCache:r,onBatch:o=()=>{},entry:n=tn()}){return new Promise(i=>{let s=new Array(t.length),a=[...new Set(t.map(q))],c=0,p=0,m=!1,h=null,F=e,d=[],u=[],l=()=>{if(!m){m=!0;for(let x of u)try{x.terminate()}catch{}i({outcomes:s,failed:h})}},y=x=>{if(m||h)return;if(c>=t.length){p>=t.length&&l();return}let _=[];for(;_.length<Xt&&c<t.length;)_.push({i:c,filePath:t[c]}),c++;x.busy=_,x.postMessage({type:"batch",items:_})},f=x=>{h||(h=x),l()};for(let x=0;x<e;x++){let _;try{_=new Zt(n,{workerData:{canopyParseWorker:!0,grammarKeys:a,noCache:r},resourceLimits:{maxOldGenerationSizeMb:1024,stackSizeMb:8},execArgv:[],env:process.env})}catch(g){f(`could not start a worker thread (${g?.message??g})`);return}_.busy=null,u.push(_),_.on("message",g=>{if(g.type==="ready"){y(_);return}if(g.type==="done"){for(let N of g.results)s[N.i]=N.outcome;p+=g.results.length,_.busy=null,o(p),p>=t.length?l():y(_);return}g.type==="fatal"&&f(g.message)}),_.on("error",g=>f(`a worker stopped (${String(g?.message??g).split(`
7
- `)[0].slice(0,160)})`)),_.on("exit",g=>{F--,d.push(g),!m&&(_.busy?f(`a worker ended early (exit code ${g})`):F<=0&&f("every worker ended before the files were done (exit codes "+d.join(", ")+")"))})}})}var mt=Number(process.env.CANOPY_PARSE_BUDGET_MS)||3e4,ce=class extends Error{constructor(e){super(`parse time budget exceeded (limit ${mt/1e3} s; stopped after ${(e/1e3).toFixed(1)} s)`),this.name="ParseBudgetError"}},ut=100;function ae(t,e,r){return t.map(o=>({...o,returns:$e(e,r,o)}))}var ft=()=>({functions:[],arrowFunctions:[],classMethods:[],imports:[],calls:[],methodCalls:[],returnEntries:[],jsxElements:[],callSites:[],apiCalls:[],socketEmits:[],socketListeners:[],rawSocketSends:[],rawSocketTypeChecks:[],routes:[],listeners:[]});function rn(t,e){let{store:r,readCache:o,parser:n,language:i,grammars:s}=e;{let a=null;try{let c=nn.readFileSync(t),p=q(t),m=r?.keyFor(c,p),h=r&&o?r.get(m):null;if(h)return{kind:"hit",plain:h};let F=performance.now(),d=()=>{let j=performance.now()-F;if(j>mt)throw new ce(j)},u=p==="javascript"?{parser:n,language:i}:s?.get(p);if(!u)throw new Error(`no ${p} grammar loaded`);let l=u.language;ke(p),a=Fe(u.parser,t).tree,d();let y=[],f=(j,ht,yt=[])=>{try{return ht()}catch(Z){if(Z.name==="ParseBudgetError")throw Z;return y.push({extractor:j,message:String(Z.message).slice(0,160)}),yt}},x=f("functionDeclarations",()=>ae(je(a,l),a,l));d();let _=f("arrowFunctions",()=>ae(Pe(a,l),a,l));d();let g=f("classMethods",()=>ae(Te(a,l),a,l));d();let N=f("importBindings",()=>ze(a)),b={functions:x,arrowFunctions:_,classMethods:g,imports:f("imports",()=>[...Le(a,l),...Je(a)]),calls:(d(),f("calls",()=>Ie(a,l))),methodCalls:(d(),f("methodCalls",()=>Re(a,l))),returnEntries:f("returnEntries",()=>Ae(a,l)),jsxElements:f("jsxElements",()=>Me(a,l)),callSites:(d(),f("callSites",()=>De(a))),apiCalls:(d(),f("apiCalls",()=>qe(a,l))),socketEmits:f("socketEmits",()=>Be(a,l)),socketListeners:f("socketListeners",()=>He(a,l)),rawSocketSends:f("rawSocketSends",()=>We(a,l)),rawSocketTypeChecks:f("rawSocketTypeChecks",()=>Ue(a,l)),routes:f("routes",()=>[...ot(a,l),...T(l)?et(a):[]]),listeners:f("listeners",()=>it(a,l)),refArgs:f("refArgs",()=>Ve(a,N)),globalPrefix:f("globalPrefix",()=>tt(a)),importBindings:N,classProps:f("classProps",()=>T(l)?Ze(a):[]),httpClients:f("httpClients",()=>Ke(a),null),exportBindings:f("exportBindings",()=>Ye(a),null),hadErrors:ne(a),exportedNames:f("exports",()=>Oe(a,l)),failed:!1,warnings:y};f("bodyHash",()=>rt(a,b),null);let v=he(b);if(r)try{r.set(m,v)}catch{}return{kind:"parsed",plain:v}}catch(c){return c.name==="ParseBudgetError"?{kind:"skipped",msg:c.message,plain:{...ft(),hadErrors:!1,failed:!1,skipped:c.message}}:{kind:"failed",msg:c.message,plain:{...ft(),hadErrors:!0,failed:!0,errorMessage:c.message}}}finally{if(a){try{a.delete()}catch{}a=null}}}}async function Fr(t,e,r,{cache:o=!0,onProgress:n=console.log,grammars:i=null,noCache:s=!1,say:a=null}={}){let c=new Map,p=0,m=0,h=0,F=o?me():null,d=!s,u=[],l={store:F,readCache:d,parser:e,language:r,grammars:i},y=new Array(t.length),f=o?dt({files:t.length}):{workers:0,why:"no cache"};if(f.workers>=2){let x=a??n;x(` parsing on ${f.workers} threads`);let _=await pt(t,{workers:f.workers,noCache:s,onBatch:g=>{(g%ut<24||g===t.length)&&n(` parsing: ${g}/${t.length} files`)}});for(let g=0;g<_.outcomes.length;g++)y[g]=_.outcomes[g];_.failed&&x(` parsing on threads did not work (${_.failed}); the rest is parsed one file at a time`)}for(let x=0;x<t.length;x++)y[x]||(x>0&&x%ut===0&&n(` parsing: ${x}/${t.length} files (${h} from cache)`),y[x]=rn(t[x],l));for(let x=0;x<t.length;x++){let _=y[x],g=t[x];_.kind==="hit"?h++:m++,_.kind==="skipped"?(u.push({filePath:g,reason:_.msg}),console.warn(` ! Skipped ${g}: ${_.msg}`)):_.kind==="failed"&&(p++,console.warn(` ! Failed to parse ${g}: ${_.msg}`)),c.set(g,_.plain),y[x]=null}return console.log(`Parsed ${c.size} files (${p} failed)`),console.log(` parse cache: ${m} file(s) parsed, ${h} served from cache`),c.cacheStats={parsed:m,cacheHits:h},c.budgetSkips=u,c}export{dn as a,pn as b,me as c,k as d,Hn as e,rn as f,Fr as g};
@@ -1,5 +0,0 @@
1
- import{fileURLToPath as __cf,pathToFileURL as __cu}from"node:url";import{dirname as __cd,join as __cj}from"node:path";import{createRequire as __cr}from"node:module";
2
- const require=__cr(import.meta.url);
3
- globalThis.__canopyBundle??=__cj(__cd(__cf(import.meta.url)),"canopy.js");
4
- globalThis.__canopyUrl??=(r)=>__cu(__cj(__cd(__cd(globalThis.__canopyBundle)),r)).href;
5
- import N from"node:fs";import F from"node:os";import S from"node:path";import fe from"node:crypto";var v="https://eu.i.posthog.com/batch/",$="phc_Ah2MwhgAE7anjWnykv5G8waaifCEUHTnaPGzHMSgYKBK";var R={duration:["<5s","5-30s","30s-2m","2-10m","10m+"],files:["<500","500-2k","2k-10k","10k+"],services:["1","2-3","4-10","10+"],askDuration:["<10s","10-30s","30-90s","90s+"]},P=["sync_failed","memory","no_files","viewer_failed","update_failed","ai_failed","ai_not_installed","ai_not_logged_in","ai_timeout","other"],re=["ok","error"],oe=["ok","error","cancelled"],se=["vscode","path","env"],d="count",C={first_run:{},sync_completed:{duration_bucket:R.duration,files_bucket:R.files,services_bucket:R.services,result:re,error_code:P},viewer_opened:{},search_used:{count:d},workflow_opened:{count:d},ask_ai_used:{count:d,result:oe,claude_source:se,duration_bucket:R.askDuration},feedback_link_clicked:{count:d},update_toast_shown:{count:d},error:{error_code:P}},L=new Set(["search_used","workflow_opened","ask_ai_used","feedback_link_clicked","update_toast_shown"]),V=new Set(["search_used","workflow_opened","feedback_link_clicked","update_toast_shown"]),ie=["event","distinct_id (the random install id)","timestamp (UTC)","canopy_version","os","arch","node_major","editor"],ce=["win32","darwin","linux"],ae=["x64","arm64","ia32","arm"],ue=["vscode","cursor","other","none"];function O(t,o){let n=Number(o);if(!Number.isFinite(n)||n<0)return null;switch(t){case"duration":return n<5e3?"<5s":n<3e4?"5-30s":n<12e4?"30s-2m":n<6e5?"2-10m":"10m+";case"files":return n<500?"<500":n<2e3?"500-2k":n<1e4?"2k-10k":"10k+";case"services":return n<=1?"1":n<=3?"2-3":n<=10?"4-10":"10+";case"askDuration":return n<1e4?"<10s":n<3e4?"10-30s":n<9e4?"30-90s":"90s+";default:return null}}function w(t,o){let n=Object.hasOwn(C,t)?C[t]:null;if(!n)return null;let i={};if(o&&typeof o=="object")for(let[u,a]of Object.entries(o)){if(!Object.hasOwn(n,u))continue;let b=n[u];b===d?Number.isInteger(a)&&a>=0&&a<=1e6&&(i[u]=a):typeof a=="string"&&b.includes(a)&&(i[u]=a)}return i}function Y({version:t,platform:o,arch:n,nodeMajor:i,editor:u}){return{canopy_version:/^\d{1,3}\.\d{1,3}\.\d{1,3}(?:-[0-9A-Za-z.-]{1,20})?$/.test(String(t))?String(t):"unknown",os:ce.includes(o)?o:"other",arch:ae.includes(n)?n:"other",node_major:Number.isInteger(i)&&i>0&&i<1e3?i:0,editor:ue.includes(u)?u:"none"}}function K(t=process.env){return t.CURSOR_TRACE_ID||/cursor/i.test(String(t.TERM_PROGRAM??""))||t.CURSOR_AGENT?"cursor":t.VSCODE_PID||t.VSCODE_IPC_HOOK_CLI||String(t.TERM_PROGRAM??"").toLowerCase()==="vscode"?"vscode":t.TERM_PROGRAM&&/windsurf|zed|jetbrains/i.test(String(t.TERM_PROGRAM))?"other":"none"}function H(){let t=[`every event: ${ie.join(", ")}`];for(let[o,n]of Object.entries(C)){let i=Object.entries(n).map(([u,a])=>`${u}: ${a===d?"a whole number":a.join(" | ")}`);t.push(`${o}${i.length?" - "+i.join("; "):" - (no extra fields)"}`)}return t}var de=5*6e4,_e=2e3,pe=100,me=t=>t!==void 0&&t!==""&&!/^(0|false|no|off)$/i.test(String(t));function he({env:t=process.env,platform:o=process.platform,home:n=F.homedir()}={}){return o==="win32"?S.join(t.APPDATA||S.join(n,"AppData","Roaming"),"canopy","config.json"):S.join(t.XDG_CONFIG_HOME||S.join(n,".config"),"canopy","config.json")}function x(t=process.env){return me(t.DO_NOT_TRACK)?"DO_NOT_TRACK is set":/^(0|false|off|no)$/i.test(String(t.CANOPY_TELEMETRY??"x"))?"CANOPY_TELEMETRY=0":t.CI!==void 0&&t.CI!==""?"a CI environment variable is present":t.CANOPY_HOOK==="1"?"this is the commit hook's background sync":null}function ke({url:t=v,key:o=$,consentVersion:n=1,env:i=process.env,platform:u=process.platform,arch:a=process.arch,home:b=F.homedir(),version:G="unknown",fetchFn:D=globalThis.fetch,now:y=()=>Date.now(),nodeMajor:z=Number(process.versions.node.split(".")[0]),file:g=he({env:i,platform:u,home:b})}={}){let h=!!(t&&o&&/^https:\/\//.test(t)),f=new Map,_=[],p=null,A=()=>{try{let e=JSON.parse(N.readFileSync(g,"utf8"));return e&&typeof e=="object"?e:{}}catch{return{}}},B=e=>{try{return N.mkdirSync(S.dirname(g),{recursive:!0}),N.writeFileSync(g,JSON.stringify(e,null,2)),!0}catch{return!1}},m=()=>{let e=A();return{telemetry:e.telemetry==="on"?"on":e.telemetry==="off"?"off":null,choiceDate:e.choiceDate??null,consentVersion:Number.isInteger(e.consentVersion)?e.consentVersion:0,installId:/^[0-9a-f-]{36}$/.test(String(e.installId??""))?e.installId:null}},T=()=>{if(!h||x(i))return!1;let e=m();return e.telemetry==="on"&&e.consentVersion>=n&&!!e.installId},J=({isTTY:e,quiet:c=!1,background:s=!1}={})=>{if(!h||x(i)||!e||c||s)return!1;let r=m();return r.telemetry===null||r.consentVersion<n},q=e=>{let s={...A(),telemetry:e?"on":"off",choiceDate:new Date(y()).toISOString().slice(0,10),consentVersion:n};e?/^[0-9a-f-]{36}$/.test(String(s.installId??""))||(s.installId=fe.randomUUID()):delete s.installId;let r=B(s);return e&&r&&k("first_run"),r},M=()=>Y({version:G,platform:u,arch:a,nodeMajor:z,editor:K(i)}),I=(e,c,s=y())=>{let r=w(e,c);if(!r)return null;let l=m();return{event:e,distinct_id:l.installId??"00000000-0000-4000-8000-000000000000",timestamp:new Date(s).toISOString(),properties:{distinct_id:l.installId??"00000000-0000-4000-8000-000000000000",...M(),...r,$process_person_profile:!1,$ip:null}}};function k(e,c={}){try{if(!T())return;let s=w(e,c);if(!s)return;if(L.has(e)){let{count:r,...l}=s,E=e+"|"+JSON.stringify(l);f.set(E,(f.get(E)??0)+(Number.isInteger(r)&&r>0?r:1))}else _.length<pe&&_.push({event:e,clean:s,ts:y()});Z()}catch{}}let W=e=>{V.has(e)&&k(e,{})},X=({result:e,durationMs:c,source:s}={})=>k("ask_ai_used",{result:e==="ok"||e==="cancelled"?e:"error",claude_source:s==="path"||s==="env"?s:"vscode",duration_bucket:O("askDuration",c)}),Q=({ms:e,files:c,services:s,ok:r=!0,errorCode:l}={})=>k("sync_completed",{duration_bucket:O("duration",e),files_bucket:O("files",c),services_bucket:O("services",s),result:r?"ok":"error",...r?{}:{error_code:l??"sync_failed"}});function Z(){p||!globalThis.setInterval||(p=setInterval(()=>{j()},de),p.unref?.())}async function j(){try{if(!T()||!_.length&&!f.size)return _.length=0,f.clear(),!1;let e=[];for(let r of _.splice(0)){let l=I(r.event,r.clean,r.ts);l&&e.push(l)}for(let[r,l]of[...f]){let E=r.indexOf("|"),U=I(r.slice(0,E),{...JSON.parse(r.slice(E+1)),count:l});U&&e.push(U)}if(f.clear(),!e.length||typeof D!="function")return!1;let c=new AbortController,s=setTimeout(()=>c.abort(),_e);try{return await D(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({api_key:o,batch:e}),signal:c.signal,credentials:"omit",redirect:"error"}),!0}catch{return!1}finally{clearTimeout(s)}}catch{return!1}}let ee=()=>{p&&(clearInterval(p),p=null)};function te(){let e=m(),c=x(i);return{configured:h,choice:e.telemetry,choiceDate:e.choiceDate,consentVersion:e.consentVersion,currentConsentVersion:n,hasInstallId:!!e.installId,hardOff:c,active:T(),file:g}}function ne(){let e={event:"sync_completed",distinct_id:m().installId??"<random install id, created only after you say yes>",timestamp:new Date(y()).toISOString(),properties:{...M(),duration_bucket:"5-30s",files_bucket:"500-2k",services_bucket:"2-3",result:"ok",$process_person_profile:!1,$ip:null}};return{sample:{api_key:h?"<set at build time>":"<not set: this build sends nothing>",batch:[e]},fields:H()}}return{configured:h,active:T,shouldAsk:J,setConsent:q,record:k,recordBrowser:W,askAiUsed:X,syncCompleted:Q,flush:j,stop:ee,status:te,show:ne,buildEvent:I,choice:m,_counters:f,_queue:_}}var Ee=null;function xe(t={}){return Ee??=ke(t)}var Oe="t.gandigoutham@gmail.com";function Se({version:t,platform:o=process.platform}){return`Canopy feedback (v${t}, ${o})`}function be({version:t,platform:o=process.platform}){return`mailto:${Oe}?subject=${encodeURIComponent(Se({version:t,platform:o}))}`}function Ae({version:t,platform:o=process.platform}){return`Feedback welcome: ${be({version:t,platform:o})}`}export{xe as a,be as b,Ae as c};