scip-query 0.19.1 → 0.19.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/README.md +18 -2
- package/dist/augment-vue-worker.js +1 -1
- package/dist/{chunk-FHLYJVXF.js → chunk-25LPM4DG.js} +2 -2
- package/dist/chunk-2CTX5CMX.js +4 -0
- package/dist/chunk-2Y373BDD.js +2 -0
- package/dist/{chunk-24ET4VLC.js → chunk-2YU7I3QO.js} +2 -2
- package/dist/{chunk-63P42UR6.js → chunk-3MJ5YA4Y.js} +2 -2
- package/dist/{chunk-ZNK6K3LB.js → chunk-3SVWW4PN.js} +2 -2
- package/dist/{chunk-WWCZCH7W.js → chunk-4333ETTV.js} +2 -2
- package/dist/{chunk-Q2WEWIKX.js → chunk-4RSI5EMG.js} +2 -2
- package/dist/{chunk-CIYUFF24.js → chunk-4SALD7RU.js} +2 -2
- package/dist/{chunk-DCDOGW32.js → chunk-4T3LTWUS.js} +2 -2
- package/dist/{chunk-34MLC6UI.js → chunk-4XTA5OMB.js} +2 -2
- package/dist/chunk-52ZYCAEO.js +2 -0
- package/dist/{chunk-SJ6XSCG7.js → chunk-54HA4ZXH.js} +2 -2
- package/dist/{chunk-J4MYRIYT.js → chunk-64RFXJT5.js} +2 -2
- package/dist/{chunk-FUFNRZFJ.js → chunk-6E7UTQY7.js} +2 -2
- package/dist/{chunk-PNESKY2Z.js → chunk-6NSFJYRC.js} +2 -2
- package/dist/{chunk-AOSFSYEA.js → chunk-7B3UPBVA.js} +2 -2
- package/dist/{chunk-XCPE3G75.js → chunk-7GXM52MI.js} +2 -2
- package/dist/{chunk-6O5JOS7T.js → chunk-A2EZV2UM.js} +2 -2
- package/dist/{chunk-4BU54UJG.js → chunk-ABMYA4TN.js} +2 -2
- package/dist/{chunk-64QITTX7.js → chunk-B5NLK2B3.js} +2 -2
- package/dist/{chunk-OLG2YPLS.js → chunk-BTEE5NZQ.js} +2 -2
- package/dist/{chunk-MP43RX4O.js → chunk-C7NIYIQ4.js} +1 -1
- package/dist/{chunk-AEM24WSF.js → chunk-CFMXJPHH.js} +2 -2
- package/dist/{chunk-JJZRS2OP.js → chunk-CNKAGUPL.js} +2 -2
- package/dist/{chunk-MQ2B33LQ.js → chunk-D4U5Q3FT.js} +2 -2
- package/dist/{chunk-YZXV3CU3.js → chunk-DGAGY7RJ.js} +1 -1
- package/dist/{chunk-FRXB74RQ.js → chunk-DLWR3NUU.js} +5 -5
- package/dist/{chunk-YGQBJUS6.js → chunk-DZ74OMG6.js} +2 -2
- package/dist/{chunk-APLNTJPJ.js → chunk-EOOJGLDU.js} +2 -2
- package/dist/{chunk-TYEGFDOP.js → chunk-F6O7AAC3.js} +2 -2
- package/dist/{chunk-HFBNIIZX.js → chunk-FECYOO5O.js} +2 -2
- package/dist/{chunk-V7J4A3AH.js → chunk-FWUUZTIO.js} +2 -2
- package/dist/{chunk-KMOMNTB4.js → chunk-GBQ5NYPR.js} +2 -2
- package/dist/{chunk-JBZXJXIS.js → chunk-GPBBJ5Y4.js} +2 -2
- package/dist/{chunk-OOUJBAKJ.js → chunk-H7UKLTWJ.js} +2 -2
- package/dist/{chunk-YILKXTIY.js → chunk-HEXVUYFQ.js} +2 -2
- package/dist/{chunk-J5XJWCB3.js → chunk-HKEHS2AS.js} +2 -2
- package/dist/{chunk-5TEUKVSM.js → chunk-I5AWSI2G.js} +2 -2
- package/dist/{chunk-XYBNOILR.js → chunk-I5RJM53C.js} +2 -2
- package/dist/{chunk-WCZAABYF.js → chunk-IG7N5ZIK.js} +2 -2
- package/dist/{chunk-C3KCSAQ4.js → chunk-IUFDSKGG.js} +2 -2
- package/dist/{chunk-OQ6TCHBB.js → chunk-IZKFSVBV.js} +2 -2
- package/dist/{chunk-5OZCNAVM.js → chunk-J77UIT3I.js} +2 -2
- package/dist/{chunk-B2WQKQKP.js → chunk-K2ERX4UT.js} +2 -2
- package/dist/{chunk-PYMZU5EG.js → chunk-KP6XRY5Z.js} +2 -2
- package/dist/{chunk-FC5K7T35.js → chunk-L7SPDE73.js} +1 -1
- package/dist/{chunk-DZXFZAZO.js → chunk-LBMJEAEW.js} +2 -2
- package/dist/chunk-LHMNRHGV.js +3 -0
- package/dist/{chunk-CKFMZE77.js → chunk-M7AIS73L.js} +2 -2
- package/dist/{chunk-53SUJOJA.js → chunk-M7MTH5NR.js} +2 -2
- package/dist/{chunk-6PKO2TNZ.js → chunk-MITTUCEH.js} +2 -2
- package/dist/chunk-MSWVMDAH.js +122 -0
- package/dist/chunk-NH5ALKPW.js +2 -0
- package/dist/{chunk-3WLRW5TC.js → chunk-NPKYOIFM.js} +3 -3
- package/dist/{chunk-GIHVWNKQ.js → chunk-NRCXJDHL.js} +2 -2
- package/dist/{chunk-5GOBZI34.js → chunk-NSS46APD.js} +2 -2
- package/dist/{chunk-HCS5LB6U.js → chunk-NZL2DBT7.js} +2 -2
- package/dist/{chunk-SYGAA54M.js → chunk-OMPZHGHO.js} +2 -2
- package/dist/{chunk-AGTATREV.js → chunk-P2PC2WGR.js} +2 -2
- package/dist/{chunk-CAKPEQZB.js → chunk-Q3AFUTGB.js} +2 -2
- package/dist/{chunk-ZJGZCBYT.js → chunk-Q4IIEGXJ.js} +2 -2
- package/dist/chunk-QDV6RDCP.js +4 -0
- package/dist/{chunk-FTRNGQGR.js → chunk-QGXBRIM5.js} +2 -2
- package/dist/{chunk-WXVGNFAO.js → chunk-QOKYJ33H.js} +1 -1
- package/dist/{chunk-FB6IKAKZ.js → chunk-QRGV2F7L.js} +2 -2
- package/dist/chunk-QVWS2VWZ.js +7 -0
- package/dist/{chunk-DFQNE73Y.js → chunk-R4FQGQ4X.js} +2 -2
- package/dist/{chunk-4CZJ4YJB.js → chunk-RV2FQIX3.js} +2 -2
- package/dist/{chunk-4FMT4HPC.js → chunk-S44IULR6.js} +2 -2
- package/dist/{chunk-LQUDSHLB.js → chunk-SOAT6NLA.js} +2 -2
- package/dist/{chunk-QHKXGMOI.js → chunk-STOL2BTL.js} +2 -2
- package/dist/chunk-SVLTAG5O.js +927 -0
- package/dist/{chunk-2WCXKANA.js → chunk-U6WNH5GC.js} +2 -2
- package/dist/chunk-U7DSEKOM.js +30 -0
- package/dist/{chunk-KMUFGAIK.js → chunk-UKZBVX4U.js} +2 -2
- package/dist/chunk-UOAV44HR.js +38 -0
- package/dist/chunk-V27BEQJN.js +7 -0
- package/dist/{chunk-VIKEPD4D.js → chunk-VGRICIQI.js} +2 -2
- package/dist/chunk-VMNZB6WI.js +4 -0
- package/dist/{chunk-LF5CIKWZ.js → chunk-VTKGCT3V.js} +5 -5
- package/dist/{chunk-WFRET75Z.js → chunk-VXQNNXJE.js} +2 -2
- package/dist/{chunk-V5WBVF6K.js → chunk-WER3B7MI.js} +2 -2
- package/dist/{chunk-SSXEYWN3.js → chunk-WQTAC523.js} +2 -2
- package/dist/{chunk-GAE7WCBK.js → chunk-X6D5IC6I.js} +2 -2
- package/dist/{chunk-FBUNGRKI.js → chunk-XLTP42QA.js} +2 -2
- package/dist/chunk-XTX6QHOF.js +4 -0
- package/dist/{chunk-AYRHVJXW.js → chunk-XYADIZHU.js} +5 -5
- package/dist/{chunk-WAU7HVDI.js → chunk-YGAGTIDK.js} +2 -2
- package/dist/{chunk-BMTBVMA3.js → chunk-YIJ7ZAA4.js} +3 -3
- package/dist/{chunk-BBBKPOIT.js → chunk-YNRNA5LK.js} +2 -2
- package/dist/{chunk-BCMOTIB6.js → chunk-YVVCVR2L.js} +2 -2
- package/dist/{chunk-RPEA7P5Z.js → chunk-ZAIILQNP.js} +3 -3
- package/dist/{chunk-7SGOWD2Y.js → chunk-ZGZUZ7XE.js} +2 -2
- package/dist/{chunk-YCSTKIYU.js → chunk-ZXJYMGD3.js} +2 -2
- package/dist/cli.js +2 -2
- package/dist/{command-descriptors-3EJHQLQZ.js → command-descriptors-MFU4BCJ7.js} +174 -167
- package/dist/{config-types-BA3xLCfG.d.ts → config-types-D20KuvvZ.d.ts} +67 -0
- package/dist/{db-CzA-9_rL.d.ts → db-G_II8yXU.d.ts} +1 -1
- package/dist/diff-gate-types-C9BoYwYD.d.ts +10 -0
- package/dist/direct-navigation-MRMQFIRB.js +3 -0
- package/dist/{health-DYy13GAe.d.ts → health-oblXYgkF.d.ts} +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/queries/affected.d.ts +2 -2
- package/dist/queries/affected.js +1 -1
- package/dist/queries/architecture.d.ts +86 -4
- package/dist/queries/architecture.js +1 -1
- package/dist/queries/bottlenecks.d.ts +2 -2
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.d.ts +2 -2
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +2 -2
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +2 -2
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.d.ts +2 -2
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.d.ts +2 -2
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +2 -2
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +2 -2
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +2 -2
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.d.ts +2 -2
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +2 -2
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +2 -2
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +2 -2
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.d.ts +2 -2
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.d.ts +2 -2
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/deep-chains.d.ts +2 -2
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/deps.d.ts +2 -2
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-gate.d.ts +3 -3
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.d.ts +4 -8
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +3 -3
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +2 -2
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.d.ts +2 -2
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/extract-candidates.d.ts +2 -2
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +2 -2
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +2 -2
- package/dist/queries/health.d.ts +3 -3
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +2 -2
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +2 -2
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +2 -2
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +3 -2
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +21 -5
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.d.ts +2 -2
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.d.ts +2 -2
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.d.ts +2 -2
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.d.ts +2 -2
- package/dist/queries/methods.js +1 -1
- package/dist/queries/not-implemented.d.ts +2 -2
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.d.ts +2 -2
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.d.ts +2 -2
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.d.ts +2 -2
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/react-component-duplicates.d.ts +2 -2
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.d.ts +2 -2
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.d.ts +2 -2
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.d.ts +2 -2
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +2 -2
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.d.ts +2 -2
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.d.ts +2 -2
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-chains.d.ts +2 -2
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.d.ts +2 -2
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.d.ts +2 -2
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +2 -2
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.d.ts +2 -2
- package/dist/queries/slice.js +1 -1
- package/dist/queries/stale-abstractions.d.ts +2 -2
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/stats.d.ts +2 -2
- package/dist/queries/surface.d.ts +2 -2
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.d.ts +2 -2
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.d.ts +2 -2
- package/dist/queries/system.js +1 -1
- package/dist/queries/test-quality.d.ts +2 -2
- package/dist/queries/test-quality.js +1 -1
- package/dist/queries/trace.d.ts +2 -2
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.d.ts +2 -2
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/twin-drift.d.ts +2 -2
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.d.ts +2 -2
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.d.ts +2 -2
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/vue-component-duplicates.d.ts +2 -2
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.d.ts +2 -2
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.d.ts +2 -2
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/queries/wrapper-candidates.d.ts +2 -2
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/reindex-worker.js +24 -24
- package/dist/reindex.d.ts +3 -3
- package/dist/reindex.js +38 -38
- package/dist/runtime.d.ts +9 -4
- package/dist/runtime.js +2 -2
- package/dist/rust-semantic-session-worker.js +1 -1
- package/dist/rust-semantic-worker.js +1 -1
- package/dist/{scip-cli-1bVKJgXi.d.ts → scip-cli-kRpaexVJ.d.ts} +1 -1
- package/dist/watch-server.js +5 -5
- package/docs/AI_FAILURE_MODES.md +1 -1
- package/docs/COMMAND_REFERENCE.md +1 -1
- package/docs/DETECTOR_GUIDE.md +1 -1
- package/docs/analyzer-inventory.md +1 -1
- package/docs/analyzer-validation-ledger.md +131 -1
- package/docs/architecture-coherence-vision.md +29 -0
- package/package.json +2 -2
- package/dist/chunk-2NA6TYP4.js +0 -120
- package/dist/chunk-5W2VAEVR.js +0 -4
- package/dist/chunk-7TJJY2C3.js +0 -2
- package/dist/chunk-DO775SYA.js +0 -2
- package/dist/chunk-DRH3AD7W.js +0 -4
- package/dist/chunk-E3KWOHH7.js +0 -5
- package/dist/chunk-EMIIOOTM.js +0 -38
- package/dist/chunk-ESNRT7QN.js +0 -927
- package/dist/chunk-IOOCKVUA.js +0 -6
- package/dist/chunk-KC2IFAAU.js +0 -3
- package/dist/chunk-NTOBQK5H.js +0 -4
- package/dist/chunk-UJKZQLDB.js +0 -2
- package/dist/chunk-US44MEVU.js +0 -29
- package/dist/chunk-XZXUMGAA.js +0 -7
- package/dist/diff-gate-types-CG2YQ_ei.d.ts +0 -4
- package/dist/direct-navigation-C2A44KFT.js +0 -3
package/dist/runtime.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { P as ProjectConfig, a as SupportedLanguage } from './config-types-
|
|
2
|
-
import { W as WatcherStatus, R as RefreshTrigger } from './scip-cli-
|
|
3
|
-
export { g as getScipVersion, i as isScipInstalled, p as printScipInstallInstructions } from './scip-cli-
|
|
1
|
+
import { P as ProjectConfig, a as SupportedLanguage } from './config-types-D20KuvvZ.js';
|
|
2
|
+
import { W as WatcherStatus, R as RefreshTrigger } from './scip-cli-kRpaexVJ.js';
|
|
3
|
+
export { g as getScipVersion, i as isScipInstalled, p as printScipInstallInstructions } from './scip-cli-kRpaexVJ.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Resolve all storage paths for a project's index files (cache dir, SQLite
|
|
@@ -32,7 +32,8 @@ interface WatcherOptions {
|
|
|
32
32
|
config: ProjectConfig;
|
|
33
33
|
languages?: SupportedLanguage[];
|
|
34
34
|
onStatus?: (status: WatcherStatus) => void;
|
|
35
|
-
onReindexComplete?: (durationMs: number) => void;
|
|
35
|
+
onReindexComplete?: (durationMs: number) => boolean | void;
|
|
36
|
+
onRefreshSuppressed?: (trigger: RefreshTrigger) => void;
|
|
36
37
|
onError?: (error: Error) => void;
|
|
37
38
|
}
|
|
38
39
|
/**
|
|
@@ -57,6 +58,7 @@ declare class Watcher {
|
|
|
57
58
|
private indexerConcurrency?;
|
|
58
59
|
private onStatus;
|
|
59
60
|
private onReindexComplete;
|
|
61
|
+
private onRefreshSuppressed;
|
|
60
62
|
private onError;
|
|
61
63
|
private status;
|
|
62
64
|
private debounceTimer;
|
|
@@ -67,6 +69,7 @@ declare class Watcher {
|
|
|
67
69
|
private reindexInFlight;
|
|
68
70
|
private lastReindexEnd;
|
|
69
71
|
private fsWatchers;
|
|
72
|
+
private sourcePollingFallbackStarted;
|
|
70
73
|
private gitPollTimer;
|
|
71
74
|
private lastGitState;
|
|
72
75
|
private gitignoreFilter;
|
|
@@ -81,6 +84,8 @@ declare class Watcher {
|
|
|
81
84
|
requestRefresh(trigger: RefreshTrigger, opts?: {
|
|
82
85
|
immediate?: boolean;
|
|
83
86
|
}): void;
|
|
87
|
+
private startSourceWatcher;
|
|
88
|
+
private handleSourceWatcherError;
|
|
84
89
|
private isIgnoredWatchPath;
|
|
85
90
|
private handleFileChange;
|
|
86
91
|
private relativeWatchPath;
|
package/dist/runtime.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{b as
|
|
2
|
-
`),t}import{fork as L}from"child_process";import{statSync as Y}from"fs";import{isAbsolute as K,join as B,relative as H}from"path";import{watch as z}from"chokidar";import X from"ignore";var S=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=T(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.gitignoreFilter=b(e.projectRoot),this.extraIgnore=X(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let e=z(this.projectRoot,{ignoreInitial:!0,ignored:(t,r)=>this.isIgnoredWatchPath(t,r?.isDirectory()??!1)});e.on("all",(t,r)=>{this.stopped||this.handleFileChange(r)}),e.on("error",t=>{this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}),this.fsWatchers.push(e)}catch(e){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}}stop(){this.stopped=!0;for(let e of this.fsWatchers)e.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(e,t={}){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=I(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}isIgnoredWatchPath(e,t){let r=this.relativeWatchPath(e);if(!r)return!1;let i=t?`${r}/`:r;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(e){let t=this.relativeWatchPath(e);!t||t===".."||t.startsWith("../")||t===".git"||t.startsWith(".git/")||this.gitignoreFilter.isIgnored(t)||this.extraIgnore.ignores(t)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=K(e)?e:B(this.projectRoot,e);return H(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=I(this.pendingTrigger,e),this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let t=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-e;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=Date.now();this.setStatus({state:"indexing",startedAt:r}),this.runReindex(t).then(i=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(i),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(e){return new Promise((t,r)=>{let i=Date.now(),o=y(this.projectRoot),n=Object.keys(o).length>0?o:this.config,c=m(this.projectRoot,n),a=n.indexer?.typescript,l=n.indexer?.clojure,p=L(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:c.indexPath,SCIP_REINDEX_OUTPUT_DB:c.dbPath,SCIP_REINDEX_LANGUAGES:(n.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(n.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:a?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:a?.projectMode??this.typescriptProjectMode,projects:a?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:e.kind,SCIP_REINDEX_TRIGGER_DETAIL:e.detail??""},stdio:"pipe"});p.on("exit",u=>{u===0?t(Date.now()-i):r(new Error(`Reindex worker exited with code ${u}`))}),p.on("error",r)})}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,t=this.readGitState();if(!e||!t||this.stopped){this.lastGitState=t;return}this.lastGitState=t;let r=e.head!==t.head,i=e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize;r&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):r?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:t.indexPath??"index changed"})}readGitState(){let e=f(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=x(this.projectRoot,e),r={head:f(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=Y(t);r.indexMtimeMs=i.mtimeMs,r.indexSize=i.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function I(s,e){return s?s.kind===e.kind?s.detail===e.detail?s:{kind:s.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${s.kind}, ${e.kind}`}:e}import{existsSync as v,mkdirSync as J,symlinkSync as V,readlinkSync as A,unlinkSync as $,readdirSync as Q}from"fs";import{join as h,dirname as w,resolve as d,relative as Z,isAbsolute as ee}from"path";import{homedir as C,platform as te}from"os";import{fileURLToPath as re}from"url";var ie=te()==="win32",_=["_shared","scip-query","scip-setup","scip-calibrate","scip-cleanup-audit","scip-cleanup-improve","scip-integrity-audit","scip-twin-drift","scip-claim-audit","scip-probe-reachability","scip-hyper-optimization","scip-api-impact","scip-concrete-plan","scip-conductor","scip-debug","scip-explore","scip-root-cause","scip-triage-issue","scip-diagram","scip-doc-reconcile","scip-directory-architecture","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook","scip-tla-model-system"];function se(s={}){let e=s.quiet?()=>{}:console.log,t=re(import.meta.url),r=d(w(t),"..","skills"),i=[h(C(),".claude","skills"),h(C(),".codex","skills"),h(C(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let n of i){let c=w(n);if(!v(c))continue;J(n,{recursive:!0});let a=ae(n);ne(n,r,a,o,e);for(let l of _){let p=h(r,l),u=h(n,l);if(!v(p)){o.skipped.push(`${a}/${l}`);continue}if(v(u)){try{let M=A(u);if(d(M)===d(p)){o.alreadyLinked.push(`${a}/${l}`),e(` ok: ${l} \u2192 ${a} (already linked)`);continue}}catch{o.skipped.push(`${a}/${l}`),e(` skip: ${l} \u2192 ${a} (exists, not a symlink)`);continue}$(u)}V(p,u,ie?"junction":"dir"),o.installed.push(`${a}/${l}`),e(` done: ${l} \u2192 ${a}`)}}return o}function ne(s,e,t,r,i){let o=new Set(_);for(let n of Q(s)){if(o.has(n))continue;let c=h(s,n),a;try{a=d(w(c),A(c))}catch{continue}oe(a,e)&&($(c),r.pruned.push(`${t}/${n}`),i(` prune: ${n} \u2192 ${t} (removed stale scip-query skill link)`))}}function oe(s,e){let t=Z(d(e),d(s));return t===""||!t.startsWith("..")&&!ee(t)}function ae(s){return s.includes(".codex")?"Codex":s.includes(".agents")?"Agents":"Claude"}export{S as Watcher,D as getScipVersion,q as initProjectConfig,se as installSkills,O as isScipInstalled,y as loadProjectConfig,N as printScipInstallInstructions,m as resolveIndexStoragePaths};
|
|
1
|
+
import{b as D,c as N,d as F,f as m,l as y}from"./chunk-V27BEQJN.js";import{a as R}from"./chunk-DGAGY7RJ.js";import{e as f,f as x}from"./chunk-LM72NQ7T.js";import{readFileSync as W,writeFileSync as G,existsSync as P}from"fs";import{isAbsolute as he,join as E,relative as de,resolve as ge}from"path";var g=".scipquery.json",k=250,j=0,T=10*6e4,U={enabled:!1,debounceMs:k,cooldownMs:j,gitPollMs:2e3,idleTimeoutMs:T,autoRefresh:!0,ignore:[]},q=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"];var fe=new Set(q);function S(s){let e=E(s,g);if(!P(e))return{};try{let t=W(e,"utf-8");return JSON.parse(t)}catch(t){let r=t instanceof Error?t.message:String(t);throw t instanceof SyntaxError?new Error(`invalid ${g} at ${e}: ${r}`,{cause:t}):new Error(`unable to read ${g} at ${e}: ${r}`,{cause:t})}}function I(s){return{...U,...s.watch}}function L(s,e){let t=E(s,g);return P(t)||G(t,JSON.stringify({languages:e,watch:{enabled:!0,debounceMs:k,cooldownMs:j,gitPollMs:2e3,idleTimeoutMs:T,autoRefresh:!0}},null,2)+`
|
|
2
|
+
`),t}import{fork as Y}from"child_process";import{statSync as K}from"fs";import{isAbsolute as B,join as H,relative as z}from"path";import{watch as X}from"chokidar";import J from"ignore";var v=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onRefreshSuppressed;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=I(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onRefreshSuppressed=e.onRefreshSuppressed??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.gitignoreFilter=R(e.projectRoot),this.extraIgnore=J(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(e){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}}stop(){this.stopped=!0;for(let e of this.fsWatchers)e.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(e,t={}){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=$(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}startSourceWatcher(e=!1){let t=X(this.projectRoot,{ignoreInitial:!0,ignored:(r,i)=>this.isIgnoredWatchPath(r,i?.isDirectory()??!1),usePolling:e,...e?{interval:500,binaryInterval:1e3}:{}});t.on("all",(r,i)=>{this.stopped||this.handleFileChange(i)}),t.on("error",r=>this.handleSourceWatcherError(t,r,e)),this.fsWatchers.push(t)}handleSourceWatcherError(e,t,r){if(r||this.sourcePollingFallbackStarted||!V(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 r=this.relativeWatchPath(e);if(!r)return!1;let i=t?`${r}/`:r;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(e){let t=this.relativeWatchPath(e);!t||t===".."||t.startsWith("../")||t===".git"||t.startsWith(".git/")||this.gitignoreFilter.isIgnored(t)||this.extraIgnore.ignores(t)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||t.endsWith(m)||t.endsWith(`${m}.previous`)||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=B(e)?e:H(this.projectRoot,e);return z(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=$(this.pendingTrigger,e),this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let t=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-e;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let r=Date.now();this.setStatus({state:"indexing",startedAt:r}),this.runReindex(t).then(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now();let o=!1;try{o=this.onReindexComplete(i)===!0}catch(n){this.onError(n instanceof Error?n:new Error(String(n)))}if(this.dirty&&!this.stopped){if(o){let c=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(c),this.setStatus({state:"idle"});return}let n=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:n,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(e){return new Promise((t,r)=>{let i=Date.now(),o=S(this.projectRoot),n=Object.keys(o).length>0?o:this.config,c=y(this.projectRoot,n),a=n.indexer?.typescript,l=n.indexer?.clojure,p=Y(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:c.indexPath,SCIP_REINDEX_OUTPUT_DB:c.dbPath,SCIP_REINDEX_LANGUAGES:(n.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(n.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:a?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:a?.projectMode??this.typescriptProjectMode,projects:a?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:e.kind,SCIP_REINDEX_TRIGGER_DETAIL:e.detail??""},stdio:"pipe"});p.on("exit",u=>{u===0?t(Date.now()-i):r(new Error(`Reindex worker exited with code ${u}`))}),p.on("error",r)})}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,t=this.readGitState();if(!e||!t||this.stopped){this.lastGitState=t;return}this.lastGitState=t;let r=e.head!==t.head,i=e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize;r&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):r?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:t.indexPath??"index changed"})}readGitState(){let e=f(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=x(this.projectRoot,e),r={head:f(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=K(t);r.indexMtimeMs=i.mtimeMs,r.indexSize=i.size}catch{r.indexMtimeMs=void 0,r.indexSize=void 0}return r}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function $(s,e){return s?s.kind===e.kind?s.detail===e.detail?s:{kind:s.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${s.kind}, ${e.kind}`}:e}function V(s){return s instanceof Error&&"code"in s&&s.code==="EMFILE"||String(s).includes("EMFILE: too many open files")}import{existsSync as C,mkdirSync as Q,symlinkSync as Z,readlinkSync as A,unlinkSync as _,readdirSync as ee}from"fs";import{join as h,dirname as b,resolve as d,relative as te,isAbsolute as re}from"path";import{homedir as w,platform as ie}from"os";import{fileURLToPath as se}from"url";var ne=ie()==="win32",M=["_shared","scip-query","scip-setup","scip-calibrate","scip-cleanup-audit","scip-cleanup-improve","scip-integrity-audit","scip-twin-drift","scip-claim-audit","scip-probe-reachability","scip-hyper-optimization","scip-api-impact","scip-concrete-plan","scip-conductor","scip-debug","scip-explore","scip-root-cause","scip-triage-issue","scip-diagram","scip-doc-reconcile","scip-directory-architecture","scip-maintainability","scip-react-maintainability","scip-vue-maintainability","scip-verify","scip-language-playbook","scip-tla-model-system"];function oe(s={}){let e=s.quiet?()=>{}:console.log,t=se(import.meta.url),r=d(b(t),"..","skills"),i=[h(w(),".claude","skills"),h(w(),".codex","skills"),h(w(),".agents","skills")],o={installed:[],skipped:[],alreadyLinked:[],pruned:[]};for(let n of i){let c=b(n);if(!C(c))continue;Q(n,{recursive:!0});let a=ce(n);ae(n,r,a,o,e);for(let l of M){let p=h(r,l),u=h(n,l);if(!C(p)){o.skipped.push(`${a}/${l}`);continue}if(C(u)){try{let O=A(u);if(d(O)===d(p)){o.alreadyLinked.push(`${a}/${l}`),e(` ok: ${l} \u2192 ${a} (already linked)`);continue}}catch{o.skipped.push(`${a}/${l}`),e(` skip: ${l} \u2192 ${a} (exists, not a symlink)`);continue}_(u)}Z(p,u,ne?"junction":"dir"),o.installed.push(`${a}/${l}`),e(` done: ${l} \u2192 ${a}`)}}return o}function ae(s,e,t,r,i){let o=new Set(M);for(let n of ee(s)){if(o.has(n))continue;let c=h(s,n),a;try{a=d(b(c),A(c))}catch{continue}le(a,e)&&(_(c),r.pruned.push(`${t}/${n}`),i(` prune: ${n} \u2192 ${t} (removed stale scip-query skill link)`))}}function le(s,e){let t=te(d(e),d(s));return t===""||!t.startsWith("..")&&!re(t)}function ce(s){return s.includes(".codex")?"Codex":s.includes(".agents")?"Agents":"Claude"}export{v as Watcher,N as getScipVersion,L as initProjectConfig,oe as installSkills,D as isScipInstalled,S as loadProjectConfig,F as printScipInstallInstructions,y as resolveIndexStoragePaths};
|
|
3
3
|
//# sourceMappingURL=runtime.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as ue,B as de,C as b,D as S,a as A,b as q,c as ee,d as ne,e as te,f as ie,g as se,h as F,i as G,j as N,k as E,l as B,n as j,o as H,p as U,q as W,r as re,u as ae,v as oe,w as le,x as ce,y as k}from"./chunk-MQ2B33LQ.js";import{a as O,f as d,g as D}from"./chunk-HGFDYOVB.js";import _ from"process";import{existsSync as pe,readFileSync as we,writeFileSync as Pe}from"fs";import{isAbsolute as De,resolve as K}from"path";import{performance as L}from"perf_hooks";import{parentPort as ke}from"worker_threads";var be="SCIP_RUST_SEMANTIC_REFERENCE_TASK_PROFILE_MS",Se="SCIP_RUST_SEMANTIC_CALLEE_TASK_PROFILE_MS",P=new Map,fe=Promise.resolve();ke?.on("message",e=>{fe=fe.then(()=>Te(e)).catch(()=>{})});async function Te(e){if(e.kind==="shutdown"){await We(),g(e.responsePath,{ok:!0},e.sharedBuffer);return}if(e.kind==="import-definitions"){try{let t=await ze(e.request);g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}catch(t){let i=B(t);if(i){g(e.responsePath,i,e.sharedBuffer);return}let n={available:!1,reason:t instanceof Error?t.message:String(t),sourcePaths:e.request.positions.map(r=>[r.id,null])};g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}return}try{let t=await ve(e.request);g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}catch(t){let i=B(t);if(i){g(e.responsePath,i,e.sharedBuffer);return}let n=ye(e.request,t instanceof Error?t.message:String(t));g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}}async function ze(e){let t={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=await d("rust.semantic.worker.session",()=>Re(e.projectRoot,e.rustAnalyzerBinary,[e.file],{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs}),()=>({kind:"import-definitions",files:1,positions:e.positions.length}));if(!i.capabilities.definitionProvider)return{available:!1,reason:"rust-analyzer initialized without textDocument/definition support.",sourcePaths:e.positions.map(o=>[o.id,null])};let n=0;await E(()=>d("rust.semantic.worker.open-source-documents",async()=>{n=await Ae(i,e.projectRoot,[e.file],{diagnosticsTimeoutMs:e.diagnosticsTimeoutMs,settleDelayMs:e.settleDelayMs,readinessDeadlineMs:e.readinessDeadlineMs})},()=>({files:1,openedDocuments:n,positions:e.positions.length})),()=>ge(P,i,e.readinessDeadlineMs));let r=0;return{available:!0,sourcePaths:await d("rust.semantic.worker.import-definitions",()=>S(e.positions,e.concurrency??8,async o=>{let c=await i.client.definition({textDocument:{uri:A(e.projectRoot,o.file)},position:{line:o.line,character:o.column}},t),f=Fe(e.projectRoot,c);return f&&(r+=1),[o.id,f]}),()=>({positions:e.positions.length,resolvedPositions:r,concurrency:e.concurrency??8}))}}async function ve(e){let t={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=e.includeReferences!==!1,n=e.includeCallees===!0,r=e.includeSignatures===!0,a=j(e),o=H(e),c=U(e),f=W(e),l=await d("rust.semantic.worker.session",()=>Ie(e),()=>({kind:"semantic",definitions:f.length,referenceDefinitions:a.length,calleeDefinitions:o.length,signatureDefinitions:c.length,references:i,callees:n,signatures:r})),p=Ee(l.capabilities,{references:i,callees:n,signatures:r});if(p)return ye(e,p);let u=0;await E(()=>d("rust.semantic.worker.open-definition-documents",async()=>{u=await Ce(l,e)},()=>({definitions:f.length,openedDocuments:u})),()=>ge(P,l,e.readinessDeadlineMs));let m=0,M=0,y=O(),J=y?new Map:null,T=y?me(_.env[be]):null,V=()=>i?d("rust.semantic.worker.references",()=>S(a,e.concurrency??8,async s=>{let w=y?L.now():0,h=await ue(l.client,ee(e.projectRoot,s,!1),{requestTimeoutMs:e.requestTimeoutMs,retryTimeoutMs:e.referenceRetryTimeoutMs,deadlineMs:e.readinessDeadlineMs}),R=te(ne(e.projectRoot,h.locations)),C=y?Math.round(L.now()-w):0;return _e(J,s.relativePath,{durationMs:C,references:R.length,hasReferences:R.length>0,slow:T!==null&&C>=T}),T!==null&&C>=T&&D({type:"span",name:"rust.semantic.worker.reference-task",durationMs:C,ok:!0,symbolId:s.symbolId,relativePath:s.relativePath,leaf:s.leaf,kind:s.kind,startLine:s.startLine,endLine:s.endLine,references:R.length,complete:h.complete}),R.length>0&&(M+=1),m+=R.length,{symbolId:s.symbolId,references:R,complete:h.complete}}),()=>({definitions:a.length,concurrency:e.concurrency??8,definitionsWithReferences:M,references:m})):Promise.resolve(a.map(s=>({symbolId:s.symbolId,references:[],complete:!0}))),Q=0,X=0,z=O(),Y=z?new Map:null,v=z?me(_.env[Se]):null,Z=()=>n?d("rust.semantic.worker.callees",()=>S(o,e.concurrency??8,async s=>{let w=z?L.now():0,h=await de(l.client,e.projectRoot,s,t),R=z?Math.round(L.now()-w):0;return Ge(Y,s.relativePath,{durationMs:R,callees:h.length,hasCallees:h.length>0,slow:v!==null&&R>=v}),v!==null&&R>=v&&D({type:"span",name:"rust.semantic.worker.callee-task",durationMs:R,ok:!0,symbolId:s.symbolId,relativePath:s.relativePath,leaf:s.leaf,kind:s.kind,startLine:s.startLine,endLine:s.endLine,callees:h.length}),h.length>0&&(X+=1),Q+=h.length,{symbolId:s.symbolId,callees:h}}),()=>({definitions:o.length,concurrency:e.concurrency??8,definitionsWithCallees:X,callees:Q})):Promise.resolve([]),I,x;i&&n&&a.length>0&&o.length>0&&je()?[I,x]=await Promise.all([V(),Z()]):(I=await V(),x=await Z()),xe(J),Ne(Y);let $=0,Me=r?await d("rust.semantic.worker.signatures",()=>S(c,e.concurrency??8,async s=>{let w=await re(l.client,e.projectRoot,s,t);return w&&($+=1),{symbolId:s.symbolId,signature:w}}),()=>({definitions:c.length,concurrency:e.concurrency??8,signaturesFound:$})):[];return{available:!0,references:I.filter(s=>s.complete).map(s=>[s.symbolId,s.references]),incompleteReferenceSymbolIds:I.filter(s=>!s.complete).map(s=>s.symbolId),...n?{callees:x.map(s=>[s.symbolId,s.callees])}:{},...r?{signatures:Me.map(s=>[s.symbolId,s.signature])}:{}}}async function Ie(e){return Re(e.projectRoot,e.rustAnalyzerBinary,W(e).map(t=>t.relativePath),{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs})}async function Re(e,t,i,n){let r=le(e,i.map(M=>({relativePath:M}))),a=oe(e,r),o=Le(t,a,r),c=P.get(o);if(c)return c;let f=ae(r),l=new ie(se(t,a),{requestTimeoutMs:n.requestTimeoutMs,configuration:f}),p=n.readinessDeadlineMs===void 0?null:{afterGeneration:l.serverStatusGeneration(),deadlineMs:n.readinessDeadlineMs},u=await E(()=>d("rust.semantic.worker.initialize",()=>l.initialize({processId:_.pid,rootUri:A(a,"."),capabilities:{textDocument:{references:{dynamicRegistration:!1},definition:{dynamicRegistration:!1},callHierarchy:{dynamicRegistration:!1},hover:{dynamicRegistration:!1}}},initializationOptions:f},{timeoutMs:n.requestTimeoutMs,deadlineMs:n.readinessDeadlineMs}),()=>({linkedProjects:r.length,relativePaths:i.length})),()=>l.shutdown({deadlineMs:n.readinessDeadlineMs}).catch(()=>{})),m={key:o,client:l,capabilities:u.capabilities,openedPaths:new Set,initializationReadiness:p};return P.set(o,m),m}async function Ce(e,t){let i=W(t).filter(l=>e.openedPaths.has(l.relativePath)?!1:pe(K(t.projectRoot,l.relativePath)));if(i.length===0)return await he(e),0;let n=e.initializationReadiness,r=t.readinessDeadlineMs===void 0?null:{statusSnapshot:n?null:e.client.serverStatusSnapshot(),initializationGeneration:n?.afterGeneration,deadlineMs:t.readinessDeadlineMs},a=ce(e.client,t.projectRoot,i);for(let l of i)e.openedPaths.add(l.relativePath);let o=t.diagnosticsTimeoutMs??1e4,c=o;await d("rust.semantic.worker.diagnostics",()=>r?N(l=>(c=l,k(e.client,a,l)),o,r.deadlineMs):k(e.client,a,o),()=>({openedDocuments:a.length,timeoutMs:c}));let f=t.settleDelayMs??5e3;if(!r)await d("rust.semantic.worker.settle",()=>b(f),()=>({openedDocuments:a.length,settleDelayMs:f}));else{let l;await d("rust.semantic.worker.readiness",async()=>{let p=m=>d("rust.semantic.worker.settle",()=>b(m),()=>({openedDocuments:a.length,settleDelayMs:m})),u=r.initializationGeneration===void 0?await G(e.client,r.statusSnapshot,a.length,r.deadlineMs,f,Date.now,p):await F(e.client,r.initializationGeneration,a.length,r.deadlineMs,f,Date.now,p);r.initializationGeneration!==void 0&&(e.initializationReadiness=null),l=u?.health},()=>({phase:r.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:a.length,health:l}))}return a.length}async function Ae(e,t,i,n){let r=i.filter(u=>e.openedPaths.has(u)?!1:pe(K(t,u)));if(r.length===0)return await he(e),0;let a=e.initializationReadiness,o=n.readinessDeadlineMs===void 0?null:{statusSnapshot:a?null:e.client.serverStatusSnapshot(),initializationGeneration:a?.afterGeneration,deadlineMs:n.readinessDeadlineMs},c=[];for(let u of r){let m=A(t,u);e.client.didOpenTextDocument({uri:m,languageId:"rust",version:1,text:we(K(t,u),"utf8")}),e.openedPaths.add(u),c.push(m)}let f=n.diagnosticsTimeoutMs??1e4,l=f;await d("rust.semantic.worker.diagnostics",()=>o?N(u=>(l=u,k(e.client,c,u)),f,o.deadlineMs):k(e.client,c,f),()=>({openedDocuments:c.length,timeoutMs:l}));let p=n.settleDelayMs??5e3;if(!o)await d("rust.semantic.worker.settle",()=>b(p),()=>({openedDocuments:c.length,settleDelayMs:p}));else{let u;await d("rust.semantic.worker.readiness",async()=>{let m=y=>d("rust.semantic.worker.settle",()=>b(y),()=>({openedDocuments:c.length,settleDelayMs:y})),M=o.initializationGeneration===void 0?await G(e.client,o.statusSnapshot,c.length,o.deadlineMs,p,Date.now,m):await F(e.client,o.initializationGeneration,c.length,o.deadlineMs,p,Date.now,m);o.initializationGeneration!==void 0&&(e.initializationReadiness=null),u=M?.health},()=>({phase:o.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:c.length,health:u}))}return c.length}async function he(e){let t=e.initializationReadiness;if(!t)return;let i;await d("rust.semantic.worker.readiness",async()=>{i=(await F(e.client,t.afterGeneration,0,t.deadlineMs,0)).health,e.initializationReadiness=null},()=>({phase:"initialize",openedDocuments:0,health:i}))}function Fe(e,t){for(let i of t){let n=q(e,i.uri);if(!(!n||n===".."||n.startsWith("../")||De(n)))return n}return null}function Ee(e,t){return t.references&&!e.referencesProvider?"rust-analyzer initialized without textDocument/references support.":t.callees&&!e.callHierarchyProvider?"rust-analyzer initialized without call hierarchy support.":t.signatures&&!e.hoverProvider?"rust-analyzer initialized without hover support.":null}function ye(e,t){let i=j(e),n=H(e),r=U(e);return{available:!1,reason:t,references:i.map(a=>[a.symbolId,[]]),...e.includeCallees?{callees:n.map(a=>[a.symbolId,[]])}:{},...e.includeSignatures?{signatures:r.map(a=>[a.symbolId,null])}:{}}}async function We(){let e=[...P.values()];P.clear(),await Promise.all(e.map(t=>t.client.shutdown().catch(()=>{})))}async function ge(e,t,i){e.get(t.key)===t&&e.delete(t.key),await t.client.shutdown({deadlineMs:i}).catch(()=>{})}function Le(e,t,i){return JSON.stringify({binary:e,sessionRoot:t,linkedProjects:i})}function _e(e,t,i){if(!e)return;let n=Oe(e,t);n.definitions+=1,i.hasReferences&&(n.definitionsWithReferences+=1),n.references+=i.references,n.durationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs),i.slow&&(n.slowTasks+=1)}function xe(e){if(!e)return;let t=[...e.entries()].sort(([i,n],[r,a])=>a.durationMs-n.durationMs||i.localeCompare(r));for(let[i,n]of t)D({type:"span",name:"rust.semantic.worker.references.by-file",durationMs:n.durationMs,ok:!0,relativePath:i,definitions:n.definitions,definitionsWithReferences:n.definitionsWithReferences,references:n.references,maxDurationMs:n.maxDurationMs,slowTasks:n.slowTasks,aggregate:"sum-task-duration"})}function Oe(e,t){let i=e.get(t);if(i)return i;let n={definitions:0,definitionsWithReferences:0,references:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(t,n),n}function Ge(e,t,i){if(!e)return;let n=Be(e,t);n.definitions+=1,i.hasCallees&&(n.definitionsWithCallees+=1),n.callees+=i.callees,n.durationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs),i.slow&&(n.slowTasks+=1)}function Ne(e){if(!e)return;let t=[...e.entries()].sort(([i,n],[r,a])=>a.durationMs-n.durationMs||i.localeCompare(r));for(let[i,n]of t)D({type:"span",name:"rust.semantic.worker.callees.by-file",durationMs:n.durationMs,ok:!0,relativePath:i,definitions:n.definitions,definitionsWithCallees:n.definitionsWithCallees,callees:n.callees,maxDurationMs:n.maxDurationMs,slowTasks:n.slowTasks,aggregate:"sum-task-duration"})}function Be(e,t){let i=e.get(t);if(i)return i;let n={definitions:0,definitionsWithCallees:0,callees:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(t,n),n}function me(e){if(e===void 0||e==="")return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}function je(){let e=_.env.SCIP_RUST_SEMANTIC_PARALLEL_OPERATIONS;return e!=="0"&&e!=="false"}function g(e,t,i){Pe(e,JSON.stringify(t));let n=new Int32Array(i);Atomics.store(n,0,1),Atomics.notify(n,0)}export{ge as discardRustAnalyzerSession};
|
|
1
|
+
import{A as ue,B as de,C as b,D as S,a as q,b as ee,c as A,d as G,e as N,f as F,g as B,h as E,i as ne,j as te,k as ie,l as se,n as j,o as H,p as U,q as W,r as re,u as ae,v as oe,w as le,x as ce,y as k}from"./chunk-D4U5Q3FT.js";import{a as O,f as d,g as D}from"./chunk-HGFDYOVB.js";import _ from"process";import{existsSync as pe,readFileSync as we,writeFileSync as Pe}from"fs";import{isAbsolute as De,resolve as K}from"path";import{performance as L}from"perf_hooks";import{parentPort as ke}from"worker_threads";var be="SCIP_RUST_SEMANTIC_REFERENCE_TASK_PROFILE_MS",Se="SCIP_RUST_SEMANTIC_CALLEE_TASK_PROFILE_MS",P=new Map,fe=Promise.resolve();ke?.on("message",e=>{fe=fe.then(()=>Te(e)).catch(()=>{})});async function Te(e){if(e.kind==="shutdown"){await We(),g(e.responsePath,{ok:!0},e.sharedBuffer);return}if(e.kind==="import-definitions"){try{let t=await ze(e.request);g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}catch(t){let i=B(t);if(i){g(e.responsePath,i,e.sharedBuffer);return}let n={available:!1,reason:t instanceof Error?t.message:String(t),sourcePaths:e.request.positions.map(r=>[r.id,null])};g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}return}try{let t=await ve(e.request);g(e.responsePath,{ok:!0,response:t},e.sharedBuffer)}catch(t){let i=B(t);if(i){g(e.responsePath,i,e.sharedBuffer);return}let n=ye(e.request,t instanceof Error?t.message:String(t));g(e.responsePath,{ok:!0,response:n},e.sharedBuffer)}}async function ze(e){let t={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=await d("rust.semantic.worker.session",()=>Re(e.projectRoot,e.rustAnalyzerBinary,[e.file],{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs}),()=>({kind:"import-definitions",files:1,positions:e.positions.length}));if(!i.capabilities.definitionProvider)return{available:!1,reason:"rust-analyzer initialized without textDocument/definition support.",sourcePaths:e.positions.map(o=>[o.id,null])};let n=0;await F(()=>d("rust.semantic.worker.open-source-documents",async()=>{n=await Ae(i,e.projectRoot,[e.file],{diagnosticsTimeoutMs:e.diagnosticsTimeoutMs,settleDelayMs:e.settleDelayMs,readinessDeadlineMs:e.readinessDeadlineMs})},()=>({files:1,openedDocuments:n,positions:e.positions.length})),()=>ge(P,i,e.readinessDeadlineMs));let r=0;return{available:!0,sourcePaths:await d("rust.semantic.worker.import-definitions",()=>S(e.positions,e.concurrency??8,async o=>{let c=await i.client.definition({textDocument:{uri:E(e.projectRoot,o.file)},position:{line:o.line,character:o.column}},t),f=Fe(e.projectRoot,c);return f&&(r+=1),[o.id,f]}),()=>({positions:e.positions.length,resolvedPositions:r,concurrency:e.concurrency??8}))}}async function ve(e){let t={timeoutMs:e.requestTimeoutMs,deadlineMs:e.readinessDeadlineMs},i=e.includeReferences!==!1,n=e.includeCallees===!0,r=e.includeSignatures===!0,a=j(e),o=H(e),c=U(e),f=W(e),l=await d("rust.semantic.worker.session",()=>Ie(e),()=>({kind:"semantic",definitions:f.length,referenceDefinitions:a.length,calleeDefinitions:o.length,signatureDefinitions:c.length,references:i,callees:n,signatures:r})),p=Ee(l.capabilities,{references:i,callees:n,signatures:r});if(p)return ye(e,p);let u=0;await F(()=>d("rust.semantic.worker.open-definition-documents",async()=>{u=await Ce(l,e)},()=>({definitions:f.length,openedDocuments:u})),()=>ge(P,l,e.readinessDeadlineMs));let m=0,M=0,y=O(),J=y?new Map:null,T=y?me(_.env[be]):null,V=()=>i?d("rust.semantic.worker.references",()=>S(a,e.concurrency??8,async s=>{let w=y?L.now():0,h=await ue(l.client,te(e.projectRoot,s,!1),{requestTimeoutMs:e.requestTimeoutMs,retryTimeoutMs:e.referenceRetryTimeoutMs,deadlineMs:e.readinessDeadlineMs}),R=se(ie(e.projectRoot,h.locations)),C=y?Math.round(L.now()-w):0;return _e(J,s.relativePath,{durationMs:C,references:R.length,hasReferences:R.length>0,slow:T!==null&&C>=T}),T!==null&&C>=T&&D({type:"span",name:"rust.semantic.worker.reference-task",durationMs:C,ok:!0,symbolId:s.symbolId,relativePath:s.relativePath,leaf:s.leaf,kind:s.kind,startLine:s.startLine,endLine:s.endLine,references:R.length,complete:h.complete}),R.length>0&&(M+=1),m+=R.length,{symbolId:s.symbolId,references:R,complete:h.complete}}),()=>({definitions:a.length,concurrency:e.concurrency??8,definitionsWithReferences:M,references:m})):Promise.resolve(a.map(s=>({symbolId:s.symbolId,references:[],complete:!0}))),Q=0,X=0,z=O(),Y=z?new Map:null,v=z?me(_.env[Se]):null,Z=()=>n?d("rust.semantic.worker.callees",()=>S(o,e.concurrency??8,async s=>{let w=z?L.now():0,h=await de(l.client,e.projectRoot,s,t),R=z?Math.round(L.now()-w):0;return Ge(Y,s.relativePath,{durationMs:R,callees:h.length,hasCallees:h.length>0,slow:v!==null&&R>=v}),v!==null&&R>=v&&D({type:"span",name:"rust.semantic.worker.callee-task",durationMs:R,ok:!0,symbolId:s.symbolId,relativePath:s.relativePath,leaf:s.leaf,kind:s.kind,startLine:s.startLine,endLine:s.endLine,callees:h.length}),h.length>0&&(X+=1),Q+=h.length,{symbolId:s.symbolId,callees:h}}),()=>({definitions:o.length,concurrency:e.concurrency??8,definitionsWithCallees:X,callees:Q})):Promise.resolve([]),I,x;i&&n&&a.length>0&&o.length>0&&je()?[I,x]=await Promise.all([V(),Z()]):(I=await V(),x=await Z()),xe(J),Ne(Y);let $=0,Me=r?await d("rust.semantic.worker.signatures",()=>S(c,e.concurrency??8,async s=>{let w=await re(l.client,e.projectRoot,s,t);return w&&($+=1),{symbolId:s.symbolId,signature:w}}),()=>({definitions:c.length,concurrency:e.concurrency??8,signaturesFound:$})):[];return{available:!0,references:I.filter(s=>s.complete).map(s=>[s.symbolId,s.references]),incompleteReferenceSymbolIds:I.filter(s=>!s.complete).map(s=>s.symbolId),...n?{callees:x.map(s=>[s.symbolId,s.callees])}:{},...r?{signatures:Me.map(s=>[s.symbolId,s.signature])}:{}}}async function Ie(e){return Re(e.projectRoot,e.rustAnalyzerBinary,W(e).map(t=>t.relativePath),{requestTimeoutMs:e.requestTimeoutMs,readinessDeadlineMs:e.readinessDeadlineMs})}async function Re(e,t,i,n){let r=le(e,i.map(M=>({relativePath:M}))),a=oe(e,r),o=Le(t,a,r),c=P.get(o);if(c)return c;let f=ae(r),l=new q(ee(t,a),{requestTimeoutMs:n.requestTimeoutMs,configuration:f}),p=n.readinessDeadlineMs===void 0?null:{afterGeneration:l.serverStatusGeneration(),deadlineMs:n.readinessDeadlineMs},u=await F(()=>d("rust.semantic.worker.initialize",()=>l.initialize({processId:_.pid,rootUri:E(a,"."),capabilities:{textDocument:{references:{dynamicRegistration:!1},definition:{dynamicRegistration:!1},callHierarchy:{dynamicRegistration:!1},hover:{dynamicRegistration:!1}}},initializationOptions:f},{timeoutMs:n.requestTimeoutMs,deadlineMs:n.readinessDeadlineMs}),()=>({linkedProjects:r.length,relativePaths:i.length})),()=>l.shutdown({deadlineMs:n.readinessDeadlineMs}).catch(()=>{})),m={key:o,client:l,capabilities:u.capabilities,openedPaths:new Set,initializationReadiness:p};return P.set(o,m),m}async function Ce(e,t){let i=W(t).filter(l=>e.openedPaths.has(l.relativePath)?!1:pe(K(t.projectRoot,l.relativePath)));if(i.length===0)return await he(e),0;let n=e.initializationReadiness,r=t.readinessDeadlineMs===void 0?null:{statusSnapshot:n?null:e.client.serverStatusSnapshot(),initializationGeneration:n?.afterGeneration,deadlineMs:t.readinessDeadlineMs},a=ce(e.client,t.projectRoot,i);for(let l of i)e.openedPaths.add(l.relativePath);let o=t.diagnosticsTimeoutMs??1e4,c=o;await d("rust.semantic.worker.diagnostics",()=>r?N(l=>(c=l,k(e.client,a,l)),o,r.deadlineMs):k(e.client,a,o),()=>({openedDocuments:a.length,timeoutMs:c}));let f=t.settleDelayMs??5e3;if(!r)await d("rust.semantic.worker.settle",()=>b(f),()=>({openedDocuments:a.length,settleDelayMs:f}));else{let l;await d("rust.semantic.worker.readiness",async()=>{let p=m=>d("rust.semantic.worker.settle",()=>b(m),()=>({openedDocuments:a.length,settleDelayMs:m})),u=r.initializationGeneration===void 0?await G(e.client,r.statusSnapshot,a.length,r.deadlineMs,f,Date.now,p):await A(e.client,r.initializationGeneration,a.length,r.deadlineMs,f,Date.now,p);r.initializationGeneration!==void 0&&(e.initializationReadiness=null),l=u?.health},()=>({phase:r.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:a.length,health:l}))}return a.length}async function Ae(e,t,i,n){let r=i.filter(u=>e.openedPaths.has(u)?!1:pe(K(t,u)));if(r.length===0)return await he(e),0;let a=e.initializationReadiness,o=n.readinessDeadlineMs===void 0?null:{statusSnapshot:a?null:e.client.serverStatusSnapshot(),initializationGeneration:a?.afterGeneration,deadlineMs:n.readinessDeadlineMs},c=[];for(let u of r){let m=E(t,u);e.client.didOpenTextDocument({uri:m,languageId:"rust",version:1,text:we(K(t,u),"utf8")}),e.openedPaths.add(u),c.push(m)}let f=n.diagnosticsTimeoutMs??1e4,l=f;await d("rust.semantic.worker.diagnostics",()=>o?N(u=>(l=u,k(e.client,c,u)),f,o.deadlineMs):k(e.client,c,f),()=>({openedDocuments:c.length,timeoutMs:l}));let p=n.settleDelayMs??5e3;if(!o)await d("rust.semantic.worker.settle",()=>b(p),()=>({openedDocuments:c.length,settleDelayMs:p}));else{let u;await d("rust.semantic.worker.readiness",async()=>{let m=y=>d("rust.semantic.worker.settle",()=>b(y),()=>({openedDocuments:c.length,settleDelayMs:y})),M=o.initializationGeneration===void 0?await G(e.client,o.statusSnapshot,c.length,o.deadlineMs,p,Date.now,m):await A(e.client,o.initializationGeneration,c.length,o.deadlineMs,p,Date.now,m);o.initializationGeneration!==void 0&&(e.initializationReadiness=null),u=M?.health},()=>({phase:o.initializationGeneration===void 0?"didOpen":"initialize+didOpen",openedDocuments:c.length,health:u}))}return c.length}async function he(e){let t=e.initializationReadiness;if(!t)return;let i;await d("rust.semantic.worker.readiness",async()=>{i=(await A(e.client,t.afterGeneration,0,t.deadlineMs,0)).health,e.initializationReadiness=null},()=>({phase:"initialize",openedDocuments:0,health:i}))}function Fe(e,t){for(let i of t){let n=ne(e,i.uri);if(!(!n||n===".."||n.startsWith("../")||De(n)))return n}return null}function Ee(e,t){return t.references&&!e.referencesProvider?"rust-analyzer initialized without textDocument/references support.":t.callees&&!e.callHierarchyProvider?"rust-analyzer initialized without call hierarchy support.":t.signatures&&!e.hoverProvider?"rust-analyzer initialized without hover support.":null}function ye(e,t){let i=j(e),n=H(e),r=U(e);return{available:!1,reason:t,references:i.map(a=>[a.symbolId,[]]),...e.includeCallees?{callees:n.map(a=>[a.symbolId,[]])}:{},...e.includeSignatures?{signatures:r.map(a=>[a.symbolId,null])}:{}}}async function We(){let e=[...P.values()];P.clear(),await Promise.all(e.map(t=>t.client.shutdown().catch(()=>{})))}async function ge(e,t,i){e.get(t.key)===t&&e.delete(t.key),await t.client.shutdown({deadlineMs:i}).catch(()=>{})}function Le(e,t,i){return JSON.stringify({binary:e,sessionRoot:t,linkedProjects:i})}function _e(e,t,i){if(!e)return;let n=Oe(e,t);n.definitions+=1,i.hasReferences&&(n.definitionsWithReferences+=1),n.references+=i.references,n.durationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs),i.slow&&(n.slowTasks+=1)}function xe(e){if(!e)return;let t=[...e.entries()].sort(([i,n],[r,a])=>a.durationMs-n.durationMs||i.localeCompare(r));for(let[i,n]of t)D({type:"span",name:"rust.semantic.worker.references.by-file",durationMs:n.durationMs,ok:!0,relativePath:i,definitions:n.definitions,definitionsWithReferences:n.definitionsWithReferences,references:n.references,maxDurationMs:n.maxDurationMs,slowTasks:n.slowTasks,aggregate:"sum-task-duration"})}function Oe(e,t){let i=e.get(t);if(i)return i;let n={definitions:0,definitionsWithReferences:0,references:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(t,n),n}function Ge(e,t,i){if(!e)return;let n=Be(e,t);n.definitions+=1,i.hasCallees&&(n.definitionsWithCallees+=1),n.callees+=i.callees,n.durationMs+=i.durationMs,n.maxDurationMs=Math.max(n.maxDurationMs,i.durationMs),i.slow&&(n.slowTasks+=1)}function Ne(e){if(!e)return;let t=[...e.entries()].sort(([i,n],[r,a])=>a.durationMs-n.durationMs||i.localeCompare(r));for(let[i,n]of t)D({type:"span",name:"rust.semantic.worker.callees.by-file",durationMs:n.durationMs,ok:!0,relativePath:i,definitions:n.definitions,definitionsWithCallees:n.definitionsWithCallees,callees:n.callees,maxDurationMs:n.maxDurationMs,slowTasks:n.slowTasks,aggregate:"sum-task-duration"})}function Be(e,t){let i=e.get(t);if(i)return i;let n={definitions:0,definitionsWithCallees:0,callees:0,durationMs:0,maxDurationMs:0,slowTasks:0};return e.set(t,n),n}function me(e){if(e===void 0||e==="")return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}function je(){let e=_.env.SCIP_RUST_SEMANTIC_PARALLEL_OPERATIONS;return e!=="0"&&e!=="false"}function g(e,t,i){Pe(e,JSON.stringify(t));let n=new Int32Array(i);Atomics.store(n,0,1),Atomics.notify(n,0)}export{ge as discardRustAnalyzerSession};
|
|
2
2
|
//# sourceMappingURL=rust-semantic-session-worker.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as o,B as p,C as q,D as r,m as a,n as b,o as c,p as d,q as e,r as f,s as g,t as h,u as i,v as j,w as k,x as l,y as m,z as n}from"./chunk-
|
|
1
|
+
import{A as o,B as p,C as q,D as r,m as a,n as b,o as c,p as d,q as e,r as f,s as g,t as h,u as i,v as j,w as k,x as l,y as m,z as n}from"./chunk-D4U5Q3FT.js";export{p as calleesForDefinition,k as cargoManifestsForDefinitions,h as hoverToRustSignature,g as hoverWithRetry,l as openDefinitionDocuments,o as referencesWithCompletion,n as referencesWithRetry,a as runRustAnalyzerReferenceBatch,r as runWithConcurrency,i as rustAnalyzerInitializationOptions,j as rustAnalyzerSessionRoot,c as rustRequestCalleeDefinitions,b as rustRequestReferenceDefinitions,e as rustRequestSessionDefinitions,d as rustRequestSignatureDefinitions,f as signatureForDefinition,q as sleep,m as waitForOpenedDocuments};
|
|
2
2
|
//# sourceMappingURL=rust-semantic-worker.js.map
|
package/dist/watch-server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as Et,B as Q,C as Ft,D as At,E as je,G as H,H as Lt,I as le,J as de,K as pe,L as Nt,N as jt,O as _e,P as _t,Q as Ot,U as Oe,V as Wt,W as $t,X as B,a as ft,b as mt,c as ht,d as De,e as gt,f as Ee,g as yt,ga as Gt,h as St,i as vt,ja as We,k as Fe,l as Ae,m as xt,n as It,p as Rt,pa as qt,q as Ct,r as wt,ra as Ut,s as Mt,sa as fe,t as kt,ta as Ht,u as Pt,ua as Bt,va as Vt,w as Tt,x as Dt,y as Le,z as Ne}from"./chunk-2NA6TYP4.js";import{b as dt,c as pt,f as bt,h as J,l as U,m as ue}from"./chunk-MP43RX4O.js";import{a as j,b as F}from"./chunk-KHE7J5ZN.js";import{a as ce,c as ut,d as Te,e as N}from"./chunk-HGFDYOVB.js";import P from"process";import{rmSync as Yr}from"fs";import{resolve as ro}from"path";import{pathToFileURL as no}from"url";import{readFileSync as Xr,writeFileSync as mo,existsSync as Zr}from"fs";import{isAbsolute as go,join as en,relative as yo,resolve as So}from"path";var $e=".scipquery.json",tn=250,rn=0,nn=10*6e4,on={enabled:!1,debounceMs:tn,cooldownMs:rn,gitPollMs:2e3,idleTimeoutMs:nn,autoRefresh:!0,ignore:[]},sn=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"];var bo=new Set(sn);function V(r){let e=en(r,$e);if(!Zr(e))return{};try{let t=Xr(e,"utf-8");return JSON.parse(t)}catch(t){let n=t instanceof Error?t.message:String(t);throw t instanceof SyntaxError?new Error(`invalid ${$e} at ${e}: ${n}`,{cause:t}):new Error(`unable to read ${$e} at ${e}: ${n}`,{cause:t})}}function me(r){return{...on,...r.watch}}import{existsSync as Kt,readFileSync as an}from"fs";function Ge(r,e,t){let n=new Date().toISOString();if(!Kt(t.dbPath))return{state:"missing",checkedAt:n,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Kt(t.metaPath))return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=JSON.parse(an(t.metaPath,"utf-8")),o=e.languages??Ot(r),a=cn(r,o,e),s=Array.isArray(i.indexedLanguages)?[...i.indexedLanguages].sort():[],c=(i.version===2||i.version===3)&&i.status==="complete"&&JSON.stringify(i.fingerprint)===JSON.stringify(a)&&JSON.stringify(s)===JSON.stringify(a.languages),l=Gt(t.dbPath,t.metaPath),d=l.state==="invalid"||l.state==="drifted",p=c&&!d;return{state:p?"fresh":"stale",checkedAt:n,metaPath:t.metaPath,updatedAt:i.updatedAt,lastRefresh:i.lastRefresh,reason:d?`SQLite generation requires repair: ${l.reason}`:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:p?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function cn(r,e,t){return bt(r,e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{fork as ln}from"child_process";import{statSync as dn}from"fs";import{isAbsolute as pn,join as un,relative as fn}from"path";import{watch as mn}from"chokidar";import hn from"ignore";var he=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=me(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.gitignoreFilter=ue(e.projectRoot),this.extraIgnore=hn(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let e=mn(this.projectRoot,{ignoreInitial:!0,ignored:(t,n)=>this.isIgnoredWatchPath(t,n?.isDirectory()??!1)});e.on("all",(t,n)=>{this.stopped||this.handleFileChange(n)}),e.on("error",t=>{this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}),this.fsWatchers.push(e)}catch(e){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}}stop(){this.stopped=!0;for(let e of this.fsWatchers)e.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(e,t={}){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=zt(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}isIgnoredWatchPath(e,t){let n=this.relativeWatchPath(e);if(!n)return!1;let i=t?`${n}/`:n;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(e){let t=this.relativeWatchPath(e);!t||t===".."||t.startsWith("../")||t===".git"||t.startsWith(".git/")||this.gitignoreFilter.isIgnored(t)||this.extraIgnore.ignores(t)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=pn(e)?e:un(this.projectRoot,e);return fn(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=zt(this.pendingTrigger,e),this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let t=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-e;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex(t).then(i=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(i),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(e){return new Promise((t,n)=>{let i=Date.now(),o=V(this.projectRoot),a=Object.keys(o).length>0?o:this.config,s=B(this.projectRoot,a),c=a.indexer?.typescript,l=a.indexer?.clojure,d=ln(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:s.indexPath,SCIP_REINDEX_OUTPUT_DB:s.dbPath,SCIP_REINDEX_LANGUAGES:(a.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(a.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:e.kind,SCIP_REINDEX_TRIGGER_DETAIL:e.detail??""},stdio:"pipe"});d.on("exit",p=>{p===0?t(Date.now()-i):n(new Error(`Reindex worker exited with code ${p}`))}),d.on("error",n)})}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,t=this.readGitState();if(!e||!t||this.stopped){this.lastGitState=t;return}this.lastGitState=t;let n=e.head!==t.head,i=e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize;n&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):n?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:t.indexPath??"index changed"})}readGitState(){let e=De(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=gt(this.projectRoot,e),n={head:De(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=dn(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function zt(r,e){return r?r.kind===e.kind?r.detail===e.detail?r:{kind:r.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${r.kind}, ${e.kind}`}:e}import{existsSync as er,statSync as In}from"fs";import{join as Rn}from"path";import{createHash as gn}from"crypto";import{readFileSync as yn}from"fs";import{dirname as Sn,join as ge}from"path";var X=2,bn="typescript-semantic";function Jt(r){let e=ge(r,bn);return{rootDir:e,requestDir:ge(e,"requests"),responseDir:ge(e,"responses")}}function Z(r){try{let e=JSON.parse(yn(ge(Sn(r),"meta.json"),"utf8"));return e.version!==2&&e.version!==3||typeof e.status!="string"||typeof e.updatedAt!="string"||e.fingerprint===void 0?null:gn("sha256").update(JSON.stringify({version:e.version,status:e.status,updatedAt:e.updatedAt,fingerprint:e.fingerprint,indexedLanguages:e.indexedLanguages})).digest("hex")}catch{return null}}function Qt(r){let e=JSON.parse(r);if(e.protocolVersion!==X||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||e.profileEnvironment!==void 0&&!vn(e.profileEnvironment)||!e.request||!xn(e.request))throw new Error("TypeScript semantic service received an invalid mailbox request.");return e}function vn(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&Object.values(r).every(e=>typeof e=="string"||e===null)}function xn(r){if(!r||typeof r!="object"||!("kind"in r))return!1;let e=r;switch(e.kind){case"availability":return!0;case"import-usage":return typeof e.file=="string";case"reference-fragments":return Et(e.files)!==null;case"references":return Yt(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return Yt(e.definitions);case"signature":return Xt(e.definition);default:return!1}}function Yt(r){return Array.isArray(r)&&r.every(Xt)}function Xt(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.symbolId=="number"&&typeof e.documentId=="number"&&typeof e.symbol=="string"&&typeof e.relativePath=="string"&&typeof e.leaf=="string"&&typeof e.startLine=="number"&&typeof e.endLine=="number"}function Cn(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var Zt;function wn(r=Cn(),e=void 0){if(e===void 0&&Zt?.projectRoot===r)return Zt;let t=V(r),n=B(r,t),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:r,config:t,paths:n,dbPath:i,dbPathSource:"env",gitContext:e};if(er(n.dbPath))return{projectRoot:r,config:t,paths:n,dbPath:n.dbPath,dbPathSource:"configured",gitContext:e};let o=Rn(r,"index.db");return{projectRoot:r,config:t,paths:n,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:Mn(o,n.dbPath),gitContext:e}}function tr(r,e={}){let{config:t,paths:n,dbPath:i,dbPathSource:o,rootFallbackWarning:a,gitContext:s}=wn(r);if(!er(i))throw new Error("No index.db found. Run: scip-query reindex");e.warnOnRootFallback&&o==="root-fallback"&&a&&console.error(a);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:r,sharedEvidenceDbPath:We(r,t,s),entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality,architecture:t.architecture,coverageContracts:t.coverageContracts,docs:t.docs},l=ue(r);return new vt(c,l)}function Mn(r,e){let t="unknown time";try{t=In(r).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${r}, modified ${t}) because the configured index was not found at ${e}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}import{mkdirSync as Pr,readFileSync as Tr,readdirSync as wi,rmSync as Mi}from"fs";import{resolve as Ie}from"path";import{resolve as kr}from"path";import{performance as y}from"perf_hooks";function ye(r){return{forFile(e,t){return rr(r,e,t)},forFiles(e,t){let n=new Map;for(let i of e)n.set(i,rr(r,i,t));return n}}}function rr(r,e,t){let n={file:e},i=t.facts||t.identifiers;if(t.text&&(n.text=Ct(r,e)),t.lines&&(n.lines=wt(r,e)),t.ast&&(n.ast=Mt(r,e)),t.imports&&(n.imports=At(r,e)),t.reexports&&(n.reexports=Ft(r,e)),i){let o=kt(r,e),a=o.facts;t.facts&&(n.facts=a),o.unavailable&&(n.sourceFactsUnavailable=o.unavailable),t.identifiers&&a&&(n.identifiers=a.fileIdentifiers,n.identifierLineMap=a.identifierLineMap)}return n}var kn={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function Se(r){if(r.startsWith("local "))return{kind:"local",id:r.slice(6),raw:r};let e=r.split(" ");if(e.length<4)return{scheme:e[0]??"",manager:e[1]??"",packageName:e[2]??"",version:"",descriptors:[],raw:r};let t=e[0],n=e[1],i=r.slice(t.length+1+n.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let a,s=i.indexOf(" ");s===-1?(a=i,i=""):(a=i.slice(0,s),i=i.slice(s+1));let c=Pn(i);return{scheme:t,manager:n,packageName:o,version:a,descriptors:c,raw:r}}function K(r){let e=Se(r);if("kind"in e)return null;for(let t=e.descriptors.length-2;t>=0;t--){let n=e.descriptors[t];if(n?.suffix==="type")return n.name}return null}function Pn(r){let e=[],t=0;for(;t<r.length;){if(r[t]==="["){let o=r.indexOf("]",t+1);if(o===-1){e.push({name:r.slice(t+1),suffix:"type-param"});break}e.push({name:r.slice(t+1,o),suffix:"type-param"}),t=o+1;continue}if(r[t]==="("&&(e.length===0||t===0||nr(r[t-1]))){let o=r.indexOf(")",t+1);if(o!==-1&&r[o+1]!=="."){e.push({name:r.slice(t+1,o),suffix:"parameter"}),t=o+1;continue}}let n;if(r[t]==="`"){let o=r.indexOf("`",t+1);if(o===-1){n=r.slice(t+1),e.push({name:n,suffix:"term"});break}n=r.slice(t+1,o),t=o+1}else{let o=t;for(;t<r.length&&!nr(r[t]);)t++;n=r.slice(o,t)}if(t>=r.length){n&&e.push({name:n,suffix:"term"});break}let i=r[t];if(i==="("){let o=r.indexOf(")",t+1);o!==-1&&r[o+1]==="."?(e.push({name:n,suffix:"method"}),t=o+2):o!==-1?(e.push({name:n,suffix:"method"}),t=o+1):(e.push({name:n,suffix:"term"}),t++)}else{let o=kn[i];o&&e.push({name:n,suffix:o}),t+=1}}return e}function nr(r){return r==="/"||r==="#"||r==="."||r==="("||r==="["||r===":"||r==="!"}function _(r){let e=Se(r);if("kind"in e&&e.kind==="local")return e.id;let t=e;return t.descriptors.length===0?"":t.descriptors[t.descriptors.length-1].name}function O(r){let e=Se(r);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function ir(r){let e=O(r);return e==="method"?!0:e!=="term"?!1:r.endsWith("().")?!0:r.startsWith("rust-analyzer ")&&r.includes("#")?!1:r.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(r):!0}function Tn(r,e={}){if(K(r.symbol)!==null)return e.includeClassMemberFallbacks===!0;let i=(r.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function or(r,e,t={}){let n=new Map;for(let o of e)r.length>0&&!Tn(o,{includeClassMemberFallbacks:t.includeClassMemberFallbacks})||n.set(o.id,o);for(let o of r)n.set(o.id,o);let i=[...n.values()];return t.sort?i.sort((o,a)=>o.start_line-a.start_line||o.end_line-a.end_line||o.symbol.localeCompare(a.symbol)):i}var Dn=J("file-definitions",{clearGroups:["definition-catalog"]}),ys=J("file-function-like-definitions",{clearGroups:["definition-catalog"]});function W(r,e,t={}){return t.includeClassMemberFallbacks?sr(r,e,void 0,{includeClassMemberFallbacks:!0}):Dn.get(r,e,()=>{let n=En(r,e);if(n)return n;let i=sr(r,e),o=Ae(r),a=ye(r).forFile(e,{text:!0}).text;return o&&a&&cr.write(r,e,Fe(r,e,a),{projectFingerprint:o,definitions:i.map(s=>({...s}))}),i})}var cr=It({kind:"file-definitions",invalidation:Rt("file-definitions"),serialize:Fn,deserialize:An});function En(r,e){let t=Ae(r);if(!t)return null;let n=ye(r).forFile(e,{text:!0}).text;if(!n)return null;let i=cr.read(r,e,Fe(r,e,n));return i?Ln(i,t,e):null}function Fn(r){return JSON.stringify(r)}function An(r){try{let e=JSON.parse(r);return!Ne(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function Ln(r,e,t){if(r.projectFingerprint!==e)return null;let n=[];for(let i of r.definitions){let o=Nn(i,t);if(!o)return null;n.push(o)}return n}function Nn(r,e){return!Ne(r)||typeof r.symbolId!="number"||typeof r.symbol!="string"||typeof r.documentId!="number"||typeof r.startLine!="number"||typeof r.startChar!="number"&&r.startChar!==void 0||typeof r.endLine!="number"||typeof r.endChar!="number"&&r.endChar!==void 0||r.relativePath!==e||typeof r.leaf!="string"||typeof r.parentTypeName!="string"&&r.parentTypeName!==null||typeof r.isFunctionLike!="boolean"||typeof r.isTypeLike!="boolean"||typeof r.kind!="number"&&r.kind!==null||typeof r.documentation!="string"&&r.documentation!==null||typeof r.enclosingSymbol!="string"&&r.enclosingSymbol!==null?null:{symbolId:r.symbolId,symbol:r.symbol,documentId:r.documentId,startLine:r.startLine,startChar:r.startChar,endLine:r.endLine,endChar:r.endChar,relativePath:r.relativePath,leaf:r.leaf,parentTypeName:r.parentTypeName,isFunctionLike:r.isFunctionLike,isTypeLike:r.isTypeLike,kind:r.kind,documentation:r.documentation,enclosingSymbol:r.enclosingSymbol}}function sr(r,e,t,n={}){let i=or(jn(r,e),_n(r,e),{sort:!0,includeClassMemberFallbacks:n.includeClassMemberFallbacks}).map(On);return t&&(i=i.filter(t)),$n(r,e,i)}function jn(r,e){return r.all(`SELECT
|
|
1
|
+
import{A as At,Aa as me,B as Lt,C as Nt,D as jt,E as le,F as de,G as _t,I as Ot,J as _e,K as Wt,L as $t,P as Oe,S as Gt,T as pe,U as We,V as qt,W as Ut,X as H,a as gt,b as yt,c as St,d as Ee,e as bt,f as Fe,g as vt,ga as Ht,h as xt,i as Rt,ja as $e,k as Ae,l as Le,m as Ct,n as Mt,p as wt,pa as Bt,r as kt,ra as Vt,s as Pt,sa as fe,t as Ne,ta as Kt,u as je,ua as zt,v as Tt,va as Yt,w as Dt,wa as Ge,x as Et,y as Q,ya as B,z as Ft,za as Jt}from"./chunk-MSWVMDAH.js";import{b as ft,c as mt,f as It,h as J,l as U,m as ue}from"./chunk-C7NIYIQ4.js";import{a as j,b as F}from"./chunk-KHE7J5ZN.js";import{a as ce,c as ht,d as De,e as N}from"./chunk-HGFDYOVB.js";import k from"process";import{rmSync as Zr}from"fs";import{resolve as ao}from"path";import{pathToFileURL as co}from"url";import{readFileSync as rn,writeFileSync as bo,existsSync as nn}from"fs";import{isAbsolute as xo,join as on,relative as Io,resolve as Ro}from"path";var qe=".scipquery.json",sn=250,an=0,cn=10*6e4,ln={enabled:!1,debounceMs:sn,cooldownMs:an,gitPollMs:2e3,idleTimeoutMs:cn,autoRefresh:!0,ignore:[]},dn=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"];var Co=new Set(dn);function V(r){let e=on(r,qe);if(!nn(e))return{};try{let t=rn(e,"utf-8");return JSON.parse(t)}catch(t){let n=t instanceof Error?t.message:String(t);throw t instanceof SyntaxError?new Error(`invalid ${qe} at ${e}: ${n}`,{cause:t}):new Error(`unable to read ${qe} at ${e}: ${n}`,{cause:t})}}function he(r){return{...ln,...r.watch}}import{existsSync as Qt,readFileSync as un}from"fs";function Ue(r,e,t){let n=new Date().toISOString();if(!Qt(t.dbPath))return{state:"missing",checkedAt:n,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Qt(t.metaPath))return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=JSON.parse(un(t.metaPath,"utf-8")),o=e.languages??$t(r),a=pn(r,o,e),s=Array.isArray(i.indexedLanguages)?[...i.indexedLanguages].sort():[],c=(i.version===2||i.version===3)&&i.status==="complete"&&JSON.stringify(i.fingerprint)===JSON.stringify(a)&&JSON.stringify(s)===JSON.stringify(a.languages),l=Ht(t.dbPath,t.metaPath),d=l.state==="invalid"||l.state==="drifted",u=c&&!d;return{state:u?"fresh":"stale",checkedAt:n,metaPath:t.metaPath,updatedAt:i.updatedAt,lastRefresh:i.lastRefresh,reason:d?`SQLite generation requires repair: ${l.reason}`:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:u?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function pn(r,e,t){return It(r,e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{fork as fn}from"child_process";import{statSync as mn}from"fs";import{isAbsolute as hn,join as gn,relative as yn}from"path";import{watch as Sn}from"chokidar";import bn from"ignore";var ge=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onRefreshSuppressed;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=he(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onRefreshSuppressed=e.onRefreshSuppressed??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.gitignoreFilter=ue(e.projectRoot),this.extraIgnore=bn(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(e){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}}stop(){this.stopped=!0;for(let e of this.fsWatchers)e.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(e,t={}){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=Xt(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}startSourceWatcher(e=!1){let t=Sn(this.projectRoot,{ignoreInitial:!0,ignored:(n,i)=>this.isIgnoredWatchPath(n,i?.isDirectory()??!1),usePolling:e,...e?{interval:500,binaryInterval:1e3}:{}});t.on("all",(n,i)=>{this.stopped||this.handleFileChange(i)}),t.on("error",n=>this.handleSourceWatcherError(t,n,e)),this.fsWatchers.push(t)}handleSourceWatcherError(e,t,n){if(n||this.sourcePollingFallbackStarted||!vn(t)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(i=>i!==e),e.close();try{this.startSourceWatcher(!0)}catch(i){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(i)}`))}}isIgnoredWatchPath(e,t){let n=this.relativeWatchPath(e);if(!n)return!1;let i=t?`${n}/`:n;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(e){let t=this.relativeWatchPath(e);!t||t===".."||t.startsWith("../")||t===".git"||t.startsWith(".git/")||this.gitignoreFilter.isIgnored(t)||this.extraIgnore.ignores(t)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||t.endsWith(Oe)||t.endsWith(`${Oe}.previous`)||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=hn(e)?e:gn(this.projectRoot,e);return yn(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=Xt(this.pendingTrigger,e),this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let t=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-e;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex(t).then(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now();let o=!1;try{o=this.onReindexComplete(i)===!0}catch(a){this.onError(a instanceof Error?a:new Error(String(a)))}if(this.dirty&&!this.stopped){if(o){let s=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(s),this.setStatus({state:"idle"});return}let a=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(e){return new Promise((t,n)=>{let i=Date.now(),o=V(this.projectRoot),a=Object.keys(o).length>0?o:this.config,s=H(this.projectRoot,a),c=a.indexer?.typescript,l=a.indexer?.clojure,d=fn(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:s.indexPath,SCIP_REINDEX_OUTPUT_DB:s.dbPath,SCIP_REINDEX_LANGUAGES:(a.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(a.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:e.kind,SCIP_REINDEX_TRIGGER_DETAIL:e.detail??""},stdio:"pipe"});d.on("exit",u=>{u===0?t(Date.now()-i):n(new Error(`Reindex worker exited with code ${u}`))}),d.on("error",n)})}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,t=this.readGitState();if(!e||!t||this.stopped){this.lastGitState=t;return}this.lastGitState=t;let n=e.head!==t.head,i=e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize;n&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):n?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:t.indexPath??"index changed"})}readGitState(){let e=Ee(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=bt(this.projectRoot,e),n={head:Ee(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=mn(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function Xt(r,e){return r?r.kind===e.kind?r.detail===e.detail?r:{kind:r.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${r.kind}, ${e.kind}`}:e}function vn(r){return r instanceof Error&&"code"in r&&r.code==="EMFILE"||String(r).includes("EMFILE: too many open files")}import{existsSync as ir,statSync as kn}from"fs";import{join as Pn}from"path";import{createHash as xn}from"crypto";import{readFileSync as In}from"fs";import{dirname as Rn,join as ye}from"path";var X=2,Cn="typescript-semantic";function er(r){let e=ye(r,Cn);return{rootDir:e,requestDir:ye(e,"requests"),responseDir:ye(e,"responses")}}function Z(r){try{let e=JSON.parse(In(ye(Rn(r),"meta.json"),"utf8"));return e.version!==2&&e.version!==3||typeof e.status!="string"||typeof e.updatedAt!="string"||e.fingerprint===void 0?null:xn("sha256").update(JSON.stringify({version:e.version,status:e.status,updatedAt:e.updatedAt,fingerprint:e.fingerprint,indexedLanguages:e.indexedLanguages})).digest("hex")}catch{return null}}function tr(r){let e=JSON.parse(r);if(e.protocolVersion!==X||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||e.profileEnvironment!==void 0&&!Mn(e.profileEnvironment)||!e.request||!wn(e.request))throw new Error("TypeScript semantic service received an invalid mailbox request.");return e}function Mn(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&Object.values(r).every(e=>typeof e=="string"||e===null)}function wn(r){if(!r||typeof r!="object"||!("kind"in r))return!1;let e=r;switch(e.kind){case"availability":return!0;case"import-usage":return typeof e.file=="string";case"reference-fragments":return Tt(e.files)!==null;case"references":return Zt(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return Zt(e.definitions);case"signature":return rr(e.definition);default:return!1}}function Zt(r){return Array.isArray(r)&&r.every(rr)}function rr(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.symbolId=="number"&&typeof e.documentId=="number"&&typeof e.symbol=="string"&&typeof e.relativePath=="string"&&typeof e.leaf=="string"&&typeof e.startLine=="number"&&typeof e.endLine=="number"}function Tn(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var nr;function Dn(r=Tn(),e=void 0){if(e===void 0&&nr?.projectRoot===r)return nr;let t=V(r),n=H(r,t),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:r,config:t,paths:n,dbPath:i,dbPathSource:"env",gitContext:e};if(ir(n.dbPath))return{projectRoot:r,config:t,paths:n,dbPath:n.dbPath,dbPathSource:"configured",gitContext:e};let o=Pn(r,"index.db");return{projectRoot:r,config:t,paths:n,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:En(o,n.dbPath),gitContext:e}}function or(r,e={}){let{config:t,paths:n,dbPath:i,dbPathSource:o,rootFallbackWarning:a,gitContext:s}=Dn(r);if(!ir(i))throw new Error("No index.db found. Run: scip-query reindex");e.warnOnRootFallback&&o==="root-fallback"&&a&&console.error(a);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:r,sharedEvidenceDbPath:$e(r,t,s),entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality,architecture:t.architecture,coverageContracts:t.coverageContracts,docs:t.docs},l=ue(r);return new Rt(c,l)}function En(r,e){let t="unknown time";try{t=kn(r).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${r}, modified ${t}) because the configured index was not found at ${e}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}import{mkdirSync as Fr,readFileSync as Ar,readdirSync as Di,rmSync as Ei}from"fs";import{resolve as Re}from"path";import{resolve as Er}from"path";import{performance as y}from"perf_hooks";function Se(r){return{forFile(e,t){return sr(r,e,t)},forFiles(e,t){let n=new Map;for(let i of e)n.set(i,sr(r,i,t));return n}}}function sr(r,e,t){let n={file:e},i=t.facts||t.identifiers;if(t.text&&(n.text=Dt(r,e)),t.lines&&(n.lines=Et(r,e)),t.ast&&(n.ast=Ft(r,e)),t.imports&&(n.imports=jt(r,e)),t.reexports&&(n.reexports=Nt(r,e)),i){let o=At(r,e),a=o.facts;t.facts&&(n.facts=a),o.unavailable&&(n.sourceFactsUnavailable=o.unavailable),t.identifiers&&a&&(n.identifiers=a.fileIdentifiers,n.identifierLineMap=a.identifierLineMap)}return n}var Fn={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function be(r){if(r.startsWith("local "))return{kind:"local",id:r.slice(6),raw:r};let e=r.split(" ");if(e.length<4)return{scheme:e[0]??"",manager:e[1]??"",packageName:e[2]??"",version:"",descriptors:[],raw:r};let t=e[0],n=e[1],i=r.slice(t.length+1+n.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let a,s=i.indexOf(" ");s===-1?(a=i,i=""):(a=i.slice(0,s),i=i.slice(s+1));let c=An(i);return{scheme:t,manager:n,packageName:o,version:a,descriptors:c,raw:r}}function K(r){let e=be(r);if("kind"in e)return null;for(let t=e.descriptors.length-2;t>=0;t--){let n=e.descriptors[t];if(n?.suffix==="type")return n.name}return null}function An(r){let e=[],t=0;for(;t<r.length;){if(r[t]==="["){let o=r.indexOf("]",t+1);if(o===-1){e.push({name:r.slice(t+1),suffix:"type-param"});break}e.push({name:r.slice(t+1,o),suffix:"type-param"}),t=o+1;continue}if(r[t]==="("&&(e.length===0||t===0||ar(r[t-1]))){let o=r.indexOf(")",t+1);if(o!==-1&&r[o+1]!=="."){e.push({name:r.slice(t+1,o),suffix:"parameter"}),t=o+1;continue}}let n;if(r[t]==="`"){let o=r.indexOf("`",t+1);if(o===-1){n=r.slice(t+1),e.push({name:n,suffix:"term"});break}n=r.slice(t+1,o),t=o+1}else{let o=t;for(;t<r.length&&!ar(r[t]);)t++;n=r.slice(o,t)}if(t>=r.length){n&&e.push({name:n,suffix:"term"});break}let i=r[t];if(i==="("){let o=r.indexOf(")",t+1);o!==-1&&r[o+1]==="."?(e.push({name:n,suffix:"method"}),t=o+2):o!==-1?(e.push({name:n,suffix:"method"}),t=o+1):(e.push({name:n,suffix:"term"}),t++)}else{let o=Fn[i];o&&e.push({name:n,suffix:o}),t+=1}}return e}function ar(r){return r==="/"||r==="#"||r==="."||r==="("||r==="["||r===":"||r==="!"}function _(r){let e=be(r);if("kind"in e&&e.kind==="local")return e.id;let t=e;return t.descriptors.length===0?"":t.descriptors[t.descriptors.length-1].name}function O(r){let e=be(r);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function cr(r){let e=O(r);return e==="method"?!0:e!=="term"?!1:r.endsWith("().")?!0:r.startsWith("rust-analyzer ")&&r.includes("#")?!1:r.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(r):!0}function Ln(r,e={}){if(K(r.symbol)!==null)return e.includeClassMemberFallbacks===!0;let i=(r.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function lr(r,e,t={}){let n=new Map;for(let o of e)r.length>0&&!Ln(o,{includeClassMemberFallbacks:t.includeClassMemberFallbacks})||n.set(o.id,o);for(let o of r)n.set(o.id,o);let i=[...n.values()];return t.sort?i.sort((o,a)=>o.start_line-a.start_line||o.end_line-a.end_line||o.symbol.localeCompare(a.symbol)):i}var Nn=J("file-definitions",{clearGroups:["definition-catalog"]}),Rs=J("file-function-like-definitions",{clearGroups:["definition-catalog"]});function W(r,e,t={}){return t.includeClassMemberFallbacks?dr(r,e,void 0,{includeClassMemberFallbacks:!0}):Nn.get(r,e,()=>{let n=jn(r,e);if(n)return n;let i=dr(r,e),o=Le(r),a=Se(r).forFile(e,{text:!0}).text;return o&&a&&pr.write(r,e,Ae(r,e,a),{projectFingerprint:o,definitions:i.map(s=>({...s}))}),i})}var pr=Mt({kind:"file-definitions",invalidation:wt("file-definitions"),serialize:_n,deserialize:On});function jn(r,e){let t=Le(r);if(!t)return null;let n=Se(r).forFile(e,{text:!0}).text;if(!n)return null;let i=pr.read(r,e,Ae(r,e,n));return i?Wn(i,t,e):null}function _n(r){return JSON.stringify(r)}function On(r){try{let e=JSON.parse(r);return!je(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function Wn(r,e,t){if(r.projectFingerprint!==e)return null;let n=[];for(let i of r.definitions){let o=$n(i,t);if(!o)return null;n.push(o)}return n}function $n(r,e){return!je(r)||typeof r.symbolId!="number"||typeof r.symbol!="string"||typeof r.documentId!="number"||typeof r.startLine!="number"||typeof r.startChar!="number"&&r.startChar!==void 0||typeof r.endLine!="number"||typeof r.endChar!="number"&&r.endChar!==void 0||r.relativePath!==e||typeof r.leaf!="string"||typeof r.parentTypeName!="string"&&r.parentTypeName!==null||typeof r.isFunctionLike!="boolean"||typeof r.isTypeLike!="boolean"||typeof r.kind!="number"&&r.kind!==null||typeof r.documentation!="string"&&r.documentation!==null||typeof r.enclosingSymbol!="string"&&r.enclosingSymbol!==null?null:{symbolId:r.symbolId,symbol:r.symbol,documentId:r.documentId,startLine:r.startLine,startChar:r.startChar,endLine:r.endLine,endChar:r.endChar,relativePath:r.relativePath,leaf:r.leaf,parentTypeName:r.parentTypeName,isFunctionLike:r.isFunctionLike,isTypeLike:r.isTypeLike,kind:r.kind,documentation:r.documentation,enclosingSymbol:r.enclosingSymbol}}function dr(r,e,t,n={}){let i=lr(Gn(r,e),qn(r,e),{sort:!0,includeClassMemberFallbacks:n.includeClassMemberFallbacks}).map(Un);return t&&(i=i.filter(t)),Bn(r,e,i)}function Gn(r,e){return r.all(`SELECT
|
|
2
2
|
gs.id,
|
|
3
3
|
gs.symbol,
|
|
4
4
|
der.document_id,
|
|
@@ -16,7 +16,7 @@ import{A as Et,B as Q,C as Ft,D as At,E as je,G as H,H as Lt,I as le,J as de,K a
|
|
|
16
16
|
JOIN documents d ON der.document_id = d.id
|
|
17
17
|
WHERE d.relative_path = ?
|
|
18
18
|
${r.symbolNoiseFor("gs")}
|
|
19
|
-
ORDER BY der.start_line, der.end_line`,e)}function
|
|
19
|
+
ORDER BY der.start_line, der.end_line`,e)}function qn(r,e){return r.all(`SELECT
|
|
20
20
|
gs.id,
|
|
21
21
|
gs.symbol,
|
|
22
22
|
c.document_id,
|
|
@@ -37,7 +37,7 @@ import{A as Et,B as Q,C as Ft,D as At,E as je,G as H,H as Lt,I as le,J as de,K a
|
|
|
37
37
|
AND m.role = 1
|
|
38
38
|
${r.symbolNoiseFor("gs")}
|
|
39
39
|
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
40
|
-
ORDER BY start_line, end_line`,e)}function
|
|
41
|
-
`),c=[];for(let l=0;l<s.length;l++){if(l===i)continue;let d=s[l]??"";a.lastIndex=0;let p;for(;(p=a.exec(d))!==null;)c.push({file:e,line:l,column:p.index})}return z(c.filter(l=>Y(t,dr.join(t,l.file))===e))}function qe(r){for(let e=r;e;e=e.getParent()){let t=e.getKindName();if(t.includes("Type")||t==="InterfaceDeclaration"||t==="TypeAliasDeclaration")return!0;if(t==="CallExpression"||t==="NewExpression"||t==="ExpressionStatement")return!1}return!1}function Ue(r,e){return r.getLineAndColumnAtPos(e.getStart()).line-1}function z(r){let e=new Set,t=[];for(let n of r){let i=`${n.file}:${n.line}:${n.column}`;e.has(i)||(e.add(i),t.push(n))}return t}function Y(r,e){let t=dr.relative(r||process.cwd(),e).replace(/\\/g,"/");return!t||t.startsWith("..")?null:t}function mr(r,e,t,n){let i=ii(e,n);return i.size===0?new Map:oi(r,t,i)}function ii(r,e){let t=new Map;for(let n of W(r,e)){let i=_(n.symbol)??n.leaf;if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push(n)}return t}function oi(r,e,t){let n=new Map,i=new Map;return e.forEachDescendant(o=>{for(let a of si(r,o)){let s=t.get(a);if(!s)continue;let c=Ue(e,o);for(let l of s){if(c<l.startLine-1||c>l.endLine+1)continue;let d=Math.abs(c-l.startLine),p=i.get(l.symbolId);p!==void 0&&p<=d||(i.set(l.symbolId,d),n.set(l.symbolId,o))}}}),n}function si(r,e){let t=[],n=i=>{i&&!t.includes(i)&&t.push(i)};if("getNameNode"in e&&typeof e.getNameNode=="function"){let i=e.getNameNode();n(i?.getText())}if("getName"in e&&typeof e.getName=="function"){let i=e.getName();n(i)}return r.Node.isIdentifier(e)&&n(e.getText()),t}var ai=J("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function hr(r,e,t,n){let i=Ve(r,e),o=He(i.get(n)??[],t);if(o)return o;let a=[];for(let s of i.values())for(let c of s)((c.leaf||_(c.symbol)||"").includes(n)||c.symbol.includes(n))&&a.push(c);return He(a,t)}function Be(r,e,t,n){return He(Ve(r,e).get(n)??[],t)}function gr(r,e){let t=new Map;for(let[n,i]of Ve(r,e)){let o=i[0];o&&t.set(n,o)}return t}function Ve(r,e){return ai.get(r,e,()=>{let t=new Map;for(let n of W(r,e)){let i=n.leaf||_(n.symbol);if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push({...n,leaf:i})}for(let n of t.values())n.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return t})}function He(r,e){let t=null,n=Number.POSITIVE_INFINITY;for(let i of r){let o=Math.abs(i.startLine-e);(o<n||o===n&&t&&i.startLine<t.startLine)&&(t=i,n=o)}return t}import Ke from"path";function yr(r,e){let t=new Map,n=null,i=null,o=()=>(i??=U(r,{extensions:de}),i),a=()=>(n??=N("typescript.source-file-index",()=>ci(r.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),n),s=c=>pe(c)?k(t,c,()=>{let l=ee(Ke.resolve(r.config.projectRoot,c));for(let{project:d,sourceFiles:p}of a()){let u=p.get(l)??null;if(u||(u=d.addSourceFileAtPathIfExists(l)??null,u&&p.set(ee(u.getFilePath()),u)),u)return{project:d,sourceFile:u}}return null}):null;return{sourceFile:c=>s(c)?.sourceFile??null,sourceFileMatch:s,indexedTypeScriptLikeDocuments:o}}function ci(r,e,t){let n=e.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[ee(o.getFilePath()),o]))}));for(let i of t){let o=ee(Ke.resolve(r,i));for(let a of n){if(a.sourceFiles.has(o))break;let s=a.project.addSourceFileAtPathIfExists(o)??null;if(s){a.sourceFiles.set(ee(s.getFilePath()),s);break}}}return n}function ee(r){return Ke.resolve(r)}function ze(r,e){for(let t of r)if(e===t.name||e.startsWith(`${t.name}/`))return t.name;return null}function Sr(r){let e=`${r.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as te,readFileSync as li}from"fs";import b from"path";var Ye=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Je(r,e){let n=e?b.dirname(b.join(r,e)):r,i=b.resolve(r);for(;n.startsWith(i);){for(let a of Ye){let s=b.join(n,a);if(te(s))return s}let o=b.dirname(n);if(o===n)break;n=o}for(let o of Ye){let a=b.join(r,o);if(te(a))return a}return null}function br(r){let e=r.config.projectRoot,t=new Set(di(e,r.config.semantic?.typescript?.tsconfigs)),n=U(r,{includeIgnored:!1,extensions:de});for(let i of n){let o=Je(e,i);o&&t.add(b.resolve(o))}if(t.size===0){let i=Je(e);i&&t.add(b.resolve(i))}return[...t].filter(i=>!vr(e,i)).sort((i,o)=>i.localeCompare(o))}function di(r,e=[]){let t=new Set;for(let n of e){let i=b.isAbsolute(n)?n:b.join(r,n);te(i)&&t.add(b.resolve(i))}for(let n of pi(r))for(let i of Ye){let o=b.join(n,i);te(o)&&t.add(b.resolve(o))}if(t.size===0){let n=Je(r);n&&t.add(b.resolve(n))}return[...t].filter(n=>!vr(r,n)).sort((n,i)=>n.localeCompare(i))}function pi(r){let e=b.join(r,"package.json");if(!te(e))return[];let t;try{t=JSON.parse(li(e,"utf8"))}catch{return[]}return(Array.isArray(t.workspaces)?t.workspaces:t.workspaces?.packages??[]).flatMap(i=>Dt(r,i))}function vr(r,e){let t=b.relative(r,e).replace(/\\/g,"/");return t.startsWith("..")||t.includes("/node_modules/")||t.startsWith("node_modules/")||t.includes("/dist/")||t.startsWith("dist/")}var ui=32;function Mr(r,e,t,n={}){return N("typescript.provider.construct",()=>new Xe(r,e,t),()=>({tsconfigs:t.length,reusedProjects:n.reusedProjects===!0}))}var Xe=class{constructor(e,t,n){this.db=e;this.tsMorph=t;this.projects=n;this.workspacePackages=Tt(e.config.projectRoot),this.sourceFiles=yr(e,n)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(e=>e.tsconfigPath)}}importUsage(e){return k(this.importUsageCache,e,()=>{let t=this.sourceFiles.sourceFile(e);if(!t)return[];let n=mi();return N("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,t,n),()=>({file:e,...n}))})}referencesFor(e){return k(this.referencesCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,t)})}referencesForDefinitions(e,t={}){let n=new Map,i=ce(),o=[];for(let d of e){let p=this.referencesCache.get(d.symbolId);p?n.set(d.symbolId,p):o.push(d)}if(o.length===0)return n;let a=o,s=t.exact?[]:o.filter(d=>!Ir(d));if(s.length>=ui){let d=this.referencesForDefinitionsBySymbolScan(s);for(let p of s){let u=d.get(p.symbolId)??[];this.referencesCache.set(p.symbolId,u),n.set(p.symbolId,u)}if(a=o.filter(p=>Ir(p)),a.length===0)return n}let c=new Map;for(let d of a){let p=c.get(d.relativePath);p?p.push(d):c.set(d.relativePath,[d])}let l=[];for(let[d,p]of c){let u=Rr();N("typescript.references-map.file",()=>{let g=this.definitionNodesForFile(d);for(let f of p){i&&(u.cacheMisses+=1);let m=g.get(f.symbolId)??null;i&&(m?u.nodeHits+=1:u.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(f,m,i?u:void 0);this.referencesCache.set(f.symbolId,h),n.set(f.symbolId,h)}catch{u.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:d,definitions:p.length,...Cr(u)}))}if(l.length>0){let d=this.referencesForDefinitionsBySymbolScan(l);for(let p of l){let u=d.get(p.symbolId)??[];this.referencesCache.set(p.symbolId,u),n.set(p.symbolId,u)}}return n}referenceFragmentsForFiles(e){let t=lr(this.db).filter(o=>pe(o.relativePath)),n=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,n);return _t(t,i,n)}referencesForDefinitionsBySymbolScan(e,t){let n=ce(),i=Rr(),o=new Map,a=new Set(e.map(c=>c.symbolId)),s=new Map(e.map(c=>[c.symbolId,c]));for(let c of e)o.set(c.symbolId,[]);return N("typescript.references-map.inverted-scan",()=>{let c=n?y.now():0,l=t?this.packageImportReferencesForFiles(t):this.packageImportReferences();for(let h of e){let S=l.get(h.symbolId)??[];if(S.length>0){let w=o.get(h.symbolId)??[];w.push(...S),o.set(h.symbolId,w)}n&&(i.packageReferenceCount+=S.length)}n&&(i.packageRefsMs+=y.now()-c);let d=new Map,p=new Map,u=this.hierarchyTargetsForDefinitions(e),g=new Set(e.map(h=>h.leaf).filter(Boolean)),f=n?y.now():0;for(let h of t??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(h))continue;let S=this.sourceFiles.sourceFile(h);S&&(n&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(S,h,a,s,u,g,d,p,o,n?i:void 0))}n&&(i.scanMs+=y.now()-f);let m=n?y.now():0;this.addHierarchyMemberReferences(e,o,n?i:void 0),n&&(i.hierarchyMs+=y.now()-m);for(let[h,S]of o){let w=z(S);o.set(h,w),n&&(i.referenceCount+=w.length)}},()=>({definitions:e.length,...Cr(i)})),o}addReferencesFromSourceFileScan(e,t,n,i,o,a,s,c,l,d){let p=this.compilerCheckerForSourceFile(e),u=e.compilerNode,g=yi(e),f=m=>{if(this.tsMorph.ts.isIdentifier(m)){if(d&&(d.identifiers+=1),!a.has(m.text)&&!g.has(m.text)){this.tsMorph.ts.forEachChild(m,f);return}let h=this.compilerReferenceSymbol(p,m,d);if(h){let S;s.has(h)?S=s.get(h)??null:(S=this.referenceDefinitionFromCompilerSymbol(h),s.set(h,S)),d&&(S?d.targetHits+=1:d.targetMisses+=1);let w=k(c,h,()=>this.compilerSymbolKeys(h)),A=null,T=null,L=S&&n.has(S.symbolId)?i.get(S.symbolId):void 0;if(L&&(A=Qe(u,m),!xr(L,t,A))){let M=u.getLineAndCharacterOfPosition(m.getStart(u));T={file:t,line:M.line,column:M.character};let C=l.get(L.symbolId)??[];C.push(T),l.set(L.symbolId,C),d&&(d.requestedHits+=1)}for(let M of w)for(let C of o.get(M)?.values()??[]){if(A??=Qe(u,m),xr(C,t,A))continue;if(!T){let x=u.getLineAndCharacterOfPosition(m.getStart(u));T={file:t,line:x.line,column:x.character}}let v=l.get(C.symbolId)??[];v.push(T),l.set(C.symbolId,v),d&&(d.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(m,f)};f(u)}hierarchyTargetsForDefinitions(e){let t=new Map;for(let n of e){let i=this.nodeForDefinition(n),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let a=o.parent;if(!this.isHierarchyContainer(a))continue;let s=this.compilerCheckerForSourceFile(i.getSourceFile()),c=s.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(s,a,c))for(let d of this.compilerSymbolKeys(l)){let p=t.get(d)??new Map;p.set(n.symbolId,n),t.set(d,p)}}return t}hierarchyMemberSymbols(e,t,n){let i=new Set,o=new Set,a=(s,c,l)=>{if(!o.has(s)){o.add(s),i.add(c);for(let d of l){let p=d.getProperty(n.name);p&&a(d,p,this.hierarchyAncestorTypesForType(e,d))}}};return a(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}addHierarchyMemberReferences(e,t,n){let i=new Map;for(let o of e){let a=this.nodeForDefinition(o),s=a?.compilerNode;if(!s||!this.isHierarchyMethod(s))continue;let c=s.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(a.getSourceFile()),d=l.getSymbolAtLocation(s.name);if(!d)continue;let p=s.getSourceFile(),u=p.getLineAndCharacterOfPosition(s.name.getStart(p)),g={definition:o,location:{file:o.relativePath,line:u.line,column:u.character}},f=t.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(l,c,d))if(h!==d)for(let S of this.compilerSymbolLocations(h))f.push(S),n&&(n.hierarchyReferences+=1);t.set(o.symbolId,f);let m=this.hierarchyRootMemberSymbols(l,c,d);for(let h of m){let S=i.get(h)??new Map;S.set(o.symbolId,g),i.set(h,S)}n&&(n.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){n&&(n.hierarchyFamilies+=1);for(let{definition:a}of o.values()){let s=t.get(a.symbolId)??[];for(let c of o.values())c.definition.symbolId!==a.symbolId&&(s.push(c.location),n&&(n.hierarchyReferences+=1));t.set(a.symbolId,s)}}}hierarchyRootMemberSymbols(e,t,n){let i=new Set,o=new Set,a=(s,c,l)=>{if(o.has(s))return;o.add(s);let d=!1;for(let p of l){let u=p.getProperty(n.name);u&&(d=!0,a(p,u,this.hierarchyAncestorTypesForType(e,p)))}if(!d)for(let p of this.compilerSymbolKeys(c))i.add(p)};return a(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}compilerSymbolKeys(e){return(e.declarations??[]).map(t=>{let n=t.getSourceFile();return`${n.fileName}\0${t.getStart(n)}\0${e.name}`})}compilerSymbolLocations(e){let t=[];for(let n of e.declarations??[]){let i=n.getSourceFile(),o=Y(this.db.config.projectRoot,i.fileName);if(!o)continue;let a=n.name,s=i.getLineAndCharacterOfPosition((a??n).getStart(i));t.push({file:o,line:s.line,column:s.character})}return t}baseTypes(e,t){try{return e.getBaseTypes(t)??[]}catch{return[]}}hierarchyAncestorTypes(e,t){let n=new Set(this.hierarchyAncestorTypesForType(e,e.getTypeAtLocation(t)));for(let i of t.heritageClauses??[])for(let o of i.types)n.add(e.getTypeAtLocation(o));return[...n]}hierarchyAncestorTypesForType(e,t){let n=new Set(this.baseTypes(e,t));for(let i of t.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let a of o.types)n.add(e.getTypeAtLocation(a));return[...n]}isHierarchyMethod(e){return this.tsMorph.ts.isMethodDeclaration(e)||this.tsMorph.ts.isMethodSignature(e)}isHierarchyContainer(e){return this.tsMorph.ts.isClassDeclaration(e)||this.tsMorph.ts.isClassExpression(e)||this.tsMorph.ts.isInterfaceDeclaration(e)}compilerReferenceSymbol(e,t,n){n&&(n.symbolLookups+=1);let i=e.getSymbolAtLocation(t);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return n&&(n.aliasResolutions+=1),e.getAliasedSymbol(i)}catch{return i}}}calleesFor(e){return k(this.calleesCache,e.symbolId,()=>k(this.fileCalleesCache,e.relativePath,()=>this.calleeMapForFile(e.relativePath)).get(e.symbolId)??[])}calleesForDefinitions(e){let t=new Map,n=new Map;for(let i of e){let o=n.get(i.relativePath);o?o.push(i):n.set(i.relativePath,[i])}for(let[i,o]of n){let a=this.fileCalleesCache.get(i),s=new Set(o.map(l=>l.symbolId)),c=a??this.calleeMapForFile(i,s);for(let l of o){let d=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,d),t.set(l.symbolId,d)}}return t}referencesForDefinitionNode(e,t,n){let i=n?y.now():0,o=this.packageImportReferencesForDefinition(e);if(n&&(n.packageRefsMs+=y.now()-i,n.packageReferenceCount+=o.length),!t)return o;let a=n?y.now():0,s=pr(t,e,o,this.db.config.projectRoot);return n&&(n.semanticRefsMs+=y.now()-a,n.referenceCount+=s.length),s}signatureFor(e){return k(this.signatureCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);if(!t||!this.tsMorph.Node.isFunctionDeclaration(t)&&!this.tsMorph.Node.isMethodDeclaration(t)&&!this.tsMorph.Node.isArrowFunction(t)&&!this.tsMorph.Node.isFunctionExpression(t)&&!this.tsMorph.Node.isConstructorDeclaration(t))return null;let n=t.getType().getCallSignatures()[0];if(!n)return null;let i=n.getParameters().map(a=>{let s=a.getDeclarations()[0],c=s?a.getTypeAtLocation(s).getText(s):a.getValueDeclaration()?.getType().getText()??"unknown";return wr(c)}),o=n.getReturnType().getText(t);return`(${i.join(",")})=>${wr(o)}`})}importUsageForSourceFile(e,t,n){let i=[],o=new Map;for(let a of t.getImportDeclarations()){n.declarations+=1;let s=Le(this.db,e,a.getModuleSpecifierValue()),c=a.getImportClause()?.isTypeOnly()??!1;for(let l of Ze(a)){n.entries+=1;let d=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(d?n.bindingSymbols+=1:n.missingBindingSymbols+=1);let p={sourcePath:s,entry:l,typeOnlyDeclaration:c,bindingSymbol:d,references:[]};if(i.push(p),c||!l.localName||!d)continue;let u=o.get(l.localName);u?u.push(p):o.set(l.localName,[p])}}return o.size>0&&t.forEachDescendant(a=>{if(a.getKindName()!=="Identifier")return;let s=o.get(a.getText());if(!s||hi(a))return;n.scannedIdentifiers+=1;let c=a.getSymbol()?.compilerSymbol;if(n.symbolLookups+=1,!!c){for(let l of s)if(l.bindingSymbol===c){l.references.push({location:ve(a,this.db.config.projectRoot),node:a}),n.matchedReferences+=1;break}}}),i.map(a=>a.typeOnlyDeclaration?fi(e,a.sourcePath,a.entry):a.entry.identifier&&!a.bindingSymbol?(n.fallbackEntries+=1,this.valueImportUsageForEntry(e,a.sourcePath,a.entry)):this.valueImportUsageFromLocations(e,a.sourcePath,a.entry,a.references))}valueImportUsageForEntry(e,t,n){let i=n.identifier?n.identifier.findReferences():[],o=[];for(let a of i)for(let s of ur(a,e,n.identifier,this.db.config.projectRoot))o.push(s);return this.valueImportUsageFromLocations(e,t,n,o)}valueImportUsageFromLocations(e,t,n,i){let o=i.some(c=>!qe(c.node)),a=i.some(c=>qe(c.node)),s=n.isTypeOnly;return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:s,isUsed:s||i.length>0,isTypeUsed:s||a,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(e){return this.packageImportReferences().get(e.symbolId)??[]}packageImportReferencesForFiles(e){let t=new Map,n=new Set;for(let o of e){let a=this.sourceFiles.sourceFile(o);if(a)for(let s of a.getImportDeclarations()){let c=ze(this.workspacePackages,s.getModuleSpecifierValue());c&&n.add(c)}}if(n.size===0)return t;let i=this.packageExportsForNames(n);for(let o of e)this.addPackageImportReferencesForDocument(t,i,o);for(let[o,a]of t)t.set(o,z(a));return t}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let e=new Map,t=this.packageExports();for(let n of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(e,t,n);for(let[n,i]of e)e.set(n,z(i));return this.packageImportReferenceIndex=e,e}addPackageImportReferencesForDocument(e,t,n){if(this.db.isIgnored(n))return;let i=this.sourceFiles.sourceFileMatch(n);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(e,t,n,o)}addPackageImportReferencesForDeclaration(e,t,n,i){let o=ze(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let a=t.get(o);if(a)for(let s of Ze(i)){if(s.kind!=="named"||!s.identifier)continue;let c=a.get(s.importedName);if(!c||c.size===0)continue;let l=fr(s.identifier,n,this.db.config.projectRoot);l.length>0&&xi(e,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(e=>e.name))),this.packageExportIndex)}packageExportsForNames(e){let t=new Map;for(let n of this.workspacePackages){if(!e.has(n.name))continue;let i=new Map;for(let o of Sr(n))this.collectPackageExports(n,o,i,new Set);i.size>0&&t.set(n.name,i)}return t}collectPackageExports(e,t,n,i){if(i.has(t))return;i.add(t);let o=this.sourceFiles.sourceFile(t);if(o)for(let a of o.getExportDeclarations()){let s=a.getModuleSpecifierValue(),c=s?Le(this.db,t,s):t;if(!c||!c.startsWith(`${e.relativeDir}/src/`))continue;let l=a.getNamedExports();if(l.length===0){if(a.isNamespaceExport())continue;this.collectPackageExports(e,c,n,i);continue}for(let d of l){let p=d.getNameNode().getText(),u=d.getAliasNode()?.getText()??p,g=this.indexedDefinitionByLeaf(c,p);if(!g)continue;let f=n.get(u);f||(f=new Set,n.set(u,f)),f.add(g.symbolId)}}}indexedDefinitionByLeaf(e,t){return k(this.indexedDefinitionLeafCache,e,()=>gr(this.db,e)).get(t)??null}nodeForDefinition(e){return k(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return k(this.fileDefinitionNodeCache,e,()=>{let t=this.sourceFiles.sourceFile(e);return t?mr(this.tsMorph,this.db,t,e):new Map})}referenceDefinitionFromCompilerSymbol(e){return this.definitionFromCompilerSymbol(e,void 0,!0)}definitionFromCompilerSymbol(e,t,n=!1){let i=e.name,o=t?y.now():0,a=e.declarations??[];t&&(t.declarationsMs+=y.now()-o,t.declarationChecks+=a.length);for(let s of a){let c=t?y.now():0,l=s.getSourceFile(),d=Y(this.db.config.projectRoot,l.fileName),p=l.getLineAndCharacterOfPosition(s.getStart(l)).line;if(t&&(t.declarationLocationMs+=y.now()-c),!d||this.db.isIgnored(d))continue;let u=t?y.now():0,g=this.compilerDeclarationName(s),f=n?Be(this.db,d,p,i)??(g&&g!==i?Be(this.db,d,p,g):null):hr(this.db,d,p,i);if(t&&(t.indexedLookupMs+=y.now()-u),f)return{symbolId:f.symbolId,symbol:f.symbol,file:f.relativePath,line:f.startLine}}return null}compilerDeclarationName(e){let t=e.name;return t&&this.tsMorph.ts.isIdentifier(t)?t.text:null}calleeMapForFile(e,t){let n=ce(),i=0,o=0,a=0,s=0,c=0,l=0,d=0,p=0,u=n?bi():void 0;return N("typescript.callee-map.file",()=>{let g=n?y.now():0,f=this.sourceFiles.sourceFile(e);if(n&&(c=Math.round(y.now()-g)),!f)return new Map;let m=n?y.now():0,h=W(this.db,e).sort((v,x)=>v.startLine-x.startLine||x.endLine-v.endLine);if(n&&(l=Math.round(y.now()-m)),i=h.length,h.length===0)return new Map;let S=new Map,w=n?y.now():0,A=this.compilerCheckerForSourceFile(f),T=f.compilerNode;n&&(d=Math.round(y.now()-w));let L=new Map,M=v=>{if(this.tsMorph.ts.isCallExpression(v)||this.tsMorph.ts.isNewExpression(v)){n&&(o+=1);let x=this.semanticCalleeForCallNode(A,T,h,v,L,t,u);x&&(n&&(a+=1),gi(S,x.callerId,x.target))}this.tsMorph.ts.forEachChild(v,M)},C=n?y.now():0;M(T),n&&(p=Math.round(y.now()-C));for(let[v,x]of S)S.set(v,Ii(x));return s=S.size,S},()=>({relativePath:e,definitions:i,callNodes:o,resolvedCallees:a,outputRows:s,requestedDefinitions:t?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:p,...u?vi(u):{}}))}semanticCalleeForCallNode(e,t,n,i,o,a,s){let c=s?y.now():0,l=Si(n,Qe(t,i));if(s&&(s.callerLookupMs+=y.now()-c),!l)return null;if(a&&!a.has(l.symbolId))return s&&(s.skippedUnrequestedCallers+=1),null;let d=i.expression,p=this.compilerSymbolForExpression(e,d,s),u=null;if(p)if(s&&(s.targetSymbolHits+=1),o.has(p))s&&(s.compilerSymbolCacheHits+=1),u=o.get(p)??null;else{s&&(s.compilerSymbolCacheMisses+=1);let g=s?y.now():0;u=this.definitionFromCompilerSymbol(p,s),s&&(s.targetLookupMs+=y.now()-g),o.set(p,u)}else s&&(s.targetMisses+=1);return u?{callerId:l.symbolId,target:{symbol:u.symbol,file:u.file,line:u.line}}:null}compilerSymbolForExpression(e,t,n){let i=n?y.now():0,o=e.getSymbolAtLocation(t);if(n&&(n.expressionSymbolMs+=y.now()-i),o)return o;n&&(n.typeFallbacks+=1);let a=n?y.now():0,s=e.getTypeAtLocation(t).getSymbol();return n&&(n.typeSymbolMs+=y.now()-a),s}compilerCheckerForSourceFile(e){let t=e.getProject(),n=this.compilerCheckerCache.get(t);return n||(n=t.getTypeChecker().compilerObject,this.compilerCheckerCache.set(t,n)),n}};function Ze(r){let e=[],t=r.getDefaultImport();t&&e.push({identifier:t,importedName:"default",localName:t.getText(),kind:"default",isTypeOnly:r.getImportClause()?.isTypeOnly()??!1});let n=r.getNamespaceImport();n&&e.push({identifier:n,importedName:"*",localName:n.getText(),kind:"namespace",isTypeOnly:r.getImportClause()?.isTypeOnly()??!1});for(let i of r.getNamedImports()){let o=i.getNameNode(),s=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);e.push({identifier:s,importedName:o.getText(),localName:s?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(r.getImportClause()?.isTypeOnly()??!1)})}return e.length===0&&e.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),e}function fi(r,e,t){return{importer:r,sourcePath:e,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function mi(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function hi(r){for(let e=r;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function gi(r,e,t){let n=r.get(e);n||(n=[],r.set(e,n)),n.push(t)}function yi(r){let e=new Set;for(let t of r.getImportDeclarations())for(let n of Ze(t))n.localName&&e.add(n.localName);return e}function Si(r,e){let t=null;for(let n of r)e<n.startLine||e>n.endLine||(!t||n.startLine>=t.startLine)&&(t=n);return t}function Qe(r,e){return r.getLineAndCharacterOfPosition(e.getStart(r)).line}function xr(r,e,t){return e===r.relativePath&&t>=r.startLine&&t<=r.endLine}function Ir(r){return r.symbol.includes("#")?O(r.symbol)==="type"&&r.relativePath.endsWith(".d.ts"):!1}function bi(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function vi(r){return{...r,callerLookupMs:Math.round(r.callerLookupMs),expressionSymbolMs:Math.round(r.expressionSymbolMs),typeSymbolMs:Math.round(r.typeSymbolMs),targetLookupMs:Math.round(r.targetLookupMs),declarationsMs:Math.round(r.declarationsMs),declarationLocationMs:Math.round(r.declarationLocationMs),indexedLookupMs:Math.round(r.indexedLookupMs)}}function Rr(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function Cr(r){return{...r,scanMs:Math.round(r.scanMs),packageRefsMs:Math.round(r.packageRefsMs),semanticRefsMs:Math.round(r.semanticRefsMs),hierarchyMs:Math.round(r.hierarchyMs)}}function xi(r,e,t){for(let n of e){let i=r.get(n)??[];i.push(...t),r.set(n,i)}}function Ii(r){let e=new Set,t=[];for(let n of r){let i=`${n.symbol}|${n.file}|${n.line}`;e.has(i)||(e.add(i),t.push(n))}return t}function wr(r){return r.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var xe=class{loadModule;discoverTsconfigs;createProjects;createProvider;db;module=null;projects=null;provider=null;stats={providerRequests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0};constructor(e,t={}){this.db=e,this.loadModule=t.loadModule??Nt,this.discoverTsconfigs=t.discoverTsconfigs??br,this.createProjects=t.createProjects??jt,this.createProvider=t.createProvider??((n,i,o)=>Mr(n,i,o,{reusedProjects:!0}))}semanticProvider(){return this.stats.providerRequests+=1,this.provider?(this.stats.sessionsReused+=1,this.provider):this.createSession()}advanceGeneration(e,t){let n=Ri(t);return this.provider?.dispose?.(),this.provider=null,this.db=e,this.projects?n.mode==="replace"?(this.projects=null,this.module=null,this.stats.sessionsReplaced+=1,n):(n.mode==="refresh"&&(Ci(this.projects,e.config.projectRoot,n),this.stats.sessionsRefreshed+=1),n):n}snapshotStats(){return{...this.stats}}dispose(){this.provider?.dispose?.(),this.provider=null,this.projects=null,this.module=null}createSession(){let e=this.module??this.loadModule();if(!e)return this.provider=_e("ts-morph is not installed"),this.provider;if(this.module=e,!this.projects){let t=this.discoverTsconfigs(this.db);if(t.length===0)return this.provider=_e("no tsconfig found"),this.provider;this.projects=this.createProjects(e,t),this.stats.projectsCreated+=this.projects.length}return this.provider=this.createProvider(this.db,e,this.projects),this.stats.sessionsCreated+=1,this.provider}};function Ri(r){let e=new Set;r.projectIdentityChanged&&e.add("project-identity-changed");for(let o of r.uncertainty)e.add(o);for(let o of r.changes)o.inputKind!=="source"&&e.add(`${o.inputKind}-input-changed`);if(e.size>0)return{mode:"replace",addedFiles:[],modifiedFiles:[],deletedFiles:[],reasons:[...e].sort()};let t=et(r.changes,"added"),n=et(r.changes,"modified"),i=et(r.changes,"deleted");return{mode:t.length+n.length+i.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:n,deletedFiles:i,reasons:[]}}function et(r,e){return r.filter(t=>t.kind===e).map(t=>t.path).sort()}function Ci(r,e,t){for(let n of r){for(let i of t.deletedFiles)n.project.getSourceFile(kr(e,i))?.forget();for(let i of t.modifiedFiles){let o=n.project.getSourceFile(kr(e,i));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&n.project.addSourceFilesFromTsConfig(n.tsconfigPath)}}var Re=class{openDb;createHost;generationIdentity;readSnapshot;now;db=null;host=null;generation=null;snapshot=null;requests=0;lastRequestAtMs=null;lastError=null;available=null;constructor(e){this.openDb=e.openDb,this.createHost=e.createHost??(t=>new xe(t)),this.generationIdentity=e.generationIdentity??Z,this.readSnapshot=e.readSnapshot??Ti,this.now=e.now??Date.now}handle(e,t){try{this.syncGeneration(e);let n=this.host.semanticProvider();switch(this.available=n.availability().available,this.requests+=1,this.lastRequestAtMs=this.now(),this.lastError=null,t.kind){case"availability":return n.availability();case"import-usage":return n.importUsage(t.file);case"references":return[...ki(n,t.definitions,{exact:t.exact===!0})];case"reference-fragments":if(!n.referenceFragmentsForFiles)throw new Error("TypeScript provider does not support reference fragments.");return[...n.referenceFragmentsForFiles(t.files)];case"callees":return[...Pi(n,t.definitions)];case"signature":return n.signatureFor(t.definition);default:return Ei(t)}}catch(n){throw this.lastError=n instanceof Error?n.message:String(n),n}}status(){let e=this.host?.snapshotStats();return{protocolVersion:X,state:this.lastError?"error":this.host?this.available?"ready":"unavailable":"idle",requests:this.requests,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastError?{lastError:this.lastError}:{},sessionsCreated:e?.sessionsCreated??0,sessionsReused:e?.sessionsReused??0,sessionsRefreshed:e?.sessionsRefreshed??0,sessionsReplaced:e?.sessionsReplaced??0,projectsCreated:e?.projectsCreated??0}}closeTypeScriptService(){this.host?.dispose(),this.db?.close(),this.host=null,this.db=null,this.generation=null,this.snapshot=null,this.available=null}syncGeneration(e){if(this.generation===e&&this.host&&this.db)return;let t=this.openDb(),n=this.generationIdentity(t.config.dbPath);if(!n||n!==e)throw t.close(),new Error("TypeScript semantic request does not match the currently published index generation.");let i=this.readSnapshot(t.config.dbPath);if(!this.host||!this.db)this.db=t,this.host=this.createHost(t);else{let o=this.db;this.host.advanceGeneration(t,Di(this.snapshot,i)),this.db=t,o.close()}this.generation=n,this.snapshot=i,this.available=null}};function tt(r){Pr(r.requestDir,{recursive:!0}),Pr(r.responseDir,{recursive:!0})}function Dr(r,e,t={}){tt(r);let n=0;for(let i of wi(r.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=Ie(r.requestDir,i),a=i.slice(0,-5),s=null;try{let c=Qt(Tr(o,"utf8"));if(a=c.id,c.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript semantic request expired before processing.");s=ut(),Te(c.profileEnvironment??{}),t.beforeRequest?.(c.deadlineAtMs);let l=e.handle(c.generation,c.request);F(Ie(r.responseDir,`${a}.json`),{ok:!0,protocolVersion:X,id:a,generation:c.generation,response:l})}catch(c){F(Ie(r.responseDir,`${a}.json`),{ok:!1,protocolVersion:X,id:a,error:c instanceof Error?c.message:String(c)})}finally{s&&Te(s),t.afterRequest?.(),Mi(o,{force:!0}),n+=1}}return n}function ki(r,e,t){return r.referencesForDefinitions?.(e,t)??new Map(e.map(n=>[n.symbolId,r.referencesFor(n)]))}function Pi(r,e){return r.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,r.calleesFor(t)]))}function Ti(r){try{let e=JSON.parse(Tr(Ie(r,"..","meta.json"),"utf8"));return dt(e.fingerprint)}catch{return null}}function Di(r,e){return e?pt(r,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function Ei(r){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(r)}`)}import{mkdirSync as Er,readFileSync as Fi,readdirSync as Ai,rmSync as Li}from"fs";import{resolve as Ce}from"path";var we=class{projectRoot;currentGeneration;createEmitter;now;active=null;requests=0;sessionsCreated=0;sessionsReplaced=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(e){this.projectRoot=Ce(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??Ut,this.now=e.now??Date.now}handle(e,t){let n=this.now();try{if(this.currentGeneration()!==e)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(t);if(i.emitter.producerIdentity!==t.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),a=i.emitter.advance({modifiedFiles:t.modifiedFiles,affectedFiles:t.affectedFiles}),s=this.now()-n;return this.requests+=1,this.lastRequestAtMs=this.now(),this.lastDurationMs=s,this.lastError=null,this.unavailable=!1,{producerIdentity:a.producerIdentity,cold:a.stats.initializations>o.initializations,durationMs:s,fragments:a.fragments.map(c=>({relativePath:c.relativePath,bytesBase64:c.bytes===null?null:Buffer.from(c.bytes).toString("base64"),occurrences:c.occurrences,symbols:c.symbols,referenceFragments:c.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(){let e=this.active?.emitter.snapshotStats();return{protocolVersion:fe,state:this.unavailable?"unavailable":this.lastError?"error":this.active?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,initializations:e?.initializations??0,programUpdates:e?.programUpdates??0,documentsEmitted:e?.documentsEmitted??0,documentsRemoved:e?.documentsRemoved??0,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{}}}close(){this.active=null}emitterFor(e){let t=`${e.tsconfigPath}\0${e.projectArgument}`;if(this.active&&this.active.sessionKey===t&&this.active.projectIdentity===e.projectIdentity)return this.active;let n=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:e.tsconfigPath,projectRoot:e.projectArgument});if(!n.available)throw this.unavailable=!0,new Error(n.reason);return this.active&&(this.sessionsReplaced+=1),this.active={sessionKey:t,projectIdentity:e.projectIdentity,emitter:n.emitter},this.sessionsCreated+=1,this.active}};function rt(r){Er(r.requestDir,{recursive:!0}),Er(r.responseDir,{recursive:!0})}function Fr(r,e,t={}){rt(r);let n=0;for(let i of Ai(r.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=Ce(r.requestDir,i),a=i.slice(0,-5);try{let s=Bt(Fi(o,"utf8"));if(a=s.id,s.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript index request expired before processing.");t.beforeRequest?.(s.deadlineAtMs);let c=e.handle(s.baseGeneration,s.request);F(Ce(r.responseDir,`${a}.json`),{ok:!0,protocolVersion:fe,id:a,baseGeneration:s.baseGeneration,response:c})}catch(s){F(Ce(r.responseDir,`${a}.json`),{ok:!1,protocolVersion:fe,id:a,error:s instanceof Error?s.message:String(s)})}finally{t.afterRequest?.(),Li(o,{force:!0}),n+=1}}return n}import{spawn as Ni}from"child_process";import{closeSync as ji,existsSync as _i,mkdirSync as Oi,openSync as Wi,readFileSync as Nr,rmSync as re,writeFileSync as $i}from"fs";import{dirname as Gi,resolve as ot}from"path";import{fileURLToPath as Ta}from"url";var qi=2e3,Ui=10;function jr(r,e,t){let n=Ee(ot(r));if(t&&Ee(t.projectRoot)===n)return{projectRoot:n,worktreeKind:"git",worktreeId:t.worktreeId,cliVersion:e};let i=mt(n);if(i.kind==="error")throw new Error(`Could not establish Git worktree identity for ${n}: ${i.message}`);return i.kind==="non-git"?{projectRoot:n,worktreeKind:"non-git",cliVersion:e}:{projectRoot:n,worktreeKind:"git",worktreeId:i.identity.worktreeId,cliVersion:e}}function _r(r){let e=r.runtime??Vi,t=H(r.cacheDir),n=Lt(t.statePath),i=n?e.isProcessAlive(n.pid)?{kind:"live",state:n}:{kind:"stale",state:n,reason:"dead-process"}:{kind:"stopped"},o=Hi("stop",i);if(o.kind==="signal-stop")return Ar(o.state.pid,r,e),nt(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};if(o.kind==="clean-stale")return nt(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};let a=ne(t.lockPath);return o.kind==="already-stopped"&&a&&e.isProcessAlive(a.pid)?(Ar(a.pid,r,e),nt(t,a.pid,e),{disposition:"stopped",pid:a.pid}):{disposition:"already-stopped"}}function Or(r,e){F(r,e)}function Wr(r){try{let e=JSON.parse(Nr(r,"utf8"));return e.version!==1||!le(e.at)||e.refreshRequestedAt!==void 0&&!le(e.refreshRequestedAt)||e.refreshDetail!==void 0&&typeof e.refreshDetail!="string"?null:{atMs:Date.parse(e.at),...e.refreshRequestedAt===void 0?{}:{refreshRequestedAtMs:Date.parse(e.refreshRequestedAt)},...e.refreshDetail===void 0?{}:{refreshDetail:e.refreshDetail}}}catch{return null}}function $r(r,e,t={}){let n=t.pid??process.pid,i=t.isProcessAlive??j,o=()=>{},a=ne(r);if(a&&i(a.pid))return{acquired:!1,lockPath:r,message:Lr(r,e,a),release:o};a&&re(r,{force:!0}),Oi(Gi(r),{recursive:!0});let s;try{s=Wi(r,"wx")}catch(d){if(Bi(d)==="EEXIST")return{acquired:!1,lockPath:r,message:Lr(r,e,ne(r)),release:o};throw d}let c={version:1,pid:n,projectRoot:ot(e),startedAt:(t.now??(()=>new Date))().toISOString()};$i(s,`${JSON.stringify(c)}
|
|
42
|
-
`);let l=!1;return{acquired:!0,lockPath:r,message:"",release:()=>{if(l)return;l=!0,ji(s);let d=ne(r);d?.pid===c.pid&&d.startedAt===c.startedAt&&re(r,{force:!0})}}}function ne(r){try{let e=JSON.parse(Nr(r,"utf-8"));return e.version!==1||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.projectRoot!="string"||!le(e.startedAt)?null:e}catch{return null}}function Hi(r,e){switch(r){case"status":return{kind:"report",classification:e};case"ensure":switch(e.kind){case"stopped":return{kind:"start"};case"stale":return e.reason==="old-heartbeat"?{kind:"replace",state:e.state}:{kind:"start"};case"live":return{kind:"reuse",state:e.state};case"incompatible":return{kind:"replace",state:e.state};default:return it(e)}case"stop":switch(e.kind){case"stopped":return{kind:"already-stopped"};case"stale":return e.reason==="old-heartbeat"?{kind:"signal-stop",state:e.state}:{kind:"clean-stale",state:e.state};case"live":case"incompatible":return{kind:"signal-stop",state:e.state};default:return it(e)}default:return it(r)}}function Gr(r){return r.idleTimeoutMs===0||r.watcher.state!=="idle"?!1:r.nowMs-r.lastActivityAtMs>=r.idleTimeoutMs}function Ar(r,e,t){if(!t.isProcessAlive(r))return;t.signalProcess(r);let n=e.stopTimeoutMs??qi,i=t.now()+n;for(;t.now()<=i;){if(!t.isProcessAlive(r))return;t.sleep(Ui)}throw new Error(`scip-query watch service pid ${r} did not stop within ${n}ms.`)}function nt(r,e,t){re(r.statePath,{force:!0}),re(r.activityPath,{force:!0}),ne(r.lockPath)?.pid===e&&!t.isProcessAlive(e)&&re(r.lockPath,{force:!0})}function Lr(r,e,t){return`error: scip-query watch is already running for ${ot(e)}${t?` (pid ${t.pid}, started ${t.startedAt}; lock: ${r})`:` (lock: ${r})`}. Stop that watcher before starting another.`}function Bi(r){return typeof r=="object"&&r&&"code"in r?r.code:void 0}var Vi={now:Date.now,isProcessAlive:j,spawnServer(r,e,t,n){if(!_i(r))throw new Error(`Watch service helper was not found at ${r}. Run npm run build first.`);Ni(process.execPath,[r,e,t,JSON.stringify(n)],{detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"}}).unref()},signalProcess(r){process.kill(r,"SIGTERM")},sleep(r){let e=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(e,0,0,r)}};function it(r){throw new Error(`Unhandled watch service value: ${JSON.stringify(r)}`)}import{existsSync as Br,lstatSync as Me,readFileSync as lt,readdirSync as Vr,realpathSync as qr,rmSync as ie,statSync as Ki}from"fs";import{join as R,resolve as $,sep as Ur}from"path";var zi=3600*1e3,Yi=2*1024*1024*1024,Ji=300*1e3;function Qi(r){let e=r.leases.filter(s=>s.managed&&!s.live&&!s.busy),t=Xi(r.leases,r.locks),n={};for(let s of r.generations)t.has(s.generationId)||(n[s.generationId]=s.unreferencedAt??r.nowMs);let i=r.generations.filter(s=>!t.has(s.generationId)).sort((s,c)=>n[s.generationId]-n[c.generationId]||s.generationId.localeCompare(c.generationId)),o=new Set;for(let s of i)r.nowMs-n[s.generationId]>=r.policy.generationTtlMs&&o.add(s.generationId);let a=r.generations.filter(s=>!o.has(s.generationId)).reduce((s,c)=>s+c.size,0);for(let s of i){if(a<=r.policy.budgetBytes)break;o.has(s.generationId)||(o.add(s.generationId),a-=s.size)}for(let s of o)delete n[s];return{deleteWorktrees:e,deleteGenerations:r.generations.filter(s=>o.has(s.generationId)),deleteLocks:r.locks.filter(s=>!s.live),deleteTemporaries:r.temporaries.filter(s=>!s.live),protectedGenerationIds:[...t].sort(),unreferencedSince:n}}function Xi(r,e){let t=new Set(r.filter(n=>n.managed&&(n.live||n.busy)).flatMap(n=>[n.lease.baseGenerationId,n.lease.activeGenerationId]).filter(n=>n!==void 0));for(let n of e)n.live&&t.add(n.generationId);return t}function Kr(r,e,t={}){if(!$t())return{kind:"disabled"};let n=ft(r);if(!n)return{kind:"unavailable"};let i=R(Oe(),"repositories",n.repositoryId);if(!Br(i))return{kind:"unavailable"};let o=(t.now??Date.now)(),a=R(i,"gc-state.json"),s=to(a);if(!t.force&&s&&o-Date.parse(s.lastSweepAt)<Ji)return{kind:"throttled",sweptAt:s.lastSweepAt};let c=yt(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=Zi(r,i,n.repositoryId,s?.unreferencedSince??{}),d=Qi({nowMs:o,...l,policy:{generationTtlMs:t.policy?.generationTtlMs??zi,budgetBytes:t.policy?.budgetBytes??Yi}}),p=0,u=0;for(let m of d.deleteWorktrees){if(!zr(m.lease))continue;let h=St(R(m.lease.localCacheDir,"cache-lifecycle.lock"));if(h)try{if(at(m.lease,!0))continue;try{_r({projectRoot:m.lease.projectRoot,cacheDir:m.lease.localCacheDir,cliVersion:e})}catch{continue}if(at(m.lease,!0))continue;ie(m.lease.localCacheDir,{recursive:!0,force:!0}),ie(m.leasePath,{force:!0}),u+=1}finally{h.release()}}for(let m of d.deleteLocks)ie(m.path,{force:!0});for(let m of d.deleteTemporaries)ie(m.path,{recursive:!0,force:!0});for(let m of d.deleteGenerations)ie(m.path,{recursive:!0,force:!0}),p+=m.size;xt(R(i,"evidence.db"));let g={kind:"swept",sweptAt:new Date(o).toISOString(),deletedWorktrees:u,deletedGenerations:d.deleteGenerations.length,deletedBytes:p,protectedGenerations:d.protectedGenerationIds.length},f={version:1,lastSweepAt:g.sweptAt,unreferencedSince:d.unreferencedSince,lastResult:g};return F(a,f,{spacing:2,trailingNewline:!0}),g}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function Zi(r,e,t,n){let i=new Set(ht(r).map(l=>$(l.path))),o=[];for(let l of st(R(e,"worktrees"))){if(!l.endsWith(".json"))continue;let d=R(e,"worktrees",l),p=eo(d);if(!p)continue;let u=$(p.projectRoot);o.push({leasePath:d,lease:p,managed:p.repositoryId===t&&zr(p),live:i.has(u)||Br(u),busy:at(p)})}let a=[];for(let l of st(R(e,"locks"))){let d=/^([a-f0-9]{64})\.lock$/.exec(l);if(!d)continue;let p=R(e,"locks",l),u=ct(p),g=u!==void 0&&j(u),f=d[1];a.push({generationId:f,path:p,live:g})}let s=[],c=[];for(let l of st(R(e,"generations"))){let d=/^\.tmp-(\d+)-/.exec(l);if(d){let g=R(e,"generations",l),f=Number(d[1]);try{c.push({path:g,size:Hr(g),live:Number.isSafeInteger(f)&&j(f)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let p=R(e,"generations",l),u;try{u=Me(p)}catch{continue}!u.isDirectory()||u.isSymbolicLink()||s.push({generationId:l,path:p,size:Hr(p),...n[l]===void 0?{}:{unreferencedAt:n[l]}})}return{leases:o,generations:s,locks:a,temporaries:c}}function zr(r){if(r.ownershipChecksum!==qt(r)||$(r.localCacheDir)!==$(Wt(r.projectRoot)))return!1;let e=$(Oe()),t=$(R(e,"projects")),n=$(r.localCacheDir);if(!n.startsWith(`${t}${Ur}`))return!1;try{let i=Me(e),o=Me(t),a=Me(n);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink())return!1;let s=qr(t);return qr(n).startsWith(`${s}${Ur}`)}catch{return!1}}function at(r,e=!1){for(let n of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=ct(R(r.localCacheDir,n));if(i!==void 0&&j(i))return!0}let t=ct(H(r.localCacheDir).lockPath);return t!==void 0&&j(t)}function eo(r){try{let e=JSON.parse(lt(r,"utf8"));return e.version!==1||typeof e.repositoryId!="string"||typeof e.worktreeId!="string"||typeof e.projectRoot!="string"||e.treeOid!==void 0&&typeof e.treeOid!="string"||typeof e.localCacheDir!="string"||e.baseGenerationId!==void 0&&typeof e.baseGenerationId!="string"||e.activeGenerationId!==void 0&&typeof e.activeGenerationId!="string"||typeof e.ownershipChecksum!="string"||!/^[a-f0-9]{64}$/.test(e.ownershipChecksum)||typeof e.lastAction!="string"||e.lastReason!==void 0&&typeof e.lastReason!="string"||typeof e.lastSeenAt!="string"?null:e}catch{return null}}function ct(r){try{let e=JSON.parse(lt(r,"utf8"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function to(r){try{let e=JSON.parse(lt(r,"utf8"));return e.version!==1||typeof e.lastSweepAt!="string"||!Number.isFinite(Date.parse(e.lastSweepAt))||!e.unreferencedSince||typeof e.unreferencedSince!="object"||!e.lastResult?null:e}catch{return null}}function st(r){try{return Vr(r)}catch{return[]}}function Hr(r){let e=0,t=[r];for(;t.length>0;){let n=t.pop();for(let i of Vr(n,{withFileTypes:!0})){let o=R(n,i.name);i.isDirectory()?t.push(o):i.isFile()&&(e+=Ki(o).size)}}return e}var io=1e3,oo=250,so=10;function ao(r){return r==="fresh"?null:{kind:"watch-startup",detail:`index ${r} when watch service started`}}async function co(r,e,t={}){let n=jr(r,e),i=n.projectRoot,o=V(i);o.watch={...o.watch,...t};let a=me(o);if(!a.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let s=B(i,o),c=H(s.cacheDir),l=$r(c.lockPath,i);if(!l.acquired)return;let d=Date.now(),p=d,u={state:"idle"},g,f,m,h=!1,S=!1,w=0,A=0,T=0,L=0,M,C,v=Jt(s.cacheDir),x=Ht(s.cacheDir);tt(v),rt(x);let ke=new Re({openDb:()=>tr(i)}),Pe=new we({projectRoot:i,currentGeneration:()=>Vt(s.dbPath)}),E=(I=!1)=>{if(!S)return;let q=Date.now();!I&&q-A<io||(A=q,Or(c.statePath,{version:1,protocolVersion:je,pid:P.pid,projectRoot:i,...n.worktreeId?{worktreeId:n.worktreeId}:{},cliVersion:e,startedAt:new Date(d).toISOString(),heartbeatAt:new Date(q).toISOString(),lastActivityAt:new Date(p).toISOString(),...a.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(p+a.idleTimeoutMs).toISOString()},watcher:u,...u.state==="idle"&&g?{indexGeneration:g}:{},...f?{lastRefresh:f}:{},...m?{lastError:m}:{},typescriptSemantic:{...ke.status(),...M===void 0?{}:{busyUntil:new Date(M).toISOString()}},typescriptIndex:{...Pe.status(),...C===void 0?{}:{busyUntil:new Date(C).toISOString()}}}))},G=()=>{p=Date.now()},oe=new he({projectRoot:i,config:{...o,watch:a},languages:o.languages,onStatus(I){u=I,I.state!=="idle"&&(g=void 0),I.state!=="idle"&&G(),E(!0)},onReindexComplete(){G();let I=Ge(i,o,s);f=I.lastRefresh,g=I.state==="fresh"?Z(s.dbPath)??void 0:void 0,m=void 0,E(!0)},onError(I){G(),g=void 0,m={at:new Date().toISOString(),message:I.message},E(!0)}}),se=()=>{h=!0};P.once("SIGINT",se),P.once("SIGTERM",se);try{oe.start();let I=Ge(i,o,s);f=I.lastRefresh,g=I.state==="fresh"?Z(s.dbPath)??void 0:void 0;let q=ao(I.state);for(q&&oe.requestRefresh(q,{immediate:!0}),G(),S=!0,E(!0);!h;){let Jr=Fr(x,Pe,{beforeRequest(D){C=D+5e3,E(!0)},afterRequest(){C=void 0,E(!0)}}),Qr=Dr(v,ke,{beforeRequest(D){M=D+5e3,E(!0)},afterRequest(){M=void 0,E(!0)}}),ae=Date.now();if(ae-L>=6e4&&(L=ae,Kr(i,e)),ae-T>=oo){T=ae;let D=Wr(c.activityPath);D&&D.atMs>p&&(p=D.atMs),D?.refreshRequestedAtMs!==void 0&&D.refreshRequestedAtMs>w&&(w=D.refreshRequestedAtMs,G(),oe.requestRefresh({kind:"watch-demand",detail:D.refreshDetail??"stale index observed by a command"},{immediate:!0}))}if((Qr>0||Jr>0)&&(G(),E(!0)),E(),Gr({watcher:u,lastActivityAtMs:p,nowMs:Date.now(),idleTimeoutMs:a.idleTimeoutMs}))break;await lo(so)}}finally{P.off("SIGINT",se),P.off("SIGTERM",se),ke.closeTypeScriptService(),Pe.close(),oe.stop(),Yr(c.statePath,{force:!0}),Yr(c.activityPath,{force:!0}),l.release()}}function lo(r){return new Promise(e=>setTimeout(e,r))}var po=P.argv[1]?no(ro(P.argv[1])).href:null;if(po===import.meta.url){let r=P.argv[2],e=P.argv[3],t=uo(P.argv[4]);if(!r||!e)console.error("watch-service: expected <project-root> <cli-version>"),P.exitCode=1;else try{await co(r,e,t)}catch(n){console.error(`watch-service: ${n instanceof Error?n.message:String(n)}`),P.exitCode=1}}function uo(r){if(!r)return{};try{let e=JSON.parse(r);return e&&typeof e=="object"?e:{}}catch{return{}}}export{co as runWatchServiceServer,ao as startupRefreshTrigger};
|
|
40
|
+
ORDER BY start_line, end_line`,e)}function Un(r){return{symbolId:r.id,symbol:r.symbol,documentId:r.document_id,startLine:r.start_line,startChar:r.start_char??0,endLine:r.end_line,endChar:r.end_char??0,relativePath:r.relative_path,leaf:_(r.symbol),parentTypeName:K(r.symbol),isFunctionLike:cr(r.symbol),isTypeLike:O(r.symbol)==="type",kind:r.kind??null,documentation:r.documentation??null,enclosingSymbol:r.enclosing_symbol??null}}function fr(r,e={}){return Hn(r,e.scope)}function Hn(r,e){return U(r,{scope:e,includeIgnored:!1}).flatMap(t=>W(r,t)).filter(t=>!r.isIgnored(t.relativePath))}function Bn(r,e,t){let n=Se(r).forFile(e,{text:!0}).text,i=Lt(r,e);return i?Qn(t,i,n):n?Vn(t,n):t}function Vn(r,e){let t=e.split(/\r?\n/),n=Kn(r,t),i=zn(r,n),o=Yn(i,t);return Jn(r,o)}function Kn(r,e){let t=r.some(i=>ve(i.symbol))?ii(e):null,n=new Map;for(let i of r)n.set(i.symbolId,ni(e,t,i));return n}function zn(r,e){return r.filter(t=>ve(t.symbol)).map(t=>({definition:t,startLine:e.get(t.symbolId)??t.startLine})).sort((t,n)=>t.startLine-n.startLine||t.definition.startLine-n.definition.startLine||t.definition.symbol.localeCompare(n.definition.symbol))}function Yn(r,e){let t=new Map;for(let n=0;n<r.length;n+=1){let i=r[n],o=r[n+1],a=o?Math.max(i.startLine,o.startLine-1):e.length-1;t.set(i.definition.symbolId,{startLine:i.startLine,endLine:oi(e,i.definition,i.startLine,a)})}return t}function Jn(r,e){return r.map(t=>{let n=e.get(t.symbolId);return n?{...t,startLine:n.startLine,endLine:n.endLine}:t})}function Qn(r,e,t=null){let n=new Map;for(let i of e){let o=n.get(i.name);o?o.push(i):n.set(i.name,[i])}return r.map(i=>{if(!ri(i)||!i.leaf)return ur(i,t);let o=n.get(i.leaf);if(!o||o.length===0)return ur(i,t);let a=t?Xn(i,o,t):null;if(a)return{...i,startLine:a.startLine,endLine:a.endLine};let s=o[0],c=Math.abs(s.startLine-i.startLine);for(let l=1;l<o.length;l+=1){let d=o[l],u=Math.abs(d.startLine-i.startLine);u<c&&(s=d,c=u)}return{...i,startLine:s.startLine,endLine:s.endLine}})}function Xn(r,e,t){let n=Zn(r.symbol);if(!n)return null;let i=t.split(/\r?\n/),o=new RegExp(`\\b${Q(n)}\\b`);for(let a of e){let s=ei(i,a.startLine);if(s&&o.test(s))return a}return null}function Zn(r){return r.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function ei(r,e){for(let t=e;t>=0;t-=1){let n=r[t]?.trim()??"";if(n){if(/^impl\b/.test(n))return ti(r,t,e);if(/^(?:struct|enum|trait|mod)\b/.test(n))return null}}return null}function ti(r,e,t){let n=[];for(let i=e;i<=t;i+=1){let o=r[i]??"";if(n.push(o),o.includes("{"))break}return n.join(" ")}function ri(r){return ve(r.symbol)?!0:O(r.symbol)==="term"&&K(r.symbol)===null}function ur(r,e){if(!e||!r.leaf||O(r.symbol)!=="term"||K(r.symbol)!==null)return r;let t=Q(r.leaf),n=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${t}\\b`),o=e.split(/\r?\n/).findIndex(a=>n.test(a));return o>=0?{...r,startLine:o,endLine:o}:r}function ni(r,e,t){if(!ve(t.symbol))return t.startLine;let n=Math.max(0,Math.min(t.startLine,r.length-1));if(!e)return n;let i=e.get(t.leaf);if(!i||i.length===0)return n;let o=null;for(let a of i){let s=Math.abs(a-t.startLine);(!o||s<o.distance)&&(o={line:a,distance:s})}return o?.line??n}function ii(r){let e=/\b(?:function|def|fn)\s+([A-Za-z_$][\w$]*)/g,t=/\b([A-Za-z_$][\w$]*)\s*[:=]\s*(?:async\s*)?(?:function\b|\()/g,n=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,i=/\b([A-Za-z_$][\w$]*)\s*\(/g,o=new Map,a=(s,c)=>{let l=o.get(s);if(!l){o.set(s,[c]);return}l[l.length-1]!==c&&l.push(c)};for(let s=0;s<r.length;s+=1){let c=r[s]??"";for(let d of c.matchAll(e))d[1]&&a(d[1],s);for(let d of c.matchAll(t))d[1]&&a(d[1],s);let l=c.match(n);l?.[1]&&a(l[1],s);for(let d of c.matchAll(i))d[1]&&a(d[1],s)}return o}function oi(r,e,t,n){let i=Math.max(t,Math.min(r.length-1,n)),o=Math.max(t,Math.min(i,e.endLine)),a=0,s=0,c=!1;for(let l=t;l<=i;l+=1){let d=si(r[l]??"");for(let u of d)u==="{"?(a+=1,c=!0):u==="}"?a=Math.max(0,a-1):u==="("?s+=1:u===")"&&(s=Math.max(0,s-1));if(c&&a===0||!c&&s===0&&l>=o)return l}return o}function si(r){let e="",t=null,n=!1;for(let i=0;i<r.length;i+=1){let o=r[i],a=r[i+1];if(!t&&o==="/"&&a==="/"){e+=" ".repeat(r.length-i);break}if(t){if(n){n=!1,e+=" ";continue}if(o==="\\"){n=!0,e+=" ";continue}o===t&&(t=null),e+=" ";continue}if(o==='"'||o==="'"||o==="`"){t=o,e+=" ";continue}e+=o}return e}function ve(r){return r.includes("().")}function w(r,e,t){if(r.has(e))return r.get(e);let n=t();return r.set(e,n),n}import mr from"path";function ai(r,e){return r.getReferences().map(t=>{let n=t.getNode();return xe(n,e)})}function ci(r){let e=r;return typeof e.findReferences=="function"?e.findReferences():[]}function hr(r,e,t,n){let i=[];for(let o of ci(r))for(let a of ai(o,n))a.file===e.relativePath&&a.line>=e.startLine&&a.line<=e.endLine||i.push(a);for(let o of t)i.push(o);return z(i)}function gr(r,e,t,n){let i=[],o=t?.getStart();for(let a of r.getReferences()){let s=a.getNode();Y(n,s.getSourceFile().getFilePath())===e&&(o!==void 0&&s.getStart()===o||i.push({location:xe(s,n),node:s}))}return i}function xe(r,e){let t=r.getSourceFile(),n=t.getLineAndColumnAtPos(r.getStart());return{file:Y(e,t.getFilePath())??t.getBaseName(),line:n.line-1,column:n.column-1}}function yr(r,e,t){let n=r.getSourceFile(),i=Be(n,r),o=r.getText(),a=new RegExp(`\\b${Q(o)}\\b`,"g"),s=n.getFullText().split(`
|
|
41
|
+
`),c=[];for(let l=0;l<s.length;l++){if(l===i)continue;let d=s[l]??"";a.lastIndex=0;let u;for(;(u=a.exec(d))!==null;)c.push({file:e,line:l,column:u.index})}return z(c.filter(l=>Y(t,mr.join(t,l.file))===e))}function He(r){for(let e=r;e;e=e.getParent()){let t=e.getKindName();if(t.includes("Type")||t==="InterfaceDeclaration"||t==="TypeAliasDeclaration")return!0;if(t==="CallExpression"||t==="NewExpression"||t==="ExpressionStatement")return!1}return!1}function Be(r,e){return r.getLineAndColumnAtPos(e.getStart()).line-1}function z(r){let e=new Set,t=[];for(let n of r){let i=`${n.file}:${n.line}:${n.column}`;e.has(i)||(e.add(i),t.push(n))}return t}function Y(r,e){let t=mr.relative(r||process.cwd(),e).replace(/\\/g,"/");return!t||t.startsWith("..")?null:t}function Sr(r,e,t,n){let i=li(e,n);return i.size===0?new Map:di(r,t,i)}function li(r,e){let t=new Map;for(let n of W(r,e)){let i=_(n.symbol)??n.leaf;if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push(n)}return t}function di(r,e,t){let n=new Map,i=new Map;return e.forEachDescendant(o=>{for(let a of ui(r,o)){let s=t.get(a);if(!s)continue;let c=Be(e,o);for(let l of s){if(c<l.startLine-1||c>l.endLine+1)continue;let d=Math.abs(c-l.startLine),u=i.get(l.symbolId);u!==void 0&&u<=d||(i.set(l.symbolId,d),n.set(l.symbolId,o))}}}),n}function ui(r,e){let t=[],n=i=>{i&&!t.includes(i)&&t.push(i)};if("getNameNode"in e&&typeof e.getNameNode=="function"){let i=e.getNameNode();n(i?.getText())}if("getName"in e&&typeof e.getName=="function"){let i=e.getName();n(i)}return r.Node.isIdentifier(e)&&n(e.getText()),t}var pi=J("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function br(r,e,t,n){let i=ze(r,e),o=Ve(i.get(n)??[],t);if(o)return o;let a=[];for(let s of i.values())for(let c of s)((c.leaf||_(c.symbol)||"").includes(n)||c.symbol.includes(n))&&a.push(c);return Ve(a,t)}function Ke(r,e,t,n){return Ve(ze(r,e).get(n)??[],t)}function vr(r,e){let t=new Map;for(let[n,i]of ze(r,e)){let o=i[0];o&&t.set(n,o)}return t}function ze(r,e){return pi.get(r,e,()=>{let t=new Map;for(let n of W(r,e)){let i=n.leaf||_(n.symbol);if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push({...n,leaf:i})}for(let n of t.values())n.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return t})}function Ve(r,e){let t=null,n=Number.POSITIVE_INFINITY;for(let i of r){let o=Math.abs(i.startLine-e);(o<n||o===n&&t&&i.startLine<t.startLine)&&(t=i,n=o)}return t}import Ye from"path";function xr(r,e){let t=new Map,n=null,i=null,o=()=>(i??=U(r,{extensions:le}),i),a=()=>(n??=N("typescript.source-file-index",()=>fi(r.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),n),s=c=>de(c)?w(t,c,()=>{let l=ee(Ye.resolve(r.config.projectRoot,c));for(let{project:d,sourceFiles:u}of a()){let p=u.get(l)??null;if(p||(p=d.addSourceFileAtPathIfExists(l)??null,p&&u.set(ee(p.getFilePath()),p)),p)return{project:d,sourceFile:p}}return null}):null;return{sourceFile:c=>s(c)?.sourceFile??null,sourceFileMatch:s,indexedTypeScriptLikeDocuments:o}}function fi(r,e,t){let n=e.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[ee(o.getFilePath()),o]))}));for(let i of t){let o=ee(Ye.resolve(r,i));for(let a of n){if(a.sourceFiles.has(o))break;let s=a.project.addSourceFileAtPathIfExists(o)??null;if(s){a.sourceFiles.set(ee(s.getFilePath()),s);break}}}return n}function ee(r){return Ye.resolve(r)}function Je(r,e){for(let t of r)if(e===t.name||e.startsWith(`${t.name}/`))return t.name;return null}function Ir(r){let e=`${r.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as te,readFileSync as mi}from"fs";import x from"path";var Qe=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Xe(r,e){let n=e?x.dirname(x.join(r,e)):r,i=x.resolve(r);for(;n.startsWith(i);){for(let a of Qe){let s=x.join(n,a);if(te(s))return s}let o=x.dirname(n);if(o===n)break;n=o}for(let o of Qe){let a=x.join(r,o);if(te(a))return a}return null}function Rr(r){let e=r.config.projectRoot,t=new Set(hi(e,r.config.semantic?.typescript?.tsconfigs)),n=U(r,{includeIgnored:!1,extensions:le});for(let i of n){let o=Xe(e,i);o&&t.add(x.resolve(o))}if(t.size===0){let i=Xe(e);i&&t.add(x.resolve(i))}return[...t].filter(i=>!Cr(e,i)).sort((i,o)=>i.localeCompare(o))}function hi(r,e=[]){let t=new Set;for(let n of e){let i=x.isAbsolute(n)?n:x.join(r,n);te(i)&&t.add(x.resolve(i))}for(let n of gi(r))for(let i of Qe){let o=x.join(n,i);te(o)&&t.add(x.resolve(o))}if(t.size===0){let n=Xe(r);n&&t.add(x.resolve(n))}return[...t].filter(n=>!Cr(r,n)).sort((n,i)=>n.localeCompare(i))}function gi(r){let e=x.join(r,"package.json");if(!te(e))return[];let t;try{t=JSON.parse(mi(e,"utf8"))}catch{return[]}return(Array.isArray(t.workspaces)?t.workspaces:t.workspaces?.packages??[]).flatMap(i=>Pt(r,i))}function Cr(r,e){let t=x.relative(r,e).replace(/\\/g,"/");return t.startsWith("..")||t.includes("/node_modules/")||t.startsWith("node_modules/")||t.includes("/dist/")||t.startsWith("dist/")}var yi=32;function Dr(r,e,t,n={}){return N("typescript.provider.construct",()=>new et(r,e,t),()=>({tsconfigs:t.length,reusedProjects:n.reusedProjects===!0}))}var et=class{constructor(e,t,n){this.db=e;this.tsMorph=t;this.projects=n;this.workspacePackages=kt(e.config.projectRoot),this.sourceFiles=xr(e,n)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(e=>e.tsconfigPath)}}importUsage(e){return w(this.importUsageCache,e,()=>{let t=this.sourceFiles.sourceFile(e);if(!t)return[];let n=bi();return N("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,t,n),()=>({file:e,...n}))})}referencesFor(e){return w(this.referencesCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,t)})}referencesForDefinitions(e,t={}){let n=new Map,i=ce(),o=[];for(let d of e){let u=this.referencesCache.get(d.symbolId);u?n.set(d.symbolId,u):o.push(d)}if(o.length===0)return n;let a=o,s=t.exact?[]:o.filter(d=>!wr(d));if(s.length>=yi){let d=this.referencesForDefinitionsBySymbolScan(s);for(let u of s){let p=d.get(u.symbolId)??[];this.referencesCache.set(u.symbolId,p),n.set(u.symbolId,p)}if(a=o.filter(u=>wr(u)),a.length===0)return n}let c=new Map;for(let d of a){let u=c.get(d.relativePath);u?u.push(d):c.set(d.relativePath,[d])}let l=[];for(let[d,u]of c){let p=kr();N("typescript.references-map.file",()=>{let g=this.definitionNodesForFile(d);for(let f of u){i&&(p.cacheMisses+=1);let m=g.get(f.symbolId)??null;i&&(m?p.nodeHits+=1:p.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(f,m,i?p:void 0);this.referencesCache.set(f.symbolId,h),n.set(f.symbolId,h)}catch{p.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:d,definitions:u.length,...Pr(p)}))}if(l.length>0){let d=this.referencesForDefinitionsBySymbolScan(l);for(let u of l){let p=d.get(u.symbolId)??[];this.referencesCache.set(u.symbolId,p),n.set(u.symbolId,p)}}return n}referenceFragmentsForFiles(e){let t=fr(this.db).filter(o=>de(o.relativePath)),n=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,n);return Wt(t,i,n)}referencesForDefinitionsBySymbolScan(e,t){let n=ce(),i=kr(),o=new Map,a=new Set(e.map(c=>c.symbolId)),s=new Map(e.map(c=>[c.symbolId,c]));for(let c of e)o.set(c.symbolId,[]);return N("typescript.references-map.inverted-scan",()=>{let c=n?y.now():0,l=t?this.packageImportReferencesForFiles(t):this.packageImportReferences();for(let h of e){let S=l.get(h.symbolId)??[];if(S.length>0){let M=o.get(h.symbolId)??[];M.push(...S),o.set(h.symbolId,M)}n&&(i.packageReferenceCount+=S.length)}n&&(i.packageRefsMs+=y.now()-c);let d=new Map,u=new Map,p=this.hierarchyTargetsForDefinitions(e),g=new Set(e.map(h=>h.leaf).filter(Boolean)),f=n?y.now():0;for(let h of t??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(h))continue;let S=this.sourceFiles.sourceFile(h);S&&(n&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(S,h,a,s,p,g,d,u,o,n?i:void 0))}n&&(i.scanMs+=y.now()-f);let m=n?y.now():0;this.addHierarchyMemberReferences(e,o,n?i:void 0),n&&(i.hierarchyMs+=y.now()-m);for(let[h,S]of o){let M=z(S);o.set(h,M),n&&(i.referenceCount+=M.length)}},()=>({definitions:e.length,...Pr(i)})),o}addReferencesFromSourceFileScan(e,t,n,i,o,a,s,c,l,d){let u=this.compilerCheckerForSourceFile(e),p=e.compilerNode,g=Ii(e),f=m=>{if(this.tsMorph.ts.isIdentifier(m)){if(d&&(d.identifiers+=1),!a.has(m.text)&&!g.has(m.text)){this.tsMorph.ts.forEachChild(m,f);return}let h=this.compilerReferenceSymbol(u,m,d);if(h){let S;s.has(h)?S=s.get(h)??null:(S=this.referenceDefinitionFromCompilerSymbol(h),s.set(h,S)),d&&(S?d.targetHits+=1:d.targetMisses+=1);let M=w(c,h,()=>this.compilerSymbolKeys(h)),A=null,P=null,L=S&&n.has(S.symbolId)?i.get(S.symbolId):void 0;if(L&&(A=Ze(p,m),!Mr(L,t,A))){let D=p.getLineAndCharacterOfPosition(m.getStart(p));P={file:t,line:D.line,column:D.character};let C=l.get(L.symbolId)??[];C.push(P),l.set(L.symbolId,C),d&&(d.requestedHits+=1)}for(let D of M)for(let C of o.get(D)?.values()??[]){if(A??=Ze(p,m),Mr(C,t,A))continue;if(!P){let I=p.getLineAndCharacterOfPosition(m.getStart(p));P={file:t,line:I.line,column:I.character}}let b=l.get(C.symbolId)??[];b.push(P),l.set(C.symbolId,b),d&&(d.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(m,f)};f(p)}hierarchyTargetsForDefinitions(e){let t=new Map;for(let n of e){let i=this.nodeForDefinition(n),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let a=o.parent;if(!this.isHierarchyContainer(a))continue;let s=this.compilerCheckerForSourceFile(i.getSourceFile()),c=s.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(s,a,c))for(let d of this.compilerSymbolKeys(l)){let u=t.get(d)??new Map;u.set(n.symbolId,n),t.set(d,u)}}return t}hierarchyMemberSymbols(e,t,n){let i=new Set,o=new Set,a=(s,c,l)=>{if(!o.has(s)){o.add(s),i.add(c);for(let d of l){let u=d.getProperty(n.name);u&&a(d,u,this.hierarchyAncestorTypesForType(e,d))}}};return a(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}addHierarchyMemberReferences(e,t,n){let i=new Map;for(let o of e){let a=this.nodeForDefinition(o),s=a?.compilerNode;if(!s||!this.isHierarchyMethod(s))continue;let c=s.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(a.getSourceFile()),d=l.getSymbolAtLocation(s.name);if(!d)continue;let u=s.getSourceFile(),p=u.getLineAndCharacterOfPosition(s.name.getStart(u)),g={definition:o,location:{file:o.relativePath,line:p.line,column:p.character}},f=t.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(l,c,d))if(h!==d)for(let S of this.compilerSymbolLocations(h))f.push(S),n&&(n.hierarchyReferences+=1);t.set(o.symbolId,f);let m=this.hierarchyRootMemberSymbols(l,c,d);for(let h of m){let S=i.get(h)??new Map;S.set(o.symbolId,g),i.set(h,S)}n&&(n.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){n&&(n.hierarchyFamilies+=1);for(let{definition:a}of o.values()){let s=t.get(a.symbolId)??[];for(let c of o.values())c.definition.symbolId!==a.symbolId&&(s.push(c.location),n&&(n.hierarchyReferences+=1));t.set(a.symbolId,s)}}}hierarchyRootMemberSymbols(e,t,n){let i=new Set,o=new Set,a=(s,c,l)=>{if(o.has(s))return;o.add(s);let d=!1;for(let u of l){let p=u.getProperty(n.name);p&&(d=!0,a(u,p,this.hierarchyAncestorTypesForType(e,u)))}if(!d)for(let u of this.compilerSymbolKeys(c))i.add(u)};return a(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}compilerSymbolKeys(e){return(e.declarations??[]).map(t=>{let n=t.getSourceFile();return`${n.fileName}\0${t.getStart(n)}\0${e.name}`})}compilerSymbolLocations(e){let t=[];for(let n of e.declarations??[]){let i=n.getSourceFile(),o=Y(this.db.config.projectRoot,i.fileName);if(!o)continue;let a=n.name,s=i.getLineAndCharacterOfPosition((a??n).getStart(i));t.push({file:o,line:s.line,column:s.character})}return t}baseTypes(e,t){try{return e.getBaseTypes(t)??[]}catch{return[]}}hierarchyAncestorTypes(e,t){let n=new Set(this.hierarchyAncestorTypesForType(e,e.getTypeAtLocation(t)));for(let i of t.heritageClauses??[])for(let o of i.types)n.add(e.getTypeAtLocation(o));return[...n]}hierarchyAncestorTypesForType(e,t){let n=new Set(this.baseTypes(e,t));for(let i of t.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let a of o.types)n.add(e.getTypeAtLocation(a));return[...n]}isHierarchyMethod(e){return this.tsMorph.ts.isMethodDeclaration(e)||this.tsMorph.ts.isMethodSignature(e)}isHierarchyContainer(e){return this.tsMorph.ts.isClassDeclaration(e)||this.tsMorph.ts.isClassExpression(e)||this.tsMorph.ts.isInterfaceDeclaration(e)}compilerReferenceSymbol(e,t,n){n&&(n.symbolLookups+=1);let i=e.getSymbolAtLocation(t);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return n&&(n.aliasResolutions+=1),e.getAliasedSymbol(i)}catch{return i}}}calleesFor(e){return w(this.calleesCache,e.symbolId,()=>w(this.fileCalleesCache,e.relativePath,()=>this.calleeMapForFile(e.relativePath)).get(e.symbolId)??[])}calleesForDefinitions(e){let t=new Map,n=new Map;for(let i of e){let o=n.get(i.relativePath);o?o.push(i):n.set(i.relativePath,[i])}for(let[i,o]of n){let a=this.fileCalleesCache.get(i),s=new Set(o.map(l=>l.symbolId)),c=a??this.calleeMapForFile(i,s);for(let l of o){let d=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,d),t.set(l.symbolId,d)}}return t}referencesForDefinitionNode(e,t,n){let i=n?y.now():0,o=this.packageImportReferencesForDefinition(e);if(n&&(n.packageRefsMs+=y.now()-i,n.packageReferenceCount+=o.length),!t)return o;let a=n?y.now():0,s=hr(t,e,o,this.db.config.projectRoot);return n&&(n.semanticRefsMs+=y.now()-a,n.referenceCount+=s.length),s}signatureFor(e){return w(this.signatureCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);if(!t||!this.tsMorph.Node.isFunctionDeclaration(t)&&!this.tsMorph.Node.isMethodDeclaration(t)&&!this.tsMorph.Node.isArrowFunction(t)&&!this.tsMorph.Node.isFunctionExpression(t)&&!this.tsMorph.Node.isConstructorDeclaration(t))return null;let n=t.getType().getCallSignatures()[0];if(!n)return null;let i=n.getParameters().map(a=>{let s=a.getDeclarations()[0],c=s?a.getTypeAtLocation(s).getText(s):a.getValueDeclaration()?.getType().getText()??"unknown";return Tr(c)}),o=n.getReturnType().getText(t);return`(${i.join(",")})=>${Tr(o)}`})}importUsageForSourceFile(e,t,n){let i=[],o=new Map;for(let a of t.getImportDeclarations()){n.declarations+=1;let s=Ne(this.db,e,a.getModuleSpecifierValue()),c=a.getImportClause()?.isTypeOnly()??!1;for(let l of tt(a)){n.entries+=1;let d=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(d?n.bindingSymbols+=1:n.missingBindingSymbols+=1);let u={sourcePath:s,entry:l,typeOnlyDeclaration:c,bindingSymbol:d,references:[]};if(i.push(u),c||!l.localName||!d)continue;let p=o.get(l.localName);p?p.push(u):o.set(l.localName,[u])}}return o.size>0&&t.forEachDescendant(a=>{if(a.getKindName()!=="Identifier")return;let s=o.get(a.getText());if(!s||vi(a))return;n.scannedIdentifiers+=1;let c=a.getSymbol()?.compilerSymbol;if(n.symbolLookups+=1,!!c){for(let l of s)if(l.bindingSymbol===c){l.references.push({location:xe(a,this.db.config.projectRoot),node:a}),n.matchedReferences+=1;break}}}),i.map(a=>a.typeOnlyDeclaration?Si(e,a.sourcePath,a.entry):a.entry.identifier&&!a.bindingSymbol?(n.fallbackEntries+=1,this.valueImportUsageForEntry(e,a.sourcePath,a.entry)):this.valueImportUsageFromLocations(e,a.sourcePath,a.entry,a.references))}valueImportUsageForEntry(e,t,n){let i=n.identifier?n.identifier.findReferences():[],o=[];for(let a of i)for(let s of gr(a,e,n.identifier,this.db.config.projectRoot))o.push(s);return this.valueImportUsageFromLocations(e,t,n,o)}valueImportUsageFromLocations(e,t,n,i){let o=i.some(c=>!He(c.node)),a=i.some(c=>He(c.node)),s=n.isTypeOnly;return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:s,isUsed:s||i.length>0,isTypeUsed:s||a,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(e){return this.packageImportReferences().get(e.symbolId)??[]}packageImportReferencesForFiles(e){let t=new Map,n=new Set;for(let o of e){let a=this.sourceFiles.sourceFile(o);if(a)for(let s of a.getImportDeclarations()){let c=Je(this.workspacePackages,s.getModuleSpecifierValue());c&&n.add(c)}}if(n.size===0)return t;let i=this.packageExportsForNames(n);for(let o of e)this.addPackageImportReferencesForDocument(t,i,o);for(let[o,a]of t)t.set(o,z(a));return t}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let e=new Map,t=this.packageExports();for(let n of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(e,t,n);for(let[n,i]of e)e.set(n,z(i));return this.packageImportReferenceIndex=e,e}addPackageImportReferencesForDocument(e,t,n){if(this.db.isIgnored(n))return;let i=this.sourceFiles.sourceFileMatch(n);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(e,t,n,o)}addPackageImportReferencesForDeclaration(e,t,n,i){let o=Je(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let a=t.get(o);if(a)for(let s of tt(i)){if(s.kind!=="named"||!s.identifier)continue;let c=a.get(s.importedName);if(!c||c.size===0)continue;let l=yr(s.identifier,n,this.db.config.projectRoot);l.length>0&&wi(e,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(e=>e.name))),this.packageExportIndex)}packageExportsForNames(e){let t=new Map;for(let n of this.workspacePackages){if(!e.has(n.name))continue;let i=new Map;for(let o of Ir(n))this.collectPackageExports(n,o,i,new Set);i.size>0&&t.set(n.name,i)}return t}collectPackageExports(e,t,n,i){if(i.has(t))return;i.add(t);let o=this.sourceFiles.sourceFile(t);if(o)for(let a of o.getExportDeclarations()){let s=a.getModuleSpecifierValue(),c=s?Ne(this.db,t,s):t;if(!c||!c.startsWith(`${e.relativeDir}/src/`))continue;let l=a.getNamedExports();if(l.length===0){if(a.isNamespaceExport())continue;this.collectPackageExports(e,c,n,i);continue}for(let d of l){let u=d.getNameNode().getText(),p=d.getAliasNode()?.getText()??u,g=this.indexedDefinitionByLeaf(c,u);if(!g)continue;let f=n.get(p);f||(f=new Set,n.set(p,f)),f.add(g.symbolId)}}}indexedDefinitionByLeaf(e,t){return w(this.indexedDefinitionLeafCache,e,()=>vr(this.db,e)).get(t)??null}nodeForDefinition(e){return w(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return w(this.fileDefinitionNodeCache,e,()=>{let t=this.sourceFiles.sourceFile(e);return t?Sr(this.tsMorph,this.db,t,e):new Map})}referenceDefinitionFromCompilerSymbol(e){return this.definitionFromCompilerSymbol(e,void 0,!0)}definitionFromCompilerSymbol(e,t,n=!1){let i=e.name,o=t?y.now():0,a=e.declarations??[];t&&(t.declarationsMs+=y.now()-o,t.declarationChecks+=a.length);for(let s of a){let c=t?y.now():0,l=s.getSourceFile(),d=Y(this.db.config.projectRoot,l.fileName),u=l.getLineAndCharacterOfPosition(s.getStart(l)).line;if(t&&(t.declarationLocationMs+=y.now()-c),!d||this.db.isIgnored(d))continue;let p=t?y.now():0,g=this.compilerDeclarationName(s),f=n?Ke(this.db,d,u,i)??(g&&g!==i?Ke(this.db,d,u,g):null):br(this.db,d,u,i);if(t&&(t.indexedLookupMs+=y.now()-p),f)return{symbolId:f.symbolId,symbol:f.symbol,file:f.relativePath,line:f.startLine}}return null}compilerDeclarationName(e){let t=e.name;return t&&this.tsMorph.ts.isIdentifier(t)?t.text:null}calleeMapForFile(e,t){let n=ce(),i=0,o=0,a=0,s=0,c=0,l=0,d=0,u=0,p=n?Ci():void 0;return N("typescript.callee-map.file",()=>{let g=n?y.now():0,f=this.sourceFiles.sourceFile(e);if(n&&(c=Math.round(y.now()-g)),!f)return new Map;let m=n?y.now():0,h=W(this.db,e).sort((b,I)=>b.startLine-I.startLine||I.endLine-b.endLine);if(n&&(l=Math.round(y.now()-m)),i=h.length,h.length===0)return new Map;let S=new Map,M=n?y.now():0,A=this.compilerCheckerForSourceFile(f),P=f.compilerNode;n&&(d=Math.round(y.now()-M));let L=new Map,D=b=>{if(this.tsMorph.ts.isCallExpression(b)||this.tsMorph.ts.isNewExpression(b)){n&&(o+=1);let I=this.semanticCalleeForCallNode(A,P,h,b,L,t,p);I&&(n&&(a+=1),xi(S,I.callerId,I.target))}this.tsMorph.ts.forEachChild(b,D)},C=n?y.now():0;D(P),n&&(u=Math.round(y.now()-C));for(let[b,I]of S)S.set(b,ki(I));return s=S.size,S},()=>({relativePath:e,definitions:i,callNodes:o,resolvedCallees:a,outputRows:s,requestedDefinitions:t?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:u,...p?Mi(p):{}}))}semanticCalleeForCallNode(e,t,n,i,o,a,s){let c=s?y.now():0,l=Ri(n,Ze(t,i));if(s&&(s.callerLookupMs+=y.now()-c),!l)return null;if(a&&!a.has(l.symbolId))return s&&(s.skippedUnrequestedCallers+=1),null;let d=i.expression,u=this.compilerSymbolForExpression(e,d,s),p=null;if(u)if(s&&(s.targetSymbolHits+=1),o.has(u))s&&(s.compilerSymbolCacheHits+=1),p=o.get(u)??null;else{s&&(s.compilerSymbolCacheMisses+=1);let g=s?y.now():0;p=this.definitionFromCompilerSymbol(u,s),s&&(s.targetLookupMs+=y.now()-g),o.set(u,p)}else s&&(s.targetMisses+=1);return p?{callerId:l.symbolId,target:{symbol:p.symbol,file:p.file,line:p.line}}:null}compilerSymbolForExpression(e,t,n){let i=n?y.now():0,o=e.getSymbolAtLocation(t);if(n&&(n.expressionSymbolMs+=y.now()-i),o)return o;n&&(n.typeFallbacks+=1);let a=n?y.now():0,s=e.getTypeAtLocation(t).getSymbol();return n&&(n.typeSymbolMs+=y.now()-a),s}compilerCheckerForSourceFile(e){let t=e.getProject(),n=this.compilerCheckerCache.get(t);return n||(n=t.getTypeChecker().compilerObject,this.compilerCheckerCache.set(t,n)),n}};function tt(r){let e=[],t=r.getDefaultImport();t&&e.push({identifier:t,importedName:"default",localName:t.getText(),kind:"default",isTypeOnly:r.getImportClause()?.isTypeOnly()??!1});let n=r.getNamespaceImport();n&&e.push({identifier:n,importedName:"*",localName:n.getText(),kind:"namespace",isTypeOnly:r.getImportClause()?.isTypeOnly()??!1});for(let i of r.getNamedImports()){let o=i.getNameNode(),s=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);e.push({identifier:s,importedName:o.getText(),localName:s?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(r.getImportClause()?.isTypeOnly()??!1)})}return e.length===0&&e.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),e}function Si(r,e,t){return{importer:r,sourcePath:e,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function bi(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function vi(r){for(let e=r;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function xi(r,e,t){let n=r.get(e);n||(n=[],r.set(e,n)),n.push(t)}function Ii(r){let e=new Set;for(let t of r.getImportDeclarations())for(let n of tt(t))n.localName&&e.add(n.localName);return e}function Ri(r,e){let t=null;for(let n of r)e<n.startLine||e>n.endLine||(!t||n.startLine>=t.startLine)&&(t=n);return t}function Ze(r,e){return r.getLineAndCharacterOfPosition(e.getStart(r)).line}function Mr(r,e,t){return e===r.relativePath&&t>=r.startLine&&t<=r.endLine}function wr(r){return r.symbol.includes("#")?O(r.symbol)==="type"&&r.relativePath.endsWith(".d.ts"):!1}function Ci(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function Mi(r){return{...r,callerLookupMs:Math.round(r.callerLookupMs),expressionSymbolMs:Math.round(r.expressionSymbolMs),typeSymbolMs:Math.round(r.typeSymbolMs),targetLookupMs:Math.round(r.targetLookupMs),declarationsMs:Math.round(r.declarationsMs),declarationLocationMs:Math.round(r.declarationLocationMs),indexedLookupMs:Math.round(r.indexedLookupMs)}}function kr(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function Pr(r){return{...r,scanMs:Math.round(r.scanMs),packageRefsMs:Math.round(r.packageRefsMs),semanticRefsMs:Math.round(r.semanticRefsMs),hierarchyMs:Math.round(r.hierarchyMs)}}function wi(r,e,t){for(let n of e){let i=r.get(n)??[];i.push(...t),r.set(n,i)}}function ki(r){let e=new Set,t=[];for(let n of r){let i=`${n.symbol}|${n.file}|${n.line}`;e.has(i)||(e.add(i),t.push(n))}return t}function Tr(r){return r.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Ie=class{loadModule;discoverTsconfigs;createProjects;createProvider;db;module=null;projects=null;provider=null;stats={providerRequests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0};constructor(e,t={}){this.db=e,this.loadModule=t.loadModule??_t,this.discoverTsconfigs=t.discoverTsconfigs??Rr,this.createProjects=t.createProjects??Ot,this.createProvider=t.createProvider??((n,i,o)=>Dr(n,i,o,{reusedProjects:!0}))}semanticProvider(){return this.stats.providerRequests+=1,this.provider?(this.stats.sessionsReused+=1,this.provider):this.createSession()}advanceGeneration(e,t){let n=Pi(t);return this.provider?.dispose?.(),this.provider=null,this.db=e,this.projects?n.mode==="replace"?(this.projects=null,this.module=null,this.stats.sessionsReplaced+=1,n):(n.mode==="refresh"&&(Ti(this.projects,e.config.projectRoot,n),this.stats.sessionsRefreshed+=1),n):n}snapshotStats(){return{...this.stats}}dispose(){this.provider?.dispose?.(),this.provider=null,this.projects=null,this.module=null}createSession(){let e=this.module??this.loadModule();if(!e)return this.provider=_e("ts-morph is not installed"),this.provider;if(this.module=e,!this.projects){let t=this.discoverTsconfigs(this.db);if(t.length===0)return this.provider=_e("no tsconfig found"),this.provider;this.projects=this.createProjects(e,t),this.stats.projectsCreated+=this.projects.length}return this.provider=this.createProvider(this.db,e,this.projects),this.stats.sessionsCreated+=1,this.provider}};function Pi(r){let e=new Set;r.projectIdentityChanged&&e.add("project-identity-changed");for(let o of r.uncertainty)e.add(o);for(let o of r.changes)o.inputKind!=="source"&&e.add(`${o.inputKind}-input-changed`);if(e.size>0)return{mode:"replace",addedFiles:[],modifiedFiles:[],deletedFiles:[],reasons:[...e].sort()};let t=rt(r.changes,"added"),n=rt(r.changes,"modified"),i=rt(r.changes,"deleted");return{mode:t.length+n.length+i.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:n,deletedFiles:i,reasons:[]}}function rt(r,e){return r.filter(t=>t.kind===e).map(t=>t.path).sort()}function Ti(r,e,t){for(let n of r){for(let i of t.deletedFiles)n.project.getSourceFile(Er(e,i))?.forget();for(let i of t.modifiedFiles){let o=n.project.getSourceFile(Er(e,i));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&n.project.addSourceFilesFromTsConfig(n.tsconfigPath)}}var Ce=class{openDb;createHost;generationIdentity;readSnapshot;now;db=null;host=null;generation=null;snapshot=null;requests=0;lastRequestAtMs=null;lastError=null;available=null;constructor(e){this.openDb=e.openDb,this.createHost=e.createHost??(t=>new Ie(t)),this.generationIdentity=e.generationIdentity??Z,this.readSnapshot=e.readSnapshot??Li,this.now=e.now??Date.now}handle(e,t){try{this.syncGeneration(e);let n=this.host.semanticProvider();switch(this.available=n.availability().available,this.requests+=1,this.lastRequestAtMs=this.now(),this.lastError=null,t.kind){case"availability":return n.availability();case"import-usage":return n.importUsage(t.file);case"references":return[...Fi(n,t.definitions,{exact:t.exact===!0})];case"reference-fragments":if(!n.referenceFragmentsForFiles)throw new Error("TypeScript provider does not support reference fragments.");return[...n.referenceFragmentsForFiles(t.files)];case"callees":return[...Ai(n,t.definitions)];case"signature":return n.signatureFor(t.definition);default:return ji(t)}}catch(n){throw this.lastError=n instanceof Error?n.message:String(n),n}}status(){let e=this.host?.snapshotStats();return{protocolVersion:X,state:this.lastError?"error":this.host?this.available?"ready":"unavailable":"idle",requests:this.requests,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastError?{lastError:this.lastError}:{},sessionsCreated:e?.sessionsCreated??0,sessionsReused:e?.sessionsReused??0,sessionsRefreshed:e?.sessionsRefreshed??0,sessionsReplaced:e?.sessionsReplaced??0,projectsCreated:e?.projectsCreated??0}}closeTypeScriptService(){this.host?.dispose(),this.db?.close(),this.host=null,this.db=null,this.generation=null,this.snapshot=null,this.available=null}syncGeneration(e){if(this.generation===e&&this.host&&this.db)return;let t=this.openDb(),n=this.generationIdentity(t.config.dbPath);if(!n||n!==e)throw t.close(),new Error("TypeScript semantic request does not match the currently published index generation.");let i=this.readSnapshot(t.config.dbPath);if(!this.host||!this.db)this.db=t,this.host=this.createHost(t);else{let o=this.db;this.host.advanceGeneration(t,Ni(this.snapshot,i)),this.db=t,o.close()}this.generation=n,this.snapshot=i,this.available=null}};function nt(r){Fr(r.requestDir,{recursive:!0}),Fr(r.responseDir,{recursive:!0})}function Lr(r,e,t={}){nt(r);let n=0;for(let i of Di(r.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=Re(r.requestDir,i),a=i.slice(0,-5),s=null;try{let c=tr(Ar(o,"utf8"));if(a=c.id,c.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript semantic request expired before processing.");s=ht(),De(c.profileEnvironment??{}),t.beforeRequest?.(c.deadlineAtMs);let l=e.handle(c.generation,c.request);F(Re(r.responseDir,`${a}.json`),{ok:!0,protocolVersion:X,id:a,generation:c.generation,response:l})}catch(c){F(Re(r.responseDir,`${a}.json`),{ok:!1,protocolVersion:X,id:a,error:c instanceof Error?c.message:String(c)})}finally{s&&De(s),t.afterRequest?.(),Ei(o,{force:!0}),n+=1}}return n}function Fi(r,e,t){return r.referencesForDefinitions?.(e,t)??new Map(e.map(n=>[n.symbolId,r.referencesFor(n)]))}function Ai(r,e){return r.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,r.calleesFor(t)]))}function Li(r){try{let e=JSON.parse(Ar(Re(r,"..","meta.json"),"utf8"));return ft(e.fingerprint)}catch{return null}}function Ni(r,e){return e?mt(r,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function ji(r){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(r)}`)}import{mkdirSync as Nr,readFileSync as _i,readdirSync as Oi,rmSync as Wi}from"fs";import{resolve as Me}from"path";var we=class{projectRoot;currentGeneration;createEmitter;now;active=null;requests=0;sessionsCreated=0;sessionsReplaced=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(e){this.projectRoot=Me(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??Vt,this.now=e.now??Date.now}handle(e,t){let n=this.now();try{if(this.currentGeneration()!==e)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(t);if(i.emitter.producerIdentity!==t.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),a=i.emitter.advance({modifiedFiles:t.modifiedFiles,affectedFiles:t.affectedFiles}),s=this.now()-n;return this.requests+=1,this.lastRequestAtMs=this.now(),this.lastDurationMs=s,this.lastError=null,this.unavailable=!1,{producerIdentity:a.producerIdentity,cold:a.stats.initializations>o.initializations,durationMs:s,fragments:a.fragments.map(c=>({relativePath:c.relativePath,bytesBase64:c.bytes===null?null:Buffer.from(c.bytes).toString("base64"),occurrences:c.occurrences,symbols:c.symbols,referenceFragments:c.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(){let e=this.active?.emitter.snapshotStats();return{protocolVersion:fe,state:this.unavailable?"unavailable":this.lastError?"error":this.active?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,initializations:e?.initializations??0,programUpdates:e?.programUpdates??0,documentsEmitted:e?.documentsEmitted??0,documentsRemoved:e?.documentsRemoved??0,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{}}}close(){this.active=null}emitterFor(e){let t=`${e.tsconfigPath}\0${e.projectArgument}`;if(this.active&&this.active.sessionKey===t&&this.active.projectIdentity===e.projectIdentity)return this.active;let n=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:e.tsconfigPath,projectRoot:e.projectArgument});if(!n.available)throw this.unavailable=!0,new Error(n.reason);return this.active&&(this.sessionsReplaced+=1),this.active={sessionKey:t,projectIdentity:e.projectIdentity,emitter:n.emitter},this.sessionsCreated+=1,this.active}};function it(r){Nr(r.requestDir,{recursive:!0}),Nr(r.responseDir,{recursive:!0})}function jr(r,e,t={}){it(r);let n=0;for(let i of Oi(r.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=Me(r.requestDir,i),a=i.slice(0,-5);try{let s=zt(_i(o,"utf8"));if(a=s.id,s.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript index request expired before processing.");t.beforeRequest?.(s.deadlineAtMs);let c=e.handle(s.baseGeneration,s.request);F(Me(r.responseDir,`${a}.json`),{ok:!0,protocolVersion:fe,id:a,baseGeneration:s.baseGeneration,response:c})}catch(s){F(Me(r.responseDir,`${a}.json`),{ok:!1,protocolVersion:fe,id:a,error:s instanceof Error?s.message:String(s)})}finally{t.afterRequest?.(),Wi(o,{force:!0}),n+=1}}return n}import{spawn as $i}from"child_process";import{closeSync as Gi,existsSync as qi,mkdirSync as Ui,openSync as Hi,readFileSync as Wr,rmSync as re,writeFileSync as Bi}from"fs";import{dirname as Vi,resolve as at}from"path";import{fileURLToPath as Na}from"url";var Ki=2e3,zi=10;function $r(r,e,t){let n=Fe(at(r));if(t&&Fe(t.projectRoot)===n)return{projectRoot:n,worktreeKind:"git",worktreeId:t.worktreeId,cliVersion:e};let i=yt(n);if(i.kind==="error")throw new Error(`Could not establish Git worktree identity for ${n}: ${i.message}`);return i.kind==="non-git"?{projectRoot:n,worktreeKind:"non-git",cliVersion:e}:{projectRoot:n,worktreeKind:"git",worktreeId:i.identity.worktreeId,cliVersion:e}}function Gr(r){let e=r.runtime??Qi,t=B(r.cacheDir),n=Jt(t.statePath),i=n?e.isProcessAlive(n.pid)?{kind:"live",state:n}:{kind:"stale",state:n,reason:"dead-process"}:{kind:"stopped"},o=Yi("stop",i);if(o.kind==="signal-stop")return _r(o.state.pid,r,e),ot(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};if(o.kind==="clean-stale")return ot(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};let a=ne(t.lockPath);return o.kind==="already-stopped"&&a&&e.isProcessAlive(a.pid)?(_r(a.pid,r,e),ot(t,a.pid,e),{disposition:"stopped",pid:a.pid}):{disposition:"already-stopped"}}function qr(r,e){F(r,e)}function Ur(r){try{let e=JSON.parse(Wr(r,"utf8"));return e.version!==1||!me(e.at)||e.refreshRequestedAt!==void 0&&!me(e.refreshRequestedAt)||e.refreshDetail!==void 0&&typeof e.refreshDetail!="string"?null:{atMs:Date.parse(e.at),...e.refreshRequestedAt===void 0?{}:{refreshRequestedAtMs:Date.parse(e.refreshRequestedAt)},...e.refreshDetail===void 0?{}:{refreshDetail:e.refreshDetail}}}catch{return null}}function Hr(r,e,t={}){let n=t.pid??process.pid,i=t.isProcessAlive??j,o=()=>{},a=ne(r);if(a&&i(a.pid))return{acquired:!1,lockPath:r,message:Or(r,e,a),release:o};a&&re(r,{force:!0}),Ui(Vi(r),{recursive:!0});let s;try{s=Hi(r,"wx")}catch(d){if(Ji(d)==="EEXIST")return{acquired:!1,lockPath:r,message:Or(r,e,ne(r)),release:o};throw d}let c={version:1,pid:n,projectRoot:at(e),startedAt:(t.now??(()=>new Date))().toISOString()};Bi(s,`${JSON.stringify(c)}
|
|
42
|
+
`);let l=!1;return{acquired:!0,lockPath:r,message:"",release:()=>{if(l)return;l=!0,Gi(s);let d=ne(r);d?.pid===c.pid&&d.startedAt===c.startedAt&&re(r,{force:!0})}}}function ne(r){try{let e=JSON.parse(Wr(r,"utf-8"));return e.version!==1||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.projectRoot!="string"||!me(e.startedAt)?null:e}catch{return null}}function Yi(r,e){switch(r){case"status":return{kind:"report",classification:e};case"ensure":switch(e.kind){case"stopped":return{kind:"start"};case"stale":return e.reason==="old-heartbeat"?{kind:"replace",state:e.state}:{kind:"start"};case"live":return{kind:"reuse",state:e.state};case"incompatible":return{kind:"replace",state:e.state};default:return st(e)}case"stop":switch(e.kind){case"stopped":return{kind:"already-stopped"};case"stale":return e.reason==="old-heartbeat"?{kind:"signal-stop",state:e.state}:{kind:"clean-stale",state:e.state};case"live":case"incompatible":return{kind:"signal-stop",state:e.state};default:return st(e)}default:return st(r)}}function Br(r){return r.idleTimeoutMs===0||r.watcher.state!=="idle"?!1:r.nowMs-r.lastActivityAtMs>=r.idleTimeoutMs}function _r(r,e,t){if(!t.isProcessAlive(r))return;t.signalProcess(r);let n=e.stopTimeoutMs??Ki,i=t.now()+n;for(;t.now()<=i;){if(!t.isProcessAlive(r))return;t.sleep(zi)}throw new Error(`scip-query watch service pid ${r} did not stop within ${n}ms.`)}function ot(r,e,t){re(r.statePath,{force:!0}),re(r.activityPath,{force:!0}),ne(r.lockPath)?.pid===e&&!t.isProcessAlive(e)&&re(r.lockPath,{force:!0})}function Or(r,e,t){return`error: scip-query watch is already running for ${at(e)}${t?` (pid ${t.pid}, started ${t.startedAt}; lock: ${r})`:` (lock: ${r})`}. Stop that watcher before starting another.`}function Ji(r){return typeof r=="object"&&r&&"code"in r?r.code:void 0}var Qi={now:Date.now,isProcessAlive:j,spawnServer(r,e,t,n){if(!qi(r))throw new Error(`Watch service helper was not found at ${r}. Run npm run build first.`);$i(process.execPath,[r,e,t,JSON.stringify(n)],{detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"}}).unref()},signalProcess(r){process.kill(r,"SIGTERM")},sleep(r){let e=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(e,0,0,r)}};function st(r){throw new Error(`Unhandled watch service value: ${JSON.stringify(r)}`)}import{existsSync as Yr,lstatSync as ke,readFileSync as ut,readdirSync as Jr,realpathSync as Vr,rmSync as ie,statSync as Xi}from"fs";import{join as R,resolve as $,sep as Kr}from"path";var Zi=3600*1e3,eo=2*1024*1024*1024,to=300*1e3;function ro(r){let e=r.leases.filter(s=>s.managed&&!s.live&&!s.busy),t=no(r.leases,r.locks),n={};for(let s of r.generations)t.has(s.generationId)||(n[s.generationId]=s.unreferencedAt??r.nowMs);let i=r.generations.filter(s=>!t.has(s.generationId)).sort((s,c)=>n[s.generationId]-n[c.generationId]||s.generationId.localeCompare(c.generationId)),o=new Set;for(let s of i)r.nowMs-n[s.generationId]>=r.policy.generationTtlMs&&o.add(s.generationId);let a=r.generations.filter(s=>!o.has(s.generationId)).reduce((s,c)=>s+c.size,0);for(let s of i){if(a<=r.policy.budgetBytes)break;o.has(s.generationId)||(o.add(s.generationId),a-=s.size)}for(let s of o)delete n[s];return{deleteWorktrees:e,deleteGenerations:r.generations.filter(s=>o.has(s.generationId)),deleteLocks:r.locks.filter(s=>!s.live),deleteTemporaries:r.temporaries.filter(s=>!s.live),protectedGenerationIds:[...t].sort(),unreferencedSince:n}}function no(r,e){let t=new Set(r.filter(n=>n.managed&&(n.live||n.busy)).flatMap(n=>[n.lease.baseGenerationId,n.lease.activeGenerationId]).filter(n=>n!==void 0));for(let n of e)n.live&&t.add(n.generationId);return t}function Qr(r,e,t={}){if(!Ut())return{kind:"disabled"};let n=gt(r);if(!n)return{kind:"unavailable"};let i=R(We(),"repositories",n.repositoryId);if(!Yr(i))return{kind:"unavailable"};let o=(t.now??Date.now)(),a=R(i,"gc-state.json"),s=so(a);if(!t.force&&s&&o-Date.parse(s.lastSweepAt)<to)return{kind:"throttled",sweptAt:s.lastSweepAt};let c=vt(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=io(r,i,n.repositoryId,s?.unreferencedSince??{}),d=ro({nowMs:o,...l,policy:{generationTtlMs:t.policy?.generationTtlMs??Zi,budgetBytes:t.policy?.budgetBytes??eo}}),u=0,p=0;for(let m of d.deleteWorktrees){if(!Xr(m.lease))continue;let h=xt(R(m.lease.localCacheDir,"cache-lifecycle.lock"));if(h)try{if(lt(m.lease,!0))continue;try{Gr({projectRoot:m.lease.projectRoot,cacheDir:m.lease.localCacheDir,cliVersion:e})}catch{continue}if(lt(m.lease,!0))continue;ie(m.lease.localCacheDir,{recursive:!0,force:!0}),ie(m.leasePath,{force:!0}),p+=1}finally{h.release()}}for(let m of d.deleteLocks)ie(m.path,{force:!0});for(let m of d.deleteTemporaries)ie(m.path,{recursive:!0,force:!0});for(let m of d.deleteGenerations)ie(m.path,{recursive:!0,force:!0}),u+=m.size;Ct(R(i,"evidence.db"));let g={kind:"swept",sweptAt:new Date(o).toISOString(),deletedWorktrees:p,deletedGenerations:d.deleteGenerations.length,deletedBytes:u,protectedGenerations:d.protectedGenerationIds.length},f={version:1,lastSweepAt:g.sweptAt,unreferencedSince:d.unreferencedSince,lastResult:g};return F(a,f,{spacing:2,trailingNewline:!0}),g}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function io(r,e,t,n){let i=new Set(St(r).map(l=>$(l.path))),o=[];for(let l of ct(R(e,"worktrees"))){if(!l.endsWith(".json"))continue;let d=R(e,"worktrees",l),u=oo(d);if(!u)continue;let p=$(u.projectRoot);o.push({leasePath:d,lease:u,managed:u.repositoryId===t&&Xr(u),live:i.has(p)||Yr(p),busy:lt(u)})}let a=[];for(let l of ct(R(e,"locks"))){let d=/^([a-f0-9]{64})\.lock$/.exec(l);if(!d)continue;let u=R(e,"locks",l),p=dt(u),g=p!==void 0&&j(p),f=d[1];a.push({generationId:f,path:u,live:g})}let s=[],c=[];for(let l of ct(R(e,"generations"))){let d=/^\.tmp-(\d+)-/.exec(l);if(d){let g=R(e,"generations",l),f=Number(d[1]);try{c.push({path:g,size:zr(g),live:Number.isSafeInteger(f)&&j(f)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let u=R(e,"generations",l),p;try{p=ke(u)}catch{continue}!p.isDirectory()||p.isSymbolicLink()||s.push({generationId:l,path:u,size:zr(u),...n[l]===void 0?{}:{unreferencedAt:n[l]}})}return{leases:o,generations:s,locks:a,temporaries:c}}function Xr(r){if(r.ownershipChecksum!==Bt(r)||$(r.localCacheDir)!==$(qt(r.projectRoot)))return!1;let e=$(We()),t=$(R(e,"projects")),n=$(r.localCacheDir);if(!n.startsWith(`${t}${Kr}`))return!1;try{let i=ke(e),o=ke(t),a=ke(n);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink())return!1;let s=Vr(t);return Vr(n).startsWith(`${s}${Kr}`)}catch{return!1}}function lt(r,e=!1){for(let n of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=dt(R(r.localCacheDir,n));if(i!==void 0&&j(i))return!0}let t=dt(B(r.localCacheDir).lockPath);return t!==void 0&&j(t)}function oo(r){try{let e=JSON.parse(ut(r,"utf8"));return e.version!==1||typeof e.repositoryId!="string"||typeof e.worktreeId!="string"||typeof e.projectRoot!="string"||e.treeOid!==void 0&&typeof e.treeOid!="string"||typeof e.localCacheDir!="string"||e.baseGenerationId!==void 0&&typeof e.baseGenerationId!="string"||e.activeGenerationId!==void 0&&typeof e.activeGenerationId!="string"||typeof e.ownershipChecksum!="string"||!/^[a-f0-9]{64}$/.test(e.ownershipChecksum)||typeof e.lastAction!="string"||e.lastReason!==void 0&&typeof e.lastReason!="string"||typeof e.lastSeenAt!="string"?null:e}catch{return null}}function dt(r){try{let e=JSON.parse(ut(r,"utf8"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function so(r){try{let e=JSON.parse(ut(r,"utf8"));return e.version!==1||typeof e.lastSweepAt!="string"||!Number.isFinite(Date.parse(e.lastSweepAt))||!e.unreferencedSince||typeof e.unreferencedSince!="object"||!e.lastResult?null:e}catch{return null}}function ct(r){try{return Jr(r)}catch{return[]}}function zr(r){let e=0,t=[r];for(;t.length>0;){let n=t.pop();for(let i of Jr(n,{withFileTypes:!0})){let o=R(n,i.name);i.isDirectory()?t.push(o):i.isFile()&&(e+=Xi(o).size)}}return e}var lo=1e3,uo=250,po=10;function fo(r){return r==="fresh"?null:{kind:"watch-startup",detail:`index ${r} when watch service started`}}async function mo(r,e,t={}){let n=$r(r,e),i=n.projectRoot,o=V(i);o.watch={...o.watch,...t};let a=he(o);if(!a.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let s=H(i,o),c=B(s.cacheDir),l=Hr(c.lockPath,i);if(!l.acquired)return;let d=Date.now(),u=d,p={state:"idle"},g,f,m,h=pe(s.dbPath),S=!1,M=!1,A=0,P=0,L=0,D=0,C,b,I=er(s.cacheDir),pt=Kt(s.cacheDir);nt(I),it(pt);let Pe=new Ce({openDb:()=>or(i)}),Te=new we({projectRoot:i,currentGeneration:()=>Yt(s.dbPath)}),E=(v=!1)=>{if(!M)return;let q=Date.now();!v&&q-P<lo||(P=q,qr(c.statePath,{version:1,protocolVersion:Ge,pid:k.pid,projectRoot:i,...n.worktreeId?{worktreeId:n.worktreeId}:{},cliVersion:e,startedAt:new Date(d).toISOString(),heartbeatAt:new Date(q).toISOString(),lastActivityAt:new Date(u).toISOString(),...a.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(u+a.idleTimeoutMs).toISOString()},watcher:p,...p.state==="idle"&&g?{indexGeneration:g}:{},...f?{lastRefresh:f}:{},...m?{lastError:m}:{},reindexActivity:h,typescriptSemantic:{...Pe.status(),...C===void 0?{}:{busyUntil:new Date(C).toISOString()}},typescriptIndex:{...Te.status(),...b===void 0?{}:{busyUntil:new Date(b).toISOString()}}}))},G=()=>{u=Date.now()},oe=new ge({projectRoot:i,config:{...o,watch:a},languages:o.languages,onStatus(v){p=v,v.state!=="idle"&&(g=void 0),v.state!=="idle"&&G(),E(!0)},onReindexComplete(){G();let v=Ue(i,o,s);return f=v.lastRefresh,g=v.state==="fresh"?Z(s.dbPath)??void 0:void 0,h=pe(s.dbPath),m=void 0,E(!0),v.state==="fresh"},onRefreshSuppressed(v){Gt(s.dbPath,v),h=pe(s.dbPath)},onError(v){G(),g=void 0,m={at:new Date().toISOString(),message:v.message},E(!0)}}),se=()=>{S=!0};k.once("SIGINT",se),k.once("SIGTERM",se);try{oe.start();let v=Ue(i,o,s);f=v.lastRefresh,g=v.state==="fresh"?Z(s.dbPath)??void 0:void 0;let q=fo(v.state);for(q&&oe.requestRefresh(q,{immediate:!0}),G(),M=!0,E(!0);!S;){let en=jr(pt,Te,{beforeRequest(T){b=T+5e3,E(!0)},afterRequest(){b=void 0,E(!0)}}),tn=Lr(I,Pe,{beforeRequest(T){C=T+5e3,E(!0)},afterRequest(){C=void 0,E(!0)}}),ae=Date.now();if(ae-D>=6e4&&(D=ae,Qr(i,e)),ae-L>=uo){L=ae;let T=Ur(c.activityPath);T&&T.atMs>u&&(u=T.atMs),T?.refreshRequestedAtMs!==void 0&&T.refreshRequestedAtMs>A&&(A=T.refreshRequestedAtMs,G(),oe.requestRefresh({kind:"watch-demand",detail:T.refreshDetail??"stale index observed by a command"},{immediate:!0}))}if((tn>0||en>0)&&(G(),E(!0)),E(),Br({watcher:p,lastActivityAtMs:u,nowMs:Date.now(),idleTimeoutMs:a.idleTimeoutMs}))break;await ho(po)}}finally{k.off("SIGINT",se),k.off("SIGTERM",se),Pe.closeTypeScriptService(),Te.close(),oe.stop(),Zr(c.statePath,{force:!0}),Zr(c.activityPath,{force:!0}),l.release()}}function ho(r){return new Promise(e=>setTimeout(e,r))}var go=k.argv[1]?co(ao(k.argv[1])).href:null;if(go===import.meta.url){let r=k.argv[2],e=k.argv[3],t=yo(k.argv[4]);if(!r||!e)console.error("watch-service: expected <project-root> <cli-version>"),k.exitCode=1;else try{await mo(r,e,t)}catch(n){console.error(`watch-service: ${n instanceof Error?n.message:String(n)}`),k.exitCode=1}}function yo(r){if(!r)return{};try{let e=JSON.parse(r);return e&&typeof e=="object"?e:{}}catch{return{}}}export{mo as runWatchServiceServer,fo as startupRefreshTrigger};
|
|
43
43
|
//# sourceMappingURL=watch-server.js.map
|
package/docs/AI_FAILURE_MODES.md
CHANGED
|
@@ -301,7 +301,7 @@ scip-query setup-agent --git-hook # pre-commit backstop: fires whoever wrote
|
|
|
301
301
|
| `co-change-partner` | Historically coupled files that usually change together but are missing from this diff. | Default diff gate. |
|
|
302
302
|
| `twin-partner` | A changed symbol has a same-(near-)name twin (identical or already-divergent) elsewhere that this diff left untouched. | Default diff gate. Advisory: findings print but never cause a nonzero exit by themselves. |
|
|
303
303
|
| `coverage-contract` | A configured `coverageContracts` entry (.scipquery.json) drifted: its declared key set no longer matches its ground-truth source. | Default diff gate, only when either side of a configured contract changed. |
|
|
304
|
-
| `architecture` | A declared architecture boundary rule has a violation absent from the committed health baseline. | Default diff gate when closed dependency rows, requireCompletePolicy, or
|
|
304
|
+
| `architecture` | A declared architecture boundary rule has a violation absent from the committed health baseline. | Default diff gate when closed dependency rows, requireCompletePolicy, requireAcyclic, requireResolvedBoundaries, requireMinimalPolicy, maxBoundaryFanOut, global maxBoundaryFiles, per-boundary maxFiles, or testPaths are configured and a baseline exists. |
|
|
305
305
|
| `doc-reference` | Docs that cite changed files and may need a matching update. Dated snapshot docs (docs.snapshotPaths) are excluded by policy. | Default diff gate. Advisory (21.2) for bare file-mention citations; blocking when the citation has a line anchor or the cited file was deleted/renamed. |
|
|
306
306
|
| `unused-params` | Fresh trailing parameters or options that no changed body uses. | Default diff gate. |
|
|
307
307
|
| `new-dead` | Changed production symbols with zero indexed consumers. | Default diff gate. |
|