scip-query 0.6.9 → 0.7.1

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.
Files changed (220) hide show
  1. package/README.md +3 -1
  2. package/dist/augment-vue-worker.js +1 -1
  3. package/dist/chunk-23YIGCYF.js +25 -0
  4. package/dist/{chunk-V4WRHJU3.js → chunk-2IYEIFPP.js} +6 -6
  5. package/dist/chunk-2JEFS2YJ.js +2 -0
  6. package/dist/chunk-33SSUPCB.js +7 -0
  7. package/dist/chunk-3GNFUVFA.js +2 -0
  8. package/dist/chunk-3OUC276S.js +2 -0
  9. package/dist/{chunk-JLFAQ2E2.js → chunk-4STLJYHI.js} +4 -4
  10. package/dist/chunk-563HLCDW.js +35 -0
  11. package/dist/chunk-5TT47UMX.js +44 -0
  12. package/dist/chunk-6H2XIIPY.js +71 -0
  13. package/dist/{chunk-I5BB33E6.js → chunk-72JOIFXL.js} +3 -3
  14. package/dist/chunk-7H4RJ4MC.js +2 -0
  15. package/dist/chunk-7O4MJYIW.js +63 -0
  16. package/dist/chunk-7OX2O53H.js +62 -0
  17. package/dist/chunk-A2AVLALL.js +2 -0
  18. package/dist/chunk-AQYBOORI.js +2 -0
  19. package/dist/chunk-ARBZM2NF.js +34 -0
  20. package/dist/{chunk-GRAEZYYU.js → chunk-BI4F6GXI.js} +2 -2
  21. package/dist/chunk-BOVNTAKQ.js +3 -0
  22. package/dist/chunk-CKIO6SVS.js +2 -0
  23. package/dist/chunk-D6Z67MZL.js +2 -0
  24. package/dist/chunk-DFK54IRN.js +2 -0
  25. package/dist/chunk-FD37DBTD.js +2 -0
  26. package/dist/chunk-FOQQDXE7.js +2 -0
  27. package/dist/chunk-GAQGJ52J.js +11 -0
  28. package/dist/chunk-IODTPF5H.js +20 -0
  29. package/dist/chunk-J6Z5YKGQ.js +4 -0
  30. package/dist/chunk-JB4PUN5S.js +40 -0
  31. package/dist/chunk-JTXKS5GK.js +3 -0
  32. package/dist/chunk-KJ3ZJIE5.js +2 -0
  33. package/dist/chunk-KJ6CW6EK.js +2 -0
  34. package/dist/{chunk-AXHDRSRI.js → chunk-KNA6Z7JB.js} +3 -3
  35. package/dist/{chunk-U3GYMGBX.js → chunk-LDV2B7ET.js} +8 -8
  36. package/dist/chunk-LWYIGRHR.js +5 -0
  37. package/dist/chunk-MDAYGS6T.js +2 -0
  38. package/dist/chunk-MX6F756F.js +2 -0
  39. package/dist/chunk-NHDPYW7O.js +2 -0
  40. package/dist/{chunk-IIKNAXAE.js → chunk-NKJKI6SE.js} +2 -2
  41. package/dist/chunk-NN3O7TPH.js +8 -0
  42. package/dist/chunk-NSTZMBAB.js +18 -0
  43. package/dist/chunk-NYEMZHUC.js +6 -0
  44. package/dist/chunk-OHEIZWIA.js +4 -0
  45. package/dist/chunk-PG3ZI5IH.js +2 -0
  46. package/dist/chunk-QAEDNTY7.js +2 -0
  47. package/dist/chunk-QE6MGGUY.js +2 -0
  48. package/dist/chunk-QPRIYXH4.js +2 -0
  49. package/dist/chunk-QWJBIBE6.js +3 -0
  50. package/dist/chunk-RCJEFQOK.js +4 -0
  51. package/dist/chunk-ROOHENEP.js +61 -0
  52. package/dist/{chunk-3JGBAAP7.js → chunk-ROZNBWIF.js} +2 -2
  53. package/dist/chunk-TGK5DFBJ.js +2 -0
  54. package/dist/chunk-TKDJQ2WD.js +59 -0
  55. package/dist/chunk-TRNAQABL.js +7 -0
  56. package/dist/chunk-U75WH4XG.js +2 -0
  57. package/dist/chunk-V53J46BX.js +2 -0
  58. package/dist/chunk-V76FCF5F.js +2 -0
  59. package/dist/chunk-VUBQBW7H.js +16 -0
  60. package/dist/chunk-WJQY2LGT.js +2 -0
  61. package/dist/{chunk-ZO5IFJRM.js → chunk-WODJHE6Z.js} +3 -3
  62. package/dist/{chunk-IX45SWX5.js → chunk-WPLKHAH7.js} +4 -4
  63. package/dist/chunk-XO6R3X5J.js +2 -0
  64. package/dist/chunk-YSZNAG4G.js +2 -0
  65. package/dist/chunk-ZNUPGRPR.js +3 -0
  66. package/dist/{chunk-UIM4WALN.js → chunk-ZXFTC5ET.js} +4 -4
  67. package/dist/cli.js +364 -527
  68. package/dist/config-types-CGIeLEpY.d.ts +108 -0
  69. package/dist/db-DdTPetj5.d.ts +69 -0
  70. package/dist/health-x7B4Xu_6.d.ts +119 -0
  71. package/dist/index.d.ts +100 -334
  72. package/dist/index.js +3 -131
  73. package/dist/postinstall.js +1 -1
  74. package/dist/queries/affected.d.ts +9 -2
  75. package/dist/queries/affected.js +1 -1
  76. package/dist/queries/bottlenecks.d.ts +12 -2
  77. package/dist/queries/bottlenecks.js +1 -1
  78. package/dist/queries/by-kind.d.ts +12 -2
  79. package/dist/queries/by-kind.js +1 -1
  80. package/dist/queries/call-graph.d.ts +19 -2
  81. package/dist/queries/call-graph.js +1 -1
  82. package/dist/queries/change-surface.d.ts +16 -2
  83. package/dist/queries/change-surface.js +1 -1
  84. package/dist/queries/code.d.ts +12 -2
  85. package/dist/queries/code.js +1 -1
  86. package/dist/queries/complexity-hotspots.d.ts +15 -2
  87. package/dist/queries/complexity-hotspots.js +1 -1
  88. package/dist/queries/complexity.d.ts +19 -2
  89. package/dist/queries/complexity.js +1 -1
  90. package/dist/queries/convergence.d.ts +22 -2
  91. package/dist/queries/convergence.js +1 -1
  92. package/dist/queries/coupling.d.ts +8 -2
  93. package/dist/queries/coupling.js +1 -1
  94. package/dist/queries/cycles.d.ts +16 -2
  95. package/dist/queries/cycles.js +1 -1
  96. package/dist/queries/dataflow.d.ts +32 -2
  97. package/dist/queries/dataflow.js +1 -1
  98. package/dist/queries/dead.d.ts +34 -2
  99. package/dist/queries/dead.js +1 -1
  100. package/dist/queries/deep-chains.d.ts +8 -2
  101. package/dist/queries/deep-chains.js +1 -1
  102. package/dist/queries/deps.d.ts +6 -2
  103. package/dist/queries/deps.js +1 -1
  104. package/dist/queries/diff-impact.d.ts +22 -2
  105. package/dist/queries/diff-impact.js +1 -1
  106. package/dist/queries/drift.d.ts +18 -2
  107. package/dist/queries/drift.js +1 -1
  108. package/dist/queries/extract-candidates.d.ts +19 -2
  109. package/dist/queries/extract-candidates.js +1 -1
  110. package/dist/queries/fan.d.ts +7 -2
  111. package/dist/queries/fan.js +1 -1
  112. package/dist/queries/files.d.ts +6 -2
  113. package/dist/queries/files.js +1 -1
  114. package/dist/queries/health.d.ts +4 -81
  115. package/dist/queries/health.js +1 -1
  116. package/dist/queries/hierarchy.d.ts +8 -2
  117. package/dist/queries/hierarchy.js +1 -1
  118. package/dist/queries/hotspots.d.ts +10 -2
  119. package/dist/queries/hotspots.js +1 -1
  120. package/dist/queries/imports.d.ts +13 -2
  121. package/dist/queries/imports.js +1 -1
  122. package/dist/queries/index.d.ts +45 -44
  123. package/dist/queries/index.js +1 -1
  124. package/dist/queries/isolated.d.ts +11 -2
  125. package/dist/queries/isolated.js +1 -1
  126. package/dist/queries/members.d.ts +10 -2
  127. package/dist/queries/members.js +1 -1
  128. package/dist/queries/methods.d.ts +8 -2
  129. package/dist/queries/methods.js +1 -1
  130. package/dist/queries/outline.d.ts +10 -2
  131. package/dist/queries/outline.js +1 -1
  132. package/dist/queries/passthrough-candidates.d.ts +14 -2
  133. package/dist/queries/passthrough-candidates.js +1 -1
  134. package/dist/queries/redundant-reexports.d.ts +13 -2
  135. package/dist/queries/redundant-reexports.js +1 -1
  136. package/dist/queries/refs.d.ts +7 -2
  137. package/dist/queries/refs.js +1 -1
  138. package/dist/queries/similar-chains.d.ts +21 -2
  139. package/dist/queries/similar-chains.js +1 -1
  140. package/dist/queries/similar-files.d.ts +12 -2
  141. package/dist/queries/similar-files.js +1 -1
  142. package/dist/queries/similar-signatures.d.ts +16 -2
  143. package/dist/queries/similar-signatures.js +1 -1
  144. package/dist/queries/similar.d.ts +21 -2
  145. package/dist/queries/similar.js +1 -1
  146. package/dist/queries/slice.d.ts +16 -2
  147. package/dist/queries/slice.js +1 -1
  148. package/dist/queries/stale-abstractions.d.ts +36 -3
  149. package/dist/queries/stale-abstractions.js +1 -1
  150. package/dist/queries/stats.d.ts +11 -2
  151. package/dist/queries/stats.js +1 -1
  152. package/dist/queries/surface.d.ts +8 -2
  153. package/dist/queries/surface.js +1 -1
  154. package/dist/queries/symbols.d.ts +10 -2
  155. package/dist/queries/symbols.js +1 -1
  156. package/dist/queries/system.d.ts +10 -2
  157. package/dist/queries/system.js +1 -1
  158. package/dist/queries/trace.d.ts +18 -2
  159. package/dist/queries/trace.js +1 -1
  160. package/dist/queries/wrapper-candidates.d.ts +14 -2
  161. package/dist/queries/wrapper-candidates.js +1 -1
  162. package/dist/reindex-worker.js +10 -10
  163. package/dist/reindex.d.ts +153 -0
  164. package/dist/reindex.js +69 -0
  165. package/dist/runtime.d.ts +108 -0
  166. package/dist/runtime.js +3 -0
  167. package/dist/scip-cli-a-xOztiK.d.ts +20 -0
  168. package/package.json +184 -4
  169. package/dist/chunk-2OP63JQQ.js +0 -2
  170. package/dist/chunk-33Z6HQBX.js +0 -5
  171. package/dist/chunk-3F453KPT.js +0 -2
  172. package/dist/chunk-3PKPUCIJ.js +0 -11
  173. package/dist/chunk-42BWO2NN.js +0 -2
  174. package/dist/chunk-4MDCFY3E.js +0 -2
  175. package/dist/chunk-4QWTQ6YV.js +0 -2
  176. package/dist/chunk-5IRX5I64.js +0 -5
  177. package/dist/chunk-5MPZ2A7J.js +0 -2
  178. package/dist/chunk-67OMD56K.js +0 -90
  179. package/dist/chunk-6UVVA5I4.js +0 -7
  180. package/dist/chunk-BAA4EJRX.js +0 -2
  181. package/dist/chunk-BT36WY5B.js +0 -114
  182. package/dist/chunk-CLKFDBS6.js +0 -39
  183. package/dist/chunk-CWMWTHV3.js +0 -2
  184. package/dist/chunk-DXO2ECRF.js +0 -7
  185. package/dist/chunk-EHEZLULQ.js +0 -85
  186. package/dist/chunk-FVH3Y44U.js +0 -1
  187. package/dist/chunk-GWBRU65E.js +0 -2
  188. package/dist/chunk-H4DXD2FB.js +0 -5
  189. package/dist/chunk-I2KUHGMX.js +0 -16
  190. package/dist/chunk-JMASYYSW.js +0 -2
  191. package/dist/chunk-KAM4C6ZD.js +0 -4
  192. package/dist/chunk-LBWLO7NA.js +0 -70
  193. package/dist/chunk-LJ2YWNQF.js +0 -2
  194. package/dist/chunk-LLDPR3DG.js +0 -6
  195. package/dist/chunk-LNUZWWWL.js +0 -2
  196. package/dist/chunk-NLJCXHFU.js +0 -84
  197. package/dist/chunk-NRAJIFQA.js +0 -2
  198. package/dist/chunk-OYRGWW6Z.js +0 -2
  199. package/dist/chunk-PVMRIOM6.js +0 -33
  200. package/dist/chunk-QRYEOK3M.js +0 -2
  201. package/dist/chunk-SF2HYG53.js +0 -4
  202. package/dist/chunk-SHGPRVWH.js +0 -2
  203. package/dist/chunk-SMOUOKAO.js +0 -2
  204. package/dist/chunk-TBJDUS4E.js +0 -71
  205. package/dist/chunk-TPXWXKL6.js +0 -2
  206. package/dist/chunk-TTCUMJ43.js +0 -19
  207. package/dist/chunk-TYR7QY5G.js +0 -2
  208. package/dist/chunk-UZG3QXTG.js +0 -2
  209. package/dist/chunk-VDMRAGBK.js +0 -6
  210. package/dist/chunk-W6SRVK2Y.js +0 -5
  211. package/dist/chunk-WGYJDGBI.js +0 -25
  212. package/dist/chunk-WYX3RU2K.js +0 -2
  213. package/dist/chunk-WZYA234B.js +0 -2
  214. package/dist/chunk-Y6ZFXZ7B.js +0 -2
  215. package/dist/chunk-YCN5XEST.js +0 -7
  216. package/dist/db-Rx8Ho_JF.d.ts +0 -838
  217. package/dist/queries/drift-policy.d.ts +0 -6
  218. package/dist/queries/drift-policy.js +0 -2
  219. package/dist/queries/health-cache-control.d.ts +0 -15
  220. package/dist/queries/health-cache-control.js +0 -2
package/dist/cli.js CHANGED
@@ -1,170 +1,13 @@
1
1
  #!/usr/bin/env node
2
- var lc=Object.defineProperty;var cc=(e,t)=>{for(var n in t)lc(e,n,{get:t[n],enumerable:!0})};import{program as I}from"commander";import{spawnSync as sc}from"child_process";import{createRequire as r_}from"module";import{existsSync as nc,realpathSync as rc}from"fs";import{fileURLToPath as mi}from"url";import{readFileSync as uc,writeFileSync as dc,existsSync as pi,mkdirSync as mc}from"fs";import{join as We,resolve as fi}from"path";import{createHash as fc}from"crypto";import{homedir as pc}from"os";var gi=".scipquery.json",gc={enabled:!1,debounceMs:3e4,cooldownMs:6e4,ignore:[]};function Le(e){let t=We(e,gi);if(!pi(t))return{};try{let n=uc(t,"utf-8");return JSON.parse(n)}catch{return{}}}function hi(e){return{...gc,...e.watch}}function hc(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return Jn(n);if(t?.dbPath)return Jn(fi(e,t.dbPath));let i=process.env.XDG_CACHE_HOME||We(pc(),".cache"),s=fc("sha256").update(fi(e)).digest("hex").slice(0,12),o=We(i,"scip-query","projects",s);return Jn(o)}function we(e,t){let n=hc(e,t);return{cacheDir:n,dbPath:We(n,"index.db"),indexPath:We(n,"index.scip"),metaPath:We(n,"meta.json")}}function yi(e,t){let n=We(e,gi);return pi(n)||dc(n,JSON.stringify({languages:t,watch:{enabled:!1,debounceMs:3e4,cooldownMs:6e4}},null,2)+`
3
- `),n}function Jn(e){return mc(e,{recursive:!0}),e}import{execFile as Bd,execFileSync as Hd}from"child_process";import{closeSync as Wd,existsSync as qe,mkdirSync as rs,mkdtempSync as Ud,openSync as Vd,readFileSync as Jd,renameSync as it,rmSync as st,writeFileSync as is}from"fs";import{cpus as qd}from"os";import{basename as en,dirname as Je,extname as zd,join as ae}from"path";import{execFileSync as Vt}from"child_process";import{platform as Jt,arch as yc}from"os";var bi=Jt()==="win32",Si="v0.7.0";function Ut(e){let t=bi?"where":"which";try{return Vt(t,[e],{stdio:"pipe"}),!0}catch{return!1}}function qn(){try{return Vt(bi?"where":"which",["scip"],{stdio:"pipe"}),!0}catch{return!1}}function bc(){let e=Jt(),t=yc(),n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";break;case"win32":n="windows",i="zip";break;default:return null}switch(t){case"arm64":r="arm64";break;case"x64":r="amd64";break;default:return null}let s=`scip-${n}-${r}.${i}`;return{url:`https://github.com/sourcegraph/scip/releases/download/${Si}/${s}`,filename:s}}function zn(){let e=bc();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Jt()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
4
- `),console.log("Or download manually:")):console.log("Download from:"),console.log(e?` ${e.url}
5
- `:` https://github.com/sourcegraph/scip/releases/tag/${Si}
6
- `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function xi(e){if(Jt()==="darwin"&&Ut("brew")){e("Installing scip CLI via Homebrew...");try{if(Vt("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),Ut("scip"))return e("Successfully installed scip CLI via Homebrew"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`Homebrew install failed: ${n}`)}}if(Ut("go")){e("Installing scip CLI via go install...");try{if(Vt("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),Ut("scip"))return e("Successfully installed scip CLI via go install"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`go install failed: ${n}`)}}return e("Could not auto-install scip CLI."),e("Install manually from: https://github.com/sourcegraph/scip/releases"),!1}import Pc from"better-sqlite3";import{execFileSync as Mc}from"child_process";import{existsSync as Oc,readdirSync as Tc,readFileSync as Fc}from"fs";import{extname as zt,join as Ni}from"path";import Sc from"ignore";import{readFileSync as xc,existsSync as Gn}from"fs";import{dirname as Kn,isAbsolute as _i,join as Yn,relative as _c,resolve as Ic}from"path";function tt(e){let t=Sc(),n=!1,r=Rc(e);for(let i of r)try{let s=xc(i,"utf-8");t.add(s),n=!0}catch{}return n||t.add(Cc),{isIgnored:i=>Ii(t,e,i),filter:i=>i.filter(s=>!Ii(t,e,s))}}function Rc(e){let t=[],n=Yn(e,".gitignore");Gn(n)&&t.push(n);let r=Kn(e),i=0;for(;r!==Kn(r)&&i<5;){let s=Yn(r,".gitignore");if(Gn(s)&&t.push(s),Gn(Yn(r,".git")))break;r=Kn(r),i++}return t}var Cc=`
7
- # Dependencies
8
- node_modules/
9
- vendor/
10
- .bundle/
11
-
12
- # Build output
13
- dist/
14
- build/
15
- out/
16
- target/
17
- bin/
18
- obj/
19
-
20
- # Python
21
- __pycache__/
22
- *.pyc
23
- *.pyo
24
- .venv/
25
- venv/
26
- .env/
27
- env/
28
- *.egg-info/
29
-
30
- # Rust
31
- target/
32
-
33
- # Java / Kotlin / Scala
34
- *.class
35
- .gradle/
36
- .mvn/
37
-
38
- # C# / .NET
39
- bin/
40
- obj/
41
- packages/
42
-
43
- # Go
44
- vendor/
45
-
46
- # Dart
47
- .dart_tool/
48
- build/
49
-
50
- # PHP
51
- vendor/
52
-
53
- # IDE / OS
54
- .idea/
55
- .vscode/
56
- *.swp
57
- *.swo
58
- .DS_Store
59
- Thumbs.db
60
-
61
- # Type definitions (often noise in queries)
62
- *.d.ts
63
- `;function Ii(e,t,n){let r=vc(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function vc(e,t){if(!t||t===".")return null;if(!_i(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=_i(t)?t:Ic(e,t),r=_c(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{readdirSync as Nc}from"fs";import{extname as Ri,join as Ec}from"path";function j(e){let t=new WeakMap,n=r=>{let i=t.get(r);return i||(i=new Map,t.set(r,i)),i};return{get(r,i,s){let o=n(r);if(o.has(i))return o.get(i);let a=s();return o.set(i,a),a},invalidate(r,i){t.get(r)?.delete(i)},invalidateAll(r){t.delete(r)},size(r){return t.get(r)?.size??0}}}function Ue(e){let t=new WeakMap;return{get(n,r){let i=t.get(n);if(i)return i.value;let s=r();return t.set(n,{value:s}),s},invalidate(n){t.delete(n)},has(n){return t.has(n)}}}function qt(e){let t=new WeakMap,n=r=>{let i=t.get(r);return i||(i=new Map,t.set(r,i)),i};return{get(r,i,s,o){let a=n(r),l=a.get(i);if(l&&l.source===s)return l.value;let c=o();return a.set(i,{source:s,value:c}),c},invalidate(r,i){t.get(r)?.delete(i)},invalidateAll(r){t.delete(r)}}}var Dc=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".rs",".py",".pyi",".java",".kt",".kts",".scala",".sc",".rb",".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx",".cs",".vb",".php",".dart"],Ci=[".vue"],vi=new Set(Dc.map(e=>e.toLowerCase())),Lc=[...vi].sort().join(","),Qn=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function ke(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(l=>l.toLowerCase()),s=i?new Set(i):vi,o=i?[...s].sort().join(","):Lc,a=`${n?"1":"0"}|${r?"1":"0"}|${o}`;return wc.get(e,a,()=>{let l=new Set;if(n){let c=e.all(`SELECT relative_path
64
- FROM documents
65
- WHERE 1 = 1
66
- ${e.pathExclusionsFor("documents")}`);for(let u of c)e.isIgnored(u.relative_path)||s.has(Ri(u.relative_path).toLowerCase())&&l.add(u.relative_path)}if(r)for(let c of kc(e.config.projectRoot,s))e.isIgnored(c)||l.add(c);return[...l].sort()})}var wc=j("source-files");function kc(e,t){let n=new Set,r=i=>{let s=i?Ec(e,i):e,o;try{o=Nc(s,{withFileTypes:!0})}catch{return}for(let a of o)if(!Qn.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(Ri(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}function Pe(e){let t=new Set((e.extensions??Ci).map(s=>s.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Oc(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=tt(e.projectRoot),r=Ac(e.projectRoot,t).filter(s=>!n.isIgnored(s)),i=new Pc(e.dbPath);try{let s=jc(i,r),o=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
67
- VALUES (?, ?, NULL, ?)`),l=i.transaction(u=>{let d=0;for(let m of u){if(s.has(m))continue;let f=Fc(Ni(e.projectRoot,m),"utf-8"),h=o.run(Bc(m),m,f);d+=Number(h.changes)}return d})(r),c={scanned:r.length,inserted:l,existing:r.length-l};return e.onStatus?.(`Augmented SQLite documents with ${l} auxiliary source file${l===1?"":"s"} (${c.existing} already present).`),c}finally{i.close()}}function Ac(e,t){let n=$c(e,t);if(n)return n;let r=[],i=s=>{let o=s?Ni(e,s):e,a;try{a=Tc(o,{withFileTypes:!0})}catch{return}for(let l of a){if(Qn.has(l.name))continue;let c=s?`${s}/${l.name}`:l.name;if(l.isDirectory()){i(c);continue}t.has(zt(l.name).toLowerCase())&&r.push(c)}};return i(""),r.sort()}function $c(e,t){try{return Mc("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
68
- `).filter(r=>r&&t.has(zt(r).toLowerCase())).sort()}catch{return null}}function jc(e,t){let n=new Set,r=500;for(let i=0;i<t.length;i+=r){let s=t.slice(i,i+r),o=e.prepare(`SELECT relative_path FROM documents WHERE relative_path IN (${s.map(()=>"?").join(",")})`).all(...s);for(let a of o)n.add(a.relative_path)}return n}function Bc(e){return zt(e).toLowerCase()===".vue"?"vue":zt(e).replace(/^\./,"").toLowerCase()||"source"}import{execFileSync as Hc}from"child_process";import{existsSync as Wc,readdirSync as Di}from"fs";import{extname as Li,join as wi}from"path";var Uc=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),Vc=[{language:"typescript",files:["tsconfig.json","tsconfig.base.json"],extensions:[".ts",".tsx",".mts",".cts"]},{language:"rust",files:["Cargo.toml"],extensions:[".rs"]},{language:"go",files:["go.mod"],extensions:[".go"]},{language:"java",files:["pom.xml","build.gradle","build.gradle.kts"],extensions:[".java"]},{language:"kotlin",files:["build.gradle.kts"],extensions:[".kt",".kts"]},{language:"scala",files:["build.sbt"],extensions:[".scala"]},{language:"python",files:["pyproject.toml","setup.py","setup.cfg","Pipfile"],extensions:[".py",".pyi"]},{language:"ruby",files:["Gemfile"],extensions:[".rb"]},{language:"cpp",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"]},{language:"c",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".c",".h"]},{language:"csharp",globs:["*.csproj","*.sln"],extensions:[".cs"]},{language:"vb",globs:["*.vbproj"],extensions:[".vb"]},{language:"dart",files:["pubspec.yaml"],extensions:[".dart"]},{language:"php",files:["composer.json"],extensions:[".php"]},{language:"javascript",files:["package.json"],extensions:[".js",".jsx",".mjs",".cjs"]}];function Ve(e){let t=[],n=Jc(e),r=Kc(e);for(let i of Vc){if(qc(e,i.files)){t.push(i.language);continue}if(zc(n,i.globs)){t.push(i.language);continue}Qc(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&Ei(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&Ei(t,"c"),t}function Jc(e){try{return Di(e)}catch{return[]}}function qc(e,t){return t?.length?t.some(n=>Wc(wi(e,n))):!1}function zc(e,t){return t?.length?e.some(n=>t.some(r=>Gc(n,r))):!1}function Gc(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,r]=t.split("*");return e.startsWith(n??"")&&e.endsWith(r??"")}function Kc(e){let t=Yc(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let s;try{s=Di(i,{withFileTypes:!0})}catch{continue}for(let o of s){if(o.name.startsWith(".")&&!o.name.endsWith("proj")&&!o.name.endsWith("sln")&&o.isDirectory())continue;let a=wi(i,o.name);if(o.isDirectory()){Uc.has(o.name)||r.push(a);continue}let l=Li(o.name).toLowerCase();l&&n.add(l)}}return n}function Yc(e){try{let t=Hc("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}),n=new Set;for(let r of t.split(`
69
- `)){if(!r)continue;let i=Li(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Qc(e,t){return t?.length?t.some(n=>e.has(n)):!1}function Ei(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as ki,readdirSync as Xc}from"fs";import{join as Xn}from"path";var Zc={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n})=>{let r=["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&r.splice(1,0,"--pnpm-workspaces"),{binary:n,args:r}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:"rust",indexerBinary:"rust-analyzer",checkCommand:"rust-analyzer --version",indexArgs:({outputPath:e})=>({binary:"rust-analyzer",args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:"https://github.com/rust-lang/rust-analyzer"},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Pi(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Pi(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:["pubspec.yaml"],installMethods:[{label:"dart pub",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({projectRoot:e,indexerBinary:t})=>{let n=Xn(e,"vendor","bin","scip-php"),r=Xn(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",ki(r)?r:ki(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Gt(e){return Zc[e]}function Pi(e,t){let n;try{n=Xc(e)}catch{return null}for(let r of n)if(t.some(i=>r.endsWith(i)))return Xn(e,r);return null}import{readFileSync as eu,writeFileSync as tu}from"fs";import{create as Zn}from"@bufbuild/protobuf";import{deserializeSCIP as nu,serializeSCIP as ru,DocumentSchema as iu,IndexSchema as su,SymbolInformationSchema as ou}from"@c4312/scip";function au(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=lu(e),n=cu(e.flatMap(i=>i.documents??[])),r=Oi(e.flatMap(i=>i.externalSymbols??[]));return Zn(su,{metadata:t,documents:n,externalSymbols:r})}function Mi(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>nu(eu(i))),r=au(n);return tu(t,Buffer.from(ru(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function lu(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function cu(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,Zn(iu,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:[...r.occurrences,...n.occurrences],symbols:Oi([...r.symbols,...n.symbols]),text:du(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Oi(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,Zn(ou,{symbol:r.symbol,documentation:mu([...r.documentation,...n.documentation]),relationships:uu([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function uu(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function du(e,t){return e?t?e.length>=t.length?e:t:e:t}function mu(e){return[...new Set(e)]}import{execFileSync as fu}from"child_process";import{createHash as pu}from"crypto";import{readdirSync as gu,readFileSync as hu}from"fs";import{join as Ti}from"path";function yu(e){return(bu(e)??Su(e)).filter(t=>t&&!Fi(t)).sort()}function Kt(e){return yu(e).map(t=>{let n=Ti(e,t);try{let r=hu(n);return{path:t,size:r.byteLength,hash:pu("sha256").update(r).digest("hex")}}catch{return{path:t,size:-1,hash:"unreadable"}}})}function bu(e){try{return fu("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
70
- `).filter(Boolean)}catch{return null}}function Su(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?Ti(e,r):e,s;try{s=gu(i,{withFileTypes:!0})}catch{continue}for(let o of s){let a=r?`${r}/${o.name}`:o.name;if(o.isDirectory()){Fi(a)||n.push(a);continue}t.push(a)}}return t}function Fi(e){return e.split("/").some(n=>xu.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var xu=new Set([".git","node_modules",".scipquery-cache",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]);import{readFileSync as _u,writeFileSync as Iu}from"fs";import{create as Ai}from"@bufbuild/protobuf";import{deserializeSCIP as Ru,DocumentSchema as Cu,IndexSchema as vu,serializeSCIP as Nu,SymbolRole as Eu}from"@c4312/scip";function $i(e){let t;try{t=Ru(_u(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=Du(t);return n.removedDefinitionOccurrences>0&&Iu(e,Buffer.from(Nu(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function Du(e){let t=new Set;for(let s of e.documents)for(let o of s.symbols)o.symbol&&t.add(o.symbol);for(let s of e.externalSymbols)s.symbol&&t.add(s.symbol);let n=0,r=0,i=[];for(let s of e.documents){let o=s.occurrences.filter(a=>(a.symbolRoles&Eu.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(o.length===s.occurrences.length){i.push(s);continue}r+=1,i.push(Ai(Cu,{language:s.language,relativePath:s.relativePath,occurrences:o,symbols:s.symbols,text:s.text,positionEncoding:s.positionEncoding}))}return{index:n===0?e:Ai(vu,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}import{execFileSync as Qt}from"child_process";import{existsSync as er,readFileSync as Lu}from"fs";import{createRequire as wu}from"module";import{platform as Bi}from"os";import{dirname as ji,join as Yt}from"path";var ku=wu(import.meta.url),Pu=Bi()==="win32";function ht(e){let t=Pu?"where":"which";try{return Qt(t,[e],{stdio:"pipe"}),!0}catch{return!1}}function tr(e){return[e.indexerBinary,...e.binaryAliases??[]]}function Xt(e){let t=tr(e);return t.length===1?t[0]:t.join(" or ")}function nt(e){for(let t of tr(e))if(ht(t))return t;return Ou(e)}function Hi(e){return nt(e)!==null||Mu(e)}function Mu(e){return Wi(e)!==null}function Ou(e){let t=Wi(e);if(!t)return null;let r=JSON.parse(Lu(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return Yt(ji(t),r);for(let i of tr(e)){let s=r[i];if(s)return Yt(ji(t),s)}return null}function Wi(e){if(!e.bundledNpmPackage)return null;try{return ku.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function nr(e,t){for(let n of e.projectLocalBinaries??[]){let r=Yt(t,n);if(er(r))return r}return null}function Tu(e,t){return nr(e,t)??nt(e)}function Ui(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||rr(n,t))return t;let r=qi(n,t);return r?{...t,DOTNET_ROOT:r}:t}function Vi(e,t){let n=Xt(e),r=t?Tu(e,t):nt(e);if(!r)return{language:e.language,binaryLabel:n,installed:!1,runnable:!1,resolvedBinary:null,installUrl:e.installUrl};if(e.indexerBinary!=="scip-dotnet")return{language:e.language,binaryLabel:n,installed:!0,runnable:!0,resolvedBinary:r};let i=Fu(r);return{language:e.language,binaryLabel:n,installed:!0,runnable:i.runnable,resolvedBinary:r,installUrl:e.installUrl,note:i.note}}function Ji(e,t){let n=e.installMethods,r=Xt(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n)if(ht(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{Qt(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env});let s=nt(e);if(s){let o=s===e.indexerBinary?"":` (using ${s})`;return t(`Successfully installed ${r} via ${i.label}${o}`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(s){let o=s instanceof Error?s.message:String(s);t(`${i.label} install failed: ${o}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function Fu(e){if(rr(e,process.env))return{runnable:!0};let t=qi(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=zi(process.env);return{runnable:!1,note:n.length>0?`.NET 9 runtime still unavailable after checking ${n.join(", ")}`:"binary is present, but scip-dotnet still needs a .NET 9 runtime"}}function qi(e,t){for(let n of zi(t))if(rr(e,{...t,DOTNET_ROOT:n}))return n;return null}function zi(e){let t=[],n=e.DOTNET_ROOT;if(n&&er(n)&&t.push(n),Bi()==="darwin"&&ht("brew"))try{let r=Qt("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=Yt(r,"libexec");er(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function rr(e,t){try{return Qt(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import Au from"better-sqlite3";import{createRequire as $u}from"module";import{existsSync as Ki,mkdtempSync as ju,readFileSync as yt,rmSync as Bu,statSync as Hu,writeFileSync as Wu}from"fs";import{cpus as Uu,tmpdir as Vu}from"os";import{dirname as sr,extname as Ju,join as rt,relative as qu,resolve as Yi}from"path";import{pathToFileURL as zu}from"url";import{Worker as Gu}from"worker_threads";function or(e){Pe({projectRoot:e.projectRoot,dbPath:e.dbPath});let t=Yi(e.projectRoot,e.tsconfig);if(!Ki(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Au(e.dbPath);try{let r=hd(n,e.projectRoot),i=rt(sr(e.dbPath),"augment-vue-meta.json"),s=Gi(n,e.projectRoot,e.tsconfig),o=Ku(i,s,e.onStatus);if(o)return o;let a=vd(n,e.projectRoot,r),l=Yu(n,e,t,r,a),c=Ld(l.occurrences),u=Qu(n,e,r,a,c);e.onStatus?.(`Resolved ${c.length} Vue references with Volar; inserted ${u} mentions.`);let d=Xu(r,c,u,l,a);return ed(i,Gi(n,e.projectRoot,e.tsconfig),d),d}finally{n.close()}}function Ku(e,t,n){let r=Zu(e,t);return r&&n?.(`Vue references unchanged; reused ${r.resolvedReferences} cached resolved references.`),r}function Yu(e,t,n,r,i){if(ld(r))return cd({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:t.tsconfig,vueFiles:r});let s=Td(),o=yd(t.projectRoot,n);return td({projectRoot:t.projectRoot,vueFiles:o.fileNames.filter(a=>a.endsWith(".vue")),context:o,symbolLookup:Id(e,t.projectRoot,s),vueSymbolLookup:i,sourceCache:s})}function Qu(e,t,n,r,i){return Nd(e,t.projectRoot,n,r,i)}function Xu(e,t,n,r,i){return{vueFiles:e.length,resolvedReferences:t.length,insertedMentions:n,skippedReferences:r.skippedReferences,syntheticSymbols:i.syntheticSymbols}}function Zu(e,t){try{let n=JSON.parse(yt(e,"utf-8"));return JSON.stringify(n.fingerprint)===JSON.stringify(t)?n.result:null}catch{return null}}function ed(e,t,n){Wu(e,JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)+`
71
- `)}function Gi(e,t,n){let r=e.prepare(`
72
- SELECT
73
- (SELECT COUNT(*) FROM documents) AS documents,
74
- (SELECT COUNT(*) FROM global_symbols) AS symbols,
75
- (SELECT COUNT(*) FROM chunks) AS chunks,
76
- (SELECT COUNT(*) FROM mentions) AS mentions,
77
- (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
78
- (SELECT MAX(id) FROM chunks) AS maxChunkId,
79
- (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
80
- `).get();return{version:2,tsconfig:n,files:Kt(t),db:r}}function td(e){let t=[],n=0,r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let s=nd(e,i);t.push(...s.occurrences),n+=s.skippedReferences}return{occurrences:t,skippedReferences:n}}function nd(e,t){let n=e.context.language.scripts.get(t.fileName),r=n?.generated?.languagePlugin.typescript?.getServiceScript(n.generated.root)?.code;if(!n||!r)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let i=e.sourceCache(t.fileName);if(!i)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let s=e.context.language.maps.get(r,n),o=bt(e.projectRoot,t.fileName),a=[...kd(i.text)],l={tokens:a.filter(c=>c.start>=t.startOffset&&c.start<t.endOffset),tokenByStart:new Map(a.map(c=>[c.start,c])),tokenTextCounts:sd(a),processedStarts:new Set};return rd({...e,fileName:t.fileName,sourceInfo:i,sourceFile:o,map:s,tokenContext:l})}function rd(e){let t=[],n=0;for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start))continue;let i=Pd(e.map,r.start);if(i===null)continue;let o=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(l=>!Md(e.projectRoot,l.fileName));if(!o){n++;continue}let a=Dd(o,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}Qi(t,e.sourceInfo,e.sourceFile,r,a),e.tokenContext.processedStarts.add(r.start),id(t,e,r,i,a)}return{occurrences:t,skippedReferences:n}}function id(e,t,n,r,i){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let s of od(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(s))continue;let o=t.tokenContext.tokenByStart.get(s);o&&(Qi(e,t.sourceInfo,t.sourceFile,o,i),t.tokenContext.processedStarts.add(s))}}function Qi(e,t,n,r,i){let s=ns(t,r.start);e.push({sourceFile:n,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+r.text.length,symbolId:i})}function sd(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function od(e,t,n,r,i,s){let o=e.getDocumentHighlights?.(t,n,[t])??[],a=[];for(let l of o)if(l.fileName===t)for(let c of l.highlightSpans){let u=ad(r,c.textSpan.start,s,i.text);u!==null&&a.push(u)}return a}function ad(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let s=ts(e,t);if(s===null)return null;let o=n.get(s);return o?.text===r?o.start:null}function ld(e){return e.length>=8&&Xi(e.length)>1}function cd(e){let t=Xi(e.vueFiles.length),n=dd(e.vueFiles),r=fd(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),s=ju(rt(Vu(),"scip-query-vue-workers-")),o=new SharedArrayBuffer(4),a=new Int32Array(o),l=ud(),c=Date.now();try{for(let d=0;d<r.length;d++)new Gu(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[d],resultPath:rt(s,`${d}.json`),sharedBuffer:o}});for(;Atomics.load(a,0)<r.length;){if(Date.now()-c>l)throw new Error(`Vue reference workers timed out after ${(l/1e3).toFixed(0)}s`);Atomics.wait(a,0,Atomics.load(a,0),100)}let u=r.map((d,m)=>{let f=JSON.parse(yt(rt(s,`${m}.json`),"utf-8"));if(!f.ok)throw new Error(`Vue reference worker failed: ${f.error}`);return f.result});return{occurrences:u.flatMap(d=>d.occurrences),skippedReferences:u.reduce((d,m)=>d+m.skippedReferences,0)}}finally{Bu(s,{recursive:!0,force:!0})}}function Xi(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:Math.min(8,Math.max(1,Uu().length-1));return Math.max(1,Math.min(e,n))}function ud(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function dd(e){let t=md(),n=[];for(let r of e){let i=Zi(r),s=Math.max(1,Math.ceil(i/t));for(let o=0;o<s;o++)n.push({fileName:r,startOffset:Math.floor(i*o/s),endOffset:o===s-1?Number.POSITIVE_INFINITY:Math.floor(i*(o+1)/s),countFileSkip:o===0})}return n}function md(){return Number.POSITIVE_INFINITY}function fd(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:pd(i)})).sort((i,s)=>s.weight-i.weight);for(let i of r){let s=n.reduce((o,a)=>a.weight<o.weight?a:o);s.tasks.push(i.task),s.weight+=i.weight}return n.map(i=>i.tasks).filter(i=>i.length>0)}function pd(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Zi(e.fileName)-e.startOffset)}function Zi(e){try{return Hu(e).size}catch{return 1}}function gd(e){e.transaction(()=>{e.prepare(`
81
- DELETE FROM mentions
82
- WHERE chunk_id IN (
83
- SELECT c.id
84
- FROM chunks c
85
- JOIN documents d ON d.id = c.document_id
86
- WHERE d.language = 'vue' OR d.relative_path LIKE '%.vue'
87
- )
88
- `).run(),e.prepare(`
89
- DELETE FROM chunks
90
- WHERE document_id IN (
91
- SELECT id
92
- FROM documents
93
- WHERE language = 'vue' OR relative_path LIKE '%.vue'
94
- )
95
- `).run()})()}function hd(e,t){return e.prepare(`
96
- SELECT relative_path AS relativePath
97
- FROM documents
98
- WHERE language = 'vue' OR relative_path LIKE '%.vue'
99
- ORDER BY relative_path
100
- `).all().map(r=>Yi(t,r.relativePath))}function yd(e,t){let{vueCore:n,ts:r,volarTs:i}=bd(e),{parsed:s,vueOptions:o}=Sd(n,r,t),a=sr(t),l=n.createVueLanguagePlugin(r,s.options,o,f=>f),c=xd(n,r,l),u=_d(a,s),{languageServiceHost:d}=i.createLanguageServiceHost(r,r.sys,c,f=>f,u),m=r.createLanguageService(d);return{ts:r,language:c,languageService:m,fileNames:s.fileNames,configDir:a}}function bd(e){let t=$u(zu(rt(e,"package.json")).href);return{vueCore:ir(t,"@vue/language-core",e),ts:ir(t,"typescript",e),volarTs:ir(t,"@volar/typescript",e)}}function Sd(e,t,n){let r=t.readConfigFile(n,t.sys.readFile);if(r.error||!r.config)throw new Error(`Failed to read ${n}`);let s=e.createParsedCommandLine(t,t.sys,n).vueOptions;return typeof e.createGlobalTypesWriter=="function"&&(s.globalTypesPath=e.createGlobalTypesWriter(s,t.sys.writeFile)),{parsed:t.parseJsonConfigFileContent(r.config,t.sys,sr(n),void 0,n,void 0,e.getAllExtensions(s).map(o=>({extension:o.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:s}}function xd(e,t,n){let r={},i=e.createLanguage([n],new Map,s=>{if(!Ki(s))return;let o=yt(s,"utf-8");r.current?.scripts.set(s,t.ScriptSnapshot.fromString(o),n.getLanguageId(s)??Od(s))});return r.current=i,i}function _d(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function ir(e,t,n){try{return e(t)}catch(r){throw(typeof r=="object"&&r!==null&&"code"in r?r.code:null)==="MODULE_NOT_FOUND"?new Error(`Vue augmentation requires ${t} to be installed in ${n}. Install Vue/Volar dependencies for that project, then rerun augment-vue.`,{cause:r}):r}}function Id(e,t,n){let r=Rd(e);return i=>{let s=bt(t,i.fileName),o=n(i.fileName);if(!o)return null;let a=ns(o,i.textSpan.start),l=r.get(s);if(!l)return null;let c=l.containingByLine.get(a.line);return c!==void 0?c:Cd(l.starts,a.line,2)}}function Rd(e){let t=e.prepare(`
101
- SELECT
102
- d.relative_path AS relativePath,
103
- der.start_line AS startLine,
104
- der.end_line AS endLine,
105
- der.symbol_id AS symbolId
106
- FROM defn_enclosing_ranges der
107
- JOIN documents d ON d.id = der.document_id
108
- ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
109
- `).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId});for(let s=r.startLine;s<=r.endLine;s++)i.containingByLine.set(s,r.symbolId)}for(let r of n.values())r.starts.sort((i,s)=>i.line-s.line);return n}function Cd(e,t,n){let r=0,i=e.length-1;for(;r<=i;){let o=Math.floor((r+i)/2);e[o].line<t?r=o+1:i=o-1}let s=null;for(let o of[i,r]){let a=e[o];if(!a)continue;let l=Math.abs(a.line-t);l>n||(!s||l<s.distance)&&(s={distance:l,symbolId:a.symbolId})}return s?.symbolId??null}function vd(e,t,n){let r=$d(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),s=e.prepare(`
110
- INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
111
- VALUES (?, ?, ?, ?)
112
- `),o=0,a=new Map;return e.transaction(()=>{for(let c of n){let u=bt(t,c),d=jd(r.name,r.version,u);s.run(d,"default",7,`Vue component|${u}`);let m=i.get(d);m&&(o++,a.set(c,m.id))}})(),{get(c){return a.get(c)??null},syntheticSymbols:o}}function Nd(e,t,n,r,i){return e.transaction(()=>(gd(e),Ed(e,t,n,r),wd(e,i)))()}function Ed(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),s=e.prepare(`
113
- INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
114
- VALUES (?, ?, ?, ?, X'00')
115
- `),o=e.prepare(`
116
- INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
117
- VALUES (?, ?, 1)
118
- `);for(let a of n){let l=r.get(a);if(!l)continue;let c=bt(t,a),u=i.get(c);if(!u)continue;let d=s.run(u.id,-1,0,0);o.run(Number(d.lastInsertRowid),l)}}function Dd(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let s=r.language.scripts.get(e.fileName),o=s?.generated?.languagePlugin.typescript?.getServiceScript(s.generated.root)?.code;if(s&&o){let a=r.language.maps.get(o,s);if(ts(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Ld(e){let t=new Set,n=[];for(let r of e){let i=es(r);t.has(i)||(t.add(i),n.push(r))}return n}function es(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function wd(e,t){let n=Ad(e,[...new Set(t.map(l=>l.sourceFile))]),r=e.prepare(`
119
- INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
120
- VALUES (?, ?, ?, ?, X'00')
121
- `),i=e.prepare(`
122
- INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
123
- VALUES (?, ?, 0)
124
- `),s=new Set,o=0,a=0;for(let l of t){let c=es(l);if(s.has(c))continue;s.add(c);let u=n.get(l.sourceFile);if(!u)continue;let d=r.run(u,a++,l.sourceLine,l.sourceLine),m=i.run(Number(d.lastInsertRowid),l.symbolId);o+=Number(m.changes)}return o}function*kd(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function Pd(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function ts(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function ns(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let s=Math.floor((n+r)/2);e.lineStarts[s]<=t?n=s+1:r=s-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function Md(e,t){return bt(e,t).startsWith("node_modules/")}function bt(e,t){return qu(e,t).replaceAll("\\","/")}function Od(e){switch(Ju(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function Td(){let e=new Map;return t=>{if(e.has(t))return e.get(t)??null;try{let n=yt(t,"utf-8"),r={text:n,lineStarts:Fd(n)};return e.set(t,r),r}catch{return e.set(t,null),null}}}function Fd(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function Ad(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let s=t.slice(i,i+r),o=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${s.map(()=>"?").join(",")})`).all(...s);for(let a of o)n.set(a.relativePath,a.id)}return n}function $d(e){try{let t=JSON.parse(yt(rt(e,"package.json"),"utf-8"));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function jd(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}async function ss(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,s=Gd(e),o=Date.now();rs(Je(s.outputScip),{recursive:!0}),rs(Je(s.outputDb),{recursive:!0});let a=e.languages??Ve(t);if(a.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${a.join(", ")}`);let l=ym(t,a,{pnpmWorkspaces:e.pnpmWorkspaces}),c=dm(ae(Je(s.outputDb),"index.lock")),u=null;try{let d=Kd({opts:e,paths:s,languages:a,fingerprint:l,start:o,onStatus:r});if(d)return d;em(i,r);let m=Yd(s);return u=m.runDir,await Qd({opts:e,languages:a,projectRoot:t,paths:s,tempPaths:m,fingerprint:l,start:o,maxHeapMb:n,skipAutoInstall:i,onStatus:r})}finally{u&&st(u,{recursive:!0,force:!0}),c()}}function Gd(e){let t=e.outputScip??ae(e.projectRoot,"index.scip"),n=e.outputDb??ae(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:ae(Je(n),"meta.json")}}function Kd(e){if(e.opts.skipIfUnchanged===!1||!qe(e.paths.outputScip)||!qe(e.paths.outputDb)||!bm(e.paths.metaPath,e.fingerprint))return null;Pe({projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let t=Date.now()-e.start;return e.onStatus(`Index unchanged; reused existing SQLite index in ${(t/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:t,reused:!0,skipped:[]}}function Yd(e){let t=Ud(ae(Je(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:ae(t,en(e.outputScip)),tempOutputDb:ae(t,en(e.outputDb)),tempMetaPath:ae(t,en(e.metaPath))}}async function Qd(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:r}=await Xd(e,t);Zd(e,t,n,r);let i=Date.now()-e.start;return e.onStatus(`Done in ${(i/1e3).toFixed(1)}s`),{languages:n.map(s=>s.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:i,reused:!1,skipped:r}}async function Xd(e,t){let{preparedRuns:n,skippedLanguages:r}=tm({languages:e.languages,tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,onStatus:e.onStatus}),i=await pm(n,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),{indexedOutputs:s}=rm(i,r);return im(s,r,e.languages,e.opts.allowPartial,e.onStatus),{indexedOutputs:s,skippedLanguages:r}}function Zd(e,t,n,r){sm(n,e.tempPaths.tempOutputScip,e.onStatus),om(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),Pe({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),Sm(e.tempPaths.tempMetaPath,{version:2,status:r.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.fingerprint,requestedLanguages:e.languages,indexedLanguages:n.map(i=>i.language),skipped:[...r]}),mm({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath})}function em(e,t){if(!ht("scip")){if(e)throw new Error(`The scip CLI is required but not found on PATH.
125
- Install from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!xi(t))throw new Error(`The scip CLI is required but could not be installed.
126
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function tm(e){let t=[],n=[],r=e.languages.map((i,s)=>({language:i,scipPath:e.languages.length>1?um(e.tempOutputScip,i,s):e.tempOutputScip}));for(let{language:i,scipPath:s}of r){let o=nm({...e,language:i,scipPath:s});"skipped"in o?n.push(o.skipped):t.push(o.prepared)}return{preparedRuns:t,skippedLanguages:n}}function nm(e){let t=Gt(e.language),n=Xt(t),r=nr(t,e.projectRoot);if(!r&&!Hi(t)){if(e.skipAutoInstall){let a=`${n} not found on PATH (auto-install disabled). ${t.installUrl??""}`.trim();return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!Ji(t,e.onStatus)){let a=`${n} could not be auto-installed. ${t.installUrl?`Install manually from ${t.installUrl}`:`Install ${n} and put it on PATH.`}`;return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}}let i=r??nt(t);if(!i){let a=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}let{binary:s,args:o}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:i});return{prepared:{language:e.language,scipPath:e.scipPath,config:t,resolvedBinary:i,binary:s,args:o,env:Ui(t,e.env,i)}}}function rm(e,t){let n=[];for(let r of e)r.skipped?t.push(r.skipped):n.push({language:r.language,scipPath:r.scipPath});return{indexedOutputs:n}}function im(e,t,n,r,i){if(e.length===0){let s=t.map(o=>` - ${o.language}: ${o.reason}`).join(`
127
- `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
128
- `+s)}if(t.length!==0&&(i(`Indexed ${e.length} of ${n.length} languages; skipped ${t.map(s=>s.language).join(", ")}.`),!r))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
129
- `+t.map(s=>` - ${s.language}: ${s.reason}`).join(`
130
- `))}function sm(e,t,n){e.length>1?(n(`Merging ${e.length} language indexes...`),Mi(e.map(r=>r.scipPath),t)):e[0].scipPath!==t&&it(e[0].scipPath,t)}function om(e,t,n,r){if(r("Converting to SQLite..."),!qe(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{let i=$i(e);i.removedDefinitionOccurrences>0&&r(`Sanitized ${i.removedDefinitionOccurrences} invalid definition occurrences across ${i.touchedDocuments} documents before SQLite conversion.`),Hd("scip",["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(i){let s=i instanceof Error?i.message:String(i);throw new Error(`Failed to convert SCIP index to SQLite: ${s}`,{cause:i})}}function am(e,t,n){if(!e.defaultOutputPath)return;let r=ae(t,e.defaultOutputPath);n!==r&&qe(r)&&it(r,n)}function lm(e,t,n){if(!e.defaultOutputPath)return null;let r=ae(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return st(i,{force:!0}),qe(r)?(it(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function cm(e){e&&(st(e.defaultOutputPath,{force:!0}),e.backupPath&&qe(e.backupPath)&&it(e.backupPath,e.defaultOutputPath))}function um(e,t,n){let r=zd(e)||".scip",i=en(e,r);return ae(Je(e),`${i}.${n+1}.${t}${r}`)}function dm(e){let t;try{t=Vd(e,"wx")}catch(n){throw(typeof n=="object"&&n&&"code"in n?n.code:void 0)==="EEXIST"?new Error(`Another scip-query reindex is already running for ${Je(e)}.`,{cause:n}):n}return is(t,JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()})+`
131
- `),()=>{try{Wd(t)}finally{st(e,{force:!0})}}}function mm(e){ar(e.tempOutputScip,e.outputScip),ar(e.tempOutputDb,e.outputDb),ar(e.tempMetaPath,e.metaPath)}function ar(e,t){st(`${t}.tmp-replace`,{force:!0}),it(e,`${t}.tmp-replace`),it(`${t}.tmp-replace`,t)}function fm(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(2,Math.max(1,qd().length-1));return Math.max(1,Math.min(e,Math.floor(r)))}async function pm(e,t,n,r){let i=e.filter(c=>c.config.defaultOutputPath),s=e.filter(c=>!c.config.defaultOutputPath),o=[],a=fm(s.length,r),l=await hm(s,a,c=>lr(c,t,n));if(a>1){let c=new Map;for(let u of l.filter(d=>d.skipped)){let d=s.find(m=>m.language===u.language);d&&(n(`Retrying ${d.language} indexer serially after parallel failure...`),c.set(d.language,await lr(d,t,n)))}o.push(...l.map(u=>c.get(u.language)??u))}else o.push(...l);for(let c of i)o.push(await lr(c,t,n));return o.sort((c,u)=>e.findIndex(d=>d.language===c.language)-e.findIndex(d=>d.language===u.language))}async function lr(e,t,n){n(`Indexing ${e.language} with ${e.resolvedBinary}...`),st(e.scipPath,{force:!0});let r=lm(e.config,t,e.scipPath);try{await gm(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),am(e.config,t,e.scipPath)}catch(i){let s=i instanceof Error?i.message:String(i),o=`${e.resolvedBinary} indexer failed: ${s.split(`
132
- `)[0]}`;return n(`Skipping ${e.language}: ${o}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:o}}}finally{cm(r)}if(!qe(e.scipPath)){let i=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`;return n(`Skipping ${e.language}: ${i}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:i}}}return{language:e.language,scipPath:e.scipPath}}function gm(e,t,n){return new Promise((r,i)=>{Bd(e,[...t],n,s=>{s?i(s):r()})})}async function hm(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=0,s=Math.max(1,Math.min(e.length,t)),o=Array.from({length:s},async()=>{for(;i<e.length;){let a=i++;r[a]=await n(e[a])}});return await Promise.all(o),r}function ym(e,t,n){return{version:1,languages:[...t].sort(),pnpmWorkspaces:n.pnpmWorkspaces===!0,files:Kt(e)}}function bm(e,t){try{let n=JSON.parse(Jd(e,"utf-8"));return n.version===2&&n.status==="complete"&&Zt(n.fingerprint)===Zt(t)&&Zt([...n.indexedLanguages??[]].sort())===Zt(t.languages)}catch{return!1}}function Sm(e,t){is(e,`${JSON.stringify(t,null,2)}
133
- `)}function Zt(e){return JSON.stringify(e)}import{createRequire as vm}from"module";import{existsSync as St,readFileSync as xm,readdirSync as _m,statSync as Im}from"fs";import B from"path";var ur=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function dr(e,t){let r=t?B.dirname(B.join(e,t)):e,i=B.resolve(e);for(;r.startsWith(i);){for(let o of ur){let a=B.join(r,o);if(St(a))return a}let s=B.dirname(r);if(s===r)break;r=s}for(let s of ur){let o=B.join(e,s);if(St(o))return o}return null}function os(e){let t=e.config.projectRoot,n=new Set(mr(t,e.config.semantic?.typescript?.tsconfigs)),r=e.all(`SELECT relative_path
2
+ import{program as Jr}from"commander";import{realpathSync as ym}from"fs";import{fileURLToPath as YR}from"url";import{spawnSync as Ll}from"child_process";import{createRequire as HS}from"module";import{fileURLToPath as El}from"url";import{statSync as bm}from"fs";function Pe(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:r,references:i,...Sm(e.config.dbPath)}}function Sm(e){try{let t=bm(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function k(e,t={}){let n=t.scope?"AND relative_path LIKE ?":"",r=t.like?"AND relative_path LIKE ?":"",i=[...t.scope?[`%${t.scope}%`]:[],...t.like?[t.like]:[]],o=e.all(`SELECT relative_path
134
3
  FROM documents
135
- WHERE (
136
- relative_path LIKE '%.ts'
137
- OR relative_path LIKE '%.tsx'
138
- OR relative_path LIKE '%.mts'
139
- OR relative_path LIKE '%.cts'
140
- OR relative_path LIKE '%.js'
141
- OR relative_path LIKE '%.jsx'
142
- OR relative_path LIKE '%.mjs'
143
- OR relative_path LIKE '%.cjs'
144
- )
145
- ${e.pathExclusionsFor("documents")}`);for(let i of r){if(e.isIgnored(i.relative_path))continue;let s=dr(t,i.relative_path);s&&n.add(B.resolve(s))}if(n.size===0){let i=dr(t);i&&n.add(B.resolve(i))}return[...n].filter(i=>!as(t,i)).sort((i,s)=>i.localeCompare(s))}function mr(e,t=[]){let n=new Set;for(let r of t){let i=B.isAbsolute(r)?r:B.join(e,r);St(i)&&n.add(B.resolve(i))}for(let r of Rm(e))for(let i of ur){let s=B.join(r,i);St(s)&&n.add(B.resolve(s))}if(n.size===0){let r=dr(e);r&&n.add(B.resolve(r))}return[...n].filter(r=>!as(e,r)).sort((r,i)=>r.localeCompare(i))}function Rm(e){let t=B.join(e,"package.json");if(!St(t))return[];let n;try{n=JSON.parse(xm(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>Cm(e,i))}function Cm(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let o=B.join(e,t);return cr(o)?[o]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),s=B.join(e,r||".");return cr(s)?_m(s).map(o=>B.join(s,o,i)).filter(cr):[]}function cr(e){try{return Im(e).isDirectory()}catch{return!1}}function as(e,t){let n=B.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}var Nm=vm(import.meta.url);function fr(e,t=[]){let n=Em(),r=mr(e,t),i=r[0];return n?r.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r}:{available:!1,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r,reason:"ts-morph is not installed"}}function Em(){try{return Nm.resolve("ts-morph"),!0}catch{return!1}}import{watch as Dm}from"fs";import{existsSync as ls,renameSync as cs}from"fs";import{join as Lm,relative as wm}from"path";import{fork as km}from"child_process";import Pm from"ignore";var tn=class{projectRoot;watchConfig;indexPaths;languages;pnpmWorkspaces;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.watchConfig=hi(t.config),this.indexPaths=we(t.projectRoot,t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=tt(t.projectRoot),this.extraIgnore=Pm(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"});try{let t=Dm(this.projectRoot,{recursive:!0},(n,r)=>{r&&!this.stopped&&this.handleFileChange(r)});this.fsWatchers.push(t)}catch{this.onError(new Error("Failed to start file watcher. On Linux, you may need to increase inotify limits: sysctl -w fs.inotify.max_user_watches=524288"))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.setStatus({state:"idle"})}handleFileChange(t){let n=wm(this.projectRoot,Lm(this.projectRoot,t));if(this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||t.endsWith(".scipquery.json"))return;if(this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let r=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:r}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&t<this.watchConfig.cooldownMs){let r=this.watchConfig.cooldownMs-t;this.dirty=!0;let i=Date.now()+r;this.setStatus({state:"cooldown",until:i,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},r);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex().then(r=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(r),this.dirty&&!this.stopped){let i=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:i,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(r=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(r instanceof Error?r:new Error(String(r))),this.setStatus({state:"idle"})})}runReindex(){return new Promise((t,n)=>{let r=Date.now(),i=this.indexPaths.dbPath+".tmp",s=Mm(this.indexPaths.indexPath),o=km(new URL("./reindex-worker.js",import.meta.url).pathname,[],{env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:s,SCIP_REINDEX_OUTPUT_DB:i,SCIP_REINDEX_LANGUAGES:this.languages?.join(",")??"",SCIP_REINDEX_PNPM_WORKSPACES:this.pnpmWorkspaces?"1":""},stdio:"pipe"});o.on("exit",a=>{if(a===0)try{ls(i)&&cs(i,this.indexPaths.dbPath),ls(s)&&cs(s,this.indexPaths.indexPath),t(Date.now()-r)}catch(l){n(new Error(`Atomic swap failed: ${l}`))}else n(new Error(`Reindex worker exited with code ${a}`))}),o.on("error",n)})}setStatus(t){this.status=t,this.onStatus(t)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}};function Mm(e){return e.endsWith(".scip")?e.slice(0,-5)+".tmp.scip":e+".tmp.scip"}import{existsSync as pr,mkdirSync as Om,symlinkSync as Tm,readlinkSync as Fm,unlinkSync as Am}from"fs";import{join as nn,dirname as us,resolve as gr}from"path";import{homedir as ds,platform as $m}from"os";import{fileURLToPath as jm}from"url";var Bm=$m()==="win32",hr=["concrete-plan","scip-explore","scip-debloat","scip-verify","scip-language-playbook"];function ms(e={}){let t=e.quiet?()=>{}:console.log,n=jm(import.meta.url),r=gr(us(n),"..","skills"),i=[nn(ds(),".claude","skills"),nn(ds(),".codex","skills")],s={installed:[],skipped:[],alreadyLinked:[]};for(let o of i){let a=us(o);if(!pr(a))continue;Om(o,{recursive:!0});let l=o.includes(".codex")?"Codex":"Claude";for(let c of hr){let u=nn(r,c),d=nn(o,c);if(!pr(u)){s.skipped.push(`${l}/${c}`);continue}if(pr(d)){try{let m=Fm(d);if(gr(m)===gr(u)){s.alreadyLinked.push(`${l}/${c}`),t(` ok: ${c} \u2192 ${l} (already linked)`);continue}}catch{s.skipped.push(`${l}/${c}`),t(` skip: ${c} \u2192 ${l} (exists, not a symlink)`);continue}Am(d)}Tm(u,d,Bm?"junction":"dir"),s.installed.push(`${l}/${c}`),t(` done: ${c} \u2192 ${l}`)}}return s}function xe(e){return e+1}function pe(e,t){return`${xe(e)}-${xe(t)}`}function ge(e,t,n){return`${e}:${pe(t,n)}`}var S={empty(e){console.log(e)},list(e,t){for(let n of e)console.log(t(n))},groupedByFile(e,t,n=r=>r.relativePath){let r="";for(let i of e){let s=n(i);s!==r&&(r&&console.log(""),console.log(s),r=s),console.log(t(i))}},sectionedReport(e){let t=!0;for(let n of e)if(!(n.skipIfEmpty&&n.rows.length===0)){t||console.log(""),t=!1,n.title!==void 0&&console.log(`\u2550\u2550\u2550 ${n.title} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(n.explanation);for(let r of n.rows)console.log(r)}},table(e,t,n){console.log(` ${e.join(" ")}`);let r=n??e.map(i=>i.length);console.log(` ${r.map(i=>"\u2500".repeat(i)).join(" ")}`);for(let i of t)console.log(i)}};import{existsSync as Zl}from"fs";import{join as e_}from"path";import Hm from"better-sqlite3";var Wm=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".scipquery-cache","__pycache__",".venv","venv"],rn=class{db;config;pathFilter;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new Hm(t.dbPath,{readonly:!0}),this.db.pragma("busy_timeout = 5000")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
146
- EXISTS (
147
- SELECT 1
148
- FROM defn_enclosing_ranges local_der
149
- JOIN documents local_d ON local_der.document_id = local_d.id
150
- WHERE local_der.symbol_id = gs.id
151
- ${this.pathExclusionsFor("local_d").trimStart()}
152
- )
153
- OR EXISTS (
154
- SELECT 1
155
- FROM mentions local_m
156
- JOIN chunks local_c ON local_m.chunk_id = local_c.id
157
- JOIN documents local_d ON local_c.document_id = local_d.id
158
- WHERE local_m.symbol_id = gs.id
159
- AND local_m.role = 1
160
- ${this.pathExclusionsFor("local_d").trimStart()}
161
- )
162
- )`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>Wm.flatMap(r=>[`AND ${n}.relative_path NOT LIKE '${r}/%'`,`AND ${n}.relative_path NOT LIKE '%/${r}/%'`])).join(`
163
- `)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.db.prepare(t).all(...n)}get(t,...n){return this.db.prepare(t).get(...n)}close(){this.db.close()}};var x={};cc(x,{HEALTH_PHASES:()=>vl,affected:()=>cl,bottlenecks:()=>Ha,byKind:()=>Ua,callGraph:()=>Ka,changeSurface:()=>ul,code:()=>Vl,complexity:()=>ql,complexityHotspots:()=>Wn,convergence:()=>Hl,coupling:()=>Aa,cycles:()=>Pn,dataflow:()=>zl,dead:()=>kn,deepChains:()=>za,deps:()=>fa,diffImpact:()=>ml,diffImpactPartial:()=>ni,diffImpactPlan:()=>ti,drift:()=>An,extractCandidates:()=>Tn,fanIn:()=>Ma,fanOut:()=>Oa,files:()=>fs,health:()=>Nl,healthPhase:()=>El,healthReportFromPhases:()=>Ll,hierarchy:()=>Ga,hotspots:()=>Ca,importedBy:()=>Ea,imports:()=>Na,isolated:()=>Mn,kindCounts:()=>Va,members:()=>Pa,mergeDiffImpactPartials:()=>ri,methods:()=>ua,outline:()=>ka,passthroughCandidates:()=>Bn,rdeps:()=>pa,redundantReexports:()=>Kl,refs:()=>da,similar:()=>Xa,similarAll:()=>On,similarChains:()=>al,similarFiles:()=>sl,similarSignatures:()=>Ql,slice:()=>Gl,staleAbstractions:()=>Hn,stats:()=>sn,surface:()=>ha,symbols:()=>Hs,system:()=>ga,topCoupling:()=>$a,topFanIn:()=>Ta,topFanOut:()=>Fa,trace:()=>ma,unusedImports:()=>Da,wrapperCandidates:()=>jn});import{statSync as Um}from"fs";function sn(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:r,references:i,...Vm(e.config.dbPath)}}function Vm(e){try{let t=Um(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function Jm(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function fs(e,t){let n=Jm(t);return e.all(`SELECT relative_path FROM documents
164
- WHERE relative_path LIKE ?
165
- ORDER BY relative_path`,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path}))}import{extname as xs}from"path";import{createRequire as Ym}from"module";import{existsSync as qm,readFileSync as zm}from"fs";import{join as Gm}from"path";var yr=j("source-text");function M(e,t){let n=t.replace(/\\/g,"/");return yr.get(e,n,()=>{let r=Gm(e.config.projectRoot,n);return qm(r)?zm(r,"utf-8"):""})}function ps(e){yr.invalidateAll(e)}function gs(e,t){yr.invalidate(e,t.replace(/\\/g,"/"))}var Km=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale|wrapper|passthrough|drift|extract)?/i;function br(e,t,n){if(n<=0)return!1;let r=M(e,t);if(!r)return!1;let i=r.split(`
166
- `);for(let s=n-1;s>=0&&s>=n-5;s-=1){let o=(i[s]??"").trim();if(o!==""){if(Km.test(o))return!0;if(!o.startsWith("//")&&!o.startsWith("*")&&!o.startsWith("/*")&&!o.startsWith("@")&&!o.startsWith("#"))return!1}}return!1}var K=Ym(import.meta.url),on=null,hs=!1;function _s(){if(hs)return null;if(on)return on;try{return on=K("tree-sitter"),on}catch{return hs=!0,null}}var Qm={".rs":"rust",".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".java":"java",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".sc":"scala",".rb":"ruby",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".hxx":"cpp",".cs":"csharp",".php":"php",".vb":"vb"},ys=new Map,Sr=new Set;function Is(e){if(Sr.has(e))return null;let t=ys.get(e);if(t)return t;let n;try{switch(e){case"rust":n=K("tree-sitter-rust");break;case"typescript":n=K("tree-sitter-typescript").typescript;break;case"tsx":n=K("tree-sitter-typescript").tsx;break;case"javascript":n=K("tree-sitter-javascript");break;case"python":n=K("tree-sitter-python");break;case"java":n=K("tree-sitter-java");break;case"kotlin":n=K("tree-sitter-kotlin");break;case"scala":n=K("tree-sitter-scala");break;case"ruby":n=K("tree-sitter-ruby");break;case"c":n=K("tree-sitter-c");break;case"cpp":n=K("tree-sitter-cpp");break;case"csharp":n=K("tree-sitter-c-sharp");break;case"php":n=K("tree-sitter-php").php;break;case"vb":{let r=K("tree-sitter-vb-dotnet");n=r.language??r;break}}}catch{return Sr.add(e),null}return ys.set(e,n),n}var bs=new Map;function Rs(e){let t=bs.get(e);if(t)return t;let n=Is(e);if(!n)return null;let r=_s();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return Sr.add(e),null}return bs.set(e,i),i}function F(e){return Qm[xs(e).toLowerCase()]??null}function ze(e){return xs(e).toLowerCase()===".vue"}var an=qt("ast-trees");function Cs(e){an.invalidateAll(e)}function vs(e,t){an.invalidate(e,t)}function O(e,t){if(ze(t))return Xm(e,t);let n=F(t);if(!n)return null;let r=M(e,t);return r?an.get(e,t,r,()=>{let i=Rs(n);if(!i)return null;try{return Ns(i,r)}catch{return null}}):null}function Xm(e,t){let n=M(e,t);return n?an.get(e,t,n,()=>{let r=Zm(n);if(!r)return null;let i=Rs(r.language);if(!i)return null;let s=`
167
- `.repeat(r.startLine)+r.body;try{return Ns(i,s)}catch{return null}}):null}function Ns(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function Zm(e){let t=[],n=/<script\b([^>]*)>([\s\S]*?)<\/script>/g;for(let l of e.matchAll(n))typeof l.index=="number"&&t.push({tagOpen:l[1]??"",body:l[2]??"",openIdx:l.index+(l[0].length-(l[2]?.length??0)-9)});if(t.length===0)return null;let r=t.find(l=>/\bsetup\b/.test(l.tagOpen))??t[0],s=r.tagOpen.match(/\blang\s*=\s*["']?([\w-]+)/)?.[1]?.toLowerCase(),o=s==="ts"||s==="typescript"?"typescript":s==="tsx"?"tsx":"javascript",a=ef(e,r.openIdx);return{body:r.body,startLine:a,language:o}}function ef(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}var ot=new Map;function tf(e,t){let n=`${e}::${t}`;if(ot.has(n))return ot.get(n)??null;let r=Is(e);if(!r)return ot.set(n,null),null;let i=_s();if(!i)return ot.set(n,null),null;try{let s=new i.Query(r,t);return ot.set(n,s),s}catch{return ot.set(n,null),null}}var nf={rust:`
4
+ WHERE 1 = 1
5
+ ${e.pathExclusionsFor("documents")}
6
+ ${n}
7
+ ${r}
8
+ ORDER BY relative_path`,...i).map(a=>a.relative_path),s=t.extensions?o.filter(a=>t.extensions.some(c=>a.toLowerCase().endsWith(c.toLowerCase()))):o;return t.includeIgnored===!1?s.filter(a=>!e.isIgnored(a)):s}function xm(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function zr(e,t){let n=xm(t);return k(e,{like:n,includeIgnored:!1}).map(r=>({relativePath:r}))}import{extname as bs}from"path";var Cm={".rs":"rust",".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".java":"java",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".sc":"scala",".rb":"ruby",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".hxx":"cpp",".cs":"csharp",".php":"php",".vb":"vb"};function P(e){return Cm[bs(e).toLowerCase()]??null}function st(e){return bs(e).toLowerCase()===".vue"}var Im=new Set(["function_item","function_signature_item"]),Rm=new Set(["function_definition"]),_m=new Set(["function_declaration","method_definition","arrow_function","function_expression"]);function en(e){switch(e){case"rust":return Im;case"python":return Rm;default:return _m}}function H(e){let t=new WeakMap,n=r=>{let i=t.get(r);return i||(i=new Map,t.set(r,i)),i};return{get(r,i,o){let s=n(r);if(s.has(i))return s.get(i);let a=o();return s.set(i,a),a},invalidate(r,i){t.get(r)?.delete(i)},invalidateAll(r){t.delete(r)},size(r){return t.get(r)?.size??0}}}function We(e){let t=new WeakMap;return{get(n,r){let i=t.get(n);if(i)return i.value;let o=r();return t.set(n,{value:o}),o},invalidate(n){t.delete(n)},has(n){return t.has(n)}}}function An(e){let t=new WeakMap,n=r=>{let i=t.get(r);return i||(i=new Map,t.set(r,i)),i};return{get(r,i,o,s){let a=n(r),c=a.get(i);if(c&&c.source===o)return c.value;let l=s();return a.set(i,{source:o,value:l}),l},invalidate(r,i){t.get(r)?.delete(i)},invalidateAll(r){t.delete(r)}}}import{createRequire as vm}from"module";var re=vm(import.meta.url),$n=null,Ss=!1;function Is(){if(Ss)return null;if($n)return $n;try{return $n=re("tree-sitter"),$n}catch{return Ss=!0,null}}var xs=new Map,Gr=new Set;function Rs(e){if(Gr.has(e))return null;let t=xs.get(e);if(t)return t;let n;try{switch(e){case"rust":n=re("tree-sitter-rust");break;case"typescript":n=re("tree-sitter-typescript").typescript;break;case"tsx":n=re("tree-sitter-typescript").tsx;break;case"javascript":n=re("tree-sitter-javascript");break;case"python":n=re("tree-sitter-python");break;case"java":n=re("tree-sitter-java");break;case"kotlin":n=re("tree-sitter-kotlin");break;case"scala":n=re("tree-sitter-scala");break;case"ruby":n=re("tree-sitter-ruby");break;case"c":n=re("tree-sitter-c");break;case"cpp":n=re("tree-sitter-cpp");break;case"csharp":n=re("tree-sitter-c-sharp");break;case"php":n=re("tree-sitter-php").php;break;case"vb":{let r=re("tree-sitter-vb-dotnet");n=r.language??r;break}}}catch{return Gr.add(e),null}return xs.set(e,n),n}var Cs=new Map;function Dm(e){let t=Cs.get(e);if(t)return t;let n=Rs(e);if(!n)return null;let r=Is();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return Gr.add(e),null}return Cs.set(e,i),i}function Nm(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function Kr(e,t){let n=Dm(e);if(!n)return null;try{return Nm(n,t)}catch{return null}}var vt=new Map;function _s(e,t){let n=`${e}::${t}`;if(vt.has(n))return vt.get(n)??null;let r=Rs(e);if(!r)return vt.set(n,null),null;let i=Is();if(!i)return vt.set(n,null),null;try{let o=new i.Query(r,t);return vt.set(n,o),o}catch{return vt.set(n,null),null}}import{existsSync as Lm,readFileSync as Em}from"fs";import{join as wm}from"path";var Qr=H("source-text");function T(e,t){let n=t.replace(/\\/g,"/");return Qr.get(e,n,()=>{let r=wm(e.config.projectRoot,n);return Lm(r)?Em(r,"utf-8"):""})}function vs(e){Qr.invalidateAll(e)}function Ds(e,t){Qr.invalidate(e,t.replace(/\\/g,"/"))}var km=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale|wrapper|passthrough|drift|extract)?/i;function Yr(e,t,n){if(n<=0)return!1;let r=T(e,t);if(!r)return!1;let i=r.split(`
9
+ `);for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(i[o]??"").trim();if(s!==""){if(km.test(s))return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function Ns(e){let t=[],n=/<script\b([^>]*)>([\s\S]*?)<\/script>/g;for(let a of e.matchAll(n))typeof a.index=="number"&&t.push({tagOpen:a[1]??"",body:a[2]??"",openIdx:a.index+(a[0].length-(a[2]?.length??0)-9)});if(t.length===0)return null;let r=t.find(a=>/\bsetup\b/.test(a.tagOpen))??t[0],o=r.tagOpen.match(/\blang\s*=\s*["']?([\w-]+)/)?.[1]?.toLowerCase(),s=o==="ts"||o==="typescript"?"typescript":o==="tsx"?"tsx":"javascript";return{body:r.body,startLine:Pm(e,r.openIdx),language:s}}function Pm(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}var jn=An("ast-trees");function Xr(e){jn.invalidateAll(e)}function Zr(e,t){jn.invalidate(e,t)}function B(e,t){if(st(t))return Tm(e,t);let n=P(t);if(!n)return null;let r=T(e,t);return r?jn.get(e,t,r,()=>Kr(n,r)):null}function Tm(e,t){let n=T(e,t);return n?jn.get(e,t,n,()=>{let r=Ns(n);if(!r)return null;let i=`
10
+ `.repeat(r.startLine)+r.body;return Kr(r.language,i)}):null}var Mm={rust:`
168
11
  (function_item name: (identifier) @name) @def
169
12
  (function_signature_item name: (identifier) @name) @def
170
13
  `,typescript:`
@@ -190,7 +33,7 @@ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
190
33
  (variable_declarator name: (identifier) @name value: (function_expression)) @def
191
34
  `,python:`
192
35
  (function_definition name: (identifier) @name) @def
193
- `},rf=new WeakMap;function Es(e,t){return Ls(e,t,rf,nf,n=>{let r=[];for(let i of n){let s=null,o=null;for(let a of i.captures)a.name==="name"?s=a.node.text:a.name==="def"&&(o={startLine:a.node.startPosition.row,endLine:a.node.endPosition.row});s&&o&&r.push({name:s,startLine:o.startLine,endLine:o.endLine})}return r})}var sf={rust:`
36
+ `},Om=new WeakMap;function ei(e,t){return ni(e,t,Om,Mm,n=>{let r=[];for(let i of n){let o=null,s=null;for(let a of i.captures)a.name==="name"?o=a.node.text:a.name==="def"&&(s={startLine:a.node.startPosition.row,endLine:a.node.endPosition.row});o&&s&&r.push({name:o,startLine:s.startLine,endLine:s.endLine})}return r})}var Fm={rust:`
194
37
  (call_expression function: (_) @target) @call
195
38
  (macro_invocation macro: (_) @target) @call
196
39
  `,typescript:`
@@ -204,53 +47,14 @@ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
204
47
  (new_expression constructor: (_) @target) @call
205
48
  `,python:`
206
49
  (call function: (_) @target) @call
207
- `},of=new WeakMap;function ln(e,t){return Ls(e,t,of,sf,n=>{let r=[];for(let i of n){let s=null,o=null;for(let l of i.captures)l.name==="target"?s=l.node:l.name==="call"&&(o=l.node);if(!s||!o)continue;let a=xt(s);a&&r.push({calleeLeaf:a,memberAccess:af(s),line:o.startPosition.row})}return r})}function af(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function Ds(e,t){return cn(e,t,lf,()=>new Map,(n,r,i)=>{let s=(l,c)=>{if(l===c)return;let u=i.get(l);u||(u=new Set,i.set(l,u)),u.add(c)},o=r==="python"?new Set(["identifier"]):new Set(["type_identifier"]),a=(l,c)=>{let u=d=>{o.has(d.type)&&d.text!==c&&s(d.text,c);for(let m of d.children)u(m)};for(let d of l.children)u(d)};if(r==="rust")for(let l of n.rootNode.descendantsOfType(["struct_item","enum_item","union_item","type_item"])){let c=l.namedChildren.find(d=>d.type==="type_identifier")?.text;if(!c)continue;let u=l.namedChildren.find(d=>d.type==="field_declaration_list"||d.type==="enum_variant_list"||d.type==="ordered_field_declaration_list");u&&a(u,c),l.type==="type_item"&&a(l,c)}else if(r==="python")for(let l of n.rootNode.descendantsOfType("class_definition")){let c=l.namedChildren.find(d=>d.type==="identifier")?.text;if(!c)continue;let u=l.namedChildren.find(d=>d.type==="block");if(u)for(let d of u.descendantsOfType("type"))for(let m of d.descendantsOfType("identifier"))m.text!==c&&s(m.text,c)}else for(let l of n.rootNode.descendantsOfType(["interface_declaration","type_alias_declaration","class_declaration"])){let c=l.namedChildren.find(u=>u.type==="type_identifier")?.text;c&&a(l,c)}})??new Map}function cn(e,t,n,r,i){let s=F(t);if(!s)return null;let o=O(e,t);if(!o)return null;let a=n.get(o);if(a)return a;let l=r();return i(o,s,l),n.set(o,l),l}function Ls(e,t,n,r,i){let s=F(t);if(!s)return null;let o=r[s];if(!o)return null;let a=O(e,t);if(!a)return null;let l=n.get(a);if(l)return l;let c=tf(s,o);if(!c)return null;let u=i(c.matches(a.rootNode));return n.set(a,u),u}var lf=new WeakMap,Ss=new WeakMap;function ws(e,t,n,r){let i=F(t);if(!i)return null;let s=O(e,t);if(!s)return null;let o=Ss.get(s);return o||(o=cf(s,i),Ss.set(s,o)),o.get(`${n}:${r}`)??null}function cf(e,t){let n=t==="rust"?new Set(["function_item","function_signature_item"]):t==="python"?new Set(["function_definition"]):new Set(["function_declaration","method_definition","arrow_function","function_expression"]),r=new Map,i=s=>{if(n.has(s.type)){let o=s.namedChildren.find(l=>l.type==="parameters"||l.type==="formal_parameters"),a=0;if(o)for(let l of o.namedChildren)l.type==="comment"||l.type==="line_comment"||l.type==="block_comment"||(a+=1);r.set(`${s.startPosition.row}:${s.endPosition.row}`,{paramCount:a})}for(let o of s.children)i(o)};return i(e.rootNode),r}function xt(e){switch(e.type){case"identifier":case"type_identifier":case"property_identifier":case"shorthand_property_identifier":return e.text;case"field_expression":case"member_expression":case"attribute":{let t=e.namedChild(e.namedChildCount-1);return t?xt(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?xt(t):null}case"super":case"self":case"this":return null;default:return null}}var uf={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function V(e){if(e.startsWith("local "))return{kind:"local",id:e.slice(6),raw:e};let t=e.split(" ");if(t.length<4)return{scheme:t[0]??"",manager:t[1]??"",packageName:t[2]??"",version:"",descriptors:[],raw:e};let n=t[0],r=t[1],i=e.slice(n.length+1+r.length+1),s;if(i.startsWith("`")){let c=i.indexOf("`",1);c===-1?(s=i.slice(1),i=""):(s=i.slice(1,c),i=i.slice(c+2))}else{let c=i.indexOf(" ");c===-1?(s=i,i=""):(s=i.slice(0,c),i=i.slice(c+1))}let o,a=i.indexOf(" ");a===-1?(o=i,i=""):(o=i.slice(0,a),i=i.slice(a+1));let l=df(i);return{scheme:n,manager:r,packageName:s,version:o,descriptors:l,raw:e}}function df(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="["){let s=e.indexOf("]",n+1);if(s===-1){t.push({name:e.slice(n+1),suffix:"type-param"});break}t.push({name:e.slice(n+1,s),suffix:"type-param"}),n=s+1;continue}if(e[n]==="("&&(t.length===0||n===0||ks(e[n-1]))){let s=e.indexOf(")",n+1);if(s!==-1&&e[s+1]!=="."){t.push({name:e.slice(n+1,s),suffix:"parameter"}),n=s+1;continue}}let r;if(e[n]==="`"){let s=e.indexOf("`",n+1);if(s===-1){r=e.slice(n+1),t.push({name:r,suffix:"term"});break}r=e.slice(n+1,s),n=s+1}else{let s=n;for(;n<e.length&&!ks(e[n]);)n++;r=e.slice(s,n)}if(n>=e.length){r&&t.push({name:r,suffix:"term"});break}let i=e[n];if(i==="("){let s=e.indexOf(")",n+1);s!==-1&&e[s+1]==="."?(t.push({name:r,suffix:"method"}),n=s+2):s!==-1?(t.push({name:r,suffix:"method"}),n=s+1):(t.push({name:r,suffix:"term"}),n++)}else{let s=uf[i];s&&t.push({name:r,suffix:s}),n+=1}}return t}function ks(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function y(e){let t=V(e);if("kind"in t&&t.kind==="local")return`local:${t.id}`;let n=t;if(n.descriptors.length===0)return n.raw;let r=[];for(let i of n.descriptors){let s=mf(i);s&&r.push(s)}return r.join(":")}function mf(e){let t=e.suffix==="namespace"?ff(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function ff(e){return e.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/,"").replace(/\.(py|pyi)$/,"").replace(/\.(rs)$/,"").replace(/\.(java|scala|kt|kts)$/,"").replace(/\.(rb)$/,"").replace(/\.(go)$/,"").replace(/\.(cs|vb)$/,"").replace(/\.(dart)$/,"").replace(/\.(php)$/,"").replace(/\.(c|cc|cpp|cxx|h|hpp)$/,"")}function k(e){let t=V(e);if("kind"in t&&t.kind==="local")return t.id;let n=t;return n.descriptors.length===0?"":n.descriptors[n.descriptors.length-1].name}function z(e){let t=V(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function G(e){return e.endsWith("().")||z(e)==="method"}function U(e){let t=z(e);return t==="method"||t==="term"}function Me(e){return z(e)==="namespace"}var pf=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function un(e){return pf.test(e)}var gf=new Set(["test","tests","_tests"]);function Oe(e){let t=V(e);if("kind"in t)return!1;for(let n=0;n<t.descriptors.length-1;n+=1){let r=t.descriptors[n];if(r?.suffix==="namespace"&&r.name&&gf.has(r.name))return!0}return!1}function Ps(e,t){let n=V(e),r=V(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,s=r.descriptors;if(s.length!==i.length+1)return!1;for(let o=0;o<i.length;o++){let a=i[o],l=s[o];if(a.name!==l.name||a.suffix!==l.suffix)return!1}return!0}function Ms(e,t){let n=V(e),r=V(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,s=r.descriptors;if(s.length<=i.length)return!1;for(let o=0;o<i.length;o++){let a=i[o],l=s[o];if(a.name!==l.name||a.suffix!==l.suffix)return!1}return!0}function Ge(e){return!e||!e.trim()?null:e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim()||null}function Ke(e){if(!e)return null;let t=Os(e);if(t)return t.replace(/\n/g," ");let n=e.indexOf("|");if(n===-1)return e.replace(/\n/g," ");let r=e.slice(n+1);return(Os(r)??r).replace(/\n/g," ")}function Os(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}var Fs=j("file-definitions");function As(e,t){Fs.invalidate(e,t)}function J(e,t){return Fs.get(e,t,()=>{let n=Sf(hf(e,t),yf(e,t));return _f(e,t,n.map(bf))})}function hf(e,t){return e.all(`SELECT
208
- gs.id,
209
- gs.symbol,
210
- der.document_id,
211
- der.start_line,
212
- der.end_line,
213
- d.relative_path,
214
- gs.display_name,
215
- gs.kind,
216
- gs.documentation,
217
- gs.enclosing_symbol
50
+ `},Am=new WeakMap;function Nt(e,t){return ni(e,t,Am,Fm,n=>{let r=[];for(let i of n){let o=null,s=null;for(let c of i.captures)c.name==="target"?o=c.node:c.name==="call"&&(s=c.node);if(!o||!s)continue;let a=Dt(o);a&&r.push({calleeLeaf:a,memberAccess:$m(o),line:s.startPosition.row})}return r})}function $m(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}var jm=new WeakMap;function ti(e,t){return tn(e,t,jm,()=>new Map,(n,r,i)=>{let o=(c,l)=>{if(c===l)return;let u=i.get(c);u||(u=new Set,i.set(c,u)),u.add(l)},s=r==="python"?new Set(["identifier"]):new Set(["type_identifier"]),a=(c,l)=>{let u=m=>{s.has(m.type)&&m.text!==l&&o(m.text,l);for(let d of m.children)u(d)};for(let m of c.children)u(m)};if(r==="rust")for(let c of n.rootNode.descendantsOfType(["struct_item","enum_item","union_item","type_item"])){let l=c.namedChildren.find(m=>m.type==="type_identifier")?.text;if(!l)continue;let u=c.namedChildren.find(m=>m.type==="field_declaration_list"||m.type==="enum_variant_list"||m.type==="ordered_field_declaration_list");u&&a(u,l),c.type==="type_item"&&a(c,l)}else if(r==="python")for(let c of n.rootNode.descendantsOfType("class_definition")){let l=c.namedChildren.find(m=>m.type==="identifier")?.text;if(!l)continue;let u=c.namedChildren.find(m=>m.type==="block");if(u)for(let m of u.descendantsOfType("type"))for(let d of m.descendantsOfType("identifier"))d.text!==l&&o(d.text,l)}else for(let c of n.rootNode.descendantsOfType(["interface_declaration","type_alias_declaration","class_declaration"])){let l=c.namedChildren.find(u=>u.type==="type_identifier")?.text;l&&a(c,l)}})??new Map}function tn(e,t,n,r,i){let o=P(t);if(!o)return null;let s=B(e,t);if(!s)return null;let a=n.get(s);if(a)return a;let c=r();return i(s,o,c),n.set(s,c),c}function ni(e,t,n,r,i){let o=P(t);if(!o)return null;let s=r[o];if(!s)return null;let a=B(e,t);if(!a)return null;let c=n.get(a);if(c)return c;let l=_s(o,s);if(!l)return null;let u=i(l.matches(a.rootNode));return n.set(a,u),u}function Dt(e){switch(e.type){case"identifier":case"type_identifier":case"property_identifier":case"shorthand_property_identifier":return e.text;case"field_expression":case"member_expression":case"attribute":{let t=e.namedChild(e.namedChildCount-1);return t?Dt(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?Dt(t):null}case"super":case"self":case"this":return null;default:return null}}var Bm={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function Q(e){if(e.startsWith("local "))return{kind:"local",id:e.slice(6),raw:e};let t=e.split(" ");if(t.length<4)return{scheme:t[0]??"",manager:t[1]??"",packageName:t[2]??"",version:"",descriptors:[],raw:e};let n=t[0],r=t[1],i=e.slice(n.length+1+r.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let s,a=i.indexOf(" ");a===-1?(s=i,i=""):(s=i.slice(0,a),i=i.slice(a+1));let c=Hm(i);return{scheme:n,manager:r,packageName:o,version:s,descriptors:c,raw:e}}function Te(e){let t=Q(e);if("kind"in t)return null;for(let n=t.descriptors.length-2;n>=0;n--){let r=t.descriptors[n];if(r?.suffix==="type")return r.name}return null}function Hm(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="["){let o=e.indexOf("]",n+1);if(o===-1){t.push({name:e.slice(n+1),suffix:"type-param"});break}t.push({name:e.slice(n+1,o),suffix:"type-param"}),n=o+1;continue}if(e[n]==="("&&(t.length===0||n===0||Ls(e[n-1]))){let o=e.indexOf(")",n+1);if(o!==-1&&e[o+1]!=="."){t.push({name:e.slice(n+1,o),suffix:"parameter"}),n=o+1;continue}}let r;if(e[n]==="`"){let o=e.indexOf("`",n+1);if(o===-1){r=e.slice(n+1),t.push({name:r,suffix:"term"});break}r=e.slice(n+1,o),n=o+1}else{let o=n;for(;n<e.length&&!Ls(e[n]);)n++;r=e.slice(o,n)}if(n>=e.length){r&&t.push({name:r,suffix:"term"});break}let i=e[n];if(i==="("){let o=e.indexOf(")",n+1);o!==-1&&e[o+1]==="."?(t.push({name:r,suffix:"method"}),n=o+2):o!==-1?(t.push({name:r,suffix:"method"}),n=o+1):(t.push({name:r,suffix:"term"}),n++)}else{let o=Bm[i];o&&t.push({name:r,suffix:o}),n+=1}}return t}function Ls(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function h(e){let t=Q(e);if("kind"in t&&t.kind==="local")return`local:${t.id}`;let n=t;if(n.descriptors.length===0)return n.raw;let r=[];for(let i of n.descriptors){let o=Wm(i);o&&r.push(o)}return r.join(":")}function Wm(e){let t=e.suffix==="namespace"?Vm(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function Vm(e){return e.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/,"").replace(/\.(py|pyi)$/,"").replace(/\.(rs)$/,"").replace(/\.(java|scala|kt|kts)$/,"").replace(/\.(rb)$/,"").replace(/\.(go)$/,"").replace(/\.(cs|vb)$/,"").replace(/\.(dart)$/,"").replace(/\.(php)$/,"").replace(/\.(c|cc|cpp|cxx|h|hpp)$/,"")}function L(e){let t=Q(e);if("kind"in t&&t.kind==="local")return t.id;let n=t;return n.descriptors.length===0?"":n.descriptors[n.descriptors.length-1].name}function ee(e){let t=Q(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function te(e){return e.endsWith("().")||ee(e)==="method"}function K(e){let t=ee(e);return t==="method"||t==="term"}function Ve(e){return ee(e)==="namespace"}var qm=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function Bn(e){return qm.test(e)}var Um=new Set(["test","tests","_tests"]);function qe(e){let t=Q(e);if("kind"in t)return!1;for(let n=0;n<t.descriptors.length-1;n+=1){let r=t.descriptors[n];if(r?.suffix==="namespace"&&r.name&&Um.has(r.name))return!0}return!1}function Es(e,t){let n=Q(e),r=Q(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,o=r.descriptors;if(o.length!==i.length+1)return!1;for(let s=0;s<i.length;s++){let a=i[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function ws(e,t){let n=Q(e),r=Q(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,o=r.descriptors;if(o.length<=i.length)return!1;for(let s=0;s<i.length;s++){let a=i[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function Lt(e,t){return e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name, gs.documentation
218
51
  FROM global_symbols gs
219
52
  JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
220
53
  JOIN documents d ON der.document_id = d.id
221
- WHERE d.relative_path = ?
222
- ${e.symbolNoiseFor("gs")}
223
- ORDER BY der.start_line, der.end_line`,t)}function yf(e,t){return e.all(`SELECT
224
- gs.id,
225
- gs.symbol,
226
- c.document_id,
227
- MIN(c.start_line) AS start_line,
228
- MAX(c.end_line) AS end_line,
229
- d.relative_path,
230
- gs.display_name,
231
- gs.kind,
232
- gs.documentation,
233
- gs.enclosing_symbol
234
- FROM global_symbols gs
235
- JOIN mentions m ON m.symbol_id = gs.id
236
- JOIN chunks c ON m.chunk_id = c.id
237
- JOIN documents d ON c.document_id = d.id
238
- WHERE d.relative_path = ?
239
- AND m.role = 1
240
- ${e.symbolNoiseFor("gs")}
241
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
242
- ORDER BY start_line, end_line`,t)}function bf(e){return{symbolId:e.id,symbol:e.symbol,documentId:e.document_id,startLine:e.start_line,endLine:e.end_line,relativePath:e.relative_path,leaf:k(e.symbol),parentTypeName:Qe(e.symbol),isFunctionLike:U(e.symbol),isTypeLike:z(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function Sf(e,t){let n=new Map;for(let r of t)e.length>0&&!xf(r)||n.set(r.id,r);for(let r of e)n.set(r.id,r);return[...n.values()].sort((r,i)=>r.start_line-i.start_line||r.end_line-i.end_line||r.symbol.localeCompare(i.symbol))}function xf(e){if(Qe(e.symbol)!==null)return!1;let n=(e.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(n)}function _e(e,t={}){return xr(e,t.scope)}function xr(e,t){let n=t?`AND relative_path LIKE '%${t}%'`:"";return e.all(`SELECT relative_path
243
- FROM documents
244
- WHERE 1 = 1
245
- ${e.pathExclusionsFor("documents")}
246
- ${n}
247
- ORDER BY relative_path`).flatMap(r=>J(e,r.relative_path)).filter(r=>!e.isIgnored(r.relativePath))}function at(e,t,n={}){if(t.length===0)return[];let r=t.flatMap(i=>J(e,i)).filter(i=>!e.isIgnored(i.relativePath));return n.onlyDocumented&&(r=r.filter(i=>i.documentation!==null&&i.documentation!=="")),n.sort&&(r=r.sort((i,s)=>i.relativePath.localeCompare(s.relativePath)||i.startLine-s.startLine||i.endLine-s.endLine)),r.map(i=>({startLine:i.startLine,endLine:i.endLine,symbol:i.symbol,shortName:y(i.symbol),signature:Ge(Ke(i.documentation)),relativePath:i.relativePath,enclosingSymbol:i.enclosingSymbol}))}function le(e,t){let n=null;for(let r of e)r.startLine>t||r.endLine<t||(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r);return n}function Ye(e,t){let n=J(e,t.relative_path).find(r=>r.symbolId===t.id);return n?{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,endLine:n.endLine,relativePath:n.relativePath}:{symbolId:t.id,symbol:t.symbol,documentId:t.document_id,startLine:t.start_line,endLine:t.end_line,relativePath:t.relative_path}}function _f(e,t,n){let r=M(e,t),i=Es(e,t);return i?Ef(n,i,r):r?If(n,r):n}function If(e,t){let n=t.split(/\r?\n/),r=Rf(e,n),i=Cf(e,r),s=vf(i,n);return Nf(e,s)}function Rf(e,t){let n=e.some(i=>dn(i.symbol))?Lf(t):null,r=new Map;for(let i of e)r.set(i.symbolId,Df(t,n,i));return r}function Cf(e,t){return e.filter(n=>dn(n.symbol)).map(n=>({definition:n,startLine:t.get(n.symbolId)??n.startLine})).sort((n,r)=>n.startLine-r.startLine||n.definition.startLine-r.definition.startLine||n.definition.symbol.localeCompare(r.definition.symbol))}function vf(e,t){let n=new Map;for(let r=0;r<e.length;r+=1){let i=e[r],s=e[r+1],o=s?Math.max(i.startLine,s.startLine-1):t.length-1;n.set(i.definition.symbolId,{startLine:i.startLine,endLine:wf(t,i.definition,i.startLine,o)})}return n}function Nf(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function Ef(e,t,n=null){let r=new Map;for(let i of t){let s=r.get(i.name);s?s.push(i):r.set(i.name,[i])}return e.map(i=>{if(!dn(i.symbol)||!i.leaf)return Ts(i,n);let s=r.get(i.leaf);if(!s||s.length===0)return Ts(i,n);let o=s[0],a=Math.abs(o.startLine-i.startLine);for(let l=1;l<s.length;l+=1){let c=s[l],u=Math.abs(c.startLine-i.startLine);u<a&&(o=c,a=u)}return{...i,startLine:o.startLine,endLine:o.endLine}})}function Ts(e,t){if(!t||!e.leaf||z(e.symbol)!=="term"||Qe(e.symbol)!==null)return e;let n=e.leaf.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`),s=t.split(/\r?\n/).findIndex(o=>r.test(o));return s>=0?{...e,startLine:s,endLine:s}:e}function Df(e,t,n){if(!dn(n.symbol))return n.startLine;let r=Math.max(0,Math.min(n.startLine,e.length-1));if(!t)return r;let i=t.get(n.leaf);if(!i||i.length===0)return r;let s=null;for(let o of i){let a=Math.abs(o-n.startLine);(!s||a<s.distance)&&(s={line:o,distance:a})}return s?.line??r}function Lf(e){let t=/\b(?:function|def|fn)\s+([A-Za-z_$][\w$]*)/g,n=/\b([A-Za-z_$][\w$]*)\s*[:=]\s*(?:async\s*)?(?:function\b|\()/g,r=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,i=/\b([A-Za-z_$][\w$]*)\s*\(/g,s=new Map,o=(a,l)=>{let c=s.get(a);if(!c){s.set(a,[l]);return}c[c.length-1]!==l&&c.push(l)};for(let a=0;a<e.length;a+=1){let l=e[a]??"";for(let u of l.matchAll(t))u[1]&&o(u[1],a);for(let u of l.matchAll(n))u[1]&&o(u[1],a);let c=l.match(r);c?.[1]&&o(c[1],a);for(let u of l.matchAll(i))u[1]&&o(u[1],a)}return s}function wf(e,t,n,r){let i=Math.max(n,Math.min(e.length-1,r)),s=Math.max(n,Math.min(i,t.endLine)),o=0,a=0,l=!1;for(let c=n;c<=i;c+=1){let u=kf(e[c]??"");for(let d of u)d==="{"?(o+=1,l=!0):d==="}"?o=Math.max(0,o-1):d==="("?a+=1:d===")"&&(a=Math.max(0,a-1));if(l&&o===0||!l&&a===0&&c>=s)return c}return s}function kf(e){let t="",n=null,r=!1;for(let i=0;i<e.length;i+=1){let s=e[i],o=e[i+1];if(!n&&s==="/"&&o==="/"){t+=" ".repeat(e.length-i);break}if(n){if(r){r=!1,t+=" ";continue}if(s==="\\"){r=!0,t+=" ";continue}s===n&&(n=null),t+=" ";continue}if(s==='"'||s==="'"||s==="`"){n=s,t+=" ";continue}t+=s}return t}function dn(e){return e.includes("().")}function Qe(e){let t=V(e);if("kind"in t)return null;for(let n=t.descriptors.length-2;n>=0;n--){let r=t.descriptors[n];if(r?.suffix==="type")return r.name}return null}function _r(e){let t=V(e);if("kind"in t)return[];let n=[];for(let r=t.descriptors.length-2;r>=0;r-=1){let i=t.descriptors[r];i?.suffix==="type"&&i.name&&n.push(i.name)}return n}import{existsSync as qf}from"fs";import{basename as $s,isAbsolute as zf,join as Gf}from"path";function w(e,t){let n=ct(e,t.trim());if(n)return n;let r=Af(e,t);if(r)return r;let i=Pf(e,t);return i||Ff(e,t)}function Pf(e,t){let n=Cr(t),r=Rr(n);if(!r)return null;let i=`%${r.path}%`,s=r.leaf,a=Mf(e,i,s,n)[0];return a?Ye(e,a):null}function Mf(e,t,n,r){let i=Ir([],[...Of(e,t,n),...Tf(e,t,n)]).filter(s=>!e.isIgnored(s.relative_path)).filter(s=>lt(s,r)>1);return i.sort((s,o)=>lt(o,r)-lt(s,r)||s.end_line-s.start_line-(o.end_line-o.start_line)||s.start_line-o.start_line||s.symbol.localeCompare(o.symbol)),i}function Of(e,t,n){return e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name, gs.documentation
248
- FROM global_symbols gs
249
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
250
- JOIN documents d ON der.document_id = d.id
251
- WHERE d.relative_path LIKE ?
252
- AND (gs.display_name = ? OR gs.symbol LIKE ?)
253
- ${e.pathExclusionsFor("d")}`,t,n,`%/${n}.%`)}function Tf(e,t,n){return e.all(`SELECT
54
+ WHERE ${t.where}
55
+ ${e.pathExclusionsFor("d")}
56
+ ${Ps(t.orderBy)}
57
+ ${Ts(t.limit)}`,...t.params??[])}function Et(e,t){return e.all(`SELECT
254
58
  gs.id,
255
59
  gs.symbol,
256
60
  c.document_id,
@@ -264,81 +68,27 @@ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
264
68
  JOIN chunks c ON m.chunk_id = c.id
265
69
  JOIN documents d ON c.document_id = d.id
266
70
  WHERE m.role = 1
267
- AND d.relative_path LIKE ?
268
- AND (gs.display_name = ? OR gs.symbol LIKE ?)
269
- ${e.pathExclusionsFor("d")}
270
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation`,t,n,`%/${n}.%`)}function Ff(e,t){let n=Cr(t),r=Vf(t),i=Hf(e,r),s=Jf(i,t,n);if(s&&!e.isIgnored(s.relative_path))return Ye(e,s);let o=null;for(let a of i){if(e.isIgnored(a.relative_path))continue;let l=Uf(a,t,n,r);l<=0||(!o||l>o.score)&&(o={row:a,score:l})}return o?Ye(e,o.row):null}function Af(e,t){let n=t.match(/^(.+):(\d+)-(\d+)$/);if(!n)return null;let[,r,i,s]=n,o=Math.max(0,parseInt(i,10)-1),a=Math.max(o,parseInt(s,10)-1),l=$f(e,r,o,a)??jf(e,r,o,a);return l&&!e.isIgnored(l.relative_path)?Ye(e,l):null}function $f(e,t,n,r){return e.get(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path
271
- FROM global_symbols gs
272
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
273
- JOIN documents d ON der.document_id = d.id
274
- WHERE d.relative_path LIKE ?
275
- AND der.start_line <= ? AND der.end_line >= ?
276
- ${e.pathExclusionsFor("d")}
277
- ORDER BY (der.end_line - der.start_line) ASC
278
- LIMIT 1`,`%${t}%`,n,r)}function jf(e,t,n,r){return e.get(`SELECT gs.id, gs.symbol, c.document_id, MIN(c.start_line) AS start_line, MAX(c.end_line) AS end_line, d.relative_path
279
- FROM global_symbols gs
280
- JOIN mentions m ON m.symbol_id = gs.id
281
- JOIN chunks c ON m.chunk_id = c.id
282
- JOIN documents d ON c.document_id = d.id
283
- WHERE m.role = 1
284
- AND d.relative_path LIKE ?
285
- AND c.start_line <= ? AND c.end_line >= ?
71
+ AND ${t.where}
286
72
  ${e.pathExclusionsFor("d")}
287
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
288
- ORDER BY (MAX(c.end_line) - MIN(c.start_line)) ASC
289
- LIMIT 1`,`%${t}%`,n,r)}function ct(e,t){let r=e.get(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path
290
- FROM global_symbols gs
291
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
292
- JOIN documents d ON der.document_id = d.id
293
- WHERE gs.symbol = ?
294
- ${e.pathExclusionsFor("d")}
295
- ORDER BY d.relative_path, der.start_line
296
- LIMIT 1`,t)??e.get(`SELECT
297
- gs.id,
298
- gs.symbol,
299
- c.document_id,
300
- MIN(c.start_line) AS start_line,
301
- MAX(c.end_line) AS end_line,
302
- d.relative_path
303
- FROM global_symbols gs
304
- JOIN mentions m ON m.symbol_id = gs.id
305
- JOIN chunks c ON m.chunk_id = c.id
306
- JOIN documents d ON c.document_id = d.id
307
- WHERE gs.symbol = ?
308
- AND m.role = 1
309
- ${e.pathExclusionsFor("d")}
310
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
311
- ORDER BY d.relative_path, start_line
312
- LIMIT 1`,t);return!r||e.isIgnored(r.relative_path)?null:Ye(e,r)}function mn(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=Bf(e,t.symbolId)[0];return n?Ye(e,n):null}function Bf(e,t){let n=e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name, gs.documentation
313
- FROM global_symbols gs
314
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
315
- JOIN documents d ON der.document_id = d.id
316
- WHERE gs.id = ?
317
- ORDER BY der.start_line, der.end_line`,t),r=e.all(`SELECT
73
+ GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
74
+ ${Ps(t.orderBy)}
75
+ ${Ts(t.limit)}`,...t.params??[])}function Ps(e){return e?`ORDER BY ${e}`:""}function Ts(e){return typeof e=="number"?`LIMIT ${e}`:""}function at(e){return!e||!e.trim()?null:e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim()||null}function ct(e){if(!e)return null;let t=ks(e);if(t)return t.replace(/\n/g," ");let n=e.indexOf("|");if(n===-1)return e.replace(/\n/g," ");let r=e.slice(n+1);return(ks(r)??r).replace(/\n/g," ")}function ks(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function Jm(e){if(Te(e.symbol)!==null)return!1;let n=(e.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(n)}function wt(e,t,n={}){let r=new Map;for(let o of t)e.length>0&&!Jm(o)||r.set(o.id,o);for(let o of e)r.set(o.id,o);let i=[...r.values()];return n.sort?i.sort((o,s)=>o.start_line-s.start_line||o.end_line-s.end_line||o.symbol.localeCompare(s.symbol)):i}var Os=H("file-definitions");function Fs(e,t){Os.invalidate(e,t)}function V(e,t){return Os.get(e,t,()=>{let n=wt(zm(e,t),Gm(e,t),{sort:!0});return Qm(e,t,n.map(Km))})}function zm(e,t){return e.all(`SELECT
318
76
  gs.id,
319
77
  gs.symbol,
320
- c.document_id,
321
- MIN(c.start_line) AS start_line,
322
- MAX(c.end_line) AS end_line,
78
+ der.document_id,
79
+ der.start_line,
80
+ der.end_line,
323
81
  d.relative_path,
324
82
  gs.display_name,
325
- gs.documentation
326
- FROM global_symbols gs
327
- JOIN mentions m ON m.symbol_id = gs.id
328
- JOIN chunks c ON m.chunk_id = c.id
329
- JOIN documents d ON c.document_id = d.id
330
- WHERE gs.id = ?
331
- AND m.role = 1
332
- ${e.pathExclusionsFor("d")}
333
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
334
- ORDER BY start_line, end_line`,t);return Ir(n,r)}function Hf(e,t){let n=t.map(()=>"(gs.symbol LIKE ? OR d.relative_path LIKE ? OR COALESCE(gs.display_name, '') LIKE ?)"),r=t.flatMap(o=>{let a=`%${o}%`;return[a,a,a]}),i=e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name, gs.documentation
83
+ gs.kind,
84
+ gs.documentation,
85
+ gs.enclosing_symbol
335
86
  FROM global_symbols gs
336
87
  JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
337
88
  JOIN documents d ON der.document_id = d.id
338
- WHERE ${n.join(`
339
- AND `)}
340
- ${e.pathExclusionsFor("d")}
341
- LIMIT 200`,...r),s=e.all(`SELECT
89
+ WHERE d.relative_path = ?
90
+ ${e.symbolNoiseFor("gs")}
91
+ ORDER BY der.start_line, der.end_line`,t)}function Gm(e,t){return e.all(`SELECT
342
92
  gs.id,
343
93
  gs.symbol,
344
94
  c.document_id,
@@ -346,40 +96,79 @@ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function
346
96
  MAX(c.end_line) AS end_line,
347
97
  d.relative_path,
348
98
  gs.display_name,
349
- gs.documentation
99
+ gs.kind,
100
+ gs.documentation,
101
+ gs.enclosing_symbol
350
102
  FROM global_symbols gs
351
103
  JOIN mentions m ON m.symbol_id = gs.id
352
104
  JOIN chunks c ON m.chunk_id = c.id
353
105
  JOIN documents d ON c.document_id = d.id
354
- WHERE m.role = 1
355
- AND ${n.join(`
356
- AND `)}
357
- ${e.pathExclusionsFor("d")}
358
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
359
- LIMIT 200`,...r);return Ir(i,s)}function Ir(e,t){let n=new Map;for(let r of t)e.length>0&&!Wf(r)||n.set(r.id,r);for(let r of e)n.set(r.id,r);return[...n.values()]}function Wf(e){if(Qe(e.symbol)!==null)return!1;let n=(e.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(n)}function Uf(e,t,n,r){let i=t.trim(),s=n,o=s.replace(/\(\)$/,""),a=t.toLowerCase(),l=n.toLowerCase(),c=l.replace(/\(\)$/,""),u=e.symbol,d=y(e.symbol),m=k(e.symbol),f=e.display_name??"",h=e.symbol.toLowerCase(),p=d.toLowerCase(),g=m.toLowerCase(),b=f.toLowerCase(),_=e.relative_path.toLowerCase(),P=/[/:.]/.test(n),L=Rr(n),C=L?.leaf.toLowerCase(),v=0;return(u===i||u===s)&&(v+=1150),(d===i||d===s)&&(v+=1100),f===o&&(v+=1180),m===o&&(v+=1160),(`${m}()`===i||`${m}()`===s)&&(v+=955),(h===a||h===l)&&(v+=1e3),(p===a||p===l)&&(v+=950),(_===a||_===l)&&(v+=925),(_.endsWith(`/${l}`)||_.endsWith(`/${a}`))&&(v+=875),b===c&&(v+=850),g===c&&(v+=825),(`${g}()`===a||`${g}()`===l)&&(v+=820),(p.endsWith(`:${l}`)||p.endsWith(`:${c}`)||p.endsWith(`:${c}()`))&&(v+=800),h.includes(l)&&(v+=120),p.includes(l)&&(v+=140),_.includes(l)&&(v+=140),b.includes(l)&&(v+=110),r.every(T=>{let D=T.toLowerCase();return h.includes(D)||p.includes(D)||_.includes(D)||b.includes(D)})&&(v+=100+r.length*15),L&&_.includes(L.path.toLowerCase())&&(v+=360,C&&(g===C||`${g}()`===C||`${g}()`==`${C}()`)&&(v+=700),G(e.symbol)&&(v+=180)),U(e.symbol)&&g===c&&(v+=60),!P&&Me(e.symbol)&&(v-=160),v-=Math.min(50,Math.max(0,e.end_line-e.start_line)),v}function Rr(e){let t=e.trim().replace(/\\/g,"/"),n=t.lastIndexOf("/");if(n<=0||n===t.length-1)return null;let r=t.slice(n+1).replace(/\(\)$/,"");return!r||r.includes(".")?null:{path:t.slice(0,n),leaf:r}}function Cr(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function Vf(e){let t=Cr(e),n=t.split(/[^A-Za-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>0);return n.length>0?[...new Set(n)]:[t]}function Jf(e,t,n){let r=t.trim(),i=e.filter(s=>{let o=y(s.symbol),a=(s.display_name??"").trim();return s.symbol===r||o===r||o===n||a===r||a===n||`${a}()`===r||lt(s,n)>1||s.relative_path===r});return i.length===0?null:(i.sort((s,o)=>lt(o,n)-lt(s,n)||s.end_line-s.start_line-(o.end_line-o.start_line)||s.relative_path.localeCompare(o.relative_path)||s.symbol.localeCompare(o.symbol)),i[0]??null)}function lt(e,t){let n=Rr(t);if(!n)return 0;let r=e.relative_path.toLowerCase(),i=k(e.symbol).toLowerCase(),s=n.path.toLowerCase(),o=n.leaf.toLowerCase();return r.includes(s)?i!==o?1:G(e.symbol)?Qe(e.symbol)===null?5:4:Qe(e.symbol)===null?3:2:0}function Q(e,t){let n=js(e,t,{allowMultiple:!1})[0]?.relativePath;return n||Kf(e,t)}function Te(e,t){return js(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function Kf(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=zf(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=Gf(e.config.projectRoot,r);return qf(i)?r:null}function js(e,t,n){let r=Bs(t);if(!r)return[];let s=e.all(`SELECT relative_path
360
- FROM documents
361
- WHERE 1 = 1
362
- ${e.pathExclusionsFor("documents")}
363
- ORDER BY relative_path`).filter(l=>!e.isIgnored(l.relative_path)).map(l=>({relativePath:l.relative_path,score:Yf(l.relative_path,r)})).filter(l=>l.score>0).sort((l,c)=>c.score-l.score||l.relativePath.localeCompare(c.relativePath));if(s.length===0){let l=w(e,t);return!l||e.isIgnored(l.relativePath)?[]:[{relativePath:l.relativePath,score:700}]}let o=s.filter(l=>l.score>=1100);if(o.length>0)return n.allowMultiple?o:[o[0]];let a=s.filter(l=>l.score>=800);return a.length>0?n.allowMultiple?a:[a[0]]:n.allowMultiple?s:[s[0]]}function Yf(e,t){let n=Bs(e),r=$s(n),i=$s(t),s=0;return n===t&&(s+=1200),n.endsWith(`/${t}`)&&(s+=1100),r===i&&(s+=900),n.startsWith(`${t}/`)&&(s+=850),n.includes(t)&&(s+=250),s}function Bs(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}function Hs(e,t){let n=Te(e,t);return at(e,n).map(({relativePath:r,...i})=>i)}import{basename as iy}from"path";var _t=new WeakMap;function Vs(e,t){let n=F(t);return n==="rust"?tp(e,t):n==="typescript"||n==="tsx"||n==="javascript"?Xf(e,t):[]}var Qf=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]);function Xf(e,t){let n=O(e,t);if(!n)return[];let r=_t.get(n);if(r)return r;let i=/(^|\/)(pages|app)\/.+\.(tsx?|jsx?)$/.test(t)||/(^|\/)(layout|page|loading|error|not-found|head|template|default)\.(tsx?|jsx?)$/.test(t),s=/(^|\/)src\/(pages|views|routes)\/.+\.(tsx?|jsx?|vue)$/.test(t),o=!1,a=n.rootNode;for(let c of a.namedChildren){if(c.type!=="expression_statement")continue;let u=c.namedChild(0);if(!u||u.type!=="call_expression")continue;let d=u.namedChild(0);if(!d)continue;let m=d.type==="member_expression"?d.namedChild(d.namedChildCount-1)?.text:d.text;if(m&&Qf.has(m)){o=!0;break}}let l=[];o&&l.push({startLine:0,endLine:a.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"}),(i||s)&&l.push({startLine:0,endLine:a.endPosition.row,reason:i?"Next.js / Remix route file":"Vite/Vue route component"});for(let c of a.namedChildren){let u=null,d=null;if(c.type==="function_declaration")u=c.namedChild(0)?.text??null,d=c;else if(c.type==="export_statement"){let m=c.namedChild(0);m?.type==="function_declaration"&&(u=m.namedChild(0)?.text??null,d=m)}else if(c.type==="lexical_declaration"){let m=c.namedChild(0);if(m?.type==="variable_declarator"){let f=m.namedChild(0)?.text,h=m.namedChild(1);f&&(h?.type==="arrow_function"||h?.type==="function_expression")&&(u=f,d=m)}}u&&/^use[A-Z]/.test(u)&&d&&l.push({startLine:d.startPosition.row,endLine:d.endPosition.row,reason:"React custom hook (use*)"})}return l.push(...Js(n,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),_t.set(n,l),l}var Zf=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function ep(e){return Zf.test(e)}function Js(e,t,n){let r=[],i=s=>{if(t.has(s.type)&&s.parent){let a=s.parent.children,l=-1;for(let c=0;c<a.length;c+=1)if(a[c].startIndex===s.startIndex&&a[c].type===s.type){l=c;break}if(l>0)for(let c=l-1;c>=0;c-=1){let u=a[c];if(n.has(u.type)){if(ep(u.text)){r.push({startLine:s.startPosition.row,endLine:s.endPosition.row,reason:"scip-query suppression comment"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let o of s.namedChildren)i(o)};return i(e.rootNode),r}function tp(e,t){let n=O(e,t);if(!n)return[];let r=_t.get(n);if(r)return r;let i=[],s=np(n);return s?(_t.set(n,s),s):(qs(n.rootNode,i,!1,!1),i.push(...Js(n,new Set(["function_item","function_signature_item","struct_item","enum_item","union_item","impl_item","mod_item","static_item","const_item"]),new Set(["line_comment","block_comment"]))),i.push(...lp(n.rootNode)),_t.set(n,i),i)}function np(e){return cp(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function qs(e,t,n,r){let i=n,s=r;e.type==="trait_item"&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait declaration body (dynamic dispatch)"}),e.type==="impl_item"&&e.childForFieldName("trait")&&(s=!0,t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl block (dynamic dispatch)"})),e.type==="function_item"||e.type==="function_signature_item"?rp(e,t,n,r):r&&ap(e)?t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)"}):e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item"?ip(e,t,n):e.type==="mod_item"&&vr(e).some(o=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(o))&&(i=!0);for(let o of e.namedChildren)qs(o,t,i,s)}function rp(e,t,n,r){let i=vr(e),s=null;r?s="trait impl method (dynamic dispatch)":n&&(s="inside #[cfg(test)] mod");for(let o of i){let a=sp(o);if(a){s=a;break}if(zs(o)){s="#[allow(dead_code)]";break}}s&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:s})}function ip(e,t,n){let r=vr(e),i=e.namedChildren.find(s=>s.type==="type_identifier")?.text;r.some(op)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:i}),r.some(zs)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",containerName:i})}function vr(e){let t=e.parent;if(!t)return[];let n=t.children,r=-1;for(let s=0;s<n.length;s+=1)if(n[s].startIndex===e.startIndex&&n[s].type===e.type){r=s;break}if(r<=0)return[];let i=[];for(let s=r-1;s>=0;s-=1){let o=n[s];if(o.type==="attribute_item"||o.type==="inner_attribute_item")i.push(o.text);else{if(o.type==="line_comment"||o.type==="block_comment")continue;break}}return i}function sp(e){return/#\[\s*tauri::command\b/.test(e)?"#[tauri::command]":/#\[\s*command\b/.test(e)?"#[command]":/#\[\s*test\b/.test(e)?"#[test]":/#\[\s*bench\b/.test(e)?"#[bench]":/#\[\s*tokio::test\b/.test(e)?"#[tokio::test]":/#\[\s*async_std::test\b/.test(e)?"#[async_std::test]":/#\[\s*wasm_bindgen\b/.test(e)?"#[wasm_bindgen]":/#\[\s*no_mangle\b/.test(e)?"#[no_mangle]":/#\[\s*napi\b/.test(e)?"#[napi]":/#\[\s*pyfunction\b/.test(e)?"#[pyfunction]":/#\[\s*pymethod\b/.test(e)?"#[pymethod]":/#\[\s*pyo3\b/.test(e)?"#[pyo3]":/#\[\s*cfg\s*\(\s*test\s*\)/.test(e)?"#[cfg(test)]":/#\[\s*doc\s*\(\s*hidden\s*\)/.test(e)?"#[doc(hidden)]":null}function op(e){return/#\[\s*derive\s*\(/.test(e)?/\bSerialize\b/.test(e)||/\bDeserialize\b/.test(e)||/\bFromRow\b/.test(e)||/\bDeriveEntityModel\b/.test(e)||/\bIntoSchema\b/.test(e)||/\bToSchema\b/.test(e)||/\bDeriveValueType\b/.test(e)||/\bsqlx::FromRow\b/.test(e)||/\bError\b/.test(e)||/\bthiserror::Error\b/.test(e):!1}function zs(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function ap(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function lp(e){let t=pp(e);if(t.size===0)return[];let n=[];for(let r of e.descendantsOfType("mod_item")){let i=r.childForFieldName("name")?.text;i&&t.has(i)&&n.push({startLine:r.startPosition.row,endLine:r.endPosition.row,reason:'serde `with = "..."` module \u2014 body invoked via reflection',containerName:i})}return n}function cp(e){for(let t=0;t<Math.min(e.namedChildCount,12);t+=1){let n=e.namedChild(t);if(!n||n.type!=="line_comment"&&n.type!=="block_comment")break;if(/@generated\b/.test(n.text)||/This file is .*generated\b/i.test(n.text)||/Code generated by/i.test(n.text)||/Generated by:\s*https?:\/\/openapi-generator/i.test(n.text)||/openapi-generator/i.test(n.text)&&/Generated by/i.test(n.text))return!0}return!1}var up=[{key:"default",re:/\bdefault\s*=\s*"([^"]+)"/g},{key:"with",re:/\bwith\s*=\s*"([^"]+)"/g},{key:"serialize_with",re:/\bserialize_with\s*=\s*"([^"]+)"/g},{key:"deserialize_with",re:/\bdeserialize_with\s*=\s*"([^"]+)"/g},{key:"skip_serializing_if",re:/\bskip_serializing_if\s*=\s*"([^"]+)"/g},{key:"getter",re:/\bgetter\s*=\s*"([^"]+)"/g},{key:"rename_all_with",re:/\brename_all_with\s*=\s*"([^"]+)"/g},{key:"schema_with",re:/\bschema_with\s*=\s*"([^"]+)"/g}],Gs=/^#!?\[\s*serde\s*\(/,dp=/^#!?\[\s*schemars\s*\(/,mp=/^#!?\[\s*validate\s*\(/,Ws=/\bwith\s*=\s*"([^"]+)"/g;function Fe(e,t){return cn(e,t,fp,()=>new Set,(n,r,i)=>{if(r==="rust"){for(let s of n.rootNode.descendantsOfType("attribute_item"))Us(s.text,i);for(let s of n.rootNode.descendantsOfType("inner_attribute_item"))Us(s.text,i)}})??new Set}var fp=new WeakMap;function Us(e,t){let n=Gs.test(e),r=dp.test(e),i=mp.test(e);if(!(!n&&!r&&!i))for(let{re:s}of up){s.lastIndex=0;let o;for(;(o=s.exec(e))!==null;){let a=o[1],l=a.split("::").pop()??a;l==="is_none"&&/\bOption\b/.test(a)||l==="is_empty"&&/\b(String|Vec|HashMap|BTreeMap|HashSet|BTreeSet)\b/.test(a)||l&&t.add(l)}}}function pp(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!Gs.test(n.text))continue;Ws.lastIndex=0;let r;for(;(r=Ws.exec(n.text))!==null;){let i=r[1],s=i.split("::").pop()??i;s&&t.add(s)}}return t}var gp=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function fn(e,t){return cn(e,t,hp,()=>new Set,(n,r,i)=>{if(!(r!=="typescript"&&r!=="tsx"&&r!=="javascript"))for(let s of n.rootNode.descendantsOfType("call_expression")){let o=s.namedChild(0);if(!o)continue;let a=xt(o);if(!a||!gp.has(a))continue;let l=s.namedChildren.find(d=>d.type==="arguments");if(!l)continue;let c=l.namedChild(0);if(!c||c.type!=="string")continue;let u=c.namedChildren.find(d=>d.type==="string_fragment");u&&i.add(u.text)}})??new Set}var hp=new WeakMap;function gn(e){return e.replace(/'''[\s\S]*?'''/g,Ae).replace(/"""[\s\S]*?"""/g,Ae).replace(/#.*$/gm,Ae).replace(/\/\/.*$/gm,Ae).replace(/\/\*[\s\S]*?\*\//g,Ae).replace(/`(?:\\[\s\S]|[^`])*`/g,Ae).replace(/'(?:\\.|[^'\\\r\n])*'/g,Ae).replace(/"(?:\\.|[^"\\\r\n])*"/g,Ae)}function Ae(e){return e.replace(/[^\r\n]/g," ")}var Nr=qt("stripped-lines");function Ks(e,t,n){return Nr.get(e,t,n,()=>gn(n).split(`
364
- `))}function Ys(e){Nr.invalidateAll(e),pn=null,It=""}function Qs(e,t){Nr.invalidate(e,t),pn=null,It=""}var pn=null,It="";function yp(e){return pn===e||(pn=e,It=gn(e)),It}function $e(e,t,n){let r=yp(e);return`${r.slice(0,t)}${" ".repeat(n-t)}${r.slice(n)}`}function X(e,t){return new RegExp(`\\b${hn(t)}\\b`,"m").test(e)}function ut(e,t){let n=new Set,r=new RegExp(`\\b${hn(t)}\\s*\\.\\s*([A-Za-z_$][\\w$]*)`,"g");for(let i of e.matchAll(r)){let s=i[1];s&&n.add(s)}return[...n]}function hn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var bp=new Set(["identifier","type_identifier","field_identifier"]),Sp=new Set(["identifier"]),xp=new Set(["identifier","property_identifier","type_identifier"]),_p=new Set(["rust","python"]),Ip=/\{([^{}]*)\}/g,Rp=/\b([A-Za-z_][\w]*)\b/g;function yn(e,t,n,r={}){if(!n)return[];let i=M(e,t);if(!i)return[];if(i.indexOf(n)===-1)return[];if(F(t))return(Ie(e,t).get(n)??[]).filter(u=>!Xs(u,r));let s=Ks(e,t,i),o=new RegExp(`\\b${hn(n)}\\b`),a=[];for(let l=0;l<s.length;l++)Xs(l,r)||o.test(s[l]??"")&&a.push(l);return a}function Xs(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var Er=j("file-identifiers");function Zs(e,t){return Er.get(e,t,()=>new Set(Ie(e,t).keys()))}var Dr=j("file-ident-lines");function Ie(e,t){return Dr.get(e,t,()=>Cp(e,t))}var Lr=j("file-idents-by-line");function eo(e,t){return Lr.get(e,t,()=>{let n=Ie(e,t),r=0;for(let s of n.values()){let o=s[s.length-1];o!==void 0&&o>r&&(r=o)}let i=new Array(r+1);for(let s=0;s<=r;s+=1)i[s]=new Set;for(let[s,o]of n)for(let a of o)i[a].add(s);return i})}function to(e){Er.invalidateAll(e),Dr.invalidateAll(e),Lr.invalidateAll(e)}function no(e,t){Er.invalidate(e,t),Dr.invalidate(e,t),Lr.invalidate(e,t)}function Cp(e,t){let n=new Map,r=(a,l)=>{let c=n.get(a);if(!c){n.set(a,[l]);return}c[c.length-1]!==l&&c.push(l)};if(F(t)){let a=O(e,t);if(a){let l=F(t),c=l==="rust"?bp:l==="python"?Sp:xp,u=d=>{if(c.has(d.type)&&r(d.text,d.startPosition.row),l&&_p.has(l)&&d.type==="string_content"){let m=d.startPosition.row;for(let f of d.text.matchAll(Ip)){let h=f[1]??"";for(let p of h.matchAll(Rp))p[1]&&r(p[1],m)}}for(let m of d.children)u(m)};return u(a.rootNode),n}}let i=M(e,t);if(!i)return n;let s=gn(i).split(/\r?\n/),o=/\b([A-Za-z_$][\w$]*)\b/g;for(let a=0;a<s.length;a+=1){let l=s[a]??"";for(let c of l.matchAll(o))c[1]&&r(c[1],a)}return n}import{existsSync as bn}from"fs";import{basename as vp,dirname as je,extname as Re,join as ce,relative as Rt,resolve as re}from"path";var Np=Ue("indexed-paths"),Ct=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],ro=[".py",".pyi"],de=[".java",".scala",".kt",".kts"],io=[".rs"],so=[".rb"],oo=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],dt=[".cs",".vb"],ao=[".dart"],vt=[".php"],Ep=new Set(Ct),wr=new Set(ro),lo=new Set(de),kr=new Set(io),Pr=new Set(so),co=new Set(oo),uo=new Set(dt),Mr=new Set(ao),mo=new Set(vt),Dp=[{extensions:Ct,lookup:Ep},{extensions:ro,lookup:wr},{extensions:de,lookup:lo},{extensions:io,lookup:kr},{extensions:so,lookup:Pr},{extensions:oo,lookup:co},{extensions:dt,lookup:uo},{extensions:ao,lookup:Mr},{extensions:vt,lookup:mo}];function Be(e,t){return t.has(Re(e).toLowerCase())}function Lp(e){return Be(e,wr)}function wp(e){return Be(e,lo)}function kp(e){return Be(e,kr)}function Pp(e){return Be(e,Pr)}function Mp(e){return Be(e,co)}function Op(e){return Be(e,uo)}function fo(e){return Re(e).toLowerCase()===".vb"}function Tp(e){return Be(e,Mr)}function Fp(e){return Be(e,mo)}function Or(e){let t=Re(e).toLowerCase();for(let n of Dp)if(n.lookup.has(t))return n.extensions;return Ct}function Ap(e){return wp(e)||Op(e)||Fp(e)}function he(e,t,n){return Lp(t)?mt(e,t,n):kp(t)?Ce(e,t,n):Pp(t)?Sn(e,t,n):Mp(t)?xn(e,t,n):Ap(t)?H(e,n.replace(/\\/g,"."),Or(t)):Tp(t)?_n(e,t,n):$p(e,t,n)}function $p(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return null;let r=je(ce(e.config.projectRoot,t)),i=re(r,n),s=Nt(e);for(let o of Up(i)){let a=ue(Rt(e.config.projectRoot,o));if(s.has(a)||bn(o))return a}return ue(Rt(e.config.projectRoot,i))}function mt(e,t,n){let r=Nt(e),i;if(n.startsWith(".")){let s=n.match(/^(\.+)(.*)$/);if(!s)return null;let o=s[1].length,a=s[2].replace(/^\./,""),l=je(ce(e.config.projectRoot,t));for(let c=1;c<o;c++)l=je(l);i=a?re(l,a.replace(/\./g,"/")):l}else i=re(e.config.projectRoot,n.replace(/\./g,"/"));for(let s of jp(i)){let o=ue(Rt(e.config.projectRoot,s));if(r.has(o)||bn(s))return o}return null}function Ce(e,t,n){if(!n)return null;let r=n.replace(/\s+as\s+.+$/,"").trim();if(!r.startsWith("crate::")&&!r.startsWith("self::")&&!r.startsWith("super::"))return null;let i=je(ce(e.config.projectRoot,t)),s;return r.startsWith("crate::")?s=re(e.config.projectRoot,"src",r.slice(7).replace(/::/g,"/")):r.startsWith("self::")?s=re(i,r.slice(6).replace(/::/g,"/")):s=re(je(i),r.slice(7).replace(/::/g,"/")),Tr(e,Bp(s))}function Sn(e,t,n){let r=je(ce(e.config.projectRoot,t)),i=re(r,n);return Tr(e,Hp(i))}function xn(e,t,n){let r=je(ce(e.config.projectRoot,t)),i=[re(r,n),re(e.config.projectRoot,n),re(e.config.projectRoot,"include",n),re(e.config.projectRoot,"src",n)];return Tr(e,i)}function H(e,t,n){let r=Nt(e),i=t.replace(/\\/g,".").replace(/::/g,".").replace(/^global::/,""),s=i.replace(/\./g,"/"),o=i.split(".").pop()??i;for(let l of n){let c=`${s}${l}`,u=[...r].find(d=>d.endsWith(c));if(u)return u}for(let l of n){let c=[...r].find(u=>vp(u)===`${o}${l}`);if(c)return c}let a=[...r].filter(l=>n.includes(Re(l).toLowerCase())).filter(l=>l.includes(`/${s}/`)||l.includes(`/${o}/`)).sort((l,c)=>l.localeCompare(c));return a.length===1?a[0]:null}function _n(e,t,n){let r=Nt(e);if(n.startsWith("package:")){let o=n.slice(8),a=o.indexOf("/");if(a<0)return null;let l=o.slice(a+1),c=ue(l.startsWith("lib/")?l:`lib/${l}`);return r.has(c)?c:null}let i=je(ce(e.config.projectRoot,t)),s=re(i,n);for(let o of Wp(s)){let a=ue(Rt(e.config.projectRoot,o));if(r.has(a)||bn(o))return a}return null}function jp(e){let t=Re(e);return wr.has(t)?[e]:[`${e}.py`,`${e}.pyi`,ce(e,"__init__.py"),ce(e,"__init__.pyi")]}function Tr(e,t){let n=Nt(e);for(let r of t){let i=ue(Rt(e.config.projectRoot,r));if(n.has(i)||bn(r))return i}return null}function Bp(e){let t=Re(e);return kr.has(t)?[e]:[`${e}.rs`,ce(e,"mod.rs")]}function Hp(e){let t=Re(e);return Pr.has(t)?[e]:[`${e}.rb`,ce(e,"index.rb")]}function Wp(e){let t=Re(e);return Mr.has(t)?[e]:[`${e}.dart`,e]}function Up(e){let t=Re(e),n=new Set;if(t){n.add(e);for(let r of Ct)n.add(e.slice(0,-t.length)+r)}else for(let r of Ct)n.add(`${e}${r}`),n.add(ce(e,`index${r}`));return[...n]}function Nt(e){return Np.get(e,()=>new Set(e.all(`SELECT relative_path
365
- FROM documents
366
- WHERE 1 = 1
367
- ${e.pathExclusionsFor("documents")}`).map(t=>ue(t.relative_path)).filter(t=>!e.isIgnored(t))))}function ue(e){return e.replace(/\\/g,"/")}var Vp=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function ee(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++){let s=e[i];(s==="{"||s==="["||s==="(")&&n++,(s==="}"||s==="]"||s===")")&&n--,s===","&&n===0&&(t.push(e.slice(r,i)),r=i+1)}return t.push(e.slice(r)),t}function ie(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function W(e,t){let n=new Set,r=(i,s)=>{let o=s||t.has(i.type);!o&&Vp.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,o)};return r(e.rootNode,!1),n}function ye(e,t,n,r,i,s,o){return{importedName:i,localName:s,sourcePath:o??H(e,r,Or(t)),kind:"named",used:X(n,s),usedMembers:[]}}function se(e,t,n){let r=[];for(let i of e.matchAll(t)){let s=i[0];if(!s||typeof i.index!="number")continue;let o=$e(e,i.index,i.index+s.length);for(let a of n(i,o))r.push(a)}return r}function go(e,t,n){let r=O(e,t);return r?Jp(e,t,r):rg(n).flatMap(i=>ig(e,t,i.clause,i.specifier,i.start,i.end,n))}function Jp(e,t,n){let r=qp(e,t,n),i=[];for(let s of n.rootNode.descendantsOfType("import_statement"))i.push(...zp(e,t,n,s,r));return i}function qp(e,t,n){let r=W(n,new Set(["import_statement"]));if(ze(t))for(let i of hg(e,t))r.add(i);return r}function zp(e,t,n,r,i){let s=Zp(r);if(!s)return[];let o=he(e,t,s),a=ie(r,"import_clause");return a?Gp(n,a,o,i,eg(r.text)):[Kp(o)]}function Gp(e,t,n,r,i){let s=[];for(let o of t.namedChildren)if(o.type==="identifier")s.push(Yp(o.text,n,r,i));else if(o.type==="namespace_import"){let a=Qp(e,o,n,r,i);a&&s.push(a)}else o.type==="named_imports"&&s.push(...Xp(o,n,r,i));return s}function Kp(e){return{importedName:"*",localName:null,sourcePath:e,kind:"side-effect",used:!0,usedMembers:[]}}function Yp(e,t,n,r){return{importedName:"default",localName:e,sourcePath:t,kind:"default",used:n.has(e),usedMembers:[],isTypeOnly:r}}function Qp(e,t,n,r,i){let o=ie(t,"identifier")?.text??"";if(!o)return null;let a=ng(e,o);return{importedName:"*",localName:o,sourcePath:n,kind:"namespace",used:a.length>0||r.has(o),usedMembers:a,isTypeOnly:i}}function Xp(e,t,n,r){let i=[];for(let s of e.namedChildren){if(s.type!=="import_specifier")continue;let o=s.namedChild(0),a=s.namedChild(1);if(!o)continue;let l=o.text,c=a?.text??l;i.push({importedName:l,localName:c,sourcePath:t,kind:"named",used:n.has(c),usedMembers:[],isTypeOnly:r||tg(s.text)})}return i}function Zp(e){let t=ie(e,"string");if(!t)return null;let n=ie(t,"string_fragment");return n?n.text:null}function eg(e){return/^\s*import\s+type\b/.test(e)}function tg(e){return/^\s*type\b/.test(e.trim())}function ng(e,t){let n=new Set;for(let r of e.rootNode.descendantsOfType("member_expression")){let i=r.namedChild(0),s=r.namedChild(1);!i||!s||i.type!=="identifier"||i.text!==t||(s.type==="property_identifier"||s.type==="identifier")&&n.add(s.text)}return[...n]}function rg(e){let t=[],n=/^[ \t]*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(n)){let s=i[0],o=i[1],a=i[2];!s||!a||typeof i.index!="number"||t.push({clause:o,specifier:a,start:i.index,end:i.index+s.length})}let r=/^[ \t]*import\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(r)){let s=i[0],o=i[1];!s||!o||typeof i.index!="number"||t.push({clause:null,specifier:o,start:i.index,end:i.index+s.length})}return t.sort((i,s)=>i.start-s.start)}function ig(e,t,n,r,i,s,o){let a=he(e,t,r),l=$e(o,i,s);return n?sg(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=ut(l,u.localName);return{...u,used:d.length>0||X(l,u.localName),usedMembers:d}}return u.kind==="side-effect"?{...u,used:!0,usedMembers:[]}:{...u,used:u.localName?X(l,u.localName):!1,usedMembers:[]}}):[{importedName:"*",localName:null,sourcePath:a,kind:"side-effect",used:!0,usedMembers:[]}]}function sg(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,s]=og(r),o=[];return i&&o.push(...po(i,n)),s&&o.push(...po(s,n)),o}function po(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?ee(r).map(i=>{let s=i.trim(),o=t||/^type\b/.test(s),a=s.replace(/^type\s+/,""),[l,c]=a.split(/\s+as\s+/);return{importedName:l.trim(),localName:(c??l).trim(),kind:"named",isTypeOnly:o}}):[]}return n.startsWith("* as ")?[{importedName:"*",localName:n.slice(5).trim(),kind:"namespace",isTypeOnly:t}]:[{importedName:"default",localName:n,kind:"default",isTypeOnly:t}]}function og(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r==="{"&&t++,r==="}"&&t--,r===","&&t===0)return[e.slice(0,n).trim(),e.slice(n+1).trim()]}return[e.trim(),null]}function ho(e,t){let n=O(e,t);if(n)return mg(e,t,n);let r=M(e,t);return r?ag(e,t,r):[]}function ag(e,t,n){return[...lg(e,t,n),...cg(e,t,n),...ug(e,t,n)]}function lg(e,t,n){let r=[],i=/^[ \t]*export\s+(?:type\s+)?\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let s of n.matchAll(i)){if(typeof s.index!="number")continue;let o=s[1]??"",a=s[2]??"",l=ee(o).map(d=>dg(d.trim())).filter(d=>!!d),c=ft(n,s.index),u=ft(n,s.index+s[0].length-1);r.push({kind:"named",sourcePath:he(e,t,a),names:l,startLine:c,endLine:u})}return r}function cg(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let s of n.matchAll(i)){if(typeof s.index!="number")continue;let o=s[2]??"",a=ft(n,s.index),l=ft(n,s.index+s[0].length-1);r.push({kind:"star-as",sourcePath:he(e,t,o),names:[],startLine:a,endLine:l})}return r}function ug(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let s of n.matchAll(i)){if(typeof s.index!="number")continue;let o=s[1]??"",a=ft(n,s.index),l=ft(n,s.index+s[0].length-1);r.push({kind:"star",sourcePath:he(e,t,o),names:[],startLine:a,endLine:l})}return r}function dg(e){if(!e)return null;let t=e.replace(/^type\s+/,"").trim();if(!t)return null;let n=t.match(/^(\w+)\s+as\s+(\w+)$/);if(n)return n[2]??null;let r=t.match(/^(\w+)$/);return r?r[1]??null:null}function ft(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function mg(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let s=fg(e,t,i);if(s===void 0)continue;let o=i.startPosition.row,a=i.endPosition.row,l=pg(i,s,o,a);r.push(l)}return r}function fg(e,t,n){let r=ie(n,"string");if(!r)return;let i=ie(r,"string_fragment");if(i)return he(e,t,i.text)}function pg(e,t,n,r){let i=ie(e,"export_clause");if(i){let o=[];for(let a of i.namedChildren){if(a.type!=="export_specifier")continue;let l=a.namedChild(0),c=a.namedChild(1);l&&o.push((c??l).text)}return{kind:"named",sourcePath:t,names:o,startLine:n,endLine:r}}return ie(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}var gg=j("vue-non-script-identifiers");function hg(e,t){return gg.get(e,t,()=>{let n=new Set,r=M(e,t);if(!r)return n;let s=r.replace(/<script\b[^>]*>[\s\S]*?<\/script>/g,o=>o.replace(/[^\r\n]/g," ")).replace(/<!--[\s\S]*?-->/g,o=>o.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,o=>o.replace(/[^\r\n]/g," "));for(let o of s.matchAll(/[A-Za-z_$][\w$]*/g))n.add(o[0]);return n})}import{basename as yo}from"path";function bo(e,t,n){let r=O(e,t);return r?yg(e,t,r):se(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(i,s)=>{let o=i[1]?.trim();if(!o)return[];let a=yo(o).replace(/\.[^.]+$/,"");return[{importedName:o,localName:a,sourcePath:xn(e,t,o),kind:"named",used:X(s,a),usedMembers:[]}]})}function yg(e,t,n){let r=W(n,new Set(["preproc_include"])),i=[];for(let s of n.rootNode.descendantsOfType("preproc_include")){let o=null;for(let l of s.namedChildren){if(l.type==="system_lib_string"){o=l.text.replace(/^<|>$/g,"");break}if(l.type==="string_literal"){o=l.namedChildren.find(u=>u.type==="string_content")?.text??l.text.replace(/^"|"$/g,"");break}}if(!o)continue;let a=yo(o).replace(/\.[^.]+$/,"");i.push({importedName:o,localName:a,sourcePath:xn(e,t,o),kind:"named",used:r.has(a),usedMembers:[]})}return i}function So(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*import\s+['"]([^'"]+)['"](?:\s+as\s+([A-Za-z_]\w*))?[\s\S]*?;$/gm)){let s=i[1]?.trim(),o=i[2]?.trim()??null,a=i[0];if(!s||!a||typeof i.index!="number")continue;let l=$e(n,i.index,i.index+a.length);r.push({importedName:s,localName:o,sourcePath:_n(e,t,s),kind:o?"namespace":"side-effect",used:o?X(l,o):!0,usedMembers:o?ut(l,o):[]})}return r}function xo(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*export\s+['"]([^'"]+)['"][\s\S]*?;$/gm)){let s=i[1]?.trim();s&&r.push({specifier:s,sourcePath:_n(e,t,s)})}return r}function _o(e,t,n){let r=O(e,t),i=F(t);if(r&&i==="csharp")return Sg(e,t,r);if(r&&i==="vb")return bg(e,t,r);let s=fo(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return se(n,s,(o,a)=>{let l=o[1]?.trim();if(!l)return[];let[c,u]=l.split(/\s*=\s*/),d=!!u,m=(d?u:c)?.trim()??l,f=m.split(".").pop()??m,h=d?c?.trim()??f:f;return[ye(e,t,a,m,f,h,H(e,m,dt))]})}function bg(e,t,n){let r=W(n,new Set(["imports_statement"])),i=[];for(let s of n.rootNode.descendantsOfType("imports_statement")){let o=s.namedChildren.filter(m=>m.type==="namespace_name");if(o.length===0)continue;let a=o[o.length-1],l=o.length>1?o[0]:null,c=a.text,u=c.split(".").pop()??c,d=l?.text??u;i.push({importedName:u,localName:d,sourcePath:H(e,c,dt),kind:l?"namespace":"named",used:r.has(d),usedMembers:[]})}return i}function Sg(e,t,n){let r=W(n,new Set(["using_directive"])),i=[];for(let s of n.rootNode.descendantsOfType("using_directive")){let o=s.namedChildren;if(o.length===0)continue;let a=null,l;o.length>=2&&o[0].type==="identifier"&&(o[1].type==="qualified_name"||o[1].type==="identifier")?(a=o[0],l=o[1]):l=o[o.length-1];let c=l.text,u=c.split(".").pop()??c,d=a?.text??u;i.push({importedName:u,localName:d,sourcePath:H(e,c,dt),kind:a?"namespace":"named",used:r.has(d),usedMembers:[]})}return i}function Io(e,t,n){let r=O(e,t),i=F(t);return r&&i==="java"?xg(e,t,r):r&&i==="kotlin"?_g(e,t,r):r&&i==="scala"?Ig(e,t,r):se(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(s,o)=>{let a=s[1]?.trim();return a?Rg(e,t,a,o):[]})}function xg(e,t,n){let r=W(n,new Set(["import_declaration"])),i=[];for(let s of n.rootNode.descendantsOfType("import_declaration")){let o=s.children.some(d=>d.type==="asterisk"),l=s.namedChildren.find(d=>d.type==="scoped_identifier")??s.namedChildren.find(d=>d.type==="identifier");if(!l)continue;let c=l.text;if(o){i.push({importedName:"*",localName:null,sourcePath:H(e,c,de),kind:"namespace",used:!0,usedMembers:[]});continue}let u=c.split(".").pop()??c;i.push({importedName:u,localName:u,sourcePath:H(e,c,de),kind:"named",used:r.has(u),usedMembers:[]})}return i}function _g(e,t,n){let r=W(n,new Set(["import_header","import_list"])),i=[];for(let s of n.rootNode.descendantsOfType("import_header")){let o=s.namedChildren.find(f=>f.type==="identifier");if(!o)continue;let a=s.namedChildren.some(f=>f.type==="wildcard_import"),l=s.namedChildren.find(f=>f.type==="import_alias");if(a){i.push({importedName:"*",localName:null,sourcePath:H(e,o.text,de),kind:"namespace",used:!0,usedMembers:[]});continue}let c=o.text,u=c.split(".").pop()??c,m=l?.namedChild(0)?.text??u;i.push({importedName:u,localName:m,sourcePath:H(e,c,de),kind:"named",used:r.has(m),usedMembers:[]})}return i}function Ig(e,t,n){let r=W(n,new Set(["import_declaration"])),i=[];for(let s of n.rootNode.descendantsOfType("import_declaration")){let o=s.namedChildren.find(d=>d.type==="namespace_selectors"||d.type==="namespace_wildcard"),a=s.namedChildren.filter(d=>d!==o&&(d.type==="identifier"||d.type==="stable_identifier")),l=a.map(d=>d.text).join(".");if(!l)continue;if(o?.type==="namespace_wildcard"){i.push({importedName:"*",localName:null,sourcePath:H(e,l,de),kind:"namespace",used:!0,usedMembers:[]});continue}if(o?.type==="namespace_selectors"){for(let d of o.namedChildren)if(d.type==="arrow_renamed_identifier"){let[m,f]=d.namedChildren;if(!m)continue;let h=m.text,p=f?.text??h;if(h==="_")continue;i.push({importedName:h,localName:p,sourcePath:H(e,`${l}.${h}`,de),kind:"named",used:r.has(p),usedMembers:[]})}else if(d.type==="identifier"){let m=d.text;i.push({importedName:m,localName:m,sourcePath:H(e,`${l}.${m}`,de),kind:"named",used:r.has(m),usedMembers:[]})}continue}let c=a[a.length-1]?.text??l,u=a.slice(0,-1).map(d=>d.text).join(".")||l;i.push({importedName:c,localName:c,sourcePath:H(e,u&&a.length>1?`${u}.${c}`:l,de),kind:"named",used:r.has(c),usedMembers:[]})}return i}function Rg(e,t,n,r){if(n.includes("{")&&n.includes("}")){let i=n.slice(0,n.indexOf("{")).replace(/\.$/,"").trim(),s=n.slice(n.indexOf("{")+1,n.lastIndexOf("}")).trim();return ee(s).flatMap(o=>{let a=o.trim();if(!a)return[];let[l,c]=a.includes("=>")?a.split(/\s*=>\s*/):a.split(/\s+as\s+/),u=l?.trim();if(!u||u==="_")return[];let d=(c??u.split(".").pop()??u).trim(),m=u==="_"?i:`${i}.${u}`.replace(/\.\./g,".");return[ye(e,t,r,m,u,d)]})}return[ye(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function Co(e,t,n){let r=O(e,t);return r?Cg(e,t,r):se(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,s)=>{let o=i[1]?.trim();return o?ee(o).flatMap(a=>{let l=a.trim();if(!l)return[];let[c,u]=l.split(/\s+as\s+/i),d=c?.trim()??l,m=d.split("\\").pop()??d,f=(u??m).trim();return[ye(e,t,s,d,m,f,H(e,d.replace(/\\/g,"."),vt))]}):[]})}function Cg(e,t,n){let r=W(n,new Set(["namespace_use_declaration"])),i=[],s=(o,a,l)=>{i.push({importedName:a,localName:l,sourcePath:H(e,o.replace(/\\/g,"."),vt),kind:"named",used:r.has(l),usedMembers:[]})};for(let o of n.rootNode.descendantsOfType("namespace_use_declaration")){let a=o.namedChildren.find(l=>l.type==="namespace_use_group");if(a){let l=o.namedChildren.find(c=>c.type==="namespace_name")?.text??"";for(let c of a.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:u,localName:d,qualified:m}=Ro(c,l);u&&s(m,u,d)}continue}for(let l of o.namedChildren){if(l.type!=="namespace_use_clause")continue;let{importedName:c,localName:u,qualified:d}=Ro(l,"");c&&s(d,c,u)}}return i}function Ro(e,t){let n=e.namedChildren.find(c=>c.type==="qualified_name"),r=e.namedChildren.filter(c=>c.type==="name"),i="";n?i=n.text:r.length>=1&&(i=r[0].text);let s=n&&r.length>0?r[r.length-1]:null,o=i.split("\\").pop()??i,a=s?.text??o,l=t?`${t}\\${i}`:i;return{importedName:o,localName:a,qualified:l}}function Eo(e,t,n){let r=O(e,t);return r?vg(e,t,r):Eg(n).flatMap(i=>Lg(e,t,i,n))}function vg(e,t,n){let r=W(n,new Set(["import_statement","import_from_statement"])),i=[];for(let s of n.rootNode.descendantsOfType("import_statement"))for(let o of s.namedChildren){let a=vo(o);if(!a)continue;let l=mt(e,t,a.qualifiedName);i.push({importedName:a.qualifiedName,localName:a.localName,sourcePath:l,kind:"namespace",used:r.has(a.localName),usedMembers:[]})}for(let s of n.rootNode.descendantsOfType("import_from_statement")){let o=s.namedChild(0);if(!o)continue;let a=Ng(o);if(a===null)continue;let l=mt(e,t,a);for(let c=1;c<s.namedChildCount;c+=1){let u=s.namedChild(c);if(u.type==="wildcard_import"){i.push({importedName:"*",localName:null,sourcePath:l,kind:"side-effect",used:!0,usedMembers:[]});continue}let d=vo(u);d&&i.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:l,kind:"named",used:r.has(d.localName),usedMembers:[]})}}return i}function vo(e){if(e.type==="aliased_import"){let t=e.namedChild(0),n=e.namedChild(1);return!t||!n?null:{qualifiedName:t.text,localName:n.text}}if(e.type==="dotted_name"){let t=e.text;return{qualifiedName:t,localName:t.split(".")[0]??t}}return e.type==="identifier"?{qualifiedName:e.text,localName:e.text}:null}function Ng(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=ie(e,"import_prefix")?.text??"",n=ie(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function Eg(e){let t=e.split(`
368
- `),n=[],r=0;for(let i=0;i<t.length;i++){let s=t[i],o=s.trimStart(),a=r;if(r+=s.length+1,!o.startsWith("import ")&&!o.startsWith("from "))continue;let l=s,c=a+s.length,u=No(s);for(;i+1<t.length&&(u>0||l.trimEnd().endsWith("\\"));){i++;let m=t[i];l+=`
369
- ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,end:c})}return n}function Dg(e){let t=e.replace(/\\\s*\n/g," ").trim();if(t.startsWith("import "))return{kind:"import",module:null,clause:t.slice(7).trim()};let n=t.match(/^from\s+([.\w]+)\s+import\s+([\s\S]+)$/);if(!n)return null;let r=n[2].trim();return r.startsWith("(")&&r.endsWith(")")&&(r=r.slice(1,-1).trim()),{kind:"from",module:n[1],clause:r}}function Lg(e,t,n,r){let i=$e(r,n.start,n.end),s=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return ee(s).flatMap(l=>{let c=l.trim().replace(/,$/,"");if(!c)return[];let[u,d]=c.split(/\s+as\s+/),m=u.trim(),f=(d??m.split(".")[0]??m).trim(),h=mt(e,t,m),p=ut(i,f);return[{importedName:m,localName:f,sourcePath:h,kind:"namespace",used:X(i,f)||p.length>0,usedMembers:p}]});let o=n.module?mt(e,t,n.module):null,a=[];for(let l of ee(s)){let c=l.trim().replace(/,$/,"");if(!c)continue;if(c==="*"){a.push({importedName:"*",localName:null,sourcePath:o,kind:"side-effect",used:!0,usedMembers:[]});continue}let[u,d]=c.split(/\s+as\s+/),m=(d??u).trim();a.push({importedName:u.trim(),localName:m,sourcePath:o,kind:"named",used:X(i,m),usedMembers:[]})}return a}function No(e){let t=0;for(let n of e)n==="("&&t++,n===")"&&t--;return t}import{basename as wg}from"path";function Do(e,t,n){let r=O(e,t);return r?kg(e,t,r):se(n,/^[ \t]*(require_relative|require)\s+["']([^"']+)["']\s*$/gm,(i,s)=>{let o=i[1],a=i[2];if(!o||!a)return[];let l=o==="require_relative"?Sn(e,t,a):null;if(l){let c=Lo(a);return[{importedName:c,localName:c,sourcePath:l,kind:"named",used:X(s,c),usedMembers:[]}]}return[{importedName:a,localName:null,sourcePath:l,kind:"side-effect",used:!0,usedMembers:[]}]})}function kg(e,t,n){let r=W(n,new Set([])),i=[],s=new Set(["require","require_relative","load"]);for(let o of n.rootNode.descendantsOfType("call")){let a=o.namedChild(0);if(!a||a.type!=="identifier"||!s.has(a.text))continue;let c=o.namedChildren.find(f=>f.type==="argument_list")?.namedChild(0);if(!c||c.type!=="string")continue;let d=c.namedChildren.find(f=>f.type==="string_content")?.text;if(!d)continue;let m=a.text==="require_relative"?Sn(e,t,d):null;if(m){let f=Lo(d);i.push({importedName:f,localName:f,sourcePath:m,kind:"named",used:r.has(f),usedMembers:[]})}else i.push({importedName:d,localName:null,sourcePath:m,kind:"side-effect",used:!0,usedMembers:[]})}return i}function Lo(e){return wg(e).replace(/\.[^.]+$/,"").split("_").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function wo(e,t,n){let r=O(e,t);return r?Pg(e,t,r):se(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,s)=>{let o=i[1]?.trim();return o?Mg(e,t,o,s):[]})}function Pg(e,t,n){let r=W(n,new Set(["use_declaration"])),i=[];for(let s of n.rootNode.descendantsOfType("use_declaration")){let o=s.namedChild(0);if(o)for(let a of Et(o,"")){if(!a.importedName||a.importedName==="*")continue;let l=Ce(e,t,a.qualifiedName)??Ce(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push({importedName:a.importedName,localName:a.localName,sourcePath:l,kind:"named",used:r.has(a.localName),usedMembers:[]})}}return i}function Et(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":{let n=e.text;return[{qualifiedName:In(t,n),importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,r=n.split("::").pop()??n;return[{qualifiedName:In(t,n),importedName:r,localName:r}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=In(t,n.text),s=[];for(let o of r.namedChildren)s.push(...Et(o,i));return s}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(...Et(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=Et(n,t),s=r.text;return i.map(o=>({...o,localName:s}))}case"use_wildcard":{let n=e.namedChild(0),r=n?n.text:"";return[{qualifiedName:In(t,`${r}::*`),importedName:"*",localName:"*"}]}default:return[]}}function In(e,t){return e?t?`${e}::${t}`:e:t}function Mg(e,t,n,r){let i=n.trim();if(i.includes("{")&&i.includes("}")){let u=i.slice(0,i.indexOf("{")).replace(/::$/,"").trim(),d=i.slice(i.indexOf("{")+1,i.lastIndexOf("}")).trim();return ee(d).flatMap(m=>{let f=m.trim();if(!f||f==="self")return[];let[h,p]=f.split(/\s+as\s+/),g=h?.trim();if(!g)return[];let b=(p??g.split("::").pop()??g).trim(),_=`${u}::${g}`.replace(/::::/g,"::");return[ye(e,t,r,_,g.split("::").pop()??g,b,Ce(e,t,u))]})}let[s,o]=i.split(/\s+as\s+/),a=s?.trim()??i,l=(o??a.split("::").pop()??a).trim(),c=Ce(e,t,a)??Ce(e,t,a.split("::").slice(0,-1).join("::"));return[ye(e,t,r,a,a.split("::").pop()??a,l,c)]}function ko(e,t,n){let r=O(e,t);if(r)return Og(e,t,r);let i=[];for(let s of n.matchAll(/^[ \t]*pub\s+use\s+(.+?)\s*;$/gm)){let o=s[1]?.trim();o&&i.push(...Fg(e,t,o))}return i}function Og(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!Tg(i))continue;let s=i.namedChildren.find(o=>o.type!=="visibility_modifier");if(s)for(let o of Et(s,""))o.importedName&&r.push(Fr(e,t,o.qualifiedName))}return r}function Tg(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function Fg(e,t,n){let r=n.trim();if(r.includes("{")&&r.includes("}")){let i=r.slice(0,r.indexOf("{")).replace(/::$/,"").trim(),s=r.slice(r.indexOf("{")+1,r.lastIndexOf("}")).trim();return ee(s).flatMap(o=>{let a=o.trim();if(!a||a==="self")return[];let[l]=a.split(/\s+as\s+/),c=`${i}::${l?.trim()??a}`.replace(/::::/g,"::");return[Fr(e,t,c)]})}return[Fr(e,t,r)]}function Fr(e,t,n){return{specifier:n,sourcePath:Ce(e,t,n)??Ce(e,t,n.split("::").slice(0,-1).join("::"))}}function Po(e,t){let n=t.toLowerCase();for(let r of e)for(let i of r.extensions)if(n.endsWith(i))return r;return null}var Ag={language:"javascript",extensions:[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],parseImports:go},$g={language:"python",extensions:[".py",".pyi"],parseImports:Eo},jg={language:"jvm",extensions:[".java",".scala",".kt",".kts"],parseImports:Io},Bg={language:"rust",extensions:[".rs"],parseImports:wo,parseExports:ko},Hg={language:"ruby",extensions:[".rb"],parseImports:Do},Wg={language:"c/cpp",extensions:[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],parseImports:bo},Ug={language:"dotnet",extensions:[".cs",".vb"],parseImports:_o},Vg={language:"dart",extensions:[".dart"],parseImports:So,parseExports:xo},Jg={language:"php",extensions:[".php"],parseImports:Co},qg=[Ag,$g,jg,Bg,Hg,Wg,Ug,Vg,Jg];function Ar(e){return Po(qg,e)}function Mo(e,t){return ho(e,t)}var $r=j("source-imports"),jr=j("source-exports");function q(e,t){let n=ue(t);return $r.get(e,n,()=>{let r=Ar(n);if(!r)return[];let i=M(e,n);return i?r.parseImports(e,n,i):[]})}function Br(e,t){let n=ue(t);return jr.get(e,n,()=>{let r=Ar(n);if(!r?.parseExports)return[];let i=M(e,n);return i?r.parseExports(e,n,i):[]})}function Oo(e){$r.invalidateAll(e),jr.invalidateAll(e)}function To(e,t){let n=ue(t);$r.invalidate(e,n),jr.invalidate(e,n)}import me from"path";import{createRequire as zg}from"module";import{existsSync as Rn,readdirSync as Gg,readFileSync as jo}from"fs";var Kg=zg(import.meta.url),Dt;function Bo(e,t){let n=Yg();if(!n)return Hr("ts-morph is not installed");let r=os(e);if(r.length===0)return Hr("no tsconfig found");try{let i=r.map(s=>({tsconfigPath:s,project:new n.Project({tsConfigFilePath:s,skipFileDependencyResolution:!1})}));return new Wr(e,n,i)}catch(i){return Hr(i instanceof Error?i.message:String(i),r[0],r)}}function Yg(){if(Dt!==void 0)return Dt;try{Dt=Kg("ts-morph")}catch{Dt=null}return Dt}function Hr(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}var Wr=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=th(t.config.projectRoot)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;sourceFileCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return ve(this.importUsageCache,t,()=>{let n=this.sourceFile(t);if(!n)return[];let r=[];for(let i of n.getImportDeclarations())for(let s of this.importUsageForDeclaration(t,i))r.push(s);return r})}referencesFor(t){return ve(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t),r=this.packageImportReferencesForDefinition(t);return n?lh(n,t,r,this.db.config.projectRoot):r})}calleesFor(t){return ve(this.calleesCache,t.symbolId,()=>ve(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}signatureFor(t){return ve(this.signatureCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);if(!n||!this.tsMorph.Node.isFunctionDeclaration(n)&&!this.tsMorph.Node.isMethodDeclaration(n)&&!this.tsMorph.Node.isArrowFunction(n)&&!this.tsMorph.Node.isFunctionExpression(n)&&!this.tsMorph.Node.isConstructorDeclaration(n))return null;let r=n.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(o=>{let a=o.getDeclarations()[0],l=a?o.getTypeAtLocation(a).getText(a):o.getValueDeclaration()?.getType().getText()??"unknown";return $o(l)}),s=r.getReturnType().getText(n);return`(${i.join(",")})=>${$o(s)}`})}importUsageForDeclaration(t,n){let r=he(this.db,t,n.getModuleSpecifierValue()),i=Fo(n);return n.getImportClause()?.isTypeOnly()?i.map(s=>Zg(t,r,s)):i.map(s=>this.valueImportUsageForEntry(t,r,s))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],s=[];for(let c of i)for(let u of ch(c,t,r.identifier,this.db.config.projectRoot))s.push(u);let o=s.some(c=>!Ao(c.node)),a=s.some(c=>Ao(c.node)),l=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:l,isUsed:l||s.length>0,isTypeUsed:l||a,isValueUsed:o,references:s.map(c=>c.location)}}sourceFile(t){return this.sourceFileMatch(t)?.sourceFile??null}sourceFileMatch(t){return yh(t)?ve(this.sourceFileCache,t,()=>{let n=me.join(this.db.config.projectRoot,t);for(let{project:r}of this.projects){let i=r.getSourceFile(n)??r.addSourceFileAtPathIfExists(n)??null;if(i)return{project:r,sourceFile:i}}return null}):null}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let t=new Map,n=this.packageExports();for(let r of this.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,r);for(let[r,i]of t)t.set(r,Ur(i));return this.packageImportReferenceIndex=t,t}indexedTypeScriptLikeDocuments(){return this.db.all(`SELECT relative_path
370
- FROM documents
371
- WHERE (
372
- relative_path LIKE '%.ts'
373
- OR relative_path LIKE '%.tsx'
374
- OR relative_path LIKE '%.mts'
375
- OR relative_path LIKE '%.cts'
376
- OR relative_path LIKE '%.js'
377
- OR relative_path LIKE '%.jsx'
378
- OR relative_path LIKE '%.mjs'
379
- OR relative_path LIKE '%.cjs'
380
- )
381
- ${this.db.pathExclusionsFor("documents")}`).map(t=>t.relative_path)}addPackageImportReferencesForDocument(t,n,r){if(this.db.isIgnored(r))return;let i=this.sourceFileMatch(r);if(i)for(let s of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,r,s)}addPackageImportReferencesForDeclaration(t,n,r,i){let s=ih(this.workspacePackages,i.getModuleSpecifierValue());if(!s)return;let o=n.get(s);if(o)for(let a of Fo(i)){if(a.kind!=="named"||!a.identifier)continue;let l=o.get(a.importedName);if(!l||l.size===0)continue;let c=uh(a.identifier,r,this.db.config.projectRoot);c.length>0&&gh(t,l,c)}}packageExports(){if(this.packageExportIndex)return this.packageExportIndex;let t=new Map;for(let n of this.workspacePackages){let r=new Map;for(let i of sh(n))this.collectPackageExports(n,i,r,new Set);r.size>0&&t.set(n.name,r)}return this.packageExportIndex=t,t}collectPackageExports(t,n,r,i){if(i.has(n))return;i.add(n);let s=this.sourceFile(n);if(s)for(let o of s.getExportDeclarations()){let a=o.getModuleSpecifierValue(),l=a?he(this.db,n,a):n;if(!l||!l.startsWith(`${t.sourceRootRelative}/`))continue;let c=o.getNamedExports();if(c.length===0){if(o.isNamespaceExport())continue;this.collectPackageExports(t,l,r,i);continue}for(let u of c){let d=u.getNameNode().getText(),m=u.getAliasNode()?.getText()??d,f=this.indexedDefinitionByLeaf(l,d);if(!f)continue;let h=r.get(m);h||(h=new Set,r.set(m,h)),h.add(f.symbolId)}}}indexedDefinitionByLeaf(t,n){return ve(this.indexedDefinitionLeafCache,t,()=>fh(this.db,t)).get(n)??null}nodeForDefinition(t){return ve(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return ve(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFile(t);if(!n)return new Map;let r=Qg(this.db,t);return r.size===0?new Map:Xg(this.tsMorph,n,r)})}definitionFromSymbol(t){let n=t.getDeclarations();for(let r of n){let i=r.getSourceFile(),s=vn(this.db.config.projectRoot,i.getFilePath());if(!s||this.db.isIgnored(s))continue;let o=Cn(i,r),a=mh(this.db,s,o,t.getName());if(a)return{symbol:a.symbol,file:a.relativePath,line:a.startLine}}return null}calleeMapForFile(t){let n=this.sourceFile(t);if(!n)return new Map;let r=J(this.db,t).sort((s,o)=>s.startLine-o.startLine||o.endLine-s.endLine);if(r.length===0)return new Map;let i=new Map;n.forEachDescendant(s=>{if(!this.tsMorph.Node.isCallExpression(s)&&!this.tsMorph.Node.isNewExpression(s))return;let o=this.semanticCalleeForCallNode(n,r,s);o&&eh(i,o.callerId,o.target)});for(let[s,o]of i)i.set(s,hh(o));return i}semanticCalleeForCallNode(t,n,r){let i=ph(n,Cn(t,r));if(!i)return null;let s=r.getExpression(),o=s.getSymbol()??s.getType().getSymbol(),a=o?this.definitionFromSymbol(o):null;return a?{callerId:i.symbolId,target:{symbol:a.symbol,file:a.file,line:a.line}}:null}};function Fo(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let r=e.getNamespaceImport();r&&t.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let i of e.getNamedImports()){let s=i.getNameNode(),a=i.getAliasNode()??(s.getKindName()==="Identifier"?s:null);t.push({identifier:a,importedName:s.getText(),localName:a?.getText()??s.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function Qg(e,t){let n=new Map;for(let r of J(e,t)){let i=k(r.symbol)??r.leaf;if(!i)continue;let s=n.get(i);s||(s=[],n.set(i,s)),s.push(r)}return n}function Xg(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(s=>{for(let o of dh(e,s)){let a=n.get(o);if(!a)continue;let l=Cn(t,s);for(let c of a){if(l<c.startLine-1||l>c.endLine+1)continue;let u=Math.abs(l-c.startLine),d=i.get(c.symbolId);d!==void 0&&d<=u||(i.set(c.symbolId,u),r.set(c.symbolId,s))}}}),r}function Zg(e,t,n){return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function eh(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function th(e){let t=me.join(e,"package.json");if(!Rn(t))return[];let n;try{n=JSON.parse(jo(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>nh(e,i)).flatMap(i=>rh(e,i))}function nh(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let o=me.join(e,t);return Rn(me.join(o,"package.json"))?[o]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),s=me.join(e,r||".");if(!Rn(s))return[];try{return Gg(s).map(o=>me.join(s,o,i)).filter(o=>Rn(me.join(o,"package.json")))}catch{return[]}}function rh(e,t){try{let n=JSON.parse(jo(me.join(t,"package.json"),"utf8"));if(!n.name)return[];let r=me.relative(e,t).replace(/\\/g,"/");return[{name:n.name,rootRelative:r,sourceRootRelative:`${r}/src`}]}catch{return[]}}function ih(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function sh(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}function oh(e,t){return e.getReferences().map(n=>{let r=n.getNode();return Ho(r,t)})}function ah(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function lh(e,t,n,r){let i=[];for(let s of ah(e))for(let o of oh(s,r))o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||i.push(o);for(let s of n)i.push(s);return Ur(i)}function ch(e,t,n,r){let i=[],s=n?.getStart();for(let o of e.getReferences()){let a=o.getNode();vn(r,a.getSourceFile().getFilePath())===t&&(s!==void 0&&a.getStart()===s||i.push({location:Ho(a,r),node:a}))}return i}function Ho(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:vn(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function uh(e,t,n){let r=e.getSourceFile(),i=Cn(r,e),s=e.getText(),o=new RegExp(`\\b${bh(s)}\\b`,"g"),a=r.getFullText().split(`
382
- `),l=[];for(let c=0;c<a.length;c++){if(c===i)continue;let u=a[c]??"";o.lastIndex=0;let d;for(;(d=o.exec(u))!==null;)l.push({file:t,line:c,column:d.index})}return Ur(l.filter(c=>vn(n,me.join(n,c.file))===t))}function Ao(e){for(let t=e;t;t=t.getParent()){let n=t.getKindName();if(n.includes("Type")||n==="InterfaceDeclaration"||n==="TypeAliasDeclaration")return!0;if(n==="CallExpression"||n==="NewExpression"||n==="ExpressionStatement")return!1}return!1}function dh(e,t){let n=[],r=i=>{i&&!n.includes(i)&&n.push(i)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let i=t.getNameNode();r(i?.getText())}if("getName"in t&&typeof t.getName=="function"){let i=t.getName();r(i)}return e.Node.isIdentifier(t)&&r(t.getText()),n}function mh(e,t,n,r){return e.all(`SELECT
106
+ WHERE d.relative_path = ?
107
+ AND m.role = 1
108
+ ${e.symbolNoiseFor("gs")}
109
+ GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
110
+ ORDER BY start_line, end_line`,t)}function Km(e){return{symbolId:e.id,symbol:e.symbol,documentId:e.document_id,startLine:e.start_line,endLine:e.end_line,relativePath:e.relative_path,leaf:L(e.symbol),parentTypeName:Te(e.symbol),isFunctionLike:K(e.symbol),isTypeLike:ee(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function Le(e,t={}){return ri(e,t.scope)}function ri(e,t){return k(e,{scope:t,includeIgnored:!1}).flatMap(n=>V(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function kt(e,t,n={}){if(t.length===0)return[];let r=t.flatMap(i=>V(e,i)).filter(i=>!e.isIgnored(i.relativePath));return n.onlyDocumented&&(r=r.filter(i=>i.documentation!==null&&i.documentation!=="")),n.sort&&(r=r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath)||i.startLine-o.startLine||i.endLine-o.endLine)),r.map(i=>({startLine:i.startLine,endLine:i.endLine,symbol:i.symbol,shortName:h(i.symbol),signature:at(ct(i.documentation)),relativePath:i.relativePath,enclosingSymbol:i.enclosingSymbol}))}function de(e,t){let n=null;for(let r of e)r.startLine>t||r.endLine<t||(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r);return n}function lt(e,t){let n=V(e,t.relative_path).find(r=>r.symbolId===t.id);return n?{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,endLine:n.endLine,relativePath:n.relativePath}:{symbolId:t.id,symbol:t.symbol,documentId:t.document_id,startLine:t.start_line,endLine:t.end_line,relativePath:t.relative_path}}function Qm(e,t,n){let r=T(e,t),i=ei(e,t);return i?nd(n,i,r):r?Ym(n,r):n}function Ym(e,t){let n=t.split(/\r?\n/),r=Xm(e,n),i=Zm(e,r),o=ed(i,n);return td(e,o)}function Xm(e,t){let n=e.some(i=>Hn(i.symbol))?id(t):null,r=new Map;for(let i of e)r.set(i.symbolId,rd(t,n,i));return r}function Zm(e,t){return e.filter(n=>Hn(n.symbol)).map(n=>({definition:n,startLine:t.get(n.symbolId)??n.startLine})).sort((n,r)=>n.startLine-r.startLine||n.definition.startLine-r.definition.startLine||n.definition.symbol.localeCompare(r.definition.symbol))}function ed(e,t){let n=new Map;for(let r=0;r<e.length;r+=1){let i=e[r],o=e[r+1],s=o?Math.max(i.startLine,o.startLine-1):t.length-1;n.set(i.definition.symbolId,{startLine:i.startLine,endLine:od(t,i.definition,i.startLine,s)})}return n}function td(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function nd(e,t,n=null){let r=new Map;for(let i of t){let o=r.get(i.name);o?o.push(i):r.set(i.name,[i])}return e.map(i=>{if(!Hn(i.symbol)||!i.leaf)return Ms(i,n);let o=r.get(i.leaf);if(!o||o.length===0)return Ms(i,n);let s=o[0],a=Math.abs(s.startLine-i.startLine);for(let c=1;c<o.length;c+=1){let l=o[c],u=Math.abs(l.startLine-i.startLine);u<a&&(s=l,a=u)}return{...i,startLine:s.startLine,endLine:s.endLine}})}function Ms(e,t){if(!t||!e.leaf||ee(e.symbol)!=="term"||Te(e.symbol)!==null)return e;let n=e.leaf.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`),o=t.split(/\r?\n/).findIndex(s=>r.test(s));return o>=0?{...e,startLine:o,endLine:o}:e}function rd(e,t,n){if(!Hn(n.symbol))return n.startLine;let r=Math.max(0,Math.min(n.startLine,e.length-1));if(!t)return r;let i=t.get(n.leaf);if(!i||i.length===0)return r;let o=null;for(let s of i){let a=Math.abs(s-n.startLine);(!o||a<o.distance)&&(o={line:s,distance:a})}return o?.line??r}function id(e){let t=/\b(?:function|def|fn)\s+([A-Za-z_$][\w$]*)/g,n=/\b([A-Za-z_$][\w$]*)\s*[:=]\s*(?:async\s*)?(?:function\b|\()/g,r=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,i=/\b([A-Za-z_$][\w$]*)\s*\(/g,o=new Map,s=(a,c)=>{let l=o.get(a);if(!l){o.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)};for(let a=0;a<e.length;a+=1){let c=e[a]??"";for(let u of c.matchAll(t))u[1]&&s(u[1],a);for(let u of c.matchAll(n))u[1]&&s(u[1],a);let l=c.match(r);l?.[1]&&s(l[1],a);for(let u of c.matchAll(i))u[1]&&s(u[1],a)}return o}function od(e,t,n,r){let i=Math.max(n,Math.min(e.length-1,r)),o=Math.max(n,Math.min(i,t.endLine)),s=0,a=0,c=!1;for(let l=n;l<=i;l+=1){let u=sd(e[l]??"");for(let m of u)m==="{"?(s+=1,c=!0):m==="}"?s=Math.max(0,s-1):m==="("?a+=1:m===")"&&(a=Math.max(0,a-1));if(c&&s===0||!c&&a===0&&l>=o)return l}return o}function sd(e){let t="",n=null,r=!1;for(let i=0;i<e.length;i+=1){let o=e[i],s=e[i+1];if(!n&&o==="/"&&s==="/"){t+=" ".repeat(e.length-i);break}if(n){if(r){r=!1,t+=" ";continue}if(o==="\\"){r=!0,t+=" ";continue}o===n&&(n=null),t+=" ";continue}if(o==='"'||o==="'"||o==="`"){n=o,t+=" ";continue}t+=o}return t}function Hn(e){return e.includes("().")}function Wn(e){let t=Q(e);if("kind"in t)return[];let n=[];for(let r=t.descriptors.length-2;r>=0;r-=1){let i=t.descriptors[r];i?.suffix==="type"&&i.name&&n.push(i.name)}return n}import{existsSync as xd}from"fs";import{basename as As,isAbsolute as Cd,join as Id}from"path";function w(e,t){let n=Tt(e,t.trim());if(n)return n;let r=dd(e,t);if(r)return r;let i=ad(e,t);return i||md(e,t)}function ad(e,t){let n=oi(t),r=ii(n);if(!r)return null;let i=`%${r.path}%`,o=r.leaf,a=cd(e,i,o,n)[0];return a?lt(e,a):null}function cd(e,t,n,r){let i=wt([],[...ld(e,t,n),...ud(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>Pt(o,r)>1);return i.sort((o,s)=>Pt(s,r)-Pt(o,r)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.start_line-s.start_line||o.symbol.localeCompare(s.symbol)),i}function ld(e,t,n){return Lt(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function ud(e,t,n){return Et(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function md(e,t){let n=oi(t),r=bd(t),i=hd(e,r),o=Sd(i,t,n);if(o&&!e.isIgnored(o.relative_path))return lt(e,o);let s=null;for(let a of i){if(e.isIgnored(a.relative_path))continue;let c=yd(a,t,n,r);c<=0||(!s||c>s.score)&&(s={row:a,score:c})}return s?lt(e,s.row):null}function dd(e,t){let n=t.match(/^(.+):(\d+)-(\d+)$/);if(!n)return null;let[,r,i,o]=n,s=Math.max(0,parseInt(i,10)-1),a=Math.max(s,parseInt(o,10)-1),c=pd(e,r,s,a)??fd(e,r,s,a);return c&&!e.isIgnored(c.relative_path)?lt(e,c):null}function pd(e,t,n,r){return Lt(e,{where:"d.relative_path LIKE ? AND der.start_line <= ? AND der.end_line >= ?",params:[`%${t}%`,n,r],orderBy:"(der.end_line - der.start_line) ASC",limit:1})[0]}function fd(e,t,n,r){return Et(e,{where:"d.relative_path LIKE ? AND c.start_line <= ? AND c.end_line >= ?",params:[`%${t}%`,n,r],orderBy:"(MAX(c.end_line) - MIN(c.start_line)) ASC",limit:1})[0]}function Tt(e,t){let r=Lt(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line",limit:1})[0]??Et(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line",limit:1})[0];return!r||e.isIgnored(r.relative_path)?null:lt(e,r)}function Vn(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=gd(e,t.symbolId)[0];return n?lt(e,n):null}function gd(e,t){let n=Lt(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),r=Et(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return wt(n,r)}function hd(e,t){let n=t.map(()=>"(gs.symbol LIKE ? OR d.relative_path LIKE ? OR COALESCE(gs.display_name, '') LIKE ?)"),r=t.flatMap(a=>{let c=`%${a}%`;return[c,c,c]}),i=n.join(`
111
+ AND `),o=Lt(e,{where:i,params:r,limit:200}),s=Et(e,{where:i,params:r,limit:200});return wt(o,s)}function yd(e,t,n,r){let i=t.trim(),o=n,s=o.replace(/\(\)$/,""),a=t.toLowerCase(),c=n.toLowerCase(),l=c.replace(/\(\)$/,""),u=e.symbol,m=h(e.symbol),d=L(e.symbol),p=e.display_name??"",y=e.symbol.toLowerCase(),f=m.toLowerCase(),b=d.toLowerCase(),E=p.toLowerCase(),x=e.relative_path.toLowerCase(),$=/[/:.]/.test(n),F=ii(n),R=F?.leaf.toLowerCase(),_=0;return(u===i||u===o)&&(_+=1150),(m===i||m===o)&&(_+=1100),p===s&&(_+=1180),d===s&&(_+=1160),(`${d}()`===i||`${d}()`===o)&&(_+=955),(y===a||y===c)&&(_+=1e3),(f===a||f===c)&&(_+=950),(x===a||x===c)&&(_+=925),(x.endsWith(`/${c}`)||x.endsWith(`/${a}`))&&(_+=875),E===l&&(_+=850),b===l&&(_+=825),(`${b}()`===a||`${b}()`===c)&&(_+=820),(f.endsWith(`:${c}`)||f.endsWith(`:${l}`)||f.endsWith(`:${l}()`))&&(_+=800),y.includes(c)&&(_+=120),f.includes(c)&&(_+=140),x.includes(c)&&(_+=140),E.includes(c)&&(_+=110),r.every(G=>{let A=G.toLowerCase();return y.includes(A)||f.includes(A)||x.includes(A)||E.includes(A)})&&(_+=100+r.length*15),F&&x.includes(F.path.toLowerCase())&&(_+=360,R&&(b===R||`${b}()`===R||`${b}()`==`${R}()`)&&(_+=700),te(e.symbol)&&(_+=180)),K(e.symbol)&&b===l&&(_+=60),!$&&Ve(e.symbol)&&(_-=160),_-=Math.min(50,Math.max(0,e.end_line-e.start_line)),_}function ii(e){let t=e.trim().replace(/\\/g,"/"),n=t.lastIndexOf("/");if(n<=0||n===t.length-1)return null;let r=t.slice(n+1).replace(/\(\)$/,"");return!r||r.includes(".")?null:{path:t.slice(0,n),leaf:r}}function oi(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function bd(e){let t=oi(e),n=t.split(/[^A-Za-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>0);return n.length>0?[...new Set(n)]:[t]}function Sd(e,t,n){let r=t.trim(),i=e.filter(o=>{let s=h(o.symbol),a=(o.display_name??"").trim();return o.symbol===r||s===r||s===n||a===r||a===n||`${a}()`===r||Pt(o,n)>1||o.relative_path===r});return i.length===0?null:(i.sort((o,s)=>Pt(s,n)-Pt(o,n)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.relative_path.localeCompare(s.relative_path)||o.symbol.localeCompare(s.symbol)),i[0]??null)}function Pt(e,t){let n=ii(t);if(!n)return 0;let r=e.relative_path.toLowerCase(),i=L(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return r.includes(o)?i!==s?1:te(e.symbol)?Te(e.symbol)===null?5:4:Te(e.symbol)===null?3:2:0}function ie(e,t){let n=$s(e,t,{allowMultiple:!1})[0]?.relativePath;return n||Rd(e,t)}function Ue(e,t){return $s(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function Rd(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=Cd(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=Id(e.config.projectRoot,r);return xd(i)?r:null}function $s(e,t,n){let r=js(t);if(!r)return[];let i=k(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:_d(a,r)})).filter(a=>a.score>0).sort((a,c)=>c.score-a.score||a.relativePath.localeCompare(c.relativePath));if(i.length===0){let a=w(e,t);return!a||e.isIgnored(a.relativePath)?[]:[{relativePath:a.relativePath,score:700}]}let o=i.filter(a=>a.score>=1100);if(o.length>0)return n.allowMultiple?o:[o[0]];let s=i.filter(a=>a.score>=800);return s.length>0?n.allowMultiple?s:[s[0]]:n.allowMultiple?i:[i[0]]}function _d(e,t){let n=js(e),r=As(n),i=As(t),o=0;return n===t&&(o+=1200),n.endsWith(`/${t}`)&&(o+=1100),r===i&&(o+=900),n.startsWith(`${t}/`)&&(o+=850),n.includes(t)&&(o+=250),o}function js(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}function si(e,t){let n=Ue(e,t);return kt(e,n).map(({relativePath:r,...i})=>i)}import{basename as Og}from"path";import{existsSync as qn}from"fs";import{basename as vd,dirname as Je,extname as Me,join as Ce,relative as nn,resolve as pe}from"path";var Dd=We("indexed-paths"),ut=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],Un=[".py",".pyi"],ce=[".java",".scala",".kt",".kts"],Jn=[".rs"],zn=[".rb"],Gn=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],ze=[".cs",".vb"],Kn=[".dart"],mt=[".php"],Nd=new Set(ut),ai=new Set(Un),Bs=new Set(ce),ci=new Set(Jn),li=new Set(zn),Hs=new Set(Gn),Ws=new Set(ze),ui=new Set(Kn),Vs=new Set(mt),Ld=[{extensions:ut,lookup:Nd},{extensions:Un,lookup:ai},{extensions:ce,lookup:Bs},{extensions:Jn,lookup:ci},{extensions:zn,lookup:li},{extensions:Gn,lookup:Hs},{extensions:ze,lookup:Ws},{extensions:Kn,lookup:ui},{extensions:mt,lookup:Vs}];function Ge(e,t){return t.has(Me(e).toLowerCase())}function Ed(e){return Ge(e,ai)}function wd(e){return Ge(e,Bs)}function kd(e){return Ge(e,ci)}function Pd(e){return Ge(e,li)}function Td(e){return Ge(e,Hs)}function Md(e){return Ge(e,Ws)}function qs(e){return Me(e).toLowerCase()===".vb"}function Od(e){return Ge(e,ui)}function Fd(e){return Ge(e,Vs)}function mi(e){let t=Me(e).toLowerCase();for(let n of Ld)if(n.lookup.has(t))return n.extensions;return ut}function Ad(e){return wd(e)||Md(e)||Fd(e)}function Ie(e,t,n){return Ed(t)?Mt(e,t,n):kd(t)?Oe(e,t,n):Pd(t)?Qn(e,t,n):Td(t)?Yn(e,t,n):Ad(t)?q(e,n.replace(/\\/g,"."),mi(t)):Od(t)?Xn(e,t,n):$d(e,t,n)}function $d(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return null;let r=Je(Ce(e.config.projectRoot,t)),i=pe(r,n),o=rn(e);for(let s of Vd(i)){let a=fe(nn(e.config.projectRoot,s));if(o.has(a)||qn(s))return a}return fe(nn(e.config.projectRoot,i))}function Mt(e,t,n){let r=rn(e),i;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=Je(Ce(e.config.projectRoot,t));for(let l=1;l<s;l++)c=Je(c);i=a?pe(c,a.replace(/\./g,"/")):c}else i=pe(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of jd(i)){let s=fe(nn(e.config.projectRoot,o));if(r.has(s)||qn(o))return s}return null}function Oe(e,t,n){if(!n)return null;let r=n.replace(/\s+as\s+.+$/,"").trim();if(!r.startsWith("crate::")&&!r.startsWith("self::")&&!r.startsWith("super::"))return null;let i=Je(Ce(e.config.projectRoot,t)),o;return r.startsWith("crate::")?o=pe(e.config.projectRoot,"src",r.slice(7).replace(/::/g,"/")):r.startsWith("self::")?o=pe(i,r.slice(6).replace(/::/g,"/")):o=pe(Je(i),r.slice(7).replace(/::/g,"/")),di(e,Bd(o))}function Qn(e,t,n){let r=Je(Ce(e.config.projectRoot,t)),i=pe(r,n);return di(e,Hd(i))}function Yn(e,t,n){let r=Je(Ce(e.config.projectRoot,t)),i=[pe(r,n),pe(e.config.projectRoot,n),pe(e.config.projectRoot,"include",n),pe(e.config.projectRoot,"src",n)];return di(e,i)}function q(e,t,n){let r=rn(e),i=t.replace(/\\/g,".").replace(/::/g,".").replace(/^global::/,""),o=i.replace(/\./g,"/"),s=i.split(".").pop()??i;for(let c of n){let l=`${o}${c}`,u=[...r].find(m=>m.endsWith(l));if(u)return u}for(let c of n){let l=[...r].find(u=>vd(u)===`${s}${c}`);if(l)return l}let a=[...r].filter(c=>n.includes(Me(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function Xn(e,t,n){let r=rn(e);if(n.startsWith("package:")){let s=n.slice(8),a=s.indexOf("/");if(a<0)return null;let c=s.slice(a+1),l=fe(c.startsWith("lib/")?c:`lib/${c}`);return r.has(l)?l:null}let i=Je(Ce(e.config.projectRoot,t)),o=pe(i,n);for(let s of Wd(o)){let a=fe(nn(e.config.projectRoot,s));if(r.has(a)||qn(s))return a}return null}function jd(e){let t=Me(e);return ai.has(t)?[e]:[`${e}.py`,`${e}.pyi`,Ce(e,"__init__.py"),Ce(e,"__init__.pyi")]}function di(e,t){let n=rn(e);for(let r of t){let i=fe(nn(e.config.projectRoot,r));if(n.has(i)||qn(r))return i}return null}function Bd(e){let t=Me(e);return ci.has(t)?[e]:[`${e}.rs`,Ce(e,"mod.rs")]}function Hd(e){let t=Me(e);return li.has(t)?[e]:[`${e}.rb`,Ce(e,"index.rb")]}function Wd(e){let t=Me(e);return ui.has(t)?[e]:[`${e}.dart`,e]}function Vd(e){let t=Me(e),n=new Set;if(t){n.add(e);for(let r of ut)n.add(e.slice(0,-t.length)+r)}else for(let r of ut)n.add(`${e}${r}`),n.add(Ce(e,`index${r}`));return[...n]}function rn(e){return Dd.get(e,()=>new Set(k(e,{includeIgnored:!1}).map(fe)))}function fe(e){return e.replace(/\\/g,"/")}import{basename as Gs}from"path";function Ot(e){return e.replace(/'''[\s\S]*?'''/g,Ke).replace(/"""[\s\S]*?"""/g,Ke).replace(/#.*$/gm,Ke).replace(/\/\/.*$/gm,Ke).replace(/\/\*[\s\S]*?\*\//g,Ke).replace(/`(?:\\[\s\S]|[^`])*`/g,Ke).replace(/'(?:\\.|[^'\\\r\n])*'/g,Ke).replace(/"(?:\\.|[^"\\\r\n])*"/g,Ke)}function Ke(e){return e.replace(/[^\r\n]/g," ")}var pi=An("stripped-lines");function Us(e,t,n){return pi.get(e,t,n,()=>Ot(n).split(`
112
+ `))}function Js(e){pi.invalidateAll(e),Zn=null,on=""}function zs(e,t){pi.invalidate(e,t),Zn=null,on=""}var Zn=null,on="";function qd(e){return Zn===e||(Zn=e,on=Ot(e)),on}function Qe(e,t,n){let r=qd(e);return`${r.slice(0,t)}${" ".repeat(n-t)}${r.slice(n)}`}function oe(e,t){return new RegExp(`\\b${er(t)}\\b`,"m").test(e)}function Ft(e,t){let n=new Set,r=new RegExp(`\\b${er(t)}\\s*\\.\\s*([A-Za-z_$][\\w$]*)`,"g");for(let i of e.matchAll(r)){let o=i[1];o&&n.add(o)}return[...n]}function er(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sn(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var Ud=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function se(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++){let o=e[i];(o==="{"||o==="["||o==="(")&&n++,(o==="}"||o==="]"||o===")")&&n--,o===","&&n===0&&(t.push(e.slice(r,i)),r=i+1)}return t.push(e.slice(r)),t}function le(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function U(e,t){let n=new Set,r=(i,o)=>{let s=o||t.has(i.type);!s&&Ud.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,s)};return r(e.rootNode,!1),n}function Ee(e,t,n,r,i,o,s){return{importedName:i,localName:o,sourcePath:s??q(e,r,mi(t)),kind:"named",used:oe(n,o),usedMembers:[]}}function W(e,t,n,r,i="named",o={}){return{importedName:e,localName:t,sourcePath:n,kind:i,used:r.has(t),usedMembers:[],isTypeOnly:o.isTypeOnly}}function At(e,t,n,r,i="named",o=[],s={}){return{importedName:e,localName:t,sourcePath:n,kind:i,used:r,usedMembers:o,isTypeOnly:s.isTypeOnly}}function dt(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function pt(e,t,n={}){return{importedName:e,localName:n.localName??null,sourcePath:t,kind:"namespace",used:n.used??!0,usedMembers:n.usedMembers??[],isTypeOnly:n.isTypeOnly}}function ge(e,t,n){let r=[];for(let i of e.matchAll(t)){let o=i[0];if(!o||typeof i.index!="number")continue;let s=Qe(e,i.index,i.index+o.length);for(let a of n(i,s))r.push(a)}return r}function he(e,t,n,r){let i=B(e,t);if(i){let o=n(i);if(o)return o}return r()}function tr(e,t,n,r){let i=B(e,t),o=P(t),s=o?n[o]:void 0;return i&&s?s(i):r()}function Ks(e,t,n){return he(e,t,r=>zd(e,t,r),()=>Jd(e,t,n))}function Jd(e,t,n){return ge(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(r,i)=>{let o=r[1]?.trim();if(!o)return[];let s=Gs(o).replace(/\.[^.]+$/,"");return[At(o,s,Yn(e,t,o),oe(i,s))]})}function zd(e,t,n){let r=U(n,new Set(["preproc_include"])),i=[];for(let o of n.rootNode.descendantsOfType("preproc_include")){let s=null;for(let c of o.namedChildren){if(c.type==="system_lib_string"){s=c.text.replace(/^<|>$/g,"");break}if(c.type==="string_literal"){s=c.namedChildren.find(u=>u.type==="string_content")?.text??c.text.replace(/^"|"$/g,"");break}}if(!s)continue;let a=Gs(s).replace(/\.[^.]+$/,"");i.push(W(s,a,Yn(e,t,s),r))}return i}function Qs(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*import\s+['"]([^'"]+)['"](?:\s+as\s+([A-Za-z_]\w*))?[\s\S]*?;$/gm)){let o=i[1]?.trim(),s=i[2]?.trim()??null,a=i[0];if(!o||!a||typeof i.index!="number")continue;let c=Qe(n,i.index,i.index+a.length);r.push({importedName:o,localName:s,sourcePath:Xn(e,t,o),kind:s?"namespace":"side-effect",used:s?oe(c,s):!0,usedMembers:s?Ft(c,s):[]})}return r}function Ys(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*export\s+['"]([^'"]+)['"][\s\S]*?;$/gm)){let o=i[1]?.trim();o&&r.push({specifier:o,sourcePath:Xn(e,t,o)})}return r}function Xs(e,t,n){return tr(e,t,{csharp:r=>Kd(e,t,r),vb:r=>Gd(e,t,r)},()=>{let r=qs(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return ge(n,r,(i,o)=>{let s=i[1]?.trim();if(!s)return[];let[a,c]=s.split(/\s*=\s*/),l=!!c,u=(l?c:a)?.trim()??s,m=u.split(".").pop()??u,d=l?a?.trim()??m:m;return[Ee(e,t,o,u,m,d,q(e,u,ze))]})})}function Gd(e,t,n){let r=U(n,new Set(["imports_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("imports_statement")){let s=o.namedChildren.filter(d=>d.type==="namespace_name");if(s.length===0)continue;let a=s[s.length-1],c=s.length>1?s[0]:null,l=a.text,u=l.split(".").pop()??l,m=c?.text??u;i.push(W(u,m,q(e,l,ze),r,c?"namespace":"named"))}return i}function Kd(e,t,n){let r=U(n,new Set(["using_directive"])),i=[];for(let o of n.rootNode.descendantsOfType("using_directive")){let s=o.namedChildren;if(s.length===0)continue;let a=null,c;s.length>=2&&s[0].type==="identifier"&&(s[1].type==="qualified_name"||s[1].type==="identifier")?(a=s[0],c=s[1]):c=s[s.length-1];let l=c.text,u=l.split(".").pop()??l,m=a?.text??u;i.push(W(u,m,q(e,l,ze),r,a?"namespace":"named"))}return i}var Qd=H("vue-non-script-identifiers");function Zs(e,t){return Qd.get(e,t,()=>{let n=new Set,r=T(e,t);if(!r)return n;let o=r.replace(/<script\b[^>]*>[\s\S]*?<\/script>/g,s=>s.replace(/[^\r\n]/g," ")).replace(/<!--[\s\S]*?-->/g,s=>s.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,s=>s.replace(/[^\r\n]/g," "));for(let s of o.matchAll(/[A-Za-z_$][\w$]*/g))n.add(s[0]);return n})}function fi(e,t,n){return he(e,t,r=>Xd(e,t,r),()=>Yd(e,t,n))}function Yd(e,t,n){return lp(n).flatMap(r=>up(e,t,r.clause,r.specifier,r.start,r.end,n))}function Xd(e,t,n){let r=Zd(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(...ep(e,t,n,o,r));return i}function Zd(e,t,n){let r=U(n,new Set(["import_statement"]));if(st(t))for(let i of Zs(e,t))r.add(i);return r}function ep(e,t,n,r,i){let o=op(r);if(!o)return[];let s=Ie(e,t,o),a=le(r,"import_clause");return a?tp(n,a,s,i,sp(r.text)):[dt("*",s)]}function tp(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(np(s.text,n,r,i));else if(s.type==="namespace_import"){let a=rp(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...ip(s,n,r,i));return o}function np(e,t,n,r){return W("default",e,t,n,"default",{isTypeOnly:r})}function rp(e,t,n,r,i){let s=le(t,"identifier")?.text??"";if(!s)return null;let a=cp(e,s);return pt("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function ip(e,t,n,r){let i=[];for(let o of e.namedChildren){if(o.type!=="import_specifier")continue;let s=o.namedChild(0),a=o.namedChild(1);if(!s)continue;let c=s.text,l=a?.text??c;i.push(W(c,l,t,n,"named",{isTypeOnly:r||ap(o.text)}))}return i}function op(e){let t=le(e,"string");if(!t)return null;let n=le(t,"string_fragment");return n?n.text:null}function sp(e){return/^\s*import\s+type\b/.test(e)}function ap(e){return/^\s*type\b/.test(e.trim())}function cp(e,t){let n=new Set;for(let r of e.rootNode.descendantsOfType("member_expression")){let i=r.namedChild(0),o=r.namedChild(1);!i||!o||i.type!=="identifier"||i.text!==t||(o.type==="property_identifier"||o.type==="identifier")&&n.add(o.text)}return[...n]}function lp(e){let t=[],n=/^[ \t]*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(n)){let o=i[0],s=i[1],a=i[2];!o||!a||typeof i.index!="number"||t.push({clause:s,specifier:a,start:i.index,end:i.index+o.length})}let r=/^[ \t]*import\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(r)){let o=i[0],s=i[1];!o||!s||typeof i.index!="number"||t.push({clause:null,specifier:s,start:i.index,end:i.index+o.length})}return t.sort((i,o)=>i.start-o.start)}function up(e,t,n,r,i,o,s){let a=Ie(e,t,r),c=Qe(s,i,o);return n?mp(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let m=Ft(c,u.localName);return pt(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:m,used:m.length>0||oe(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?dt(u.importedName,u.sourcePath):At(u.importedName,u.localName??"",u.sourcePath,u.localName?oe(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[dt("*",a)]}function mp(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=dp(r),s=[];return i&&s.push(...ea(i,n)),o&&s.push(...ea(o,n)),s}function ea(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?se(r).map(i=>{let o=i.trim(),s=t||/^type\b/.test(o),a=o.replace(/^type\s+/,""),[c,l]=a.split(/\s+as\s+/);return{importedName:c.trim(),localName:(l??c).trim(),kind:"named",isTypeOnly:s}}):[]}return n.startsWith("* as ")?[{importedName:"*",localName:n.slice(5).trim(),kind:"namespace",isTypeOnly:t}]:[{importedName:"default",localName:n,kind:"default",isTypeOnly:t}]}function dp(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r==="{"&&t++,r==="}"&&t--,r===","&&t===0)return[e.slice(0,n).trim(),e.slice(n+1).trim()]}return[e.trim(),null]}function gi(e,t,n){let r=B(e,t);return r?bp(e,t,r):pp(e,t,n)}function pp(e,t,n){return[...fp(e,t,n),...gp(e,t,n),...hp(e,t,n)]}function fp(e,t,n){let r=[],i=/^[ \t]*export\s+(?:type\s+)?\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[1]??"",a=o[2]??"",c=se(s).map(m=>yp(m.trim())).filter(m=>!!m),l=$t(n,o.index),u=$t(n,o.index+o[0].length-1);r.push({kind:"named",sourcePath:Ie(e,t,a),names:c,startLine:l,endLine:u})}return r}function gp(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[2]??"",a=$t(n,o.index),c=$t(n,o.index+o[0].length-1);r.push({kind:"star-as",sourcePath:Ie(e,t,s),names:[],startLine:a,endLine:c})}return r}function hp(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[1]??"",a=$t(n,o.index),c=$t(n,o.index+o[0].length-1);r.push({kind:"star",sourcePath:Ie(e,t,s),names:[],startLine:a,endLine:c})}return r}function yp(e){if(!e)return null;let t=e.replace(/^type\s+/,"").trim();if(!t)return null;let n=t.match(/^(\w+)\s+as\s+(\w+)$/);if(n)return n[2]??null;let r=t.match(/^(\w+)$/);return r?r[1]??null:null}function $t(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function bp(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=Sp(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,c=xp(i,o,s,a);r.push(c)}return r}function Sp(e,t,n){let r=le(n,"string");if(!r)return;let i=le(r,"string_fragment");if(i)return Ie(e,t,i.text)}function xp(e,t,n,r){let i=le(e,"export_clause");if(i){let s=[];for(let a of i.namedChildren){if(a.type!=="export_specifier")continue;let c=a.namedChild(0),l=a.namedChild(1);c&&s.push((l??c).text)}return{kind:"named",sourcePath:t,names:s,startLine:n,endLine:r}}return le(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}function ta(e,t,n){return tr(e,t,{java:r=>Cp(e,t,r),kotlin:r=>Ip(e,t,r),scala:r=>Rp(e,t,r)},()=>ge(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?_p(e,t,o,i):[]}))}function Cp(e,t,n){let r=U(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.children.some(m=>m.type==="asterisk"),c=o.namedChildren.find(m=>m.type==="scoped_identifier")??o.namedChildren.find(m=>m.type==="identifier");if(!c)continue;let l=c.text;if(s){i.push(pt("*",q(e,l,ce)));continue}let u=l.split(".").pop()??l;i.push(W(u,u,q(e,l,ce),r))}return i}function Ip(e,t,n){let r=U(n,new Set(["import_header","import_list"])),i=[];for(let o of n.rootNode.descendantsOfType("import_header")){let s=o.namedChildren.find(p=>p.type==="identifier");if(!s)continue;let a=o.namedChildren.some(p=>p.type==="wildcard_import"),c=o.namedChildren.find(p=>p.type==="import_alias");if(a){i.push(pt("*",q(e,s.text,ce)));continue}let l=s.text,u=l.split(".").pop()??l,d=c?.namedChild(0)?.text??u;i.push(W(u,d,q(e,l,ce),r))}return i}function Rp(e,t,n){let r=U(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.namedChildren.find(m=>m.type==="namespace_selectors"||m.type==="namespace_wildcard"),a=o.namedChildren.filter(m=>m!==s&&(m.type==="identifier"||m.type==="stable_identifier")),c=a.map(m=>m.text).join(".");if(!c)continue;if(s?.type==="namespace_wildcard"){i.push(pt("*",q(e,c,ce)));continue}if(s?.type==="namespace_selectors"){for(let m of s.namedChildren)if(m.type==="arrow_renamed_identifier"){let[d,p]=m.namedChildren;if(!d)continue;let y=d.text,f=p?.text??y;if(y==="_")continue;i.push(W(y,f,q(e,`${c}.${y}`,ce),r))}else if(m.type==="identifier"){let d=m.text;i.push(W(d,d,q(e,`${c}.${d}`,ce),r))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(m=>m.text).join(".")||c;i.push(W(l,l,q(e,u&&a.length>1?`${u}.${l}`:c,ce),r))}return i}function _p(e,t,n,r){if(n.includes("{")&&n.includes("}")){let i=n.slice(0,n.indexOf("{")).replace(/\.$/,"").trim(),o=n.slice(n.indexOf("{")+1,n.lastIndexOf("}")).trim();return se(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.includes("=>")?a.split(/\s*=>\s*/):a.split(/\s+as\s+/),u=c?.trim();if(!u||u==="_")return[];let m=(l??u.split(".").pop()??u).trim(),d=u==="_"?i:`${i}.${u}`.replace(/\.\./g,".");return[Ee(e,t,r,d,u,m)]})}return[Ee(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function ra(e,t,n){return he(e,t,r=>vp(e,t,r),()=>ge(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?se(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.split(/\s+as\s+/i),u=c?.trim()??a,m=u.split("\\").pop()??u,d=(l??m).trim();return[Ee(e,t,i,u,m,d,q(e,u.replace(/\\/g,"."),mt))]}):[]}))}function vp(e,t,n){let r=U(n,new Set(["namespace_use_declaration"])),i=[],o=(s,a,c)=>{i.push(W(a,c,q(e,s.replace(/\\/g,"."),mt),r))};for(let s of n.rootNode.descendantsOfType("namespace_use_declaration")){let a=s.namedChildren.find(c=>c.type==="namespace_use_group");if(a){let c=s.namedChildren.find(l=>l.type==="namespace_name")?.text??"";for(let l of a.namedChildren){if(l.type!=="namespace_use_clause")continue;let{importedName:u,localName:m,qualified:d}=na(l,c);u&&o(d,u,m)}continue}for(let c of s.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:l,localName:u,qualified:m}=na(c,"");l&&o(m,l,u)}}return i}function na(e,t){let n=e.namedChildren.find(l=>l.type==="qualified_name"),r=e.namedChildren.filter(l=>l.type==="name"),i="";n?i=n.text:r.length>=1&&(i=r[0].text);let o=n&&r.length>0?r[r.length-1]:null,s=i.split("\\").pop()??i,a=o?.text??s,c=t?`${t}\\${i}`:i;return{importedName:s,localName:a,qualified:c}}function oa(e,t,n){return he(e,t,r=>Dp(e,t,r),()=>Lp(n).flatMap(r=>wp(e,t,r,n)))}function Dp(e,t,n){let r=U(n,new Set(["import_statement","import_from_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))for(let s of o.namedChildren){let a=ia(s);if(!a)continue;let c=Mt(e,t,a.qualifiedName);i.push({importedName:a.qualifiedName,localName:a.localName,sourcePath:c,kind:"namespace",used:r.has(a.localName),usedMembers:[]})}for(let o of n.rootNode.descendantsOfType("import_from_statement")){let s=o.namedChild(0);if(!s)continue;let a=Np(s);if(a===null)continue;let c=Mt(e,t,a);for(let l=1;l<o.namedChildCount;l+=1){let u=o.namedChild(l);if(u.type==="wildcard_import"){i.push({importedName:"*",localName:null,sourcePath:c,kind:"side-effect",used:!0,usedMembers:[]});continue}let m=ia(u);m&&i.push({importedName:m.qualifiedName,localName:m.localName,sourcePath:c,kind:"named",used:r.has(m.localName),usedMembers:[]})}}return i}function ia(e){if(e.type==="aliased_import"){let t=e.namedChild(0),n=e.namedChild(1);return!t||!n?null:{qualifiedName:t.text,localName:n.text}}if(e.type==="dotted_name"){let t=e.text;return{qualifiedName:t,localName:t.split(".")[0]??t}}return e.type==="identifier"?{qualifiedName:e.text,localName:e.text}:null}function Np(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=le(e,"import_prefix")?.text??"",n=le(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function Lp(e){let t=e.split(`
113
+ `),n=[],r=0;for(let i=0;i<t.length;i++){let o=t[i],s=o.trimStart(),a=r;if(r+=o.length+1,!s.startsWith("import ")&&!s.startsWith("from "))continue;let c=o,l=a+o.length,u=sn(o);for(;i+1<t.length&&(u>0||c.trimEnd().endsWith("\\"));){i++;let d=t[i];c+=`
114
+ ${d}`,l+=1+d.length,u+=sn(d),r+=d.length+1}let m=Ep(c);m&&n.push({...m,start:a,end:l})}return n}function Ep(e){let t=e.replace(/\\\s*\n/g," ").trim();if(t.startsWith("import "))return{kind:"import",module:null,clause:t.slice(7).trim()};let n=t.match(/^from\s+([.\w]+)\s+import\s+([\s\S]+)$/);if(!n)return null;let r=n[2].trim();return r.startsWith("(")&&r.endsWith(")")&&(r=r.slice(1,-1).trim()),{kind:"from",module:n[1],clause:r}}function wp(e,t,n,r){let i=Qe(r,n.start,n.end),o=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return se(o).flatMap(c=>{let l=c.trim().replace(/,$/,"");if(!l)return[];let[u,m]=l.split(/\s+as\s+/),d=u.trim(),p=(m??d.split(".")[0]??d).trim(),y=Mt(e,t,d),f=Ft(i,p);return[{importedName:d,localName:p,sourcePath:y,kind:"namespace",used:oe(i,p)||f.length>0,usedMembers:f}]});let s=n.module?Mt(e,t,n.module):null,a=[];for(let c of se(o)){let l=c.trim().replace(/,$/,"");if(!l)continue;if(l==="*"){a.push({importedName:"*",localName:null,sourcePath:s,kind:"side-effect",used:!0,usedMembers:[]});continue}let[u,m]=l.split(/\s+as\s+/),d=(m??u).trim();a.push({importedName:u.trim(),localName:d,sourcePath:s,kind:"named",used:oe(i,d),usedMembers:[]})}return a}import{basename as kp}from"path";function sa(e,t,n){return he(e,t,r=>Tp(e,t,r),()=>Pp(e,t,n))}function Pp(e,t,n){return ge(n,/^[ \t]*(require_relative|require)\s+["']([^"']+)["']\s*$/gm,(r,i)=>{let o=r[1],s=r[2];if(!o||!s)return[];let a=o==="require_relative"?Qn(e,t,s):null;if(a){let c=aa(s);return[At(c,c,a,oe(i,c))]}return[dt(s,a)]})}function Tp(e,t,n){let r=U(n,new Set([])),i=[],o=new Set(["require","require_relative","load"]);for(let s of n.rootNode.descendantsOfType("call")){let a=s.namedChild(0);if(!a||a.type!=="identifier"||!o.has(a.text))continue;let l=s.namedChildren.find(p=>p.type==="argument_list")?.namedChild(0);if(!l||l.type!=="string")continue;let m=l.namedChildren.find(p=>p.type==="string_content")?.text;if(!m)continue;let d=a.text==="require_relative"?Qn(e,t,m):null;if(d){let p=aa(m);i.push(W(p,p,d,r))}else i.push(dt(m,d))}return i}function aa(e){return kp(e).replace(/\.[^.]+$/,"").split("_").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function ca(e,t,n){return he(e,t,r=>Mp(e,t,r),()=>ge(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?Op(e,t,o,i):[]}))}function Mp(e,t,n){let r=U(n,new Set(["use_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("use_declaration")){let s=o.namedChild(0);if(s)for(let a of an(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=Oe(e,t,a.qualifiedName)??Oe(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push(W(a.importedName,a.localName,c,r))}}return i}function an(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":{let n=e.text;return[{qualifiedName:nr(t,n),importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,r=n.split("::").pop()??n;return[{qualifiedName:nr(t,n),importedName:r,localName:r}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=nr(t,n.text),o=[];for(let s of r.namedChildren)o.push(...an(s,i));return o}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(...an(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=an(n,t),o=r.text;return i.map(s=>({...s,localName:o}))}case"use_wildcard":{let n=e.namedChild(0),r=n?n.text:"";return[{qualifiedName:nr(t,`${r}::*`),importedName:"*",localName:"*"}]}default:return[]}}function nr(e,t){return e?t?`${e}::${t}`:e:t}function Op(e,t,n,r){let i=n.trim();if(i.includes("{")&&i.includes("}")){let u=i.slice(0,i.indexOf("{")).replace(/::$/,"").trim(),m=i.slice(i.indexOf("{")+1,i.lastIndexOf("}")).trim();return se(m).flatMap(d=>{let p=d.trim();if(!p||p==="self")return[];let[y,f]=p.split(/\s+as\s+/),b=y?.trim();if(!b)return[];let E=(f??b.split("::").pop()??b).trim(),x=`${u}::${b}`.replace(/::::/g,"::");return[Ee(e,t,r,x,b.split("::").pop()??b,E,Oe(e,t,u))]})}let[o,s]=i.split(/\s+as\s+/),a=o?.trim()??i,c=(s??a.split("::").pop()??a).trim(),l=Oe(e,t,a)??Oe(e,t,a.split("::").slice(0,-1).join("::"));return[Ee(e,t,r,a,a.split("::").pop()??a,c,l)]}function la(e,t,n){let r=B(e,t);if(r)return Fp(e,t,r);let i=[];for(let o of n.matchAll(/^[ \t]*pub\s+use\s+(.+?)\s*;$/gm)){let s=o[1]?.trim();s&&i.push(...$p(e,t,s))}return i}function Fp(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!Ap(i))continue;let o=i.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of an(o,""))s.importedName&&r.push(hi(e,t,s.qualifiedName))}return r}function Ap(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function $p(e,t,n){let r=n.trim();if(r.includes("{")&&r.includes("}")){let i=r.slice(0,r.indexOf("{")).replace(/::$/,"").trim(),o=r.slice(r.indexOf("{")+1,r.lastIndexOf("}")).trim();return se(o).flatMap(s=>{let a=s.trim();if(!a||a==="self")return[];let[c]=a.split(/\s+as\s+/),l=`${i}::${c?.trim()??a}`.replace(/::::/g,"::");return[hi(e,t,l)]})}return[hi(e,t,r)]}function hi(e,t,n){return{specifier:n,sourcePath:Oe(e,t,n)??Oe(e,t,n.split("::").slice(0,-1).join("::"))}}function ft({language:e,extensions:t,imports:n,parseImports:r}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:r}}function ua(e,t){let n=t.toLowerCase();for(let r of e)for(let i of r.extensions)if(n.endsWith(i))return r;return null}var jp={language:"javascript",extensions:ut,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:fi,parseReExports:gi},Bp=ft({language:"python",extensions:Un,imports:"ast-with-regex-fallback",parseImports:oa}),Hp=ft({language:"jvm",extensions:ce,imports:"ast-dispatch-with-regex-fallback",parseImports:ta}),Wp={language:"rust",extensions:Jn,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:ca,parseExports:la},Vp=ft({language:"ruby",extensions:zn,imports:"ast-with-regex-fallback",parseImports:sa}),qp=ft({language:"c/cpp",extensions:Gn,imports:"ast-with-regex-fallback",parseImports:Ks}),Up=ft({language:"dotnet",extensions:ze,imports:"ast-dispatch-with-regex-fallback",parseImports:Xs}),Jp={language:"dart",extensions:Kn,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:Qs,parseExports:Ys},zp=ft({language:"php",extensions:mt,imports:"ast-with-regex-fallback",parseImports:ra}),Gp=[jp,Bp,Hp,Wp,Vp,qp,Up,Jp,zp];function rr(e){return ua(Gp,e)}var yi=H("source-imports"),bi=H("source-exports"),Si=H("source-reexports");function ma(e,t){let n=fe(t);return Si.get(e,n,()=>{let r=rr(n);if(!r?.parseReExports)return[];let i=T(e,n);return i?r.parseReExports(e,n,i):[]})}function Y(e,t){let n=fe(t);return yi.get(e,n,()=>{let r=rr(n);if(!r)return[];let i=T(e,n);return i?r.parseImports(e,n,i):[]})}function xi(e,t){let n=fe(t);return bi.get(e,n,()=>{let r=rr(n);if(!r?.parseExports)return[];let i=T(e,n);return i?r.parseExports(e,n,i):[]})}function da(e){yi.invalidateAll(e),bi.invalidateAll(e),Si.invalidateAll(e)}function pa(e,t){let n=fe(t);yi.invalidate(e,n),bi.invalidate(e,n),Si.invalidate(e,n)}var fa=H("file-dep-graph");function ae(e,t){return fa.get(e,t??"",()=>{let n=new Map,r=new Set(k(e,{includeIgnored:!1})),i=(o,s)=>Qp(e,n,r,o,s);for(let o of Kp(e,t))i(o.from_file,o.to_file);for(let o of r)if(!(t&&!o.includes(t)))for(let s of Y(e,o))s.sourcePath&&i(o,s.sourcePath);return n})}function Kp(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
115
+ d1.relative_path AS from_file,
116
+ d2.relative_path AS to_file
117
+ FROM mentions m
118
+ JOIN chunks c ON m.chunk_id = c.id
119
+ JOIN documents d1 ON c.document_id = d1.id
120
+ JOIN global_symbols gs ON m.symbol_id = gs.id
121
+ JOIN (
122
+ SELECT m2.symbol_id, c2.document_id
123
+ FROM mentions m2
124
+ JOIN chunks c2 ON m2.chunk_id = c2.id
125
+ WHERE m2.role = 1
126
+ GROUP BY m2.symbol_id
127
+ ) sym_def ON sym_def.symbol_id = gs.id
128
+ JOIN documents d2 ON sym_def.document_id = d2.id
129
+ WHERE d1.id != d2.id
130
+ AND m.role != 1
131
+ ${e.pathExclusionsFor("d1","d2")}
132
+ ${n}`)}function Qp(e,t,n,r,i){if(r===i||e.isIgnored(r)||e.isIgnored(i)||!n.has(i))return;let o=t.get(r);o||(o=new Set,t.set(r,o)),o.add(i)}function ga(e){fa.invalidateAll(e)}import{readdirSync as Yp}from"fs";import{extname as ha,join as Xp}from"path";var Zp=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".rs",".py",".pyi",".java",".kt",".kts",".scala",".sc",".rb",".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx",".cs",".vb",".php",".dart"],ya=[".vue"],ba=new Set(Zp.map(e=>e.toLowerCase())),ef=[...ba].sort().join(","),Ci=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function Ye(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(c=>c.toLowerCase()),o=i?new Set(i):ba,s=i?[...o].sort().join(","):ef,a=`${n?"1":"0"}|${r?"1":"0"}|${s}`;return tf.get(e,a,()=>{let c=new Set;if(n)for(let l of k(e,{includeIgnored:!1}))o.has(ha(l).toLowerCase())&&c.add(l);if(r)for(let l of nf(e.config.projectRoot,o))e.isIgnored(l)||c.add(l);return[...c].sort()})}var tf=H("source-files");function nf(e,t){let n=new Set,r=i=>{let o=i?Xp(e,i):e,s;try{s=Yp(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!Ci.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(ha(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}function ue(e){let t=cn(e);return of(t)?"test":sf(t)?"worker":af(t)?"entry":cf(t)?"barrel":"source"}function ir(e){return ue(e)==="barrel"}function xa(e){return rf.get(e,()=>{let t=ae(e),n=Ye(e).filter(o=>{let s=ue(o);return s==="entry"||s==="worker"}),r=new Set,i=new Set;for(;n.length>0;){let o=n.shift();if(!r.has(o)){r.add(o),ue(o)==="barrel"&&i.add(o);for(let s of t.get(o)??[])r.has(s)||n.push(s)}}return i})}var rf=We("live-barrels");function Ii(e,t){return xa(e).has(cn(t))}function Ca(e){let t=xa(e);return Ye(e).filter(n=>ir(n)&&!t.has(n))}function gt(e,t){let n=ue(t);return n==="entry"||n==="worker"||Ii(e,t)}function ln(e,t,n){let r=e.config.entryRoots;if(!r)return!1;let i=cn(n);return!!(r.files?.some(o=>cn(o)===i)||r.pathPrefixes?.some(o=>i.startsWith(cn(o)))||r.qualifiedVars?.some(o=>lf(t,o))||r.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}}))}var Ia=["%/__tests__/%","%.test.%","%.spec.%","%/test/%","%/tests/%","%_test.%","%_spec.%","%/test_%.%","%/spec_%.%"],Ra=["%/test-utils/%"];function of(e){return!!(/\.(?:test|spec)\.[a-z0-9]+$/i.test(e)||/(?:^|\/)(?:_)?test_[^/]+$/i.test(e)||/(?:^|\/)spec_[^/]+$/i.test(e)||/(?:^|\/)[^/]+_test\.[a-z0-9]+$/i.test(e)||/(?:^|\/)[^/]+_tests\.rs$/i.test(e)||/(?:^|\/)tests\.rs$/i.test(e)||/(?:^|\/)[^/]+_spec\.[a-z0-9]+$/i.test(e)||/(?:^|\/)__tests__\//i.test(e)||/(?:^|\/)test\//i.test(e)||/(?:^|\/)tests\//i.test(e)||/(?:^|\/)__fixtures__\//i.test(e)||/(?:^|\/)__mocks__\//i.test(e)||/(?:^|\/)test-support\//i.test(e)||/(?:^|\/)test-utils\//i.test(e)||/(?:^|\/)testing\//i.test(e))}function sf(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function af(e){let t=e.split("/"),n=t[t.length-1]??e;return n==="cli.ts"||n==="cli.js"||n==="postinstall.ts"||n==="postinstall.js"||n==="main.ts"||n==="main.js"||n==="main.rs"||n==="main.go"||n==="main.py"||n==="build.rs"||n==="lib.rs"||/\bsrc\/bin\/[^/]+\.rs$/.test(e)||/(?:^|\/)examples\/[^/]+\.rs$/.test(e)||/(?:^|\/)tests\/[^/]+\.rs$/.test(e)||/(?:^|\/)benches\/[^/]+\.rs$/.test(e)?!0:n==="index.ts"||n==="index.js"?/(?:^|\/)(?:apps|services)\/[^/]+\/src\/index\.(?:ts|js)$/.test(e)?!0:t.length<=2:!1}function cf(e){return e==="index.ts"||e==="index.js"||e.endsWith("/index.ts")||e.endsWith("/index.js")||e.endsWith("/mod.rs")||e.endsWith("/__init__.py")}function cn(e){return e.replace(/\\/g,"/")}function lf(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let r=t.slice(0,n),i=t.slice(n+1);return e.includes(Sa(r)+"/")&&e.includes(Sa(i)+".")}function Sa(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}var un=new WeakMap;function Da(e,t){let n=P(t);return n==="rust"?ff(e,t):n==="typescript"||n==="tsx"||n==="javascript"?mf(e,t):[]}var uf=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]);function mf(e,t){let n=B(e,t);if(!n)return[];let r=un.get(n);if(r)return r;let i=/(^|\/)(pages|app)\/.+\.(tsx?|jsx?)$/.test(t)||/(^|\/)(layout|page|loading|error|not-found|head|template|default)\.(tsx?|jsx?)$/.test(t),o=/(^|\/)src\/(pages|views|routes)\/.+\.(tsx?|jsx?|vue)$/.test(t),s=!1,a=n.rootNode;for(let l of a.namedChildren){if(l.type!=="expression_statement")continue;let u=l.namedChild(0);if(!u||u.type!=="call_expression")continue;let m=u.namedChild(0);if(!m)continue;let d=m.type==="member_expression"?m.namedChild(m.namedChildCount-1)?.text:m.text;if(d&&uf.has(d)){s=!0;break}}let c=[];s&&c.push({startLine:0,endLine:a.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"}),(i||o)&&c.push({startLine:0,endLine:a.endPosition.row,reason:i?"Next.js / Remix route file":"Vite/Vue route component"});for(let l of a.namedChildren){let u=null,m=null;if(l.type==="function_declaration")u=l.namedChild(0)?.text??null,m=l;else if(l.type==="export_statement"){let d=l.namedChild(0);d?.type==="function_declaration"&&(u=d.namedChild(0)?.text??null,m=d)}else if(l.type==="lexical_declaration"){let d=l.namedChild(0);if(d?.type==="variable_declarator"){let p=d.namedChild(0)?.text,y=d.namedChild(1);p&&(y?.type==="arrow_function"||y?.type==="function_expression")&&(u=p,m=d)}}u&&/^use[A-Z]/.test(u)&&m&&c.push({startLine:m.startPosition.row,endLine:m.endPosition.row,reason:"React custom hook (use*)"})}return c.push(...Na(n,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),un.set(n,c),c}var df=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function pf(e){return df.test(e)}function Na(e,t,n){let r=[],i=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,c=-1;for(let l=0;l<a.length;l+=1)if(a[l].startIndex===o.startIndex&&a[l].type===o.type){c=l;break}if(c>0)for(let l=c-1;l>=0;l-=1){let u=a[l];if(n.has(u.type)){if(pf(u.text)){r.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)i(s)};return i(e.rootNode),r}function ff(e,t){let n=B(e,t);if(!n)return[];let r=un.get(n);if(r)return r;let i=[],o=gf(n);return o?(un.set(n,o),o):(La(n.rootNode,i,!1,!1),i.push(...Na(n,new Set(["function_item","function_signature_item","struct_item","enum_item","union_item","impl_item","mod_item","static_item","const_item"]),new Set(["line_comment","block_comment"]))),i.push(...Cf(n.rootNode)),un.set(n,i),i)}function gf(e){return If(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function La(e,t,n,r){let i=n,o=r;e.type==="trait_item"&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait declaration body (dynamic dispatch)"}),e.type==="impl_item"&&e.childForFieldName("trait")&&(o=!0,t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl block (dynamic dispatch)"})),e.type==="function_item"||e.type==="function_signature_item"?hf(e,t,n,r):r&&xf(e)?t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)"}):e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item"?yf(e,t,n):e.type==="mod_item"&&Ri(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)La(s,t,i,o)}function hf(e,t,n,r){let i=Ri(e),o=null;r?o="trait impl method (dynamic dispatch)":n&&(o="inside #[cfg(test)] mod");for(let s of i){let a=bf(s);if(a){o=a;break}if(Ea(s)){o="#[allow(dead_code)]";break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o})}function yf(e,t,n){let r=Ri(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(Sf)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:i}),r.some(Ea)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",containerName:i})}function Ri(e){let t=e.parent;if(!t)return[];let n=t.children,r=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){r=o;break}if(r<=0)return[];let i=[];for(let o=r-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")i.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return i}function bf(e){return/#\[\s*tauri::command\b/.test(e)?"#[tauri::command]":/#\[\s*command\b/.test(e)?"#[command]":/#\[\s*test\b/.test(e)?"#[test]":/#\[\s*bench\b/.test(e)?"#[bench]":/#\[\s*tokio::test\b/.test(e)?"#[tokio::test]":/#\[\s*async_std::test\b/.test(e)?"#[async_std::test]":/#\[\s*wasm_bindgen\b/.test(e)?"#[wasm_bindgen]":/#\[\s*no_mangle\b/.test(e)?"#[no_mangle]":/#\[\s*napi\b/.test(e)?"#[napi]":/#\[\s*pyfunction\b/.test(e)?"#[pyfunction]":/#\[\s*pymethod\b/.test(e)?"#[pymethod]":/#\[\s*pyo3\b/.test(e)?"#[pyo3]":/#\[\s*cfg\s*\(\s*test\s*\)/.test(e)?"#[cfg(test)]":/#\[\s*doc\s*\(\s*hidden\s*\)/.test(e)?"#[doc(hidden)]":null}function Sf(e){return/#\[\s*derive\s*\(/.test(e)?/\bSerialize\b/.test(e)||/\bDeserialize\b/.test(e)||/\bFromRow\b/.test(e)||/\bDeriveEntityModel\b/.test(e)||/\bIntoSchema\b/.test(e)||/\bToSchema\b/.test(e)||/\bDeriveValueType\b/.test(e)||/\bsqlx::FromRow\b/.test(e)||/\bError\b/.test(e)||/\bthiserror::Error\b/.test(e):!1}function Ea(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function xf(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function Cf(e){let t=Nf(e);if(t.size===0)return[];let n=[];for(let r of e.descendantsOfType("mod_item")){let i=r.childForFieldName("name")?.text;i&&t.has(i)&&n.push({startLine:r.startPosition.row,endLine:r.endPosition.row,reason:'serde `with = "..."` module \u2014 body invoked via reflection',containerName:i})}return n}function If(e){for(let t=0;t<Math.min(e.namedChildCount,12);t+=1){let n=e.namedChild(t);if(!n||n.type!=="line_comment"&&n.type!=="block_comment")break;if(/@generated\b/.test(n.text)||/This file is .*generated\b/i.test(n.text)||/Code generated by/i.test(n.text)||/Generated by:\s*https?:\/\/openapi-generator/i.test(n.text)||/openapi-generator/i.test(n.text)&&/Generated by/i.test(n.text))return!0}return!1}var Rf=[{key:"default",re:/\bdefault\s*=\s*"([^"]+)"/g},{key:"with",re:/\bwith\s*=\s*"([^"]+)"/g},{key:"serialize_with",re:/\bserialize_with\s*=\s*"([^"]+)"/g},{key:"deserialize_with",re:/\bdeserialize_with\s*=\s*"([^"]+)"/g},{key:"skip_serializing_if",re:/\bskip_serializing_if\s*=\s*"([^"]+)"/g},{key:"getter",re:/\bgetter\s*=\s*"([^"]+)"/g},{key:"rename_all_with",re:/\brename_all_with\s*=\s*"([^"]+)"/g},{key:"schema_with",re:/\bschema_with\s*=\s*"([^"]+)"/g}],wa=/^#!?\[\s*serde\s*\(/,_f=/^#!?\[\s*schemars\s*\(/,vf=/^#!?\[\s*validate\s*\(/,_a=/\bwith\s*=\s*"([^"]+)"/g;function jt(e,t){return tn(e,t,Df,()=>new Set,(n,r,i)=>{if(r==="rust"){for(let o of n.rootNode.descendantsOfType("attribute_item"))va(o.text,i);for(let o of n.rootNode.descendantsOfType("inner_attribute_item"))va(o.text,i)}})??new Set}var Df=new WeakMap;function va(e,t){let n=wa.test(e),r=_f.test(e),i=vf.test(e);if(!(!n&&!r&&!i))for(let{re:o}of Rf){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;){let a=s[1],c=a.split("::").pop()??a;c==="is_none"&&/\bOption\b/.test(a)||c==="is_empty"&&/\b(String|Vec|HashMap|BTreeMap|HashSet|BTreeSet)\b/.test(a)||c&&t.add(c)}}}function Nf(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!wa.test(n.text))continue;_a.lastIndex=0;let r;for(;(r=_a.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}var Lf=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function ka(e,t){return tn(e,t,Ef,()=>new Set,(n,r,i)=>{if(!(r!=="typescript"&&r!=="tsx"&&r!=="javascript"))for(let o of n.rootNode.descendantsOfType("call_expression")){let s=o.namedChild(0);if(!s)continue;let a=Dt(s);if(!a||!Lf.has(a))continue;let c=o.namedChildren.find(m=>m.type==="arguments");if(!c)continue;let l=c.namedChild(0);if(!l||l.type!=="string")continue;let u=l.namedChildren.find(m=>m.type==="string_fragment");u&&i.add(u.text)}})??new Set}var Ef=new WeakMap;var wf=new Set(["identifier","type_identifier","field_identifier"]),kf=new Set(["identifier"]),Pf=new Set(["identifier","property_identifier","type_identifier"]),Tf=new Set(["rust","python"]),Mf=/\{([^{}]*)\}/g,Of=/\b([A-Za-z_][\w]*)\b/g;function or(e,t,n,r={}){if(!n)return[];let i=T(e,t);if(!i)return[];if(i.indexOf(n)===-1)return[];if(P(t))return(ht(e,t).get(n)??[]).filter(u=>!Pa(u,r));let o=Us(e,t,i),s=new RegExp(`\\b${er(n)}\\b`),a=[];for(let c=0;c<o.length;c++)Pa(c,r)||s.test(o[c]??"")&&a.push(c);return a}function Pa(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var _i=H("file-identifiers");function Ta(e,t){return _i.get(e,t,()=>new Set(ht(e,t).keys()))}var vi=H("file-ident-lines");function ht(e,t){return vi.get(e,t,()=>Ff(e,t))}var Di=H("file-idents-by-line");function Ma(e,t){return Di.get(e,t,()=>{let n=ht(e,t),r=0;for(let o of n.values()){let s=o[o.length-1];s!==void 0&&s>r&&(r=s)}let i=new Array(r+1);for(let o=0;o<=r;o+=1)i[o]=new Set;for(let[o,s]of n)for(let a of s)i[a].add(o);return i})}function Oa(e){_i.invalidateAll(e),vi.invalidateAll(e),Di.invalidateAll(e)}function Fa(e,t){_i.invalidate(e,t),vi.invalidate(e,t),Di.invalidate(e,t)}function Ff(e,t){let n=new Map,r=(a,c)=>{let l=n.get(a);if(!l){n.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)};if(P(t)){let a=B(e,t);if(a){let c=P(t),l=c==="rust"?wf:c==="python"?kf:Pf,u=m=>{if(l.has(m.type)&&r(m.text,m.startPosition.row),c&&Tf.has(c)&&m.type==="string_content"){let d=m.startPosition.row;for(let p of m.text.matchAll(Mf)){let y=p[1]??"";for(let f of y.matchAll(Of))f[1]&&r(f[1],d)}}for(let d of m.children)u(d)};return u(a.rootNode),n}}let i=T(e,t);if(!i)return n;let o=Ot(i).split(/\r?\n/),s=/\b([A-Za-z_$][\w$]*)\b/g;for(let a=0;a<o.length;a+=1){let c=o[a]??"";for(let l of c.matchAll(s))l[1]&&r(l[1],a)}return n}function Aa(e,t){return Ni(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
133
+ m.symbol_id,
134
+ d.relative_path,
135
+ COUNT(*) AS ref_count
136
+ FROM mentions m
137
+ JOIN chunks c ON m.chunk_id = c.id
138
+ JOIN documents d ON c.document_id = d.id
139
+ WHERE m.role != 1
140
+ ${r}
141
+ ${e.pathExclusionsFor("d")}
142
+ GROUP BY m.symbol_id, d.relative_path`,...n??[])})}function $a(e,t){return Ni(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path
143
+ FROM mentions m
144
+ JOIN chunks c ON m.chunk_id = c.id
145
+ JOIN documents d ON c.document_id = d.id
146
+ WHERE m.role != 1
147
+ ${r}
148
+ ${e.pathExclusionsFor("d")}`,...n??[])}).filter(n=>n.symbol_id!==null)}function sr(e,t){return Ni(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path, c.document_id,
149
+ c.start_line AS chunk_start, c.end_line AS chunk_end
150
+ FROM mentions m
151
+ JOIN chunks c ON m.chunk_id = c.id
152
+ JOIN documents d ON c.document_id = d.id
153
+ WHERE m.role != 1
154
+ ${r}
155
+ ${e.pathExclusionsFor("d")}
156
+ ORDER BY d.relative_path, c.start_line`,...n??[])})}function Ni(e,t,n){if(!t)return n();if(t.length===0)return[];let r=[];for(let i=0;i<t.length;i+=750)r.push(...n(t.slice(i,i+750)));return r}function ja(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Xe(e,t){return ja(e)===ja(t)}function ar(e,t){let n=Ba(e);return n?t.filter(r=>Ba(r.file)===n):t}function cr(e,t,n,r){let i=n.find(o=>o.file===t);if(i)return i;if(r){let o=new Set(Y(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(Xe(a,s.file))return s;return null}return n.length===1?n[0]:null}function Ba(e){let t=P(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var Ha=We("global-leaf-index");function yt(e){return Ha.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
157
+ COALESCE(der_doc.relative_path, mention_doc.relative_path) AS relative_path
158
+ FROM global_symbols gs
159
+ LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
160
+ LEFT JOIN documents der_doc ON der_doc.id = der.document_id
161
+ LEFT JOIN (
162
+ SELECT m.symbol_id, MIN(d.relative_path) AS relative_path
163
+ FROM mentions m
164
+ JOIN chunks c ON m.chunk_id = c.id
165
+ JOIN documents d ON c.document_id = d.id
166
+ WHERE m.role = 1
167
+ GROUP BY m.symbol_id
168
+ ) mention_doc ON mention_doc.symbol_id = gs.id
169
+ WHERE 1 = 1
170
+ ${e.symbolNoiseFor("gs")}`),n=new Map;for(let r of t){if(!r.relative_path||e.isIgnored(r.relative_path))continue;let i=L(r.symbol);if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.some(s=>s.symbolId===r.id)||o.push({symbol:r.symbol,symbolId:r.id,file:r.relative_path})}return n})}function Wa(e){Ha.invalidate(e)}function Re(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import Va from"path";function Af(e,t){return e.getReferences().map(n=>{let r=n.getNode();return Ja(r,t)})}function $f(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function qa(e,t,n,r){let i=[];for(let o of $f(e))for(let s of Af(o,r))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||i.push(s);for(let o of n)i.push(o);return lr(i)}function Ua(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();mn(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:Ja(a,r),node:a}))}return i}function Ja(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:mn(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function za(e,t,n){let r=e.getSourceFile(),i=Bt(r,e),o=e.getText(),s=new RegExp(`\\b${jf(o)}\\b`,"g"),a=r.getFullText().split(`
171
+ `),c=[];for(let l=0;l<a.length;l++){if(l===i)continue;let u=a[l]??"";s.lastIndex=0;let m;for(;(m=s.exec(u))!==null;)c.push({file:t,line:l,column:m.index})}return lr(c.filter(l=>mn(n,Va.join(n,l.file))===t))}function Li(e){for(let t=e;t;t=t.getParent()){let n=t.getKindName();if(n.includes("Type")||n==="InterfaceDeclaration"||n==="TypeAliasDeclaration")return!0;if(n==="CallExpression"||n==="NewExpression"||n==="ExpressionStatement")return!1}return!1}function Bt(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function lr(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.line}:${r.column}`;t.has(i)||(t.add(i),n.push(r))}return n}function mn(e,t){let n=Va.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function jf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ga(e,t,n,r){let i=Bf(t,r);return i.size===0?new Map:Hf(e,n,i)}function Bf(e,t){let n=new Map;for(let r of V(e,t)){let i=L(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function Hf(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of Wf(e,o)){let a=n.get(s);if(!a)continue;let c=Bt(t,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let u=Math.abs(c-l.startLine),m=i.get(l.symbolId);m!==void 0&&m<=u||(i.set(l.symbolId,u),r.set(l.symbolId,o))}}}),r}function Wf(e,t){let n=[],r=i=>{i&&!n.includes(i)&&n.push(i)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let i=t.getNameNode();r(i?.getText())}if("getName"in t&&typeof t.getName=="function"){let i=t.getName();r(i)}return e.Node.isIdentifier(t)&&r(t.getText()),n}function Ka(e,t,n,r){return e.all(`SELECT
383
172
  gs.id AS symbolId,
384
173
  gs.symbol,
385
174
  d.relative_path AS relativePath,
@@ -399,7 +188,7 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
399
188
  WHERE d.relative_path = ?
400
189
  AND COALESCE(gs.display_name, gs.symbol) LIKE ?
401
190
  ORDER BY ABS(COALESCE(der.start_line, c.start_line) - ?)
402
- LIMIT 5`,t,`%${r}%`,n)[0]??null}function fh(e,t){let n=e.all(`SELECT
191
+ LIMIT 5`,t,`%${r}%`,n)[0]??null}function Qa(e,t){let n=e.all(`SELECT
403
192
  d.id AS documentId,
404
193
  gs.id AS symbolId,
405
194
  gs.symbol,
@@ -439,29 +228,7 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
439
228
  WHERE d.relative_path = ?
440
229
  AND m.role = 1
441
230
  GROUP BY gs.id, gs.symbol, d.id, d.relative_path, gs.display_name, gs.kind, gs.documentation, gs.enclosing_symbol
442
- ORDER BY startLine, endLine`,t,t),r=new Set,i=new Map;for(let s of n){if(r.has(s.symbolId))continue;r.add(s.symbolId);let o=s.leaf||k(s.symbol);!o||i.has(o)||i.set(o,{...s,leaf:o})}return i}function ph(e,t){let n=null;for(let r of e)t<r.startLine||t>r.endLine||(!n||r.startLine>=n.startLine)&&(n=r);return n}function Cn(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Ur(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.line}:${r.column}`;t.has(i)||(t.add(i),n.push(r))}return n}function gh(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function hh(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}|${r.line}`;t.has(i)||(t.add(i),n.push(r))}return n}function ve(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}function vn(e,t){let n=me.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function yh(e){return/\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(e)}function $o(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}function bh(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Vr=new WeakMap;function Jr(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,r=Vr.get(e);r||(r=new Map,Vr.set(e,r));let i=r.get(n);if(i)return i;let s=Bo(e,t);return r.set(n,s),s}function qr(e){Vr.delete(e)}function Lt(e,t){let n=Nn(e,t);return n?n.importUsage(t):[]}function wt(e,t){let n=Nn(e,t.relativePath);return n?n.referencesFor(t):[]}function pt(e,t){let n=new Map;for(let r of t)for(let i of wt(e,r)){if(i.file===r.relativePath||e.isIgnored(i.file))continue;let s=n.get(r.symbolId);s||(s=new Set,n.set(r.symbolId,s)),s.add(i.file)}return n}function Wo(e,t){let n=new Map;for(let r of t){let i=Nn(e,r.relativePath);if(!i)continue;let s=i.calleesFor(r);s.length>0&&n.set(r.symbolId,s)}return n}function Uo(e,t){let n=Nn(e,t.relativePath);return n?n.signatureFor(t):null}function Nn(e,t){if(!Sh(t))return null;let n=Jr(e,t);return n.availability().available?n:null}function Sh(e){return/\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(e)}var zo=j("file-dep-graph");function Go(e){zo.invalidateAll(e),Ko.invalidate(e),Xo.invalidate(e)}function Z(e,t){return zo.get(e,t??"",()=>{let n=new Map,r=_h(e),i=(s,o)=>Ih(e,n,r,s,o);for(let s of xh(e,t))i(s.from_file,s.to_file);for(let s of r)if(!(t&&!s.includes(t)))for(let o of q(e,s))o.sourcePath&&i(s,o.sourcePath);return n})}function xh(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
443
- d1.relative_path AS from_file,
444
- d2.relative_path AS to_file
445
- FROM mentions m
446
- JOIN chunks c ON m.chunk_id = c.id
447
- JOIN documents d1 ON c.document_id = d1.id
448
- JOIN global_symbols gs ON m.symbol_id = gs.id
449
- JOIN (
450
- SELECT m2.symbol_id, c2.document_id
451
- FROM mentions m2
452
- JOIN chunks c2 ON m2.chunk_id = c2.id
453
- WHERE m2.role = 1
454
- GROUP BY m2.symbol_id
455
- ) sym_def ON sym_def.symbol_id = gs.id
456
- JOIN documents d2 ON sym_def.document_id = d2.id
457
- WHERE d1.id != d2.id
458
- AND m.role != 1
459
- ${e.pathExclusionsFor("d1","d2")}
460
- ${n}`)}function _h(e){return new Set(e.all(`SELECT relative_path
461
- FROM documents
462
- WHERE 1 = 1
463
- ${e.pathExclusionsFor("documents")}
464
- ORDER BY relative_path`).map(t=>t.relative_path).filter(t=>!e.isIgnored(t)))}function Ih(e,t,n,r,i){if(r===i||e.isIgnored(r)||e.isIgnored(i)||!n.has(i))return;let s=t.get(r);s||(s=new Set,t.set(r,s)),s.add(i)}function te(e,t,n={}){let r=En(e,[t],{additive:n.additive,semantic:n.semantic}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(s=>G(s.symbol)):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function oe(e,t,n={}){let r=Ch(e)?Nh(e,t,{semantic:n.semantic!==!1}):vh(e).get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}var Ko=Ue("caller-rows"),Rh=2e4;function Ch(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>Rh}function vh(e){return Ko.get(e,()=>{let t=_e(e),n=En(e,t),r=new Map;for(let o of t)r.set(o.symbol,o.symbolId);let i=new Map,s=new Map;for(let o of t){let a=n.get(o.symbolId);if(!(!a||a.length===0))for(let l of a){let c=r.get(l.symbol);if(c===void 0||c===o.symbolId)continue;let u=i.get(c);u||(u=[],i.set(c,u),s.set(c,new Set));let d=`${o.symbol}|${o.relativePath}`;s.get(c).has(d)||(s.get(c).add(d),u.push({symbol:o.symbol,file:o.relativePath}))}}return i})}function Nh(e,t,n){let r=[],i=new Set,s=a=>{if(a.symbol===t.symbol)return;let l=`${a.symbol}|${a.file}`;i.has(l)||(i.add(l),r.push(a))};for(let a of Ne(e,t))a.file!==t.relativePath&&s({symbol:a.enclosingSymbol??a.file,file:a.file});let o=n.semantic?Eh(e,t):null;if(o)for(let a of wt(e,o)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let l=le(J(e,a.file),a.line);s({symbol:l?.symbol??a.file,file:a.file})}return r}function Eh(e,t){return e.get(`SELECT
231
+ ORDER BY startLine, endLine`,t,t),r=new Set,i=new Map;for(let o of n){if(r.has(o.symbolId))continue;r.add(o.symbolId);let s=o.leaf||L(o.symbol);!s||i.has(s)||i.set(s,{...o,leaf:s})}return i}import Vf from"path";var dn=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function ur(e){let t=e.toLowerCase();return dn.some(n=>t.endsWith(n))}function Ya(e,t){let n=new Map,r=i=>ur(i)?Re(n,i,()=>{let o=Vf.join(e.config.projectRoot,i);for(let{project:s}of t){let a=s.getSourceFile(o)??s.addSourceFileAtPathIfExists(o)??null;if(a)return{project:s,sourceFile:a}}return null}):null;return{sourceFile:i=>r(i)?.sourceFile??null,sourceFileMatch:r,indexedTypeScriptLikeDocuments:()=>k(e,{extensions:dn})}}import Ze from"path";import{existsSync as mr,readdirSync as qf,readFileSync as Xa}from"fs";function Za(e){let t=Ze.join(e,"package.json");if(!mr(t))return[];let n;try{n=JSON.parse(Xa(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>Uf(e,i)).flatMap(i=>Jf(e,i))}function Uf(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=Ze.join(e,t);return mr(Ze.join(s,"package.json"))?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=Ze.join(e,r||".");if(!mr(o))return[];try{return qf(o).map(s=>Ze.join(o,s,i)).filter(s=>mr(Ze.join(s,"package.json")))}catch{return[]}}function Jf(e,t){try{let n=JSON.parse(Xa(Ze.join(t,"package.json"),"utf8"));if(!n.name)return[];let r=Ze.relative(e,t).replace(/\\/g,"/");return[{name:n.name,rootRelative:r,sourceRootRelative:`${r}/src`}]}catch{return[]}}function ec(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function tc(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}import{existsSync as pn,readFileSync as zf,readdirSync as Gf,statSync as Kf}from"fs";import J from"path";var wi=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function ki(e,t){let r=t?J.dirname(J.join(e,t)):e,i=J.resolve(e);for(;r.startsWith(i);){for(let s of wi){let a=J.join(r,s);if(pn(a))return a}let o=J.dirname(r);if(o===r)break;r=o}for(let o of wi){let s=J.join(e,o);if(pn(s))return s}return null}function nc(e){let t=e.config.projectRoot,n=new Set(Pi(t,e.config.semantic?.typescript?.tsconfigs)),r=k(e,{includeIgnored:!1,extensions:dn});for(let i of r){let o=ki(t,i);o&&n.add(J.resolve(o))}if(n.size===0){let i=ki(t);i&&n.add(J.resolve(i))}return[...n].filter(i=>!rc(t,i)).sort((i,o)=>i.localeCompare(o))}function Pi(e,t=[]){let n=new Set;for(let r of t){let i=J.isAbsolute(r)?r:J.join(e,r);pn(i)&&n.add(J.resolve(i))}for(let r of Qf(e))for(let i of wi){let o=J.join(r,i);pn(o)&&n.add(J.resolve(o))}if(n.size===0){let r=ki(e);r&&n.add(J.resolve(r))}return[...n].filter(r=>!rc(e,r)).sort((r,i)=>r.localeCompare(i))}function Qf(e){let t=J.join(e,"package.json");if(!pn(t))return[];let n;try{n=JSON.parse(zf(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>Yf(e,i))}function Yf(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=J.join(e,t);return Ei(s)?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=J.join(e,r||".");return Ei(o)?Gf(o).map(s=>J.join(o,s,i)).filter(Ei):[]}function Ei(e){try{return Kf(e).isDirectory()}catch{return!1}}function rc(e,t){let n=J.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}import{createRequire as Xf}from"module";var Zf=Xf(import.meta.url),fn;function ic(){if(fn!==void 0)return fn;try{fn=Zf("ts-morph")}catch{fn=null}return fn}function oc(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!1})}))}function dr(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function cc(e,t){let n=ic();if(!n)return dr("ts-morph is not installed");let r=nc(e);if(r.length===0)return dr("no tsconfig found");try{let i=oc(n,r);return new Ti(e,n,i)}catch(i){return dr(i instanceof Error?i.message:String(i),r[0],r)}}var Ti=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Za(t.config.projectRoot),this.sourceFiles=Ya(t,r)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return Re(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=[];for(let i of n.getImportDeclarations())for(let o of this.importUsageForDeclaration(t,i))r.push(o);return r})}referencesFor(t){return Re(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t),r=this.packageImportReferencesForDefinition(t);return n?qa(n,t,r,this.db.config.projectRoot):r})}calleesFor(t){return Re(this.calleesCache,t.symbolId,()=>Re(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}signatureFor(t){return Re(this.signatureCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);if(!n||!this.tsMorph.Node.isFunctionDeclaration(n)&&!this.tsMorph.Node.isMethodDeclaration(n)&&!this.tsMorph.Node.isArrowFunction(n)&&!this.tsMorph.Node.isFunctionExpression(n)&&!this.tsMorph.Node.isConstructorDeclaration(n))return null;let r=n.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return ac(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${ac(o)}`})}importUsageForDeclaration(t,n){let r=Ie(this.db,t,n.getModuleSpecifierValue()),i=sc(n);return n.getImportClause()?.isTypeOnly()?i.map(o=>eg(t,r,o)):i.map(o=>this.valueImportUsageForEntry(t,r,o))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let l of i)for(let u of Ua(l,t,r.identifier,this.db.config.projectRoot))o.push(u);let s=o.some(l=>!Li(l.node)),a=o.some(l=>Li(l.node)),c=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:c,isUsed:c||o.length>0,isTypeUsed:c||a,isValueUsed:s,references:o.map(l=>l.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let t=new Map,n=this.packageExports();for(let r of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,r);for(let[r,i]of t)t.set(r,lr(i));return this.packageImportReferenceIndex=t,t}addPackageImportReferencesForDocument(t,n,r){if(this.db.isIgnored(r))return;let i=this.sourceFiles.sourceFileMatch(r);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,r,o)}addPackageImportReferencesForDeclaration(t,n,r,i){let o=ec(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of sc(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=za(a.identifier,r,this.db.config.projectRoot);l.length>0&&rg(t,c,l)}}packageExports(){if(this.packageExportIndex)return this.packageExportIndex;let t=new Map;for(let n of this.workspacePackages){let r=new Map;for(let i of tc(n))this.collectPackageExports(n,i,r,new Set);r.size>0&&t.set(n.name,r)}return this.packageExportIndex=t,t}collectPackageExports(t,n,r,i){if(i.has(n))return;i.add(n);let o=this.sourceFiles.sourceFile(n);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?Ie(this.db,n,a):n;if(!c||!c.startsWith(`${t.sourceRootRelative}/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,c,r,i);continue}for(let u of l){let m=u.getNameNode().getText(),d=u.getAliasNode()?.getText()??m,p=this.indexedDefinitionByLeaf(c,m);if(!p)continue;let y=r.get(d);y||(y=new Set,r.set(d,y)),y.add(p.symbolId)}}}indexedDefinitionByLeaf(t,n){return Re(this.indexedDefinitionLeafCache,t,()=>Qa(this.db,t)).get(n)??null}nodeForDefinition(t){return Re(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Re(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?Ga(this.tsMorph,this.db,n,t):new Map})}definitionFromSymbol(t){let n=t.getDeclarations();for(let r of n){let i=r.getSourceFile(),o=mn(this.db.config.projectRoot,i.getFilePath());if(!o||this.db.isIgnored(o))continue;let s=Bt(i,r),a=Ka(this.db,o,s,t.getName());if(a)return{symbol:a.symbol,file:a.relativePath,line:a.startLine}}return null}calleeMapForFile(t){let n=this.sourceFiles.sourceFile(t);if(!n)return new Map;let r=V(this.db,t).sort((o,s)=>o.startLine-s.startLine||s.endLine-o.endLine);if(r.length===0)return new Map;let i=new Map;n.forEachDescendant(o=>{if(!this.tsMorph.Node.isCallExpression(o)&&!this.tsMorph.Node.isNewExpression(o))return;let s=this.semanticCalleeForCallNode(n,r,o);s&&tg(i,s.callerId,s.target)});for(let[o,s]of i)i.set(o,ig(s));return i}semanticCalleeForCallNode(t,n,r){let i=ng(n,Bt(t,r));if(!i)return null;let o=r.getExpression(),s=o.getSymbol()??o.getType().getSymbol(),a=s?this.definitionFromSymbol(s):null;return a?{callerId:i.symbolId,target:{symbol:a.symbol,file:a.file,line:a.line}}:null}};function sc(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let r=e.getNamespaceImport();r&&t.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let i of e.getNamedImports()){let o=i.getNameNode(),a=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);t.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function eg(e,t,n){return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function tg(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function ng(e,t){let n=null;for(let r of e)t<r.startLine||t>r.endLine||(!n||r.startLine>=n.startLine)&&(n=r);return n}function rg(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function ig(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}|${r.line}`;t.has(i)||(t.add(i),n.push(r))}return n}function ac(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Mi=new WeakMap;function Oi(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,r=Mi.get(e);r||(r=new Map,Mi.set(e,r));let i=r.get(n);if(i)return i;let o=cc(e,t);return r.set(n,o),o}function Fi(e){Mi.delete(e)}function gn(e,t){let n=pr(e,t);return n?n.importUsage(t):[]}function hn(e,t){let n=pr(e,t.relativePath);return n?n.referencesFor(t):[]}function Ht(e,t){let n=new Map;for(let r of t)for(let i of hn(e,r)){if(i.file===r.relativePath||e.isIgnored(i.file))continue;let o=n.get(r.symbolId);o||(o=new Set,n.set(r.symbolId,o)),o.add(i.file)}return n}function lc(e,t){let n=new Map;for(let r of t){let i=pr(e,r.relativePath);if(!i)continue;let o=i.calleesFor(r);o.length>0&&n.set(r.symbolId,o)}return n}function uc(e,t){let n=pr(e,t.relativePath);return n?n.signatureFor(t):null}function pr(e,t){if(!ur(t))return null;let n=Oi(e,t);return n.availability().available?n:null}function fr(e,t){let n=new Map;for(let r of Y(e,t)){if(!r.sourcePath)continue;let i=r.localName??r.importedName;if(i&&mc(n,i,r.sourcePath),r.kind==="namespace")for(let o of r.usedMembers)mc(n,o,r.sourcePath)}return n}function mc(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function Wt(e,t,n){let r=yt(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[yn(r[0])];let i=r.filter(c=>c.file===t);if(i.length>0)return i.map(yn);let o=fr(e,t),s=o.get(n);if(s)for(let c of s){let l=r.filter(u=>Xe(c,u.file));if(l.length>0)return l.map(yn)}let a=new Set;for(let c of o.values())for(let l of c)a.add(l);for(let c of a){let l=r.filter(u=>Xe(c,u.file));if(l.length>0&&l.length===r.length)return l.map(yn)}return[]}function pc(e,t,n){let r=Wt(e,t,n);if(r.length>0)return r;let i=yt(e).get(n);return!i||i.length===0?[]:i.map(yn)}function fc(e,t,n={}){let r=Vn(e,t);if(!r)return[];let i=L(r.symbol);if(!i)return[];if(n.semantic!==!1){let s=hn(e,{...r,leaf:i,parentTypeName:null,isFunctionLike:!1,isTypeLike:!1,kind:null,documentation:null,enclosingSymbol:null});if(s.length>0){let a=new Map;for(let c of s){let l=a.get(c.file)??[];l.push(c.line),a.set(c.file,l)}return dc(e,a)}}let o=new Map;for(let s of Ye(e)){let a=T(e,s);if(!a||a.indexOf(i)===-1||s!==r.relativePath&&!Wt(e,s,i).some(u=>u.symbolId===r.symbolId))continue;let c=or(e,s,i,s===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{});c.length>0&&o.set(s,c)}return dc(e,o)}function gc(e,t){let n=new Map;for(let o of t){if(!o.leaf)continue;let s=n.get(o.leaf)??[];s.push(o),n.set(o.leaf,s)}if(n.size===0)return new Map;let r=new Set(t.map(o=>o.symbolId)),i=new Map;for(let o of Ye(e)){let s=Ta(e,o);if(s.size!==0){for(let a of s)if(n.has(a))for(let c of Wt(e,o,a)){if(!r.has(c.symbolId)||o===c.relativePath)continue;let l=i.get(c.symbolId);l||(l=new Set,i.set(c.symbolId,l)),l.add(o)}}}return i}function yn(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function dc(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=V(e,i);for(let a of o){let c=de(s,a),l=`${i}|${a}|${c?.symbol??""}`;r.has(l)||(r.add(l),n.push({file:i,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function Ai(e,t){let n=ug(e,t);return n?mg(e,sg(e,n.match,n.identifier)):[]}function et(e,t,n={}){return og(e,t,n).map(r=>({file:r.file,line:r.line,enclosingSymbol:r.enclosingSymbol}))}function og(e,t,n={}){let r=fc(e,t,{semantic:n.semantic}),i=r.length>0?hc(r,"source-attribution"):hc(Ai(e,t),"scip-reference-chunk");return n.includeIgnored===!0?i:i.filter(o=>!e.isIgnored(o.file))}function hc(e,t){return e.map(n=>({...n,provenance:t}))}function sg(e,t,n){let r=new Map;for(let[i,o]of ag(e,t.symbolId))r.set(i,cg(e,i,o,t,n));return r}function ag(e,t){let n=new Map;for(let r of sr(e,[t])){if(e.isIgnored(r.relative_path))continue;let i=n.get(r.relative_path);i||(i=[],n.set(r.relative_path,i)),i.push({start_line:r.chunk_start,end_line:r.chunk_end})}return n}function cg(e,t,n,r,i){let o=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},s=i?or(e,t,i,o):[];return n.flatMap(a=>lg(s,a))}function lg(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function ug(e,t){let n=Vn(e,t);return n?{match:n,identifier:L(n.symbol)||null}:null}function mg(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=V(e,i);for(let a of o){let c=de(s,a),l=`${i}|${a}|${c?.symbol??""}`;r.has(l)||(r.add(l),n.push({file:i,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function me(e,t,n={}){let r=gr(e,[t],{additive:n.additive,semantic:n.semantic}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>te(o.symbol)):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function ye(e,t,n={}){let r=pg(e)?gg(e,t,{semantic:n.semantic!==!1}):fg(e).get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}var yc=We("caller-rows"),dg=2e4;function pg(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>dg}function fg(e){return yc.get(e,()=>{let t=Le(e),n=gr(e,t),r=new Map;for(let s of t)r.set(s.symbol,s.symbolId);let i=new Map,o=new Map;for(let s of t){let a=n.get(s.symbolId);if(!(!a||a.length===0))for(let c of a){let l=r.get(c.symbol);if(l===void 0||l===s.symbolId)continue;let u=i.get(l);u||(u=[],i.set(l,u),o.set(l,new Set));let m=`${s.symbol}|${s.relativePath}`;o.get(l).has(m)||(o.get(l).add(m),u.push({symbol:s.symbol,file:s.relativePath,source:"caller-map-inversion"}))}}return i})}function gg(e,t,n){let r=[],i=new Set,o=a=>{if(a.symbol===t.symbol)return;let c=`${a.symbol}|${a.file}`;i.has(c)||(i.add(c),r.push(a))};for(let a of Ai(e,t))a.file!==t.relativePath&&o({symbol:a.enclosingSymbol??a.file,file:a.file,source:"resolved-reference"});let s=n.semantic?hg(e,t):null;if(s)for(let a of hn(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let c=de(V(e,a.file),a.line);o({symbol:c?.symbol??a.file,file:a.file,source:"semantic-reference"})}return r}function hg(e,t){return e.get(`SELECT
465
232
  d.id AS documentId,
466
233
  gs.id AS symbolId,
467
234
  gs.symbol,
@@ -480,31 +247,10 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
480
247
  LEFT JOIN chunks c ON c.document_id = der.document_id
481
248
  JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
482
249
  WHERE gs.id = ?
483
- LIMIT 1`,t.symbolId)??null}function Ne(e,t){let n=Ph(e,t);return n?Mh(e,Dh(e,n.match,n.identifier)):[]}function Dh(e,t,n){let r=new Map;for(let[i,s]of Lh(e,t.symbolId))r.set(i,wh(e,i,s,t,n));return r}function Lh(e,t){let n=new Map,r=e.all(`SELECT DISTINCT d.relative_path, c.start_line, c.end_line
250
+ LIMIT 1`,t.symbolId)??null}function gr(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let u of t)P(u.relativePath)&&Nt(e,u.relativePath)!==null?i.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[m,d]of u){let p=s.get(m);p||(p=[],s.set(m,p));let y=a.get(m);y||(y=new Set,a.set(m,y));for(let f of d){let b=`${f.symbol}|${f.chunkId}`;y.has(b)||(y.add(b),p.push(f))}}};i.length>0&&c(yg(e,i)),n.semantic!==!1&&c(Ig(lc(e,t)));let l=r?t:o;return l.length>0&&c(Cg(e,l)),s}function yg(e,t){let n=new Map,r=bg(t,n),i=yt(e);for(let[o,s]of r){let a=Nt(e,o);if(a)for(let c of a){let l=Sg(s,c.line);if(!l)continue;let u=xg(e,o,i,c.calleeLeaf,c.memberAccess);u&&u.symbol!==l.symbol&&n.get(l.symbolId).push({symbol:u.symbol,file:u.file,chunkId:c.line,source:"ast-callsite"})}}return n}function bg(e,t){let n=new Map;for(let r of e){let i=n.get(r.relativePath);i?i.push(r):n.set(r.relativePath,[r]),t.set(r.symbolId,[])}for(let r of n.values())r.sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine));return n}function Sg(e,t){return e.find(n=>t>=n.startLine&&t<=n.endLine)??null}function xg(e,t,n,r,i){let o=ar(t,n.get(r)??[]);return o.length===0?null:cr(e,t,o,i)}function Cg(e,t){if(t.length===0)return new Map;let n=e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
484
251
  FROM mentions m
485
252
  JOIN chunks c ON m.chunk_id = c.id
486
- JOIN documents d ON c.document_id = d.id
487
- WHERE m.symbol_id = ?
488
- AND m.role != 1
489
- ${e.pathExclusionsFor("d")}
490
- ORDER BY d.relative_path, c.start_line`,t);for(let i of r){if(e.isIgnored(i.relative_path))continue;let s=n.get(i.relative_path);s||(s=[],n.set(i.relative_path,s)),s.push({start_line:i.start_line,end_line:i.end_line})}return n}function wh(e,t,n,r,i){let s=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},o=i?yn(e,t,i,s):[];return n.flatMap(a=>kh(o,a))}function kh(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function Ph(e,t){let n=mn(e,t);return n?{match:n,identifier:k(n.symbol)||null}:null}function Mh(e,t){let n=[],r=new Set;for(let[i,s]of t){let o=J(e,i);for(let a of s){let l=le(o,a),c=`${i}|${a}|${l?.symbol??""}`;r.has(c)||(r.add(c),n.push({file:i,line:a,enclosingSymbol:l?.symbol??null}))}}return n}function En(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],s=[];for(let u of t)F(u.relativePath)&&ln(e,u.relativePath)!==null?i.push(u):s.push(u);let o=new Map,a=new Map,l=u=>{for(let[d,m]of u){let f=o.get(d);f||(f=[],o.set(d,f));let h=a.get(d);h||(h=new Set,a.set(d,h));for(let p of m){let g=`${p.symbol}|${p.chunkId}`;h.has(g)||(h.add(g),f.push(p))}}};i.length>0&&l(Oh(e,i)),n.semantic!==!1&&l(zh(Wo(e,t)));let c=r?t:s;return c.length>0&&l(jh(e,c)),o}function Oh(e,t){let n=new Map,r=Th(t,n),i=kt(e);for(let[s,o]of r){let a=ln(e,s);if(a)for(let l of a){let c=Fh(o,l.line);if(!c)continue;let u=Ah(e,s,i,l.calleeLeaf,l.memberAccess);u&&u.symbol!==c.symbol&&n.get(c.symbolId).push({symbol:u.symbol,file:u.file,chunkId:l.line})}}return n}function Th(e,t){let n=new Map;for(let r of e){let i=n.get(r.relativePath);i?i.push(r):n.set(r.relativePath,[r]),t.set(r.symbolId,[])}for(let r of n.values())r.sort((i,s)=>i.endLine-i.startLine-(s.endLine-s.startLine));return n}function Fh(e,t){return e.find(n=>t>=n.startLine&&t<=n.endLine)??null}function Ah(e,t,n,r,i){let s=Yo(t,n.get(r)??[]);return s.length===0?null:Qo(e,t,s,i)}function Yo(e,t){let n=Vo(e);return n?t.filter(r=>Vo(r.file)===n):t}function Qo(e,t,n,r){let i=n.find(s=>s.file===t);if(i)return i;if(r){let s=new Set(q(e,t).map(o=>o.sourcePath).filter(o=>!!o));for(let o of n)for(let a of s)if($h(a,o.file))return o;return null}return n.length===1?n[0]:null}function $h(e,t){let n=r=>r.replace(/\\/g,"/").replace(/^\.\//,"");return n(e)===n(t)}function Vo(e){let t=F(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var Xo=Ue("global-leaf-index");function kt(e){return Xo.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
491
- COALESCE(der_doc.relative_path, mention_doc.relative_path) AS relative_path
492
- FROM global_symbols gs
493
- LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
494
- LEFT JOIN documents der_doc ON der_doc.id = der.document_id
495
- LEFT JOIN (
496
- SELECT m.symbol_id, MIN(d.relative_path) AS relative_path
497
- FROM mentions m
498
- JOIN chunks c ON m.chunk_id = c.id
499
- JOIN documents d ON c.document_id = d.id
500
- WHERE m.role = 1
501
- GROUP BY m.symbol_id
502
- ) mention_doc ON mention_doc.symbol_id = gs.id
503
- WHERE 1 = 1
504
- ${e.symbolNoiseFor("gs")}`),n=new Map;for(let r of t){if(!r.relative_path||e.isIgnored(r.relative_path))continue;let i=k(r.symbol);if(!i)continue;let s=n.get(i);s||(s=[],n.set(i,s)),s.some(o=>o.symbolId===r.id)||s.push({symbol:r.symbol,symbolId:r.id,file:r.relative_path})}return n})}function jh(e,t){if(t.length===0)return new Map;let n=e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
505
- FROM mentions m
506
- JOIN chunks c ON m.chunk_id = c.id
507
- WHERE m.role != 1`),r=new Map;for(let c of n)r.has(c.document_id)||r.set(c.document_id,[]),r.get(c.document_id).push(c);let i=new Map(e.all("SELECT id, relative_path FROM documents").map(c=>[c.id,c.relative_path])),s=new Map,o=e.all(`SELECT gs.id AS symbol_id, gs.symbol,
253
+ WHERE m.role != 1`),r=new Map;for(let l of n)r.has(l.document_id)||r.set(l.document_id,[]),r.get(l.document_id).push(l);let i=new Map(e.all("SELECT id, relative_path FROM documents").map(l=>[l.id,l.relative_path])),o=new Map,s=e.all(`SELECT gs.id AS symbol_id, gs.symbol,
508
254
  COALESCE(der.document_id, def_chunk.document_id) AS document_id
509
255
  FROM global_symbols gs
510
256
  LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
@@ -514,22 +260,10 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
514
260
  JOIN chunks c ON m.chunk_id = c.id
515
261
  WHERE m.role = 1
516
262
  GROUP BY m.symbol_id
517
- ) def_chunk ON def_chunk.symbol_id = gs.id`);for(let c of o)s.has(c.symbol_id)||s.set(c.symbol_id,{symbol:c.symbol,file:c.document_id!==null?i.get(c.document_id)??"":""});let a=new Map,l=i;for(let c of t){let u=r.get(c.documentId)??[],d=new Set,m=[],f=null,h=()=>{if(f)return f;let p=l.get(c.documentId)??"",g=new Set;if(p){let b=eo(e,p),_=Math.max(0,c.startLine),P=Math.min(b.length-1,c.endLine);for(let L=_;L<=P;L+=1)for(let C of b[L])g.add(C)}return f=g,g};for(let p of u){if(p.symbol_id===c.symbolId)continue;let g=s.get(p.symbol_id);if(!g)continue;if(!(p.start_line>=c.startLine&&p.end_line<=c.endLine)){if(!(p.start_line<=c.endLine&&p.end_line>=c.startLine))continue;let L=k(g.symbol);if(!L||!h().has(L))continue}let _=`${g.symbol}|${p.chunk_id}`;d.has(_)||(d.add(_),m.push({...g,chunkId:p.chunk_id}))}a.set(c.symbolId,m)}return a}function Zo(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=e.all(`SELECT relative_path FROM documents
518
- WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`),s=kt(e),o=t??_e(e),a=new Set(o.map(l=>l.symbolId));return Bh(e,r,i,s,a),Hh(e,r,o,a),Jh(e,r,i,s,a),n.semantic!==!1&&Gh(r,pt(e,qh(o))),r}function Bh(e,t,n,r,i){for(let s of n){if(!F(s.relative_path)||e.isIgnored(s.relative_path))continue;let o=ln(e,s.relative_path);if(o)for(let a of o){let l=Yo(s.relative_path,r.get(a.calleeLeaf)??[]);if(!l||l.length===0)continue;let c=Qo(e,s.relative_path,l,a.memberAccess);c&&i.has(c.symbolId)&&c.file!==s.relative_path&&zr(t,c.symbolId,s.relative_path)}}}function Hh(e,t,n,r){let i=Uh(n);for(let s of Wh(e,r))e.isIgnored(s.relative_path)||Vh(s,i.get(s.symbol_id))||zr(t,s.symbol_id,s.relative_path)}function Wh(e,t){if(!t)return qo(e);let n=[...t];if(n.length===0)return[];let r=[];for(let i=0;i<n.length;i+=Jo)r.push(...qo(e,n.slice(i,i+Jo)));return r}var Jo=750;function qo(e,t){let n=t&&t.length>0?`AND m.symbol_id IN (${t.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path, c.document_id,
519
- c.start_line AS chunk_start, c.end_line AS chunk_end
520
- FROM mentions m
521
- JOIN chunks c ON m.chunk_id = c.id
522
- JOIN documents d ON c.document_id = d.id
523
- WHERE m.role != 1
524
- ${n}
525
- ${e.pathExclusionsFor("d")}`,...t??[])}function Uh(e){let t=new Map;for(let n of e)t.set(n.symbolId,{docId:n.documentId,startLine:n.startLine,endLine:n.endLine});return t}function Vh(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function Jh(e,t,n,r,i){for(let s of n){if(e.isIgnored(s.relative_path)||F(s.relative_path)!=="rust")continue;let o=Fe(e,s.relative_path);if(o.size!==0)for(let a of o){let l=r.get(a);if(l)for(let c of l)i.has(c.symbolId)&&c.file!==s.relative_path&&zr(t,c.symbolId,s.relative_path)}}}function zr(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function qh(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function zh(e){let t=new Map;for(let[n,r]of e){let i=[];for(let s of r)i.push({symbol:s.symbol,file:s.file,chunkId:-1});t.set(n,i)}return t}function Gh(e,t){for(let[n,r]of t){let i=e.get(n);i||(i=new Set,e.set(n,i));for(let s of r)i.add(s)}}function ne(e){let t=Pt(e);return Yh(t)?"test":Qh(t)?"worker":Xh(t)?"entry":Zh(t)?"barrel":"source"}function Dn(e){return ne(e)==="barrel"}function ta(e){return Kh.get(e,()=>{let t=Z(e),n=ke(e).filter(s=>{let o=ne(s);return o==="entry"||o==="worker"}),r=new Set,i=new Set;for(;n.length>0;){let s=n.shift();if(!r.has(s)){r.add(s),ne(s)==="barrel"&&i.add(s);for(let o of t.get(s)??[])r.has(o)||n.push(o)}}return i})}var Kh=Ue("live-barrels");function Gr(e,t){return ta(e).has(Pt(t))}function na(e){let t=ta(e);return ke(e).filter(n=>Dn(n)&&!t.has(n))}function Xe(e,t){let n=ne(t);return n==="entry"||n==="worker"||Gr(e,t)}function Mt(e,t,n){let r=e.config.entryRoots;if(!r)return!1;let i=Pt(n);return!!(r.files?.some(s=>Pt(s)===i)||r.pathPrefixes?.some(s=>i.startsWith(Pt(s)))||r.qualifiedVars?.some(s=>ey(t,s))||r.symbolPatterns?.some(s=>{try{return new RegExp(s).test(t)}catch{return!1}}))}var ra=["%/__tests__/%","%.test.%","%.spec.%","%/test/%","%/tests/%","%_test.%","%_spec.%","%/test_%.%","%/spec_%.%"],ia=["%/test-utils/%"];function Yh(e){return!!(/\.(?:test|spec)\.[a-z0-9]+$/i.test(e)||/(?:^|\/)(?:_)?test_[^/]+$/i.test(e)||/(?:^|\/)spec_[^/]+$/i.test(e)||/(?:^|\/)[^/]+_test\.[a-z0-9]+$/i.test(e)||/(?:^|\/)[^/]+_tests\.rs$/i.test(e)||/(?:^|\/)tests\.rs$/i.test(e)||/(?:^|\/)[^/]+_spec\.[a-z0-9]+$/i.test(e)||/(?:^|\/)__tests__\//i.test(e)||/(?:^|\/)test\//i.test(e)||/(?:^|\/)tests\//i.test(e)||/(?:^|\/)__fixtures__\//i.test(e)||/(?:^|\/)__mocks__\//i.test(e)||/(?:^|\/)test-support\//i.test(e)||/(?:^|\/)test-utils\//i.test(e)||/(?:^|\/)testing\//i.test(e))}function Qh(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function Xh(e){let t=e.split("/"),n=t[t.length-1]??e;return n==="cli.ts"||n==="cli.js"||n==="postinstall.ts"||n==="postinstall.js"||n==="main.ts"||n==="main.js"||n==="main.rs"||n==="main.go"||n==="main.py"||n==="build.rs"||n==="lib.rs"||/\bsrc\/bin\/[^/]+\.rs$/.test(e)||/(?:^|\/)examples\/[^/]+\.rs$/.test(e)||/(?:^|\/)tests\/[^/]+\.rs$/.test(e)||/(?:^|\/)benches\/[^/]+\.rs$/.test(e)?!0:n==="index.ts"||n==="index.js"?/(?:^|\/)(?:apps|services)\/[^/]+\/src\/index\.(?:ts|js)$/.test(e)?!0:t.length<=2:!1}function Zh(e){return e==="index.ts"||e==="index.js"||e.endsWith("/index.ts")||e.endsWith("/index.js")||e.endsWith("/mod.rs")||e.endsWith("/__init__.py")}function Pt(e){return e.replace(/\\/g,"/")}function ey(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let r=t.slice(0,n),i=t.slice(n+1);return e.includes(ea(r)+"/")&&e.includes(ea(i)+".")}function ea(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function gt(e,t,n){let r=kt(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[Ot(r[0])];let i=r.filter(l=>l.file===t);if(i.length>0)return i.map(Ot);let s=ty(e,t),o=s.get(n);if(o)for(let l of o){let c=r.filter(u=>sa(l,u.file));if(c.length>0)return c.map(Ot)}let a=new Set;for(let l of s.values())for(let c of l)a.add(c);for(let l of a){let c=r.filter(u=>sa(l,u.file));if(c.length>0&&c.length===r.length)return c.map(Ot)}return[]}function aa(e,t,n){let r=gt(e,t,n);if(r.length>0)return r;let i=kt(e).get(n);return!i||i.length===0?[]:i.map(Ot)}function He(e,t,n={}){let r=mn(e,t);if(!r)return[];let i=k(r.symbol);if(!i)return[];if(n.semantic!==!1){let o=wt(e,{...r,leaf:i,parentTypeName:null,isFunctionLike:!1,isTypeLike:!1,kind:null,documentation:null,enclosingSymbol:null});if(o.length>0){let a=new Map;for(let l of o){let c=a.get(l.file)??[];c.push(l.line),a.set(l.file,c)}return oa(e,a)}}let s=new Map;for(let o of ke(e)){let a=M(e,o);if(!a||a.indexOf(i)===-1||o!==r.relativePath&&!gt(e,o,i).some(u=>u.symbolId===r.symbolId))continue;let l=yn(e,o,i,o===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{});l.length>0&&s.set(o,l)}return oa(e,s)}function la(e,t){let n=new Map;for(let s of t){if(!s.leaf)continue;let o=n.get(s.leaf)??[];o.push(s),n.set(s.leaf,o)}if(n.size===0)return new Map;let r=new Set(t.map(s=>s.symbolId)),i=new Map;for(let s of ke(e)){let o=Zs(e,s);if(o.size!==0){for(let a of o)if(n.has(a))for(let l of gt(e,s,a)){if(!r.has(l.symbolId)||s===l.relativePath)continue;let c=i.get(l.symbolId);c||(c=new Set,i.set(l.symbolId,c)),c.add(s)}}}return i}function ty(e,t){let n=new Map;for(let r of q(e,t)){if(!r.sourcePath)continue;let i=r.localName??r.importedName;if(i){let s=n.get(i);s||(s=new Set,n.set(i,s)),s.add(r.sourcePath)}if(r.kind==="namespace")for(let s of r.usedMembers){let o=n.get(s);o||(o=new Set,n.set(s,o)),o.add(r.sourcePath)}}return n}function sa(e,t){let n=r=>r.replace(/\\/g,"/").replace(/^\.\//,"");return n(e)===n(t)}function Ot(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function oa(e,t){let n=[],r=new Set;for(let[i,s]of t){let o=J(e,i);for(let a of s){let l=le(o,a),c=`${i}|${a}|${l?.symbol??""}`;r.has(c)||(r.add(c),n.push({file:i,line:a,enclosingSymbol:l?.symbol??null}))}}return n}function ca(e,t,n){let r=t.identifierResolution==="strict"?gt:aa;for(let i of t.paths){let s=F(i);if(!s&&!(t.includeVueSfc&&ze(i))||e.isIgnored(i)||t.skipPath?.(i))continue;let o=Ie(e,i);for(let[a,l]of o)if(!(t.candidateNames&&!t.candidateNames.has(a)))for(let c of r(e,i,a))n({sourceFile:i,name:a,target:c,occurrences:l.length,kind:"identifier"});if(t.includeCrossLanguageDispatchNames){for(let a of fn(e,i))if(!(t.candidateNames&&!t.candidateNames.has(a)))for(let l of gt(e,i,a))n({sourceFile:i,name:a,target:l,occurrences:1,kind:"cross-language-dispatch"})}if(t.includeRustAttributeNames&&s==="rust"){for(let a of Fe(e,i))if(!(t.candidateNames&&!t.candidateNames.has(a)))for(let l of r(e,i,a))n({sourceFile:i,name:a,target:l,occurrences:1,kind:"rust-attribute"})}}}var N=class{constructor(t){this.db=t}db;scopedDefinitions(t){return xr(this.db,t)}definitionsForFile(t){return J(this.db,t)}productionCallableDefinitions(t={}){let{scope:n,minLoc:r=1,maxLoc:i=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:o=!1,excludeTypesFiles:a=!1,requireFunctionLikeSymbol:l=!1,requireCallableSymbol:c=!1,excludeRustTraitImplMembers:u=!1,includeSuppressed:d=!1,sortByLocDesc:m=!1}=t,f=[];for(let h of this.scopedDefinitions(n)){let p=h.relativePath;if(this.db.isIgnored(p)||o&&Xe(this.db,p)||!ny(h,{requireFunctionLikeSymbol:l,requireCallableSymbol:c})||s!==void 0&&h.symbol===s)continue;let g=Kr(h);g<r||g>i||a&&ry(p)||u&&un(h.symbol)||ne(p)!=="test"&&(Oe(h.symbol)||!d&&br(this.db,p,h.startLine)||f.push(h))}return m?f.sort((h,p)=>Kr(p)-Kr(h)):f}calleeMap(t,n={}){return En(this.db,t,n)}crossFileCallerMap(t,n={}){return Zo(this.db,t,n)}sourceFallbackCallerFiles(t){return la(this.db,t)}fileDependencyGraph(t){return Z(this.db,t)}fileKind(t){return ne(t)}hasSuppressionComment(t){return br(this.db,t.relativePath,t.startLine)}sourceFiles(){return ke(this.db)}scanSourceReferences(t,n){ca(this.db,t,n)}callableSignature(t){return ws(this.db,t.relativePath,t.startLine,t.endLine)}};function Kr(e){return e.endLine-e.startLine+1}function ny(e,t){return t.requireCallableSymbol?G(e.symbol):t.requireFunctionLikeSymbol?U(e.symbol):e.isFunctionLike}function ry(e){return(e.split("/").pop()??"").includes("types")}function ua(e,t){let n=w(e,t);if(!n)return[];let r=k(n.symbol),s=new N(e).definitionsForFile(n.relativePath).filter(l=>G(l.symbol)),o=s.filter(l=>l.parentTypeName===r||l.symbol.includes(r));return(o.length>0?o:sy(iy(n.relativePath))===r?s.filter(l=>l.symbol.includes("<invalid-global-code>")):[]).map(l=>({startLine:l.startLine,endLine:l.endLine,name:k(l.symbol)}))}function sy(e){return e.replace(/\.[^.]+$/,"")}function da(e,t,n={}){let r=w(e,t);if(!r)return[];let s=!U(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],o=He(e,r,{semantic:n.semantic}),a=(o.length>0?o:Ne(e,r)).filter(d=>!e.isIgnored(d.file)).map(d=>({relativePath:d.file,line:d.line})),l=oy(e,r),c=new Set,u=[];for(let d of[...s,...a,...l]){let m=`${d.relativePath}:${d.line}`;c.has(m)||(c.add(m),u.push(d))}return u}function oy(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=ay(t.symbol);if(n.length===0)return[];let r=e.all(`SELECT relative_path
526
- FROM documents
527
- WHERE relative_path LIKE '%.rb'
528
- ${e.pathExclusionsFor("documents")}
529
- ORDER BY relative_path`),i=[];for(let s of r){if(e.isIgnored(s.relative_path))continue;let o=M(e,s.relative_path);if(!o)continue;let a=o.split(`
530
- `);for(let l=0;l<a.length;l++){let c=a[l]??"";n.some(u=>new RegExp(`@${u}\\b|\\b${u}:`).test(c))&&i.push({relativePath:s.relative_path,line:l})}}return i}function ay(e){let n=(e.split(":").pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),r=n.split("_").filter(Boolean),i=new Set;return n&&i.add(n),r.length>=1&&i.add(r[r.length-1]),r.length>=2&&i.add(r.slice(-2).join("_")),[...i]}function ma(e,t,n={}){let r=w(e,t);if(!r)return{definitions:[],referencedBy:[]};let i=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",r.symbolId),s=Ke(i?.documentation??null),o=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:cy(s,i?.display_name??null,r.symbol),source:ly(e,r.relativePath,r.startLine,r.endLine)}],a=He(e,r,{semantic:n.semantic}),c=(a.length>0?a:Ne(e,r)).filter(u=>!e.isIgnored(u.file)).map(u=>({relativePath:u.file,line:u.line,enclosingSymbol:u.enclosingSymbol,enclosingShort:u.enclosingSymbol?y(u.enclosingSymbol):"(top-level)"}));return{definitions:o,referencedBy:c}}function ly(e,t,n,r){let i=M(e,t);if(!i)return null;let o=i.split(`
263
+ ) def_chunk ON def_chunk.symbol_id = gs.id`);for(let l of s)o.has(l.symbol_id)||o.set(l.symbol_id,{symbol:l.symbol,file:l.document_id!==null?i.get(l.document_id)??"":""});let a=new Map,c=i;for(let l of t){let u=r.get(l.documentId)??[],m=new Set,d=[],p=null,y=()=>{if(p)return p;let f=c.get(l.documentId)??"",b=new Set;if(f){let E=Ma(e,f),x=Math.max(0,l.startLine),$=Math.min(E.length-1,l.endLine);for(let F=x;F<=$;F+=1)for(let R of E[F])b.add(R)}return p=b,b};for(let f of u){if(f.symbol_id===l.symbolId)continue;let b=o.get(f.symbol_id);if(!b)continue;if(!(f.start_line>=l.startLine&&f.end_line<=l.endLine)){if(!(f.start_line<=l.endLine&&f.end_line>=l.startLine))continue;let F=L(b.symbol);if(!F||!y().has(F))continue}let x=`${b.symbol}|${f.chunk_id}`;m.has(x)||(m.add(x),d.push({...b,chunkId:f.chunk_id,source:"scip-chunk"}))}a.set(l.symbolId,d)}return a}function Ig(e){let t=new Map;for(let[n,r]of e){let i=[];for(let o of r)i.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee"});t.set(n,i)}return t}function bc(e){yc.invalidate(e)}function Sc(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=k(e,{includeIgnored:!1}),o=yt(e),s=t??Le(e),a=new Set(s.map(c=>c.symbolId));return Rg(e,r,i,o,a),_g(e,r,s,a),Lg(e,r,i,o,a),n.semantic!==!1&&wg(r,Ht(e,Eg(s))),r}function Rg(e,t,n,r,i){for(let o of n){if(!P(o))continue;let s=Nt(e,o);if(s)for(let a of s){let c=ar(o,r.get(a.calleeLeaf)??[]);if(!c||c.length===0)continue;let l=cr(e,o,c,a.memberAccess);l&&i.has(l.symbolId)&&l.file!==o&&$i(t,l.symbolId,o)}}}function _g(e,t,n,r){let i=Dg(n);for(let o of vg(e,r))e.isIgnored(o.relative_path)||Ng(o,i.get(o.symbol_id))||$i(t,o.symbol_id,o.relative_path)}function vg(e,t){return sr(e,t?[...t]:void 0)}function Dg(e){let t=new Map;for(let n of e)t.set(n.symbolId,{docId:n.documentId,startLine:n.startLine,endLine:n.endLine});return t}function Ng(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function Lg(e,t,n,r,i){for(let o of n){if(P(o)!=="rust")continue;let s=jt(e,o);if(s.size!==0)for(let a of s){let c=r.get(a);if(c)for(let l of c)i.has(l.symbolId)&&l.file!==o&&$i(t,l.symbolId,o)}}}function $i(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function Eg(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function wg(e,t){for(let[n,r]of t){let i=e.get(n);i||(i=new Set,e.set(n,i));for(let o of r)i.add(o)}}var xc=new WeakMap;function Cc(e,t,n,r){let i=P(t);if(!i)return null;let o=B(e,t);if(!o)return null;let s=xc.get(o);return s||(s=kg(o,i),xc.set(o,s)),s.get(`${n}:${r}`)??null}function kg(e,t){let n=en(t),r=new Map,i=o=>{if(n.has(o.type)){let s=o.namedChildren.find(c=>c.type==="parameters"||c.type==="formal_parameters"),a=0;if(s)for(let c of s.namedChildren)c.type==="comment"||c.type==="line_comment"||c.type==="block_comment"||(a+=1);r.set(`${o.startPosition.row}:${o.endPosition.row}`,{paramCount:a})}for(let s of o.children)i(s)};return i(e.rootNode),r}function Ic(e,t,n){let r=t.identifierResolution==="strict"?Wt:pc;for(let i of t.paths){let o=P(i);if(!(!o&&!(t.includeVueSfc&&st(i)))&&!e.isIgnored(i)&&!t.skipPath?.(i))try{let s=(c,l,u,m)=>{if(t.candidateNames&&!t.candidateNames.has(c))return;let d=t.resolveTargets?t.resolveTargets({sourceFile:i,name:c,kind:l,defaultTargets:m}):m();for(let p of d)n({sourceFile:i,name:c,target:p,occurrences:u,kind:l})},a=ht(e,i);for(let[c,l]of a)s(c,"identifier",l.length,()=>r(e,i,c));if(t.includeCrossLanguageDispatchNames)for(let c of ka(e,i))s(c,"cross-language-dispatch",1,()=>Wt(e,i,c));if(t.includeRustAttributeNames&&o==="rust")for(let c of jt(e,i))s(c,"rust-attribute",1,()=>r(e,i,c))}finally{t.afterPath?.(i)}}}var v=class{constructor(t){this.db=t}db;scopedDefinitions(t){return ri(this.db,t)}definitionsForFile(t){return V(this.db,t)}productionCallableDefinitions(t={}){let{scope:n,minLoc:r=1,maxLoc:i=Number.POSITIVE_INFINITY,excludeSymbol:o,excludeEntrySurfaces:s=!1,excludeTypesFiles:a=!1,requireFunctionLikeSymbol:c=!1,requireCallableSymbol:l=!1,excludeRustTraitImplMembers:u=!1,includeSuppressed:m=!1,sortByLocDesc:d=!1}=t,p=[];for(let y of this.scopedDefinitions(n)){let f=y.relativePath;if(this.db.isIgnored(f)||s&&gt(this.db,f)||!Pg(y,{requireFunctionLikeSymbol:c,requireCallableSymbol:l})||o!==void 0&&y.symbol===o)continue;let b=ji(y);b<r||b>i||a&&Tg(f)||u&&Bn(y.symbol)||ue(f)!=="test"&&(qe(y.symbol)||!m&&Yr(this.db,f,y.startLine)||p.push(y))}return d?p.sort((y,f)=>ji(f)-ji(y)):p}calleeMap(t,n={}){return gr(this.db,t,n)}crossFileCallerMap(t,n={}){return Sc(this.db,t,n)}sourceFallbackCallerFiles(t){return gc(this.db,t)}callerFileMap(t,n={}){let r=this.crossFileCallerMap(t,{semantic:n.semantic});return n.sourceFallback===!1?r:Mg(r,this.sourceFallbackCallerFiles(t))}frameworkReferencedSymbolIds(t){let n=new Map;for(let i of t){if(!i.leaf)continue;let o=n.get(i.leaf)??[];o.push(i.symbolId),n.set(i.leaf,o)}let r=new Set;for(let i of k(this.db,{includeIgnored:!1}))if(P(i)==="rust")for(let o of jt(this.db,i))for(let s of n.get(o)??[])r.add(s);return r}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let r=new Map(t.map(o=>[o.symbolId,o.symbol])),i=this.calleeMap(t,n);return new Set([...i.entries()].filter(([o,s])=>{let a=r.get(o);return s.some(c=>c.symbol!==a)}).map(([o])=>o))}fileDependencyGraph(t){return ae(this.db,t)}fileKind(t){return ue(t)}hasSuppressionComment(t){return Yr(this.db,t.relativePath,t.startLine)}sourceFiles(){return Ye(this.db)}scanSourceReferences(t,n){Ic(this.db,t,n)}callableSignature(t){return Cc(this.db,t.relativePath,t.startLine,t.endLine)}};function Pg(e,t){return t.requireCallableSymbol?te(e.symbol):t.requireFunctionLikeSymbol?K(e.symbol):e.isFunctionLike}function ji(e){return e.endLine-e.startLine+1}function Tg(e){return(e.split("/").pop()??"").includes("types")}function Mg(e,t){let n=new Map;for(let[r,i]of e)n.set(r,new Set(i));for(let[r,i]of t){let o=n.get(r)??new Set;for(let s of i)o.add(s);n.set(r,o)}return n}function Bi(e,t){let n=w(e,t);if(!n)return[];let r=L(n.symbol),o=new v(e).definitionsForFile(n.relativePath).filter(c=>te(c.symbol)),s=o.filter(c=>c.parentTypeName===r||c.symbol.includes(r));return(s.length>0?s:Fg(Og(n.relativePath))===r?o.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:L(c.symbol)}))}function Fg(e){return e.replace(/\.[^.]+$/,"")}function Hi(e,t,n={}){let r=w(e,t);if(!r)return[];let o=!K(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=et(e,r,{semantic:n.semantic}).map(u=>({relativePath:u.file,line:u.line})),a=Ag(e,r),c=new Set,l=[];for(let u of[...o,...s,...a]){let m=`${u.relativePath}:${u.line}`;c.has(m)||(c.add(m),l.push(u))}return l}function Ag(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=$g(t.symbol);if(n.length===0)return[];let r=[];for(let i of k(e,{extensions:[".rb"],includeIgnored:!1})){let o=T(e,i);if(!o)continue;let s=o.split(`
264
+ `);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&r.push({relativePath:i,line:a})}}return r}function $g(e){let n=(e.split(":").pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),r=n.split("_").filter(Boolean),i=new Set;return n&&i.add(n),r.length>=1&&i.add(r[r.length-1]),r.length>=2&&i.add(r.slice(-2).join("_")),[...i]}function Wi(e,t,n={}){let r=w(e,t);if(!r)return{definitions:[],referencedBy:[]};let i=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",r.symbolId),o=ct(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:Bg(o,i?.display_name??null,r.symbol),source:jg(e,r.relativePath,r.startLine,r.endLine)}],a=et(e,r,{semantic:n.semantic}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?h(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function jg(e,t,n,r){let i=T(e,t);if(!i)return null;let s=i.split(`
531
265
  `).slice(n,r+1).join(`
532
- `).trimEnd();return o.length>0?o:null}function cy(e,t,n){let r=Ge(e);if(r&&!uy(r))return r;let i=(t??"").trim();return i?U(n)&&!i.endsWith("()")?`${i}()`:i:y(n)}function uy(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function fa(e,t){let n=Q(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
266
+ `).trimEnd();return s.length>0?s:null}function Bg(e,t,n){let r=at(e);if(r&&!Hg(r))return r;let i=(t??"").trim();return i?K(n)&&!i.endsWith("()")?`${i}()`:i:h(n)}function Hg(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Vi(e,t){let n=ie(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
533
267
  FROM mentions m
534
268
  JOIN chunks c ON m.chunk_id = c.id
535
269
  JOIN documents d1 ON c.document_id = d1.id
@@ -545,7 +279,7 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
545
279
  WHERE d1.relative_path = ?
546
280
  AND d2.relative_path <> d1.relative_path
547
281
  AND ${e.localSymbolPredicate}
548
- ORDER BY d2.relative_path`,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function pa(e,t){let n=Q(e,t);return n?e.all(`SELECT DISTINCT d1.relative_path
282
+ ORDER BY d2.relative_path`,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function qi(e,t){let n=ie(e,t);return n?e.all(`SELECT DISTINCT d1.relative_path
549
283
  FROM mentions m
550
284
  JOIN chunks c ON m.chunk_id = c.id
551
285
  JOIN documents d1 ON c.document_id = d1.id
@@ -560,9 +294,9 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
560
294
  JOIN documents d2 ON sym_def.document_id = d2.id
561
295
  WHERE d2.relative_path = ?
562
296
  AND d1.relative_path != ?
563
- ORDER BY d1.relative_path`,n,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function ga(e,t){let n=Te(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.map(()=>"?").join(", "),s=e.all(`SELECT relative_path FROM documents
297
+ ORDER BY d1.relative_path`,n,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function Ui(e,t){let n=Ue(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
564
298
  WHERE relative_path IN (${r})
565
- ORDER BY relative_path`,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),o=at(e,s,{onlyDocumented:!0,sort:!0}).map(({relativePath:d,...m})=>m),l=e.all(`SELECT DISTINCT d2.relative_path
299
+ ORDER BY relative_path`,...n).map(m=>m.relative_path).filter(m=>!e.isIgnored(m)),s=kt(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:m,...d})=>d),c=e.all(`SELECT DISTINCT d2.relative_path
566
300
  FROM mentions m
567
301
  JOIN chunks c ON m.chunk_id = c.id
568
302
  JOIN documents d1 ON c.document_id = d1.id
@@ -578,7 +312,7 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
578
312
  WHERE d1.relative_path IN (${r})
579
313
  AND d2.relative_path NOT IN (${r})
580
314
  AND ${e.localSymbolPredicate}
581
- ORDER BY d2.relative_path`,...n,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),u=e.all(`SELECT DISTINCT d1.relative_path
315
+ ORDER BY d2.relative_path`,...n,...n).map(m=>m.relative_path).filter(m=>!e.isIgnored(m)),u=e.all(`SELECT DISTINCT d1.relative_path
582
316
  FROM mentions m
583
317
  JOIN chunks c ON m.chunk_id = c.id
584
318
  JOIN documents d1 ON c.document_id = d1.id
@@ -593,7 +327,7 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
593
327
  JOIN documents d2 ON sym_def.document_id = d2.id
594
328
  WHERE d2.relative_path IN (${r})
595
329
  AND d1.relative_path NOT IN (${r})
596
- ORDER BY d1.relative_path`,...n,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d));return{files:s,symbols:o,dependsOn:l,dependedOnBy:u}}function ha(e,t){let n=Te(e,t);return n.length===0?[]:fy([...dy(e,n),...my(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(py)}function dy(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
330
+ ORDER BY d1.relative_path`,...n,...n).map(m=>m.relative_path).filter(m=>!e.isIgnored(m));return{files:o,symbols:s,dependsOn:c,dependedOnBy:u}}function Ji(e,t){let n=Ue(e,t);return n.length===0?[]:qg([...Wg(e,n),...Vg(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(Ug)}function Wg(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
597
331
  FROM mentions m
598
332
  JOIN chunks c ON m.chunk_id = c.id
599
333
  JOIN documents d1 ON c.document_id = d1.id
@@ -620,38 +354,7 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
620
354
  AND m.role != 1
621
355
  AND ${e.localSymbolPredicate}
622
356
  ${e.pathExclusionsFor("d1")}
623
- ORDER BY d1.relative_path`,...t,...t,...t)}function my(e,t){let n=new N(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>G(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function fy(e){let t=new Set;return e.filter(n=>{let r=`${n.relative_path}|${n.symbol}`;return t.has(r)?!1:(t.add(r),!0)})}function py(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:y(e.symbol)}}var wn=750;function kn(e,t={}){let{scope:n,minLoc:r=1,includeTests:i=!1,skipBarrels:s=!1,includeMembers:o=!1,deadCodeOnly:a=!1,scanLimit:l,semantic:c=!0}=t,u=Iy(xy(e,{scope:n,minLoc:r,includeTests:i,includeMembers:o}),l),d=s?new Set(na(e)):new Set,m=a?new Map:gy(e,d,u.map(b=>b.symbolId)),f=a?by(e,u.map(b=>b.symbolId),d):new Set,h=a?u.filter(b=>!f.has(b.symbolId)):u;a?Ey(e,h,m,d):Ny(e,h,m,d);let p=a?h.filter(b=>!ya(m,b.symbolId)):u;Py(e,p,m,{includeTests:i,inactiveBarrelPaths:d,includeSemantic:!a&&c});let g=a?h.filter(b=>!ya(m,b.symbolId)):u;return vy(e,Ry(g,m))}function gy(e,t,n){if(n)return hy(e,t,n);let r=e.all(`SELECT
624
- m.symbol_id,
625
- d.relative_path,
626
- COUNT(*) AS ref_count
627
- FROM mentions m
628
- JOIN chunks c ON m.chunk_id = c.id
629
- JOIN documents d ON c.document_id = d.id
630
- WHERE m.role != 1
631
- ${e.pathExclusionsFor("d")}
632
- GROUP BY m.symbol_id, d.relative_path`),i=new Map;for(let s of r){if(e.isIgnored(s.relative_path)||t.has(s.relative_path))continue;let o=i.get(s.symbol_id);o||(o=new Map,i.set(s.symbol_id,o)),o.set(s.relative_path,s.ref_count)}return i}function hy(e,t,n){let r=new Map;for(let i=0;i<n.length;i+=wn)for(let s of yy(e,n.slice(i,i+wn))){if(e.isIgnored(s.relative_path)||t.has(s.relative_path))continue;let o=r.get(s.symbol_id);o||(o=new Map,r.set(s.symbol_id,o)),o.set(s.relative_path,s.ref_count)}return r}function yy(e,t){return t.length===0?[]:e.all(`SELECT
633
- m.symbol_id,
634
- d.relative_path,
635
- COUNT(*) AS ref_count
636
- FROM mentions m
637
- JOIN chunks c ON m.chunk_id = c.id
638
- JOIN documents d ON c.document_id = d.id
639
- WHERE m.role != 1
640
- AND m.symbol_id IN (${t.map(()=>"?").join(",")})
641
- ${e.pathExclusionsFor("d")}
642
- GROUP BY m.symbol_id, d.relative_path`,...t)}function by(e,t,n){let r=new Set;for(let i=0;i<t.length;i+=wn)for(let s of Sy(e,t.slice(i,i+wn)))e.isIgnored(s.relative_path)||n.has(s.relative_path)||r.add(s.symbol_id);return r}function Sy(e,t){return t.length===0?[]:e.all(`SELECT DISTINCT m.symbol_id, d.relative_path
643
- FROM mentions m
644
- JOIN chunks c ON m.chunk_id = c.id
645
- JOIN documents d ON c.document_id = d.id
646
- WHERE m.role != 1
647
- AND m.symbol_id IN (${t.map(()=>"?").join(",")})
648
- ${e.pathExclusionsFor("d")}`,...t).filter(n=>n.symbol_id!==null)}function xy(e,t){let n=My(e),r=[];for(let i of _y(e,t.scope))try{for(let s of J(e,i))e.isIgnored(s.relativePath)||Me(s.symbol)||Sa(s.symbol)&&(!s.isFunctionLike&&s.enclosingSymbol&&Sa(s.enclosingSymbol)||!t.includeTests&&!Ra(s.relativePath)||!t.includeTests&&n(s.relativePath,s.startLine,s.symbol,s.parentTypeName)||un(s.symbol)||Oe(s.symbol)||!t.includeMembers&&!Ty(s)||s.endLine-s.startLine+1<t.minLoc||r.push(s))}finally{As(e,i),xa(e,i)}return r}function _y(e,t){let n=t?"AND relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`SELECT relative_path
649
- FROM documents
650
- WHERE 1 = 1
651
- ${e.pathExclusionsFor("documents")}
652
- ${n}
653
- ORDER BY relative_path`,...r).map(i=>i.relative_path)}function Iy(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Ry(e,t){return e.map(n=>Cy(n,t)).filter(n=>n.cross_file_refs===0).sort((n,r)=>r.loc-n.loc||n.relative_path.localeCompare(r.relative_path)||n.start_line-r.start_line)}function Cy(e,t){let n=t.get(e.symbolId)??new Map,r=n.get(e.relativePath)??0,i=0;for(let[s,o]of n)s!==e.relativePath&&(i+=o);return{relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine,loc:e.endLine-e.startLine+1,symbol:e.symbol,same_file_refs:r,cross_file_refs:i}}function vy(e,t){let n=[],r=0,i=0,s=0;for(let o of t){if(e.isIgnored(o.relative_path)||Xe(e,o.relative_path)||Mt(e,o.symbol,o.relative_path))continue;let a=o.same_file_refs===0?"dead-code":"file-internal";a==="dead-code"?r++:i++,s+=o.loc,n.push({relativePath:o.relative_path,startLine:o.start_line,endLine:o.end_line,loc:o.loc,symbol:o.symbol,shortName:y(o.symbol),sameFileRefs:o.same_file_refs,kind:a})}return{symbols:n,totalCount:n.length,deadCodeCount:r,fileInternalCount:i,totalLoc:s}}function Ny(e,t,n,r){if(t.length===0)return;let i=new N(e),s=new Set(t.map(l=>l.symbolId)),o=new Set(t.map(l=>l.leaf).filter(Boolean)),a=new Set(i.sourceFiles());for(let l of _a(e))a.add(l);i.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:o,skipPath:l=>r.has(l)},l=>{s.has(l.target.symbolId)&&(Ly(e,l)||Ln(n,l.target.symbolId,l.sourceFile,wy(l)))})}function Ey(e,t,n,r){if(t.length===0)return;let i=new N(e),s=Dy(t),o=new Set(i.sourceFiles());for(let a of _a(e))o.add(a);for(let a of o){let l=F(a);if(!(!l&&!ze(a))&&!e.isIgnored(a)&&!r.has(a))try{let c=ky(e,a),u=Ie(e,a);for(let[d,m]of u){let f=s.get(d);if(!f)continue;let h=Yr(a,d,f,c,{permissive:!0});for(let p of h){let g=a===p.relativePath?Math.max(0,m.length-1):m.length;Ia(e,{sourceFile:a,name:d,target:p,occurrences:g})||Ln(n,p.symbolId,a,g)}}for(let d of fn(e,a)){let m=s.get(d);if(m)for(let f of Yr(a,d,m,c,{permissive:!1}))Ln(n,f.symbolId,a,1)}if(l==="rust")for(let d of Fe(e,a)){let m=s.get(d);if(m)for(let f of Yr(a,d,m,c,{permissive:!0}))Ln(n,f.symbolId,a,1)}}finally{xa(e,a)}}}function xa(e,t){no(e,t),To(e,t),Qs(e,t),vs(e,t),gs(e,t)}function Dy(e){let t=new Map;for(let n of e){if(!n.leaf)continue;let r=t.get(n.leaf)??[];r.push(n),t.set(n.leaf,r)}return t}function Yr(e,t,n,r,i){let s=n.filter(l=>l.relativePath===e);if(s.length>0)return s;let o=r.get(t);if(o)for(let l of o){let c=n.filter(u=>ba(l,u.relativePath));if(c.length>0)return c}let a=new Set;for(let l of r.values())for(let c of l)a.add(c);for(let l of a){let c=n.filter(u=>ba(l,u.relativePath));if(c.length>0&&c.length===n.length)return c}return i.permissive?[...n]:[]}function ya(e,t){let n=e.get(t);if(!n)return!1;for(let r of n.values())if(r>0)return!0;return!1}function _a(e){let t=e.all(`SELECT relative_path FROM documents
654
- WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`);return new Set(t.map(n=>n.relative_path))}function Ly(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&Ia(e,t)}function wy(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function Ln(e,t,n,r){if(r<=0)return;let i=e.get(t);i||(i=new Map,e.set(t,i)),i.set(n,(i.get(n)??0)+r)}function Ia(e,t){return t.occurrences>1?!1:q(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function ky(e,t){let n=new Map;for(let r of q(e,t)){if(!r.sourcePath)continue;let i=r.localName??r.importedName;if(i){let s=n.get(i);s||(s=new Set,n.set(i,s)),s.add(r.sourcePath)}if(r.kind==="namespace")for(let s of r.usedMembers){let o=n.get(s);o||(o=new Set,n.set(s,o)),o.add(r.sourcePath)}}return n}function ba(e,t){let n=r=>r.replace(/\\/g,"/").replace(/^\.\//,"");return n(e)===n(t)}function Py(e,t,n,r){for(let i of t){let s=oe(e,i,{semantic:r.includeSemantic!==!1});if(s.length===0)continue;let o=n.get(i.symbolId);o||(o=new Map,n.set(i.symbolId,o));for(let a of s){let l=a.file;l===i.relativePath||e.isIgnored(l)||r.inactiveBarrelPaths.has(l)||!r.includeTests&&!Ra(l)||o.set(l,Math.max(1,o.get(l)??0))}}}function My(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let s=Vs(e,r);return i={ranges:s.map(o=>({startLine:o.startLine,endLine:o.endLine})),containers:new Set(s.map(o=>o.containerName).filter(o=>!!o))},t.set(r,i),i};return(r,i,s,o)=>{let a=n(r);for(let l of a.ranges)if(i>=l.startLine&&i<=l.endLine)return!0;if(o&&a.containers.has(o))return!0;for(let l of _r(s))if(a.containers.has(l))return!0;return!1}}function Ra(e){return[...new Set([...ra,...ia])].every(n=>!Oy(e,n))}function Oy(e,t){return new RegExp(`^${t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".")}$`).test(e)}function Sa(e){return U(e)||e.endsWith("().")||e.endsWith(".")}function Ty(e){return G(e.symbol)||_r(e.symbol).length===0}function Ca(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"",o=e.all(`SELECT
357
+ ORDER BY d1.relative_path`,...t,...t,...t)}function Vg(e,t){let n=new v(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>te(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function qg(e){let t=new Set;return e.filter(n=>{let r=`${n.relative_path}|${n.symbol}`;return t.has(r)?!1:(t.add(r),!0)})}function Ug(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:h(e.symbol)}}function Rc(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=Da(e,r);return i={ranges:o.map(s=>({startLine:s.startLine,endLine:s.endLine})),containers:new Set(o.map(s=>s.containerName).filter(s=>!!s))},t.set(r,i),i};return(r,i,o,s)=>{let a=n(r);for(let c of a.ranges)if(i>=c.startLine&&i<=c.endLine)return!0;if(s&&a.containers.has(s))return!0;for(let c of Wn(o))if(a.containers.has(c))return!0;return!1}}function _c(e){ga(e),bc(e),Wa(e)}var Jg=[{kind:"symbol-evidence",clearDatabase:_c},{kind:"semantic-provider",clearDatabase:Fi},{kind:"identifier-index",clearDatabase:Oa,clearFile:Fa},{kind:"language-parser",clearDatabase:da,clearFile:pa},{kind:"source-stripper",clearDatabase:Js,clearFile:zs},{kind:"ast-tree",clearDatabase:Xr,clearFile:Zr},{kind:"source-text",clearDatabase:vs,clearFile:Ds},{kind:"definition-catalog",clearFile:Fs}],vc=["symbol-evidence","identifier-index","language-parser","source-stripper","ast-tree","source-text"],Dc=["identifier-index","language-parser","source-stripper","ast-tree","source-text"];function Nc(e,t){let n=new Set(t.kinds);for(let r of Jg)n.has(r.kind)&&(t.scope.kind==="database"?r.clearDatabase?.(e):r.clearFile?.(e,zg(t.scope.relativePath)))}function zi(e,t={}){Nc(e,{scope:{kind:"database"},kinds:t.semanticProvider===!0?[...vc,"semantic-provider"]:vc})}function Gi(e,t,n={}){Nc(e,{scope:{kind:"file",relativePath:t},kinds:n.definitions===!0?[...Dc,"definition-catalog"]:Dc})}function zg(e){return e.replace(/\\/g,"/")}function Ec(e,t){return t.isIgnoredPath(e.relativePath)?we("ignored-file"):Ve(e.symbol)?we("module-like-symbol"):Lc(e.symbol)?!e.isFunctionLike&&e.enclosingSymbol&&Lc(e.enclosingSymbol)?we("nested-non-callable-value"):!t.includeTests&&!Ki(e.relativePath)?we("test-file"):!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName)?we("excluded-file-region"):Bn(e.symbol)?we("rust-trait-impl-member"):qe(e.symbol)?we("rust-test-module"):!t.includeMembers&&!Kg(e)?we("member"):e.endLine-e.startLine+1<t.minLoc?we("below-min-loc"):{accepted:!0}:we("non-value-symbol")}function Ki(e){return[...new Set([...Ia,...Ra])].every(n=>!Gg(e,n))}function we(e){return{accepted:!1,rejectionReason:e}}function Gg(e,t){return new RegExp(`^${t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".")}$`).test(e)}function Lc(e){return K(e)||e.endsWith("().")||e.endsWith(".")}function Kg(e){return te(e.symbol)||Wn(e.symbol).length===0}function j(e){return e.endLine-e.startLine+1}function hr(e,t){return j(e)-j(t)||e.relativePath.localeCompare(t.relativePath)}function ne(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Vt(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}`;t.has(i)||(t.add(i),n.push(r))}return n}function wc(){return new Map}function kc(e,t,n){let r=new Map;for(let i of Aa(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||yr(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function Pc(e,t,n){let r=new Set;for(let i of $a(e,t))e.isIgnored(i.relative_path)||n.has(i.relative_path)||r.add(i.symbol_id);return r}function Qi(e,t){let n=e.get(t);if(!n)return!1;for(let r of n.values())if(r.occurrences>0)return!0;return!1}function Tc(e){return e?.occurrences??0}function yr(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=Oc(e,t,n);o.occurrences+=r,o.sources.add(i)}function Mc(e,t,n,r,i){if(r<=0)return;let o=Oc(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function Oc(e,t,n){let r=e.get(t);r||(r=new Map,e.set(t,r));let i=r.get(n);return i||(i={occurrences:0,sources:new Set},r.set(n,i)),i}function bn(e,t={}){let{scope:n,minLoc:r=1,includeTests:i=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:c,semantic:l=!0}=t,u=ne(Qg(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c),m=o?new Set(Ca(e)):new Set,d=a?wc():kc(e,m,u.map(E=>E.symbolId)),p=a?Pc(e,u.map(E=>E.symbolId),m):new Set,y=a?u.filter(E=>!p.has(E.symbolId)):u;a?th(e,y,d,m):eh(e,y,d,m);let f=a?y.filter(E=>!Qi(d,E.symbolId)):u;sh(e,f,d,{includeTests:i,inactiveBarrelPaths:m,includeSemantic:!a&&l});let b=a?y.filter(E=>!Qi(d,E.symbolId)):u;return Zg(e,Yg(b,d))}function Qg(e,t){let n=Rc(e),r=[];for(let i of k(e,{scope:t.scope}))try{for(let o of V(e,i))Ec(o,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:a=>e.isIgnored(a),isExcludedRegion:n}).accepted&&r.push(o)}finally{Gi(e,i,{definitions:!0})}return r}function Yg(e,t){return e.map(n=>Xg(n,t)).filter(n=>n.cross_file_refs===0).sort((n,r)=>r.loc-n.loc||n.relative_path.localeCompare(r.relative_path)||n.start_line-r.start_line)}function Xg(e,t){let n=t.get(e.symbolId)??new Map,r=Tc(n.get(e.relativePath)),i=0;for(let[o,s]of n)o!==e.relativePath&&(i+=s.occurrences);return{relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine,loc:e.endLine-e.startLine+1,symbol:e.symbol,same_file_refs:r,cross_file_refs:i}}function Zg(e,t){let n=[],r=0,i=0,o=0;for(let s of t){if(e.isIgnored(s.relative_path)||gt(e,s.relative_path)||ln(e,s.symbol,s.relative_path))continue;let a=s.same_file_refs===0?"dead-code":"file-internal";a==="dead-code"?r++:i++,o+=s.loc,n.push({relativePath:s.relative_path,startLine:s.start_line,endLine:s.end_line,loc:s.loc,symbol:s.symbol,shortName:h(s.symbol),sameFileRefs:s.same_file_refs,kind:a})}return{symbols:n,totalCount:n.length,deadCodeCount:r,fileInternalCount:i,totalLoc:o}}function eh(e,t,n,r){if(t.length===0)return;let i=new v(e),o=new Set(t.map(c=>c.symbolId)),s=new Set(t.map(c=>c.leaf).filter(Boolean)),a=new Set(i.sourceFiles());for(let c of k(e))a.add(c);i.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>r.has(c)},c=>{o.has(c.target.symbolId)&&(ih(e,c)||yr(n,c.target.symbolId,c.sourceFile,oh(c),"source-fallback"))})}function th(e,t,n,r){if(t.length===0)return;let i=new v(e),o=nh(t),s=new Set(i.sourceFiles());for(let u of k(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let m=c.get(u);return m||(m=fr(e,u),c.set(u,m)),m};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>r.has(u),resolveTargets:({sourceFile:u,name:m,kind:d})=>{let p=o.get(m);return p?rh(u,m,p,l(u),{permissive:d!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),Gi(e,u)}},u=>{let m=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&Fc(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:m})||yr(n,u.target.symbolId,u.sourceFile,m,"source-fallback")})}function nh(e){let t=new Map;for(let n of e){if(!n.leaf)continue;let r=t.get(n.leaf)??[];r.push(n),t.set(n.leaf,r)}return t}function rh(e,t,n,r,i){let o=n.filter(c=>c.relativePath===e);if(o.length>0)return o;let s=r.get(t);if(s)for(let c of s){let l=n.filter(u=>Xe(c,u.relativePath));if(l.length>0)return l}let a=new Set;for(let c of r.values())for(let l of c)a.add(l);for(let c of a){let l=n.filter(u=>Xe(c,u.relativePath));if(l.length>0&&l.length===n.length)return l}return i.permissive?[...n]:[]}function ih(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&Fc(e,t)}function oh(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function Fc(e,t){return t.occurrences>1?!1:Y(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function sh(e,t,n,r){for(let i of t){let o=ye(e,i,{semantic:r.includeSemantic!==!1});if(o.length!==0)for(let s of o){let a=s.file;a===i.relativePath||e.isIgnored(a)||r.inactiveBarrelPaths.has(a)||!r.includeTests&&!Ki(a)||Mc(n,i.symbolId,a,1,"caller-map")}}}function Yi(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"",s=e.all(`SELECT
655
358
  gs.symbol,
656
359
  COUNT(*) AS ref_count,
657
360
  COUNT(DISTINCT ref_d.id) AS file_count,
@@ -674,18 +377,14 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
674
377
  ${i}
675
378
  GROUP BY gs.id
676
379
  ORDER BY ref_count DESC
677
- LIMIT ?`,n).filter(a=>!e.isIgnored(a.defined_in)).map(a=>({symbol:a.symbol,shortName:y(a.symbol),refCount:a.ref_count,fileCount:a.file_count,definedIn:a.defined_in}));return o.length>0?o:Fy(e,r,n)}function Fy(e,t,n){return _e(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>Ay(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function Ay(e,t){let n=oe(e,t,{limit:500});return{symbol:t.symbol,shortName:y(t.symbol),refCount:n.length,fileCount:new Set(n.map(r=>r.file)).size,definedIn:t.relativePath}}function Na(e,t,n={}){return La(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function Ea(e,t){let n=$y(e,t);return n.length>0?n:jy(e,t)}function Da(e,t,n={}){return La(e,t,n)?.filter(r=>!r.used).map(r=>({symbol:r.symbol,shortName:r.shortName,importedIn:r.importer}))??[]}function $y(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
380
+ LIMIT ?`,n).filter(a=>!e.isIgnored(a.defined_in)).map(a=>({symbol:a.symbol,shortName:h(a.symbol),refCount:a.ref_count,fileCount:a.file_count,definedIn:a.defined_in}));return s.length>0?s:ah(e,r,n)}function ah(e,t,n){return Le(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>ch(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function ch(e,t){let n=ye(e,t,{limit:500});return{symbol:t.symbol,shortName:h(t.symbol),refCount:n.length,fileCount:new Set(n.map(r=>r.file)).size,definedIn:t.relativePath}}function Xi(e,t,n={}){return $c(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function Zi(e,t){let n=lh(e,t);return n.length>0?n:uh(e,t)}function eo(e,t,n={}){return $c(e,t,n)?.filter(r=>!r.used).map(r=>({symbol:r.symbol,shortName:r.shortName,importedIn:r.importer}))??[]}function lh(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
678
381
  FROM mentions m
679
382
  JOIN chunks c ON m.chunk_id = c.id
680
383
  JOIN documents d ON c.document_id = d.id
681
384
  JOIN global_symbols gs ON m.symbol_id = gs.id
682
385
  WHERE gs.symbol LIKE ?
683
386
  AND m.role = 2
684
- ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:y(r.symbol),fromFile:r.importer}))}function jy(e,t){let n=w(e,t),r=n?.relativePath??null,i=n?k(n.symbol):t.replace(/\(\)$/,""),s=n?Me(n.symbol):!1,o=e.all(`SELECT relative_path
685
- FROM documents
686
- WHERE 1 = 1
687
- ${e.pathExclusionsFor("documents")}
688
- ORDER BY relative_path`),a=new Set;for(let l of o)if(!e.isIgnored(l.relative_path))for(let c of q(e,l.relative_path))By(c,l.relative_path,{targetFile:r,targetLeaf:i,targetIsModule:s})&&a.add(l.relative_path);return[...a].sort().map(l=>({symbol:n?.symbol??i,shortName:n?y(n.symbol):i,fromFile:l}))}function By(e,t,n){return!e.sourcePath||n.targetFile&&va(e.sourcePath)!==va(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&Vy(t)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function La(e,t,n={}){let r=Q(e,t);return r?Hy(e,r,n)??(n.semantic===!1?null:Wy(e,r))??Uy(e,r):null}function Hy(e,t,n){let i=e.all(`SELECT DISTINCT
387
+ ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:h(r.symbol),fromFile:r.importer}))}function uh(e,t){let n=w(e,t),r=n?.relativePath??null,i=n?L(n.symbol):t.replace(/\(\)$/,""),o=n?Ve(n.symbol):!1,s=new Set;for(let a of k(e,{includeIgnored:!1}))for(let c of Y(e,a))mh(c,a,{targetFile:r,targetLeaf:i,targetIsModule:o})&&s.add(a);return[...s].sort().map(a=>({symbol:n?.symbol??i,shortName:n?h(n.symbol):i,fromFile:a}))}function mh(e,t,n){return!e.sourcePath||n.targetFile&&Ac(e.sourcePath)!==Ac(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&gh(t)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function $c(e,t,n={}){let r=ie(e,t);return r?dh(e,r,n)??(n.semantic===!1?null:ph(e,r))??fh(e,r):null}function dh(e,t,n){let i=e.all(`SELECT DISTINCT
689
388
  gs.symbol,
690
389
  def_d.relative_path AS from_file,
691
390
  imp_d.relative_path AS importer,
@@ -711,11 +410,11 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
711
410
  LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
712
411
  WHERE imp_d.relative_path = ?
713
412
  AND m.role = 2
714
- ORDER BY def_d.relative_path, gs.symbol`,t).filter(s=>!e.isIgnored(s.importer));if(i.length>0){let s=n.semantic===!1?[]:Lt(e,t);return i.map(o=>({symbol:o.symbol,shortName:y(o.symbol),fromFile:o.from_file??"(external)",importer:o.importer,used:o.used!==0||s.some(a=>a.isUsed&&a.sourcePath===o.from_file)}))}return null}function Wy(e,t){let n=Lt(e,t);return n.length>0?n.map(r=>{let i=wa(r.importedName,r.localName,r.kind);return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:r.kind==="side-effect"?!0:r.isUsed}}):null}function Uy(e,t){return q(e,t).map(n=>{let r=wa(n.importedName,n.localName,n.kind),i=n.kind==="side-effect"?!0:n.used;return{symbol:r,shortName:r,fromFile:n.sourcePath??"(external)",importer:t,used:i}})}function wa(e,t,n){return n==="namespace"&&e==="*"&&t?`* as ${t}`:n==="default"&&t?`default as ${t}`:n==="side-effect"?"(side effect import)":t&&t!==e?`${e} as ${t}`:e}function va(e){return e.replace(/\\/g,"/")}function Vy(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function ka(e,t){let n=Te(e,t),r=at(e,n,{sort:!0});if(r.length===0)return[];let i=r.map(a=>({symbol:a.symbol,shortName:a.shortName,startLine:a.startLine,endLine:a.endLine,children:[]})),s=new Map;for(let a of i)s.set(a.symbol,a);let o=[];for(let a=0;a<r.length;a++){let l=r[a],c=i[a];if(l.enclosingSymbol&&s.has(l.enclosingSymbol)){s.get(l.enclosingSymbol).children.push(c);continue}let u=null,d=1/0;for(let m of i)if(m!==c&&m.startLine<=c.startLine&&m.endLine>=c.endLine){if(m.startLine===c.startLine&&m.endLine===c.endLine&&!Ms(m.symbol,c.symbol))continue;let h=m.endLine-m.startLine;h<d&&(d=h,u=m)}u?u.children.push(c):o.push(c)}return o}function Pa(e,t){let n=w(e,t);return n?new N(e).definitionsForFile(n.relativePath).filter(i=>i.symbol!==n.symbol).filter(i=>Ps(n.symbol,i.symbol)).sort((i,s)=>i.startLine-s.startLine||i.endLine-s.endLine).map(i=>({symbol:i.symbol,shortName:y(i.symbol),startLine:i.startLine,endLine:i.endLine,kind:z(i.symbol)??"unknown"})):[]}function Ma(e,t){let n=w(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
413
+ ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:gn(e,t);return i.map(s=>({symbol:s.symbol,shortName:h(s.symbol),fromFile:s.from_file??"(external)",importer:s.importer,used:s.used!==0||o.some(a=>a.isUsed&&a.sourcePath===s.from_file)}))}return null}function ph(e,t){let n=gn(e,t);return n.length>0?n.map(r=>{let i=jc(r.importedName,r.localName,r.kind);return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:r.kind==="side-effect"?!0:r.isUsed}}):null}function fh(e,t){return Y(e,t).map(n=>{let r=jc(n.importedName,n.localName,n.kind),i=n.kind==="side-effect"?!0:n.used;return{symbol:r,shortName:r,fromFile:n.sourcePath??"(external)",importer:t,used:i}})}function jc(e,t,n){return n==="namespace"&&e==="*"&&t?`* as ${t}`:n==="default"&&t?`default as ${t}`:n==="side-effect"?"(side effect import)":t&&t!==e?`${e} as ${t}`:e}function Ac(e){return e.replace(/\\/g,"/")}function gh(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function to(e,t){let n=Ue(e,t),r=kt(e,n,{sort:!0});if(r.length===0)return[];let i=r.map(a=>({symbol:a.symbol,shortName:a.shortName,startLine:a.startLine,endLine:a.endLine,children:[]})),o=new Map;for(let a of i)o.set(a.symbol,a);let s=[];for(let a=0;a<r.length;a++){let c=r[a],l=i[a];if(c.enclosingSymbol&&o.has(c.enclosingSymbol)){o.get(c.enclosingSymbol).children.push(l);continue}let u=null,m=1/0;for(let d of i)if(d!==l&&d.startLine<=l.startLine&&d.endLine>=l.endLine){if(d.startLine===l.startLine&&d.endLine===l.endLine&&!ws(d.symbol,l.symbol))continue;let y=d.endLine-d.startLine;y<m&&(m=y,u=d)}u?u.children.push(l):s.push(l)}return s}function no(e,t){let n=w(e,t);return n?new v(e).definitionsForFile(n.relativePath).filter(i=>i.symbol!==n.symbol).filter(i=>Es(n.symbol,i.symbol)).sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine).map(i=>({symbol:i.symbol,shortName:h(i.symbol),startLine:i.startLine,endLine:i.endLine,kind:ee(i.symbol)??"unknown"})):[]}function ro(e,t){let n=w(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
715
414
  FROM mentions m
716
415
  JOIN chunks c ON m.chunk_id = c.id
717
416
  WHERE m.symbol_id = ?
718
- AND m.role != 1`,n.symbolId);return[{name:y(n.symbol),count:r?.file_count??0}]}function Oa(e,t){let n=Q(e,t);if(!n)return[];let i=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
417
+ AND m.role != 1`,n.symbolId);return[{name:h(n.symbol),count:r?.file_count??0}]}function io(e,t){let n=ie(e,t);if(!n)return[];let i=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
719
418
  FROM mentions m
720
419
  JOIN chunks c ON m.chunk_id = c.id
721
420
  JOIN documents d ON c.document_id = d.id
@@ -732,7 +431,7 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
732
431
  AND m.role != 1
733
432
  AND def_d.id != d.id
734
433
  GROUP BY d.id
735
- ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(i.length>0)return i;let o=Z(e).get(n);return!o||o.size===0?[]:[{name:n,count:o.size}]}function Ta(e,t={}){return Jy(e,t).map(n=>({name:y(n.symbol),count:n.file_count}))}function Jy(e,t){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT gs.symbol, COUNT(DISTINCT c.document_id) AS file_count
434
+ ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(i.length>0)return i;let s=ae(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function oo(e,t={}){return hh(e,t).map(n=>({name:h(n.symbol),count:n.file_count}))}function hh(e,t){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT gs.symbol, COUNT(DISTINCT c.document_id) AS file_count
736
435
  FROM mentions m
737
436
  JOIN chunks c ON m.chunk_id = c.id
738
437
  JOIN global_symbols gs ON m.symbol_id = gs.id
@@ -751,7 +450,7 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
751
450
  GROUP BY gs.id
752
451
  HAVING file_count > 1
753
452
  ORDER BY file_count DESC
754
- LIMIT ?`,n)}function Fa(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND d.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
453
+ LIMIT ?`,n)}function so(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND d.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
755
454
  FROM mentions m
756
455
  JOIN chunks c ON m.chunk_id = c.id
757
456
  JOIN documents d ON c.document_id = d.id
@@ -771,7 +470,7 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
771
470
  ${i}
772
471
  GROUP BY d.id
773
472
  ORDER BY symbol_count DESC
774
- LIMIT ?`,n).filter(o=>!e.isIgnored(o.relative_path)).map(o=>({name:o.relative_path,count:o.symbol_count}))}function Aa(e,t,n){let r=Q(e,t)??t,i=Q(e,n)??n,s=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
473
+ LIMIT ?`,n).filter(s=>!e.isIgnored(s.relative_path)).map(s=>({name:s.relative_path,count:s.symbol_count}))}function ao(e,t,n){let r=ie(e,t)??t,i=ie(e,n)??n,o=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
775
474
  FROM global_symbols gs
776
475
  WHERE (
777
476
  -- Defined in file1, referenced in file2
@@ -803,7 +502,7 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
803
502
  JOIN documents d ON c.document_id = d.id
804
503
  WHERE m.symbol_id = gs.id AND m.role != 1 AND d.relative_path = ?
805
504
  )
806
- )`,r,i,i,r);return{file1:r,file2:i,sharedSymbols:s?.shared??0}}function $a(e,t={}){let{limit:n=20,scope:r}=t,i=r?`AND d1.relative_path LIKE '%${r}%' AND d2.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT
505
+ )`,r,i,i,r);return{file1:r,file2:i,sharedSymbols:o?.shared??0}}function co(e,t={}){let{limit:n=20,scope:r}=t,i=r?`AND d1.relative_path LIKE '%${r}%' AND d2.relative_path LIKE '%${r}%'`:"";return e.all(`SELECT
807
506
  def_d.relative_path AS file1,
808
507
  ref_d.relative_path AS file2,
809
508
  COUNT(DISTINCT gs.id) AS shared
@@ -825,12 +524,12 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
825
524
  ${i}
826
525
  GROUP BY def_d.id, ref_d.id
827
526
  ORDER BY shared DESC
828
- LIMIT ?`,n).filter(o=>!e.isIgnored(o.file1)&&!e.isIgnored(o.file2)).map(o=>({file1:o.file1,file2:o.file2,sharedSymbols:o.shared}))}function Pn(e,t={}){let{scope:n,maxDepth:r=10}=t,i=Z(e,n),s=[],o=new Set,a=new Set,l=[];function c(d,m){if(m>r)return;if(a.has(d)){let h=l.indexOf(d);if(h!==-1){let p=l.slice(h).concat(d),g=p.indexOf(p.reduce((P,L)=>P<L?P:L)),b=[...p.slice(g,-1),...p.slice(0,g),p[g]],_=b.join(" -> ");u.has(_)||(u.add(_),s.push({path:b,kind:qy(b)}))}return}if(o.has(d))return;o.add(d),a.add(d),l.push(d);let f=i.get(d);if(f)for(let h of f)c(h,m+1);l.pop(),a.delete(d)}let u=new Set;for(let d of i.keys())o.has(d)||c(d,0);return s.sort((d,m)=>d.kind!==m.kind?d.kind==="real"?-1:1:d.path.length-m.path.length),s}function qy(e){for(let r of e){let i=ne(r);if(i==="test"||i==="barrel"||i==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":Dn(t)||Dn(n)||ja(t,n)||ja(n,t)||Ba(t,n)||Ba(n,t)||ne(t)==="entry"||ne(n)==="entry"?"module-hierarchy":"real"}function ja(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function Ba(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),r=t.replace(/\.rs$/,"");if(n===r+"_tests"||n===r+"/tests")return!0;let i=e.split("/"),s=t.split("/");if(i.length===s.length&&i.includes("tests")&&s.includes("src")){let o=i[i.length-1],a=s[s.length-1];if(o&&o===a)return!0}return!1}function Ha(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:s=2,scanLimit:o}=t,a=new N(e);return Gy(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),o).map(u=>zy(e,u,t.semantic!==!1)).filter(u=>u.fanIn>=i&&u.fanOut>=s).sort((u,d)=>d.score-u.score||d.fanIn-u.fanIn).slice(0,n)}function zy(e,t,n){let r=new Set(oe(e,t,{limit:500,semantic:n}).map(s=>s.file)).size,i=new Set(te(e,t,{limit:500,semantic:n}).filter(s=>s.file!==t.relativePath).map(s=>`${s.symbol}|${s.file}`)).size;return{symbol:t.symbol,shortName:y(t.symbol),fanIn:r,fanOut:i,score:r*i,definedIn:t.relativePath}}function Gy(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Mn(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,s=new N(e),o=t.semantic!==!1,a=Ky(s.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,sortByLocDesc:typeof i=="number"&&i>0}),i),l=s.crossFileCallerMap(a,{semantic:o}),c=new Set(l.keys()),u=new Map;for(let b of a){let _=k(b.symbol);if(!_)continue;let P=u.get(_)??[];P.push(b.symbolId),u.set(_,P)}let d=e.all(`SELECT relative_path FROM documents WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`);for(let b of d){if(e.isIgnored(b.relative_path)||F(b.relative_path)!=="rust")continue;let _=Fe(e,b.relative_path);for(let P of _){let L=u.get(P);if(L)for(let C of L)c.add(C)}}let m=Wa(s,a,{additive:!1,semantic:o}),f=a.filter(b=>!c.has(b.symbolId)).filter(b=>!m.has(b.symbolId)),h=s.sourceFallbackCallerFiles(f);for(let b of h.keys())c.add(b);let p=f.filter(b=>!c.has(b.symbolId)),g=Wa(s,p,{additive:!0,semantic:o});for(let b of g)m.add(b);return p.filter(b=>!m.has(b.symbolId)).sort((b,_)=>_.endLine-_.startLine-(b.endLine-b.startLine)||b.relativePath.localeCompare(_.relativePath)||b.startLine-_.startLine).map(b=>({symbol:b.symbol,shortName:y(b.symbol),relativePath:b.relativePath,startLine:b.startLine,endLine:b.endLine,loc:b.endLine-b.startLine+1}))}function Wa(e,t,n){if(t.length===0)return new Set;let r=new Map(t.map(s=>[s.symbolId,s.symbol])),i=e.calleeMap(t,{additive:n.additive,semantic:n.semantic});return new Set([...i.entries()].filter(([s,o])=>{let a=r.get(s);return o.some(l=>l.symbol!==a)}).map(([s])=>s))}function Ky(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}var Xr={0:"UnspecifiedKind",1:"AbstractMethod",2:"Accessor",3:"Array",4:"Assertion",5:"AssociatedType",6:"Attribute",7:"Axiom",8:"Boolean",9:"Class",10:"Constant",11:"Constructor",12:"Contract",13:"DataFamily",14:"DefinitionMacro",15:"Delegate",16:"Enum",17:"EnumMember",18:"Error",19:"Event",20:"Fact",21:"Field",22:"File",23:"Function",24:"Getter",25:"Grammar",26:"Instance",27:"Interface",28:"Key",29:"Lang",30:"Lemma",31:"Library",32:"Macro",33:"Method",34:"MethodAlias",35:"MethodReceiver",36:"MethodSpecification",37:"Message",38:"Modifier",39:"Module",40:"Namespace",41:"Null",42:"Number",43:"Object",44:"Operator",45:"Package",46:"PackageObject",47:"Parameter",48:"ParameterLabel",49:"Pattern",50:"Predicate",51:"Property",52:"Protocol",53:"ProtocolMethod",54:"PureVirtualMethod",55:"Quasiquoter",56:"SelfParameter",57:"Setter",58:"Signature",59:"SingletonClass",60:"SingletonMethod",61:"StaticDataMember",62:"StaticEvent",63:"StaticField",64:"StaticMethod",65:"StaticProperty",66:"StaticVariable",67:"String",68:"Struct",69:"Subscript",70:"Tactic",71:"Theorem",72:"ThisParameter",73:"Trait",74:"TraitMethod",75:"Type",76:"TypeAlias",77:"TypeClass",78:"TypeClassMethod",79:"TypeFamily",80:"TypeParameter",81:"Union",82:"Value",83:"Variable"},Qr=new Map;for(let[e,t]of Object.entries(Xr))Qr.set(t.toLowerCase(),Number(e));function Yy(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=Qr.get(n);if(r!==void 0)return r;for(let[i,s]of Qr)if(i.includes(n))return s;return null}function Ua(e,t,n={}){let{scope:r,limit:i=100}=n,s=Yy(t);return s===null?[]:Ja(e,r).map(a=>({row:a,resolvedKind:qa(a)})).filter(a=>a.resolvedKind===s).slice(0,i).map(({row:a,resolvedKind:l})=>({symbol:a.symbol,shortName:y(a.symbol),kind:l,kindName:Xr[l]??"Unknown",relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function Va(e,t={}){let n=new Map;for(let r of Ja(e,t.scope)){let i=qa(r);i===null||i===0||n.set(i,(n.get(i)??0)+1)}return[...n.entries()].sort((r,i)=>i[1]-r[1]||r[0]-i[0]).map(([r,i])=>({kind:r,kindName:Xr[r]??"Unknown",count:i}))}function Ja(e,t){return _e(e,{scope:t}).map(Qy)}function Qy(e){return{symbol:e.symbol,kind:e.kind,documentation:e.documentation,enclosing_symbol:e.enclosingSymbol,relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine}}function qa(e){return e.kind!==null&&e.kind!==0?Xy(e.kind,e.symbol,e.documentation):Zy(e.symbol,e.documentation,e.enclosing_symbol)}function Xy(e,t,n){let r=(n??"").toLowerCase();if(z(t)==="type"){if(r.includes("type "))return 76;if(r.includes("interface "))return 27;if(r.includes("struct "))return 68;if(r.includes("trait "))return 73;if(r.includes("class "))return 9}return e}function Zy(e,t,n){let r=V(e);if("kind"in r)return null;let i=r.descriptors,s=i[i.length-2]??null,o=z(e),a=(t??"").toLowerCase();return o==="type"?a.includes("type ")?76:a.includes("interface ")?27:a.includes("struct ")?68:a.includes("trait ")?73:(a.includes("class "),9):o==="method"?s?.suffix==="type"?33:23:o==="namespace"?39:o!=="term"?null:a.includes("async def ")||a.includes("def ")?23:(n?z(n):s?.suffix??null)==="type"?21:83}function za(e,t={}){let{limit:n=10,scope:r,minDepth:i=3}=t,s=Z(e,r),o=new Map,a=[],l=new Map,c=new Map,u=new Set,d=[],m=0;for(let C of s.keys()){if(l.has(C))continue;let v=[],T=(s.get(C)??new Set).values();for(l.set(C,m),c.set(C,m),m+=1,d.push(C),u.add(C),v.push({node:C,iter:T,pendingChild:null});v.length>0;){let D=v[v.length-1];if(D.pendingChild!==null){let et=D.pendingChild;D.pendingChild=null,c.set(D.node,Math.min(c.get(D.node),c.get(et)))}let $=D.iter.next();if($.done){if(c.get(D.node)===l.get(D.node)){let et=[];for(;;){let Wt=d.pop();if(u.delete(Wt),et.push(Wt),o.set(Wt,a.length),Wt===D.node)break}a.push(et)}v.pop();continue}let Y=$.value;if(l.has(Y))u.has(Y)&&c.set(D.node,Math.min(c.get(D.node),l.get(Y)));else{l.set(Y,m),c.set(Y,m),m+=1,d.push(Y),u.add(Y);let et=(s.get(Y)??new Set).values();D.pendingChild=Y,v.push({node:Y,iter:et,pendingChild:null})}}}let f=new Map,h=new Array(a.length);for(let C=0;C<a.length;C++)h[C]=a[C].length,f.set(C,new Set);for(let[C,v]of s){let T=o.get(C);for(let D of v){let $=o.get(D);$!==T&&f.get(T).add($)}}let p=new Array(a.length),g=new Array(a.length);for(let C=0;C<a.length;C++){let v=[],T=0;for(let D of f.get(C)){let $=g[D];$>T&&(T=$,v=p[D])}p[C]=[C,...v],g[C]=h[C]+T}function b(C){return p[C]}let _=a.map(C=>[...C].sort()),P=new Set,L=[];for(let C=0;C<a.length;C++){let v=b(C),T=[];for(let $ of v)T.push(..._[$]);if(T.length<i)continue;let D=T.join(" ");P.has(D)||(P.add(D),L.push({chain:T,depth:T.length}))}return L.sort((C,v)=>v.depth-C.depth),L.slice(0,n)}function Ga(e,t){let n=w(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
829
- WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:y(r.symbol),depth:0}],s=r.enclosing_symbol,o=1,a=new Set([r.symbol]);for(;s&&!a.has(s)&&o<20;){a.add(s);let d=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",s);if(!d)break;i.push({symbol:d.symbol,shortName:y(d.symbol),depth:o}),s=d.enclosing_symbol,o++}if(i.length>1)return i;let l=V(r.symbol);if("kind"in l)return i;let c=l.descriptors;if(c.length<=1)return i;let u=[i[0]];for(let d=c.length-2,m=1;d>=0;d--,m++){let h=c.slice(0,d+1).map(p=>p.suffix==="method"?`${p.name}()`:p.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");u.push({symbol:h,shortName:h,depth:m})}return u}function Ka(e,t,n={}){let r=w(e,t);if(!r)return null;let i=n.semantic!==!1,s=oe(e,r,{limit:50,semantic:i}),o=eb(te(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i}));return{symbol:r.symbol,shortName:y(r.symbol),callers:s.map(a=>({symbol:a.symbol,shortName:y(a.symbol),file:a.file})),callees:o.map(a=>({symbol:a.symbol,shortName:y(a.symbol),file:a.file}))}}function eb(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}`;t.has(i)||(t.add(i),n.push(r))}return n}function Tt(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function Ft(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function Ya(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);let r=e.size+t.size-n;return r===0?0:n/r}function Zr(e){let t=e.length;if(t===0)return new Map;let n=new Map;for(let i of e)for(let s of i)n.set(s,(n.get(s)??0)+1);let r=new Map;for(let[i,s]of n)r.set(i,Math.log(t/s));return r}function tb(e){let t=[...e.values()].sort((r,i)=>r-i);if(t.length===0)return 0;let n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function Qa(e,t,n){let r=Tt(e,t);if(r.size===0)return{similarity:0,significantShared:[],trivialShared:[]};let i=0,s=0,o=0,a=new Set([...e,...t]);for(let f of a){let h=n.get(f)??0,p=e.has(f)?h:0,g=t.has(f)?h:0;i+=p*g,s+=p*p,o+=g*g}let l=Math.sqrt(s)*Math.sqrt(o),c=l>0?i/l:0,u=tb(n),d=[],m=[];for(let f of r)(n.get(f)??0)>=u?d.push(f):m.push(f);return d.sort((f,h)=>(n.get(h)??0)-(n.get(f)??0)),{similarity:c,significantShared:d,trivialShared:m}}function Xa(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,s=ib(e,t,{semantic:n.semantic!==!1});if(!s)return[];if(!U(s.symbol))return[];let o=nb(e,s,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return o.length>0?o.slice(0,i):ab(e,t,{minSimilarity:r,limit:i})}function nb(e,t,n,r){let i=el(e,{minCallees:3,excludeSymbol:t.symbol,scanLimit:r.scanLimit,semantic:r.semantic}),s=Zr([t,...i].map(a=>a.callees)),o=[];for(let a of i){if(a.callees.size<3)continue;let l=Za(t,a,s,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0});l&&o.push(l)}return o.sort((a,l)=>l.similarity-a.similarity),o}function Za(e,t,n,r){let{similarity:i,significantShared:s}=Qa(e.callees,t.callees,n);if(i<r.minSimilarity)return null;let o=Tt(e.callees,t.callees).size;if(s.length<r.requireSignificantShared&&o<r.requireSharedCount)return null;let a=s.length>0?s:[...Tt(e.callees,t.callees)];return{symbolA:e.symbol,shortNameA:y(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:y(t.symbol),fileB:t.file,similarity:i,similarityBasis:"callees",sharedCallees:a.map(y),uniqueToA:[...Ft(e.callees,t.callees)].map(y),uniqueToB:[...Ft(t.callees,e.callees)].map(y)}}function On(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:s=4,crossFileOnly:o=!1,scanLimit:a}=t,l=el(e,{minCallees:s,scope:i,scanLimit:a,semantic:t.semantic!==!1}),c=Zr(l.map(p=>p.callees)),u=new Map;for(let p of l)for(let g of p.callees)u.set(g,(u.get(g)??0)+1);let d=Math.max(8,Math.ceil(Math.sqrt(l.length))),m=new Map;for(let p=0;p<l.length;p+=1)for(let g of l[p].callees){if((u.get(g)??0)>d)continue;let b=m.get(g);b||(b=[],m.set(g,b)),b.push(p)}let f=[],h=new Set;e:for(let p=0;p<l.length;p+=1){let g=l[p],b=new Set;for(let _ of g.callees){let P=m.get(_);if(P)for(let L of P)L>p&&b.add(L)}for(let _ of b){let P=`${p}|${_}`;if(h.has(P))continue;h.add(P);let L=l[_];if(o&&g.file===L.file)continue;if(g.paramCount>=0&&L.paramCount>=0){let v=Math.abs(g.paramCount-L.paramCount),T=Math.max(2,Math.ceil(Math.max(g.paramCount,L.paramCount)*.5));if(v>T)continue}let C=Za(g,L,c,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4});if(C&&(f.push(C),f.length>r*5))break e}}return f.sort((p,g)=>g.similarity-p.similarity),f.slice(0,r)}var rb=["ScipDatabase#all","ScipDatabase#get","ScipDatabase#prepare","ScipDatabase#pathExclusionsFor","ScipDatabase#isIgnored","ScipDatabase#symbolNoiseFor","PerDbValue#get","PerDbValue#has",":storage:db:ScipDatabase:all",":storage:db:ScipDatabase:get",":storage:db:ScipDatabase:prepare",":storage:db:ScipDatabase:pathExclusionsFor",":storage:db:ScipDatabase:isIgnored",":storage:db:ScipDatabase:symbolNoiseFor",":storage:per-db-cache:PerDbValue:get",":storage:per-db-cache:PerDbValue:has"];function ib(e,t,n){let r=w(e,t),i=new N(e);if(!r)return null;let s=te(e,r,{semantic:n.semantic});return{symbol:r.symbol,file:r.relativePath,callees:tl(s.map(o=>o.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}function el(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:s}=t,o=new N(e),a=sb(o.productionCallableDefinitions({scope:r,minLoc:5,excludeSymbol:i,sortByLocDesc:typeof s=="number"&&s>0}),s),l=o.calleeMap(a,{semantic:t.semantic!==!1});return a.map(c=>({symbol:c.symbol,file:c.relativePath,callees:tl((l.get(c.symbolId)??[]).map(u=>u.symbol)),paramCount:o.callableSignature(c)?.paramCount??-1})).filter(c=>c.callees.size>=n)}function sb(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function tl(e){return new Set([...e].filter(t=>!ob(t)))}function ob(e){return rb.some(t=>e.includes(t))}function ab(e,t,n){let r=lb(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,s=[];for(let o of ub(e)){if(o.symbol===r.symbol||o.tokens.size<3)continue;let a=Tt(r.tokens,o.tokens);if(a.size<2)continue;let l=new Set([...r.tokens,...o.tokens]),c=l.size>0?a.size/l.size:0;c<i||s.push({symbolA:r.symbol,shortNameA:y(r.symbol),fileA:r.file,symbolB:o.symbol,shortNameB:y(o.symbol),fileB:o.file,similarity:c,similarityBasis:"source-tokens",sharedCallees:[...a].sort(),uniqueToA:[...Ft(r.tokens,o.tokens)].sort(),uniqueToB:[...Ft(o.tokens,r.tokens)].sort()})}return s.sort((o,a)=>a.similarity-o.similarity||o.shortNameB.localeCompare(a.shortNameB)),s.slice(0,n.limit)}function lb(e,t){let n=w(e,t);if(!n||!U(n.symbol))return null;let r=cb(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function cb(e,t){let n=k(t.symbol),r=nl(e,t.relativePath,t.startLine,t.endLine,n),i=rl(r,n);return i.size>0?i:null}function ub(e){let t=new N(e);return t.scopedDefinitions().filter(n=>n.isFunctionLike).filter(n=>t.fileKind(n.relativePath)!=="test").filter(n=>!Oe(n.symbol)).map(n=>({symbol:n.symbol,file:n.relativePath,tokens:rl(nl(e,n.relativePath,n.startLine,n.endLine,n.leaf),n.leaf)})).filter(n=>n.tokens.size>0)}function nl(e,t,n,r,i){let s=M(e,t);if(!s)return"";let o=s.split(`
830
- `);if(r>=n&&r-n<=12)return o.slice(n,r+1).join(`
831
- `);let a=[new RegExp(`\\bdef\\s+${At(i)}\\b`),new RegExp(`\\bfun\\s+${At(i)}\\b`),new RegExp(`\\bfn\\s+${At(i)}\\b`),new RegExp(`\\bfunction\\s+${At(i)}\\b`),new RegExp(`\\b${At(i)}\\s*\\(`)],l=o.findIndex(c=>a.some(u=>u.test(c)));if(l>=0){let c=l;for(let u=l+1;u<o.length&&u<=l+8;u++){let d=o[u]??"";if(u>l&&mb(d)||(c=u,d.trim()===""&&u>l+1))break}return o.slice(l,c+1).join(`
832
- `)}return o.slice(n,Math.min(o.length,n+8)).join(`
833
- `)}function rl(e,t){if(!e)return new Set;let n=new Set(["public","private","protected","final","static","class","def","fun","fn","function","return","string","bool","boolean","void","unit","self","this","new","const","let","var","end","pub"]),r=db(t),s=e.replace(/["'`]/g," ").replace(/\b\d+\b/g," NUM ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^A-Za-z0-9_]+/g," ").replace(/_/g," ").toLowerCase().split(/\s+/).map(o=>o.trim()).filter(o=>o.length>1).filter(o=>!n.has(o)).filter(o=>!r.has(o));return new Set(s)}function db(e){return new Set(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9_]+|_/).map(t=>t.toLowerCase()).filter(t=>t.length>1))}function mb(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function At(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sl(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:s}=t,o=t.minDeps??(s?1:3),a=fb(e,{scope:i,minDeps:o}),l=[];if(s){let c=a.find(u=>u.file.includes(s));if(!c)return[];for(let u of a){if(u.file===c.file)continue;let d=il(c,u,n);d&&l.push(d)}}else for(let c=0;c<a.length;c++){for(let u=c+1;u<a.length;u++){let d=il(a[c],a[u],n);d&&l.push(d)}if(l.length>r*5)break}return l.sort((c,u)=>u.similarity-c.similarity),l.slice(0,r)}function fb(e,t){let{scope:n,minDeps:r}=t,i=Z(e,n),s=pb(i),o=[];for(let[a,l]of i)l.size>=r&&o.push({file:a,deps:new Set([...l].filter(c=>!s.has(c)))});return o}function pb(e){let t=new Set,n=e.size;if(n===0)return t;let r=new Map;for(let i of e.values())for(let s of i)r.set(s,(r.get(s)??0)+1);for(let[i,s]of r)s>=5&&s/n>.3&&t.add(i);return t}function il(e,t,n){let r=new Set;for(let a of e.deps)t.deps.has(a)&&r.add(a);if(r.size<3||e.deps.size<4||t.deps.size<4)return null;let i=Ya(e.deps,t.deps);if(i<n)return null;let s=[];for(let a of e.deps)t.deps.has(a)||s.push(a);let o=[];for(let a of t.deps)e.deps.has(a)||o.push(a);return{fileA:e.file,fileB:t.file,similarity:i,sharedDeps:[...r],uniqueToA:s,uniqueToB:o}}function al(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:s=3,maxChainLength:o=8}=t,a=Z(e,i),l=Ib(a,s,o);if(l.length===0)return[];let c=gb(l);return c.length<2?[]:_b(bb(c,n,r),r)}function gb(e){let t=hb(e),n=[];for(let r of e){let i=r.filter(s=>!t.has(s));i.length>=2&&n.push({original:r,filtered:i})}return n}function hb(e){let{nodeFreq:t,tailFreq:n}=yb(e),r=e.length*.9,i=e.length*.8,s=new Set;for(let[a,l]of t)l>r&&s.add(a);for(let[a,l]of n)l>i&&s.add(a);let o=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let l=a.split("/").pop()??"";o.includes(l)&&s.add(a)}return s}function yb(e){let t=new Map,n=new Map;for(let r of e){let i=new Set;for(let s of r)i.has(s)||(t.set(s,(t.get(s)??0)+1),i.add(s));for(let s=Math.max(0,r.length-2);s<r.length;s++)n.set(r[s],(n.get(r[s])??0)+1)}return{nodeFreq:t,tailFreq:n}}function bb(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let s=i+1;s<e.length;s++){let o=Sb(e[i],e[s],t);o&&r.push(o)}if(r.length>n*10)break}return r.sort((i,s)=>Math.abs(s.similarity-i.similarity)>.01?s.similarity-i.similarity:i.divergencePoints.length-s.divergencePoints.length),r}function Sb(e,t,n){if(!xb(e.filtered,t.filtered))return null;let{distance:r,ops:i}=Rb(e.filtered,t.filtered),s=Math.max(e.filtered.length,t.filtered.length);if(s===0)return null;let o=1-r/s;if(o<n||r===0)return null;let a=i.filter(c=>c.type==="substitute").map(c=>({index:c.indexA,nodeA:e.filtered[c.indexA],nodeB:t.filtered[c.indexB]}));return a.length===0||i.filter(c=>c.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:o,editDistance:r,divergencePoints:a,commonPrefix:Cb(e.original,t.original),commonSuffix:vb(e.original,t.original)}}function xb(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function _b(e,t){let n=[];for(let r of e)if(n.some(s=>ol(r.chainA,s.chainA)&&ol(r.chainB,s.chainB))||n.push(r),n.length>=t)break;return n}function Ib(e,t,n){let r=[];for(let s of e.keys()){if(r.length>=500)break;ll(e,s,[s],new Set([s]),t,n,r,500)}return r}function ll(e,t,n,r,i,s,o,a){if(o.length>=a)return;if(n.length>=s){n.length>=i&&o.push([...n]);return}let l=e.get(t);if(!l||l.size===0){n.length>=i&&o.push([...n]);return}let c=!1;for(let u of l)if(!r.has(u)&&(r.add(u),n.push(u),ll(e,u,n,r,i,s,o,a),n.pop(),r.delete(u),c=!0,o.length>=a))return;!c&&n.length>=i&&o.push([...n])}function Rb(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let l=0;l<=n;l++)i[l][0]=l;for(let l=0;l<=r;l++)i[0][l]=l;for(let l=1;l<=n;l++)for(let c=1;c<=r;c++)e[l-1]===t[c-1]?i[l][c]=i[l-1][c-1]:i[l][c]=1+Math.min(i[l-1][c],i[l][c-1],i[l-1][c-1]);let s=[],o=n,a=r;for(;o>0||a>0;)o>0&&a>0&&e[o-1]===t[a-1]?(s.unshift({type:"match",indexA:o-1,indexB:a-1}),o--,a--):o>0&&a>0&&i[o][a]===i[o-1][a-1]+1?(s.unshift({type:"substitute",indexA:o-1,indexB:a-1}),o--,a--):a>0&&i[o][a]===i[o][a-1]+1?(s.unshift({type:"insert",indexA:o,indexB:a-1}),a--):(s.unshift({type:"delete",indexA:o-1,indexB:a}),o--);return{distance:i[n][r],ops:s}}function Cb(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}function vb(e,t){let n=[],r=e.length-1,i=t.length-1;for(;r>=0&&i>=0&&e[r]===t[i];)n.unshift(e[r]),r--,i--;return n}function ol(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function Tn(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:s=20,scanLimit:o}=t,a=new N(e),l=a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),c=Pb(l,o),u=a.calleeMap(c,{semantic:t.semantic!==!1}),d=[];for(let m of c){let f=Nb(m,u.get(m.symbolId)??[],i);f&&d.push(f)}return d.sort((m,f)=>f.clusters.length-m.clusters.length||f.loc-m.loc),d.slice(0,s)}function Nb(e,t,n){let r=new Set(t.map(a=>a.symbol));if(r.size<n)return null;let i=Eb(r,t),s=Db(r,i);if(s.length<2)return null;let o=Lb(s,i);return o.length===0?null:{symbol:e.symbol,shortName:y(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:kb(e),totalCallees:r.size,clusters:o}}function Eb(e,t){let n=new Map;for(let i of e)n.set(i,new Set);let r=new Map;for(let i of t){let s=r.get(i.chunkId);s||(s=new Set,r.set(i.chunkId,s)),s.add(i.symbol)}for(let i of r.values()){let s=[...i];for(let o=0;o<s.length;o++)for(let a=o+1;a<s.length;a++)n.get(s[o]).add(s[a]),n.get(s[a]).add(s[o])}return n}function Db(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let s=new Set,o=[i];for(;o.length>0;){let a=o.pop();if(!n.has(a)){n.add(a),s.add(a);for(let l of t.get(a)??[])n.has(l)||o.push(l)}}r.push(s)}return r}function Lb(e,t){return e.filter(n=>n.size>=3).map(n=>wb(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function wb(e,t,n){let r=new Set;for(let a of t)if(a!==e)for(let l of a)r.add(l);let i=0;for(let a of e)for(let l of n.get(a)??[])r.has(l)&&i++;let s=e.size*r.size,o=s>0?1-i/s:1;return{callees:[...e].map(y),isolation:o}}function kb(e){return e.endLine-e.startLine+1}function Pb(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function cl(e,t,n={}){let{maxDepth:r=5,scope:i}=n,s=w(e,t);if(!s)return[];let o=[],a=new Set([s.symbolId]),l=new Set,c=[s];for(let u=1;u<=r&&c.length!==0;u++){let d=[];for(let m of c)for(let f of Mb(e,m,i)){let h=`${f.file}|${f.shortName}`;if(f.symbolId!==null){if(a.has(f.symbolId))continue;a.add(f.symbolId)}else if(l.has(h))continue;l.add(h),o.push({symbol:f.symbol,shortName:f.shortName,file:f.file,depth:u}),f.symbolId!==null&&f.symbolMatch&&d.push(f.symbolMatch)}c=d}return o.sort((u,d)=>u.depth-d.depth||u.file.localeCompare(d.file)),o}function Mb(e,t,n){let r=oe(e,t,{limit:500}).filter(c=>!e.isIgnored(c.file)).filter(c=>!n||c.file.includes(n)),i=new Set(r.map(c=>c.file)),s=[];for(let c of Ob(e,t,n)){if(i.has(c))continue;let u=J(e,c),d=u.length>0?le(u,u[0].startLine):null;s.push({symbol:d?.symbol??c,file:c})}let o=[...r,...s],a=[],l=new Set;for(let c of o){let u=ct(e,c.symbol);if(!u){let m=`${c.file}|${c.symbol}`;if(l.has(m))continue;l.add(m),a.push({symbolId:null,symbol:c.symbol,shortName:y(c.symbol),file:c.file,symbolMatch:null});continue}if(u.symbolId===t.symbolId||e.isIgnored(u.relativePath)||!Tb(u.symbol))continue;let d=`${u.symbolId}|${u.relativePath}`;l.has(d)||(l.add(d),a.push({symbolId:u.symbolId,symbol:u.symbol,shortName:y(u.symbol),file:u.relativePath,symbolMatch:u}))}return a}function Ob(e,t,n){let r=n?"AND consumer_d.relative_path LIKE ?":"",i=[t.symbolId,t.documentId];return n&&i.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
527
+ LIMIT ?`,n).filter(s=>!e.isIgnored(s.file1)&&!e.isIgnored(s.file2)).map(s=>({file1:s.file1,file2:s.file2,sharedSymbols:s.shared}))}function Sn(e,t={}){let{scope:n,maxDepth:r=10}=t,i=ae(e,n),o=[],s=new Set,a=new Set,c=[];function l(m,d){if(d>r)return;if(a.has(m)){let y=c.indexOf(m);if(y!==-1){let f=c.slice(y).concat(m),b=f.indexOf(f.reduce(($,F)=>$<F?$:F)),E=[...f.slice(b,-1),...f.slice(0,b),f[b]],x=E.join(" -> ");u.has(x)||(u.add(x),o.push({path:E,kind:yh(E)}))}return}if(s.has(m))return;s.add(m),a.add(m),c.push(m);let p=i.get(m);if(p)for(let y of p)l(y,d+1);c.pop(),a.delete(m)}let u=new Set;for(let m of i.keys())s.has(m)||l(m,0);return o.sort((m,d)=>m.kind!==d.kind?m.kind==="real"?-1:1:m.path.length-d.path.length),o}function yh(e){for(let r of e){let i=ue(r);if(i==="test"||i==="barrel"||i==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":ir(t)||ir(n)||Bc(t,n)||Bc(n,t)||Hc(t,n)||Hc(n,t)||ue(t)==="entry"||ue(n)==="entry"?"module-hierarchy":"real"}function Bc(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function Hc(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),r=t.replace(/\.rs$/,"");if(n===r+"_tests"||n===r+"/tests")return!0;let i=e.split("/"),o=t.split("/");if(i.length===o.length&&i.includes("tests")&&o.includes("src")){let s=i[i.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}function lo(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new v(e);return ne(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(u=>bh(e,u,t.semantic!==!1)).filter(u=>u.fanIn>=i&&u.fanOut>=o).sort((u,m)=>m.score-u.score||m.fanIn-u.fanIn).slice(0,n)}function bh(e,t,n){let r=new Set(ye(e,t,{limit:500,semantic:n}).map(o=>o.file)).size,i=new Set(me(e,t,{limit:500,semantic:n}).filter(o=>o.file!==t.relativePath).map(o=>`${o.symbol}|${o.file}`)).size;return{symbol:t.symbol,shortName:h(t.symbol),fanIn:r,fanOut:i,score:r*i,definedIn:t.relativePath}}function xn(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new v(e),s=t.semantic!==!1,a=ne(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,sortByLocDesc:typeof i=="number"&&i>0}),i),c=o.crossFileCallerMap(a,{semantic:s}),l=new Set(c.keys());for(let f of o.frameworkReferencedSymbolIds(a))l.add(f);let u=o.symbolsWithNonSelfCallees(a,{additive:!1,semantic:s}),m=a.filter(f=>!l.has(f.symbolId)).filter(f=>!u.has(f.symbolId)),d=o.sourceFallbackCallerFiles(m);for(let f of d.keys())l.add(f);let p=m.filter(f=>!l.has(f.symbolId)),y=o.symbolsWithNonSelfCallees(p,{additive:!0,semantic:s});for(let f of y)u.add(f);return p.filter(f=>!u.has(f.symbolId)).sort((f,b)=>j(b)-j(f)||f.relativePath.localeCompare(b.relativePath)||f.startLine-b.startLine).map(f=>({symbol:f.symbol,shortName:h(f.symbol),relativePath:f.relativePath,startLine:f.startLine,endLine:f.endLine,loc:j(f)}))}var mo={0:"UnspecifiedKind",1:"AbstractMethod",2:"Accessor",3:"Array",4:"Assertion",5:"AssociatedType",6:"Attribute",7:"Axiom",8:"Boolean",9:"Class",10:"Constant",11:"Constructor",12:"Contract",13:"DataFamily",14:"DefinitionMacro",15:"Delegate",16:"Enum",17:"EnumMember",18:"Error",19:"Event",20:"Fact",21:"Field",22:"File",23:"Function",24:"Getter",25:"Grammar",26:"Instance",27:"Interface",28:"Key",29:"Lang",30:"Lemma",31:"Library",32:"Macro",33:"Method",34:"MethodAlias",35:"MethodReceiver",36:"MethodSpecification",37:"Message",38:"Modifier",39:"Module",40:"Namespace",41:"Null",42:"Number",43:"Object",44:"Operator",45:"Package",46:"PackageObject",47:"Parameter",48:"ParameterLabel",49:"Pattern",50:"Predicate",51:"Property",52:"Protocol",53:"ProtocolMethod",54:"PureVirtualMethod",55:"Quasiquoter",56:"SelfParameter",57:"Setter",58:"Signature",59:"SingletonClass",60:"SingletonMethod",61:"StaticDataMember",62:"StaticEvent",63:"StaticField",64:"StaticMethod",65:"StaticProperty",66:"StaticVariable",67:"String",68:"Struct",69:"Subscript",70:"Tactic",71:"Theorem",72:"ThisParameter",73:"Trait",74:"TraitMethod",75:"Type",76:"TypeAlias",77:"TypeClass",78:"TypeClassMethod",79:"TypeFamily",80:"TypeParameter",81:"Union",82:"Value",83:"Variable"},uo=new Map;for(let[e,t]of Object.entries(mo))uo.set(t.toLowerCase(),Number(e));function Sh(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=uo.get(n);if(r!==void 0)return r;for(let[i,o]of uo)if(i.includes(n))return o;return null}function po(e,t,n={}){let{scope:r,limit:i=100}=n,o=Sh(t);return o===null?[]:Wc(e,r).map(a=>({row:a,resolvedKind:Vc(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:h(a.symbol),kind:c,kindName:mo[c]??"Unknown",relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function fo(e,t={}){let n=new Map;for(let r of Wc(e,t.scope)){let i=Vc(r);i===null||i===0||n.set(i,(n.get(i)??0)+1)}return[...n.entries()].sort((r,i)=>i[1]-r[1]||r[0]-i[0]).map(([r,i])=>({kind:r,kindName:mo[r]??"Unknown",count:i}))}function Wc(e,t){return Le(e,{scope:t}).map(xh)}function xh(e){return{symbol:e.symbol,kind:e.kind,documentation:e.documentation,enclosing_symbol:e.enclosingSymbol,relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine}}function Vc(e){return e.kind!==null&&e.kind!==0?Ch(e.kind,e.symbol,e.documentation):Ih(e.symbol,e.documentation,e.enclosing_symbol)}function Ch(e,t,n){let r=(n??"").toLowerCase();if(ee(t)==="type"){if(r.includes("type "))return 76;if(r.includes("interface "))return 27;if(r.includes("struct "))return 68;if(r.includes("trait "))return 73;if(r.includes("class "))return 9}return e}function Ih(e,t,n){let r=Q(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=ee(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?76:a.includes("interface ")?27:a.includes("struct ")?68:a.includes("trait ")?73:(a.includes("class "),9):s==="method"?o?.suffix==="type"?33:23:s==="namespace"?39:s!=="term"?null:a.includes("async def ")||a.includes("def ")?23:(n?ee(n):o?.suffix??null)==="type"?21:83}function go(e,t={}){let{limit:n=10,scope:r,minDepth:i=3}=t,o=ae(e,r),s=new Map,a=[],c=new Map,l=new Map,u=new Set,m=[],d=0;for(let R of o.keys()){if(c.has(R))continue;let _=[],G=(o.get(R)??new Set).values();for(c.set(R,d),l.set(R,d),d+=1,m.push(R),u.add(R),_.push({node:R,iter:G,pendingChild:null});_.length>0;){let A=_[_.length-1];if(A.pendingChild!==null){let _t=A.pendingChild;A.pendingChild=null,l.set(A.node,Math.min(l.get(A.node),l.get(_t)))}let De=A.iter.next();if(De.done){if(l.get(A.node)===c.get(A.node)){let _t=[];for(;;){let Fn=m.pop();if(u.delete(Fn),_t.push(Fn),s.set(Fn,a.length),Fn===A.node)break}a.push(_t)}_.pop();continue}let Ne=De.value;if(c.has(Ne))u.has(Ne)&&l.set(A.node,Math.min(l.get(A.node),c.get(Ne)));else{c.set(Ne,d),l.set(Ne,d),d+=1,m.push(Ne),u.add(Ne);let _t=(o.get(Ne)??new Set).values();A.pendingChild=Ne,_.push({node:Ne,iter:_t,pendingChild:null})}}}let p=new Map,y=new Array(a.length);for(let R=0;R<a.length;R++)y[R]=a[R].length,p.set(R,new Set);for(let[R,_]of o){let G=s.get(R);for(let A of _){let De=s.get(A);De!==G&&p.get(G).add(De)}}let f=new Array(a.length),b=new Array(a.length);for(let R=0;R<a.length;R++){let _=[],G=0;for(let A of p.get(R)){let De=b[A];De>G&&(G=De,_=f[A])}f[R]=[R,..._],b[R]=y[R]+G}function E(R){return f[R]}let x=a.map(R=>[...R].sort()),$=new Set,F=[];for(let R=0;R<a.length;R++){let _=E(R),G=[];for(let De of _)G.push(...x[De]);if(G.length<i)continue;let A=G.join(" ");$.has(A)||($.add(A),F.push({chain:G,depth:G.length}))}return F.sort((R,_)=>_.depth-R.depth),F.slice(0,n)}function ho(e,t){let n=w(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
528
+ WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:h(r.symbol),depth:0}],o=r.enclosing_symbol,s=1,a=new Set([r.symbol]);for(;o&&!a.has(o)&&s<20;){a.add(o);let m=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!m)break;i.push({symbol:m.symbol,shortName:h(m.symbol),depth:s}),o=m.enclosing_symbol,s++}if(i.length>1)return i;let c=Q(r.symbol);if("kind"in c)return i;let l=c.descriptors;if(l.length<=1)return i;let u=[i[0]];for(let m=l.length-2,d=1;m>=0;m--,d++){let y=l.slice(0,m+1).map(f=>f.suffix==="method"?`${f.name}()`:f.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");u.push({symbol:y,shortName:y,depth:d})}return u}function yo(e,t,n={}){let r=w(e,t);if(!r)return null;let i=n.semantic!==!1,o=ye(e,r,{limit:50,semantic:i}),s=Vt(me(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i}));return{symbol:r.symbol,shortName:h(r.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:h(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:h(a.symbol),file:a.file}))}}function Cn(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function In(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function qc(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);let r=e.size+t.size-n;return r===0?0:n/r}function bo(e){let t=e.length;if(t===0)return new Map;let n=new Map;for(let i of e)for(let o of i)n.set(o,(n.get(o)??0)+1);let r=new Map;for(let[i,o]of n)r.set(i,Math.log(t/o));return r}function Rh(e){let t=[...e.values()].sort((r,i)=>r-i);if(t.length===0)return 0;let n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function Uc(e,t,n){let r=Cn(e,t);if(r.size===0)return{similarity:0,significantShared:[],trivialShared:[]};let i=0,o=0,s=0,a=new Set([...e,...t]);for(let p of a){let y=n.get(p)??0,f=e.has(p)?y:0,b=t.has(p)?y:0;i+=f*b,o+=f*f,s+=b*b}let c=Math.sqrt(o)*Math.sqrt(s),l=c>0?i/c:0,u=Rh(n),m=[],d=[];for(let p of r)(n.get(p)??0)>=u?m.push(p):d.push(p);return m.sort((p,y)=>(n.get(y)??0)-(n.get(p)??0)),{similarity:l,significantShared:m,trivialShared:d}}function So(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=Dh(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!K(o.symbol))return[];let s=_h(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):Lh(e,t,{minSimilarity:r,limit:i})}function _h(e,t,n,r){let i=zc(e,{minCallees:3,excludeSymbol:t.symbol,scanLimit:r.scanLimit,semantic:r.semantic}),o=bo([t,...i].map(a=>a.callees)),s=[];for(let a of i){if(a.callees.size<3)continue;let c=Jc(t,a,o,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0});c&&s.push(c)}return s.sort((a,c)=>c.similarity-a.similarity),s}function Jc(e,t,n,r){let{similarity:i,significantShared:o}=Uc(e.callees,t.callees,n);if(i<r.minSimilarity)return null;let s=Cn(e.callees,t.callees).size;if(o.length<r.requireSignificantShared&&s<r.requireSharedCount)return null;let a=o.length>0?o:[...Cn(e.callees,t.callees)];return{symbolA:e.symbol,shortNameA:h(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:h(t.symbol),fileB:t.file,similarity:i,similarityBasis:"callees",sharedCallees:a.map(h),uniqueToA:[...In(e.callees,t.callees)].map(h),uniqueToB:[...In(t.callees,e.callees)].map(h)}}function _n(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=zc(e,{minCallees:o,scope:i,scanLimit:a,semantic:t.semantic!==!1}),l=bo(c.map(f=>f.callees)),u=new Map;for(let f of c)for(let b of f.callees)u.set(b,(u.get(b)??0)+1);let m=Math.max(8,Math.ceil(Math.sqrt(c.length))),d=new Map;for(let f=0;f<c.length;f+=1)for(let b of c[f].callees){if((u.get(b)??0)>m)continue;let E=d.get(b);E||(E=[],d.set(b,E)),E.push(f)}let p=[],y=new Set;e:for(let f=0;f<c.length;f+=1){let b=c[f],E=new Set;for(let x of b.callees){let $=d.get(x);if($)for(let F of $)F>f&&E.add(F)}for(let x of E){let $=`${f}|${x}`;if(y.has($))continue;y.add($);let F=c[x];if(s&&b.file===F.file)continue;if(b.paramCount>=0&&F.paramCount>=0){let _=Math.abs(b.paramCount-F.paramCount),G=Math.max(2,Math.ceil(Math.max(b.paramCount,F.paramCount)*.5));if(_>G)continue}let R=Jc(b,F,l,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4});if(R&&(p.push(R),p.length>r*5))break e}}return p.sort((f,b)=>b.similarity-f.similarity),p.slice(0,r)}var vh=["ScipDatabase#all","ScipDatabase#get","ScipDatabase#prepare","ScipDatabase#pathExclusionsFor","ScipDatabase#isIgnored","ScipDatabase#symbolNoiseFor","PerDbValue#get","PerDbValue#has",":storage:db:ScipDatabase:all",":storage:db:ScipDatabase:get",":storage:db:ScipDatabase:prepare",":storage:db:ScipDatabase:pathExclusionsFor",":storage:db:ScipDatabase:isIgnored",":storage:db:ScipDatabase:symbolNoiseFor",":storage:per-db-cache:PerDbValue:get",":storage:per-db-cache:PerDbValue:has"];function Dh(e,t,n){let r=w(e,t),i=new v(e);if(!r)return null;let o=me(e,r,{semantic:n.semantic});return{symbol:r.symbol,file:r.relativePath,callees:Gc(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}function zc(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=new v(e),a=ne(s.productionCallableDefinitions({scope:r,minLoc:5,excludeSymbol:i,sortByLocDesc:typeof o=="number"&&o>0}),o),c=s.calleeMap(a,{semantic:t.semantic!==!1});return a.map(l=>({symbol:l.symbol,file:l.relativePath,callees:Gc((c.get(l.symbolId)??[]).map(u=>u.symbol)),paramCount:s.callableSignature(l)?.paramCount??-1})).filter(l=>l.callees.size>=n)}function Gc(e){return new Set([...e].filter(t=>!Nh(t)))}function Nh(e){return vh.some(t=>e.includes(t))}function Lh(e,t,n){let r=Eh(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[];for(let s of kh(e)){if(s.symbol===r.symbol||s.tokens.size<3)continue;let a=Cn(r.tokens,s.tokens);if(a.size<2)continue;let c=new Set([...r.tokens,...s.tokens]),l=c.size>0?a.size/c.size:0;l<i||o.push({symbolA:r.symbol,shortNameA:h(r.symbol),fileA:r.file,symbolB:s.symbol,shortNameB:h(s.symbol),fileB:s.file,similarity:l,similarityBasis:"source-tokens",sharedCallees:[...a].sort(),uniqueToA:[...In(r.tokens,s.tokens)].sort(),uniqueToB:[...In(s.tokens,r.tokens)].sort()})}return o.sort((s,a)=>a.similarity-s.similarity||s.shortNameB.localeCompare(a.shortNameB)),o.slice(0,n.limit)}function Eh(e,t){let n=w(e,t);if(!n||!K(n.symbol))return null;let r=wh(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function wh(e,t){let n=L(t.symbol),r=Kc(e,t.relativePath,t.startLine,t.endLine,n),i=Qc(r,n);return i.size>0?i:null}function kh(e){let t=new v(e);return t.scopedDefinitions().filter(n=>n.isFunctionLike).filter(n=>t.fileKind(n.relativePath)!=="test").filter(n=>!qe(n.symbol)).map(n=>({symbol:n.symbol,file:n.relativePath,tokens:Qc(Kc(e,n.relativePath,n.startLine,n.endLine,n.leaf),n.leaf)})).filter(n=>n.tokens.size>0)}function Kc(e,t,n,r,i){let o=T(e,t);if(!o)return"";let s=o.split(`
529
+ `);if(r>=n&&r-n<=12)return s.slice(n,r+1).join(`
530
+ `);let a=[new RegExp(`\\bdef\\s+${Rn(i)}\\b`),new RegExp(`\\bfun\\s+${Rn(i)}\\b`),new RegExp(`\\bfn\\s+${Rn(i)}\\b`),new RegExp(`\\bfunction\\s+${Rn(i)}\\b`),new RegExp(`\\b${Rn(i)}\\s*\\(`)],c=s.findIndex(l=>a.some(u=>u.test(l)));if(c>=0){let l=c;for(let u=c+1;u<s.length&&u<=c+8;u++){let m=s[u]??"";if(u>c&&Th(m)||(l=u,m.trim()===""&&u>c+1))break}return s.slice(c,l+1).join(`
531
+ `)}return s.slice(n,Math.min(s.length,n+8)).join(`
532
+ `)}function Qc(e,t){if(!e)return new Set;let n=new Set(["public","private","protected","final","static","class","def","fun","fn","function","return","string","bool","boolean","void","unit","self","this","new","const","let","var","end","pub"]),r=Ph(t),o=e.replace(/["'`]/g," ").replace(/\b\d+\b/g," NUM ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^A-Za-z0-9_]+/g," ").replace(/_/g," ").toLowerCase().split(/\s+/).map(s=>s.trim()).filter(s=>s.length>1).filter(s=>!n.has(s)).filter(s=>!r.has(s));return new Set(o)}function Ph(e){return new Set(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9_]+|_/).map(t=>t.toLowerCase()).filter(t=>t.length>1))}function Th(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Rn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xo(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),a=Mh(e,{scope:i,minDeps:s}),c=[];if(o){let l=a.find(u=>u.file.includes(o));if(!l)return[];for(let u of a){if(u.file===l.file)continue;let m=Yc(l,u,n);m&&c.push(m)}}else for(let l=0;l<a.length;l++){for(let u=l+1;u<a.length;u++){let m=Yc(a[l],a[u],n);m&&c.push(m)}if(c.length>r*5)break}return c.sort((l,u)=>u.similarity-l.similarity),c.slice(0,r)}function Mh(e,t){let{scope:n,minDeps:r}=t,i=ae(e,n),o=Oh(i),s=[];for(let[a,c]of i)c.size>=r&&s.push({file:a,deps:new Set([...c].filter(l=>!o.has(l)))});return s}function Oh(e){let t=new Set,n=e.size;if(n===0)return t;let r=new Map;for(let i of e.values())for(let o of i)r.set(o,(r.get(o)??0)+1);for(let[i,o]of r)o>=5&&o/n>.3&&t.add(i);return t}function Yc(e,t,n){let r=new Set;for(let a of e.deps)t.deps.has(a)&&r.add(a);if(r.size<3||e.deps.size<4||t.deps.size<4)return null;let i=qc(e.deps,t.deps);if(i<n)return null;let o=[];for(let a of e.deps)t.deps.has(a)||o.push(a);let s=[];for(let a of t.deps)e.deps.has(a)||s.push(a);return{fileA:e.file,fileB:t.file,similarity:i,sharedDeps:[...r],uniqueToA:o,uniqueToB:s}}function Co(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=ae(e,i),c=Vh(a,o,s);if(c.length===0)return[];let l=Fh(c);return l.length<2?[]:Wh(jh(l,n,r),r)}function Fh(e){let t=Ah(e),n=[];for(let r of e){let i=r.filter(o=>!t.has(o));i.length>=2&&n.push({original:r,filtered:i})}return n}function Ah(e){let{nodeFreq:t,tailFreq:n}=$h(e),r=e.length*.9,i=e.length*.8,o=new Set;for(let[a,c]of t)c>r&&o.add(a);for(let[a,c]of n)c>i&&o.add(a);let s=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let c=a.split("/").pop()??"";s.includes(c)&&o.add(a)}return o}function $h(e){let t=new Map,n=new Map;for(let r of e){let i=new Set;for(let o of r)i.has(o)||(t.set(o,(t.get(o)??0)+1),i.add(o));for(let o=Math.max(0,r.length-2);o<r.length;o++)n.set(r[o],(n.get(r[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function jh(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=Bh(e[i],e[o],t);s&&r.push(s)}if(r.length>n*10)break}return r.sort((i,o)=>Math.abs(o.similarity-i.similarity)>.01?o.similarity-i.similarity:i.divergencePoints.length-o.divergencePoints.length),r}function Bh(e,t,n){if(!Hh(e.filtered,t.filtered))return null;let{distance:r,ops:i}=qh(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-r/o;if(s<n||r===0)return null;let a=i.filter(l=>l.type==="substitute").map(l=>({index:l.indexA,nodeA:e.filtered[l.indexA],nodeB:t.filtered[l.indexB]}));return a.length===0||i.filter(l=>l.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:r,divergencePoints:a,commonPrefix:Uh(e.original,t.original),commonSuffix:Jh(e.original,t.original)}}function Hh(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function Wh(e,t){let n=[];for(let r of e)if(n.some(o=>Xc(r.chainA,o.chainA)&&Xc(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function Vh(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;Zc(e,o,[o],new Set([o]),t,n,r,500)}return r}function Zc(e,t,n,r,i,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=i&&s.push([...n]);return}let c=e.get(t);if(!c||c.size===0){n.length>=i&&s.push([...n]);return}let l=!1;for(let u of c)if(!r.has(u)&&(r.add(u),n.push(u),Zc(e,u,n,r,i,o,s,a),n.pop(),r.delete(u),l=!0,s.length>=a))return;!l&&n.length>=i&&s.push([...n])}function qh(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let c=0;c<=n;c++)i[c][0]=c;for(let c=0;c<=r;c++)i[0][c]=c;for(let c=1;c<=n;c++)for(let l=1;l<=r;l++)e[c-1]===t[l-1]?i[c][l]=i[c-1][l-1]:i[c][l]=1+Math.min(i[c-1][l],i[c][l-1],i[c-1][l-1]);let o=[],s=n,a=r;for(;s>0||a>0;)s>0&&a>0&&e[s-1]===t[a-1]?(o.unshift({type:"match",indexA:s-1,indexB:a-1}),s--,a--):s>0&&a>0&&i[s][a]===i[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&i[s][a]===i[s][a-1]+1?(o.unshift({type:"insert",indexA:s,indexB:a-1}),a--):(o.unshift({type:"delete",indexA:s-1,indexB:a}),s--);return{distance:i[n][r],ops:o}}function Uh(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}function Jh(e,t){let n=[],r=e.length-1,i=t.length-1;for(;r>=0&&i>=0&&e[r]===t[i];)n.unshift(e[r]),r--,i--;return n}function Xc(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function vn(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new v(e),c=a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),l=ne(c,s),u=a.calleeMap(l,{semantic:t.semantic!==!1}),m=[];for(let d of l){let p=zh(d,u.get(d.symbolId)??[],i);p&&m.push(p)}return m.sort((d,p)=>p.clusters.length-d.clusters.length||p.loc-d.loc),m.slice(0,o)}function zh(e,t,n){let r=new Set(t.map(a=>a.symbol));if(r.size<n)return null;let i=Gh(r,t),o=Kh(r,i);if(o.length<2)return null;let s=Qh(o,i);return s.length===0?null:{symbol:e.symbol,shortName:h(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:j(e),totalCallees:r.size,clusters:s}}function Gh(e,t){let n=new Map;for(let i of e)n.set(i,new Set);let r=new Map;for(let i of t){let o=r.get(i.chunkId);o||(o=new Set,r.set(i.chunkId,o)),o.add(i.symbol)}for(let i of r.values()){let o=[...i];for(let s=0;s<o.length;s++)for(let a=s+1;a<o.length;a++)n.get(o[s]).add(o[a]),n.get(o[a]).add(o[s])}return n}function Kh(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=new Set,s=[i];for(;s.length>0;){let a=s.pop();if(!n.has(a)){n.add(a),o.add(a);for(let c of t.get(a)??[])n.has(c)||s.push(c)}}r.push(o)}return r}function Qh(e,t){return e.filter(n=>n.size>=3).map(n=>Yh(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function Yh(e,t,n){let r=new Set;for(let a of t)if(a!==e)for(let c of a)r.add(c);let i=0;for(let a of e)for(let c of n.get(a)??[])r.has(c)&&i++;let o=e.size*r.size,s=o>0?1-i/o:1;return{callees:[...e].map(h),isolation:s}}function Io(e,t,n={}){let{maxDepth:r=5,scope:i}=n,o=w(e,t);if(!o)return[];let s=[],a=new Set([o.symbolId]),c=new Set,l=[o];for(let u=1;u<=r&&l.length!==0;u++){let m=[];for(let d of l)for(let p of Xh(e,d,i)){let y=`${p.file}|${p.shortName}`;if(p.symbolId!==null){if(a.has(p.symbolId))continue;a.add(p.symbolId)}else if(c.has(y))continue;c.add(y),s.push({symbol:p.symbol,shortName:p.shortName,file:p.file,depth:u}),p.symbolId!==null&&p.symbolMatch&&m.push(p.symbolMatch)}l=m}return s.sort((u,m)=>u.depth-m.depth||u.file.localeCompare(m.file)),s}function Xh(e,t,n){let r=ye(e,t,{limit:500}).filter(l=>!e.isIgnored(l.file)).filter(l=>!n||l.file.includes(n)),i=new Set(r.map(l=>l.file)),o=[];for(let l of Zh(e,t,n)){if(i.has(l))continue;let u=V(e,l),m=u.length>0?de(u,u[0].startLine):null;o.push({symbol:m?.symbol??l,file:l})}let s=[...r,...o],a=[],c=new Set;for(let l of s){let u=Tt(e,l.symbol);if(!u){let d=`${l.file}|${l.symbol}`;if(c.has(d))continue;c.add(d),a.push({symbolId:null,symbol:l.symbol,shortName:h(l.symbol),file:l.file,symbolMatch:null});continue}if(u.symbolId===t.symbolId||e.isIgnored(u.relativePath)||!ey(u.symbol))continue;let m=`${u.symbolId}|${u.relativePath}`;c.has(m)||(c.add(m),a.push({symbolId:u.symbolId,symbol:u.symbol,shortName:h(u.symbol),file:u.relativePath,symbolMatch:u}))}return a}function Zh(e,t,n){let r=n?"AND consumer_d.relative_path LIKE ?":"",i=[t.symbolId,t.documentId];return n&&i.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
834
533
  FROM mentions m
835
534
  JOIN chunks c ON m.chunk_id = c.id
836
535
  JOIN documents consumer_d ON consumer_d.id = c.document_id
@@ -838,30 +537,30 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
838
537
  AND m.role != 1
839
538
  AND c.document_id != ?
840
539
  ${e.pathExclusionsFor("consumer_d")}
841
- ${r}`,...i).map(s=>s.relative_path).filter(s=>!e.isIgnored(s)))}function Tb(e){let t=z(e);return t==="method"||t==="type"||e.endsWith("().")}function ul(e,t,n={}){let r=Q(e,t);if(!r)return null;let i=Fb(e,r);if(!i||e.isIgnored(i.relative_path))return null;let s=[],o=0,a=Ab(e,i.relative_path),l=n.semantic===!1?new Map:pt(e,a);for(let c of a){let u=$b(e,i,c,l.get(c.symbolId)??new Set);o+=u,s.push({symbol:c.symbol,shortName:y(c.symbol),startLine:c.startLine,endLine:c.endLine,externalConsumers:u,riskLevel:jb(u)})}return{file:i.relative_path,symbols:s,totalExternalConsumers:o}}function Fb(e,t){return e.get(`SELECT id, relative_path FROM documents
540
+ ${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function ey(e){let t=ee(e);return t==="method"||t==="type"||e.endsWith("().")}function Ro(e,t,n={}){let r=ie(e,t);if(!r)return null;let i=ty(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=ny(e,i.relative_path),c=n.semantic===!1?new Map:Ht(e,a);for(let l of a){let u=ry(e,i,l,c.get(l.symbolId)??new Set);s+=u,o.push({symbol:l.symbol,shortName:h(l.symbol),startLine:l.startLine,endLine:l.endLine,externalConsumers:u,riskLevel:iy(u)})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s}}function ty(e,t){return e.get(`SELECT id, relative_path FROM documents
842
541
  WHERE relative_path = ?
843
542
  ${e.pathExclusionsFor("documents")}
844
- LIMIT 1`,t)??null}function Ab(e,t){return new N(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function $b(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
543
+ LIMIT 1`,t)??null}function ny(e,t){return new v(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function ry(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
845
544
  FROM mentions m
846
545
  JOIN chunks c ON m.chunk_id = c.id
847
546
  JOIN documents consumer_d ON consumer_d.id = c.document_id
848
547
  WHERE m.symbol_id = ?
849
548
  AND m.role != 1
850
- AND c.document_id != ?`,n.symbolId,t.id);return new Set([...i.map(s=>s.relative_path),...[...r].filter(s=>s!==t.relative_path)]).size}function jb(e){return e>10?"high":e>0?"medium":"low"}import{execFileSync as ei}from"child_process";function ml(e,t={}){let n=ti(e,t);return n.note?Bb(n.note,n.changedFileLines):n.changedFiles.length===0?Hb(n.changedFileLines):ri(n.changedFiles,[ni(e,n.changedFiles,n.changedFiles)])}function ti(e,t={}){let{base:n="HEAD"}=t;try{let r=Wb(e.config.projectRoot,n);return{changedFileLines:r,changedFiles:Ub(e,r),note:r.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],note:"Unable to compute git diff."}}}function ni(e,t,n){let r=new N(e),i=new Set(n),s=[],o=new Map,a=t.flatMap(c=>r.definitionsForFile(c)).filter(Gb).sort((c,u)=>c.relativePath.localeCompare(u.relativePath)||c.startLine-u.startLine),l=pt(e,a);for(let c of a)Vb(e,c,n,i,s,o,l.get(c.symbolId)??new Set);return{changedSymbols:s,consumerEntries:[...o.entries()].map(([c,u])=>({file:c,symbols:[...u].sort()}))}}function ri(e,t){let n=new Map,r=t.flatMap(s=>s.changedSymbols);for(let s of t)for(let o of s.consumerEntries){let a=n.get(o.file);a||(a=new Set,n.set(o.file,a));for(let l of o.symbols)a.add(l)}let i=zb(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:i.length}}}function Bb(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function Hb(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function Wb(e,t){let n=ei("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=ei("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=ei("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([n,r,i].flatMap(s=>s.split(`
851
- `)).map(s=>s.trim()).filter(s=>s.length>0))]}function Ub(e,t){let n=[];for(let r of t){let i=e.get(`SELECT relative_path FROM documents
549
+ AND c.document_id != ?`,n.symbolId,t.id);return new Set([...i.map(o=>o.relative_path),...[...r].filter(o=>o!==t.relative_path)]).size}function iy(e){return e>10?"high":e>0?"medium":"low"}import{execFileSync as _o}from"child_process";function br(e,t={}){let n=qt(e,t);return n.note?oy(n.note,n.changedFileLines):n.changedFiles.length===0?sy(n.changedFileLines):xr(n.changedFiles,[Sr(e,n.changedFiles,n.changedFiles)])}function qt(e,t={}){let{base:n="HEAD"}=t;try{let r=ay(e.config.projectRoot,n);return{changedFileLines:r,changedFiles:cy(e,r),note:r.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],note:"Unable to compute git diff."}}}function Sr(e,t,n){let r=new v(e),i=new Set(n),o=[],s=new Map,a=t.flatMap(l=>r.definitionsForFile(l)).filter(py).sort((l,u)=>l.relativePath.localeCompare(u.relativePath)||l.startLine-u.startLine),c=Ht(e,a);for(let l of a)ly(e,l,n,i,o,s,c.get(l.symbolId)??new Set);return{changedSymbols:o,consumerEntries:[...s.entries()].map(([l,u])=>({file:l,symbols:[...u].sort()}))}}function xr(e,t){let n=new Map,r=t.flatMap(o=>o.changedSymbols);for(let o of t)for(let s of o.consumerEntries){let a=n.get(s.file);a||(a=new Set,n.set(s.file,a));for(let c of s.symbols)a.add(c)}let i=dy(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:i.length}}}function oy(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function sy(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function ay(e,t){let n=_o("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=_o("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=_o("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:1e4});return[...new Set([n,r,i].flatMap(o=>o.split(`
550
+ `)).map(o=>o.trim()).filter(o=>o.length>0))]}function cy(e,t){let n=[];for(let r of t){let i=e.get(`SELECT relative_path FROM documents
852
551
  WHERE relative_path LIKE ?
853
- LIMIT 1`,`%${r}`);i&&!e.isIgnored(i.relative_path)&&n.push(i.relative_path)}return n}function Vb(e,t,n,r,i,s,o){let a=Math.max(Jb(e,t.symbolId),o.size);if(!Kb(t,a))return;let l=y(t.symbol);i.push({symbol:t.symbol,shortName:l,file:t.relativePath,fanIn:a});for(let c of qb(e,t.symbolId,n))dl(e,r,s,c,l);for(let c of o)dl(e,r,s,c,l)}function Jb(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS fan_in
552
+ LIMIT 1`,`%${r}`);i&&!e.isIgnored(i.relative_path)&&n.push(i.relative_path)}return n}function ly(e,t,n,r,i,o,s){let a=Math.max(uy(e,t.symbolId),s.size);if(!fy(t,a))return;let c=h(t.symbol);i.push({symbol:t.symbol,shortName:c,file:t.relativePath,fanIn:a});for(let l of my(e,t.symbolId,n))el(e,r,o,l,c);for(let l of s)el(e,r,o,l,c)}function uy(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS fan_in
854
553
  FROM mentions m
855
554
  JOIN chunks c ON m.chunk_id = c.id
856
555
  WHERE m.symbol_id = ?
857
- AND m.role != 1`,t)?.fan_in??0}function qb(e,t,n){return n.length===0?[]:e.all(`SELECT DISTINCT ref_d.relative_path
556
+ AND m.role != 1`,t)?.fan_in??0}function my(e,t,n){return n.length===0?[]:e.all(`SELECT DISTINCT ref_d.relative_path
858
557
  FROM mentions m
859
558
  JOIN chunks c ON m.chunk_id = c.id
860
559
  JOIN documents ref_d ON c.document_id = ref_d.id
861
560
  WHERE m.symbol_id = ?
862
561
  AND m.role != 1
863
562
  AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
864
- ${e.pathExclusionsFor("ref_d")}`,t,...n).map(i=>i.relative_path)}function dl(e,t,n,r,i){if(e.isIgnored(r)||t.has(r))return;let s=n.get(r);s||(s=new Set,n.set(r,s)),s.add(i)}function zb(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function Gb(e){return!(Me(e.symbol)||e.parentTypeName!==null&&!G(e.symbol))}function Kb(e,t){return G(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}import $t from"path";function Ze(e){let n=e.replace(/\\/g,"/").split("/").filter(Boolean);return n.length<=1?"(root)":n.length>=3&&["src","lib","app","server","client"].includes(n[0])?`${n[0]}/${n[1]}`:n[0]}function ii(e,t){if(e===t)return"ok";let n=Fn(e),r=Fn(t);return n&&r?Yb(n,r)?"ok":"violation":Qb(e,t)}function fl(e,t){let n=Fn(Ze(e)),r=Fn(Ze(t));return!!n&&!!r}function Fn(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function Yb(e,t){return t==="domain"?!0:e==="domain"?!1:{analysis:new Set(["domain","source","storage","symbols"]),core:new Set(["analysis","domain","resolution","source","storage","symbols"]),"language-parsers":new Set(["domain","resolution","source","storage"]),queries:new Set(["analysis","core","domain","language-parsers","resolution","semantic","source","storage","symbols"]),reindex:new Set(["domain","language-parsers","resolution","runtime","source","storage","symbols"]),resolution:new Set(["domain","source","storage","symbols"]),runtime:new Set(["domain","queries","reindex","resolution","source","storage","symbols"]),semantic:new Set(["domain","resolution","storage","symbols"]),source:new Set(["domain","storage"]),storage:new Set(["domain","source"]),symbols:new Set(["analysis","domain","language-parsers","resolution","semantic","source","storage"])}[e]?.has(t)??!1}function Qb(e,t){if(t==="shared")return"ok";let n={app:new Set(["core","shared","ui"]),core:new Set(["shared"]),infra:new Set(["core","shared"]),ui:new Set(["core","shared"])};return n[e]?n[e].has(t)?"ok":"violation":null}function An(e,t){let{scope:n,minDeviation:r=5}=t??{},i=t?.semantic!==!1,o=new N(e).fileDependencyGraph(n),a=iS(e,n);return tS([...Xb(e,o,a,{semantic:i}),...Zb(o),...eS(o,r)])}function Xb(e,t,n,r){let i=[];for(let[s,o]of t){if(Ee(s))continue;let a=n.get(s)??new Set;for(let l of o)if(!Ee(l)&&!a.has(l)){if(r.semantic&&uS(e,s,l)||dS(e,s,l)||mS(e,s,l)||cS(l)||pS(e,s,l)||fS(l))continue;i.push({file:s,kind:"unused-import",description:`Depends on ${l} but references none of its symbols`,dep:l})}}return i}function Zb(e){let t=[],n=lS(e);for(let[r,i]of e){if(Ee(r))continue;let s=Ze(r);for(let o of i){if(Ee(o))continue;let a=Ze(o);if(s===a)continue;(ii(s,a)??n.get(`${s}->${a}`))==="violation"&&t.push({file:r,kind:"layer-violation",description:`Imports from ${a}/ (${o}) \u2014 may cross architectural boundary`,dep:o,detail:`${s}/ should not depend on ${a}/`})}}return t}function eS(e,t){let n=[];for(let[r,i]of nS(e)){let s=i.filter(a=>!Ee(a));if(s.length<t)continue;let o=rS(e,s);for(let a of s)for(let l of e.get(a)??[])Ee(l)||(o.get(l)??0)===1&&$t.dirname(l)!==r&&$t.dirname(l)!==$t.dirname(r)&&(fl(a,l)||n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${l}`,dep:l}))}return n}function tS(e){return{results:e,unusedImports:e.filter(t=>t.kind==="unused-import").length,layerViolations:e.filter(t=>t.kind==="layer-violation").length,patternDeviations:e.filter(t=>t.kind==="pattern-deviation").length}}function nS(e){let t=new Map;for(let n of e.keys()){let r=$t.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function rS(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])Ee(i)||n.set(i,(n.get(i)??0)+1);return n}function iS(e,t){let n=new Map;return sS(e,n,t),aS(e,n),n}function sS(e,t,n){for(let r of oS(e,n))pl(e,t,r.from_file,r.to_file)}function oS(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
563
+ ${e.pathExclusionsFor("ref_d")}`,t,...n).map(i=>i.relative_path)}function el(e,t,n,r,i){if(e.isIgnored(r)||t.has(r))return;let o=n.get(r);o||(o=new Set,n.set(r,o)),o.add(i)}function dy(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function py(e){return!(Ve(e.symbol)||e.parentTypeName!==null&&!te(e.symbol))}function fy(e,t){return te(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}import Dn from"path";function bt(e){let n=e.replace(/\\/g,"/").split("/").filter(Boolean);return n.length<=1?"(root)":n.length>=3&&["src","lib","app","server","client"].includes(n[0])?`${n[0]}/${n[1]}`:n[0]}function vo(e,t){if(e===t)return"ok";let n=Cr(e),r=Cr(t);return n&&r?gy(n,r)?"ok":"violation":hy(e,t)}function tl(e,t){let n=Cr(bt(e)),r=Cr(bt(t));return!!n&&!!r}function Cr(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function gy(e,t){return t==="domain"?!0:e==="domain"?!1:{analysis:new Set(["domain","source","storage","symbols"]),core:new Set(["analysis","domain","resolution","source","storage","symbols"]),"language-parsers":new Set(["domain","resolution","source","storage"]),queries:new Set(["analysis","core","domain","language-parsers","resolution","semantic","source","storage","symbols"]),reindex:new Set(["domain","language-parsers","resolution","runtime","semantic","source","storage","symbols"]),resolution:new Set(["domain","source","storage","symbols"]),runtime:new Set(["domain","queries","reindex","resolution","semantic","source","storage","symbols"]),semantic:new Set(["domain","resolution","storage","symbols"]),source:new Set(["domain","storage"]),storage:new Set(["domain","source"]),symbols:new Set(["analysis","domain","language-parsers","resolution","semantic","source","storage"])}[e]?.has(t)??!1}function hy(e,t){if(t==="shared")return"ok";let n={app:new Set(["core","shared","ui"]),core:new Set(["shared"]),infra:new Set(["core","shared"]),ui:new Set(["core","shared"])};return n[e]?n[e].has(t)?"ok":"violation":null}function Nn(e,t){let{scope:n,minDeviation:r=5}=t??{},i=t?.semantic!==!1,s=new v(e).fileDependencyGraph(n),a=Ry(e,n);return xy([...yy(e,s,a,{semantic:i}),...by(s),...Sy(s,r)])}function yy(e,t,n,r){let i=[];for(let[o,s]of t){if(Fe(o))continue;let a=n.get(o)??new Set;for(let c of s)if(!Fe(c)&&!a.has(c)){if(r.semantic&&Ey(e,o,c)||wy(e,o,c)||ky(e,o,c)||Ly(c)||Ty(e,o,c)||Py(c))continue;i.push({file:o,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c})}}return i}function by(e){let t=[],n=Ny(e);for(let[r,i]of e){if(Fe(r))continue;let o=bt(r);for(let s of i){if(Fe(s))continue;let a=bt(s);if(o===a)continue;(vo(o,a)??n.get(`${o}->${a}`))==="violation"&&t.push({file:r,kind:"layer-violation",description:`Imports from ${a}/ (${s}) \u2014 may cross architectural boundary`,dep:s,detail:`${o}/ should not depend on ${a}/`})}}return t}function Sy(e,t){let n=[];for(let[r,i]of Cy(e)){let o=i.filter(a=>!Fe(a));if(o.length<t)continue;let s=Iy(e,o);for(let a of o)for(let c of e.get(a)??[])Fe(c)||(s.get(c)??0)===1&&Dn.dirname(c)!==r&&Dn.dirname(c)!==Dn.dirname(r)&&(tl(a,c)||n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${c}`,dep:c}))}return n}function xy(e){return{results:e,unusedImports:e.filter(t=>t.kind==="unused-import").length,layerViolations:e.filter(t=>t.kind==="layer-violation").length,patternDeviations:e.filter(t=>t.kind==="pattern-deviation").length}}function Cy(e){let t=new Map;for(let n of e.keys()){let r=Dn.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function Iy(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])Fe(i)||n.set(i,(n.get(i)??0)+1);return n}function Ry(e,t){let n=new Map;return _y(e,n,t),Dy(e,n),n}function _y(e,t,n){for(let r of vy(e,n))nl(e,t,r.from_file,r.to_file)}function vy(e,t){let n=t?`AND d1.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
865
564
  FROM mentions m
866
565
  JOIN chunks c ON m.chunk_id = c.id
867
566
  JOIN documents d1 ON c.document_id = d1.id
@@ -877,25 +576,24 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
877
576
  WHERE d1.id != d2.id
878
577
  AND m.role != 1
879
578
  ${e.pathExclusionsFor("d1","d2")}
880
- ${n}`)}function aS(e,t){let n=new N(e),r=e.all(`SELECT relative_path FROM documents
881
- WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`);n.scanSourceReferences({paths:r.map(i=>i.relative_path),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||pl(e,t,i.sourceFile,i.target.relativePath))})}function pl(e,t,n,r){if(e.isIgnored(n)||e.isIgnored(r))return;let i=t.get(n);i||(i=new Set,t.set(n,i)),i.add(r)}function lS(e){let t=new Map;for(let[r,i]of e){if(Ee(r))continue;let s=Ze(r);for(let o of i){if(Ee(o))continue;let a=Ze(o);if(s===a||ii(s,a))continue;let l=`${s}->${a}`;t.set(l,(t.get(l)??0)+1)}}let n=new Map;for(let[r,i]of t)n.set(r,i<=2?"violation":"ok");return n}function cS(e){return e.includes("types")||e.endsWith(".d.ts")}function uS(e,t,n){let r=Lt(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function dS(e,t,n){let r=q(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function mS(e,t,n){let r=q(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function fS(e){return e.endsWith(".vue")}function pS(e,t,n){let r=q(e,t).filter(i=>i.sourcePath===n);return r.length===0?!1:r.every(i=>i.kind==="side-effect"||i.kind==="namespace"&&i.usedMembers.length===0&&!i.used)}function Ee(e){let t=ne(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||gS($t.basename(e)))}function gS(e){return!!(e==="index.ts"||e==="index.js"||e==="cli.ts"||e==="main.ts"||e==="main.rs"||e.includes("worker.")||e.includes("postinstall.")||e==="health.ts"||e==="health.js")}import{basename as jt,extname as $n}from"path";function jn(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:s}=t??{},o=new N(e),a=CS(o.fileDependencyGraph(n)),l=NS(yS(o,n,r).sort((d,m)=>si(d)-si(m)||d.relativePath.localeCompare(m.relativePath)),s),c=RS(o.crossFileCallerMap(l,{semantic:t?.semantic!==!1}),o.sourceFallbackCallerFiles(l)),u=[];for(let d of l){let m=hS(e,o,d,{callerFileMap:c,reverseFanIn:a});m&&u.push(m)}return u.sort((d,m)=>m.callerFanIn-d.callerFanIn||m.loc-d.loc),u.slice(0,i)}function hS(e,t,n,r){let i=bS(t,n,r.callerFileMap);if(i.length!==1)return null;let s=i[0],o=SS(e,n.symbolId,s);if(!o)return null;let a=xS(t,e,s,n.symbol,o);if(a&&Oe(a.symbol))return null;let l=_S(r.callerFileMap,r.reverseFanIn,s,a);return l<=3?null:{symbol:n.symbol,shortName:y(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:si(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?y(a.symbol):jt(s),callerFanIn:l}}function si(e){return e.endLine-e.startLine+1}function yS(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:2,maxLoc:n,requireFunctionLikeSymbol:!0})}function bS(e,t,n){let r=jt(t.relativePath,$n(t.relativePath));return[...n.get(t.symbolId)??[]].filter(i=>i!==t.relativePath).filter(i=>jt(i,$n(i))!==r).filter(i=>{let s=e.fileKind(i);return s!=="barrel"&&s!=="entry"&&s!=="test"})}function SS(e,t,n){return e.get(`SELECT c.start_line, c.end_line
579
+ ${n}`)}function Dy(e,t){new v(e).scanSourceReferences({paths:k(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},r=>{r.target.relativePath!==r.sourceFile&&(e.isIgnored(r.target.relativePath)||nl(e,t,r.sourceFile,r.target.relativePath))})}function nl(e,t,n,r){if(e.isIgnored(n)||e.isIgnored(r))return;let i=t.get(n);i||(i=new Set,t.set(n,i)),i.add(r)}function Ny(e){let t=new Map;for(let[r,i]of e){if(Fe(r))continue;let o=bt(r);for(let s of i){if(Fe(s))continue;let a=bt(s);if(o===a||vo(o,a))continue;let c=`${o}->${a}`;t.set(c,(t.get(c)??0)+1)}}let n=new Map;for(let[r,i]of t)n.set(r,i<=2?"violation":"ok");return n}function Ly(e){return e.includes("types")||e.endsWith(".d.ts")}function Ey(e,t,n){let r=gn(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function wy(e,t,n){let r=Y(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function ky(e,t,n){let r=Y(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function Py(e){return e.endsWith(".vue")}function Ty(e,t,n){let r=Y(e,t).filter(i=>i.sourcePath===n);return r.length===0?!1:r.every(i=>i.kind==="side-effect"||i.kind==="namespace"&&i.usedMembers.length===0&&!i.used)}function Fe(e){let t=ue(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||My(Dn.basename(e)))}function My(e){return!!(e==="index.ts"||e==="index.js"||e==="cli.ts"||e==="main.ts"||e==="main.rs"||e.includes("worker.")||e.includes("postinstall.")||e==="health.ts"||e==="health.js")}import{basename as En,extname as Rr}from"path";function Ut(e){let t=e.orderCandidates?[...e.candidates()].sort(e.orderCandidates):e.candidates(),n=ne(t,e.scanLimit),r=e.prepare?.(n)??void 0,i=[];for(let o of n){let s=e.evaluate(o,r);s&&i.push(s)}return e.orderResults&&i.sort(e.orderResults),typeof e.limit=="number"?i.slice(0,e.limit):i}var rl=H("definition-consumer-file-usage");function Ln(e,t,n){return e.callerFileMap(t,{semantic:n.semantic,sourceFallback:n.sourceFallback})}function Ir(e,t,n){let r=[],i=0,o=0,s=L(t.symbol);for(let a of n)Fy(e,a,t.relativePath,s)?i++:Do(e,a,s)?o++:r.push(a);return{realConsumers:r,barrelConsumers:i,importOnlyConsumers:o}}function Do(e,t,n){if(!n)return!1;let r=P(t);if(!r)return!1;let i=rl.get(e,t,()=>Oy(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function il(e){rl.invalidateAll(e)}function Oy(e,t,n){let r=new Set,i=new Set,o=B(e,t);if(!o)return{importedLeaves:r,usedLeaves:i};let s=n==="rust"?new Set(["use_declaration"]):n==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),a=(c,l)=>{let u=l||s.has(c.type);(c.type==="identifier"||c.type==="type_identifier"||c.type==="property_identifier"||c.type==="field_identifier")&&(u?r.add(c.text):i.add(c.text));for(let m of c.children)a(m,u)};return a(o.rootNode,!1),{importedLeaves:r,usedLeaves:i}}function Fy(e,t,n,r){if(!r)return!1;let i=T(e,t);if(!i)return!1;let o=ma(e,t);if(o.length===0)return!1;let s=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`\\b${s}\\b`),c=i.split(`
580
+ `),l=0;for(let u=0;u<c.length;u++){if(!a.test(c[u]??""))continue;if(l++,!o.find(d=>d.startLine<=u&&u<=d.endLine))return!1}return l>0}function wn(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new v(e),a=qy(s.fileDependencyGraph(n));return Ut({candidates:()=>$y(s,n,r),orderCandidates:hr,scanLimit:o,prepare:c=>({callerFileMap:Ln(s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>Ay(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function Ay(e,t,n,r){let i=jy(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=By(e,n.symbolId,o);if(!s)return null;let a=Hy(t,e,o,n.symbol,s);if(a&&qe(a.symbol))return null;let c=Wy(r.callerFileMap,r.reverseFanIn,o,a);return c<=3?null:{symbol:n.symbol,shortName:h(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:j(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?h(a.symbol):En(o),callerFanIn:c}}function $y(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:2,maxLoc:n,requireFunctionLikeSymbol:!0})}function jy(e,t,n,r){let i=En(n.relativePath,Rr(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>En(s,Rr(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return Ir(e,n,o).realConsumers}function By(e,t,n){return e.get(`SELECT c.start_line, c.end_line
882
581
  FROM mentions m
883
582
  JOIN chunks c ON m.chunk_id = c.id
884
583
  JOIN documents d ON c.document_id = d.id
885
584
  WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
886
- LIMIT 1`,t,n)}function xS(e,t,n,r,i){let s=e.definitionsForFile(n),o=IS(t,n,r,i.start_line,i.end_line);return le(s,o)}function _S(e,t,n,r){if(r?.isFunctionLike){let i=[...e.get(r.symbolId)??[]].filter(s=>s!==r.relativePath);if(i.length>0)return i.length}return vS(t,n)}function IS(e,t,n,r,i){let s=k(n);if(!s)return r;let o=Ie(e,t).get(s);if(!o||o.length===0)return r;for(let a of o)if(a>=r&&a<=i)return a;return r}function RS(...e){let t=new Map;for(let n of e)for(let[r,i]of n){let s=t.get(r);s||(s=new Set,t.set(r,s));for(let o of i)s.add(o)}return t}function CS(e){let t=new Map;for(let[n,r]of e){t.has(n)||t.set(n,t.get(n)??0);for(let i of r)t.set(i,(t.get(i)??0)+1)}return t}function vS(e,t){let n=e.get(t)??0;if(n>0)return n;let r=jt(t,$n(t)),i=0;for(let[s,o]of e)s!==t&&jt(s,$n(s))===r&&o>i&&(i=o);return i}function NS(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function hl(e,t,n,r){let i=F(t);if(!i)return!0;let s=O(e,t);if(!s)return!0;let o=gl.get(s);return o||(o=ES(s,i),gl.set(s,o)),o.get(`${n}:${r}`)??!0}var gl=new WeakMap;function ES(e,t){let n=t==="rust"?new Set(["function_item","function_signature_item"]):t==="python"?new Set(["function_definition"]):new Set(["function_declaration","method_definition","arrow_function","function_expression"]),r=new Map,i=s=>{n.has(s.type)&&r.set(`${s.startPosition.row}:${s.endPosition.row}`,DS(s,t));for(let o of s.children)i(o)};return i(e.rootNode),r}function DS(e,t){let n=e.namedChildren.find(d=>d.type==="block"||d.type==="statement_block");if(!n)return!1;let r=n.namedChildren.filter(d=>d.type!=="comment"&&d.type!=="line_comment"&&d.type!=="block_comment");if(r.length!==1)return!1;let i=r[0],s=null;if(i.type==="return_statement"||i.type==="expression_statement"?s=i.namedChild(0)??null:t==="rust"&&(i.type==="call_expression"||i.type==="macro_invocation")&&(s=i),!s)return!1;let o=t==="python"?"call":"call_expression";if(s.type!==o)return!1;let a=s.namedChildren.find(d=>d.type==="arguments"||d.type==="argument_list");if(!a)return!1;let l=a.namedChildren.filter(d=>d.type!=="comment"),c=e.namedChildren.find(d=>d.type==="parameters"||d.type==="formal_parameters");if(!c)return!1;let u=[];for(let d of c.namedChildren)if(d.type==="identifier")u.push(d.text);else{let m=d.namedChildren.find(f=>f.type==="identifier");m&&u.push(m.text)}if(l.length!==u.length)return!1;for(let d=0;d<u.length;d+=1){let m=l[d];if(m.type!=="identifier"||m.text!==u[d])return!1}return!0}function Bn(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:s}=t??{},o=new N(e),a=PS(kS(o,n,r).sort((u,d)=>oi(u)-oi(d)||u.relativePath.localeCompare(d.relativePath)),s),l=o.calleeMap(a,{semantic:t?.semantic!==!1}),c=[];for(let u of a){let d=LS(e,u,l.get(u.symbolId)??[]);d&&c.push(d)}return c.sort((u,d)=>u.loc-d.loc||u.file.localeCompare(d.file)),c.slice(0,i)}function LS(e,t,n){let r=wS(n);if(r.size!==1||!hl(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0];return{symbol:t.symbol,shortName:y(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:oi(t),forwardsTo:i.symbol,forwardsToShort:y(i.symbol),forwardsToFile:i.file}}function wS(e){let t=e.some(r=>U(r.symbol))?e.filter(r=>U(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function kS(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:3,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0})}function oi(e){return e.endLine-e.startLine+1}function PS(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Hn(e,t){let{scope:n,minLoc:r=3,maxLoc:i=80,limit:s=30,includeLowConfidence:o=!1,scanLimit:a}=t??{},l=t?.semantic!==!1,c=new N(e),u=c.scopedDefinitions(n),d=VS(c,n),m=YS(MS(e,c,u,{minLoc:r,maxLoc:i}).sort((_,P)=>Bt(P)-Bt(_)||_.relativePath.localeCompare(P.relativePath)),a),f=OS(c,m,{semantic:l}),h=$S(e,c,u,m,{semantic:l}),p=TS(m);return FS(e,m,f,p).filter(_=>!h.has(_.definition.symbolId)).filter(_=>!_.transitivelyReachable).filter(_=>_.realConsumers.length<=1).filter(_=>!(_.realConsumers.length===0&&_.barrelConsumers>0)).filter(_=>qS(_.definition,_.realConsumers.length,d)).map(_=>AS(e,_)).filter(_=>o||_.confidence!=="low").sort((_,P)=>{let L={high:0,medium:1,low:2};return L[_.confidence]-L[P.confidence]||P.loc-_.loc||_.file.localeCompare(P.file)||_.startLine-P.startLine}).slice(0,s)}function MS(e,t,n,r){return n.filter(i=>i.isTypeLike&&Bt(i)>=r.minLoc).filter(i=>Bt(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>!JS(i.symbol)).filter(i=>!t.hasSuppressionComment(i))}function OS(e,t,n){return Rl(e.crossFileCallerMap(t,{semantic:n.semantic}),e.sourceFallbackCallerFiles(t))}function TS(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);r||(r=new Map,t.set(n.relativePath,r));let i=k(n.symbol);i&&r.set(i,n)}return t}function FS(e,t,n,r){return t.map(i=>{let o=[...n.get(i.symbolId)??new Set].filter(u=>u!==i.relativePath&&!e.isIgnored(u)),{realConsumers:a,barrelConsumers:l}=zS(e,i.relativePath,i.symbol,o),c=GS(e,i,n,r);return{definition:i,realConsumers:a,barrelConsumers:l,transitivelyReachable:c}})}function AS(e,t){let n=Il(e,t.definition.relativePath,t.definition.startLine),r=bl(t.definition.relativePath)?!0:XS(e,t.definition),{confidence:i,reason:s}=ZS(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:y(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:Bt(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:s}}function $S(e,t,n,r,i){let s=BS(e,jS(n),r),o=s.map(c=>c.singleton);if(s.length===0)return new Set;let a=Rl(t.crossFileCallerMap(o,{semantic:i.semantic}),t.sourceFallbackCallerFiles(o)),l=new Set;for(let{singleton:c,classId:u}of s)WS(e,c,a)&&l.add(u);return l}function jS(e){let t=new Map;for(let n of e){let r=k(n.symbol);r&&t.set(yl(n.relativePath,r),n)}return t}function BS(e,t,n){let r=[];for(let i of n){let s=HS(e,t,i);s&&r.push({singleton:s,classId:i.symbolId})}return r}function HS(e,t,n){if(Il(e,n.relativePath,n.startLine)!=="class")return null;let r=k(n.symbol);if(!r)return null;let i=US(e,n.relativePath,r);return i?t.get(yl(n.relativePath,i))??null:null}function WS(e,t,n){let r=k(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(s=>s!==t.relativePath&&!e.isIgnored(s)&&!xl(e,s,r))}function yl(e,t){return`${e}\0${t}`}function US(e,t,n){let r=M(e,t);if(!r)return null;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${i}\\s*\\(`);return r.match(s)?.[1]??null}function VS(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function JS(e){let t=V(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let r=n[n.length-1],i=n[n.length-2];return r?.suffix==="type"&&i?.suffix==="type"}function bl(e){let n=(e.split("/").pop()??"").replace(/\.[^.]+$/,"");return!!(n==="types"||n==="models"||n==="schema"||n==="common"||n==="protocol"||n==="proto"||n==="dto"||n==="mod"||/(^|\/)types(\/|\.)/.test(e)||/(^|\/)models?(\/|\.)/.test(e)||/(^|\/)proto(?:col)?(\/|\.)/.test(e)||/(^|\/)schema(\/|\.)/.test(e))}function qS(e,t,n){return!(bl(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function zS(e,t,n,r){let i=[],s=0,o=k(n);for(let a of r)QS(e,a,t,o)||xl(e,a,o)?s++:i.push(a);return{realConsumers:i,barrelConsumers:s}}function GS(e,t,n,r){let i=Ds(e,t.relativePath),s=k(t.symbol);if(!s)return!1;let o=i.get(s);if(!o||o.size===0)return!1;let a=r.get(t.relativePath);if(!a)return!1;for(let l of o){let c=a.get(l);if(!c)continue;let u=n.get(c.symbolId);if(u){for(let d of u)if(d!==t.relativePath&&!e.isIgnored(d))return!0}}return!1}var Sl=j("stale-abs-file-usage");function xl(e,t,n){if(!n)return!1;let r=F(t);if(!r)return!1;let i=Sl.get(e,t,()=>KS(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function KS(e,t,n){let r=new Set,i=new Set,s=O(e,t);if(!s)return{importedLeaves:r,usedLeaves:i};let o=n==="rust"?new Set(["use_declaration"]):n==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),a=(l,c)=>{let u=c||o.has(l.type);(l.type==="identifier"||l.type==="type_identifier"||l.type==="property_identifier"||l.type==="field_identifier")&&(u?r.add(l.text):i.add(l.text));for(let d of l.children)a(d,u)};return a(s.rootNode,!1),{importedLeaves:r,usedLeaves:i}}function YS(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function _l(e){Sl.invalidateAll(e)}function QS(e,t,n,r){if(!r)return!1;let i=M(e,t);if(!i)return!1;let s=Mo(e,t);if(s.length===0)return!1;let o=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`\\b${o}\\b`),l=i.split(`
887
- `),c=0;for(let u=0;u<l.length;u++){if(!a.test(l[u]??""))continue;if(c++,!s.find(m=>m.startLine<=u&&u<=m.endLine))return!1}return c>0}function Il(e,t,n){let r=M(e,t);if(!r)return"other";let i=r.split(`
888
- `),s=Math.max(0,n-2),o=Math.min(i.length-1,n+2);for(let a=s;a<=o;a++){let c=(i[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(c))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(c))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(c))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(c))return"enum"}return"other"}function XS(e,t){let n=M(e,t.relativePath);if(!n)return!1;let r=k(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`),o=n.split(`
889
- `);for(let a=0;a<o.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&s.test(o[a]??""))return!0;return!1}function ZS(e,t,n){return e===0?{confidence:"high",reason:"unused \u2014 no consumers and defining file has no real usage"}:e===1&&t==="class"?{confidence:"low",reason:"1 consumer + class kind \u2014 likely 1:1 encapsulation, not over-abstraction"}:e===1&&!n?{confidence:"high",reason:"1 consumer + defining file never uses it \u2014 type belongs with its consumer"}:{confidence:"medium",reason:"1 consumer \u2014 single-use abstraction"}}function Bt(e){return e.endLine-e.startLine+1}function Rl(...e){let t=new Map;for(let n of e)for(let[r,i]of n){let s=t.get(r);s||(s=new Set,t.set(r,s));for(let o of i)s.add(o)}return t}function Wn(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:s}=t??{},{definitions:o,callerMap:a,calleeMap:l}=ex(e,n,s,t?.semantic!==!1);return o.map(c=>{let u=c.endLine-c.startLine+1,d=a.get(c.symbolId)?.size??0,m=l.get(c.symbolId)??[],f=m.filter(g=>g.file!==c.relativePath),h=new Set(f.map(g=>`${g.symbol}|${g.file}`)).size,p=new Set(m.map(g=>`${g.symbol}|${g.file}`)).size;return{symbol:c.symbol,shortName:y(c.symbol),file:c.relativePath,startLine:c.startLine,endLine:c.endLine,loc:u,fanIn:d,fanOut:h,calleeCount:p,score:Math.round(u/50*(d/5)*Math.max(h/5,1)*100)/100}}).filter(c=>c.loc>=r).sort((c,u)=>u.score-c.score||u.loc-c.loc).slice(0,i)}function ex(e,t,n,r){let i=new N(e),s=tx(i.productionCallableDefinitions({scope:t,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof n=="number"&&n>0}),n);return{definitions:s,callerMap:i.crossFileCallerMap(s,{semantic:r}),calleeMap:i.calleeMap(s,{semantic:r})}}function tx(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}import{getHeapStatistics as nx}from"v8";var rx=64*1024*1024;function ai(e,t={}){Go(e),t.semanticProvider===!0&&qr(e),to(e),Oo(e),Ys(e),Cs(e),ps(e)}function li(){let e=globalThis.gc;if(!e)return;let t=nx();t.heap_size_limit-t.used_heap_size<rx||e()}var ix=50,sx=75e3,ox=5e3,Cl=2500,vl=["overview","dead","isolated","cycles","similar","extract-candidates","wrapper-candidates","passthrough-candidates","stale-abstractions","drift","complexity-hotspots"],ax={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:kl(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:Pl(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:Ml(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:Ol(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:Tl(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:Fl(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:Al(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:$l(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:jl(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:Bl(e,t,n)})};function Nl(e,t={}){return Dl(e,t.full===!0,(n,r)=>{let i=lx(e,t.scope,n,r);return wl(i)})}function El(e,t,n={}){return Dl(e,n.full===!0,(r,i)=>ax[t](e,n.scope,i,r))}function Dl(e,t,n){let r=sn(e),i=px(r,t);try{return n(r,i)}finally{ai(e,{semanticProvider:!0}),li()}}function Ll(e){let t=fe(e,"overview"),n={statsResult:t.statsResult,warnings:t.warnings,dead:fe(e,"dead").dead,isolated:fe(e,"isolated").isolated,realCycleCount:fe(e,"cycles").realCycleCount,similarCount:fe(e,"similar").similarCount,extractCount:fe(e,"extract-candidates").extractCount,wrappers:fe(e,"wrapper-candidates").wrappers,passthroughs:fe(e,"passthrough-candidates").passthroughs,stale:fe(e,"stale-abstractions").stale,drift:fe(e,"drift").drift,complexity:fe(e,"complexity-hotspots").complexity};return wl(n)}function fe(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function wl(e){let t=mx(e);return{score:fx(e),overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.loc,isolatedSymbols:e.isolated.count,isolatedLoc:e.isolated.loc,cycles:e.realCycleCount,similarPairs:e.similarCount,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount},actions:t,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0}}function lx(e,t,n,r){let i=cx(e,t,r),s=ux(e,t,r),o=dx(e,t,r);return{statsResult:n,warnings:r.warnings,...i,...s,...o}}function cx(e,t,n){return{dead:kl(e,t,n),isolated:Pl(e,t,n),realCycleCount:Ml(e,t,n)}}function ux(e,t,n){return{similarCount:Ol(e,t,n),extractCount:Tl(e,t,n),wrappers:Fl(e,t,n),passthroughs:Al(e,t,n),stale:$l(e,t,n)}}function dx(e,t,n){return{drift:jl(e,t,n),complexity:Bl(e,t,n)}}function kl(e,t,n){return be(e,n,"dead",()=>{let r=kn(e,{scope:t,minLoc:3,skipBarrels:!0,deadCodeOnly:!0,scanLimit:n.candidateScanLimit,semantic:!1});return Un(yx(e,r.symbols))})}function Pl(e,t,n){return be(e,n,"isolated",()=>{let r=Mn(e,{scope:t,minLoc:3,scanLimit:n.candidateScanLimit,semantic:!1});return Un(bx(e,r))})}function Ml(e,t,n){return be(e,n,"cycles",()=>Pn(e,{scope:t}).filter(i=>i.kind==="real").length)}function Ol(e,t,n){return be(e,n,"similar",()=>On(e,{scope:t,minSimilarity:.6,limit:50,minCallees:4,scanLimit:n.candidateScanLimit,semantic:!1}).length)}function Tl(e,t,n){return be(e,n,"extract-candidates",()=>Tn(e,{scope:t,minLoc:15,minCallees:5,limit:50,scanLimit:n.candidateScanLimit,semantic:!1}).length)}function Fl(e,t,n){return be(e,n,"wrapper-candidates",()=>Un(jn(e,{scope:t,maxLoc:15,limit:50,scanLimit:n.candidateScanLimit,semantic:!1})))}function Al(e,t,n){return be(e,n,"passthrough-candidates",()=>Un(Bn(e,{scope:t,maxLoc:15,limit:50,scanLimit:n.candidateScanLimit,semantic:!1})))}function $l(e,t,n){return be(e,n,"stale-abstractions",()=>{let r=Hn(e,{scope:t,minLoc:3,limit:50,scanLimit:n.candidateScanLimit,semantic:!1}),i=r.filter(s=>s.consumers===0).length;return{count:r.length,loc:r.reduce((s,o)=>s+o.loc,0),unused:i,singleUse:r.length-i}})}function jl(e,t,n){return be(e,n,"drift",()=>{let r=An(e,{scope:t,semantic:!1});return{count:r.unusedImports+r.layerViolations,unusedImports:r.unusedImports,layerViolations:r.layerViolations}})}function Bl(e,t,n){return be(e,n,"complexity-hotspots",()=>{let r=Wn(e,{scope:t,minLoc:10,limit:10,scanLimit:n.candidateScanLimit,semantic:!1});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score})),extremeCount:r.filter(i=>i.score>ix).length}})}function mx(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",description:`${e.dead.count} symbols with zero references anywhere \u2014 safe to delete`,effort:"low",impact:"high",count:e.dead.count,locRecoverable:e.dead.loc}),e.isolated.count>0&&t.push({category:"Isolated symbols",description:`${e.isolated.count} symbols completely disconnected from the codebase graph`,effort:"low",impact:"medium",count:e.isolated.count,locRecoverable:e.isolated.loc}),e.realCycleCount>0&&t.push({category:"Circular dependencies",description:`${e.realCycleCount} cycle(s) \u2014 break with dependency inversion or module restructuring`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",description:`${e.similarCount} pairs with real logic overlap (beyond shared imports) \u2014 consolidation candidates`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.extractCount>0&&t.push({category:"Extraction candidates",description:`${e.extractCount} large functions with isolated callee clusters \u2014 extract method opportunities`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",description:`${e.wrappers.count} single-consumer symbols that could be inlined`,effort:"low",impact:"low",count:e.wrappers.count,locRecoverable:e.wrappers.loc}),e.passthroughs.count>0&&t.push({category:"Passthrough functions",description:`${e.passthroughs.count} functions that just forward to one callee \u2014 unnecessary indirection`,effort:"low",impact:"low",count:e.passthroughs.count,locRecoverable:e.passthroughs.loc}),e.stale.count>0){let i=[];e.stale.unused>0&&i.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&i.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",description:`${i.join(", ")} \u2014 premature abstraction`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let i=[];e.drift.unusedImports>0&&i.push(`${e.drift.unusedImports} unused imports`),e.drift.layerViolations>0&&i.push(`${e.drift.layerViolations} layer violations`),t.push({category:"Structural drift",description:i.join(", "),effort:e.drift.layerViolations>0?"medium":"low",impact:e.drift.layerViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}let n={high:3,medium:2,low:1},r={low:3,medium:2,high:1};return t.sort((i,s)=>{let o=n[i.impact]*r[i.effort];return n[s.impact]*r[s.effort]-o}),t}function fx(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=100,i=e.dead.count/n;r-=Math.min(20,Math.round(i*200));let s=e.isolated.count/n;r-=Math.min(10,Math.round(s*200)),r-=Math.min(15,e.realCycleCount*5);let o=e.similarCount/n*1e3;r-=Math.min(10,Math.round(o));let a=e.extractCount/n*1e3;r-=Math.min(5,Math.round(a/2)),r-=Math.min(3,e.wrappers.count),r-=Math.min(3,e.passthroughs.count);let l=e.stale.count/Math.max(n*.1,1);r-=Math.min(8,Math.round(l*10));let c=e.drift.count/t;return r-=Math.min(5,Math.round(c*50)),r-=Math.min(5,e.complexity.extremeCount*2),Math.max(0,Math.min(100,r))}function px(e,t){return e.symbols>=sx||e.documents>=ox?t?{candidateScanLimit:void 0,releaseCachesBetweenPhases:!0,warnings:["Large index detected; running unbounded health analyses because --full was supplied."]}:{candidateScanLimit:Cl,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${Cl} symbols. Run "scip-query health --full" for unbounded candidate counts.`]}:{candidateScanLimit:void 0,releaseCachesBetweenPhases:!0,warnings:[]}}function gx(e,t){t.releaseCachesBetweenPhases&&(_l(e),ai(e),li())}function be(e,t,n,r){hx(n);try{return r()}finally{gx(e,t)}}function hx(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function yx(e,t){return t.filter(n=>!Xe(e,n.relativePath)&&!Mt(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function bx(e,t){return t.filter(n=>!Xe(e,n.relativePath)&&!Mt(e,n.symbol,n.relativePath))}function Un(e){return{count:e.length,loc:e.reduce((t,n)=>t+n.loc,0)}}function Hl(e,t,n,r={}){let i=w(e,t),s=w(e,n);if(!i||!s)return null;let o=new Set(te(e,i,{semantic:r.semantic}).map(g=>g.symbol)),a=new Set(te(e,s,{semantic:r.semantic}).map(g=>g.symbol)),l=[];for(let g of o)a.has(g)&&l.push(g);let c=[];for(let g of o)a.has(g)||c.push(g);let u=[];for(let g of a)o.has(g)||u.push(g);let d=new Set([...o,...a]),m=d.size>0?l.length/d.size:0,f;d.size===0?f="Neither function calls other tracked symbols. There is no callee-pattern evidence for consolidation; inspect the source bodies directly.":l.length===0?f="These functions do not share any callees. They are not a callee-based consolidation candidate.":c.length===0&&u.length===0?f="These functions have identical tracked callee sets. They are a strong structural match, but identical callees do not prove interchangeable semantics; inspect signatures, control flow, and return values before consolidating.":c.length===0?f="A's tracked callees are a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic before replacing A with B.":u.length===0?f="B's tracked callees are a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic before replacing B with A.":c.length<=2&&u.length<=2?f=`Create a shared function with the ${l.length} common callees. Pass the ${c.length+u.length} divergent callees as parameters or strategy callbacks.`:f=`Extract the ${l.length} shared callees into a common helper. Each function calls the helper plus its own unique logic (${c.length} callees in A, ${u.length} in B).`;let h=i.endLine-i.startLine+1,p=s.endLine-s.startLine+1;return{symbolA:{symbol:i.symbol,shortName:y(i.symbol),file:i.relativePath,loc:h},symbolB:{symbol:s.symbol,shortName:y(s.symbol),file:s.relativePath,loc:p},similarity:m,sharedCallees:l.map(y),uniqueToA:c.map(y),uniqueToB:u.map(y),consolidationStrategy:f}}import{readFileSync as Wl}from"fs";import{extname as Sx,join as Ul}from"path";function Vl(e,t,n={}){let{context:r=0}=n,i=xx(t);if(i)return Ix(e,i.filePath,i.startLine,i.endLine,r);let s=w(e,t);return s?_x(e,s,r):null}function xx(e){let t=e.match(/^(.+\.\w+):(\d+)-(\d+)$/);return t?{filePath:t[1],startLine:parseInt(t[2],10),endLine:parseInt(t[3],10)}:null}function _x(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=Ul(e.config.projectRoot,t.relativePath),s;try{s=Wl(i,"utf-8")}catch{return null}let o=s.split(`
890
- `),a=Math.max(0,t.startLine-n),l=Math.min(o.length-1,t.endLine+n),c=o.slice(a,l+1).join(`
891
- `);return{symbol:t.symbol,shortName:y(t.symbol),relativePath:t.relativePath,startLine:a,endLine:l,language:r?.language??Jl(t.relativePath),source:c}}function Ix(e,t,n,r,i){let s=Q(e,t);if(!s)return null;let o=e.get("SELECT relative_path, language FROM documents WHERE relative_path = ?",s);if(!o)return null;let a=Ul(e.config.projectRoot,o.relative_path),l;try{l=Wl(a,"utf-8")}catch{return null}let c=l.split(`
892
- `),u=Math.max(0,n-1-i),d=Math.min(c.length-1,r-1+i),m=c.slice(u,d+1).join(`
893
- `);return{symbol:`${o.relative_path}:${n}-${r}`,shortName:`${o.relative_path}:${n}-${r}`,relativePath:o.relative_path,startLine:u,endLine:d,language:o.language??Jl(o.relative_path),source:m}}function Jl(e){switch(Sx(e).toLowerCase()){case".ts":case".tsx":case".mts":case".cts":return"typescript";case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".py":case".pyi":return"python";case".rs":return"rust";case".go":return"go";case".java":return"java";case".kt":case".kts":return"kotlin";case".scala":return"scala";case".rb":return"ruby";case".php":return"php";case".cs":return"csharp";case".vb":return"vb";case".dart":return"dart";case".c":case".h":return"c";case".cc":case".cpp":case".cxx":case".hpp":case".hh":case".hxx":return"cpp";case".vue":return"vue";default:return null}}import{readFileSync as Rx}from"fs";import{join as Cx}from"path";function ql(e,t,n={}){let r=w(e,t);if(!r)return null;let i=new N(e),s=Lx(Nx(e,r.relativePath,r.startLine,r.endLine),vx(e,r.relativePath)),o=r.endLine-r.startLine+1,l=i.calleeMap([r],{additive:!0,semantic:n.semantic}).get(r.symbolId)??[],c=new Set(l.map(u=>u.symbol));return{symbol:r.symbol,shortName:y(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:o,branches:s,cyclomaticEstimate:s+1,calleeCount:c.size,fanIn:Ex(e,r.symbolId),fanOut:Dx(l,r.relativePath)}}function vx(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function Nx(e,t,n,r){try{return Rx(Cx(e.config.projectRoot,t),"utf-8").split(`
585
+ LIMIT 1`,t,n)}function Hy(e,t,n,r,i){let o=e.definitionsForFile(n),s=Vy(t,n,r,i.start_line,i.end_line);return de(o,s)}function Wy(e,t,n,r){if(r?.isFunctionLike){let i=[...e.get(r.symbolId)??[]].filter(o=>o!==r.relativePath);if(i.length>0)return i.length}return Uy(t,n)}function Vy(e,t,n,r,i){let o=L(n);if(!o)return r;let s=ht(e,t).get(o);if(!s||s.length===0)return r;for(let a of s)if(a>=r&&a<=i)return a;return r}function qy(e){let t=new Map;for(let[n,r]of e){t.has(n)||t.set(n,t.get(n)??0);for(let i of r)t.set(i,(t.get(i)??0)+1)}return t}function Uy(e,t){let n=e.get(t)??0;if(n>0)return n;let r=En(t,Rr(t)),i=0;for(let[o,s]of e)o!==t&&En(o,Rr(o))===r&&s>i&&(i=s);return i}function sl(e,t,n,r){let i=P(t);if(!i)return!0;let o=B(e,t);if(!o)return!0;let s=ol.get(o);return s||(s=Jy(o,i),ol.set(o,s)),s.get(`${n}:${r}`)??!0}var ol=new WeakMap;function Jy(e,t){let n=en(t),r=new Map,i=o=>{n.has(o.type)&&r.set(`${o.startPosition.row}:${o.endPosition.row}`,zy(o,t));for(let s of o.children)i(s)};return i(e.rootNode),r}function zy(e,t){let n=e.namedChildren.find(m=>m.type==="block"||m.type==="statement_block");if(!n)return!1;let r=n.namedChildren.filter(m=>m.type!=="comment"&&m.type!=="line_comment"&&m.type!=="block_comment");if(r.length!==1)return!1;let i=r[0],o=null;if(i.type==="return_statement"||i.type==="expression_statement"?o=i.namedChild(0)??null:t==="rust"&&(i.type==="call_expression"||i.type==="macro_invocation")&&(o=i),!o)return!1;let s=t==="python"?"call":"call_expression";if(o.type!==s)return!1;let a=o.namedChildren.find(m=>m.type==="arguments"||m.type==="argument_list");if(!a)return!1;let c=a.namedChildren.filter(m=>m.type!=="comment"),l=e.namedChildren.find(m=>m.type==="parameters"||m.type==="formal_parameters");if(!l)return!1;let u=[];for(let m of l.namedChildren)if(m.type==="identifier")u.push(m.text);else{let d=m.namedChildren.find(p=>p.type==="identifier");d&&u.push(d.text)}if(c.length!==u.length)return!1;for(let m=0;m<u.length;m+=1){let d=c[m];if(d.type!=="identifier"||d.text!==u[m])return!1}return!0}function kn(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new v(e);return Ut({candidates:()=>Qy(s,n,r),orderCandidates:hr,scanLimit:o,prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>Gy(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function Gy(e,t,n){let r=Ky(n);if(r.size!==1||!sl(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0];return{symbol:t.symbol,shortName:h(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:j(t),forwardsTo:i.symbol,forwardsToShort:h(i.symbol),forwardsToFile:i.file}}function Ky(e){let t=e.some(r=>K(r.symbol))?e.filter(r=>K(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function Qy(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:3,maxLoc:n,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0})}function Pn(e,t){let{scope:n,minLoc:r=3,maxLoc:i=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},c=t?.semantic!==!1,l=new v(e),u=l.scopedDefinitions(n),m=cb(l,n),d=ne(Yy(e,l,u,{minLoc:r,maxLoc:i}).sort((x,$)=>j($)-j(x)||x.relativePath.localeCompare($.relativePath)),a),p=Xy(l,d,{semantic:c}),y=nb(e,l,u,d,{semantic:c}),f=Zy(d);return eb(e,d,p,f).filter(x=>!y.has(x.definition.symbolId)).filter(x=>!x.transitivelyReachable).filter(x=>x.realConsumers.length<=1).filter(x=>!(x.realConsumers.length===0&&x.barrelConsumers>0)).filter(x=>ub(x.definition,x.realConsumers.length,m)).map(x=>tb(e,x)).filter(x=>s||x.confidence!=="low").sort((x,$)=>{let F={high:0,medium:1,low:2};return F[x.confidence]-F[$.confidence]||$.loc-x.loc||x.file.localeCompare($.file)||x.startLine-$.startLine}).slice(0,o)}function Yy(e,t,n,r){return n.filter(i=>i.isTypeLike&&j(i)>=r.minLoc).filter(i=>j(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>!lb(i.symbol)).filter(i=>!t.hasSuppressionComment(i))}function Xy(e,t,n){return Ln(e,t,{semantic:n.semantic})}function Zy(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);r||(r=new Map,t.set(n.relativePath,r));let i=L(n.symbol);i&&r.set(i,n)}return t}function eb(e,t,n,r){return t.map(i=>{let s=[...n.get(i.symbolId)??new Set].filter(m=>m!==i.relativePath&&!e.isIgnored(m)),{realConsumers:a,barrelConsumers:c,importOnlyConsumers:l}=Ir(e,i,s),u=mb(e,i,n,r);return{definition:i,realConsumers:a,barrelConsumers:c+l,transitivelyReachable:u}})}function tb(e,t){let n=ll(e,t.definition.relativePath,t.definition.startLine),r=cl(t.definition.relativePath)?!0:db(e,t.definition),{confidence:i,reason:o}=pb(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:h(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:j(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:o}}function nb(e,t,n,r,i){let o=ib(e,rb(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=Ln(t,s,{semantic:i.semantic}),c=new Set;for(let{singleton:l,classId:u}of o)sb(e,l,a)&&c.add(u);return c}function rb(e){let t=new Map;for(let n of e){let r=L(n.symbol);r&&t.set(al(n.relativePath,r),n)}return t}function ib(e,t,n){let r=[];for(let i of n){let o=ob(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function ob(e,t,n){if(ll(e,n.relativePath,n.startLine)!=="class")return null;let r=L(n.symbol);if(!r)return null;let i=ab(e,n.relativePath,r);return i?t.get(al(n.relativePath,i))??null:null}function sb(e,t,n){let r=L(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!Do(e,o,r))}function al(e,t){return`${e}\0${t}`}function ab(e,t,n){let r=T(e,t);if(!r)return null;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${i}\\s*\\(`);return r.match(o)?.[1]??null}function cb(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function lb(e){let t=Q(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let r=n[n.length-1],i=n[n.length-2];return r?.suffix==="type"&&i?.suffix==="type"}function cl(e){let n=(e.split("/").pop()??"").replace(/\.[^.]+$/,"");return!!(n==="types"||n.endsWith("-types")||n==="models"||n==="schema"||n==="common"||n==="protocol"||n==="proto"||n==="dto"||n==="mod"||/(^|\/)types(\/|\.)/.test(e)||/(^|\/)models?(\/|\.)/.test(e)||/(^|\/)proto(?:col)?(\/|\.)/.test(e)||/(^|\/)schema(\/|\.)/.test(e))}function ub(e,t,n){return!(cl(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function mb(e,t,n,r){let i=ti(e,t.relativePath),o=L(t.symbol);if(!o)return!1;let s=i.get(o);if(!s||s.size===0)return!1;let a=r.get(t.relativePath);if(!a)return!1;for(let c of s){let l=a.get(c);if(!l)continue;let u=n.get(l.symbolId);if(u){for(let m of u)if(m!==t.relativePath&&!e.isIgnored(m))return!0}}return!1}function ll(e,t,n){let r=T(e,t);if(!r)return"other";let i=r.split(`
586
+ `),o=Math.max(0,n-2),s=Math.min(i.length-1,n+2);for(let a=o;a<=s;a++){let l=(i[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(l))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(l))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(l))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(l))return"enum"}return"other"}function db(e,t){let n=T(e,t.relativePath);if(!n)return!1;let r=L(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${i}\\b`),s=n.split(`
587
+ `);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function pb(e,t,n){return e===0?{confidence:"high",reason:"unused \u2014 no consumers and defining file has no real usage"}:e===1&&t==="class"?{confidence:"low",reason:"1 consumer + class kind \u2014 likely 1:1 encapsulation, not over-abstraction"}:e===1&&!n?{confidence:"high",reason:"1 consumer + defining file never uses it \u2014 type belongs with its consumer"}:{confidence:"medium",reason:"1 consumer \u2014 single-use abstraction"}}function Tn(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new v(e);return Ut({candidates:()=>s.productionCallableDefinitions({scope:n,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,prepare:a=>({callerMap:s.crossFileCallerMap(a,{semantic:t?.semantic!==!1}),calleeMap:s.calleeMap(a,{semantic:t?.semantic!==!1})}),evaluate:(a,c)=>fb(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function fb(e,t,n){let r=e.endLine-e.startLine+1;if(r<n)return null;let i=t.callerMap.get(e.symbolId)?.size??0,o=t.calleeMap.get(e.symbolId)??[],s=o.filter(l=>l.file!==e.relativePath),a=new Set(s.map(l=>`${l.symbol}|${l.file}`)).size,c=new Set(o.map(l=>`${l.symbol}|${l.file}`)).size;return{symbol:e.symbol,shortName:h(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:a,calleeCount:c,score:Math.round(r/50*(i/5)*Math.max(a/5,1)*100)/100}}function ul(e){let t=gb(e);return{score:hb(e),overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.loc,isolatedSymbols:e.isolated.count,isolatedLoc:e.isolated.loc,cycles:e.realCycleCount,similarPairs:e.similarCount,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount},actions:t,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0}}function gb(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",description:`${e.dead.count} symbols with zero references anywhere \u2014 safe to delete`,effort:"low",impact:"high",count:e.dead.count,locRecoverable:e.dead.loc}),e.isolated.count>0&&t.push({category:"Isolated symbols",description:`${e.isolated.count} symbols completely disconnected from the codebase graph`,effort:"low",impact:"medium",count:e.isolated.count,locRecoverable:e.isolated.loc}),e.realCycleCount>0&&t.push({category:"Circular dependencies",description:`${e.realCycleCount} cycle(s) \u2014 break with dependency inversion or module restructuring`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",description:`${e.similarCount} pairs with real logic overlap (beyond shared imports) \u2014 consolidation candidates`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.extractCount>0&&t.push({category:"Extraction candidates",description:`${e.extractCount} large functions with isolated callee clusters \u2014 extract method opportunities`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",description:`${e.wrappers.count} single-consumer symbols that could be inlined`,effort:"low",impact:"low",count:e.wrappers.count,locRecoverable:e.wrappers.loc}),e.passthroughs.count>0&&t.push({category:"Passthrough functions",description:`${e.passthroughs.count} functions that just forward to one callee \u2014 unnecessary indirection`,effort:"low",impact:"low",count:e.passthroughs.count,locRecoverable:e.passthroughs.loc}),e.stale.count>0){let i=[];e.stale.unused>0&&i.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&i.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",description:`${i.join(", ")} \u2014 premature abstraction`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let i=[];e.drift.unusedImports>0&&i.push(`${e.drift.unusedImports} unused imports`),e.drift.layerViolations>0&&i.push(`${e.drift.layerViolations} layer violations`),t.push({category:"Structural drift",description:i.join(", "),effort:e.drift.layerViolations>0?"medium":"low",impact:e.drift.layerViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}let n={high:3,medium:2,low:1},r={low:3,medium:2,high:1};return t.sort((i,o)=>{let s=n[i.impact]*r[i.effort];return n[o.impact]*r[o.effort]-s}),t}function hb(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=100,i=e.dead.count/n;r-=Math.min(20,Math.round(i*200));let o=e.isolated.count/n;r-=Math.min(10,Math.round(o*200)),r-=Math.min(15,e.realCycleCount*5);let s=e.similarCount/n*1e3;r-=Math.min(10,Math.round(s));let a=e.extractCount/n*1e3;r-=Math.min(5,Math.round(a/2)),r-=Math.min(3,e.wrappers.count),r-=Math.min(3,e.passthroughs.count);let c=e.stale.count/Math.max(n*.1,1);r-=Math.min(8,Math.round(c*10));let l=e.drift.count/t;return r-=Math.min(5,Math.round(l*50)),r-=Math.min(5,e.complexity.extremeCount*2),Math.max(0,Math.min(100,r))}import{getHeapStatistics as yb}from"v8";var bb=64*1024*1024;function No(){let e=globalThis.gc;if(!e)return;let t=yb();t.heap_size_limit-t.used_heap_size<bb||e()}var Sb=50,xb=75e3,Cb=5e3,ml=2500,Mn=["overview","dead","isolated","cycles","similar","extract-candidates","wrapper-candidates","passthrough-candidates","stale-abstractions","drift","complexity-hotspots"],Ib={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:vb(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:Db(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:Nb(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:Lb(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:Eb(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:wb(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:kb(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:Pb(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:Tb(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:Mb(e,t,n)})};function Lo(e,t,n={}){return Rb(e,n.full===!0,(r,i)=>Ib[t](e,n.scope,i,r))}function Rb(e,t,n){let r=Pe(e),i=Ob(r,t);try{return n(r,i)}finally{zi(e,{semanticProvider:!0}),No()}}function Eo(e){return ul(_b(e))}function _b(e){let t=_e(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:_e(e,"dead").dead,isolated:_e(e,"isolated").isolated,realCycleCount:_e(e,"cycles").realCycleCount,similarCount:_e(e,"similar").similarCount,extractCount:_e(e,"extract-candidates").extractCount,wrappers:_e(e,"wrapper-candidates").wrappers,passthroughs:_e(e,"passthrough-candidates").passthroughs,stale:_e(e,"stale-abstractions").stale,drift:_e(e,"drift").drift,complexity:_e(e,"complexity-hotspots").complexity}}function _e(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function vb(e,t,n){return Ae(e,n,"dead",()=>{let r=bn(e,{scope:t,minLoc:3,skipBarrels:!0,deadCodeOnly:!0,scanLimit:n.candidateScanLimit,semantic:!1});return wo($b(e,r.symbols))})}function Db(e,t,n){return Ae(e,n,"isolated",()=>{let r=xn(e,{scope:t,minLoc:3,scanLimit:n.candidateScanLimit,semantic:!1});return wo(jb(e,r))})}function Nb(e,t,n){return Ae(e,n,"cycles",()=>Sn(e,{scope:t}).filter(i=>i.kind==="real").length)}function Lb(e,t,n){return Ae(e,n,"similar",()=>_n(e,{scope:t,minSimilarity:.6,limit:50,minCallees:4,scanLimit:n.candidateScanLimit,semantic:!1}).length)}function Eb(e,t,n){return Ae(e,n,"extract-candidates",()=>vn(e,{scope:t,minLoc:15,minCallees:5,limit:50,scanLimit:n.candidateScanLimit,semantic:!1}).length)}function wb(e,t,n){return dl(e,n,"wrapper-candidates",()=>wn(e,{scope:t,maxLoc:15,limit:50,scanLimit:n.candidateScanLimit,semantic:!1}))}function kb(e,t,n){return dl(e,n,"passthrough-candidates",()=>kn(e,{scope:t,maxLoc:15,limit:50,scanLimit:n.candidateScanLimit,semantic:!1}))}function Pb(e,t,n){return Ae(e,n,"stale-abstractions",()=>{let r=Pn(e,{scope:t,minLoc:3,limit:50,scanLimit:n.candidateScanLimit,semantic:!1}),i=r.filter(o=>o.consumers===0).length;return{count:r.length,loc:r.reduce((o,s)=>o+s.loc,0),unused:i,singleUse:r.length-i}})}function Tb(e,t,n){return Ae(e,n,"drift",()=>{let r=Nn(e,{scope:t,semantic:!1});return{count:r.unusedImports+r.layerViolations,unusedImports:r.unusedImports,layerViolations:r.layerViolations}})}function Mb(e,t,n){return Ae(e,n,"complexity-hotspots",()=>{let r=Tn(e,{scope:t,minLoc:10,limit:10,scanLimit:n.candidateScanLimit,semantic:!1});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score})),extremeCount:r.filter(i=>i.score>Sb).length}})}function Ob(e,t){return e.symbols>=xb||e.documents>=Cb?t?{candidateScanLimit:void 0,releaseCachesBetweenPhases:!0,warnings:["Large index detected; running unbounded health analyses because --full was supplied."]}:{candidateScanLimit:ml,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${ml} symbols. Run "scip-query health --full" for unbounded candidate counts.`]}:{candidateScanLimit:void 0,releaseCachesBetweenPhases:!0,warnings:[]}}function Fb(e,t){t.releaseCachesBetweenPhases&&(il(e),zi(e),No())}function Ae(e,t,n,r){Ab(n);try{return r()}finally{Fb(e,t)}}function dl(e,t,n,r){return Ae(e,t,n,()=>wo(r()))}function Ab(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function $b(e,t){return t.filter(n=>!gt(e,n.relativePath)&&!ln(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function jb(e,t){return t.filter(n=>!gt(e,n.relativePath)&&!ln(e,n.symbol,n.relativePath))}function wo(e){return{count:e.length,loc:e.reduce((t,n)=>t+n.loc,0)}}function ko(e,t,n,r={}){let i=w(e,t),o=w(e,n);if(!i||!o)return null;let s=new Set(me(e,i,{semantic:r.semantic}).map(b=>b.symbol)),a=new Set(me(e,o,{semantic:r.semantic}).map(b=>b.symbol)),c=[];for(let b of s)a.has(b)&&c.push(b);let l=[];for(let b of s)a.has(b)||l.push(b);let u=[];for(let b of a)s.has(b)||u.push(b);let m=new Set([...s,...a]),d=m.size>0?c.length/m.size:0,p;m.size===0?p="Neither function calls other tracked symbols. There is no callee-pattern evidence for consolidation; inspect the source bodies directly.":c.length===0?p="These functions do not share any callees. They are not a callee-based consolidation candidate.":l.length===0&&u.length===0?p="These functions have identical tracked callee sets. They are a strong structural match, but identical callees do not prove interchangeable semantics; inspect signatures, control flow, and return values before consolidating.":l.length===0?p="A's tracked callees are a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic before replacing A with B.":u.length===0?p="B's tracked callees are a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic before replacing B with A.":l.length<=2&&u.length<=2?p=`Create a shared function with the ${c.length} common callees. Pass the ${l.length+u.length} divergent callees as parameters or strategy callbacks.`:p=`Extract the ${c.length} shared callees into a common helper. Each function calls the helper plus its own unique logic (${l.length} callees in A, ${u.length} in B).`;let y=i.endLine-i.startLine+1,f=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:h(i.symbol),file:i.relativePath,loc:y},symbolB:{symbol:o.symbol,shortName:h(o.symbol),file:o.relativePath,loc:f},similarity:d,sharedCallees:c.map(h),uniqueToA:l.map(h),uniqueToB:u.map(h),consolidationStrategy:p}}import{readFileSync as pl}from"fs";import{extname as Bb,join as fl}from"path";function Po(e,t,n={}){let{context:r=0}=n,i=Hb(t);if(i)return Vb(e,i.filePath,i.startLine,i.endLine,r);let o=w(e,t);return o?Wb(e,o,r):null}function Hb(e){let t=e.match(/^(.+\.\w+):(\d+)-(\d+)$/);return t?{filePath:t[1],startLine:parseInt(t[2],10),endLine:parseInt(t[3],10)}:null}function Wb(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=fl(e.config.projectRoot,t.relativePath),o;try{o=pl(i,"utf-8")}catch{return null}let s=o.split(`
588
+ `),a=Math.max(0,t.startLine-n),c=Math.min(s.length-1,t.endLine+n),l=s.slice(a,c+1).join(`
589
+ `);return{symbol:t.symbol,shortName:h(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:r?.language??gl(t.relativePath),source:l}}function Vb(e,t,n,r,i){let o=ie(e,t);if(!o)return null;let s=e.get("SELECT relative_path, language FROM documents WHERE relative_path = ?",o);if(!s)return null;let a=fl(e.config.projectRoot,s.relative_path),c;try{c=pl(a,"utf-8")}catch{return null}let l=c.split(`
590
+ `),u=Math.max(0,n-1-i),m=Math.min(l.length-1,r-1+i),d=l.slice(u,m+1).join(`
591
+ `);return{symbol:`${s.relative_path}:${n}-${r}`,shortName:`${s.relative_path}:${n}-${r}`,relativePath:s.relative_path,startLine:u,endLine:m,language:s.language??gl(s.relative_path),source:d}}function gl(e){switch(Bb(e).toLowerCase()){case".ts":case".tsx":case".mts":case".cts":return"typescript";case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".py":case".pyi":return"python";case".rs":return"rust";case".go":return"go";case".java":return"java";case".kt":case".kts":return"kotlin";case".scala":return"scala";case".rb":return"ruby";case".php":return"php";case".cs":return"csharp";case".vb":return"vb";case".dart":return"dart";case".c":case".h":return"c";case".cc":case".cpp":case".cxx":case".hpp":case".hh":case".hxx":return"cpp";case".vue":return"vue";default:return null}}import{readFileSync as qb}from"fs";import{join as Ub}from"path";function To(e,t,n={}){let r=w(e,t);if(!r)return null;let i=new v(e),o=Qb(zb(e,r.relativePath,r.startLine,r.endLine),Jb(e,r.relativePath)),s=r.endLine-r.startLine+1,c=i.calleeMap([r],{additive:!0,semantic:n.semantic}).get(r.symbolId)??[],l=new Set(c.map(u=>u.symbol));return{symbol:r.symbol,shortName:h(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o,cyclomaticEstimate:o+1,calleeCount:l.size,fanIn:Gb(e,r.symbolId),fanOut:Kb(c,r.relativePath)}}function Jb(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function zb(e,t,n,r){try{return qb(Ub(e.config.projectRoot,t),"utf-8").split(`
894
592
  `).slice(n,r+1).join(`
895
- `)}catch{return""}}function Ex(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
593
+ `)}catch{return""}}function Gb(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
896
594
  FROM mentions m
897
595
  JOIN chunks c ON m.chunk_id = c.id
898
- WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function Dx(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function Lx(e,t){let n=wx(e),r=0,i=[/\bif\b/g,/\belse\s+if\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bswitch\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*[^?]/g,/&&/g,/\|\|/g];for(let s of i){let o=n.match(s);o&&(r+=o.length)}if(t==="python"){let s=[/\belif\b/g,/\bexcept\b/g,/\bfinally\b/g];for(let o of s){let a=n.match(o);a&&(r+=a.length)}}else if(t==="rust"){let s=[/\bmatch\b/g,/=>/g,/\bloop\b/g];for(let o of s){let a=n.match(o);a&&(r+=a.length)}}else if(t==="ruby"){let s=[/\belsif\b/g,/\bunless\b/g,/\brescue\b/g,/\bwhen\b/g];for(let o of s){let a=n.match(o);a&&(r+=a.length)}}else if(t==="go"){let s=[/\bselect\b/g,/\bdefer\b/g];for(let o of s){let a=n.match(o);a&&(r+=a.length)}}return r}function wx(e){return e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*/g,"").replace(/#.*/g,"").replace(/"(?:[^"\\]|\\.)*"/g,'""').replace(/'(?:[^'\\]|\\.)*'/g,"''").replace(/`(?:[^`\\]|\\.)*`/g,"``")}function zl(e,t,n={}){let r=w(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],s=He(e,r,{semantic:n.semantic}),a=(s.length>0?s:Ne(e,r)).filter(u=>!e.isIgnored(u.file)).map(u=>({file:u.file,line:u.line,enclosingSymbol:u.enclosingSymbol??"(top-level)",enclosingShort:u.enclosingSymbol?y(u.enclosingSymbol):"(top-level)"})),{producers:l,consumers:c}=kx(e,r,a,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:y(r.symbol),relativePath:r.relativePath,definitionSites:i.filter(u=>!e.isIgnored(u.file)),usageSites:a,producers:l.filter(u=>!e.isIgnored(u.file)).map(u=>({symbol:u.symbol,shortName:y(u.symbol),file:u.file})),consumers:c.filter(u=>!e.isIgnored(u.file)).map(u=>({symbol:u.symbol,shortName:u.symbol===u.file?"(top-level)":y(u.symbol),file:u.file}))}}function kx(e,t,n,r){let i=ci(te(e,t,{limit:30,semantic:r.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),s=ci(oe(e,t,{limit:30,semantic:r.semantic})),o=s.length>0?s:ci(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:o}}function ci(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}`;t.has(i)||(t.add(i),n.push(r))}return n}function Gl(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,s=w(e,t);return s?r==="backward"?Px(e,s,i,{semantic:n.semantic!==!1}):Mx(e,s,{semantic:n.semantic!==!1}):null}function Px(e,t,n,r){let i=[],s=new Set([t.symbol]),o=[t];for(let a=1;a<=n&&o.length!==0;a++){let l=[];for(let c of o){let u=te(e,c,{semantic:r.semantic});for(let d of u){if(s.has(d.symbol))continue;s.add(d.symbol),i.push({symbol:d.symbol,shortName:y(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=ct(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&l.push(m)}}o=l}return{symbol:t.symbol,shortName:y(t.symbol),direction:"backward",connectedSymbols:i}}function Mx(e,t,n){let r=He(e,t,{semantic:n.semantic}),i=r.length>0?r:Ne(e,t),s=new Set,o=[],a=new N(e);for(let l of i){if(o.length>=30)break;if(e.isIgnored(l.file))continue;let c=l.enclosingSymbol??le(a.definitionsForFile(l.file),l.line)?.symbol??null;if(!c||c===t.symbol)continue;let u=ct(e,c);!u||e.isIgnored(u.relativePath)||s.has(u.symbol)||(s.add(u.symbol),o.push({symbol:u.symbol,shortName:y(u.symbol),file:u.relativePath,relationship:`references target at ${l.file}:${l.line+1}`}))}return o.sort((l,c)=>l.file.localeCompare(c.file)),{symbol:t.symbol,shortName:y(t.symbol),direction:"forward",connectedSymbols:o}}function Kl(e,t={}){let{scope:n,limit:r}=t,i=new N(e),s=Wx([...Ox(e,n),...Ax(e,i,n)]);return Ux(s),r?s.slice(0,r):s}function Ox(e,t){let n=[];for(let r of Tx(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||Gr(e,r.barrel_path))continue;let i=Fx(e,r),s=i?.barrel_consumers??0,o=i?.direct_consumers??0;s!==0||o!==0||n.push({barrelFile:r.barrel_path,symbol:r.symbol,shortName:y(r.symbol),originalFile:r.original_path,barrelConsumers:s,directConsumers:o})}return n}function Tx(e,t){let n=t?`AND barrel_d.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
596
+ WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function Kb(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function Qb(e,t){let n=Ot(e),r=0,i=[/\bif\b/g,/\belse\s+if\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bswitch\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*[^?]/g,/&&/g,/\|\|/g];for(let o of i){let s=n.match(o);s&&(r+=s.length)}if(t==="python"){let o=[/\belif\b/g,/\bexcept\b/g,/\bfinally\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="rust"){let o=[/\bmatch\b/g,/=>/g,/\bloop\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="ruby"){let o=[/\belsif\b/g,/\bunless\b/g,/\brescue\b/g,/\bwhen\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="go"){let o=[/\bselect\b/g,/\bdefer\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}return r}function Mo(e,t,n={}){let r=w(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=et(e,r,{semantic:n.semantic}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?h(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=Yb(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:h(r.symbol),relativePath:r.relativePath,definitionSites:i.filter(c=>!e.isIgnored(c.file)),usageSites:o,producers:s.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:h(c.symbol),file:c.file})),consumers:a.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:c.symbol===c.file?"(top-level)":h(c.symbol),file:c.file}))}}function Yb(e,t,n,r){let i=Vt(me(e,t,{limit:30,semantic:r.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=Vt(ye(e,t,{limit:30,semantic:r.semantic})),s=o.length>0?o:Vt(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:s}}function Oo(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=w(e,t);return o?r==="backward"?Xb(e,o,i,{semantic:n.semantic!==!1}):Zb(e,o,{semantic:n.semantic!==!1}):null}function Xb(e,t,n,r){let i=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let c=[];for(let l of s){let u=me(e,l,{semantic:r.semantic});for(let m of u){if(o.has(m.symbol))continue;o.add(m.symbol),i.push({symbol:m.symbol,shortName:h(m.symbol),file:m.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let d=Tt(e,m.symbol);d&&!e.isIgnored(d.relativePath)&&c.push(d)}}s=c}return{symbol:t.symbol,shortName:h(t.symbol),direction:"backward",connectedSymbols:i}}function Zb(e,t,n){let r=new Set,i=[],o=new v(e);for(let s of et(e,t,{semantic:n.semantic})){if(i.length>=30)break;let a=s.enclosingSymbol??de(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=Tt(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:h(c.symbol),file:c.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return i.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:h(t.symbol),direction:"forward",connectedSymbols:i}}function Fo(e,t={}){let{scope:n,limit:r}=t,i=new v(e),o=cS([...eS(e,n),...rS(e,i,n)]);return lS(o),r?o.slice(0,r):o}function eS(e,t){let n=[];for(let r of tS(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||Ii(e,r.barrel_path))continue;let i=nS(e,r),o=i?.barrel_consumers??0,s=i?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:r.barrel_path,symbol:r.symbol,shortName:h(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s})}return n}function tS(e,t){let n=t?`AND barrel_d.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
899
597
  barrel_d.id AS barrel_doc_id,
900
598
  barrel_d.relative_path AS barrel_path,
901
599
  gs.id AS symbol_id,
@@ -925,7 +623,7 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
925
623
  -- Only function-level symbols (ending with ().), not module-level
926
624
  AND gs.symbol LIKE '%().'
927
625
  ${n}
928
- ORDER BY barrel_d.relative_path, gs.symbol`)}function Fx(e,t){return e.get(`SELECT
626
+ ORDER BY barrel_d.relative_path, gs.symbol`)}function nS(e,t){return e.get(`SELECT
929
627
  SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
930
628
  SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
931
629
  FROM (
@@ -954,95 +652,234 @@ ${m}`,c+=1+m.length,u+=No(m),r+=m.length+1}let d=Dg(l);d&&n.push({...d,start:a,e
954
652
  AND consumer_d.id != ?
955
653
  ${e.pathExclusionsFor("consumer_d")}
956
654
  GROUP BY consumer_d.id
957
- )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function Ax(e,t,n){let r=[];for(let i of $x(e,n))Yl(e,i,i)>0||r.push(...jx(e,t,i));return r}function $x(e,t){return e.all(`SELECT relative_path
958
- FROM documents
959
- WHERE 1 = 1
960
- ${t?"AND relative_path LIKE ?":""}
961
- ${e.pathExclusionsFor("documents")}
962
- ORDER BY relative_path`,...t?[`%${t}%`]:[]).map(r=>r.relative_path).filter(r=>!e.isIgnored(r)).filter(r=>Br(e,r).length>0)}function jx(e,t,n){return Br(e,n).filter(r=>r.sourcePath&&!e.isIgnored(r.sourcePath)).flatMap(r=>Bx(e,t,n,r.sourcePath))}function Bx(e,t,n,r){let i=Hx(t,r);return i?[{barrelFile:n,symbol:i.symbol,shortName:y(i.symbol),originalFile:r,barrelConsumers:0,directConsumers:Yl(e,r,n)}]:[]}function Yl(e,t,n){let r=e.all(`SELECT relative_path
963
- FROM documents
964
- WHERE 1 = 1
965
- ${e.pathExclusionsFor("documents")}
966
- ORDER BY relative_path`),i=new Set;for(let s of r)if(!(e.isIgnored(s.relative_path)||s.relative_path===n))for(let o of q(e,s.relative_path))o.sourcePath===t&&i.add(s.relative_path);return i.size}function Hx(e,t){let n=e.definitionsForFile(t);return n.find(r=>z(r.symbol)==="method")??n[0]??null}function Wx(e){let t=new Set,n=[];for(let r of e){let i=`${r.barrelFile}|${r.symbol}|${r.originalFile}`;t.has(i)||(t.add(i),n.push(r))}return n}function Ux(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function Ql(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:s}=t,o=t.semantic!==!1,a=new Map,l=Jx(_e(e,{scope:n}).filter(u=>u.isFunctionLike&&!e.isIgnored(u.relativePath)).filter(u=>u.endLine-u.startLine+1>=r).sort((u,d)=>typeof s!="number"||s<=0?0:ui(d)-ui(u)||u.relativePath.localeCompare(d.relativePath)),s);for(let u of l){let d=ui(u),m=Vx(e,u,{semantic:o});if(!m)continue;let f={symbol:u.symbol,shortName:y(u.symbol),file:u.relativePath,startLine:u.startLine,endLine:u.endLine,loc:d},h=a.get(m);h?h.push(f):a.set(m,[f])}let c=[];for(let[u,d]of a)d.length<2||c.push({signature:u,functions:d});return c.sort((u,d)=>{let m=d.functions.length-u.functions.length;if(m!==0)return m;let f=u.functions.reduce((p,g)=>p+g.loc,0);return d.functions.reduce((p,g)=>p+g.loc,0)-f}),i?c.slice(0,i):c}function Vx(e,t,n){if(n.semantic){let s=Uo(e,t);if(s)return s}let r=qx(t.documentation),i=r?Kx(r):null;return i||Yx(zx(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function ui(e){return e.endLine-e.startLine+1}function Jx(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function qx(e){return Ge(Ke(e))}function zx(e,t,n,r,i){let s=M(e,t);if(!s)return null;let o=s.split(/\r?\n/),a=Xx(o,n,r,i);for(let l of a){let c=Math.min(o.length-1,Math.max(l,l+4)),u="";for(let d=l;d<=c;d+=1){let m=o[d]?.trim();if(m&&(u=u?`${u} ${m}`:m,Gx(u)))return u}if(u&&u.includes("("))return u}return null}function Gx(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||Zx(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function Kx(e){if(!e||!e.trim())return null;let t=e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim(),n=t.indexOf("(");return n===-1||(t=t.slice(n),t=t.replace(/\s+/g,"").toLowerCase(),t.length<3)?null:t}function Yx(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),r=n.indexOf("(");if(r===-1)return null;let i=n.slice(0,r),o=new RegExp(`\\b${Xl(t)}\\b`,"i").exec(i);o&&typeof o.index=="number"&&(i=i.slice(0,o.index)),i=i.replace(/\b(public|private|protected|internal|final|static|abstract|sealed|virtual|override|async|suspend|inline|constexpr|consteval|constinit|const|pub|fn|function|def|sub|friend|shared|readonly|new|open|partial|export)\b/gi," ").replace(/\s+/g," ").trim();let a=Qx(n.slice(r)).replace(/\)\s*=\s*[\s\S]*$/,")").replace(/\s+throws\s+[^={]+$/i,"").replace(/\s+where\s+.+$/i,"").replace(/\s+/g," ").trim();if(!a.startsWith("("))return null;let l=`${i?`${i} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return l.length>=3?l:null}function Qx(e){let t=0,n=0,r=0,i=0,s=null,o=!1;for(let a=0;a<e.length;a+=1){let l=e[a];if(s){if(o){o=!1;continue}if(l==="\\"){o=!0;continue}l===s&&(s=null);continue}if(l==='"'||l==="'"||l==="`"){s=l;continue}if(l==="(")t+=1;else if(l===")")t=Math.max(0,t-1);else if(l==="[")r+=1;else if(l==="]")r=Math.max(0,r-1);else if(l==="<")i+=1;else if(l===">")i=Math.max(0,i-1);else if(l==="{"){if(t===0&&r===0&&i===0)return e.slice(0,a);n+=1}else if(l==="}")n=Math.max(0,n-1);else if(l==="="&&e[a+1]===">"&&t===0&&n===0&&r===0&&i===0)return e.slice(0,a)}return e}function Xx(e,t,n,r){let i=Xl(r),s=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),o=new RegExp(`\\bdef\\s+${i}\\b`,"i"),a=[],l=new Set,c=Math.max(0,Math.min(t,e.length-1)),u=Math.max(c,Math.min(e.length-1,Math.max(n,t+4)));for(let d=c;d<=u;d+=1){let m=e[d]??"";(s.test(m)||o.test(m))&&!l.has(d)&&(l.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let m=e[d]??"";(s.test(m)||o.test(m))&&!l.has(d)&&(l.add(d),a.push(d))}return a}function Zx(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}function Xl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function De(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function Ht(e){let t=Le(e),n=we(e,t);return process.env.SCIP_QUERY_INDEX_DB??(Zl(n.dbPath)?n.dbPath:e_(e,"index.db"))}function t_(){let e=De(),t=Le(e),n=we(e,t),r=Ht(e);Zl(r)||(console.error("error: No index.db found. Run: scip-query reindex"),process.exit(1));let i={dbPath:r,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:e,entryRoots:t.entryRoots,semantic:t.semantic},s=tt(e);return new rn(i,s)}function R(e){let t=t_();try{return e(t)}finally{t.close()}}function ec(e,t){return t.concat([e])}function E(e){return parseInt(e,10)}function di(e){let t=parseInt(e,10);if(!Number.isFinite(t)||t<1)throw new Error(`Expected a positive integer, got ${e}`);return t}function Vn(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function tc(e){switch(e.state){case"idle":return"Watching (idle)";case"waiting":{let t=Math.round((e.reindexAt-Date.now())/1e3);return`${e.changedFiles} file(s) changed, reindexing in ${t}s...`}case"indexing":return`Reindexing... (${Math.round((Date.now()-e.startedAt)/1e3)}s)`;case"cooldown":return`Cooldown (${Math.round((e.until-Date.now())/1e3)}s)${e.dirty?" \u2014 changes pending":""}`;default:return n_(e)}}function n_(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}var i_=r_(import.meta.url),{version:s_}=c_(),oc="__health-phase",ac="__diff-impact-batch",o_=10,a_=75e3,l_=5e3,ic=2500;function c_(){for(let e of["../package.json","../../package.json"])try{return i_(e)}catch{}return{version:"0.0.0"}}function Se(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
967
- `)}function A(e,t,n){let r=x.stats(e);return r.symbols>=a_||r.documents>=l_?n?(console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0}):(console.error(`Large index detected; ${t} will scan the highest-priority ${ic} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:ic,semantic:!1}):{semantic:!0}}function u_(e){let t=x.HEALTH_PHASES.map(n=>d_(n,e));return x.healthReportFromPhases(t)}function d_(e,t){let n=process.argv[1]??mi(import.meta.url),r=[...process.execArgv,n,oc,e];t.scope&&r.push("--scope",t.scope),t.full&&r.push("--full");let i=sc(process.execPath,r,{cwd:process.cwd(),env:process.env,encoding:"utf8",maxBuffer:10*1024*1024});if(i.status!==0){let s=i.stderr.trim();throw new Error(`Health phase "${e}" failed${s?`:
968
- ${s}`:""}`)}return JSON.parse(i.stdout)}function m_(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
655
+ )`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function rS(e,t,n){let r=[];for(let i of iS(e,n))hl(e,i,i)>0||r.push(...oS(e,t,i));return r}function iS(e,t){return k(e,{scope:t,includeIgnored:!1}).filter(n=>xi(e,n).length>0)}function oS(e,t,n){return xi(e,n).filter(r=>r.sourcePath&&!e.isIgnored(r.sourcePath)).flatMap(r=>sS(e,t,n,r.sourcePath))}function sS(e,t,n,r){let i=aS(t,r);return i?[{barrelFile:n,symbol:i.symbol,shortName:h(i.symbol),originalFile:r,barrelConsumers:0,directConsumers:hl(e,r,n)}]:[]}function hl(e,t,n){let r=new Set;for(let i of k(e,{includeIgnored:!1}))if(i!==n)for(let o of Y(e,i))o.sourcePath===t&&r.add(i);return r.size}function aS(e,t){let n=e.definitionsForFile(t);return n.find(r=>ee(r.symbol)==="method")??n[0]??null}function cS(e){let t=new Set,n=[];for(let r of e){let i=`${r.barrelFile}|${r.symbol}|${r.originalFile}`;t.has(i)||(t.add(i),n.push(r))}return n}function lS(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function Ao(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o}=t,s=t.semantic!==!1,a=mS(e,uS(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:s}),c=pS(a);return i?c.slice(0,i):c}function uS(e,t){let n=Le(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>j(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>j(i)-j(r)||r.relativePath.localeCompare(i.relativePath)),ne(n,t.scanLimit)}function mS(e,t,n){let r=new Map;for(let i of t){let o=fS(e,i,n);if(!o)continue;let s=r.get(o)??[];s.push(dS(i)),r.set(o,s)}return r}function dS(e){return{symbol:e.symbol,shortName:h(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:j(e)}}function pS(e){let t=[];for(let[n,r]of e)r.length>=2&&t.push({signature:n,functions:r});return t.sort((n,r)=>{let i=r.functions.length-n.functions.length;if(i!==0)return i;let o=n.functions.reduce((a,c)=>a+c.loc,0);return r.functions.reduce((a,c)=>a+c.loc,0)-o}),t}function fS(e,t,n){if(n.semantic){let o=uc(e,t);if(o)return o}let r=gS(t.documentation),i=r?bS(r):null;return i||SS(hS(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function gS(e){return at(ct(e))}function hS(e,t,n,r,i){let o=T(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=CS(s,n,r,i);for(let c of a){let l=Math.min(s.length-1,Math.max(c,c+4)),u="";for(let m=c;m<=l;m+=1){let d=s[m]?.trim();if(d&&(u=u?`${u} ${d}`:d,yS(u)))return u}if(u&&u.includes("("))return u}return null}function yS(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||sn(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function bS(e){if(!e||!e.trim())return null;let t=e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim(),n=t.indexOf("(");return n===-1||(t=t.slice(n),t=t.replace(/\s+/g,"").toLowerCase(),t.length<3)?null:t}function SS(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),r=n.indexOf("(");if(r===-1)return null;let i=n.slice(0,r),s=new RegExp(`\\b${yl(t)}\\b`,"i").exec(i);s&&typeof s.index=="number"&&(i=i.slice(0,s.index)),i=i.replace(/\b(public|private|protected|internal|final|static|abstract|sealed|virtual|override|async|suspend|inline|constexpr|consteval|constinit|const|pub|fn|function|def|sub|friend|shared|readonly|new|open|partial|export)\b/gi," ").replace(/\s+/g," ").trim();let a=xS(n.slice(r)).replace(/\)\s*=\s*[\s\S]*$/,")").replace(/\s+throws\s+[^={]+$/i,"").replace(/\s+where\s+.+$/i,"").replace(/\s+/g," ").trim();if(!a.startsWith("("))return null;let c=`${i?`${i} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return c.length>=3?c:null}function xS(e){let t=0,n=0,r=0,i=0,o=null,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c===o&&(o=null);continue}if(c==='"'||c==="'"||c==="`"){o=c;continue}if(c==="(")t+=1;else if(c===")")t=Math.max(0,t-1);else if(c==="[")r+=1;else if(c==="]")r=Math.max(0,r-1);else if(c==="<")i+=1;else if(c===">")i=Math.max(0,i-1);else if(c==="{"){if(t===0&&r===0&&i===0)return e.slice(0,a);n+=1}else if(c==="}")n=Math.max(0,n-1);else if(c==="="&&e[a+1]===">"&&t===0&&n===0&&r===0&&i===0)return e.slice(0,a)}return e}function CS(e,t,n,r){let i=yl(r),o=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${i}\\b`,"i"),a=[],c=new Set,l=Math.max(0,Math.min(t,e.length-1)),u=Math.max(l,Math.min(e.length-1,Math.max(n,t+4)));for(let m=l;m<=u;m+=1){let d=e[m]??"";(o.test(d)||s.test(d))&&!c.has(m)&&(c.add(m),a.push(m))}for(let m=0;m<e.length;m+=1){let d=e[m]??"";(o.test(d)||s.test(d))&&!c.has(m)&&(c.add(m),a.push(m))}return a}function yl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{existsSync as vl}from"fs";import{join as $S}from"path";import IS from"better-sqlite3";var RS=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".scipquery-cache","__pycache__",".venv","venv"],_r=class{db;config;pathFilter;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new IS(t.dbPath,{readonly:!0}),this.db.pragma("busy_timeout = 5000")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
656
+ EXISTS (
657
+ SELECT 1
658
+ FROM defn_enclosing_ranges local_der
659
+ JOIN documents local_d ON local_der.document_id = local_d.id
660
+ WHERE local_der.symbol_id = gs.id
661
+ ${this.pathExclusionsFor("local_d").trimStart()}
662
+ )
663
+ OR EXISTS (
664
+ SELECT 1
665
+ FROM mentions local_m
666
+ JOIN chunks local_c ON local_m.chunk_id = local_c.id
667
+ JOIN documents local_d ON local_c.document_id = local_d.id
668
+ WHERE local_m.symbol_id = gs.id
669
+ AND local_m.role = 1
670
+ ${this.pathExclusionsFor("local_d").trimStart()}
671
+ )
672
+ )`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>RS.flatMap(r=>[`AND ${n}.relative_path NOT LIKE '${r}/%'`,`AND ${n}.relative_path NOT LIKE '%/${r}/%'`])).join(`
673
+ `)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.db.prepare(t).all(...n)}get(t,...n){return this.db.prepare(t).get(...n)}close(){this.db.close()}};import _S from"ignore";import{readFileSync as vS,existsSync as $o}from"fs";import{dirname as jo,isAbsolute as bl,join as Bo,relative as DS,resolve as NS}from"path";function Jt(e){let t=_S(),n=!1,r=LS(e);for(let i of r)try{let o=vS(i,"utf-8");t.add(o),n=!0}catch{}return n||t.add(ES),{isIgnored:i=>Sl(t,e,i),filter:i=>i.filter(o=>!Sl(t,e,o))}}function LS(e){let t=[],n=Bo(e,".gitignore");$o(n)&&t.push(n);let r=jo(e),i=0;for(;r!==jo(r)&&i<5;){let o=Bo(r,".gitignore");if($o(o)&&t.push(o),$o(Bo(r,".git")))break;r=jo(r),i++}return t}var ES=`
674
+ # Dependencies
675
+ node_modules/
676
+ vendor/
677
+ .bundle/
678
+
679
+ # Build output
680
+ dist/
681
+ build/
682
+ out/
683
+ target/
684
+ bin/
685
+ obj/
686
+
687
+ # Python
688
+ __pycache__/
689
+ *.pyc
690
+ *.pyo
691
+ .venv/
692
+ venv/
693
+ .env/
694
+ env/
695
+ *.egg-info/
696
+
697
+ # Rust
698
+ target/
699
+
700
+ # Java / Kotlin / Scala
701
+ *.class
702
+ .gradle/
703
+ .mvn/
704
+
705
+ # C# / .NET
706
+ bin/
707
+ obj/
708
+ packages/
709
+
710
+ # Go
711
+ vendor/
712
+
713
+ # Dart
714
+ .dart_tool/
715
+ build/
716
+
717
+ # PHP
718
+ vendor/
719
+
720
+ # IDE / OS
721
+ .idea/
722
+ .vscode/
723
+ *.swp
724
+ *.swo
725
+ .DS_Store
726
+ Thumbs.db
727
+
728
+ # Type definitions (often noise in queries)
729
+ *.d.ts
730
+ `;function Sl(e,t,n){let r=wS(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function wS(e,t){if(!t||t===".")return null;if(!bl(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=bl(t)?t:NS(e,t),r=DS(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{readFileSync as kS,writeFileSync as PS,existsSync as Cl,mkdirSync as TS}from"fs";import{join as St,resolve as xl}from"path";import{createHash as MS}from"crypto";import{homedir as OS}from"os";var Il=".scipquery.json",FS={enabled:!1,debounceMs:3e4,cooldownMs:6e4,ignore:[]};function zt(e){let t=St(e,Il);if(!Cl(t))return{};try{let n=kS(t,"utf-8");return JSON.parse(n)}catch{return{}}}function Rl(e){return{...FS,...e.watch}}function AS(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return Ho(n);if(t?.dbPath)return Ho(xl(e,t.dbPath));let i=process.env.XDG_CACHE_HOME||St(OS(),".cache"),o=MS("sha256").update(xl(e)).digest("hex").slice(0,12),s=St(i,"scip-query","projects",o);return Ho(s)}function Gt(e,t){let n=AS(e,t);return{cacheDir:n,dbPath:St(n,"index.db"),indexPath:St(n,"index.scip"),metaPath:St(n,"meta.json")}}function _l(e,t){let n=St(e,Il);return Cl(n)||PS(n,JSON.stringify({languages:t,watch:{enabled:!1,debounceMs:3e4,cooldownMs:6e4}},null,2)+`
731
+ `),n}function Ho(e){return TS(e,{recursive:!0}),e}function nt(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}function vr(e=nt()){let t=zt(e),n=Gt(e,t),r=process.env.SCIP_QUERY_INDEX_DB??(vl(n.dbPath)?n.dbPath:$S(e,"index.db"));return{projectRoot:e,config:t,paths:n,dbPath:r}}function Wo(e){return vr(e).dbPath}function jS(){let{projectRoot:e,config:t,paths:n,dbPath:r}=vr();vl(r)||(console.error("error: No index.db found. Run: scip-query reindex"),process.exit(1));let i={dbPath:r,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:e,entryRoots:t.entryRoots,semantic:t.semantic},o=Jt(e);return new _r(i,o)}function rt(e){let t=jS();try{return e(t)}finally{t.close()}}function Vo(e,t){return t.concat([e])}function Kt(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Dl(e){switch(e.state){case"idle":return"Watching (idle)";case"waiting":{let t=Math.round((e.reindexAt-Date.now())/1e3);return`${e.changedFiles} file(s) changed, reindexing in ${t}s...`}case"indexing":return`Reindexing... (${Math.round((Date.now()-e.startedAt)/1e3)}s)`;case"cooldown":return`Cooldown (${Math.round((e.until-Date.now())/1e3)}s)${e.dirty?" \u2014 changes pending":""}`;default:return BS(e)}}function BS(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}function $e(e){return e+1}function be(e,t){return`${$e(e)}-${$e(t)}`}function Se(e,t,n){return`${e}:${be(t,n)}`}var N={empty(e){console.log(e)},list(e,t){for(let n of e)console.log(t(n))},groupedByFile(e,t,n=r=>r.relativePath){let r="";for(let i of e){let o=n(i);o!==r&&(r&&console.log(""),console.log(o),r=o),console.log(t(i))}},sectionedReport(e){let t=!0;for(let n of e)if(!(n.skipIfEmpty&&n.rows.length===0)){t||console.log(""),t=!1,n.title!==void 0&&console.log(`\u2550\u2550\u2550 ${n.title} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(n.explanation);for(let r of n.rows)console.log(r)}},table(e,t,n){console.log(` ${e.join(" ")}`);let r=n??e.map(i=>i.length);console.log(` ${r.map(i=>"\u2500".repeat(i)).join(" ")}`);for(let i of t)console.log(i)}};var WS=HS(import.meta.url),{version:Dr}=JS(),Nr="__health-phase",Lr="__diff-impact-batch",VS=10,qS=75e3,US=5e3,Nl=2500;function JS(){for(let e of["../package.json","../../package.json"])try{return WS(e)}catch{}return{version:"0.0.0"}}function On(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
732
+ `)}function wl(e,t,n){let r=Pe(e);return r.symbols>=qS||r.documents>=US?n?(console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0}):(console.error(`Large index detected; ${t} will scan the highest-priority ${Nl} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:Nl,semantic:!1}):{semantic:!0}}function kl(e){let t=Mn.map(n=>zS(n,e));return Eo(t)}function zS(e,t){let n=process.argv[1]??El(import.meta.url),r=[...process.execArgv,n,Nr,e];t.scope&&r.push("--scope",t.scope),t.full&&r.push("--full");let i=Ll(process.execPath,r,{cwd:process.cwd(),env:process.env,encoding:"utf8",maxBuffer:10*1024*1024});if(i.status!==0){let o=i.stderr.trim();throw new Error(`Health phase "${e}" failed${o?`:
733
+ ${o}`:""}`)}return JSON.parse(i.stdout)}function Pl(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
969
734
  Codebase Health Score: ${e.score}/100
970
- `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${Vn(e.overview.indexSizeBytes)}
735
+ `),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${Kt(e.overview.indexSizeBytes)}
971
736
  `),e.warnings&&e.warnings.length>0){console.log(" Warnings:");for(let r of e.warnings)console.log(` ${r}`);console.log("")}console.log(" Findings:");let n=e.findings;if(n.deadSymbols>0&&console.log(` Dead code: ${n.deadSymbols} symbols (${n.deadLoc} LOC)`),n.isolatedSymbols>0&&console.log(` Isolated symbols: ${n.isolatedSymbols} (${n.isolatedLoc} LOC)`),n.cycles>0&&console.log(` Circular deps: ${n.cycles}`),n.similarPairs>0&&console.log(` Similar pairs: ${n.similarPairs}`),n.extractionCandidates>0&&console.log(` Extract candidates: ${n.extractionCandidates}`),n.wrappers>0&&console.log(` Wrapper functions: ${n.wrappers}`),n.passthroughs>0&&console.log(` Passthroughs: ${n.passthroughs}`),n.staleTypes>0&&console.log(` Stale abstractions: ${n.staleTypes}`),n.driftedFiles>0&&console.log(` Pattern drift: ${n.driftedFiles} files`),n.complexityHotspotCount>0&&console.log(` Complexity hotspots: ${n.complexityHotspotCount}`),e.actions.length>0){console.log(`
972
- Prioritized Actions (highest impact + lowest effort first):`);for(let r=0;r<e.actions.length;r++){let i=e.actions[r],s=i.locRecoverable>0?` (~${i.locRecoverable} LOC recoverable)`:"";console.log(` ${r+1}. [${i.effort} effort / ${i.impact} impact] ${i.description}${s}`)}}if(e.topComplexity.length>0){console.log(`
737
+ Prioritized Actions (highest impact + lowest effort first):`);for(let r=0;r<e.actions.length;r++){let i=e.actions[r],o=i.locRecoverable>0?` (~${i.locRecoverable} LOC recoverable)`:"";console.log(` ${r+1}. [${i.effort} effort / ${i.impact} impact] ${i.description}${o}`)}}if(e.topComplexity.length>0){console.log(`
973
738
  Top Complexity Hotspots:`);for(let r of e.topComplexity)console.log(` ${r.score.toFixed(1).padStart(6)} ${r.symbol}`)}e.actions.length===0&&console.log(`
974
- No issues found. Codebase is clean.`)}function f_(e){return R(t=>{let n=x.diffImpactPlan(t,{base:e.base});if(n.note)return x.diffImpact(t,{base:e.base});if(n.changedFiles.length===0)return x.diffImpact(t,{base:e.base});let r=[];for(let i of h_(n.changedFiles,o_))r.push(p_(i,e));return x.mergeDiffImpactPartials(n.changedFiles,r)})}function p_(e,t){let n=process.argv[1]??mi(import.meta.url),r=[...process.execArgv,n,ac];t.base&&r.push("--base",t.base);let i=sc(process.execPath,r,{cwd:process.cwd(),env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},encoding:"utf8",maxBuffer:10*1024*1024});if(i.status!==0){let s=i.stderr.trim();throw new Error(`Diff-impact batch failed${s?`:
975
- ${s}`:""}`)}return JSON.parse(i.stdout)}function g_(e){console.log(`Changed files: ${e.summary.totalChangedFiles}`),console.log(`Changed symbols: ${e.summary.totalChangedSymbols}`),console.log(`Affected consumer files: ${e.summary.totalAffectedFiles}`),e.summary.note&&console.log(`Note: ${e.summary.note}`),console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),S.list(e.changedSymbols,t=>` ${t.file} ${t.shortName} (fan-in: ${t.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
976
- Affected consumer files:`),S.list(e.affectedConsumers,t=>` ${t.file} (${t.consumedSymbols} symbol(s))`))}function h_(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}I.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(s_);I.command("reindex").description("Index the codebase and convert to SQLite").option("-l, --language <lang>","Index only this language (can be repeated)",ec,[]).option("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)").option("--force","Rebuild even if source inputs are unchanged").option("--allow-partial","Write an incomplete index when one or more detected languages fail").option("--indexer-concurrency <n>","Number of language indexers to run at once",di).action(async e=>{let t=De(),n=Le(t),r=we(t,n);try{let i=await ss({projectRoot:t,languages:e.language.length>0?e.language:n.languages,outputScip:r.indexPath,outputDb:r.dbPath,pnpmWorkspaces:e.pnpmWorkspaces||n.indexer?.typescript?.pnpmWorkspaces,skipIfUnchanged:!e.force,allowPartial:e.allowPartial,indexerConcurrency:e.indexerConcurrency});console.log(`${i.reused?"Reused":"Indexed"} ${i.languages.join(", ")} in ${(i.durationMs/1e3).toFixed(1)}s`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exit(1)}});I.command("augment-sources").description("Add source files skipped by upstream SCIP indexers to the SQLite documents table").action(()=>{let e=De(),t=Ht(e);try{let n=Pe({projectRoot:e,dbPath:t,onStatus:r=>console.log(r)});console.log(`Scanned ${n.scanned} auxiliary source files; inserted ${n.inserted}.`)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}});I.command("augment-vue").description("Add compiler-resolved Vue SFC references to the SQLite index using Volar").option("--project <tsconfig>","Vue tsconfig path","frontend/tsconfig.scip.json").action(e=>{let t=De(),n=Ht(t);try{let r=or({projectRoot:t,dbPath:n,tsconfig:e.project,onStatus:i=>console.log(i)});console.log(`Vue files: ${r.vueFiles}; resolved references: ${r.resolvedReferences}; inserted mentions: ${r.insertedMentions}.`)}catch(r){console.error(`error: ${r instanceof Error?r.message:r}`),process.exit(1)}});I.command("stats").description("Show index statistics").action(()=>R(e=>{let t=x.stats(e);console.log(`Documents: ${t.documents}`),console.log(`Symbols: ${t.symbols}`),console.log(`Definitions: ${t.definitions}`),console.log(`References: ${t.references}`),console.log(`Index size: ${Vn(t.indexSizeBytes)}`),t.lastBuilt&&console.log(`Last built: ${t.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}));I.command("files <pattern>").description("Find files matching a pattern").action(e=>R(t=>{S.list(x.files(t,e),n=>n.relativePath)}));I.command("symbols <file>").description("List symbols defined in a file (with line ranges + signatures)").action(e=>R(t=>{S.list(x.symbols(t,e),n=>{let r=n.signature?` \u2014 ${n.signature}`:"";return` ${pe(n.startLine,n.endLine)} ${n.shortName}${r}`})}));I.command("methods <className>").description("List methods of a class (with line ranges)").action(e=>R(t=>{S.list(x.methods(t,e),n=>` ${pe(n.startLine,n.endLine)} ${n.name}`)}));I.command("refs <symbol>").description("Find all files referencing a symbol").option("--full","Run unbounded semantic analysis on large indexes").action((e,t)=>R(n=>{let r=A(n,"refs",!!t.full);S.groupedByFile(x.refs(n,e,{semantic:r.semantic}),i=>` line ${xe(i.line)}`)}));I.command("trace <symbol>").description("Trace a symbol: definition + all references").option("--full","Run unbounded semantic analysis on large indexes").action((e,t)=>R(n=>{let r=A(n,"trace",!!t.full),i=x.trace(n,e,{semantic:r.semantic}),s=[];for(let l of i.definitions){let c=l.signature?` \u2014 ${l.signature}`:"";s.push(` ${ge(l.relativePath,l.startLine,l.endLine)}${c}`),l.source&&s.push(l.source.split(`
977
- `).map((u,d)=>` ${xe(l.startLine+d)} ${u}`).join(`
978
- `))}let o=[],a="";for(let l of i.referencedBy)l.relativePath!==a&&(a&&o.push(""),o.push(` ${l.relativePath}`),a=l.relativePath),o.push(` line ${xe(l.line)} in ${l.enclosingShort}`);S.sectionedReport([{title:"DEFINITION",rows:s},{title:"REFERENCED BY",rows:o}])}));I.command("deps <file>").description("Files this file depends on (internal)").action(e=>R(t=>{S.list(x.deps(t,e),n=>n.relativePath)}));I.command("rdeps <file>").description("Files that depend on this file/module").action(e=>R(t=>{S.list(x.rdeps(t,e),n=>n.relativePath)}));I.command("system <module>").description("Full module map: files, symbols, deps in/out").action(e=>R(t=>{let n=x.system(t,e);S.sectionedReport([{title:"FILES",rows:n.files},{title:"EXPORTED SYMBOLS",rows:n.symbols.map(r=>` ${pe(r.startLine,r.endLine)} ${r.shortName}`)},{title:"DEPENDS ON (internal)",rows:n.dependsOn.map(r=>` ${r}`)},{title:"DEPENDED ON BY",rows:n.dependedOnBy.map(r=>` ${r}`)}])}));I.command("surface <module>").description("What symbols consumers actually use from this module").action(e=>R(t=>{S.list(x.surface(t,e),n=>` ${n.consumer} \u2192 ${n.shortName}`)}));I.command("dead [scope]").description("Find dead code and file-internal symbols (no cross-file consumers)").option("--min-loc <n>","Only show symbols >= N lines",E,1).option("--include-tests","Include test files").option("--skip-barrels","Ignore refs from barrel re-export files").option("--include-members","Include class members").option("--only-dead","Show only [dead code] symbols (skip [file-internal only])").option("--only-internal","Show only [file-internal only] symbols (skip [dead code])").option("--full","Run unbounded semantic analysis on large indexes").action((e,t)=>R(n=>{let r=A(n,"dead",!!t.full),i={scope:e||void 0,minLoc:t.minLoc,includeTests:t.includeTests,skipBarrels:t.skipBarrels,includeMembers:t.includeMembers,scanLimit:r.scanLimit,semantic:r.semantic},s=x.dead(n,i),o=s.symbols.filter(g=>g.kind==="dead-code"),a=s.symbols.filter(g=>g.kind!=="dead-code"),l=!t.onlyInternal,c=!t.onlyDead,u=l?o:[],d=c?a:[];if(u.length===0&&d.length===0)return S.empty("No matching dead-code symbols found.");let m=(g,b,_,P)=>{console.log(`\u2550\u2550\u2550 ${b} (${g.length}, ${P} LOC) \u2550\u2550\u2550`),console.log(_),console.log("");let L=new Map;for(let T of g){let D=L.get(T.relativePath)??[];D.push(T),L.set(T.relativePath,D)}let C=[...L.entries()].map(([T,D])=>({file:T,bucket:D,totalLoc:D.reduce(($,Y)=>$+Y.loc,0)})).sort((T,D)=>D.totalLoc-T.totalLoc||T.file.localeCompare(D.file)),v=!0;for(let{file:T,bucket:D}of C){v||console.log(""),v=!1,console.log(` ${T}`),D.sort(($,Y)=>$.startLine-Y.startLine);for(let $ of D)console.log(` ${pe($.startLine,$.endLine)} (${$.loc} LOC) ${$.shortName}`)}},f=u.reduce((g,b)=>g+b.loc,0),h=d.reduce((g,b)=>g+b.loc,0);u.length>0&&m(u,"DEAD CODE",` Zero references anywhere \u2014 no cross-file callers AND no same-file uses.
979
- Safe to delete.`,f),d.length>0&&(u.length>0&&console.log(""),m(d,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
739
+ No issues found. Codebase is clean.`)}function Tl(e){return rt(t=>{let n=qt(t,{base:e.base});if(n.note)return br(t,{base:e.base});if(n.changedFiles.length===0)return br(t,{base:e.base});let r=[];for(let i of KS(n.changedFiles,VS))r.push(GS(i,e));return xr(n.changedFiles,r)})}function GS(e,t){let n=process.argv[1]??El(import.meta.url),r=[...process.execArgv,n,Lr];t.base&&r.push("--base",t.base);let i=Ll(process.execPath,r,{cwd:process.cwd(),env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},encoding:"utf8",maxBuffer:10*1024*1024});if(i.status!==0){let o=i.stderr.trim();throw new Error(`Diff-impact batch failed${o?`:
740
+ ${o}`:""}`)}return JSON.parse(i.stdout)}function Ml(e){console.log(`Changed files: ${e.summary.totalChangedFiles}`),console.log(`Changed symbols: ${e.summary.totalChangedSymbols}`),console.log(`Affected consumer files: ${e.summary.totalAffectedFiles}`),e.summary.note&&console.log(`Note: ${e.summary.note}`),console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),N.list(e.changedSymbols,t=>` ${t.file} ${t.shortName} (fan-in: ${t.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
741
+ Affected consumer files:`),N.list(e.affectedConsumers,t=>` ${t.file} (${t.consumedSymbols} symbol(s))`))}function KS(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}var Ol=Vo,D=(e=>parseInt(e,10)),Er=(e=>{let t=parseInt(e,10);if(!Number.isFinite(t)||t<1)throw new Error(`Expected a positive integer, got ${e}`);return t}),wr=parseFloat,qo=parseInt;function g(e,t,n,...r){return r.length>0?{flags:e,description:t,parser:n,defaultValue:r[0]}:{flags:e,description:t,parser:n}}function S(e,t=[]){return{category:e,examples:t}}import{existsSync as Go,mkdirSync as tx,symlinkSync as nx,readlinkSync as rx,unlinkSync as ix}from"fs";import{join as kr,dirname as jl,resolve as Ko}from"path";import{homedir as Bl,platform as ox}from"os";import{fileURLToPath as sx}from"url";import{execFileSync as Fl}from"child_process";import{platform as Uo,arch as ZS}from"os";import{execFileSync as QS}from"child_process";import{platform as YS}from"os";var XS=YS()==="win32";function xe(e){let t=XS?"where":"which";try{return QS(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var Al="v0.7.0";function Jo(){return xe("scip")}function ex(){let e=Uo(),t=ZS(),n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";break;case"win32":n="windows",i="zip";break;default:return null}switch(t){case"arm64":r="arm64";break;case"x64":r="amd64";break;default:return null}let o=`scip-${n}-${r}.${i}`;return{url:`https://github.com/sourcegraph/scip/releases/download/${Al}/${o}`,filename:o}}function zo(){let e=ex();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Uo()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
742
+ `),console.log("Or download manually:")):console.log("Download from:"),console.log(e?` ${e.url}
743
+ `:` https://github.com/sourcegraph/scip/releases/tag/${Al}
744
+ `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function $l(e){if(Uo()==="darwin"&&xe("brew")){e("Installing scip CLI via Homebrew...");try{if(Fl("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),xe("scip"))return e("Successfully installed scip CLI via Homebrew"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`Homebrew install failed: ${n}`)}}if(xe("go")){e("Installing scip CLI via go install...");try{if(Fl("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),xe("scip"))return e("Successfully installed scip CLI via go install"),!0}catch(t){let n=t instanceof Error?t.message:String(t);e(`go install failed: ${n}`)}}return e("Could not auto-install scip CLI."),e("Install manually from: https://github.com/sourcegraph/scip/releases"),!1}var ax=ox()==="win32",Qo=["concrete-plan","scip-explore","scip-debloat","scip-verify","scip-language-playbook"];function Hl(e={}){let t=e.quiet?()=>{}:console.log,n=sx(import.meta.url),r=Ko(jl(n),"..","skills"),i=[kr(Bl(),".claude","skills"),kr(Bl(),".codex","skills")],o={installed:[],skipped:[],alreadyLinked:[]};for(let s of i){let a=jl(s);if(!Go(a))continue;tx(s,{recursive:!0});let c=s.includes(".codex")?"Codex":"Claude";for(let l of Qo){let u=kr(r,l),m=kr(s,l);if(!Go(u)){o.skipped.push(`${c}/${l}`);continue}if(Go(m)){try{let d=rx(m);if(Ko(d)===Ko(u)){o.alreadyLinked.push(`${c}/${l}`),t(` ok: ${l} \u2192 ${c} (already linked)`);continue}}catch{o.skipped.push(`${c}/${l}`),t(` skip: ${l} \u2192 ${c} (exists, not a symlink)`);continue}ix(m)}nx(u,m,ax?"junction":"dir"),o.installed.push(`${c}/${l}`),t(` done: ${l} \u2192 ${c}`)}}return o}import{existsSync as Wu}from"fs";import{execFileSync as SI}from"child_process";import{closeSync as xI,existsSync as ps,mkdirSync as Pu,mkdtempSync as CI,openSync as II,readFileSync as RI,renameSync as fs,rmSync as gs,writeFileSync as Tu}from"fs";import{basename as jr,dirname as It,extname as _I,join as je}from"path";import cx from"better-sqlite3";import{execFileSync as lx}from"child_process";import{existsSync as ux,readdirSync as mx,readFileSync as dx}from"fs";import{extname as Pr,join as Wl}from"path";function it(e){let t=new Set((e.extensions??ya).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!ux(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Jt(e.projectRoot),r=px(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new cx(e.dbPath);try{let o=gx(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
745
+ VALUES (?, ?, NULL, ?)`),c=i.transaction(u=>{let m=0;for(let d of u){if(o.has(d))continue;let p=dx(Wl(e.projectRoot,d),"utf-8"),y=s.run(hx(d),d,p);m+=Number(y.changes)}return m})(r),l={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${l.existing} already present).`),l}finally{i.close()}}function px(e,t){let n=fx(e,t);if(n)return n;let r=[],i=o=>{let s=o?Wl(e,o):e,a;try{a=mx(s,{withFileTypes:!0})}catch{return}for(let c of a){if(Ci.has(c.name))continue;let l=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(l);continue}t.has(Pr(c.name).toLowerCase())&&r.push(l)}};return i(""),r.sort()}function fx(e,t){try{return lx("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
746
+ `).filter(r=>r&&t.has(Pr(r).toLowerCase())).sort()}catch{return null}}function gx(e,t){let n=new Set,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),s=e.prepare(`SELECT relative_path FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let a of s)n.add(a.relative_path)}return n}function hx(e){return Pr(e).toLowerCase()===".vue"?"vue":Pr(e).replace(/^\./,"").toLowerCase()||"source"}import{execFileSync as yx}from"child_process";import{existsSync as bx,readdirSync as ql}from"fs";import{extname as Ul,join as Jl}from"path";var Sx=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),xx=[{language:"typescript",files:["tsconfig.json","tsconfig.base.json"],extensions:[".ts",".tsx",".mts",".cts"]},{language:"rust",files:["Cargo.toml"],extensions:[".rs"]},{language:"go",files:["go.mod"],extensions:[".go"]},{language:"java",files:["pom.xml","build.gradle","build.gradle.kts"],extensions:[".java"]},{language:"kotlin",files:["build.gradle.kts"],extensions:[".kt",".kts"]},{language:"scala",files:["build.sbt"],extensions:[".scala"]},{language:"python",files:["pyproject.toml","setup.py","setup.cfg","Pipfile"],extensions:[".py",".pyi"]},{language:"ruby",files:["Gemfile"],extensions:[".rb"]},{language:"cpp",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"]},{language:"c",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".c",".h"]},{language:"csharp",globs:["*.csproj","*.sln"],extensions:[".cs"]},{language:"vb",globs:["*.vbproj"],extensions:[".vb"]},{language:"dart",files:["pubspec.yaml"],extensions:[".dart"]},{language:"php",files:["composer.json"],extensions:[".php"]},{language:"javascript",files:["package.json"],extensions:[".js",".jsx",".mjs",".cjs"]}];function xt(e){let t=[],n=Cx(e),r=vx(e);for(let i of xx){if(Ix(e,i.files)){t.push(i.language);continue}if(Rx(n,i.globs)){t.push(i.language);continue}Nx(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&Vl(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&Vl(t,"c"),t}function Cx(e){try{return ql(e)}catch{return[]}}function Ix(e,t){return t?.length?t.some(n=>bx(Jl(e,n))):!1}function Rx(e,t){return t?.length?e.some(n=>t.some(r=>_x(n,r))):!1}function _x(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,r]=t.split("*");return e.startsWith(n??"")&&e.endsWith(r??"")}function vx(e){let t=Dx(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let o;try{o=ql(i,{withFileTypes:!0})}catch{continue}for(let s of o){if(s.name.startsWith(".")&&!s.name.endsWith("proj")&&!s.name.endsWith("sln")&&s.isDirectory())continue;let a=Jl(i,s.name);if(s.isDirectory()){Sx.has(s.name)||r.push(a);continue}let c=Ul(s.name).toLowerCase();c&&n.add(c)}}return n}function Dx(e){try{let t=yx("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}),n=new Set;for(let r of t.split(`
747
+ `)){if(!r)continue;let i=Ul(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Nx(e,t){return t?.length?t.some(n=>e.has(n)):!1}function Vl(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as zl,readdirSync as Lx}from"fs";import{join as Yo}from"path";var Ex={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n})=>{let r=["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&r.splice(1,0,"--pnpm-workspaces"),{binary:n,args:r}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:"rust",indexerBinary:"rust-analyzer",checkCommand:"rust-analyzer --version",indexArgs:({outputPath:e})=>({binary:"rust-analyzer",args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:"https://github.com/rust-lang/rust-analyzer"},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Gl(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Gl(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:["pubspec.yaml"],installMethods:[{label:"dart pub",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({projectRoot:e,indexerBinary:t})=>{let n=Yo(e,"vendor","bin","scip-php"),r=Yo(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",zl(r)?r:zl(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Tr(e){return Ex[e]}function Gl(e,t){let n;try{n=Lx(e)}catch{return null}for(let r of n)if(t.some(i=>r.endsWith(i)))return Yo(e,r);return null}import{readFileSync as wx,writeFileSync as kx}from"fs";import{create as Xo}from"@bufbuild/protobuf";import{deserializeSCIP as Px,serializeSCIP as Tx,DocumentSchema as Mx,IndexSchema as Ox,SymbolInformationSchema as Fx}from"@c4312/scip";function Ax(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=$x(e),n=jx(e.flatMap(i=>i.documents??[])),r=Ql(e.flatMap(i=>i.externalSymbols??[]));return Xo(Ox,{metadata:t,documents:n,externalSymbols:r})}function Kl(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Px(wx(i))),r=Ax(n);return kx(t,Buffer.from(Tx(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function $x(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function jx(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,Xo(Mx,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:[...r.occurrences,...n.occurrences],symbols:Ql([...r.symbols,...n.symbols]),text:Hx(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Ql(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,Xo(Fx,{symbol:r.symbol,documentation:Wx([...r.documentation,...n.documentation]),relationships:Bx([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function Bx(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function Hx(e,t){return e?t?e.length>=t.length?e:t:e:t}function Wx(e){return[...new Set(e)]}import{execFileSync as Vx}from"child_process";import{createHash as qx}from"crypto";import{readdirSync as Ux,readFileSync as Jx}from"fs";import{join as Yl}from"path";function zx(e){return(Gx(e)??Kx(e)).filter(t=>t&&!Xl(t)).sort()}function Mr(e){return zx(e).map(t=>{let n=Yl(e,t);try{let r=Jx(n);return{path:t,size:r.byteLength,hash:qx("sha256").update(r).digest("hex")}}catch{return{path:t,size:-1,hash:"unreadable"}}})}function Gx(e){try{return Vx("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"]}).split(`
748
+ `).filter(Boolean)}catch{return null}}function Kx(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?Yl(e,r):e,o;try{o=Ux(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=r?`${r}/${s.name}`:s.name;if(s.isDirectory()){Xl(a)||n.push(a);continue}t.push(a)}}return t}function Xl(e){return e.split("/").some(n=>Qx.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var Qx=new Set([".git","node_modules",".scipquery-cache",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]);import{readFileSync as Yx,writeFileSync as Xx}from"fs";import{create as Zl}from"@bufbuild/protobuf";import{deserializeSCIP as Zx,DocumentSchema as eC,IndexSchema as tC,serializeSCIP as nC,SymbolRole as rC}from"@c4312/scip";function eu(e){let t;try{t=Zx(Yx(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=iC(t);return n.removedDefinitionOccurrences>0&&Xx(e,Buffer.from(nC(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function iC(e){let t=new Set;for(let o of e.documents)for(let s of o.symbols)s.symbol&&t.add(s.symbol);for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,r=0,i=[];for(let o of e.documents){let s=o.occurrences.filter(a=>(a.symbolRoles&rC.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(Zl(eC,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:Zl(tC,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}import{execFile as oC}from"child_process";import{existsSync as Or,renameSync as es,rmSync as ts}from"fs";import{cpus as sC}from"os";import{join as tu}from"path";function aC(e,t,n){if(!e.defaultOutputPath)return;let r=tu(t,e.defaultOutputPath);n!==r&&Or(r)&&es(r,n)}function cC(e,t,n){if(!e.defaultOutputPath)return null;let r=tu(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return ts(i,{force:!0}),Or(r)?(es(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function lC(e){e&&(ts(e.defaultOutputPath,{force:!0}),e.backupPath&&Or(e.backupPath)&&es(e.backupPath,e.defaultOutputPath))}function uC(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(2,Math.max(1,sC().length-1));return Math.max(1,Math.min(e,Math.floor(r)))}async function nu(e,t,n,r){let i=e.filter(l=>l.config.defaultOutputPath),o=e.filter(l=>!l.config.defaultOutputPath),s=[],a=uC(o.length,r),c=await dC(o,a,l=>Zo(l,t,n));if(a>1){let l=new Map;for(let u of c.filter(m=>m.skipped)){let m=o.find(d=>d.language===u.language);m&&(n(`Retrying ${m.language} indexer serially after parallel failure...`),l.set(m.language,await Zo(m,t,n)))}s.push(...c.map(u=>l.get(u.language)??u))}else s.push(...c);for(let l of i)s.push(await Zo(l,t,n));return s.sort((l,u)=>e.findIndex(m=>m.language===l.language)-e.findIndex(m=>m.language===u.language))}async function Zo(e,t,n){n(`Indexing ${e.language} with ${e.resolvedBinary}...`),ts(e.scipPath,{force:!0});let r=cC(e.config,t,e.scipPath);try{await mC(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),aC(e.config,t,e.scipPath)}catch(i){let o=i instanceof Error?i.message:String(i),s=`${e.resolvedBinary} indexer failed: ${o.split(`
749
+ `)[0]}`;return n(`Skipping ${e.language}: ${s}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:s}}}finally{lC(r)}if(!Or(e.scipPath)){let i=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`;return n(`Skipping ${e.language}: ${i}`),{language:e.language,scipPath:e.scipPath,skipped:{language:e.language,reason:i}}}return{language:e.language,scipPath:e.scipPath}}function mC(e,t,n){return new Promise((r,i)=>{oC(e,[...t],n,o=>{o?i(o):r()})})}async function dC(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=0,o=Math.max(1,Math.min(e.length,t)),s=Array.from({length:o},async()=>{for(;i<e.length;){let a=i++;r[a]=await n(e[a])}});return await Promise.all(s),r}import{execFileSync as rs}from"child_process";import{existsSync as ns,readFileSync as pC}from"fs";import{createRequire as fC}from"module";import{platform as gC}from"os";import{dirname as ru,join as Fr}from"path";var hC=fC(import.meta.url);function is(e){return[e.indexerBinary,...e.binaryAliases??[]]}function Ar(e){let t=is(e);return t.length===1?t[0]:t.join(" or ")}function Qt(e){for(let t of is(e))if(xe(t))return t;return bC(e)}function iu(e){return Qt(e)!==null||yC(e)}function yC(e){return ou(e)!==null}function bC(e){let t=ou(e);if(!t)return null;let r=JSON.parse(pC(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return Fr(ru(t),r);for(let i of is(e)){let o=r[i];if(o)return Fr(ru(t),o)}return null}function ou(e){if(!e.bundledNpmPackage)return null;try{return hC.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function os(e,t){for(let n of e.projectLocalBinaries??[]){let r=Fr(t,n);if(ns(r))return r}return null}function SC(e,t){return os(e,t)??Qt(e)}function su(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||ss(n,t))return t;let r=lu(n,t);return r?{...t,DOTNET_ROOT:r}:t}function au(e,t){let n=Ar(e),r=t?SC(e,t):Qt(e);if(!r)return{language:e.language,binaryLabel:n,installed:!1,runnable:!1,resolvedBinary:null,installUrl:e.installUrl};if(e.indexerBinary!=="scip-dotnet")return{language:e.language,binaryLabel:n,installed:!0,runnable:!0,resolvedBinary:r};let i=xC(r);return{language:e.language,binaryLabel:n,installed:!0,runnable:i.runnable,resolvedBinary:r,installUrl:e.installUrl,note:i.note}}function cu(e,t){let n=e.installMethods,r=Ar(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n)if(xe(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{rs(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env});let o=Qt(e);if(o){let s=o===e.indexerBinary?"":` (using ${o})`;return t(`Successfully installed ${r} via ${i.label}${s}`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(o){let s=o instanceof Error?o.message:String(o);t(`${i.label} install failed: ${s}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function xC(e){if(ss(e,process.env))return{runnable:!0};let t=lu(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=uu(process.env);return{runnable:!1,note:n.length>0?`.NET 9 runtime still unavailable after checking ${n.join(", ")}`:"binary is present, but scip-dotnet still needs a .NET 9 runtime"}}function lu(e,t){for(let n of uu(t))if(ss(e,{...t,DOTNET_ROOT:n}))return n;return null}function uu(e){let t=[],n=e.DOTNET_ROOT;if(n&&ns(n)&&t.push(n),gC()==="darwin"&&xe("brew"))try{let r=rs("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=Fr(r,"libexec");ns(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function ss(e,t){try{return rs(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import eI from"better-sqlite3";import{existsSync as tI,readFileSync as nI,writeFileSync as rI}from"fs";import{dirname as iI,join as oI,resolve as sI}from"path";import{readFileSync as CC,rmSync as IC,statSync as RC,mkdtempSync as _C}from"fs";import{cpus as vC,tmpdir as DC}from"os";import{join as as}from"path";import{Worker as NC}from"worker_threads";function mu(e){return e.length>=8&&pu(e.length)>1}function du(e){let t=pu(e.vueFiles.length),n=EC(e.vueFiles),r=kC(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=_C(as(DC(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),c=LC(),l=Date.now();try{for(let m=0;m<r.length;m++)new NC(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[m],resultPath:as(o,`${m}.json`),sharedBuffer:s}});for(;Atomics.load(a,0)<r.length;){if(Date.now()-l>c)throw new Error(`Vue reference workers timed out after ${(c/1e3).toFixed(0)}s`);Atomics.wait(a,0,Atomics.load(a,0),100)}let u=r.map((m,d)=>{let p=JSON.parse(CC(as(o,`${d}.json`),"utf-8"));if(!p.ok)throw new Error(`Vue reference worker failed: ${p.error}`);return p.result});return{occurrences:u.flatMap(m=>m.occurrences),skippedReferences:u.reduce((m,d)=>m+d.skippedReferences,0)}}finally{IC(o,{recursive:!0,force:!0})}}function pu(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:Math.min(8,Math.max(1,vC().length-1));return Math.max(1,Math.min(e,n))}function LC(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function EC(e){let t=wC(),n=[];for(let r of e){let i=fu(r),o=Math.max(1,Math.ceil(i/t));for(let s=0;s<o;s++)n.push({fileName:r,startOffset:Math.floor(i*s/o),endOffset:s===o-1?Number.POSITIVE_INFINITY:Math.floor(i*(s+1)/o),countFileSkip:s===0})}return n}function wC(){return Number.POSITIVE_INFINITY}function kC(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:PC(i)})).sort((i,o)=>o.weight-i.weight);for(let i of r){let o=n.reduce((s,a)=>a.weight<s.weight?a:s);o.tasks.push(i.task),o.weight+=i.weight}return n.map(i=>i.tasks).filter(i=>i.length>0)}function PC(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,fu(e.fileName)-e.startOffset)}function fu(e){try{return RC(e).size}catch{return 1}}import{createRequire as TC}from"module";import{existsSync as MC,readFileSync as ls}from"fs";import{dirname as gu,extname as OC,join as hu,relative as FC,resolve as AC}from"path";import{pathToFileURL as $C}from"url";function jC(e){e.transaction(()=>{e.prepare(`
750
+ DELETE FROM mentions
751
+ WHERE chunk_id IN (
752
+ SELECT c.id
753
+ FROM chunks c
754
+ JOIN documents d ON d.id = c.document_id
755
+ WHERE d.language = 'vue' OR d.relative_path LIKE '%.vue'
756
+ )
757
+ `).run(),e.prepare(`
758
+ DELETE FROM chunks
759
+ WHERE document_id IN (
760
+ SELECT id
761
+ FROM documents
762
+ WHERE language = 'vue' OR relative_path LIKE '%.vue'
763
+ )
764
+ `).run()})()}function yu(e,t){return e.prepare(`
765
+ SELECT relative_path AS relativePath
766
+ FROM documents
767
+ WHERE language = 'vue' OR relative_path LIKE '%.vue'
768
+ ORDER BY relative_path
769
+ `).all().map(r=>AC(t,r.relativePath))}function bu(e,t){let{vueCore:n,ts:r,volarTs:i}=BC(e),{parsed:o,vueOptions:s}=HC(n,r,t),a=gu(t),c=n.createVueLanguagePlugin(r,o.options,s,p=>p),l=WC(n,r,c),u=VC(a,o),{languageServiceHost:m}=i.createLanguageServiceHost(r,r.sys,l,p=>p,u),d=r.createLanguageService(m);return{ts:r,language:l,languageService:d,fileNames:o.fileNames,configDir:a}}function BC(e){let t=TC($C(hu(e,"package.json")).href);return{vueCore:cs(t,"@vue/language-core",e),ts:cs(t,"typescript",e),volarTs:cs(t,"@volar/typescript",e)}}function HC(e,t,n){let r=t.readConfigFile(n,t.sys.readFile);if(r.error||!r.config)throw new Error(`Failed to read ${n}`);let o=e.createParsedCommandLine(t,t.sys,n).vueOptions;return typeof e.createGlobalTypesWriter=="function"&&(o.globalTypesPath=e.createGlobalTypesWriter(o,t.sys.writeFile)),{parsed:t.parseJsonConfigFileContent(r.config,t.sys,gu(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function WC(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!MC(o))return;let s=ls(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??KC(o))});return r.current=i,i}function VC(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function cs(e,t,n){try{return e(t)}catch(r){throw(typeof r=="object"&&r!==null&&"code"in r?r.code:null)==="MODULE_NOT_FOUND"?new Error(`Vue augmentation requires ${t} to be installed in ${n}. Install Vue/Volar dependencies for that project, then rerun augment-vue.`,{cause:r}):r}}function Su(e,t,n){let r=qC(e);return i=>{let o=Ct(t,i.fileName),s=n.get(i.fileName);if(!s)return null;let a=n.positionAt(s,i.textSpan.start),c=r.get(o);if(!c)return null;let l=c.containingByLine.get(a.line);return l!==void 0?l:UC(c.starts,a.line,2)}}function qC(e){let t=e.prepare(`
770
+ SELECT
771
+ d.relative_path AS relativePath,
772
+ der.start_line AS startLine,
773
+ der.end_line AS endLine,
774
+ der.symbol_id AS symbolId
775
+ FROM defn_enclosing_ranges der
776
+ JOIN documents d ON d.id = der.document_id
777
+ ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
778
+ `).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,r.symbolId)}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function UC(e,t,n){let r=0,i=e.length-1;for(;r<=i;){let s=Math.floor((r+i)/2);e[s].line<t?r=s+1:i=s-1}let o=null;for(let s of[i,r]){let a=e[s];if(!a)continue;let c=Math.abs(a.line-t);c>n||(!o||c<o.distance)&&(o={distance:c,symbolId:a.symbolId})}return o?.symbolId??null}function xu(e,t,n){let r=XC(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
779
+ INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
780
+ VALUES (?, ?, ?, ?)
781
+ `),s=0,a=new Map;return e.transaction(()=>{for(let l of n){let u=Ct(t,l),m=Eu(r.name,r.version,u);o.run(m,"default",7,`Vue component|${u}`);let d=ZC(i,r,t,l);d&&(s++,a.set(l,d))}})(),{get(l){return a.get(l)??null},syntheticSymbols:s}}function Cu(e,t,n,r,i){return e.transaction(()=>(jC(e),JC(e,t,n,r),zC(e,i)))()}function JC(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
782
+ INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
783
+ VALUES (?, ?, ?, ?, X'00')
784
+ `),s=e.prepare(`
785
+ INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
786
+ VALUES (?, ?, 1)
787
+ `);for(let a of n){let c=r.get(a);if(!c)continue;let l=Ct(t,a),u=i.get(l);if(!u)continue;let m=o.run(u.id,-1,0,0);s.run(Number(m.lastInsertRowid),c)}}function Iu(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let o=r.language.scripts.get(e.fileName),s=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&s){let a=r.language.maps.get(s,o);if(us(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Ru(e){let t=new Set,n=[];for(let r of e){let i=_u(r);t.has(i)||(t.add(i),n.push(r))}return n}function _u(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function zC(e,t){let n=YC(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
788
+ INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
789
+ VALUES (?, ?, ?, ?, X'00')
790
+ `),i=e.prepare(`
791
+ INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
792
+ VALUES (?, ?, 0)
793
+ `),o=new Set,s=0,a=0;for(let c of t){let l=_u(c);if(o.has(l))continue;o.add(l);let u=n.get(c.sourceFile);if(!u)continue;let m=r.run(u,a++,c.sourceLine,c.sourceLine),d=i.run(Number(m.lastInsertRowid),c.symbolId);s+=Number(d.changes)}return s}function*vu(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function Du(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function us(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function GC(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let o=Math.floor((n+r)/2);e.lineStarts[o]<=t?n=o+1:r=o-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function Nu(e,t){return Ct(e,t).startsWith("node_modules/")}function Ct(e,t){return FC(e,t).replaceAll("\\","/")}function KC(e){switch(OC(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function Lu(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=ls(t,"utf-8"),r={text:n,lineStarts:QC(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:GC}}function QC(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function YC(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),s=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let a of s)n.set(a.relativePath,a.id)}return n}function XC(e){try{let t=JSON.parse(ls(hu(e,"package.json"),"utf-8"));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function ZC(e,t,n,r){let i=Ct(n,r),o=Eu(t.name,t.version,i);return e.get(o)?.id??null}function Eu(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function ms(e){it({projectRoot:e.projectRoot,dbPath:e.dbPath});let t=sI(e.projectRoot,e.tsconfig);if(!tI(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new eI(e.dbPath);try{let r=yu(n,e.projectRoot),i=oI(iI(e.dbPath),"augment-vue-meta.json"),o=wu(n,e.projectRoot,e.tsconfig),s=aI(i,o,e.onStatus);if(s)return s;let a=cI({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus});return mI(i,wu(n,e.projectRoot,e.tsconfig),a),a}finally{n.close()}}function aI(e,t,n){let r=uI(e,t);return r&&n?.(`Vue references unchanged; reused ${r.resolvedReferences} cached resolved references.`),r}function cI(e){let t=xu(e.db,e.projectRoot,e.vueFiles),n=lI(e,t),r=Ru(n.occurrences),i=Cu(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,insertedMentions:i,skippedReferences:n.skippedReferences,syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function lI(e,t){if(mu(e.vueFiles))return du({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=Lu(),r=bu(e.projectRoot,e.configPath);return dI({projectRoot:e.projectRoot,vueFiles:r.fileNames.filter(i=>i.endsWith(".vue")),context:r,symbolLookup:Su(e.db,e.projectRoot,n),vueSymbolLookup:t,sourceReader:n})}function uI(e,t){try{let n=JSON.parse(nI(e,"utf-8"));return JSON.stringify(n.fingerprint)===JSON.stringify(t)?n.result:null}catch{return null}}function mI(e,t,n){rI(e,JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)+`
794
+ `)}function wu(e,t,n){let r=e.prepare(`
795
+ SELECT
796
+ (SELECT COUNT(*) FROM documents) AS documents,
797
+ (SELECT COUNT(*) FROM global_symbols) AS symbols,
798
+ (SELECT COUNT(*) FROM chunks) AS chunks,
799
+ (SELECT COUNT(*) FROM mentions) AS mentions,
800
+ (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
801
+ (SELECT MAX(id) FROM chunks) AS maxChunkId,
802
+ (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
803
+ `).get();return{version:2,tsconfig:n,files:Mr(t),db:r}}function dI(e){let t=[],n=0,r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=pI(e,i);t.push(...o.occurrences),n+=o.skippedReferences}return{occurrences:t,skippedReferences:n}}function pI(e,t){let n=e.context.language.scripts.get(t.fileName),r=n?.generated?.languagePlugin.typescript?.getServiceScript(n.generated.root)?.code;if(!n||!r)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let i=e.sourceReader.get(t.fileName);if(!i)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let o=e.context.language.maps.get(r,n),s=Ct(e.projectRoot,t.fileName),a=[...vu(i.text)],c={tokens:a.filter(l=>l.start>=t.startOffset&&l.start<t.endOffset),tokenByStart:new Map(a.map(l=>[l.start,l])),tokenTextCounts:hI(a),processedStarts:new Set};return fI({...e,fileName:t.fileName,sourceInfo:i,sourceFile:s,map:o,tokenContext:c})}function fI(e){let t=[],n=0;for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start))continue;let i=Du(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(c=>!Nu(e.projectRoot,c.fileName));if(!s){n++;continue}let a=Iu(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}ku(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a),e.tokenContext.processedStarts.add(r.start),gI(t,e,r,i,a)}return{occurrences:t,skippedReferences:n}}function gI(e,t,n,r,i){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let o of yI(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(o))continue;let s=t.tokenContext.tokenByStart.get(o);s&&(ku(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i),t.tokenContext.processedStarts.add(o))}}function ku(e,t,n,r,i,o){let s=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,symbolId:o})}function hI(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function yI(e,t,n,r,i,o){let s=e.getDocumentHighlights?.(t,n,[t])??[],a=[];for(let c of s)if(c.fileName===t)for(let l of c.highlightSpans){let u=bI(r,l.textSpan.start,o,i.text);u!==null&&a.push(u)}return a}function bI(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=us(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function Mu(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=vI(e),s=Date.now();Pu(It(o.outputScip),{recursive:!0}),Pu(It(o.outputDb),{recursive:!0});let a=e.languages??xt(t);if(a.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${a.join(", ")}`);let c=HI(t,a,{pnpmWorkspaces:e.pnpmWorkspaces}),l=jI(je(It(o.outputDb),"index.lock")),u=null;try{let m=DI({opts:e,paths:o,languages:a,fingerprint:c,start:s,onStatus:r});if(m)return m;kI(i,r);let d=NI(o);return u=d.runDir,await LI({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:d,fingerprint:c,start:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r})}finally{u&&gs(u,{recursive:!0,force:!0}),l()}}function vI(e){let t=e.outputScip??je(e.projectRoot,"index.scip"),n=e.outputDb??je(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:je(It(n),"meta.json")}}function DI(e){if(e.opts.skipIfUnchanged===!1||!ps(e.paths.outputScip)||!ps(e.paths.outputDb)||!WI(e.paths.metaPath,e.fingerprint))return null;it({projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let t=Date.now()-e.start;return e.onStatus(`Index unchanged; reused existing SQLite index in ${(t/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:t,reused:!0,skipped:[]}}function NI(e){let t=CI(je(It(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:je(t,jr(e.outputScip)),tempOutputDb:je(t,jr(e.outputDb)),tempMetaPath:je(t,jr(e.metaPath))}}async function LI(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:r}=await EI(e,t);wI(e,t,n,r);let i=Date.now()-e.start;return e.onStatus(`Done in ${(i/1e3).toFixed(1)}s`),{languages:n.map(o=>o.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:i,reused:!1,skipped:r}}async function EI(e,t){let{preparedRuns:n,skippedLanguages:r}=PI({languages:e.languages,tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,onStatus:e.onStatus}),i=await nu(n,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),{indexedOutputs:o}=MI(i,r);return OI(o,r,e.languages,e.opts.allowPartial,e.onStatus),{indexedOutputs:o,skippedLanguages:r}}function wI(e,t,n,r){FI(n,e.tempPaths.tempOutputScip,e.onStatus),AI(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),it({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),VI(e.tempPaths.tempMetaPath,{version:2,status:r.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.fingerprint,requestedLanguages:e.languages,indexedLanguages:n.map(i=>i.language),skipped:[...r]}),BI({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath})}function kI(e,t){if(!xe("scip")){if(e)throw new Error(`The scip CLI is required but not found on PATH.
804
+ Install from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!$l(t))throw new Error(`The scip CLI is required but could not be installed.
805
+ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function PI(e){let t=[],n=[],r=e.languages.map((i,o)=>({language:i,scipPath:e.languages.length>1?$I(e.tempOutputScip,i,o):e.tempOutputScip}));for(let{language:i,scipPath:o}of r){let s=TI({...e,language:i,scipPath:o});"skipped"in s?n.push(s.skipped):t.push(s.prepared)}return{preparedRuns:t,skippedLanguages:n}}function TI(e){let t=Tr(e.language),n=Ar(t),r=os(t,e.projectRoot);if(!r&&!iu(t)){if(e.skipAutoInstall){let a=`${n} not found on PATH (auto-install disabled). ${t.installUrl??""}`.trim();return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!cu(t,e.onStatus)){let a=`${n} could not be auto-installed. ${t.installUrl?`Install manually from ${t.installUrl}`:`Install ${n} and put it on PATH.`}`;return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}}let i=r??Qt(t);if(!i){let a=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${a}`),{skipped:{language:e.language,reason:a}}}let{binary:o,args:s}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:i});return{prepared:{language:e.language,scipPath:e.scipPath,config:t,resolvedBinary:i,binary:o,args:s,env:su(t,e.env,i)}}}function MI(e,t){let n=[];for(let r of e)r.skipped?t.push(r.skipped):n.push({language:r.language,scipPath:r.scipPath});return{indexedOutputs:n}}function OI(e,t,n,r,i){if(e.length===0){let o=t.map(s=>` - ${s.language}: ${s.reason}`).join(`
806
+ `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
807
+ `+o)}if(t.length!==0&&(i(`Indexed ${e.length} of ${n.length} languages; skipped ${t.map(o=>o.language).join(", ")}.`),!r))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
808
+ `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
809
+ `))}function FI(e,t,n){e.length>1?(n(`Merging ${e.length} language indexes...`),Kl(e.map(r=>r.scipPath),t)):e[0].scipPath!==t&&fs(e[0].scipPath,t)}function AI(e,t,n,r){if(r("Converting to SQLite..."),!ps(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{let i=eu(e);i.removedDefinitionOccurrences>0&&r(`Sanitized ${i.removedDefinitionOccurrences} invalid definition occurrences across ${i.touchedDocuments} documents before SQLite conversion.`),SI("scip",["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`Failed to convert SCIP index to SQLite: ${o}`,{cause:i})}}function $I(e,t,n){let r=_I(e)||".scip",i=jr(e,r);return je(It(e),`${i}.${n+1}.${t}${r}`)}function jI(e){let t;try{t=II(e,"wx")}catch(n){throw(typeof n=="object"&&n&&"code"in n?n.code:void 0)==="EEXIST"?new Error(`Another scip-query reindex is already running for ${It(e)}.`,{cause:n}):n}return Tu(t,JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()})+`
810
+ `),()=>{try{xI(t)}finally{gs(e,{force:!0})}}}function BI(e){ds(e.tempOutputScip,e.outputScip),ds(e.tempOutputDb,e.outputDb),ds(e.tempMetaPath,e.metaPath)}function ds(e,t){gs(`${t}.tmp-replace`,{force:!0}),fs(e,`${t}.tmp-replace`),fs(`${t}.tmp-replace`,t)}function HI(e,t,n){return{version:1,languages:[...t].sort(),pnpmWorkspaces:n.pnpmWorkspaces===!0,files:Mr(e)}}function WI(e,t){try{let n=JSON.parse(RI(e,"utf-8"));return n.version===2&&n.status==="complete"&&$r(n.fingerprint)===$r(t)&&$r([...n.indexedLanguages??[]].sort())===$r(t.languages)}catch{return!1}}function VI(e,t){Tu(e,`${JSON.stringify(t,null,2)}
811
+ `)}function $r(e){return JSON.stringify(e)}import{createRequire as qI}from"module";var UI=qI(import.meta.url);function Ou(e,t=[]){let n=JI(),r=Pi(e,t),i=r[0];return n?r.length===0?{available:!1,dependencyAvailable:n,reason:"no tsconfig found"}:{available:!0,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r}:{available:!1,dependencyAvailable:n,tsconfigPath:i,tsconfigPaths:r,reason:"ts-morph is not installed"}}function JI(){try{return UI.resolve("ts-morph"),!0}catch{return!1}}function hs(e,t){let n=t.languages??xt(e),r=n.map(o=>{let s=au(Tr(o),e);return{...s,language:o,resolvedBinary:s.resolvedBinary??void 0}}),i=n.includes("typescript")?{language:"typescript",...Ou(e,t.semantic?.typescript?.tsconfigs)}:void 0;return{languages:n,indexers:r,semantic:i}}import{watch as zI}from"fs";import{existsSync as Fu,renameSync as Au}from"fs";import{join as GI,relative as KI}from"path";import{fork as QI}from"child_process";import YI from"ignore";var Br=class{projectRoot;watchConfig;indexPaths;languages;pnpmWorkspaces;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitignoreFilter;extraIgnore;stopped=!1;constructor(t){this.projectRoot=t.projectRoot,this.watchConfig=Rl(t.config),this.indexPaths=Gt(t.projectRoot,t.config),this.languages=t.languages,this.pnpmWorkspaces=t.config.indexer?.typescript?.pnpmWorkspaces??!1,this.onStatus=t.onStatus??(()=>{}),this.onReindexComplete=t.onReindexComplete??(()=>{}),this.onError=t.onError??(n=>console.error(n.message)),this.gitignoreFilter=Jt(t.projectRoot),this.extraIgnore=YI(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"});try{let t=zI(this.projectRoot,{recursive:!0},(n,r)=>{r&&!this.stopped&&this.handleFileChange(r)});this.fsWatchers.push(t)}catch{this.onError(new Error("Failed to start file watcher. On Linux, you may need to increase inotify limits: sysctl -w fs.inotify.max_user_watches=524288"))}}stop(){this.stopped=!0;for(let t of this.fsWatchers)t.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.setStatus({state:"idle"})}handleFileChange(t){let n=KI(this.projectRoot,GI(this.projectRoot,t));if(this.gitignoreFilter.isIgnored(n)||this.extraIgnore.ignores(n)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||t.endsWith(".scipquery.json"))return;if(this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let r=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:r}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let t=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&t<this.watchConfig.cooldownMs){let r=this.watchConfig.cooldownMs-t;this.dirty=!0;let i=Date.now()+r;this.setStatus({state:"cooldown",until:i,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},r);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex().then(r=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(r),this.dirty&&!this.stopped){let i=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:i,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(r=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(r instanceof Error?r:new Error(String(r))),this.setStatus({state:"idle"})})}runReindex(){return new Promise((t,n)=>{let r=Date.now(),i=this.indexPaths.dbPath+".tmp",o=XI(this.indexPaths.indexPath),s=QI(new URL("./reindex-worker.js",import.meta.url).pathname,[],{env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:o,SCIP_REINDEX_OUTPUT_DB:i,SCIP_REINDEX_LANGUAGES:this.languages?.join(",")??"",SCIP_REINDEX_PNPM_WORKSPACES:this.pnpmWorkspaces?"1":""},stdio:"pipe"});s.on("exit",a=>{if(a===0)try{Fu(i)&&Au(i,this.indexPaths.dbPath),Fu(o)&&Au(o,this.indexPaths.indexPath),t(Date.now()-r)}catch(c){n(new Error(`Atomic swap failed: ${c}`))}else n(new Error(`Reindex worker exited with code ${a}`))}),s.on("error",n)})}setStatus(t){this.status=t,this.onStatus(t)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}};function XI(e){return e.endsWith(".scip")?e.slice(0,-5)+".tmp.scip":e+".tmp.scip"}function X(e){return(...t)=>{let{args:n,opts:r}=ZI(t);rt(i=>e({db:i,args:n,opts:r}))}}function Z(e,t){return X(n=>{let r=wl(n.db,e,z(n.opts,"full"));t({...n,budget:r})})}function $u(e){return X(t=>Xt(t,e,{kind:"list"}))}function ju(e){return X(t=>Xt(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function Bu(e){return X(t=>Xt(t,e,{kind:"grouped",key:e.key}))}function Yt(e){return X(t=>ys(t,e))}function Hr(e,t){return Z(e,n=>ys(n,t))}function ot(e,t){return Z(e,n=>Xt(n,t,{kind:"list"}))}function Wr(e,t){return Z(e,n=>Xt(n,t,{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function Vr(e,t){return Z(e,n=>Xt(n,t,{kind:"grouped",key:t.key}))}function M(e,t){return String(e[t])}function ke(e,t){let n=e[t];return typeof n=="string"?n:void 0}function O(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Rt(e,t){let n=e[t];return typeof n=="number"?n:void 0}function z(e,t){return!!e[t]}function Hu(e,t){let n=e[t];return Array.isArray(n)&&n.every(r=>typeof r=="string")?n:[]}function I(e,t,n){return Rt(e,t)??n}function Xt(e,t,n){ys(e,{query:t.query,emptyMessage:(r,i)=>r.length===0&&t.emptyMessage?t.emptyMessage(i):void 0,heuristicLabel:t.heuristicLabel,render:(r,i)=>{n.kind==="list"?N.list(r,o=>t.format(o,i)):n.kind==="table"?N.table(n.headers,r.map(o=>t.format(o,i)),n.dashWidths):N.groupedByFile(r,o=>t.format(o,i),n.key?o=>n.key(o,i):void 0)},after:t.after})}function ys(e,t){let n=t.query(e),r=t.emptyMessage?.(n,e);if(r){N.empty(r);return}t.heuristicLabel&&On(t.heuristicLabel),t.render(n,e),t.after?.(n,e)}function ZI(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:Be(t)}}function Be(e){if(!e||typeof e!="object")return{};let t=e;if(typeof t.opts=="function"){let n=t.opts();return n&&typeof n=="object"?n:{}}return e}var eR=new Set(["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"]);function tR(e){return e.filter(t=>eR.has(t))}async function Vu(e){let t=Be(e),n=nt(),r=zt(n),i=Gt(n,r);try{let o=tR(Hu(t,"language")),s=await Mu({projectRoot:n,languages:o.length>0?o:r.languages,outputScip:i.indexPath,outputDb:i.dbPath,pnpmWorkspaces:z(t,"pnpmWorkspaces")||r.indexer?.typescript?.pnpmWorkspaces,skipIfUnchanged:!z(t,"force"),allowPartial:z(t,"allowPartial"),indexerConcurrency:Rt(t,"indexerConcurrency")});console.log(`${s.reused?"Reused":"Indexed"} ${s.languages.join(", ")} in ${(s.durationMs/1e3).toFixed(1)}s`)}catch(o){console.error(`error: ${o instanceof Error?o.message:o}`),process.exit(1)}}function qu(){let e=nt(),t=Wo(e);try{let n=it({projectRoot:e,dbPath:t,onStatus:r=>console.log(r)});console.log(`Scanned ${n.scanned} auxiliary source files; inserted ${n.inserted}.`)}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Uu(e){let t=Be(e),n=nt(),r=Wo(n);try{let i=ms({projectRoot:n,dbPath:r,tsconfig:O(t,"project")??"frontend/tsconfig.scip.json",onStatus:o=>console.log(o)});console.log(`Vue files: ${i.vueFiles}; resolved references: ${i.resolvedReferences}; inserted mentions: ${i.insertedMentions}.`)}catch(i){console.error(`error: ${i instanceof Error?i.message:i}`),process.exit(1)}}function Ju(e){let t=Be(e);rt(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=qt(n,{base:O(t,"base")}),o=Sr(n,r,i.changedFiles);console.log(JSON.stringify(o))})}function zu(e){let t=Be(e);try{Ml(Tl({base:O(t,"base")}))}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Gu(e,t){let n=Be(t);rt(r=>{Mn.includes(e)||(console.error(`error: Unknown health phase: ${e}`),process.exit(1));let i=Lo(r,e,{scope:O(n,"scope"),full:z(n,"full")});console.log(JSON.stringify(i))})}function Ku(e){let t=Be(e);try{let n=kl({scope:O(t,"scope"),full:z(t,"full"),json:z(t,"json")});Pl(n,z(t,"json"))}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Qu(){let e=Hl(),t=e.installed.length+e.alreadyLinked.length;console.log(`
812
+ ${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")}function Yu(){let e=!1;Jo()?console.log("scip CLI: installed"):(zo(),e=!0);let t=nt(),n=zt(t),r=hs(t,n);if(r.languages.length===0){console.log(`
813
+ No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
814
+ Detected languages: ${r.languages.join(", ")}`),console.log(`
815
+ Indexer readiness:`);for(let i of r.indexers){let o=i.runnable?" OK":i.installed?" WARN":" MISSING",s=i.resolvedBinary?` (${i.resolvedBinary})`:"";console.log(`${o} ${i.language}: ${i.binaryLabel}${s}`),i.note&&console.log(` ${i.note}`),!i.installed&&i.installUrl&&console.log(` install: ${i.installUrl}`),i.runnable||(e=!0)}if(r.semantic){let i=r.semantic,o=i.available?" OK":i.dependencyAvailable?" WARN":" MISSING",s=i.tsconfigPaths&&i.tsconfigPaths.length>1?` (${i.tsconfigPaths.length} tsconfigs)`:i.tsconfigPath?` (${i.tsconfigPath})`:"";console.log(`
816
+ Semantic provider readiness:`),console.log(`${o} typescript: ts-morph${s}`),i.reason&&console.log(` ${i.reason}; semantic checks will fall back to SCIP/source evidence`)}process.exitCode=e?1:0}function Xu(){let e=nt(),t=xt(e),n=_l(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function Zu(e){let t=Be(e),n=nt(),r=zt(n),i=Rt(t,"debounce"),o=Rt(t,"cooldown");i&&((r.watch??={}).debounceMs=i),o&&((r.watch??={}).cooldownMs=o);let s=new Br({projectRoot:n,config:r,languages:r.languages,onStatus:a=>{process.stdout.write(`\r\x1B[K${Dl(a)}`)},onReindexComplete:a=>{console.log(`
817
+ Reindex complete in ${(a/1e3).toFixed(1)}s`)},onError:a=>{console.error(`
818
+ Watch error: ${a.message}`)}});console.log(`Watching ${n}`),console.log(`Debounce: ${r.watch?.debounceMs??3e4}ms | Cooldown: ${r.watch?.cooldownMs??6e4}ms`),console.log(`Press Ctrl+C to stop.
819
+ `),s.start(),process.on("SIGINT",()=>{s.stop(),console.log(`
820
+ Stopped.`),process.exit(0)})}function em(){let{projectRoot:e,config:t,paths:n,dbPath:r}=vr(),i=hs(e,t);if(console.log(`Project: ${e}`),console.log(`DB path: ${r}`),r!==n.dbPath&&console.log(`Config: ${n.dbPath} (fallback to project root index.db)`),i.semantic){let o=i.semantic.available?"available":"fallback",s=i.semantic.tsconfigPaths&&i.semantic.tsconfigPaths.length>1?` (${i.semantic.tsconfigPaths.length} tsconfigs)`:i.semantic.tsconfigPath?` (${i.semantic.tsconfigPath})`:"";console.log(`TS sem: ${o}${s}`),i.semantic.reason&&console.log(`TS note: ${i.semantic.reason}`)}console.log(`Exists: ${Wu(r)?"yes":"no"}`),Wu(r)&&rt(o=>{let s=Pe(o);if(console.log(`Symbols: ${s.symbols}`),console.log(`Files: ${s.documents}`),console.log(`Size: ${Kt(s.indexSizeBytes)}`),s.lastBuilt){let a=Math.round((Date.now()-s.lastBuilt.getTime())/1e3);console.log(`Built: ${a}s ago`)}})}function ve({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,...o}){return{...o,renderShape:"list",handler:$u({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i})}}function qr({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,headers:o,dashWidths:s,...a}){return{...a,renderShape:"table",handler:ju({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,headers:o,dashWidths:s})}}function tm({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,key:o,...s}){return{...s,renderShape:"grouped-by-file",handler:Bu({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,key:o})}}var rR=Z("dead",({db:e,args:t,opts:n,budget:r})=>{let i={scope:ke(t,0)||void 0,minLoc:I(n,"minLoc",1),includeTests:z(n,"includeTests"),skipBarrels:z(n,"skipBarrels"),includeMembers:z(n,"includeMembers"),scanLimit:r.scanLimit,semantic:r.semantic},o=bn(e,i),s=o.symbols.filter(f=>f.kind==="dead-code"),a=o.symbols.filter(f=>f.kind!=="dead-code"),c=!z(n,"onlyInternal"),l=!z(n,"onlyDead"),u=c?s:[],m=l?a:[];if(u.length===0&&m.length===0){N.empty("No matching dead-code symbols found.");return}let d=u.reduce((f,b)=>f+b.loc,0),p=m.reduce((f,b)=>f+b.loc,0);u.length>0&&nm(u,"DEAD CODE",` Zero references anywhere \u2014 no cross-file callers AND no same-file uses.
821
+ Safe to delete.`,d),m.length>0&&(u.length>0&&console.log(""),nm(m,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
980
822
  single-use helper, an abstraction-in-progress, or a callback registered
981
823
  through a framework path that static analysis cannot trace (signal
982
824
  handlers, event listeners, dependency injection). NOT necessarily dead \u2014
983
- review case by case.`,h));let p=[];l&&p.push(`${u.length} dead code (${f} LOC)`),c&&p.push(`${d.length} file-internal (${h} LOC)`),console.log(`
984
- \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(`Total: ${u.length+d.length} symbols \u2014 ${p.join(" + ")}`)}));I.command("hotspots").description("Most-referenced symbols in the codebase (choke points)").option("-n, --limit <n>","Number of results",E,30).option("-s, --scope <path>","Limit to files matching path").action(e=>R(t=>{let n=x.hotspots(t,{limit:e.limit,scope:e.scope});S.table(["refs","files","symbol"],n.map(r=>` ${String(r.refCount).padStart(4)} ${String(r.fileCount).padStart(5)} ${r.shortName}`))}));I.command("imports <file>").description("What symbols does this file import?").option("--full","Run unbounded semantic analysis on large indexes").action((e,t)=>R(n=>{let r=A(n,"imports",!!t.full),i=x.imports(n,e,{semantic:r.semantic});if(i.length===0){S.empty("No imports found (indexer may not emit role=2 for this language).");return}S.list(i,s=>` ${s.shortName} \u2190 ${s.fromFile}`)}));I.command("imported-by <symbol>").description("Which files import this symbol?").action(e=>R(t=>{S.list(x.importedBy(t,e),n=>` ${n.fromFile}`)}));I.command("unused-imports <file>").description("Find imports not referenced in the same file").option("--full","Run unbounded semantic analysis on large indexes").action((e,t)=>R(n=>{let r=A(n,"unused-imports",!!t.full),i=x.unusedImports(n,e,{semantic:r.semantic});if(i.length===0)return S.empty("No unused imports found.");S.list(i,s=>` ${s.shortName} in ${s.importedIn}`),console.log(`
985
- ${i.length} unused import(s)`)}));I.command("outline <file>").description("Tree view of symbols in a file (using nesting hierarchy)").action(e=>R(t=>{let n=x.outline(t,e);function r(i,s){for(let o of i){let a=" ".repeat(s);console.log(`${a}${pe(o.startLine,o.endLine)} ${o.shortName}`),r(o.children,s+1)}}r(n,0)}));I.command("members <symbol>").description("All children of a symbol (methods, fields, nested types)").action(e=>R(t=>{S.list(x.members(t,e),n=>` ${pe(n.startLine,n.endLine)} [${n.kind}] ${n.shortName}`)}));I.command("fan-in [symbol]").description("How many files reference a symbol (or top fan-in across codebase)").option("-n, --limit <n>","Number of results for top mode",E,30).option("-s, --scope <path>","Limit to files matching path").action((e,t)=>R(n=>{if(e){let r=x.fanIn(n,e);if(r.length===0)return S.empty(`No fan-in for ${e}.`);S.list(r,i=>` ${String(i.count).padStart(4)} files ${i.name}`)}else S.table(["files","symbol"],x.topFanIn(n,{limit:t.limit,scope:t.scope}).map(r=>` ${String(r.count).padStart(5)} ${r.name}`))}));I.command("fan-out [file]").description("How many external symbols a file uses (or top fan-out across codebase)").option("-n, --limit <n>","Number of results for top mode",E,30).option("-s, --scope <path>","Limit to files matching path").action((e,t)=>R(n=>{if(e){let r=x.fanOut(n,e);if(r.length===0)return S.empty(`No fan-out for ${e}.`);S.list(r,i=>` ${String(i.count).padStart(4)} symbols ${i.name}`)}else S.table(["symbols","file"],x.topFanOut(n,{limit:t.limit,scope:t.scope}).map(r=>` ${String(r.count).padStart(7)} ${r.name}`))}));I.command("coupling [file1] [file2]").description("Coupling between two files, or top coupled pairs in codebase").option("-n, --limit <n>","Number of results for top mode",E,20).option("-s, --scope <path>","Limit to files matching path").action((e,t,n)=>R(r=>{if(e&&t){let i=x.coupling(r,e,t);console.log(`${i.file1} \u2194 ${i.file2}: ${i.sharedSymbols} shared symbols`)}else S.table(["shared","file1 \u2192 file2"],x.topCoupling(r,{limit:n.limit,scope:n.scope}).map(i=>` ${String(i.sharedSymbols).padStart(6)} ${i.file1} \u2192 ${i.file2}`))}));I.command("cycles").description("Detect circular dependency chains between files").option("-s, --scope <path>","Limit to files matching path").option("--max-depth <n>","Maximum cycle depth",E,10).action(e=>R(t=>{let n=x.cycles(t,{scope:e.scope,maxDepth:e.maxDepth});if(n.length===0)return S.empty("No circular dependencies found.");let r=n.filter(s=>s.kind==="real"),i=n.filter(s=>s.kind==="module-hierarchy");for(let s=0;s<r.length;s++){console.log(`
986
- Cycle ${s+1} (${r[s].path.length-1} files):`);for(let o=0;o<r[s].path.length;o++){let a=o<r[s].path.length-1?" \u2192":" (cycle)";console.log(` ${r[s].path[o]}${a}`)}}r.length===0?console.log("No real circular dependencies found."):console.log(`
987
- ${r.length} real cycle(s) found.`),i.length>0&&console.log(`(${i.length} module-hierarchy cycle(s) hidden \u2014 barrel files participating in normal parent/child re-export patterns. Pass --include-module-hierarchy to see them.)`)}));I.command("bottlenecks").description("Find coupling hubs: high fan-in AND high fan-out").option("-n, --limit <n>","Number of results",E,20).option("-s, --scope <path>","Limit to files matching path").option("--min-fan-in <n>","Minimum fan-in",E,2).option("--min-fan-out <n>","Minimum fan-out",E,2).option("--full","Run unbounded semantic analysis on large indexes").action(e=>R(t=>{let n=A(t,"bottlenecks",!!e.full),r=x.bottlenecks(t,{limit:e.limit,scope:e.scope,minFanIn:e.minFanIn,minFanOut:e.minFanOut,scanLimit:n.scanLimit,semantic:n.semantic});if(r.length===0)return S.empty("No bottlenecks found.");S.table(["score","fan-in","fan-out","symbol"],r.map(i=>` ${String(i.score).padStart(5)} ${String(i.fanIn).padStart(6)} ${String(i.fanOut).padStart(7)} ${i.shortName}`))}));I.command("isolated").description("Find completely orphaned symbols (no references at all)").option("-s, --scope <path>","Limit to files matching path").option("--min-loc <n>","Minimum lines of code",E,3).option("--full","Run unbounded semantic analysis on large indexes").action(e=>R(t=>{let n=A(t,"isolated",!!e.full),r=x.isolated(t,{scope:e.scope,minLoc:e.minLoc,scanLimit:n.scanLimit,semantic:n.semantic});if(r.length===0)return S.empty("No isolated symbols found.");S.groupedByFile(r,i=>` ${pe(i.startLine,i.endLine)} (${i.loc} LOC) ${i.shortName}`),console.log(`
988
- ${r.length} isolated symbol(s)`)}));I.command("by-kind <kind>").description("Find symbols by SCIP kind (class, interface, enum, function, etc.)").option("-s, --scope <path>","Limit to files matching path").option("-n, --limit <n>","Number of results",E,100).action((e,t)=>R(n=>{let r=x.byKind(n,e,{scope:t.scope,limit:t.limit});if(r.length===0)return S.empty(`No symbols found for kind "${e}". Use "kind-counts" to see available kinds.`);S.list(r,i=>` ${ge(i.relativePath,i.startLine,i.endLine)} [${i.kindName}] ${i.shortName}`),console.log(`
989
- ${r.length} symbol(s)`)}));I.command("kind-counts").description("Histogram of symbol kinds in the codebase").option("-s, --scope <path>","Limit to files matching path").action(e=>R(t=>{let n=x.kindCounts(t,{scope:e.scope});S.table(["count","kind"],n.map(r=>` ${String(r.count).padStart(5)} ${r.kindName} (${r.kind})`))}));I.command("deep-chains").description("Find the longest transitive dependency chains").option("-n, --limit <n>","Number of chains to show",E,10).option("-s, --scope <path>","Limit to files matching path").option("--min-depth <n>","Minimum chain depth",E,3).action(e=>R(t=>{let n=x.deepChains(t,{limit:e.limit,scope:e.scope,minDepth:e.minDepth});if(n.length===0)return S.empty("No deep chains found.");for(let r=0;r<n.length;r++){console.log(`
990
- Chain ${r+1} (depth ${n[r].depth}):`);for(let i of n[r].chain)console.log(` \u2192 ${i}`)}}));I.command("hierarchy <symbol>").description("Show a symbol's ancestry chain (method \u2192 class \u2192 module)").action(e=>R(t=>{let n=x.hierarchy(t,e);if(n.length===0)return S.empty("Symbol not found.");S.list(n,r=>`${" ".repeat(r.depth)}${r.shortName}`)}));I.command("call-graph <symbol>").description("Show incoming callers and outgoing callees for a symbol").option("--full","Run unbounded semantic analysis on large indexes").action((e,t)=>R(n=>{let r=A(n,"call-graph",!!t.full),i=x.callGraph(n,e,{semantic:r.semantic});if(!i)return S.empty("Symbol not found.");console.log(`Symbol: ${i.shortName}
991
- `),S.sectionedReport([{title:`CALLERS (${i.callers.length})`,rows:i.callers.map(s=>` ${s.file} ${s.shortName}`)},{title:`CALLEES (${i.callees.length})`,rows:i.callees.map(s=>` ${s.file} ${s.shortName}`)}])}));I.command("similar [symbol]").description("Find heuristic function similarity candidates from callee fingerprints").option("--min-similarity <n>","Minimum Jaccard similarity (0-1)",parseFloat,.4).option("-n, --limit <n>","Number of results",E,20).option("-s, --scope <path>","Limit to files matching path").option("--min-callees <n>","Minimum callees to consider",E,4).option("--cross-file-only","Only show cross-file pairs (skip same-file matches)").option("--full","Run unbounded semantic analysis on large indexes").action((e,t)=>R(n=>{let r=A(n,"similar",!!t.full);if(e){let i=x.similar(n,e,{minSimilarity:t.minSimilarity,limit:t.limit,scanLimit:r.scanLimit,semantic:r.semantic});if(i.length===0)return S.empty("No similar symbols found.");Se("similarity candidates"),S.list(i,s=>{let o=s.similarityBasis??"callees",a=o==="source-tokens"?"Shared source tokens":"Shared callees",l=o==="source-tokens"?"Only tokens in":"Only in",c=[`
992
- ${Math.round(s.similarity*100)}% similar:`,` A: ${s.shortNameA} (${s.fileA})`,` B: ${s.shortNameB} (${s.fileB})`,` ${a}: ${s.sharedCallees.join(", ")}`];return s.uniqueToA.length&&c.push(` ${l} A: ${s.uniqueToA.join(", ")}`),s.uniqueToB.length&&c.push(` ${l} B: ${s.uniqueToB.join(", ")}`),c.join(`
993
- `)})}else{let i=x.similarAll(n,{minSimilarity:t.minSimilarity,limit:t.limit,scope:t.scope,minCallees:t.minCallees,crossFileOnly:t.crossFileOnly,scanLimit:r.scanLimit,semantic:r.semantic});if(i.length===0)return S.empty("No similar symbol pairs found.");Se("similarity candidates"),S.list(i,s=>`
994
- ${Math.round(s.similarity*100)}% similar:
995
- A: ${s.shortNameA} (${s.fileA})
996
- B: ${s.shortNameB} (${s.fileB})
997
- Shared ${s.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${s.sharedCallees.join(", ")}`),console.log(`
998
- ${i.length} similar pair(s) found.`)}}));I.command("similar-files [file]").description("Find heuristic similar-file candidates from dependency profiles").option("--min-similarity <n>","Minimum Jaccard similarity (0-1)",parseFloat,.5).option("-n, --limit <n>","Number of results",E,20).option("-s, --scope <path>","Limit to files matching path").option("--min-deps <n>","Minimum dependencies to consider",E).action((e,t)=>R(n=>{let r=x.similarFiles(n,{minSimilarity:t.minSimilarity,limit:t.limit,scope:t.scope,minDeps:t.minDeps,filePattern:e});if(r.length===0)return S.empty("No similar file pairs found.");Se("similar file candidates"),S.list(r,i=>{let s=[`
999
- ${Math.round(i.similarity*100)}% similar:`,` ${i.fileA}`,` ${i.fileB}`,` Shared deps (${i.sharedDeps.length}): ${i.sharedDeps.join(", ")}`];return i.uniqueToA.length&&s.push(` Only in first: ${i.uniqueToA.join(", ")}`),i.uniqueToB.length&&s.push(` Only in second: ${i.uniqueToB.join(", ")}`),s.join(`
825
+ review case by case.`,p));let y=[];c&&y.push(`${u.length} dead code (${d} LOC)`),l&&y.push(`${m.length} file-internal (${p} LOC)`),console.log(`
826
+ \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(`Total: ${u.length+m.length} symbols \u2014 ${y.join(" + ")}`)});function nm(e,t,n,r){console.log(`\u2550\u2550\u2550 ${t} (${e.length}, ${r} LOC) \u2550\u2550\u2550`),console.log(n),console.log("");let i=new Map;for(let a of e){let c=i.get(a.relativePath)??[];c.push(a),i.set(a.relativePath,c)}let o=[...i.entries()].map(([a,c])=>({file:a,bucket:c,totalLoc:c.reduce((l,u)=>l+u.loc,0)})).sort((a,c)=>c.totalLoc-a.totalLoc||a.file.localeCompare(c.file)),s=!0;for(let{file:a,bucket:c}of o){s||console.log(""),s=!1,console.log(` ${a}`),c.sort((l,u)=>l.startLine-u.startLine);for(let l of c)console.log(` ${be(l.startLine,l.endLine)} (${l.loc} LOC) ${l.shortName}`)}}var iR=ot("unused-imports",{query:({db:e,args:t,budget:n})=>eo(e,M(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} in ${e.importedIn}`,emptyMessage:()=>"No unused imports found.",after:e=>console.log(`
827
+ ${e.length} unused import(s)`)}),oR=Vr("isolated",{query:({db:e,opts:t,budget:n})=>xn(e,{scope:O(t,"scope"),minLoc:I(t,"minLoc",3),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${be(e.startLine,e.endLine)} (${e.loc} LOC) ${e.shortName}`,emptyMessage:()=>"No isolated symbols found.",after:e=>console.log(`
828
+ ${e.length} isolated symbol(s)`)}),sR=Z("extract-candidates",({db:e,opts:t,budget:n})=>{let r=vn(e,{scope:O(t,"scope"),minLoc:I(t,"minLoc",10),minCallees:I(t,"minCallees",6),limit:I(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic});if(r.length===0)return N.empty("No extraction candidates found.");On("extraction candidates");for(let i of r){console.log(`
829
+ ${Se(i.relativePath,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC, ${i.totalCallees} callees)`);for(let o=0;o<i.clusters.length;o++){let s=i.clusters[o];console.log(` Cluster ${o+1} (${Math.round(s.isolation*100)}% isolated, ${s.callees.length} callees):`);for(let a of s.callees)console.log(` ${a}`)}}console.log(`
830
+ ${r.length} extraction candidate(s) found.`)}),aR=ot("wrapper-candidates",{query:({db:e,opts:t,budget:n})=>wn(e,{scope:O(t,"scope"),maxLoc:I(t,"maxLoc",15),limit:I(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${Se(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
831
+ Only called by: ${e.singleCallerShort} (fan-in: ${e.callerFanIn})`,emptyMessage:()=>"No wrapper candidates found.",heuristicLabel:"wrapper candidates",after:e=>console.log(`
832
+ ${e.length} wrapper candidate(s).`)}),cR=ot("passthrough-candidates",{query:({db:e,opts:t,budget:n})=>kn(e,{scope:O(t,"scope"),maxLoc:I(t,"maxLoc",15),limit:I(t,"limit",30),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${Se(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.loc} LOC)
833
+ Forwards to: ${e.forwardsToShort} (${e.forwardsToFile})`,emptyMessage:()=>"No passthrough candidates found.",heuristicLabel:"passthrough candidates",after:e=>console.log(`
834
+ ${e.length} passthrough candidate(s).`)}),lR=ot("stale-abstractions",{query:({db:e,opts:t,budget:n})=>Pn(e,{scope:O(t,"scope"),minLoc:I(t,"minLoc",3),limit:I(t,"limit",30),includeLowConfidence:z(t,"includeLowConfidence"),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=e.consumers===0?"unused":`${e.consumers} consumer`,n=e.barrelConsumers>0?`, +${e.barrelConsumers} barrel`:"";return` [${e.confidence}] ${Se(e.file,e.startLine,e.endLine)} ${e.shortName} (${e.kind}, ${e.loc} LOC, ${t}${n})
835
+ ${e.reason}`},emptyMessage:()=>"No stale abstractions found.",heuristicLabel:"stale abstraction candidates",after:e=>console.log(`
836
+ ${e.length} stale abstraction(s).`)}),uR=Wr("complexity-hotspots",{headers:["score"," LOC","fan-in","fan-out","callees","symbol"],query:({db:e,opts:t,budget:n})=>Tn(e,{scope:O(t,"scope"),minLoc:I(t,"minLoc",10),limit:I(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${e.score.toFixed(1).padStart(5)} ${String(e.loc).padStart(4)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${String(e.calleeCount).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No complexity hotspots found.",heuristicLabel:"complexity hotspot candidates",dashWidths:[5,4,6,7,7,6]}),mR=Hr("similar",{query:({db:e,args:t,opts:n,budget:r})=>{let i=ke(t,0);return i?{mode:"target",rows:So(e,i,{minSimilarity:I(n,"minSimilarity",.4),limit:I(n,"limit",20),scanLimit:r.scanLimit,semantic:r.semantic})}:{mode:"all",rows:_n(e,{minSimilarity:I(n,"minSimilarity",.4),limit:I(n,"limit",20),scope:O(n,"scope"),minCallees:I(n,"minCallees",4),crossFileOnly:z(n,"crossFileOnly"),scanLimit:r.scanLimit,semantic:r.semantic})}},emptyMessage:e=>{if(!(e.rows.length>0))return e.mode==="target"?"No similar symbols found.":"No similar symbol pairs found."},heuristicLabel:"similarity candidates",render:e=>{if(e.mode==="target"){N.list(e.rows,t=>{let n=t.similarityBasis??"callees",r=n==="source-tokens"?"Shared source tokens":"Shared callees",i=n==="source-tokens"?"Only tokens in":"Only in",o=[`
837
+ ${Math.round(t.similarity*100)}% similar:`,` A: ${t.shortNameA} (${t.fileA})`,` B: ${t.shortNameB} (${t.fileB})`,` ${r}: ${t.sharedCallees.join(", ")}`];return t.uniqueToA.length&&o.push(` ${i} A: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&o.push(` ${i} B: ${t.uniqueToB.join(", ")}`),o.join(`
838
+ `)});return}N.list(e.rows,t=>`
839
+ ${Math.round(t.similarity*100)}% similar:
840
+ A: ${t.shortNameA} (${t.fileA})
841
+ B: ${t.shortNameB} (${t.fileB})
842
+ Shared ${t.similarityBasis==="source-tokens"?"source tokens":"callees"}: ${t.sharedCallees.join(", ")}`),console.log(`
843
+ ${e.rows.length} similar pair(s) found.`)}}),dR=Yt({query:({db:e,args:t,opts:n})=>xo(e,{minSimilarity:I(n,"minSimilarity",.5),limit:I(n,"limit",20),scope:O(n,"scope"),minDeps:Rt(n,"minDeps"),filePattern:ke(t,0)}),emptyMessage:e=>e.length===0?"No similar file pairs found.":void 0,heuristicLabel:"similar file candidates",render:e=>{N.list(e,t=>{let n=[`
844
+ ${Math.round(t.similarity*100)}% similar:`,` ${t.fileA}`,` ${t.fileB}`,` Shared deps (${t.sharedDeps.length}): ${t.sharedDeps.join(", ")}`];return t.uniqueToA.length&&n.push(` Only in first: ${t.uniqueToA.join(", ")}`),t.uniqueToB.length&&n.push(` Only in second: ${t.uniqueToB.join(", ")}`),n.join(`
1000
845
  `)}),console.log(`
1001
- ${r.length} similar pair(s) found.`)}));I.command("similar-chains").description("Find heuristic similar-chain candidates from dependency flows").option("--min-similarity <n>","Minimum chain similarity (0-1)",parseFloat,.5).option("-n, --limit <n>","Number of results",E,15).option("-s, --scope <path>","Limit to files matching path").option("--min-length <n>","Minimum chain length",E,3).option("--max-length <n>","Maximum chain length",E,8).action(e=>R(t=>{let n=x.similarChains(t,{minSimilarity:e.minSimilarity,limit:e.limit,scope:e.scope,minChainLength:e.minLength,maxChainLength:e.maxLength});if(n.length===0)return S.empty("No similar chains found.");Se("similar chain candidates");for(let r=0;r<n.length;r++){let i=n[r];console.log(`
1002
- \u2500\u2500 Chain pair ${r+1} (${Math.round(i.similarity*100)}% similar, ${i.divergencePoints.length} divergence point(s)) \u2500\u2500`),console.log(` Chain A: ${i.chainA.join(" \u2192 ")}`),console.log(` Chain B: ${i.chainB.join(" \u2192 ")}`),i.commonPrefix.length&&console.log(` Common prefix: ${i.commonPrefix.join(" \u2192 ")}`),i.commonSuffix.length&&console.log(` Common suffix: ${i.commonSuffix.join(" \u2192 ")}`),console.log(" Divergence points (consolidation targets):");for(let s of i.divergencePoints)console.log(` [${s.index}] ${s.nodeA} \u2194 ${s.nodeB}`)}console.log(`
1003
- ${n.length} similar chain pair(s) found.`)}));I.command("extract-candidates").description("Find heuristic extraction candidates from isolated callee clusters").option("-s, --scope <path>","Limit to files matching path").option("--min-loc <n>","Minimum function LOC",E,10).option("--min-callees <n>","Minimum callees to analyze",E,6).option("-n, --limit <n>","Number of results",E,20).option("--full","Run unbounded semantic analysis on large indexes").action(e=>R(t=>{let n=A(t,"extract-candidates",!!e.full),r=x.extractCandidates(t,{scope:e.scope,minLoc:e.minLoc,minCallees:e.minCallees,limit:e.limit,scanLimit:n.scanLimit,semantic:n.semantic});if(r.length===0)return S.empty("No extraction candidates found.");Se("extraction candidates");for(let i of r){console.log(`
1004
- ${ge(i.relativePath,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC, ${i.totalCallees} callees)`);for(let s=0;s<i.clusters.length;s++){let o=i.clusters[s];console.log(` Cluster ${s+1} (${Math.round(o.isolation*100)}% isolated, ${o.callees.length} callees):`);for(let a of o.callees)console.log(` ${a}`)}}console.log(`
1005
- ${r.length} extraction candidate(s) found.`)}));I.command("affected <symbol>").description("Transitive closure of symbols that could break if this symbol changes").option("--max-depth <n>","Maximum traversal depth",E,5).option("-s, --scope <path>","Limit to files matching path").action((e,t)=>R(n=>{let r=x.affected(n,e,{maxDepth:t.maxDepth,scope:t.scope});if(r.length===0)return S.empty("No affected symbols found.");let i=-1;for(let s of r)s.depth!==i&&(console.log(`
1006
- \u2500\u2500 Depth ${s.depth} \u2500\u2500`),i=s.depth),console.log(` ${s.file} ${s.shortName}`);console.log(`
1007
- ${r.length} affected symbol(s) across ${new Set(r.map(s=>s.file)).size} files.`)}));I.command("change-surface <file>").description("Pre-change briefing: exports, consumers, and blast-radius risk").option("--full","Run unbounded semantic analysis on large indexes").action((e,t)=>R(n=>{let r=A(n,"change-surface",!!t.full),i=x.changeSurface(n,e,{semantic:r.semantic});if(!i)return S.empty("File not found in index.");console.log(`File: ${i.file}`),console.log(`External consumers: ${i.totalExternalConsumers}
1008
- `),S.list(i.symbols,s=>{let o=s.riskLevel==="high"?" *** HIGH RISK ***":s.riskLevel==="medium"?" * medium risk *":"";return` ${pe(s.startLine,s.endLine)} ${s.shortName} [${s.externalConsumers} consumers]${o}`})}));I.command(ac,{hidden:!0}).option("--base <ref>","Git ref to diff against (default: HEAD)").action(e=>R(t=>{let n=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),r=x.diffImpactPlan(t,{base:e.base}),i=x.diffImpactPartial(t,n,r.changedFiles);console.log(JSON.stringify(i))}));I.command("diff-impact").description("Compute changed symbols and downstream consumers from current git diff").option("--base <ref>","Git ref to diff against (default: HEAD)").action(e=>{try{g_(f_({base:e.base}))}catch(t){console.error(`error: ${t instanceof Error?t.message:t}`),process.exit(1)}});I.command("drift [module]").description("Detect heuristic drift candidates: unused imports, layer violations, and pattern deviations").option("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",di,5).option("--full","Run unbounded semantic analysis on large indexes").action((e,t)=>R(n=>{let r=A(n,"drift",!!t.full),i=x.drift(n,{scope:e,minDeviation:t.minDeviation,semantic:r.semantic});if(i.results.length===0)return S.empty("No drift detected.");Se("drift candidates"),console.log(""),S.groupedByFile(i.results,s=>{let a=` [${s.kind==="unused-import"?"UNUSED":s.kind==="layer-violation"?"LAYER":"UNIQUE"}] ${s.description}`;return s.detail?`${a}
1009
- ${s.detail}`:a},s=>s.file),console.log(`
1010
- ${i.unusedImports} unused import(s), ${i.layerViolations} layer violation(s), ${i.patternDeviations} pattern deviation(s)`)}));I.command("wrapper-candidates").description("Find heuristic wrapper candidates only called by one consumer").option("-s, --scope <path>","Limit to files matching path").option("--max-loc <n>","Maximum LOC for candidates",E,15).option("-n, --limit <n>","Number of results",E,30).option("--full","Run unbounded semantic analysis on large indexes").action(e=>R(t=>{let n=A(t,"wrapper-candidates",!!e.full),r=x.wrapperCandidates(t,{scope:e.scope,maxLoc:e.maxLoc,limit:e.limit,scanLimit:n.scanLimit,semantic:n.semantic});if(r.length===0)return S.empty("No wrapper candidates found.");Se("wrapper candidates"),S.list(r,i=>` ${ge(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)
1011
- Only called by: ${i.singleCallerShort} (fan-in: ${i.callerFanIn})`),console.log(`
1012
- ${r.length} wrapper candidate(s).`)}));I.command("passthrough-candidates").description("Find heuristic passthrough candidates that forward to one callee").option("-s, --scope <path>","Limit to files matching path").option("--max-loc <n>","Maximum LOC for candidates",E,15).option("-n, --limit <n>","Number of results",E,30).option("--full","Run unbounded semantic analysis on large indexes").action(e=>R(t=>{let n=A(t,"passthrough-candidates",!!e.full),r=x.passthroughCandidates(t,{scope:e.scope,maxLoc:e.maxLoc,limit:e.limit,scanLimit:n.scanLimit,semantic:n.semantic});if(r.length===0)return S.empty("No passthrough candidates found.");Se("passthrough candidates"),S.list(r,i=>` ${ge(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.loc} LOC)
1013
- Forwards to: ${i.forwardsToShort} (${i.forwardsToFile})`),console.log(`
1014
- ${r.length} passthrough candidate(s).`)}));I.command("stale-abstractions").description("Find heuristic stale abstraction candidates with 0-1 consumers").option("-s, --scope <path>","Limit to files matching path").option("--min-loc <n>","Minimum LOC",E,3).option("-n, --limit <n>","Number of results",E,30).option("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",!1).option("--full","Run unbounded semantic analysis on large indexes").action(e=>R(t=>{let n=A(t,"stale-abstractions",!!e.full),r=x.staleAbstractions(t,{scope:e.scope,minLoc:e.minLoc,limit:e.limit,includeLowConfidence:!!e.includeLowConfidence,scanLimit:n.scanLimit,semantic:n.semantic});if(r.length===0)return S.empty("No stale abstractions found.");Se("stale abstraction candidates"),S.list(r,i=>{let s=i.consumers===0?"unused":`${i.consumers} consumer`,o=i.barrelConsumers>0?`, +${i.barrelConsumers} barrel`:"";return` [${i.confidence}] ${ge(i.file,i.startLine,i.endLine)} ${i.shortName} (${i.kind}, ${i.loc} LOC, ${s}${o})
1015
- ${i.reason}`}),console.log(`
1016
- ${r.length} stale abstraction(s).`)}));I.command("complexity-hotspots").description("Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out").option("-s, --scope <path>","Limit to files matching path").option("--min-loc <n>","Minimum LOC",E,10).option("-n, --limit <n>","Number of results",E,20).option("--full","Run unbounded semantic analysis on large indexes").action(e=>R(t=>{let n=A(t,"complexity-hotspots",!!e.full),r=x.complexityHotspots(t,{scope:e.scope,minLoc:e.minLoc,limit:e.limit,scanLimit:n.scanLimit,semantic:n.semantic});if(r.length===0)return S.empty("No complexity hotspots found.");Se("complexity hotspot candidates"),S.table(["score"," LOC","fan-in","fan-out","callees","symbol"],r.map(i=>` ${i.score.toFixed(1).padStart(5)} ${String(i.loc).padStart(4)} ${String(i.fanIn).padStart(6)} ${String(i.fanOut).padStart(7)} ${String(i.calleeCount).padStart(7)} ${i.shortName}`),[5,4,6,7,7,6])}));I.command(oc,{hidden:!0}).argument("<phase>").option("-s, --scope <path>","Limit to files matching path").option("--full","Run unbounded candidate analyses on large indexes").action((e,t)=>R(n=>{x.HEALTH_PHASES.includes(e)||(console.error(`error: Unknown health phase: ${e}`),process.exit(1));let r=x.healthPhase(n,e,{scope:t.scope,full:!!t.full});console.log(JSON.stringify(r))}));I.command("health").description("Composite codebase health report with prioritized action list").option("-s, --scope <path>","Limit to files matching path").option("--full","Run unbounded candidate analyses on large indexes").option("--json","Output as JSON for programmatic consumption").action(e=>{try{let t=u_({scope:e.scope,full:!!e.full,json:!!e.json});m_(t,!!e.json)}catch(t){console.error(`error: ${t instanceof Error?t.message:t}`),process.exit(1)}});I.command("convergence <symbol1> <symbol2>").description("Show what a consolidated version of two similar functions would look like").option("--full","Run unbounded semantic analysis on large indexes").action((e,t,n)=>R(r=>{let i=A(r,"convergence",!!n.full),s=x.convergence(r,e,t,{semantic:i.semantic});if(!s)return S.empty("One or both symbols not found.");console.log(`
1017
- ${Math.round(s.similarity*100)}% callee overlap
1018
- `),console.log(` A: ${s.symbolA.shortName} (${s.symbolA.file}, ${s.symbolA.loc} LOC)`),console.log(` B: ${s.symbolB.shortName} (${s.symbolB.file}, ${s.symbolB.loc} LOC)
1019
- `),console.log(` Shared callees (${s.sharedCallees.length}):`);for(let o of s.sharedCallees)console.log(` ${o}`);if(s.uniqueToA.length>0){console.log(`
1020
- Unique to A (${s.uniqueToA.length}):`);for(let o of s.uniqueToA)console.log(` ${o}`)}if(s.uniqueToB.length>0){console.log(`
1021
- Unique to B (${s.uniqueToB.length}):`);for(let o of s.uniqueToB)console.log(` ${o}`)}console.log(`
1022
- Strategy: ${s.consolidationStrategy}`)}));I.command("code <symbol>").description("Read the source code for a symbol (bounded to its definition range)").option("-C, --context <n>","Extra lines of context above/below",E,0).action((e,t)=>R(n=>{let r=x.code(n,e,{context:t.context});if(!r)return S.empty("Symbol not found or file unreadable.");console.log(`${ge(r.relativePath,r.startLine,r.endLine)} ${r.shortName} [${r.language??"unknown"}]
846
+ ${e.length} similar pair(s) found.`)}}),pR=Yt({query:({db:e,opts:t})=>Co(e,{minSimilarity:I(t,"minSimilarity",.5),limit:I(t,"limit",15),scope:O(t,"scope"),minChainLength:I(t,"minLength",3),maxChainLength:I(t,"maxLength",8)}),emptyMessage:e=>e.length===0?"No similar chains found.":void 0,heuristicLabel:"similar chain candidates",render:e=>{for(let t=0;t<e.length;t++){let n=e[t];console.log(`
847
+ \u2500\u2500 Chain pair ${t+1} (${Math.round(n.similarity*100)}% similar, ${n.divergencePoints.length} divergence point(s)) \u2500\u2500`),console.log(` Chain A: ${n.chainA.join(" \u2192 ")}`),console.log(` Chain B: ${n.chainB.join(" \u2192 ")}`),n.commonPrefix.length&&console.log(` Common prefix: ${n.commonPrefix.join(" \u2192 ")}`),n.commonSuffix.length&&console.log(` Common suffix: ${n.commonSuffix.join(" \u2192 ")}`),console.log(" Divergence points (consolidation targets):");for(let r of n.divergencePoints)console.log(` [${r.index}] ${r.nodeA} \u2194 ${r.nodeB}`)}console.log(`
848
+ ${e.length} similar chain pair(s) found.`)}}),fR=Hr("drift",{query:({db:e,args:t,opts:n,budget:r})=>Nn(e,{scope:ke(t,0),minDeviation:I(n,"minDeviation",5),semantic:r.semantic}),emptyMessage:e=>e.results.length===0?"No drift detected.":void 0,heuristicLabel:"drift candidates",render:e=>{console.log(""),N.groupedByFile(e.results,t=>{let r=` [${t.kind==="unused-import"?"UNUSED":t.kind==="layer-violation"?"LAYER":"UNIQUE"}] ${t.description}`;return t.detail?`${r}
849
+ ${t.detail}`:r},t=>t.file),console.log(`
850
+ ${e.unusedImports} unused import(s), ${e.layerViolations} layer violation(s), ${e.patternDeviations} pattern deviation(s)`)}}),gR=Hr("convergence",{query:({db:e,args:t,budget:n})=>ko(e,M(t,0),M(t,1),{semantic:n.semantic}),emptyMessage:e=>e?void 0:"One or both symbols not found.",render:e=>{if(e){console.log(`
851
+ ${Math.round(e.similarity*100)}% callee overlap
852
+ `),console.log(` A: ${e.symbolA.shortName} (${e.symbolA.file}, ${e.symbolA.loc} LOC)`),console.log(` B: ${e.symbolB.shortName} (${e.symbolB.file}, ${e.symbolB.loc} LOC)
853
+ `),console.log(` Shared callees (${e.sharedCallees.length}):`);for(let t of e.sharedCallees)console.log(` ${t}`);if(e.uniqueToA.length>0){console.log(`
854
+ Unique to A (${e.uniqueToA.length}):`);for(let t of e.uniqueToA)console.log(` ${t}`)}if(e.uniqueToB.length>0){console.log(`
855
+ Unique to B (${e.uniqueToB.length}):`);for(let t of e.uniqueToB)console.log(` ${t}`)}console.log(`
856
+ Strategy: ${e.consolidationStrategy}`)}}}),hR=ot("similar-signatures",{query:({db:e,opts:t,budget:n})=>Ao(e,{scope:O(t,"scope"),minLoc:I(t,"minLoc",3),limit:I(t,"limit",20),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>{let t=`
857
+ Signature: ${e.signature} (${e.functions.length} functions)`,n=e.functions.map(r=>` ${Se(r.file,r.startLine,r.endLine)} ${r.shortName} (${r.loc} LOC)`).join(`
858
+ `);return`${t}
859
+ ${n}`},emptyMessage:()=>"No same-shape function groups found.",after:e=>console.log(`
860
+ ${e.length} group(s) found.`)});function Zt(e){return{docs:S("Cleanup"),...e}}function He({heuristicLabel:e,...t}){return Zt({...t,heuristic:{label:e}})}var rm=[Zt({id:"dead",command:"dead [scope]",description:"Find dead code and file-internal symbols (no cross-file consumers)",options:[g("--min-loc <n>","Only show symbols >= N lines",D,1),g("--include-tests","Include test files"),g("--skip-barrels","Ignore refs from barrel re-export files"),g("--include-members","Include class members"),g("--only-dead","Show only [dead code] symbols (skip [file-internal only])"),g("--only-internal","Show only [file-internal only] symbols (skip [dead code])"),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",renderShape:"custom",docs:S("Cleanup",["scip-query dead --min-loc 10"]),handler:rR}),Zt({id:"unused-imports",command:"unused-imports <file>",description:"Find imports not referenced in the same file",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"list",handler:iR}),Zt({id:"isolated",command:"isolated",description:"Find completely orphaned symbols (no references at all)",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum lines of code",D,3),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",renderShape:"grouped-by-file",handler:oR}),He({id:"similar",command:"similar [symbol]",description:"Find heuristic function similarity candidates from callee fingerprints",options:[g("--min-similarity <n>","Minimum Jaccard similarity (0-1)",wr,.4),g("-n, --limit <n>","Number of results",D,20),g("-s, --scope <path>","Limit to files matching path"),g("--min-callees <n>","Minimum callees to consider",D,4),g("--cross-file-only","Only show cross-file pairs (skip same-file matches)"),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"similarity candidates",budget:"candidate-scan",renderShape:"custom",handler:mR}),He({id:"similar-files",command:"similar-files [file]",description:"Find heuristic similar-file candidates from dependency profiles",options:[g("--min-similarity <n>","Minimum Jaccard similarity (0-1)",wr,.5),g("-n, --limit <n>","Number of results",D,20),g("-s, --scope <path>","Limit to files matching path"),g("--min-deps <n>","Minimum dependencies to consider",D)],heuristicLabel:"similar file candidates",renderShape:"custom",handler:dR}),He({id:"similar-chains",command:"similar-chains",description:"Find heuristic similar-chain candidates from dependency flows",options:[g("--min-similarity <n>","Minimum chain similarity (0-1)",wr,.5),g("-n, --limit <n>","Number of results",D,15),g("-s, --scope <path>","Limit to files matching path"),g("--min-length <n>","Minimum chain length",D,3),g("--max-length <n>","Maximum chain length",D,8)],heuristicLabel:"similar chain candidates",renderShape:"custom",handler:pR}),He({id:"extract-candidates",command:"extract-candidates",description:"Find heuristic extraction candidates from isolated callee clusters",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum function LOC",D,10),g("--min-callees <n>","Minimum callees to analyze",D,6),g("-n, --limit <n>","Number of results",D,20),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"extraction candidates",budget:"candidate-scan",renderShape:"custom",handler:sR}),He({id:"drift",command:"drift [module]",description:"Detect heuristic drift candidates: unused imports, layer violations, and pattern deviations",options:[g("--min-deviation <n>","Minimum sibling files before reporting unique dependency deviations",Er,5),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:fR}),He({id:"wrapper-candidates",command:"wrapper-candidates",description:"Find heuristic wrapper candidates only called by one consumer",options:[g("-s, --scope <path>","Limit to files matching path"),g("--max-loc <n>","Maximum LOC for candidates",D,15),g("-n, --limit <n>","Number of results",D,30),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"wrapper candidates",budget:"candidate-scan",renderShape:"list",handler:aR}),He({id:"passthrough-candidates",command:"passthrough-candidates",description:"Find heuristic passthrough candidates that forward to one callee",options:[g("-s, --scope <path>","Limit to files matching path"),g("--max-loc <n>","Maximum LOC for candidates",D,15),g("-n, --limit <n>","Number of results",D,30),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"passthrough candidates",budget:"candidate-scan",renderShape:"list",handler:cR}),He({id:"stale-abstractions",command:"stale-abstractions",description:"Find heuristic stale abstraction candidates with 0-1 consumers",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum LOC",D,3),g("-n, --limit <n>","Number of results",D,30),g("--include-low-confidence","Include 1-consumer classes (usually encapsulation, not stale)",void 0,!1),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"stale abstraction candidates",budget:"candidate-scan",renderShape:"list",handler:lR}),He({id:"complexity-hotspots",command:"complexity-hotspots",description:"Find heuristic complexity hotspot candidates from LOC x fan-in x fan-out",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum LOC",D,10),g("-n, --limit <n>","Number of results",D,20),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"complexity hotspot candidates",budget:"candidate-scan",renderShape:"table",handler:uR}),Zt({id:"convergence",command:"convergence <symbol1> <symbol2>",description:"Show what a consolidated version of two similar functions would look like",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",handler:gR}),tm({id:"redundant-reexports",command:"redundant-reexports",description:"Find barrel re-exports that nobody imports through",options:[g("-s, --scope <path>","Limit to files matching path"),g("-n, --limit <n>","Number of results",D,30)],docs:S("Cleanup"),query:({db:e,opts:t})=>Fo(e,{scope:O(t,"scope"),limit:I(t,"limit",30)}),format:e=>` ${e.shortName} (from ${e.originalFile})
861
+ barrel: ${e.barrelConsumers} consumer(s) | direct: ${e.directConsumers} consumer(s)`,key:e=>e.barrelFile,emptyMessage:()=>"No redundant re-exports found.",after:e=>console.log(`
862
+ ${e.length} redundant re-export(s).`)}),Zt({id:"similar-signatures",command:"similar-signatures",description:"Find functions with near-identical type signatures (same shape)",options:[g("-s, --scope <path>","Limit to files matching path"),g("--min-loc <n>","Minimum LOC per function",D,3),g("-n, --limit <n>","Number of groups",D,20),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",renderShape:"list",handler:hR})];var yR=X(({db:e})=>{let t=Pe(e);console.log(`Documents: ${t.documents}`),console.log(`Symbols: ${t.symbols}`),console.log(`Definitions: ${t.definitions}`),console.log(`References: ${t.references}`),console.log(`Index size: ${Kt(t.indexSizeBytes)}`),t.lastBuilt&&console.log(`Last built: ${t.lastBuilt.toISOString().replace("T"," ").slice(0,19)}`)}),im=[{id:"stats",command:"stats",description:"Show index statistics",renderShape:"custom",docs:S("Core"),handler:yR}];var bR=Wr("bottlenecks",{headers:["score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>lo(e,{limit:I(t,"limit",20),scope:O(t,"scope"),minFanIn:I(t,"minFanIn",2),minFanOut:I(t,"minFanOut",2),scanLimit:n.scanLimit,semantic:n.semantic}),format:e=>` ${String(e.score).padStart(5)} ${String(e.fanIn).padStart(6)} ${String(e.fanOut).padStart(7)} ${e.shortName}`,emptyMessage:()=>"No bottlenecks found."}),SR=Z("call-graph",({db:e,args:t,budget:n})=>{let r=yo(e,M(t,0),{semantic:n.semantic});if(!r)return N.empty("Symbol not found.");console.log(`Symbol: ${r.shortName}
863
+ `),N.sectionedReport([{title:`CALLERS (${r.callers.length})`,rows:r.callers.map(i=>` ${i.file} ${i.shortName}`)},{title:`CALLEES (${r.callees.length})`,rows:r.callees.map(i=>` ${i.file} ${i.shortName}`)}])}),xR=X(({db:e,args:t,opts:n})=>{let r=ke(t,0);if(r){let i=ro(e,r);if(i.length===0)return N.empty(`No fan-in for ${r}.`);N.list(i,o=>` ${String(o.count).padStart(4)} files ${o.name}`);return}N.table(["files","symbol"],oo(e,{limit:I(n,"limit",30),scope:O(n,"scope")}).map(i=>` ${String(i.count).padStart(5)} ${i.name}`))}),CR=X(({db:e,args:t,opts:n})=>{let r=ke(t,0);if(r){let i=io(e,r);if(i.length===0)return N.empty(`No fan-out for ${r}.`);N.list(i,o=>` ${String(o.count).padStart(4)} symbols ${o.name}`);return}N.table(["symbols","file"],so(e,{limit:I(n,"limit",30),scope:O(n,"scope")}).map(i=>` ${String(i.count).padStart(7)} ${i.name}`))}),IR=X(({db:e,args:t,opts:n})=>{let r=ke(t,0),i=ke(t,1);if(r&&i){let o=ao(e,r,i);console.log(`${o.file1} \u2194 ${o.file2}: ${o.sharedSymbols} shared symbols`);return}N.table(["shared","file1 \u2192 file2"],co(e,{limit:I(n,"limit",20),scope:O(n,"scope")}).map(o=>` ${String(o.sharedSymbols).padStart(6)} ${o.file1} \u2192 ${o.file2}`))}),RR=Yt({query:({db:e,opts:t})=>Sn(e,{scope:O(t,"scope"),maxDepth:I(t,"maxDepth",10)}),emptyMessage:e=>e.length===0?"No circular dependencies found.":void 0,render:e=>{let t=e.filter(r=>r.kind==="real"),n=e.filter(r=>r.kind==="module-hierarchy");for(let r=0;r<t.length;r++){console.log(`
864
+ Cycle ${r+1} (${t[r].path.length-1} files):`);for(let i=0;i<t[r].path.length;i++){let o=i<t[r].path.length-1?" \u2192":" (cycle)";console.log(` ${t[r].path[i]}${o}`)}}t.length===0?console.log("No real circular dependencies found."):console.log(`
865
+ ${t.length} real cycle(s) found.`),n.length>0&&console.log(`(${n.length} module-hierarchy cycle(s) hidden \u2014 barrel files participating in normal parent/child re-export patterns. Pass --include-module-hierarchy to see them.)`)}}),_R=Yt({query:({db:e,opts:t})=>go(e,{limit:I(t,"limit",10),scope:O(t,"scope"),minDepth:I(t,"minDepth",3)}),emptyMessage:e=>e.length===0?"No deep chains found.":void 0,render:e=>{for(let t=0;t<e.length;t++){console.log(`
866
+ Chain ${t+1} (depth ${e[t].depth}):`);for(let n of e[t].chain)console.log(` \u2192 ${n}`)}}}),om=[qr({id:"hotspots",command:"hotspots",description:"Most-referenced symbols in the codebase (choke points)",options:[g("-n, --limit <n>","Number of results",D,30),g("-s, --scope <path>","Limit to files matching path")],docs:S("Graph"),headers:["refs","files","symbol"],query:({db:e,opts:t})=>Yi(e,{limit:I(t,"limit",30),scope:O(t,"scope")}),format:e=>` ${String(e.refCount).padStart(4)} ${String(e.fileCount).padStart(5)} ${e.shortName}`}),{id:"fan-in",command:"fan-in [symbol]",description:"How many files reference a symbol (or top fan-in across codebase)",options:[g("-n, --limit <n>","Number of results for top mode",D,30),g("-s, --scope <path>","Limit to files matching path")],renderShape:"custom",docs:S("Graph"),handler:xR},{id:"fan-out",command:"fan-out [file]",description:"How many external symbols a file uses (or top fan-out across codebase)",options:[g("-n, --limit <n>","Number of results for top mode",D,30),g("-s, --scope <path>","Limit to files matching path")],renderShape:"custom",docs:S("Graph"),handler:CR},{id:"coupling",command:"coupling [file1] [file2]",description:"Coupling between two files, or top coupled pairs in codebase",options:[g("-n, --limit <n>","Number of results for top mode",D,20),g("-s, --scope <path>","Limit to files matching path")],renderShape:"custom",docs:S("Graph"),handler:IR},{id:"cycles",command:"cycles",description:"Detect circular dependency chains between files",options:[g("-s, --scope <path>","Limit to files matching path"),g("--max-depth <n>","Maximum cycle depth",D,10)],renderShape:"custom",docs:S("Graph"),handler:RR},{id:"bottlenecks",command:"bottlenecks",description:"Find coupling hubs: high fan-in AND high fan-out",options:[g("-n, --limit <n>","Number of results",D,20),g("-s, --scope <path>","Limit to files matching path"),g("--min-fan-in <n>","Minimum fan-in",D,2),g("--min-fan-out <n>","Minimum fan-out",D,2),g("--full","Run unbounded semantic analysis on large indexes")],budget:"candidate-scan",renderShape:"table",docs:S("Graph"),handler:bR},{id:"deep-chains",command:"deep-chains",description:"Find the longest transitive dependency chains",options:[g("-n, --limit <n>","Number of chains to show",D,10),g("-s, --scope <path>","Limit to files matching path"),g("--min-depth <n>","Minimum chain depth",D,3)],renderShape:"custom",docs:S("Graph"),handler:_R},{id:"call-graph",command:"call-graph <symbol>",description:"Show incoming callers and outgoing callees for a symbol",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"sectioned-report",docs:S("Graph"),handler:SR}];var vR=Z("complexity",({db:e,args:t,budget:n})=>{let r=To(e,M(t,0),{semantic:n.semantic});if(!r)return N.empty("Symbol not found.");console.log(`${Se(r.relativePath,r.startLine,r.endLine)} ${r.shortName}
867
+ `),console.log(` LOC: ${r.loc}`),console.log(` Branches: ${r.branches}`),console.log(` Cyclomatic estimate: ${r.cyclomaticEstimate}`),console.log(` Callees: ${r.calleeCount}`),console.log(` Fan-in: ${r.fanIn}`),console.log(` Fan-out: ${r.fanOut}`)}),sm=[{id:"complexity",command:"complexity <symbol>",description:"Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",docs:S("Health"),handler:vR}];var DR=X(({db:e,args:t,opts:n})=>{let r=Io(e,M(t,0),{maxDepth:I(n,"maxDepth",5),scope:O(n,"scope")});if(r.length===0)return N.empty("No affected symbols found.");let i=-1;for(let o of r)o.depth!==i&&(console.log(`
868
+ \u2500\u2500 Depth ${o.depth} \u2500\u2500`),i=o.depth),console.log(` ${o.file} ${o.shortName}`);console.log(`
869
+ ${r.length} affected symbol(s) across ${new Set(r.map(o=>o.file)).size} files.`)}),NR=Z("change-surface",({db:e,args:t,budget:n})=>{let r=Ro(e,M(t,0),{semantic:n.semantic});if(!r)return N.empty("File not found in index.");console.log(`File: ${r.file}`),console.log(`External consumers: ${r.totalExternalConsumers}
870
+ `),N.list(r.symbols,i=>{let o=i.riskLevel==="high"?" *** HIGH RISK ***":i.riskLevel==="medium"?" * medium risk *":"";return` ${be(i.startLine,i.endLine)} ${i.shortName} [${i.externalConsumers} consumers]${o}`})}),am=[{id:"affected",command:"affected <symbol>",description:"Transitive closure of symbols that could break if this symbol changes",options:[g("--max-depth <n>","Maximum traversal depth",D,5),g("-s, --scope <path>","Limit to files matching path")],renderShape:"custom",docs:S("Impact"),handler:DR},{id:"change-surface",command:"change-surface <file>",description:"Pre-change briefing: exports, consumers, and blast-radius risk",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"list",docs:S("Impact"),handler:NR}];var LR=X(({db:e,args:t})=>{let n=Ui(e,M(t,0));N.sectionedReport([{title:"FILES",rows:n.files},{title:"EXPORTED SYMBOLS",rows:n.symbols.map(r=>` ${be(r.startLine,r.endLine)} ${r.shortName}`)},{title:"DEPENDS ON (internal)",rows:n.dependsOn.map(r=>` ${r}`)},{title:"DEPENDED ON BY",rows:n.dependedOnBy.map(r=>` ${r}`)}])}),ER=Z("trace",({db:e,args:t,budget:n})=>{let r=Wi(e,M(t,0),{semantic:n.semantic}),i=[];for(let a of r.definitions){let c=a.signature?` \u2014 ${a.signature}`:"";i.push(` ${Se(a.relativePath,a.startLine,a.endLine)}${c}`),a.source&&i.push(a.source.split(`
871
+ `).map((l,u)=>` ${$e(a.startLine+u)} ${l}`).join(`
872
+ `))}let o=[],s="";for(let a of r.referencedBy)a.relativePath!==s&&(s&&o.push(""),o.push(` ${a.relativePath}`),s=a.relativePath),o.push(` line ${$e(a.line)} in ${a.enclosingShort}`);N.sectionedReport([{title:"DEFINITION",rows:i},{title:"REFERENCED BY",rows:o}])}),wR=X(({db:e,args:t})=>{let n=to(e,M(t,0));function r(i,o){for(let s of i){let a=" ".repeat(o);console.log(`${a}${be(s.startLine,s.endLine)} ${s.shortName}`),r(s.children,o+1)}}r(n,0)}),kR=ot("imports",{query:({db:e,args:t,budget:n})=>Xi(e,M(t,0),{semantic:n.semantic}),format:e=>` ${e.shortName} \u2190 ${e.fromFile}`,emptyMessage:()=>"No imports found (indexer may not emit role=2 for this language)."}),PR=Vr("refs",{query:({db:e,args:t,budget:n})=>Hi(e,M(t,0),{semantic:n.semantic}),format:e=>` line ${$e(e.line)}`}),TR=X(({db:e,args:t,opts:n})=>{let r=Po(e,M(t,0),{context:I(n,"context",0)});if(!r)return N.empty("Symbol not found or file unreadable.");console.log(`${Se(r.relativePath,r.startLine,r.endLine)} ${r.shortName} [${r.language??"unknown"}]
1023
873
  `);let i=r.source.split(`
1024
- `);for(let s=0;s<i.length;s++)console.log(` ${String(xe(r.startLine+s)).padStart(4)} ${i[s]}`)}));I.command("complexity <symbol>").description("Per-symbol complexity: branches, cyclomatic estimate, fan-in/out, callees").option("--full","Run unbounded semantic analysis on large indexes").action((e,t)=>R(n=>{let r=A(n,"complexity",!!t.full),i=x.complexity(n,e,{semantic:r.semantic});if(!i)return S.empty("Symbol not found.");console.log(`${ge(i.relativePath,i.startLine,i.endLine)} ${i.shortName}
1025
- `),console.log(` LOC: ${i.loc}`),console.log(` Branches: ${i.branches}`),console.log(` Cyclomatic estimate: ${i.cyclomaticEstimate}`),console.log(` Callees: ${i.calleeCount}`),console.log(` Fan-in: ${i.fanIn}`),console.log(` Fan-out: ${i.fanOut}`)}));I.command("dataflow <symbol>").description("Reference-level dataflow: definition sites, usage sites, producers, consumers").option("--full","Run unbounded semantic analysis on large indexes").action((e,t)=>R(n=>{let r=A(n,"dataflow",!!t.full),i=x.dataflow(n,e,{semantic:r.semantic});if(!i)return S.empty("Symbol not found.");if(console.log(`${i.shortName} (${i.relativePath})
1026
- `),i.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let s of i.definitionSites)console.log(` ${s.file}:${xe(s.line)}`)}if(i.usageSites.length>0){console.log(`
1027
- \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let s of i.usageSites)console.log(` ${s.file}:${xe(s.line)} in ${s.enclosingShort}`)}if(i.producers.length>0){console.log(`
1028
- \u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let s of i.producers)console.log(` ${s.file} ${s.shortName}`)}if(i.consumers.length>0){console.log(`
1029
- \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let s of i.consumers)console.log(` ${s.file} ${s.shortName}`)}}));I.command("slice <symbol>").description("Reference-level program slice: what affects this (backward) or what this affects (forward)").option("--forward","Forward slice (what does this affect). Default is backward.").option("--depth <n>","Max transitive depth for backward slice",E,3).option("--full","Run unbounded semantic analysis on large indexes").action((e,t)=>R(n=>{let r=t.forward?"forward":"backward",i=A(n,"slice",!!t.full),s=x.slice(n,e,{direction:r,maxDepth:t.depth,semantic:i.semantic});if(!s)return S.empty("Symbol not found.");if(console.log(`${s.direction} slice of ${s.shortName}
1030
- `),s.connectedSymbols.length===0){console.log(" No connected symbols found.");return}S.list(s.connectedSymbols,o=>` ${o.file} ${o.shortName}
1031
- ${o.relationship}`),console.log(`
1032
- ${s.connectedSymbols.length} connected symbol(s).`)}));I.command("install-skills").description(`Install skills (${hr.join(", ")}) into Claude Code and Codex`).action(()=>{let e=ms(),t=e.installed.length+e.alreadyLinked.length;console.log(`
1033
- ${e.installed.length} installed, ${e.alreadyLinked.length} already linked, ${e.skipped.length} skipped.`),t>0&&console.log("Skills will be available in your next Claude Code / Codex session.")});I.command("check-deps").description("Check whether scip-query and the detected language indexers are actually runnable").action(()=>{let e=!1;qn()?console.log("scip CLI: installed"):(zn(),e=!0);let t=De(),n=Le(t),r=n.languages??Ve(t);if(r.length===0){console.log(`
1034
- No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
1035
- Detected languages: ${r.join(", ")}`),console.log(`
1036
- Indexer readiness:`);for(let i of r){let s=Vi(Gt(i),t),o=s.runnable?" OK":s.installed?" WARN":" MISSING",a=s.resolvedBinary?` (${s.resolvedBinary})`:"";console.log(`${o} ${i}: ${s.binaryLabel}${a}`),s.note&&console.log(` ${s.note}`),!s.installed&&s.installUrl&&console.log(` install: ${s.installUrl}`),s.runnable||(e=!0)}if(r.includes("typescript")){let i=fr(t,n.semantic?.typescript?.tsconfigs),s=i.available?" OK":i.dependencyAvailable?" WARN":" MISSING",o=i.tsconfigPaths&&i.tsconfigPaths.length>1?` (${i.tsconfigPaths.length} tsconfigs)`:i.tsconfigPath?` (${i.tsconfigPath})`:"";console.log(`
1037
- Semantic provider readiness:`),console.log(`${s} typescript: ts-morph${o}`),i.reason&&console.log(` ${i.reason}; semantic checks will fall back to SCIP/source evidence`)}process.exitCode=e?1:0});I.command("redundant-reexports").description("Find barrel re-exports that nobody imports through").option("-s, --scope <path>","Limit to files matching path").option("-n, --limit <n>","Number of results",E,30).action(e=>R(t=>{let n=x.redundantReexports(t,{scope:e.scope,limit:e.limit});if(n.length===0)return S.empty("No redundant re-exports found.");S.groupedByFile(n,r=>` ${r.shortName} (from ${r.originalFile})
1038
- barrel: ${r.barrelConsumers} consumer(s) | direct: ${r.directConsumers} consumer(s)`,r=>r.barrelFile),console.log(`
1039
- ${n.length} redundant re-export(s).`)}));I.command("similar-signatures").description("Find functions with near-identical type signatures (same shape)").option("-s, --scope <path>","Limit to files matching path").option("--min-loc <n>","Minimum LOC per function",E,3).option("-n, --limit <n>","Number of groups",E,20).option("--full","Run unbounded semantic analysis on large indexes").action(e=>R(t=>{let n=A(t,"similar-signatures",!!e.full),r=x.similarSignatures(t,{scope:e.scope,minLoc:e.minLoc,limit:e.limit,scanLimit:n.scanLimit,semantic:n.semantic});if(r.length===0)return S.empty("No same-shape function groups found.");S.list(r,i=>{let s=`
1040
- Signature: ${i.signature} (${i.functions.length} functions)`,o=i.functions.map(a=>` ${ge(a.file,a.startLine,a.endLine)} ${a.shortName} (${a.loc} LOC)`).join(`
1041
- `);return`${s}
1042
- ${o}`}),console.log(`
1043
- ${r.length} group(s) found.`)}));I.command("init").description("Create a .scipquery.json config file for this project").action(()=>{let e=De(),t=Ve(e),n=yi(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)});I.command("watch").description("Watch for file changes and reindex automatically").option("--debounce <ms>","Ms to wait after last change (default: 30000)",parseInt).option("--cooldown <ms>","Min ms between reindexes (default: 60000)",parseInt).action(e=>{let t=De(),n=Le(t);e.debounce&&((n.watch??={}).debounceMs=e.debounce),e.cooldown&&((n.watch??={}).cooldownMs=e.cooldown);let r=new tn({projectRoot:t,config:n,languages:n.languages,onStatus:i=>{process.stdout.write(`\r\x1B[K${tc(i)}`)},onReindexComplete:i=>{console.log(`
1044
- Reindex complete in ${(i/1e3).toFixed(1)}s`)},onError:i=>{console.error(`
1045
- Watch error: ${i.message}`)}});console.log(`Watching ${t}`),console.log(`Debounce: ${n.watch?.debounceMs??3e4}ms | Cooldown: ${n.watch?.cooldownMs??6e4}ms`),console.log(`Press Ctrl+C to stop.
1046
- `),r.start(),process.on("SIGINT",()=>{r.stop(),console.log(`
1047
- Stopped.`),process.exit(0)})});I.command("status").description("Show index status for this project").action(()=>{let e=De(),t=Le(e),n=we(e,t),r=Ht(e);if(console.log(`Project: ${e}`),console.log(`DB path: ${r}`),r!==n.dbPath&&console.log(`Config: ${n.dbPath} (fallback to project root index.db)`),(t.languages??Ve(e)).includes("typescript")){let i=fr(e,t.semantic?.typescript?.tsconfigs),s=i.available?"available":"fallback",o=i.tsconfigPaths&&i.tsconfigPaths.length>1?` (${i.tsconfigPaths.length} tsconfigs)`:i.tsconfigPath?` (${i.tsconfigPath})`:"";console.log(`TS sem: ${s}${o}`),i.reason&&console.log(`TS note: ${i.reason}`)}console.log(`Exists: ${nc(r)?"yes":"no"}`),nc(r)&&R(i=>{let s=x.stats(i);if(console.log(`Symbols: ${s.symbols}`),console.log(`Files: ${s.documents}`),console.log(`Size: ${Vn(s.indexSizeBytes)}`),s.lastBuilt){let o=Math.round((Date.now()-s.lastBuilt.getTime())/1e3);console.log(`Built: ${o}s ago`)}})});y_()&&I.parse();function y_(){if(!process.argv[1])return!1;let e=mi(import.meta.url);try{return rc(e)===rc(process.argv[1])}catch{return e===process.argv[1]}}export{I as program,Se as renderHeuristicNotice};
874
+ `);for(let o=0;o<i.length;o++)console.log(` ${String($e(r.startLine+o)).padStart(4)} ${i[o]}`)}),MR=Z("dataflow",({db:e,args:t,budget:n})=>{let r=Mo(e,M(t,0),{semantic:n.semantic});if(!r)return N.empty("Symbol not found.");if(console.log(`${r.shortName} (${r.relativePath})
875
+ `),r.definitionSites.length>0){console.log(" \u2550\u2550\u2550 DEFINED AT \u2550\u2550\u2550");for(let i of r.definitionSites)console.log(` ${i.file}:${$e(i.line)}`)}if(r.usageSites.length>0){console.log(`
876
+ \u2550\u2550\u2550 USED AT \u2550\u2550\u2550`);for(let i of r.usageSites)console.log(` ${i.file}:${$e(i.line)} in ${i.enclosingShort}`)}if(r.producers.length>0){console.log(`
877
+ \u2550\u2550\u2550 PRODUCERS (feeds into this) \u2550\u2550\u2550`);for(let i of r.producers)console.log(` ${i.file} ${i.shortName}`)}if(r.consumers.length>0){console.log(`
878
+ \u2550\u2550\u2550 CONSUMERS (this feeds into) \u2550\u2550\u2550`);for(let i of r.consumers)console.log(` ${i.file} ${i.shortName}`)}}),OR=Z("slice",({db:e,args:t,opts:n,budget:r})=>{let i=z(n,"forward")?"forward":"backward",o=Oo(e,M(t,0),{direction:i,maxDepth:I(n,"depth",3),semantic:r.semantic});if(!o)return N.empty("Symbol not found.");if(console.log(`${o.direction} slice of ${o.shortName}
879
+ `),o.connectedSymbols.length===0){console.log(" No connected symbols found.");return}N.list(o.connectedSymbols,s=>` ${s.file} ${s.shortName}
880
+ ${s.relationship}`),console.log(`
881
+ ${o.connectedSymbols.length} connected symbol(s).`)}),cm=[ve({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:S("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>zr(e,M(t,0)),format:e=>e.relativePath}),ve({id:"symbols",command:"symbols <file>",description:"List symbols defined in a file (with line ranges + signatures)",docs:S("Navigation",["scip-query symbols src/runtime/cli.ts"]),query:({db:e,args:t})=>si(e,M(t,0)),format:e=>{let t=e.signature?` \u2014 ${e.signature}`:"";return` ${be(e.startLine,e.endLine)} ${e.shortName}${t}`}}),ve({id:"methods",command:"methods <className>",description:"List methods of a class (with line ranges)",docs:S("Navigation"),query:({db:e,args:t})=>Bi(e,M(t,0)),format:e=>` ${be(e.startLine,e.endLine)} ${e.name}`}),{id:"refs",command:"refs <symbol>",description:"Find all files referencing a symbol",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"grouped-by-file",docs:S("Navigation",["scip-query refs login"]),handler:PR},{id:"trace",command:"trace <symbol>",description:"Trace a symbol: definition + all references",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"sectioned-report",docs:S("Navigation",["scip-query trace parseSymbol"]),handler:ER},ve({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:S("Navigation"),query:({db:e,args:t})=>Vi(e,M(t,0)),format:e=>e.relativePath}),ve({id:"rdeps",command:"rdeps <file>",description:"Files that depend on this file/module",docs:S("Navigation"),query:({db:e,args:t})=>qi(e,M(t,0)),format:e=>e.relativePath}),{id:"system",command:"system <module>",description:"Full module map: files, symbols, deps in/out",renderShape:"sectioned-report",docs:S("Navigation",["scip-query system queries"]),handler:LR},ve({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:S("Navigation"),query:({db:e,args:t})=>Ji(e,M(t,0)),format:e=>` ${e.consumer} \u2192 ${e.shortName}`}),{id:"imports",command:"imports <file>",description:"What symbols does this file import?",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"list",docs:S("Navigation"),handler:kR},ve({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:S("Navigation"),query:({db:e,args:t})=>Zi(e,M(t,0)),format:e=>` ${e.fromFile}`}),{id:"outline",command:"outline <file>",description:"Tree view of symbols in a file (using nesting hierarchy)",renderShape:"custom",docs:S("Navigation"),handler:wR},ve({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:S("Navigation"),query:({db:e,args:t})=>no(e,M(t,0)),format:e=>` ${be(e.startLine,e.endLine)} [${e.kind}] ${e.shortName}`}),ve({id:"by-kind",command:"by-kind <kind>",description:"Find symbols by SCIP kind (class, interface, enum, function, etc.)",options:[g("-s, --scope <path>","Limit to files matching path"),g("-n, --limit <n>","Number of results",D,100)],docs:S("Navigation"),query:({db:e,args:t,opts:n})=>po(e,M(t,0),{scope:O(n,"scope"),limit:I(n,"limit",100)}),format:e=>` ${Se(e.relativePath,e.startLine,e.endLine)} [${e.kindName}] ${e.shortName}`,emptyMessage:({args:e})=>`No symbols found for kind "${M(e,0)}". Use "kind-counts" to see available kinds.`,after:e=>console.log(`
882
+ ${e.length} symbol(s)`)}),qr({id:"kind-counts",command:"kind-counts",description:"Histogram of symbol kinds in the codebase",options:[g("-s, --scope <path>","Limit to files matching path")],docs:S("Navigation"),headers:["count","kind"],query:({db:e,opts:t})=>fo(e,{scope:O(t,"scope")}),format:e=>` ${String(e.count).padStart(5)} ${e.kindName} (${e.kind})`}),ve({id:"hierarchy",command:"hierarchy <symbol>",description:"Show a symbol's ancestry chain (method \u2192 class \u2192 module)",docs:S("Navigation"),query:({db:e,args:t})=>ho(e,M(t,0)),format:e=>`${" ".repeat(e.depth)}${e.shortName}`,emptyMessage:()=>"Symbol not found."}),{id:"code",command:"code <symbol>",description:"Read the source code for a symbol (bounded to its definition range)",options:[g("-C, --context <n>","Extra lines of context above/below",D,0)],renderShape:"custom",docs:S("Navigation"),handler:TR},{id:"dataflow",command:"dataflow <symbol>",description:"Reference-level dataflow: definition sites, usage sites, producers, consumers",options:[g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",docs:S("Navigation"),handler:MR},{id:"slice",command:"slice <symbol>",description:"Reference-level program slice: what affects this (backward) or what this affects (forward)",options:[g("--forward","Forward slice (what does this affect). Default is backward."),g("--depth <n>","Max transitive depth for backward slice",D,3),g("--full","Run unbounded semantic analysis on large indexes")],budget:"semantic",renderShape:"custom",docs:S("Navigation"),handler:OR}];var lm=["stats","files","symbols","methods","refs","trace","deps","rdeps","system","surface","dead","hotspots","imports","imported-by","unused-imports","outline","members","fan-in","fan-out","coupling","cycles","bottlenecks","isolated","by-kind","kind-counts","deep-chains","hierarchy","call-graph","similar","similar-files","similar-chains","extract-candidates","affected","change-surface","drift","wrapper-candidates","passthrough-candidates","stale-abstractions","complexity-hotspots","convergence","code","complexity","dataflow","slice","redundant-reexports","similar-signatures"],FR=[im,cm,om,rm,am,sm],um=FR.flat(),mm=new Map(um.map(e=>[e.id,e])),H0=lm.map(e=>{let t=mm.get(e);if(!t)throw new Error(`Missing query command descriptor: ${e}`);return t});for(let e of um)if(!lm.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);function C(e){let t=mm.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var dm=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[g("-l, --language <lang>","Index only this language (can be repeated)",Ol,[]),g("--pnpm-workspaces","Enable pnpm workspace support (TypeScript)"),g("--force","Rebuild even if source inputs are unchanged"),g("--allow-partial","Write an incomplete index when one or more detected languages fail"),g("--indexer-concurrency <n>","Number of language indexers to run at once",Er)],renderShape:"custom",docs:S("Indexing",["scip-query reindex"]),handler:Vu},{id:"augment-sources",command:"augment-sources",description:"Add source files skipped by upstream SCIP indexers to the SQLite documents table",renderShape:"custom",docs:S("Indexing"),handler:qu},{id:"augment-vue",command:"augment-vue",description:"Add compiler-resolved Vue SFC references to the SQLite index using Volar",options:[g("--project <tsconfig>","Vue tsconfig path",void 0,"frontend/tsconfig.scip.json")],renderShape:"custom",docs:S("Indexing"),handler:Uu},C("stats"),C("files"),C("symbols"),C("methods"),C("refs"),C("trace"),C("deps"),C("rdeps"),C("system"),C("surface"),C("dead"),C("hotspots"),C("imports"),C("imported-by"),C("unused-imports"),C("outline"),C("members"),C("fan-in"),C("fan-out"),C("coupling"),C("cycles"),C("bottlenecks"),C("isolated"),C("by-kind"),C("kind-counts"),C("deep-chains"),C("hierarchy"),C("call-graph"),C("similar"),C("similar-files"),C("similar-chains"),C("extract-candidates"),C("affected"),C("change-surface"),{id:Lr,command:Lr,description:"Internal diff-impact batch worker",hidden:!0,options:[g("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:Ju},{id:"diff-impact",command:"diff-impact",description:"Compute changed symbols and downstream consumers from current git diff",options:[g("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",docs:S("Impact"),handler:zu},C("drift"),C("wrapper-candidates"),C("passthrough-candidates"),C("stale-abstractions"),C("complexity-hotspots"),{id:Nr,command:Nr,description:"Internal health phase worker",hidden:!0,arguments:[{name:"<phase>"}],options:[g("-s, --scope <path>","Limit to files matching path"),g("--full","Run unbounded candidate analyses on large indexes")],renderShape:"custom",handler:Gu},{id:"health",command:"health",description:"Composite codebase health report with prioritized action list",options:[g("-s, --scope <path>","Limit to files matching path"),g("--full","Run unbounded candidate analyses on large indexes"),g("--json","Output as JSON for programmatic consumption")],renderShape:"custom",docs:S("Health",["scip-query health --json"]),handler:Ku},C("convergence"),C("code"),C("complexity"),C("dataflow"),C("slice"),{id:"install-skills",command:"install-skills",description:`Install skills (${Qo.join(", ")}) into Claude Code and Codex`,renderShape:"custom",docs:S("Maintenance"),handler:Qu},{id:"check-deps",command:"check-deps",description:"Check whether scip-query and the detected language indexers are actually runnable",renderShape:"custom",docs:S("Maintenance"),handler:Yu},C("redundant-reexports"),C("similar-signatures"),{id:"init",command:"init",description:"Create a .scipquery.json config file for this project",renderShape:"custom",docs:S("Maintenance"),handler:Xu},{id:"watch",command:"watch",description:"Watch for file changes and reindex automatically",options:[g("--debounce <ms>","Ms to wait after last change (default: 30000)",qo),g("--cooldown <ms>","Min ms between reindexes (default: 60000)",qo)],renderShape:"custom",docs:S("Maintenance"),handler:Zu},{id:"status",command:"status",description:"Show index status for this project",renderShape:"custom",docs:S("Maintenance"),handler:em}];function pm(e,t){return t.map(n=>{let r=n.hidden?e.command(n.command,{hidden:!0}):e.command(n.command);r.description(n.description);for(let i of n.arguments??[])r.argument(i.name);for(let i of n.options??[])i.parser&&Object.hasOwn(i,"defaultValue")?r.option(i.flags,i.description,i.parser,i.defaultValue):i.parser?r.option(i.flags,i.description,i.parser):Object.hasOwn(i,"defaultValue")?r.option(i.flags,i.description,i.defaultValue):r.option(i.flags,i.description);return r.action((...i)=>n.handler(...i)),{descriptor:n,command:r}})}import{existsSync as AR,mkdirSync as $R,readFileSync as jR,writeFileSync as BR}from"fs";import{homedir as HR}from"os";import{join as Ur}from"path";var WR=1440*60*1e3,gm="update-check.json",VR="https://registry.npmjs.org/scip-query/latest";async function hm(e={}){let t=e.env??process.env;if(t.SCIP_QUERY_UPDATE_CHECK==="0"||t.NO_UPDATE_NOTIFIER)return;let n=e.cacheDir??JR(t),r=e.now??Date.now(),i=e.currentVersion??Dr,o=zR(n),s=o&&r-o.checkedAt<WR?o.latestVersion:await GR(n,e.fetchLatestVersion??QR,r);if(!s||!UR(s,i))return;(e.writeNotice??(c=>console.error(c)))(qR(i,s))}function qR(e,t){return[`scip-query update available: ${e} -> ${t}.`,"Agent: tell your human to update with: npm install -g scip-query@latest",""].join(`
883
+ `)}function UR(e,t){let n=fm(e),r=fm(t);if(!n||!r)return e!==t;for(let i=0;i<n.length;i++){let o=n[i]-r[i];if(o>0)return!0;if(o<0)return!1}return!1}function JR(e){let t=e.XDG_CACHE_HOME||Ur(HR(),".cache");return Ur(t,"scip-query")}function zR(e){let t=Ur(e,gm);if(!AR(t))return null;try{let n=JSON.parse(jR(t,"utf8"));return typeof n.checkedAt=="number"&&(typeof n.latestVersion=="string"||n.latestVersion===null)?{checkedAt:n.checkedAt,latestVersion:n.latestVersion}:null}catch{return null}}async function GR(e,t,n){let r;try{r=await t()}catch{r=null}return KR(e,{checkedAt:n,latestVersion:r}),r}function KR(e,t){try{$R(e,{recursive:!0}),BR(Ur(e,gm),`${JSON.stringify(t,null,2)}
884
+ `)}catch{}}async function QR(){let e=await fetch(VR,{signal:AbortSignal.timeout(1e3)});if(!e.ok)return null;let t=await e.json();return typeof t.version=="string"?t.version:null}function fm(e){let t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}Jr.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(Dr);pm(Jr,dm);Jr.hook("preAction",async()=>{await hm()});XR()&&await Jr.parseAsync();function XR(){if(!process.argv[1])return!1;let e=YR(import.meta.url);try{return ym(e)===ym(process.argv[1])}catch{return e===process.argv[1]}}export{Jr as program,On as renderHeuristicNotice};
1048
885
  //# sourceMappingURL=cli.js.map