scip-query 0.6.7 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/augment-vue-worker.js +1 -1
- package/dist/chunk-23YIGCYF.js +25 -0
- package/dist/{chunk-KQWFRAQI.js → chunk-2IYEIFPP.js} +6 -6
- package/dist/chunk-2JEFS2YJ.js +2 -0
- package/dist/chunk-33SSUPCB.js +7 -0
- package/dist/chunk-3GNFUVFA.js +2 -0
- package/dist/{chunk-ZNNCDAYX.js → chunk-3OUC276S.js} +2 -2
- package/dist/{chunk-PQTGBYXV.js → chunk-4STLJYHI.js} +4 -4
- package/dist/chunk-563HLCDW.js +35 -0
- package/dist/chunk-5TT47UMX.js +44 -0
- package/dist/chunk-6H2XIIPY.js +71 -0
- package/dist/{chunk-HTJ5BOYP.js → chunk-72JOIFXL.js} +3 -3
- package/dist/chunk-7H4RJ4MC.js +2 -0
- package/dist/chunk-7O4MJYIW.js +63 -0
- package/dist/chunk-7OX2O53H.js +62 -0
- package/dist/chunk-A2AVLALL.js +2 -0
- package/dist/chunk-AQYBOORI.js +2 -0
- package/dist/chunk-ARBZM2NF.js +34 -0
- package/dist/{chunk-2CC7RA6B.js → chunk-BI4F6GXI.js} +2 -2
- package/dist/chunk-BOVNTAKQ.js +3 -0
- package/dist/chunk-CKIO6SVS.js +2 -0
- package/dist/chunk-D6Z67MZL.js +2 -0
- package/dist/chunk-DFK54IRN.js +2 -0
- package/dist/chunk-FD37DBTD.js +2 -0
- package/dist/chunk-FOQQDXE7.js +2 -0
- package/dist/chunk-GAQGJ52J.js +11 -0
- package/dist/chunk-IODTPF5H.js +20 -0
- package/dist/chunk-J6Z5YKGQ.js +4 -0
- package/dist/chunk-JB4PUN5S.js +40 -0
- package/dist/chunk-JTXKS5GK.js +3 -0
- package/dist/chunk-KJ3ZJIE5.js +2 -0
- package/dist/chunk-KJ6CW6EK.js +2 -0
- package/dist/{chunk-2R7OKZE5.js → chunk-KNA6Z7JB.js} +3 -3
- package/dist/{chunk-FYO3FPFH.js → chunk-LDV2B7ET.js} +8 -8
- package/dist/chunk-LWYIGRHR.js +5 -0
- package/dist/chunk-MDAYGS6T.js +2 -0
- package/dist/chunk-MX6F756F.js +2 -0
- package/dist/chunk-NHDPYW7O.js +2 -0
- package/dist/{chunk-TYRPQE6R.js → chunk-NKJKI6SE.js} +2 -2
- package/dist/chunk-NN3O7TPH.js +8 -0
- package/dist/chunk-NSTZMBAB.js +18 -0
- package/dist/chunk-NYEMZHUC.js +6 -0
- package/dist/chunk-OHEIZWIA.js +4 -0
- package/dist/chunk-PG3ZI5IH.js +2 -0
- package/dist/chunk-QAEDNTY7.js +2 -0
- package/dist/chunk-QE6MGGUY.js +2 -0
- package/dist/chunk-QPRIYXH4.js +2 -0
- package/dist/chunk-QWJBIBE6.js +3 -0
- package/dist/chunk-RCJEFQOK.js +4 -0
- package/dist/chunk-ROOHENEP.js +61 -0
- package/dist/{chunk-2YA36CXK.js → chunk-ROZNBWIF.js} +2 -2
- package/dist/chunk-TGK5DFBJ.js +2 -0
- package/dist/chunk-TKDJQ2WD.js +59 -0
- package/dist/chunk-TRNAQABL.js +7 -0
- package/dist/chunk-U75WH4XG.js +2 -0
- package/dist/chunk-V53J46BX.js +2 -0
- package/dist/chunk-V76FCF5F.js +2 -0
- package/dist/chunk-VUBQBW7H.js +16 -0
- package/dist/chunk-WJQY2LGT.js +2 -0
- package/dist/{chunk-ILQSK2KJ.js → chunk-WODJHE6Z.js} +3 -3
- package/dist/{chunk-RRWPHKZA.js → chunk-WPLKHAH7.js} +4 -4
- package/dist/chunk-XO6R3X5J.js +2 -0
- package/dist/chunk-YSZNAG4G.js +2 -0
- package/dist/chunk-ZNUPGRPR.js +3 -0
- package/dist/{chunk-OCQN6WF4.js → chunk-ZXFTC5ET.js} +4 -4
- package/dist/cli.js +361 -505
- package/dist/config-types-CGIeLEpY.d.ts +108 -0
- package/dist/db-DdTPetj5.d.ts +69 -0
- package/dist/health-x7B4Xu_6.d.ts +119 -0
- package/dist/index.d.ts +109 -336
- package/dist/index.js +3 -131
- package/dist/postinstall.js +1 -1
- package/dist/queries/affected.d.ts +9 -2
- package/dist/queries/affected.js +1 -1
- package/dist/queries/bottlenecks.d.ts +14 -2
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.d.ts +12 -2
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +22 -3
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +19 -3
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/code.d.ts +12 -2
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +16 -2
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +22 -3
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.d.ts +25 -3
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +8 -2
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +16 -2
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +35 -3
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.d.ts +34 -2
- package/dist/queries/dead.js +1 -1
- package/dist/queries/deep-chains.d.ts +8 -2
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/deps.d.ts +6 -2
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-impact.d.ts +22 -2
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/drift.d.ts +19 -2
- package/dist/queries/drift.js +1 -1
- package/dist/queries/extract-candidates.d.ts +20 -2
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +7 -2
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +6 -2
- package/dist/queries/files.js +1 -1
- package/dist/queries/health.d.ts +4 -81
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +8 -2
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +10 -2
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +19 -4
- package/dist/queries/imports.js +1 -1
- package/dist/queries/index.d.ts +45 -44
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.d.ts +13 -2
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/members.d.ts +10 -2
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.d.ts +8 -2
- package/dist/queries/methods.js +1 -1
- package/dist/queries/outline.d.ts +10 -2
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.d.ts +15 -2
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +13 -2
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.d.ts +10 -3
- package/dist/queries/refs.js +1 -1
- package/dist/queries/similar-chains.d.ts +21 -2
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.d.ts +12 -2
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.d.ts +18 -2
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +24 -2
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.d.ts +17 -2
- package/dist/queries/slice.js +1 -1
- package/dist/queries/stale-abstractions.d.ts +37 -3
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/stats.d.ts +11 -2
- package/dist/queries/stats.js +1 -1
- package/dist/queries/surface.d.ts +8 -2
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.d.ts +10 -2
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.d.ts +10 -2
- package/dist/queries/system.js +1 -1
- package/dist/queries/trace.d.ts +21 -3
- package/dist/queries/trace.js +1 -1
- package/dist/queries/wrapper-candidates.d.ts +15 -2
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/reindex-worker.js +10 -10
- package/dist/reindex.d.ts +153 -0
- package/dist/reindex.js +69 -0
- package/dist/runtime.d.ts +108 -0
- package/dist/runtime.js +3 -0
- package/dist/scip-cli-a-xOztiK.d.ts +20 -0
- package/package.json +184 -4
- package/dist/chunk-2AUZ3PLO.js +0 -2
- package/dist/chunk-3A2M7AF3.js +0 -4
- package/dist/chunk-3EJRPTTB.js +0 -2
- package/dist/chunk-3SWWYJPB.js +0 -6
- package/dist/chunk-4M4FEWBL.js +0 -7
- package/dist/chunk-4Y6KUJDO.js +0 -39
- package/dist/chunk-55ZJ2FCW.js +0 -6
- package/dist/chunk-6FLGPRBR.js +0 -5
- package/dist/chunk-6XRB6ATD.js +0 -16
- package/dist/chunk-7EQ4J66C.js +0 -2
- package/dist/chunk-7TGEXAN5.js +0 -25
- package/dist/chunk-ABLXPGAZ.js +0 -2
- package/dist/chunk-BG7YU4DJ.js +0 -2
- package/dist/chunk-D2R6IIEO.js +0 -2
- package/dist/chunk-E47WMJ5F.js +0 -2
- package/dist/chunk-EEA3R37V.js +0 -11
- package/dist/chunk-FAN2CVZT.js +0 -2
- package/dist/chunk-FVH3Y44U.js +0 -1
- package/dist/chunk-G47V5V3U.js +0 -90
- package/dist/chunk-GS55K4WJ.js +0 -85
- package/dist/chunk-H4DXD2FB.js +0 -5
- package/dist/chunk-HADDFTMU.js +0 -2
- package/dist/chunk-IARIBTCL.js +0 -2
- package/dist/chunk-IBWYWAWE.js +0 -70
- package/dist/chunk-JVMXNDRU.js +0 -2
- package/dist/chunk-K345WFTU.js +0 -2
- package/dist/chunk-K6ULLR7M.js +0 -19
- package/dist/chunk-KAM4C6ZD.js +0 -4
- package/dist/chunk-KCC3GMCX.js +0 -2
- package/dist/chunk-KRVRD6KZ.js +0 -5
- package/dist/chunk-KYGNCIJ6.js +0 -84
- package/dist/chunk-LHLXHH43.js +0 -2
- package/dist/chunk-LJ2YWNQF.js +0 -2
- package/dist/chunk-M7GBLQG4.js +0 -7
- package/dist/chunk-MEVK6R7N.js +0 -2
- package/dist/chunk-QRYEOK3M.js +0 -2
- package/dist/chunk-QYWGC7JV.js +0 -114
- package/dist/chunk-R373SHXM.js +0 -2
- package/dist/chunk-RUAJV3TN.js +0 -2
- package/dist/chunk-S57GUI2T.js +0 -7
- package/dist/chunk-SVUVC5VS.js +0 -2
- package/dist/chunk-T426XELO.js +0 -12
- package/dist/chunk-TBJDUS4E.js +0 -71
- package/dist/chunk-TX7BHRMT.js +0 -2
- package/dist/chunk-WPY46NIL.js +0 -5
- package/dist/chunk-X3Z4KZNX.js +0 -2
- package/dist/db-DdlToIC-.d.ts +0 -835
- package/dist/queries/drift-policy.d.ts +0 -6
- package/dist/queries/drift-policy.js +0 -2
- package/dist/queries/health-cache-control.d.ts +0 -15
- 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
|
-
|
|
3
|
-
`),n}function jn(e){return Gl(e,{recursive:!0}),e}import{execFile as Id,execFileSync as Rd}from"child_process";import{closeSync as Cd,existsSync as Ue,mkdirSync as Vi,mkdtempSync as vd,openSync as Nd,readFileSync as Ed,renameSync as tt,rmSync as nt,writeFileSync as Ji}from"fs";import{cpus as Dd}from"os";import{basename as Xt,dirname as We,extname as Ld,join as se}from"path";import{execFileSync as Wt}from"child_process";import{platform as Ut,arch as Zl}from"os";var si=Ut()==="win32",oi="v0.7.0";function Ht(e){let t=si?"where":"which";try{return Wt(t,[e],{stdio:"pipe"}),!0}catch{return!1}}function Bn(){try{return Wt(si?"where":"which",["scip"],{stdio:"pipe"}),!0}catch{return!1}}function ec(){let e=Ut(),t=Zl(),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/${oi}/${s}`,filename:s}}function Hn(){let e=ec();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Ut()==="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/${oi}
|
|
6
|
-
`),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function ai(e){if(Ut()==="darwin"&&Ht("brew")){e("Installing scip CLI via Homebrew...");try{if(Wt("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),Ht("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(Ht("go")){e("Installing scip CLI via go install...");try{if(Wt("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),Ht("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 fc from"better-sqlite3";import{execFileSync as gc}from"child_process";import{existsSync as hc,readdirSync as yc,readFileSync as bc}from"fs";import{extname as Jt,join as pi}from"path";import tc from"ignore";import{readFileSync as nc,existsSync as Wn}from"fs";import{dirname as Un,isAbsolute as li,join as Vn,relative as rc,resolve as ic}from"path";function Xe(e){let t=tc(),n=!1,r=sc(e);for(let i of r)try{let s=nc(i,"utf-8");t.add(s),n=!0}catch{}return n||t.add(oc),{isIgnored:i=>ci(t,e,i),filter:i=>i.filter(s=>!ci(t,e,s))}}function sc(e){let t=[],n=Vn(e,".gitignore");Wn(n)&&t.push(n);let r=Un(e),i=0;for(;r!==Un(r)&&i<5;){let s=Vn(r,".gitignore");if(Wn(s)&&t.push(s),Wn(Vn(r,".git")))break;r=Un(r),i++}return t}var oc=`
|
|
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 ci(e,t,n){let r=ac(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function ac(e,t){if(!t||t===".")return null;if(!li(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=li(t)?t:ic(e,t),r=rc(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{readdirSync as lc}from"fs";import{extname as ui,join as cc}from"path";function A(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 Be(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 Vt(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 uc=[".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"],di=[".vue"],mi=new Set(uc.map(e=>e.toLowerCase())),dc=[...mi].sort().join(","),Jn=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function Le(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(l=>l.toLowerCase()),s=i?new Set(i):mi,o=i?[...s].sort().join(","):dc,a=`${n?"1":"0"}|${r?"1":"0"}|${o}`;return mc.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(ui(u.relative_path).toLowerCase())&&l.add(u.relative_path)}if(r)for(let c of pc(e.config.projectRoot,s))e.isIgnored(c)||l.add(c);return[...l].sort()})}var mc=A("source-files");function pc(e,t){let n=new Set,r=i=>{let s=i?cc(e,i):e,o;try{o=lc(s,{withFileTypes:!0})}catch{return}for(let a of o)if(!Jn.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(ui(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}function we(e){let t=new Set((e.extensions??di).map(s=>s.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!hc(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Xe(e.projectRoot),r=Sc(e.projectRoot,t).filter(s=>!n.isIgnored(s)),i=new fc(e.dbPath);try{let s=_c(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=bc(pi(e.projectRoot,m),"utf-8"),h=o.run(Ic(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 Sc(e,t){let n=xc(e,t);if(n)return n;let r=[],i=s=>{let o=s?pi(e,s):e,a;try{a=yc(o,{withFileTypes:!0})}catch{return}for(let l of a){if(Jn.has(l.name))continue;let c=s?`${s}/${l.name}`:l.name;if(l.isDirectory()){i(c);continue}t.has(Jt(l.name).toLowerCase())&&r.push(c)}};return i(""),r.sort()}function xc(e,t){try{return gc("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
|
|
68
|
-
`).filter(r=>r&&t.has(Jt(r).toLowerCase())).sort()}catch{return null}}function _c(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 Ic(e){return Jt(e).toLowerCase()===".vue"?"vue":Jt(e).replace(/^\./,"").toLowerCase()||"source"}import{execFileSync as Rc}from"child_process";import{existsSync as Cc,readdirSync as gi}from"fs";import{extname as hi,join as yi}from"path";var vc=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),Nc=[{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 He(e){let t=[],n=Ec(e),r=kc(e);for(let i of Nc){if(Dc(e,i.files)){t.push(i.language);continue}if(Lc(n,i.globs)){t.push(i.language);continue}Oc(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&fi(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&fi(t,"c"),t}function Ec(e){try{return gi(e)}catch{return[]}}function Dc(e,t){return t?.length?t.some(n=>Cc(yi(e,n))):!1}function Lc(e,t){return t?.length?e.some(n=>t.some(r=>wc(n,r))):!1}function wc(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=Pc(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=gi(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=yi(i,o.name);if(o.isDirectory()){vc.has(o.name)||r.push(a);continue}let l=hi(o.name).toLowerCase();l&&n.add(l)}}return n}function Pc(e){try{let t=Rc("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=hi(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Oc(e,t){return t?.length?t.some(n=>e.has(n)):!1}function fi(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as bi,readdirSync as Mc}from"fs";import{join as qn}from"path";var Tc={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",Si(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",Si(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=qn(e,"vendor","bin","scip-php"),r=qn(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",bi(r)?r:bi(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function qt(e){return Tc[e]}function Si(e,t){let n;try{n=Mc(e)}catch{return null}for(let r of n)if(t.some(i=>r.endsWith(i)))return qn(e,r);return null}import{readFileSync as Fc,writeFileSync as Ac}from"fs";import{create as zn}from"@bufbuild/protobuf";import{deserializeSCIP as $c,serializeSCIP as jc,DocumentSchema as Bc,IndexSchema as Hc,SymbolInformationSchema as Wc}from"@c4312/scip";function Uc(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=Vc(e),n=Jc(e.flatMap(i=>i.documents??[])),r=_i(e.flatMap(i=>i.externalSymbols??[]));return zn(Hc,{metadata:t,documents:n,externalSymbols:r})}function xi(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>$c(Fc(i))),r=Uc(n);return Ac(t,Buffer.from(jc(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function Vc(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 Jc(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(Bc,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:[...r.occurrences,...n.occurrences],symbols:_i([...r.symbols,...n.symbols]),text:zc(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function _i(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(Wc,{symbol:r.symbol,documentation:Gc([...r.documentation,...n.documentation]),relationships:qc([...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 qc(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 zc(e,t){return e?t?e.length>=t.length?e:t:e:t}function Gc(e){return[...new Set(e)]}import{execFileSync as Kc}from"child_process";import{createHash as Yc}from"crypto";import{readdirSync as Qc,readFileSync as Xc}from"fs";import{join as Ii}from"path";function Zc(e){return(eu(e)??tu(e)).filter(t=>t&&!Ri(t)).sort()}function zt(e){return Zc(e).map(t=>{let n=Ii(e,t);try{let r=Xc(n);return{path:t,size:r.byteLength,hash:Yc("sha256").update(r).digest("hex")}}catch{return{path:t,size:-1,hash:"unreadable"}}})}function eu(e){try{return Kc("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 tu(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?Ii(e,r):e,s;try{s=Qc(i,{withFileTypes:!0})}catch{continue}for(let o of s){let a=r?`${r}/${o.name}`:o.name;if(o.isDirectory()){Ri(a)||n.push(a);continue}t.push(a)}}return t}function Ri(e){return e.split("/").some(n=>nu.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var nu=new Set([".git","node_modules",".scipquery-cache",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]);import{readFileSync as ru,writeFileSync as iu}from"fs";import{create as Ci}from"@bufbuild/protobuf";import{deserializeSCIP as su,DocumentSchema as ou,IndexSchema as au,serializeSCIP as lu,SymbolRole as cu}from"@c4312/scip";function vi(e){let t;try{t=su(ru(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=uu(t);return n.removedDefinitionOccurrences>0&&iu(e,Buffer.from(lu(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function uu(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&cu.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(o.length===s.occurrences.length){i.push(s);continue}r+=1,i.push(Ci(ou,{language:s.language,relativePath:s.relativePath,occurrences:o,symbols:s.symbols,text:s.text,positionEncoding:s.positionEncoding}))}return{index:n===0?e:Ci(au,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}import{execFileSync as Kt}from"child_process";import{existsSync as Gn,readFileSync as du}from"fs";import{createRequire as mu}from"module";import{platform as Ei}from"os";import{dirname as Ni,join as Gt}from"path";var pu=mu(import.meta.url),fu=Ei()==="win32";function ft(e){let t=fu?"where":"which";try{return Kt(t,[e],{stdio:"pipe"}),!0}catch{return!1}}function Kn(e){return[e.indexerBinary,...e.binaryAliases??[]]}function Yt(e){let t=Kn(e);return t.length===1?t[0]:t.join(" or ")}function Ze(e){for(let t of Kn(e))if(ft(t))return t;return hu(e)}function Di(e){return Ze(e)!==null||gu(e)}function gu(e){return Li(e)!==null}function hu(e){let t=Li(e);if(!t)return null;let r=JSON.parse(du(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return Gt(Ni(t),r);for(let i of Kn(e)){let s=r[i];if(s)return Gt(Ni(t),s)}return null}function Li(e){if(!e.bundledNpmPackage)return null;try{return pu.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function Yn(e,t){for(let n of e.projectLocalBinaries??[]){let r=Gt(t,n);if(Gn(r))return r}return null}function yu(e,t){return Yn(e,t)??Ze(e)}function wi(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||Qn(n,t))return t;let r=Oi(n,t);return r?{...t,DOTNET_ROOT:r}:t}function ki(e,t){let n=Yt(e),r=t?yu(e,t):Ze(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=bu(r);return{language:e.language,binaryLabel:n,installed:!0,runnable:i.runnable,resolvedBinary:r,installUrl:e.installUrl,note:i.note}}function Pi(e,t){let n=e.installMethods,r=Yt(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(ft(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{Kt(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env});let s=Ze(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 bu(e){if(Qn(e,process.env))return{runnable:!0};let t=Oi(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=Mi(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 Oi(e,t){for(let n of Mi(t))if(Qn(e,{...t,DOTNET_ROOT:n}))return n;return null}function Mi(e){let t=[],n=e.DOTNET_ROOT;if(n&&Gn(n)&&t.push(n),Ei()==="darwin"&&ft("brew"))try{let r=Kt("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=Gt(r,"libexec");Gn(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function Qn(e,t){try{return Kt(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import Su from"better-sqlite3";import{createRequire as xu}from"module";import{existsSync as Fi,mkdtempSync as _u,readFileSync as gt,rmSync as Iu,statSync as Ru,writeFileSync as Cu}from"fs";import{cpus as vu,tmpdir as Nu}from"os";import{dirname as Zn,extname as Eu,join as et,relative as Du,resolve as Ai}from"path";import{pathToFileURL as Lu}from"url";import{Worker as wu}from"worker_threads";function er(e){we({projectRoot:e.projectRoot,dbPath:e.dbPath});let t=Ai(e.projectRoot,e.tsconfig);if(!Fi(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Su(e.dbPath);try{let r=Xu(n,e.projectRoot),i=et(Zn(e.dbPath),"augment-vue-meta.json"),s=Ti(n,e.projectRoot,e.tsconfig),o=ku(i,s,e.onStatus);if(o)return o;let a=ad(n,e.projectRoot,r),l=Pu(n,e,t,r,a),c=dd(l.occurrences),u=Ou(n,e,r,a,c);e.onStatus?.(`Resolved ${c.length} Vue references with Volar; inserted ${u} mentions.`);let d=Mu(r,c,u,l,a);return Fu(i,Ti(n,e.projectRoot,e.tsconfig),d),d}finally{n.close()}}function ku(e,t,n){let r=Tu(e,t);return r&&n?.(`Vue references unchanged; reused ${r.resolvedReferences} cached resolved references.`),r}function Pu(e,t,n,r,i){if(Vu(r))return Ju({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:t.tsconfig,vueFiles:r});let s=yd(),o=Zu(t.projectRoot,n);return Au({projectRoot:t.projectRoot,vueFiles:o.fileNames.filter(a=>a.endsWith(".vue")),context:o,symbolLookup:id(e,t.projectRoot,s),vueSymbolLookup:i,sourceCache:s})}function Ou(e,t,n,r,i){return ld(e,t.projectRoot,n,r,i)}function Mu(e,t,n,r,i){return{vueFiles:e.length,resolvedReferences:t.length,insertedMentions:n,skippedReferences:r.skippedReferences,syntheticSymbols:i.syntheticSymbols}}function Tu(e,t){try{let n=JSON.parse(gt(e,"utf-8"));return JSON.stringify(n.fingerprint)===JSON.stringify(t)?n.result:null}catch{return null}}function Fu(e,t,n){Cu(e,JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)+`
|
|
71
|
-
`)}function Ti(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:zt(t),db:r}}function Au(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=$u(e,i);t.push(...s.occurrences),n+=s.skippedReferences}return{occurrences:t,skippedReferences:n}}function $u(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=ht(e.projectRoot,t.fileName),a=[...pd(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:Hu(a),processedStarts:new Set};return ju({...e,fileName:t.fileName,sourceInfo:i,sourceFile:o,map:s,tokenContext:l})}function ju(e){let t=[],n=0;for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start))continue;let i=fd(e.map,r.start);if(i===null)continue;let o=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(l=>!gd(e.projectRoot,l.fileName));if(!o){n++;continue}let a=ud(o,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}$i(t,e.sourceInfo,e.sourceFile,r,a),e.tokenContext.processedStarts.add(r.start),Bu(t,e,r,i,a)}return{occurrences:t,skippedReferences:n}}function Bu(e,t,n,r,i){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let s of Wu(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&&($i(e,t.sourceInfo,t.sourceFile,o,i),t.tokenContext.processedStarts.add(s))}}function $i(e,t,n,r,i){let s=Ui(t,r.start);e.push({sourceFile:n,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+r.text.length,symbolId:i})}function Hu(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function Wu(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=Uu(r,c.textSpan.start,s,i.text);u!==null&&a.push(u)}return a}function Uu(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let s=Wi(e,t);if(s===null)return null;let o=n.get(s);return o?.text===r?o.start:null}function Vu(e){return e.length>=8&&ji(e.length)>1}function Ju(e){let t=ji(e.vueFiles.length),n=zu(e.vueFiles),r=Ku(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),s=_u(et(Nu(),"scip-query-vue-workers-")),o=new SharedArrayBuffer(4),a=new Int32Array(o),l=qu(),c=Date.now();try{for(let d=0;d<r.length;d++)new wu(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[d],resultPath:et(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(gt(et(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{Iu(s,{recursive:!0,force:!0})}}function ji(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,vu().length-1));return Math.max(1,Math.min(e,n))}function qu(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function zu(e){let t=Gu(),n=[];for(let r of e){let i=Bi(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 Gu(){return Number.POSITIVE_INFINITY}function Ku(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Yu(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 Yu(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Bi(e.fileName)-e.startOffset)}function Bi(e){try{return Ru(e).size}catch{return 1}}function Qu(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 Xu(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=>Ai(t,r.relativePath))}function Zu(e,t){let{vueCore:n,ts:r,volarTs:i}=ed(e),{parsed:s,vueOptions:o}=td(n,r,t),a=Zn(t),l=n.createVueLanguagePlugin(r,s.options,o,f=>f),c=nd(n,r,l),u=rd(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 ed(e){let t=xu(Lu(et(e,"package.json")).href);return{vueCore:Xn(t,"@vue/language-core",e),ts:Xn(t,"typescript",e),volarTs:Xn(t,"@volar/typescript",e)}}function td(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,Zn(n),void 0,n,void 0,e.getAllExtensions(s).map(o=>({extension:o.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:s}}function nd(e,t,n){let r={},i=e.createLanguage([n],new Map,s=>{if(!Fi(s))return;let o=gt(s,"utf-8");r.current?.scripts.set(s,t.ScriptSnapshot.fromString(o),n.getLanguageId(s)??hd(s))});return r.current=i,i}function rd(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Xn(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=sd(e);return i=>{let s=ht(t,i.fileName),o=n(i.fileName);if(!o)return null;let a=Ui(o,i.textSpan.start),l=r.get(s);if(!l)return null;let c=l.containingByLine.get(a.line);return c!==void 0?c:od(l.starts,a.line,2)}}function sd(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 od(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 ad(e,t,n){let r=xd(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=ht(t,c),d=_d(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 ld(e,t,n,r,i){return e.transaction(()=>(Qu(e),cd(e,t,n,r),md(e,i)))()}function cd(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=ht(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 ud(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(Wi(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function dd(e){let t=new Set,n=[];for(let r of e){let i=Hi(r);t.has(i)||(t.add(i),n.push(r))}return n}function Hi(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function md(e,t){let n=Sd(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=Hi(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*pd(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 fd(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Wi(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Ui(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 gd(e,t){return ht(e,t).startsWith("node_modules/")}function ht(e,t){return Du(e,t).replaceAll("\\","/")}function hd(e){switch(Eu(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 yd(){let e=new Map;return t=>{if(e.has(t))return e.get(t)??null;try{let n=gt(t,"utf-8"),r={text:n,lineStarts:bd(n)};return e.set(t,r),r}catch{return e.set(t,null),null}}}function bd(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function Sd(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 xd(e){try{let t=JSON.parse(gt(et(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 _d(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}async function qi(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,s=wd(e),o=Date.now();Vi(We(s.outputScip),{recursive:!0}),Vi(We(s.outputDb),{recursive:!0});let a=e.languages??He(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=Zd(t,a,{pnpmWorkspaces:e.pnpmWorkspaces}),c=zd(se(We(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;Fd(i,r);let m=Pd(s);return u=m.runDir,await Od({opts:e,languages:a,projectRoot:t,paths:s,tempPaths:m,fingerprint:l,start:o,maxHeapMb:n,skipAutoInstall:i,onStatus:r})}finally{u&&nt(u,{recursive:!0,force:!0}),c()}}function wd(e){let t=e.outputScip??se(e.projectRoot,"index.scip"),n=e.outputDb??se(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:se(We(n),"meta.json")}}function kd(e){if(e.opts.skipIfUnchanged===!1||!Ue(e.paths.outputScip)||!Ue(e.paths.outputDb)||!em(e.paths.metaPath,e.fingerprint))return null;we({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 Pd(e){let t=vd(se(We(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:se(t,Xt(e.outputScip)),tempOutputDb:se(t,Xt(e.outputDb)),tempMetaPath:se(t,Xt(e.metaPath))}}async function Od(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:r}=await Md(e,t);Td(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 Md(e,t){let{preparedRuns:n,skippedLanguages:r}=Ad({languages:e.languages,tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,onStatus:e.onStatus}),i=await Yd(n,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),{indexedOutputs:s}=jd(i,r);return Bd(s,r,e.languages,e.opts.allowPartial,e.onStatus),{indexedOutputs:s,skippedLanguages:r}}function Td(e,t,n,r){Hd(n,e.tempPaths.tempOutputScip,e.onStatus),Wd(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),we({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),tm(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]}),Gd({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 Fd(e,t){if(!ft("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..."),!ai(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 Ad(e){let t=[],n=[],r=e.languages.map((i,s)=>({language:i,scipPath:e.languages.length>1?qd(e.tempOutputScip,i,s):e.tempOutputScip}));for(let{language:i,scipPath:s}of r){let o=$d({...e,language:i,scipPath:s});"skipped"in o?n.push(o.skipped):t.push(o.prepared)}return{preparedRuns:t,skippedLanguages:n}}function $d(e){let t=qt(e.language),n=Yt(t),r=Yn(t,e.projectRoot);if(!r&&!Di(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...`),!Pi(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??Ze(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:wi(t,e.env,i)}}}function jd(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 Bd(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 Hd(e,t,n){e.length>1?(n(`Merging ${e.length} language indexes...`),xi(e.map(r=>r.scipPath),t)):e[0].scipPath!==t&&tt(e[0].scipPath,t)}function Wd(e,t,n,r){if(r("Converting to SQLite..."),!Ue(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{let i=vi(e);i.removedDefinitionOccurrences>0&&r(`Sanitized ${i.removedDefinitionOccurrences} invalid definition occurrences across ${i.touchedDocuments} documents before SQLite conversion.`),Rd("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 Ud(e,t,n){if(!e.defaultOutputPath)return;let r=se(t,e.defaultOutputPath);n!==r&&Ue(r)&&tt(r,n)}function Vd(e,t,n){if(!e.defaultOutputPath)return null;let r=se(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return nt(i,{force:!0}),Ue(r)?(tt(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Jd(e){e&&(nt(e.defaultOutputPath,{force:!0}),e.backupPath&&Ue(e.backupPath)&&tt(e.backupPath,e.defaultOutputPath))}function qd(e,t,n){let r=Ld(e)||".scip",i=Xt(e,r);return se(We(e),`${i}.${n+1}.${t}${r}`)}function zd(e){let t;try{t=Nd(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 ${We(e)}.`,{cause:n}):n}return Ji(t,JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()})+`
|
|
131
|
-
`),()=>{try{Cd(t)}finally{nt(e,{force:!0})}}}function Gd(e){tr(e.tempOutputScip,e.outputScip),tr(e.tempOutputDb,e.outputDb),tr(e.tempMetaPath,e.metaPath)}function tr(e,t){nt(`${t}.tmp-replace`,{force:!0}),tt(e,`${t}.tmp-replace`),tt(`${t}.tmp-replace`,t)}function Kd(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,Dd().length-1));return Math.max(1,Math.min(e,Math.floor(r)))}async function Yd(e,t,n,r){let i=e.filter(c=>c.config.defaultOutputPath),s=e.filter(c=>!c.config.defaultOutputPath),o=[],a=Kd(s.length,r),l=await Xd(s,a,c=>nr(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 nr(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 nr(c,t,n));return o.sort((c,u)=>e.findIndex(d=>d.language===c.language)-e.findIndex(d=>d.language===u.language))}async function nr(e,t,n){n(`Indexing ${e.language} with ${e.resolvedBinary}...`),nt(e.scipPath,{force:!0});let r=Vd(e.config,t,e.scipPath);try{await Qd(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),Ud(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{Jd(r)}if(!Ue(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 Qd(e,t,n){return new Promise((r,i)=>{Id(e,[...t],n,s=>{s?i(s):r()})})}async function Xd(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 Zd(e,t,n){return{version:1,languages:[...t].sort(),pnpmWorkspaces:n.pnpmWorkspaces===!0,files:zt(e)}}function em(e,t){try{let n=JSON.parse(Ed(e,"utf-8"));return n.version===2&&n.status==="complete"&&Qt(n.fingerprint)===Qt(t)&&Qt([...n.indexedLanguages??[]].sort())===Qt(t.languages)}catch{return!1}}function tm(e,t){Ji(e,`${JSON.stringify(t,null,2)}
|
|
133
|
-
`)}function Qt(e){return JSON.stringify(e)}import{createRequire as am}from"module";import{existsSync as yt,readFileSync as nm,readdirSync as rm,statSync as im}from"fs";import $ from"path";var ir=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function sr(e,t){let r=t?$.dirname($.join(e,t)):e,i=$.resolve(e);for(;r.startsWith(i);){for(let o of ir){let a=$.join(r,o);if(yt(a))return a}let s=$.dirname(r);if(s===r)break;r=s}for(let s of ir){let o=$.join(e,s);if(yt(o))return o}return null}function zi(e){let t=e.config.projectRoot,n=new Set(or(t,e.config.semantic?.typescript?.tsconfigs)),r=e.all(`SELECT relative_path
|
|
2
|
+
import{program as gs}from"commander";import{realpathSync as pm}from"fs";import{fileURLToPath as TR}from"url";import{spawnSync as Dc}from"child_process";import{createRequire as AS}from"module";import{fileURLToPath as Nc}from"url";import{statSync as fm}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,...gm(e.config.dbPath)}}function gm(e){try{let t=fm(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
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
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=sr(t,i.relative_path);s&&n.add($.resolve(s))}if(n.size===0){let i=sr(t);i&&n.add($.resolve(i))}return[...n].filter(i=>!Gi(t,i)).sort((i,s)=>i.localeCompare(s))}function or(e,t=[]){let n=new Set;for(let r of t){let i=$.isAbsolute(r)?r:$.join(e,r);yt(i)&&n.add($.resolve(i))}for(let r of sm(e))for(let i of ir){let s=$.join(r,i);yt(s)&&n.add($.resolve(s))}if(n.size===0){let r=sr(e);r&&n.add($.resolve(r))}return[...n].filter(r=>!Gi(e,r)).sort((r,i)=>r.localeCompare(i))}function sm(e){let t=$.join(e,"package.json");if(!yt(t))return[];let n;try{n=JSON.parse(nm(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>om(e,i))}function om(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let o=$.join(e,t);return rr(o)?[o]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),s=$.join(e,r||".");return rr(s)?rm(s).map(o=>$.join(s,o,i)).filter(rr):[]}function rr(e){try{return im(e).isDirectory()}catch{return!1}}function Gi(e,t){let n=$.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}var lm=am(import.meta.url);function ar(e,t=[]){let n=cm(),r=or(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 cm(){try{return lm.resolve("ts-morph"),!0}catch{return!1}}import{watch as um}from"fs";import{existsSync as Ki,renameSync as Yi}from"fs";import{join as dm,relative as mm}from"path";import{fork as pm}from"child_process";import fm from"ignore";var Zt=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=ri(t.config),this.indexPaths=De(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=Xe(t.projectRoot),this.extraIgnore=fm(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"});try{let t=um(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=mm(this.projectRoot,dm(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=gm(this.indexPaths.indexPath),o=pm(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{Ki(i)&&Yi(i,this.indexPaths.dbPath),Ki(s)&&Yi(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 gm(e){return e.endsWith(".scip")?e.slice(0,-5)+".tmp.scip":e+".tmp.scip"}import{existsSync as lr,mkdirSync as hm,symlinkSync as ym,readlinkSync as bm,unlinkSync as Sm}from"fs";import{join as en,dirname as Qi,resolve as cr}from"path";import{homedir as Xi,platform as xm}from"os";import{fileURLToPath as _m}from"url";var Im=xm()==="win32",ur=["concrete-plan","scip-explore","scip-debloat","scip-verify","scip-language-playbook"];function Zi(e={}){let t=e.quiet?()=>{}:console.log,n=_m(import.meta.url),r=cr(Qi(n),"..","skills"),i=[en(Xi(),".claude","skills"),en(Xi(),".codex","skills")],s={installed:[],skipped:[],alreadyLinked:[]};for(let o of i){let a=Qi(o);if(!lr(a))continue;hm(o,{recursive:!0});let l=o.includes(".codex")?"Codex":"Claude";for(let c of ur){let u=en(r,c),d=en(o,c);if(!lr(u)){s.skipped.push(`${l}/${c}`);continue}if(lr(d)){try{let m=bm(d);if(cr(m)===cr(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}Sm(d)}ym(u,d,Im?"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 fe(e,t,n){return`${e}:${pe(t,n)}`}var b={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 Fl}from"fs";import{join as Ex}from"path";import Rm from"better-sqlite3";var tn=class{db;config;pathFilter;constructor(t,n){this.config=t,this.pathFilter=n??null,this.db=new Rm(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=>[`AND ${n}.relative_path NOT LIKE 'node_modules/%'`,`AND ${n}.relative_path NOT LIKE '.git/%'`]).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 S={};Jl(S,{HEALTH_PHASES:()=>ll,affected:()=>qa,bottlenecks:()=>Ca,byKind:()=>Na,callGraph:()=>Pa,changeSurface:()=>za,code:()=>El,complexity:()=>Ll,complexityHotspots:()=>Fn,convergence:()=>Cl,coupling:()=>xa,cycles:()=>Nn,dataflow:()=>wl,dead:()=>vn,deepChains:()=>wa,deps:()=>ta,diffImpact:()=>Ka,diffImpactPartial:()=>Vr,diffImpactPlan:()=>Ur,drift:()=>kn,extractCandidates:()=>Ln,fanIn:()=>ha,fanOut:()=>ya,files:()=>es,health:()=>cl,healthPhase:()=>ul,healthReportFromPhases:()=>ml,hierarchy:()=>ka,hotspots:()=>aa,importedBy:()=>ua,imports:()=>ca,isolated:()=>En,kindCounts:()=>Ea,members:()=>ga,mergeDiffImpactPartials:()=>Jr,methods:()=>Xo,outline:()=>fa,passthroughCandidates:()=>Mn,rdeps:()=>na,redundantReexports:()=>Pl,refs:()=>Zo,similar:()=>Ta,similarAll:()=>Dn,similarChains:()=>Va,similarFiles:()=>Wa,similarSignatures:()=>Ml,slice:()=>kl,staleAbstractions:()=>Tn,stats:()=>nn,surface:()=>ia,symbols:()=>vs,system:()=>ra,topCoupling:()=>_a,topFanIn:()=>ba,topFanOut:()=>Sa,trace:()=>ea,unusedImports:()=>da,wrapperCandidates:()=>On});import{statSync as Cm}from"fs";function nn(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=Cm(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function Nm(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function es(e,t){let n=Nm(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 as}from"path";import{createRequire as km}from"module";import{existsSync as Em,readFileSync as Dm}from"fs";import{join as Lm}from"path";var ts=A("source-text");function P(e,t){let n=t.replace(/\\/g,"/");return ts.get(e,n,()=>{let r=Lm(e.config.projectRoot,n);return Em(r)?Dm(r,"utf-8"):""})}function ns(e){ts.invalidateAll(e)}var wm=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale|wrapper|passthrough|drift|extract)?/i;function dr(e,t,n){if(n<=0)return!1;let r=P(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(wm.test(o))return!0;if(!o.startsWith("//")&&!o.startsWith("*")&&!o.startsWith("/*")&&!o.startsWith("@")&&!o.startsWith("#"))return!1}}return!1}var q=km(import.meta.url),rn=null,rs=!1;function ls(){if(rs)return null;if(rn)return rn;try{return rn=q("tree-sitter"),rn}catch{return rs=!0,null}}var Pm={".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"},is=new Map,mr=new Set;function cs(e){if(mr.has(e))return null;let t=is.get(e);if(t)return t;let n;try{switch(e){case"rust":n=q("tree-sitter-rust");break;case"typescript":n=q("tree-sitter-typescript").typescript;break;case"tsx":n=q("tree-sitter-typescript").tsx;break;case"javascript":n=q("tree-sitter-javascript");break;case"python":n=q("tree-sitter-python");break;case"java":n=q("tree-sitter-java");break;case"kotlin":n=q("tree-sitter-kotlin");break;case"scala":n=q("tree-sitter-scala");break;case"ruby":n=q("tree-sitter-ruby");break;case"c":n=q("tree-sitter-c");break;case"cpp":n=q("tree-sitter-cpp");break;case"csharp":n=q("tree-sitter-c-sharp");break;case"php":n=q("tree-sitter-php").php;break;case"vb":{let r=q("tree-sitter-vb-dotnet");n=r.language??r;break}}}catch{return mr.add(e),null}return is.set(e,n),n}var ss=new Map;function us(e){let t=ss.get(e);if(t)return t;let n=cs(e);if(!n)return null;let r=ls();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return mr.add(e),null}return ss.set(e,i),i}function T(e){return Pm[as(e).toLowerCase()]??null}function St(e){return as(e).toLowerCase()===".vue"}var pr=Vt("ast-trees");function ds(e){pr.invalidateAll(e)}function O(e,t){if(St(t))return Om(e,t);let n=T(t);if(!n)return null;let r=P(e,t);return r?pr.get(e,t,r,()=>{let i=us(n);if(!i)return null;try{return ms(i,r)}catch{return null}}):null}function Om(e,t){let n=P(e,t);return n?pr.get(e,t,n,()=>{let r=Mm(n);if(!r)return null;let i=us(r.language);if(!i)return null;let s=`
|
|
167
|
-
`.repeat(r.startLine)+r.body;try{return ms(i,s)}catch{return null}}):null}function ms(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function Mm(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=Tm(e,r.openIdx);return{body:r.body,startLine:a,language:o}}function Tm(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}var rt=new Map;function Fm(e,t){let n=`${e}::${t}`;if(rt.has(n))return rt.get(n)??null;let r=cs(e);if(!r)return rt.set(n,null),null;let i=ls();if(!i)return rt.set(n,null),null;try{let s=new i.Query(r,t);return rt.set(n,s),s}catch{return rt.set(n,null),null}}var Am={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(l=>a.toLowerCase().endsWith(l.toLowerCase()))):o;return t.includeIgnored===!1?s.filter(a=>!e.isIgnored(a)):s}function hm(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function Vr(e,t){let n=hm(t);return k(e,{like:n,includeIgnored:!1}).map(r=>({relativePath:r}))}import{extname as hs}from"path";var ym={".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 ym[hs(e).toLowerCase()]??null}function st(e){return hs(e).toLowerCase()===".vue"}var bm=new Set(["function_item","function_signature_item"]),Sm=new Set(["function_definition"]),xm=new Set(["function_declaration","method_definition","arrow_function","function_expression"]);function en(e){switch(e){case"rust":return bm;case"python":return Sm;default:return xm}}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),l=a.get(i);if(l&&l.source===o)return l.value;let c=s();return a.set(i,{source:o,value:c}),c},invalidate(r,i){t.get(r)?.delete(i)},invalidateAll(r){t.delete(r)}}}import{createRequire as Cm}from"module";var re=Cm(import.meta.url),$n=null,ys=!1;function xs(){if(ys)return null;if($n)return $n;try{return $n=re("tree-sitter"),$n}catch{return ys=!0,null}}var bs=new Map,Ur=new Set;function Cs(e){if(Ur.has(e))return null;let t=bs.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 Ur.add(e),null}return bs.set(e,n),n}var Ss=new Map;function Im(e){let t=Ss.get(e);if(t)return t;let n=Cs(e);if(!n)return null;let r=xs();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return Ur.add(e),null}return Ss.set(e,i),i}function Rm(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function Jr(e,t){let n=Im(e);if(!n)return null;try{return Rm(n,t)}catch{return null}}var vt=new Map;function Is(e,t){let n=`${e}::${t}`;if(vt.has(n))return vt.get(n)??null;let r=Cs(e);if(!r)return vt.set(n,null),null;let i=xs();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 _m,readFileSync as vm}from"fs";import{join as Dm}from"path";var zr=H("source-text");function T(e,t){let n=t.replace(/\\/g,"/");return zr.get(e,n,()=>{let r=Dm(e.config.projectRoot,n);return _m(r)?vm(r,"utf-8"):""})}function Rs(e){zr.invalidateAll(e)}function _s(e,t){zr.invalidate(e,t.replace(/\\/g,"/"))}var Nm=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale|wrapper|passthrough|drift|extract)?/i;function Gr(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(Nm.test(s))return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function vs(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:Lm(e,r.openIdx),language:s}}function Lm(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 Kr(e){jn.invalidateAll(e)}function Qr(e,t){jn.invalidate(e,t)}function B(e,t){if(st(t))return Em(e,t);let n=P(t);if(!n)return null;let r=T(e,t);return r?jn.get(e,t,r,()=>Jr(n,r)):null}function Em(e,t){let n=T(e,t);return n?jn.get(e,t,n,()=>{let r=vs(n);if(!r)return null;let i=`
|
|
10
|
+
`.repeat(r.startLine)+r.body;return Jr(r.language,i)}):null}var wm={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
|
-
`}
|
|
36
|
+
`},km=new WeakMap;function Yr(e,t){return Zr(e,t,km,wm,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 Pm={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
|
-
`},
|
|
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
|
+
`},Tm=new WeakMap;function Nt(e,t){return Zr(e,t,Tm,Pm,n=>{let r=[];for(let i of n){let o=null,s=null;for(let l of i.captures)l.name==="target"?o=l.node:l.name==="call"&&(s=l.node);if(!o||!s)continue;let a=Dt(o);a&&r.push({calleeLeaf:a,memberAccess:Mm(o),line:s.startPosition.row})}return r})}function Mm(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}var Om=new WeakMap;function Xr(e,t){return tn(e,t,Om,()=>new Map,(n,r,i)=>{let o=(l,c)=>{if(l===c)return;let u=i.get(l);u||(u=new Set,i.set(l,u)),u.add(c)},s=r==="python"?new Set(["identifier"]):new Set(["type_identifier"]),a=(l,c)=>{let u=m=>{s.has(m.type)&&m.text!==c&&o(m.text,c);for(let d of m.children)u(d)};for(let m of l.children)u(m)};if(r==="rust")for(let l of n.rootNode.descendantsOfType(["struct_item","enum_item","union_item","type_item"])){let c=l.namedChildren.find(m=>m.type==="type_identifier")?.text;if(!c)continue;let u=l.namedChildren.find(m=>m.type==="field_declaration_list"||m.type==="enum_variant_list"||m.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(m=>m.type==="identifier")?.text;if(!c)continue;let u=l.namedChildren.find(m=>m.type==="block");if(u)for(let m of u.descendantsOfType("type"))for(let d of m.descendantsOfType("identifier"))d.text!==c&&o(d.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 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 l=r();return i(s,o,l),n.set(s,l),l}function Zr(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 l=n.get(a);if(l)return l;let c=Is(o,s);if(!c)return null;let u=i(c.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 Fm={"/":"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 c=i.indexOf("`",1);c===-1?(o=i.slice(1),i=""):(o=i.slice(1,c),i=i.slice(c+2))}else{let c=i.indexOf(" ");c===-1?(o=i,i=""):(o=i.slice(0,c),i=i.slice(c+1))}let s,a=i.indexOf(" ");a===-1?(s=i,i=""):(s=i.slice(0,a),i=i.slice(a+1));let l=Am(i);return{scheme:n,manager:r,packageName:o,version:s,descriptors:l,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 Am(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||Ds(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&&!Ds(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=Fm[i];o&&t.push({name:r,suffix:o}),n+=1}}return t}function Ds(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=$m(i);o&&r.push(o)}return r.join(":")}function $m(e){let t=e.suffix==="namespace"?jm(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function jm(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 qe(e){return ee(e)==="namespace"}var Bm=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function Bn(e){return Bm.test(e)}var Hm=new Set(["test","tests","_tests"]);function Ve(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&&Hm.has(r.name))return!0}return!1}function Ns(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],l=o[s];if(a.name!==l.name||a.suffix!==l.suffix)return!1}return!0}function Ls(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],l=o[s];if(a.name!==l.name||a.suffix!==l.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
|
|
222
|
-
${e.
|
|
223
|
-
|
|
224
|
-
|
|
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 Zm(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:w(e.symbol),parentTypeName:ze(e.symbol),isFunctionLike:H(e.symbol),isTypeLike:U(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function ep(e,t){let n=new Map;for(let r of t)e.length>0&&!tp(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 tp(e){if(ze(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 oe(e,t={}){return fr(e,t.scope)}function fr(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=>z(e,r.relative_path)).filter(r=>!e.isIgnored(r.relativePath))}function it(e,t,n={}){if(t.length===0)return[];let r=t.flatMap(i=>z(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:g(i.symbol),signature:Ve(Je(i.documentation)),relativePath:i.relativePath,enclosingSymbol:i.enclosingSymbol}))}function ae(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 qe(e,t){let n=z(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 np(e,t,n){let r=P(e,t),i=ps(e,t);return i?lp(n,i,r):r?rp(n,r):n}function rp(e,t){let n=t.split(/\r?\n/),r=ip(e,n),i=sp(e,r),s=op(i,n);return ap(e,s)}function ip(e,t){let n=e.some(i=>ln(i.symbol))?up(t):null,r=new Map;for(let i of e)r.set(i.symbolId,cp(t,n,i));return r}function sp(e,t){return e.filter(n=>ln(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 op(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:dp(t,i.definition,i.startLine,o)})}return n}function ap(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function lp(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(!ln(i.symbol)||!i.leaf)return _s(i,n);let s=r.get(i.leaf);if(!s||s.length===0)return _s(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 _s(e,t){if(!t||!e.leaf||U(e.symbol)!=="term"||ze(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 cp(e,t,n){if(!ln(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 up(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 dp(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=mp(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 mp(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 ln(e){return e.includes("().")}function ze(e){let t=W(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 gr(e){let t=W(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 Ep}from"fs";import{basename as Is,isAbsolute as Dp,join as Lp}from"path";function L(e,t){let n=ot(e,t.trim());if(n)return n;let r=bp(e,t);if(r)return r;let i=pp(e,t);return i||yp(e,t)}function pp(e,t){let n=br(t),r=yr(n);if(!r)return null;let i=`%${r.path}%`,s=r.leaf,a=fp(e,i,s,n)[0];return a?qe(e,a):null}function fp(e,t,n,r){let i=hr([],[...gp(e,t,n),...hp(e,t,n)]).filter(s=>!e.isIgnored(s.relative_path)).filter(s=>st(s,r)>1);return i.sort((s,o)=>st(o,r)-st(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 gp(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 hp(e,t,n){return e.all(`SELECT
|
|
54
|
+
WHERE ${t.where}
|
|
55
|
+
${e.pathExclusionsFor("d")}
|
|
56
|
+
${ws(t.orderBy)}
|
|
57
|
+
${ks(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
|
|
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 yp(e,t){let n=br(t),r=vp(t),i=Ip(e,r),s=Np(i,t,n);if(s&&!e.isIgnored(s.relative_path))return qe(e,s);let o=null;for(let a of i){if(e.isIgnored(a.relative_path))continue;let l=Cp(a,t,n,r);l<=0||(!o||l>o.score)&&(o={row:a,score:l})}return o?qe(e,o.row):null}function bp(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=Sp(e,r,o,a)??xp(e,r,o,a);return l&&!e.isIgnored(l.relative_path)?qe(e,l):null}function Sp(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 xp(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 >= ?
|
|
286
|
-
${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 ot(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
|
|
71
|
+
AND ${t.where}
|
|
309
72
|
${e.pathExclusionsFor("d")}
|
|
310
|
-
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
311
|
-
|
|
312
|
-
LIMIT
|
|
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
|
+
${ws(t.orderBy)}
|
|
75
|
+
${ks(t.limit)}`,...t.params??[])}function ws(e){return e?`ORDER BY ${e}`:""}function ks(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 lt(e){if(!e)return null;let t=Es(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(Es(r)??r).replace(/\n/g," ")}function Es(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function Wm(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&&!Wm(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 Ts=H("file-definitions");function Ms(e,t){Ts.invalidate(e,t)}function q(e,t){return Ts.get(e,t,()=>{let n=wt(qm(e,t),Vm(e,t),{sort:!0});return Jm(e,t,n.map(Um))})}function qm(e,t){return e.all(`SELECT
|
|
318
76
|
gs.id,
|
|
319
77
|
gs.symbol,
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
78
|
+
der.document_id,
|
|
79
|
+
der.start_line,
|
|
80
|
+
der.end_line,
|
|
323
81
|
d.relative_path,
|
|
324
82
|
gs.display_name,
|
|
325
|
-
gs.
|
|
326
|
-
|
|
327
|
-
|
|
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 hr(n,r)}function Ip(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
|
|
339
|
-
|
|
340
|
-
|
|
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 Vm(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.
|
|
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
|
|
355
|
-
AND
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
FROM documents
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
ORDER BY relative_path`).filter(l=>!e.isIgnored(l.relative_path)).map(l=>({relativePath:l.relative_path,score:kp(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=L(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 kp(e,t){let n=Cs(e),r=Is(n),i=Is(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 Cs(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}function vs(e,t){let n=Oe(e,t);return it(e,n).map(({relativePath:r,...i})=>i)}import{basename as Bh}from"path";var xt=new WeakMap;function Ds(e,t){let n=T(t);return n==="rust"?Fp(e,t):n==="typescript"||n==="tsx"||n==="javascript"?Op(e,t):[]}var Pp=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]);function Op(e,t){let n=O(e,t);if(!n)return[];let r=xt.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&&Pp.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(...Ls(n,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),xt.set(n,l),l}var Mp=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function Tp(e){return Mp.test(e)}function Ls(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(Tp(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 Fp(e,t){let n=O(e,t);if(!n)return[];let r=xt.get(n);if(r)return r;let i=[],s=Ap(n);return s?(xt.set(n,s),s):(ws(n.rootNode,i,!1,!1),i.push(...Ls(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(...Up(n.rootNode)),xt.set(n,i),i)}function Ap(e){return Vp(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function ws(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"?$p(e,t,n,r):r&&Wp(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"?jp(e,t,n):e.type==="mod_item"&&Sr(e).some(o=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(o))&&(i=!0);for(let o of e.namedChildren)ws(o,t,i,s)}function $p(e,t,n,r){let i=Sr(e),s=null;r?s="trait impl method (dynamic dispatch)":n&&(s="inside #[cfg(test)] mod");for(let o of i){let a=Bp(o);if(a){s=a;break}if(ks(o)){s="#[allow(dead_code)]";break}}s&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:s})}function jp(e,t,n){let r=Sr(e),i=e.namedChildren.find(s=>s.type==="type_identifier")?.text;r.some(Hp)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:i}),r.some(ks)&&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 Sr(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 Bp(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 Hp(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 ks(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function Wp(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function Up(e){let t=Kp(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 Vp(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 Jp=[{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}],Ps=/^#!?\[\s*serde\s*\(/,qp=/^#!?\[\s*schemars\s*\(/,zp=/^#!?\[\s*validate\s*\(/,Ns=/\bwith\s*=\s*"([^"]+)"/g;function at(e,t){return on(e,t,Gp,()=>new Set,(n,r,i)=>{if(r==="rust"){for(let s of n.rootNode.descendantsOfType("attribute_item"))Es(s.text,i);for(let s of n.rootNode.descendantsOfType("inner_attribute_item"))Es(s.text,i)}})??new Set}var Gp=new WeakMap;function Es(e,t){let n=Ps.test(e),r=qp.test(e),i=zp.test(e);if(!(!n&&!r&&!i))for(let{re:s}of Jp){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 Kp(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!Ps.test(n.text))continue;Ns.lastIndex=0;let r;for(;(r=Ns.exec(n.text))!==null;){let i=r[1],s=i.split("::").pop()??i;s&&t.add(s)}}return t}var Yp=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function Os(e,t){return on(e,t,Qp,()=>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=bt(o);if(!a||!Yp.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 Qp=new WeakMap;function dn(e){return e.replace(/'''[\s\S]*?'''/g,Me).replace(/"""[\s\S]*?"""/g,Me).replace(/#.*$/gm,Me).replace(/\/\/.*$/gm,Me).replace(/\/\*[\s\S]*?\*\//g,Me).replace(/`(?:\\[\s\S]|[^`])*`/g,Me).replace(/'(?:\\.|[^'\\\r\n])*'/g,Me).replace(/"(?:\\.|[^"\\\r\n])*"/g,Me)}function Me(e){return e.replace(/[^\r\n]/g," ")}var Ms=Vt("stripped-lines");function Ts(e,t,n){return Ms.get(e,t,n,()=>dn(n).split(`
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
${e.pathExclusionsFor("documents")}`).map(t=>ge(t.relative_path)).filter(t=>!e.isIgnored(t))))}function ge(e){return e.replace(/\\/g,"/")}var Nf=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function X(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 ne(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function B(e,t){let n=new Set,r=(i,s)=>{let o=s||t.has(i.type);!o&&Nf.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??j(e,r,vr(t)),kind:"named",used:Y(n,s),usedMembers:[]}}function re(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=Te(e,i.index,i.index+s.length);for(let a of n(i,o))r.push(a)}return r}function to(e,t,n){let r=O(e,t);return r?Ef(e,t,r):jf(n).flatMap(i=>Bf(e,t,i.clause,i.specifier,i.start,i.end,n))}function Ef(e,t,n){let r=Df(e,t,n),i=[];for(let s of n.rootNode.descendantsOfType("import_statement"))i.push(...Lf(e,t,n,s,r));return i}function Df(e,t,n){let r=B(n,new Set(["import_statement"]));if(St(t))for(let i of Xf(e,t))r.add(i);return r}function Lf(e,t,n,r,i){let s=Tf(r);if(!s)return[];let o=he(e,t,s),a=ne(r,"import_clause");return a?wf(n,a,o,i,Ff(r.text)):[kf(o)]}function wf(e,t,n,r,i){let s=[];for(let o of t.namedChildren)if(o.type==="identifier")s.push(Pf(o.text,n,r,i));else if(o.type==="namespace_import"){let a=Of(e,o,n,r,i);a&&s.push(a)}else o.type==="named_imports"&&s.push(...Mf(o,n,r,i));return s}function kf(e){return{importedName:"*",localName:null,sourcePath:e,kind:"side-effect",used:!0,usedMembers:[]}}function Pf(e,t,n,r){return{importedName:"default",localName:e,sourcePath:t,kind:"default",used:n.has(e),usedMembers:[],isTypeOnly:r}}function Of(e,t,n,r,i){let o=ne(t,"identifier")?.text??"";if(!o)return null;let a=$f(e,o);return{importedName:"*",localName:o,sourcePath:n,kind:"namespace",used:a.length>0||r.has(o),usedMembers:a,isTypeOnly:i}}function Mf(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||Af(s.text)})}return i}function Tf(e){let t=ne(e,"string");if(!t)return null;let n=ne(t,"string_fragment");return n?n.text:null}function Ff(e){return/^\s*import\s+type\b/.test(e)}function Af(e){return/^\s*type\b/.test(e.trim())}function $f(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 jf(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 Bf(e,t,n,r,i,s,o){let a=he(e,t,r),l=Te(o,i,s);return n?Hf(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=lt(l,u.localName);return{...u,used:d.length>0||Y(l,u.localName),usedMembers:d}}return u.kind==="side-effect"?{...u,used:!0,usedMembers:[]}:{...u,used:u.localName?Y(l,u.localName):!1,usedMembers:[]}}):[{importedName:"*",localName:null,sourcePath:a,kind:"side-effect",used:!0,usedMembers:[]}]}function Hf(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,s]=Wf(r),o=[];return i&&o.push(...eo(i,n)),s&&o.push(...eo(s,n)),o}function eo(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?X(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 Wf(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 no(e,t){let n=O(e,t);if(n)return Gf(e,t,n);let r=P(e,t);return r?Uf(e,t,r):[]}function Uf(e,t,n){return[...Vf(e,t,n),...Jf(e,t,n),...qf(e,t,n)]}function Vf(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=X(o).map(d=>zf(d.trim())).filter(d=>!!d),c=dt(n,s.index),u=dt(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 Jf(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=dt(n,s.index),l=dt(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 qf(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=dt(n,s.index),l=dt(n,s.index+s[0].length-1);r.push({kind:"star",sourcePath:he(e,t,o),names:[],startLine:a,endLine:l})}return r}function zf(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 dt(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Gf(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let s=Kf(e,t,i);if(s===void 0)continue;let o=i.startPosition.row,a=i.endPosition.row,l=Yf(i,s,o,a);r.push(l)}return r}function Kf(e,t,n){let r=ne(n,"string");if(!r)return;let i=ne(r,"string_fragment");if(i)return he(e,t,i.text)}function Yf(e,t,n,r){let i=ne(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 ne(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}var Qf=A("vue-non-script-identifiers");function Xf(e,t){return Qf.get(e,t,()=>{let n=new Set,r=P(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 ro}from"path";function io(e,t,n){let r=O(e,t);return r?Zf(e,t,r):re(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(i,s)=>{let o=i[1]?.trim();if(!o)return[];let a=ro(o).replace(/\.[^.]+$/,"");return[{importedName:o,localName:a,sourcePath:hn(e,t,o),kind:"named",used:Y(s,a),usedMembers:[]}]})}function Zf(e,t,n){let r=B(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=ro(o).replace(/\.[^.]+$/,"");i.push({importedName:o,localName:a,sourcePath:hn(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=Te(n,i.index,i.index+a.length);r.push({importedName:s,localName:o,sourcePath:yn(e,t,s),kind:o?"namespace":"side-effect",used:o?Y(l,o):!0,usedMembers:o?lt(l,o):[]})}return r}function oo(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:yn(e,t,s)})}return r}function ao(e,t,n){let r=O(e,t),i=T(t);if(r&&i==="csharp")return tg(e,t,r);if(r&&i==="vb")return eg(e,t,r);let s=Zs(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return re(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,j(e,m,ct))]})}function eg(e,t,n){let r=B(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:j(e,c,ct),kind:l?"namespace":"named",used:r.has(d),usedMembers:[]})}return i}function tg(e,t,n){let r=B(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:j(e,c,ct),kind:a?"namespace":"named",used:r.has(d),usedMembers:[]})}return i}function lo(e,t,n){let r=O(e,t),i=T(t);return r&&i==="java"?ng(e,t,r):r&&i==="kotlin"?rg(e,t,r):r&&i==="scala"?ig(e,t,r):re(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(s,o)=>{let a=s[1]?.trim();return a?sg(e,t,a,o):[]})}function ng(e,t,n){let r=B(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:j(e,c,ce),kind:"namespace",used:!0,usedMembers:[]});continue}let u=c.split(".").pop()??c;i.push({importedName:u,localName:u,sourcePath:j(e,c,ce),kind:"named",used:r.has(u),usedMembers:[]})}return i}function rg(e,t,n){let r=B(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:j(e,o.text,ce),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:j(e,c,ce),kind:"named",used:r.has(m),usedMembers:[]})}return i}function ig(e,t,n){let r=B(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:j(e,l,ce),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:j(e,`${l}.${h}`,ce),kind:"named",used:r.has(p),usedMembers:[]})}else if(d.type==="identifier"){let m=d.text;i.push({importedName:m,localName:m,sourcePath:j(e,`${l}.${m}`,ce),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:j(e,u&&a.length>1?`${u}.${c}`:l,ce),kind:"named",used:r.has(c),usedMembers:[]})}return i}function sg(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 X(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 uo(e,t,n){let r=O(e,t);return r?og(e,t,r):re(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,s)=>{let o=i[1]?.trim();return o?X(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,j(e,d.replace(/\\/g,"."),Rt))]}):[]})}function og(e,t,n){let r=B(n,new Set(["namespace_use_declaration"])),i=[],s=(o,a,l)=>{i.push({importedName:a,localName:l,sourcePath:j(e,o.replace(/\\/g,"."),Rt),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}=co(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}=co(l,"");c&&s(d,c,u)}}return i}function co(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 fo(e,t,n){let r=O(e,t);return r?ag(e,t,r):cg(n).flatMap(i=>dg(e,t,i,n))}function ag(e,t,n){let r=B(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=mo(o);if(!a)continue;let l=ut(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=lg(o);if(a===null)continue;let l=ut(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=mo(u);d&&i.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:l,kind:"named",used:r.has(d.localName),usedMembers:[]})}}return i}function mo(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 lg(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=ne(e,"import_prefix")?.text??"",n=ne(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function cg(e){let t=e.split(`
|
|
368
|
-
|
|
369
|
-
${m}`,c+=1+m.length,u+=po(m),r+=m.length+1}let d=ug(l);d&&n.push({...d,start:a,end:c})}return n}function ug(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 dg(e,t,n,r){let i=Te(r,n.start,n.end),s=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return X(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=ut(e,t,m),p=lt(i,f);return[{importedName:m,localName:f,sourcePath:h,kind:"namespace",used:Y(i,f)||p.length>0,usedMembers:p}]});let o=n.module?ut(e,t,n.module):null,a=[];for(let l of X(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:Y(i,m),usedMembers:[]})}return a}function po(e){let t=0;for(let n of e)n==="("&&t++,n===")"&&t--;return t}import{basename as mg}from"path";function go(e,t,n){let r=O(e,t);return r?pg(e,t,r):re(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"?gn(e,t,a):null;if(l){let c=ho(a);return[{importedName:c,localName:c,sourcePath:l,kind:"named",used:Y(s,c),usedMembers:[]}]}return[{importedName:a,localName:null,sourcePath:l,kind:"side-effect",used:!0,usedMembers:[]}]})}function pg(e,t,n){let r=B(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"?gn(e,t,d):null;if(m){let f=ho(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 ho(e){return mg(e).replace(/\.[^.]+$/,"").split("_").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function yo(e,t,n){let r=O(e,t);return r?fg(e,t,r):re(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(i,s)=>{let o=i[1]?.trim();return o?gg(e,t,o,s):[]})}function fg(e,t,n){let r=B(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 vt(o,"")){if(!a.importedName||a.importedName==="*")continue;let l=Ie(e,t,a.qualifiedName)??Ie(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 vt(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":{let n=e.text;return[{qualifiedName:bn(t,n),importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,r=n.split("::").pop()??n;return[{qualifiedName:bn(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=bn(t,n.text),s=[];for(let o of r.namedChildren)s.push(...vt(o,i));return s}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(...vt(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=vt(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:bn(t,`${r}::*`),importedName:"*",localName:"*"}]}default:return[]}}function bn(e,t){return e?t?`${e}::${t}`:e:t}function gg(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 X(d).flatMap(m=>{let f=m.trim();if(!f||f==="self")return[];let[h,p]=f.split(/\s+as\s+/),y=h?.trim();if(!y)return[];let _=(p??y.split("::").pop()??y).trim(),E=`${u}::${y}`.replace(/::::/g,"::");return[ye(e,t,r,E,y.split("::").pop()??y,_,Ie(e,t,u))]})}let[s,o]=i.split(/\s+as\s+/),a=s?.trim()??i,l=(o??a.split("::").pop()??a).trim(),c=Ie(e,t,a)??Ie(e,t,a.split("::").slice(0,-1).join("::"));return[ye(e,t,r,a,a.split("::").pop()??a,l,c)]}function bo(e,t,n){let r=O(e,t);if(r)return hg(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(...bg(e,t,o))}return i}function hg(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!yg(i))continue;let s=i.namedChildren.find(o=>o.type!=="visibility_modifier");if(s)for(let o of vt(s,""))o.importedName&&r.push(Er(e,t,o.qualifiedName))}return r}function yg(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function bg(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 X(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[Er(e,t,c)]})}return[Er(e,t,r)]}function Er(e,t,n){return{specifier:n,sourcePath:Ie(e,t,n)??Ie(e,t,n.split("::").slice(0,-1).join("::"))}}function So(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 Sg={language:"javascript",extensions:[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],parseImports:to},xg={language:"python",extensions:[".py",".pyi"],parseImports:fo},_g={language:"jvm",extensions:[".java",".scala",".kt",".kts"],parseImports:lo},Ig={language:"rust",extensions:[".rs"],parseImports:yo,parseExports:bo},Rg={language:"ruby",extensions:[".rb"],parseImports:go},Cg={language:"c/cpp",extensions:[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],parseImports:io},vg={language:"dotnet",extensions:[".cs",".vb"],parseImports:ao},Ng={language:"dart",extensions:[".dart"],parseImports:so,parseExports:oo},Eg={language:"php",extensions:[".php"],parseImports:uo},Dg=[Sg,xg,_g,Ig,Rg,Cg,vg,Ng,Eg];function Dr(e){return So(Dg,e)}function xo(e,t){return no(e,t)}var _o=A("source-imports"),Io=A("source-exports");function J(e,t){let n=ge(t);return _o.get(e,n,()=>{let r=Dr(n);if(!r)return[];let i=P(e,n);return i?r.parseImports(e,n,i):[]})}function Lr(e,t){let n=ge(t);return Io.get(e,n,()=>{let r=Dr(n);if(!r?.parseExports)return[];let i=P(e,n);return i?r.parseExports(e,n,i):[]})}function Ro(e){_o.invalidateAll(e),Io.invalidateAll(e)}import ue from"path";import{createRequire as Lg}from"module";import{existsSync as Sn,readdirSync as wg,readFileSync as Eo}from"fs";var kg=Lg(import.meta.url),Nt;function Do(e,t){let n=Pg();if(!n)return wr("ts-morph is not installed");let r=zi(e);if(r.length===0)return wr("no tsconfig found");try{let i=r.map(s=>({tsconfigPath:s,project:new n.Project({tsConfigFilePath:s,skipFileDependencyResolution:!1})}));return new kr(e,n,i)}catch(i){return wr(i instanceof Error?i.message:String(i),r[0],r)}}function Pg(){if(Nt!==void 0)return Nt;try{Nt=kg("ts-morph")}catch{Nt=null}return Nt}function wr(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}var kr=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Ag(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 Re(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 Re(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t),r=this.packageImportReferencesForDefinition(t);return n?Vg(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(o=>{let a=o.getDeclarations()[0],l=a?o.getTypeAtLocation(a).getText(a):o.getValueDeclaration()?.getType().getText()??"unknown";return No(l)}),s=r.getReturnType().getText(n);return`(${i.join(",")})=>${No(s)}`})}importUsageForDeclaration(t,n){let r=he(this.db,t,n.getModuleSpecifierValue()),i=Co(n);return n.getImportClause()?.isTypeOnly()?i.map(s=>Tg(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 Jg(c,t,r.identifier,this.db.config.projectRoot))s.push(u);let o=s.some(c=>!vo(c.node)),a=s.some(c=>vo(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 Zg(t)?Re(this.sourceFileCache,t,()=>{let n=ue.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,Pr(i));return this.packageImportReferenceIndex=t,t}indexedTypeScriptLikeDocuments(){return this.db.all(`SELECT relative_path
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
)
|
|
381
|
-
|
|
382
|
-
|
|
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 Um(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 ei(e,t.scope)}function ei(e,t){return k(e,{scope:t,includeIgnored:!1}).flatMap(n=>q(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function kt(e,t,n={}){if(t.length===0)return[];let r=t.flatMap(i=>q(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(lt(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 ct(e,t){let n=q(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 Jm(e,t,n){let r=T(e,t),i=Yr(e,t);return i?Xm(n,i,r):r?zm(n,r):n}function zm(e,t){let n=t.split(/\r?\n/),r=Gm(e,n),i=Km(e,r),o=Qm(i,n);return Ym(e,o)}function Gm(e,t){let n=e.some(i=>Hn(i.symbol))?ed(t):null,r=new Map;for(let i of e)r.set(i.symbolId,Zm(t,n,i));return r}function Km(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 Qm(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:td(t,i.definition,i.startLine,s)})}return n}function Ym(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function Xm(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 Ps(i,n);let o=r.get(i.leaf);if(!o||o.length===0)return Ps(i,n);let s=o[0],a=Math.abs(s.startLine-i.startLine);for(let l=1;l<o.length;l+=1){let c=o[l],u=Math.abs(c.startLine-i.startLine);u<a&&(s=c,a=u)}return{...i,startLine:s.startLine,endLine:s.endLine}})}function Ps(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 Zm(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 ed(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,l)=>{let c=o.get(a);if(!c){o.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]&&s(u[1],a);for(let u of l.matchAll(n))u[1]&&s(u[1],a);let c=l.match(r);c?.[1]&&s(c[1],a);for(let u of l.matchAll(i))u[1]&&s(u[1],a)}return o}function td(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,l=!1;for(let c=n;c<=i;c+=1){let u=nd(e[c]??"");for(let m of u)m==="{"?(s+=1,l=!0):m==="}"?s=Math.max(0,s-1):m==="("?a+=1:m===")"&&(a=Math.max(0,a-1));if(l&&s===0||!l&&a===0&&c>=o)return c}return o}function nd(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 hd}from"fs";import{basename as Os,isAbsolute as yd,join as bd}from"path";function w(e,t){let n=Tt(e,t.trim());if(n)return n;let r=ld(e,t);if(r)return r;let i=rd(e,t);return i||ad(e,t)}function rd(e,t){let n=ni(t),r=ti(n);if(!r)return null;let i=`%${r.path}%`,o=r.leaf,a=id(e,i,o,n)[0];return a?ct(e,a):null}function id(e,t,n,r){let i=wt([],[...od(e,t,n),...sd(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 od(e,t,n){return Lt(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function sd(e,t,n){return Et(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function ad(e,t){let n=ni(t),r=fd(t),i=dd(e,r),o=gd(i,t,n);if(o&&!e.isIgnored(o.relative_path))return ct(e,o);let s=null;for(let a of i){if(e.isIgnored(a.relative_path))continue;let l=pd(a,t,n,r);l<=0||(!s||l>s.score)&&(s={row:a,score:l})}return s?ct(e,s.row):null}function ld(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),l=cd(e,r,s,a)??ud(e,r,s,a);return l&&!e.isIgnored(l.relative_path)?ct(e,l):null}function cd(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 ud(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:ct(e,r)}function qn(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=md(e,t.symbolId)[0];return n?ct(e,n):null}function md(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 dd(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 l=`%${a}%`;return[l,l,l]}),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 pd(e,t,n,r){let i=t.trim(),o=n,s=o.replace(/\(\)$/,""),a=t.toLowerCase(),l=n.toLowerCase(),c=l.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=ti(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===l)&&(_+=1e3),(f===a||f===l)&&(_+=950),(x===a||x===l)&&(_+=925),(x.endsWith(`/${l}`)||x.endsWith(`/${a}`))&&(_+=875),E===c&&(_+=850),b===c&&(_+=825),(`${b}()`===a||`${b}()`===l)&&(_+=820),(f.endsWith(`:${l}`)||f.endsWith(`:${c}`)||f.endsWith(`:${c}()`))&&(_+=800),y.includes(l)&&(_+=120),f.includes(l)&&(_+=140),x.includes(l)&&(_+=140),E.includes(l)&&(_+=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===c&&(_+=60),!$&&qe(e.symbol)&&(_-=160),_-=Math.min(50,Math.max(0,e.end_line-e.start_line)),_}function ti(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 ni(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function fd(e){let t=ni(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 gd(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=ti(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=Fs(e,t,{allowMultiple:!1})[0]?.relativePath;return n||Sd(e,t)}function Ue(e,t){return Fs(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function Sd(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=yd(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=bd(e.config.projectRoot,r);return hd(i)?r:null}function Fs(e,t,n){let r=As(t);if(!r)return[];let i=k(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:xd(a,r)})).filter(a=>a.score>0).sort((a,l)=>l.score-a.score||a.relativePath.localeCompare(l.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 xd(e,t){let n=As(e),r=Os(n),i=Os(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 As(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}function ri(e,t){let n=Ue(e,t);return kt(e,n).map(({relativePath:r,...i})=>i)}import{basename as kg}from"path";import{existsSync as Vn}from"fs";import{basename as Cd,dirname as Je,extname as Me,join as Ce,relative as nn,resolve as pe}from"path";var Id=We("indexed-paths"),ut=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],Un=[".py",".pyi"],le=[".java",".scala",".kt",".kts"],Jn=[".rs"],zn=[".rb"],Gn=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],ze=[".cs",".vb"],Kn=[".dart"],mt=[".php"],Rd=new Set(ut),ii=new Set(Un),$s=new Set(le),oi=new Set(Jn),si=new Set(zn),js=new Set(Gn),Bs=new Set(ze),ai=new Set(Kn),Hs=new Set(mt),_d=[{extensions:ut,lookup:Rd},{extensions:Un,lookup:ii},{extensions:le,lookup:$s},{extensions:Jn,lookup:oi},{extensions:zn,lookup:si},{extensions:Gn,lookup:js},{extensions:ze,lookup:Bs},{extensions:Kn,lookup:ai},{extensions:mt,lookup:Hs}];function Ge(e,t){return t.has(Me(e).toLowerCase())}function vd(e){return Ge(e,ii)}function Dd(e){return Ge(e,$s)}function Nd(e){return Ge(e,oi)}function Ld(e){return Ge(e,si)}function Ed(e){return Ge(e,js)}function wd(e){return Ge(e,Bs)}function Ws(e){return Me(e).toLowerCase()===".vb"}function kd(e){return Ge(e,ai)}function Pd(e){return Ge(e,Hs)}function li(e){let t=Me(e).toLowerCase();for(let n of _d)if(n.lookup.has(t))return n.extensions;return ut}function Td(e){return Dd(e)||wd(e)||Pd(e)}function Ie(e,t,n){return vd(t)?Mt(e,t,n):Nd(t)?Oe(e,t,n):Ld(t)?Qn(e,t,n):Ed(t)?Yn(e,t,n):Td(t)?V(e,n.replace(/\\/g,"."),li(t)):kd(t)?Xn(e,t,n):Md(e,t,n)}function Md(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 jd(i)){let a=fe(nn(e.config.projectRoot,s));if(o.has(a)||Vn(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(/^\./,""),l=Je(Ce(e.config.projectRoot,t));for(let c=1;c<s;c++)l=Je(l);i=a?pe(l,a.replace(/\./g,"/")):l}else i=pe(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of Od(i)){let s=fe(nn(e.config.projectRoot,o));if(r.has(s)||Vn(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,"/")),ci(e,Fd(o))}function Qn(e,t,n){let r=Je(Ce(e.config.projectRoot,t)),i=pe(r,n);return ci(e,Ad(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 ci(e,i)}function V(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 l of n){let c=`${o}${l}`,u=[...r].find(m=>m.endsWith(c));if(u)return u}for(let l of n){let c=[...r].find(u=>Cd(u)===`${s}${l}`);if(c)return c}let a=[...r].filter(l=>n.includes(Me(l).toLowerCase())).filter(l=>l.includes(`/${o}/`)||l.includes(`/${s}/`)).sort((l,c)=>l.localeCompare(c));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 l=s.slice(a+1),c=fe(l.startsWith("lib/")?l:`lib/${l}`);return r.has(c)?c:null}let i=Je(Ce(e.config.projectRoot,t)),o=pe(i,n);for(let s of $d(o)){let a=fe(nn(e.config.projectRoot,s));if(r.has(a)||Vn(s))return a}return null}function Od(e){let t=Me(e);return ii.has(t)?[e]:[`${e}.py`,`${e}.pyi`,Ce(e,"__init__.py"),Ce(e,"__init__.pyi")]}function ci(e,t){let n=rn(e);for(let r of t){let i=fe(nn(e.config.projectRoot,r));if(n.has(i)||Vn(r))return i}return null}function Fd(e){let t=Me(e);return oi.has(t)?[e]:[`${e}.rs`,Ce(e,"mod.rs")]}function Ad(e){let t=Me(e);return si.has(t)?[e]:[`${e}.rb`,Ce(e,"index.rb")]}function $d(e){let t=Me(e);return ai.has(t)?[e]:[`${e}.dart`,e]}function jd(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 Id.get(e,()=>new Set(k(e,{includeIgnored:!1}).map(fe)))}function fe(e){return e.replace(/\\/g,"/")}import{basename as Js}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 ui=An("stripped-lines");function qs(e,t,n){return ui.get(e,t,n,()=>Ot(n).split(`
|
|
112
|
+
`))}function Vs(e){ui.invalidateAll(e),Zn=null,on=""}function Us(e,t){ui.invalidate(e,t),Zn=null,on=""}var Zn=null,on="";function Bd(e){return Zn===e||(Zn=e,on=Ot(e)),on}function Qe(e,t,n){let r=Bd(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 Hd=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 ce(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&&Hd.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??V(e,r,li(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 zs(e,t,n){return he(e,t,r=>qd(e,t,r),()=>Wd(e,t,n))}function Wd(e,t,n){return ge(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(r,i)=>{let o=r[1]?.trim();if(!o)return[];let s=Js(o).replace(/\.[^.]+$/,"");return[At(o,s,Yn(e,t,o),oe(i,s))]})}function qd(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 l of o.namedChildren){if(l.type==="system_lib_string"){s=l.text.replace(/^<|>$/g,"");break}if(l.type==="string_literal"){s=l.namedChildren.find(u=>u.type==="string_content")?.text??l.text.replace(/^"|"$/g,"");break}}if(!s)continue;let a=Js(s).replace(/\.[^.]+$/,"");i.push(W(s,a,Yn(e,t,s),r))}return i}function Gs(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 l=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(l,s):!0,usedMembers:s?Ft(l,s):[]})}return r}function Ks(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 Qs(e,t,n){return tr(e,t,{csharp:r=>Ud(e,t,r),vb:r=>Vd(e,t,r)},()=>{let r=Ws(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,l]=s.split(/\s*=\s*/),c=!!l,u=(c?l:a)?.trim()??s,m=u.split(".").pop()??u,d=c?a?.trim()??m:m;return[Ee(e,t,o,u,m,d,V(e,u,ze))]})})}function Vd(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],l=s.length>1?s[0]:null,c=a.text,u=c.split(".").pop()??c,m=l?.text??u;i.push(W(u,m,V(e,c,ze),r,l?"namespace":"named"))}return i}function Ud(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,l;s.length>=2&&s[0].type==="identifier"&&(s[1].type==="qualified_name"||s[1].type==="identifier")?(a=s[0],l=s[1]):l=s[s.length-1];let c=l.text,u=c.split(".").pop()??c,m=a?.text??u;i.push(W(u,m,V(e,c,ze),r,a?"namespace":"named"))}return i}var Jd=H("vue-non-script-identifiers");function Ys(e,t){return Jd.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 mi(e,t,n){return he(e,t,r=>Gd(e,t,r),()=>zd(e,t,n))}function zd(e,t,n){return op(n).flatMap(r=>sp(e,t,r.clause,r.specifier,r.start,r.end,n))}function Gd(e,t,n){let r=Kd(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(...Qd(e,t,n,o,r));return i}function Kd(e,t,n){let r=U(n,new Set(["import_statement"]));if(st(t))for(let i of Ys(e,t))r.add(i);return r}function Qd(e,t,n,r,i){let o=tp(r);if(!o)return[];let s=Ie(e,t,o),a=ce(r,"import_clause");return a?Yd(n,a,s,i,np(r.text)):[dt("*",s)]}function Yd(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(Xd(s.text,n,r,i));else if(s.type==="namespace_import"){let a=Zd(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...ep(s,n,r,i));return o}function Xd(e,t,n,r){return W("default",e,t,n,"default",{isTypeOnly:r})}function Zd(e,t,n,r,i){let s=ce(t,"identifier")?.text??"";if(!s)return null;let a=ip(e,s);return pt("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function ep(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 l=s.text,c=a?.text??l;i.push(W(l,c,t,n,"named",{isTypeOnly:r||rp(o.text)}))}return i}function tp(e){let t=ce(e,"string");if(!t)return null;let n=ce(t,"string_fragment");return n?n.text:null}function np(e){return/^\s*import\s+type\b/.test(e)}function rp(e){return/^\s*type\b/.test(e.trim())}function ip(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 op(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 sp(e,t,n,r,i,o,s){let a=Ie(e,t,r),l=Qe(s,i,o);return n?ap(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let m=Ft(l,u.localName);return pt(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:m,used:m.length>0||oe(l,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(l,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[dt("*",a)]}function ap(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=lp(r),s=[];return i&&s.push(...Xs(i,n)),o&&s.push(...Xs(o,n)),s}function Xs(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+/,""),[l,c]=a.split(/\s+as\s+/);return{importedName:l.trim(),localName:(c??l).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 lp(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 di(e,t,n){let r=B(e,t);return r?fp(e,t,r):cp(e,t,n)}function cp(e,t,n){return[...up(e,t,n),...mp(e,t,n),...dp(e,t,n)]}function up(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]??"",l=se(s).map(m=>pp(m.trim())).filter(m=>!!m),c=$t(n,o.index),u=$t(n,o.index+o[0].length-1);r.push({kind:"named",sourcePath:Ie(e,t,a),names:l,startLine:c,endLine:u})}return r}function mp(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),l=$t(n,o.index+o[0].length-1);r.push({kind:"star-as",sourcePath:Ie(e,t,s),names:[],startLine:a,endLine:l})}return r}function dp(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),l=$t(n,o.index+o[0].length-1);r.push({kind:"star",sourcePath:Ie(e,t,s),names:[],startLine:a,endLine:l})}return r}function pp(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 fp(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=gp(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,l=hp(i,o,s,a);r.push(l)}return r}function gp(e,t,n){let r=ce(n,"string");if(!r)return;let i=ce(r,"string_fragment");if(i)return Ie(e,t,i.text)}function hp(e,t,n,r){let i=ce(e,"export_clause");if(i){let s=[];for(let a of i.namedChildren){if(a.type!=="export_specifier")continue;let l=a.namedChild(0),c=a.namedChild(1);l&&s.push((c??l).text)}return{kind:"named",sourcePath:t,names:s,startLine:n,endLine:r}}return ce(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}function Zs(e,t,n){return tr(e,t,{java:r=>yp(e,t,r),kotlin:r=>bp(e,t,r),scala:r=>Sp(e,t,r)},()=>ge(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?xp(e,t,o,i):[]}))}function yp(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"),l=o.namedChildren.find(m=>m.type==="scoped_identifier")??o.namedChildren.find(m=>m.type==="identifier");if(!l)continue;let c=l.text;if(s){i.push(pt("*",V(e,c,le)));continue}let u=c.split(".").pop()??c;i.push(W(u,u,V(e,c,le),r))}return i}function bp(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"),l=o.namedChildren.find(p=>p.type==="import_alias");if(a){i.push(pt("*",V(e,s.text,le)));continue}let c=s.text,u=c.split(".").pop()??c,d=l?.namedChild(0)?.text??u;i.push(W(u,d,V(e,c,le),r))}return i}function Sp(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")),l=a.map(m=>m.text).join(".");if(!l)continue;if(s?.type==="namespace_wildcard"){i.push(pt("*",V(e,l,le)));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,V(e,`${l}.${y}`,le),r))}else if(m.type==="identifier"){let d=m.text;i.push(W(d,d,V(e,`${l}.${d}`,le),r))}continue}let c=a[a.length-1]?.text??l,u=a.slice(0,-1).map(m=>m.text).join(".")||l;i.push(W(c,c,V(e,u&&a.length>1?`${u}.${c}`:l,le),r))}return i}function xp(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[l,c]=a.includes("=>")?a.split(/\s*=>\s*/):a.split(/\s+as\s+/),u=l?.trim();if(!u||u==="_")return[];let m=(c??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 ta(e,t,n){return he(e,t,r=>Cp(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[l,c]=a.split(/\s+as\s+/i),u=l?.trim()??a,m=u.split("\\").pop()??u,d=(c??m).trim();return[Ee(e,t,i,u,m,d,V(e,u.replace(/\\/g,"."),mt))]}):[]}))}function Cp(e,t,n){let r=U(n,new Set(["namespace_use_declaration"])),i=[],o=(s,a,l)=>{i.push(W(a,l,V(e,s.replace(/\\/g,"."),mt),r))};for(let s of n.rootNode.descendantsOfType("namespace_use_declaration")){let a=s.namedChildren.find(l=>l.type==="namespace_use_group");if(a){let l=s.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:m,qualified:d}=ea(c,l);u&&o(d,u,m)}continue}for(let l of s.namedChildren){if(l.type!=="namespace_use_clause")continue;let{importedName:c,localName:u,qualified:m}=ea(l,"");c&&o(m,c,u)}}return i}function ea(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 o=n&&r.length>0?r[r.length-1]:null,s=i.split("\\").pop()??i,a=o?.text??s,l=t?`${t}\\${i}`:i;return{importedName:s,localName:a,qualified:l}}function ra(e,t,n){return he(e,t,r=>Ip(e,t,r),()=>_p(n).flatMap(r=>Dp(e,t,r,n)))}function Ip(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=na(s);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 o of n.rootNode.descendantsOfType("import_from_statement")){let s=o.namedChild(0);if(!s)continue;let a=Rp(s);if(a===null)continue;let l=Mt(e,t,a);for(let c=1;c<o.namedChildCount;c+=1){let u=o.namedChild(c);if(u.type==="wildcard_import"){i.push({importedName:"*",localName:null,sourcePath:l,kind:"side-effect",used:!0,usedMembers:[]});continue}let m=na(u);m&&i.push({importedName:m.qualifiedName,localName:m.localName,sourcePath:l,kind:"named",used:r.has(m.localName),usedMembers:[]})}}return i}function na(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 Rp(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=ce(e,"import_prefix")?.text??"",n=ce(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function _p(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 l=o,c=a+o.length,u=sn(o);for(;i+1<t.length&&(u>0||l.trimEnd().endsWith("\\"));){i++;let d=t[i];l+=`
|
|
114
|
+
${d}`,c+=1+d.length,u+=sn(d),r+=d.length+1}let m=vp(l);m&&n.push({...m,start:a,end:c})}return n}function vp(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 Dp(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(l=>{let c=l.trim().replace(/,$/,"");if(!c)return[];let[u,m]=c.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 l of se(o)){let c=l.trim().replace(/,$/,"");if(!c)continue;if(c==="*"){a.push({importedName:"*",localName:null,sourcePath:s,kind:"side-effect",used:!0,usedMembers:[]});continue}let[u,m]=c.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 Np}from"path";function ia(e,t,n){return he(e,t,r=>Ep(e,t,r),()=>Lp(e,t,n))}function Lp(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 l=oa(s);return[At(l,l,a,oe(i,l))]}return[dt(s,a)]})}function Ep(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 c=s.namedChildren.find(p=>p.type==="argument_list")?.namedChild(0);if(!c||c.type!=="string")continue;let m=c.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=oa(m);i.push(W(p,p,d,r))}else i.push(dt(m,d))}return i}function oa(e){return Np(e).replace(/\.[^.]+$/,"").split("_").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function sa(e,t,n){return he(e,t,r=>wp(e,t,r),()=>ge(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?kp(e,t,o,i):[]}))}function wp(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 l=Oe(e,t,a.qualifiedName)??Oe(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push(W(a.importedName,a.localName,l,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 kp(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,l=(s??a.split("::").pop()??a).trim(),c=Oe(e,t,a)??Oe(e,t,a.split("::").slice(0,-1).join("::"));return[Ee(e,t,r,a,a.split("::").pop()??a,l,c)]}function aa(e,t,n){let r=B(e,t);if(r)return Pp(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(...Mp(e,t,s))}return i}function Pp(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!Tp(i))continue;let o=i.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of an(o,""))s.importedName&&r.push(pi(e,t,s.qualifiedName))}return r}function Tp(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function Mp(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[l]=a.split(/\s+as\s+/),c=`${i}::${l?.trim()??a}`.replace(/::::/g,"::");return[pi(e,t,c)]})}return[pi(e,t,r)]}function pi(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 la(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 Op={language:"javascript",extensions:ut,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:mi,parseReExports:di},Fp=ft({language:"python",extensions:Un,imports:"ast-with-regex-fallback",parseImports:ra}),Ap=ft({language:"jvm",extensions:le,imports:"ast-dispatch-with-regex-fallback",parseImports:Zs}),$p={language:"rust",extensions:Jn,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:sa,parseExports:aa},jp=ft({language:"ruby",extensions:zn,imports:"ast-with-regex-fallback",parseImports:ia}),Bp=ft({language:"c/cpp",extensions:Gn,imports:"ast-with-regex-fallback",parseImports:zs}),Hp=ft({language:"dotnet",extensions:ze,imports:"ast-dispatch-with-regex-fallback",parseImports:Qs}),Wp={language:"dart",extensions:Kn,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:Gs,parseExports:Ks},qp=ft({language:"php",extensions:mt,imports:"ast-with-regex-fallback",parseImports:ta}),Vp=[Op,Fp,Ap,$p,jp,Bp,Hp,Wp,qp];function rr(e){return la(Vp,e)}var fi=H("source-imports"),gi=H("source-exports"),hi=H("source-reexports");function ca(e,t){let n=fe(t);return hi.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 fi.get(e,n,()=>{let r=rr(n);if(!r)return[];let i=T(e,n);return i?r.parseImports(e,n,i):[]})}function yi(e,t){let n=fe(t);return gi.get(e,n,()=>{let r=rr(n);if(!r?.parseExports)return[];let i=T(e,n);return i?r.parseExports(e,n,i):[]})}function ua(e){fi.invalidateAll(e),gi.invalidateAll(e),hi.invalidateAll(e)}function ma(e,t){let n=fe(t);fi.invalidate(e,n),gi.invalidate(e,n),hi.invalidate(e,n)}var da=H("file-dep-graph");function ae(e,t){return da.get(e,t??"",()=>{let n=new Map,r=new Set(k(e,{includeIgnored:!1})),i=(o,s)=>Jp(e,n,r,o,s);for(let o of Up(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 Up(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 Jp(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 pa(e){da.invalidateAll(e)}import{readdirSync as zp}from"fs";import{extname as fa,join as Gp}from"path";var Kp=[".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"],ga=[".vue"],ha=new Set(Kp.map(e=>e.toLowerCase())),Qp=[...ha].sort().join(","),bi=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(l=>l.toLowerCase()),o=i?new Set(i):ha,s=i?[...o].sort().join(","):Qp,a=`${n?"1":"0"}|${r?"1":"0"}|${s}`;return Yp.get(e,a,()=>{let l=new Set;if(n)for(let c of k(e,{includeIgnored:!1}))o.has(fa(c).toLowerCase())&&l.add(c);if(r)for(let c of Xp(e.config.projectRoot,o))e.isIgnored(c)||l.add(c);return[...l].sort()})}var Yp=H("source-files");function Xp(e,t){let n=new Set,r=i=>{let o=i?Gp(e,i):e,s;try{s=zp(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!bi.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(fa(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}function ue(e){let t=ln(e);return ef(t)?"test":tf(t)?"worker":nf(t)?"entry":rf(t)?"barrel":"source"}function ir(e){return ue(e)==="barrel"}function ba(e){return Zp.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 Zp=We("live-barrels");function Si(e,t){return ba(e).has(ln(t))}function Sa(e){let t=ba(e);return Ye(e).filter(n=>ir(n)&&!t.has(n))}function gt(e,t){let n=ue(t);return n==="entry"||n==="worker"||Si(e,t)}function cn(e,t,n){let r=e.config.entryRoots;if(!r)return!1;let i=ln(n);return!!(r.files?.some(o=>ln(o)===i)||r.pathPrefixes?.some(o=>i.startsWith(ln(o)))||r.qualifiedVars?.some(o=>of(t,o))||r.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}}))}var xa=["%/__tests__/%","%.test.%","%.spec.%","%/test/%","%/tests/%","%_test.%","%_spec.%","%/test_%.%","%/spec_%.%"],Ca=["%/test-utils/%"];function ef(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 tf(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function nf(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 rf(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 ln(e){return e.replace(/\\/g,"/")}function of(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(ya(r)+"/")&&e.includes(ya(i)+".")}function ya(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}var un=new WeakMap;function _a(e,t){let n=P(t);return n==="rust"?uf(e,t):n==="typescript"||n==="tsx"||n==="javascript"?af(e,t):[]}var sf=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]);function af(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 c of a.namedChildren){if(c.type!=="expression_statement")continue;let u=c.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&&sf.has(d)){s=!0;break}}let l=[];s&&l.push({startLine:0,endLine:a.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)"}),(i||o)&&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,m=null;if(c.type==="function_declaration")u=c.namedChild(0)?.text??null,m=c;else if(c.type==="export_statement"){let d=c.namedChild(0);d?.type==="function_declaration"&&(u=d.namedChild(0)?.text??null,m=d)}else if(c.type==="lexical_declaration"){let d=c.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&&l.push({startLine:m.startPosition.row,endLine:m.endPosition.row,reason:"React custom hook (use*)"})}return l.push(...va(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,l),l}var lf=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function cf(e){return lf.test(e)}function va(e,t,n){let r=[],i=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,l=-1;for(let c=0;c<a.length;c+=1)if(a[c].startIndex===o.startIndex&&a[c].type===o.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(cf(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 uf(e,t){let n=B(e,t);if(!n)return[];let r=un.get(n);if(r)return r;let i=[],o=mf(n);return o?(un.set(n,o),o):(Da(n.rootNode,i,!1,!1),i.push(...va(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(...yf(n.rootNode)),un.set(n,i),i)}function mf(e){return bf(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)"}]:null}function Da(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"?df(e,t,n,r):r&&hf(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"?pf(e,t,n):e.type==="mod_item"&&xi(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)Da(s,t,i,o)}function df(e,t,n,r){let i=xi(e),o=null;r?o="trait impl method (dynamic dispatch)":n&&(o="inside #[cfg(test)] mod");for(let s of i){let a=ff(s);if(a){o=a;break}if(Na(s)){o="#[allow(dead_code)]";break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o})}function pf(e,t,n){let r=xi(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(gf)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(<reflective>)] \u2014 fields accessed via macro/reflection",containerName:i}),r.some(Na)&&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 xi(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 ff(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 gf(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 Na(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function hf(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function yf(e){let t=Rf(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 bf(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 Sf=[{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}],La=/^#!?\[\s*serde\s*\(/,xf=/^#!?\[\s*schemars\s*\(/,Cf=/^#!?\[\s*validate\s*\(/,Ia=/\bwith\s*=\s*"([^"]+)"/g;function jt(e,t){return tn(e,t,If,()=>new Set,(n,r,i)=>{if(r==="rust"){for(let o of n.rootNode.descendantsOfType("attribute_item"))Ra(o.text,i);for(let o of n.rootNode.descendantsOfType("inner_attribute_item"))Ra(o.text,i)}})??new Set}var If=new WeakMap;function Ra(e,t){let n=La.test(e),r=xf.test(e),i=Cf.test(e);if(!(!n&&!r&&!i))for(let{re:o}of Sf){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;){let a=s[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 Rf(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){if(!La.test(n.text))continue;Ia.lastIndex=0;let r;for(;(r=Ia.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}var _f=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function Ea(e,t){return tn(e,t,vf,()=>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||!_f.has(a))continue;let l=o.namedChildren.find(m=>m.type==="arguments");if(!l)continue;let c=l.namedChild(0);if(!c||c.type!=="string")continue;let u=c.namedChildren.find(m=>m.type==="string_fragment");u&&i.add(u.text)}})??new Set}var vf=new WeakMap;var Df=new Set(["identifier","type_identifier","field_identifier"]),Nf=new Set(["identifier"]),Lf=new Set(["identifier","property_identifier","type_identifier"]),Ef=new Set(["rust","python"]),wf=/\{([^{}]*)\}/g,kf=/\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=>!wa(u,r));let o=qs(e,t,i),s=new RegExp(`\\b${er(n)}\\b`),a=[];for(let l=0;l<o.length;l++)wa(l,r)||s.test(o[l]??"")&&a.push(l);return a}function wa(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var Ci=H("file-identifiers");function ka(e,t){return Ci.get(e,t,()=>new Set(ht(e,t).keys()))}var Ii=H("file-ident-lines");function ht(e,t){return Ii.get(e,t,()=>Pf(e,t))}var Ri=H("file-idents-by-line");function Pa(e,t){return Ri.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 Ta(e){Ci.invalidateAll(e),Ii.invalidateAll(e),Ri.invalidateAll(e)}function Ma(e,t){Ci.invalidate(e,t),Ii.invalidate(e,t),Ri.invalidate(e,t)}function Pf(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(P(t)){let a=B(e,t);if(a){let l=P(t),c=l==="rust"?Df:l==="python"?Nf:Lf,u=m=>{if(c.has(m.type)&&r(m.text,m.startPosition.row),l&&Ef.has(l)&&m.type==="string_content"){let d=m.startPosition.row;for(let p of m.text.matchAll(wf)){let y=p[1]??"";for(let f of y.matchAll(kf))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 l=o[a]??"";for(let c of l.matchAll(s))c[1]&&r(c[1],a)}return n}function Oa(e,t){return _i(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 Fa(e,t){return _i(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 _i(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 _i(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 Aa(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Xe(e,t){return Aa(e)===Aa(t)}function ar(e,t){let n=$a(e);return n?t.filter(r=>$a(r.file)===n):t}function lr(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 $a(e){let t=P(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var ja=We("global-leaf-index");function yt(e){return ja.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 Ba(e){ja.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 Ha from"path";function Tf(e,t){return e.getReferences().map(n=>{let r=n.getNode();return Va(r,t)})}function Mf(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function Wa(e,t,n,r){let i=[];for(let o of Mf(e))for(let s of Tf(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 cr(i)}function qa(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:Va(a,r),node:a}))}return i}function Va(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 Ua(e,t,n){let r=e.getSourceFile(),i=Bt(r,e),o=e.getText(),s=new RegExp(`\\b${Of(o)}\\b`,"g"),a=r.getFullText().split(`
|
|
171
|
+
`),l=[];for(let c=0;c<a.length;c++){if(c===i)continue;let u=a[c]??"";s.lastIndex=0;let m;for(;(m=s.exec(u))!==null;)l.push({file:t,line:c,column:m.index})}return cr(l.filter(c=>mn(n,Ha.join(n,c.file))===t))}function vi(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 cr(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=Ha.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function Of(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ja(e,t,n,r){let i=Ff(t,r);return i.size===0?new Map:Af(e,n,i)}function Ff(e,t){let n=new Map;for(let r of q(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 Af(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of $f(e,o)){let a=n.get(s);if(!a)continue;let l=Bt(t,o);for(let c of a){if(l<c.startLine-1||l>c.endLine+1)continue;let u=Math.abs(l-c.startLine),m=i.get(c.symbolId);m!==void 0&&m<=u||(i.set(c.symbolId,u),r.set(c.symbolId,o))}}}),r}function $f(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 za(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+=po(m),r+=m.length+1}let d=ug(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
|
|
191
|
+
LIMIT 5`,t,`%${r}%`,n)[0]??null}function Ga(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+=po(m),r+=m.length+1}let d=ug(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||w(s.symbol);!o||i.has(o)||i.set(o,{...s,leaf:o})}return i}function Yg(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 xn(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Pr(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 Qg(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function Xg(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 Re(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}function _n(e,t){let n=ue.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function Zg(e){return/\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(e)}function No(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}function eh(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Or=new WeakMap;function Mr(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,r=Or.get(e);r||(r=new Map,Or.set(e,r));let i=r.get(n);if(i)return i;let s=Do(e,t);return r.set(n,s),s}function Tr(e){Or.delete(e)}function Et(e,t){let n=In(e,t);return n?n.importUsage(t):[]}function Dt(e,t){let n=In(e,t.relativePath);return n?n.referencesFor(t):[]}function mt(e,t){let n=new Map;for(let r of t)for(let i of Dt(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=In(e,r.relativePath);if(!i)continue;let s=i.calleesFor(r);s.length>0&&n.set(r.symbolId,s)}return n}function ko(e,t){let n=In(e,t.relativePath);return n?n.signatureFor(t):null}function In(e,t){if(!th(t))return null;let n=Mr(e,t);return n.availability().available?n:null}function th(e){return/\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(e)}var To=A("file-dep-graph");function Fo(e){To.invalidateAll(e),Ao.invalidate(e),Bo.invalidate(e)}function Q(e,t){return To.get(e,t??"",()=>{let n=new Map,r=rh(e),i=(s,o)=>ih(e,n,r,s,o);for(let s of nh(e,t))i(s.from_file,s.to_file);for(let s of r)if(!(t&&!s.includes(t)))for(let o of J(e,s))o.sourcePath&&i(s,o.sourcePath);return n})}function nh(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 rh(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 Z(e,t,n={}){let r=Rn(e,[t],{additive:n.additive}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(s=>V(s.symbol)):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function ie(e,t,n={}){let r=oh(e)?lh(e,t):ah(e).get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}var Ao=Be("caller-rows"),sh=2e4;function oh(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>sh}function ah(e){return Ao.get(e,()=>{let t=oe(e),n=Rn(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 lh(e,t){let n=[],r=new Set,i=o=>{if(o.symbol===t.symbol)return;let a=`${o.symbol}|${o.file}`;r.has(a)||(r.add(a),n.push(o))};for(let o of Ce(e,t))o.file!==t.relativePath&&i({symbol:o.enclosingSymbol??o.file,file:o.file});let s=ch(e,t);if(s)for(let o of Dt(e,s)){if(o.file===t.relativePath||e.isIgnored(o.file))continue;let a=ae(z(e,o.file),o.line);i({symbol:a?.symbol??o.file,file:o.file})}return n}function ch(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 jf 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 Ka(e,t){let n=new Map,r=i=>ur(i)?Re(n,i,()=>{let o=jf.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 Bf,readFileSync as Qa}from"fs";function Ya(e){let t=Ze.join(e,"package.json");if(!mr(t))return[];let n;try{n=JSON.parse(Qa(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>Hf(e,i)).flatMap(i=>Wf(e,i))}function Hf(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 Bf(o).map(s=>Ze.join(o,s,i)).filter(s=>mr(Ze.join(s,"package.json")))}catch{return[]}}function Wf(e,t){try{let n=JSON.parse(Qa(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 Xa(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Za(e){return[`${e.sourceRootRelative}/index.ts`,`${e.sourceRootRelative}/index.tsx`,`${e.sourceRootRelative}/index.mts`,`${e.sourceRootRelative}/index.cts`]}import{existsSync as pn,readFileSync as qf,readdirSync as Vf,statSync as Uf}from"fs";import J from"path";var Ni=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Li(e,t){let r=t?J.dirname(J.join(e,t)):e,i=J.resolve(e);for(;r.startsWith(i);){for(let s of Ni){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 Ni){let s=J.join(e,o);if(pn(s))return s}return null}function el(e){let t=e.config.projectRoot,n=new Set(Ei(t,e.config.semantic?.typescript?.tsconfigs)),r=k(e,{includeIgnored:!1,extensions:dn});for(let i of r){let o=Li(t,i);o&&n.add(J.resolve(o))}if(n.size===0){let i=Li(t);i&&n.add(J.resolve(i))}return[...n].filter(i=>!tl(t,i)).sort((i,o)=>i.localeCompare(o))}function Ei(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 Jf(e))for(let i of Ni){let o=J.join(r,i);pn(o)&&n.add(J.resolve(o))}if(n.size===0){let r=Li(e);r&&n.add(J.resolve(r))}return[...n].filter(r=>!tl(e,r)).sort((r,i)=>r.localeCompare(i))}function Jf(e){let t=J.join(e,"package.json");if(!pn(t))return[];let n;try{n=JSON.parse(qf(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>zf(e,i))}function zf(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=J.join(e,t);return Di(s)?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=J.join(e,r||".");return Di(o)?Vf(o).map(s=>J.join(o,s,i)).filter(Di):[]}function Di(e){try{return Uf(e).isDirectory()}catch{return!1}}function tl(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 Gf}from"module";var Kf=Gf(import.meta.url),fn;function nl(){if(fn!==void 0)return fn;try{fn=Kf("ts-morph")}catch{fn=null}return fn}function rl(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 sl(e,t){let n=nl();if(!n)return dr("ts-morph is not installed");let r=el(e);if(r.length===0)return dr("no tsconfig found");try{let i=rl(n,r);return new wi(e,n,i)}catch(i){return dr(i instanceof Error?i.message:String(i),r[0],r)}}var wi=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Ya(t.config.projectRoot),this.sourceFiles=Ka(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?Wa(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],l=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return ol(l)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${ol(o)}`})}importUsageForDeclaration(t,n){let r=Ie(this.db,t,n.getModuleSpecifierValue()),i=il(n);return n.getImportClause()?.isTypeOnly()?i.map(o=>Qf(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 c of i)for(let u of qa(c,t,r.identifier,this.db.config.projectRoot))o.push(u);let s=o.some(c=>!vi(c.node)),a=o.some(c=>vi(c.node)),l=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:l,isUsed:l||o.length>0,isTypeUsed:l||a,isValueUsed:s,references:o.map(c=>c.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,cr(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=Xa(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of il(i)){if(a.kind!=="named"||!a.identifier)continue;let l=s.get(a.importedName);if(!l||l.size===0)continue;let c=Ua(a.identifier,r,this.db.config.projectRoot);c.length>0&&Zf(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 Za(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(),l=a?Ie(this.db,n,a):n;if(!l||!l.startsWith(`${t.sourceRootRelative}/`))continue;let c=s.getNamedExports();if(c.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,l,r,i);continue}for(let u of c){let m=u.getNameNode().getText(),d=u.getAliasNode()?.getText()??m,p=this.indexedDefinitionByLeaf(l,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,()=>Ga(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?Ja(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=za(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=q(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&&Yf(i,s.callerId,s.target)});for(let[o,s]of i)i.set(o,eg(s));return i}semanticCalleeForCallNode(t,n,r){let i=Xf(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 il(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 Qf(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 Yf(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function Xf(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 Zf(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function eg(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 ol(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var ki=new WeakMap;function Pi(e,t){let n=`${e.config.projectRoot}:typescript-workspace`,r=ki.get(e);r||(r=new Map,ki.set(e,r));let i=r.get(n);if(i)return i;let o=sl(e,t);return r.set(n,o),o}function Ti(e){ki.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 al(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 ll(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=Pi(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&&cl(n,i,r.sourcePath),r.kind==="namespace")for(let o of r.usedMembers)cl(n,o,r.sourcePath)}return n}function cl(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(l=>l.file===t);if(i.length>0)return i.map(yn);let o=fr(e,t),s=o.get(n);if(s)for(let l of s){let c=r.filter(u=>Xe(l,u.file));if(c.length>0)return c.map(yn)}let a=new Set;for(let l of o.values())for(let c of l)a.add(c);for(let l of a){let c=r.filter(u=>Xe(l,u.file));if(c.length>0&&c.length===r.length)return c.map(yn)}return[]}function ml(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 dl(e,t,n={}){let r=qn(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 l of s){let c=a.get(l.file)??[];c.push(l.line),a.set(l.file,c)}return ul(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 l=or(e,s,i,s===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{});l.length>0&&o.set(s,l)}return ul(e,o)}function pl(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=ka(e,o);if(s.size!==0){for(let a of s)if(n.has(a))for(let l of Wt(e,o,a)){if(!r.has(l.symbolId)||o===l.relativePath)continue;let c=i.get(l.symbolId);c||(c=new Set,i.set(l.symbolId,c)),c.add(o)}}}return i}function yn(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function ul(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=q(e,i);for(let a of o){let l=de(s,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 Mi(e,t){let n=sg(e,t);return n?ag(e,ng(e,n.match,n.identifier)):[]}function et(e,t,n={}){return tg(e,t,n).map(r=>({file:r.file,line:r.line,enclosingSymbol:r.enclosingSymbol}))}function tg(e,t,n={}){let r=dl(e,t,{semantic:n.semantic}),i=r.length>0?fl(r,"source-attribution"):fl(Mi(e,t),"scip-reference-chunk");return n.includeIgnored===!0?i:i.filter(o=>!e.isIgnored(o.file))}function fl(e,t){return e.map(n=>({...n,provenance:t}))}function ng(e,t,n){let r=new Map;for(let[i,o]of rg(e,t.symbolId))r.set(i,ig(e,i,o,t,n));return r}function rg(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 ig(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=>og(s,a))}function og(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function sg(e,t){let n=qn(e,t);return n?{match:n,identifier:L(n.symbol)||null}:null}function ag(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=q(e,i);for(let a of o){let l=de(s,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 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=cg(e)?mg(e,t,{semantic:n.semantic!==!1}):ug(e).get(t.symbolId)??[];return typeof n.limit=="number"?r.slice(0,n.limit):r}var gl=We("caller-rows"),lg=2e4;function cg(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>lg}function ug(e){return gl.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 l of a){let c=r.get(l.symbol);if(c===void 0||c===s.symbolId)continue;let u=i.get(c);u||(u=[],i.set(c,u),o.set(c,new Set));let m=`${s.symbol}|${s.relativePath}`;o.get(c).has(m)||(o.get(c).add(m),u.push({symbol:s.symbol,file:s.relativePath,source:"caller-map-inversion"}))}}return i})}function mg(e,t,n){let r=[],i=new Set,o=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 Mi(e,t))a.file!==t.relativePath&&o({symbol:a.enclosingSymbol??a.file,file:a.file,source:"resolved-reference"});let s=n.semantic?dg(e,t):null;if(s)for(let a of hn(e,s)){if(a.file===t.relativePath||e.isIgnored(a.file))continue;let l=de(q(e,a.file),a.line);o({symbol:l?.symbol??a.file,file:a.file,source:"semantic-reference"})}return r}function dg(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+=po(m),r+=m.length+1}let d=ug(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
|
|
484
|
-
FROM mentions m
|
|
485
|
-
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 mh(e,t,n,r,i){let s=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},o=i?pn(e,t,i,s):[];return n.flatMap(a=>ph(o,a))}function ph(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function fh(e,t){let n=cn(e,t);return n?{match:n,identifier:w(n.symbol)||null}:null}function gh(e,t){let n=[],r=new Set;for(let[i,s]of t){let o=z(e,i);for(let a of s){let l=ae(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 Rn(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],s=[];for(let u of t)T(u.relativePath)&&sn(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 y=`${p.symbol}|${p.chunkId}`;h.has(y)||(h.add(y),f.push(p))}}};i.length>0&&l(hh(e,i)),l(Lh(wo(e,t)));let c=r?t:s;return c.length>0&&l(_h(e,c)),o}function hh(e,t){let n=new Map,r=yh(t,n),i=Lt(e);for(let[s,o]of r){let a=sn(e,s);if(a)for(let l of a){let c=bh(o,l.line);if(!c)continue;let u=Sh(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 yh(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 bh(e,t){return e.find(n=>t>=n.startLine&&t<=n.endLine)??null}function Sh(e,t,n,r,i){let s=$o(t,n.get(r)??[]);return s.length===0?null:jo(e,t,s,i)}function $o(e,t){let n=Po(e);return n?t.filter(r=>Po(r.file)===n):t}function jo(e,t,n,r){let i=n.find(s=>s.file===t);if(i)return i;if(r){let s=new Set(J(e,t).map(o=>o.sourcePath).filter(o=>!!o));for(let o of n)for(let a of s)if(xh(a,o.file))return o;return null}return n.length===1?n[0]:null}function xh(e,t){let n=r=>r.replace(/\\/g,"/").replace(/^\.\//,"");return n(e)===n(t)}function Po(e){let t=T(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var Bo=Be("global-leaf-index");function Lt(e){return Bo.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=w(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 _h(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
|
|
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,l=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&&l(pg(e,i)),n.semantic!==!1&&l(bg(al(e,t)));let c=r?t:o;return c.length>0&&l(yg(e,c)),s}function pg(e,t){let n=new Map,r=fg(t,n),i=yt(e);for(let[o,s]of r){let a=Nt(e,o);if(a)for(let l of a){let c=gg(s,l.line);if(!c)continue;let u=hg(e,o,i,l.calleeLeaf,l.memberAccess);u&&u.symbol!==c.symbol&&n.get(c.symbolId).push({symbol:u.symbol,file:u.file,chunkId:l.line,source:"ast-callsite"})}}return n}function fg(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 gg(e,t){return e.find(n=>t>=n.startLine&&t<=n.endLine)??null}function hg(e,t,n,r,i){let o=ar(t,n.get(r)??[]);return o.length===0?null:lr(e,t,o,i)}function yg(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
251
|
FROM mentions m
|
|
506
252
|
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])),
|
|
253
|
+
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])),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+=po(m),r+=m.length+1}let d=ug(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
|
|
518
|
-
|
|
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 vh(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 Nh(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function Eh(e,t,n,r,i){for(let s of n){if(e.isIgnored(s.relative_path)||T(s.relative_path)!=="rust")continue;let o=at(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&&Fr(t,c.symbolId,s.relative_path)}}}function Fr(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function Dh(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function Lh(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 wh(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 ee(e){let t=wt(e);return Ph(t)?"test":Oh(t)?"worker":Mh(t)?"entry":Th(t)?"barrel":"source"}function Cn(e){return ee(e)==="barrel"}function Uo(e){return kh.get(e,()=>{let t=Q(e),n=Le(e).filter(s=>{let o=ee(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),ee(s)==="barrel"&&i.add(s);for(let o of t.get(s)??[])r.has(o)||n.push(o)}}return i})}var kh=Be("live-barrels");function Ar(e,t){return Uo(e).has(wt(t))}function Vo(e){let t=Uo(e);return Le(e).filter(n=>Cn(n)&&!t.has(n))}function Ke(e,t){let n=ee(t);return n==="entry"||n==="worker"||Ar(e,t)}function kt(e,t,n){let r=e.config.entryRoots;if(!r)return!1;let i=wt(n);return!!(r.files?.some(s=>wt(s)===i)||r.pathPrefixes?.some(s=>i.startsWith(wt(s)))||r.qualifiedVars?.some(s=>Fh(t,s))||r.symbolPatterns?.some(s=>{try{return new RegExp(s).test(t)}catch{return!1}}))}var Jo=["%/__tests__/%","%.test.%","%.spec.%","%/test/%","%/tests/%","%_test.%","%_spec.%","%/test_%.%","%/spec_%.%"],qo=["%/test-utils/%"];function Ph(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 Oh(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function Mh(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 Th(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 wt(e){return e.replace(/\\/g,"/")}function Fh(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(Wo(r)+"/")&&e.includes(Wo(i)+".")}function Wo(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function pt(e,t,n){let r=Lt(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[Pt(r[0])];let i=r.filter(l=>l.file===t);if(i.length>0)return i.map(Pt);let s=Ah(e,t),o=s.get(n);if(o)for(let l of o){let c=r.filter(u=>zo(l,u.file));if(c.length>0)return c.map(Pt)}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=>zo(l,u.file));if(c.length>0&&c.length===r.length)return c.map(Pt)}return[]}function Ko(e,t,n){let r=pt(e,t,n);if(r.length>0)return r;let i=Lt(e).get(n);return!i||i.length===0?[]:i.map(Pt)}function $e(e,t){let n=cn(e,t);if(!n)return[];let r=w(n.symbol);if(!r)return[];let i=Dt(e,{...n,leaf:r,parentTypeName:null,isFunctionLike:!1,isTypeLike:!1,kind:null,documentation:null,enclosingSymbol:null});if(i.length>0){let o=new Map;for(let a of i){let l=o.get(a.file)??[];l.push(a.line),o.set(a.file,l)}return Go(e,o)}let s=new Map;for(let o of Le(e)){let a=P(e,o);if(!a||a.indexOf(r)===-1||o!==n.relativePath&&!pt(e,o,r).some(u=>u.symbolId===n.symbolId))continue;let l=pn(e,o,r,o===n.relativePath?{excludeStartLine:n.startLine,excludeEndLine:n.endLine}:{});l.length>0&&s.set(o,l)}return Go(e,s)}function Yo(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 Le(e)){let o=js(e,s);if(o.size!==0){for(let a of o)if(n.has(a))for(let l of pt(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 Ah(e,t){let n=new Map;for(let r of J(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 zo(e,t){let n=r=>r.replace(/\\/g,"/").replace(/^\.\//,"");return n(e)===n(t)}function Pt(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function Go(e,t){let n=[],r=new Set;for(let[i,s]of t){let o=z(e,i);for(let a of s){let l=ae(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 Qo(e,t,n){let r=t.identifierResolution==="strict"?pt:Ko;for(let i of t.paths){let s=T(i);if(!s&&!(t.includeVueSfc&&St(i))||e.isIgnored(i)||t.skipPath?.(i))continue;let o=Ge(e,i);for(let[a,l]of o)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 Os(e,i))for(let l of pt(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 at(e,i))for(let l of r(e,i,a))n({sourceFile:i,name:a,target:l,occurrences:1,kind:"rust-attribute"})}}var v=class{constructor(t){this.db=t}db;scopedDefinitions(t){return fr(this.db,t)}definitionsForFile(t){return z(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&&Ke(this.db,p)||!$h(h,{requireFunctionLikeSymbol:l,requireCallableSymbol:c})||s!==void 0&&h.symbol===s)continue;let y=$r(h);y<r||y>i||a&&jh(p)||u&&an(h.symbol)||ee(p)!=="test"&&(Pe(h.symbol)||!d&&dr(this.db,p,h.startLine)||f.push(h))}return m?f.sort((h,p)=>$r(p)-$r(h)):f}calleeMap(t,n={}){return Rn(this.db,t,n)}crossFileCallerMap(t){return Ho(this.db,t)}sourceFallbackCallerFiles(t){return Yo(this.db,t)}fileDependencyGraph(t){return Q(this.db,t)}fileKind(t){return ee(t)}hasSuppressionComment(t){return dr(this.db,t.relativePath,t.startLine)}sourceFiles(){return Le(this.db)}scanSourceReferences(t,n){Qo(this.db,t,n)}callableSignature(t){return hs(this.db,t.relativePath,t.startLine,t.endLine)}};function $r(e){return e.endLine-e.startLine+1}function $h(e,t){return t.requireCallableSymbol?V(e.symbol):t.requireFunctionLikeSymbol?H(e.symbol):e.isFunctionLike}function jh(e){return(e.split("/").pop()??"").includes("types")}function Xo(e,t){let n=L(e,t);if(!n)return[];let r=w(n.symbol),s=new v(e).definitionsForFile(n.relativePath).filter(l=>V(l.symbol)),o=s.filter(l=>l.parentTypeName===r||l.symbol.includes(r));return(o.length>0?o:Hh(Bh(n.relativePath))===r?s.filter(l=>l.symbol.includes("<invalid-global-code>")):[]).map(l=>({startLine:l.startLine,endLine:l.endLine,name:w(l.symbol)}))}function Hh(e){return e.replace(/\.[^.]+$/,"")}function Zo(e,t){let n=L(e,t);if(!n)return[];let i=!H(n.symbol)&&!e.isIgnored(n.relativePath)?[{relativePath:n.relativePath,line:n.startLine}]:[],s=$e(e,n),o=(s.length>0?s:Ce(e,n)).filter(u=>!e.isIgnored(u.file)).map(u=>({relativePath:u.file,line:u.line})),a=Wh(e,n),l=new Set,c=[];for(let u of[...i,...o,...a]){let d=`${u.relativePath}:${u.line}`;l.has(d)||(l.add(d),c.push(u))}return c}function Wh(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=Uh(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=P(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 Uh(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 ea(e,t){let n=L(e,t);if(!n)return{definitions:[],referencedBy:[]};let r=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",n.symbolId),i=Je(r?.documentation??null),s=e.isIgnored(n.relativePath)?[]:[{relativePath:n.relativePath,startLine:n.startLine,endLine:n.endLine,signature:Jh(i,r?.display_name??null,n.symbol),source:Vh(e,n.relativePath,n.startLine,n.endLine)}],o=$e(e,n),l=(o.length>0?o:Ce(e,n)).filter(c=>!e.isIgnored(c.file)).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?g(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:l}}function Vh(e,t,n,r){let i=P(e,t);if(!i)return null;let o=i.split(`
|
|
263
|
+
) def_chunk ON def_chunk.symbol_id = gs.id`);for(let c of s)o.has(c.symbol_id)||o.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)??[],m=new Set,d=[],p=null,y=()=>{if(p)return p;let f=l.get(c.documentId)??"",b=new Set;if(f){let E=Pa(e,f),x=Math.max(0,c.startLine),$=Math.min(E.length-1,c.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===c.symbolId)continue;let b=o.get(f.symbol_id);if(!b)continue;if(!(f.start_line>=c.startLine&&f.end_line<=c.endLine)){if(!(f.start_line<=c.endLine&&f.end_line>=c.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(c.symbolId,d)}return a}function bg(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 hl(e){gl.invalidate(e)}function yl(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(l=>l.symbolId));return Sg(e,r,i,o,a),xg(e,r,s,a),_g(e,r,i,o,a),n.semantic!==!1&&Dg(r,Ht(e,vg(s))),r}function Sg(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 l=ar(o,r.get(a.calleeLeaf)??[]);if(!l||l.length===0)continue;let c=lr(e,o,l,a.memberAccess);c&&i.has(c.symbolId)&&c.file!==o&&Oi(t,c.symbolId,o)}}}function xg(e,t,n,r){let i=Ig(n);for(let o of Cg(e,r))e.isIgnored(o.relative_path)||Rg(o,i.get(o.symbol_id))||Oi(t,o.symbol_id,o.relative_path)}function Cg(e,t){return sr(e,t?[...t]:void 0)}function Ig(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 Rg(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function _g(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 l=r.get(a);if(l)for(let c of l)i.has(c.symbolId)&&c.file!==o&&Oi(t,c.symbolId,o)}}}function Oi(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function vg(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function Dg(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 bl=new WeakMap;function Sl(e,t,n,r){let i=P(t);if(!i)return null;let o=B(e,t);if(!o)return null;let s=bl.get(o);return s||(s=Ng(o,i),bl.set(o,s)),s.get(`${n}:${r}`)??null}function Ng(e,t){let n=en(t),r=new Map,i=o=>{if(n.has(o.type)){let s=o.namedChildren.find(l=>l.type==="parameters"||l.type==="formal_parameters"),a=0;if(s)for(let l of s.namedChildren)l.type==="comment"||l.type==="line_comment"||l.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 xl(e,t,n){let r=t.identifierResolution==="strict"?Wt:ml;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=(l,c,u,m)=>{if(t.candidateNames&&!t.candidateNames.has(l))return;let d=t.resolveTargets?t.resolveTargets({sourceFile:i,name:l,kind:c,defaultTargets:m}):m();for(let p of d)n({sourceFile:i,name:l,target:p,occurrences:u,kind:c})},a=ht(e,i);for(let[l,c]of a)s(l,"identifier",c.length,()=>r(e,i,l));if(t.includeCrossLanguageDispatchNames)for(let l of Ea(e,i))s(l,"cross-language-dispatch",1,()=>Wt(e,i,l));if(t.includeRustAttributeNames&&o==="rust")for(let l of jt(e,i))s(l,"rust-attribute",1,()=>r(e,i,l))}finally{t.afterPath?.(i)}}}var v=class{constructor(t){this.db=t}db;scopedDefinitions(t){return ei(this.db,t)}definitionsForFile(t){return q(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:l=!1,requireCallableSymbol:c=!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&>(this.db,f)||!Lg(y,{requireFunctionLikeSymbol:l,requireCallableSymbol:c})||o!==void 0&&y.symbol===o)continue;let b=Fi(y);b<r||b>i||a&&Eg(f)||u&&Bn(y.symbol)||ue(f)!=="test"&&(Ve(y.symbol)||!m&&Gr(this.db,f,y.startLine)||p.push(y))}return d?p.sort((y,f)=>Fi(f)-Fi(y)):p}calleeMap(t,n={}){return gr(this.db,t,n)}crossFileCallerMap(t,n={}){return yl(this.db,t,n)}sourceFallbackCallerFiles(t){return pl(this.db,t)}callerFileMap(t,n={}){let r=this.crossFileCallerMap(t,{semantic:n.semantic});return n.sourceFallback===!1?r:wg(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(l=>l.symbol!==a)}).map(([o])=>o))}fileDependencyGraph(t){return ae(this.db,t)}fileKind(t){return ue(t)}hasSuppressionComment(t){return Gr(this.db,t.relativePath,t.startLine)}sourceFiles(){return Ye(this.db)}scanSourceReferences(t,n){xl(this.db,t,n)}callableSignature(t){return Sl(this.db,t.relativePath,t.startLine,t.endLine)}};function Lg(e,t){return t.requireCallableSymbol?te(e.symbol):t.requireFunctionLikeSymbol?K(e.symbol):e.isFunctionLike}function Fi(e){return e.endLine-e.startLine+1}function Eg(e){return(e.split("/").pop()??"").includes("types")}function wg(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 Ai(e,t){let n=w(e,t);if(!n)return[];let r=L(n.symbol),o=new v(e).definitionsForFile(n.relativePath).filter(l=>te(l.symbol)),s=o.filter(l=>l.parentTypeName===r||l.symbol.includes(r));return(s.length>0?s:Pg(kg(n.relativePath))===r?o.filter(l=>l.symbol.includes("<invalid-global-code>")):[]).map(l=>({startLine:l.startLine,endLine:l.endLine,name:L(l.symbol)}))}function Pg(e){return e.replace(/\.[^.]+$/,"")}function $i(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=Tg(e,r),l=new Set,c=[];for(let u of[...o,...s,...a]){let m=`${u.relativePath}:${u.line}`;l.has(m)||(l.add(m),c.push(u))}return c}function Tg(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=Mg(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 l=s[a]??"";n.some(c=>new RegExp(`@${c}\\b|\\b${c}:`).test(l))&&r.push({relativePath:i,line:a})}}return r}function Mg(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 ji(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=lt(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:Fg(o,i?.display_name??null,r.symbol),source:Og(e,r.relativePath,r.startLine,r.endLine)}],a=et(e,r,{semantic:n.semantic}).map(l=>({relativePath:l.file,line:l.line,enclosingSymbol:l.enclosingSymbol,enclosingShort:l.enclosingSymbol?h(l.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function Og(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
|
|
266
|
+
`).trimEnd();return s.length>0?s:null}function Fg(e,t,n){let r=at(e);if(r&&!Ag(r))return r;let i=(t??"").trim();return i?K(n)&&!i.endsWith("()")?`${i}()`:i:h(n)}function Ag(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Bi(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+=po(m),r+=m.length+1}let d=ug(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
|
|
282
|
+
ORDER BY d2.relative_path`,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function Hi(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+=po(m),r+=m.length+1}let d=ug(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
|
|
297
|
+
ORDER BY d1.relative_path`,n,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function Wi(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(
|
|
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),l=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+=po(m),r+=m.length+1}let d=ug(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(
|
|
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+=po(m),r+=m.length+1}let d=ug(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(
|
|
330
|
+
ORDER BY d1.relative_path`,...n,...n).map(m=>m.relative_path).filter(m=>!e.isIgnored(m));return{files:o,symbols:s,dependsOn:l,dependedOnBy:u}}function qi(e,t){let n=Ue(e,t);return n.length===0?[]:Bg([...$g(e,n),...jg(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(Hg)}function $g(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,17 +354,7 @@ ${m}`,c+=1+m.length,u+=po(m),r+=m.length+1}let d=ug(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
|
|
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`),r=new Map;for(let i of n){if(e.isIgnored(i.relative_path)||t.has(i.relative_path))continue;let s=r.get(i.symbol_id);s||(s=new Map,r.set(i.symbol_id,s)),s.set(i.relative_path,i.ref_count)}return r}function Xh(e,t){let n=cy(e);return oe(e,{scope:t.scope}).filter(r=>!e.isIgnored(r.relativePath)).filter(r=>!ke(r.symbol)).filter(r=>sa(r.symbol)).filter(r=>r.isFunctionLike||!r.enclosingSymbol||!sa(r.enclosingSymbol)).filter(r=>t.includeTests||oa(r.relativePath)).filter(r=>t.includeTests||!n(r.relativePath,r.startLine,r.symbol,r.parentTypeName)).filter(r=>!an(r.symbol)).filter(r=>!Pe(r.symbol)).filter(r=>t.includeMembers||dy(r)).filter(r=>r.endLine-r.startLine+1>=t.minLoc)}function Zh(e,t){return e.map(n=>ey(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 ey(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 ty(e,t){let n=[],r=0,i=0,s=0;for(let o of t){if(e.isIgnored(o.relative_path)||Ke(e,o.relative_path)||kt(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:g(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){let r=new v(e),i=new Set(r.sourceFiles());for(let s of ry(e))i.add(s);r.scanSourceReferences({paths:i,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",skipPath:s=>n.has(s)},s=>{iy(e,s)||oy(t,s.target.symbolId,s.sourceFile,sy(s))})}function ry(e){let t=e.all(`SELECT relative_path FROM documents
|
|
633
|
-
WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`);return new Set(t.map(n=>n.relative_path))}function iy(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&ay(e,t)}function sy(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function oy(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 ay(e,t){return t.occurrences>1?!1:J(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function ly(e,t,n,r){for(let i of t){let s=ie(e,i);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&&!oa(l)||o.set(l,Math.max(1,o.get(l)??0))}}}function cy(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let s=Ds(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 gr(s))if(a.containers.has(l))return!0;return!1}}function oa(e){return[...new Set([...Jo,...qo])].every(n=>!uy(e,n))}function uy(e,t){return new RegExp(`^${t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".")}$`).test(e)}function sa(e){return H(e)||e.endsWith("().")||e.endsWith(".")}function dy(e){return V(e.symbol)||gr(e.symbol).length===0}function aa(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 jg(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 Bg(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 Hg(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:h(e.symbol)}}function Cl(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=_a(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 l of a.ranges)if(i>=l.startLine&&i<=l.endLine)return!0;if(s&&a.containers.has(s))return!0;for(let l of Wn(o))if(a.containers.has(l))return!0;return!1}}function Il(e){pa(e),hl(e),Ba(e)}var Wg=[{kind:"symbol-evidence",clearDatabase:Il},{kind:"semantic-provider",clearDatabase:Ti},{kind:"identifier-index",clearDatabase:Ta,clearFile:Ma},{kind:"language-parser",clearDatabase:ua,clearFile:ma},{kind:"source-stripper",clearDatabase:Vs,clearFile:Us},{kind:"ast-tree",clearDatabase:Kr,clearFile:Qr},{kind:"source-text",clearDatabase:Rs,clearFile:_s},{kind:"definition-catalog",clearFile:Ms}],Rl=["symbol-evidence","identifier-index","language-parser","source-stripper","ast-tree","source-text"],_l=["identifier-index","language-parser","source-stripper","ast-tree","source-text"];function vl(e,t){let n=new Set(t.kinds);for(let r of Wg)n.has(r.kind)&&(t.scope.kind==="database"?r.clearDatabase?.(e):r.clearFile?.(e,qg(t.scope.relativePath)))}function Vi(e,t={}){vl(e,{scope:{kind:"database"},kinds:t.semanticProvider===!0?[...Rl,"semantic-provider"]:Rl})}function Ui(e,t,n={}){vl(e,{scope:{kind:"file",relativePath:t},kinds:n.definitions===!0?[..._l,"definition-catalog"]:_l})}function qg(e){return e.replace(/\\/g,"/")}function Nl(e,t){return t.isIgnoredPath(e.relativePath)?we("ignored-file"):qe(e.symbol)?we("module-like-symbol"):Dl(e.symbol)?!e.isFunctionLike&&e.enclosingSymbol&&Dl(e.enclosingSymbol)?we("nested-non-callable-value"):!t.includeTests&&!Ji(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"):Ve(e.symbol)?we("rust-test-module"):!t.includeMembers&&!Ug(e)?we("member"):e.endLine-e.startLine+1<t.minLoc?we("below-min-loc"):{accepted:!0}:we("non-value-symbol")}function Ji(e){return[...new Set([...xa,...Ca])].every(n=>!Vg(e,n))}function we(e){return{accepted:!1,rejectionReason:e}}function Vg(e,t){return new RegExp(`^${t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".")}$`).test(e)}function Dl(e){return K(e)||e.endsWith("().")||e.endsWith(".")}function Ug(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 qt(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 Ll(){return new Map}function El(e,t,n){let r=new Map;for(let i of Oa(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 wl(e,t,n){let r=new Set;for(let i of Fa(e,t))e.isIgnored(i.relative_path)||n.has(i.relative_path)||r.add(i.symbol_id);return r}function zi(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 kl(e){return e?.occurrences??0}function yr(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=Tl(e,t,n);o.occurrences+=r,o.sources.add(i)}function Pl(e,t,n,r,i){if(r<=0)return;let o=Tl(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function Tl(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:l,semantic:c=!0}=t,u=ne(Jg(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),l),m=o?new Set(Sa(e)):new Set,d=a?Ll():El(e,m,u.map(E=>E.symbolId)),p=a?wl(e,u.map(E=>E.symbolId),m):new Set,y=a?u.filter(E=>!p.has(E.symbolId)):u;a?Yg(e,y,d,m):Qg(e,y,d,m);let f=a?y.filter(E=>!zi(d,E.symbolId)):u;nh(e,f,d,{includeTests:i,inactiveBarrelPaths:m,includeSemantic:!a&&c});let b=a?y.filter(E=>!zi(d,E.symbolId)):u;return Kg(e,zg(b,d))}function Jg(e,t){let n=Cl(e),r=[];for(let i of k(e,{scope:t.scope}))try{for(let o of q(e,i))Nl(o,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:a=>e.isIgnored(a),isExcludedRegion:n}).accepted&&r.push(o)}finally{Ui(e,i,{definitions:!0})}return r}function zg(e,t){return e.map(n=>Gg(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 Gg(e,t){let n=t.get(e.symbolId)??new Map,r=kl(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 Kg(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)||cn(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 Qg(e,t,n,r){if(t.length===0)return;let i=new v(e),o=new Set(t.map(l=>l.symbolId)),s=new Set(t.map(l=>l.leaf).filter(Boolean)),a=new Set(i.sourceFiles());for(let l of k(e))a.add(l);i.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:l=>r.has(l)},l=>{o.has(l.target.symbolId)&&(eh(e,l)||yr(n,l.target.symbolId,l.sourceFile,th(l),"source-fallback"))})}function Yg(e,t,n,r){if(t.length===0)return;let i=new v(e),o=Xg(t),s=new Set(i.sourceFiles());for(let u of k(e))s.add(u);let a=new Set(o.keys()),l=new Map,c=u=>{let m=l.get(u);return m||(m=fr(e,u),l.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?Zg(u,m,p,c(u),{permissive:d!=="cross-language-dispatch"}):[]},afterPath:u=>{l.delete(u),Ui(e,u)}},u=>{let m=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&Ml(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:m})||yr(n,u.target.symbolId,u.sourceFile,m,"source-fallback")})}function Xg(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 Zg(e,t,n,r,i){let o=n.filter(l=>l.relativePath===e);if(o.length>0)return o;let s=r.get(t);if(s)for(let l of s){let c=n.filter(u=>Xe(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=>Xe(l,u.relativePath));if(c.length>0&&c.length===n.length)return c}return i.permissive?[...n]:[]}function eh(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&Ml(e,t)}function th(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function Ml(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 nh(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&&!Ji(a)||Pl(n,i.symbolId,a,1,"caller-map")}}}function Gi(e,t={}){let{limit:n=30,scope:r}=t,i=r?`AND def_d.relative_path LIKE '%${r}%'`:"",s=e.all(`SELECT
|
|
634
358
|
gs.symbol,
|
|
635
359
|
COUNT(*) AS ref_count,
|
|
636
360
|
COUNT(DISTINCT ref_d.id) AS file_count,
|
|
@@ -653,18 +377,14 @@ ${m}`,c+=1+m.length,u+=po(m),r+=m.length+1}let d=ug(l);d&&n.push({...d,start:a,e
|
|
|
653
377
|
${i}
|
|
654
378
|
GROUP BY gs.id
|
|
655
379
|
ORDER BY ref_count DESC
|
|
656
|
-
LIMIT ?`,n).filter(a=>!e.isIgnored(a.defined_in)).map(a=>({symbol:a.symbol,shortName:
|
|
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:rh(e,r,n)}function rh(e,t,n){return Le(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>ih(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function ih(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 Ki(e,t,n={}){return Fl(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function Qi(e,t){let n=oh(e,t);return n.length>0?n:sh(e,t)}function Yi(e,t,n={}){return Fl(e,t,n)?.filter(r=>!r.used).map(r=>({symbol:r.symbol,shortName:r.shortName,importedIn:r.importer}))??[]}function oh(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
|
|
657
381
|
FROM mentions m
|
|
658
382
|
JOIN chunks c ON m.chunk_id = c.id
|
|
659
383
|
JOIN documents d ON c.document_id = d.id
|
|
660
384
|
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
661
385
|
WHERE gs.symbol LIKE ?
|
|
662
386
|
AND m.role = 2
|
|
663
|
-
ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:
|
|
664
|
-
FROM documents
|
|
665
|
-
WHERE 1 = 1
|
|
666
|
-
${e.pathExclusionsFor("documents")}
|
|
667
|
-
ORDER BY relative_path`),a=new Set;for(let l of o)if(!e.isIgnored(l.relative_path))for(let c of J(e,l.relative_path))hy(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?g(n.symbol):i,fromFile:l}))}function hy(e,t,n){return!e.sourcePath||n.targetFile&&la(e.sourcePath)!==la(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&xy(t)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function ma(e,t){let n=K(e,t);return n?yy(e,n)??by(e,n)??Sy(e,n):null}function yy(e,t){let r=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 sh(e,t){let n=w(e,t),r=n?.relativePath??null,i=n?L(n.symbol):t.replace(/\(\)$/,""),o=n?qe(n.symbol):!1,s=new Set;for(let a of k(e,{includeIgnored:!1}))for(let l of Y(e,a))ah(l,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 ah(e,t,n){return!e.sourcePath||n.targetFile&&Ol(e.sourcePath)!==Ol(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&mh(t)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function Fl(e,t,n={}){let r=ie(e,t);return r?lh(e,r,n)??(n.semantic===!1?null:ch(e,r))??uh(e,r):null}function lh(e,t,n){let i=e.all(`SELECT DISTINCT
|
|
668
388
|
gs.symbol,
|
|
669
389
|
def_d.relative_path AS from_file,
|
|
670
390
|
imp_d.relative_path AS importer,
|
|
@@ -690,11 +410,11 @@ ${m}`,c+=1+m.length,u+=po(m),r+=m.length+1}let d=ug(l);d&&n.push({...d,start:a,e
|
|
|
690
410
|
LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
691
411
|
WHERE imp_d.relative_path = ?
|
|
692
412
|
AND m.role = 2
|
|
693
|
-
ORDER BY def_d.relative_path, gs.symbol`,t).filter(
|
|
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 ch(e,t){let n=gn(e,t);return n.length>0?n.map(r=>{let i=Al(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 uh(e,t){return Y(e,t).map(n=>{let r=Al(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 Al(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 Ol(e){return e.replace(/\\/g,"/")}function mh(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function Xi(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 l=r[a],c=i[a];if(l.enclosingSymbol&&o.has(l.enclosingSymbol)){o.get(l.enclosingSymbol).children.push(c);continue}let u=null,m=1/0;for(let d of i)if(d!==c&&d.startLine<=c.startLine&&d.endLine>=c.endLine){if(d.startLine===c.startLine&&d.endLine===c.endLine&&!Ls(d.symbol,c.symbol))continue;let y=d.endLine-d.startLine;y<m&&(m=y,u=d)}u?u.children.push(c):s.push(c)}return s}function Zi(e,t){let n=w(e,t);return n?new v(e).definitionsForFile(n.relativePath).filter(i=>i.symbol!==n.symbol).filter(i=>Ns(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 eo(e,t){let n=w(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
|
|
694
414
|
FROM mentions m
|
|
695
415
|
JOIN chunks c ON m.chunk_id = c.id
|
|
696
416
|
WHERE m.symbol_id = ?
|
|
697
|
-
AND m.role != 1`,n.symbolId);return[{name:
|
|
417
|
+
AND m.role != 1`,n.symbolId);return[{name:h(n.symbol),count:r?.file_count??0}]}function to(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
|
|
698
418
|
FROM mentions m
|
|
699
419
|
JOIN chunks c ON m.chunk_id = c.id
|
|
700
420
|
JOIN documents d ON c.document_id = d.id
|
|
@@ -711,7 +431,7 @@ ${m}`,c+=1+m.length,u+=po(m),r+=m.length+1}let d=ug(l);d&&n.push({...d,start:a,e
|
|
|
711
431
|
AND m.role != 1
|
|
712
432
|
AND def_d.id != d.id
|
|
713
433
|
GROUP BY d.id
|
|
714
|
-
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
|
|
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 no(e,t={}){return dh(e,t).map(n=>({name:h(n.symbol),count:n.file_count}))}function dh(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
|
|
715
435
|
FROM mentions m
|
|
716
436
|
JOIN chunks c ON m.chunk_id = c.id
|
|
717
437
|
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
@@ -730,7 +450,7 @@ ${m}`,c+=1+m.length,u+=po(m),r+=m.length+1}let d=ug(l);d&&n.push({...d,start:a,e
|
|
|
730
450
|
GROUP BY gs.id
|
|
731
451
|
HAVING file_count > 1
|
|
732
452
|
ORDER BY file_count DESC
|
|
733
|
-
LIMIT ?`,n)}function
|
|
453
|
+
LIMIT ?`,n)}function ro(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
|
|
734
454
|
FROM mentions m
|
|
735
455
|
JOIN chunks c ON m.chunk_id = c.id
|
|
736
456
|
JOIN documents d ON c.document_id = d.id
|
|
@@ -750,7 +470,7 @@ ${m}`,c+=1+m.length,u+=po(m),r+=m.length+1}let d=ug(l);d&&n.push({...d,start:a,e
|
|
|
750
470
|
${i}
|
|
751
471
|
GROUP BY d.id
|
|
752
472
|
ORDER BY symbol_count DESC
|
|
753
|
-
LIMIT ?`,n).filter(
|
|
473
|
+
LIMIT ?`,n).filter(s=>!e.isIgnored(s.relative_path)).map(s=>({name:s.relative_path,count:s.symbol_count}))}function io(e,t,n){let r=ie(e,t)??t,i=ie(e,n)??n,o=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
|
|
754
474
|
FROM global_symbols gs
|
|
755
475
|
WHERE (
|
|
756
476
|
-- Defined in file1, referenced in file2
|
|
@@ -782,7 +502,7 @@ ${m}`,c+=1+m.length,u+=po(m),r+=m.length+1}let d=ug(l);d&&n.push({...d,start:a,e
|
|
|
782
502
|
JOIN documents d ON c.document_id = d.id
|
|
783
503
|
WHERE m.symbol_id = gs.id AND m.role != 1 AND d.relative_path = ?
|
|
784
504
|
)
|
|
785
|
-
)`,r,i,i,r);return{file1:r,file2:i,sharedSymbols:
|
|
505
|
+
)`,r,i,i,r);return{file1:r,file2:i,sharedSymbols:o?.shared??0}}function oo(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
|
|
786
506
|
def_d.relative_path AS file1,
|
|
787
507
|
ref_d.relative_path AS file2,
|
|
788
508
|
COUNT(DISTINCT gs.id) AS shared
|
|
@@ -804,12 +524,12 @@ ${m}`,c+=1+m.length,u+=po(m),r+=m.length+1}let d=ug(l);d&&n.push({...d,start:a,e
|
|
|
804
524
|
${i}
|
|
805
525
|
GROUP BY def_d.id, ref_d.id
|
|
806
526
|
ORDER BY shared DESC
|
|
807
|
-
LIMIT ?`,n).filter(
|
|
808
|
-
WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:
|
|
809
|
-
`);if(r>=n&&r-n<=12)return
|
|
810
|
-
`);let a=[new RegExp(`\\bdef\\s+${
|
|
811
|
-
`)}return
|
|
812
|
-
`)}function
|
|
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,l=[];function c(m,d){if(d>r)return;if(a.has(m)){let y=l.indexOf(m);if(y!==-1){let f=l.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:ph(E)}))}return}if(s.has(m))return;s.add(m),a.add(m),l.push(m);let p=i.get(m);if(p)for(let y of p)c(y,d+1);l.pop(),a.delete(m)}let u=new Set;for(let m of i.keys())s.has(m)||c(m,0);return o.sort((m,d)=>m.kind!==d.kind?m.kind==="real"?-1:1:m.path.length-d.path.length),o}function ph(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)||$l(t,n)||$l(n,t)||jl(t,n)||jl(n,t)||ue(t)==="entry"||ue(n)==="entry"?"module-hierarchy":"real"}function $l(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 jl(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 so(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=>fh(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 fh(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),l=o.crossFileCallerMap(a,{semantic:s}),c=new Set(l.keys());for(let f of o.frameworkReferencedSymbolIds(a))c.add(f);let u=o.symbolsWithNonSelfCallees(a,{additive:!1,semantic:s}),m=a.filter(f=>!c.has(f.symbolId)).filter(f=>!u.has(f.symbolId)),d=o.sourceFallbackCallerFiles(m);for(let f of d.keys())c.add(f);let p=m.filter(f=>!c.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 lo={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"},ao=new Map;for(let[e,t]of Object.entries(lo))ao.set(t.toLowerCase(),Number(e));function gh(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=ao.get(n);if(r!==void 0)return r;for(let[i,o]of ao)if(i.includes(n))return o;return null}function co(e,t,n={}){let{scope:r,limit:i=100}=n,o=gh(t);return o===null?[]:Bl(e,r).map(a=>({row:a,resolvedKind:Hl(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:l})=>({symbol:a.symbol,shortName:h(a.symbol),kind:l,kindName:lo[l]??"Unknown",relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function uo(e,t={}){let n=new Map;for(let r of Bl(e,t.scope)){let i=Hl(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:lo[r]??"Unknown",count:i}))}function Bl(e,t){return Le(e,{scope:t}).map(hh)}function hh(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 Hl(e){return e.kind!==null&&e.kind!==0?yh(e.kind,e.symbol,e.documentation):bh(e.symbol,e.documentation,e.enclosing_symbol)}function yh(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 bh(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 mo(e,t={}){let{limit:n=10,scope:r,minDepth:i=3}=t,o=ae(e,r),s=new Map,a=[],l=new Map,c=new Map,u=new Set,m=[],d=0;for(let R of o.keys()){if(l.has(R))continue;let _=[],G=(o.get(R)??new Set).values();for(l.set(R,d),c.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,c.set(A.node,Math.min(c.get(A.node),c.get(_t)))}let De=A.iter.next();if(De.done){if(c.get(A.node)===l.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(l.has(Ne))u.has(Ne)&&c.set(A.node,Math.min(c.get(A.node),l.get(Ne)));else{l.set(Ne,d),c.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 po(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 l=Q(r.symbol);if("kind"in l)return i;let c=l.descriptors;if(c.length<=1)return i;let u=[i[0]];for(let m=c.length-2,d=1;m>=0;m--,d++){let y=c.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 fo(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=qt(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 Wl(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 go(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 Sh(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 ql(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 l=Math.sqrt(o)*Math.sqrt(s),c=l>0?i/l:0,u=Sh(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:c,significantShared:m,trivialShared:d}}function ho(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=Ih(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!K(o.symbol))return[];let s=xh(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):_h(e,t,{minSimilarity:r,limit:i})}function xh(e,t,n,r){let i=Ul(e,{minCallees:3,excludeSymbol:t.symbol,scanLimit:r.scanLimit,semantic:r.semantic}),o=go([t,...i].map(a=>a.callees)),s=[];for(let a of i){if(a.callees.size<3)continue;let l=Vl(t,a,o,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0});l&&s.push(l)}return s.sort((a,l)=>l.similarity-a.similarity),s}function Vl(e,t,n,r){let{similarity:i,significantShared:o}=ql(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,l=Ul(e,{minCallees:o,scope:i,scanLimit:a,semantic:t.semantic!==!1}),c=go(l.map(f=>f.callees)),u=new Map;for(let f of l)for(let b of f.callees)u.set(b,(u.get(b)??0)+1);let m=Math.max(8,Math.ceil(Math.sqrt(l.length))),d=new Map;for(let f=0;f<l.length;f+=1)for(let b of l[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<l.length;f+=1){let b=l[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=l[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=Vl(b,F,c,{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 Ch=["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 Ih(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:Jl(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}function Ul(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),l=s.calleeMap(a,{semantic:t.semantic!==!1});return a.map(c=>({symbol:c.symbol,file:c.relativePath,callees:Jl((l.get(c.symbolId)??[]).map(u=>u.symbol)),paramCount:s.callableSignature(c)?.paramCount??-1})).filter(c=>c.callees.size>=n)}function Jl(e){return new Set([...e].filter(t=>!Rh(t)))}function Rh(e){return Ch.some(t=>e.includes(t))}function _h(e,t,n){let r=vh(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[];for(let s of Nh(e)){if(s.symbol===r.symbol||s.tokens.size<3)continue;let a=Cn(r.tokens,s.tokens);if(a.size<2)continue;let l=new Set([...r.tokens,...s.tokens]),c=l.size>0?a.size/l.size:0;c<i||o.push({symbolA:r.symbol,shortNameA:h(r.symbol),fileA:r.file,symbolB:s.symbol,shortNameB:h(s.symbol),fileB:s.file,similarity:c,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 vh(e,t){let n=w(e,t);if(!n||!K(n.symbol))return null;let r=Dh(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function Dh(e,t){let n=L(t.symbol),r=zl(e,t.relativePath,t.startLine,t.endLine,n),i=Gl(r,n);return i.size>0?i:null}function Nh(e){let t=new v(e);return t.scopedDefinitions().filter(n=>n.isFunctionLike).filter(n=>t.fileKind(n.relativePath)!=="test").filter(n=>!Ve(n.symbol)).map(n=>({symbol:n.symbol,file:n.relativePath,tokens:Gl(zl(e,n.relativePath,n.startLine,n.endLine,n.leaf),n.leaf)})).filter(n=>n.tokens.size>0)}function zl(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*\\(`)],l=s.findIndex(c=>a.some(u=>u.test(c)));if(l>=0){let c=l;for(let u=l+1;u<s.length&&u<=l+8;u++){let m=s[u]??"";if(u>l&&Eh(m)||(c=u,m.trim()===""&&u>l+1))break}return s.slice(l,c+1).join(`
|
|
531
|
+
`)}return s.slice(n,Math.min(s.length,n+8)).join(`
|
|
532
|
+
`)}function Gl(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=Lh(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 Lh(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 Eh(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 yo(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),a=wh(e,{scope:i,minDeps:s}),l=[];if(o){let c=a.find(u=>u.file.includes(o));if(!c)return[];for(let u of a){if(u.file===c.file)continue;let m=Kl(c,u,n);m&&l.push(m)}}else for(let c=0;c<a.length;c++){for(let u=c+1;u<a.length;u++){let m=Kl(a[c],a[u],n);m&&l.push(m)}if(l.length>r*5)break}return l.sort((c,u)=>u.similarity-c.similarity),l.slice(0,r)}function wh(e,t){let{scope:n,minDeps:r}=t,i=ae(e,n),o=kh(i),s=[];for(let[a,l]of i)l.size>=r&&s.push({file:a,deps:new Set([...l].filter(c=>!o.has(c)))});return s}function kh(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 Kl(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=Wl(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 bo(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=ae(e,i),l=jh(a,o,s);if(l.length===0)return[];let c=Ph(l);return c.length<2?[]:$h(Oh(c,n,r),r)}function Ph(e){let t=Th(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 Th(e){let{nodeFreq:t,tailFreq:n}=Mh(e),r=e.length*.9,i=e.length*.8,o=new Set;for(let[a,l]of t)l>r&&o.add(a);for(let[a,l]of n)l>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 l=a.split("/").pop()??"";s.includes(l)&&o.add(a)}return o}function Mh(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 Oh(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=Fh(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 Fh(e,t,n){if(!Ah(e.filtered,t.filtered))return null;let{distance:r,ops:i}=Bh(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(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:s,editDistance:r,divergencePoints:a,commonPrefix:Hh(e.original,t.original),commonSuffix:Wh(e.original,t.original)}}function Ah(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function $h(e,t){let n=[];for(let r of e)if(n.some(o=>Ql(r.chainA,o.chainA)&&Ql(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function jh(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;Yl(e,o,[o],new Set([o]),t,n,r,500)}return r}function Yl(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 l=e.get(t);if(!l||l.size===0){n.length>=i&&s.push([...n]);return}let c=!1;for(let u of l)if(!r.has(u)&&(r.add(u),n.push(u),Yl(e,u,n,r,i,o,s,a),n.pop(),r.delete(u),c=!0,s.length>=a))return;!c&&n.length>=i&&s.push([...n])}function Bh(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 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 Hh(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 Wh(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 Ql(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),l=a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),c=ne(l,s),u=a.calleeMap(c,{semantic:t.semantic!==!1}),m=[];for(let d of c){let p=qh(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 qh(e,t,n){let r=new Set(t.map(a=>a.symbol));if(r.size<n)return null;let i=Vh(r,t),o=Uh(r,i);if(o.length<2)return null;let s=Jh(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 Vh(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 Uh(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 l of t.get(a)??[])n.has(l)||s.push(l)}}r.push(o)}return r}function Jh(e,t){return e.filter(n=>n.size>=3).map(n=>zh(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function zh(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 o=e.size*r.size,s=o>0?1-i/o:1;return{callees:[...e].map(h),isolation:s}}function So(e,t,n={}){let{maxDepth:r=5,scope:i}=n,o=w(e,t);if(!o)return[];let s=[],a=new Set([o.symbolId]),l=new Set,c=[o];for(let u=1;u<=r&&c.length!==0;u++){let m=[];for(let d of c)for(let p of Gh(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(l.has(y))continue;l.add(y),s.push({symbol:p.symbol,shortName:p.shortName,file:p.file,depth:u}),p.symbolId!==null&&p.symbolMatch&&m.push(p.symbolMatch)}c=m}return s.sort((u,m)=>u.depth-m.depth||u.file.localeCompare(m.file)),s}function Gh(e,t,n){let r=ye(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)),o=[];for(let c of Kh(e,t,n)){if(i.has(c))continue;let u=q(e,c),m=u.length>0?de(u,u[0].startLine):null;o.push({symbol:m?.symbol??c,file:c})}let s=[...r,...o],a=[],l=new Set;for(let c of s){let u=Tt(e,c.symbol);if(!u){let d=`${c.file}|${c.symbol}`;if(l.has(d))continue;l.add(d),a.push({symbolId:null,symbol:c.symbol,shortName:h(c.symbol),file:c.file,symbolMatch:null});continue}if(u.symbolId===t.symbolId||e.isIgnored(u.relativePath)||!Qh(u.symbol))continue;let m=`${u.symbolId}|${u.relativePath}`;l.has(m)||(l.add(m),a.push({symbolId:u.symbolId,symbol:u.symbol,shortName:h(u.symbol),file:u.relativePath,symbolMatch:u}))}return a}function Kh(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
|
|
813
533
|
FROM mentions m
|
|
814
534
|
JOIN chunks c ON m.chunk_id = c.id
|
|
815
535
|
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
@@ -817,30 +537,30 @@ ${m}`,c+=1+m.length,u+=po(m),r+=m.length+1}let d=ug(l);d&&n.push({...d,start:a,e
|
|
|
817
537
|
AND m.role != 1
|
|
818
538
|
AND c.document_id != ?
|
|
819
539
|
${e.pathExclusionsFor("consumer_d")}
|
|
820
|
-
${r}`,...i).map(
|
|
540
|
+
${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function Qh(e){let t=ee(e);return t==="method"||t==="type"||e.endsWith("().")}function xo(e,t,n={}){let r=ie(e,t);if(!r)return null;let i=Yh(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=Xh(e,i.relative_path),l=n.semantic===!1?new Map:Ht(e,a);for(let c of a){let u=Zh(e,i,c,l.get(c.symbolId)??new Set);s+=u,o.push({symbol:c.symbol,shortName:h(c.symbol),startLine:c.startLine,endLine:c.endLine,externalConsumers:u,riskLevel:ey(u)})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s}}function Yh(e,t){return e.get(`SELECT id, relative_path FROM documents
|
|
821
541
|
WHERE relative_path = ?
|
|
822
542
|
${e.pathExclusionsFor("documents")}
|
|
823
|
-
LIMIT 1`,t)??null}function
|
|
543
|
+
LIMIT 1`,t)??null}function Xh(e,t){return new v(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function Zh(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
824
544
|
FROM mentions m
|
|
825
545
|
JOIN chunks c ON m.chunk_id = c.id
|
|
826
546
|
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
827
547
|
WHERE m.symbol_id = ?
|
|
828
548
|
AND m.role != 1
|
|
829
|
-
AND c.document_id != ?`,n.symbolId,t.id);return new Set([...i.map(
|
|
830
|
-
`)).map(
|
|
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 ey(e){return e>10?"high":e>0?"medium":"low"}import{execFileSync as Co}from"child_process";function br(e,t={}){let n=Vt(e,t);return n.note?ty(n.note,n.changedFileLines):n.changedFiles.length===0?ny(n.changedFileLines):xr(n.changedFiles,[Sr(e,n.changedFiles,n.changedFiles)])}function Vt(e,t={}){let{base:n="HEAD"}=t;try{let r=ry(e.config.projectRoot,n);return{changedFileLines:r,changedFiles:iy(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(c=>r.definitionsForFile(c)).filter(cy).sort((c,u)=>c.relativePath.localeCompare(u.relativePath)||c.startLine-u.startLine),l=Ht(e,a);for(let c of a)oy(e,c,n,i,o,s,l.get(c.symbolId)??new Set);return{changedSymbols:o,consumerEntries:[...s.entries()].map(([c,u])=>({file:c,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 l of s.symbols)a.add(l)}let i=ly(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:i.length}}}function ty(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function ny(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 ry(e,t){let n=Co("git",["diff","--name-only",t],{encoding:"utf-8",cwd:e,timeout:1e4}),r=Co("git",["diff","--name-only","--cached",t],{encoding:"utf-8",cwd:e,timeout:1e4}),i=Co("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 iy(e,t){let n=[];for(let r of t){let i=e.get(`SELECT relative_path FROM documents
|
|
831
551
|
WHERE relative_path LIKE ?
|
|
832
|
-
LIMIT 1`,`%${r}`);i&&!e.isIgnored(i.relative_path)&&n.push(i.relative_path)}return n}function
|
|
552
|
+
LIMIT 1`,`%${r}`);i&&!e.isIgnored(i.relative_path)&&n.push(i.relative_path)}return n}function oy(e,t,n,r,i,o,s){let a=Math.max(sy(e,t.symbolId),s.size);if(!uy(t,a))return;let l=h(t.symbol);i.push({symbol:t.symbol,shortName:l,file:t.relativePath,fanIn:a});for(let c of ay(e,t.symbolId,n))Xl(e,r,o,c,l);for(let c of s)Xl(e,r,o,c,l)}function sy(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS fan_in
|
|
833
553
|
FROM mentions m
|
|
834
554
|
JOIN chunks c ON m.chunk_id = c.id
|
|
835
555
|
WHERE m.symbol_id = ?
|
|
836
|
-
AND m.role != 1`,t)?.fan_in??0}function
|
|
556
|
+
AND m.role != 1`,t)?.fan_in??0}function ay(e,t,n){return n.length===0?[]:e.all(`SELECT DISTINCT ref_d.relative_path
|
|
837
557
|
FROM mentions m
|
|
838
558
|
JOIN chunks c ON m.chunk_id = c.id
|
|
839
559
|
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
840
560
|
WHERE m.symbol_id = ?
|
|
841
561
|
AND m.role != 1
|
|
842
562
|
AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
|
|
843
|
-
${e.pathExclusionsFor("ref_d")}`,t,...n).map(i=>i.relative_path)}function
|
|
563
|
+
${e.pathExclusionsFor("ref_d")}`,t,...n).map(i=>i.relative_path)}function Xl(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 ly(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function cy(e){return!(qe(e.symbol)||e.parentTypeName!==null&&!te(e.symbol))}function uy(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 Io(e,t){if(e===t)return"ok";let n=Cr(e),r=Cr(t);return n&&r?my(n,r)?"ok":"violation":dy(e,t)}function Zl(e,t){let n=Cr(bt(e)),r=Cr(bt(t));return!!n&&!!r}function Cr(e){return/^src\/([^/]+)$/.exec(e)?.[1]??null}function my(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 dy(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=Sy(e,n);return hy([...py(e,s,a,{semantic:i}),...fy(s),...gy(s,r)])}function py(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 l of s)if(!Fe(l)&&!a.has(l)){if(r.semantic&&vy(e,o,l)||Dy(e,o,l)||Ny(e,o,l)||_y(l)||Ey(e,o,l)||Ly(l))continue;i.push({file:o,kind:"unused-import",description:`Depends on ${l} but references none of its symbols`,dep:l})}}return i}function fy(e){let t=[],n=Ry(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;(Io(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 gy(e,t){let n=[];for(let[r,i]of yy(e)){let o=i.filter(a=>!Fe(a));if(o.length<t)continue;let s=by(e,o);for(let a of o)for(let l of e.get(a)??[])Fe(l)||(s.get(l)??0)===1&&Dn.dirname(l)!==r&&Dn.dirname(l)!==Dn.dirname(r)&&(Zl(a,l)||n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${l}`,dep:l}))}return n}function hy(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 yy(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 by(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 Sy(e,t){let n=new Map;return xy(e,n,t),Iy(e,n),n}function xy(e,t,n){for(let r of Cy(e,n))ec(e,t,r.from_file,r.to_file)}function Cy(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
|
|
844
564
|
FROM mentions m
|
|
845
565
|
JOIN chunks c ON m.chunk_id = c.id
|
|
846
566
|
JOIN documents d1 ON c.document_id = d1.id
|
|
@@ -856,25 +576,24 @@ ${m}`,c+=1+m.length,u+=po(m),r+=m.length+1}let d=ug(l);d&&n.push({...d,start:a,e
|
|
|
856
576
|
WHERE d1.id != d2.id
|
|
857
577
|
AND m.role != 1
|
|
858
578
|
${e.pathExclusionsFor("d1","d2")}
|
|
859
|
-
${n}`)}function
|
|
860
|
-
|
|
579
|
+
${n}`)}function Iy(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)||ec(e,t,r.sourceFile,r.target.relativePath))})}function ec(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 Ry(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||Io(o,a))continue;let l=`${o}->${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 _y(e){return e.includes("types")||e.endsWith(".d.ts")}function vy(e,t,n){let r=gn(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function Dy(e,t,n){let r=Y(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function Ny(e,t,n){let r=Y(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function Ly(e){return e.endsWith(".vue")}function Ey(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"||wy(Dn.basename(e)))}function wy(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 tc=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)Py(e,a,t.relativePath,s)?i++:Ro(e,a,s)?o++:r.push(a);return{realConsumers:r,barrelConsumers:i,importOnlyConsumers:o}}function Ro(e,t,n){if(!n)return!1;let r=P(t);if(!r)return!1;let i=tc.get(e,t,()=>ky(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function nc(e){tc.invalidateAll(e)}function ky(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=(l,c)=>{let u=c||s.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 m of l.children)a(m,u)};return a(o.rootNode,!1),{importedLeaves:r,usedLeaves:i}}function Py(e,t,n,r){if(!r)return!1;let i=T(e,t);if(!i)return!1;let o=ca(e,t);if(o.length===0)return!1;let s=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`\\b${s}\\b`),l=i.split(`
|
|
580
|
+
`),c=0;for(let u=0;u<l.length;u++){if(!a.test(l[u]??""))continue;if(c++,!o.find(d=>d.startLine<=u&&u<=d.endLine))return!1}return c>0}function wn(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new v(e),a=By(s.fileDependencyGraph(n));return Ut({candidates:()=>My(s,n,r),orderCandidates:hr,scanLimit:o,prepare:l=>({callerFileMap:Ln(s,l,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(l,c)=>Ty(e,s,l,c),orderResults:(l,c)=>c.callerFanIn-l.callerFanIn||c.loc-l.loc,limit:i})}function Ty(e,t,n,r){let i=Oy(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=Fy(e,n.symbolId,o);if(!s)return null;let a=Ay(t,e,o,n.symbol,s);if(a&&Ve(a.symbol))return null;let l=$y(r.callerFileMap,r.reverseFanIn,o,a);return l<=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:l}}function My(e,t,n){return e.productionCallableDefinitions({scope:t,minLoc:2,maxLoc:n,requireFunctionLikeSymbol:!0})}function Oy(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 Fy(e,t,n){return e.get(`SELECT c.start_line, c.end_line
|
|
861
581
|
FROM mentions m
|
|
862
582
|
JOIN chunks c ON m.chunk_id = c.id
|
|
863
583
|
JOIN documents d ON c.document_id = d.id
|
|
864
584
|
WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
|
|
865
|
-
LIMIT 1`,t,n)}function
|
|
866
|
-
`),
|
|
867
|
-
`),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 NS(e,t){let n=P(e,t.relativePath);if(!n)return!1;let r=w(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`\\b${i}\\b`),o=n.split(`
|
|
868
|
-
`);for(let a=0;a<o.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&s.test(o[a]??""))return!0;return!1}function ES(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 $t(e){return e.endLine-e.startLine+1}function ol(...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 Fn(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:s}=t??{},{definitions:o,callerMap:a,calleeMap:l}=DS(e,n,s);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(y=>y.file!==c.relativePath),h=new Set(f.map(y=>`${y.symbol}|${y.file}`)).size,p=new Set(m.map(y=>`${y.symbol}|${y.file}`)).size;return{symbol:c.symbol,shortName:g(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 DS(e,t,n){let r=new v(e),i=LS(r.productionCallableDefinitions({scope:t,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof n=="number"&&n>0}),n);return{definitions:i,callerMap:r.crossFileCallerMap(i),calleeMap:r.calleeMap(i)}}function LS(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}import{getHeapStatistics as wS}from"v8";var kS=64*1024*1024;function Kr(e,t={}){Fo(e),t.semanticProvider===!0&&Tr(e),Us(e),Ro(e),Fs(e),ds(e),ns(e)}function Yr(){let e=globalThis.gc;if(!e)return;let t=wS();t.heap_size_limit-t.used_heap_size<kS||e()}var PS=50,OS=75e3,MS=5e3,al=2500,ll=["overview","dead","isolated","cycles","similar","extract-candidates","wrapper-candidates","passthrough-candidates","stale-abstractions","drift","complexity-hotspots"],TS={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:fl(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:gl(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:hl(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:yl(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:bl(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:Sl(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:xl(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:_l(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:Il(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:Rl(e,t,n)})};function cl(e,t={}){return dl(e,t.full===!0,(n,r)=>{let i=FS(e,t.scope,n,r);return pl(i)})}function ul(e,t,n={}){return dl(e,n.full===!0,(r,i)=>TS[t](e,n.scope,i,r))}function dl(e,t,n){let r=nn(e),i=WS(r,t);try{return n(r,i)}finally{Kr(e,{semanticProvider:!0}),Yr()}}function ml(e){let t=de(e,"overview"),n={statsResult:t.statsResult,warnings:t.warnings,dead:de(e,"dead").dead,isolated:de(e,"isolated").isolated,realCycleCount:de(e,"cycles").realCycleCount,similarCount:de(e,"similar").similarCount,extractCount:de(e,"extract-candidates").extractCount,wrappers:de(e,"wrapper-candidates").wrappers,passthroughs:de(e,"passthrough-candidates").passthroughs,stale:de(e,"stale-abstractions").stale,drift:de(e,"drift").drift,complexity:de(e,"complexity-hotspots").complexity};return pl(n)}function de(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function pl(e){let t=BS(e);return{score:HS(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 FS(e,t,n,r){let i=AS(e,t,r),s=$S(e,t,r),o=jS(e,t,r);return{statsResult:n,warnings:r.warnings,...i,...s,...o}}function AS(e,t,n){return{dead:fl(e,t,n),isolated:gl(e,t,n),realCycleCount:hl(e,t,n)}}function $S(e,t,n){return{similarCount:yl(e,t,n),extractCount:bl(e,t,n),wrappers:Sl(e,t,n),passthroughs:xl(e,t,n),stale:_l(e,t,n)}}function jS(e,t,n){return{drift:Il(e,t,n),complexity:Rl(e,t,n)}}function fl(e,t,n){return be(e,n,"dead",()=>{let r=vn(e,{scope:t,minLoc:3,skipBarrels:!0});return An(JS(e,r.symbols))})}function gl(e,t,n){return be(e,n,"isolated",()=>{let r=En(e,{scope:t,minLoc:3});return An(qS(e,r))})}function hl(e,t,n){return be(e,n,"cycles",()=>Nn(e,{scope:t}).filter(i=>i.kind==="real").length)}function yl(e,t,n){return be(e,n,"similar",()=>Dn(e,{scope:t,minSimilarity:.6,limit:50,minCallees:4,scanLimit:n.candidateScanLimit}).length)}function bl(e,t,n){return be(e,n,"extract-candidates",()=>Ln(e,{scope:t,minLoc:15,minCallees:5,limit:50,scanLimit:n.candidateScanLimit}).length)}function Sl(e,t,n){return be(e,n,"wrapper-candidates",()=>An(On(e,{scope:t,maxLoc:15,limit:50,scanLimit:n.candidateScanLimit})))}function xl(e,t,n){return be(e,n,"passthrough-candidates",()=>An(Mn(e,{scope:t,maxLoc:15,limit:50,scanLimit:n.candidateScanLimit})))}function _l(e,t,n){return be(e,n,"stale-abstractions",()=>{let r=Tn(e,{scope:t,minLoc:3,limit:50,scanLimit:n.candidateScanLimit}),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 Il(e,t,n){return be(e,n,"drift",()=>{let r=kn(e,{scope:t});return{count:r.unusedImports+r.layerViolations,unusedImports:r.unusedImports,layerViolations:r.layerViolations}})}function Rl(e,t,n){return be(e,n,"complexity-hotspots",()=>{let r=Fn(e,{scope:t,minLoc:10,limit:10,scanLimit:n.candidateScanLimit});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score})),extremeCount:r.filter(i=>i.score>PS).length}})}function BS(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 HS(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 WS(e,t){return e.symbols>=OS||e.documents>=MS?t?{candidateScanLimit:void 0,releaseCachesBetweenPhases:!0,warnings:["Large index detected; running unbounded health analyses because --full was supplied."]}:{candidateScanLimit:al,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${al} symbols. Run "scip-query health --full" for unbounded candidate counts.`]}:{candidateScanLimit:void 0,releaseCachesBetweenPhases:!0,warnings:[]}}function US(e,t){t.releaseCachesBetweenPhases&&(il(e),Kr(e),Yr())}function be(e,t,n,r){VS(n);try{return r()}finally{US(e,t)}}function VS(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function JS(e,t){return t.filter(n=>!Ke(e,n.relativePath)&&!kt(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function qS(e,t){return t.filter(n=>!Ke(e,n.relativePath)&&!kt(e,n.symbol,n.relativePath))}function An(e){return{count:e.length,loc:e.reduce((t,n)=>t+n.loc,0)}}function Cl(e,t,n){let r=L(e,t),i=L(e,n);if(!r||!i)return null;let s=new Set(Z(e,r).map(p=>p.symbol)),o=new Set(Z(e,i).map(p=>p.symbol)),a=[];for(let p of s)o.has(p)&&a.push(p);let l=[];for(let p of s)o.has(p)||l.push(p);let c=[];for(let p of o)s.has(p)||c.push(p);let u=new Set([...s,...o]),d=u.size>0?a.length/u.size:0,m;u.size===0?m="Neither function calls other tracked symbols. There is no callee-pattern evidence for consolidation; inspect the source bodies directly.":a.length===0?m="These functions do not share any callees. They are not a callee-based consolidation candidate.":l.length===0&&c.length===0?m="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?m="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.":c.length===0?m="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&&c.length<=2?m=`Create a shared function with the ${a.length} common callees. Pass the ${l.length+c.length} divergent callees as parameters or strategy callbacks.`:m=`Extract the ${a.length} shared callees into a common helper. Each function calls the helper plus its own unique logic (${l.length} callees in A, ${c.length} in B).`;let f=r.endLine-r.startLine+1,h=i.endLine-i.startLine+1;return{symbolA:{symbol:r.symbol,shortName:g(r.symbol),file:r.relativePath,loc:f},symbolB:{symbol:i.symbol,shortName:g(i.symbol),file:i.relativePath,loc:h},similarity:d,sharedCallees:a.map(g),uniqueToA:l.map(g),uniqueToB:c.map(g),consolidationStrategy:m}}import{readFileSync as vl}from"fs";import{extname as zS,join as Nl}from"path";function El(e,t,n={}){let{context:r=0}=n,i=GS(t);if(i)return YS(e,i.filePath,i.startLine,i.endLine,r);let s=L(e,t);return s?KS(e,s,r):null}function GS(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 KS(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=Nl(e.config.projectRoot,t.relativePath),s;try{s=vl(i,"utf-8")}catch{return null}let o=s.split(`
|
|
869
|
-
`),a
|
|
870
|
-
`)
|
|
871
|
-
`),u
|
|
872
|
-
`);return{symbol:`${o.relative_path}:${n}-${r}`,shortName:`${o.relative_path}:${n}-${r}`,relativePath:o.relative_path,startLine:u,endLine:d,language:o.language??Dl(o.relative_path),source:m}}function Dl(e){switch(zS(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 QS}from"fs";import{join as XS}from"path";function Ll(e,t){let n=L(e,t);if(!n)return null;let r=new v(e),i=rx(ex(e,n.relativePath,n.startLine,n.endLine),ZS(e,n.relativePath)),s=n.endLine-n.startLine+1,a=r.calleeMap([n],{additive:!0}).get(n.symbolId)??[],l=new Set(a.map(c=>c.symbol));return{symbol:n.symbol,shortName:g(n.symbol),relativePath:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:s,branches:i,cyclomaticEstimate:i+1,calleeCount:l.size,fanIn:tx(e,n.symbolId),fanOut:nx(a,n.relativePath)}}function ZS(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function ex(e,t,n,r){try{return QS(XS(e.config.projectRoot,t),"utf-8").split(`
|
|
585
|
+
LIMIT 1`,t,n)}function Ay(e,t,n,r,i){let o=e.definitionsForFile(n),s=jy(t,n,r,i.start_line,i.end_line);return de(o,s)}function $y(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 Hy(t,n)}function jy(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 By(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 Hy(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 ic(e,t,n,r){let i=P(t);if(!i)return!0;let o=B(e,t);if(!o)return!0;let s=rc.get(o);return s||(s=Wy(o,i),rc.set(o,s)),s.get(`${n}:${r}`)??!0}var rc=new WeakMap;function Wy(e,t){let n=en(t),r=new Map,i=o=>{n.has(o.type)&&r.set(`${o.startPosition.row}:${o.endPosition.row}`,qy(o,t));for(let s of o.children)i(s)};return i(e.rootNode),r}function qy(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 l=a.namedChildren.filter(m=>m.type!=="comment"),c=e.namedChildren.find(m=>m.type==="parameters"||m.type==="formal_parameters");if(!c)return!1;let u=[];for(let m of c.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(l.length!==u.length)return!1;for(let m=0;m<u.length;m+=1){let d=l[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:()=>Jy(s,n,r),orderCandidates:hr,scanLimit:o,prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,l)=>Vy(e,a,l.get(a.symbolId)??[]),orderResults:(a,l)=>a.loc-l.loc||a.file.localeCompare(l.file),limit:i})}function Vy(e,t,n){let r=Uy(n);if(r.size!==1||!ic(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 Uy(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 Jy(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??{},l=t?.semantic!==!1,c=new v(e),u=c.scopedDefinitions(n),m=ib(c,n),d=ne(zy(e,c,u,{minLoc:r,maxLoc:i}).sort((x,$)=>j($)-j(x)||x.relativePath.localeCompare($.relativePath)),a),p=Gy(c,d,{semantic:l}),y=Xy(e,c,u,d,{semantic:l}),f=Ky(d);return Qy(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=>sb(x.definition,x.realConsumers.length,m)).map(x=>Yy(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 zy(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=>!ob(i.symbol)).filter(i=>!t.hasSuppressionComment(i))}function Gy(e,t,n){return Ln(e,t,{semantic:n.semantic})}function Ky(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 Qy(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:l,importOnlyConsumers:c}=Ir(e,i,s),u=ab(e,i,n,r);return{definition:i,realConsumers:a,barrelConsumers:l+c,transitivelyReachable:u}})}function Yy(e,t){let n=ac(e,t.definition.relativePath,t.definition.startLine),r=sc(t.definition.relativePath)?!0:lb(e,t.definition),{confidence:i,reason:o}=cb(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 Xy(e,t,n,r,i){let o=eb(e,Zy(n),r),s=o.map(c=>c.singleton);if(o.length===0)return new Set;let a=Ln(t,s,{semantic:i.semantic}),l=new Set;for(let{singleton:c,classId:u}of o)nb(e,c,a)&&l.add(u);return l}function Zy(e){let t=new Map;for(let n of e){let r=L(n.symbol);r&&t.set(oc(n.relativePath,r),n)}return t}function eb(e,t,n){let r=[];for(let i of n){let o=tb(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function tb(e,t,n){if(ac(e,n.relativePath,n.startLine)!=="class")return null;let r=L(n.symbol);if(!r)return null;let i=rb(e,n.relativePath,r);return i?t.get(oc(n.relativePath,i))??null:null}function nb(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)&&!Ro(e,o,r))}function oc(e,t){return`${e}\0${t}`}function rb(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 ib(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function ob(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 sc(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 sb(e,t,n){return!(sc(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function ab(e,t,n,r){let i=Xr(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 l of s){let c=a.get(l);if(!c)continue;let u=n.get(c.symbolId);if(u){for(let m of u)if(m!==t.relativePath&&!e.isIgnored(m))return!0}}return!1}function ac(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 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 lb(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 cb(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,l)=>ub(a,l,r),orderResults:(a,l)=>l.score-a.score||l.loc-a.loc,limit:i})}function ub(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(c=>c.file!==e.relativePath),a=new Set(s.map(c=>`${c.symbol}|${c.file}`)).size,l=new Set(o.map(c=>`${c.symbol}|${c.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:l,score:Math.round(r/50*(i/5)*Math.max(a/5,1)*100)/100}}function lc(e){let t=mb(e);return{score:db(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 mb(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 db(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 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))}import{getHeapStatistics as pb}from"v8";var fb=64*1024*1024;function _o(){let e=globalThis.gc;if(!e)return;let t=pb();t.heap_size_limit-t.used_heap_size<fb||e()}var gb=50,hb=75e3,yb=5e3,cc=2500,Mn=["overview","dead","isolated","cycles","similar","extract-candidates","wrapper-candidates","passthrough-candidates","stale-abstractions","drift","complexity-hotspots"],bb={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:Cb(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:Ib(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:Rb(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:_b(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:vb(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:Db(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:Nb(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:Lb(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:Eb(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:wb(e,t,n)})};function vo(e,t,n={}){return Sb(e,n.full===!0,(r,i)=>bb[t](e,n.scope,i,r))}function Sb(e,t,n){let r=Pe(e),i=kb(r,t);try{return n(r,i)}finally{Vi(e,{semanticProvider:!0}),_o()}}function Do(e){return lc(xb(e))}function xb(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 Cb(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 No(Mb(e,r.symbols))})}function Ib(e,t,n){return Ae(e,n,"isolated",()=>{let r=xn(e,{scope:t,minLoc:3,scanLimit:n.candidateScanLimit,semantic:!1});return No(Ob(e,r))})}function Rb(e,t,n){return Ae(e,n,"cycles",()=>Sn(e,{scope:t}).filter(i=>i.kind==="real").length)}function _b(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 vb(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 Db(e,t,n){return uc(e,n,"wrapper-candidates",()=>wn(e,{scope:t,maxLoc:15,limit:50,scanLimit:n.candidateScanLimit,semantic:!1}))}function Nb(e,t,n){return uc(e,n,"passthrough-candidates",()=>kn(e,{scope:t,maxLoc:15,limit:50,scanLimit:n.candidateScanLimit,semantic:!1}))}function Lb(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 Eb(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 wb(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>gb).length}})}function kb(e,t){return e.symbols>=hb||e.documents>=yb?t?{candidateScanLimit:void 0,releaseCachesBetweenPhases:!0,warnings:["Large index detected; running unbounded health analyses because --full was supplied."]}:{candidateScanLimit:cc,releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${cc} symbols. Run "scip-query health --full" for unbounded candidate counts.`]}:{candidateScanLimit:void 0,releaseCachesBetweenPhases:!0,warnings:[]}}function Pb(e,t){t.releaseCachesBetweenPhases&&(nc(e),Vi(e),_o())}function Ae(e,t,n,r){Tb(n);try{return r()}finally{Pb(e,t)}}function uc(e,t,n,r){return Ae(e,t,n,()=>No(r()))}function Tb(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function Mb(e,t){return t.filter(n=>!gt(e,n.relativePath)&&!cn(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function Ob(e,t){return t.filter(n=>!gt(e,n.relativePath)&&!cn(e,n.symbol,n.relativePath))}function No(e){return{count:e.length,loc:e.reduce((t,n)=>t+n.loc,0)}}function Lo(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)),l=[];for(let b of s)a.has(b)&&l.push(b);let c=[];for(let b of s)a.has(b)||c.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?l.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.":l.length===0?p="These functions do not share any callees. They are not a callee-based consolidation candidate.":c.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.":c.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.":c.length<=2&&u.length<=2?p=`Create a shared function with the ${l.length} common callees. Pass the ${c.length+u.length} divergent callees as parameters or strategy callbacks.`:p=`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 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:l.map(h),uniqueToA:c.map(h),uniqueToB:u.map(h),consolidationStrategy:p}}import{readFileSync as mc}from"fs";import{extname as Fb,join as dc}from"path";function Eo(e,t,n={}){let{context:r=0}=n,i=Ab(t);if(i)return jb(e,i.filePath,i.startLine,i.endLine,r);let o=w(e,t);return o?$b(e,o,r):null}function Ab(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 $b(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=dc(e.config.projectRoot,t.relativePath),o;try{o=mc(i,"utf-8")}catch{return null}let s=o.split(`
|
|
588
|
+
`),a=Math.max(0,t.startLine-n),l=Math.min(s.length-1,t.endLine+n),c=s.slice(a,l+1).join(`
|
|
589
|
+
`);return{symbol:t.symbol,shortName:h(t.symbol),relativePath:t.relativePath,startLine:a,endLine:l,language:r?.language??pc(t.relativePath),source:c}}function jb(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=dc(e.config.projectRoot,s.relative_path),l;try{l=mc(a,"utf-8")}catch{return null}let c=l.split(`
|
|
590
|
+
`),u=Math.max(0,n-1-i),m=Math.min(c.length-1,r-1+i),d=c.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??pc(s.relative_path),source:d}}function pc(e){switch(Fb(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 Bb}from"fs";import{join as Hb}from"path";function wo(e,t,n={}){let r=w(e,t);if(!r)return null;let i=new v(e),o=Jb(qb(e,r.relativePath,r.startLine,r.endLine),Wb(e,r.relativePath)),s=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:h(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o,cyclomaticEstimate:o+1,calleeCount:c.size,fanIn:Vb(e,r.symbolId),fanOut:Ub(l,r.relativePath)}}function Wb(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function qb(e,t,n,r){try{return Bb(Hb(e.config.projectRoot,t),"utf-8").split(`
|
|
873
592
|
`).slice(n,r+1).join(`
|
|
874
|
-
`)}catch{return""}}function
|
|
593
|
+
`)}catch{return""}}function Vb(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
|
|
875
594
|
FROM mentions m
|
|
876
595
|
JOIN chunks c ON m.chunk_id = c.id
|
|
877
|
-
WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function
|
|
596
|
+
WHERE m.symbol_id = ? AND m.role != 1`,t)?.c??0}function Ub(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function Jb(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 ko(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(l=>({file:l.file,line:l.line,enclosingSymbol:l.enclosingSymbol??"(top-level)",enclosingShort:l.enclosingSymbol?h(l.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=zb(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:h(r.symbol),relativePath:r.relativePath,definitionSites:i.filter(l=>!e.isIgnored(l.file)),usageSites:o,producers:s.filter(l=>!e.isIgnored(l.file)).map(l=>({symbol:l.symbol,shortName:h(l.symbol),file:l.file})),consumers:a.filter(l=>!e.isIgnored(l.file)).map(l=>({symbol:l.symbol,shortName:l.symbol===l.file?"(top-level)":h(l.symbol),file:l.file}))}}function zb(e,t,n,r){let i=qt(me(e,t,{limit:30,semantic:r.semantic}).map(a=>({symbol:a.symbol,file:a.file}))),o=qt(ye(e,t,{limit:30,semantic:r.semantic})),s=o.length>0?o:qt(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:s}}function Po(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=w(e,t);return o?r==="backward"?Gb(e,o,i,{semantic:n.semantic!==!1}):Kb(e,o,{semantic:n.semantic!==!1}):null}function Gb(e,t,n,r){let i=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let l=[];for(let c of s){let u=me(e,c,{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)&&l.push(d)}}s=l}return{symbol:t.symbol,shortName:h(t.symbol),direction:"backward",connectedSymbols:i}}function Kb(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 l=Tt(e,a);!l||e.isIgnored(l.relativePath)||r.has(l.symbol)||(r.add(l.symbol),i.push({symbol:l.symbol,shortName:h(l.symbol),file:l.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 To(e,t={}){let{scope:n,limit:r}=t,i=new v(e),o=iS([...Qb(e,n),...Zb(e,i,n)]);return oS(o),r?o.slice(0,r):o}function Qb(e,t){let n=[];for(let r of Yb(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||Si(e,r.barrel_path))continue;let i=Xb(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 Yb(e,t){let n=t?`AND barrel_d.relative_path LIKE '%${t}%'`:"";return e.all(`SELECT DISTINCT
|
|
878
597
|
barrel_d.id AS barrel_doc_id,
|
|
879
598
|
barrel_d.relative_path AS barrel_path,
|
|
880
599
|
gs.id AS symbol_id,
|
|
@@ -904,7 +623,7 @@ ${m}`,c+=1+m.length,u+=po(m),r+=m.length+1}let d=ug(l);d&&n.push({...d,start:a,e
|
|
|
904
623
|
-- Only function-level symbols (ending with ().), not module-level
|
|
905
624
|
AND gs.symbol LIKE '%().'
|
|
906
625
|
${n}
|
|
907
|
-
ORDER BY barrel_d.relative_path, gs.symbol`)}function
|
|
626
|
+
ORDER BY barrel_d.relative_path, gs.symbol`)}function Xb(e,t){return e.get(`SELECT
|
|
908
627
|
SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
|
|
909
628
|
SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
|
|
910
629
|
FROM (
|
|
@@ -933,95 +652,232 @@ ${m}`,c+=1+m.length,u+=po(m),r+=m.length+1}let d=ug(l);d&&n.push({...d,start:a,e
|
|
|
933
652
|
AND consumer_d.id != ?
|
|
934
653
|
${e.pathExclusionsFor("consumer_d")}
|
|
935
654
|
GROUP BY consumer_d.id
|
|
936
|
-
)`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
655
|
+
)`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function Zb(e,t,n){let r=[];for(let i of eS(e,n))fc(e,i,i)>0||r.push(...tS(e,t,i));return r}function eS(e,t){return k(e,{scope:t,includeIgnored:!1}).filter(n=>yi(e,n).length>0)}function tS(e,t,n){return yi(e,n).filter(r=>r.sourcePath&&!e.isIgnored(r.sourcePath)).flatMap(r=>nS(e,t,n,r.sourcePath))}function nS(e,t,n,r){let i=rS(t,r);return i?[{barrelFile:n,symbol:i.symbol,shortName:h(i.symbol),originalFile:r,barrelConsumers:0,directConsumers:fc(e,r,n)}]:[]}function fc(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 rS(e,t){let n=e.definitionsForFile(t);return n.find(r=>ee(r.symbol)==="method")??n[0]??null}function iS(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 oS(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function Mo(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o}=t,s=t.semantic!==!1,a=aS(e,sS(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:s}),l=cS(a);return i?l.slice(0,i):l}function sS(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 aS(e,t,n){let r=new Map;for(let i of t){let o=uS(e,i,n);if(!o)continue;let s=r.get(o)??[];s.push(lS(i)),r.set(o,s)}return r}function lS(e){return{symbol:e.symbol,shortName:h(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:j(e)}}function cS(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,l)=>a+l.loc,0);return r.functions.reduce((a,l)=>a+l.loc,0)-o}),t}function uS(e,t,n){if(n.semantic){let o=ll(e,t);if(o)return o}let r=mS(t.documentation),i=r?fS(r):null;return i||gS(dS(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function mS(e){return at(lt(e))}function dS(e,t,n,r,i){let o=T(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=yS(s,n,r,i);for(let l of a){let c=Math.min(s.length-1,Math.max(l,l+4)),u="";for(let m=l;m<=c;m+=1){let d=s[m]?.trim();if(d&&(u=u?`${u} ${d}`:d,pS(u)))return u}if(u&&u.includes("("))return u}return null}function pS(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 fS(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 gS(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${gc(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=hS(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 hS(e){let t=0,n=0,r=0,i=0,o=null,s=!1;for(let a=0;a<e.length;a+=1){let l=e[a];if(o){if(s){s=!1;continue}if(l==="\\"){s=!0;continue}l===o&&(o=null);continue}if(l==='"'||l==="'"||l==="`"){o=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 yS(e,t,n,r){let i=gc(r),o=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),s=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 m=c;m<=u;m+=1){let d=e[m]??"";(o.test(d)||s.test(d))&&!l.has(m)&&(l.add(m),a.push(m))}for(let m=0;m<e.length;m+=1){let d=e[m]??"";(o.test(d)||s.test(d))&&!l.has(m)&&(l.add(m),a.push(m))}return a}function gc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}import{existsSync as Rc}from"fs";import{join as MS}from"path";import bS from"better-sqlite3";var SS=["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 bS(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=>SS.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 xS from"ignore";import{readFileSync as CS,existsSync as Oo}from"fs";import{dirname as Fo,isAbsolute as hc,join as Ao,relative as IS,resolve as RS}from"path";function Jt(e){let t=xS(),n=!1,r=_S(e);for(let i of r)try{let o=CS(i,"utf-8");t.add(o),n=!0}catch{}return n||t.add(vS),{isIgnored:i=>yc(t,e,i),filter:i=>i.filter(o=>!yc(t,e,o))}}function _S(e){let t=[],n=Ao(e,".gitignore");Oo(n)&&t.push(n);let r=Fo(e),i=0;for(;r!==Fo(r)&&i<5;){let o=Ao(r,".gitignore");if(Oo(o)&&t.push(o),Oo(Ao(r,".git")))break;r=Fo(r),i++}return t}var vS=`
|
|
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 yc(e,t,n){let r=DS(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function DS(e,t){if(!t||t===".")return null;if(!hc(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=hc(t)?t:RS(e,t),r=IS(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{readFileSync as NS,writeFileSync as LS,existsSync as Sc,mkdirSync as ES}from"fs";import{join as St,resolve as bc}from"path";import{createHash as wS}from"crypto";import{homedir as kS}from"os";var xc=".scipquery.json",PS={enabled:!1,debounceMs:3e4,cooldownMs:6e4,ignore:[]};function zt(e){let t=St(e,xc);if(!Sc(t))return{};try{let n=NS(t,"utf-8");return JSON.parse(n)}catch{return{}}}function Cc(e){return{...PS,...e.watch}}function TS(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return $o(n);if(t?.dbPath)return $o(bc(e,t.dbPath));let i=process.env.XDG_CACHE_HOME||St(kS(),".cache"),o=wS("sha256").update(bc(e)).digest("hex").slice(0,12),s=St(i,"scip-query","projects",o);return $o(s)}function Gt(e,t){let n=TS(e,t);return{cacheDir:n,dbPath:St(n,"index.db"),indexPath:St(n,"index.scip"),metaPath:St(n,"meta.json")}}function Ic(e,t){let n=St(e,xc);return Sc(n)||LS(n,JSON.stringify({languages:t,watch:{enabled:!1,debounceMs:3e4,cooldownMs:6e4}},null,2)+`
|
|
731
|
+
`),n}function $o(e){return ES(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??(Rc(n.dbPath)?n.dbPath:MS(e,"index.db"));return{projectRoot:e,config:t,paths:n,dbPath:r}}function jo(e){return vr(e).dbPath}function OS(){let{projectRoot:e,config:t,paths:n,dbPath:r}=vr();Rc(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=OS();try{return e(t)}finally{t.close()}}function Bo(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 _c(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 FS(e)}}function FS(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 $S=AS(import.meta.url),{version:Lc}=WS(),Dr="__health-phase",Nr="__diff-impact-batch",jS=10,BS=75e3,HS=5e3,vc=2500;function WS(){for(let e of["../package.json","../../package.json"])try{return $S(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 Ec(e,t,n){let r=Pe(e);return r.symbols>=BS||r.documents>=HS?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 ${vc} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:vc,semantic:!1}):{semantic:!0}}function wc(e){let t=Mn.map(n=>qS(n,e));return Do(t)}function qS(e,t){let n=process.argv[1]??Nc(import.meta.url),r=[...process.execArgv,n,Dr,e];t.scope&&r.push("--scope",t.scope),t.full&&r.push("--full");let i=Dc(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 kc(e,t){if(t){console.log(JSON.stringify(e,null,2));return}if(console.log(`
|
|
948
734
|
Codebase Health Score: ${e.score}/100
|
|
949
|
-
`),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${
|
|
735
|
+
`),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${Kt(e.overview.indexSizeBytes)}
|
|
950
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(`
|
|
951
|
-
Prioritized Actions (highest impact + lowest effort first):`);for(let r=0;r<e.actions.length;r++){let i=e.actions[r],
|
|
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(`
|
|
952
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(`
|
|
953
|
-
No issues found. Codebase is clean.`)}function
|
|
954
|
-
${
|
|
955
|
-
Affected consumer files:`),
|
|
956
|
-
`).
|
|
957
|
-
|
|
958
|
-
|
|
739
|
+
No issues found. Codebase is clean.`)}function Pc(e){return rt(t=>{let n=Vt(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 US(n.changedFiles,jS))r.push(VS(i,e));return xr(n.changedFiles,r)})}function VS(e,t){let n=process.argv[1]??Nc(import.meta.url),r=[...process.execArgv,n,Nr];t.base&&r.push("--base",t.base);let i=Dc(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 Tc(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 US(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}var Mc=Bo,D=(e=>parseInt(e,10)),Lr=(e=>{let t=parseInt(e,10);if(!Number.isFinite(t)||t<1)throw new Error(`Expected a positive integer, got ${e}`);return t}),Er=parseFloat,Ho=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 Uo,mkdirSync as YS,symlinkSync as XS,readlinkSync as ZS,unlinkSync as ex}from"fs";import{join as wr,dirname as $c,resolve as Jo}from"path";import{homedir as jc,platform as tx}from"os";import{fileURLToPath as nx}from"url";import{execFileSync as Oc}from"child_process";import{platform as Wo,arch as KS}from"os";import{execFileSync as JS}from"child_process";import{platform as zS}from"os";var GS=zS()==="win32";function xe(e){let t=GS?"where":"which";try{return JS(t,[e],{stdio:"pipe"}),!0}catch{return!1}}var Fc="v0.7.0";function qo(){return xe("scip")}function QS(){let e=Wo(),t=KS(),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/${Fc}/${o}`,filename:o}}function Vo(){let e=QS();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Wo()==="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/${Fc}
|
|
744
|
+
`),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function Ac(e){if(Wo()==="darwin"&&xe("brew")){e("Installing scip CLI via Homebrew...");try{if(Oc("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(Oc("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 rx=tx()==="win32",zo=["concrete-plan","scip-explore","scip-debloat","scip-verify","scip-language-playbook"];function Bc(e={}){let t=e.quiet?()=>{}:console.log,n=nx(import.meta.url),r=Jo($c(n),"..","skills"),i=[wr(jc(),".claude","skills"),wr(jc(),".codex","skills")],o={installed:[],skipped:[],alreadyLinked:[]};for(let s of i){let a=$c(s);if(!Uo(a))continue;YS(s,{recursive:!0});let l=s.includes(".codex")?"Codex":"Claude";for(let c of zo){let u=wr(r,c),m=wr(s,c);if(!Uo(u)){o.skipped.push(`${l}/${c}`);continue}if(Uo(m)){try{let d=ZS(m);if(Jo(d)===Jo(u)){o.alreadyLinked.push(`${l}/${c}`),t(` ok: ${c} \u2192 ${l} (already linked)`);continue}}catch{o.skipped.push(`${l}/${c}`),t(` skip: ${c} \u2192 ${l} (exists, not a symlink)`);continue}ex(m)}XS(u,m,rx?"junction":"dir"),o.installed.push(`${l}/${c}`),t(` done: ${c} \u2192 ${l}`)}}return o}import{existsSync as Hu}from"fs";import{execFileSync as gI}from"child_process";import{closeSync as hI,existsSync as us,mkdirSync as ku,mkdtempSync as yI,openSync as bI,readFileSync as SI,renameSync as ms,rmSync as ds,writeFileSync as Pu}from"fs";import{basename as $r,dirname as It,extname as xI,join as je}from"path";import ix from"better-sqlite3";import{execFileSync as ox}from"child_process";import{existsSync as sx,readdirSync as ax,readFileSync as lx}from"fs";import{extname as kr,join as Hc}from"path";function it(e){let t=new Set((e.extensions??ga).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!sx(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Jt(e.projectRoot),r=cx(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new ix(e.dbPath);try{let o=mx(i,r),s=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
|
|
745
|
+
VALUES (?, ?, NULL, ?)`),l=i.transaction(u=>{let m=0;for(let d of u){if(o.has(d))continue;let p=lx(Hc(e.projectRoot,d),"utf-8"),y=s.run(dx(d),d,p);m+=Number(y.changes)}return m})(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 cx(e,t){let n=ux(e,t);if(n)return n;let r=[],i=o=>{let s=o?Hc(e,o):e,a;try{a=ax(s,{withFileTypes:!0})}catch{return}for(let l of a){if(bi.has(l.name))continue;let c=o?`${o}/${l.name}`:l.name;if(l.isDirectory()){i(c);continue}t.has(kr(l.name).toLowerCase())&&r.push(c)}};return i(""),r.sort()}function ux(e,t){try{return ox("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
|
|
746
|
+
`).filter(r=>r&&t.has(kr(r).toLowerCase())).sort()}catch{return null}}function mx(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 dx(e){return kr(e).toLowerCase()===".vue"?"vue":kr(e).replace(/^\./,"").toLowerCase()||"source"}import{execFileSync as px}from"child_process";import{existsSync as fx,readdirSync as qc}from"fs";import{extname as Vc,join as Uc}from"path";var gx=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),hx=[{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=yx(e),r=Cx(e);for(let i of hx){if(bx(e,i.files)){t.push(i.language);continue}if(Sx(n,i.globs)){t.push(i.language);continue}Rx(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&Wc(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&Wc(t,"c"),t}function yx(e){try{return qc(e)}catch{return[]}}function bx(e,t){return t?.length?t.some(n=>fx(Uc(e,n))):!1}function Sx(e,t){return t?.length?e.some(n=>t.some(r=>xx(n,r))):!1}function xx(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 Cx(e){let t=Ix(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=qc(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=Uc(i,s.name);if(s.isDirectory()){gx.has(s.name)||r.push(a);continue}let l=Vc(s.name).toLowerCase();l&&n.add(l)}}return n}function Ix(e){try{let t=px("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=Vc(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Rx(e,t){return t?.length?t.some(n=>e.has(n)):!1}function Wc(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as Jc,readdirSync as _x}from"fs";import{join as Go}from"path";var vx={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",zc(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",zc(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=Go(e,"vendor","bin","scip-php"),r=Go(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",Jc(r)?r:Jc(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Pr(e){return vx[e]}function zc(e,t){let n;try{n=_x(e)}catch{return null}for(let r of n)if(t.some(i=>r.endsWith(i)))return Go(e,r);return null}import{readFileSync as Dx,writeFileSync as Nx}from"fs";import{create as Ko}from"@bufbuild/protobuf";import{deserializeSCIP as Lx,serializeSCIP as Ex,DocumentSchema as wx,IndexSchema as kx,SymbolInformationSchema as Px}from"@c4312/scip";function Tx(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=Mx(e),n=Ox(e.flatMap(i=>i.documents??[])),r=Kc(e.flatMap(i=>i.externalSymbols??[]));return Ko(kx,{metadata:t,documents:n,externalSymbols:r})}function Gc(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Lx(Dx(i))),r=Tx(n);return Nx(t,Buffer.from(Ex(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function Mx(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 Ox(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,Ko(wx,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:[...r.occurrences,...n.occurrences],symbols:Kc([...r.symbols,...n.symbols]),text:Ax(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Kc(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,Ko(Px,{symbol:r.symbol,documentation:$x([...r.documentation,...n.documentation]),relationships:Fx([...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 Fx(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 Ax(e,t){return e?t?e.length>=t.length?e:t:e:t}function $x(e){return[...new Set(e)]}import{execFileSync as jx}from"child_process";import{createHash as Bx}from"crypto";import{readdirSync as Hx,readFileSync as Wx}from"fs";import{join as Qc}from"path";function qx(e){return(Vx(e)??Ux(e)).filter(t=>t&&!Yc(t)).sort()}function Tr(e){return qx(e).map(t=>{let n=Qc(e,t);try{let r=Wx(n);return{path:t,size:r.byteLength,hash:Bx("sha256").update(r).digest("hex")}}catch{return{path:t,size:-1,hash:"unreadable"}}})}function Vx(e){try{return jx("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 Ux(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?Qc(e,r):e,o;try{o=Hx(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=r?`${r}/${s.name}`:s.name;if(s.isDirectory()){Yc(a)||n.push(a);continue}t.push(a)}}return t}function Yc(e){return e.split("/").some(n=>Jx.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var Jx=new Set([".git","node_modules",".scipquery-cache",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]);import{readFileSync as zx,writeFileSync as Gx}from"fs";import{create as Xc}from"@bufbuild/protobuf";import{deserializeSCIP as Kx,DocumentSchema as Qx,IndexSchema as Yx,serializeSCIP as Xx,SymbolRole as Zx}from"@c4312/scip";function Zc(e){let t;try{t=Kx(zx(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=eC(t);return n.removedDefinitionOccurrences>0&&Gx(e,Buffer.from(Xx(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function eC(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&Zx.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(Xc(Qx,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:Xc(Yx,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}import{execFile as tC}from"child_process";import{existsSync as Mr,renameSync as Yo,rmSync as Xo}from"fs";import{cpus as nC}from"os";import{join as eu}from"path";function rC(e,t,n){if(!e.defaultOutputPath)return;let r=eu(t,e.defaultOutputPath);n!==r&&Mr(r)&&Yo(r,n)}function iC(e,t,n){if(!e.defaultOutputPath)return null;let r=eu(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Xo(i,{force:!0}),Mr(r)?(Yo(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function oC(e){e&&(Xo(e.defaultOutputPath,{force:!0}),e.backupPath&&Mr(e.backupPath)&&Yo(e.backupPath,e.defaultOutputPath))}function sC(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,nC().length-1));return Math.max(1,Math.min(e,Math.floor(r)))}async function tu(e,t,n,r){let i=e.filter(c=>c.config.defaultOutputPath),o=e.filter(c=>!c.config.defaultOutputPath),s=[],a=sC(o.length,r),l=await lC(o,a,c=>Qo(c,t,n));if(a>1){let c=new Map;for(let u of l.filter(m=>m.skipped)){let m=o.find(d=>d.language===u.language);m&&(n(`Retrying ${m.language} indexer serially after parallel failure...`),c.set(m.language,await Qo(m,t,n)))}s.push(...l.map(u=>c.get(u.language)??u))}else s.push(...l);for(let c of i)s.push(await Qo(c,t,n));return s.sort((c,u)=>e.findIndex(m=>m.language===c.language)-e.findIndex(m=>m.language===u.language))}async function Qo(e,t,n){n(`Indexing ${e.language} with ${e.resolvedBinary}...`),Xo(e.scipPath,{force:!0});let r=iC(e.config,t,e.scipPath);try{await aC(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),rC(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{oC(r)}if(!Mr(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 aC(e,t,n){return new Promise((r,i)=>{tC(e,[...t],n,o=>{o?i(o):r()})})}async function lC(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 es}from"child_process";import{existsSync as Zo,readFileSync as cC}from"fs";import{createRequire as uC}from"module";import{platform as mC}from"os";import{dirname as nu,join as Or}from"path";var dC=uC(import.meta.url);function ts(e){return[e.indexerBinary,...e.binaryAliases??[]]}function Fr(e){let t=ts(e);return t.length===1?t[0]:t.join(" or ")}function Qt(e){for(let t of ts(e))if(xe(t))return t;return fC(e)}function ru(e){return Qt(e)!==null||pC(e)}function pC(e){return iu(e)!==null}function fC(e){let t=iu(e);if(!t)return null;let r=JSON.parse(cC(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return Or(nu(t),r);for(let i of ts(e)){let o=r[i];if(o)return Or(nu(t),o)}return null}function iu(e){if(!e.bundledNpmPackage)return null;try{return dC.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function ns(e,t){for(let n of e.projectLocalBinaries??[]){let r=Or(t,n);if(Zo(r))return r}return null}function gC(e,t){return ns(e,t)??Qt(e)}function ou(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||rs(n,t))return t;let r=lu(n,t);return r?{...t,DOTNET_ROOT:r}:t}function su(e,t){let n=Fr(e),r=t?gC(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=hC(r);return{language:e.language,binaryLabel:n,installed:!0,runnable:i.runnable,resolvedBinary:r,installUrl:e.installUrl,note:i.note}}function au(e,t){let n=e.installMethods,r=Fr(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{es(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 hC(e){if(rs(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=cu(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 cu(t))if(rs(e,{...t,DOTNET_ROOT:n}))return n;return null}function cu(e){let t=[],n=e.DOTNET_ROOT;if(n&&Zo(n)&&t.push(n),mC()==="darwin"&&xe("brew"))try{let r=es("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e}).toString().trim(),i=Or(r,"libexec");Zo(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function rs(e,t){try{return es(e,["--version"],{stdio:"pipe",env:t}),!0}catch{return!1}}import QC from"better-sqlite3";import{existsSync as YC,readFileSync as XC,writeFileSync as ZC}from"fs";import{dirname as eI,join as tI,resolve as nI}from"path";import{readFileSync as yC,rmSync as bC,statSync as SC,mkdtempSync as xC}from"fs";import{cpus as CC,tmpdir as IC}from"os";import{join as is}from"path";import{Worker as RC}from"worker_threads";function uu(e){return e.length>=8&&du(e.length)>1}function mu(e){let t=du(e.vueFiles.length),n=vC(e.vueFiles),r=NC(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=xC(is(IC(),"scip-query-vue-workers-")),s=new SharedArrayBuffer(4),a=new Int32Array(s),l=_C(),c=Date.now();try{for(let m=0;m<r.length;m++)new RC(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[m],resultPath:is(o,`${m}.json`),sharedBuffer:s}});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((m,d)=>{let p=JSON.parse(yC(is(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{bC(o,{recursive:!0,force:!0})}}function du(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,CC().length-1));return Math.max(1,Math.min(e,n))}function _C(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function vC(e){let t=DC(),n=[];for(let r of e){let i=pu(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 DC(){return Number.POSITIVE_INFINITY}function NC(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:LC(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 LC(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,pu(e.fileName)-e.startOffset)}function pu(e){try{return SC(e).size}catch{return 1}}import{createRequire as EC}from"module";import{existsSync as wC,readFileSync as ss}from"fs";import{dirname as fu,extname as kC,join as gu,relative as PC,resolve as TC}from"path";import{pathToFileURL as MC}from"url";function OC(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 hu(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=>TC(t,r.relativePath))}function yu(e,t){let{vueCore:n,ts:r,volarTs:i}=FC(e),{parsed:o,vueOptions:s}=AC(n,r,t),a=fu(t),l=n.createVueLanguagePlugin(r,o.options,s,p=>p),c=$C(n,r,l),u=jC(a,o),{languageServiceHost:m}=i.createLanguageServiceHost(r,r.sys,c,p=>p,u),d=r.createLanguageService(m);return{ts:r,language:c,languageService:d,fileNames:o.fileNames,configDir:a}}function FC(e){let t=EC(MC(gu(e,"package.json")).href);return{vueCore:os(t,"@vue/language-core",e),ts:os(t,"typescript",e),volarTs:os(t,"@volar/typescript",e)}}function AC(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,fu(n),void 0,n,void 0,e.getAllExtensions(o).map(s=>({extension:s.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function $C(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!wC(o))return;let s=ss(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(s),n.getLanguageId(o)??UC(o))});return r.current=i,i}function jC(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function os(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 bu(e,t,n){let r=BC(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),l=r.get(o);if(!l)return null;let c=l.containingByLine.get(a.line);return c!==void 0?c:HC(l.starts,a.line,2)}}function BC(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 HC(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 l=Math.abs(a.line-t);l>n||(!o||l<o.distance)&&(o={distance:l,symbolId:a.symbolId})}return o?.symbolId??null}function Su(e,t,n){let r=GC(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 c of n){let u=Ct(t,c),m=Lu(r.name,r.version,u);o.run(m,"default",7,`Vue component|${u}`);let d=KC(i,r,t,c);d&&(s++,a.set(c,d))}})(),{get(c){return a.get(c)??null},syntheticSymbols:s}}function xu(e,t,n,r,i){return e.transaction(()=>(OC(e),WC(e,t,n,r),qC(e,i)))()}function WC(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 l=r.get(a);if(!l)continue;let c=Ct(t,a),u=i.get(c);if(!u)continue;let m=o.run(u.id,-1,0,0);s.run(Number(m.lastInsertRowid),l)}}function Cu(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(as(a,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Iu(e){let t=new Set,n=[];for(let r of e){let i=Ru(r);t.has(i)||(t.add(i),n.push(r))}return n}function Ru(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function qC(e,t){let n=zC(e,[...new Set(t.map(l=>l.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 l of t){let c=Ru(l);if(o.has(c))continue;o.add(c);let u=n.get(l.sourceFile);if(!u)continue;let m=r.run(u,a++,l.sourceLine,l.sourceLine),d=i.run(Number(m.lastInsertRowid),l.symbolId);s+=Number(d.changes)}return s}function*_u(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 vu(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function as(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function VC(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 Du(e,t){return Ct(e,t).startsWith("node_modules/")}function Ct(e,t){return PC(e,t).replaceAll("\\","/")}function UC(e){switch(kC(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 Nu(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=ss(t,"utf-8"),r={text:n,lineStarts:JC(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:VC}}function JC(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function zC(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 GC(e){try{let t=JSON.parse(ss(gu(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 KC(e,t,n,r){let i=Ct(n,r),o=Lu(t.name,t.version,i);return e.get(o)?.id??null}function Lu(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function ls(e){it({projectRoot:e.projectRoot,dbPath:e.dbPath});let t=nI(e.projectRoot,e.tsconfig);if(!YC(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new QC(e.dbPath);try{let r=hu(n,e.projectRoot),i=tI(eI(e.dbPath),"augment-vue-meta.json"),o=Eu(n,e.projectRoot,e.tsconfig),s=rI(i,o,e.onStatus);if(s)return s;let a=iI({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus});return aI(i,Eu(n,e.projectRoot,e.tsconfig),a),a}finally{n.close()}}function rI(e,t,n){let r=sI(e,t);return r&&n?.(`Vue references unchanged; reused ${r.resolvedReferences} cached resolved references.`),r}function iI(e){let t=Su(e.db,e.projectRoot,e.vueFiles),n=oI(e,t),r=Iu(n.occurrences),i=xu(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 oI(e,t){if(uu(e.vueFiles))return mu({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=Nu(),r=yu(e.projectRoot,e.configPath);return lI({projectRoot:e.projectRoot,vueFiles:r.fileNames.filter(i=>i.endsWith(".vue")),context:r,symbolLookup:bu(e.db,e.projectRoot,n),vueSymbolLookup:t,sourceReader:n})}function sI(e,t){try{let n=JSON.parse(XC(e,"utf-8"));return JSON.stringify(n.fingerprint)===JSON.stringify(t)?n.result:null}catch{return null}}function aI(e,t,n){ZC(e,JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)+`
|
|
794
|
+
`)}function Eu(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:Tr(t),db:r}}function lI(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=cI(e,i);t.push(...o.occurrences),n+=o.skippedReferences}return{occurrences:t,skippedReferences:n}}function cI(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=[..._u(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:dI(a),processedStarts:new Set};return uI({...e,fileName:t.fileName,sourceInfo:i,sourceFile:s,map:o,tokenContext:l})}function uI(e){let t=[],n=0;for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start))continue;let i=vu(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(l=>!Du(e.projectRoot,l.fileName));if(!s){n++;continue}let a=Cu(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}wu(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a),e.tokenContext.processedStarts.add(r.start),mI(t,e,r,i,a)}return{occurrences:t,skippedReferences:n}}function mI(e,t,n,r,i){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let o of pI(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&&(wu(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i),t.tokenContext.processedStarts.add(o))}}function wu(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 dI(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function pI(e,t,n,r,i,o){let s=e.getDocumentHighlights?.(t,n,[t])??[],a=[];for(let l of s)if(l.fileName===t)for(let c of l.highlightSpans){let u=fI(r,c.textSpan.start,o,i.text);u!==null&&a.push(u)}return a}function fI(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=as(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function Tu(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=CI(e),s=Date.now();ku(It(o.outputScip),{recursive:!0}),ku(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 l=AI(t,a,{pnpmWorkspaces:e.pnpmWorkspaces}),c=OI(je(It(o.outputDb),"index.lock")),u=null;try{let m=II({opts:e,paths:o,languages:a,fingerprint:l,start:s,onStatus:r});if(m)return m;NI(i,r);let d=RI(o);return u=d.runDir,await _I({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:d,fingerprint:l,start:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r})}finally{u&&ds(u,{recursive:!0,force:!0}),c()}}function CI(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 II(e){if(e.opts.skipIfUnchanged===!1||!us(e.paths.outputScip)||!us(e.paths.outputDb)||!$I(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 RI(e){let t=yI(je(It(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:je(t,$r(e.outputScip)),tempOutputDb:je(t,$r(e.outputDb)),tempMetaPath:je(t,$r(e.metaPath))}}async function _I(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:r}=await vI(e,t);DI(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 vI(e,t){let{preparedRuns:n,skippedLanguages:r}=LI({languages:e.languages,tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,onStatus:e.onStatus}),i=await tu(n,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),{indexedOutputs:o}=wI(i,r);return kI(o,r,e.languages,e.opts.allowPartial,e.onStatus),{indexedOutputs:o,skippedLanguages:r}}function DI(e,t,n,r){PI(n,e.tempPaths.tempOutputScip,e.onStatus),TI(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),it({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),jI(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]}),FI({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 NI(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..."),!Ac(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 LI(e){let t=[],n=[],r=e.languages.map((i,o)=>({language:i,scipPath:e.languages.length>1?MI(e.tempOutputScip,i,o):e.tempOutputScip}));for(let{language:i,scipPath:o}of r){let s=EI({...e,language:i,scipPath:o});"skipped"in s?n.push(s.skipped):t.push(s.prepared)}return{preparedRuns:t,skippedLanguages:n}}function EI(e){let t=Pr(e.language),n=Fr(t),r=ns(t,e.projectRoot);if(!r&&!ru(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...`),!au(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:ou(t,e.env,i)}}}function wI(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 kI(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 PI(e,t,n){e.length>1?(n(`Merging ${e.length} language indexes...`),Gc(e.map(r=>r.scipPath),t)):e[0].scipPath!==t&&ms(e[0].scipPath,t)}function TI(e,t,n,r){if(r("Converting to SQLite..."),!us(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{let i=Zc(e);i.removedDefinitionOccurrences>0&&r(`Sanitized ${i.removedDefinitionOccurrences} invalid definition occurrences across ${i.touchedDocuments} documents before SQLite conversion.`),gI("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 MI(e,t,n){let r=xI(e)||".scip",i=$r(e,r);return je(It(e),`${i}.${n+1}.${t}${r}`)}function OI(e){let t;try{t=bI(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 Pu(t,JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()})+`
|
|
810
|
+
`),()=>{try{hI(t)}finally{ds(e,{force:!0})}}}function FI(e){cs(e.tempOutputScip,e.outputScip),cs(e.tempOutputDb,e.outputDb),cs(e.tempMetaPath,e.metaPath)}function cs(e,t){ds(`${t}.tmp-replace`,{force:!0}),ms(e,`${t}.tmp-replace`),ms(`${t}.tmp-replace`,t)}function AI(e,t,n){return{version:1,languages:[...t].sort(),pnpmWorkspaces:n.pnpmWorkspaces===!0,files:Tr(e)}}function $I(e,t){try{let n=JSON.parse(SI(e,"utf-8"));return n.version===2&&n.status==="complete"&&Ar(n.fingerprint)===Ar(t)&&Ar([...n.indexedLanguages??[]].sort())===Ar(t.languages)}catch{return!1}}function jI(e,t){Pu(e,`${JSON.stringify(t,null,2)}
|
|
811
|
+
`)}function Ar(e){return JSON.stringify(e)}import{createRequire as BI}from"module";var HI=BI(import.meta.url);function Mu(e,t=[]){let n=WI(),r=Ei(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 WI(){try{return HI.resolve("ts-morph"),!0}catch{return!1}}function ps(e,t){let n=t.languages??xt(e),r=n.map(o=>{let s=su(Pr(o),e);return{...s,language:o,resolvedBinary:s.resolvedBinary??void 0}}),i=n.includes("typescript")?{language:"typescript",...Mu(e,t.semantic?.typescript?.tsconfigs)}:void 0;return{languages:n,indexers:r,semantic:i}}import{watch as qI}from"fs";import{existsSync as Ou,renameSync as Fu}from"fs";import{join as VI,relative as UI}from"path";import{fork as JI}from"child_process";import zI from"ignore";var jr=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=Cc(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=zI(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"});try{let t=qI(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=UI(this.projectRoot,VI(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=GI(this.indexPaths.indexPath),s=JI(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{Ou(i)&&Fu(i,this.indexPaths.dbPath),Ou(o)&&Fu(o,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}`))}),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 GI(e){return e.endsWith(".scip")?e.slice(0,-5)+".tmp.scip":e+".tmp.scip"}function X(e){return(...t)=>{let{args:n,opts:r}=KI(t);rt(i=>e({db:i,args:n,opts:r}))}}function Z(e,t){return X(n=>{let r=Ec(n.db,e,z(n.opts,"full"));t({...n,budget:r})})}function Au(e){return X(t=>Xt(t,e,{kind:"list"}))}function $u(e){return X(t=>Xt(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function ju(e){return X(t=>Xt(t,e,{kind:"grouped",key:e.key}))}function Yt(e){return X(t=>fs(t,e))}function Br(e,t){return Z(e,n=>fs(n,t))}function ot(e,t){return Z(e,n=>Xt(n,t,{kind:"list"}))}function Hr(e,t){return Z(e,n=>Xt(n,t,{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function Wr(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 Bu(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){fs(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 fs(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 KI(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 QI=new Set(["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php"]);function YI(e){return e.filter(t=>QI.has(t))}async function Wu(e){let t=Be(e),n=nt(),r=zt(n),i=Gt(n,r);try{let o=YI(Bu(t,"language")),s=await Tu({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=jo(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 Vu(e){let t=Be(e),n=nt(),r=jo(n);try{let i=ls({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 Uu(e){let t=Be(e);rt(n=>{let r=JSON.parse(process.env.SCIP_QUERY_DIFF_IMPACT_FILES??"[]"),i=Vt(n,{base:O(t,"base")}),o=Sr(n,r,i.changedFiles);console.log(JSON.stringify(o))})}function Ju(e){let t=Be(e);try{Tc(Pc({base:O(t,"base")}))}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function zu(e,t){let n=Be(t);rt(r=>{Mn.includes(e)||(console.error(`error: Unknown health phase: ${e}`),process.exit(1));let i=vo(r,e,{scope:O(n,"scope"),full:z(n,"full")});console.log(JSON.stringify(i))})}function Gu(e){let t=Be(e);try{let n=wc({scope:O(t,"scope"),full:z(t,"full"),json:z(t,"json")});kc(n,z(t,"json"))}catch(n){console.error(`error: ${n instanceof Error?n.message:n}`),process.exit(1)}}function Ku(){let e=Bc(),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 Qu(){let e=!1;qo()?console.log("scip CLI: installed"):(Vo(),e=!0);let t=nt(),n=zt(t),r=ps(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 Yu(){let e=nt(),t=xt(e),n=Ic(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)}function Xu(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 jr({projectRoot:n,config:r,languages:r.languages,onStatus:a=>{process.stdout.write(`\r\x1B[K${_c(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 Zu(){let{projectRoot:e,config:t,paths:n,dbPath:r}=vr(),i=ps(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: ${Hu(r)?"yes":"no"}`),Hu(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:Au({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:$u({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,headers:o,dashWidths:s})}}function em({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,key:o,...s}){return{...s,renderShape:"grouped-by-file",handler:ju({query:e,format:t,emptyMessage:n,heuristicLabel:r,after:i,key:o})}}var ZI=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"),l=!z(n,"onlyInternal"),c=!z(n,"onlyDead"),u=l?s:[],m=c?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&&tm(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(""),tm(m,"FILE-INTERNAL ONLY",` Used only within the same file (no cross-file callers). Could be a
|
|
959
822
|
single-use helper, an abstraction-in-progress, or a callback registered
|
|
960
823
|
through a framework path that static analysis cannot trace (signal
|
|
961
824
|
handlers, event listeners, dependency injection). NOT necessarily dead \u2014
|
|
962
|
-
review case by case.`,
|
|
963
|
-
\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: ${
|
|
964
|
-
${
|
|
965
|
-
|
|
966
|
-
${
|
|
967
|
-
${
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
${
|
|
972
|
-
`
|
|
973
|
-
${
|
|
974
|
-
A: ${
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
${
|
|
978
|
-
|
|
825
|
+
review case by case.`,p));let y=[];l&&y.push(`${u.length} dead code (${d} LOC)`),c&&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 tm(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 l=i.get(a.relativePath)??[];l.push(a),i.set(a.relativePath,l)}let o=[...i.entries()].map(([a,l])=>({file:a,bucket:l,totalLoc:l.reduce((c,u)=>c+u.loc,0)})).sort((a,l)=>l.totalLoc-a.totalLoc||a.file.localeCompare(l.file)),s=!0;for(let{file:a,bucket:l}of o){s||console.log(""),s=!1,console.log(` ${a}`),l.sort((c,u)=>c.startLine-u.startLine);for(let c of l)console.log(` ${be(c.startLine,c.endLine)} (${c.loc} LOC) ${c.shortName}`)}}var eR=ot("unused-imports",{query:({db:e,args:t,budget:n})=>Yi(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)`)}),tR=Wr("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)`)}),nR=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.`)}),rR=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).`)}),iR=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).`)}),oR=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).`)}),sR=Hr("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]}),aR=Br("similar",{query:({db:e,args:t,opts:n,budget:r})=>{let i=ke(t,0);return i?{mode:"target",rows:ho(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.`)}}),lR=Yt({query:({db:e,args:t,opts:n})=>yo(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(`
|
|
979
845
|
`)}),console.log(`
|
|
980
|
-
${
|
|
981
|
-
\u2500\u2500 Chain pair ${
|
|
982
|
-
${
|
|
983
|
-
${
|
|
984
|
-
${
|
|
985
|
-
|
|
986
|
-
${
|
|
987
|
-
`),
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
${
|
|
992
|
-
|
|
993
|
-
${n
|
|
994
|
-
|
|
995
|
-
${
|
|
996
|
-
${
|
|
997
|
-
`),
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
846
|
+
${e.length} similar pair(s) found.`)}}),cR=Yt({query:({db:e,opts:t})=>bo(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.`)}}),uR=Br("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)`)}}),mR=Br("convergence",{query:({db:e,args:t,budget:n})=>Lo(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}`)}}}),dR=ot("similar-signatures",{query:({db:e,opts:t,budget:n})=>Mo(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 nm=[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:ZI}),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:eR}),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:tR}),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)",Er,.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:aR}),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)",Er,.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:lR}),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)",Er,.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:cR}),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:nR}),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",Lr,5),g("--full","Run unbounded semantic analysis on large indexes")],heuristicLabel:"drift candidates",budget:"semantic",renderShape:"grouped-by-file",handler:uR}),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:rR}),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:iR}),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:oR}),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:sR}),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:mR}),em({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})=>To(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:dR})];var pR=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)}`)}),rm=[{id:"stats",command:"stats",description:"Show index statistics",renderShape:"custom",docs:S("Core"),handler:pR}];var fR=Hr("bottlenecks",{headers:["score","fan-in","fan-out","symbol"],query:({db:e,opts:t,budget:n})=>so(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."}),gR=Z("call-graph",({db:e,args:t,budget:n})=>{let r=fo(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}`)}])}),hR=X(({db:e,args:t,opts:n})=>{let r=ke(t,0);if(r){let i=eo(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"],no(e,{limit:I(n,"limit",30),scope:O(n,"scope")}).map(i=>` ${String(i.count).padStart(5)} ${i.name}`))}),yR=X(({db:e,args:t,opts:n})=>{let r=ke(t,0);if(r){let i=to(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"],ro(e,{limit:I(n,"limit",30),scope:O(n,"scope")}).map(i=>` ${String(i.count).padStart(7)} ${i.name}`))}),bR=X(({db:e,args:t,opts:n})=>{let r=ke(t,0),i=ke(t,1);if(r&&i){let o=io(e,r,i);console.log(`${o.file1} \u2194 ${o.file2}: ${o.sharedSymbols} shared symbols`);return}N.table(["shared","file1 \u2192 file2"],oo(e,{limit:I(n,"limit",20),scope:O(n,"scope")}).map(o=>` ${String(o.sharedSymbols).padStart(6)} ${o.file1} \u2192 ${o.file2}`))}),SR=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.)`)}}),xR=Yt({query:({db:e,opts:t})=>mo(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}`)}}}),im=[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})=>Gi(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:hR},{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:yR},{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:bR},{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:SR},{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:fR},{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:xR},{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:gR}];var CR=Z("complexity",({db:e,args:t,budget:n})=>{let r=wo(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}`)}),om=[{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:CR}];var IR=X(({db:e,args:t,opts:n})=>{let r=So(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.`)}),RR=Z("change-surface",({db:e,args:t,budget:n})=>{let r=xo(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}`})}),sm=[{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:IR},{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:RR}];var _R=X(({db:e,args:t})=>{let n=Wi(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}`)}])}),vR=Z("trace",({db:e,args:t,budget:n})=>{let r=ji(e,M(t,0),{semantic:n.semantic}),i=[];for(let a of r.definitions){let l=a.signature?` \u2014 ${a.signature}`:"";i.push(` ${Se(a.relativePath,a.startLine,a.endLine)}${l}`),a.source&&i.push(a.source.split(`
|
|
871
|
+
`).map((c,u)=>` ${$e(a.startLine+u)} ${c}`).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}])}),DR=X(({db:e,args:t})=>{let n=Xi(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)}),NR=ot("imports",{query:({db:e,args:t,budget:n})=>Ki(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)."}),LR=Wr("refs",{query:({db:e,args:t,budget:n})=>$i(e,M(t,0),{semantic:n.semantic}),format:e=>` line ${$e(e.line)}`}),ER=X(({db:e,args:t,opts:n})=>{let r=Eo(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"}]
|
|
1002
873
|
`);let i=r.source.split(`
|
|
1003
|
-
`);for(let
|
|
1004
|
-
`),
|
|
1005
|
-
|
|
1006
|
-
\u2550\u2550\u2550
|
|
1007
|
-
\u2550\u2550\u2550
|
|
1008
|
-
|
|
1009
|
-
`),i.connectedSymbols.length===0){console.log(" No connected symbols found.");return}b.list(i.connectedSymbols,s=>` ${s.file} ${s.shortName}
|
|
874
|
+
`);for(let o=0;o<i.length;o++)console.log(` ${String($e(r.startLine+o)).padStart(4)} ${i[o]}`)}),wR=Z("dataflow",({db:e,args:t,budget:n})=>{let r=ko(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}`)}}),kR=Z("slice",({db:e,args:t,opts:n,budget:r})=>{let i=z(n,"forward")?"forward":"backward",o=Po(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}
|
|
1010
880
|
${s.relationship}`),console.log(`
|
|
1011
|
-
${
|
|
1012
|
-
${e.
|
|
1013
|
-
No supported project languages detected in the current directory.`),process.exitCode=e?1:0;return}console.log(`
|
|
1014
|
-
Detected languages: ${r.join(", ")}`),console.log(`
|
|
1015
|
-
Indexer readiness:`);for(let i of r){let s=ki(qt(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=ar(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(`
|
|
1016
|
-
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});x.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",N,30).action(e=>R(t=>{let n=S.redundantReexports(t,{scope:e.scope,limit:e.limit});if(n.length===0)return b.empty("No redundant re-exports found.");b.groupedByFile(n,r=>` ${r.shortName} (from ${r.originalFile})
|
|
1017
|
-
barrel: ${r.barrelConsumers} consumer(s) | direct: ${r.directConsumers} consumer(s)`,r=>r.barrelFile),console.log(`
|
|
1018
|
-
${n.length} redundant re-export(s).`)}));x.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",N,3).option("-n, --limit <n>","Number of groups",N,20).action(e=>R(t=>{let n=S.similarSignatures(t,{scope:e.scope,minLoc:e.minLoc,limit:e.limit});if(n.length===0)return b.empty("No same-shape function groups found.");b.list(n,r=>{let i=`
|
|
1019
|
-
Signature: ${r.signature} (${r.functions.length} functions)`,s=r.functions.map(o=>` ${fe(o.file,o.startLine,o.endLine)} ${o.shortName} (${o.loc} LOC)`).join(`
|
|
1020
|
-
`);return`${i}
|
|
1021
|
-
${s}`}),console.log(`
|
|
1022
|
-
${n.length} group(s) found.`)}));x.command("init").description("Create a .scipquery.json config file for this project").action(()=>{let e=Ne(),t=He(e),n=ii(e,t);console.log(`Config written to ${n}`),console.log(`Detected languages: ${t.join(", ")||"(none)"}`)});x.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=Ne(),n=Ee(t);e.debounce&&((n.watch??={}).debounceMs=e.debounce),e.cooldown&&((n.watch??={}).cooldownMs=e.cooldown);let r=new Zt({projectRoot:t,config:n,languages:n.languages,onStatus:i=>{process.stdout.write(`\r\x1B[K${$l(i)}`)},onReindexComplete:i=>{console.log(`
|
|
1023
|
-
Reindex complete in ${(i/1e3).toFixed(1)}s`)},onError:i=>{console.error(`
|
|
1024
|
-
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.
|
|
1025
|
-
`),r.start(),process.on("SIGINT",()=>{r.stop(),console.log(`
|
|
1026
|
-
Stopped.`),process.exit(0)})});x.command("status").description("Show index status for this project").action(()=>{let e=Ne(),t=Ee(e),n=De(e,t),r=jt(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??He(e)).includes("typescript")){let i=ar(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: ${jl(r)?"yes":"no"}`),jl(r)&&R(i=>{let s=S.stats(i);if(console.log(`Symbols: ${s.symbols}`),console.log(`Files: ${s.documents}`),console.log(`Size: ${$n(s.indexSizeBytes)}`),s.lastBuilt){let o=Math.round((Date.now()-s.lastBuilt.getTime())/1e3);console.log(`Built: ${o}s ago`)}})});Wx()&&x.parse();function Wx(){if(!process.argv[1])return!1;let e=Zr(import.meta.url);try{return Bl(e)===Bl(process.argv[1])}catch{return e===process.argv[1]}}export{x as program,Se as renderHeuristicNotice};
|
|
881
|
+
${o.connectedSymbols.length} connected symbol(s).`)}),am=[ve({id:"files",command:"files <pattern>",description:"Find files matching a pattern",docs:S("Navigation",["scip-query files auth"]),query:({db:e,args:t})=>Vr(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})=>ri(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})=>Ai(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:LR},{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:vR},ve({id:"deps",command:"deps <file>",description:"Files this file depends on (internal)",docs:S("Navigation"),query:({db:e,args:t})=>Bi(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})=>Hi(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:_R},ve({id:"surface",command:"surface <module>",description:"What symbols consumers actually use from this module",docs:S("Navigation"),query:({db:e,args:t})=>qi(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:NR},ve({id:"imported-by",command:"imported-by <symbol>",description:"Which files import this symbol?",docs:S("Navigation"),query:({db:e,args:t})=>Qi(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:DR},ve({id:"members",command:"members <symbol>",description:"All children of a symbol (methods, fields, nested types)",docs:S("Navigation"),query:({db:e,args:t})=>Zi(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})=>co(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})=>uo(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})=>po(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:ER},{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:wR},{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:kR}];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"],PR=[rm,am,im,nm,sm,om],cm=PR.flat(),um=new Map(cm.map(e=>[e.id,e])),R0=lm.map(e=>{let t=um.get(e);if(!t)throw new Error(`Missing query command descriptor: ${e}`);return t});for(let e of cm)if(!lm.includes(e.id))throw new Error(`Query command descriptor is not ordered: ${e.id}`);function C(e){let t=um.get(e);if(!t)throw new Error(`Unknown query command descriptor: ${e}`);return t}var mm=[{id:"reindex",command:"reindex",description:"Index the codebase and convert to SQLite",options:[g("-l, --language <lang>","Index only this language (can be repeated)",Mc,[]),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",Lr)],renderShape:"custom",docs:S("Indexing",["scip-query reindex"]),handler:Wu},{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:Vu},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:Nr,command:Nr,description:"Internal diff-impact batch worker",hidden:!0,options:[g("--base <ref>","Git ref to diff against (default: HEAD)")],renderShape:"custom",handler:Uu},{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:Ju},C("drift"),C("wrapper-candidates"),C("passthrough-candidates"),C("stale-abstractions"),C("complexity-hotspots"),{id:Dr,command:Dr,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:zu},{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:Gu},C("convergence"),C("code"),C("complexity"),C("dataflow"),C("slice"),{id:"install-skills",command:"install-skills",description:`Install skills (${zo.join(", ")}) into Claude Code and Codex`,renderShape:"custom",docs:S("Maintenance"),handler:Ku},{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:Qu},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:Yu},{id:"watch",command:"watch",description:"Watch for file changes and reindex automatically",options:[g("--debounce <ms>","Ms to wait after last change (default: 30000)",Ho),g("--cooldown <ms>","Min ms between reindexes (default: 60000)",Ho)],renderShape:"custom",docs:S("Maintenance"),handler:Xu},{id:"status",command:"status",description:"Show index status for this project",renderShape:"custom",docs:S("Maintenance"),handler:Zu}];function dm(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}})}gs.name("scip-query").description("Language-agnostic code intelligence CLI powered by SCIP indexes").version(Lc);dm(gs,mm);MR()&&gs.parse();function MR(){if(!process.argv[1])return!1;let e=TR(import.meta.url);try{return pm(e)===pm(process.argv[1])}catch{return e===process.argv[1]}}export{gs as program,On as renderHeuristicNotice};
|
|
1027
883
|
//# sourceMappingURL=cli.js.map
|