scip-query 0.19.0 → 0.19.3
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/CHANGELOG.md +25 -0
- package/README.md +17 -1
- package/dist/augment-vue-worker.js +1 -1
- package/dist/{chunk-YHYTDWFT.js → chunk-24ET4VLC.js} +2 -2
- package/dist/{chunk-GBB2RUDN.js → chunk-26JI77AY.js} +130 -130
- package/dist/{chunk-MFBXBLHA.js → chunk-2E7QY4B5.js} +2 -2
- package/dist/{chunk-PXJIEMND.js → chunk-2ROSOG2I.js} +2 -2
- package/dist/{chunk-XKWEMFHP.js → chunk-2WCXKANA.js} +2 -2
- package/dist/{chunk-EZGT3NJX.js → chunk-33RLKB6L.js} +2 -2
- package/dist/{chunk-GJ3FR5WG.js → chunk-34MLC6UI.js} +2 -2
- package/dist/{chunk-G6RQVDTI.js → chunk-4BUMNEYQ.js} +2 -2
- package/dist/{chunk-XTSVYYAL.js → chunk-4CZJ4YJB.js} +2 -2
- package/dist/{chunk-TCVRJ56J.js → chunk-4FMT4HPC.js} +2 -2
- package/dist/{chunk-7FG5M53V.js → chunk-53SUJOJA.js} +2 -2
- package/dist/{chunk-AEDB4WXE.js → chunk-5FUAFNMP.js} +2 -2
- package/dist/chunk-5GCAM4JE.js +122 -0
- package/dist/{chunk-YBAC3RON.js → chunk-5GOBZI34.js} +2 -2
- package/dist/{chunk-LJD7V7UO.js → chunk-5OR4QRPR.js} +2 -2
- package/dist/{chunk-X36LKKVG.js → chunk-5OZCNAVM.js} +2 -2
- package/dist/{chunk-7EI4MU5A.js → chunk-5TZ2MQBG.js} +2 -2
- package/dist/{chunk-GNJHHPZE.js → chunk-64QITTX7.js} +2 -2
- package/dist/{chunk-HOXI4F5I.js → chunk-6EWBPAA3.js} +2 -2
- package/dist/{chunk-EZHARAL4.js → chunk-6FIA5BEB.js} +2 -2
- package/dist/{chunk-4ZCNFENR.js → chunk-77IOFJVY.js} +2 -2
- package/dist/{chunk-T5CSWYAZ.js → chunk-AD7WUFFT.js} +2 -2
- package/dist/{chunk-OGHGTD6Z.js → chunk-AEM24WSF.js} +2 -2
- package/dist/{chunk-S65OEY2G.js → chunk-AFVU2GB2.js} +2 -2
- package/dist/{chunk-SATRCB5O.js → chunk-AOSFSYEA.js} +2 -2
- package/dist/{chunk-3OSRXJKK.js → chunk-APLNTJPJ.js} +2 -2
- package/dist/{chunk-TDGCALH6.js → chunk-AYRHVJXW.js} +2 -2
- package/dist/{chunk-MDDF67O2.js → chunk-B26UX7ZD.js} +2 -2
- package/dist/{chunk-JFGUBZWE.js → chunk-C3KCSAQ4.js} +2 -2
- package/dist/{chunk-XESK6725.js → chunk-C3VQZFP2.js} +2 -2
- package/dist/{chunk-FLIF3JWA.js → chunk-CAKPEQZB.js} +2 -2
- package/dist/{chunk-PKAPOFF5.js → chunk-CIYUFF24.js} +2 -2
- package/dist/{chunk-J3U47L4Q.js → chunk-DO775SYA.js} +2 -2
- package/dist/{chunk-AM2LGOEX.js → chunk-EGKWRX5I.js} +2 -2
- package/dist/{chunk-PAZFJMXB.js → chunk-EHU4TZJJ.js} +2 -2
- package/dist/{chunk-YYR7ADNB.js → chunk-EII5ZHL2.js} +2 -2
- package/dist/{chunk-F5L7WEZF.js → chunk-EYF5HOUZ.js} +2 -2
- package/dist/{chunk-RIGY5DDE.js → chunk-FB6IKAKZ.js} +2 -2
- package/dist/{chunk-BGUYAA3Q.js → chunk-FBUNGRKI.js} +2 -2
- package/dist/{chunk-M2TRDR25.js → chunk-FC5K7T35.js} +1 -1
- package/dist/{chunk-KWBA6FDD.js → chunk-FRXB74RQ.js} +2 -2
- package/dist/{chunk-BYPVNKJT.js → chunk-FTRNGQGR.js} +2 -2
- package/dist/{chunk-54UYBTZW.js → chunk-FUFNRZFJ.js} +2 -2
- package/dist/{chunk-TDZXQAH7.js → chunk-FYE4PWWP.js} +2 -2
- package/dist/{chunk-QNMOZ3CJ.js → chunk-GAE7WCBK.js} +2 -2
- package/dist/{chunk-2ZNZSNVW.js → chunk-HAC5EI2T.js} +2 -2
- package/dist/{chunk-WT7TOU2C.js → chunk-HCSTQGQE.js} +2 -2
- package/dist/{chunk-UXOVHGT6.js → chunk-HFBNIIZX.js} +2 -2
- package/dist/{chunk-JHK2DMUQ.js → chunk-HGFDYOVB.js} +1 -1
- package/dist/{chunk-UJL3N6TC.js → chunk-HHOJH3RJ.js} +2 -2
- package/dist/{chunk-X65VYV2S.js → chunk-HNTLCR4F.js} +2 -2
- package/dist/{chunk-RJLU7IMR.js → chunk-IICQP2DY.js} +2 -2
- package/dist/{chunk-J65FQLDL.js → chunk-IXAALOUP.js} +2 -2
- package/dist/{chunk-XDVT7QPG.js → chunk-J4MYRIYT.js} +2 -2
- package/dist/{chunk-TAB7AWKO.js → chunk-J5XJWCB3.js} +2 -2
- package/dist/{chunk-DWN7QDTV.js → chunk-JFO2UVQP.js} +2 -2
- package/dist/{chunk-FMC3BI4I.js → chunk-JRCJEHRG.js} +2 -2
- package/dist/{chunk-4XTPZ5CR.js → chunk-KMOMNTB4.js} +2 -2
- package/dist/{chunk-ZL5Y23AJ.js → chunk-LM72NQ7T.js} +1 -1
- package/dist/{chunk-4ZHJAHLE.js → chunk-LSJDKJIB.js} +2 -2
- package/dist/{chunk-VV5WJLRO.js → chunk-MP43RX4O.js} +1 -1
- package/dist/{chunk-D5OXYOJP.js → chunk-MQ2B33LQ.js} +1 -1
- package/dist/{chunk-MTFHE7ZO.js → chunk-MRYPDVOS.js} +2 -2
- package/dist/{chunk-GMZYT44R.js → chunk-NLNZK7RL.js} +5 -5
- package/dist/{chunk-ZXWFN7CK.js → chunk-OAM22BCR.js} +2 -2
- package/dist/{chunk-TOYQTO44.js → chunk-OLG2YPLS.js} +2 -2
- package/dist/{chunk-PBADFBRR.js → chunk-OQ6TCHBB.js} +2 -2
- package/dist/{chunk-3KQOIXLO.js → chunk-PCIFZHWS.js} +2 -2
- package/dist/{chunk-KD6TPIXM.js → chunk-PJENL245.js} +2 -2
- package/dist/{chunk-F334Z5UA.js → chunk-PLDIXTKR.js} +2 -2
- package/dist/{chunk-BOXAKNN6.js → chunk-PNESKY2Z.js} +2 -2
- package/dist/{chunk-QHOUNTDZ.js → chunk-PTYQQHZM.js} +2 -2
- package/dist/{chunk-2FAJTZSX.js → chunk-QKW7ISEW.js} +2 -2
- package/dist/{chunk-AWSRND4W.js → chunk-QNO3QIMN.js} +2 -2
- package/dist/{chunk-DV6B262O.js → chunk-SJ6XSCG7.js} +2 -2
- package/dist/{chunk-XPYXEEDO.js → chunk-SOS256TP.js} +2 -2
- package/dist/{chunk-DQIJMKNE.js → chunk-TDUU63FC.js} +2 -2
- package/dist/chunk-TOIS2VAI.js +4 -0
- package/dist/{chunk-TC3X33N6.js → chunk-TYEGFDOP.js} +2 -2
- package/dist/chunk-UJKZQLDB.js +2 -0
- package/dist/chunk-V27BEQJN.js +7 -0
- package/dist/{chunk-J6BR4MD6.js → chunk-VIKEPD4D.js} +2 -2
- package/dist/{chunk-XDSB47KO.js → chunk-WAU7HVDI.js} +2 -2
- package/dist/chunk-WFWQWQK6.js +3 -0
- package/dist/chunk-WWCZCH7W.js +3 -0
- package/dist/{chunk-QB5WSOTY.js → chunk-XAMVIPE2.js} +2 -2
- package/dist/{chunk-A45K6VUK.js → chunk-XWE7PZQH.js} +2 -2
- package/dist/{chunk-547VY366.js → chunk-XWJ3JYRG.js} +2 -2
- package/dist/{chunk-QN67MWDU.js → chunk-XYBNOILR.js} +2 -2
- package/dist/{chunk-IWK562KR.js → chunk-XYNWAZ6J.js} +2 -2
- package/dist/{chunk-UVMME4FI.js → chunk-YGBHQOB2.js} +2 -2
- package/dist/{chunk-ZNSLF5AC.js → chunk-YGQBJUS6.js} +2 -2
- package/dist/{chunk-6DHPQS72.js → chunk-YILKXTIY.js} +2 -2
- package/dist/{chunk-X3OOU7CF.js → chunk-Z7M7X3ZG.js} +2 -2
- package/dist/{chunk-G6QQCX45.js → chunk-ZJGZCBYT.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{command-descriptors-SWFWGIFK.js → command-descriptors-QJEYYND2.js} +168 -166
- package/dist/direct-navigation-TT23TDBS.js +3 -0
- package/dist/index.js +1 -1
- package/dist/queries/affected.js +1 -1
- package/dist/queries/architecture.js +1 -1
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.js +1 -1
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.js +1 -1
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.js +1 -1
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.js +1 -1
- package/dist/queries/test-quality.js +1 -1
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/reindex-worker.js +24 -24
- package/dist/reindex.js +38 -38
- package/dist/runtime.d.ts +6 -1
- package/dist/runtime.js +2 -2
- package/dist/rust-semantic-session-server.js +1 -1
- package/dist/rust-semantic-session-worker.js +1 -1
- package/dist/rust-semantic-worker.js +1 -1
- package/dist/watch-server.js +5 -5
- package/package.json +1 -1
- package/dist/chunk-42QYU6FD.js +0 -3
- package/dist/chunk-6SHX42QQ.js +0 -6
- package/dist/chunk-AERYQJ52.js +0 -3
- package/dist/chunk-IXORBCMR.js +0 -120
- package/dist/chunk-NEG77KKH.js +0 -4
- package/dist/chunk-OYYZLJVT.js +0 -2
- package/dist/direct-navigation-RKMPBXMI.js +0 -3
package/dist/watch-server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as Et,B as Q,C as Ft,D as At,E as je,G as H,H as Lt,I as le,J as de,K as pe,L as Nt,N as jt,O as _e,P as _t,Q as Ot,U as Oe,V as Wt,W as $t,X as B,a as ft,b as mt,c as ht,d as De,e as gt,f as Ee,g as yt,ga as Gt,h as St,i as vt,ja as We,k as Fe,l as Ae,m as xt,n as It,p as Rt,pa as qt,q as Ct,r as wt,ra as Ut,s as Mt,sa as fe,t as kt,ta as Ht,u as Pt,ua as Bt,va as Vt,w as Tt,x as Dt,y as Le,z as Ne}from"./chunk-IXORBCMR.js";import{b as dt,c as pt,f as bt,h as J,l as U,m as ue}from"./chunk-VV5WJLRO.js";import{a as j,b as F}from"./chunk-KHE7J5ZN.js";import{a as ce,c as ut,d as Te,e as N}from"./chunk-JHK2DMUQ.js";import P from"process";import{rmSync as Yr}from"fs";import{resolve as ro}from"path";import{pathToFileURL as no}from"url";import{readFileSync as Xr,writeFileSync as mo,existsSync as Zr}from"fs";import{isAbsolute as go,join as en,relative as yo,resolve as So}from"path";var $e=".scipquery.json",tn=250,rn=0,nn=10*6e4,on={enabled:!1,debounceMs:tn,cooldownMs:rn,gitPollMs:2e3,idleTimeoutMs:nn,autoRefresh:!0,ignore:[]},sn=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"];var bo=new Set(sn);function V(r){let e=en(r,$e);if(!Zr(e))return{};try{let t=Xr(e,"utf-8");return JSON.parse(t)}catch(t){let n=t instanceof Error?t.message:String(t);throw t instanceof SyntaxError?new Error(`invalid ${$e} at ${e}: ${n}`,{cause:t}):new Error(`unable to read ${$e} at ${e}: ${n}`,{cause:t})}}function me(r){return{...on,...r.watch}}import{existsSync as Kt,readFileSync as an}from"fs";function Ge(r,e,t){let n=new Date().toISOString();if(!Kt(t.dbPath))return{state:"missing",checkedAt:n,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Kt(t.metaPath))return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=JSON.parse(an(t.metaPath,"utf-8")),o=e.languages??Ot(r),a=cn(r,o,e),s=Array.isArray(i.indexedLanguages)?[...i.indexedLanguages].sort():[],c=(i.version===2||i.version===3)&&i.status==="complete"&&JSON.stringify(i.fingerprint)===JSON.stringify(a)&&JSON.stringify(s)===JSON.stringify(a.languages),l=Gt(t.dbPath,t.metaPath),d=l.state==="invalid"||l.state==="drifted",p=c&&!d;return{state:p?"fresh":"stale",checkedAt:n,metaPath:t.metaPath,updatedAt:i.updatedAt,lastRefresh:i.lastRefresh,reason:d?`SQLite generation requires repair: ${l.reason}`:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:p?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function cn(r,e,t){return bt(r,e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{fork as ln}from"child_process";import{statSync as dn}from"fs";import{isAbsolute as pn,join as un,relative as fn}from"path";import{watch as mn}from"chokidar";import hn from"ignore";var he=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=me(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.gitignoreFilter=ue(e.projectRoot),this.extraIgnore=hn(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let e=mn(this.projectRoot,{ignoreInitial:!0,ignored:(t,n)=>this.isIgnoredWatchPath(t,n?.isDirectory()??!1)});e.on("all",(t,n)=>{this.stopped||this.handleFileChange(n)}),e.on("error",t=>{this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}),this.fsWatchers.push(e)}catch(e){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}}stop(){this.stopped=!0;for(let e of this.fsWatchers)e.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(e,t={}){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=zt(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}isIgnoredWatchPath(e,t){let n=this.relativeWatchPath(e);if(!n)return!1;let i=t?`${n}/`:n;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(e){let t=this.relativeWatchPath(e);!t||t===".."||t.startsWith("../")||t===".git"||t.startsWith(".git/")||this.gitignoreFilter.isIgnored(t)||this.extraIgnore.ignores(t)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=pn(e)?e:un(this.projectRoot,e);return fn(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=zt(this.pendingTrigger,e),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 t=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-e;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex(t).then(i=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(i),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,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(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(e){return new Promise((t,n)=>{let i=Date.now(),o=V(this.projectRoot),a=Object.keys(o).length>0?o:this.config,s=B(this.projectRoot,a),c=a.indexer?.typescript,l=a.indexer?.clojure,d=ln(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:s.indexPath,SCIP_REINDEX_OUTPUT_DB:s.dbPath,SCIP_REINDEX_LANGUAGES:(a.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(a.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:e.kind,SCIP_REINDEX_TRIGGER_DETAIL:e.detail??""},stdio:"pipe"});d.on("exit",p=>{p===0?t(Date.now()-i):n(new Error(`Reindex worker exited with code ${p}`))}),d.on("error",n)})}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,t=this.readGitState();if(!e||!t||this.stopped){this.lastGitState=t;return}this.lastGitState=t;let n=e.head!==t.head,i=e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize;n&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):n?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:t.indexPath??"index changed"})}readGitState(){let e=De(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=gt(this.projectRoot,e),n={head:De(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=dn(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function zt(r,e){return r?r.kind===e.kind?r.detail===e.detail?r:{kind:r.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${r.kind}, ${e.kind}`}:e}import{existsSync as er,statSync as In}from"fs";import{join as Rn}from"path";import{createHash as gn}from"crypto";import{readFileSync as yn}from"fs";import{dirname as Sn,join as ge}from"path";var X=2,bn="typescript-semantic";function Jt(r){let e=ge(r,bn);return{rootDir:e,requestDir:ge(e,"requests"),responseDir:ge(e,"responses")}}function Z(r){try{let e=JSON.parse(yn(ge(Sn(r),"meta.json"),"utf8"));return e.version!==2&&e.version!==3||typeof e.status!="string"||typeof e.updatedAt!="string"||e.fingerprint===void 0?null:gn("sha256").update(JSON.stringify({version:e.version,status:e.status,updatedAt:e.updatedAt,fingerprint:e.fingerprint,indexedLanguages:e.indexedLanguages})).digest("hex")}catch{return null}}function Qt(r){let e=JSON.parse(r);if(e.protocolVersion!==X||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||e.profileEnvironment!==void 0&&!vn(e.profileEnvironment)||!e.request||!xn(e.request))throw new Error("TypeScript semantic service received an invalid mailbox request.");return e}function vn(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&Object.values(r).every(e=>typeof e=="string"||e===null)}function xn(r){if(!r||typeof r!="object"||!("kind"in r))return!1;let e=r;switch(e.kind){case"availability":return!0;case"import-usage":return typeof e.file=="string";case"reference-fragments":return Et(e.files)!==null;case"references":return Yt(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return Yt(e.definitions);case"signature":return Xt(e.definition);default:return!1}}function Yt(r){return Array.isArray(r)&&r.every(Xt)}function Xt(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.symbolId=="number"&&typeof e.documentId=="number"&&typeof e.symbol=="string"&&typeof e.relativePath=="string"&&typeof e.leaf=="string"&&typeof e.startLine=="number"&&typeof e.endLine=="number"}function Cn(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var Zt;function wn(r=Cn(),e=void 0){if(e===void 0&&Zt?.projectRoot===r)return Zt;let t=V(r),n=B(r,t),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:r,config:t,paths:n,dbPath:i,dbPathSource:"env",gitContext:e};if(er(n.dbPath))return{projectRoot:r,config:t,paths:n,dbPath:n.dbPath,dbPathSource:"configured",gitContext:e};let o=Rn(r,"index.db");return{projectRoot:r,config:t,paths:n,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:Mn(o,n.dbPath),gitContext:e}}function tr(r,e={}){let{config:t,paths:n,dbPath:i,dbPathSource:o,rootFallbackWarning:a,gitContext:s}=wn(r);if(!er(i))throw new Error("No index.db found. Run: scip-query reindex");e.warnOnRootFallback&&o==="root-fallback"&&a&&console.error(a);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:r,sharedEvidenceDbPath:We(r,t,s),entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality,architecture:t.architecture,coverageContracts:t.coverageContracts,docs:t.docs},l=ue(r);return new vt(c,l)}function Mn(r,e){let t="unknown time";try{t=In(r).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${r}, modified ${t}) because the configured index was not found at ${e}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}import{mkdirSync as Pr,readFileSync as Tr,readdirSync as wi,rmSync as Mi}from"fs";import{resolve as Ie}from"path";import{resolve as kr}from"path";import{performance as y}from"perf_hooks";function ye(r){return{forFile(e,t){return rr(r,e,t)},forFiles(e,t){let n=new Map;for(let i of e)n.set(i,rr(r,i,t));return n}}}function rr(r,e,t){let n={file:e},i=t.facts||t.identifiers;if(t.text&&(n.text=Ct(r,e)),t.lines&&(n.lines=wt(r,e)),t.ast&&(n.ast=Mt(r,e)),t.imports&&(n.imports=At(r,e)),t.reexports&&(n.reexports=Ft(r,e)),i){let o=kt(r,e),a=o.facts;t.facts&&(n.facts=a),o.unavailable&&(n.sourceFactsUnavailable=o.unavailable),t.identifiers&&a&&(n.identifiers=a.fileIdentifiers,n.identifierLineMap=a.identifierLineMap)}return n}var kn={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function Se(r){if(r.startsWith("local "))return{kind:"local",id:r.slice(6),raw:r};let e=r.split(" ");if(e.length<4)return{scheme:e[0]??"",manager:e[1]??"",packageName:e[2]??"",version:"",descriptors:[],raw:r};let t=e[0],n=e[1],i=r.slice(t.length+1+n.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let a,s=i.indexOf(" ");s===-1?(a=i,i=""):(a=i.slice(0,s),i=i.slice(s+1));let c=Pn(i);return{scheme:t,manager:n,packageName:o,version:a,descriptors:c,raw:r}}function K(r){let e=Se(r);if("kind"in e)return null;for(let t=e.descriptors.length-2;t>=0;t--){let n=e.descriptors[t];if(n?.suffix==="type")return n.name}return null}function Pn(r){let e=[],t=0;for(;t<r.length;){if(r[t]==="["){let o=r.indexOf("]",t+1);if(o===-1){e.push({name:r.slice(t+1),suffix:"type-param"});break}e.push({name:r.slice(t+1,o),suffix:"type-param"}),t=o+1;continue}if(r[t]==="("&&(e.length===0||t===0||nr(r[t-1]))){let o=r.indexOf(")",t+1);if(o!==-1&&r[o+1]!=="."){e.push({name:r.slice(t+1,o),suffix:"parameter"}),t=o+1;continue}}let n;if(r[t]==="`"){let o=r.indexOf("`",t+1);if(o===-1){n=r.slice(t+1),e.push({name:n,suffix:"term"});break}n=r.slice(t+1,o),t=o+1}else{let o=t;for(;t<r.length&&!nr(r[t]);)t++;n=r.slice(o,t)}if(t>=r.length){n&&e.push({name:n,suffix:"term"});break}let i=r[t];if(i==="("){let o=r.indexOf(")",t+1);o!==-1&&r[o+1]==="."?(e.push({name:n,suffix:"method"}),t=o+2):o!==-1?(e.push({name:n,suffix:"method"}),t=o+1):(e.push({name:n,suffix:"term"}),t++)}else{let o=kn[i];o&&e.push({name:n,suffix:o}),t+=1}}return e}function nr(r){return r==="/"||r==="#"||r==="."||r==="("||r==="["||r===":"||r==="!"}function _(r){let e=Se(r);if("kind"in e&&e.kind==="local")return e.id;let t=e;return t.descriptors.length===0?"":t.descriptors[t.descriptors.length-1].name}function O(r){let e=Se(r);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function ir(r){let e=O(r);return e==="method"?!0:e!=="term"?!1:r.endsWith("().")?!0:r.startsWith("rust-analyzer ")&&r.includes("#")?!1:r.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(r):!0}function Tn(r,e={}){if(K(r.symbol)!==null)return e.includeClassMemberFallbacks===!0;let i=(r.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function or(r,e,t={}){let n=new Map;for(let o of e)r.length>0&&!Tn(o,{includeClassMemberFallbacks:t.includeClassMemberFallbacks})||n.set(o.id,o);for(let o of r)n.set(o.id,o);let i=[...n.values()];return t.sort?i.sort((o,a)=>o.start_line-a.start_line||o.end_line-a.end_line||o.symbol.localeCompare(a.symbol)):i}var Dn=J("file-definitions",{clearGroups:["definition-catalog"]}),ys=J("file-function-like-definitions",{clearGroups:["definition-catalog"]});function W(r,e,t={}){return t.includeClassMemberFallbacks?sr(r,e,void 0,{includeClassMemberFallbacks:!0}):Dn.get(r,e,()=>{let n=En(r,e);if(n)return n;let i=sr(r,e),o=Ae(r),a=ye(r).forFile(e,{text:!0}).text;return o&&a&&cr.write(r,e,Fe(r,e,a),{projectFingerprint:o,definitions:i.map(s=>({...s}))}),i})}var cr=It({kind:"file-definitions",invalidation:Rt("file-definitions"),serialize:Fn,deserialize:An});function En(r,e){let t=Ae(r);if(!t)return null;let n=ye(r).forFile(e,{text:!0}).text;if(!n)return null;let i=cr.read(r,e,Fe(r,e,n));return i?Ln(i,t,e):null}function Fn(r){return JSON.stringify(r)}function An(r){try{let e=JSON.parse(r);return!Ne(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function Ln(r,e,t){if(r.projectFingerprint!==e)return null;let n=[];for(let i of r.definitions){let o=Nn(i,t);if(!o)return null;n.push(o)}return n}function Nn(r,e){return!Ne(r)||typeof r.symbolId!="number"||typeof r.symbol!="string"||typeof r.documentId!="number"||typeof r.startLine!="number"||typeof r.startChar!="number"&&r.startChar!==void 0||typeof r.endLine!="number"||typeof r.endChar!="number"&&r.endChar!==void 0||r.relativePath!==e||typeof r.leaf!="string"||typeof r.parentTypeName!="string"&&r.parentTypeName!==null||typeof r.isFunctionLike!="boolean"||typeof r.isTypeLike!="boolean"||typeof r.kind!="number"&&r.kind!==null||typeof r.documentation!="string"&&r.documentation!==null||typeof r.enclosingSymbol!="string"&&r.enclosingSymbol!==null?null:{symbolId:r.symbolId,symbol:r.symbol,documentId:r.documentId,startLine:r.startLine,startChar:r.startChar,endLine:r.endLine,endChar:r.endChar,relativePath:r.relativePath,leaf:r.leaf,parentTypeName:r.parentTypeName,isFunctionLike:r.isFunctionLike,isTypeLike:r.isTypeLike,kind:r.kind,documentation:r.documentation,enclosingSymbol:r.enclosingSymbol}}function sr(r,e,t,n={}){let i=or(jn(r,e),_n(r,e),{sort:!0,includeClassMemberFallbacks:n.includeClassMemberFallbacks}).map(On);return t&&(i=i.filter(t)),$n(r,e,i)}function jn(r,e){return r.all(`SELECT
|
|
1
|
+
import{$ as Ht,A as Lt,Aa as Jt,B as Q,C as Nt,D as jt,E as _e,G as H,H as _t,I as le,J as de,K as pe,L as Ot,N as Wt,O as Oe,P as $t,Q as Gt,U as We,X as qt,Y as fe,Z as $e,_ as Ut,a as gt,aa as B,b as yt,c as St,d as Ee,e as bt,f as Fe,g as vt,h as xt,i as Rt,k as Ae,l as Le,la as Bt,m as Ct,n as wt,oa as Ge,p as kt,q as Mt,r as Pt,s as Tt,t as Dt,u as Et,ua as Vt,w as Ft,wa as Kt,x as At,xa as me,y as Ne,ya as zt,z as je,za as Yt}from"./chunk-5GCAM4JE.js";import{b as ft,c as mt,f as It,h as J,l as U,m as ue}from"./chunk-MP43RX4O.js";import{a as j,b as F}from"./chunk-KHE7J5ZN.js";import{a as ce,c as ht,d as De,e as N}from"./chunk-HGFDYOVB.js";import M from"process";import{rmSync as Zr}from"fs";import{resolve as ao}from"path";import{pathToFileURL as co}from"url";import{readFileSync as rn,writeFileSync as bo,existsSync as nn}from"fs";import{isAbsolute as xo,join as on,relative as Io,resolve as Ro}from"path";var qe=".scipquery.json",sn=250,an=0,cn=10*6e4,ln={enabled:!1,debounceMs:sn,cooldownMs:an,gitPollMs:2e3,idleTimeoutMs:cn,autoRefresh:!0,ignore:[]},dn=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"];var Co=new Set(dn);function V(r){let e=on(r,qe);if(!nn(e))return{};try{let t=rn(e,"utf-8");return JSON.parse(t)}catch(t){let n=t instanceof Error?t.message:String(t);throw t instanceof SyntaxError?new Error(`invalid ${qe} at ${e}: ${n}`,{cause:t}):new Error(`unable to read ${qe} at ${e}: ${n}`,{cause:t})}}function he(r){return{...ln,...r.watch}}import{existsSync as Qt,readFileSync as pn}from"fs";function Ue(r,e,t){let n=new Date().toISOString();if(!Qt(t.dbPath))return{state:"missing",checkedAt:n,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Qt(t.metaPath))return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=JSON.parse(pn(t.metaPath,"utf-8")),o=e.languages??Gt(r),a=un(r,o,e),s=Array.isArray(i.indexedLanguages)?[...i.indexedLanguages].sort():[],c=(i.version===2||i.version===3)&&i.status==="complete"&&JSON.stringify(i.fingerprint)===JSON.stringify(a)&&JSON.stringify(s)===JSON.stringify(a.languages),l=Bt(t.dbPath,t.metaPath),d=l.state==="invalid"||l.state==="drifted",p=c&&!d;return{state:p?"fresh":"stale",checkedAt:n,metaPath:t.metaPath,updatedAt:i.updatedAt,lastRefresh:i.lastRefresh,reason:d?`SQLite generation requires repair: ${l.reason}`:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:p?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function un(r,e,t){return It(r,e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{fork as fn}from"child_process";import{statSync as mn}from"fs";import{isAbsolute as hn,join as gn,relative as yn}from"path";import{watch as Sn}from"chokidar";import bn from"ignore";var ge=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onRefreshSuppressed;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=he(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onRefreshSuppressed=e.onRefreshSuppressed??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.gitignoreFilter=ue(e.projectRoot),this.extraIgnore=bn(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(e){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}}stop(){this.stopped=!0;for(let e of this.fsWatchers)e.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(e,t={}){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=Xt(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}startSourceWatcher(e=!1){let t=Sn(this.projectRoot,{ignoreInitial:!0,ignored:(n,i)=>this.isIgnoredWatchPath(n,i?.isDirectory()??!1),usePolling:e,...e?{interval:500,binaryInterval:1e3}:{}});t.on("all",(n,i)=>{this.stopped||this.handleFileChange(i)}),t.on("error",n=>this.handleSourceWatcherError(t,n,e)),this.fsWatchers.push(t)}handleSourceWatcherError(e,t,n){if(n||this.sourcePollingFallbackStarted||!vn(t)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(i=>i!==e),e.close();try{this.startSourceWatcher(!0)}catch(i){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(i)}`))}}isIgnoredWatchPath(e,t){let n=this.relativeWatchPath(e);if(!n)return!1;let i=t?`${n}/`:n;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(e){let t=this.relativeWatchPath(e);!t||t===".."||t.startsWith("../")||t===".git"||t.startsWith(".git/")||this.gitignoreFilter.isIgnored(t)||this.extraIgnore.ignores(t)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||t.endsWith(We)||t.endsWith(`${We}.previous`)||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=hn(e)?e:gn(this.projectRoot,e);return yn(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=Xt(this.pendingTrigger,e),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 t=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-e;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex(t).then(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now();let o=!1;try{o=this.onReindexComplete(i)===!0}catch(a){this.onError(a instanceof Error?a:new Error(String(a)))}if(this.dirty&&!this.stopped){if(o){let s=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(s),this.setStatus({state:"idle"});return}let a=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:a,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(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(e){return new Promise((t,n)=>{let i=Date.now(),o=V(this.projectRoot),a=Object.keys(o).length>0?o:this.config,s=B(this.projectRoot,a),c=a.indexer?.typescript,l=a.indexer?.clojure,d=fn(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:s.indexPath,SCIP_REINDEX_OUTPUT_DB:s.dbPath,SCIP_REINDEX_LANGUAGES:(a.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(a.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:e.kind,SCIP_REINDEX_TRIGGER_DETAIL:e.detail??""},stdio:"pipe"});d.on("exit",p=>{p===0?t(Date.now()-i):n(new Error(`Reindex worker exited with code ${p}`))}),d.on("error",n)})}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,t=this.readGitState();if(!e||!t||this.stopped){this.lastGitState=t;return}this.lastGitState=t;let n=e.head!==t.head,i=e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize;n&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):n?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:t.indexPath??"index changed"})}readGitState(){let e=Ee(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=bt(this.projectRoot,e),n={head:Ee(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=mn(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function Xt(r,e){return r?r.kind===e.kind?r.detail===e.detail?r:{kind:r.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${r.kind}, ${e.kind}`}:e}function vn(r){return r instanceof Error&&"code"in r&&r.code==="EMFILE"||String(r).includes("EMFILE: too many open files")}import{existsSync as ir,statSync as Mn}from"fs";import{join as Pn}from"path";import{createHash as xn}from"crypto";import{readFileSync as In}from"fs";import{dirname as Rn,join as ye}from"path";var X=2,Cn="typescript-semantic";function er(r){let e=ye(r,Cn);return{rootDir:e,requestDir:ye(e,"requests"),responseDir:ye(e,"responses")}}function Z(r){try{let e=JSON.parse(In(ye(Rn(r),"meta.json"),"utf8"));return e.version!==2&&e.version!==3||typeof e.status!="string"||typeof e.updatedAt!="string"||e.fingerprint===void 0?null:xn("sha256").update(JSON.stringify({version:e.version,status:e.status,updatedAt:e.updatedAt,fingerprint:e.fingerprint,indexedLanguages:e.indexedLanguages})).digest("hex")}catch{return null}}function tr(r){let e=JSON.parse(r);if(e.protocolVersion!==X||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||e.profileEnvironment!==void 0&&!wn(e.profileEnvironment)||!e.request||!kn(e.request))throw new Error("TypeScript semantic service received an invalid mailbox request.");return e}function wn(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&Object.values(r).every(e=>typeof e=="string"||e===null)}function kn(r){if(!r||typeof r!="object"||!("kind"in r))return!1;let e=r;switch(e.kind){case"availability":return!0;case"import-usage":return typeof e.file=="string";case"reference-fragments":return Lt(e.files)!==null;case"references":return Zt(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return Zt(e.definitions);case"signature":return rr(e.definition);default:return!1}}function Zt(r){return Array.isArray(r)&&r.every(rr)}function rr(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.symbolId=="number"&&typeof e.documentId=="number"&&typeof e.symbol=="string"&&typeof e.relativePath=="string"&&typeof e.leaf=="string"&&typeof e.startLine=="number"&&typeof e.endLine=="number"}function Tn(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var nr;function Dn(r=Tn(),e=void 0){if(e===void 0&&nr?.projectRoot===r)return nr;let t=V(r),n=B(r,t),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:r,config:t,paths:n,dbPath:i,dbPathSource:"env",gitContext:e};if(ir(n.dbPath))return{projectRoot:r,config:t,paths:n,dbPath:n.dbPath,dbPathSource:"configured",gitContext:e};let o=Pn(r,"index.db");return{projectRoot:r,config:t,paths:n,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:En(o,n.dbPath),gitContext:e}}function or(r,e={}){let{config:t,paths:n,dbPath:i,dbPathSource:o,rootFallbackWarning:a,gitContext:s}=Dn(r);if(!ir(i))throw new Error("No index.db found. Run: scip-query reindex");e.warnOnRootFallback&&o==="root-fallback"&&a&&console.error(a);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:r,sharedEvidenceDbPath:Ge(r,t,s),entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality,architecture:t.architecture,coverageContracts:t.coverageContracts,docs:t.docs},l=ue(r);return new Rt(c,l)}function En(r,e){let t="unknown time";try{t=Mn(r).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${r}, modified ${t}) because the configured index was not found at ${e}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}import{mkdirSync as Fr,readFileSync as Ar,readdirSync as Di,rmSync as Ei}from"fs";import{resolve as Re}from"path";import{resolve as Er}from"path";import{performance as y}from"perf_hooks";function Se(r){return{forFile(e,t){return sr(r,e,t)},forFiles(e,t){let n=new Map;for(let i of e)n.set(i,sr(r,i,t));return n}}}function sr(r,e,t){let n={file:e},i=t.facts||t.identifiers;if(t.text&&(n.text=Mt(r,e)),t.lines&&(n.lines=Pt(r,e)),t.ast&&(n.ast=Tt(r,e)),t.imports&&(n.imports=jt(r,e)),t.reexports&&(n.reexports=Nt(r,e)),i){let o=Dt(r,e),a=o.facts;t.facts&&(n.facts=a),o.unavailable&&(n.sourceFactsUnavailable=o.unavailable),t.identifiers&&a&&(n.identifiers=a.fileIdentifiers,n.identifierLineMap=a.identifierLineMap)}return n}var Fn={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function be(r){if(r.startsWith("local "))return{kind:"local",id:r.slice(6),raw:r};let e=r.split(" ");if(e.length<4)return{scheme:e[0]??"",manager:e[1]??"",packageName:e[2]??"",version:"",descriptors:[],raw:r};let t=e[0],n=e[1],i=r.slice(t.length+1+n.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let a,s=i.indexOf(" ");s===-1?(a=i,i=""):(a=i.slice(0,s),i=i.slice(s+1));let c=An(i);return{scheme:t,manager:n,packageName:o,version:a,descriptors:c,raw:r}}function K(r){let e=be(r);if("kind"in e)return null;for(let t=e.descriptors.length-2;t>=0;t--){let n=e.descriptors[t];if(n?.suffix==="type")return n.name}return null}function An(r){let e=[],t=0;for(;t<r.length;){if(r[t]==="["){let o=r.indexOf("]",t+1);if(o===-1){e.push({name:r.slice(t+1),suffix:"type-param"});break}e.push({name:r.slice(t+1,o),suffix:"type-param"}),t=o+1;continue}if(r[t]==="("&&(e.length===0||t===0||ar(r[t-1]))){let o=r.indexOf(")",t+1);if(o!==-1&&r[o+1]!=="."){e.push({name:r.slice(t+1,o),suffix:"parameter"}),t=o+1;continue}}let n;if(r[t]==="`"){let o=r.indexOf("`",t+1);if(o===-1){n=r.slice(t+1),e.push({name:n,suffix:"term"});break}n=r.slice(t+1,o),t=o+1}else{let o=t;for(;t<r.length&&!ar(r[t]);)t++;n=r.slice(o,t)}if(t>=r.length){n&&e.push({name:n,suffix:"term"});break}let i=r[t];if(i==="("){let o=r.indexOf(")",t+1);o!==-1&&r[o+1]==="."?(e.push({name:n,suffix:"method"}),t=o+2):o!==-1?(e.push({name:n,suffix:"method"}),t=o+1):(e.push({name:n,suffix:"term"}),t++)}else{let o=Fn[i];o&&e.push({name:n,suffix:o}),t+=1}}return e}function ar(r){return r==="/"||r==="#"||r==="."||r==="("||r==="["||r===":"||r==="!"}function _(r){let e=be(r);if("kind"in e&&e.kind==="local")return e.id;let t=e;return t.descriptors.length===0?"":t.descriptors[t.descriptors.length-1].name}function O(r){let e=be(r);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function cr(r){let e=O(r);return e==="method"?!0:e!=="term"?!1:r.endsWith("().")?!0:r.startsWith("rust-analyzer ")&&r.includes("#")?!1:r.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(r):!0}function Ln(r,e={}){if(K(r.symbol)!==null)return e.includeClassMemberFallbacks===!0;let i=(r.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function lr(r,e,t={}){let n=new Map;for(let o of e)r.length>0&&!Ln(o,{includeClassMemberFallbacks:t.includeClassMemberFallbacks})||n.set(o.id,o);for(let o of r)n.set(o.id,o);let i=[...n.values()];return t.sort?i.sort((o,a)=>o.start_line-a.start_line||o.end_line-a.end_line||o.symbol.localeCompare(a.symbol)):i}var Nn=J("file-definitions",{clearGroups:["definition-catalog"]}),Rs=J("file-function-like-definitions",{clearGroups:["definition-catalog"]});function W(r,e,t={}){return t.includeClassMemberFallbacks?dr(r,e,void 0,{includeClassMemberFallbacks:!0}):Nn.get(r,e,()=>{let n=jn(r,e);if(n)return n;let i=dr(r,e),o=Le(r),a=Se(r).forFile(e,{text:!0}).text;return o&&a&&ur.write(r,e,Ae(r,e,a),{projectFingerprint:o,definitions:i.map(s=>({...s}))}),i})}var ur=wt({kind:"file-definitions",invalidation:kt("file-definitions"),serialize:_n,deserialize:On});function jn(r,e){let t=Le(r);if(!t)return null;let n=Se(r).forFile(e,{text:!0}).text;if(!n)return null;let i=ur.read(r,e,Ae(r,e,n));return i?Wn(i,t,e):null}function _n(r){return JSON.stringify(r)}function On(r){try{let e=JSON.parse(r);return!je(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function Wn(r,e,t){if(r.projectFingerprint!==e)return null;let n=[];for(let i of r.definitions){let o=$n(i,t);if(!o)return null;n.push(o)}return n}function $n(r,e){return!je(r)||typeof r.symbolId!="number"||typeof r.symbol!="string"||typeof r.documentId!="number"||typeof r.startLine!="number"||typeof r.startChar!="number"&&r.startChar!==void 0||typeof r.endLine!="number"||typeof r.endChar!="number"&&r.endChar!==void 0||r.relativePath!==e||typeof r.leaf!="string"||typeof r.parentTypeName!="string"&&r.parentTypeName!==null||typeof r.isFunctionLike!="boolean"||typeof r.isTypeLike!="boolean"||typeof r.kind!="number"&&r.kind!==null||typeof r.documentation!="string"&&r.documentation!==null||typeof r.enclosingSymbol!="string"&&r.enclosingSymbol!==null?null:{symbolId:r.symbolId,symbol:r.symbol,documentId:r.documentId,startLine:r.startLine,startChar:r.startChar,endLine:r.endLine,endChar:r.endChar,relativePath:r.relativePath,leaf:r.leaf,parentTypeName:r.parentTypeName,isFunctionLike:r.isFunctionLike,isTypeLike:r.isTypeLike,kind:r.kind,documentation:r.documentation,enclosingSymbol:r.enclosingSymbol}}function dr(r,e,t,n={}){let i=lr(Gn(r,e),qn(r,e),{sort:!0,includeClassMemberFallbacks:n.includeClassMemberFallbacks}).map(Un);return t&&(i=i.filter(t)),Bn(r,e,i)}function Gn(r,e){return r.all(`SELECT
|
|
2
2
|
gs.id,
|
|
3
3
|
gs.symbol,
|
|
4
4
|
der.document_id,
|
|
@@ -16,7 +16,7 @@ import{A as Et,B as Q,C as Ft,D as At,E as je,G as H,H as Lt,I as le,J as de,K a
|
|
|
16
16
|
JOIN documents d ON der.document_id = d.id
|
|
17
17
|
WHERE d.relative_path = ?
|
|
18
18
|
${r.symbolNoiseFor("gs")}
|
|
19
|
-
ORDER BY der.start_line, der.end_line`,e)}function
|
|
19
|
+
ORDER BY der.start_line, der.end_line`,e)}function qn(r,e){return r.all(`SELECT
|
|
20
20
|
gs.id,
|
|
21
21
|
gs.symbol,
|
|
22
22
|
c.document_id,
|
|
@@ -37,7 +37,7 @@ import{A as Et,B as Q,C as Ft,D as At,E as je,G as H,H as Lt,I as le,J as de,K a
|
|
|
37
37
|
AND m.role = 1
|
|
38
38
|
${r.symbolNoiseFor("gs")}
|
|
39
39
|
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
40
|
-
ORDER BY start_line, end_line`,e)}function
|
|
41
|
-
`),c=[];for(let l=0;l<s.length;l++){if(l===i)continue;let d=s[l]??"";a.lastIndex=0;let p;for(;(p=a.exec(d))!==null;)c.push({file:e,line:l,column:p.index})}return z(c.filter(l=>Y(t,dr.join(t,l.file))===e))}function qe(r){for(let e=r;e;e=e.getParent()){let t=e.getKindName();if(t.includes("Type")||t==="InterfaceDeclaration"||t==="TypeAliasDeclaration")return!0;if(t==="CallExpression"||t==="NewExpression"||t==="ExpressionStatement")return!1}return!1}function Ue(r,e){return r.getLineAndColumnAtPos(e.getStart()).line-1}function z(r){let e=new Set,t=[];for(let n of r){let i=`${n.file}:${n.line}:${n.column}`;e.has(i)||(e.add(i),t.push(n))}return t}function Y(r,e){let t=dr.relative(r||process.cwd(),e).replace(/\\/g,"/");return!t||t.startsWith("..")?null:t}function mr(r,e,t,n){let i=ii(e,n);return i.size===0?new Map:oi(r,t,i)}function ii(r,e){let t=new Map;for(let n of W(r,e)){let i=_(n.symbol)??n.leaf;if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push(n)}return t}function oi(r,e,t){let n=new Map,i=new Map;return e.forEachDescendant(o=>{for(let a of si(r,o)){let s=t.get(a);if(!s)continue;let c=Ue(e,o);for(let l of s){if(c<l.startLine-1||c>l.endLine+1)continue;let d=Math.abs(c-l.startLine),p=i.get(l.symbolId);p!==void 0&&p<=d||(i.set(l.symbolId,d),n.set(l.symbolId,o))}}}),n}function si(r,e){let t=[],n=i=>{i&&!t.includes(i)&&t.push(i)};if("getNameNode"in e&&typeof e.getNameNode=="function"){let i=e.getNameNode();n(i?.getText())}if("getName"in e&&typeof e.getName=="function"){let i=e.getName();n(i)}return r.Node.isIdentifier(e)&&n(e.getText()),t}var ai=J("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function hr(r,e,t,n){let i=Ve(r,e),o=He(i.get(n)??[],t);if(o)return o;let a=[];for(let s of i.values())for(let c of s)((c.leaf||_(c.symbol)||"").includes(n)||c.symbol.includes(n))&&a.push(c);return He(a,t)}function Be(r,e,t,n){return He(Ve(r,e).get(n)??[],t)}function gr(r,e){let t=new Map;for(let[n,i]of Ve(r,e)){let o=i[0];o&&t.set(n,o)}return t}function Ve(r,e){return ai.get(r,e,()=>{let t=new Map;for(let n of W(r,e)){let i=n.leaf||_(n.symbol);if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push({...n,leaf:i})}for(let n of t.values())n.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return t})}function He(r,e){let t=null,n=Number.POSITIVE_INFINITY;for(let i of r){let o=Math.abs(i.startLine-e);(o<n||o===n&&t&&i.startLine<t.startLine)&&(t=i,n=o)}return t}import Ke from"path";function yr(r,e){let t=new Map,n=null,i=null,o=()=>(i??=U(r,{extensions:de}),i),a=()=>(n??=N("typescript.source-file-index",()=>ci(r.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),n),s=c=>pe(c)?k(t,c,()=>{let l=ee(Ke.resolve(r.config.projectRoot,c));for(let{project:d,sourceFiles:p}of a()){let u=p.get(l)??null;if(u||(u=d.addSourceFileAtPathIfExists(l)??null,u&&p.set(ee(u.getFilePath()),u)),u)return{project:d,sourceFile:u}}return null}):null;return{sourceFile:c=>s(c)?.sourceFile??null,sourceFileMatch:s,indexedTypeScriptLikeDocuments:o}}function ci(r,e,t){let n=e.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[ee(o.getFilePath()),o]))}));for(let i of t){let o=ee(Ke.resolve(r,i));for(let a of n){if(a.sourceFiles.has(o))break;let s=a.project.addSourceFileAtPathIfExists(o)??null;if(s){a.sourceFiles.set(ee(s.getFilePath()),s);break}}}return n}function ee(r){return Ke.resolve(r)}function ze(r,e){for(let t of r)if(e===t.name||e.startsWith(`${t.name}/`))return t.name;return null}function Sr(r){let e=`${r.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as te,readFileSync as li}from"fs";import b from"path";var Ye=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Je(r,e){let n=e?b.dirname(b.join(r,e)):r,i=b.resolve(r);for(;n.startsWith(i);){for(let a of Ye){let s=b.join(n,a);if(te(s))return s}let o=b.dirname(n);if(o===n)break;n=o}for(let o of Ye){let a=b.join(r,o);if(te(a))return a}return null}function br(r){let e=r.config.projectRoot,t=new Set(di(e,r.config.semantic?.typescript?.tsconfigs)),n=U(r,{includeIgnored:!1,extensions:de});for(let i of n){let o=Je(e,i);o&&t.add(b.resolve(o))}if(t.size===0){let i=Je(e);i&&t.add(b.resolve(i))}return[...t].filter(i=>!vr(e,i)).sort((i,o)=>i.localeCompare(o))}function di(r,e=[]){let t=new Set;for(let n of e){let i=b.isAbsolute(n)?n:b.join(r,n);te(i)&&t.add(b.resolve(i))}for(let n of pi(r))for(let i of Ye){let o=b.join(n,i);te(o)&&t.add(b.resolve(o))}if(t.size===0){let n=Je(r);n&&t.add(b.resolve(n))}return[...t].filter(n=>!vr(r,n)).sort((n,i)=>n.localeCompare(i))}function pi(r){let e=b.join(r,"package.json");if(!te(e))return[];let t;try{t=JSON.parse(li(e,"utf8"))}catch{return[]}return(Array.isArray(t.workspaces)?t.workspaces:t.workspaces?.packages??[]).flatMap(i=>Dt(r,i))}function vr(r,e){let t=b.relative(r,e).replace(/\\/g,"/");return t.startsWith("..")||t.includes("/node_modules/")||t.startsWith("node_modules/")||t.includes("/dist/")||t.startsWith("dist/")}var ui=32;function Mr(r,e,t,n={}){return N("typescript.provider.construct",()=>new Xe(r,e,t),()=>({tsconfigs:t.length,reusedProjects:n.reusedProjects===!0}))}var Xe=class{constructor(e,t,n){this.db=e;this.tsMorph=t;this.projects=n;this.workspacePackages=Tt(e.config.projectRoot),this.sourceFiles=yr(e,n)}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;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(e=>e.tsconfigPath)}}importUsage(e){return k(this.importUsageCache,e,()=>{let t=this.sourceFiles.sourceFile(e);if(!t)return[];let n=mi();return N("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,t,n),()=>({file:e,...n}))})}referencesFor(e){return k(this.referencesCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,t)})}referencesForDefinitions(e,t={}){let n=new Map,i=ce(),o=[];for(let d of e){let p=this.referencesCache.get(d.symbolId);p?n.set(d.symbolId,p):o.push(d)}if(o.length===0)return n;let a=o,s=t.exact?[]:o.filter(d=>!Ir(d));if(s.length>=ui){let d=this.referencesForDefinitionsBySymbolScan(s);for(let p of s){let u=d.get(p.symbolId)??[];this.referencesCache.set(p.symbolId,u),n.set(p.symbolId,u)}if(a=o.filter(p=>Ir(p)),a.length===0)return n}let c=new Map;for(let d of a){let p=c.get(d.relativePath);p?p.push(d):c.set(d.relativePath,[d])}let l=[];for(let[d,p]of c){let u=Rr();N("typescript.references-map.file",()=>{let g=this.definitionNodesForFile(d);for(let f of p){i&&(u.cacheMisses+=1);let m=g.get(f.symbolId)??null;i&&(m?u.nodeHits+=1:u.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(f,m,i?u:void 0);this.referencesCache.set(f.symbolId,h),n.set(f.symbolId,h)}catch{u.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:d,definitions:p.length,...Cr(u)}))}if(l.length>0){let d=this.referencesForDefinitionsBySymbolScan(l);for(let p of l){let u=d.get(p.symbolId)??[];this.referencesCache.set(p.symbolId,u),n.set(p.symbolId,u)}}return n}referenceFragmentsForFiles(e){let t=lr(this.db).filter(o=>pe(o.relativePath)),n=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,n);return _t(t,i,n)}referencesForDefinitionsBySymbolScan(e,t){let n=ce(),i=Rr(),o=new Map,a=new Set(e.map(c=>c.symbolId)),s=new Map(e.map(c=>[c.symbolId,c]));for(let c of e)o.set(c.symbolId,[]);return N("typescript.references-map.inverted-scan",()=>{let c=n?y.now():0,l=t?this.packageImportReferencesForFiles(t):this.packageImportReferences();for(let h of e){let S=l.get(h.symbolId)??[];if(S.length>0){let w=o.get(h.symbolId)??[];w.push(...S),o.set(h.symbolId,w)}n&&(i.packageReferenceCount+=S.length)}n&&(i.packageRefsMs+=y.now()-c);let d=new Map,p=new Map,u=this.hierarchyTargetsForDefinitions(e),g=new Set(e.map(h=>h.leaf).filter(Boolean)),f=n?y.now():0;for(let h of t??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(h))continue;let S=this.sourceFiles.sourceFile(h);S&&(n&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(S,h,a,s,u,g,d,p,o,n?i:void 0))}n&&(i.scanMs+=y.now()-f);let m=n?y.now():0;this.addHierarchyMemberReferences(e,o,n?i:void 0),n&&(i.hierarchyMs+=y.now()-m);for(let[h,S]of o){let w=z(S);o.set(h,w),n&&(i.referenceCount+=w.length)}},()=>({definitions:e.length,...Cr(i)})),o}addReferencesFromSourceFileScan(e,t,n,i,o,a,s,c,l,d){let p=this.compilerCheckerForSourceFile(e),u=e.compilerNode,g=yi(e),f=m=>{if(this.tsMorph.ts.isIdentifier(m)){if(d&&(d.identifiers+=1),!a.has(m.text)&&!g.has(m.text)){this.tsMorph.ts.forEachChild(m,f);return}let h=this.compilerReferenceSymbol(p,m,d);if(h){let S;s.has(h)?S=s.get(h)??null:(S=this.referenceDefinitionFromCompilerSymbol(h),s.set(h,S)),d&&(S?d.targetHits+=1:d.targetMisses+=1);let w=k(c,h,()=>this.compilerSymbolKeys(h)),A=null,T=null,L=S&&n.has(S.symbolId)?i.get(S.symbolId):void 0;if(L&&(A=Qe(u,m),!xr(L,t,A))){let M=u.getLineAndCharacterOfPosition(m.getStart(u));T={file:t,line:M.line,column:M.character};let C=l.get(L.symbolId)??[];C.push(T),l.set(L.symbolId,C),d&&(d.requestedHits+=1)}for(let M of w)for(let C of o.get(M)?.values()??[]){if(A??=Qe(u,m),xr(C,t,A))continue;if(!T){let x=u.getLineAndCharacterOfPosition(m.getStart(u));T={file:t,line:x.line,column:x.character}}let v=l.get(C.symbolId)??[];v.push(T),l.set(C.symbolId,v),d&&(d.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(m,f)};f(u)}hierarchyTargetsForDefinitions(e){let t=new Map;for(let n of e){let i=this.nodeForDefinition(n),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let a=o.parent;if(!this.isHierarchyContainer(a))continue;let s=this.compilerCheckerForSourceFile(i.getSourceFile()),c=s.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(s,a,c))for(let d of this.compilerSymbolKeys(l)){let p=t.get(d)??new Map;p.set(n.symbolId,n),t.set(d,p)}}return t}hierarchyMemberSymbols(e,t,n){let i=new Set,o=new Set,a=(s,c,l)=>{if(!o.has(s)){o.add(s),i.add(c);for(let d of l){let p=d.getProperty(n.name);p&&a(d,p,this.hierarchyAncestorTypesForType(e,d))}}};return a(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}addHierarchyMemberReferences(e,t,n){let i=new Map;for(let o of e){let a=this.nodeForDefinition(o),s=a?.compilerNode;if(!s||!this.isHierarchyMethod(s))continue;let c=s.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(a.getSourceFile()),d=l.getSymbolAtLocation(s.name);if(!d)continue;let p=s.getSourceFile(),u=p.getLineAndCharacterOfPosition(s.name.getStart(p)),g={definition:o,location:{file:o.relativePath,line:u.line,column:u.character}},f=t.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(l,c,d))if(h!==d)for(let S of this.compilerSymbolLocations(h))f.push(S),n&&(n.hierarchyReferences+=1);t.set(o.symbolId,f);let m=this.hierarchyRootMemberSymbols(l,c,d);for(let h of m){let S=i.get(h)??new Map;S.set(o.symbolId,g),i.set(h,S)}n&&(n.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){n&&(n.hierarchyFamilies+=1);for(let{definition:a}of o.values()){let s=t.get(a.symbolId)??[];for(let c of o.values())c.definition.symbolId!==a.symbolId&&(s.push(c.location),n&&(n.hierarchyReferences+=1));t.set(a.symbolId,s)}}}hierarchyRootMemberSymbols(e,t,n){let i=new Set,o=new Set,a=(s,c,l)=>{if(o.has(s))return;o.add(s);let d=!1;for(let p of l){let u=p.getProperty(n.name);u&&(d=!0,a(p,u,this.hierarchyAncestorTypesForType(e,p)))}if(!d)for(let p of this.compilerSymbolKeys(c))i.add(p)};return a(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}compilerSymbolKeys(e){return(e.declarations??[]).map(t=>{let n=t.getSourceFile();return`${n.fileName}\0${t.getStart(n)}\0${e.name}`})}compilerSymbolLocations(e){let t=[];for(let n of e.declarations??[]){let i=n.getSourceFile(),o=Y(this.db.config.projectRoot,i.fileName);if(!o)continue;let a=n.name,s=i.getLineAndCharacterOfPosition((a??n).getStart(i));t.push({file:o,line:s.line,column:s.character})}return t}baseTypes(e,t){try{return e.getBaseTypes(t)??[]}catch{return[]}}hierarchyAncestorTypes(e,t){let n=new Set(this.hierarchyAncestorTypesForType(e,e.getTypeAtLocation(t)));for(let i of t.heritageClauses??[])for(let o of i.types)n.add(e.getTypeAtLocation(o));return[...n]}hierarchyAncestorTypesForType(e,t){let n=new Set(this.baseTypes(e,t));for(let i of t.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let a of o.types)n.add(e.getTypeAtLocation(a));return[...n]}isHierarchyMethod(e){return this.tsMorph.ts.isMethodDeclaration(e)||this.tsMorph.ts.isMethodSignature(e)}isHierarchyContainer(e){return this.tsMorph.ts.isClassDeclaration(e)||this.tsMorph.ts.isClassExpression(e)||this.tsMorph.ts.isInterfaceDeclaration(e)}compilerReferenceSymbol(e,t,n){n&&(n.symbolLookups+=1);let i=e.getSymbolAtLocation(t);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return n&&(n.aliasResolutions+=1),e.getAliasedSymbol(i)}catch{return i}}}calleesFor(e){return k(this.calleesCache,e.symbolId,()=>k(this.fileCalleesCache,e.relativePath,()=>this.calleeMapForFile(e.relativePath)).get(e.symbolId)??[])}calleesForDefinitions(e){let t=new Map,n=new Map;for(let i of e){let o=n.get(i.relativePath);o?o.push(i):n.set(i.relativePath,[i])}for(let[i,o]of n){let a=this.fileCalleesCache.get(i),s=new Set(o.map(l=>l.symbolId)),c=a??this.calleeMapForFile(i,s);for(let l of o){let d=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,d),t.set(l.symbolId,d)}}return t}referencesForDefinitionNode(e,t,n){let i=n?y.now():0,o=this.packageImportReferencesForDefinition(e);if(n&&(n.packageRefsMs+=y.now()-i,n.packageReferenceCount+=o.length),!t)return o;let a=n?y.now():0,s=pr(t,e,o,this.db.config.projectRoot);return n&&(n.semanticRefsMs+=y.now()-a,n.referenceCount+=s.length),s}signatureFor(e){return k(this.signatureCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);if(!t||!this.tsMorph.Node.isFunctionDeclaration(t)&&!this.tsMorph.Node.isMethodDeclaration(t)&&!this.tsMorph.Node.isArrowFunction(t)&&!this.tsMorph.Node.isFunctionExpression(t)&&!this.tsMorph.Node.isConstructorDeclaration(t))return null;let n=t.getType().getCallSignatures()[0];if(!n)return null;let i=n.getParameters().map(a=>{let s=a.getDeclarations()[0],c=s?a.getTypeAtLocation(s).getText(s):a.getValueDeclaration()?.getType().getText()??"unknown";return wr(c)}),o=n.getReturnType().getText(t);return`(${i.join(",")})=>${wr(o)}`})}importUsageForSourceFile(e,t,n){let i=[],o=new Map;for(let a of t.getImportDeclarations()){n.declarations+=1;let s=Le(this.db,e,a.getModuleSpecifierValue()),c=a.getImportClause()?.isTypeOnly()??!1;for(let l of Ze(a)){n.entries+=1;let d=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(d?n.bindingSymbols+=1:n.missingBindingSymbols+=1);let p={sourcePath:s,entry:l,typeOnlyDeclaration:c,bindingSymbol:d,references:[]};if(i.push(p),c||!l.localName||!d)continue;let u=o.get(l.localName);u?u.push(p):o.set(l.localName,[p])}}return o.size>0&&t.forEachDescendant(a=>{if(a.getKindName()!=="Identifier")return;let s=o.get(a.getText());if(!s||hi(a))return;n.scannedIdentifiers+=1;let c=a.getSymbol()?.compilerSymbol;if(n.symbolLookups+=1,!!c){for(let l of s)if(l.bindingSymbol===c){l.references.push({location:ve(a,this.db.config.projectRoot),node:a}),n.matchedReferences+=1;break}}}),i.map(a=>a.typeOnlyDeclaration?fi(e,a.sourcePath,a.entry):a.entry.identifier&&!a.bindingSymbol?(n.fallbackEntries+=1,this.valueImportUsageForEntry(e,a.sourcePath,a.entry)):this.valueImportUsageFromLocations(e,a.sourcePath,a.entry,a.references))}valueImportUsageForEntry(e,t,n){let i=n.identifier?n.identifier.findReferences():[],o=[];for(let a of i)for(let s of ur(a,e,n.identifier,this.db.config.projectRoot))o.push(s);return this.valueImportUsageFromLocations(e,t,n,o)}valueImportUsageFromLocations(e,t,n,i){let o=i.some(c=>!qe(c.node)),a=i.some(c=>qe(c.node)),s=n.isTypeOnly;return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:s,isUsed:s||i.length>0,isTypeUsed:s||a,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(e){return this.packageImportReferences().get(e.symbolId)??[]}packageImportReferencesForFiles(e){let t=new Map,n=new Set;for(let o of e){let a=this.sourceFiles.sourceFile(o);if(a)for(let s of a.getImportDeclarations()){let c=ze(this.workspacePackages,s.getModuleSpecifierValue());c&&n.add(c)}}if(n.size===0)return t;let i=this.packageExportsForNames(n);for(let o of e)this.addPackageImportReferencesForDocument(t,i,o);for(let[o,a]of t)t.set(o,z(a));return t}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let e=new Map,t=this.packageExports();for(let n of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(e,t,n);for(let[n,i]of e)e.set(n,z(i));return this.packageImportReferenceIndex=e,e}addPackageImportReferencesForDocument(e,t,n){if(this.db.isIgnored(n))return;let i=this.sourceFiles.sourceFileMatch(n);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(e,t,n,o)}addPackageImportReferencesForDeclaration(e,t,n,i){let o=ze(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let a=t.get(o);if(a)for(let s of Ze(i)){if(s.kind!=="named"||!s.identifier)continue;let c=a.get(s.importedName);if(!c||c.size===0)continue;let l=fr(s.identifier,n,this.db.config.projectRoot);l.length>0&&xi(e,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(e=>e.name))),this.packageExportIndex)}packageExportsForNames(e){let t=new Map;for(let n of this.workspacePackages){if(!e.has(n.name))continue;let i=new Map;for(let o of Sr(n))this.collectPackageExports(n,o,i,new Set);i.size>0&&t.set(n.name,i)}return t}collectPackageExports(e,t,n,i){if(i.has(t))return;i.add(t);let o=this.sourceFiles.sourceFile(t);if(o)for(let a of o.getExportDeclarations()){let s=a.getModuleSpecifierValue(),c=s?Le(this.db,t,s):t;if(!c||!c.startsWith(`${e.relativeDir}/src/`))continue;let l=a.getNamedExports();if(l.length===0){if(a.isNamespaceExport())continue;this.collectPackageExports(e,c,n,i);continue}for(let d of l){let p=d.getNameNode().getText(),u=d.getAliasNode()?.getText()??p,g=this.indexedDefinitionByLeaf(c,p);if(!g)continue;let f=n.get(u);f||(f=new Set,n.set(u,f)),f.add(g.symbolId)}}}indexedDefinitionByLeaf(e,t){return k(this.indexedDefinitionLeafCache,e,()=>gr(this.db,e)).get(t)??null}nodeForDefinition(e){return k(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return k(this.fileDefinitionNodeCache,e,()=>{let t=this.sourceFiles.sourceFile(e);return t?mr(this.tsMorph,this.db,t,e):new Map})}referenceDefinitionFromCompilerSymbol(e){return this.definitionFromCompilerSymbol(e,void 0,!0)}definitionFromCompilerSymbol(e,t,n=!1){let i=e.name,o=t?y.now():0,a=e.declarations??[];t&&(t.declarationsMs+=y.now()-o,t.declarationChecks+=a.length);for(let s of a){let c=t?y.now():0,l=s.getSourceFile(),d=Y(this.db.config.projectRoot,l.fileName),p=l.getLineAndCharacterOfPosition(s.getStart(l)).line;if(t&&(t.declarationLocationMs+=y.now()-c),!d||this.db.isIgnored(d))continue;let u=t?y.now():0,g=this.compilerDeclarationName(s),f=n?Be(this.db,d,p,i)??(g&&g!==i?Be(this.db,d,p,g):null):hr(this.db,d,p,i);if(t&&(t.indexedLookupMs+=y.now()-u),f)return{symbolId:f.symbolId,symbol:f.symbol,file:f.relativePath,line:f.startLine}}return null}compilerDeclarationName(e){let t=e.name;return t&&this.tsMorph.ts.isIdentifier(t)?t.text:null}calleeMapForFile(e,t){let n=ce(),i=0,o=0,a=0,s=0,c=0,l=0,d=0,p=0,u=n?bi():void 0;return N("typescript.callee-map.file",()=>{let g=n?y.now():0,f=this.sourceFiles.sourceFile(e);if(n&&(c=Math.round(y.now()-g)),!f)return new Map;let m=n?y.now():0,h=W(this.db,e).sort((v,x)=>v.startLine-x.startLine||x.endLine-v.endLine);if(n&&(l=Math.round(y.now()-m)),i=h.length,h.length===0)return new Map;let S=new Map,w=n?y.now():0,A=this.compilerCheckerForSourceFile(f),T=f.compilerNode;n&&(d=Math.round(y.now()-w));let L=new Map,M=v=>{if(this.tsMorph.ts.isCallExpression(v)||this.tsMorph.ts.isNewExpression(v)){n&&(o+=1);let x=this.semanticCalleeForCallNode(A,T,h,v,L,t,u);x&&(n&&(a+=1),gi(S,x.callerId,x.target))}this.tsMorph.ts.forEachChild(v,M)},C=n?y.now():0;M(T),n&&(p=Math.round(y.now()-C));for(let[v,x]of S)S.set(v,Ii(x));return s=S.size,S},()=>({relativePath:e,definitions:i,callNodes:o,resolvedCallees:a,outputRows:s,requestedDefinitions:t?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:p,...u?vi(u):{}}))}semanticCalleeForCallNode(e,t,n,i,o,a,s){let c=s?y.now():0,l=Si(n,Qe(t,i));if(s&&(s.callerLookupMs+=y.now()-c),!l)return null;if(a&&!a.has(l.symbolId))return s&&(s.skippedUnrequestedCallers+=1),null;let d=i.expression,p=this.compilerSymbolForExpression(e,d,s),u=null;if(p)if(s&&(s.targetSymbolHits+=1),o.has(p))s&&(s.compilerSymbolCacheHits+=1),u=o.get(p)??null;else{s&&(s.compilerSymbolCacheMisses+=1);let g=s?y.now():0;u=this.definitionFromCompilerSymbol(p,s),s&&(s.targetLookupMs+=y.now()-g),o.set(p,u)}else s&&(s.targetMisses+=1);return u?{callerId:l.symbolId,target:{symbol:u.symbol,file:u.file,line:u.line}}:null}compilerSymbolForExpression(e,t,n){let i=n?y.now():0,o=e.getSymbolAtLocation(t);if(n&&(n.expressionSymbolMs+=y.now()-i),o)return o;n&&(n.typeFallbacks+=1);let a=n?y.now():0,s=e.getTypeAtLocation(t).getSymbol();return n&&(n.typeSymbolMs+=y.now()-a),s}compilerCheckerForSourceFile(e){let t=e.getProject(),n=this.compilerCheckerCache.get(t);return n||(n=t.getTypeChecker().compilerObject,this.compilerCheckerCache.set(t,n)),n}};function Ze(r){let e=[],t=r.getDefaultImport();t&&e.push({identifier:t,importedName:"default",localName:t.getText(),kind:"default",isTypeOnly:r.getImportClause()?.isTypeOnly()??!1});let n=r.getNamespaceImport();n&&e.push({identifier:n,importedName:"*",localName:n.getText(),kind:"namespace",isTypeOnly:r.getImportClause()?.isTypeOnly()??!1});for(let i of r.getNamedImports()){let o=i.getNameNode(),s=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);e.push({identifier:s,importedName:o.getText(),localName:s?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(r.getImportClause()?.isTypeOnly()??!1)})}return e.length===0&&e.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),e}function fi(r,e,t){return{importer:r,sourcePath:e,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function mi(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function hi(r){for(let e=r;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function gi(r,e,t){let n=r.get(e);n||(n=[],r.set(e,n)),n.push(t)}function yi(r){let e=new Set;for(let t of r.getImportDeclarations())for(let n of Ze(t))n.localName&&e.add(n.localName);return e}function Si(r,e){let t=null;for(let n of r)e<n.startLine||e>n.endLine||(!t||n.startLine>=t.startLine)&&(t=n);return t}function Qe(r,e){return r.getLineAndCharacterOfPosition(e.getStart(r)).line}function xr(r,e,t){return e===r.relativePath&&t>=r.startLine&&t<=r.endLine}function Ir(r){return r.symbol.includes("#")?O(r.symbol)==="type"&&r.relativePath.endsWith(".d.ts"):!1}function bi(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function vi(r){return{...r,callerLookupMs:Math.round(r.callerLookupMs),expressionSymbolMs:Math.round(r.expressionSymbolMs),typeSymbolMs:Math.round(r.typeSymbolMs),targetLookupMs:Math.round(r.targetLookupMs),declarationsMs:Math.round(r.declarationsMs),declarationLocationMs:Math.round(r.declarationLocationMs),indexedLookupMs:Math.round(r.indexedLookupMs)}}function Rr(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function Cr(r){return{...r,scanMs:Math.round(r.scanMs),packageRefsMs:Math.round(r.packageRefsMs),semanticRefsMs:Math.round(r.semanticRefsMs),hierarchyMs:Math.round(r.hierarchyMs)}}function xi(r,e,t){for(let n of e){let i=r.get(n)??[];i.push(...t),r.set(n,i)}}function Ii(r){let e=new Set,t=[];for(let n of r){let i=`${n.symbol}|${n.file}|${n.line}`;e.has(i)||(e.add(i),t.push(n))}return t}function wr(r){return r.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var xe=class{loadModule;discoverTsconfigs;createProjects;createProvider;db;module=null;projects=null;provider=null;stats={providerRequests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0};constructor(e,t={}){this.db=e,this.loadModule=t.loadModule??Nt,this.discoverTsconfigs=t.discoverTsconfigs??br,this.createProjects=t.createProjects??jt,this.createProvider=t.createProvider??((n,i,o)=>Mr(n,i,o,{reusedProjects:!0}))}semanticProvider(){return this.stats.providerRequests+=1,this.provider?(this.stats.sessionsReused+=1,this.provider):this.createSession()}advanceGeneration(e,t){let n=Ri(t);return this.provider?.dispose?.(),this.provider=null,this.db=e,this.projects?n.mode==="replace"?(this.projects=null,this.module=null,this.stats.sessionsReplaced+=1,n):(n.mode==="refresh"&&(Ci(this.projects,e.config.projectRoot,n),this.stats.sessionsRefreshed+=1),n):n}snapshotStats(){return{...this.stats}}dispose(){this.provider?.dispose?.(),this.provider=null,this.projects=null,this.module=null}createSession(){let e=this.module??this.loadModule();if(!e)return this.provider=_e("ts-morph is not installed"),this.provider;if(this.module=e,!this.projects){let t=this.discoverTsconfigs(this.db);if(t.length===0)return this.provider=_e("no tsconfig found"),this.provider;this.projects=this.createProjects(e,t),this.stats.projectsCreated+=this.projects.length}return this.provider=this.createProvider(this.db,e,this.projects),this.stats.sessionsCreated+=1,this.provider}};function Ri(r){let e=new Set;r.projectIdentityChanged&&e.add("project-identity-changed");for(let o of r.uncertainty)e.add(o);for(let o of r.changes)o.inputKind!=="source"&&e.add(`${o.inputKind}-input-changed`);if(e.size>0)return{mode:"replace",addedFiles:[],modifiedFiles:[],deletedFiles:[],reasons:[...e].sort()};let t=et(r.changes,"added"),n=et(r.changes,"modified"),i=et(r.changes,"deleted");return{mode:t.length+n.length+i.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:n,deletedFiles:i,reasons:[]}}function et(r,e){return r.filter(t=>t.kind===e).map(t=>t.path).sort()}function Ci(r,e,t){for(let n of r){for(let i of t.deletedFiles)n.project.getSourceFile(kr(e,i))?.forget();for(let i of t.modifiedFiles){let o=n.project.getSourceFile(kr(e,i));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&n.project.addSourceFilesFromTsConfig(n.tsconfigPath)}}var Re=class{openDb;createHost;generationIdentity;readSnapshot;now;db=null;host=null;generation=null;snapshot=null;requests=0;lastRequestAtMs=null;lastError=null;available=null;constructor(e){this.openDb=e.openDb,this.createHost=e.createHost??(t=>new xe(t)),this.generationIdentity=e.generationIdentity??Z,this.readSnapshot=e.readSnapshot??Ti,this.now=e.now??Date.now}handle(e,t){try{this.syncGeneration(e);let n=this.host.semanticProvider();switch(this.available=n.availability().available,this.requests+=1,this.lastRequestAtMs=this.now(),this.lastError=null,t.kind){case"availability":return n.availability();case"import-usage":return n.importUsage(t.file);case"references":return[...ki(n,t.definitions,{exact:t.exact===!0})];case"reference-fragments":if(!n.referenceFragmentsForFiles)throw new Error("TypeScript provider does not support reference fragments.");return[...n.referenceFragmentsForFiles(t.files)];case"callees":return[...Pi(n,t.definitions)];case"signature":return n.signatureFor(t.definition);default:return Ei(t)}}catch(n){throw this.lastError=n instanceof Error?n.message:String(n),n}}status(){let e=this.host?.snapshotStats();return{protocolVersion:X,state:this.lastError?"error":this.host?this.available?"ready":"unavailable":"idle",requests:this.requests,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastError?{lastError:this.lastError}:{},sessionsCreated:e?.sessionsCreated??0,sessionsReused:e?.sessionsReused??0,sessionsRefreshed:e?.sessionsRefreshed??0,sessionsReplaced:e?.sessionsReplaced??0,projectsCreated:e?.projectsCreated??0}}closeTypeScriptService(){this.host?.dispose(),this.db?.close(),this.host=null,this.db=null,this.generation=null,this.snapshot=null,this.available=null}syncGeneration(e){if(this.generation===e&&this.host&&this.db)return;let t=this.openDb(),n=this.generationIdentity(t.config.dbPath);if(!n||n!==e)throw t.close(),new Error("TypeScript semantic request does not match the currently published index generation.");let i=this.readSnapshot(t.config.dbPath);if(!this.host||!this.db)this.db=t,this.host=this.createHost(t);else{let o=this.db;this.host.advanceGeneration(t,Di(this.snapshot,i)),this.db=t,o.close()}this.generation=n,this.snapshot=i,this.available=null}};function tt(r){Pr(r.requestDir,{recursive:!0}),Pr(r.responseDir,{recursive:!0})}function Dr(r,e,t={}){tt(r);let n=0;for(let i of wi(r.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=Ie(r.requestDir,i),a=i.slice(0,-5),s=null;try{let c=Qt(Tr(o,"utf8"));if(a=c.id,c.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript semantic request expired before processing.");s=ut(),Te(c.profileEnvironment??{}),t.beforeRequest?.(c.deadlineAtMs);let l=e.handle(c.generation,c.request);F(Ie(r.responseDir,`${a}.json`),{ok:!0,protocolVersion:X,id:a,generation:c.generation,response:l})}catch(c){F(Ie(r.responseDir,`${a}.json`),{ok:!1,protocolVersion:X,id:a,error:c instanceof Error?c.message:String(c)})}finally{s&&Te(s),t.afterRequest?.(),Mi(o,{force:!0}),n+=1}}return n}function ki(r,e,t){return r.referencesForDefinitions?.(e,t)??new Map(e.map(n=>[n.symbolId,r.referencesFor(n)]))}function Pi(r,e){return r.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,r.calleesFor(t)]))}function Ti(r){try{let e=JSON.parse(Tr(Ie(r,"..","meta.json"),"utf8"));return dt(e.fingerprint)}catch{return null}}function Di(r,e){return e?pt(r,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function Ei(r){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(r)}`)}import{mkdirSync as Er,readFileSync as Fi,readdirSync as Ai,rmSync as Li}from"fs";import{resolve as Ce}from"path";var we=class{projectRoot;currentGeneration;createEmitter;now;active=null;requests=0;sessionsCreated=0;sessionsReplaced=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(e){this.projectRoot=Ce(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??Ut,this.now=e.now??Date.now}handle(e,t){let n=this.now();try{if(this.currentGeneration()!==e)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(t);if(i.emitter.producerIdentity!==t.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),a=i.emitter.advance({modifiedFiles:t.modifiedFiles,affectedFiles:t.affectedFiles}),s=this.now()-n;return this.requests+=1,this.lastRequestAtMs=this.now(),this.lastDurationMs=s,this.lastError=null,this.unavailable=!1,{producerIdentity:a.producerIdentity,cold:a.stats.initializations>o.initializations,durationMs:s,fragments:a.fragments.map(c=>({relativePath:c.relativePath,bytesBase64:c.bytes===null?null:Buffer.from(c.bytes).toString("base64"),occurrences:c.occurrences,symbols:c.symbols,referenceFragments:c.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(){let e=this.active?.emitter.snapshotStats();return{protocolVersion:fe,state:this.unavailable?"unavailable":this.lastError?"error":this.active?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,initializations:e?.initializations??0,programUpdates:e?.programUpdates??0,documentsEmitted:e?.documentsEmitted??0,documentsRemoved:e?.documentsRemoved??0,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{}}}close(){this.active=null}emitterFor(e){let t=`${e.tsconfigPath}\0${e.projectArgument}`;if(this.active&&this.active.sessionKey===t&&this.active.projectIdentity===e.projectIdentity)return this.active;let n=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:e.tsconfigPath,projectRoot:e.projectArgument});if(!n.available)throw this.unavailable=!0,new Error(n.reason);return this.active&&(this.sessionsReplaced+=1),this.active={sessionKey:t,projectIdentity:e.projectIdentity,emitter:n.emitter},this.sessionsCreated+=1,this.active}};function rt(r){Er(r.requestDir,{recursive:!0}),Er(r.responseDir,{recursive:!0})}function Fr(r,e,t={}){rt(r);let n=0;for(let i of Ai(r.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=Ce(r.requestDir,i),a=i.slice(0,-5);try{let s=Bt(Fi(o,"utf8"));if(a=s.id,s.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript index request expired before processing.");t.beforeRequest?.(s.deadlineAtMs);let c=e.handle(s.baseGeneration,s.request);F(Ce(r.responseDir,`${a}.json`),{ok:!0,protocolVersion:fe,id:a,baseGeneration:s.baseGeneration,response:c})}catch(s){F(Ce(r.responseDir,`${a}.json`),{ok:!1,protocolVersion:fe,id:a,error:s instanceof Error?s.message:String(s)})}finally{t.afterRequest?.(),Li(o,{force:!0}),n+=1}}return n}import{spawn as Ni}from"child_process";import{closeSync as ji,existsSync as _i,mkdirSync as Oi,openSync as Wi,readFileSync as Nr,rmSync as re,writeFileSync as $i}from"fs";import{dirname as Gi,resolve as ot}from"path";import{fileURLToPath as Ta}from"url";var qi=2e3,Ui=10;function jr(r,e,t){let n=Ee(ot(r));if(t&&Ee(t.projectRoot)===n)return{projectRoot:n,worktreeKind:"git",worktreeId:t.worktreeId,cliVersion:e};let i=mt(n);if(i.kind==="error")throw new Error(`Could not establish Git worktree identity for ${n}: ${i.message}`);return i.kind==="non-git"?{projectRoot:n,worktreeKind:"non-git",cliVersion:e}:{projectRoot:n,worktreeKind:"git",worktreeId:i.identity.worktreeId,cliVersion:e}}function _r(r){let e=r.runtime??Vi,t=H(r.cacheDir),n=Lt(t.statePath),i=n?e.isProcessAlive(n.pid)?{kind:"live",state:n}:{kind:"stale",state:n,reason:"dead-process"}:{kind:"stopped"},o=Hi("stop",i);if(o.kind==="signal-stop")return Ar(o.state.pid,r,e),nt(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};if(o.kind==="clean-stale")return nt(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};let a=ne(t.lockPath);return o.kind==="already-stopped"&&a&&e.isProcessAlive(a.pid)?(Ar(a.pid,r,e),nt(t,a.pid,e),{disposition:"stopped",pid:a.pid}):{disposition:"already-stopped"}}function Or(r,e){F(r,e)}function Wr(r){try{let e=JSON.parse(Nr(r,"utf8"));return e.version!==1||!le(e.at)||e.refreshRequestedAt!==void 0&&!le(e.refreshRequestedAt)||e.refreshDetail!==void 0&&typeof e.refreshDetail!="string"?null:{atMs:Date.parse(e.at),...e.refreshRequestedAt===void 0?{}:{refreshRequestedAtMs:Date.parse(e.refreshRequestedAt)},...e.refreshDetail===void 0?{}:{refreshDetail:e.refreshDetail}}}catch{return null}}function $r(r,e,t={}){let n=t.pid??process.pid,i=t.isProcessAlive??j,o=()=>{},a=ne(r);if(a&&i(a.pid))return{acquired:!1,lockPath:r,message:Lr(r,e,a),release:o};a&&re(r,{force:!0}),Oi(Gi(r),{recursive:!0});let s;try{s=Wi(r,"wx")}catch(d){if(Bi(d)==="EEXIST")return{acquired:!1,lockPath:r,message:Lr(r,e,ne(r)),release:o};throw d}let c={version:1,pid:n,projectRoot:ot(e),startedAt:(t.now??(()=>new Date))().toISOString()};$i(s,`${JSON.stringify(c)}
|
|
42
|
-
`);let l=!1;return{acquired:!0,lockPath:r,message:"",release:()=>{if(l)return;l=!0,ji(s);let d=ne(r);d?.pid===c.pid&&d.startedAt===c.startedAt&&re(r,{force:!0})}}}function ne(r){try{let e=JSON.parse(Nr(r,"utf-8"));return e.version!==1||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.projectRoot!="string"||!le(e.startedAt)?null:e}catch{return null}}function Hi(r,e){switch(r){case"status":return{kind:"report",classification:e};case"ensure":switch(e.kind){case"stopped":return{kind:"start"};case"stale":return e.reason==="old-heartbeat"?{kind:"replace",state:e.state}:{kind:"start"};case"live":return{kind:"reuse",state:e.state};case"incompatible":return{kind:"replace",state:e.state};default:return it(e)}case"stop":switch(e.kind){case"stopped":return{kind:"already-stopped"};case"stale":return e.reason==="old-heartbeat"?{kind:"signal-stop",state:e.state}:{kind:"clean-stale",state:e.state};case"live":case"incompatible":return{kind:"signal-stop",state:e.state};default:return it(e)}default:return it(r)}}function Gr(r){return r.idleTimeoutMs===0||r.watcher.state!=="idle"?!1:r.nowMs-r.lastActivityAtMs>=r.idleTimeoutMs}function Ar(r,e,t){if(!t.isProcessAlive(r))return;t.signalProcess(r);let n=e.stopTimeoutMs??qi,i=t.now()+n;for(;t.now()<=i;){if(!t.isProcessAlive(r))return;t.sleep(Ui)}throw new Error(`scip-query watch service pid ${r} did not stop within ${n}ms.`)}function nt(r,e,t){re(r.statePath,{force:!0}),re(r.activityPath,{force:!0}),ne(r.lockPath)?.pid===e&&!t.isProcessAlive(e)&&re(r.lockPath,{force:!0})}function Lr(r,e,t){return`error: scip-query watch is already running for ${ot(e)}${t?` (pid ${t.pid}, started ${t.startedAt}; lock: ${r})`:` (lock: ${r})`}. Stop that watcher before starting another.`}function Bi(r){return typeof r=="object"&&r&&"code"in r?r.code:void 0}var Vi={now:Date.now,isProcessAlive:j,spawnServer(r,e,t,n){if(!_i(r))throw new Error(`Watch service helper was not found at ${r}. Run npm run build first.`);Ni(process.execPath,[r,e,t,JSON.stringify(n)],{detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"}}).unref()},signalProcess(r){process.kill(r,"SIGTERM")},sleep(r){let e=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(e,0,0,r)}};function it(r){throw new Error(`Unhandled watch service value: ${JSON.stringify(r)}`)}import{existsSync as Br,lstatSync as Me,readFileSync as lt,readdirSync as Vr,realpathSync as qr,rmSync as ie,statSync as Ki}from"fs";import{join as R,resolve as $,sep as Ur}from"path";var zi=3600*1e3,Yi=2*1024*1024*1024,Ji=300*1e3;function Qi(r){let e=r.leases.filter(s=>s.managed&&!s.live&&!s.busy),t=Xi(r.leases,r.locks),n={};for(let s of r.generations)t.has(s.generationId)||(n[s.generationId]=s.unreferencedAt??r.nowMs);let i=r.generations.filter(s=>!t.has(s.generationId)).sort((s,c)=>n[s.generationId]-n[c.generationId]||s.generationId.localeCompare(c.generationId)),o=new Set;for(let s of i)r.nowMs-n[s.generationId]>=r.policy.generationTtlMs&&o.add(s.generationId);let a=r.generations.filter(s=>!o.has(s.generationId)).reduce((s,c)=>s+c.size,0);for(let s of i){if(a<=r.policy.budgetBytes)break;o.has(s.generationId)||(o.add(s.generationId),a-=s.size)}for(let s of o)delete n[s];return{deleteWorktrees:e,deleteGenerations:r.generations.filter(s=>o.has(s.generationId)),deleteLocks:r.locks.filter(s=>!s.live),deleteTemporaries:r.temporaries.filter(s=>!s.live),protectedGenerationIds:[...t].sort(),unreferencedSince:n}}function Xi(r,e){let t=new Set(r.filter(n=>n.managed&&(n.live||n.busy)).flatMap(n=>[n.lease.baseGenerationId,n.lease.activeGenerationId]).filter(n=>n!==void 0));for(let n of e)n.live&&t.add(n.generationId);return t}function Kr(r,e,t={}){if(!$t())return{kind:"disabled"};let n=ft(r);if(!n)return{kind:"unavailable"};let i=R(Oe(),"repositories",n.repositoryId);if(!Br(i))return{kind:"unavailable"};let o=(t.now??Date.now)(),a=R(i,"gc-state.json"),s=to(a);if(!t.force&&s&&o-Date.parse(s.lastSweepAt)<Ji)return{kind:"throttled",sweptAt:s.lastSweepAt};let c=yt(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=Zi(r,i,n.repositoryId,s?.unreferencedSince??{}),d=Qi({nowMs:o,...l,policy:{generationTtlMs:t.policy?.generationTtlMs??zi,budgetBytes:t.policy?.budgetBytes??Yi}}),p=0,u=0;for(let m of d.deleteWorktrees){if(!zr(m.lease))continue;let h=St(R(m.lease.localCacheDir,"cache-lifecycle.lock"));if(h)try{if(at(m.lease,!0))continue;try{_r({projectRoot:m.lease.projectRoot,cacheDir:m.lease.localCacheDir,cliVersion:e})}catch{continue}if(at(m.lease,!0))continue;ie(m.lease.localCacheDir,{recursive:!0,force:!0}),ie(m.leasePath,{force:!0}),u+=1}finally{h.release()}}for(let m of d.deleteLocks)ie(m.path,{force:!0});for(let m of d.deleteTemporaries)ie(m.path,{recursive:!0,force:!0});for(let m of d.deleteGenerations)ie(m.path,{recursive:!0,force:!0}),p+=m.size;xt(R(i,"evidence.db"));let g={kind:"swept",sweptAt:new Date(o).toISOString(),deletedWorktrees:u,deletedGenerations:d.deleteGenerations.length,deletedBytes:p,protectedGenerations:d.protectedGenerationIds.length},f={version:1,lastSweepAt:g.sweptAt,unreferencedSince:d.unreferencedSince,lastResult:g};return F(a,f,{spacing:2,trailingNewline:!0}),g}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function Zi(r,e,t,n){let i=new Set(ht(r).map(l=>$(l.path))),o=[];for(let l of st(R(e,"worktrees"))){if(!l.endsWith(".json"))continue;let d=R(e,"worktrees",l),p=eo(d);if(!p)continue;let u=$(p.projectRoot);o.push({leasePath:d,lease:p,managed:p.repositoryId===t&&zr(p),live:i.has(u)||Br(u),busy:at(p)})}let a=[];for(let l of st(R(e,"locks"))){let d=/^([a-f0-9]{64})\.lock$/.exec(l);if(!d)continue;let p=R(e,"locks",l),u=ct(p),g=u!==void 0&&j(u),f=d[1];a.push({generationId:f,path:p,live:g})}let s=[],c=[];for(let l of st(R(e,"generations"))){let d=/^\.tmp-(\d+)-/.exec(l);if(d){let g=R(e,"generations",l),f=Number(d[1]);try{c.push({path:g,size:Hr(g),live:Number.isSafeInteger(f)&&j(f)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let p=R(e,"generations",l),u;try{u=Me(p)}catch{continue}!u.isDirectory()||u.isSymbolicLink()||s.push({generationId:l,path:p,size:Hr(p),...n[l]===void 0?{}:{unreferencedAt:n[l]}})}return{leases:o,generations:s,locks:a,temporaries:c}}function zr(r){if(r.ownershipChecksum!==qt(r)||$(r.localCacheDir)!==$(Wt(r.projectRoot)))return!1;let e=$(Oe()),t=$(R(e,"projects")),n=$(r.localCacheDir);if(!n.startsWith(`${t}${Ur}`))return!1;try{let i=Me(e),o=Me(t),a=Me(n);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink())return!1;let s=qr(t);return qr(n).startsWith(`${s}${Ur}`)}catch{return!1}}function at(r,e=!1){for(let n of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=ct(R(r.localCacheDir,n));if(i!==void 0&&j(i))return!0}let t=ct(H(r.localCacheDir).lockPath);return t!==void 0&&j(t)}function eo(r){try{let e=JSON.parse(lt(r,"utf8"));return e.version!==1||typeof e.repositoryId!="string"||typeof e.worktreeId!="string"||typeof e.projectRoot!="string"||e.treeOid!==void 0&&typeof e.treeOid!="string"||typeof e.localCacheDir!="string"||e.baseGenerationId!==void 0&&typeof e.baseGenerationId!="string"||e.activeGenerationId!==void 0&&typeof e.activeGenerationId!="string"||typeof e.ownershipChecksum!="string"||!/^[a-f0-9]{64}$/.test(e.ownershipChecksum)||typeof e.lastAction!="string"||e.lastReason!==void 0&&typeof e.lastReason!="string"||typeof e.lastSeenAt!="string"?null:e}catch{return null}}function ct(r){try{let e=JSON.parse(lt(r,"utf8"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function to(r){try{let e=JSON.parse(lt(r,"utf8"));return e.version!==1||typeof e.lastSweepAt!="string"||!Number.isFinite(Date.parse(e.lastSweepAt))||!e.unreferencedSince||typeof e.unreferencedSince!="object"||!e.lastResult?null:e}catch{return null}}function st(r){try{return Vr(r)}catch{return[]}}function Hr(r){let e=0,t=[r];for(;t.length>0;){let n=t.pop();for(let i of Vr(n,{withFileTypes:!0})){let o=R(n,i.name);i.isDirectory()?t.push(o):i.isFile()&&(e+=Ki(o).size)}}return e}var io=1e3,oo=250,so=10;function ao(r){return r==="fresh"?null:{kind:"watch-startup",detail:`index ${r} when watch service started`}}async function co(r,e,t={}){let n=jr(r,e),i=n.projectRoot,o=V(i);o.watch={...o.watch,...t};let a=me(o);if(!a.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let s=B(i,o),c=H(s.cacheDir),l=$r(c.lockPath,i);if(!l.acquired)return;let d=Date.now(),p=d,u={state:"idle"},g,f,m,h=!1,S=!1,w=0,A=0,T=0,L=0,M,C,v=Jt(s.cacheDir),x=Ht(s.cacheDir);tt(v),rt(x);let ke=new Re({openDb:()=>tr(i)}),Pe=new we({projectRoot:i,currentGeneration:()=>Vt(s.dbPath)}),E=(I=!1)=>{if(!S)return;let q=Date.now();!I&&q-A<io||(A=q,Or(c.statePath,{version:1,protocolVersion:je,pid:P.pid,projectRoot:i,...n.worktreeId?{worktreeId:n.worktreeId}:{},cliVersion:e,startedAt:new Date(d).toISOString(),heartbeatAt:new Date(q).toISOString(),lastActivityAt:new Date(p).toISOString(),...a.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(p+a.idleTimeoutMs).toISOString()},watcher:u,...u.state==="idle"&&g?{indexGeneration:g}:{},...f?{lastRefresh:f}:{},...m?{lastError:m}:{},typescriptSemantic:{...ke.status(),...M===void 0?{}:{busyUntil:new Date(M).toISOString()}},typescriptIndex:{...Pe.status(),...C===void 0?{}:{busyUntil:new Date(C).toISOString()}}}))},G=()=>{p=Date.now()},oe=new he({projectRoot:i,config:{...o,watch:a},languages:o.languages,onStatus(I){u=I,I.state!=="idle"&&(g=void 0),I.state!=="idle"&&G(),E(!0)},onReindexComplete(){G();let I=Ge(i,o,s);f=I.lastRefresh,g=I.state==="fresh"?Z(s.dbPath)??void 0:void 0,m=void 0,E(!0)},onError(I){G(),g=void 0,m={at:new Date().toISOString(),message:I.message},E(!0)}}),se=()=>{h=!0};P.once("SIGINT",se),P.once("SIGTERM",se);try{oe.start();let I=Ge(i,o,s);f=I.lastRefresh,g=I.state==="fresh"?Z(s.dbPath)??void 0:void 0;let q=ao(I.state);for(q&&oe.requestRefresh(q,{immediate:!0}),G(),S=!0,E(!0);!h;){let Jr=Fr(x,Pe,{beforeRequest(D){C=D+5e3,E(!0)},afterRequest(){C=void 0,E(!0)}}),Qr=Dr(v,ke,{beforeRequest(D){M=D+5e3,E(!0)},afterRequest(){M=void 0,E(!0)}}),ae=Date.now();if(ae-L>=6e4&&(L=ae,Kr(i,e)),ae-T>=oo){T=ae;let D=Wr(c.activityPath);D&&D.atMs>p&&(p=D.atMs),D?.refreshRequestedAtMs!==void 0&&D.refreshRequestedAtMs>w&&(w=D.refreshRequestedAtMs,G(),oe.requestRefresh({kind:"watch-demand",detail:D.refreshDetail??"stale index observed by a command"},{immediate:!0}))}if((Qr>0||Jr>0)&&(G(),E(!0)),E(),Gr({watcher:u,lastActivityAtMs:p,nowMs:Date.now(),idleTimeoutMs:a.idleTimeoutMs}))break;await lo(so)}}finally{P.off("SIGINT",se),P.off("SIGTERM",se),ke.closeTypeScriptService(),Pe.close(),oe.stop(),Yr(c.statePath,{force:!0}),Yr(c.activityPath,{force:!0}),l.release()}}function lo(r){return new Promise(e=>setTimeout(e,r))}var po=P.argv[1]?no(ro(P.argv[1])).href:null;if(po===import.meta.url){let r=P.argv[2],e=P.argv[3],t=uo(P.argv[4]);if(!r||!e)console.error("watch-service: expected <project-root> <cli-version>"),P.exitCode=1;else try{await co(r,e,t)}catch(n){console.error(`watch-service: ${n instanceof Error?n.message:String(n)}`),P.exitCode=1}}function uo(r){if(!r)return{};try{let e=JSON.parse(r);return e&&typeof e=="object"?e:{}}catch{return{}}}export{co as runWatchServiceServer,ao as startupRefreshTrigger};
|
|
40
|
+
ORDER BY start_line, end_line`,e)}function Un(r){return{symbolId:r.id,symbol:r.symbol,documentId:r.document_id,startLine:r.start_line,startChar:r.start_char??0,endLine:r.end_line,endChar:r.end_char??0,relativePath:r.relative_path,leaf:_(r.symbol),parentTypeName:K(r.symbol),isFunctionLike:cr(r.symbol),isTypeLike:O(r.symbol)==="type",kind:r.kind??null,documentation:r.documentation??null,enclosingSymbol:r.enclosing_symbol??null}}function fr(r,e={}){return Hn(r,e.scope)}function Hn(r,e){return U(r,{scope:e,includeIgnored:!1}).flatMap(t=>W(r,t)).filter(t=>!r.isIgnored(t.relativePath))}function Bn(r,e,t){let n=Se(r).forFile(e,{text:!0}).text,i=Et(r,e);return i?Qn(t,i,n):n?Vn(t,n):t}function Vn(r,e){let t=e.split(/\r?\n/),n=Kn(r,t),i=zn(r,n),o=Yn(i,t);return Jn(r,o)}function Kn(r,e){let t=r.some(i=>ve(i.symbol))?ii(e):null,n=new Map;for(let i of r)n.set(i.symbolId,ni(e,t,i));return n}function zn(r,e){return r.filter(t=>ve(t.symbol)).map(t=>({definition:t,startLine:e.get(t.symbolId)??t.startLine})).sort((t,n)=>t.startLine-n.startLine||t.definition.startLine-n.definition.startLine||t.definition.symbol.localeCompare(n.definition.symbol))}function Yn(r,e){let t=new Map;for(let n=0;n<r.length;n+=1){let i=r[n],o=r[n+1],a=o?Math.max(i.startLine,o.startLine-1):e.length-1;t.set(i.definition.symbolId,{startLine:i.startLine,endLine:oi(e,i.definition,i.startLine,a)})}return t}function Jn(r,e){return r.map(t=>{let n=e.get(t.symbolId);return n?{...t,startLine:n.startLine,endLine:n.endLine}:t})}function Qn(r,e,t=null){let n=new Map;for(let i of e){let o=n.get(i.name);o?o.push(i):n.set(i.name,[i])}return r.map(i=>{if(!ri(i)||!i.leaf)return pr(i,t);let o=n.get(i.leaf);if(!o||o.length===0)return pr(i,t);let a=t?Xn(i,o,t):null;if(a)return{...i,startLine:a.startLine,endLine:a.endLine};let s=o[0],c=Math.abs(s.startLine-i.startLine);for(let l=1;l<o.length;l+=1){let d=o[l],p=Math.abs(d.startLine-i.startLine);p<c&&(s=d,c=p)}return{...i,startLine:s.startLine,endLine:s.endLine}})}function Xn(r,e,t){let n=Zn(r.symbol);if(!n)return null;let i=t.split(/\r?\n/),o=new RegExp(`\\b${Q(n)}\\b`);for(let a of e){let s=ei(i,a.startLine);if(s&&o.test(s))return a}return null}function Zn(r){return r.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function ei(r,e){for(let t=e;t>=0;t-=1){let n=r[t]?.trim()??"";if(n){if(/^impl\b/.test(n))return ti(r,t,e);if(/^(?:struct|enum|trait|mod)\b/.test(n))return null}}return null}function ti(r,e,t){let n=[];for(let i=e;i<=t;i+=1){let o=r[i]??"";if(n.push(o),o.includes("{"))break}return n.join(" ")}function ri(r){return ve(r.symbol)?!0:O(r.symbol)==="term"&&K(r.symbol)===null}function pr(r,e){if(!e||!r.leaf||O(r.symbol)!=="term"||K(r.symbol)!==null)return r;let t=Q(r.leaf),n=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${t}\\b`),o=e.split(/\r?\n/).findIndex(a=>n.test(a));return o>=0?{...r,startLine:o,endLine:o}:r}function ni(r,e,t){if(!ve(t.symbol))return t.startLine;let n=Math.max(0,Math.min(t.startLine,r.length-1));if(!e)return n;let i=e.get(t.leaf);if(!i||i.length===0)return n;let o=null;for(let a of i){let s=Math.abs(a-t.startLine);(!o||s<o.distance)&&(o={line:a,distance:s})}return o?.line??n}function ii(r){let e=/\b(?:function|def|fn)\s+([A-Za-z_$][\w$]*)/g,t=/\b([A-Za-z_$][\w$]*)\s*[:=]\s*(?:async\s*)?(?:function\b|\()/g,n=/^\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,a=(s,c)=>{let l=o.get(s);if(!l){o.set(s,[c]);return}l[l.length-1]!==c&&l.push(c)};for(let s=0;s<r.length;s+=1){let c=r[s]??"";for(let d of c.matchAll(e))d[1]&&a(d[1],s);for(let d of c.matchAll(t))d[1]&&a(d[1],s);let l=c.match(n);l?.[1]&&a(l[1],s);for(let d of c.matchAll(i))d[1]&&a(d[1],s)}return o}function oi(r,e,t,n){let i=Math.max(t,Math.min(r.length-1,n)),o=Math.max(t,Math.min(i,e.endLine)),a=0,s=0,c=!1;for(let l=t;l<=i;l+=1){let d=si(r[l]??"");for(let p of d)p==="{"?(a+=1,c=!0):p==="}"?a=Math.max(0,a-1):p==="("?s+=1:p===")"&&(s=Math.max(0,s-1));if(c&&a===0||!c&&s===0&&l>=o)return l}return o}function si(r){let e="",t=null,n=!1;for(let i=0;i<r.length;i+=1){let o=r[i],a=r[i+1];if(!t&&o==="/"&&a==="/"){e+=" ".repeat(r.length-i);break}if(t){if(n){n=!1,e+=" ";continue}if(o==="\\"){n=!0,e+=" ";continue}o===t&&(t=null),e+=" ";continue}if(o==='"'||o==="'"||o==="`"){t=o,e+=" ";continue}e+=o}return e}function ve(r){return r.includes("().")}function k(r,e,t){if(r.has(e))return r.get(e);let n=t();return r.set(e,n),n}import mr from"path";function ai(r,e){return r.getReferences().map(t=>{let n=t.getNode();return xe(n,e)})}function ci(r){let e=r;return typeof e.findReferences=="function"?e.findReferences():[]}function hr(r,e,t,n){let i=[];for(let o of ci(r))for(let a of ai(o,n))a.file===e.relativePath&&a.line>=e.startLine&&a.line<=e.endLine||i.push(a);for(let o of t)i.push(o);return z(i)}function gr(r,e,t,n){let i=[],o=t?.getStart();for(let a of r.getReferences()){let s=a.getNode();Y(n,s.getSourceFile().getFilePath())===e&&(o!==void 0&&s.getStart()===o||i.push({location:xe(s,n),node:s}))}return i}function xe(r,e){let t=r.getSourceFile(),n=t.getLineAndColumnAtPos(r.getStart());return{file:Y(e,t.getFilePath())??t.getBaseName(),line:n.line-1,column:n.column-1}}function yr(r,e,t){let n=r.getSourceFile(),i=Be(n,r),o=r.getText(),a=new RegExp(`\\b${Q(o)}\\b`,"g"),s=n.getFullText().split(`
|
|
41
|
+
`),c=[];for(let l=0;l<s.length;l++){if(l===i)continue;let d=s[l]??"";a.lastIndex=0;let p;for(;(p=a.exec(d))!==null;)c.push({file:e,line:l,column:p.index})}return z(c.filter(l=>Y(t,mr.join(t,l.file))===e))}function He(r){for(let e=r;e;e=e.getParent()){let t=e.getKindName();if(t.includes("Type")||t==="InterfaceDeclaration"||t==="TypeAliasDeclaration")return!0;if(t==="CallExpression"||t==="NewExpression"||t==="ExpressionStatement")return!1}return!1}function Be(r,e){return r.getLineAndColumnAtPos(e.getStart()).line-1}function z(r){let e=new Set,t=[];for(let n of r){let i=`${n.file}:${n.line}:${n.column}`;e.has(i)||(e.add(i),t.push(n))}return t}function Y(r,e){let t=mr.relative(r||process.cwd(),e).replace(/\\/g,"/");return!t||t.startsWith("..")?null:t}function Sr(r,e,t,n){let i=li(e,n);return i.size===0?new Map:di(r,t,i)}function li(r,e){let t=new Map;for(let n of W(r,e)){let i=_(n.symbol)??n.leaf;if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push(n)}return t}function di(r,e,t){let n=new Map,i=new Map;return e.forEachDescendant(o=>{for(let a of pi(r,o)){let s=t.get(a);if(!s)continue;let c=Be(e,o);for(let l of s){if(c<l.startLine-1||c>l.endLine+1)continue;let d=Math.abs(c-l.startLine),p=i.get(l.symbolId);p!==void 0&&p<=d||(i.set(l.symbolId,d),n.set(l.symbolId,o))}}}),n}function pi(r,e){let t=[],n=i=>{i&&!t.includes(i)&&t.push(i)};if("getNameNode"in e&&typeof e.getNameNode=="function"){let i=e.getNameNode();n(i?.getText())}if("getName"in e&&typeof e.getName=="function"){let i=e.getName();n(i)}return r.Node.isIdentifier(e)&&n(e.getText()),t}var ui=J("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function br(r,e,t,n){let i=ze(r,e),o=Ve(i.get(n)??[],t);if(o)return o;let a=[];for(let s of i.values())for(let c of s)((c.leaf||_(c.symbol)||"").includes(n)||c.symbol.includes(n))&&a.push(c);return Ve(a,t)}function Ke(r,e,t,n){return Ve(ze(r,e).get(n)??[],t)}function vr(r,e){let t=new Map;for(let[n,i]of ze(r,e)){let o=i[0];o&&t.set(n,o)}return t}function ze(r,e){return ui.get(r,e,()=>{let t=new Map;for(let n of W(r,e)){let i=n.leaf||_(n.symbol);if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push({...n,leaf:i})}for(let n of t.values())n.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return t})}function Ve(r,e){let t=null,n=Number.POSITIVE_INFINITY;for(let i of r){let o=Math.abs(i.startLine-e);(o<n||o===n&&t&&i.startLine<t.startLine)&&(t=i,n=o)}return t}import Ye from"path";function xr(r,e){let t=new Map,n=null,i=null,o=()=>(i??=U(r,{extensions:de}),i),a=()=>(n??=N("typescript.source-file-index",()=>fi(r.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),n),s=c=>pe(c)?k(t,c,()=>{let l=ee(Ye.resolve(r.config.projectRoot,c));for(let{project:d,sourceFiles:p}of a()){let u=p.get(l)??null;if(u||(u=d.addSourceFileAtPathIfExists(l)??null,u&&p.set(ee(u.getFilePath()),u)),u)return{project:d,sourceFile:u}}return null}):null;return{sourceFile:c=>s(c)?.sourceFile??null,sourceFileMatch:s,indexedTypeScriptLikeDocuments:o}}function fi(r,e,t){let n=e.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[ee(o.getFilePath()),o]))}));for(let i of t){let o=ee(Ye.resolve(r,i));for(let a of n){if(a.sourceFiles.has(o))break;let s=a.project.addSourceFileAtPathIfExists(o)??null;if(s){a.sourceFiles.set(ee(s.getFilePath()),s);break}}}return n}function ee(r){return Ye.resolve(r)}function Je(r,e){for(let t of r)if(e===t.name||e.startsWith(`${t.name}/`))return t.name;return null}function Ir(r){let e=`${r.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as te,readFileSync as mi}from"fs";import x from"path";var Qe=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Xe(r,e){let n=e?x.dirname(x.join(r,e)):r,i=x.resolve(r);for(;n.startsWith(i);){for(let a of Qe){let s=x.join(n,a);if(te(s))return s}let o=x.dirname(n);if(o===n)break;n=o}for(let o of Qe){let a=x.join(r,o);if(te(a))return a}return null}function Rr(r){let e=r.config.projectRoot,t=new Set(hi(e,r.config.semantic?.typescript?.tsconfigs)),n=U(r,{includeIgnored:!1,extensions:de});for(let i of n){let o=Xe(e,i);o&&t.add(x.resolve(o))}if(t.size===0){let i=Xe(e);i&&t.add(x.resolve(i))}return[...t].filter(i=>!Cr(e,i)).sort((i,o)=>i.localeCompare(o))}function hi(r,e=[]){let t=new Set;for(let n of e){let i=x.isAbsolute(n)?n:x.join(r,n);te(i)&&t.add(x.resolve(i))}for(let n of gi(r))for(let i of Qe){let o=x.join(n,i);te(o)&&t.add(x.resolve(o))}if(t.size===0){let n=Xe(r);n&&t.add(x.resolve(n))}return[...t].filter(n=>!Cr(r,n)).sort((n,i)=>n.localeCompare(i))}function gi(r){let e=x.join(r,"package.json");if(!te(e))return[];let t;try{t=JSON.parse(mi(e,"utf8"))}catch{return[]}return(Array.isArray(t.workspaces)?t.workspaces:t.workspaces?.packages??[]).flatMap(i=>At(r,i))}function Cr(r,e){let t=x.relative(r,e).replace(/\\/g,"/");return t.startsWith("..")||t.includes("/node_modules/")||t.startsWith("node_modules/")||t.includes("/dist/")||t.startsWith("dist/")}var yi=32;function Dr(r,e,t,n={}){return N("typescript.provider.construct",()=>new et(r,e,t),()=>({tsconfigs:t.length,reusedProjects:n.reusedProjects===!0}))}var et=class{constructor(e,t,n){this.db=e;this.tsMorph=t;this.projects=n;this.workspacePackages=Ft(e.config.projectRoot),this.sourceFiles=xr(e,n)}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;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(e=>e.tsconfigPath)}}importUsage(e){return k(this.importUsageCache,e,()=>{let t=this.sourceFiles.sourceFile(e);if(!t)return[];let n=bi();return N("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,t,n),()=>({file:e,...n}))})}referencesFor(e){return k(this.referencesCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,t)})}referencesForDefinitions(e,t={}){let n=new Map,i=ce(),o=[];for(let d of e){let p=this.referencesCache.get(d.symbolId);p?n.set(d.symbolId,p):o.push(d)}if(o.length===0)return n;let a=o,s=t.exact?[]:o.filter(d=>!kr(d));if(s.length>=yi){let d=this.referencesForDefinitionsBySymbolScan(s);for(let p of s){let u=d.get(p.symbolId)??[];this.referencesCache.set(p.symbolId,u),n.set(p.symbolId,u)}if(a=o.filter(p=>kr(p)),a.length===0)return n}let c=new Map;for(let d of a){let p=c.get(d.relativePath);p?p.push(d):c.set(d.relativePath,[d])}let l=[];for(let[d,p]of c){let u=Mr();N("typescript.references-map.file",()=>{let g=this.definitionNodesForFile(d);for(let f of p){i&&(u.cacheMisses+=1);let m=g.get(f.symbolId)??null;i&&(m?u.nodeHits+=1:u.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(f,m,i?u:void 0);this.referencesCache.set(f.symbolId,h),n.set(f.symbolId,h)}catch{u.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:d,definitions:p.length,...Pr(u)}))}if(l.length>0){let d=this.referencesForDefinitionsBySymbolScan(l);for(let p of l){let u=d.get(p.symbolId)??[];this.referencesCache.set(p.symbolId,u),n.set(p.symbolId,u)}}return n}referenceFragmentsForFiles(e){let t=fr(this.db).filter(o=>pe(o.relativePath)),n=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,n);return $t(t,i,n)}referencesForDefinitionsBySymbolScan(e,t){let n=ce(),i=Mr(),o=new Map,a=new Set(e.map(c=>c.symbolId)),s=new Map(e.map(c=>[c.symbolId,c]));for(let c of e)o.set(c.symbolId,[]);return N("typescript.references-map.inverted-scan",()=>{let c=n?y.now():0,l=t?this.packageImportReferencesForFiles(t):this.packageImportReferences();for(let h of e){let S=l.get(h.symbolId)??[];if(S.length>0){let w=o.get(h.symbolId)??[];w.push(...S),o.set(h.symbolId,w)}n&&(i.packageReferenceCount+=S.length)}n&&(i.packageRefsMs+=y.now()-c);let d=new Map,p=new Map,u=this.hierarchyTargetsForDefinitions(e),g=new Set(e.map(h=>h.leaf).filter(Boolean)),f=n?y.now():0;for(let h of t??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(h))continue;let S=this.sourceFiles.sourceFile(h);S&&(n&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(S,h,a,s,u,g,d,p,o,n?i:void 0))}n&&(i.scanMs+=y.now()-f);let m=n?y.now():0;this.addHierarchyMemberReferences(e,o,n?i:void 0),n&&(i.hierarchyMs+=y.now()-m);for(let[h,S]of o){let w=z(S);o.set(h,w),n&&(i.referenceCount+=w.length)}},()=>({definitions:e.length,...Pr(i)})),o}addReferencesFromSourceFileScan(e,t,n,i,o,a,s,c,l,d){let p=this.compilerCheckerForSourceFile(e),u=e.compilerNode,g=Ii(e),f=m=>{if(this.tsMorph.ts.isIdentifier(m)){if(d&&(d.identifiers+=1),!a.has(m.text)&&!g.has(m.text)){this.tsMorph.ts.forEachChild(m,f);return}let h=this.compilerReferenceSymbol(p,m,d);if(h){let S;s.has(h)?S=s.get(h)??null:(S=this.referenceDefinitionFromCompilerSymbol(h),s.set(h,S)),d&&(S?d.targetHits+=1:d.targetMisses+=1);let w=k(c,h,()=>this.compilerSymbolKeys(h)),A=null,P=null,L=S&&n.has(S.symbolId)?i.get(S.symbolId):void 0;if(L&&(A=Ze(u,m),!wr(L,t,A))){let D=u.getLineAndCharacterOfPosition(m.getStart(u));P={file:t,line:D.line,column:D.character};let C=l.get(L.symbolId)??[];C.push(P),l.set(L.symbolId,C),d&&(d.requestedHits+=1)}for(let D of w)for(let C of o.get(D)?.values()??[]){if(A??=Ze(u,m),wr(C,t,A))continue;if(!P){let I=u.getLineAndCharacterOfPosition(m.getStart(u));P={file:t,line:I.line,column:I.character}}let b=l.get(C.symbolId)??[];b.push(P),l.set(C.symbolId,b),d&&(d.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(m,f)};f(u)}hierarchyTargetsForDefinitions(e){let t=new Map;for(let n of e){let i=this.nodeForDefinition(n),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let a=o.parent;if(!this.isHierarchyContainer(a))continue;let s=this.compilerCheckerForSourceFile(i.getSourceFile()),c=s.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(s,a,c))for(let d of this.compilerSymbolKeys(l)){let p=t.get(d)??new Map;p.set(n.symbolId,n),t.set(d,p)}}return t}hierarchyMemberSymbols(e,t,n){let i=new Set,o=new Set,a=(s,c,l)=>{if(!o.has(s)){o.add(s),i.add(c);for(let d of l){let p=d.getProperty(n.name);p&&a(d,p,this.hierarchyAncestorTypesForType(e,d))}}};return a(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}addHierarchyMemberReferences(e,t,n){let i=new Map;for(let o of e){let a=this.nodeForDefinition(o),s=a?.compilerNode;if(!s||!this.isHierarchyMethod(s))continue;let c=s.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(a.getSourceFile()),d=l.getSymbolAtLocation(s.name);if(!d)continue;let p=s.getSourceFile(),u=p.getLineAndCharacterOfPosition(s.name.getStart(p)),g={definition:o,location:{file:o.relativePath,line:u.line,column:u.character}},f=t.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(l,c,d))if(h!==d)for(let S of this.compilerSymbolLocations(h))f.push(S),n&&(n.hierarchyReferences+=1);t.set(o.symbolId,f);let m=this.hierarchyRootMemberSymbols(l,c,d);for(let h of m){let S=i.get(h)??new Map;S.set(o.symbolId,g),i.set(h,S)}n&&(n.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){n&&(n.hierarchyFamilies+=1);for(let{definition:a}of o.values()){let s=t.get(a.symbolId)??[];for(let c of o.values())c.definition.symbolId!==a.symbolId&&(s.push(c.location),n&&(n.hierarchyReferences+=1));t.set(a.symbolId,s)}}}hierarchyRootMemberSymbols(e,t,n){let i=new Set,o=new Set,a=(s,c,l)=>{if(o.has(s))return;o.add(s);let d=!1;for(let p of l){let u=p.getProperty(n.name);u&&(d=!0,a(p,u,this.hierarchyAncestorTypesForType(e,p)))}if(!d)for(let p of this.compilerSymbolKeys(c))i.add(p)};return a(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}compilerSymbolKeys(e){return(e.declarations??[]).map(t=>{let n=t.getSourceFile();return`${n.fileName}\0${t.getStart(n)}\0${e.name}`})}compilerSymbolLocations(e){let t=[];for(let n of e.declarations??[]){let i=n.getSourceFile(),o=Y(this.db.config.projectRoot,i.fileName);if(!o)continue;let a=n.name,s=i.getLineAndCharacterOfPosition((a??n).getStart(i));t.push({file:o,line:s.line,column:s.character})}return t}baseTypes(e,t){try{return e.getBaseTypes(t)??[]}catch{return[]}}hierarchyAncestorTypes(e,t){let n=new Set(this.hierarchyAncestorTypesForType(e,e.getTypeAtLocation(t)));for(let i of t.heritageClauses??[])for(let o of i.types)n.add(e.getTypeAtLocation(o));return[...n]}hierarchyAncestorTypesForType(e,t){let n=new Set(this.baseTypes(e,t));for(let i of t.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let a of o.types)n.add(e.getTypeAtLocation(a));return[...n]}isHierarchyMethod(e){return this.tsMorph.ts.isMethodDeclaration(e)||this.tsMorph.ts.isMethodSignature(e)}isHierarchyContainer(e){return this.tsMorph.ts.isClassDeclaration(e)||this.tsMorph.ts.isClassExpression(e)||this.tsMorph.ts.isInterfaceDeclaration(e)}compilerReferenceSymbol(e,t,n){n&&(n.symbolLookups+=1);let i=e.getSymbolAtLocation(t);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return n&&(n.aliasResolutions+=1),e.getAliasedSymbol(i)}catch{return i}}}calleesFor(e){return k(this.calleesCache,e.symbolId,()=>k(this.fileCalleesCache,e.relativePath,()=>this.calleeMapForFile(e.relativePath)).get(e.symbolId)??[])}calleesForDefinitions(e){let t=new Map,n=new Map;for(let i of e){let o=n.get(i.relativePath);o?o.push(i):n.set(i.relativePath,[i])}for(let[i,o]of n){let a=this.fileCalleesCache.get(i),s=new Set(o.map(l=>l.symbolId)),c=a??this.calleeMapForFile(i,s);for(let l of o){let d=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,d),t.set(l.symbolId,d)}}return t}referencesForDefinitionNode(e,t,n){let i=n?y.now():0,o=this.packageImportReferencesForDefinition(e);if(n&&(n.packageRefsMs+=y.now()-i,n.packageReferenceCount+=o.length),!t)return o;let a=n?y.now():0,s=hr(t,e,o,this.db.config.projectRoot);return n&&(n.semanticRefsMs+=y.now()-a,n.referenceCount+=s.length),s}signatureFor(e){return k(this.signatureCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);if(!t||!this.tsMorph.Node.isFunctionDeclaration(t)&&!this.tsMorph.Node.isMethodDeclaration(t)&&!this.tsMorph.Node.isArrowFunction(t)&&!this.tsMorph.Node.isFunctionExpression(t)&&!this.tsMorph.Node.isConstructorDeclaration(t))return null;let n=t.getType().getCallSignatures()[0];if(!n)return null;let i=n.getParameters().map(a=>{let s=a.getDeclarations()[0],c=s?a.getTypeAtLocation(s).getText(s):a.getValueDeclaration()?.getType().getText()??"unknown";return Tr(c)}),o=n.getReturnType().getText(t);return`(${i.join(",")})=>${Tr(o)}`})}importUsageForSourceFile(e,t,n){let i=[],o=new Map;for(let a of t.getImportDeclarations()){n.declarations+=1;let s=Ne(this.db,e,a.getModuleSpecifierValue()),c=a.getImportClause()?.isTypeOnly()??!1;for(let l of tt(a)){n.entries+=1;let d=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(d?n.bindingSymbols+=1:n.missingBindingSymbols+=1);let p={sourcePath:s,entry:l,typeOnlyDeclaration:c,bindingSymbol:d,references:[]};if(i.push(p),c||!l.localName||!d)continue;let u=o.get(l.localName);u?u.push(p):o.set(l.localName,[p])}}return o.size>0&&t.forEachDescendant(a=>{if(a.getKindName()!=="Identifier")return;let s=o.get(a.getText());if(!s||vi(a))return;n.scannedIdentifiers+=1;let c=a.getSymbol()?.compilerSymbol;if(n.symbolLookups+=1,!!c){for(let l of s)if(l.bindingSymbol===c){l.references.push({location:xe(a,this.db.config.projectRoot),node:a}),n.matchedReferences+=1;break}}}),i.map(a=>a.typeOnlyDeclaration?Si(e,a.sourcePath,a.entry):a.entry.identifier&&!a.bindingSymbol?(n.fallbackEntries+=1,this.valueImportUsageForEntry(e,a.sourcePath,a.entry)):this.valueImportUsageFromLocations(e,a.sourcePath,a.entry,a.references))}valueImportUsageForEntry(e,t,n){let i=n.identifier?n.identifier.findReferences():[],o=[];for(let a of i)for(let s of gr(a,e,n.identifier,this.db.config.projectRoot))o.push(s);return this.valueImportUsageFromLocations(e,t,n,o)}valueImportUsageFromLocations(e,t,n,i){let o=i.some(c=>!He(c.node)),a=i.some(c=>He(c.node)),s=n.isTypeOnly;return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:s,isUsed:s||i.length>0,isTypeUsed:s||a,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(e){return this.packageImportReferences().get(e.symbolId)??[]}packageImportReferencesForFiles(e){let t=new Map,n=new Set;for(let o of e){let a=this.sourceFiles.sourceFile(o);if(a)for(let s of a.getImportDeclarations()){let c=Je(this.workspacePackages,s.getModuleSpecifierValue());c&&n.add(c)}}if(n.size===0)return t;let i=this.packageExportsForNames(n);for(let o of e)this.addPackageImportReferencesForDocument(t,i,o);for(let[o,a]of t)t.set(o,z(a));return t}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let e=new Map,t=this.packageExports();for(let n of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(e,t,n);for(let[n,i]of e)e.set(n,z(i));return this.packageImportReferenceIndex=e,e}addPackageImportReferencesForDocument(e,t,n){if(this.db.isIgnored(n))return;let i=this.sourceFiles.sourceFileMatch(n);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(e,t,n,o)}addPackageImportReferencesForDeclaration(e,t,n,i){let o=Je(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let a=t.get(o);if(a)for(let s of tt(i)){if(s.kind!=="named"||!s.identifier)continue;let c=a.get(s.importedName);if(!c||c.size===0)continue;let l=yr(s.identifier,n,this.db.config.projectRoot);l.length>0&&ki(e,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(e=>e.name))),this.packageExportIndex)}packageExportsForNames(e){let t=new Map;for(let n of this.workspacePackages){if(!e.has(n.name))continue;let i=new Map;for(let o of Ir(n))this.collectPackageExports(n,o,i,new Set);i.size>0&&t.set(n.name,i)}return t}collectPackageExports(e,t,n,i){if(i.has(t))return;i.add(t);let o=this.sourceFiles.sourceFile(t);if(o)for(let a of o.getExportDeclarations()){let s=a.getModuleSpecifierValue(),c=s?Ne(this.db,t,s):t;if(!c||!c.startsWith(`${e.relativeDir}/src/`))continue;let l=a.getNamedExports();if(l.length===0){if(a.isNamespaceExport())continue;this.collectPackageExports(e,c,n,i);continue}for(let d of l){let p=d.getNameNode().getText(),u=d.getAliasNode()?.getText()??p,g=this.indexedDefinitionByLeaf(c,p);if(!g)continue;let f=n.get(u);f||(f=new Set,n.set(u,f)),f.add(g.symbolId)}}}indexedDefinitionByLeaf(e,t){return k(this.indexedDefinitionLeafCache,e,()=>vr(this.db,e)).get(t)??null}nodeForDefinition(e){return k(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return k(this.fileDefinitionNodeCache,e,()=>{let t=this.sourceFiles.sourceFile(e);return t?Sr(this.tsMorph,this.db,t,e):new Map})}referenceDefinitionFromCompilerSymbol(e){return this.definitionFromCompilerSymbol(e,void 0,!0)}definitionFromCompilerSymbol(e,t,n=!1){let i=e.name,o=t?y.now():0,a=e.declarations??[];t&&(t.declarationsMs+=y.now()-o,t.declarationChecks+=a.length);for(let s of a){let c=t?y.now():0,l=s.getSourceFile(),d=Y(this.db.config.projectRoot,l.fileName),p=l.getLineAndCharacterOfPosition(s.getStart(l)).line;if(t&&(t.declarationLocationMs+=y.now()-c),!d||this.db.isIgnored(d))continue;let u=t?y.now():0,g=this.compilerDeclarationName(s),f=n?Ke(this.db,d,p,i)??(g&&g!==i?Ke(this.db,d,p,g):null):br(this.db,d,p,i);if(t&&(t.indexedLookupMs+=y.now()-u),f)return{symbolId:f.symbolId,symbol:f.symbol,file:f.relativePath,line:f.startLine}}return null}compilerDeclarationName(e){let t=e.name;return t&&this.tsMorph.ts.isIdentifier(t)?t.text:null}calleeMapForFile(e,t){let n=ce(),i=0,o=0,a=0,s=0,c=0,l=0,d=0,p=0,u=n?Ci():void 0;return N("typescript.callee-map.file",()=>{let g=n?y.now():0,f=this.sourceFiles.sourceFile(e);if(n&&(c=Math.round(y.now()-g)),!f)return new Map;let m=n?y.now():0,h=W(this.db,e).sort((b,I)=>b.startLine-I.startLine||I.endLine-b.endLine);if(n&&(l=Math.round(y.now()-m)),i=h.length,h.length===0)return new Map;let S=new Map,w=n?y.now():0,A=this.compilerCheckerForSourceFile(f),P=f.compilerNode;n&&(d=Math.round(y.now()-w));let L=new Map,D=b=>{if(this.tsMorph.ts.isCallExpression(b)||this.tsMorph.ts.isNewExpression(b)){n&&(o+=1);let I=this.semanticCalleeForCallNode(A,P,h,b,L,t,u);I&&(n&&(a+=1),xi(S,I.callerId,I.target))}this.tsMorph.ts.forEachChild(b,D)},C=n?y.now():0;D(P),n&&(p=Math.round(y.now()-C));for(let[b,I]of S)S.set(b,Mi(I));return s=S.size,S},()=>({relativePath:e,definitions:i,callNodes:o,resolvedCallees:a,outputRows:s,requestedDefinitions:t?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:p,...u?wi(u):{}}))}semanticCalleeForCallNode(e,t,n,i,o,a,s){let c=s?y.now():0,l=Ri(n,Ze(t,i));if(s&&(s.callerLookupMs+=y.now()-c),!l)return null;if(a&&!a.has(l.symbolId))return s&&(s.skippedUnrequestedCallers+=1),null;let d=i.expression,p=this.compilerSymbolForExpression(e,d,s),u=null;if(p)if(s&&(s.targetSymbolHits+=1),o.has(p))s&&(s.compilerSymbolCacheHits+=1),u=o.get(p)??null;else{s&&(s.compilerSymbolCacheMisses+=1);let g=s?y.now():0;u=this.definitionFromCompilerSymbol(p,s),s&&(s.targetLookupMs+=y.now()-g),o.set(p,u)}else s&&(s.targetMisses+=1);return u?{callerId:l.symbolId,target:{symbol:u.symbol,file:u.file,line:u.line}}:null}compilerSymbolForExpression(e,t,n){let i=n?y.now():0,o=e.getSymbolAtLocation(t);if(n&&(n.expressionSymbolMs+=y.now()-i),o)return o;n&&(n.typeFallbacks+=1);let a=n?y.now():0,s=e.getTypeAtLocation(t).getSymbol();return n&&(n.typeSymbolMs+=y.now()-a),s}compilerCheckerForSourceFile(e){let t=e.getProject(),n=this.compilerCheckerCache.get(t);return n||(n=t.getTypeChecker().compilerObject,this.compilerCheckerCache.set(t,n)),n}};function tt(r){let e=[],t=r.getDefaultImport();t&&e.push({identifier:t,importedName:"default",localName:t.getText(),kind:"default",isTypeOnly:r.getImportClause()?.isTypeOnly()??!1});let n=r.getNamespaceImport();n&&e.push({identifier:n,importedName:"*",localName:n.getText(),kind:"namespace",isTypeOnly:r.getImportClause()?.isTypeOnly()??!1});for(let i of r.getNamedImports()){let o=i.getNameNode(),s=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);e.push({identifier:s,importedName:o.getText(),localName:s?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(r.getImportClause()?.isTypeOnly()??!1)})}return e.length===0&&e.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),e}function Si(r,e,t){return{importer:r,sourcePath:e,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function bi(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function vi(r){for(let e=r;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function xi(r,e,t){let n=r.get(e);n||(n=[],r.set(e,n)),n.push(t)}function Ii(r){let e=new Set;for(let t of r.getImportDeclarations())for(let n of tt(t))n.localName&&e.add(n.localName);return e}function Ri(r,e){let t=null;for(let n of r)e<n.startLine||e>n.endLine||(!t||n.startLine>=t.startLine)&&(t=n);return t}function Ze(r,e){return r.getLineAndCharacterOfPosition(e.getStart(r)).line}function wr(r,e,t){return e===r.relativePath&&t>=r.startLine&&t<=r.endLine}function kr(r){return r.symbol.includes("#")?O(r.symbol)==="type"&&r.relativePath.endsWith(".d.ts"):!1}function Ci(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function wi(r){return{...r,callerLookupMs:Math.round(r.callerLookupMs),expressionSymbolMs:Math.round(r.expressionSymbolMs),typeSymbolMs:Math.round(r.typeSymbolMs),targetLookupMs:Math.round(r.targetLookupMs),declarationsMs:Math.round(r.declarationsMs),declarationLocationMs:Math.round(r.declarationLocationMs),indexedLookupMs:Math.round(r.indexedLookupMs)}}function Mr(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function Pr(r){return{...r,scanMs:Math.round(r.scanMs),packageRefsMs:Math.round(r.packageRefsMs),semanticRefsMs:Math.round(r.semanticRefsMs),hierarchyMs:Math.round(r.hierarchyMs)}}function ki(r,e,t){for(let n of e){let i=r.get(n)??[];i.push(...t),r.set(n,i)}}function Mi(r){let e=new Set,t=[];for(let n of r){let i=`${n.symbol}|${n.file}|${n.line}`;e.has(i)||(e.add(i),t.push(n))}return t}function Tr(r){return r.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Ie=class{loadModule;discoverTsconfigs;createProjects;createProvider;db;module=null;projects=null;provider=null;stats={providerRequests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0};constructor(e,t={}){this.db=e,this.loadModule=t.loadModule??Ot,this.discoverTsconfigs=t.discoverTsconfigs??Rr,this.createProjects=t.createProjects??Wt,this.createProvider=t.createProvider??((n,i,o)=>Dr(n,i,o,{reusedProjects:!0}))}semanticProvider(){return this.stats.providerRequests+=1,this.provider?(this.stats.sessionsReused+=1,this.provider):this.createSession()}advanceGeneration(e,t){let n=Pi(t);return this.provider?.dispose?.(),this.provider=null,this.db=e,this.projects?n.mode==="replace"?(this.projects=null,this.module=null,this.stats.sessionsReplaced+=1,n):(n.mode==="refresh"&&(Ti(this.projects,e.config.projectRoot,n),this.stats.sessionsRefreshed+=1),n):n}snapshotStats(){return{...this.stats}}dispose(){this.provider?.dispose?.(),this.provider=null,this.projects=null,this.module=null}createSession(){let e=this.module??this.loadModule();if(!e)return this.provider=Oe("ts-morph is not installed"),this.provider;if(this.module=e,!this.projects){let t=this.discoverTsconfigs(this.db);if(t.length===0)return this.provider=Oe("no tsconfig found"),this.provider;this.projects=this.createProjects(e,t),this.stats.projectsCreated+=this.projects.length}return this.provider=this.createProvider(this.db,e,this.projects),this.stats.sessionsCreated+=1,this.provider}};function Pi(r){let e=new Set;r.projectIdentityChanged&&e.add("project-identity-changed");for(let o of r.uncertainty)e.add(o);for(let o of r.changes)o.inputKind!=="source"&&e.add(`${o.inputKind}-input-changed`);if(e.size>0)return{mode:"replace",addedFiles:[],modifiedFiles:[],deletedFiles:[],reasons:[...e].sort()};let t=rt(r.changes,"added"),n=rt(r.changes,"modified"),i=rt(r.changes,"deleted");return{mode:t.length+n.length+i.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:n,deletedFiles:i,reasons:[]}}function rt(r,e){return r.filter(t=>t.kind===e).map(t=>t.path).sort()}function Ti(r,e,t){for(let n of r){for(let i of t.deletedFiles)n.project.getSourceFile(Er(e,i))?.forget();for(let i of t.modifiedFiles){let o=n.project.getSourceFile(Er(e,i));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&n.project.addSourceFilesFromTsConfig(n.tsconfigPath)}}var Ce=class{openDb;createHost;generationIdentity;readSnapshot;now;db=null;host=null;generation=null;snapshot=null;requests=0;lastRequestAtMs=null;lastError=null;available=null;constructor(e){this.openDb=e.openDb,this.createHost=e.createHost??(t=>new Ie(t)),this.generationIdentity=e.generationIdentity??Z,this.readSnapshot=e.readSnapshot??Li,this.now=e.now??Date.now}handle(e,t){try{this.syncGeneration(e);let n=this.host.semanticProvider();switch(this.available=n.availability().available,this.requests+=1,this.lastRequestAtMs=this.now(),this.lastError=null,t.kind){case"availability":return n.availability();case"import-usage":return n.importUsage(t.file);case"references":return[...Fi(n,t.definitions,{exact:t.exact===!0})];case"reference-fragments":if(!n.referenceFragmentsForFiles)throw new Error("TypeScript provider does not support reference fragments.");return[...n.referenceFragmentsForFiles(t.files)];case"callees":return[...Ai(n,t.definitions)];case"signature":return n.signatureFor(t.definition);default:return ji(t)}}catch(n){throw this.lastError=n instanceof Error?n.message:String(n),n}}status(){let e=this.host?.snapshotStats();return{protocolVersion:X,state:this.lastError?"error":this.host?this.available?"ready":"unavailable":"idle",requests:this.requests,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastError?{lastError:this.lastError}:{},sessionsCreated:e?.sessionsCreated??0,sessionsReused:e?.sessionsReused??0,sessionsRefreshed:e?.sessionsRefreshed??0,sessionsReplaced:e?.sessionsReplaced??0,projectsCreated:e?.projectsCreated??0}}closeTypeScriptService(){this.host?.dispose(),this.db?.close(),this.host=null,this.db=null,this.generation=null,this.snapshot=null,this.available=null}syncGeneration(e){if(this.generation===e&&this.host&&this.db)return;let t=this.openDb(),n=this.generationIdentity(t.config.dbPath);if(!n||n!==e)throw t.close(),new Error("TypeScript semantic request does not match the currently published index generation.");let i=this.readSnapshot(t.config.dbPath);if(!this.host||!this.db)this.db=t,this.host=this.createHost(t);else{let o=this.db;this.host.advanceGeneration(t,Ni(this.snapshot,i)),this.db=t,o.close()}this.generation=n,this.snapshot=i,this.available=null}};function nt(r){Fr(r.requestDir,{recursive:!0}),Fr(r.responseDir,{recursive:!0})}function Lr(r,e,t={}){nt(r);let n=0;for(let i of Di(r.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=Re(r.requestDir,i),a=i.slice(0,-5),s=null;try{let c=tr(Ar(o,"utf8"));if(a=c.id,c.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript semantic request expired before processing.");s=ht(),De(c.profileEnvironment??{}),t.beforeRequest?.(c.deadlineAtMs);let l=e.handle(c.generation,c.request);F(Re(r.responseDir,`${a}.json`),{ok:!0,protocolVersion:X,id:a,generation:c.generation,response:l})}catch(c){F(Re(r.responseDir,`${a}.json`),{ok:!1,protocolVersion:X,id:a,error:c instanceof Error?c.message:String(c)})}finally{s&&De(s),t.afterRequest?.(),Ei(o,{force:!0}),n+=1}}return n}function Fi(r,e,t){return r.referencesForDefinitions?.(e,t)??new Map(e.map(n=>[n.symbolId,r.referencesFor(n)]))}function Ai(r,e){return r.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,r.calleesFor(t)]))}function Li(r){try{let e=JSON.parse(Ar(Re(r,"..","meta.json"),"utf8"));return ft(e.fingerprint)}catch{return null}}function Ni(r,e){return e?mt(r,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function ji(r){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(r)}`)}import{mkdirSync as Nr,readFileSync as _i,readdirSync as Oi,rmSync as Wi}from"fs";import{resolve as we}from"path";var ke=class{projectRoot;currentGeneration;createEmitter;now;active=null;requests=0;sessionsCreated=0;sessionsReplaced=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(e){this.projectRoot=we(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??Kt,this.now=e.now??Date.now}handle(e,t){let n=this.now();try{if(this.currentGeneration()!==e)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(t);if(i.emitter.producerIdentity!==t.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),a=i.emitter.advance({modifiedFiles:t.modifiedFiles,affectedFiles:t.affectedFiles}),s=this.now()-n;return this.requests+=1,this.lastRequestAtMs=this.now(),this.lastDurationMs=s,this.lastError=null,this.unavailable=!1,{producerIdentity:a.producerIdentity,cold:a.stats.initializations>o.initializations,durationMs:s,fragments:a.fragments.map(c=>({relativePath:c.relativePath,bytesBase64:c.bytes===null?null:Buffer.from(c.bytes).toString("base64"),occurrences:c.occurrences,symbols:c.symbols,referenceFragments:c.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(){let e=this.active?.emitter.snapshotStats();return{protocolVersion:me,state:this.unavailable?"unavailable":this.lastError?"error":this.active?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,initializations:e?.initializations??0,programUpdates:e?.programUpdates??0,documentsEmitted:e?.documentsEmitted??0,documentsRemoved:e?.documentsRemoved??0,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{}}}close(){this.active=null}emitterFor(e){let t=`${e.tsconfigPath}\0${e.projectArgument}`;if(this.active&&this.active.sessionKey===t&&this.active.projectIdentity===e.projectIdentity)return this.active;let n=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:e.tsconfigPath,projectRoot:e.projectArgument});if(!n.available)throw this.unavailable=!0,new Error(n.reason);return this.active&&(this.sessionsReplaced+=1),this.active={sessionKey:t,projectIdentity:e.projectIdentity,emitter:n.emitter},this.sessionsCreated+=1,this.active}};function it(r){Nr(r.requestDir,{recursive:!0}),Nr(r.responseDir,{recursive:!0})}function jr(r,e,t={}){it(r);let n=0;for(let i of Oi(r.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=we(r.requestDir,i),a=i.slice(0,-5);try{let s=Yt(_i(o,"utf8"));if(a=s.id,s.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript index request expired before processing.");t.beforeRequest?.(s.deadlineAtMs);let c=e.handle(s.baseGeneration,s.request);F(we(r.responseDir,`${a}.json`),{ok:!0,protocolVersion:me,id:a,baseGeneration:s.baseGeneration,response:c})}catch(s){F(we(r.responseDir,`${a}.json`),{ok:!1,protocolVersion:me,id:a,error:s instanceof Error?s.message:String(s)})}finally{t.afterRequest?.(),Wi(o,{force:!0}),n+=1}}return n}import{spawn as $i}from"child_process";import{closeSync as Gi,existsSync as qi,mkdirSync as Ui,openSync as Hi,readFileSync as Wr,rmSync as re,writeFileSync as Bi}from"fs";import{dirname as Vi,resolve as at}from"path";import{fileURLToPath as Na}from"url";var Ki=2e3,zi=10;function $r(r,e,t){let n=Fe(at(r));if(t&&Fe(t.projectRoot)===n)return{projectRoot:n,worktreeKind:"git",worktreeId:t.worktreeId,cliVersion:e};let i=yt(n);if(i.kind==="error")throw new Error(`Could not establish Git worktree identity for ${n}: ${i.message}`);return i.kind==="non-git"?{projectRoot:n,worktreeKind:"non-git",cliVersion:e}:{projectRoot:n,worktreeKind:"git",worktreeId:i.identity.worktreeId,cliVersion:e}}function Gr(r){let e=r.runtime??Qi,t=H(r.cacheDir),n=_t(t.statePath),i=n?e.isProcessAlive(n.pid)?{kind:"live",state:n}:{kind:"stale",state:n,reason:"dead-process"}:{kind:"stopped"},o=Yi("stop",i);if(o.kind==="signal-stop")return _r(o.state.pid,r,e),ot(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};if(o.kind==="clean-stale")return ot(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};let a=ne(t.lockPath);return o.kind==="already-stopped"&&a&&e.isProcessAlive(a.pid)?(_r(a.pid,r,e),ot(t,a.pid,e),{disposition:"stopped",pid:a.pid}):{disposition:"already-stopped"}}function qr(r,e){F(r,e)}function Ur(r){try{let e=JSON.parse(Wr(r,"utf8"));return e.version!==1||!le(e.at)||e.refreshRequestedAt!==void 0&&!le(e.refreshRequestedAt)||e.refreshDetail!==void 0&&typeof e.refreshDetail!="string"?null:{atMs:Date.parse(e.at),...e.refreshRequestedAt===void 0?{}:{refreshRequestedAtMs:Date.parse(e.refreshRequestedAt)},...e.refreshDetail===void 0?{}:{refreshDetail:e.refreshDetail}}}catch{return null}}function Hr(r,e,t={}){let n=t.pid??process.pid,i=t.isProcessAlive??j,o=()=>{},a=ne(r);if(a&&i(a.pid))return{acquired:!1,lockPath:r,message:Or(r,e,a),release:o};a&&re(r,{force:!0}),Ui(Vi(r),{recursive:!0});let s;try{s=Hi(r,"wx")}catch(d){if(Ji(d)==="EEXIST")return{acquired:!1,lockPath:r,message:Or(r,e,ne(r)),release:o};throw d}let c={version:1,pid:n,projectRoot:at(e),startedAt:(t.now??(()=>new Date))().toISOString()};Bi(s,`${JSON.stringify(c)}
|
|
42
|
+
`);let l=!1;return{acquired:!0,lockPath:r,message:"",release:()=>{if(l)return;l=!0,Gi(s);let d=ne(r);d?.pid===c.pid&&d.startedAt===c.startedAt&&re(r,{force:!0})}}}function ne(r){try{let e=JSON.parse(Wr(r,"utf-8"));return e.version!==1||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.projectRoot!="string"||!le(e.startedAt)?null:e}catch{return null}}function Yi(r,e){switch(r){case"status":return{kind:"report",classification:e};case"ensure":switch(e.kind){case"stopped":return{kind:"start"};case"stale":return e.reason==="old-heartbeat"?{kind:"replace",state:e.state}:{kind:"start"};case"live":return{kind:"reuse",state:e.state};case"incompatible":return{kind:"replace",state:e.state};default:return st(e)}case"stop":switch(e.kind){case"stopped":return{kind:"already-stopped"};case"stale":return e.reason==="old-heartbeat"?{kind:"signal-stop",state:e.state}:{kind:"clean-stale",state:e.state};case"live":case"incompatible":return{kind:"signal-stop",state:e.state};default:return st(e)}default:return st(r)}}function Br(r){return r.idleTimeoutMs===0||r.watcher.state!=="idle"?!1:r.nowMs-r.lastActivityAtMs>=r.idleTimeoutMs}function _r(r,e,t){if(!t.isProcessAlive(r))return;t.signalProcess(r);let n=e.stopTimeoutMs??Ki,i=t.now()+n;for(;t.now()<=i;){if(!t.isProcessAlive(r))return;t.sleep(zi)}throw new Error(`scip-query watch service pid ${r} did not stop within ${n}ms.`)}function ot(r,e,t){re(r.statePath,{force:!0}),re(r.activityPath,{force:!0}),ne(r.lockPath)?.pid===e&&!t.isProcessAlive(e)&&re(r.lockPath,{force:!0})}function Or(r,e,t){return`error: scip-query watch is already running for ${at(e)}${t?` (pid ${t.pid}, started ${t.startedAt}; lock: ${r})`:` (lock: ${r})`}. Stop that watcher before starting another.`}function Ji(r){return typeof r=="object"&&r&&"code"in r?r.code:void 0}var Qi={now:Date.now,isProcessAlive:j,spawnServer(r,e,t,n){if(!qi(r))throw new Error(`Watch service helper was not found at ${r}. Run npm run build first.`);$i(process.execPath,[r,e,t,JSON.stringify(n)],{detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"}}).unref()},signalProcess(r){process.kill(r,"SIGTERM")},sleep(r){let e=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(e,0,0,r)}};function st(r){throw new Error(`Unhandled watch service value: ${JSON.stringify(r)}`)}import{existsSync as Yr,lstatSync as Me,readFileSync as pt,readdirSync as Jr,realpathSync as Vr,rmSync as ie,statSync as Xi}from"fs";import{join as R,resolve as $,sep as Kr}from"path";var Zi=3600*1e3,eo=2*1024*1024*1024,to=300*1e3;function ro(r){let e=r.leases.filter(s=>s.managed&&!s.live&&!s.busy),t=no(r.leases,r.locks),n={};for(let s of r.generations)t.has(s.generationId)||(n[s.generationId]=s.unreferencedAt??r.nowMs);let i=r.generations.filter(s=>!t.has(s.generationId)).sort((s,c)=>n[s.generationId]-n[c.generationId]||s.generationId.localeCompare(c.generationId)),o=new Set;for(let s of i)r.nowMs-n[s.generationId]>=r.policy.generationTtlMs&&o.add(s.generationId);let a=r.generations.filter(s=>!o.has(s.generationId)).reduce((s,c)=>s+c.size,0);for(let s of i){if(a<=r.policy.budgetBytes)break;o.has(s.generationId)||(o.add(s.generationId),a-=s.size)}for(let s of o)delete n[s];return{deleteWorktrees:e,deleteGenerations:r.generations.filter(s=>o.has(s.generationId)),deleteLocks:r.locks.filter(s=>!s.live),deleteTemporaries:r.temporaries.filter(s=>!s.live),protectedGenerationIds:[...t].sort(),unreferencedSince:n}}function no(r,e){let t=new Set(r.filter(n=>n.managed&&(n.live||n.busy)).flatMap(n=>[n.lease.baseGenerationId,n.lease.activeGenerationId]).filter(n=>n!==void 0));for(let n of e)n.live&&t.add(n.generationId);return t}function Qr(r,e,t={}){if(!Ht())return{kind:"disabled"};let n=gt(r);if(!n)return{kind:"unavailable"};let i=R($e(),"repositories",n.repositoryId);if(!Yr(i))return{kind:"unavailable"};let o=(t.now??Date.now)(),a=R(i,"gc-state.json"),s=so(a);if(!t.force&&s&&o-Date.parse(s.lastSweepAt)<to)return{kind:"throttled",sweptAt:s.lastSweepAt};let c=vt(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=io(r,i,n.repositoryId,s?.unreferencedSince??{}),d=ro({nowMs:o,...l,policy:{generationTtlMs:t.policy?.generationTtlMs??Zi,budgetBytes:t.policy?.budgetBytes??eo}}),p=0,u=0;for(let m of d.deleteWorktrees){if(!Xr(m.lease))continue;let h=xt(R(m.lease.localCacheDir,"cache-lifecycle.lock"));if(h)try{if(lt(m.lease,!0))continue;try{Gr({projectRoot:m.lease.projectRoot,cacheDir:m.lease.localCacheDir,cliVersion:e})}catch{continue}if(lt(m.lease,!0))continue;ie(m.lease.localCacheDir,{recursive:!0,force:!0}),ie(m.leasePath,{force:!0}),u+=1}finally{h.release()}}for(let m of d.deleteLocks)ie(m.path,{force:!0});for(let m of d.deleteTemporaries)ie(m.path,{recursive:!0,force:!0});for(let m of d.deleteGenerations)ie(m.path,{recursive:!0,force:!0}),p+=m.size;Ct(R(i,"evidence.db"));let g={kind:"swept",sweptAt:new Date(o).toISOString(),deletedWorktrees:u,deletedGenerations:d.deleteGenerations.length,deletedBytes:p,protectedGenerations:d.protectedGenerationIds.length},f={version:1,lastSweepAt:g.sweptAt,unreferencedSince:d.unreferencedSince,lastResult:g};return F(a,f,{spacing:2,trailingNewline:!0}),g}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function io(r,e,t,n){let i=new Set(St(r).map(l=>$(l.path))),o=[];for(let l of ct(R(e,"worktrees"))){if(!l.endsWith(".json"))continue;let d=R(e,"worktrees",l),p=oo(d);if(!p)continue;let u=$(p.projectRoot);o.push({leasePath:d,lease:p,managed:p.repositoryId===t&&Xr(p),live:i.has(u)||Yr(u),busy:lt(p)})}let a=[];for(let l of ct(R(e,"locks"))){let d=/^([a-f0-9]{64})\.lock$/.exec(l);if(!d)continue;let p=R(e,"locks",l),u=dt(p),g=u!==void 0&&j(u),f=d[1];a.push({generationId:f,path:p,live:g})}let s=[],c=[];for(let l of ct(R(e,"generations"))){let d=/^\.tmp-(\d+)-/.exec(l);if(d){let g=R(e,"generations",l),f=Number(d[1]);try{c.push({path:g,size:zr(g),live:Number.isSafeInteger(f)&&j(f)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let p=R(e,"generations",l),u;try{u=Me(p)}catch{continue}!u.isDirectory()||u.isSymbolicLink()||s.push({generationId:l,path:p,size:zr(p),...n[l]===void 0?{}:{unreferencedAt:n[l]}})}return{leases:o,generations:s,locks:a,temporaries:c}}function Xr(r){if(r.ownershipChecksum!==Vt(r)||$(r.localCacheDir)!==$(Ut(r.projectRoot)))return!1;let e=$($e()),t=$(R(e,"projects")),n=$(r.localCacheDir);if(!n.startsWith(`${t}${Kr}`))return!1;try{let i=Me(e),o=Me(t),a=Me(n);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink())return!1;let s=Vr(t);return Vr(n).startsWith(`${s}${Kr}`)}catch{return!1}}function lt(r,e=!1){for(let n of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=dt(R(r.localCacheDir,n));if(i!==void 0&&j(i))return!0}let t=dt(H(r.localCacheDir).lockPath);return t!==void 0&&j(t)}function oo(r){try{let e=JSON.parse(pt(r,"utf8"));return e.version!==1||typeof e.repositoryId!="string"||typeof e.worktreeId!="string"||typeof e.projectRoot!="string"||e.treeOid!==void 0&&typeof e.treeOid!="string"||typeof e.localCacheDir!="string"||e.baseGenerationId!==void 0&&typeof e.baseGenerationId!="string"||e.activeGenerationId!==void 0&&typeof e.activeGenerationId!="string"||typeof e.ownershipChecksum!="string"||!/^[a-f0-9]{64}$/.test(e.ownershipChecksum)||typeof e.lastAction!="string"||e.lastReason!==void 0&&typeof e.lastReason!="string"||typeof e.lastSeenAt!="string"?null:e}catch{return null}}function dt(r){try{let e=JSON.parse(pt(r,"utf8"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function so(r){try{let e=JSON.parse(pt(r,"utf8"));return e.version!==1||typeof e.lastSweepAt!="string"||!Number.isFinite(Date.parse(e.lastSweepAt))||!e.unreferencedSince||typeof e.unreferencedSince!="object"||!e.lastResult?null:e}catch{return null}}function ct(r){try{return Jr(r)}catch{return[]}}function zr(r){let e=0,t=[r];for(;t.length>0;){let n=t.pop();for(let i of Jr(n,{withFileTypes:!0})){let o=R(n,i.name);i.isDirectory()?t.push(o):i.isFile()&&(e+=Xi(o).size)}}return e}var lo=1e3,po=250,uo=10;function fo(r){return r==="fresh"?null:{kind:"watch-startup",detail:`index ${r} when watch service started`}}async function mo(r,e,t={}){let n=$r(r,e),i=n.projectRoot,o=V(i);o.watch={...o.watch,...t};let a=he(o);if(!a.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let s=B(i,o),c=H(s.cacheDir),l=Hr(c.lockPath,i);if(!l.acquired)return;let d=Date.now(),p=d,u={state:"idle"},g,f,m,h=fe(s.dbPath),S=!1,w=!1,A=0,P=0,L=0,D=0,C,b,I=er(s.cacheDir),ut=zt(s.cacheDir);nt(I),it(ut);let Pe=new Ce({openDb:()=>or(i)}),Te=new ke({projectRoot:i,currentGeneration:()=>Jt(s.dbPath)}),E=(v=!1)=>{if(!w)return;let q=Date.now();!v&&q-P<lo||(P=q,qr(c.statePath,{version:1,protocolVersion:_e,pid:M.pid,projectRoot:i,...n.worktreeId?{worktreeId:n.worktreeId}:{},cliVersion:e,startedAt:new Date(d).toISOString(),heartbeatAt:new Date(q).toISOString(),lastActivityAt:new Date(p).toISOString(),...a.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(p+a.idleTimeoutMs).toISOString()},watcher:u,...u.state==="idle"&&g?{indexGeneration:g}:{},...f?{lastRefresh:f}:{},...m?{lastError:m}:{},reindexActivity:h,typescriptSemantic:{...Pe.status(),...C===void 0?{}:{busyUntil:new Date(C).toISOString()}},typescriptIndex:{...Te.status(),...b===void 0?{}:{busyUntil:new Date(b).toISOString()}}}))},G=()=>{p=Date.now()},oe=new ge({projectRoot:i,config:{...o,watch:a},languages:o.languages,onStatus(v){u=v,v.state!=="idle"&&(g=void 0),v.state!=="idle"&&G(),E(!0)},onReindexComplete(){G();let v=Ue(i,o,s);return f=v.lastRefresh,g=v.state==="fresh"?Z(s.dbPath)??void 0:void 0,h=fe(s.dbPath),m=void 0,E(!0),v.state==="fresh"},onRefreshSuppressed(v){qt(s.dbPath,v),h=fe(s.dbPath)},onError(v){G(),g=void 0,m={at:new Date().toISOString(),message:v.message},E(!0)}}),se=()=>{S=!0};M.once("SIGINT",se),M.once("SIGTERM",se);try{oe.start();let v=Ue(i,o,s);f=v.lastRefresh,g=v.state==="fresh"?Z(s.dbPath)??void 0:void 0;let q=fo(v.state);for(q&&oe.requestRefresh(q,{immediate:!0}),G(),w=!0,E(!0);!S;){let en=jr(ut,Te,{beforeRequest(T){b=T+5e3,E(!0)},afterRequest(){b=void 0,E(!0)}}),tn=Lr(I,Pe,{beforeRequest(T){C=T+5e3,E(!0)},afterRequest(){C=void 0,E(!0)}}),ae=Date.now();if(ae-D>=6e4&&(D=ae,Qr(i,e)),ae-L>=po){L=ae;let T=Ur(c.activityPath);T&&T.atMs>p&&(p=T.atMs),T?.refreshRequestedAtMs!==void 0&&T.refreshRequestedAtMs>A&&(A=T.refreshRequestedAtMs,G(),oe.requestRefresh({kind:"watch-demand",detail:T.refreshDetail??"stale index observed by a command"},{immediate:!0}))}if((tn>0||en>0)&&(G(),E(!0)),E(),Br({watcher:u,lastActivityAtMs:p,nowMs:Date.now(),idleTimeoutMs:a.idleTimeoutMs}))break;await ho(uo)}}finally{M.off("SIGINT",se),M.off("SIGTERM",se),Pe.closeTypeScriptService(),Te.close(),oe.stop(),Zr(c.statePath,{force:!0}),Zr(c.activityPath,{force:!0}),l.release()}}function ho(r){return new Promise(e=>setTimeout(e,r))}var go=M.argv[1]?co(ao(M.argv[1])).href:null;if(go===import.meta.url){let r=M.argv[2],e=M.argv[3],t=yo(M.argv[4]);if(!r||!e)console.error("watch-service: expected <project-root> <cli-version>"),M.exitCode=1;else try{await mo(r,e,t)}catch(n){console.error(`watch-service: ${n instanceof Error?n.message:String(n)}`),M.exitCode=1}}function yo(r){if(!r)return{};try{let e=JSON.parse(r);return e&&typeof e=="object"?e:{}}catch{return{}}}export{mo as runWatchServiceServer,fo as startupRefreshTrigger};
|
|
43
43
|
//# sourceMappingURL=watch-server.js.map
|
package/package.json
CHANGED
package/dist/chunk-42QYU6FD.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{a as Re}from"./chunk-KD6TPIXM.js";import{a as Fe}from"./chunk-7EI4MU5A.js";import{a as se,b as F,e as ae}from"./chunk-KWBA6FDD.js";import{a as fe,c as ue,d as he,e as v}from"./chunk-YHYTDWFT.js";import{a as De}from"./chunk-MFBXBLHA.js";import{a as ke}from"./chunk-WT7TOU2C.js";import{a as ve}from"./chunk-C2QSK7E7.js";import{a as Se}from"./chunk-X3OOU7CF.js";import{a as Ce}from"./chunk-J65FQLDL.js";import{a as ye}from"./chunk-547VY366.js";import{a as be}from"./chunk-QHOUNTDZ.js";import{a as ge}from"./chunk-YBAC3RON.js";import{b as de}from"./chunk-7FG5M53V.js";import{a as ce,b as le}from"./chunk-AERYQJ52.js";import{a as ne,b as oe,c as re,g as L,h as _}from"./chunk-PAZFJMXB.js";import{b as me}from"./chunk-AM2LGOEX.js";import{a as P,c as ee,d as te,e as ie}from"./chunk-RIGY5DDE.js";import{a as Q}from"./chunk-4XTPZ5CR.js";import{a as $e,e as we}from"./chunk-UJL3N6TC.js";import{a as j,c as H,d as z,e as pe}from"./chunk-J3U47L4Q.js";import{a as Z}from"./chunk-ZXWFN7CK.js";import{f as x,g as G}from"./chunk-FLIF3JWA.js";import{e as X}from"./chunk-UVMME4FI.js";import{e as R,f as Y,g as M}from"./chunk-TDGCALH6.js";import{a as V}from"./chunk-QNMOZ3CJ.js";import{e as W}from"./chunk-XDSB47KO.js";import{s as J}from"./chunk-M2TRDR25.js";import{createHash as st}from"crypto";import{existsSync as K}from"fs";function O(e){let[t,i]=T(e,":"),o=t||"unknown",n=(a={})=>{let s=a.actionTier??Ue(o);return{sourceAnalyzer:o,actionTier:s,rootCauseKey:a.rootCauseKey??(i||e),label:a.label??`${o} finding`,relatedFiles:a.relatedFiles??[],why:a.why??[],remediation:a.remediation??qe(s,o),file:a.file}};if(!i)return n({rootCauseKey:e,why:["Baseline identity did not include analyzer payload."]});if(["dead","isolated","extract","wrapper","passthrough","stale"].includes(o)){let[a,s]=T(i,":");return n({file:a,relatedFiles:a?[a]:[],rootCauseKey:s?`${a}:${s}`:i,label:`${o} finding`,why:s?[`Baseline subject: ${s}.`]:[]})}if(o==="cycle"){let a=i.split(">").filter(Boolean);return n({relatedFiles:a,rootCauseKey:i,label:"cycle finding",why:a.length>0?[`Cycle path: ${a.join(" > ")}.`]:[]})}if(o==="similar"){let a=i.split("|").filter(Boolean);return n({relatedFiles:[],rootCauseKey:i,label:"similarity finding",why:a.length>0?[`Similar symbols: ${a.join(" | ")}.`]:[]})}if(o==="architecture"){let[a,s]=T(i,":");if(a==="forbidden-edge"){let[c,l]=T(s,":"),r=N(c),f=N(l);return n({actionTier:"direct",rootCauseKey:i,label:"architecture boundary violation",why:[`Declared boundary rule rejects ${r} -> ${f}.`],remediation:`Move the dependency behind an allowed boundary, or deliberately update the ${r} dependency rule and baseline.`})}if(a==="cycle"){let c=s.split("|").filter(Boolean).map(N);return n({actionTier:"direct",rootCauseKey:i,label:"forbidden architecture cycle",why:[`requireAcyclic rejects the connected boundary group: ${c.join(", ")}.`],remediation:"Break the boundary cycle, or deliberately revise the acyclicity rule and baseline."})}if(a==="missing-policy-row"){let c=N(s);return n({actionTier:"direct",rootCauseKey:i,label:"incomplete architecture policy",why:[`requireCompletePolicy rejects the missing outgoing dependency row for ${c}.`],remediation:`Declare the allowed outgoing dependencies for ${c}, including an empty row when it must depend on nothing.`})}}if(o==="drift"){let[a,s]=T(i,":"),[c,l]=T(s,":");return n({actionTier:a==="unused-import"?"direct":"signal",file:c,relatedFiles:[...new Set([c,l].filter(Boolean))],rootCauseKey:i,label:`${a||"drift"} finding`,why:[...a?[`Drift kind: ${a}.`]:[],...l?[`Related dependency: ${l}.`]:[]]})}return n({why:["Baseline analyzer prefix is not recognized by this diff-gate version."]})}function Ue(e){switch(e){case"dead":case"isolated":case"cycle":case"passthrough":case"architecture":return"direct";case"similar":case"extract":case"wrapper":case"stale":return"signal";default:return"signal"}}function qe(e,t){return e==="direct"?`Fix the new ${t} baseline finding, or knowingly accept it via health --write-baseline.`:`Review the new ${t} baseline signal; fix it if it reflects real debt, or knowingly accept it via health --write-baseline.`}function T(e,t){let i=e.indexOf(t);return i<0?[e,""]:[e.slice(0,i),e.slice(i+t.length)]}function N(e){try{return decodeURIComponent(e)}catch{return e}}import{existsSync as Te,readFileSync as Ae,writeFileSync as We}from"fs";import{isAbsolute as Je,join as Ve}from"path";var Ye=25e3,Xe=2500,Ze=2500;function Qe(e){let t=ve(e);return t.symbols>=Ye||t.documents>=Xe?Ze:void 0}var et=".scipquery-baseline.json";function A(e,t){return t&&Je(t)?t:Ve(e.config.projectRoot,t??et)}function xe(e,t={}){let{scope:i}=t,o=Qe(e),n=[],a=me(e,{scope:i,...v.dead,scanLimit:o});for(let s of a.symbols)x(e,s.relativePath)||G(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&n.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of Ce(e,{scope:i,...v.isolated,scanLimit:o}))x(e,s.relativePath)||G(e,s.symbol,s.relativePath)||n.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of ge(e,{scope:i}))s.kind==="real"&&n.push(`cycle:${tt(s.path)}`);for(let s of we(e,{scope:i,...v.similar,scanLimit:o}))n.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of ce(e,{scope:i,...v.duplicateBodies,scanLimit:o}))n.push(`duplicate-bodies:${s.hash}:${s.functions.map(c=>c.symbol).sort().join("|")}`);for(let s of be(e,{scope:i,...v.extract,scanLimit:o}))n.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of De(e,{scope:i,...v.wrappers,scanLimit:o}))n.push(`wrapper:${s.file}:${s.shortName}`);for(let s of Se(e,{scope:i,...v.passthroughs,scanLimit:o}))n.push(`passthrough:${s.file}:${s.shortName}`);for(let s of ke(e,{scope:i,...v.stale,scanLimit:o}))n.push(`stale:${s.file}:${s.shortName}`);for(let s of ye(e,{scope:i,...v.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)s.kind!=="architecture-violation"&&n.push(`drift:${s.kind}:${s.file}:${s.dep}`);return n.push(...z(H(e,{scope:i}))),[...new Set(n)].sort()}function tt(e){if(e.length===0)return"";let t=0;for(let i=1;i<e.length;i++)e[i]<e[t]&&(t=i);return[...e.slice(t),...e.slice(0,t)].join(">")}function ei(e,t={}){let i=xe(e,{scope:t.scope}),o=A(e,t.path);return We(o,JSON.stringify({version:1,findings:i},null,2)+`
|
|
2
|
-
`),{path:o,findingCount:i.length}}function Ge(e,t={}){let i=A(e,t.path);if(!Te(i))throw new Error(`No baseline found at ${i}. Create one with: scip-query health --write-baseline`);let o=JSON.parse(Ae(i,"utf-8")),n=new Set(o.findings??[]),a=xe(e,{scope:t.scope}),s=new Set(a);return{baselinePath:i,baselineCount:n.size,current:a,newFindings:a.filter(c=>!n.has(c)),fixedFindings:[...n].filter(c=>!s.has(c))}}function Ee(e,t={}){let i=A(e,t.path);if(!Te(i))throw new Error(`No baseline found at ${i}. Create one with: scip-query health --write-baseline`);let o=JSON.parse(Ae(i,"utf-8")),n=new Set((o.findings??[]).filter(c=>c.startsWith(j))),a=z(H(e,{scope:t.scope})),s=new Set(a);return{baselinePath:i,baselineCount:n.size,current:a,newFindings:a.filter(c=>!n.has(c)),fixedFindings:[...n].filter(c=>!s.has(c))}}import{existsSync as it,mkdirSync as ni,readdirSync as nt,readFileSync as ot,writeFileSync as oi}from"fs";import{createHash as si}from"crypto";import{join as U}from"path";var E=U(".scipquery","suppressions");function rt(e){return U(e,E)}function Ie(e){let t=rt(e);if(!it(t))return{suppressions:[],warnings:[]};let i=[],o=[];for(let n of nt(t).sort()){if(!n.endsWith(".json"))continue;let a=U(t,n),s;try{s=JSON.parse(ot(a,"utf-8"))}catch{o.push(`${E}/${n}: malformed JSON \u2014 ignored`);continue}if(typeof s!="object"||s===null||Array.isArray(s)){o.push(`${E}/${n}: not a suppression object \u2014 ignored`);continue}let c=s;if(typeof c.reason!="string"||c.reason.trim()===""){o.push(`${E}/${n}: missing reason \u2014 ignored`);continue}if(!c.id&&!c.check){o.push(`${E}/${n}: needs an id or a check \u2014 ignored`);continue}i.push(c)}return{suppressions:i,warnings:o}}var Ii=["echo","incomplete-migration","co-change-partner","twin-partner","coverage-contract","architecture","doc-reference","unused-params","new-dead","baseline"];function ji(e,t={}){let i=t.base??"HEAD",{minTogether:o=6,minConfidence:n=.6,maxEchoChecks:a=Number.POSITIVE_INFINITY,maxHelpers:s=Number.POSITIVE_INFINITY,minSimilarity:c=.8,includeBaseline:l=!1,scanLimit:r}=t,f=t.semantic!==!1,p=t.historyMode??"bounded",u=new Set(t.skip??[]),h=re(e,{base:i}),m=oe(e,{base:i,plan:h}),y=m.changedFiles,S=new Set(y),d=new Set(h.changedFileLines),w=new Set([...S,...d]),$=L(e.config.projectRoot,i,_(h,y)),C=It(e.config.projectRoot,i,h,$),g={base:i,changedFiles:y,changedSymbols:m.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],findings:[],attributionNotes:m.attributionNotes,rootCauseGroups:[],note:m.summary.note};if(y.length===0)return g;let k=(I,_e)=>{if(u.has(I)){g.skipped.push({check:I,reason:"skipped via --skip"});return}let He=g.findings.length,ze=g.skipped.length,Oe=g.checksRun.length;J(`diff-gate.check.${I}`,_e,()=>({check:I,changedFiles:y.length,changedSymbols:m.changedSymbols.length,findingsAdded:g.findings.length-He,skippedAdded:g.skipped.length-ze,checksRunAdded:g.checksRun.length-Oe}))};return k("echo",()=>dt(e,m.changedSymbols,S,C,a,c,r,f,g)),k("incomplete-migration",()=>mt(e,i,h,s,r,f,$,g)),k("co-change-partner",()=>yt(e,w,o,n,p,g)),k("twin-partner",()=>bt(e,m.changedSymbols,S,r,g)),k("coverage-contract",()=>Ct(e,w,g)),k("architecture",()=>Bt(e,g)),k("doc-reference",()=>vt(e,S,d,h.changedRanges,h.renamedFiles,g)),k("unused-params",()=>Tt(e,y,g)),k("new-dead",()=>At(e,m.changedSymbols,C,g)),l&&k("baseline",()=>Nt(e,g)),ct(g,[...e.config.suppressions??[],...Ie(e.config.projectRoot).suppressions]),g.rootCauseGroups=at(g.findings),g}function Ni(e){return e.checksRun.length===0&&e.note===ne}function Bi(e){return e.filter(t=>!t.advisory)}function at(e){let t=new Map;for(let i of e){let o=i.groupKey??`${i.check}:${i.id}`,n=t.get(o);n||(n={groupKey:o,check:i.check,severity:i.severity,actionTier:i.actionTier,sourceAnalyzer:i.sourceAnalyzer,rootCauseKey:i.rootCauseKey,count:0,findingIds:[],files:new Set,relatedFiles:new Set,message:i.message,remediation:i.remediation},t.set(o,n)),n.count+=1,n.findingIds.push(i.id),n.severity=Pe(n.severity,i.severity),n.actionTier=Le(n.actionTier,i.actionTier),i.file&&n.files.add(i.file);for(let a of i.relatedFiles??[])n.relatedFiles.add(a)}return[...t.values()].map(i=>({...i,files:[...i.files].sort(),relatedFiles:[...i.relatedFiles].sort()})).sort((i,o)=>o.count-i.count||B(o.severity)-B(i.severity)||i.groupKey.localeCompare(o.groupKey))}function Pe(e,t){return B(t)>B(e)?t:e}function B(e){return e==="error"?2:e==="warning"?1:0}function Le(e,t){return e?t&&je(t)>je(e)?t:e:t}function je(e){return e==="direct"?2:e==="signal"?1:0}function ct(e,t){if(t.length===0||e.findings.length===0)return;let i=[];for(let o of e.findings){let n=t.find(a=>lt(a,o));n?e.suppressed.push({finding:o,suppression:n}):i.push(o)}e.findings=i}function lt(e,t){return!e.reason||e.reason.trim()===""||e.expiresAt&&Date.parse(e.expiresAt)<=Date.now()||e.id&&e.id!==t.id&&!t.legacySuppressionIds?.includes(e.id)||e.check&&e.check!==t.check||e.file&&e.file!==t.file?!1:!!(e.id||e.check)}function D(e,t){e.findings.push({...t,suppressionHint:`scip-query: ignore ${t.check} ${t.id} -- <reason>`})}function dt(e,t,i,o,n,a,s,c,l){l.checksRun.push("echo");for(let r of t.slice(0,n)){if(!M(r.symbol)||o(r))continue;let f=le(e,r.symbol,{maxLoc:15,scanLimit:s}).filter(d=>!i.has(d.file)).slice(0,5).map(d=>({otherFile:d.file,otherShort:d.shortName,otherSymbol:d.symbol,similarity:1,similarityBasis:"exact-body",sharedEvidence:[`exact normalized body (${d.loc} LOC)`]}));if(f.length>0){let d=b("echo",r.symbol,r.file),w=b("echo",r.symbol,r.file,...f.map(C=>`${C.otherSymbol}|${C.otherFile}`).sort()),$=f[0];D(l,{id:d,legacySuppressionIds:w===d?void 0:[w],groupKey:d,actionTier:"direct",check:"echo",severity:"warning",evidence:"heuristic",confidence:1,file:r.file,symbol:r.symbol,relatedFiles:[...new Set(f.map(C=>C.otherFile))].sort(),sourceAnalyzer:"duplicate-bodies",rootCauseKey:`${r.symbol}:${$.otherSymbol}`,message:Be(r,f),why:Ke(r,f),remediation:Me("direct",r.shortName,$.otherShort)});continue}let p=$e(e,r.symbol,{minSimilarity:a,limit:5,scanLimit:s,semantic:c,sourceCandidateMode:"target-pruned"}),u=[];for(let d of p){let w=d.fileA===r.file?d.fileB:d.fileA,$=d.fileA===r.file?d.shortNameB:d.shortNameA,C=d.fileA===r.file?d.symbolB:d.symbolA;i.has(w)||u.push({otherFile:w,otherShort:$,otherSymbol:C,similarity:d.similarity,similarityBasis:d.similarityBasis??"callees",sharedEvidence:d.sharedCallees})}if(u.length===0)continue;let h=u[0],m=b("echo",r.symbol,r.file,...u.map(d=>`${d.otherSymbol}|${d.otherFile}`).sort()),y=b("echo",r.symbol,r.file),S=ft(r,u);D(l,{id:y,legacySuppressionIds:m===y?void 0:[m],groupKey:y,actionTier:S,check:"echo",severity:"warning",evidence:"heuristic",confidence:h.similarity,file:r.file,symbol:r.symbol,relatedFiles:[...new Set(u.map(d=>d.otherFile))].sort(),message:Be(r,u),why:Ke(r,u),remediation:Me(S,r.shortName,h.otherShort)})}t.length>n&&l.skipped.push({check:"echo",reason:`echo check capped at ${n} of ${t.length} changed symbols`})}function ft(e,t){return t.some(o=>ut(e.symbol,o))?"direct":"signal"}function ut(e,t){if(t.similarityBasis==="exact-body")return!0;if(t.similarityBasis!=="source-tokens"||t.similarity<.98||t.sharedEvidence.length>8)return!1;let i=R(e),o=R(t.otherSymbol);return!i||!o?!1:i===o?!0:pt(t.sharedEvidence)?!1:ht(i,o)}function ht(e,t){let i=Ne(e),o=Ne(t);if(i.length===0||o.length===0)return!1;let n=new Set(o),a=i.filter(s=>n.has(s)).length;return a>=2&&a/Math.min(i.length,o.length)>=.5}function Ne(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}var gt=new Set(["bytes","crypto","hex","num","random","secret","to","token"]);function pt(e){return e.length>=3&&e.every(t=>gt.has(t.toLowerCase()))}function Be(e,t){let i=t[0],o=Math.round(i.similarity*100);return t.length===1?`${e.shortName} (${e.file}) is ${o}% similar to established ${i.otherShort} (${i.otherFile})`:`${e.shortName} (${e.file}) resembles ${t.length} established symbol(s); strongest is ${o}% similar to ${i.otherShort} (${i.otherFile})`}function Ke(e,t){let i=[`${e.shortName} was changed in this diff.`];for(let o of t.slice(0,3))i.push(`${o.otherShort} is outside this diff and scored ${Math.round(o.similarity*100)}% similar by ${o.similarityBasis} evidence.`),i.push(`Shared evidence: ${o.sharedEvidence.slice(0,5).join(", ")||"(none listed)"}.`);return t.length>3&&i.push(`${t.length-3} additional similar match(es) grouped into this finding.`),i}function Me(e,t,i){return e==="direct"?`Extract or reuse the shared behavior with ${i}, or keep the duplicate with a suppression reason.`:`Review whether ${t} is intentionally parallel to the established implementation(s); extract shared behavior only if the product semantics match.`}function mt(e,t,i,o,n,a,s,c){let l=Fe(e,{base:t,maxHelpers:o,diffPlan:i,scanLimit:n,semantic:a,baseContentAt:s});if(!l.available){c.skipped.push({check:"incomplete-migration",reason:"no git history"});return}c.checksRun.push("incomplete-migration"),l.note&&c.skipped.push({check:"incomplete-migration",reason:l.note});for(let r of l.findings){let f=r.leftovers.map(d=>`${d.shortName} (${d.file}, ${Math.round(d.containment*100)}% helper / ${Math.round(d.siteCoverage*100)}% site, ${d.migrationScope})`).join(", "),p=r.leftovers.map(d=>`${d.shortName}: ${d.migrationScope} (${d.migrationScopeReasons[0]})`).join("; "),u=[...r.migratedFiles,...r.leftovers.map(d=>d.file)],h=r.leftovers.length===0?void 0:Math.max(...r.leftovers.map(d=>Math.min(d.containment,d.siteCoverage))),m=r.leftovers.some(d=>d.migrationScope==="possible-subtype"),y=b("incomplete-migration",r.helperSymbol,r.helperFile,u.join("|")),S=b("incomplete-migration",r.helperSymbol,r.helperFile);D(c,{id:S,legacySuppressionIds:y===S?void 0:[y],check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:h,file:r.helperFile,symbol:r.helperSymbol,relatedFiles:u,message:`new helper ${r.helperShortName} (${r.helperFile}) is wired into ${r.migratedFiles.length} file(s), but ${r.leftovers.length} similar un-migrated site(s) remain: ${f}`,why:[`${r.helperShortName} is new in this diff and already referenced by ${r.migratedFiles.join(", ")}.`,`Helper shape: ${r.helperShape}; ${r.specificHelperCalleeCount}/${r.helperCalleeCount} helper callees are specific enough to score.`,`Unchanged site(s) still contain the helper's callee pattern: ${f}.`,`Migration scope hints: ${p}.`],remediation:m?`Migrate same-scope sites to ${r.helperShortName}; review possible subtype/variant sites before applying the helper.`:`Migrate the remaining sites to ${r.helperShortName}, or confirm they are intentionally different.`})}}function yt(e,t,i,o,n,a){let s=Q(e,{historyMode:n}).directionalCoChangePairsForFiles(t,{minTogether:i,minConfidence:0,maxFilesPerCommit:20});if(!s){a.skipped.push({check:"co-change-partner",reason:"no git history"});return}a.checksRun.push("co-change-partner");let c=new Set,l;for(let r of s){let f=t.has(r.fileA),p=t.has(r.fileB);if(f===p)continue;let u=f?r.fileA:r.fileB,h=f?r.fileB:r.fileA,m=f?r.changesA:r.changesB,y=m>0?r.together/m:0;if(y<o||P(h)||P(u)||!K(`${e.config.projectRoot}/${h}`))continue;let S=`${u}|${h}`;if(c.has(S))continue;c.add(S);let d=b("co-change-partner",u,h,String(r.together)),w=b("co-change-partner",u,h),$=ee(u,h),C=te({fileA:u,fileB:h,together:r.together,confidence:y,commitScope:r.commitScope,recency:r.recency,subjectContext:r.subjectContext},$,(l??=ie(e))(u,h)),g=[u,h].sort().join("|");a.findings.push({id:w,legacySuppressionIds:d===w?void 0:[d],check:"co-change-partner",severity:"warning",evidence:"change-graph",actionTier:"signal",groupKey:`co-change-partner:${g}`,confidence:y,file:u,relatedFiles:[h],sourceAnalyzer:"co-change",rootCauseKey:g,partnerClass:$.partnerClass,partnerClassReasons:$.reasons,commitScope:r.commitScope,recency:r.recency,focusedTogether:r.focusedTogether,broadTogether:r.broadTogether,broadCommitRatio:r.broadCommitRatio,lastTogetherAt:r.lastTogetherAt,recentTogether:r.recentTogether,subjectContext:r.subjectContext,...C?{declaredCouplingSuggestion:C}:{},message:`${u} changed, but ${h} did not \u2014 they change together ${r.together}x (${Math.round(y*100)}% of the time)`,why:[`${u} is in this diff and ${h} is not.`,`Git history shows ${r.together} co-change(s), which is ${Math.round(y*100)}% of changes to the edited side.`,`History context: ${St(r)}.`,`Subject context: ${$t(r.subjectContext)}.`,...wt(r),`Partner class: ${$.partnerClass} (${$.reasons.join("; ")}).`],remediation:C?`Update ${h} alongside this change, declare the coupling "${C.name}", or confirm the coupling no longer holds.`:`Update ${h} alongside this change, or confirm the coupling no longer holds.`})}}function bt(e,t,i,o,n){n.checksRun.push("twin-partner");let a=de(e,{scanLimit:o}).filter(l=>l.relationship==="divergent"||l.relationship==="identical");if(a.length===0)return;let s=new Map;for(let l of a)for(let r of l.members)s.set(r.symbol,l);let c=new Set;for(let l of t){if(!M(l.symbol))continue;let r=s.get(l.symbol);if(!r)continue;let f=r.members.filter(m=>m.symbol!==l.symbol&&!i.has(m.file));if(f.length===0)continue;let p=[l.symbol,...f.map(m=>m.symbol)].sort().join("|");if(c.has(p))continue;c.add(p);let u=f[0],h=b("twin-partner",l.symbol,l.file,u.symbol);D(n,{id:h,groupKey:`twin-partner:${p}`,check:"twin-partner",severity:"warning",evidence:"heuristic",actionTier:"signal",advisory:!0,confidence:r.relationship==="identical"?1:Math.max(0,1-r.maxDivergence),file:l.file,symbol:l.symbol,relatedFiles:f.map(m=>m.file).sort(),sourceAnalyzer:"twin-drift",rootCauseKey:p,message:`${l.shortName} (${l.file}) changed but its same-name twin ${u.shortName} (${u.file}) did not \u2014 verify the change shouldn't apply to both, or consolidate them.`,why:[`${l.symbol} is in this diff.`,`${u.symbol} shares its (near-)name and is classified '${r.relationship}' with it, but ${u.file} is not in this diff.`,r.relationship==="divergent"?`The two bodies already diverge (~${Math.round(r.maxDivergence*100)}% token difference) \u2014 this diff may widen or narrow that drift.`:"The two bodies were byte-identical before this diff.","Advisory: twin-partner never fails the gate by itself \u2014 see the twin-partner entry in the diff-gate checks table."],remediation:`Update ${u.file} alongside this change, consolidate ${l.shortName}/${u.shortName} into one helper, or confirm the twin should diverge on purpose.`})}}function Ct(e,t,i){i.checksRun.push("coverage-contract");let o=e.config.coverageContracts??[];for(let n of o){if(!ue(n,t))continue;let a=fe(e,n);if(a.status==="ok")continue;let s=b("coverage-contract",n.name,n.file);D(i,{id:s,groupKey:`coverage-contract:${n.name}`,check:"coverage-contract",severity:a.status==="unavailable"?"warning":"error",evidence:"graph-fact",actionTier:"direct",file:n.file,sourceAnalyzer:"coverage-contracts",rootCauseKey:n.name,message:he(a),why:[`Contract "${n.name}" declares that ${n.file} (${n.keys.type}) must track ${n.mustEqual.type}.`,a.status==="unavailable"?`The declared side could not be evaluated: ${a.unavailableReason}.`:`Missing: ${a.missing.join(", ")||"none"}. Extra: ${a.extra.join(", ")||"none"}.`,"Either side of this contract changed in this diff."],remediation:a.status==="unavailable"?"Investigate why the declared key set could not be parsed (see the reason above) \u2014 do not treat this as a pass.":`Update ${n.file} so its ${n.keys.type==="object-literal-keys"||n.keys.type==="string-array"?n.keys.identifier:n.keys.marker} matches ${n.mustEqual.type}, or fix the ground-truth source if the declared set is right.`})}}function St(e){return`${e.commitScope}/${e.recency}; ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent, last ${kt(e.lastTogetherAt)}`}function $t(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",i=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",o=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(n=>`"${n}"`).join("; "):"none";return`labels ${t}; refs ${i}; samples ${o}; external issue/PR labels ${e.externalIssueLabelStatus}`}function wt(e){let t=[];return e.commitScope==="broad-sweep"&&t.push("Broad-sweep history is weaker than focused co-edits; confirm this is a real coordination contract."),e.recency==="stale"&&t.push("The pair has no co-change in the recent history window; confirm the coupling still holds."),t}function kt(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}var q=3;function vt(e,t,i,o,n,a){a.checksRun.push("doc-reference");let s=F.referenceTargets(e,t,o);if(s.size===0)return;let c=new Set(n.map(r=>r.from)),l=[];for(let r of ae(e,s))i.has(r.doc)||se(e,r.doc)||l.push(Dt(e,r,c));for(let r of Ft(l))D(a,r)}function Dt(e,t,i){let o=t.citedClaims.length>0?t.citedClaims:F.citationContexts(e,t.doc,t.cited),n=F.classifyCitation(o),a=F.hasLineAnchoredCitation(t.citations),s=t.cited.some(p=>i.has(p)||!K(`${e.config.projectRoot}/${p}`)),c=!(a||s),l=t.cited[0]??"",r=b("doc-reference",t.doc,t.cited.join("|")),f=b("doc-reference",t.doc,l);return{id:f,legacySuppressionIds:r===f?void 0:[r],check:"doc-reference",severity:"warning",evidence:"change-graph",actionTier:n.actionTier,groupKey:`doc-reference:${l}`,rootCauseKey:l,confidence:1,file:t.doc,relatedFiles:t.cited,citationKind:n.citationKind,citationKindReasons:n.reasons,citedClaims:o,...c?{advisory:!0}:{},message:`${t.doc} cites ${t.cited.join(", ")} as ${F.citationKindLabel(n.citationKind)} \u2014 changed in this diff, doc untouched`,why:[`${t.cited.join(", ")} changed in this diff.`,`${t.doc} cites the changed file(s) but was not updated in the same diff.`,...n.reasons.map(p=>`Citation kind evidence: ${p}`),c?"Advisory: bare file-mention citation (no line anchor, cited file still present under the same path) \u2014 21.2 calibration found this citation shape low-precision; verify at your leisure.":a?"Blocking: citation includes a line anchor that may now point at the wrong lines.":"Blocking: the cited file was deleted or renamed in this diff \u2014 the citation almost certainly needs an update."],remediation:F.citationRemediation(n.citationKind,t.doc)}}function Ft(e){let t=new Map;for(let o of e){let n=o.rootCauseKey??"",a=t.get(n);a?a.push(o):t.set(n,[o])}let i=[];for(let[o,n]of t)n.length<=q?i.push(...n):i.push(Rt(o,n));return i}function Rt(e,t){let i=[...t].sort((f,p)=>(f.file??"").localeCompare(p.file??"")),o=i.slice(0,q).map(f=>({doc:f.file??"",citedClaims:f.citedClaims??[]})),n=i.length-o.length,a=i.every(f=>f.advisory===!0),s=i.reduce((f,p)=>Pe(f,p.severity),"info"),c=i.reduce((f,p)=>Le(f,p.actionTier),void 0),l=i.map(f=>f.file??"").filter(f=>f.length>0),r=[...new Set(i.flatMap(f=>[f.id,...f.legacySuppressionIds??[]]))];return{id:b("doc-reference","hub-cluster",e),memberFindingIds:r,check:"doc-reference",severity:s,evidence:"change-graph",actionTier:c,groupKey:`doc-reference:${e}`,rootCauseKey:e,confidence:1,file:o[0]?.doc,relatedFiles:[e],citationCount:i.length,citationExemplars:o,suppressedCount:n,...a?{advisory:!0}:{},message:`${e} is cited by ${i.length} doc(s) changed in this diff, doc(s) untouched \u2014 showing ${o.length} example(s), ${n} more damped`,why:[`${e} changed in this diff.`,`${i.length} doc(s) cite it but were not updated in the same diff: ${l.join(", ")}.`,...o.map(f=>`Example \u2014 ${f.doc}: ${f.citedClaims[0]??"(no captured citation text)"}`),`${n} additional doc(s) also cite this file, past the per-hub-file cascade cap (${q}) \u2014 not silently dropped: counted in citationCount/suppressedCount and individually addressable via memberFindingIds.`,a?"Advisory: every citation in this cluster is a bare file-mention (no line anchor, cited file still present).":"Blocking: at least one citation in this cluster is line-anchored or cites a deleted/renamed file."],remediation:`Review the ${o.length} example doc(s) above; ${i.length} total doc(s) cite ${e} the same way \u2014 see citationExemplars and memberFindingIds in --json for the complete list.`}}function Tt(e,t,i){i.checksRun.push("unused-params");for(let o of Re(e,{files:t,limit:50})){let n=b("unused-params",o.symbol,o.file,o.unusedTrailing.join("|")),a=b("unused-params",o.symbol,o.file);D(i,{id:a,legacySuppressionIds:n===a?void 0:[n],check:"unused-params",severity:"warning",evidence:"heuristic",confidence:.85,file:o.file,startLine:o.startLine,endLine:o.endLine,symbol:o.symbol,message:`${o.shortName} (${o.file}) has trailing unused parameter(s): ${o.unusedTrailing.join(", ")}`,why:[`${o.shortName} is in a changed file.`,`The trailing parameter(s) ${o.unusedTrailing.join(", ")} are not referenced in the function body.`],remediation:"Drop the unused trailing parameters and their call-site arguments."})}}function At(e,t,i,o){o.checksRun.push("new-dead");let n=new Z(e),a=W(e.config.projectRoot),s=a.length>1;for(let c of t){if(i(c)||c.fanIn>0||n.fileKind(c.file)==="test"||x(e,c.file)||G(e,c.symbol,c.file)||Et(c.symbol))continue;let l=b("new-dead",c.symbol,c.file),r=s&&xt(a,c.file)&&Gt(e,c.symbol);D(o,{id:l,check:"new-dead",severity:"warning",evidence:r?"heuristic":"graph-fact",confidence:r?.4:.9,file:c.file,symbol:c.symbol,message:r?`${c.shortName} (${c.file}) unconfirmed (cross-package ambiguous-name resolution gap): zero indexed consumers found, but this name is ambiguous project-wide and lives in a workspace package \u2014 verify manually before treating as dead`:`${c.shortName} (${c.file}) was changed but has zero indexed consumers`,why:r?[`${c.shortName} is a changed production symbol in a workspace package.`,"The index, semantic, and source-fallback layers all report zero consumers for this symbol.","Its leaf name is ambiguous project-wide (a same-named definition exists elsewhere), and cross-package consumers reached only through a re-exporting barrel are a known unresolvable shape for this tool \u2014 see docs/plans/2026-07-02-followups.md item 2."]:[`${c.shortName} is a changed production symbol.`,"The index reports zero consumers for this symbol.","The symbol is not in a detected entry surface or configured live root."],remediation:r?"Verify with a direct code search before deleting; this tool cannot confidently resolve this symbol.":"Wire it up, or remove it before it becomes permanent dead code."})}}function xt(e,t){return e.some(i=>t===i.relativeDir||t.startsWith(`${i.relativeDir}/`))}function Gt(e,t){let i=R(t);return i?(X(e).get(i)?.length??0)>1:!1}function Et(e){if(Y(e)!=="type")return!1;let t=R(e);return t.startsWith("_Assert")||t.startsWith("Assert")}function It(e,t,i,o){let n=new Map(i.renamedFiles.map(s=>[s.to,s.from])),a=o??L(e,t,_(i));return s=>{let c=n.get(s.file)??s.file,l=R(s.symbol);if(!l)return!1;let r=a(c);return r!==null&&jt(r,l)}}function jt(e,t){return new RegExp(`\\b${V(t)}\\b`).test(e)}function Nt(e,t){if(!K(A(e))){t.skipped.push({check:"baseline",reason:"no .scipquery-baseline.json \u2014 run health --write-baseline to enable"});return}t.checksRun.push("baseline");let i=Ge(e);for(let o of i.newFindings.filter(n=>!n.startsWith(j))){let n=O(o),a=b("baseline",o);D(t,{id:a,groupKey:`baseline:${n.sourceAnalyzer}:${n.rootCauseKey}`,check:"baseline",severity:"error",evidence:"baseline",actionTier:n.actionTier,confidence:1,file:n.file,relatedFiles:n.relatedFiles.length>0?n.relatedFiles:void 0,sourceAnalyzer:n.sourceAnalyzer,rootCauseKey:n.rootCauseKey,message:`new ${n.label} vs committed baseline: ${o}`,why:["A committed health baseline exists.","The current health result contains a finding not present in that baseline.",`Underlying analyzer: ${n.sourceAnalyzer}.`,`Inherited action tier: ${n.actionTier}.`,`Root cause key: ${n.rootCauseKey}.`,...n.why],remediation:n.remediation})}}function Bt(e,t){if(!pe(e.config.architecture)){t.skipped.push({check:"architecture",reason:"no closed architecture dependency rows, requireCompletePolicy rule, or requireAcyclic rule configured"});return}if(!K(A(e))){t.skipped.push({check:"architecture",reason:"no .scipquery-baseline.json \u2014 run health --write-baseline to enable"});return}t.checksRun.push("architecture");let i=Ee(e);for(let o of i.newFindings){let n=O(o),a=b("architecture",o);D(t,{id:a,groupKey:`architecture:${n.rootCauseKey}`,check:"architecture",severity:"error",evidence:"baseline",actionTier:"direct",confidence:1,sourceAnalyzer:"architecture",rootCauseKey:n.rootCauseKey,message:`new ${n.label} vs committed baseline: ${o}`,why:["The project declares an enforceable architecture rule.","The current boundary graph contains a violation not present in the committed baseline.",...n.why],remediation:n.remediation})}}function b(e,...t){return`SQ${st("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}export{xe as a,ei as b,Ge as c,Ii as d,ji as e,Ni as f,Bi as g,It as h};
|
|
3
|
-
//# sourceMappingURL=chunk-42QYU6FD.js.map
|
package/dist/chunk-6SHX42QQ.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{a as t}from"./chunk-ZL5Y23AJ.js";import{execFileSync as a}from"child_process";import{createRequire as S}from"module";import{existsSync as y}from"fs";import{platform as s,arch as g}from"os";var f="v0.8.1",l="https://github.com/sourcegraph/scip",h="SCIP_QUERY_SCIP_BIN";function x(e){if(e.isOnPath("scip"))return{source:"path",path:"scip"};let r=e.env[h];if(r&&e.fileExists(r))return{source:"env",path:r};if(e.platform==="win32"){let n=e.resolveSidecar(e.arch);if(n&&e.fileExists(n))return{source:"sidecar",path:n}}return null}function C(e){let r=S(import.meta.url);for(let n of e==="arm64"?["arm64","x64"]:[e])try{return r.resolve(`scip-query-scip-windows/scip-win32-${n}.exe`)}catch{}return null}function m(e=process.env){return x({platform:s(),arch:g(),env:e,isOnPath:t,fileExists:y,resolveSidecar:C})?.path??null}function N(){return m()!==null}function O(){let e=m();if(!e)return null;try{return a(e,["--version"],{stdio:"pipe"}).toString().trim()}catch{return null}}function P(){let e=s(),r=g(),n,o,c;switch(e){case"darwin":n="darwin",c="tar.gz";break;case"linux":n="linux",c="tar.gz";break;default:return null}switch(r){case"arm64":o="arm64";break;case"x64":o="amd64";break;default:return null}let u=`scip-${n}-${o}.${c}`;return{url:`${l}/releases/download/${f}/${u}`,filename:u}}function j(){let e=P();console.log("\nThe `scip` CLI is required but not found on PATH.\n"),s()==="darwin"?(console.log("Install via Homebrew:"),console.log(` brew install sourcegraph/scip/scip
|
|
2
|
-
`),console.log("Or download manually:")):s()==="win32"?(console.log("On Windows the scip binary ships via the npm sidecar package scip-query-scip-windows,"),console.log("installed automatically with scip-query. If it is missing:"),console.log(" npm install -g scip-query-scip-windows"),console.log(`Or set ${h} to a local scip.exe path.
|
|
3
|
-
`),console.log("Upstream release page:")):console.log("Download from:"),console.log(e?` ${e.url}
|
|
4
|
-
`:` ${l}/releases/tag/${f}
|
|
5
|
-
`),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function L(e){if(s()==="darwin"&&t("brew")){e("Installing scip CLI via Homebrew...");try{if(a("brew",["install","sourcegraph/scip/scip"],{stdio:"inherit",timeout:3e5,env:process.env}),t("scip"))return e("Successfully installed scip CLI via Homebrew"),!0}catch(r){let n=r instanceof Error?r.message:String(r);e(`Homebrew install failed: ${n}`)}}if(t("go")){e("Installing scip CLI via go install...");try{if(a("go",["install","github.com/sourcegraph/scip/cmd/scip@latest"],{stdio:"inherit",timeout:3e5,env:process.env}),t("scip"))return e("Successfully installed scip CLI via go install"),!0}catch(r){let n=r instanceof Error?r.message:String(r);e(`go install failed: ${n}`)}}return e("Could not auto-install scip CLI."),e(`Install manually from: ${l}/releases`),!1}import{createHash as w}from"crypto";import{mkdirSync as I,realpathSync as b}from"fs";import{homedir as E}from"os";import{join as i,resolve as d}from"path";function _(e,r){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return p(n);if(r?.dbPath)return p(d(e,r.dbPath));let o=R(e);return p(o)}function v(){let e=process.env.XDG_CACHE_HOME;return i(e||i(E(),".cache"),"scip-query")}function R(e){let r=d(e);try{r=b(r)}catch{}let n=w("sha256").update(r).digest("hex").slice(0,12);return i(v(),"projects",n)}function J(e){if(!/^[a-f0-9]{24}$/.test(e))throw new Error(`invalid repository cache identity: ${e}`);return i(v(),"repositories",e)}function T(e){return process.env.SCIP_QUERY_SHARED_CACHE!=="0"&&!process.env.SCIP_QUERY_CACHE_DIR&&!process.env.SCIP_QUERY_INDEX_DB&&!e?.dbPath}function z(e,r){let n=_(e,r);return{cacheDir:n,dbPath:i(n,"index.db"),indexPath:i(n,"index.scip"),metaPath:i(n,"meta.json")}}function p(e){return I(e,{recursive:!0}),e}export{m as a,N as b,O as c,j as d,L as e,R as f,J as g,T as h,z as i};
|
|
6
|
-
//# sourceMappingURL=chunk-6SHX42QQ.js.map
|
package/dist/chunk-AERYQJ52.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{c as p}from"./chunk-4XTPZ5CR.js";import{b as B}from"./chunk-B75HZHUP.js";import{a as m}from"./chunk-BGBBVSH4.js";import{d as f,t as g}from"./chunk-TDGCALH6.js";import{b as y}from"./chunk-QNMOZ3CJ.js";import{z as d}from"./chunk-M2TRDR25.js";import{createHash as C}from"crypto";var b=3;function w(n,t={}){let{scope:e,maxLoc:o=15,minLoc:i=b,limit:r,scanLimit:a}=t,l=p(n),u=L(n,{scope:e,maxLoc:o,scanLimit:a}).map(s=>h(n,s,l,i)).filter(s=>s!==null),c=I(u);return r?c.slice(0,r):c}function H(n,t,e={}){let{scope:o,maxLoc:i=15,minLoc:r=b,scanLimit:a}=e,l=p(n),u=L(n,{scope:o,maxLoc:i,scanLimit:a}).map(s=>h(n,s,l,r)).filter(s=>s!==null),c=u.find(s=>s.symbol===t);return c?u.filter(s=>s.symbol!==c.symbol&&s.normalizedBody===c.normalizedBody&&s.file!==c.file).sort(z).map(({normalizedBody:s,...S})=>S):[]}function A(n){let t=E(n);return y(t).replace(/\s+/g,"")}function I(n){let t=new Map;for(let o of n){if(o.normalizedBody.length<8)continue;let i=W(o.normalizedBody),r=t.get(i)??[];r.push(o),t.set(i,r)}let e=[];for(let[o,i]of t){let r=new Set(i.map(l=>l.file));if(i.length<2||r.size<2)continue;let a=[...i].sort(z).map(({normalizedBody:l,...u})=>u);e.push({hash:o,canonical:a[0],functions:a})}return e.sort((o,i)=>{let r=i.functions.length-o.functions.length;if(r!==0)return r;let a=D(i)-D(o);return a!==0?a:o.canonical.file.localeCompare(i.canonical.file)}),e}function L(n,t){let e=g(n,{scope:t.scope}).filter(o=>o.isFunctionLike&&!n.isIgnored(o.relativePath)).filter(o=>m(o)<=t.maxLoc);return e.sort((o,i)=>m(i)-m(o)||o.relativePath.localeCompare(i.relativePath)),B(e,t.scanLimit)}function h(n,t,e,o){let i=x(n,t);if(!i||P(i)<o)return null;let r=v(n,t);return r?{symbol:t.symbol,shortName:f(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:m(t),ageCommits:e?.get(t.relativePath)?.commitsAgo??null,normalizedBody:r}:null}function v(n,t){let e=x(n,t);return e&&A(e)||null}function x(n,t){let e=d(n,t.relativePath);return e.length===0?null:e.slice(t.startLine,t.endLine+1).join(`
|
|
2
|
-
`)}function E(n){let t=n.indexOf("{"),e=n.lastIndexOf("}");if(t>=0&&e>t)return n.slice(t+1,e);let o=n.indexOf("=>");return o>=0?n.slice(o+2).replace(/;+\s*$/,""):n}function P(n){return E(n).split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0).length}function W(n){return C("sha256").update(n).digest("hex").slice(0,16)}function z(n,t){let e=n.ageCommits??-1;return(t.ageCommits??-1)-e||n.file.localeCompare(t.file)||n.startLine-t.startLine}function D(n){return n.functions.reduce((t,e)=>t+e.loc,0)}export{w as a,H as b,A as c,I as d,v as e,x as f,E as g};
|
|
3
|
-
//# sourceMappingURL=chunk-AERYQJ52.js.map
|