scip-query 0.19.3 → 0.19.5
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 +27 -0
- package/README.md +1 -1
- package/dist/augment-vue-worker.js +1 -1
- package/dist/{chunk-LSJDKJIB.js → chunk-25LPM4DG.js} +2 -2
- package/dist/chunk-2CTX5CMX.js +4 -0
- package/dist/chunk-2Y373BDD.js +2 -0
- package/dist/{chunk-24ET4VLC.js → chunk-2YU7I3QO.js} +2 -2
- package/dist/{chunk-QNO3QIMN.js → chunk-3MJ5YA4Y.js} +2 -2
- package/dist/{chunk-B26UX7ZD.js → chunk-3SVWW4PN.js} +2 -2
- package/dist/{chunk-WWCZCH7W.js → chunk-4333ETTV.js} +2 -2
- package/dist/{chunk-6EWBPAA3.js → chunk-4RSI5EMG.js} +2 -2
- package/dist/{chunk-CIYUFF24.js → chunk-4SALD7RU.js} +2 -2
- package/dist/{chunk-XWE7PZQH.js → chunk-4T3LTWUS.js} +2 -2
- package/dist/{chunk-34MLC6UI.js → chunk-4XTA5OMB.js} +2 -2
- package/dist/chunk-52ZYCAEO.js +2 -0
- package/dist/{chunk-SJ6XSCG7.js → chunk-54HA4ZXH.js} +2 -2
- package/dist/{chunk-J4MYRIYT.js → chunk-64RFXJT5.js} +2 -2
- package/dist/{chunk-FUFNRZFJ.js → chunk-6E7UTQY7.js} +2 -2
- package/dist/{chunk-PNESKY2Z.js → chunk-6NSFJYRC.js} +2 -2
- package/dist/{chunk-AOSFSYEA.js → chunk-7B3UPBVA.js} +2 -2
- package/dist/{chunk-4BUMNEYQ.js → chunk-7GXM52MI.js} +2 -2
- package/dist/chunk-7UY7SD7D.js +927 -0
- package/dist/{chunk-SOS256TP.js → chunk-A2EZV2UM.js} +2 -2
- package/dist/{chunk-6FIA5BEB.js → chunk-ABMYA4TN.js} +2 -2
- package/dist/{chunk-64QITTX7.js → chunk-B5NLK2B3.js} +2 -2
- package/dist/{chunk-OLG2YPLS.js → chunk-BTEE5NZQ.js} +2 -2
- package/dist/{chunk-MP43RX4O.js → chunk-C7NIYIQ4.js} +1 -1
- package/dist/{chunk-AEM24WSF.js → chunk-CFMXJPHH.js} +2 -2
- package/dist/{chunk-HHOJH3RJ.js → chunk-CNKAGUPL.js} +2 -2
- package/dist/{chunk-MQ2B33LQ.js → chunk-D4U5Q3FT.js} +2 -2
- package/dist/{chunk-YZXV3CU3.js → chunk-DGAGY7RJ.js} +1 -1
- package/dist/{chunk-FRXB74RQ.js → chunk-DLWR3NUU.js} +5 -5
- package/dist/{chunk-YGQBJUS6.js → chunk-DZ74OMG6.js} +2 -2
- package/dist/{chunk-APLNTJPJ.js → chunk-EOOJGLDU.js} +2 -2
- package/dist/{chunk-TYEGFDOP.js → chunk-F6O7AAC3.js} +2 -2
- package/dist/{chunk-HFBNIIZX.js → chunk-FECYOO5O.js} +2 -2
- package/dist/{chunk-AFVU2GB2.js → chunk-FWUUZTIO.js} +2 -2
- package/dist/{chunk-KMOMNTB4.js → chunk-GBQ5NYPR.js} +2 -2
- package/dist/{chunk-2ROSOG2I.js → chunk-GPBBJ5Y4.js} +2 -2
- package/dist/{chunk-IXAALOUP.js → chunk-H7UKLTWJ.js} +2 -2
- package/dist/{chunk-YILKXTIY.js → chunk-HEXVUYFQ.js} +2 -2
- package/dist/{chunk-J5XJWCB3.js → chunk-HKEHS2AS.js} +2 -2
- package/dist/{chunk-JRCJEHRG.js → chunk-I5AWSI2G.js} +2 -2
- package/dist/{chunk-XYBNOILR.js → chunk-I5RJM53C.js} +2 -2
- package/dist/{chunk-AD7WUFFT.js → chunk-IG7N5ZIK.js} +2 -2
- package/dist/{chunk-C3KCSAQ4.js → chunk-IUFDSKGG.js} +2 -2
- package/dist/{chunk-OQ6TCHBB.js → chunk-IZKFSVBV.js} +2 -2
- package/dist/{chunk-5OZCNAVM.js → chunk-J77UIT3I.js} +2 -2
- package/dist/{chunk-EGKWRX5I.js → chunk-K2ERX4UT.js} +2 -2
- package/dist/{chunk-FYE4PWWP.js → chunk-KP6XRY5Z.js} +2 -2
- package/dist/{chunk-FC5K7T35.js → chunk-L7SPDE73.js} +1 -1
- package/dist/{chunk-YGBHQOB2.js → chunk-LBMJEAEW.js} +2 -2
- package/dist/chunk-LHMNRHGV.js +3 -0
- package/dist/{chunk-5TZ2MQBG.js → chunk-M7AIS73L.js} +2 -2
- package/dist/{chunk-53SUJOJA.js → chunk-M7MTH5NR.js} +2 -2
- package/dist/{chunk-HNTLCR4F.js → chunk-MITTUCEH.js} +2 -2
- package/dist/{chunk-5GCAM4JE.js → chunk-MSWVMDAH.js} +6 -6
- package/dist/chunk-NH5ALKPW.js +2 -0
- package/dist/{chunk-EHU4TZJJ.js → chunk-NPKYOIFM.js} +3 -3
- package/dist/{chunk-XWJ3JYRG.js → chunk-NRCXJDHL.js} +2 -2
- package/dist/{chunk-5GOBZI34.js → chunk-NSS46APD.js} +2 -2
- package/dist/{chunk-5FUAFNMP.js → chunk-NZL2DBT7.js} +2 -2
- package/dist/{chunk-C3VQZFP2.js → chunk-OMPZHGHO.js} +2 -2
- package/dist/{chunk-XYNWAZ6J.js → chunk-P2PC2WGR.js} +2 -2
- package/dist/{chunk-CAKPEQZB.js → chunk-Q3AFUTGB.js} +2 -2
- package/dist/{chunk-ZJGZCBYT.js → chunk-Q4IIEGXJ.js} +2 -2
- package/dist/chunk-QDV6RDCP.js +4 -0
- package/dist/{chunk-FTRNGQGR.js → chunk-QGXBRIM5.js} +2 -2
- package/dist/{chunk-WXVGNFAO.js → chunk-QOKYJ33H.js} +1 -1
- package/dist/{chunk-FB6IKAKZ.js → chunk-QRGV2F7L.js} +2 -2
- package/dist/chunk-QVWS2VWZ.js +7 -0
- package/dist/{chunk-77IOFJVY.js → chunk-R4FQGQ4X.js} +2 -2
- package/dist/{chunk-4CZJ4YJB.js → chunk-RV2FQIX3.js} +2 -2
- package/dist/{chunk-4FMT4HPC.js → chunk-S44IULR6.js} +2 -2
- package/dist/{chunk-PCIFZHWS.js → chunk-SOAT6NLA.js} +2 -2
- package/dist/{chunk-TDUU63FC.js → chunk-STOL2BTL.js} +2 -2
- package/dist/{chunk-TOIS2VAI.js → chunk-TW4OG5FC.js} +2 -2
- package/dist/{chunk-2WCXKANA.js → chunk-U6WNH5GC.js} +2 -2
- package/dist/chunk-U7DSEKOM.js +30 -0
- package/dist/{chunk-EII5ZHL2.js → chunk-UKZBVX4U.js} +2 -2
- package/dist/chunk-UOAV44HR.js +38 -0
- package/dist/{chunk-VIKEPD4D.js → chunk-VGRICIQI.js} +2 -2
- package/dist/{chunk-JFO2UVQP.js → chunk-VTKGCT3V.js} +5 -5
- package/dist/{chunk-PJENL245.js → chunk-VXQNNXJE.js} +2 -2
- package/dist/{chunk-HAC5EI2T.js → chunk-WER3B7MI.js} +2 -2
- package/dist/{chunk-5OR4QRPR.js → chunk-WQTAC523.js} +2 -2
- package/dist/{chunk-GAE7WCBK.js → chunk-X6D5IC6I.js} +2 -2
- package/dist/chunk-XAGAZSFE.js +6 -0
- package/dist/{chunk-FBUNGRKI.js → chunk-XLTP42QA.js} +2 -2
- package/dist/chunk-XTX6QHOF.js +4 -0
- package/dist/{chunk-AYRHVJXW.js → chunk-XYADIZHU.js} +5 -5
- package/dist/{chunk-WAU7HVDI.js → chunk-YGAGTIDK.js} +2 -2
- package/dist/{chunk-IICQP2DY.js → chunk-YIJ7ZAA4.js} +3 -3
- package/dist/{chunk-EYF5HOUZ.js → chunk-YNRNA5LK.js} +2 -2
- package/dist/{chunk-QKW7ISEW.js → chunk-YVVCVR2L.js} +2 -2
- package/dist/{chunk-Z7M7X3ZG.js → chunk-ZGZUZ7XE.js} +2 -2
- package/dist/{chunk-PTYQQHZM.js → chunk-ZXJYMGD3.js} +2 -2
- package/dist/cli.js +3 -3
- package/dist/command-descriptors-N2TL4XM2.js +613 -0
- package/dist/{config-types-BA3xLCfG.d.ts → config-types-D20KuvvZ.d.ts} +67 -0
- package/dist/{db-CzA-9_rL.d.ts → db-G_II8yXU.d.ts} +1 -1
- package/dist/diff-gate-types-C9BoYwYD.d.ts +10 -0
- package/dist/direct-navigation-DUCZCTOE.js +3 -0
- package/dist/{health-DYy13GAe.d.ts → health-oblXYgkF.d.ts} +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/queries/affected.d.ts +2 -2
- package/dist/queries/affected.js +1 -1
- package/dist/queries/architecture.d.ts +86 -4
- package/dist/queries/architecture.js +1 -1
- package/dist/queries/bottlenecks.d.ts +2 -2
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.d.ts +2 -2
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +2 -2
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +2 -2
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.d.ts +2 -2
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.d.ts +2 -2
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +2 -2
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +2 -2
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +2 -2
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.d.ts +2 -2
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +2 -2
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +2 -2
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +2 -2
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.d.ts +2 -2
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.d.ts +2 -2
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/deep-chains.d.ts +2 -2
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/deps.d.ts +2 -2
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-gate.d.ts +3 -3
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.d.ts +4 -8
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +3 -3
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +2 -2
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.d.ts +2 -2
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/extract-candidates.d.ts +2 -2
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +2 -2
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +2 -2
- package/dist/queries/health.d.ts +3 -3
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +2 -2
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +2 -2
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +2 -2
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +3 -2
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +21 -5
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.d.ts +2 -2
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.d.ts +2 -2
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.d.ts +2 -2
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.d.ts +2 -2
- package/dist/queries/methods.js +1 -1
- package/dist/queries/not-implemented.d.ts +2 -2
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.d.ts +2 -2
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.d.ts +2 -2
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.d.ts +2 -2
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/react-component-duplicates.d.ts +2 -2
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.d.ts +2 -2
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.d.ts +2 -2
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.d.ts +2 -2
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +2 -2
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.d.ts +2 -2
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.d.ts +2 -2
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-chains.d.ts +2 -2
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.d.ts +2 -2
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.d.ts +2 -2
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +2 -2
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.d.ts +2 -2
- package/dist/queries/slice.js +1 -1
- package/dist/queries/stale-abstractions.d.ts +2 -2
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/stats.d.ts +2 -2
- package/dist/queries/surface.d.ts +2 -2
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.d.ts +2 -2
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.d.ts +2 -2
- package/dist/queries/system.js +1 -1
- package/dist/queries/test-quality.d.ts +2 -2
- package/dist/queries/test-quality.js +1 -1
- package/dist/queries/trace.d.ts +2 -2
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.d.ts +2 -2
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/twin-drift.d.ts +2 -2
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.d.ts +2 -2
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.d.ts +2 -2
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/vue-component-duplicates.d.ts +2 -2
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.d.ts +2 -2
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.d.ts +2 -2
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/queries/wrapper-candidates.d.ts +2 -2
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/reindex-worker.js +7 -7
- package/dist/reindex.d.ts +3 -3
- package/dist/reindex.js +1 -1
- package/dist/runtime.d.ts +3 -3
- package/dist/runtime.js +2 -2
- package/dist/rust-semantic-session-worker.js +1 -1
- package/dist/rust-semantic-worker.js +1 -1
- package/dist/{scip-cli-1bVKJgXi.d.ts → scip-cli-kRpaexVJ.d.ts} +1 -1
- package/dist/watch-server.js +4 -4
- package/docs/AI_FAILURE_MODES.md +1 -1
- package/docs/COMMAND_REFERENCE.md +6 -6
- package/docs/DETECTOR_GUIDE.md +1 -1
- package/docs/analyzer-inventory.md +1 -1
- package/docs/analyzer-validation-ledger.md +131 -1
- package/docs/architecture-coherence-vision.md +29 -0
- package/package.json +2 -2
- package/skills/_shared/SKILL.md +6 -16
- package/skills/scip-api-impact/SKILL.md +22 -21
- package/skills/scip-claim-audit/SKILL.md +18 -17
- package/skills/scip-cleanup-audit/SKILL.md +24 -20
- package/skills/scip-cleanup-improve/SKILL.md +19 -18
- package/skills/scip-concrete-plan/HIGH_ASSURANCE.md +317 -0
- package/skills/scip-concrete-plan/SKILL.md +70 -227
- package/skills/scip-conductor/SKILL.md +14 -14
- package/skills/scip-debug/SKILL.md +21 -21
- package/skills/scip-diagram/SKILL.md +27 -27
- package/skills/scip-directory-architecture/SKILL.md +44 -32
- package/skills/scip-doc-reconcile/SKILL.md +17 -17
- package/skills/scip-explore/SKILL.md +23 -23
- package/skills/scip-hyper-optimization/SKILL.md +23 -23
- package/skills/scip-language-playbook/SKILL.md +34 -34
- package/skills/scip-maintainability/SKILL.md +21 -21
- package/skills/scip-probe-reachability/SKILL.md +10 -9
- package/skills/scip-query/SKILL.md +39 -39
- package/skills/scip-react-maintainability/SKILL.md +21 -21
- package/skills/scip-root-cause/SKILL.md +21 -20
- package/skills/scip-setup/SKILL.md +25 -24
- package/skills/scip-tla-model-system/SKILL.md +7 -7
- package/skills/scip-triage-issue/SKILL.md +27 -20
- package/skills/scip-twin-drift/SKILL.md +18 -16
- package/skills/scip-verify/SKILL.md +25 -9
- package/skills/scip-vue-maintainability/SKILL.md +21 -21
- package/dist/chunk-26JI77AY.js +0 -927
- package/dist/chunk-2E7QY4B5.js +0 -7
- package/dist/chunk-33RLKB6L.js +0 -4
- package/dist/chunk-DO775SYA.js +0 -2
- package/dist/chunk-HCSTQGQE.js +0 -4
- package/dist/chunk-MRYPDVOS.js +0 -5
- package/dist/chunk-NLNZK7RL.js +0 -5
- package/dist/chunk-OAM22BCR.js +0 -2
- package/dist/chunk-PLDIXTKR.js +0 -38
- package/dist/chunk-UJKZQLDB.js +0 -2
- package/dist/chunk-WFWQWQK6.js +0 -3
- package/dist/chunk-XAMVIPE2.js +0 -29
- package/dist/command-descriptors-QJEYYND2.js +0 -607
- package/dist/diff-gate-types-CG2YQ_ei.d.ts +0 -4
- package/dist/direct-navigation-TT23TDBS.js +0 -3
package/dist/watch-server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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
|
|
1
|
+
import{A as At,Aa as me,B as Lt,C as Nt,D as jt,E as le,F as de,G as _t,I as Ot,J as _e,K as Wt,L as $t,P as Oe,S as Gt,T as pe,U as We,V as qt,W as Ut,X as H,a as gt,b as yt,c as St,d as Ee,e as bt,f as Fe,g as vt,ga as Ht,h as xt,i as Rt,ja as $e,k as Ae,l as Le,m as Ct,n as Mt,p as wt,pa as Bt,r as kt,ra as Vt,s as Pt,sa as fe,t as Ne,ta as Kt,u as je,ua as zt,v as Tt,va as Yt,w as Dt,wa as Ge,x as Et,y as Q,ya as B,z as Ft,za as Jt}from"./chunk-MSWVMDAH.js";import{b as ft,c as mt,f as It,h as J,l as U,m as ue}from"./chunk-C7NIYIQ4.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 k 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 un}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(un(t.metaPath,"utf-8")),o=e.languages??$t(r),a=pn(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=Ht(t.dbPath,t.metaPath),d=l.state==="invalid"||l.state==="drifted",u=c&&!d;return{state:u?"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:u?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 pn(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(Oe)||t.endsWith(`${Oe}.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=H(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",u=>{u===0?t(Date.now()-i):n(new Error(`Reindex worker exited with code ${u}`))}),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 kn}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&&!Mn(e.profileEnvironment)||!e.request||!wn(e.request))throw new Error("TypeScript semantic service received an invalid mailbox request.");return e}function Mn(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&Object.values(r).every(e=>typeof e=="string"||e===null)}function wn(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 Tt(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=H(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:$e(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=kn(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=Dt(r,e)),t.lines&&(n.lines=Et(r,e)),t.ast&&(n.ast=Ft(r,e)),t.imports&&(n.imports=jt(r,e)),t.reexports&&(n.reexports=Nt(r,e)),i){let o=At(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&&pr.write(r,e,Ae(r,e,a),{projectFingerprint:o,definitions:i.map(s=>({...s}))}),i})}var pr=Mt({kind:"file-definitions",invalidation:wt("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=pr.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,
|
|
@@ -37,7 +37,7 @@ 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
|
|
|
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 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=
|
|
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};
|
|
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=Lt(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 ur(i,t);let o=n.get(i.leaf);if(!o||o.length===0)return ur(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],u=Math.abs(d.startLine-i.startLine);u<c&&(s=d,c=u)}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 ur(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 u of d)u==="{"?(a+=1,c=!0):u==="}"?a=Math.max(0,a-1):u==="("?s+=1:u===")"&&(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 w(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 u;for(;(u=a.exec(d))!==null;)c.push({file:e,line:l,column:u.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 ui(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),u=i.get(l.symbolId);u!==void 0&&u<=d||(i.set(l.symbolId,d),n.set(l.symbolId,o))}}}),n}function ui(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 pi=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 pi.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:le}),i),a=()=>(n??=N("typescript.source-file-index",()=>fi(r.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),n),s=c=>de(c)?w(t,c,()=>{let l=ee(Ye.resolve(r.config.projectRoot,c));for(let{project:d,sourceFiles:u}of a()){let p=u.get(l)??null;if(p||(p=d.addSourceFileAtPathIfExists(l)??null,p&&u.set(ee(p.getFilePath()),p)),p)return{project:d,sourceFile:p}}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:le});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=>Pt(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=kt(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 w(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 w(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 u=this.referencesCache.get(d.symbolId);u?n.set(d.symbolId,u):o.push(d)}if(o.length===0)return n;let a=o,s=t.exact?[]:o.filter(d=>!wr(d));if(s.length>=yi){let d=this.referencesForDefinitionsBySymbolScan(s);for(let u of s){let p=d.get(u.symbolId)??[];this.referencesCache.set(u.symbolId,p),n.set(u.symbolId,p)}if(a=o.filter(u=>wr(u)),a.length===0)return n}let c=new Map;for(let d of a){let u=c.get(d.relativePath);u?u.push(d):c.set(d.relativePath,[d])}let l=[];for(let[d,u]of c){let p=kr();N("typescript.references-map.file",()=>{let g=this.definitionNodesForFile(d);for(let f of u){i&&(p.cacheMisses+=1);let m=g.get(f.symbolId)??null;i&&(m?p.nodeHits+=1:p.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(f,m,i?p:void 0);this.referencesCache.set(f.symbolId,h),n.set(f.symbolId,h)}catch{p.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:d,definitions:u.length,...Pr(p)}))}if(l.length>0){let d=this.referencesForDefinitionsBySymbolScan(l);for(let u of l){let p=d.get(u.symbolId)??[];this.referencesCache.set(u.symbolId,p),n.set(u.symbolId,p)}}return n}referenceFragmentsForFiles(e){let t=fr(this.db).filter(o=>de(o.relativePath)),n=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,n);return Wt(t,i,n)}referencesForDefinitionsBySymbolScan(e,t){let n=ce(),i=kr(),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 M=o.get(h.symbolId)??[];M.push(...S),o.set(h.symbolId,M)}n&&(i.packageReferenceCount+=S.length)}n&&(i.packageRefsMs+=y.now()-c);let d=new Map,u=new Map,p=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,p,g,d,u,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 M=z(S);o.set(h,M),n&&(i.referenceCount+=M.length)}},()=>({definitions:e.length,...Pr(i)})),o}addReferencesFromSourceFileScan(e,t,n,i,o,a,s,c,l,d){let u=this.compilerCheckerForSourceFile(e),p=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(u,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 M=w(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(p,m),!Mr(L,t,A))){let D=p.getLineAndCharacterOfPosition(m.getStart(p));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 M)for(let C of o.get(D)?.values()??[]){if(A??=Ze(p,m),Mr(C,t,A))continue;if(!P){let I=p.getLineAndCharacterOfPosition(m.getStart(p));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(p)}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 u=t.get(d)??new Map;u.set(n.symbolId,n),t.set(d,u)}}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 u=d.getProperty(n.name);u&&a(d,u,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 u=s.getSourceFile(),p=u.getLineAndCharacterOfPosition(s.name.getStart(u)),g={definition:o,location:{file:o.relativePath,line:p.line,column:p.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 u of l){let p=u.getProperty(n.name);p&&(d=!0,a(u,p,this.hierarchyAncestorTypesForType(e,u)))}if(!d)for(let u of this.compilerSymbolKeys(c))i.add(u)};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 w(this.calleesCache,e.symbolId,()=>w(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 w(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 u={sourcePath:s,entry:l,typeOnlyDeclaration:c,bindingSymbol:d,references:[]};if(i.push(u),c||!l.localName||!d)continue;let p=o.get(l.localName);p?p.push(u):o.set(l.localName,[u])}}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&&wi(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 u=d.getNameNode().getText(),p=d.getAliasNode()?.getText()??u,g=this.indexedDefinitionByLeaf(c,u);if(!g)continue;let f=n.get(p);f||(f=new Set,n.set(p,f)),f.add(g.symbolId)}}}indexedDefinitionByLeaf(e,t){return w(this.indexedDefinitionLeafCache,e,()=>vr(this.db,e)).get(t)??null}nodeForDefinition(e){return w(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return w(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),u=l.getLineAndCharacterOfPosition(s.getStart(l)).line;if(t&&(t.declarationLocationMs+=y.now()-c),!d||this.db.isIgnored(d))continue;let p=t?y.now():0,g=this.compilerDeclarationName(s),f=n?Ke(this.db,d,u,i)??(g&&g!==i?Ke(this.db,d,u,g):null):br(this.db,d,u,i);if(t&&(t.indexedLookupMs+=y.now()-p),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,u=0,p=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,M=n?y.now():0,A=this.compilerCheckerForSourceFile(f),P=f.compilerNode;n&&(d=Math.round(y.now()-M));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,p);I&&(n&&(a+=1),xi(S,I.callerId,I.target))}this.tsMorph.ts.forEachChild(b,D)},C=n?y.now():0;D(P),n&&(u=Math.round(y.now()-C));for(let[b,I]of S)S.set(b,ki(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:u,...p?Mi(p):{}}))}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,u=this.compilerSymbolForExpression(e,d,s),p=null;if(u)if(s&&(s.targetSymbolHits+=1),o.has(u))s&&(s.compilerSymbolCacheHits+=1),p=o.get(u)??null;else{s&&(s.compilerSymbolCacheMisses+=1);let g=s?y.now():0;p=this.definitionFromCompilerSymbol(u,s),s&&(s.targetLookupMs+=y.now()-g),o.set(u,p)}else s&&(s.targetMisses+=1);return p?{callerId:l.symbolId,target:{symbol:p.symbol,file:p.file,line:p.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 Mr(r,e,t){return e===r.relativePath&&t>=r.startLine&&t<=r.endLine}function wr(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 Mi(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 kr(){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 wi(r,e,t){for(let n of e){let i=r.get(n)??[];i.push(...t),r.set(n,i)}}function ki(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??_t,this.discoverTsconfigs=t.discoverTsconfigs??Rr,this.createProjects=t.createProjects??Ot,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=_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 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 Me}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=Me(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??Vt,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 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=Me(r.requestDir,i),a=i.slice(0,-5);try{let s=zt(_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(Me(r.responseDir,`${a}.json`),{ok:!0,protocolVersion:fe,id:a,baseGeneration:s.baseGeneration,response:c})}catch(s){F(Me(r.responseDir,`${a}.json`),{ok:!1,protocolVersion:fe,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=B(r.cacheDir),n=Jt(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||!me(e.at)||e.refreshRequestedAt!==void 0&&!me(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"||!me(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 ke,readFileSync as ut,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(!Ut())return{kind:"disabled"};let n=gt(r);if(!n)return{kind:"unavailable"};let i=R(We(),"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}}),u=0,p=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}),p+=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}),u+=m.size;Ct(R(i,"evidence.db"));let g={kind:"swept",sweptAt:new Date(o).toISOString(),deletedWorktrees:p,deletedGenerations:d.deleteGenerations.length,deletedBytes:u,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),u=oo(d);if(!u)continue;let p=$(u.projectRoot);o.push({leasePath:d,lease:u,managed:u.repositoryId===t&&Xr(u),live:i.has(p)||Yr(p),busy:lt(u)})}let a=[];for(let l of ct(R(e,"locks"))){let d=/^([a-f0-9]{64})\.lock$/.exec(l);if(!d)continue;let u=R(e,"locks",l),p=dt(u),g=p!==void 0&&j(p),f=d[1];a.push({generationId:f,path:u,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 u=R(e,"generations",l),p;try{p=ke(u)}catch{continue}!p.isDirectory()||p.isSymbolicLink()||s.push({generationId:l,path:u,size:zr(u),...n[l]===void 0?{}:{unreferencedAt:n[l]}})}return{leases:o,generations:s,locks:a,temporaries:c}}function Xr(r){if(r.ownershipChecksum!==Bt(r)||$(r.localCacheDir)!==$(qt(r.projectRoot)))return!1;let e=$(We()),t=$(R(e,"projects")),n=$(r.localCacheDir);if(!n.startsWith(`${t}${Kr}`))return!1;try{let i=ke(e),o=ke(t),a=ke(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(B(r.localCacheDir).lockPath);return t!==void 0&&j(t)}function oo(r){try{let e=JSON.parse(ut(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(ut(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(ut(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,uo=250,po=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=H(i,o),c=B(s.cacheDir),l=Hr(c.lockPath,i);if(!l.acquired)return;let d=Date.now(),u=d,p={state:"idle"},g,f,m,h=pe(s.dbPath),S=!1,M=!1,A=0,P=0,L=0,D=0,C,b,I=er(s.cacheDir),pt=Kt(s.cacheDir);nt(I),it(pt);let Pe=new Ce({openDb:()=>or(i)}),Te=new we({projectRoot:i,currentGeneration:()=>Yt(s.dbPath)}),E=(v=!1)=>{if(!M)return;let q=Date.now();!v&&q-P<lo||(P=q,qr(c.statePath,{version:1,protocolVersion:Ge,pid:k.pid,projectRoot:i,...n.worktreeId?{worktreeId:n.worktreeId}:{},cliVersion:e,startedAt:new Date(d).toISOString(),heartbeatAt:new Date(q).toISOString(),lastActivityAt:new Date(u).toISOString(),...a.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(u+a.idleTimeoutMs).toISOString()},watcher:p,...p.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=()=>{u=Date.now()},oe=new ge({projectRoot:i,config:{...o,watch:a},languages:o.languages,onStatus(v){p=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=pe(s.dbPath),m=void 0,E(!0),v.state==="fresh"},onRefreshSuppressed(v){Gt(s.dbPath,v),h=pe(s.dbPath)},onError(v){G(),g=void 0,m={at:new Date().toISOString(),message:v.message},E(!0)}}),se=()=>{S=!0};k.once("SIGINT",se),k.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(),M=!0,E(!0);!S;){let en=jr(pt,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>=uo){L=ae;let T=Ur(c.activityPath);T&&T.atMs>u&&(u=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:p,lastActivityAtMs:u,nowMs:Date.now(),idleTimeoutMs:a.idleTimeoutMs}))break;await ho(po)}}finally{k.off("SIGINT",se),k.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=k.argv[1]?co(ao(k.argv[1])).href:null;if(go===import.meta.url){let r=k.argv[2],e=k.argv[3],t=yo(k.argv[4]);if(!r||!e)console.error("watch-service: expected <project-root> <cli-version>"),k.exitCode=1;else try{await mo(r,e,t)}catch(n){console.error(`watch-service: ${n instanceof Error?n.message:String(n)}`),k.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/docs/AI_FAILURE_MODES.md
CHANGED
|
@@ -301,7 +301,7 @@ scip-query setup-agent --git-hook # pre-commit backstop: fires whoever wrote
|
|
|
301
301
|
| `co-change-partner` | Historically coupled files that usually change together but are missing from this diff. | Default diff gate. |
|
|
302
302
|
| `twin-partner` | A changed symbol has a same-(near-)name twin (identical or already-divergent) elsewhere that this diff left untouched. | Default diff gate. Advisory: findings print but never cause a nonzero exit by themselves. |
|
|
303
303
|
| `coverage-contract` | A configured `coverageContracts` entry (.scipquery.json) drifted: its declared key set no longer matches its ground-truth source. | Default diff gate, only when either side of a configured contract changed. |
|
|
304
|
-
| `architecture` | A declared architecture boundary rule has a violation absent from the committed health baseline. | Default diff gate when closed dependency rows, requireCompletePolicy, or
|
|
304
|
+
| `architecture` | A declared architecture boundary rule has a violation absent from the committed health baseline. | Default diff gate when closed dependency rows, requireCompletePolicy, requireAcyclic, requireResolvedBoundaries, requireMinimalPolicy, maxBoundaryFanOut/maxBoundaryFiles, or testPaths are configured and a baseline exists. |
|
|
305
305
|
| `doc-reference` | Docs that cite changed files and may need a matching update. Dated snapshot docs (docs.snapshotPaths) are excluded by policy. | Default diff gate. Advisory (21.2) for bare file-mention citations; blocking when the citation has a line anchor or the cited file was deleted/renamed. |
|
|
306
306
|
| `unused-params` | Fresh trailing parameters or options that no changed body uses. | Default diff gate. |
|
|
307
307
|
| `new-dead` | Changed production symbols with zero indexed consumers. | Default diff gate. |
|
|
@@ -24,11 +24,11 @@ This syntax summary is generated from the CLI command descriptors. Keep workflow
|
|
|
24
24
|
|---|---|---|
|
|
25
25
|
| `files <pattern>` | Find files matching a pattern | `--json` |
|
|
26
26
|
| `methods <className>` | List methods of a class (with line ranges) | `--json` |
|
|
27
|
-
| `refs <symbol>` | Find all files referencing a symbol | `--full`<br>`--json` |
|
|
28
|
-
| `trace <symbol>` | Trace a symbol: definition + all references | `--full`<br>`--json` |
|
|
27
|
+
| `refs <symbol>` | Find all files referencing a symbol | `--full`<br>`-n, --limit <n>`<br>`--cursor <cursor>`<br>`--json`<br>`--compact` |
|
|
28
|
+
| `trace <symbol>` | Trace a symbol: definition + all references | `--full`<br>`--compact`<br>`--json` |
|
|
29
29
|
| `deps <file>` | Files this file depends on (internal) | `--json` |
|
|
30
30
|
| `rdeps <file>` | Files that depend on this file/module | `--json` |
|
|
31
|
-
| `system <module>` | Full module map: files, symbols, deps in/out | `--json` |
|
|
31
|
+
| `system <module>` | Full module map: files, symbols, deps in/out | `--compact`<br>`--json` |
|
|
32
32
|
| `surface <module>` | What symbols consumers actually use from this module | `--json` |
|
|
33
33
|
| `imports <file>` | What symbols does this file import? | `--full`<br>`--json` |
|
|
34
34
|
| `imported-by <symbol>` | Which files import this symbol? | `--json` |
|
|
@@ -100,7 +100,7 @@ This syntax summary is generated from the CLI command descriptors. Keep workflow
|
|
|
100
100
|
| `affected <symbol>` | Transitive closure of symbols that could break if this symbol changes | `--max-depth <n>`<br>`-s, --scope <path>`<br>`--json` |
|
|
101
101
|
| `change-surface <file>` | Pre-change briefing: exports, consumers, and blast-radius risk | `--full`<br>`--json` |
|
|
102
102
|
| `co-change [file]` | Files that change together in git history without a dependency edge — hidden coupling candidates | `--min-together <n>`<br>`-n, --limit <n>`<br>`--all`<br>`--full`<br>`--json` |
|
|
103
|
-
| `diff-gate` | Gate the current diff: architecture regressions plus echo, migration, coordination, doc-drift, unused-param, and new-dead candidates; exit 1 on blocking findings | `--base <ref>`<br>`--min-together <n>`<br>`--max-echo-checks <n>`<br>`--max-helpers <n>`<br>`--baseline`<br>`--full`<br>`--skip <check>`<br>`--hook`<br>`--json` |
|
|
103
|
+
| `diff-gate` | Gate the current diff: architecture regressions plus echo, migration, coordination, doc-drift, unused-param, and new-dead candidates; exit 1 on blocking findings | `--base <ref>`<br>`--min-together <n>`<br>`--max-echo-checks <n>`<br>`--max-helpers <n>`<br>`--baseline`<br>`--full`<br>`--skip <check>`<br>`--hook`<br>`--json`<br>`--compact` |
|
|
104
104
|
| `incomplete-migration` | Partially-completed extraction candidates: new helpers in the diff wired into some sites while similar un-migrated sites remain | `--base <ref>`<br>`--min-containment <n>`<br>`--max-helpers <n>`<br>`-n, --limit <n>`<br>`--full`<br>`--json` |
|
|
105
105
|
| `diff-impact` | Compute changed symbols and downstream consumers from current git diff | `--base <ref>`<br>`--json` |
|
|
106
106
|
|
|
@@ -114,7 +114,7 @@ This syntax summary is generated from the CLI command descriptors. Keep workflow
|
|
|
114
114
|
|
|
115
115
|
| Command | Description | Options |
|
|
116
116
|
|---|---|---|
|
|
117
|
-
| `plan-context <target>` | Pre-edit planning context for a symbol, file, or module | `--impact-depth <n>`<br>`--slice-depth <n>`<br>`-s, --scope <path>`<br>`-n, --limit <n>`<br>`--full`<br>`--json` |
|
|
117
|
+
| `plan-context <target>` | Pre-edit planning context for a symbol, file, or module | `--impact-depth <n>`<br>`--slice-depth <n>`<br>`-s, --scope <path>`<br>`-n, --limit <n>`<br>`--full`<br>`--json`<br>`--compact` |
|
|
118
118
|
|
|
119
119
|
### Health
|
|
120
120
|
|
|
@@ -177,7 +177,7 @@ enforce (see `docs/plans/2026-07-02-followups.md` items 6 and 9).
|
|
|
177
177
|
Followup #6 closed the one confirmed gap in an otherwise-wired battery command: `co-change`
|
|
178
178
|
(`src/runtime/query-commands/impact.ts`) used the plain `dbCommand` and never disclosed a budget,
|
|
179
179
|
even though its per-pair classification loop in `queries.coChange`
|
|
180
|
-
(`src/queries/
|
|
180
|
+
(`src/queries/cleanup/co-change.ts`) does real filesystem/graph work whose cost scales with
|
|
181
181
|
candidate-pair count on a large repository. It now flows through `budgetedDbCommand` and
|
|
182
182
|
`coChange` accepts a `scanLimit` option that truncates the (already priority-sorted) candidate
|
|
183
183
|
pairs before classification, so the disclosed budget is truthful rather than cosmetic.
|
package/docs/DETECTOR_GUIDE.md
CHANGED
|
@@ -92,7 +92,7 @@ coverage, reciprocity, and connected-group signals.
|
|
|
92
92
|
| `co-change-partner` | Historically coupled files that usually change together but are missing from this diff. | Default diff gate. |
|
|
93
93
|
| `twin-partner` | A changed symbol has a same-(near-)name twin (identical or already-divergent) elsewhere that this diff left untouched. | Default diff gate. Advisory: findings print but never cause a nonzero exit by themselves. |
|
|
94
94
|
| `coverage-contract` | A configured `coverageContracts` entry (.scipquery.json) drifted: its declared key set no longer matches its ground-truth source. | Default diff gate, only when either side of a configured contract changed. |
|
|
95
|
-
| `architecture` | A declared architecture boundary rule has a violation absent from the committed health baseline. | Default diff gate when closed dependency rows, requireCompletePolicy, or
|
|
95
|
+
| `architecture` | A declared architecture boundary rule has a violation absent from the committed health baseline. | Default diff gate when closed dependency rows, requireCompletePolicy, requireAcyclic, requireResolvedBoundaries, requireMinimalPolicy, maxBoundaryFanOut/maxBoundaryFiles, or testPaths are configured and a baseline exists. |
|
|
96
96
|
| `doc-reference` | Docs that cite changed files and may need a matching update. Dated snapshot docs (docs.snapshotPaths) are excluded by policy. | Default diff gate. Advisory (21.2) for bare file-mention citations; blocking when the citation has a line anchor or the cited file was deleted/renamed. |
|
|
97
97
|
| `unused-params` | Fresh trailing parameters or options that no changed body uses. | Default diff gate. |
|
|
98
98
|
| `new-dead` | Changed production symbols with zero indexed consumers. | Default diff gate. |
|
|
@@ -94,7 +94,7 @@ The declared-coupling config has been refreshed after the inventory surfaced old
|
|
|
94
94
|
| `hotspots` | Most referenced symbols | Support/contextual signal | Identifies choke points. Not a smell alone. |
|
|
95
95
|
| `fan-in` / `fan-out` | Reference counts into symbols or out of files | Support analysis | Raw graph metrics. |
|
|
96
96
|
| `coupling` | Shared symbols between two files or top coupled pairs, coupling kind, action tier, evidence reasons, recommendation | Contextual signal | May reveal boundary problems, but shared symbols can be intended. Output now makes the coordination-pressure interpretation explicit. |
|
|
97
|
-
| `architecture` | Project-owned boundary paths and dependency rules applied to resolved import and re-export edges, with mapping coverage, policy-row coverage, edge breadth, reciprocity, and SCCs | Split by evidence | Forbidden edges, required-but-missing policy rows,
|
|
97
|
+
| `architecture` | Project-owned boundary paths and dependency rules applied to resolved import and re-export edges, with mapping coverage, policy-row coverage, edge breadth, reciprocity, and SCCs | Split by evidence | Forbidden edges, required-but-missing policy rows, cycles under `requireAcyclic`, and boundaries hiding an internal sub-directory cycle under `requireResolvedBoundaries` are direct policy findings. Unmapped files, reciprocity, and advisory cycles remain report-only signals. |
|
|
98
98
|
| `deep-chains` | Longest dependency chains after SCC condensation, suffix de-duplication, chain kind, action tier, evidence reasons, recommendation | Contextual signal | Long chains imply propagation risk, but action depends on layers and ownership. Strict suffix duplicates are now removed from top results. |
|
|
99
99
|
| `complexity` | Branch count, cyclomatic estimate, callee count, fan-in, fan-out for one symbol | Direct repair pressure | This is closer to the user-specified "cyclomatic complexity" analyzer than `complexity-hotspots`. Should score strongly when branches/cyclomatic exceed thresholds. |
|
|
100
100
|
| `self-audit` | Cheap evidence paths checked against TypeScript compiler oracle | Meta analysis | Measures analyzer accuracy. Should guide trust/weight, not code health directly. |
|