scip-query 0.19.6 → 0.19.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/README.md +28 -15
- package/dist/augment-vue-worker.js +1 -1
- package/dist/chunk-2465DLHK.js +3 -0
- package/dist/{chunk-2CVXCGL4.js → chunk-24GTWJ3N.js} +2 -2
- package/dist/{chunk-XVJ3V7LM.js → chunk-2SNGN6U4.js} +2 -2
- package/dist/{chunk-FKGN4A4E.js → chunk-2U3OLUNJ.js} +2 -2
- package/dist/{chunk-UUJBLG6J.js → chunk-33KUO7CG.js} +2 -2
- package/dist/{chunk-N3SE646F.js → chunk-33XTHFKR.js} +2 -2
- package/dist/{chunk-WXAAURU7.js → chunk-3EDFLQ6A.js} +2 -2
- package/dist/chunk-3ZSJ3PWF.js +16 -0
- package/dist/{chunk-G4UQL4CP.js → chunk-43KC6EQZ.js} +2 -2
- package/dist/{chunk-NQLSSVOB.js → chunk-464PLI5O.js} +2 -2
- package/dist/chunk-46XGSFNI.js +2 -0
- package/dist/{chunk-NN4ZIRPK.js → chunk-47BU5Z4T.js} +2 -2
- package/dist/chunk-4BV4QAZJ.js +5 -0
- package/dist/chunk-4YTUWQ6M.js +18 -0
- package/dist/{chunk-LMFVTUW2.js → chunk-5ML2BNRH.js} +2 -2
- package/dist/{chunk-OP3MTFJR.js → chunk-5YLUDDAF.js} +2 -2
- package/dist/chunk-67QRR5YC.js +6 -0
- package/dist/{chunk-273W2U4Y.js → chunk-6GXYN7YA.js} +2 -2
- package/dist/{chunk-JELJLXEE.js → chunk-6M7RONVB.js} +2 -2
- package/dist/{chunk-MLGTCX56.js → chunk-7FT5Y65S.js} +2 -2
- package/dist/{chunk-F42A3AKG.js → chunk-7KYNAMMH.js} +2 -2
- package/dist/{chunk-VP542C25.js → chunk-7LSVMFX7.js} +2 -2
- package/dist/{chunk-YWB2EBNB.js → chunk-7QHY3H7P.js} +2 -2
- package/dist/{chunk-UQK5CRUK.js → chunk-7RAG65VK.js} +2 -2
- package/dist/{chunk-CYJM7CYF.js → chunk-7SWJEWJF.js} +2 -2
- package/dist/{chunk-47X75ZKH.js → chunk-7VCOXZH3.js} +2 -2
- package/dist/chunk-A2TNXAXO.js +8 -0
- package/dist/{chunk-TYQ76QHQ.js → chunk-A3QXWFBK.js} +2 -2
- package/dist/{chunk-S2GP3CU3.js → chunk-AA4UWRNL.js} +2 -2
- package/dist/{chunk-OBKDTVZ3.js → chunk-ACAM6O5R.js} +2 -2
- package/dist/chunk-AQOFWNQJ.js +1 -0
- package/dist/chunk-AZFUMCQB.js +2 -0
- package/dist/{chunk-IYAOX36F.js → chunk-BDOIKGDI.js} +2 -2
- package/dist/{chunk-7E3TH5ZN.js → chunk-BNXICU42.js} +2 -2
- package/dist/chunk-C5Q44Q5D.js +3 -0
- package/dist/{chunk-OQ2A4G2G.js → chunk-CTF2GDEX.js} +2 -2
- package/dist/chunk-DHEQMPLW.js +2 -0
- package/dist/{chunk-EVOC5I5I.js → chunk-DQBCO2UY.js} +2 -2
- package/dist/{chunk-YLVE3SXZ.js → chunk-DQGSM7RZ.js} +2 -2
- package/dist/chunk-E2LAW7SL.js +30 -0
- package/dist/chunk-E3HYEQO7.js +2 -0
- package/dist/chunk-E4NFOAD4.js +6 -0
- package/dist/chunk-E5HNT4X2.js +3 -0
- package/dist/{chunk-6XHTISLI.js → chunk-ELLMY7XJ.js} +2 -2
- package/dist/chunk-FD3HFKXR.js +5 -0
- package/dist/{chunk-RJHCPSZ7.js → chunk-FIJCV235.js} +2 -2
- package/dist/{chunk-KLVJABXA.js → chunk-FJ5UDTQF.js} +2 -2
- package/dist/{chunk-SHKZ7OVJ.js → chunk-GHKEJTCE.js} +2 -2
- package/dist/{chunk-JERWGHQT.js → chunk-GLZTVKAB.js} +3 -3
- package/dist/{chunk-A43URCQ3.js → chunk-GNC4JVAN.js} +2 -2
- package/dist/chunk-HIB452NU.js +949 -0
- package/dist/{chunk-U5CNPPTZ.js → chunk-HZYDQPNY.js} +2 -2
- package/dist/chunk-IF6FP6B2.js +66 -0
- package/dist/{chunk-CSTYYXKC.js → chunk-JAY7YWS3.js} +2 -2
- package/dist/{chunk-6XFC7PQ5.js → chunk-JHF3E4YM.js} +2 -2
- package/dist/chunk-JORHF5AL.js +108 -0
- package/dist/{chunk-QBYYWGAT.js → chunk-K2WO7XY7.js} +2 -2
- package/dist/chunk-KFZNKUNT.js +2 -0
- package/dist/{chunk-J7VT2CRB.js → chunk-KJ2IIBZN.js} +2 -2
- package/dist/{chunk-336DC5NJ.js → chunk-KKME5ZAI.js} +2 -2
- package/dist/chunk-KSGTULOS.js +9 -0
- package/dist/{chunk-E2ZXPB7J.js → chunk-KXDJAG4N.js} +3 -3
- package/dist/{chunk-Z2LHPIOM.js → chunk-L4S2A7BV.js} +2 -2
- package/dist/chunk-LP3ARJKF.js +8 -0
- package/dist/chunk-LSOR3LQG.js +3 -0
- package/dist/{chunk-FHCTEANE.js → chunk-MLFZP76A.js} +2 -2
- package/dist/{chunk-RBFFD4V2.js → chunk-MNSTUIDD.js} +2 -2
- package/dist/{chunk-3OIKRYU5.js → chunk-MSBDMFER.js} +2 -2
- package/dist/{chunk-7LABSJSR.js → chunk-MZZBAITE.js} +5 -5
- package/dist/{chunk-QQWOFXNW.js → chunk-NE3TZUCI.js} +2 -2
- package/dist/{chunk-JZNLMHWY.js → chunk-NTUMF2X3.js} +2 -2
- package/dist/{chunk-DD5BOU5I.js → chunk-O23I56NA.js} +2 -2
- package/dist/{chunk-YHXBD52M.js → chunk-O3O4XXO6.js} +2 -2
- package/dist/{chunk-FQTPPXNA.js → chunk-OUBAF226.js} +2 -2
- package/dist/chunk-P3UO3EH3.js +2 -0
- package/dist/{chunk-5OC3HWP5.js → chunk-QGGLL3UH.js} +2 -2
- package/dist/chunk-QIQ63BHW.js +16 -0
- package/dist/{chunk-RWRLUZ6U.js → chunk-QJIVBYEK.js} +2 -2
- package/dist/chunk-QOXBSI6G.js +20 -0
- package/dist/{chunk-7Q6VYYCH.js → chunk-QXK6UUSM.js} +2 -2
- package/dist/{chunk-ZTTISZ7J.js → chunk-RA3AYNWP.js} +2 -2
- package/dist/chunk-RJMDJR3A.js +2 -0
- package/dist/{chunk-TFUU5MQQ.js → chunk-RLH5VUMG.js} +2 -2
- package/dist/{chunk-OHWZKLVA.js → chunk-S4S2WOIX.js} +2 -2
- package/dist/{chunk-YTUD45PU.js → chunk-SERUIGV5.js} +2 -2
- package/dist/{chunk-2OXVAGGT.js → chunk-SMQWE25B.js} +2 -2
- package/dist/{chunk-K42M2KWT.js → chunk-TAVELHYR.js} +2 -2
- package/dist/{chunk-MGBJHRFB.js → chunk-TWMJ3Y3G.js} +2 -2
- package/dist/chunk-VAXNI5NE.js +146 -0
- package/dist/chunk-VVY2G5ET.js +2 -0
- package/dist/{chunk-XF3KLXN3.js → chunk-W3DBTGL4.js} +2 -2
- package/dist/{chunk-26X7KCJR.js → chunk-WANA4KAQ.js} +2 -2
- package/dist/chunk-WJL2L6MV.js +60 -0
- package/dist/chunk-WUW7YUAH.js +11 -0
- package/dist/{chunk-PC44K7RF.js → chunk-WWKWUPSU.js} +2 -2
- package/dist/{chunk-2EZSOTSY.js → chunk-WY45BHKQ.js} +2 -2
- package/dist/chunk-X4FR5BZF.js +9 -0
- package/dist/chunk-X6RKPDY7.js +2 -0
- package/dist/{chunk-GK3GRUJX.js → chunk-YLFORA5G.js} +2 -2
- package/dist/{chunk-NBRUH7OE.js → chunk-YTVWB7YJ.js} +2 -2
- package/dist/{chunk-YGQN3XGZ.js → chunk-ZCEJ63SP.js} +2 -2
- package/dist/{chunk-2GSQR6YA.js → chunk-ZJ5CBXK3.js} +2 -2
- package/dist/chunk-ZL2OGDCD.js +2 -0
- package/dist/cli.js +8 -3
- package/dist/command-descriptors-ZW5J4ZEM.js +631 -0
- package/dist/{config-types-BWQ5xPGI.d.ts → config-types-B6MEoRNy.d.ts} +4 -0
- package/dist/{db-B0r1o7Vt.d.ts → db-DYLKr9Wn.d.ts} +1 -1
- package/dist/direct-navigation-42YHQPOI.js +3 -0
- package/dist/{health-CFnlCiTz.d.ts → health-DgxIDXJC.d.ts} +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/postinstall.js +1 -1
- package/dist/queries/affected.d.ts +2 -2
- package/dist/queries/affected.js +1 -1
- package/dist/queries/architecture.d.ts +2 -2
- 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 +2 -2
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.d.ts +2 -2
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +2 -2
- 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 +2 -2
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +3 -3
- 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 +26 -25
- package/dist/reindex.d.ts +7 -3
- package/dist/reindex.js +34 -33
- package/dist/runtime.d.ts +3 -10
- package/dist/runtime.js +3 -3
- package/dist/rust-semantic-session-server.js +1 -1
- package/dist/rust-semantic-session-worker.js +1 -1
- package/dist/rust-semantic-worker.js +1 -1
- package/dist/{scip-cli-DCvnlZCu.d.ts → scip-cli-Cc6c00-a.d.ts} +2 -2
- package/dist/watch-server.js +5 -5
- package/docs/AGENT_GUIDE.md +19 -3
- package/docs/CLI_JSON_OUTPUT.md +86 -1
- package/docs/COMMAND_REFERENCE.md +5 -3
- package/docs/SECURITY_MODEL.md +129 -0
- package/docs/TELEMETRY_RETENTION.md +5 -0
- package/docs/schemas/cli-output-page.schema.json +104 -0
- package/package.json +8 -7
- package/skills/_shared/SKILL.md +4 -2
- package/skills/scip-audit/SKILL.md +3 -2
- package/skills/scip-explore/SKILL.md +1 -1
- package/skills/scip-improve/SKILL.md +1 -1
- package/skills/scip-plan/SKILL.md +1 -1
- package/skills/scip-verify/SKILL.md +7 -2
- package/dist/chunk-24QNP7MN.js +0 -2
- package/dist/chunk-2ZOCHAL2.js +0 -8
- package/dist/chunk-35SQLYCQ.js +0 -2
- package/dist/chunk-4CGVLUDP.js +0 -18
- package/dist/chunk-4RI4BJGT.js +0 -8
- package/dist/chunk-52HQTTPB.js +0 -2
- package/dist/chunk-A63U2W3P.js +0 -3
- package/dist/chunk-ADFSIJP2.js +0 -16
- package/dist/chunk-AOLE4DYM.js +0 -6
- package/dist/chunk-B5MHCHP3.js +0 -107
- package/dist/chunk-DGAGY7RJ.js +0 -60
- package/dist/chunk-DGMCFMPG.js +0 -11
- package/dist/chunk-GA64UPMI.js +0 -6
- package/dist/chunk-HEBAY673.js +0 -2
- package/dist/chunk-HELS7KFF.js +0 -2
- package/dist/chunk-IPDCSB6N.js +0 -6
- package/dist/chunk-JJJCO4QC.js +0 -945
- package/dist/chunk-KP4KBDVF.js +0 -3
- package/dist/chunk-LRTP3DKL.js +0 -3
- package/dist/chunk-P6HBYNBE.js +0 -5
- package/dist/chunk-QHKUY4FW.js +0 -2
- package/dist/chunk-QHRL4LKM.js +0 -2
- package/dist/chunk-UXP636P5.js +0 -144
- package/dist/chunk-VEVBIAOJ.js +0 -16
- package/dist/chunk-VKRQDBW5.js +0 -9
- package/dist/chunk-VOQFGC2W.js +0 -67
- package/dist/chunk-WMXRRBII.js +0 -8
- package/dist/chunk-X3NLZHPA.js +0 -20
- package/dist/chunk-Z5QQPJ3U.js +0 -30
- package/dist/chunk-ZLJLE6LK.js +0 -2
- package/dist/command-descriptors-SJDZ7QGR.js +0 -617
- package/dist/direct-navigation-HTKOZEOM.js +0 -3
package/dist/watch-server.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{$ as Pe,A as ft,Aa as Or,B as vr,Ba as Ae,C as xr,Ca as $r,D as Ir,Da as Gr,E as ce,Ea as Br,F as Rr,Fa as bt,G as Cr,Ga as J,H as wr,Ha as Hr,I as Pr,Ia as Ne,J as Mr,K as Re,Ka as Ur,L as Ce,La as Vr,M as Tr,O as kr,P as mt,Q as Er,T as Dr,X as Fr,_ as Ar,a as er,aa as ht,ba as Nr,c as ve,ca as _r,da as z,f as ir,g as or,h as sr,i as ot,j as ar,k as st,l as dr,m as ur,n as fr,o as mr,pa as Lr,q as dt,r as ut,s as hr,sa as gt,t as gr,v as yr,x as Sr,y as br,ya as jr,z as pt}from"./chunk-UXP636P5.js";import{b as Jt,c as Xt,g as pr,i as ae,m as Y,n as we}from"./chunk-VOQFGC2W.js";import{A as Ee,B as De,C as Fe,a as Qt,b as se,c as Zt,g as rr,h as nr,i as D,j as F,k as at,l as cr,m as ct,n as lr,o as K,p as lt,q as Ie,s as yt,t as Wr,u as Me,v as St,w as qr,y as Te,z as ke}from"./chunk-VKRQDBW5.js";import{a as xe,c as tr,d as it,e as O}from"./chunk-HGFDYOVB.js";import{a as T}from"./chunk-APMMR5Y2.js";import P from"process";import{rmSync as Si}from"fs";import{resolve as zs}from"path";import{pathToFileURL as Js}from"url";import{existsSync as Ii,readFileSync as Ri}from"fs";import{isAbsolute as da,join as Ci,relative as ua,resolve as pa}from"path";var W=1,X=2,xi="./node_modules/scip-query/docs/schemas/project-config.schema.json";function Kr(r){let e=r;if(typeof r=="string")try{e=JSON.parse(r)}catch(s){return{kind:"malformed",reason:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}}if(!Qt(e))return{kind:"malformed",reason:"project config must be a JSON object"};let t=e.schemaVersion;if(t!==void 0&&!Number.isInteger(t))return{kind:"malformed",reason:"schemaVersion must be an integer"};let n=t===void 0?W:t;if(n!==W&&n!==X)return{kind:"unsupported",schemaVersion:n,direction:n<W?"older":"future"};let i=e.$schema;if(i!==void 0&&(typeof i!="string"||i.trim()===""))return{kind:"malformed",reason:"$schema must be a non-empty string when present"};let o=Yr(e),a=n!==X||typeof e.$schema!="string";return n===W?{kind:"legacy",sourceVersion:W,config:o,needsMigration:a}:{kind:"supported",sourceVersion:X,config:o,needsMigration:a}}function Yr(r){let e=r,{$schema:t,schemaVersion:n,...i}=e;return{$schema:typeof t=="string"&&t.trim()!==""?t:xi,schemaVersion:X,...i}}var _e=".scipquery.json",wi=250,Pi=0,Mi=10*6e4,Ti={enabled:!1,debounceMs:wi,cooldownMs:Pi,gitPollMs:2e3,idleTimeoutMs:Mi,autoRefresh:!0,ignore:[]};var ha=new Set(er);function Q(r){let e=Ci(r,_e);if(!Ii(e))return{};let t;try{t=Ri(e,"utf-8")}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`unable to read ${_e} at ${e}: ${i}`,{cause:n})}return ki(Kr(t),e,"read").config}function Le(r){return{...Ti,...r.watch}}function ki(r,e,t){if(r.kind==="legacy"||r.kind==="supported")return r;if(r.kind==="malformed"){let i=t==="read"?`invalid ${_e} at ${e}: ${r.reason}`:`Cannot update ${e}: the latest project config is ${r.reason}.`;throw new Error(`${i} The file was left untouched.`)}let n=t==="read"?`invalid ${_e} at ${e}`:`Cannot update ${e}: the latest project config is invalid`;throw new Error(`${n} (unsupported ${r.direction} schemaVersion ${r.schemaVersion}; this scip-query reads legacy v${W} and current v${X}). Upgrade scip-query before retrying; the file was left untouched.`)}import{existsSync as zr,readFileSync as Ei}from"fs";function vt(r,e,t){let n=new Date().toISOString();if(!zr(t.dbPath))return{state:"missing",checkedAt:n,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!zr(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=ve(Ei(t.metaPath,"utf-8"));if(i.kind==="unsupported")return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Reindex metadata version ${i.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(i.kind==="malformed")return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Could not decode reindex metadata: ${i.reason}`,remedy:"Run: scip-query reindex"};let o=i.metadata,a=e.languages??Dr(r),s=Di(r,a,e),c=[...o.indexedLanguages??[]].sort(),l=i.capabilities.publishableGeneration&&JSON.stringify(o.fingerprint)===JSON.stringify(s)&&JSON.stringify(c)===JSON.stringify(s.languages),d=Lr(t.dbPath,t.metaPath),u=d.state==="invalid"||d.state==="drifted",p=l&&!u;return{state:p?"fresh":"stale",checkedAt:n,metaPath:t.metaPath,updatedAt:o.updatedAt,lastRefresh:o.lastRefresh,reason:u?`SQLite generation requires repair: ${d.reason}`:l?"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 Di(r,e,t){return pr(r,e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{statSync as Fi}from"fs";import{basename as Ai,isAbsolute as Ni,join as _i,relative as Li}from"path";import{watch as ji}from"chokidar";import Oi from"ignore";var je=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onError;reindexRunner;subscriptionFactory;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;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=Le(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.onReindexError=e.onReindexError??(()=>{}),this.onRefreshSuppressed=e.onRefreshSuppressed??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.clock=e.clock??qi,this.reindexRunner=e.reindexRunner??Vi(),this.subscriptionFactory=e.subscriptionFactory??$i,this.gitignoreFilter=we(e.projectRoot),this.extraIgnore=Oi(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,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(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let e=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer();let t=this.activeOperation;return t&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"}),this.stopPromise=this.finishStop(e,t).finally(()=>{this.stopInProgress=!1}),this.stopPromise}requestRefresh(e,t={}){if(!this.stopped){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=Xr(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(e=!1){let t=this.subscriptionFactory(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||!Ki(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")||Ai(t).startsWith(Fr)||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=Ni(e)?e:_i(this.projectRoot,e);return Li(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=Xr(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=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let o=this.watchConfig.cooldownMs-e;this.dirty=!0;let a=this.wallNow()+o;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},o);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let n=this.wallNow();this.setStatus({state:"indexing",startedAt:n});let i=this.reindexRunner.start(this.reindexRequest(t));this.activeOperation=i,i.completion.then(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let a=!1;try{a=this.onReindexComplete(o,t)===!0}catch(s){this.onError(s instanceof Error?s:new Error(String(s)))}if(this.dirty&&!this.stopped){if(a){let c=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(c),this.setStatus({state:"idle"});return}let s=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:s,dirty:!0}),this.cooldownTimer=this.clock.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(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let a=o instanceof Error?o:new Error(String(o));this.onReindexError(a,t),this.onError(a),this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===i&&(this.activeOperation=null)})}async finishStop(e,t){let n=[],i=t?t.cancel():null,o=await Promise.allSettled(e.map(a=>Promise.resolve().then(()=>a.close())));for(let a of o)a.status==="rejected"&&n.push(`watch subscription close failed: ${String(a.reason)}`);if(i)try{let a=await i;a.state==="degraded"&&n.push(a.reason)}catch(a){n.push(`reindex cancellation failed: ${a instanceof Error?a.message:String(a)}`)}return n.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:n.join("; ")}),{state:"degraded",reasons:n}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}reindexRequest(e){return{projectRoot:this.projectRoot,config:this.config,languages:this.languages,pnpmWorkspaces:this.pnpmWorkspaces,typescriptProjectMode:this.typescriptProjectMode,typescriptProjects:this.typescriptProjects,clojureConfigPath:this.clojureConfigPath,indexerConcurrency:this.indexerConcurrency,trigger:e}}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=this.clock.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=ot(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=ar(this.projectRoot,e),n={head:ot(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=Fi(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function Wi(r){let{projectRoot:e,config:t,languages:n,pnpmWorkspaces:i,typescriptProjectMode:o,typescriptProjects:a,clojureConfigPath:s,indexerConcurrency:c,trigger:l}=r,d=Q(e),u=Object.keys(d).length>0?d:t,p=z(e,u),y=u.indexer?.typescript,f=u.indexer?.clojure;return{workerPath:new URL("./reindex-worker.js",import.meta.url).pathname,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:e,SCIP_REINDEX_OUTPUT_SCIP:p.indexPath,SCIP_REINDEX_OUTPUT_DB:p.dbPath,SCIP_REINDEX_LANGUAGES:(u.languages??n)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(u.indexerConcurrency??c??""),SCIP_REINDEX_PNPM_WORKSPACES:y?.pnpmWorkspaces??i?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:y?.projectMode??o,projects:y?.projects??a??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:f?.configPath??s??"",SCIP_REINDEX_TRIGGER_KIND:l.kind,SCIP_REINDEX_TRIGGER_DETAIL:l.detail??"",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1"}}}var qi={now:T,wallNow:()=>Date.now(),setTimeout:(r,e)=>setTimeout(r,e),clearTimeout:r=>clearTimeout(r),setInterval:(r,e)=>setInterval(r,e),clearInterval:r=>clearInterval(r)},$i=(r,e)=>ji(r,e),Gi=15*6e4,Bi=1e3,Hi=64*1024;function Ui(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function Jr(r,e){let t=r instanceof Error?r.message:String(r),n=e.stderrTail.trim()||e.stdoutTail.trim();return n?`${t}
|
|
2
|
-
${n}`:t}function Vi(r={}){let e=r.timeoutMs??Gi,t=r.terminationGraceMs??Bi,n=r.maxOutputBytes??Hi,i=r.resolveLaunch??Wi;return{start(o){let a=i(o),s=new AbortController,c=Ui(),l=!1,d=Vr({command:process.execPath,args:[...process.execArgv,a.workerPath],label:"watch reindex worker",env:a.env,timeoutMs:e,terminationGraceMs:t,maxStdoutBytes:n,maxStderrBytes:n,outputLimitBehavior:"truncate-tail",signal:s.signal,detached:!0}).then(u=>{if(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated},u.status!==0)throw new Error(Jr(new Error(`Reindex worker exited with ${u.signal?`signal ${u.signal}`:`code ${u.status}`}`),c));return u.durationMs}).catch(u=>{throw u instanceof Ur&&(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated}),new Error(Jr(u,c),{cause:u})}).finally(()=>{l=!0});return{completion:d,async cancel(){l||s.abort();try{await d}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function Xr(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 Ki(r){return r instanceof Error&&"code"in r&&r.code==="EMFILE"||String(r).includes("EMFILE: too many open files")}import{existsSync as nn,statSync as Qi}from"fs";import{join as Zi}from"path";import{join as Yi}from"path";var Z=3,zi=2,Ji="typescript-semantic";function Zr(r){let e=Yi(r,Ji),t=Wr(e);return{...t,requestDir:t.legacyRequestDir}}function xt(r){return fr(r)}function en(r){let e=JSON.parse(r),t=e.protocolVersion,n=t===zi;if(!n&&t!==Z||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||!Number.isFinite(e.deadlineAtMs)||e.profileEnvironment!==void 0&&!Zt(e.profileEnvironment)||!e.request||!Xi(e.request)||!n&&(e.mailboxVersion!==yt||typeof e.operationKey!="string"||!/^[a-f0-9]{64}$/.test(e.operationKey)||e.id!==qr(e.operationKey)||typeof e.clientId!="string"||!e.clientId||typeof e.enqueuedAtMs!="number"||!Number.isFinite(e.enqueuedAtMs)||e.deadlineAtMs<e.enqueuedAtMs))throw new Error("TypeScript semantic service received an invalid mailbox request.");if(!n){let o=e,a=St("typescript-semantic-v3",{generation:o.generation,profileEnvironment:o.profileEnvironment,request:o.request});if(o.operationKey!==a)throw new Error("TypeScript semantic service received a mismatched mailbox operation identity.");return o}let i=St("typescript-semantic-v2",{id:e.id,generation:e.generation,request:e.request});return{protocolVersion:Z,mailboxVersion:yt,id:e.id,operationKey:i,clientId:"legacy-v2",enqueuedAtMs:e.deadlineAtMs,deadlineAtMs:e.deadlineAtMs,generation:e.generation,...e.profileEnvironment?{profileEnvironment:e.profileEnvironment}:{},request:e.request}}function Xi(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 vr(e.files)!==null;case"references":return Qr(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return Qr(e.definitions);case"signature":return tn(e.definition);default:return!1}}function Qr(r){return Array.isArray(r)&&r.every(tn)}function tn(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 eo(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var rn;function to(r=eo(),e=void 0){if(e===void 0&&rn?.projectRoot===r)return rn;let t=Q(r),n=z(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(nn(n.dbPath))return{projectRoot:r,config:t,paths:n,dbPath:n.dbPath,dbPathSource:"configured",gitContext:e};let o=Zi(r,"index.db");return{projectRoot:r,config:t,paths:n,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:ro(o,n.dbPath),gitContext:e}}function on(r,e={}){let{config:t,paths:n,dbPath:i,dbPathSource:o,rootFallbackWarning:a,gitContext:s}=to(r);if(!nn(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:gt(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=we(r);return new mr(c,l)}function ro(r,e){let t="unknown time";try{t=Qi(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{randomUUID as rs}from"crypto";import{resolve as Dn}from"path";import{performance as S}from"perf_hooks";function Oe(r){return{forFile(e,t){return sn(r,e,t)},forFiles(e,t){let n=new Map;for(let i of e)n.set(i,sn(r,i,t));return n}}}function sn(r,e,t){let n={file:e},i=t.facts||t.identifiers;if(t.text&&(n.text=xr(r,e)),t.lines&&(n.lines=Ir(r,e)),t.ast&&(n.ast=Rr(r,e)),t.imports&&(n.imports=Mr(r,e)),t.reexports&&(n.reexports=Pr(r,e)),i){let o=Cr(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 no={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function We(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=io(i);return{scheme:t,manager:n,packageName:o,version:a,descriptors:c,raw:r}}function ee(r){let e=We(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 io(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||an(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&&!an(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=no[i];o&&e.push({name:n,suffix:o}),t+=1}}return e}function an(r){return r==="/"||r==="#"||r==="."||r==="("||r==="["||r===":"||r==="!"}function q(r){let e=We(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 $(r){let e=We(r);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function cn(r){let e=$(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 oo(r,e={}){if(ee(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 ln(r,e,t={}){let n=new Map;for(let o of e)r.length>0&&!oo(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 so=ae("file-definitions",{clearGroups:["definition-catalog"]}),yc=ae("file-function-like-definitions",{clearGroups:["definition-catalog"]});function G(r,e,t={}){return t.includeClassMemberFallbacks?dn(r,e,void 0,{includeClassMemberFallbacks:!0}):so.get(r,e,()=>{let n=ao(r,e);if(n)return n;let i=dn(r,e),o=ut(r),a=Oe(r).forFile(e,{text:!0}).text;return o&&a&&pn.write(r,e,dt(r,e,a),{projectFingerprint:o,definitions:i.map(s=>({...s}))}),i})}var pn=gr({kind:"file-definitions",invalidation:yr("file-definitions"),serialize:co,deserialize:lo});function ao(r,e){let t=ut(r);if(!t)return null;let n=Oe(r).forFile(e,{text:!0}).text;if(!n)return null;let i=pn.read(r,e,dt(r,e,n));return i?uo(i,t,e):null}function co(r){return JSON.stringify(r)}function lo(r){try{let e=JSON.parse(r);return!ft(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function uo(r,e,t){if(r.projectFingerprint!==e)return null;let n=[];for(let i of r.definitions){let o=po(i,t);if(!o)return null;n.push(o)}return n}function po(r,e){return!ft(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 dn(r,e,t,n={}){let i=ln(fo(r,e),mo(r,e),{sort:!0,includeClassMemberFallbacks:n.includeClassMemberFallbacks}).map(ho);return t&&(i=i.filter(t)),yo(r,e,i)}function fo(r,e){return r.all(`SELECT
|
|
1
|
+
import{B as Mr,Ba as Vr,C as Tr,Ca as Ne,D as kr,Da as zr,E as ht,Ea as Jr,F as gt,Fa as Xr,G as Er,Ga as It,H as Dr,Ha as X,I as Fr,Ia as Qr,J as le,Ja as Le,K as Ar,L as _r,La as Zr,M as Nr,Ma as en,N as Lr,Na as tn,O as jr,P as we,Q as Pe,R as Or,T as Wr,U as yt,V as qr,Y as $r,a as ar,aa as Gr,c as Ie,da as Br,ea as Te,f as ot,g as lr,h as dr,i as K,k as st,l as fr,m as mr,n as hr,o as at,p as gr,q as ct,qa as Ur,r as br,s as vr,t as Rr,ta as St,u as Cr,w as ft,x as mt,y as wr,z as Pr,za as Hr}from"./chunk-VAXNI5NE.js";import{b as ce,f as J,g as Me}from"./chunk-IF6FP6B2.js";import{b as nr,c as ir,j as xr,m as ut,o as Ir}from"./chunk-C5Q44Q5D.js";import{A as Fe,B as Ae,C as xt,D as _e,a as or,b as ae,c as sr,g as ur,h as pr,i as F,j as A,k as lt,l as yr,m as dt,n as Sr,o as z,p as pt,q as Ce,s as bt,t as Yr,u as ke,v as vt,w as Kr,y as Ee,z as De}from"./chunk-X4FR5BZF.js";import{a as Re,c as cr,d as it,e as W}from"./chunk-HGFDYOVB.js";import{a as T}from"./chunk-APMMR5Y2.js";import{a as tr,g as rr,h as D}from"./chunk-46XGSFNI.js";import P from"process";import{rmSync as Ei}from"fs";import{resolve as na}from"path";import{pathToFileURL as ia}from"url";import{existsSync as Ai}from"fs";import{isAbsolute as xa,join as _i,relative as Ia,resolve as Ra}from"path";var $=1,Q=2,Fi="./node_modules/scip-query/docs/schemas/project-config.schema.json";function rn(r){let e=r;if(typeof r=="string")try{e=JSON.parse(r)}catch(a){return{kind:"malformed",reason:`invalid JSON: ${a instanceof Error?a.message:String(a)}`}}if(!or(e))return{kind:"malformed",reason:"project config must be a JSON object"};let t=e.schemaVersion;if(t!==void 0&&!Number.isInteger(t))return{kind:"malformed",reason:"schemaVersion must be an integer"};let n=t===void 0?$:t;if(n!==$&&n!==Q)return{kind:"unsupported",schemaVersion:n,direction:n<$?"older":"future"};let i=e.$schema;if(i!==void 0&&(typeof i!="string"||i.trim()===""))return{kind:"malformed",reason:"$schema must be a non-empty string when present"};let o=nn(e),s=n!==Q||typeof e.$schema!="string";return n===$?{kind:"legacy",sourceVersion:$,config:o,needsMigration:s}:{kind:"supported",sourceVersion:Q,config:o,needsMigration:s}}function nn(r){let e=r,{$schema:t,schemaVersion:n,...i}=e;return{$schema:typeof t=="string"&&t.trim()!==""?t:Fi,schemaVersion:Q,...i}}var je=".scipquery.json",Ni=250,Li=0,ji=10*6e4,Oi={enabled:!1,debounceMs:Ni,cooldownMs:Li,gitPollMs:2e3,idleTimeoutMs:ji,autoRefresh:!0,ignore:[]};var Ma=new Set(ar);function Z(r){let e=_i(r,je);if(!Ai(e))return{};let t;try{t=rr(e,{maxBytes:tr,inputKind:"scip-query project config"})}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`unable to read ${je} at ${e}: ${i}`,{cause:n})}return Wi(rn(t),e,"read").config}function Oe(r){return{...Oi,...r.watch}}function Wi(r,e,t){if(r.kind==="legacy"||r.kind==="supported")return r;if(r.kind==="malformed"){let i=t==="read"?`invalid ${je} at ${e}: ${r.reason}`:`Cannot update ${e}: the latest project config is ${r.reason}.`;throw new Error(`${i} The file was left untouched.`)}let n=t==="read"?`invalid ${je} at ${e}`:`Cannot update ${e}: the latest project config is invalid`;throw new Error(`${n} (unsupported ${r.direction} schemaVersion ${r.schemaVersion}; this scip-query reads legacy v${$} and current v${Q}). Upgrade scip-query before retrying; the file was left untouched.`)}import{existsSync as on}from"fs";function Rt(r,e,t){let n=new Date().toISOString();if(!on(t.dbPath))return{state:"missing",checkedAt:n,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!on(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=Ie(D(t.metaPath,"reindex metadata"));if(i.kind==="unsupported")return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Reindex metadata version ${i.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(i.kind==="malformed")return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Could not decode reindex metadata: ${i.reason}`,remedy:"Run: scip-query reindex"};let o=i.metadata,s=e.languages??$r(r),a=qi(r,s,e),c=[...o.indexedLanguages??[]].sort(),l=i.capabilities.publishableGeneration&&JSON.stringify(o.fingerprint)===JSON.stringify(a)&&JSON.stringify(c)===JSON.stringify(a.languages),d=Ur(t.dbPath,t.metaPath),u=d.state==="invalid"||d.state==="drifted",p=l&&!u;return{state:p?"fresh":"stale",checkedAt:n,metaPath:t.metaPath,updatedAt:o.updatedAt,lastRefresh:o.lastRefresh,reason:u?`SQLite generation requires repair: ${d.reason}`:l?"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 qi(r,e,t){return Ir(r,e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{statSync as $i}from"fs";import{basename as Gi,isAbsolute as Bi,join as Ui,relative as Hi}from"path";import{watch as Vi}from"chokidar";import Yi from"ignore";var We=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onError;reindexRunner;subscriptionFactory;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;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=Oe(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.onReindexError=e.onReindexError??(()=>{}),this.onRefreshSuppressed=e.onRefreshSuppressed??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.clock=e.clock??zi,this.reindexRunner=e.reindexRunner??to(),this.subscriptionFactory=e.subscriptionFactory??Ji,this.gitignoreFilter=Me(e.projectRoot),this.extraIgnore=Yi(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,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(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let e=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer();let t=this.activeOperation;return t&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"}),this.stopPromise=this.finishStop(e,t).finally(()=>{this.stopInProgress=!1}),this.stopPromise}requestRefresh(e,t={}){if(!this.stopped){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=an(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(e=!1){let t=this.subscriptionFactory(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||!ro(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")||Gi(t).startsWith(Gr)||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=Bi(e)?e:Ui(this.projectRoot,e);return Hi(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=an(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=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let o=this.watchConfig.cooldownMs-e;this.dirty=!0;let s=this.wallNow()+o;this.setStatus({state:"cooldown",until:s,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},o);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let n=this.wallNow();this.setStatus({state:"indexing",startedAt:n});let i=this.reindexRunner.start(this.reindexRequest(t));this.activeOperation=i,i.completion.then(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let s=!1;try{s=this.onReindexComplete(o,t)===!0}catch(a){this.onError(a instanceof Error?a:new Error(String(a)))}if(this.dirty&&!this.stopped){if(s){let c=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(c),this.setStatus({state:"idle"});return}let a=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=this.clock.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(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let s=o instanceof Error?o:new Error(String(o));this.onReindexError(s,t),this.onError(s),this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===i&&(this.activeOperation=null)})}async finishStop(e,t){let n=[],i=t?t.cancel():null,o=await Promise.allSettled(e.map(s=>Promise.resolve().then(()=>s.close())));for(let s of o)s.status==="rejected"&&n.push(`watch subscription close failed: ${String(s.reason)}`);if(i)try{let s=await i;s.state==="degraded"&&n.push(s.reason)}catch(s){n.push(`reindex cancellation failed: ${s instanceof Error?s.message:String(s)}`)}return n.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:n.join("; ")}),{state:"degraded",reasons:n}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}reindexRequest(e){return{projectRoot:this.projectRoot,config:this.config,languages:this.languages,pnpmWorkspaces:this.pnpmWorkspaces,typescriptProjectMode:this.typescriptProjectMode,typescriptProjects:this.typescriptProjects,clojureConfigPath:this.clojureConfigPath,indexerConcurrency:this.indexerConcurrency,trigger:e}}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=this.clock.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=at(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=gr(this.projectRoot,e),n={head:at(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=$i(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function Ki(r){let{projectRoot:e,config:t,languages:n,pnpmWorkspaces:i,typescriptProjectMode:o,typescriptProjects:s,clojureConfigPath:a,indexerConcurrency:c,trigger:l}=r,d=Z(e),u=Object.keys(d).length>0?d:t,p=K(e,u),y=u.indexer?.typescript,f=u.indexer?.clojure;return{workerPath:new URL("./reindex-worker.js",import.meta.url).pathname,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:e,SCIP_REINDEX_OUTPUT_SCIP:p.indexPath,SCIP_REINDEX_OUTPUT_DB:p.dbPath,SCIP_REINDEX_LANGUAGES:(u.languages??n)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(u.indexerConcurrency??c??""),SCIP_REINDEX_PNPM_WORKSPACES:y?.pnpmWorkspaces??i?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:y?.projectMode??o,projects:y?.projects??s??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:f?.configPath??a??"",SCIP_REINDEX_TRIGGER_KIND:l.kind,SCIP_REINDEX_TRIGGER_DETAIL:l.detail??"",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1"}}}var zi={now:T,wallNow:()=>Date.now(),setTimeout:(r,e)=>setTimeout(r,e),clearTimeout:r=>clearTimeout(r),setInterval:(r,e)=>setInterval(r,e),clearInterval:r=>clearInterval(r)},Ji=(r,e)=>Vi(r,e),Xi=15*6e4,Qi=1e3,Zi=64*1024;function eo(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function sn(r,e){let t=r instanceof Error?r.message:String(r),n=e.stderrTail.trim()||e.stdoutTail.trim();return n?`${t}
|
|
2
|
+
${n}`:t}function to(r={}){let e=r.timeoutMs??Xi,t=r.terminationGraceMs??Qi,n=r.maxOutputBytes??Zi,i=r.resolveLaunch??Ki;return{start(o){let s=i(o),a=new AbortController,c=eo(),l=!1,d=en({command:process.execPath,args:[...process.execArgv,s.workerPath],label:"watch reindex worker",env:s.env,timeoutMs:e,terminationGraceMs:t,maxStdoutBytes:n,maxStderrBytes:n,outputLimitBehavior:"truncate-tail",signal:a.signal,detached:!0}).then(u=>{if(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated},u.status!==0)throw new Error(sn(new Error(`Reindex worker exited with ${u.signal?`signal ${u.signal}`:`code ${u.status}`}`),c));return u.durationMs}).catch(u=>{throw u instanceof Zr&&(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated}),new Error(sn(u,c),{cause:u})}).finally(()=>{l=!0});return{completion:d,async cancel(){l||a.abort();try{await d}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function an(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 ro(r){return r instanceof Error&&"code"in r&&r.code==="EMFILE"||String(r).includes("EMFILE: too many open files")}import{existsSync as fn,statSync as ao}from"fs";import{join as co}from"path";import{join as no}from"path";var ee=3,io=2,oo="typescript-semantic";function ln(r){let e=no(r,oo),t=Yr(e);return{...t,requestDir:t.legacyRequestDir}}function Ct(r){return Rr(r)}function dn(r){let e=JSON.parse(r),t=e.protocolVersion,n=t===io;if(!n&&t!==ee||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||!Number.isFinite(e.deadlineAtMs)||e.profileEnvironment!==void 0&&!sr(e.profileEnvironment)||!e.request||!so(e.request)||!n&&(e.mailboxVersion!==bt||typeof e.operationKey!="string"||!/^[a-f0-9]{64}$/.test(e.operationKey)||e.id!==Kr(e.operationKey)||typeof e.clientId!="string"||!e.clientId||typeof e.enqueuedAtMs!="number"||!Number.isFinite(e.enqueuedAtMs)||e.deadlineAtMs<e.enqueuedAtMs))throw new Error("TypeScript semantic service received an invalid mailbox request.");if(!n){let o=e,s=vt("typescript-semantic-v3",{generation:o.generation,profileEnvironment:o.profileEnvironment,request:o.request});if(o.operationKey!==s)throw new Error("TypeScript semantic service received a mismatched mailbox operation identity.");return o}let i=vt("typescript-semantic-v2",{id:e.id,generation:e.generation,request:e.request});return{protocolVersion:ee,mailboxVersion:bt,id:e.id,operationKey:i,clientId:"legacy-v2",enqueuedAtMs:e.deadlineAtMs,deadlineAtMs:e.deadlineAtMs,generation:e.generation,...e.profileEnvironment?{profileEnvironment:e.profileEnvironment}:{},request:e.request}}function so(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 Er(e.files)!==null;case"references":return cn(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return cn(e.definitions);case"signature":return un(e.definition);default:return!1}}function cn(r){return Array.isArray(r)&&r.every(un)}function un(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 lo(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var pn;function uo(r=lo(),e=void 0){if(e===void 0&&pn?.projectRoot===r)return pn;let t=Z(r),n=K(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(fn(n.dbPath))return{projectRoot:r,config:t,paths:n,dbPath:n.dbPath,dbPathSource:"configured",gitContext:e};let o=co(r,"index.db");return{projectRoot:r,config:t,paths:n,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:po(o,n.dbPath),gitContext:e}}function mn(r,e={}){let{config:t,paths:n,dbPath:i,dbPathSource:o,rootFallbackWarning:s,gitContext:a}=uo(r);if(!fn(i))throw new Error("No index.db found. Run: scip-query reindex");e.warnOnRootFallback&&o==="root-fallback"&&s&&console.error(s);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:r,sharedEvidenceDbPath:St(r,t,a),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=Me(r);return new Cr(c,l)}function po(r,e){let t="unknown time";try{t=ao(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{randomUUID as ps}from"crypto";import{resolve as Bn}from"path";import{performance as S}from"perf_hooks";function qe(r){return{forFile(e,t){return hn(r,e,t)},forFiles(e,t){let n=new Map;for(let i of e)n.set(i,hn(r,i,t));return n}}}function hn(r,e,t){let n={file:e},i=t.facts||t.identifiers;if(t.text&&(n.text=Dr(r,e)),t.lines&&(n.lines=Fr(r,e)),t.ast&&(n.ast=Ar(r,e)),t.imports&&(n.imports=jr(r,e)),t.reexports&&(n.reexports=Lr(r,e)),i){let o=_r(r,e),s=o.facts;t.facts&&(n.facts=s),o.unavailable&&(n.sourceFactsUnavailable=o.unavailable),t.identifiers&&s&&(n.identifiers=s.fileIdentifiers,n.identifierLineMap=s.identifierLineMap)}return n}var fo={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function $e(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 s,a=i.indexOf(" ");a===-1?(s=i,i=""):(s=i.slice(0,a),i=i.slice(a+1));let c=mo(i);return{scheme:t,manager:n,packageName:o,version:s,descriptors:c,raw:r}}function te(r){let e=$e(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 mo(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||gn(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&&!gn(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=fo[i];o&&e.push({name:n,suffix:o}),t+=1}}return e}function gn(r){return r==="/"||r==="#"||r==="."||r==="("||r==="["||r===":"||r==="!"}function G(r){let e=$e(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 B(r){let e=$e(r);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function yn(r){let e=B(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 ho(r,e={}){if(te(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 Sn(r,e,t={}){let n=new Map;for(let o of e)r.length>0&&!ho(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,s)=>o.start_line-s.start_line||o.end_line-s.end_line||o.symbol.localeCompare(s.symbol)):i}var go=ce("file-definitions",{clearGroups:["definition-catalog"]}),Ec=ce("file-function-like-definitions",{clearGroups:["definition-catalog"]});function U(r,e,t={}){return t.includeClassMemberFallbacks?bn(r,e,void 0,{includeClassMemberFallbacks:!0}):go.get(r,e,()=>{let n=yo(r,e);if(n)return n;let i=bn(r,e),o=mt(r),s=qe(r).forFile(e,{text:!0}).text;return o&&s&&xn.write(r,e,ft(r,e,s),{projectFingerprint:o,definitions:i.map(a=>({...a}))}),i})}var xn=Pr({kind:"file-definitions",invalidation:Mr("file-definitions"),serialize:So,deserialize:bo});function yo(r,e){let t=mt(r);if(!t)return null;let n=qe(r).forFile(e,{text:!0}).text;if(!n)return null;let i=xn.read(r,e,ft(r,e,n));return i?vo(i,t,e):null}function So(r){return JSON.stringify(r)}function bo(r){try{let e=JSON.parse(r);return!gt(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function vo(r,e,t){if(r.projectFingerprint!==e)return null;let n=[];for(let i of r.definitions){let o=xo(i,t);if(!o)return null;n.push(o)}return n}function xo(r,e){return!gt(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 bn(r,e,t,n={}){let i=Sn(Io(r,e),Ro(r,e),{sort:!0,includeClassMemberFallbacks:n.includeClassMemberFallbacks}).map(Co);return t&&(i=i.filter(t)),Po(r,e,i)}function Io(r,e){return r.all(`SELECT
|
|
3
3
|
gs.id,
|
|
4
4
|
gs.symbol,
|
|
5
5
|
der.document_id,
|
|
@@ -17,7 +17,7 @@ ${n}`:t}function Vi(r={}){let e=r.timeoutMs??Gi,t=r.terminationGraceMs??Bi,n=r.m
|
|
|
17
17
|
JOIN documents d ON der.document_id = d.id
|
|
18
18
|
WHERE d.relative_path = ?
|
|
19
19
|
${r.symbolNoiseFor("gs")}
|
|
20
|
-
ORDER BY der.start_line, der.end_line`,e)}function
|
|
20
|
+
ORDER BY der.start_line, der.end_line`,e)}function Ro(r,e){return r.all(`SELECT
|
|
21
21
|
gs.id,
|
|
22
22
|
gs.symbol,
|
|
23
23
|
c.document_id,
|
|
@@ -38,6 +38,6 @@ ${n}`:t}function Vi(r={}){let e=r.timeoutMs??Gi,t=r.terminationGraceMs??Bi,n=r.m
|
|
|
38
38
|
AND m.role = 1
|
|
39
39
|
${r.symbolNoiseFor("gs")}
|
|
40
40
|
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
41
|
-
ORDER BY start_line, end_line`,e)}function
|
|
42
|
-
`),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 te(c.filter(l=>re(t,mn.join(t,l.file))===e))}function It(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 Rt(r,e){return r.getLineAndColumnAtPos(e.getStart()).line-1}function te(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 re(r,e){let t=mn.relative(r||process.cwd(),e).replace(/\\/g,"/");return!t||t.startsWith("..")?null:t}function Sn(r,e,t,n){let i=_o(e,n);return i.size===0?new Map:Lo(r,t,i)}function _o(r,e){let t=new Map;for(let n of G(r,e)){let i=q(n.symbol)??n.leaf;if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push(n)}return t}function Lo(r,e,t){let n=new Map,i=new Map;return e.forEachDescendant(o=>{for(let a of jo(r,o)){let s=t.get(a);if(!s)continue;let c=Rt(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 jo(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 Oo=ae("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function bn(r,e,t,n){let i=Pt(r,e),o=Ct(i.get(n)??[],t);if(o)return o;let a=[];for(let s of i.values())for(let c of s)((c.leaf||q(c.symbol)||"").includes(n)||c.symbol.includes(n))&&a.push(c);return Ct(a,t)}function wt(r,e,t,n){return Ct(Pt(r,e).get(n)??[],t)}function vn(r,e){let t=new Map;for(let[n,i]of Pt(r,e)){let o=i[0];o&&t.set(n,o)}return t}function Pt(r,e){return Oo.get(r,e,()=>{let t=new Map;for(let n of G(r,e)){let i=n.leaf||q(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 Ct(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 Mt from"path";function xn(r,e){let t=new Map,n=null,i=null,o=()=>(i??=Y(r,{extensions:Re}),i),a=()=>(n??=O("typescript.source-file-index",()=>Wo(r.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),n),s=c=>Ce(c)?A(t,c,()=>{let l=le(Mt.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(le(p.getFilePath()),p)),p)return{project:d,sourceFile:p}}return null}):null;return{sourceFile:c=>s(c)?.sourceFile??null,sourceFileMatch:s,indexedTypeScriptLikeDocuments:o}}function Wo(r,e,t){let n=e.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[le(o.getFilePath()),o]))}));for(let i of t){let o=le(Mt.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(le(s.getFilePath()),s);break}}}return n}function le(r){return Mt.resolve(r)}function Tt(r,e){for(let t of r)if(e===t.name||e.startsWith(`${t.name}/`))return t.name;return null}function In(r){let e=`${r.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as de,readFileSync as qo}from"fs";import x from"path";var kt=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Et(r,e){let n=e?x.dirname(x.join(r,e)):r,i=x.resolve(r);for(;n.startsWith(i);){for(let a of kt){let s=x.join(n,a);if(de(s))return s}let o=x.dirname(n);if(o===n)break;n=o}for(let o of kt){let a=x.join(r,o);if(de(a))return a}return null}function Rn(r){let e=r.config.projectRoot,t=new Set($o(e,r.config.semantic?.typescript?.tsconfigs)),n=Y(r,{includeIgnored:!1,extensions:Re});for(let i of n){let o=Et(e,i);o&&t.add(x.resolve(o))}if(t.size===0){let i=Et(e);i&&t.add(x.resolve(i))}return[...t].filter(i=>!Cn(e,i)).sort((i,o)=>i.localeCompare(o))}function $o(r,e=[]){let t=new Set;for(let n of e){let i=x.isAbsolute(n)?n:x.join(r,n);de(i)&&t.add(x.resolve(i))}for(let n of Go(r))for(let i of kt){let o=x.join(n,i);de(o)&&t.add(x.resolve(o))}if(t.size===0){let n=Et(r);n&&t.add(x.resolve(n))}return[...t].filter(n=>!Cn(r,n)).sort((n,i)=>n.localeCompare(i))}function Go(r){let e=x.join(r,"package.json");if(!de(e))return[];let t;try{t=JSON.parse(qo(e,"utf8"))}catch{return[]}return(Array.isArray(t.workspaces)?t.workspaces:t.workspaces?.packages??[]).flatMap(i=>br(r,i))}function Cn(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 Bo=32;function En(r,e,t,n={}){return O("typescript.provider.construct",()=>new Ft(r,e,t),()=>({tsconfigs:t.length,reusedProjects:n.reusedProjects===!0}))}var Ft=class{constructor(e,t,n){this.db=e;this.tsMorph=t;this.projects=n;this.workspacePackages=Sr(e.config.projectRoot),this.sourceFiles=xn(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 A(this.importUsageCache,e,()=>{let t=this.sourceFiles.sourceFile(e);if(!t)return[];let n=Uo();return O("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,t,n),()=>({file:e,...n}))})}referencesFor(e){return A(this.referencesCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,t)})}referencesForDefinitions(e,t={}){let n=new Map,i=xe(),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=>!Pn(d));if(s.length>=Bo){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=>Pn(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=Mn();O("typescript.references-map.file",()=>{let y=this.definitionNodesForFile(d);for(let f of u){i&&(p.cacheMisses+=1);let h=y.get(f.symbolId)??null;i&&(h?p.nodeHits+=1:p.nodeMisses+=1);try{let m=this.referencesForDefinitionNode(f,h,i?p:void 0);this.referencesCache.set(f.symbolId,m),n.set(f.symbolId,m)}catch{p.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:d,definitions:u.length,...Tn(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=fn(this.db).filter(o=>Ce(o.relativePath)),n=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,n);return Er(t,i,n)}referencesForDefinitionsBySymbolScan(e,t){let n=xe(),i=Mn(),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 O("typescript.references-map.inverted-scan",()=>{let c=n?S.now():0,l=t?this.packageImportReferencesForFiles(t):this.packageImportReferences();for(let m of e){let g=l.get(m.symbolId)??[];if(g.length>0){let R=o.get(m.symbolId)??[];R.push(...g),o.set(m.symbolId,R)}n&&(i.packageReferenceCount+=g.length)}n&&(i.packageRefsMs+=S.now()-c);let d=new Map,u=new Map,p=this.hierarchyTargetsForDefinitions(e),y=new Set(e.map(m=>m.leaf).filter(Boolean)),f=n?S.now():0;for(let m of t??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(m))continue;let g=this.sourceFiles.sourceFile(m);g&&(n&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(g,m,a,s,p,y,d,u,o,n?i:void 0))}n&&(i.scanMs+=S.now()-f);let h=n?S.now():0;this.addHierarchyMemberReferences(e,o,n?i:void 0),n&&(i.hierarchyMs+=S.now()-h);for(let[m,g]of o){let R=te(g);o.set(m,R),n&&(i.referenceCount+=R.length)}},()=>({definitions:e.length,...Tn(i)})),o}addReferencesFromSourceFileScan(e,t,n,i,o,a,s,c,l,d){let u=this.compilerCheckerForSourceFile(e),p=e.compilerNode,y=Yo(e),f=h=>{if(this.tsMorph.ts.isIdentifier(h)){if(d&&(d.identifiers+=1),!a.has(h.text)&&!y.has(h.text)){this.tsMorph.ts.forEachChild(h,f);return}let m=this.compilerReferenceSymbol(u,h,d);if(m){let g;s.has(m)?g=s.get(m)??null:(g=this.referenceDefinitionFromCompilerSymbol(m),s.set(m,g)),d&&(g?d.targetHits+=1:d.targetMisses+=1);let R=A(c,m,()=>this.compilerSymbolKeys(m)),M=null,k=null,j=g&&n.has(g.symbolId)?i.get(g.symbolId):void 0;if(j&&(M=Dt(p,h),!wn(j,t,M))){let L=p.getLineAndCharacterOfPosition(h.getStart(p));k={file:t,line:L.line,column:L.character};let N=l.get(j.symbolId)??[];N.push(k),l.set(j.symbolId,N),d&&(d.requestedHits+=1)}for(let L of R)for(let N of o.get(L)?.values()??[]){if(M??=Dt(p,h),wn(N,t,M))continue;if(!k){let C=p.getLineAndCharacterOfPosition(h.getStart(p));k={file:t,line:C.line,column:C.character}}let I=l.get(N.symbolId)??[];I.push(k),l.set(N.symbolId,I),d&&(d.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(h,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)),y={definition:o,location:{file:o.relativePath,line:p.line,column:p.character}},f=t.get(o.symbolId)??[];for(let m of this.hierarchyMemberSymbols(l,c,d))if(m!==d)for(let g of this.compilerSymbolLocations(m))f.push(g),n&&(n.hierarchyReferences+=1);t.set(o.symbolId,f);let h=this.hierarchyRootMemberSymbols(l,c,d);for(let m of h){let g=i.get(m)??new Map;g.set(o.symbolId,y),i.set(m,g)}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=re(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 A(this.calleesCache,e.symbolId,()=>A(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?S.now():0,o=this.packageImportReferencesForDefinition(e);if(n&&(n.packageRefsMs+=S.now()-i,n.packageReferenceCount+=o.length),!t)return o;let a=n?S.now():0,s=hn(t,e,o,this.db.config.projectRoot);return n&&(n.semanticRefsMs+=S.now()-a,n.referenceCount+=s.length),s}signatureFor(e){return A(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 kn(c)}),o=n.getReturnType().getText(t);return`(${i.join(",")})=>${kn(o)}`})}importUsageForSourceFile(e,t,n){let i=[],o=new Map;for(let a of t.getImportDeclarations()){n.declarations+=1;let s=pt(this.db,e,a.getModuleSpecifierValue()),c=a.getImportClause()?.isTypeOnly()??!1;for(let l of At(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||Vo(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:$e(a,this.db.config.projectRoot),node:a}),n.matchedReferences+=1;break}}}),i.map(a=>a.typeOnlyDeclaration?Ho(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 gn(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=>!It(c.node)),a=i.some(c=>It(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=Tt(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,te(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,te(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=Tt(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let a=t.get(o);if(a)for(let s of At(i)){if(s.kind!=="named"||!s.identifier)continue;let c=a.get(s.importedName);if(!c||c.size===0)continue;let l=yn(s.identifier,n,this.db.config.projectRoot);l.length>0&&Qo(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 In(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?pt(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,y=this.indexedDefinitionByLeaf(c,u);if(!y)continue;let f=n.get(p);f||(f=new Set,n.set(p,f)),f.add(y.symbolId)}}}indexedDefinitionByLeaf(e,t){return A(this.indexedDefinitionLeafCache,e,()=>vn(this.db,e)).get(t)??null}nodeForDefinition(e){return A(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return A(this.fileDefinitionNodeCache,e,()=>{let t=this.sourceFiles.sourceFile(e);return t?Sn(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?S.now():0,a=e.declarations??[];t&&(t.declarationsMs+=S.now()-o,t.declarationChecks+=a.length);for(let s of a){let c=t?S.now():0,l=s.getSourceFile(),d=re(this.db.config.projectRoot,l.fileName),u=l.getLineAndCharacterOfPosition(s.getStart(l)).line;if(t&&(t.declarationLocationMs+=S.now()-c),!d||this.db.isIgnored(d))continue;let p=t?S.now():0,y=this.compilerDeclarationName(s),f=n?wt(this.db,d,u,i)??(y&&y!==i?wt(this.db,d,u,y):null):bn(this.db,d,u,i);if(t&&(t.indexedLookupMs+=S.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=xe(),i=0,o=0,a=0,s=0,c=0,l=0,d=0,u=0,p=n?Jo():void 0;return O("typescript.callee-map.file",()=>{let y=n?S.now():0,f=this.sourceFiles.sourceFile(e);if(n&&(c=Math.round(S.now()-y)),!f)return new Map;let h=n?S.now():0,m=G(this.db,e).sort((I,C)=>I.startLine-C.startLine||C.endLine-I.endLine);if(n&&(l=Math.round(S.now()-h)),i=m.length,m.length===0)return new Map;let g=new Map,R=n?S.now():0,M=this.compilerCheckerForSourceFile(f),k=f.compilerNode;n&&(d=Math.round(S.now()-R));let j=new Map,L=I=>{if(this.tsMorph.ts.isCallExpression(I)||this.tsMorph.ts.isNewExpression(I)){n&&(o+=1);let C=this.semanticCalleeForCallNode(M,k,m,I,j,t,p);C&&(n&&(a+=1),Ko(g,C.callerId,C.target))}this.tsMorph.ts.forEachChild(I,L)},N=n?S.now():0;L(k),n&&(u=Math.round(S.now()-N));for(let[I,C]of g)g.set(I,Zo(C));return s=g.size,g},()=>({relativePath:e,definitions:i,callNodes:o,resolvedCallees:a,outputRows:s,requestedDefinitions:t?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:u,...p?Xo(p):{}}))}semanticCalleeForCallNode(e,t,n,i,o,a,s){let c=s?S.now():0,l=zo(n,Dt(t,i));if(s&&(s.callerLookupMs+=S.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 y=s?S.now():0;p=this.definitionFromCompilerSymbol(u,s),s&&(s.targetLookupMs+=S.now()-y),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?S.now():0,o=e.getSymbolAtLocation(t);if(n&&(n.expressionSymbolMs+=S.now()-i),o)return o;n&&(n.typeFallbacks+=1);let a=n?S.now():0,s=e.getTypeAtLocation(t).getSymbol();return n&&(n.typeSymbolMs+=S.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 At(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 Ho(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 Uo(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function Vo(r){for(let e=r;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function Ko(r,e,t){let n=r.get(e);n||(n=[],r.set(e,n)),n.push(t)}function Yo(r){let e=new Set;for(let t of r.getImportDeclarations())for(let n of At(t))n.localName&&e.add(n.localName);return e}function zo(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 Dt(r,e){return r.getLineAndCharacterOfPosition(e.getStart(r)).line}function wn(r,e,t){return e===r.relativePath&&t>=r.startLine&&t<=r.endLine}function Pn(r){return r.symbol.includes("#")?$(r.symbol)==="type"&&r.relativePath.endsWith(".d.ts"):!1}function Jo(){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 Xo(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 Mn(){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 Tn(r){return{...r,scanMs:Math.round(r.scanMs),packageRefsMs:Math.round(r.packageRefsMs),semanticRefsMs:Math.round(r.semanticRefsMs),hierarchyMs:Math.round(r.hierarchyMs)}}function Qo(r,e,t){for(let n of e){let i=r.get(n)??[];i.push(...t),r.set(n,i)}}function Zo(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 kn(r){return r.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Ge=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??Tr,this.discoverTsconfigs=t.discoverTsconfigs??Rn,this.createProjects=t.createProjects??kr,this.createProvider=t.createProvider??((n,i,o)=>En(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=es(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"&&(ts(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=mt("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=mt("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 es(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=Nt(r.changes,"added"),n=Nt(r.changes,"modified"),i=Nt(r.changes,"deleted");return{mode:t.length+n.length+i.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:n,deletedFiles:i,reasons:[]}}function Nt(r,e){return r.filter(t=>t.kind===e).map(t=>t.path).sort()}function ts(r,e,t){for(let n of r){for(let i of t.deletedFiles)n.project.getSourceFile(Dn(e,i))?.forget();for(let i of t.modifiedFiles){let o=n.project.getSourceFile(Dn(e,i));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&n.project.addSourceFilesFromTsConfig(n.tsconfigPath)}}var Be=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 Ge(t)),this.generationIdentity=e.generationIdentity?t=>e.generationIdentity(t.config.dbPath):t=>t.generation.identity,this.readSnapshot=e.readSnapshot?t=>e.readSnapshot(t.config.dbPath):os,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[...ns(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[...is(n,t.definitions)];case"signature":return n.signatureFor(t.definition);default:return as(t)}}catch(n){throw this.lastError=n instanceof Error?n.message:String(n),n}}status(e){let t=this.host?.snapshotStats();return{protocolVersion:Z,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:t?.sessionsCreated??0,sessionsReused:t?.sessionsReused??0,sessionsRefreshed:t?.sessionsRefreshed??0,sessionsReplaced:t?.sessionsReplaced??0,projectsCreated:t?.projectsCreated??0,...e?{mailbox:e}:{}}}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);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);if(!this.host||!this.db)this.db=t,this.host=this.createHost(t);else{let o=this.db;this.host.advanceGeneration(t,ss(this.snapshot,i)),this.db=t,o.close()}this.generation=n,this.snapshot=i,this.available=null}};function _t(r){Me(r)}function An(r,e,t={}){_t(r);let n=t.nowMs??Date.now(),i=Te(r,{ownerId:t.ownerId??cs,nowMs:n,limits:t.limits,owner:ls,liveness:ds}),o=0;for(let a of i){let s=a.requestId,c=null;try{let l=en(ke(a,t.limits));if(s=l.id,s!==a.requestId)throw new Error("TypeScript semantic request identity does not match its mailbox path.");if(l.deadlineAtMs<n)throw new Error("TypeScript semantic request expired before processing.");c=tr(),it(l.profileEnvironment??{}),t.beforeRequest?.(l.deadlineAtMs);let d=e.handle(l.generation,l.request);Ee(r,a,{ok:!0,protocolVersion:Z,id:s,generation:l.generation,response:d},{nowMs:n,limits:t.limits})}catch(l){let d=l instanceof Error?l.message:String(l);De(r,a,{ok:!1,protocolVersion:Z,id:s,error:d},d,{nowMs:n,limits:t.limits})}finally{c&&it(c),t.afterRequest?.(),o+=1}}return o}function Nn(r){return Fe(r)}function ns(r,e,t){return r.referencesForDefinitions?.(e,t)??new Map(e.map(n=>[n.symbolId,r.referencesFor(n)]))}function is(r,e){return r.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,r.calleesFor(t)]))}function os(r){if(!r.generation.metadataRaw)return null;let e=ve(r.generation.metadataRaw);return e.kind!=="legacy"&&e.kind!=="supported"||!e.capabilities.usableForEvidenceCache?null:Jt(e.metadata.fingerprint)}function ss(r,e){return e?Xt(r,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function as(r){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(r)}`)}var cs=`typescript-semantic-${process.pid}-${rs()}`,Fn=D(process.pid),ls={pid:process.pid,...Fn?{processIdentity:Fn}:{}},ds={isProcessAlive:F,readProcessIdentity:D};import{randomUUID as us}from"crypto";import{resolve as ps}from"path";var He=class{projectRoot;currentGeneration;createEmitter;wallNow;monotonicNow;active=null;requests=0;sessionsCreated=0;sessionsReplaced=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(e){this.projectRoot=ps(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??Or,this.wallNow=e.wallNow??e.now??Date.now,this.monotonicNow=e.monotonicNow??e.now??T}handle(e,t){let n=this.monotonicNow();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.monotonicNow()-n;return this.requests+=1,this.lastRequestAtMs=this.wallNow(),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(e){let t=this.active?.emitter.snapshotStats();return{protocolVersion:Ae,state:this.unavailable?"unavailable":this.lastError?"error":this.active?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,initializations:t?.initializations??0,programUpdates:t?.programUpdates??0,documentsEmitted:t?.documentsEmitted??0,documentsRemoved:t?.documentsRemoved??0,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{},...e?{mailbox:e}:{}}}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 Lt(r){Me(r)}function Ln(r,e,t={}){Lt(r);let n=t.nowMs??Date.now(),i=Te(r,{ownerId:t.ownerId??fs,nowMs:n,limits:t.limits,owner:ms,liveness:hs}),o=0;for(let a of i){let s=a.requestId;try{let c=Gr(ke(a,t.limits));if(s=c.id,s!==a.requestId)throw new Error("TypeScript index request identity does not match its mailbox path.");if(c.deadlineAtMs<n)throw new Error("TypeScript index request expired before processing.");t.beforeRequest?.(c.deadlineAtMs);let l=e.handle(c.baseGeneration,c.request);Ee(r,a,{ok:!0,protocolVersion:Ae,id:s,baseGeneration:c.baseGeneration,response:l},{nowMs:n,limits:t.limits})}catch(c){let l=c instanceof Error?c.message:String(c);De(r,a,{ok:!1,protocolVersion:Ae,id:s,error:l},l,{nowMs:n,limits:t.limits})}finally{t.afterRequest?.(),o+=1}}return o}function jn(r){return Fe(r)}var fs=`typescript-index-${process.pid}-${us()}`,_n=D(process.pid),ms={pid:process.pid,..._n?{processIdentity:_n}:{}},hs={isProcessAlive:F,readProcessIdentity:D};import{spawn as Es}from"child_process";import{existsSync as Ds,readFileSync as Fs,rmSync as ei}from"fs";import{dirname as ql,resolve as Ht}from"path";import{fileURLToPath as Gl}from"url";import{createHash as gs,randomUUID as jt}from"crypto";import{existsSync as ys,linkSync as Ss,mkdirSync as On,readFileSync as bs,readdirSync as vs,rmSync as ne}from"fs";import{basename as xs,dirname as Is,join as v}from"path";var B=1,Rs=10*6e4,Cs=10080*6e4,Ve="requests",ue="claims",Ue="completions",qn="staging";function $n(r,e,t={}){let n=t.now?.()??new Date,i=Ps(t.ttlMs),o=Ms(t.idempotencyKey),a=o?`key-${gs("sha256").update(o).digest("hex")}`:`request-${(t.randomId??jt)()}`,s={version:B,requestId:a,...o?{idempotencyKey:o}:{},createdAt:n.toISOString(),deadlineAt:new Date(n.getTime()+i).toISOString(),detail:e.trim().slice(0,2048)||"stale index observed by a command"},c=Xn(r,a);if(qt(r,c,s,t.onStage))return{disposition:"accepted",request:s};let d=Wt(c);if(!d)throw new Error(`Watch refresh request identity ${a} exists but is malformed.`);return{disposition:"duplicate",request:d}}function Gn(r,e={}){let t=e.now?.()??new Date,n=`claim-${(e.randomId??jt)()}`,i=Math.max(1,Math.floor(e.limit??64)),o=Yn(r).sort(Ts),a=[];for(let s of o){if(a.length>=i)break;if(Wn(r,s.requestId))continue;if(Date.parse(s.deadlineAt)<=t.getTime()){Kn(r,{version:B,requestId:s.requestId,outcome:"expired",completedAt:t.toISOString()});continue}let c={version:B,requestId:s.requestId,claimId:n,claimedAt:t.toISOString()};if(qt(r,Qn(r,s.requestId),c)){if(Wn(r,s.requestId)){zn(r,s.requestId,n);continue}a.push(s)}}return{claimId:n,requests:a}}function Bn(r,e,t=()=>new Date,n){let i=t().toISOString();for(let o of e.requests)Kn(r,{version:B,requestId:o.requestId,claimId:e.claimId,outcome:"completed",completedAt:i});n?.("after-completion"),Ke(r,e),n?.("after-claim-release")}function Ke(r,e){for(let t of e.requests)zn(r,t.requestId,e.claimId)}function Hn(r){let e=0;for(let t of H(v(r,ue)))ne(t,{force:!0}),e++;return e>0&&K(v(r,ue)),Jn(r),e}function Ot(r){let e=Yn(r),t=new Map,n=ws(v(r,Ve),Wt);for(let c of H(v(r,Ue))){let l=Ye(c);if(!l){n++;continue}t.set(l.requestId,l)}let i=new Set;for(let c of H(v(r,ue))){let l=Vn(c);if(!l){n++;continue}i.add(l.requestId)}let o=e.filter(c=>!t.has(c.requestId)&&!i.has(c.requestId)),a=[...t.values()].filter(c=>c.outcome==="completed").length,s=[...t.values()].filter(c=>c.outcome==="expired").length;return{pending:o.length,claimed:e.filter(c=>!t.has(c.requestId)&&i.has(c.requestId)).length,completed:a,expired:s,invalid:n,...o.length>0?{oldestPendingAt:o.map(c=>c.createdAt).reduce((c,l)=>ks(c,l))}:{}}}function Un(r,e={}){let t=(e.now?.()??new Date).getTime(),n=Math.max(0,e.retentionMs??Cs),i=0;for(let o of H(v(r,Ue))){let a=Ye(o);!a||t-Date.parse(a.completedAt)<n||(ne(o,{force:!0}),ne(Xn(r,a.requestId),{force:!0}),i++)}return i>0&&(K(v(r,Ue)),K(v(r,Ve))),Jn(r),i}function Wt(r){return $t(r,e=>{let t=e;return t.version===B&&pe(t.requestId)&&(t.idempotencyKey===void 0||typeof t.idempotencyKey=="string")&&se(t.createdAt)&&se(t.deadlineAt)&&Date.parse(t.deadlineAt)>=Date.parse(t.createdAt)&&typeof t.detail=="string"&&t.detail.length>0})}function Vn(r){return $t(r,e=>{let t=e;return t.version===B&&pe(t.requestId)&&pe(t.claimId)&&se(t.claimedAt)})}function Ye(r){return $t(r,e=>{let t=e;return t.version===B&&pe(t.requestId)&&(t.claimId===void 0||pe(t.claimId))&&(t.outcome==="completed"||t.outcome==="expired")&&se(t.completedAt)})}function Kn(r,e){let t=Zn(r,e.requestId);if(qt(r,t,e))return;let n=Ye(t);if(!n||n.requestId!==e.requestId||n.outcome!==e.outcome)throw new Error(`Watch refresh completion ${e.requestId} conflicts with an existing record.`)}function qt(r,e,t,n){let i=v(r,qn),o=Is(e);On(i,{recursive:!0}),On(o,{recursive:!0});let a=v(i,`${xs(e)}.${process.pid}.${jt()}.tmp`);try{Ie(a,t,{spacing:2,trailingNewline:!0}),n?.("after-staged");try{Ss(a,e)}catch(s){if(s.code==="EEXIST")return!1;throw s}return K(o),n?.("after-published"),!0}finally{ne(a,{force:!0})}}function Yn(r){let e=[];for(let t of H(v(r,Ve))){let n=Wt(t);n&&e.push(n)}return e}function zn(r,e,t){let n=Qn(r,e),i=Vn(n);!i||i.claimId!==t||(ne(n,{force:!0}),K(v(r,ue)))}function Jn(r){for(let e of H(v(r,qn),".tmp"))ne(e,{force:!0})}function ws(r,e){return H(r).filter(t=>!e(t)).length}function H(r,e=".json"){return ys(r)?vs(r,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(e)).map(t=>v(r,t.name)).sort():[]}function $t(r,e){try{let t=JSON.parse(bs(r,"utf8"));return e(t)?t:null}catch{return null}}function Xn(r,e){return v(r,Ve,`${e}.json`)}function Qn(r,e){return v(r,ue,`${e}.json`)}function Zn(r,e){return v(r,Ue,`${e}.json`)}function Wn(r,e){return Ye(Zn(r,e))!==null}function Ps(r){if(r===void 0)return Rs;if(!Number.isFinite(r)||r<=0)throw new Error("Watch refresh request ttlMs must be positive.");return Math.floor(r)}function Ms(r){let e=r?.trim();return e?e.slice(0,512):void 0}function pe(r){return typeof r=="string"&&/^[a-z0-9][a-z0-9-]{0,127}$/i.test(r)}function Ts(r,e){return Date.parse(r.createdAt)-Date.parse(e.createdAt)||r.requestId.localeCompare(e.requestId)}function ks(r,e){return Date.parse(e)<Date.parse(r)?e:r}var As=2e3,Ns=10;function ri(r,e,t){let n=st(Ht(r));if(t&&st(t.projectRoot)===n)return{projectRoot:n,worktreeKind:"git",worktreeId:t.worktreeId,cliVersion:e};let i=or(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 ni(r){let e=r.runtime??js,t=J(r.cacheDir),n=Hr(t.statePath),i=n?e.isProcessAlive(n.pid)?{kind:"live",state:n}:{kind:"stale",state:n,reason:"dead-process"}:{kind:"stopped"},o=_s("stop",i);if(o.kind==="signal-stop")return ti(o.state,r,e),Gt(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};if(o.kind==="clean-stale")return Gt(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};let a=ai(t.lockPath);return o.kind==="already-stopped"&&a&&e.isProcessAlive(a.pid)?(ti(a,r,e),Gt(t,a.pid,e),{disposition:"stopped",pid:a.pid}):{disposition:"already-stopped"}}function ii(r,e){Ie(r,e)}function oi(r){try{let e=JSON.parse(Fs(r,"utf8"));return e.version!==1||!Ne(e.at)||e.refreshRequestedAt!==void 0&&!Ne(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 si(r,e,t={}){let n=t.pid??process.pid,i=t.isProcessAlive??F,o=()=>{},a=t.readProcessIdentity??D,s=t.now??(()=>new Date),c={...at,wallNow:()=>s().getTime(),isProcessAlive:i,readProcessIdentity:a},l=cr(r,{kind:"watch",pid:n,processIdentity:a(n),detail:{projectRoot:Ht(e)},parseLegacy:ze,runtime:c});if(l.kind==="contended"){let d=ci(l.observation);return{acquired:!1,lockPath:r,message:Ls(r,e,d),release:o}}return{acquired:!0,lockPath:r,message:"",release:()=>{l.lock.release()}}}function ai(r){return ci(ct(r,{parseLegacy:ze}))}var ze=r=>{let e=li(r);return e?{pid:e.pid,...e.processIdentity?{processIdentity:e.processIdentity}:{}}:null};function ci(r){if(r.state==="valid"&&r.record?.kind==="watch"){let e=r.record.detail?.projectRoot;return typeof e!="string"?null:{version:1,pid:r.record.pid,...r.record.processIdentity?{processIdentity:r.record.processIdentity}:{},projectRoot:e,startedAt:r.record.startedAt}}return li(r.parsed)}function li(r){try{let e=r;if(e.version!==1||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.projectRoot!="string"||!Ne(e.startedAt))return null;let t=e.processIdentity===void 0?null:rr(e.processIdentity);return e.processIdentity!==void 0&&(!t||t.pid!==e.pid)?null:{version:1,pid:e.pid,...t?{processIdentity:t}:{},projectRoot:e.projectRoot,startedAt:e.startedAt}}catch{return null}}function _s(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:"refuse-replace",state:e.state,reason:"old-heartbeat"}:{kind:"start"};case"live":return{kind:"reuse",state:e.state};case"incompatible":return{kind:"replace",state:e.state};default:return Bt(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 Bt(e)}default:return Bt(r)}}function di(r){return r.idleTimeoutMs===0||r.watcher.state!=="idle"?!1:r.nowMs-r.lastActivityAtMs>=r.idleTimeoutMs}function ti(r,e,t){let{pid:n}=r;if(!t.isProcessAlive(n))return;Os(r,t),t.signalProcess(n);let i=e.stopTimeoutMs??As,o=t.monotonicNow??T,a=o()+i;for(;o()<=a;){if(!t.isProcessAlive(n))return;t.sleep(Ns)}throw new Error(`scip-query watch service pid ${n} did not stop within ${i}ms.`)}function Gt(r,e,t){if(ei(r.statePath,{force:!0}),ei(r.activityPath,{force:!0}),ai(r.lockPath)?.pid===e&&!t.isProcessAlive(e)){let i={...at,wallNow:t.now,isProcessAlive:t.isProcessAlive,readProcessIdentity:t.readProcessIdentity},o=ct(r.lockPath,{parseLegacy:ze,runtime:i});lr(r.lockPath,o,{parseLegacy:ze,runtime:i})}}function Ls(r,e,t){return`error: scip-query watch is already running for ${Ht(e)}${t?` (pid ${t.pid}, started ${t.startedAt}; lock: ${r})`:` (lock: ${r})`}. Stop that watcher before starting another.`}var js={now:Date.now,monotonicNow:T,isProcessAlive:F,readProcessIdentity:D,spawnServer(r,e,t,n){if(!Ds(r))throw new Error(`Watch service helper was not found at ${r}. Run npm run build first.`);Es(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 Os(r,e){if(!r.processIdentity)throw new Error(`Refusing to signal scip-query watch pid ${r.pid}: its ownership record has no process identity.`);let t=e.readProcessIdentity(r.pid);if(!t)throw new Error(`Refusing to signal scip-query watch pid ${r.pid}: its process identity is unavailable.`);if(!nr(r.processIdentity,t))throw new Error(`Refusing to signal scip-query watch pid ${r.pid}: its process identity does not match the ownership record.`)}function Bt(r){throw new Error(`Unhandled watch service value: ${JSON.stringify(r)}`)}import{existsSync as mi,lstatSync as Je,readFileSync as Yt,readdirSync as hi,realpathSync as ui,rmSync as fe,statSync as Ws}from"fs";import{join as w,resolve as U,sep as pi}from"path";var qs=3600*1e3,$s=2*1024*1024*1024,Gs=300*1e3;function Bs(r){let e=r.leases.filter(s=>s.managed&&!s.live&&!s.busy),t=Hs(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 Hs(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 gi(r,e,t={}){if(!_r())return{kind:"disabled"};let n=ir(r);if(!n)return{kind:"unavailable"};let i=w(ht(),"repositories",n.repositoryId);if(!mi(i))return{kind:"unavailable"};let o=(t.now??Date.now)(),a=w(i,"gc-state.json"),s=Ks(a);if(!t.force&&s&&o-Date.parse(s.lastSweepAt)<Gs)return{kind:"throttled",sweptAt:s.lastSweepAt};let c=dr(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=Us(r,i,n.repositoryId,s?.unreferencedSince??{}),d=Bs({nowMs:o,...l,policy:{generationTtlMs:t.policy?.generationTtlMs??qs,budgetBytes:t.policy?.budgetBytes??$s}}),u=0,p=0;for(let h of d.deleteWorktrees){if(!yi(h.lease))continue;let m=ur(w(h.lease.localCacheDir,"cache-lifecycle.lock"));if(m)try{if(Vt(h.lease,!0))continue;try{ni({projectRoot:h.lease.projectRoot,cacheDir:h.lease.localCacheDir,cliVersion:e})}catch{continue}if(Vt(h.lease,!0))continue;fe(h.lease.localCacheDir,{recursive:!0,force:!0}),fe(h.leasePath,{force:!0}),p+=1}finally{m.release()}}for(let h of d.deleteLocks)fe(h.path,{force:!0});for(let h of d.deleteTemporaries)fe(h.path,{recursive:!0,force:!0});for(let h of d.deleteGenerations)fe(h.path,{recursive:!0,force:!0}),u+=h.size;hr(w(i,"evidence.db"));let y={kind:"swept",sweptAt:new Date(o).toISOString(),deletedWorktrees:p,deletedGenerations:d.deleteGenerations.length,deletedBytes:u,protectedGenerations:d.protectedGenerationIds.length},f={version:1,lastSweepAt:y.sweptAt,unreferencedSince:d.unreferencedSince,lastResult:y};return lt(a,f,{spacing:2,trailingNewline:!0}),y}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function Us(r,e,t,n){let i=new Set(sr(r).map(l=>U(l.path))),o=[];for(let l of Ut(w(e,"worktrees"))){if(!l.endsWith(".json"))continue;let d=w(e,"worktrees",l),u=Vs(d);if(!u)continue;let p=U(u.projectRoot);o.push({leasePath:d,lease:u,managed:u.repositoryId===t&&yi(u),live:i.has(p)||mi(p),busy:Vt(u)})}let a=[];for(let l of Ut(w(e,"locks"))){let d=/^([a-f0-9]{64})\.lock$/.exec(l);if(!d)continue;let u=w(e,"locks",l),p=Kt(u),y=p!==void 0&&F(p),f=d[1];a.push({generationId:f,path:u,live:y})}let s=[],c=[];for(let l of Ut(w(e,"generations"))){let d=/^\.tmp-(\d+)-/.exec(l);if(d){let y=w(e,"generations",l),f=Number(d[1]);try{c.push({path:y,size:fi(y),live:Number.isSafeInteger(f)&&F(f)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let u=w(e,"generations",l),p;try{p=Je(u)}catch{continue}!p.isDirectory()||p.isSymbolicLink()||s.push({generationId:l,path:u,size:fi(u),...n[l]===void 0?{}:{unreferencedAt:n[l]}})}return{leases:o,generations:s,locks:a,temporaries:c}}function yi(r){if(r.ownershipChecksum!==jr(r)||U(r.localCacheDir)!==U(Nr(r.projectRoot)))return!1;let e=U(ht()),t=U(w(e,"projects")),n=U(r.localCacheDir);if(!n.startsWith(`${t}${pi}`))return!1;try{let i=Je(e),o=Je(t),a=Je(n);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink())return!1;let s=ui(t);return ui(n).startsWith(`${s}${pi}`)}catch{return!1}}function Vt(r,e=!1){for(let n of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=Kt(w(r.localCacheDir,n));if(i!==void 0&&F(i))return!0}let t=Kt(J(r.localCacheDir).lockPath);return t!==void 0&&F(t)}function Vs(r){try{let e=JSON.parse(Yt(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 Kt(r){try{let e=JSON.parse(Yt(r,"utf8"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function Ks(r){try{let e=JSON.parse(Yt(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 Ut(r){try{return hi(r)}catch{return[]}}function fi(r){let e=0,t=[r];for(;t.length>0;){let n=t.pop();for(let i of hi(n,{withFileTypes:!0})){let o=w(n,i.name);i.isDirectory()?t.push(o):i.isFile()&&(e+=Ws(o).size)}}return e}var Xe=class{root;now;randomId;retryDelayMs;active;retryNotBeforeMs=0;currentStatus;constructor(e,t={}){this.root=e,this.now=t.now??Date.now,this.randomId=t.randomId,this.retryDelayMs=Math.max(1,Math.floor(t.retryDelayMs??1e3)),this.currentStatus=Ot(e)}initializeAfterOwnershipAcquired(){let e=Hn(this.root),t=Un(this.root,{now:()=>new Date(this.now())});return this.refreshStatus(),{recoveredClaims:e,prunedHistory:t}}observeLegacyRequest(e,t){$n(this.root,t??"stale index observed by a legacy command",{idempotencyKey:`legacy-activity:${e}`,now:()=>new Date(e)}),this.refreshStatus()}poll(e,t){if(this.active||e.state!=="idle"||this.now()<this.retryNotBeforeMs)return!1;let n=Gn(this.root,{now:()=>new Date(this.now()),...this.randomId?{randomId:this.randomId}:{}});if(this.refreshStatus(),n.requests.length===0)return!1;this.active=n;try{return t(Ys(n)),!0}catch(i){throw Ke(this.root,n),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),i}}completeActive(){return this.active?(Bn(this.root,this.active,()=>new Date(this.now())),this.active=void 0,this.retryNotBeforeMs=0,this.refreshStatus(),!0):!1}failActive(){return this.active?(Ke(this.root,this.active),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),!0):!1}status(){return{...this.currentStatus}}refreshStatus(){this.currentStatus=Ot(this.root)}};function Ys(r){if(r.requests.length===1)return r.requests[0].detail;let t=[...new Set(r.requests.map(n=>n.detail))].slice(0,3).join("; ");return`${r.requests.length} coalesced refresh requests${t?`: ${t}`:""}`.slice(0,2048)}var Xs=1e3,Qs=250,Zs=10;function ea(r){return r==="fresh"?null:{kind:"watch-startup",detail:`index ${r} when watch service started`}}async function ta(r,e,t={}){let n=ri(r,e),i=n.projectRoot,o=Q(i);o.watch={...o.watch,...t};let a=Le(o);if(!a.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let s=z(i,o),c=J(s.cacheDir),l=D(P.pid),d=si(c.lockPath,i,{readProcessIdentity:b=>b===P.pid?l:D(b)});if(!d.acquired)return;let u=new Xe(c.refreshRequestsPath,{retryDelayMs:Math.max(1e3,a.cooldownMs)});u.initializeAfterOwnershipAcquired();let p=Date.now(),y=T(),f=p,h=y,m={state:"idle"},g,R,M,k=Pe(s.dbPath),j=!1,L=!1,N=0,I=Number.NEGATIVE_INFINITY,C=Number.NEGATIVE_INFINITY,zt=Number.NEGATIVE_INFINITY,me,he,Qe=Zr(s.cacheDir),Ze=$r(s.cacheDir);_t(Qe),Lt(Ze);let et=new Be({openDb:()=>on(i)}),tt=new He({projectRoot:i,currentGeneration:()=>Br(s.dbPath)}),_=(b=!1)=>{if(!L)return;let Se=Date.now(),be=T();!b&&be-I<Xs||(I=be,ii(c.statePath,{version:1,protocolVersion:bt,pid:P.pid,...l?{processIdentity:l}:{},projectRoot:i,...n.worktreeId?{worktreeId:n.worktreeId}:{},cliVersion:e,startedAt:new Date(p).toISOString(),heartbeatAt:new Date(Se).toISOString(),lastActivityAt:new Date(f).toISOString(),...a.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(f+a.idleTimeoutMs).toISOString()},watcher:m,...m.state==="idle"&&g?{indexGeneration:g}:{},...R?{lastRefresh:R}:{},...M?{lastError:M}:{},reindexActivity:k,refreshRequests:u.status(),typescriptSemantic:{...et.status(Nn(Qe)),...me===void 0?{}:{busyUntil:new Date(me).toISOString()}},typescriptIndex:{...tt.status(jn(Ze)),...he===void 0?{}:{busyUntil:new Date(he).toISOString()}}}))},V=()=>{f=Date.now(),h=T()},ge=new je({projectRoot:i,config:{...o,watch:a},languages:o.languages,onStatus(b){m=b,b.state!=="idle"&&(g=void 0),b.state!=="idle"&&V(),_(!0)},onReindexComplete(){V();let b=vt(i,o,s);return R=b.lastRefresh,g=b.state==="fresh"?xt(s.dbPath)??void 0:void 0,k=Pe(s.dbPath),u.completeActive(),M=void 0,_(!0),b.state==="fresh"},onReindexError(){u.failActive()},onRefreshSuppressed(b){Ar(s.dbPath,b),k=Pe(s.dbPath)},onError(b){V(),g=void 0,M={at:new Date().toISOString(),message:b.message},_(!0)}}),ye=()=>{j=!0};P.once("SIGINT",ye),P.once("SIGTERM",ye);let rt=!1,nt,ie;try{ge.start();let b=vt(i,o,s);R=b.lastRefresh,g=b.state==="fresh"?xt(s.dbPath)??void 0:void 0;let Se=ea(b.state);for(Se&&ge.requestRefresh(Se,{immediate:!0}),V(),L=!0,_(!0);!j;){let be=Ln(Ze,tt,{beforeRequest(E){he=E+5e3,_(!0)},afterRequest(){he=void 0,_(!0)}}),bi=An(Qe,et,{beforeRequest(E){me=E+5e3,_(!0)},afterRequest(){me=void 0,_(!0)}}),oe=T();if(oe-zt>=6e4&&(zt=oe,gi(i,e)),oe-C>=Qs){C=oe;let E=oi(c.activityPath);E&&E.atMs>f&&(f=E.atMs,h=oe),E?.refreshRequestedAtMs!==void 0&&E.refreshRequestedAtMs>N&&(N=E.refreshRequestedAtMs,u.observeLegacyRequest(E.refreshRequestedAtMs,E.refreshDetail??"stale index observed by a legacy command")),u.poll(m,vi=>{V(),ge.requestRefresh({kind:"watch-demand",detail:vi},{immediate:!0})})}if((bi>0||be>0)&&(V(),_(!0)),_(),di({watcher:m,lastActivityAtMs:h,nowMs:T(),idleTimeoutMs:a.idleTimeoutMs}))break;await ra(Zs)}}catch(b){rt=!0,nt=b}finally{P.off("SIGINT",ye),P.off("SIGTERM",ye),et.closeTypeScriptService(),tt.close();let b=await ge.stop();b.state==="stopped"?(Si(c.statePath,{force:!0}),Si(c.activityPath,{force:!0}),d.release()):(M={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${b.reasons.join("; ")}`},_(!0),ie=new Error(M.message))}if(rt&&ie)throw new AggregateError([nt,ie],"Watch service execution and shutdown both failed.");if(rt)throw nt;if(ie)throw ie}function ra(r){return new Promise(e=>setTimeout(e,r))}var na=P.argv[1]?Js(zs(P.argv[1])).href:null;if(na===import.meta.url){let r=P.argv[2],e=P.argv[3],t=ia(P.argv[4]);if(!r||!e)console.error("watch-service: expected <project-root> <cli-version>"),P.exitCode=1;else try{await ta(r,e,t)}catch(n){console.error(`watch-service: ${n instanceof Error?n.message:String(n)}`),P.exitCode=1}}function ia(r){if(!r)return{};try{let e=JSON.parse(r);return e&&typeof e=="object"?e:{}}catch{return{}}}export{ta as runWatchServiceServer,ea as startupRefreshTrigger};
|
|
41
|
+
ORDER BY start_line, end_line`,e)}function Co(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:G(r.symbol),parentTypeName:te(r.symbol),isFunctionLike:yn(r.symbol),isTypeLike:B(r.symbol)==="type",kind:r.kind??null,documentation:r.documentation??null,enclosingSymbol:r.enclosing_symbol??null}}function In(r,e={}){return wo(r,e.scope)}function wo(r,e){return J(r,{scope:e,includeIgnored:!1}).flatMap(t=>U(r,t)).filter(t=>!r.isIgnored(t.relativePath))}function Po(r,e,t){let n=qe(r).forFile(e,{text:!0}).text,i=Nr(r,e);return i?Fo(t,i,n):n?Mo(t,n):t}function Mo(r,e){let t=e.split(/\r?\n/),n=To(r,t),i=ko(r,n),o=Eo(i,t);return Do(r,o)}function To(r,e){let t=r.some(i=>Ge(i.symbol))?Wo(e):null,n=new Map;for(let i of r)n.set(i.symbolId,Oo(e,t,i));return n}function ko(r,e){return r.filter(t=>Ge(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 Eo(r,e){let t=new Map;for(let n=0;n<r.length;n+=1){let i=r[n],o=r[n+1],s=o?Math.max(i.startLine,o.startLine-1):e.length-1;t.set(i.definition.symbolId,{startLine:i.startLine,endLine:qo(e,i.definition,i.startLine,s)})}return t}function Do(r,e){return r.map(t=>{let n=e.get(t.symbolId);return n?{...t,startLine:n.startLine,endLine:n.endLine}:t})}function Fo(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(!jo(i)||!i.leaf)return vn(i,t);let o=n.get(i.leaf);if(!o||o.length===0)return vn(i,t);let s=t?Ao(i,o,t):null;if(s)return{...i,startLine:s.startLine,endLine:s.endLine};let a=o[0],c=Math.abs(a.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&&(a=d,c=u)}return{...i,startLine:a.startLine,endLine:a.endLine}})}function Ao(r,e,t){let n=_o(r.symbol);if(!n)return null;let i=t.split(/\r?\n/),o=new RegExp(`\\b${le(n)}\\b`);for(let s of e){let a=No(i,s.startLine);if(a&&o.test(a))return s}return null}function _o(r){return r.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function No(r,e){for(let t=e;t>=0;t-=1){let n=r[t]?.trim()??"";if(n){if(/^impl\b/.test(n))return Lo(r,t,e);if(/^(?:struct|enum|trait|mod)\b/.test(n))return null}}return null}function Lo(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 jo(r){return Ge(r.symbol)?!0:B(r.symbol)==="term"&&te(r.symbol)===null}function vn(r,e){if(!e||!r.leaf||B(r.symbol)!=="term"||te(r.symbol)!==null)return r;let t=le(r.leaf),n=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${t}\\b`),o=e.split(/\r?\n/).findIndex(s=>n.test(s));return o>=0?{...r,startLine:o,endLine:o}:r}function Oo(r,e,t){if(!Ge(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 s of i){let a=Math.abs(s-t.startLine);(!o||a<o.distance)&&(o={line:s,distance:a})}return o?.line??n}function Wo(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,s=(a,c)=>{let l=o.get(a);if(!l){o.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)};for(let a=0;a<r.length;a+=1){let c=r[a]??"";for(let d of c.matchAll(e))d[1]&&s(d[1],a);for(let d of c.matchAll(t))d[1]&&s(d[1],a);let l=c.match(n);l?.[1]&&s(l[1],a);for(let d of c.matchAll(i))d[1]&&s(d[1],a)}return o}function qo(r,e,t,n){let i=Math.max(t,Math.min(r.length-1,n)),o=Math.max(t,Math.min(i,e.endLine)),s=0,a=0,c=!1;for(let l=t;l<=i;l+=1){let d=$o(r[l]??"");for(let u of d)u==="{"?(s+=1,c=!0):u==="}"?s=Math.max(0,s-1):u==="("?a+=1:u===")"&&(a=Math.max(0,a-1));if(c&&s===0||!c&&a===0&&l>=o)return l}return o}function $o(r){let e="",t=null,n=!1;for(let i=0;i<r.length;i+=1){let o=r[i],s=r[i+1];if(!t&&o==="/"&&s==="/"){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 Ge(r){return r.includes("().")}function _(r,e,t){if(r.has(e))return r.get(e);let n=t();return r.set(e,n),n}import wn from"path";import{realpathSync as Rn}from"fs";function Go(r,e){return r.getReferences().map(t=>{let n=t.getNode();return Be(n,e)})}function Bo(r){let e=r;return typeof e.findReferences=="function"?e.findReferences():[]}function Pn(r,e,t,n){let i=[];for(let o of Bo(r))for(let s of Go(o,n))s.file===e.relativePath&&s.line>=e.startLine&&s.line<=e.endLine||i.push(s);for(let o of t)i.push(o);return re(i)}function Mn(r,e,t,n){let i=[],o=t?.getStart();for(let s of r.getReferences()){let a=s.getNode();ne(n,a.getSourceFile().getFilePath())===e&&(o!==void 0&&a.getStart()===o||i.push({location:Be(a,n),node:a}))}return i}function Be(r,e){let t=r.getSourceFile(),n=t.getLineAndColumnAtPos(r.getStart());return{file:ne(e,t.getFilePath())??t.getBaseName(),line:n.line-1,column:n.column-1}}function Tn(r,e,t){let n=r.getSourceFile(),i=Pt(n,r),o=r.getText(),s=new RegExp(`\\b${le(o)}\\b`,"g"),a=n.getFullText().split(`
|
|
42
|
+
`),c=[];for(let l=0;l<a.length;l++){if(l===i)continue;let d=a[l]??"";s.lastIndex=0;let u;for(;(u=s.exec(d))!==null;)c.push({file:e,line:l,column:u.index})}return re(c.filter(l=>ne(t,wn.join(t,l.file))===e))}function wt(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 Pt(r,e){return r.getLineAndColumnAtPos(e.getStart()).line-1}function re(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 ne(r,e){let t=r||process.cwd(),n=Cn(t,e);if(n)return n;try{return Cn(Rn(t),Rn(e))}catch{return null}}function Cn(r,e){let t=wn.relative(r,e).replace(/\\/g,"/");return!t||t===".."||t.startsWith("../")?null:t}function kn(r,e,t,n){let i=Uo(e,n);return i.size===0?new Map:Ho(r,t,i)}function Uo(r,e){let t=new Map;for(let n of U(r,e)){let i=G(n.symbol)??n.leaf;if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push(n)}return t}function Ho(r,e,t){let n=new Map,i=new Map;return e.forEachDescendant(o=>{for(let s of Vo(r,o)){let a=t.get(s);if(!a)continue;let c=Pt(e,o);for(let l of a){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 Vo(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 Yo=ce("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function En(r,e,t,n){let i=kt(r,e),o=Mt(i.get(n)??[],t);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||G(c.symbol)||"").includes(n)||c.symbol.includes(n))&&s.push(c);return Mt(s,t)}function Tt(r,e,t,n){return Mt(kt(r,e).get(n)??[],t)}function Dn(r,e){let t=new Map;for(let[n,i]of kt(r,e)){let o=i[0];o&&t.set(n,o)}return t}function kt(r,e){return Yo.get(r,e,()=>{let t=new Map;for(let n of U(r,e)){let i=n.leaf||G(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 Mt(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 Ko from"path";import{realpathSync as zo}from"fs";function Fn(r,e){let t=new Map,n=null,i=null,o=()=>(i??=J(r,{extensions:we}),i),s=()=>(n??=W("typescript.source-file-index",()=>Jo(r.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),n),a=c=>Pe(c)?_(t,c,()=>{let l=An(r.config.projectRoot,c);if(!l)return null;for(let{project:d,sourceFiles:u}of s()){let p=u.get(l)??null;if(p||(p=d.addSourceFileAtPathIfExists(l)??null,p&&Et(u,p)),p)return{project:d,sourceFile:p}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function Jo(r,e,t){let n=e.map(({project:i})=>{let o=new Map;for(let s of i.getSourceFiles())Et(o,s);return{project:i,sourceFiles:o}});for(let i of t){let o=An(r,i);if(o)for(let s of n){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){Et(s.sourceFiles,a);break}}}return n}function Et(r,e){let t=Dt(e.getFilePath());r.set(t,e);try{r.set(Dt(zo(t)),e)}catch(n){if(!ut(n))throw n}}function An(r,e){try{return Dt(xr(r,e,{inputKind:"indexed TypeScript source file"}).absolutePath)}catch(t){if(!ut(t))throw t;return null}}function Dt(r){return Ko.resolve(r)}function Ft(r,e){for(let t of r)if(e===t.name||e.startsWith(`${t.name}/`))return t.name;return null}function _n(r){let e=`${r.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as de}from"fs";import x from"path";var At=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function _t(r,e){let n=e?x.dirname(x.join(r,e)):r,i=x.resolve(r);for(;n.startsWith(i);){for(let s of At){let a=x.join(n,s);if(de(a))return a}let o=x.dirname(n);if(o===n)break;n=o}for(let o of At){let s=x.join(r,o);if(de(s))return s}return null}function Nn(r){let e=r.config.projectRoot,t=new Set(Xo(e,r.config.semantic?.typescript?.tsconfigs)),n=J(r,{includeIgnored:!1,extensions:we});for(let i of n){let o=_t(e,i);o&&t.add(x.resolve(o))}if(t.size===0){let i=_t(e);i&&t.add(x.resolve(i))}return[...t].filter(i=>!Ln(e,i)).sort((i,o)=>i.localeCompare(o))}function Xo(r,e=[]){let t=new Set;for(let n of e){let i=x.isAbsolute(n)?n:x.join(r,n);de(i)&&t.add(x.resolve(i))}for(let n of Qo(r))for(let i of At){let o=x.join(n,i);de(o)&&t.add(x.resolve(o))}if(t.size===0){let n=_t(r);n&&t.add(x.resolve(n))}return[...t].filter(n=>!Ln(r,n)).sort((n,i)=>n.localeCompare(i))}function Qo(r){let e=x.join(r,"package.json");if(!de(e))return[];let t;try{t=JSON.parse(D(e,"project package manifest"))}catch{return[]}return(Array.isArray(t.workspaces)?t.workspaces:t.workspaces?.packages??[]).flatMap(i=>kr(r,i))}function Ln(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 Zo=32;function Gn(r,e,t,n={}){return W("typescript.provider.construct",()=>new Lt(r,e,t),()=>({tsconfigs:t.length,reusedProjects:n.reusedProjects===!0}))}var Lt=class{constructor(e,t,n){this.db=e;this.tsMorph=t;this.projects=n;this.workspacePackages=Tr(e.config.projectRoot),this.sourceFiles=Fn(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 _(this.importUsageCache,e,()=>{let t=this.sourceFiles.sourceFile(e);if(!t)return[];let n=ts();return W("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,t,n),()=>({file:e,...n}))})}referencesFor(e){return _(this.referencesCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,t)})}referencesForDefinitions(e,t={}){let n=new Map,i=Re(),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 s=o,a=t.exact?[]:o.filter(d=>!On(d));if(a.length>=Zo){let d=this.referencesForDefinitionsBySymbolScan(a);for(let u of a){let p=d.get(u.symbolId)??[];this.referencesCache.set(u.symbolId,p),n.set(u.symbolId,p)}if(s=o.filter(u=>On(u)),s.length===0)return n}let c=new Map;for(let d of s){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=Wn();W("typescript.references-map.file",()=>{let y=this.definitionNodesForFile(d);for(let f of u){i&&(p.cacheMisses+=1);let h=y.get(f.symbolId)??null;i&&(h?p.nodeHits+=1:p.nodeMisses+=1);try{let m=this.referencesForDefinitionNode(f,h,i?p:void 0);this.referencesCache.set(f.symbolId,m),n.set(f.symbolId,m)}catch{p.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:d,definitions:u.length,...qn(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=In(this.db).filter(o=>Pe(o.relativePath)),n=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,n);return qr(t,i,n)}referencesForDefinitionsBySymbolScan(e,t){let n=Re(),i=Wn(),o=new Map,s=new Set(e.map(c=>c.symbolId)),a=new Map(e.map(c=>[c.symbolId,c]));for(let c of e)o.set(c.symbolId,[]);return W("typescript.references-map.inverted-scan",()=>{let c=n?S.now():0,l=t?this.packageImportReferencesForFiles(t):this.packageImportReferences();for(let m of e){let g=l.get(m.symbolId)??[];if(g.length>0){let R=o.get(m.symbolId)??[];R.push(...g),o.set(m.symbolId,R)}n&&(i.packageReferenceCount+=g.length)}n&&(i.packageRefsMs+=S.now()-c);let d=new Map,u=new Map,p=this.hierarchyTargetsForDefinitions(e),y=new Set(e.map(m=>m.leaf).filter(Boolean)),f=n?S.now():0;for(let m of t??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(m))continue;let g=this.sourceFiles.sourceFile(m);g&&(n&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(g,m,s,a,p,y,d,u,o,n?i:void 0))}n&&(i.scanMs+=S.now()-f);let h=n?S.now():0;this.addHierarchyMemberReferences(e,o,n?i:void 0),n&&(i.hierarchyMs+=S.now()-h);for(let[m,g]of o){let R=re(g);o.set(m,R),n&&(i.referenceCount+=R.length)}},()=>({definitions:e.length,...qn(i)})),o}addReferencesFromSourceFileScan(e,t,n,i,o,s,a,c,l,d){let u=this.compilerCheckerForSourceFile(e),p=e.compilerNode,y=is(e),f=h=>{if(this.tsMorph.ts.isIdentifier(h)){if(d&&(d.identifiers+=1),!s.has(h.text)&&!y.has(h.text)){this.tsMorph.ts.forEachChild(h,f);return}let m=this.compilerReferenceSymbol(u,h,d);if(m){let g;a.has(m)?g=a.get(m)??null:(g=this.referenceDefinitionFromCompilerSymbol(m),a.set(m,g)),d&&(g?d.targetHits+=1:d.targetMisses+=1);let R=_(c,m,()=>this.compilerSymbolKeys(m)),M=null,k=null,O=g&&n.has(g.symbolId)?i.get(g.symbolId):void 0;if(O&&(M=Nt(p,h),!jn(O,t,M))){let j=p.getLineAndCharacterOfPosition(h.getStart(p));k={file:t,line:j.line,column:j.character};let N=l.get(O.symbolId)??[];N.push(k),l.set(O.symbolId,N),d&&(d.requestedHits+=1)}for(let j of R)for(let N of o.get(j)?.values()??[]){if(M??=Nt(p,h),jn(N,t,M))continue;if(!k){let C=p.getLineAndCharacterOfPosition(h.getStart(p));k={file:t,line:C.line,column:C.character}}let I=l.get(N.symbolId)??[];I.push(k),l.set(N.symbolId,I),d&&(d.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(h,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 s=o.parent;if(!this.isHierarchyContainer(s))continue;let a=this.compilerCheckerForSourceFile(i.getSourceFile()),c=a.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(a,s,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,s=(a,c,l)=>{if(!o.has(a)){o.add(a),i.add(c);for(let d of l){let u=d.getProperty(n.name);u&&s(d,u,this.hierarchyAncestorTypesForType(e,d))}}};return s(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}addHierarchyMemberReferences(e,t,n){let i=new Map;for(let o of e){let s=this.nodeForDefinition(o),a=s?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let c=a.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(s.getSourceFile()),d=l.getSymbolAtLocation(a.name);if(!d)continue;let u=a.getSourceFile(),p=u.getLineAndCharacterOfPosition(a.name.getStart(u)),y={definition:o,location:{file:o.relativePath,line:p.line,column:p.character}},f=t.get(o.symbolId)??[];for(let m of this.hierarchyMemberSymbols(l,c,d))if(m!==d)for(let g of this.compilerSymbolLocations(m))f.push(g),n&&(n.hierarchyReferences+=1);t.set(o.symbolId,f);let h=this.hierarchyRootMemberSymbols(l,c,d);for(let m of h){let g=i.get(m)??new Map;g.set(o.symbolId,y),i.set(m,g)}n&&(n.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){n&&(n.hierarchyFamilies+=1);for(let{definition:s}of o.values()){let a=t.get(s.symbolId)??[];for(let c of o.values())c.definition.symbolId!==s.symbolId&&(a.push(c.location),n&&(n.hierarchyReferences+=1));t.set(s.symbolId,a)}}}hierarchyRootMemberSymbols(e,t,n){let i=new Set,o=new Set,s=(a,c,l)=>{if(o.has(a))return;o.add(a);let d=!1;for(let u of l){let p=u.getProperty(n.name);p&&(d=!0,s(u,p,this.hierarchyAncestorTypesForType(e,u)))}if(!d)for(let u of this.compilerSymbolKeys(c))i.add(u)};return s(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=ne(this.db.config.projectRoot,i.fileName);if(!o)continue;let s=n.name,a=i.getLineAndCharacterOfPosition((s??n).getStart(i));t.push({file:o,line:a.line,column:a.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 s of o.types)n.add(e.getTypeAtLocation(s));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 _(this.calleesCache,e.symbolId,()=>_(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 s=this.fileCalleesCache.get(i),a=new Set(o.map(l=>l.symbolId)),c=s??this.calleeMapForFile(i,a);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?S.now():0,o=this.packageImportReferencesForDefinition(e);if(n&&(n.packageRefsMs+=S.now()-i,n.packageReferenceCount+=o.length),!t)return o;let s=n?S.now():0,a=Pn(t,e,o,this.db.config.projectRoot);return n&&(n.semanticRefsMs+=S.now()-s,n.referenceCount+=a.length),a}signatureFor(e){return _(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(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return $n(c)}),o=n.getReturnType().getText(t);return`(${i.join(",")})=>${$n(o)}`})}importUsageForSourceFile(e,t,n){let i=[],o=new Map;for(let s of t.getImportDeclarations()){n.declarations+=1;let a=ht(this.db,e,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of jt(s)){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:a,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(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||rs(s))return;n.scannedIdentifiers+=1;let c=s.getSymbol()?.compilerSymbol;if(n.symbolLookups+=1,!!c){for(let l of a)if(l.bindingSymbol===c){l.references.push({location:Be(s,this.db.config.projectRoot),node:s}),n.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?es(e,s.sourcePath,s.entry):s.entry.identifier&&!s.bindingSymbol?(n.fallbackEntries+=1,this.valueImportUsageForEntry(e,s.sourcePath,s.entry)):this.valueImportUsageFromLocations(e,s.sourcePath,s.entry,s.references))}valueImportUsageForEntry(e,t,n){let i=n.identifier?n.identifier.findReferences():[],o=[];for(let s of i)for(let a of Mn(s,e,n.identifier,this.db.config.projectRoot))o.push(a);return this.valueImportUsageFromLocations(e,t,n,o)}valueImportUsageFromLocations(e,t,n,i){let o=i.some(c=>!wt(c.node)),s=i.some(c=>wt(c.node)),a=n.isTypeOnly;return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:a,isUsed:a||i.length>0,isTypeUsed:a||s,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 s=this.sourceFiles.sourceFile(o);if(s)for(let a of s.getImportDeclarations()){let c=Ft(this.workspacePackages,a.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,s]of t)t.set(o,re(s));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,re(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=Ft(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=t.get(o);if(s)for(let a of jt(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=Tn(a.identifier,n,this.db.config.projectRoot);l.length>0&&cs(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 _n(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 s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?ht(this.db,t,a):t;if(!c||!c.startsWith(`${e.relativeDir}/src/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(e,c,n,i);continue}for(let d of l){let u=d.getNameNode().getText(),p=d.getAliasNode()?.getText()??u,y=this.indexedDefinitionByLeaf(c,u);if(!y)continue;let f=n.get(p);f||(f=new Set,n.set(p,f)),f.add(y.symbolId)}}}indexedDefinitionByLeaf(e,t){return _(this.indexedDefinitionLeafCache,e,()=>Dn(this.db,e)).get(t)??null}nodeForDefinition(e){return _(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return _(this.fileDefinitionNodeCache,e,()=>{let t=this.sourceFiles.sourceFile(e);return t?kn(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?S.now():0,s=e.declarations??[];t&&(t.declarationsMs+=S.now()-o,t.declarationChecks+=s.length);for(let a of s){let c=t?S.now():0,l=a.getSourceFile(),d=ne(this.db.config.projectRoot,l.fileName),u=l.getLineAndCharacterOfPosition(a.getStart(l)).line;if(t&&(t.declarationLocationMs+=S.now()-c),!d||this.db.isIgnored(d))continue;let p=t?S.now():0,y=this.compilerDeclarationName(a),f=n?Tt(this.db,d,u,i)??(y&&y!==i?Tt(this.db,d,u,y):null):En(this.db,d,u,i);if(t&&(t.indexedLookupMs+=S.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=Re(),i=0,o=0,s=0,a=0,c=0,l=0,d=0,u=0,p=n?ss():void 0;return W("typescript.callee-map.file",()=>{let y=n?S.now():0,f=this.sourceFiles.sourceFile(e);if(n&&(c=Math.round(S.now()-y)),!f)return new Map;let h=n?S.now():0,m=U(this.db,e).sort((I,C)=>I.startLine-C.startLine||C.endLine-I.endLine);if(n&&(l=Math.round(S.now()-h)),i=m.length,m.length===0)return new Map;let g=new Map,R=n?S.now():0,M=this.compilerCheckerForSourceFile(f),k=f.compilerNode;n&&(d=Math.round(S.now()-R));let O=new Map,j=I=>{if(this.tsMorph.ts.isCallExpression(I)||this.tsMorph.ts.isNewExpression(I)){n&&(o+=1);let C=this.semanticCalleeForCallNode(M,k,m,I,O,t,p);C&&(n&&(s+=1),ns(g,C.callerId,C.target))}this.tsMorph.ts.forEachChild(I,j)},N=n?S.now():0;j(k),n&&(u=Math.round(S.now()-N));for(let[I,C]of g)g.set(I,ls(C));return a=g.size,g},()=>({relativePath:e,definitions:i,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:t?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:u,...p?as(p):{}}))}semanticCalleeForCallNode(e,t,n,i,o,s,a){let c=a?S.now():0,l=os(n,Nt(t,i));if(a&&(a.callerLookupMs+=S.now()-c),!l)return null;if(s&&!s.has(l.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let d=i.expression,u=this.compilerSymbolForExpression(e,d,a),p=null;if(u)if(a&&(a.targetSymbolHits+=1),o.has(u))a&&(a.compilerSymbolCacheHits+=1),p=o.get(u)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let y=a?S.now():0;p=this.definitionFromCompilerSymbol(u,a),a&&(a.targetLookupMs+=S.now()-y),o.set(u,p)}else a&&(a.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?S.now():0,o=e.getSymbolAtLocation(t);if(n&&(n.expressionSymbolMs+=S.now()-i),o)return o;n&&(n.typeFallbacks+=1);let s=n?S.now():0,a=e.getTypeAtLocation(t).getSymbol();return n&&(n.typeSymbolMs+=S.now()-s),a}compilerCheckerForSourceFile(e){let t=e.getProject(),n=this.compilerCheckerCache.get(t);return n||(n=t.getTypeChecker().compilerObject,this.compilerCheckerCache.set(t,n)),n}};function jt(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(),a=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);e.push({identifier:a,importedName:o.getText(),localName:a?.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 es(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 ts(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function rs(r){for(let e=r;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function ns(r,e,t){let n=r.get(e);n||(n=[],r.set(e,n)),n.push(t)}function is(r){let e=new Set;for(let t of r.getImportDeclarations())for(let n of jt(t))n.localName&&e.add(n.localName);return e}function os(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 Nt(r,e){return r.getLineAndCharacterOfPosition(e.getStart(r)).line}function jn(r,e,t){return e===r.relativePath&&t>=r.startLine&&t<=r.endLine}function On(r){return r.symbol.includes("#")?B(r.symbol)==="type"&&r.relativePath.endsWith(".d.ts"):!1}function ss(){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 as(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 Wn(){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 qn(r){return{...r,scanMs:Math.round(r.scanMs),packageRefsMs:Math.round(r.packageRefsMs),semanticRefsMs:Math.round(r.semanticRefsMs),hierarchyMs:Math.round(r.hierarchyMs)}}function cs(r,e,t){for(let n of e){let i=r.get(n)??[];i.push(...t),r.set(n,i)}}function ls(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 $n(r){return r.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Ue=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??Or,this.discoverTsconfigs=t.discoverTsconfigs??Nn,this.createProjects=t.createProjects??Wr,this.createProvider=t.createProvider??((n,i,o)=>Gn(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=ds(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"&&(us(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=yt("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=yt("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 ds(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=Ot(r.changes,"added"),n=Ot(r.changes,"modified"),i=Ot(r.changes,"deleted");return{mode:t.length+n.length+i.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:n,deletedFiles:i,reasons:[]}}function Ot(r,e){return r.filter(t=>t.kind===e).map(t=>t.path).sort()}function us(r,e,t){for(let n of r){for(let i of t.deletedFiles)n.project.getSourceFile(Bn(e,i))?.forget();for(let i of t.modifiedFiles){let o=n.project.getSourceFile(Bn(e,i));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&n.project.addSourceFilesFromTsConfig(n.tsconfigPath)}}var He=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 Ue(t)),this.generationIdentity=e.generationIdentity?t=>e.generationIdentity(t.config.dbPath):t=>t.generation.identity,this.readSnapshot=e.readSnapshot?t=>e.readSnapshot(t.config.dbPath):hs,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[...fs(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[...ms(n,t.definitions)];case"signature":return n.signatureFor(t.definition);default:return ys(t)}}catch(n){throw this.lastError=n instanceof Error?n.message:String(n),n}}status(e){let t=this.host?.snapshotStats();return{protocolVersion:ee,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:t?.sessionsCreated??0,sessionsReused:t?.sessionsReused??0,sessionsRefreshed:t?.sessionsRefreshed??0,sessionsReplaced:t?.sessionsReplaced??0,projectsCreated:t?.projectsCreated??0,...e?{mailbox:e}:{}}}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);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);if(!this.host||!this.db)this.db=t,this.host=this.createHost(t);else{let o=this.db;this.host.advanceGeneration(t,gs(this.snapshot,i)),this.db=t,o.close()}this.generation=n,this.snapshot=i,this.available=null}};function Wt(r){ke(r)}function Hn(r,e,t={}){Wt(r);let n=t.nowMs??Date.now(),i=Ee(r,{ownerId:t.ownerId??Ss,nowMs:n,limits:t.limits,owner:bs,liveness:vs}),o=0;for(let s of i){let a=s.requestId,c=null;try{let l=dn(De(s,t.limits));if(a=l.id,a!==s.requestId)throw new Error("TypeScript semantic request identity does not match its mailbox path.");if(l.deadlineAtMs<n)throw new Error("TypeScript semantic request expired before processing.");c=cr(),it(l.profileEnvironment??{}),t.beforeRequest?.(l.deadlineAtMs);let d=e.handle(l.generation,l.request);Fe(r,s,{ok:!0,protocolVersion:ee,id:a,generation:l.generation,response:d},{nowMs:n,limits:t.limits})}catch(l){let d=l instanceof Error?l.message:String(l);Ae(r,s,{ok:!1,protocolVersion:ee,id:a,error:d},d,{nowMs:n,limits:t.limits})}finally{c&&it(c),t.afterRequest?.(),o+=1}}return o}function Vn(r){return _e(r)}function fs(r,e,t){return r.referencesForDefinitions?.(e,t)??new Map(e.map(n=>[n.symbolId,r.referencesFor(n)]))}function ms(r,e){return r.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,r.calleesFor(t)]))}function hs(r){if(!r.generation.metadataRaw)return null;let e=Ie(r.generation.metadataRaw);return e.kind!=="legacy"&&e.kind!=="supported"||!e.capabilities.usableForEvidenceCache?null:nr(e.metadata.fingerprint)}function gs(r,e){return e?ir(r,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function ys(r){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(r)}`)}var Ss=`typescript-semantic-${process.pid}-${ps()}`,Un=F(process.pid),bs={pid:process.pid,...Un?{processIdentity:Un}:{}},vs={isProcessAlive:A,readProcessIdentity:F};import{randomUUID as xs}from"crypto";import{resolve as Is}from"path";var Ve=class{projectRoot;currentGeneration;createEmitter;wallNow;monotonicNow;active=null;requests=0;sessionsCreated=0;sessionsReplaced=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(e){this.projectRoot=Is(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??Vr,this.wallNow=e.wallNow??e.now??Date.now,this.monotonicNow=e.monotonicNow??e.now??T}handle(e,t){let n=this.monotonicNow();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(),s=i.emitter.advance({modifiedFiles:t.modifiedFiles,affectedFiles:t.affectedFiles}),a=this.monotonicNow()-n;return this.requests+=1,this.lastRequestAtMs=this.wallNow(),this.lastDurationMs=a,this.lastError=null,this.unavailable=!1,{producerIdentity:s.producerIdentity,cold:s.stats.initializations>o.initializations,durationMs:a,fragments:s.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(e){let t=this.active?.emitter.snapshotStats();return{protocolVersion:Ne,state:this.unavailable?"unavailable":this.lastError?"error":this.active?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,initializations:t?.initializations??0,programUpdates:t?.programUpdates??0,documentsEmitted:t?.documentsEmitted??0,documentsRemoved:t?.documentsRemoved??0,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{},...e?{mailbox:e}:{}}}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 qt(r){ke(r)}function Kn(r,e,t={}){qt(r);let n=t.nowMs??Date.now(),i=Ee(r,{ownerId:t.ownerId??Rs,nowMs:n,limits:t.limits,owner:Cs,liveness:ws}),o=0;for(let s of i){let a=s.requestId;try{let c=Jr(De(s,t.limits));if(a=c.id,a!==s.requestId)throw new Error("TypeScript index request identity does not match its mailbox path.");if(c.deadlineAtMs<n)throw new Error("TypeScript index request expired before processing.");t.beforeRequest?.(c.deadlineAtMs);let l=e.handle(c.baseGeneration,c.request);Fe(r,s,{ok:!0,protocolVersion:Ne,id:a,baseGeneration:c.baseGeneration,response:l},{nowMs:n,limits:t.limits})}catch(c){let l=c instanceof Error?c.message:String(c);Ae(r,s,{ok:!1,protocolVersion:Ne,id:a,error:l},l,{nowMs:n,limits:t.limits})}finally{t.afterRequest?.(),o+=1}}return o}function zn(r){return _e(r)}var Rs=`typescript-index-${process.pid}-${xs()}`,Yn=F(process.pid),Cs={pid:process.pid,...Yn?{processIdentity:Yn}:{}},ws={isProcessAlive:A,readProcessIdentity:F};import{spawn as Ws}from"child_process";import{existsSync as qs,rmSync as pi}from"fs";import{dirname as id,resolve as Kt}from"path";import{fileURLToPath as sd}from"url";import{createHash as Ps,randomUUID as $t}from"crypto";import{existsSync as Ms,linkSync as Ts,mkdirSync as Jn,readdirSync as ks,rmSync as ie}from"fs";import{basename as Es,dirname as Ds,join as v}from"path";var H=1,Fs=10*6e4,As=10080*6e4,Ke="requests",ue="claims",Ye="completions",Qn="staging";function Zn(r,e,t={}){let n=t.now?.()??new Date,i=Ns(t.ttlMs),o=Ls(t.idempotencyKey),s=o?`key-${Ps("sha256").update(o).digest("hex")}`:`request-${(t.randomId??$t)()}`,a={version:H,requestId:s,...o?{idempotencyKey:o}:{},createdAt:n.toISOString(),deadlineAt:new Date(n.getTime()+i).toISOString(),detail:e.trim().slice(0,2048)||"stale index observed by a command"},c=li(r,s);if(Ut(r,c,a,t.onStage))return{disposition:"accepted",request:a};let d=Bt(c);if(!d)throw new Error(`Watch refresh request identity ${s} exists but is malformed.`);return{disposition:"duplicate",request:d}}function ei(r,e={}){let t=e.now?.()??new Date,n=`claim-${(e.randomId??$t)()}`,i=Math.max(1,Math.floor(e.limit??64)),o=si(r).sort(js),s=[];for(let a of o){if(s.length>=i)break;if(Xn(r,a.requestId))continue;if(Date.parse(a.deadlineAt)<=t.getTime()){oi(r,{version:H,requestId:a.requestId,outcome:"expired",completedAt:t.toISOString()});continue}let c={version:H,requestId:a.requestId,claimId:n,claimedAt:t.toISOString()};if(Ut(r,di(r,a.requestId),c)){if(Xn(r,a.requestId)){ai(r,a.requestId,n);continue}s.push(a)}}return{claimId:n,requests:s}}function ti(r,e,t=()=>new Date,n){let i=t().toISOString();for(let o of e.requests)oi(r,{version:H,requestId:o.requestId,claimId:e.claimId,outcome:"completed",completedAt:i});n?.("after-completion"),ze(r,e),n?.("after-claim-release")}function ze(r,e){for(let t of e.requests)ai(r,t.requestId,e.claimId)}function ri(r){let e=0;for(let t of V(v(r,ue)))ie(t,{force:!0}),e++;return e>0&&z(v(r,ue)),ci(r),e}function Gt(r){let e=si(r),t=new Map,n=_s(v(r,Ke),Bt);for(let c of V(v(r,Ye))){let l=Je(c);if(!l){n++;continue}t.set(l.requestId,l)}let i=new Set;for(let c of V(v(r,ue))){let l=ii(c);if(!l){n++;continue}i.add(l.requestId)}let o=e.filter(c=>!t.has(c.requestId)&&!i.has(c.requestId)),s=[...t.values()].filter(c=>c.outcome==="completed").length,a=[...t.values()].filter(c=>c.outcome==="expired").length;return{pending:o.length,claimed:e.filter(c=>!t.has(c.requestId)&&i.has(c.requestId)).length,completed:s,expired:a,invalid:n,...o.length>0?{oldestPendingAt:o.map(c=>c.createdAt).reduce((c,l)=>Os(c,l))}:{}}}function ni(r,e={}){let t=(e.now?.()??new Date).getTime(),n=Math.max(0,e.retentionMs??As),i=0;for(let o of V(v(r,Ye))){let s=Je(o);!s||t-Date.parse(s.completedAt)<n||(ie(o,{force:!0}),ie(li(r,s.requestId),{force:!0}),i++)}return i>0&&(z(v(r,Ye)),z(v(r,Ke))),ci(r),i}function Bt(r){return Ht(r,e=>{let t=e;return t.version===H&&pe(t.requestId)&&(t.idempotencyKey===void 0||typeof t.idempotencyKey=="string")&&ae(t.createdAt)&&ae(t.deadlineAt)&&Date.parse(t.deadlineAt)>=Date.parse(t.createdAt)&&typeof t.detail=="string"&&t.detail.length>0})}function ii(r){return Ht(r,e=>{let t=e;return t.version===H&&pe(t.requestId)&&pe(t.claimId)&&ae(t.claimedAt)})}function Je(r){return Ht(r,e=>{let t=e;return t.version===H&&pe(t.requestId)&&(t.claimId===void 0||pe(t.claimId))&&(t.outcome==="completed"||t.outcome==="expired")&&ae(t.completedAt)})}function oi(r,e){let t=ui(r,e.requestId);if(Ut(r,t,e))return;let n=Je(t);if(!n||n.requestId!==e.requestId||n.outcome!==e.outcome)throw new Error(`Watch refresh completion ${e.requestId} conflicts with an existing record.`)}function Ut(r,e,t,n){let i=v(r,Qn),o=Ds(e);Jn(i,{recursive:!0}),Jn(o,{recursive:!0});let s=v(i,`${Es(e)}.${process.pid}.${$t()}.tmp`);try{Ce(s,t,{spacing:2,trailingNewline:!0}),n?.("after-staged");try{Ts(s,e)}catch(a){if(a.code==="EEXIST")return!1;throw a}return z(o),n?.("after-published"),!0}finally{ie(s,{force:!0})}}function si(r){let e=[];for(let t of V(v(r,Ke))){let n=Bt(t);n&&e.push(n)}return e}function ai(r,e,t){let n=di(r,e),i=ii(n);!i||i.claimId!==t||(ie(n,{force:!0}),z(v(r,ue)))}function ci(r){for(let e of V(v(r,Qn),".tmp"))ie(e,{force:!0})}function _s(r,e){return V(r).filter(t=>!e(t)).length}function V(r,e=".json"){return Ms(r)?ks(r,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(e)).map(t=>v(r,t.name)).sort():[]}function Ht(r,e){try{let t=JSON.parse(D(r,"watch refresh request record"));return e(t)?t:null}catch{return null}}function li(r,e){return v(r,Ke,`${e}.json`)}function di(r,e){return v(r,ue,`${e}.json`)}function ui(r,e){return v(r,Ye,`${e}.json`)}function Xn(r,e){return Je(ui(r,e))!==null}function Ns(r){if(r===void 0)return Fs;if(!Number.isFinite(r)||r<=0)throw new Error("Watch refresh request ttlMs must be positive.");return Math.floor(r)}function Ls(r){let e=r?.trim();return e?e.slice(0,512):void 0}function pe(r){return typeof r=="string"&&/^[a-z0-9][a-z0-9-]{0,127}$/i.test(r)}function js(r,e){return Date.parse(r.createdAt)-Date.parse(e.createdAt)||r.requestId.localeCompare(e.requestId)}function Os(r,e){return Date.parse(e)<Date.parse(r)?e:r}var $s=2e3,Gs=10;function mi(r,e,t){let n=ct(Kt(r));if(t&&ct(t.projectRoot)===n)return{projectRoot:n,worktreeKind:"git",worktreeId:t.worktreeId,cliVersion:e};let i=mr(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 hi(r){let e=r.runtime??Hs,t=X(r.cacheDir),n=Qr(t.statePath),i=n?e.isProcessAlive(n.pid)?{kind:"live",state:n}:{kind:"stale",state:n,reason:"dead-process"}:{kind:"stopped"},o=Bs("stop",i);if(o.kind==="signal-stop")return fi(o.state,r,e),Vt(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};if(o.kind==="clean-stale")return Vt(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};let s=bi(t.lockPath);return o.kind==="already-stopped"&&s&&e.isProcessAlive(s.pid)?(fi(s,r,e),Vt(t,s.pid,e),{disposition:"stopped",pid:s.pid}):{disposition:"already-stopped"}}function gi(r,e){Ce(r,e)}function yi(r){try{let e=JSON.parse(D(r,"watch activity record"));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 Si(r,e,t={}){let n=t.pid??process.pid,i=t.isProcessAlive??A,o=()=>{},s=t.readProcessIdentity??F,a=t.now??(()=>new Date),c={...lt,wallNow:()=>a().getTime(),isProcessAlive:i,readProcessIdentity:s},l=yr(r,{kind:"watch",pid:n,processIdentity:s(n),detail:{projectRoot:Kt(e)},parseLegacy:Xe,runtime:c});if(l.kind==="contended"){let d=vi(l.observation);return{acquired:!1,lockPath:r,message:Us(r,e,d),release:o}}return{acquired:!0,lockPath:r,message:"",release:()=>{l.lock.release()}}}function bi(r){return vi(dt(r,{parseLegacy:Xe}))}var Xe=r=>{let e=xi(r);return e?{pid:e.pid,...e.processIdentity?{processIdentity:e.processIdentity}:{}}:null};function vi(r){if(r.state==="valid"&&r.record?.kind==="watch"){let e=r.record.detail?.projectRoot;return typeof e!="string"?null:{version:1,pid:r.record.pid,...r.record.processIdentity?{processIdentity:r.record.processIdentity}:{},projectRoot:e,startedAt:r.record.startedAt}}return xi(r.parsed)}function xi(r){try{let e=r;if(e.version!==1||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.projectRoot!="string"||!Le(e.startedAt))return null;let t=e.processIdentity===void 0?null:ur(e.processIdentity);return e.processIdentity!==void 0&&(!t||t.pid!==e.pid)?null:{version:1,pid:e.pid,...t?{processIdentity:t}:{},projectRoot:e.projectRoot,startedAt:e.startedAt}}catch{return null}}function Bs(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:"refuse-replace",state:e.state,reason:"old-heartbeat"}:{kind:"start"};case"live":return{kind:"reuse",state:e.state};case"incompatible":return{kind:"replace",state:e.state};default:return Yt(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 Yt(e)}default:return Yt(r)}}function Ii(r){return r.idleTimeoutMs===0||r.watcher.state!=="idle"?!1:r.nowMs-r.lastActivityAtMs>=r.idleTimeoutMs}function fi(r,e,t){let{pid:n}=r;if(!t.isProcessAlive(n))return;Vs(r,t),t.signalProcess(n);let i=e.stopTimeoutMs??$s,o=t.monotonicNow??T,s=o()+i;for(;o()<=s;){if(!t.isProcessAlive(n))return;t.sleep(Gs)}throw new Error(`scip-query watch service pid ${n} did not stop within ${i}ms.`)}function Vt(r,e,t){if(pi(r.statePath,{force:!0}),pi(r.activityPath,{force:!0}),bi(r.lockPath)?.pid===e&&!t.isProcessAlive(e)){let i={...lt,wallNow:t.now,isProcessAlive:t.isProcessAlive,readProcessIdentity:t.readProcessIdentity},o=dt(r.lockPath,{parseLegacy:Xe,runtime:i});Sr(r.lockPath,o,{parseLegacy:Xe,runtime:i})}}function Us(r,e,t){return`error: scip-query watch is already running for ${Kt(e)}${t?` (pid ${t.pid}, started ${t.startedAt}; lock: ${r})`:` (lock: ${r})`}. Stop that watcher before starting another.`}var Hs={now:Date.now,monotonicNow:T,isProcessAlive:A,readProcessIdentity:F,spawnServer(r,e,t,n){if(!qs(r))throw new Error(`Watch service helper was not found at ${r}. Run npm run build first.`);Ws(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 Vs(r,e){if(!r.processIdentity)throw new Error(`Refusing to signal scip-query watch pid ${r.pid}: its ownership record has no process identity.`);let t=e.readProcessIdentity(r.pid);if(!t)throw new Error(`Refusing to signal scip-query watch pid ${r.pid}: its process identity is unavailable.`);if(!pr(r.processIdentity,t))throw new Error(`Refusing to signal scip-query watch pid ${r.pid}: its process identity does not match the ownership record.`)}function Yt(r){throw new Error(`Unhandled watch service value: ${JSON.stringify(r)}`)}import{existsSync as Pi,lstatSync as Qe,readdirSync as Mi,realpathSync as Ri,rmSync as fe,statSync as Ys}from"fs";import{join as w,resolve as me,sep as Ci}from"path";var Ks=3600*1e3,zs=2*1024*1024*1024,Js=300*1e3;function Xs(r){let e=r.leases.filter(a=>a.managed&&!a.live&&!a.busy),t=Qs(r.leases,r.locks),n={};for(let a of r.generations)t.has(a.generationId)||(n[a.generationId]=a.unreferencedAt??r.nowMs);let i=r.generations.filter(a=>!t.has(a.generationId)).sort((a,c)=>n[a.generationId]-n[c.generationId]||a.generationId.localeCompare(c.generationId)),o=new Set;for(let a of i)r.nowMs-n[a.generationId]>=r.policy.generationTtlMs&&o.add(a.generationId);let s=r.generations.filter(a=>!o.has(a.generationId)).reduce((a,c)=>a+c.size,0);for(let a of i){if(s<=r.policy.budgetBytes)break;o.has(a.generationId)||(o.add(a.generationId),s-=a.size)}for(let a of o)delete n[a];return{deleteWorktrees:e,deleteGenerations:r.generations.filter(a=>o.has(a.generationId)),deleteLocks:r.locks.filter(a=>!a.live),deleteTemporaries:r.temporaries.filter(a=>!a.live),protectedGenerationIds:[...t].sort(),unreferencedSince:n}}function Qs(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 Ti(r,e,t={}){if(!dr())return{kind:"disabled"};let n=fr(r);if(!n)return{kind:"unavailable"};let i=w(ot(),"repositories",n.repositoryId);if(!Pi(i))return{kind:"unavailable"};let o=(t.now??Date.now)(),s=w(i,"gc-state.json"),a=ta(s);if(!t.force&&a&&o-Date.parse(a.lastSweepAt)<Js)return{kind:"throttled",sweptAt:a.lastSweepAt};let c=br(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=Zs(r,i,n.repositoryId,a?.unreferencedSince??{}),d=Xs({nowMs:o,...l,policy:{generationTtlMs:t.policy?.generationTtlMs??Ks,budgetBytes:t.policy?.budgetBytes??zs}}),u=0,p=0;for(let h of d.deleteWorktrees){if(!ki(h.lease))continue;let m=vr(w(h.lease.localCacheDir,"cache-lifecycle.lock"));if(m)try{if(Jt(h.lease,!0))continue;try{hi({projectRoot:h.lease.projectRoot,cacheDir:h.lease.localCacheDir,cliVersion:e})}catch{continue}if(Jt(h.lease,!0))continue;fe(h.lease.localCacheDir,{recursive:!0,force:!0}),fe(h.leasePath,{force:!0}),p+=1}finally{m.release()}}for(let h of d.deleteLocks)fe(h.path,{force:!0});for(let h of d.deleteTemporaries)fe(h.path,{recursive:!0,force:!0});for(let h of d.deleteGenerations)fe(h.path,{recursive:!0,force:!0}),u+=h.size;wr(w(i,"evidence.db"));let y={kind:"swept",sweptAt:new Date(o).toISOString(),deletedWorktrees:p,deletedGenerations:d.deleteGenerations.length,deletedBytes:u,protectedGenerations:d.protectedGenerationIds.length},f={version:1,lastSweepAt:y.sweptAt,unreferencedSince:d.unreferencedSince,lastResult:y};return pt(s,f,{spacing:2,trailingNewline:!0}),y}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function Zs(r,e,t,n){let i=new Set(hr(r).map(l=>me(l.path))),o=[];for(let l of zt(w(e,"worktrees"))){if(!l.endsWith(".json"))continue;let d=w(e,"worktrees",l),u=ea(d);if(!u)continue;let p=me(u.projectRoot);o.push({leasePath:d,lease:u,managed:u.repositoryId===t&&ki(u),live:i.has(p)||Pi(p),busy:Jt(u)})}let s=[];for(let l of zt(w(e,"locks"))){let d=/^([a-f0-9]{64})\.lock$/.exec(l);if(!d)continue;let u=w(e,"locks",l),p=Xt(u),y=p!==void 0&&A(p),f=d[1];s.push({generationId:f,path:u,live:y})}let a=[],c=[];for(let l of zt(w(e,"generations"))){let d=/^\.tmp-(\d+)-/.exec(l);if(d){let y=w(e,"generations",l),f=Number(d[1]);try{c.push({path:y,size:wi(y),live:Number.isSafeInteger(f)&&A(f)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let u=w(e,"generations",l),p;try{p=Qe(u)}catch{continue}!p.isDirectory()||p.isSymbolicLink()||a.push({generationId:l,path:u,size:wi(u),...n[l]===void 0?{}:{unreferencedAt:n[l]}})}return{leases:o,generations:a,locks:s,temporaries:c}}function ki(r){if(r.ownershipChecksum!==Hr(r)||st(r.localCacheDir)!==st(lr(r.projectRoot)))return!1;let e=me(ot()),t=me(w(e,"projects")),n=me(r.localCacheDir);if(!n.startsWith(`${t}${Ci}`))return!1;try{let i=Qe(e),o=Qe(t),s=Qe(n);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!s.isDirectory()||s.isSymbolicLink())return!1;let a=Ri(t);return Ri(n).startsWith(`${a}${Ci}`)}catch{return!1}}function Jt(r,e=!1){for(let n of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=Xt(w(r.localCacheDir,n));if(i!==void 0&&A(i))return!0}let t=Xt(X(r.localCacheDir).lockPath);return t!==void 0&&A(t)}function ea(r){try{let e=JSON.parse(D(r,"worktree cache lease"));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 Xt(r){try{let e=JSON.parse(D(r,"watch lock record"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function ta(r){try{let e=JSON.parse(D(r,"repository cache GC state"));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 zt(r){try{return Mi(r)}catch{return[]}}function wi(r){let e=0,t=[r];for(;t.length>0;){let n=t.pop();for(let i of Mi(n,{withFileTypes:!0})){let o=w(n,i.name);i.isDirectory()?t.push(o):i.isFile()&&(e+=Ys(o).size)}}return e}var Ze=class{root;now;randomId;retryDelayMs;active;retryNotBeforeMs=0;currentStatus;constructor(e,t={}){this.root=e,this.now=t.now??Date.now,this.randomId=t.randomId,this.retryDelayMs=Math.max(1,Math.floor(t.retryDelayMs??1e3)),this.currentStatus=Gt(e)}initializeAfterOwnershipAcquired(){let e=ri(this.root),t=ni(this.root,{now:()=>new Date(this.now())});return this.refreshStatus(),{recoveredClaims:e,prunedHistory:t}}observeLegacyRequest(e,t){Zn(this.root,t??"stale index observed by a legacy command",{idempotencyKey:`legacy-activity:${e}`,now:()=>new Date(e)}),this.refreshStatus()}poll(e,t){if(this.active||e.state!=="idle"||this.now()<this.retryNotBeforeMs)return!1;let n=ei(this.root,{now:()=>new Date(this.now()),...this.randomId?{randomId:this.randomId}:{}});if(this.refreshStatus(),n.requests.length===0)return!1;this.active=n;try{return t(ra(n)),!0}catch(i){throw ze(this.root,n),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),i}}completeActive(){return this.active?(ti(this.root,this.active,()=>new Date(this.now())),this.active=void 0,this.retryNotBeforeMs=0,this.refreshStatus(),!0):!1}failActive(){return this.active?(ze(this.root,this.active),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),!0):!1}status(){return{...this.currentStatus}}refreshStatus(){this.currentStatus=Gt(this.root)}};function ra(r){if(r.requests.length===1)return r.requests[0].detail;let t=[...new Set(r.requests.map(n=>n.detail))].slice(0,3).join("; ");return`${r.requests.length} coalesced refresh requests${t?`: ${t}`:""}`.slice(0,2048)}var oa=1e3,sa=250,aa=6e4,ca=10,la=50;function da(r){return r>0?ca:la}function ua(r){return r==="fresh"?null:{kind:"watch-startup",detail:`index ${r} when watch service started`}}async function pa(r,e,t={}){let n=mi(r,e),i=n.projectRoot,o=Z(i);o.watch={...o.watch,...t};let s=Oe(o);if(!s.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let a=K(i,o),c=X(a.cacheDir),l=F(P.pid),d=Si(c.lockPath,i,{readProcessIdentity:b=>b===P.pid?l:F(b)});if(!d.acquired)return;let u=new Ze(c.refreshRequestsPath,{retryDelayMs:Math.max(1e3,s.cooldownMs)});u.initializeAfterOwnershipAcquired();let p=Date.now(),y=T(),f=p,h=y,m={state:"idle"},g,R,M,k=Te(a.dbPath),O=!1,j=!1,N=0,I=Number.NEGATIVE_INFINITY,C=Number.NEGATIVE_INFINITY,Qt=Number.NEGATIVE_INFINITY,Zt=Number.NEGATIVE_INFINITY,he,ge,ye=ln(a.cacheDir),Se=zr(a.cacheDir);Wt(ye),qt(Se);let et=new He({openDb:()=>mn(i)}),tt=new Ve({projectRoot:i,currentGeneration:()=>Xr(a.dbPath)}),L=(b=!1)=>{if(!j)return;let xe=Date.now(),se=T();!b&&se-I<oa||(I=se,gi(c.statePath,{version:1,protocolVersion:It,pid:P.pid,...l?{processIdentity:l}:{},projectRoot:i,...n.worktreeId?{worktreeId:n.worktreeId}:{},cliVersion:e,startedAt:new Date(p).toISOString(),heartbeatAt:new Date(xe).toISOString(),lastActivityAt:new Date(f).toISOString(),...s.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(f+s.idleTimeoutMs).toISOString()},watcher:m,...m.state==="idle"&&g?{indexGeneration:g}:{},...R?{lastRefresh:R}:{},...M?{lastError:M}:{},reindexActivity:k,refreshRequests:u.status(),typescriptSemantic:{...et.status(Vn(ye)),...he===void 0?{}:{busyUntil:new Date(he).toISOString()}},typescriptIndex:{...tt.status(zn(Se)),...ge===void 0?{}:{busyUntil:new Date(ge).toISOString()}}}))},Y=()=>{f=Date.now(),h=T()},be=new We({projectRoot:i,config:{...o,watch:s},languages:o.languages,onStatus(b){m=b,b.state!=="idle"&&(g=void 0),b.state!=="idle"&&Y(),L(!0)},onReindexComplete(){Y();let b=Rt(i,o,a);return R=b.lastRefresh,g=b.state==="fresh"?Ct(a.dbPath)??void 0:void 0,k=Te(a.dbPath),u.completeActive(),M=void 0,L(!0),b.state==="fresh"},onReindexError(){u.failActive()},onRefreshSuppressed(b){Br(a.dbPath,b),k=Te(a.dbPath)},onError(b){Y(),g=void 0,M={at:new Date().toISOString(),message:b.message},L(!0)}}),ve=()=>{O=!0};P.once("SIGINT",ve),P.once("SIGTERM",ve);let rt=!1,nt,oe;try{be.start();let b=Rt(i,o,a);R=b.lastRefresh,g=b.state==="fresh"?Ct(a.dbPath)??void 0:void 0;let xe=ua(b.state);for(xe&&be.requestRefresh(xe,{immediate:!0}),Y(),j=!0,L(!0);!O;){let se=Kn(Se,tt,{beforeRequest(E){ge=E+5e3,L(!0)},afterRequest(){ge=void 0,L(!0)}}),er=Hn(ye,et,{beforeRequest(E){he=E+5e3,L(!0)},afterRequest(){he=void 0,L(!0)}}),q=T();if(q-Zt>=aa&&(Zt=q,xt(Se),xt(ye)),q-Qt>=6e4&&(Qt=q,Ti(i,e)),q-C>=sa){C=q;let E=yi(c.activityPath);E&&E.atMs>f&&(f=E.atMs,h=q),E?.refreshRequestedAtMs!==void 0&&E.refreshRequestedAtMs>N&&(N=E.refreshRequestedAtMs,u.observeLegacyRequest(E.refreshRequestedAtMs,E.refreshDetail??"stale index observed by a legacy command")),u.poll(m,Di=>{Y(),be.requestRefresh({kind:"watch-demand",detail:Di},{immediate:!0})})}if((er>0||se>0)&&(Y(),L(!0)),L(),Ii({watcher:m,lastActivityAtMs:h,nowMs:T(),idleTimeoutMs:s.idleTimeoutMs}))break;await fa(da(er+se))}}catch(b){rt=!0,nt=b}finally{P.off("SIGINT",ve),P.off("SIGTERM",ve),et.closeTypeScriptService(),tt.close();let b=await be.stop();b.state==="stopped"?(Ei(c.statePath,{force:!0}),Ei(c.activityPath,{force:!0}),d.release()):(M={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${b.reasons.join("; ")}`},L(!0),oe=new Error(M.message))}if(rt&&oe)throw new AggregateError([nt,oe],"Watch service execution and shutdown both failed.");if(rt)throw nt;if(oe)throw oe}function fa(r){return new Promise(e=>setTimeout(e,r))}var ma=P.argv[1]?ia(na(P.argv[1])).href:null;if(ma===import.meta.url){let r=P.argv[2],e=P.argv[3],t=ha(P.argv[4]);if(!r||!e)console.error("watch-service: expected <project-root> <cli-version>"),P.exitCode=1;else try{await pa(r,e,t)}catch(n){console.error(`watch-service: ${tn(n instanceof Error?n.message:String(n))}`),P.exitCode=1}}function ha(r){if(!r)return{};try{let e=JSON.parse(r);return e&&typeof e=="object"?e:{}}catch{return{}}}export{pa as runWatchServiceServer,ua as startupRefreshTrigger,da as watchServiceLoopDelayMs};
|
|
43
43
|
//# sourceMappingURL=watch-server.js.map
|
package/docs/AGENT_GUIDE.md
CHANGED
|
@@ -27,7 +27,10 @@ For analyzer implementation work, follow [Regex Policy](REGEX_POLICY.md): regex
|
|
|
27
27
|
explicit `watch.enabled: false` is preserved. Use `scip-query setup --guided`
|
|
28
28
|
for a recommended automatic-indexing choice, or
|
|
29
29
|
`scip-query setup --no-hooks --json` when the repo should not write Codex or
|
|
30
|
-
Claude Code lifecycle hooks.
|
|
30
|
+
Claude Code lifecycle hooks. Non-interactive setup and ordinary reindex
|
|
31
|
+
diagnose missing global tools without installing them. Pass
|
|
32
|
+
`--install-missing` only after reviewing the pinned package identities and
|
|
33
|
+
granting that user-environment change for the current operation.
|
|
31
34
|
|
|
32
35
|
Setup reports three change scopes. Repository records are shared project
|
|
33
36
|
facts and history that must survive clones, so commit `.scipquery.json`,
|
|
@@ -37,7 +40,9 @@ For analyzer implementation work, follow [Regex Policy](REGEX_POLICY.md): regex
|
|
|
37
40
|
not commit `.codex/hooks.json` or `.claude/settings.local.json`; setup keeps
|
|
38
41
|
them out of Git through `.git/info/exclude`. User-environment changes install
|
|
39
42
|
skills or indexers for the current machine. Use `setup --guided` to answer
|
|
40
|
-
each repository, checkout, or user-scope question separately
|
|
43
|
+
each repository, checkout, or user-scope question separately; use
|
|
44
|
+
`setup --install-missing` for an explicit non-interactive installation
|
|
45
|
+
grant.
|
|
41
46
|
|
|
42
47
|
2. **Resolve blockers**
|
|
43
48
|
|
|
@@ -459,7 +464,18 @@ Numeric thresholds below are recommended starting points for review sessions; co
|
|
|
459
464
|
|
|
460
465
|
## Tips for AI Agents
|
|
461
466
|
|
|
462
|
-
- **Check freshness before
|
|
467
|
+
- **Check freshness once before the first graph claim in a work session**:
|
|
468
|
+
run `scip-query status --capabilities`, then reuse that generation until
|
|
469
|
+
source changes. After edits, let an active watcher or pending hook refresh
|
|
470
|
+
finish. Run `scip-query reindex` only when freshness is `stale`, `missing`,
|
|
471
|
+
or `unknown` and no responsible watcher is available.
|
|
472
|
+
- **Retrieve complete output**: an incomplete page is not evidence. Before
|
|
473
|
+
making a conclusion, changing to another evidence command, or reporting
|
|
474
|
+
completion, run every emitted `Continue exactly:` command unchanged until
|
|
475
|
+
`complete: true`. Never pipe scip-query through `head`, `tail`, or a
|
|
476
|
+
line-range `sed`. The universal `--output-cursor` pages the
|
|
477
|
+
rendered output; a result cursor such as `refs --cursor` advances logical
|
|
478
|
+
query coverage and is a separate obligation.
|
|
463
479
|
- **Use `--json` on `health`** for programmatic consumption — parse the JSON to make decisions
|
|
464
480
|
- **Run `change-surface` before every file modification** — it takes <1 second and prevents surprises
|
|
465
481
|
- **Run `diff-impact --json` before committing** — catches unexpected blast radius across downstream consumers
|