scip-query 0.18.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.md +1 -0
- package/dist/augment-vue-worker.js +1 -1
- package/dist/{chunk-OTTHMUMV.js → chunk-2FAJTZSX.js} +2 -2
- package/dist/{chunk-EJ65IVPV.js → chunk-2ZNZSNVW.js} +2 -2
- package/dist/chunk-35NLDRZC.js +2 -0
- package/dist/{chunk-QPF7CS5W.js → chunk-3KQOIXLO.js} +2 -2
- package/dist/{chunk-VCRMI56V.js → chunk-3OSRXJKK.js} +2 -2
- package/dist/chunk-42QYU6FD.js +3 -0
- package/dist/{chunk-ODH4FT3P.js → chunk-4ZCNFENR.js} +2 -2
- package/dist/{chunk-GWCW25ON.js → chunk-4ZHJAHLE.js} +2 -2
- package/dist/chunk-547VY366.js +18 -0
- package/dist/{chunk-NX2YAXVQ.js → chunk-54UYBTZW.js} +2 -2
- package/dist/{chunk-7ROLM67J.js → chunk-6DHPQS72.js} +2 -2
- package/dist/chunk-6SHX42QQ.js +6 -0
- package/dist/{chunk-ABDXTPCT.js → chunk-7EI4MU5A.js} +2 -2
- package/dist/{chunk-J7IMQRCU.js → chunk-7FG5M53V.js} +2 -2
- package/dist/chunk-A45K6VUK.js +2 -0
- package/dist/{chunk-MPBN5DO4.js → chunk-AEDB4WXE.js} +2 -2
- package/dist/{chunk-O5A7BTMA.js → chunk-AERYQJ52.js} +2 -2
- package/dist/chunk-AM2LGOEX.js +3 -0
- package/dist/{chunk-43QUXX3E.js → chunk-AWSRND4W.js} +2 -2
- package/dist/{chunk-5GAUXLOE.js → chunk-BOXAKNN6.js} +2 -2
- package/dist/{chunk-IKMOYFUM.js → chunk-BYPVNKJT.js} +2 -2
- package/dist/chunk-DQIJMKNE.js +3 -0
- package/dist/{chunk-K65T4TJS.js → chunk-DV6B262O.js} +2 -2
- package/dist/chunk-DWN7QDTV.js +26 -0
- package/dist/{chunk-HOZ3IXZ5.js → chunk-EZGT3NJX.js} +2 -2
- package/dist/{chunk-SW7LKHRU.js → chunk-EZHARAL4.js} +2 -2
- package/dist/chunk-F334Z5UA.js +38 -0
- package/dist/{chunk-SWJEREML.js → chunk-F5L7WEZF.js} +2 -2
- package/dist/{chunk-5CJ6AQN7.js → chunk-FLIF3JWA.js} +2 -2
- package/dist/chunk-FMC3BI4I.js +2 -0
- package/dist/{chunk-YMFHC5J2.js → chunk-G6QQCX45.js} +2 -2
- package/dist/{chunk-35TZERMO.js → chunk-G6RQVDTI.js} +2 -2
- package/dist/chunk-GBB2RUDN.js +927 -0
- package/dist/{chunk-LL5NQB5V.js → chunk-GJ3FR5WG.js} +2 -2
- package/dist/chunk-GMZYT44R.js +5 -0
- package/dist/{chunk-OQFPCIXO.js → chunk-GNJHHPZE.js} +2 -2
- package/dist/chunk-HOXI4F5I.js +4 -0
- package/dist/{chunk-PV3GKBO5.js → chunk-IWK562KR.js} +2 -2
- package/dist/chunk-IXORBCMR.js +120 -0
- package/dist/chunk-J3U47L4Q.js +2 -0
- package/dist/{chunk-O5Y3ISO3.js → chunk-J65FQLDL.js} +2 -2
- package/dist/{chunk-45QWQSWS.js → chunk-J6BR4MD6.js} +2 -2
- package/dist/{chunk-J7WYG63U.js → chunk-JFGUBZWE.js} +2 -2
- package/dist/{chunk-FMD46HAG.js → chunk-KD6TPIXM.js} +2 -2
- package/dist/{chunk-3M2UCPFS.js → chunk-KHE7J5ZN.js} +1 -1
- package/dist/{chunk-IG6X65MG.js → chunk-KWBA6FDD.js} +2 -2
- package/dist/{chunk-LADYDOS5.js → chunk-LJD7V7UO.js} +2 -2
- package/dist/{chunk-D5F3IQYP.js → chunk-MDDF67O2.js} +2 -2
- package/dist/{chunk-BAMVG4WQ.js → chunk-MFBXBLHA.js} +2 -2
- package/dist/{chunk-VXDMXZKC.js → chunk-MTFHE7ZO.js} +2 -2
- package/dist/chunk-NEG77KKH.js +4 -0
- package/dist/{chunk-WA64GKWB.js → chunk-NH7WNNQC.js} +3 -3
- package/dist/{chunk-K3UVTL3J.js → chunk-OGHGTD6Z.js} +2 -2
- package/dist/chunk-OYYZLJVT.js +2 -0
- package/dist/{chunk-MNRKD3WP.js → chunk-PAZFJMXB.js} +2 -2
- package/dist/{chunk-U244OVE6.js → chunk-PBADFBRR.js} +2 -2
- package/dist/{chunk-UWR52GNZ.js → chunk-PKAPOFF5.js} +2 -2
- package/dist/{chunk-POGZSZPX.js → chunk-PXJIEMND.js} +2 -2
- package/dist/{chunk-PZV2PGBR.js → chunk-QB5WSOTY.js} +2 -2
- package/dist/{chunk-MN54AGZ3.js → chunk-QHOUNTDZ.js} +2 -2
- package/dist/chunk-QN67MWDU.js +2 -0
- package/dist/{chunk-JLZUM476.js → chunk-QNMOZ3CJ.js} +2 -2
- package/dist/{chunk-AWYKDRYV.js → chunk-RIGY5DDE.js} +2 -2
- package/dist/chunk-RJLU7IMR.js +10 -0
- package/dist/{chunk-AV54WZUK.js → chunk-S65OEY2G.js} +2 -2
- package/dist/chunk-SATRCB5O.js +20 -0
- package/dist/chunk-T5CSWYAZ.js +2 -0
- package/dist/{chunk-H4T2AST4.js → chunk-TC3X33N6.js} +2 -2
- package/dist/{chunk-3CJXFMR5.js → chunk-TCVRJ56J.js} +2 -2
- package/dist/{chunk-7XP7ZRSI.js → chunk-TDGCALH6.js} +2 -2
- package/dist/chunk-TDZXQAH7.js +2 -0
- package/dist/{chunk-SUYCF4SX.js → chunk-TOYQTO44.js} +2 -2
- package/dist/chunk-UJL3N6TC.js +5 -0
- package/dist/chunk-UVMME4FI.js +16 -0
- package/dist/{chunk-6JSTKSZH.js → chunk-UXOVHGT6.js} +2 -2
- package/dist/chunk-VV5WJLRO.js +67 -0
- package/dist/{chunk-GTANVH72.js → chunk-WT7TOU2C.js} +2 -2
- package/dist/{chunk-4FLF7BHJ.js → chunk-X36LKKVG.js} +2 -2
- package/dist/{chunk-OSBLECSI.js → chunk-X3OOU7CF.js} +2 -2
- package/dist/chunk-X65VYV2S.js +2 -0
- package/dist/chunk-XBN5VO53.js +2 -0
- package/dist/{chunk-TLTLJ4SW.js → chunk-XDSB47KO.js} +2 -2
- package/dist/{chunk-4L4X66GE.js → chunk-XDVT7QPG.js} +2 -2
- package/dist/chunk-XESK6725.js +2 -0
- package/dist/{chunk-P4L5QQT5.js → chunk-XPYXEEDO.js} +2 -2
- package/dist/{chunk-T4P27T6S.js → chunk-XTSVYYAL.js} +2 -2
- package/dist/{chunk-27YDE22N.js → chunk-YBAC3RON.js} +2 -2
- package/dist/{chunk-2DBY4MO7.js → chunk-YHYTDWFT.js} +2 -2
- package/dist/chunk-YYR7ADNB.js +2 -0
- package/dist/chunk-ZL5Y23AJ.js +3 -0
- package/dist/{chunk-CMLHZWRS.js → chunk-ZNSLF5AC.js} +2 -2
- package/dist/chunk-ZXWFN7CK.js +2 -0
- package/dist/cli.js +2 -2
- package/dist/{command-descriptors-AQWWJNTT.js → command-descriptors-SWFWGIFK.js} +173 -167
- package/dist/{config-types-70s7NxKB.d.ts → config-types-BA3xLCfG.d.ts} +28 -1
- package/dist/{db-BBmJ0v3b.d.ts → db-CzA-9_rL.d.ts} +6 -18
- package/dist/direct-navigation-RKMPBXMI.js +3 -0
- package/dist/{health-CWpFL_6z.d.ts → health-DYy13GAe.d.ts} +3 -1
- package/dist/index.d.ts +23 -41
- package/dist/index.js +1 -1
- package/dist/postinstall.js +1 -1
- package/dist/queries/affected.d.ts +2 -2
- package/dist/queries/affected.js +1 -1
- package/dist/queries/architecture.d.ts +83 -0
- package/dist/queries/architecture.js +2 -0
- 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 +5 -3
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.d.ts +2 -2
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +2 -2
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +27 -10
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.d.ts +2 -2
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/extract-candidates.d.ts +2 -2
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +2 -2
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +2 -2
- package/dist/queries/health.d.ts +3 -3
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +2 -2
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +2 -2
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +2 -2
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +2 -2
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +5 -4
- 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 +12 -10
- package/dist/reindex.js +38 -38
- package/dist/runtime.d.ts +10 -9
- package/dist/runtime.js +2 -1
- package/dist/rust-semantic-session-server.js +1 -1
- package/dist/{scip-cli-CoMzb7Zu.d.ts → scip-cli-1bVKJgXi.d.ts} +1 -1
- package/dist/watch-server.js +7 -6
- package/docs/AI_FAILURE_MODES.md +1 -0
- package/docs/COMMAND_REFERENCE.md +3 -2
- package/docs/DETECTOR_GUIDE.md +5 -3
- package/docs/analyzer-inventory.md +16 -6
- package/docs/analyzer-validation-ledger.md +12 -1
- package/docs/architecture-coherence-vision.md +219 -0
- package/package.json +5 -1
- package/skills/_shared/SKILL.md +4 -3
- package/skills/scip-conductor/SKILL.md +1 -1
- package/skills/scip-directory-architecture/SKILL.md +116 -2
- package/skills/scip-maintainability/SKILL.md +3 -3
- package/skills/scip-query/SKILL.md +1 -1
- package/skills/scip-twin-drift/SKILL.md +1 -1
- package/skills/scip-verify/SKILL.md +1 -1
- package/dist/chunk-2GX3TNOW.js +0 -38
- package/dist/chunk-45XOH33S.js +0 -2
- package/dist/chunk-4MFMTEJ4.js +0 -5
- package/dist/chunk-BECOMXAL.js +0 -2
- package/dist/chunk-BJJHBKEC.js +0 -2
- package/dist/chunk-DDGO34I2.js +0 -26
- package/dist/chunk-DUKRAHV2.js +0 -2
- package/dist/chunk-EMEXMHOP.js +0 -7
- package/dist/chunk-GWNE2WJN.js +0 -3
- package/dist/chunk-H4JNB7RT.js +0 -3
- package/dist/chunk-L2RE5P3X.js +0 -2
- package/dist/chunk-L2TSLMPT.js +0 -5
- package/dist/chunk-NQBMGFFD.js +0 -2
- package/dist/chunk-OINSINYW.js +0 -2
- package/dist/chunk-OM6JHEW3.js +0 -16
- package/dist/chunk-OUXPJ4H5.js +0 -3
- package/dist/chunk-OWXNDSG3.js +0 -2
- package/dist/chunk-Q4UM4JJP.js +0 -2
- package/dist/chunk-QEIGJJBC.js +0 -20
- package/dist/chunk-R4VPIS4D.js +0 -10
- package/dist/chunk-RDX6WWHN.js +0 -4
- package/dist/chunk-RUQE7DZT.js +0 -2
- package/dist/chunk-S43DIBME.js +0 -18
- package/dist/chunk-SALRDXWM.js +0 -121
- package/dist/chunk-SMBIGBGN.js +0 -67
- package/dist/chunk-VQWDZ34M.js +0 -928
- package/dist/chunk-W3557RPL.js +0 -3
- package/dist/chunk-W3SKYOTF.js +0 -2
- package/dist/chunk-XEEQX5X3.js +0 -3
- package/dist/direct-navigation-K3CTVVBU.js +0 -3
package/dist/runtime.d.ts
CHANGED
|
@@ -1,15 +1,10 @@
|
|
|
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-BA3xLCfG.js';
|
|
2
|
+
import { W as WatcherStatus, R as RefreshTrigger } from './scip-cli-1bVKJgXi.js';
|
|
3
|
+
export { g as getScipVersion, i as isScipInstalled, p as printScipInstallInstructions } from './scip-cli-1bVKJgXi.js';
|
|
4
4
|
|
|
5
|
-
/**
|
|
6
|
-
* Load project config from .scipquery.json in the project root.
|
|
7
|
-
* Returns defaults for anything not specified.
|
|
8
|
-
*/
|
|
9
|
-
declare function loadProjectConfig(projectRoot: string): ProjectConfig;
|
|
10
5
|
/**
|
|
11
6
|
* Resolve all storage paths for a project's index files (cache dir, SQLite
|
|
12
|
-
* db, .scip index, meta.json). Distinct from
|
|
7
|
+
* db, .scip index, meta.json). Distinct from queries/internal/file-resolution.ts's
|
|
13
8
|
* resolveIndexedPaths, which resolves a file-pattern query against the
|
|
14
9
|
* already-indexed documents table -- a different job that happens to share
|
|
15
10
|
* "resolve" + "index" + "paths" vocabulary.
|
|
@@ -20,6 +15,12 @@ declare function resolveIndexStoragePaths(projectRoot: string, config?: ProjectC
|
|
|
20
15
|
indexPath: string;
|
|
21
16
|
metaPath: string;
|
|
22
17
|
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Load project config from .scipquery.json in the project root.
|
|
21
|
+
* Returns defaults for anything not specified.
|
|
22
|
+
*/
|
|
23
|
+
declare function loadProjectConfig(projectRoot: string): ProjectConfig;
|
|
23
24
|
/**
|
|
24
25
|
* Scaffold a default .scipquery.json in the project root.
|
|
25
26
|
* Does not overwrite an existing config.
|
package/dist/runtime.js
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import{b as
|
|
1
|
+
import{b as O,c as D,d as N,i as m}from"./chunk-6SHX42QQ.js";import{a as b}from"./chunk-YZXV3CU3.js";import{e as f,f as x}from"./chunk-ZL5Y23AJ.js";import{readFileSync as G,writeFileSync as F,existsSync as P}from"fs";import{isAbsolute as ue,join as R,relative as pe,resolve as he}from"path";var g=".scipquery.json",k=250,j=0,E=10*6e4,W={enabled:!1,debounceMs:k,cooldownMs:j,gitPollMs:2e3,idleTimeoutMs:E,autoRefresh:!0,ignore:[]},U=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"];var de=new Set(U);function y(s){let e=R(s,g);if(!P(e))return{};try{let t=G(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 T(s){return{...W,...s.watch}}function q(s,e){let t=R(s,g);return P(t)||F(t,JSON.stringify({languages:e,watch:{enabled:!0,debounceMs:k,cooldownMs:j,gitPollMs:2e3,idleTimeoutMs:E,autoRefresh:!0}},null,2)+`
|
|
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};
|
|
2
3
|
//# sourceMappingURL=runtime.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./chunk-P5XHIJHI.js";import{a as b,b as v}from"./chunk-
|
|
1
|
+
import"./chunk-P5XHIJHI.js";import{a as b,b as v}from"./chunk-KHE7J5ZN.js";import{a as w,g as k}from"./chunk-JHK2DMUQ.js";import d from"process";import{closeSync as ee,mkdirSync as y,openSync as re,readFileSync as O,readdirSync as ne,rmSync as h,writeFileSync as te}from"fs";import{dirname as se,resolve as c}from"path";import{pathToFileURL as oe}from"url";import{spawn as x}from"child_process";import{createHash as B,randomUUID as W}from"crypto";import{existsSync as L,mkdirSync as ge,readFileSync as he,realpathSync as Ee,rmSync as Ie}from"fs";import{tmpdir as _e}from"os";import{resolve as ke}from"path";var T=2;var g=class{constructor(r,n=z){this.createRequester=r;this.applyEnvironment=n}createRequester;applyEnvironment;requester=null;identityKey=null;semanticResponseCache=null;handle(r){this.applyEnvironment(r.workerEnvironment??{});let n;if(this.requester?this.identityKey!==r.identityKey?(this.semanticResponseCache=null,this.requester.shutdown(),this.requester=this.createRequester(),this.identityKey=r.identityKey,n="invalidated"):n="reused":(this.requester=this.createRequester(),this.identityKey=r.identityKey,n="created"),r.kind==="semantic"){let s=j(r.request),o=n==="reused"&&s!==null&&this.semanticResponseCache?.identityKey===r.identityKey&&this.semanticResponseCache.requestKey===s?this.semanticResponseCache.response:null;if(o)return M(!0,r.request.definitions.length),{session:n,response:o};let a=this.requester.requestSemantic(r.request,r.timeoutMs);return s!==null&&F(a)&&(this.semanticResponseCache={identityKey:r.identityKey,requestKey:s,response:a}),M(!1,r.request.definitions.length),{session:n,response:a}}return{session:n,response:this.requester.requestImportDefinitions(r.request,r.timeoutMs)}}shutdown(){this.requester?.shutdown(),this.requester=null,this.identityKey=null,this.semanticResponseCache=null}};function j(e){if(e.includeReferences===!1||e.includeCallees!==!0||e.includeSignatures===!0||(e.referenceDefinitions?.length??0)===0||(e.calleeDefinitions?.length??0)===0)return null;let{readinessDeadlineMs:r,...n}=e;return $(I(n))}function F(e){return e.available&&Array.isArray(e.callees)&&(e.incompleteReferenceSymbolIds?.length??0)===0}function M(e,r){w()&&k({type:"span",name:"rust.semantic.durable-session.response-cache",durationMs:0,ok:!0,hit:e,definitions:r})}function z(e){for(let r of Object.keys(process.env))Y(r)&&delete process.env[r];for(let[r,n]of Object.entries(e))n!==null&&(process.env[r]=n)}function K(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function Y(e){return K(e)||e.startsWith("SCIP_RUST_")||e==="SCIP_QUERY_PROFILE"||e==="SCIP_QUERY_PROFILE_CACHE_STATE"||e==="SCIP_QUERY_PROFILE_COMMAND"||e==="SCIP_QUERY_PROFILE_OUT"||e==="SCIP_QUERY_PROFILE_RUN_ID"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND"||e==="SCIP_QUERY_PROFILE_MIN_MS"}var Ae={now:Date.now,randomId:W,isProcessAlive:b,spawnServer(e,r,n){if(!L(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);x(process.execPath,[e,r,n],{detached:!0,stdio:"ignore"}).unref()},sleep(e){let r=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(r,0,0,e)}};function I(e){return Array.isArray(e)?`[${e.map(I).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${JSON.stringify(r)}:${I(n)}`).join(",")}}`:JSON.stringify(e)}function $(e){return B("sha256").update(e).digest("hex")}import{existsSync as H,mkdtempSync as A,readFileSync as C,rmSync as D}from"fs";import{tmpdir as q}from"os";import{join as _}from"path";import{fileURLToPath as P,pathToFileURL as V}from"url";import{SHARE_ENV as J,Worker as Q}from"worker_threads";function U(e={}){let r=null,n=null,s=1,o=!1,a=()=>{n&&(D(n,{recursive:!0,force:!0}),n=null)},f=()=>{let t=r;r=null,t&&t.terminate(),a()},u=()=>{if(r)return r;let t=e.semanticWorkerPath?V(e.semanticWorkerPath):Z();if(!H(P(t)))throw new Error(`Rust semantic session worker was not found at ${P(t)}. Run npm run build before using built semantic Rust queries.`);return n=A(_(q(),"scip-query-rust-session-")),r=new Q(t,e.shareEnvironment?{env:J}:void 0),r.unref(),r},l=()=>{let t=n??A(_(q(),"scip-query-rust-session-"));return n=t,_(t,`${s++}.json`)};return{requestSemantic(t,i){if(o)throw new Error("Rust semantic session was already disposed.");let R=u(),p=l(),S=new SharedArrayBuffer(4),E=new Int32Array(S);if(R.postMessage({kind:"semantic",request:t,responsePath:p,sharedBuffer:S}),Atomics.wait(E,0,0,i)==="timed-out")throw f(),new Error(`Rust semantic session worker timed out after ${(i/1e3).toFixed(0)}s`);try{let m=G(C(p,"utf8"));if(!m.ok)throw new Error(m.error);return m.response}finally{D(p,{force:!0})}},requestImportDefinitions(t,i){if(o)throw new Error("Rust semantic session was already disposed.");let R=u(),p=l(),S=new SharedArrayBuffer(4),E=new Int32Array(S);if(R.postMessage({kind:"import-definitions",request:t,responsePath:p,sharedBuffer:S}),Atomics.wait(E,0,0,i)==="timed-out")throw f(),new Error(`Rust semantic import-definition session worker timed out after ${(i/1e3).toFixed(0)}s`);try{let m=X(C(p,"utf8"));if(!m.ok)throw new Error(m.error);return m.response}finally{D(p,{force:!0})}},shutdown(){if(o)return;if(o=!0,!r){a();return}let t=l(),i=new SharedArrayBuffer(4),R=new Int32Array(i);r.postMessage({kind:"shutdown",responsePath:t,sharedBuffer:i}),Atomics.wait(R,0,0,5e3),f()}}}function G(e){let r=JSON.parse(e);if(!r||typeof r!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=r;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof r.error=="string"?r.error:"Rust semantic session worker failed."}}function X(e){let r=JSON.parse(e);if(!r||typeof r!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=r;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof r.error=="string"?r.error:"Rust semantic session worker failed."}}function Z(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}var ie=10*6e4,ae=10,ue=1e3;function le(e,r,n={}){let s=c(e,"requests"),o=c(e,"responses");y(s,{recursive:!0}),y(o,{recursive:!0});let a=0;for(let f of ne(s).filter(u=>u.endsWith(".json")).sort()){let u=c(s,f),l=null;try{l=fe(O(u,"utf8")),n.beforeRequest?.(l.request);let t=r.handle(l.request);v(c(o,`${l.id}.json`),{ok:!0,...t})}catch(t){let i=l?.id??f.slice(0,-5);v(c(o,`${i}.json`),{ok:!1,error:t instanceof Error?t.message:String(t)})}finally{h(u,{force:!0}),a+=1}}return a}async function ce(e,r){y(c(e,"requests"),{recursive:!0}),y(c(e,"responses"),{recursive:!0});let n=c(e,"server.lock");if(!Re(n))return;let s=new g(()=>U({semanticWorkerPath:r,shareEnvironment:!0})),o=!1,a=Date.now(),f=0,u,l=()=>{o=!0};d.once("SIGINT",l),d.once("SIGTERM",l);let t=(i=!1)=>{let R=Date.now();!i&&R-f<ue||(f=R,v(c(e,"server.json"),{protocolVersion:T,pid:d.pid,heartbeatAtMs:R,...u===void 0?{}:{busyUntilMs:u}}))};try{t(!0);let i=pe();for(;!o&&Date.now()-a<i;)le(e,s,{beforeRequest(p){u=Date.now()+p.timeoutMs+5e3,t(!0)}})>0?(a=Date.now(),u=void 0,t(!0)):t(),await me(ae)}finally{s.shutdown(),h(c(e,"server.json"),{force:!0}),h(n,{force:!0})}}function Re(e){y(se(e),{recursive:!0});for(let r=0;r<2;r+=1)try{let n=re(e,"wx");return te(n,String(d.pid)),ee(n),!0}catch{let n=de(e);if(n!==null&&b(n))return!1;h(e,{force:!0})}return!1}function de(e){try{let r=Number(O(e,"utf8"));return Number.isInteger(r)&&r>0?r:null}catch{return null}}function fe(e){let r=JSON.parse(e);if(typeof r.id!="string"||!r.request||typeof r.request!="object")throw new Error("Durable Rust semantic helper received an invalid mailbox request.");return{id:r.id,request:r.request}}function pe(){let e=Number(d.env.SCIP_RUST_SEMANTIC_DURABLE_IDLE_MS);return Number.isInteger(e)&&e>=0?e:ie}function me(e){return new Promise(r=>setTimeout(r,e))}var Se=d.argv[1]?oe(c(d.argv[1])).href:null;if(Se===import.meta.url){let e=d.argv[2],r=d.argv[3];!e||!r?(console.error("durable-rust-session: expected <session-dir> <semantic-worker-path>"),d.exitCode=1):await ce(e,r)}export{le as processDurableRustSessionRequests};
|
|
2
2
|
//# sourceMappingURL=rust-semantic-session-server.js.map
|
package/dist/watch-server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as Q,B as bt,Ba as Gt,C as xt,Ca as pe,D as vt,Da as Wt,Ea as $t,F as se,Fa as qt,G as Rt,H as Mt,J as Dt,K as Tt,L as Pt,M as Ct,N as ae,O as ce,P as kt,R as Ft,S as Ee,T as wt,U as Et,V as Lt,Y as Nt,a as nt,aa as H,b as rt,ba as de,c as Pe,ca as Le,d as it,da as jt,ea as At,f as ot,fa as B,g as st,h as at,j as Ce,k as ke,l as ct,m as lt,o as dt,p as pt,q as ut,qa as _t,r as ft,s as mt,t as ht,ta as Ne,v as gt,w as yt,x as Fe,y as we,z as St,za as Ot}from"./chunk-SALRDXWM.js";import{b as K,f as q,j as It,k as le}from"./chunk-SMBIGBGN.js";import{a as V,b as j}from"./chunk-3M2UCPFS.js";import{a as oe,c as tt,d as Te,e as N}from"./chunk-JHK2DMUQ.js";import C from"process";import{rmSync as _n}from"fs";import{resolve as Ri}from"path";import{pathToFileURL as Mi}from"url";import{existsSync as Ht,readFileSync as Wn}from"fs";function je(n,e,t){let r=new Date().toISOString();if(!Ht(t.dbPath))return{state:"missing",checkedAt:r,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Ht(t.metaPath))return{state:"unknown",checkedAt:r,metaPath:t.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=JSON.parse(Wn(t.metaPath,"utf-8")),o=e.languages??Nt(n),a=$n(n,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=_t(t.dbPath,t.metaPath),d=l.state==="invalid"||l.state==="drifted",p=c&&!d;return{state:p?"fresh":"stale",checkedAt:r,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:r,metaPath:t.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function $n(n,e,t){return It(n,e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{fork as qn}from"child_process";import{statSync as Hn}from"fs";import{isAbsolute as Bn,join as Un,relative as zn}from"path";import{watch as Jn}from"chokidar";import Vn from"ignore";var ue=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=de(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=le(e.projectRoot),this.extraIgnore=Vn(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let e=Jn(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=Bt(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=Bn(e)?e:Un(this.projectRoot,e);return zn(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=Bt(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=H(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=qn(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):r(new Error(`Reindex worker exited with code ${p}`))}),d.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=Pe(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=it(this.projectRoot,e),r={head:Pe(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=Hn(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 Bt(n,e){return n?n.kind===e.kind?n.detail===e.detail?n:{kind:n.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${n.kind}, ${e.kind}`}:e}import{existsSync as Qt,statSync as tr}from"fs";import{join as nr}from"path";import{createHash as Kn}from"crypto";import{readFileSync as Qn}from"fs";import{dirname as Yn,join as fe}from"path";var Y=2,Xn="typescript-semantic";function zt(n){let e=fe(n,Xn);return{rootDir:e,requestDir:fe(e,"requests"),responseDir:fe(e,"responses")}}function X(n){try{let e=JSON.parse(Qn(fe(Yn(n),"meta.json"),"utf8"));return e.version!==2&&e.version!==3||typeof e.status!="string"||typeof e.updatedAt!="string"||e.fingerprint===void 0?null:Kn("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 Jt(n){let e=JSON.parse(n);if(e.protocolVersion!==Y||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||e.profileEnvironment!==void 0&&!Zn(e.profileEnvironment)||!e.request||!er(e.request))throw new Error("TypeScript semantic service received an invalid mailbox request.");return e}function Zn(n){return!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.values(n).every(e=>typeof e=="string"||e===null)}function er(n){if(!n||typeof n!="object"||!("kind"in n))return!1;let e=n;switch(e.kind){case"availability":return!0;case"import-usage":return typeof e.file=="string";case"reference-fragments":return St(e.files)!==null;case"references":return Ut(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return Ut(e.definitions);case"signature":return Vt(e.definition);default:return!1}}function Ut(n){return Array.isArray(n)&&n.every(Vt)}function Vt(n){if(!n||typeof n!="object")return!1;let e=n;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 rr(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var Kt;function ir(n=rr(),e=void 0){if(e===void 0&&Kt?.projectRoot===n)return Kt;let t=H(n),r=B(n,t),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:n,config:t,paths:r,dbPath:i,dbPathSource:"env",gitContext:e};if(Qt(r.dbPath))return{projectRoot:n,config:t,paths:r,dbPath:r.dbPath,dbPathSource:"configured",gitContext:e};let o=nr(n,"index.db");return{projectRoot:n,config:t,paths:r,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:or(o,r.dbPath),gitContext:e}}function Yt(n,e={}){let{config:t,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:a,gitContext:s}=ir(n);if(!Qt(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??r.indexPath,projectRoot:n,sharedEvidenceDbPath:Ne(n,t,s),entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality,coverageContracts:t.coverageContracts,docs:t.docs},l=le(n);return new at(c,l)}function or(n,e){let t="unknown time";try{t=tr(n).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${n}, 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 Dn,readFileSync as Tn,readdirSync as ii,rmSync as oi}from"fs";import{resolve as be}from"path";import{resolve as Mn}from"path";import{performance as y}from"perf_hooks";function me(n){return{forFile(e,t){return Xt(n,e,t)},forFiles(e,t){let r=new Map;for(let i of e)r.set(i,Xt(n,i,t));return r}}}function Xt(n,e,t){let r={file:e},i=t.facts||t.identifiers;if(t.text&&(r.text=pt(n,e)),t.lines&&(r.lines=ut(n,e)),t.ast&&(r.ast=ft(n,e)),t.imports&&(r.imports=xt(n,e)),t.reexports&&(r.reexports=bt(n,e)),i){let o=mt(n,e),a=o.facts;t.facts&&(r.facts=a),o.unavailable&&(r.sourceFactsUnavailable=o.unavailable),t.identifiers&&a&&(r.identifiers=a.fileIdentifiers,r.identifierLineMap=a.identifierLineMap)}return r}var sr={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function he(n){if(n.startsWith("local "))return{kind:"local",id:n.slice(6),raw:n};let e=n.split(" ");if(e.length<4)return{scheme:e[0]??"",manager:e[1]??"",packageName:e[2]??"",version:"",descriptors:[],raw:n};let t=e[0],r=e[1],i=n.slice(t.length+1+r.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=ar(i);return{scheme:t,manager:r,packageName:o,version:a,descriptors:c,raw:n}}function U(n){let e=he(n);if("kind"in e)return null;for(let t=e.descriptors.length-2;t>=0;t--){let r=e.descriptors[t];if(r?.suffix==="type")return r.name}return null}function ar(n){let e=[],t=0;for(;t<n.length;){if(n[t]==="["){let o=n.indexOf("]",t+1);if(o===-1){e.push({name:n.slice(t+1),suffix:"type-param"});break}e.push({name:n.slice(t+1,o),suffix:"type-param"}),t=o+1;continue}if(n[t]==="("&&(e.length===0||t===0||Zt(n[t-1]))){let o=n.indexOf(")",t+1);if(o!==-1&&n[o+1]!=="."){e.push({name:n.slice(t+1,o),suffix:"parameter"}),t=o+1;continue}}let r;if(n[t]==="`"){let o=n.indexOf("`",t+1);if(o===-1){r=n.slice(t+1),e.push({name:r,suffix:"term"});break}r=n.slice(t+1,o),t=o+1}else{let o=t;for(;t<n.length&&!Zt(n[t]);)t++;r=n.slice(o,t)}if(t>=n.length){r&&e.push({name:r,suffix:"term"});break}let i=n[t];if(i==="("){let o=n.indexOf(")",t+1);o!==-1&&n[o+1]==="."?(e.push({name:r,suffix:"method"}),t=o+2):o!==-1?(e.push({name:r,suffix:"method"}),t=o+1):(e.push({name:r,suffix:"term"}),t++)}else{let o=sr[i];o&&e.push({name:r,suffix:o}),t+=1}}return e}function Zt(n){return n==="/"||n==="#"||n==="."||n==="("||n==="["||n===":"||n==="!"}function A(n){let e=he(n);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 _(n){let e=he(n);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function en(n){let e=_(n);return e==="method"?!0:e!=="term"?!1:n.endsWith("().")?!0:n.startsWith("rust-analyzer ")&&n.includes("#")?!1:n.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(n):!0}function cr(n,e={}){if(U(n.symbol)!==null)return e.includeClassMemberFallbacks===!0;let i=(n.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function tn(n,e,t={}){let r=new Map;for(let o of e)n.length>0&&!cr(o,{includeClassMemberFallbacks:t.includeClassMemberFallbacks})||r.set(o.id,o);for(let o of n)r.set(o.id,o);let i=[...r.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 lr=K("file-definitions",{clearGroups:["definition-catalog"]}),Co=K("file-function-like-definitions",{clearGroups:["definition-catalog"]});function O(n,e,t={}){return t.includeClassMemberFallbacks?nn(n,e,void 0,{includeClassMemberFallbacks:!0}):lr.get(n,e,()=>{let r=dr(n,e);if(r)return r;let i=nn(n,e),o=ke(n),a=me(n).forFile(e,{text:!0}).text;return o&&a&&on.write(n,e,Ce(n,e,a),{projectFingerprint:o,definitions:i.map(s=>({...s}))}),i})}var on=lt({kind:"file-definitions",invalidation:dt("file-definitions"),serialize:pr,deserialize:ur});function dr(n,e){let t=ke(n);if(!t)return null;let r=me(n).forFile(e,{text:!0}).text;if(!r)return null;let i=on.read(n,e,Ce(n,e,r));return i?fr(i,t,e):null}function pr(n){return JSON.stringify(n)}function ur(n){try{let e=JSON.parse(n);return!we(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function fr(n,e,t){if(n.projectFingerprint!==e)return null;let r=[];for(let i of n.definitions){let o=mr(i,t);if(!o)return null;r.push(o)}return r}function mr(n,e){return!we(n)||typeof n.symbolId!="number"||typeof n.symbol!="string"||typeof n.documentId!="number"||typeof n.startLine!="number"||typeof n.startChar!="number"&&n.startChar!==void 0||typeof n.endLine!="number"||typeof n.endChar!="number"&&n.endChar!==void 0||n.relativePath!==e||typeof n.leaf!="string"||typeof n.parentTypeName!="string"&&n.parentTypeName!==null||typeof n.isFunctionLike!="boolean"||typeof n.isTypeLike!="boolean"||typeof n.kind!="number"&&n.kind!==null||typeof n.documentation!="string"&&n.documentation!==null||typeof n.enclosingSymbol!="string"&&n.enclosingSymbol!==null?null:{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,startChar:n.startChar,endLine:n.endLine,endChar:n.endChar,relativePath:n.relativePath,leaf:n.leaf,parentTypeName:n.parentTypeName,isFunctionLike:n.isFunctionLike,isTypeLike:n.isTypeLike,kind:n.kind,documentation:n.documentation,enclosingSymbol:n.enclosingSymbol}}function nn(n,e,t,r={}){let i=tn(hr(n,e),gr(n,e),{sort:!0,includeClassMemberFallbacks:r.includeClassMemberFallbacks}).map(yr);return t&&(i=i.filter(t)),br(n,e,i)}function hr(n,e){return n.all(`SELECT
|
|
1
|
+
import{A as Et,B as Q,C as Ft,D as At,E as je,G as H,H as Lt,I as le,J as de,K as pe,L as Nt,N as jt,O as _e,P as _t,Q as Ot,U as Oe,V as Wt,W as $t,X as B,a as ft,b as mt,c as ht,d as De,e as gt,f as Ee,g as yt,ga as Gt,h as St,i as vt,ja as We,k as Fe,l as Ae,m as xt,n as It,p as Rt,pa as qt,q as Ct,r as wt,ra as Ut,s as Mt,sa as fe,t as kt,ta as Ht,u as Pt,ua as Bt,va as Vt,w as Tt,x as Dt,y as Le,z as Ne}from"./chunk-IXORBCMR.js";import{b as dt,c as pt,f as bt,h as J,l as U,m as ue}from"./chunk-VV5WJLRO.js";import{a as j,b as F}from"./chunk-KHE7J5ZN.js";import{a as ce,c as ut,d as Te,e as N}from"./chunk-JHK2DMUQ.js";import P from"process";import{rmSync as Yr}from"fs";import{resolve as ro}from"path";import{pathToFileURL as no}from"url";import{readFileSync as Xr,writeFileSync as mo,existsSync as Zr}from"fs";import{isAbsolute as go,join as en,relative as yo,resolve as So}from"path";var $e=".scipquery.json",tn=250,rn=0,nn=10*6e4,on={enabled:!1,debounceMs:tn,cooldownMs:rn,gitPollMs:2e3,idleTimeoutMs:nn,autoRefresh:!0,ignore:[]},sn=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"];var bo=new Set(sn);function V(r){let e=en(r,$e);if(!Zr(e))return{};try{let t=Xr(e,"utf-8");return JSON.parse(t)}catch(t){let n=t instanceof Error?t.message:String(t);throw t instanceof SyntaxError?new Error(`invalid ${$e} at ${e}: ${n}`,{cause:t}):new Error(`unable to read ${$e} at ${e}: ${n}`,{cause:t})}}function me(r){return{...on,...r.watch}}import{existsSync as Kt,readFileSync as an}from"fs";function Ge(r,e,t){let n=new Date().toISOString();if(!Kt(t.dbPath))return{state:"missing",checkedAt:n,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Kt(t.metaPath))return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=JSON.parse(an(t.metaPath,"utf-8")),o=e.languages??Ot(r),a=cn(r,o,e),s=Array.isArray(i.indexedLanguages)?[...i.indexedLanguages].sort():[],c=(i.version===2||i.version===3)&&i.status==="complete"&&JSON.stringify(i.fingerprint)===JSON.stringify(a)&&JSON.stringify(s)===JSON.stringify(a.languages),l=Gt(t.dbPath,t.metaPath),d=l.state==="invalid"||l.state==="drifted",p=c&&!d;return{state:p?"fresh":"stale",checkedAt:n,metaPath:t.metaPath,updatedAt:i.updatedAt,lastRefresh:i.lastRefresh,reason:d?`SQLite generation requires repair: ${l.reason}`:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:p?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function cn(r,e,t){return bt(r,e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{fork as ln}from"child_process";import{statSync as dn}from"fs";import{isAbsolute as pn,join as un,relative as fn}from"path";import{watch as mn}from"chokidar";import hn from"ignore";var he=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=me(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.gitignoreFilter=ue(e.projectRoot),this.extraIgnore=hn(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{let e=mn(this.projectRoot,{ignoreInitial:!0,ignored:(t,n)=>this.isIgnoredWatchPath(t,n?.isDirectory()??!1)});e.on("all",(t,n)=>{this.stopped||this.handleFileChange(n)}),e.on("error",t=>{this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`))}),this.fsWatchers.push(e)}catch(e){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}}stop(){this.stopped=!0;for(let e of this.fsWatchers)e.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(e,t={}){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=zt(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}isIgnoredWatchPath(e,t){let n=this.relativeWatchPath(e);if(!n)return!1;let i=t?`${n}/`:n;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(e){let t=this.relativeWatchPath(e);!t||t===".."||t.startsWith("../")||t===".git"||t.startsWith(".git/")||this.gitignoreFilter.isIgnored(t)||this.extraIgnore.ignores(t)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=pn(e)?e:un(this.projectRoot,e);return fn(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=zt(this.pendingTrigger,e),this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let t=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-e;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex(t).then(i=>{if(this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onReindexComplete(i),this.dirty&&!this.stopped){let o=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(e){return new Promise((t,n)=>{let i=Date.now(),o=V(this.projectRoot),a=Object.keys(o).length>0?o:this.config,s=B(this.projectRoot,a),c=a.indexer?.typescript,l=a.indexer?.clojure,d=ln(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:s.indexPath,SCIP_REINDEX_OUTPUT_DB:s.dbPath,SCIP_REINDEX_LANGUAGES:(a.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(a.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:e.kind,SCIP_REINDEX_TRIGGER_DETAIL:e.detail??""},stdio:"pipe"});d.on("exit",p=>{p===0?t(Date.now()-i):n(new Error(`Reindex worker exited with code ${p}`))}),d.on("error",n)})}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,t=this.readGitState();if(!e||!t||this.stopped){this.lastGitState=t;return}this.lastGitState=t;let n=e.head!==t.head,i=e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize;n&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):n?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:t.indexPath??"index changed"})}readGitState(){let e=De(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=gt(this.projectRoot,e),n={head:De(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=dn(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function zt(r,e){return r?r.kind===e.kind?r.detail===e.detail?r:{kind:r.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${r.kind}, ${e.kind}`}:e}import{existsSync as er,statSync as In}from"fs";import{join as Rn}from"path";import{createHash as gn}from"crypto";import{readFileSync as yn}from"fs";import{dirname as Sn,join as ge}from"path";var X=2,bn="typescript-semantic";function Jt(r){let e=ge(r,bn);return{rootDir:e,requestDir:ge(e,"requests"),responseDir:ge(e,"responses")}}function Z(r){try{let e=JSON.parse(yn(ge(Sn(r),"meta.json"),"utf8"));return e.version!==2&&e.version!==3||typeof e.status!="string"||typeof e.updatedAt!="string"||e.fingerprint===void 0?null:gn("sha256").update(JSON.stringify({version:e.version,status:e.status,updatedAt:e.updatedAt,fingerprint:e.fingerprint,indexedLanguages:e.indexedLanguages})).digest("hex")}catch{return null}}function Qt(r){let e=JSON.parse(r);if(e.protocolVersion!==X||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||e.profileEnvironment!==void 0&&!vn(e.profileEnvironment)||!e.request||!xn(e.request))throw new Error("TypeScript semantic service received an invalid mailbox request.");return e}function vn(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&Object.values(r).every(e=>typeof e=="string"||e===null)}function xn(r){if(!r||typeof r!="object"||!("kind"in r))return!1;let e=r;switch(e.kind){case"availability":return!0;case"import-usage":return typeof e.file=="string";case"reference-fragments":return Et(e.files)!==null;case"references":return Yt(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return Yt(e.definitions);case"signature":return Xt(e.definition);default:return!1}}function Yt(r){return Array.isArray(r)&&r.every(Xt)}function Xt(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.symbolId=="number"&&typeof e.documentId=="number"&&typeof e.symbol=="string"&&typeof e.relativePath=="string"&&typeof e.leaf=="string"&&typeof e.startLine=="number"&&typeof e.endLine=="number"}function Cn(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var Zt;function wn(r=Cn(),e=void 0){if(e===void 0&&Zt?.projectRoot===r)return Zt;let t=V(r),n=B(r,t),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:r,config:t,paths:n,dbPath:i,dbPathSource:"env",gitContext:e};if(er(n.dbPath))return{projectRoot:r,config:t,paths:n,dbPath:n.dbPath,dbPathSource:"configured",gitContext:e};let o=Rn(r,"index.db");return{projectRoot:r,config:t,paths:n,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:Mn(o,n.dbPath),gitContext:e}}function tr(r,e={}){let{config:t,paths:n,dbPath:i,dbPathSource:o,rootFallbackWarning:a,gitContext:s}=wn(r);if(!er(i))throw new Error("No index.db found. Run: scip-query reindex");e.warnOnRootFallback&&o==="root-fallback"&&a&&console.error(a);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:r,sharedEvidenceDbPath:We(r,t,s),entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality,architecture:t.architecture,coverageContracts:t.coverageContracts,docs:t.docs},l=ue(r);return new vt(c,l)}function Mn(r,e){let t="unknown time";try{t=In(r).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${r}, modified ${t}) because the configured index was not found at ${e}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}import{mkdirSync as Pr,readFileSync as Tr,readdirSync as wi,rmSync as Mi}from"fs";import{resolve as Ie}from"path";import{resolve as kr}from"path";import{performance as y}from"perf_hooks";function ye(r){return{forFile(e,t){return rr(r,e,t)},forFiles(e,t){let n=new Map;for(let i of e)n.set(i,rr(r,i,t));return n}}}function rr(r,e,t){let n={file:e},i=t.facts||t.identifiers;if(t.text&&(n.text=Ct(r,e)),t.lines&&(n.lines=wt(r,e)),t.ast&&(n.ast=Mt(r,e)),t.imports&&(n.imports=At(r,e)),t.reexports&&(n.reexports=Ft(r,e)),i){let o=kt(r,e),a=o.facts;t.facts&&(n.facts=a),o.unavailable&&(n.sourceFactsUnavailable=o.unavailable),t.identifiers&&a&&(n.identifiers=a.fileIdentifiers,n.identifierLineMap=a.identifierLineMap)}return n}var kn={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function Se(r){if(r.startsWith("local "))return{kind:"local",id:r.slice(6),raw:r};let e=r.split(" ");if(e.length<4)return{scheme:e[0]??"",manager:e[1]??"",packageName:e[2]??"",version:"",descriptors:[],raw:r};let t=e[0],n=e[1],i=r.slice(t.length+1+n.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let a,s=i.indexOf(" ");s===-1?(a=i,i=""):(a=i.slice(0,s),i=i.slice(s+1));let c=Pn(i);return{scheme:t,manager:n,packageName:o,version:a,descriptors:c,raw:r}}function K(r){let e=Se(r);if("kind"in e)return null;for(let t=e.descriptors.length-2;t>=0;t--){let n=e.descriptors[t];if(n?.suffix==="type")return n.name}return null}function Pn(r){let e=[],t=0;for(;t<r.length;){if(r[t]==="["){let o=r.indexOf("]",t+1);if(o===-1){e.push({name:r.slice(t+1),suffix:"type-param"});break}e.push({name:r.slice(t+1,o),suffix:"type-param"}),t=o+1;continue}if(r[t]==="("&&(e.length===0||t===0||nr(r[t-1]))){let o=r.indexOf(")",t+1);if(o!==-1&&r[o+1]!=="."){e.push({name:r.slice(t+1,o),suffix:"parameter"}),t=o+1;continue}}let n;if(r[t]==="`"){let o=r.indexOf("`",t+1);if(o===-1){n=r.slice(t+1),e.push({name:n,suffix:"term"});break}n=r.slice(t+1,o),t=o+1}else{let o=t;for(;t<r.length&&!nr(r[t]);)t++;n=r.slice(o,t)}if(t>=r.length){n&&e.push({name:n,suffix:"term"});break}let i=r[t];if(i==="("){let o=r.indexOf(")",t+1);o!==-1&&r[o+1]==="."?(e.push({name:n,suffix:"method"}),t=o+2):o!==-1?(e.push({name:n,suffix:"method"}),t=o+1):(e.push({name:n,suffix:"term"}),t++)}else{let o=kn[i];o&&e.push({name:n,suffix:o}),t+=1}}return e}function nr(r){return r==="/"||r==="#"||r==="."||r==="("||r==="["||r===":"||r==="!"}function _(r){let e=Se(r);if("kind"in e&&e.kind==="local")return e.id;let t=e;return t.descriptors.length===0?"":t.descriptors[t.descriptors.length-1].name}function O(r){let e=Se(r);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function ir(r){let e=O(r);return e==="method"?!0:e!=="term"?!1:r.endsWith("().")?!0:r.startsWith("rust-analyzer ")&&r.includes("#")?!1:r.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(r):!0}function Tn(r,e={}){if(K(r.symbol)!==null)return e.includeClassMemberFallbacks===!0;let i=(r.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function or(r,e,t={}){let n=new Map;for(let o of e)r.length>0&&!Tn(o,{includeClassMemberFallbacks:t.includeClassMemberFallbacks})||n.set(o.id,o);for(let o of r)n.set(o.id,o);let i=[...n.values()];return t.sort?i.sort((o,a)=>o.start_line-a.start_line||o.end_line-a.end_line||o.symbol.localeCompare(a.symbol)):i}var Dn=J("file-definitions",{clearGroups:["definition-catalog"]}),ys=J("file-function-like-definitions",{clearGroups:["definition-catalog"]});function W(r,e,t={}){return t.includeClassMemberFallbacks?sr(r,e,void 0,{includeClassMemberFallbacks:!0}):Dn.get(r,e,()=>{let n=En(r,e);if(n)return n;let i=sr(r,e),o=Ae(r),a=ye(r).forFile(e,{text:!0}).text;return o&&a&&cr.write(r,e,Fe(r,e,a),{projectFingerprint:o,definitions:i.map(s=>({...s}))}),i})}var cr=It({kind:"file-definitions",invalidation:Rt("file-definitions"),serialize:Fn,deserialize:An});function En(r,e){let t=Ae(r);if(!t)return null;let n=ye(r).forFile(e,{text:!0}).text;if(!n)return null;let i=cr.read(r,e,Fe(r,e,n));return i?Ln(i,t,e):null}function Fn(r){return JSON.stringify(r)}function An(r){try{let e=JSON.parse(r);return!Ne(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function Ln(r,e,t){if(r.projectFingerprint!==e)return null;let n=[];for(let i of r.definitions){let o=Nn(i,t);if(!o)return null;n.push(o)}return n}function Nn(r,e){return!Ne(r)||typeof r.symbolId!="number"||typeof r.symbol!="string"||typeof r.documentId!="number"||typeof r.startLine!="number"||typeof r.startChar!="number"&&r.startChar!==void 0||typeof r.endLine!="number"||typeof r.endChar!="number"&&r.endChar!==void 0||r.relativePath!==e||typeof r.leaf!="string"||typeof r.parentTypeName!="string"&&r.parentTypeName!==null||typeof r.isFunctionLike!="boolean"||typeof r.isTypeLike!="boolean"||typeof r.kind!="number"&&r.kind!==null||typeof r.documentation!="string"&&r.documentation!==null||typeof r.enclosingSymbol!="string"&&r.enclosingSymbol!==null?null:{symbolId:r.symbolId,symbol:r.symbol,documentId:r.documentId,startLine:r.startLine,startChar:r.startChar,endLine:r.endLine,endChar:r.endChar,relativePath:r.relativePath,leaf:r.leaf,parentTypeName:r.parentTypeName,isFunctionLike:r.isFunctionLike,isTypeLike:r.isTypeLike,kind:r.kind,documentation:r.documentation,enclosingSymbol:r.enclosingSymbol}}function sr(r,e,t,n={}){let i=or(jn(r,e),_n(r,e),{sort:!0,includeClassMemberFallbacks:n.includeClassMemberFallbacks}).map(On);return t&&(i=i.filter(t)),$n(r,e,i)}function jn(r,e){return r.all(`SELECT
|
|
2
2
|
gs.id,
|
|
3
3
|
gs.symbol,
|
|
4
4
|
der.document_id,
|
|
@@ -15,8 +15,8 @@ import{A as Q,B as bt,Ba as Gt,C as xt,Ca as pe,D as vt,Da as Wt,Ea as $t,F as s
|
|
|
15
15
|
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
16
16
|
JOIN documents d ON der.document_id = d.id
|
|
17
17
|
WHERE d.relative_path = ?
|
|
18
|
-
${
|
|
19
|
-
ORDER BY der.start_line, der.end_line`,e)}function
|
|
18
|
+
${r.symbolNoiseFor("gs")}
|
|
19
|
+
ORDER BY der.start_line, der.end_line`,e)}function _n(r,e){return r.all(`SELECT
|
|
20
20
|
gs.id,
|
|
21
21
|
gs.symbol,
|
|
22
22
|
c.document_id,
|
|
@@ -35,8 +35,9 @@ import{A as Q,B as bt,Ba as Gt,C as xt,Ca as pe,D as vt,Da as Wt,Ea as $t,F as s
|
|
|
35
35
|
JOIN documents d ON c.document_id = d.id
|
|
36
36
|
WHERE d.relative_path = ?
|
|
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=>J(t,an.join(t,l.file))===e))}function Ae(n){for(let e=n;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 _e(n,e){return n.getLineAndColumnAtPos(e.getStart()).line-1}function z(n){let e=new Set,t=[];for(let r of n){let i=`${r.file}:${r.line}:${r.column}`;e.has(i)||(e.add(i),t.push(r))}return t}function J(n,e){let t=an.relative(n||process.cwd(),e).replace(/\\/g,"/");return!t||t.startsWith("..")?null:t}function pn(n,e,t,r){let i=_r(e,r);return i.size===0?new Map:Or(n,t,i)}function _r(n,e){let t=new Map;for(let r of O(n,e)){let i=A(r.symbol)??r.leaf;if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push(r)}return t}function Or(n,e,t){let r=new Map,i=new Map;return e.forEachDescendant(o=>{for(let a of Gr(n,o)){let s=t.get(a);if(!s)continue;let c=_e(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),r.set(l.symbolId,o))}}}),r}function Gr(n,e){let t=[],r=i=>{i&&!t.includes(i)&&t.push(i)};if("getNameNode"in e&&typeof e.getNameNode=="function"){let i=e.getNameNode();r(i?.getText())}if("getName"in e&&typeof e.getName=="function"){let i=e.getName();r(i)}return n.Node.isIdentifier(e)&&r(e.getText()),t}var Wr=K("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function un(n,e,t,r){let i=We(n,e),o=Oe(i.get(r)??[],t);if(o)return o;let a=[];for(let s of i.values())for(let c of s)((c.leaf||A(c.symbol)||"").includes(r)||c.symbol.includes(r))&&a.push(c);return Oe(a,t)}function Ge(n,e,t,r){return Oe(We(n,e).get(r)??[],t)}function fn(n,e){let t=new Map;for(let[r,i]of We(n,e)){let o=i[0];o&&t.set(r,o)}return t}function We(n,e){return Wr.get(n,e,()=>{let t=new Map;for(let r of O(n,e)){let i=r.leaf||A(r.symbol);if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push({...r,leaf:i})}for(let r of t.values())r.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return t})}function Oe(n,e){let t=null,r=Number.POSITIVE_INFINITY;for(let i of n){let o=Math.abs(i.startLine-e);(o<r||o===r&&t&&i.startLine<t.startLine)&&(t=i,r=o)}return t}import $e from"path";function mn(n,e){let t=new Map,r=null,i=null,o=()=>(i??=q(n,{extensions:ae}),i),a=()=>(r??=N("typescript.source-file-index",()=>$r(n.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),r),s=c=>ce(c)?P(t,c,()=>{let l=Z($e.resolve(n.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(Z(u.getFilePath()),u)),u)return{project:d,sourceFile:u}}return null}):null;return{sourceFile:c=>s(c)?.sourceFile??null,sourceFileMatch:s,indexedTypeScriptLikeDocuments:o}}function $r(n,e,t){let r=e.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[Z(o.getFilePath()),o]))}));for(let i of t){let o=Z($e.resolve(n,i));for(let a of r){if(a.sourceFiles.has(o))break;let s=a.project.addSourceFileAtPathIfExists(o)??null;if(s){a.sourceFiles.set(Z(s.getFilePath()),s);break}}}return r}function Z(n){return $e.resolve(n)}function qe(n,e){for(let t of n)if(e===t.name||e.startsWith(`${t.name}/`))return t.name;return null}function hn(n){let e=`${n.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as ee,readFileSync as qr}from"fs";import b from"path";var He=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Be(n,e){let r=e?b.dirname(b.join(n,e)):n,i=b.resolve(n);for(;r.startsWith(i);){for(let a of He){let s=b.join(r,a);if(ee(s))return s}let o=b.dirname(r);if(o===r)break;r=o}for(let o of He){let a=b.join(n,o);if(ee(a))return a}return null}function gn(n){let e=n.config.projectRoot,t=new Set(Hr(e,n.config.semantic?.typescript?.tsconfigs)),r=q(n,{includeIgnored:!1,extensions:ae});for(let i of r){let o=Be(e,i);o&&t.add(b.resolve(o))}if(t.size===0){let i=Be(e);i&&t.add(b.resolve(i))}return[...t].filter(i=>!yn(e,i)).sort((i,o)=>i.localeCompare(o))}function Hr(n,e=[]){let t=new Set;for(let r of e){let i=b.isAbsolute(r)?r:b.join(n,r);ee(i)&&t.add(b.resolve(i))}for(let r of Br(n))for(let i of He){let o=b.join(r,i);ee(o)&&t.add(b.resolve(o))}if(t.size===0){let r=Be(n);r&&t.add(b.resolve(r))}return[...t].filter(r=>!yn(n,r)).sort((r,i)=>r.localeCompare(i))}function Br(n){let e=b.join(n,"package.json");if(!ee(e))return[];let t;try{t=JSON.parse(qr(e,"utf8"))}catch{return[]}return(Array.isArray(t.workspaces)?t.workspaces:t.workspaces?.packages??[]).flatMap(i=>yt(n,i))}function yn(n,e){let t=b.relative(n,e).replace(/\\/g,"/");return t.startsWith("..")||t.includes("/node_modules/")||t.startsWith("node_modules/")||t.includes("/dist/")||t.startsWith("dist/")}var Ur=32;function Rn(n,e,t,r={}){return N("typescript.provider.construct",()=>new ze(n,e,t),()=>({tsconfigs:t.length,reusedProjects:r.reusedProjects===!0}))}var ze=class{constructor(e,t,r){this.db=e;this.tsMorph=t;this.projects=r;this.workspacePackages=gt(e.config.projectRoot),this.sourceFiles=mn(e,r)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;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 P(this.importUsageCache,e,()=>{let t=this.sourceFiles.sourceFile(e);if(!t)return[];let r=Jr();return N("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,t,r),()=>({file:e,...r}))})}referencesFor(e){return P(this.referencesCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,t)})}referencesForDefinitions(e,t={}){let r=new Map,i=oe(),o=[];for(let d of e){let p=this.referencesCache.get(d.symbolId);p?r.set(d.symbolId,p):o.push(d)}if(o.length===0)return r;let a=o,s=t.exact?[]:o.filter(d=>!bn(d));if(s.length>=Ur){let d=this.referencesForDefinitionsBySymbolScan(s);for(let p of s){let u=d.get(p.symbolId)??[];this.referencesCache.set(p.symbolId,u),r.set(p.symbolId,u)}if(a=o.filter(p=>bn(p)),a.length===0)return r}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=xn();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),r.set(f.symbolId,h)}catch{u.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:d,definitions:p.length,...In(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),r.set(p.symbolId,u)}}return r}referenceFragmentsForFiles(e){let t=sn(this.db).filter(o=>ce(o.relativePath)),r=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,r);return wt(t,i,r)}referencesForDefinitionsBySymbolScan(e,t){let r=oe(),i=xn(),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=r?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 D=o.get(h.symbolId)??[];D.push(...S),o.set(h.symbolId,D)}r&&(i.packageReferenceCount+=S.length)}r&&(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=r?y.now():0;for(let h of t??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(h))continue;let S=this.sourceFiles.sourceFile(h);S&&(r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(S,h,a,s,u,g,d,p,o,r?i:void 0))}r&&(i.scanMs+=y.now()-f);let m=r?y.now():0;this.addHierarchyMemberReferences(e,o,r?i:void 0),r&&(i.hierarchyMs+=y.now()-m);for(let[h,S]of o){let D=z(S);o.set(h,D),r&&(i.referenceCount+=D.length)}},()=>({definitions:e.length,...In(i)})),o}addReferencesFromSourceFileScan(e,t,r,i,o,a,s,c,l,d){let p=this.compilerCheckerForSourceFile(e),u=e.compilerNode,g=Qr(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 D=P(c,h,()=>this.compilerSymbolKeys(h)),E=null,k=null,L=S&&r.has(S.symbolId)?i.get(S.symbolId):void 0;if(L&&(E=Ue(u,m),!Sn(L,t,E))){let T=u.getLineAndCharacterOfPosition(m.getStart(u));k={file:t,line:T.line,column:T.character};let M=l.get(L.symbolId)??[];M.push(k),l.set(L.symbolId,M),d&&(d.requestedHits+=1)}for(let T of D)for(let M of o.get(T)?.values()??[]){if(E??=Ue(u,m),Sn(M,t,E))continue;if(!k){let I=u.getLineAndCharacterOfPosition(m.getStart(u));k={file:t,line:I.line,column:I.character}}let x=l.get(M.symbolId)??[];x.push(k),l.set(M.symbolId,x),d&&(d.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(m,f)};f(u)}hierarchyTargetsForDefinitions(e){let t=new Map;for(let r of e){let i=this.nodeForDefinition(r),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(r.symbolId,r),t.set(d,p)}}return t}hierarchyMemberSymbols(e,t,r){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(r.name);p&&a(d,p,this.hierarchyAncestorTypesForType(e,d))}}};return a(e.getTypeAtLocation(t),r,this.hierarchyAncestorTypes(e,t)),i}addHierarchyMemberReferences(e,t,r){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),r&&(r.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)}r&&(r.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){r&&(r.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),r&&(r.hierarchyReferences+=1));t.set(a.symbolId,s)}}}hierarchyRootMemberSymbols(e,t,r){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(r.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),r,this.hierarchyAncestorTypes(e,t)),i}compilerSymbolKeys(e){return(e.declarations??[]).map(t=>{let r=t.getSourceFile();return`${r.fileName}\0${t.getStart(r)}\0${e.name}`})}compilerSymbolLocations(e){let t=[];for(let r of e.declarations??[]){let i=r.getSourceFile(),o=J(this.db.config.projectRoot,i.fileName);if(!o)continue;let a=r.name,s=i.getLineAndCharacterOfPosition((a??r).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 r=new Set(this.hierarchyAncestorTypesForType(e,e.getTypeAtLocation(t)));for(let i of t.heritageClauses??[])for(let o of i.types)r.add(e.getTypeAtLocation(o));return[...r]}hierarchyAncestorTypesForType(e,t){let r=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)r.add(e.getTypeAtLocation(a));return[...r]}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,r){r&&(r.symbolLookups+=1);let i=e.getSymbolAtLocation(t);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return r&&(r.aliasResolutions+=1),e.getAliasedSymbol(i)}catch{return i}}}calleesFor(e){return P(this.calleesCache,e.symbolId,()=>P(this.fileCalleesCache,e.relativePath,()=>this.calleeMapForFile(e.relativePath)).get(e.symbolId)??[])}calleesForDefinitions(e){let t=new Map,r=new Map;for(let i of e){let o=r.get(i.relativePath);o?o.push(i):r.set(i.relativePath,[i])}for(let[i,o]of r){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,r){let i=r?y.now():0,o=this.packageImportReferencesForDefinition(e);if(r&&(r.packageRefsMs+=y.now()-i,r.packageReferenceCount+=o.length),!t)return o;let a=r?y.now():0,s=cn(t,e,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=y.now()-a,r.referenceCount+=s.length),s}signatureFor(e){return P(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 r=t.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(a=>{let s=a.getDeclarations()[0],c=s?a.getTypeAtLocation(s).getText(s):a.getValueDeclaration()?.getType().getText()??"unknown";return vn(c)}),o=r.getReturnType().getText(t);return`(${i.join(",")})=>${vn(o)}`})}importUsageForSourceFile(e,t,r){let i=[],o=new Map;for(let a of t.getImportDeclarations()){r.declarations+=1;let s=Fe(this.db,e,a.getModuleSpecifierValue()),c=a.getImportClause()?.isTypeOnly()??!1;for(let l of Je(a)){r.entries+=1;let d=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(d?r.bindingSymbols+=1:r.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||Vr(a))return;r.scannedIdentifiers+=1;let c=a.getSymbol()?.compilerSymbol;if(r.symbolLookups+=1,!!c){for(let l of s)if(l.bindingSymbol===c){l.references.push({location:ye(a,this.db.config.projectRoot),node:a}),r.matchedReferences+=1;break}}}),i.map(a=>a.typeOnlyDeclaration?zr(e,a.sourcePath,a.entry):a.entry.identifier&&!a.bindingSymbol?(r.fallbackEntries+=1,this.valueImportUsageForEntry(e,a.sourcePath,a.entry)):this.valueImportUsageFromLocations(e,a.sourcePath,a.entry,a.references))}valueImportUsageForEntry(e,t,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let a of i)for(let s of ln(a,e,r.identifier,this.db.config.projectRoot))o.push(s);return this.valueImportUsageFromLocations(e,t,r,o)}valueImportUsageFromLocations(e,t,r,i){let o=i.some(c=>!Ae(c.node)),a=i.some(c=>Ae(c.node)),s=r.isTypeOnly;return{importer:e,sourcePath:t,importedName:r.importedName,localName:r.localName,kind:r.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,r=new Set;for(let o of e){let a=this.sourceFiles.sourceFile(o);if(a)for(let s of a.getImportDeclarations()){let c=qe(this.workspacePackages,s.getModuleSpecifierValue());c&&r.add(c)}}if(r.size===0)return t;let i=this.packageExportsForNames(r);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 r of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(e,t,r);for(let[r,i]of e)e.set(r,z(i));return this.packageImportReferenceIndex=e,e}addPackageImportReferencesForDocument(e,t,r){if(this.db.isIgnored(r))return;let i=this.sourceFiles.sourceFileMatch(r);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(e,t,r,o)}addPackageImportReferencesForDeclaration(e,t,r,i){let o=qe(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let a=t.get(o);if(a)for(let s of Je(i)){if(s.kind!=="named"||!s.identifier)continue;let c=a.get(s.importedName);if(!c||c.size===0)continue;let l=dn(s.identifier,r,this.db.config.projectRoot);l.length>0&&ei(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 r of this.workspacePackages){if(!e.has(r.name))continue;let i=new Map;for(let o of hn(r))this.collectPackageExports(r,o,i,new Set);i.size>0&&t.set(r.name,i)}return t}collectPackageExports(e,t,r,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?Fe(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,r,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=r.get(u);f||(f=new Set,r.set(u,f)),f.add(g.symbolId)}}}indexedDefinitionByLeaf(e,t){return P(this.indexedDefinitionLeafCache,e,()=>fn(this.db,e)).get(t)??null}nodeForDefinition(e){return P(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return P(this.fileDefinitionNodeCache,e,()=>{let t=this.sourceFiles.sourceFile(e);return t?pn(this.tsMorph,this.db,t,e):new Map})}referenceDefinitionFromCompilerSymbol(e){return this.definitionFromCompilerSymbol(e,void 0,!0)}definitionFromCompilerSymbol(e,t,r=!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=J(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=r?Ge(this.db,d,p,i)??(g&&g!==i?Ge(this.db,d,p,g):null):un(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 r=oe(),i=0,o=0,a=0,s=0,c=0,l=0,d=0,p=0,u=r?Xr():void 0;return N("typescript.callee-map.file",()=>{let g=r?y.now():0,f=this.sourceFiles.sourceFile(e);if(r&&(c=Math.round(y.now()-g)),!f)return new Map;let m=r?y.now():0,h=O(this.db,e).sort((x,I)=>x.startLine-I.startLine||I.endLine-x.endLine);if(r&&(l=Math.round(y.now()-m)),i=h.length,h.length===0)return new Map;let S=new Map,D=r?y.now():0,E=this.compilerCheckerForSourceFile(f),k=f.compilerNode;r&&(d=Math.round(y.now()-D));let L=new Map,T=x=>{if(this.tsMorph.ts.isCallExpression(x)||this.tsMorph.ts.isNewExpression(x)){r&&(o+=1);let I=this.semanticCalleeForCallNode(E,k,h,x,L,t,u);I&&(r&&(a+=1),Kr(S,I.callerId,I.target))}this.tsMorph.ts.forEachChild(x,T)},M=r?y.now():0;T(k),r&&(p=Math.round(y.now()-M));for(let[x,I]of S)S.set(x,ti(I));return s=S.size,S},()=>({relativePath:e,definitions:i,callNodes:o,resolvedCallees:a,outputRows:s,requestedDefinitions:t?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:p,...u?Zr(u):{}}))}semanticCalleeForCallNode(e,t,r,i,o,a,s){let c=s?y.now():0,l=Yr(r,Ue(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,r){let i=r?y.now():0,o=e.getSymbolAtLocation(t);if(r&&(r.expressionSymbolMs+=y.now()-i),o)return o;r&&(r.typeFallbacks+=1);let a=r?y.now():0,s=e.getTypeAtLocation(t).getSymbol();return r&&(r.typeSymbolMs+=y.now()-a),s}compilerCheckerForSourceFile(e){let t=e.getProject(),r=this.compilerCheckerCache.get(t);return r||(r=t.getTypeChecker().compilerObject,this.compilerCheckerCache.set(t,r)),r}};function Je(n){let e=[],t=n.getDefaultImport();t&&e.push({identifier:t,importedName:"default",localName:t.getText(),kind:"default",isTypeOnly:n.getImportClause()?.isTypeOnly()??!1});let r=n.getNamespaceImport();r&&e.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:n.getImportClause()?.isTypeOnly()??!1});for(let i of n.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()||(n.getImportClause()?.isTypeOnly()??!1)})}return e.length===0&&e.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),e}function zr(n,e,t){return{importer:n,sourcePath:e,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function Jr(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function Vr(n){for(let e=n;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function Kr(n,e,t){let r=n.get(e);r||(r=[],n.set(e,r)),r.push(t)}function Qr(n){let e=new Set;for(let t of n.getImportDeclarations())for(let r of Je(t))r.localName&&e.add(r.localName);return e}function Yr(n,e){let t=null;for(let r of n)e<r.startLine||e>r.endLine||(!t||r.startLine>=t.startLine)&&(t=r);return t}function Ue(n,e){return n.getLineAndCharacterOfPosition(e.getStart(n)).line}function Sn(n,e,t){return e===n.relativePath&&t>=n.startLine&&t<=n.endLine}function bn(n){return n.symbol.includes("#")?_(n.symbol)==="type"&&n.relativePath.endsWith(".d.ts"):!1}function Xr(){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 Zr(n){return{...n,callerLookupMs:Math.round(n.callerLookupMs),expressionSymbolMs:Math.round(n.expressionSymbolMs),typeSymbolMs:Math.round(n.typeSymbolMs),targetLookupMs:Math.round(n.targetLookupMs),declarationsMs:Math.round(n.declarationsMs),declarationLocationMs:Math.round(n.declarationLocationMs),indexedLookupMs:Math.round(n.indexedLookupMs)}}function xn(){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 In(n){return{...n,scanMs:Math.round(n.scanMs),packageRefsMs:Math.round(n.packageRefsMs),semanticRefsMs:Math.round(n.semanticRefsMs),hierarchyMs:Math.round(n.hierarchyMs)}}function ei(n,e,t){for(let r of e){let i=n.get(r)??[];i.push(...t),n.set(r,i)}}function ti(n){let e=new Set,t=[];for(let r of n){let i=`${r.symbol}|${r.file}|${r.line}`;e.has(i)||(e.add(i),t.push(r))}return t}function vn(n){return n.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Se=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??kt,this.discoverTsconfigs=t.discoverTsconfigs??gn,this.createProjects=t.createProjects??Ft,this.createProvider=t.createProvider??((r,i,o)=>Rn(r,i,o,{reusedProjects:!0}))}semanticProvider(){return this.stats.providerRequests+=1,this.provider?(this.stats.sessionsReused+=1,this.provider):this.createSession()}advanceGeneration(e,t){let r=ni(t);return this.provider?.dispose?.(),this.provider=null,this.db=e,this.projects?r.mode==="replace"?(this.projects=null,this.module=null,this.stats.sessionsReplaced+=1,r):(r.mode==="refresh"&&(ri(this.projects,e.config.projectRoot,r),this.stats.sessionsRefreshed+=1),r):r}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=Ee("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=Ee("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 ni(n){let e=new Set;n.projectIdentityChanged&&e.add("project-identity-changed");for(let o of n.uncertainty)e.add(o);for(let o of n.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=Ve(n.changes,"added"),r=Ve(n.changes,"modified"),i=Ve(n.changes,"deleted");return{mode:t.length+r.length+i.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:r,deletedFiles:i,reasons:[]}}function Ve(n,e){return n.filter(t=>t.kind===e).map(t=>t.path).sort()}function ri(n,e,t){for(let r of n){for(let i of t.deletedFiles)r.project.getSourceFile(Mn(e,i))?.forget();for(let i of t.modifiedFiles){let o=r.project.getSourceFile(Mn(e,i));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&r.project.addSourceFilesFromTsConfig(r.tsconfigPath)}}var xe=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 Se(t)),this.generationIdentity=e.generationIdentity??X,this.readSnapshot=e.readSnapshot??ci,this.now=e.now??Date.now}handle(e,t){try{this.syncGeneration(e);let r=this.host.semanticProvider();switch(this.available=r.availability().available,this.requests+=1,this.lastRequestAtMs=this.now(),this.lastError=null,t.kind){case"availability":return r.availability();case"import-usage":return r.importUsage(t.file);case"references":return[...si(r,t.definitions,{exact:t.exact===!0})];case"reference-fragments":if(!r.referenceFragmentsForFiles)throw new Error("TypeScript provider does not support reference fragments.");return[...r.referenceFragmentsForFiles(t.files)];case"callees":return[...ai(r,t.definitions)];case"signature":return r.signatureFor(t.definition);default:return di(t)}}catch(r){throw this.lastError=r instanceof Error?r.message:String(r),r}}status(){let e=this.host?.snapshotStats();return{protocolVersion:Y,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(),r=this.generationIdentity(t.config.dbPath);if(!r||r!==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,li(this.snapshot,i)),this.db=t,o.close()}this.generation=r,this.snapshot=i,this.available=null}};function Ke(n){Dn(n.requestDir,{recursive:!0}),Dn(n.responseDir,{recursive:!0})}function Pn(n,e,t={}){Ke(n);let r=0;for(let i of ii(n.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=be(n.requestDir,i),a=i.slice(0,-5),s=null;try{let c=Jt(Tn(o,"utf8"));if(a=c.id,c.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript semantic request expired before processing.");s=tt(),Te(c.profileEnvironment??{}),t.beforeRequest?.(c.deadlineAtMs);let l=e.handle(c.generation,c.request);j(be(n.responseDir,`${a}.json`),{ok:!0,protocolVersion:Y,id:a,generation:c.generation,response:l})}catch(c){j(be(n.responseDir,`${a}.json`),{ok:!1,protocolVersion:Y,id:a,error:c instanceof Error?c.message:String(c)})}finally{s&&Te(s),t.afterRequest?.(),oi(o,{force:!0}),r+=1}}return r}function si(n,e,t){return n.referencesForDefinitions?.(e,t)??new Map(e.map(r=>[r.symbolId,n.referencesFor(r)]))}function ai(n,e){return n.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,n.calleesFor(t)]))}function ci(n){try{let e=JSON.parse(Tn(be(n,"..","meta.json"),"utf8"));return Et(e.fingerprint)}catch{return null}}function li(n,e){return e?Lt(n,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function di(n){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(n)}`)}import{mkdirSync as Cn,readFileSync as pi,readdirSync as ui,rmSync as fi}from"fs";import{resolve as Ie}from"path";var ve=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=Ie(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??Gt,this.now=e.now??Date.now}handle(e,t){let r=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()-r;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:pe,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 r=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:e.tsconfigPath,projectRoot:e.projectArgument});if(!r.available)throw this.unavailable=!0,new Error(r.reason);return this.active&&(this.sessionsReplaced+=1),this.active={sessionKey:t,projectIdentity:e.projectIdentity,emitter:r.emitter},this.sessionsCreated+=1,this.active}};function Qe(n){Cn(n.requestDir,{recursive:!0}),Cn(n.responseDir,{recursive:!0})}function kn(n,e,t={}){Qe(n);let r=0;for(let i of ui(n.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=Ie(n.requestDir,i),a=i.slice(0,-5);try{let s=$t(pi(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);j(Ie(n.responseDir,`${a}.json`),{ok:!0,protocolVersion:pe,id:a,baseGeneration:s.baseGeneration,response:c})}catch(s){j(Ie(n.responseDir,`${a}.json`),{ok:!1,protocolVersion:pe,id:a,error:s instanceof Error?s.message:String(s)})}finally{t.afterRequest?.(),fi(o,{force:!0}),r+=1}}return r}import{existsSync as Ln,lstatSync as Re,readFileSync as et,readdirSync as Nn,realpathSync as Fn,rmSync as te,statSync as mi}from"fs";import{join as R,resolve as G,sep as wn}from"path";var hi=3600*1e3,gi=2*1024*1024*1024,yi=300*1e3;function Si(n){let e=n.leases.filter(s=>s.managed&&!s.live&&!s.busy),t=bi(n.leases,n.locks),r={};for(let s of n.generations)t.has(s.generationId)||(r[s.generationId]=s.unreferencedAt??n.nowMs);let i=n.generations.filter(s=>!t.has(s.generationId)).sort((s,c)=>r[s.generationId]-r[c.generationId]||s.generationId.localeCompare(c.generationId)),o=new Set;for(let s of i)n.nowMs-r[s.generationId]>=n.policy.generationTtlMs&&o.add(s.generationId);let a=n.generations.filter(s=>!o.has(s.generationId)).reduce((s,c)=>s+c.size,0);for(let s of i){if(a<=n.policy.budgetBytes)break;o.has(s.generationId)||(o.add(s.generationId),a-=s.size)}for(let s of o)delete r[s];return{deleteWorktrees:e,deleteGenerations:n.generations.filter(s=>o.has(s.generationId)),deleteLocks:n.locks.filter(s=>!s.live),deleteTemporaries:n.temporaries.filter(s=>!s.live),protectedGenerationIds:[...t].sort(),unreferencedSince:r}}function bi(n,e){let t=new Set(n.filter(r=>r.managed&&(r.live||r.busy)).flatMap(r=>[r.lease.baseGenerationId,r.lease.activeGenerationId]).filter(r=>r!==void 0));for(let r of e)r.live&&t.add(r.generationId);return t}function jn(n,e,t={}){if(!At())return{kind:"disabled"};let r=nt(n);if(!r)return{kind:"unavailable"};let i=R(Le(),"repositories",r.repositoryId);if(!Ln(i))return{kind:"unavailable"};let o=(t.now??Date.now)(),a=R(i,"gc-state.json"),s=vi(a);if(!t.force&&s&&o-Date.parse(s.lastSweepAt)<yi)return{kind:"throttled",sweptAt:s.lastSweepAt};let c=ot(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=xi(n,i,r.repositoryId,s?.unreferencedSince??{}),d=Si({nowMs:o,...l,policy:{generationTtlMs:t.policy?.generationTtlMs??hi,budgetBytes:t.policy?.budgetBytes??gi}}),p=0,u=0;for(let m of d.deleteWorktrees){if(!An(m.lease))continue;let h=st(R(m.lease.localCacheDir,"cache-lifecycle.lock"));if(h)try{if(Xe(m.lease,!0))continue;try{Mt({projectRoot:m.lease.projectRoot,cacheDir:m.lease.localCacheDir,cliVersion:e})}catch{continue}if(Xe(m.lease,!0))continue;te(m.lease.localCacheDir,{recursive:!0,force:!0}),te(m.leasePath,{force:!0}),u+=1}finally{h.release()}}for(let m of d.deleteLocks)te(m.path,{force:!0});for(let m of d.deleteTemporaries)te(m.path,{recursive:!0,force:!0});for(let m of d.deleteGenerations)te(m.path,{recursive:!0,force:!0}),p+=m.size;ct(R(i,"evidence.db"));let g={kind:"swept",sweptAt:new Date(o).toISOString(),deletedWorktrees:u,deletedGenerations:d.deleteGenerations.length,deletedBytes:p,protectedGenerations:d.protectedGenerationIds.length},f={version:1,lastSweepAt:g.sweptAt,unreferencedSince:d.unreferencedSince,lastResult:g};return j(a,f,{spacing:2,trailingNewline:!0}),g}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function xi(n,e,t,r){let i=new Set(rt(n).map(l=>G(l.path))),o=[];for(let l of Ye(R(e,"worktrees"))){if(!l.endsWith(".json"))continue;let d=R(e,"worktrees",l),p=Ii(d);if(!p)continue;let u=G(p.projectRoot);o.push({leasePath:d,lease:p,managed:p.repositoryId===t&&An(p),live:i.has(u)||Ln(u),busy:Xe(p)})}let a=[];for(let l of Ye(R(e,"locks"))){let d=/^([a-f0-9]{64})\.lock$/.exec(l);if(!d)continue;let p=R(e,"locks",l),u=Ze(p),g=u!==void 0&&V(u),f=d[1];a.push({generationId:f,path:p,live:g})}let s=[],c=[];for(let l of Ye(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:En(g),live:Number.isSafeInteger(f)&&V(f)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let p=R(e,"generations",l),u;try{u=Re(p)}catch{continue}!u.isDirectory()||u.isSymbolicLink()||s.push({generationId:l,path:p,size:En(p),...r[l]===void 0?{}:{unreferencedAt:r[l]}})}return{leases:o,generations:s,locks:a,temporaries:c}}function An(n){if(n.ownershipChecksum!==Ot(n)||G(n.localCacheDir)!==G(jt(n.projectRoot)))return!1;let e=G(Le()),t=G(R(e,"projects")),r=G(n.localCacheDir);if(!r.startsWith(`${t}${wn}`))return!1;try{let i=Re(e),o=Re(t),a=Re(r);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink())return!1;let s=Fn(t);return Fn(r).startsWith(`${s}${wn}`)}catch{return!1}}function Xe(n,e=!1){for(let r of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=Ze(R(n.localCacheDir,r));if(i!==void 0&&V(i))return!0}let t=Ze(se(n.localCacheDir).lockPath);return t!==void 0&&V(t)}function Ii(n){try{let e=JSON.parse(et(n,"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 Ze(n){try{let e=JSON.parse(et(n,"utf8"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function vi(n){try{let e=JSON.parse(et(n,"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 Ye(n){try{return Nn(n)}catch{return[]}}function En(n){let e=0,t=[n];for(;t.length>0;){let r=t.pop();for(let i of Nn(r,{withFileTypes:!0})){let o=R(r,i.name);i.isDirectory()?t.push(o):i.isFile()&&(e+=mi(o).size)}}return e}var Di=1e3,Ti=250,Pi=10;function Ci(n){return n==="fresh"?null:{kind:"watch-startup",detail:`index ${n} when watch service started`}}async function ki(n,e,t={}){let r=Rt(n,e),i=r.projectRoot,o=H(i);o.watch={...o.watch,...t};let a=de(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=se(s.cacheDir),l=Pt(c.lockPath,i);if(!l.acquired)return;let d=Date.now(),p=d,u={state:"idle"},g,f,m,h=!1,S=!1,D=0,E=0,k=0,L=0,T,M,x=zt(s.cacheDir),I=Wt(s.cacheDir);Ke(x),Qe(I);let Me=new xe({openDb:()=>Yt(i)}),De=new ve({projectRoot:i,currentGeneration:()=>qt(s.dbPath)}),w=(v=!1)=>{if(!S)return;let $=Date.now();!v&&$-E<Di||(E=$,Dt(c.statePath,{version:1,protocolVersion:vt,pid:C.pid,projectRoot:i,...r.worktreeId?{worktreeId:r.worktreeId}:{},cliVersion:e,startedAt:new Date(d).toISOString(),heartbeatAt:new Date($).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:{...Me.status(),...T===void 0?{}:{busyUntil:new Date(T).toISOString()}},typescriptIndex:{...De.status(),...M===void 0?{}:{busyUntil:new Date(M).toISOString()}}}))},W=()=>{p=Date.now()},ne=new ue({projectRoot:i,config:{...o,watch:a},languages:o.languages,onStatus(v){u=v,v.state!=="idle"&&(g=void 0),v.state!=="idle"&&W(),w(!0)},onReindexComplete(){W();let v=je(i,o,s);f=v.lastRefresh,g=v.state==="fresh"?X(s.dbPath)??void 0:void 0,m=void 0,w(!0)},onError(v){W(),g=void 0,m={at:new Date().toISOString(),message:v.message},w(!0)}}),re=()=>{h=!0};C.once("SIGINT",re),C.once("SIGTERM",re);try{ne.start();let v=je(i,o,s);f=v.lastRefresh,g=v.state==="fresh"?X(s.dbPath)??void 0:void 0;let $=Ci(v.state);for($&&ne.requestRefresh($,{immediate:!0}),W(),S=!0,w(!0);!h;){let On=kn(I,De,{beforeRequest(F){M=F+5e3,w(!0)},afterRequest(){M=void 0,w(!0)}}),Gn=Pn(x,Me,{beforeRequest(F){T=F+5e3,w(!0)},afterRequest(){T=void 0,w(!0)}}),ie=Date.now();if(ie-L>=6e4&&(L=ie,jn(i,e)),ie-k>=Ti){k=ie;let F=Tt(c.activityPath);F&&F.atMs>p&&(p=F.atMs),F?.refreshRequestedAtMs!==void 0&&F.refreshRequestedAtMs>D&&(D=F.refreshRequestedAtMs,W(),ne.requestRefresh({kind:"watch-demand",detail:F.refreshDetail??"stale index observed by a command"},{immediate:!0}))}if((Gn>0||On>0)&&(W(),w(!0)),w(),Ct({watcher:u,lastActivityAtMs:p,nowMs:Date.now(),idleTimeoutMs:a.idleTimeoutMs}))break;await Fi(Pi)}}finally{C.off("SIGINT",re),C.off("SIGTERM",re),Me.closeTypeScriptService(),De.close(),ne.stop(),_n(c.statePath,{force:!0}),_n(c.activityPath,{force:!0}),l.release()}}function Fi(n){return new Promise(e=>setTimeout(e,n))}var wi=C.argv[1]?Mi(Ri(C.argv[1])).href:null;if(wi===import.meta.url){let n=C.argv[2],e=C.argv[3],t=Ei(C.argv[4]);if(!n||!e)console.error("watch-service: expected <project-root> <cli-version>"),C.exitCode=1;else try{await ki(n,e,t)}catch(r){console.error(`watch-service: ${r instanceof Error?r.message:String(r)}`),C.exitCode=1}}function Ei(n){if(!n)return{};try{let e=JSON.parse(n);return e&&typeof e=="object"?e:{}}catch{return{}}}export{ki as runWatchServiceServer,Ci as startupRefreshTrigger};
|
|
40
|
+
ORDER BY start_line, end_line`,e)}function On(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:ir(r.symbol),isTypeLike:O(r.symbol)==="type",kind:r.kind??null,documentation:r.documentation??null,enclosingSymbol:r.enclosing_symbol??null}}function lr(r,e={}){return Wn(r,e.scope)}function Wn(r,e){return U(r,{scope:e,includeIgnored:!1}).flatMap(t=>W(r,t)).filter(t=>!r.isIgnored(t.relativePath))}function $n(r,e,t){let n=ye(r).forFile(e,{text:!0}).text,i=Pt(r,e);return i?Vn(t,i,n):n?Gn(t,n):t}function Gn(r,e){let t=e.split(/\r?\n/),n=qn(r,t),i=Un(r,n),o=Hn(i,t);return Bn(r,o)}function qn(r,e){let t=r.some(i=>be(i.symbol))?Zn(e):null,n=new Map;for(let i of r)n.set(i.symbolId,Xn(e,t,i));return n}function Un(r,e){return r.filter(t=>be(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 Hn(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:ei(e,i.definition,i.startLine,a)})}return t}function Bn(r,e){return r.map(t=>{let n=e.get(t.symbolId);return n?{...t,startLine:n.startLine,endLine:n.endLine}:t})}function Vn(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(!Qn(i)||!i.leaf)return ar(i,t);let o=n.get(i.leaf);if(!o||o.length===0)return ar(i,t);let a=t?Kn(i,o,t):null;if(a)return{...i,startLine:a.startLine,endLine:a.endLine};let s=o[0],c=Math.abs(s.startLine-i.startLine);for(let l=1;l<o.length;l+=1){let d=o[l],p=Math.abs(d.startLine-i.startLine);p<c&&(s=d,c=p)}return{...i,startLine:s.startLine,endLine:s.endLine}})}function Kn(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=Yn(i,a.startLine);if(s&&o.test(s))return a}return null}function zn(r){return r.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function Yn(r,e){for(let t=e;t>=0;t-=1){let n=r[t]?.trim()??"";if(n){if(/^impl\b/.test(n))return Jn(r,t,e);if(/^(?:struct|enum|trait|mod)\b/.test(n))return null}}return null}function Jn(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 Qn(r){return be(r.symbol)?!0:O(r.symbol)==="term"&&K(r.symbol)===null}function ar(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 Xn(r,e,t){if(!be(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 Zn(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 ei(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=ti(r[l]??"");for(let p of d)p==="{"?(a+=1,c=!0):p==="}"?a=Math.max(0,a-1):p==="("?s+=1:p===")"&&(s=Math.max(0,s-1));if(c&&a===0||!c&&s===0&&l>=o)return l}return o}function ti(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 be(r){return r.includes("().")}function k(r,e,t){if(r.has(e))return r.get(e);let n=t();return r.set(e,n),n}import dr from"path";function ri(r,e){return r.getReferences().map(t=>{let n=t.getNode();return ve(n,e)})}function ni(r){let e=r;return typeof e.findReferences=="function"?e.findReferences():[]}function pr(r,e,t,n){let i=[];for(let o of ni(r))for(let a of ri(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 ur(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:ve(s,n),node:s}))}return i}function ve(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 fr(r,e,t){let n=r.getSourceFile(),i=Ue(n,r),o=r.getText(),a=new RegExp(`\\b${Q(o)}\\b`,"g"),s=n.getFullText().split(`
|
|
41
|
+
`),c=[];for(let l=0;l<s.length;l++){if(l===i)continue;let d=s[l]??"";a.lastIndex=0;let p;for(;(p=a.exec(d))!==null;)c.push({file:e,line:l,column:p.index})}return z(c.filter(l=>Y(t,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};
|
|
42
43
|
//# sourceMappingURL=watch-server.js.map
|
package/docs/AI_FAILURE_MODES.md
CHANGED
|
@@ -301,6 +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 requireAcyclic are configured and a baseline exists. |
|
|
304
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. |
|
|
305
306
|
| `unused-params` | Fresh trailing parameters or options that no changed body uses. | Default diff gate. |
|
|
306
307
|
| `new-dead` | Changed production symbols with zero indexed consumers. | Default diff gate. |
|
|
@@ -64,7 +64,7 @@ This syntax summary is generated from the CLI command descriptors. Keep workflow
|
|
|
64
64
|
| `recent-duplicates` | Directional duplicate candidates: recent code that re-implements established callable, React, or Vue code | `--window <n>`<br>`--min-similarity <n>`<br>`-n, --limit <n>`<br>`-s, --scope <path>`<br>`--full`<br>`--json` |
|
|
65
65
|
| `doc-drift [doc]` | Stale-doc candidates: code the doc references or co-changed with kept changing after the doc stopped | `-n, --limit <n>`<br>`--min-coupling <n>`<br>`--full`<br>`--json` |
|
|
66
66
|
| `unused-params` | Speculative-generality candidates: trailing parameters no body ever uses (TS/JS) | `-s, --scope <path>`<br>`-n, --limit <n>`<br>`--full`<br>`--json` |
|
|
67
|
-
| `drift [module]` | Detect
|
|
67
|
+
| `drift [module]` | Detect drift candidates: unused imports and declared architecture violations; pass --architecture for boundary context | `--min-deviation <n>`<br>`--patterns`<br>`--architecture`<br>`-n, --limit <n>`<br>`--full`<br>`--json` |
|
|
68
68
|
| `wrapper-candidates` | Find heuristic wrapper candidates only called by one consumer (high false-positive rate on codebases with intentional layering/ambient types — treat as exploration, not findings) | `-s, --scope <path>`<br>`--max-loc <n>`<br>`-n, --limit <n>`<br>`--full`<br>`--json` |
|
|
69
69
|
| `passthrough-candidates` | Find heuristic passthrough candidates that forward to one callee | `-s, --scope <path>`<br>`--max-loc <n>`<br>`-n, --limit <n>`<br>`--full`<br>`--json` |
|
|
70
70
|
| `stale-abstractions` | Find heuristic stale abstraction candidates with 0-1 consumers (high false-positive rate on codebases with intentional layering/ambient types — treat as exploration, not findings) | `-s, --scope <path>`<br>`--min-loc <n>`<br>`-n, --limit <n>`<br>`--include-low-confidence`<br>`--full`<br>`--json` |
|
|
@@ -88,6 +88,7 @@ This syntax summary is generated from the CLI command descriptors. Keep workflow
|
|
|
88
88
|
| `fan-out [file]` | How many external symbols a file uses (or top fan-out across codebase) | `-n, --limit <n>`<br>`-s, --scope <path>`<br>`--full`<br>`--json` |
|
|
89
89
|
| `coupling [file1] [file2]` | Coupling between two files, or top coupled pairs in codebase | `-n, --limit <n>`<br>`-s, --scope <path>`<br>`--full`<br>`--json` |
|
|
90
90
|
| `cycles` | Detect circular dependency chains between files | `-s, --scope <path>`<br>`--max-depth <n>`<br>`--json` |
|
|
91
|
+
| `architecture` | Evaluate project-owned architectural boundaries and dependency rules | `-s, --scope <path>`<br>`--json` |
|
|
91
92
|
| `bottlenecks` | Find coupling hubs: high fan-in AND high fan-out | `-n, --limit <n>`<br>`-s, --scope <path>`<br>`--min-fan-in <n>`<br>`--min-fan-out <n>`<br>`--full`<br>`--json` |
|
|
92
93
|
| `deep-chains` | Find the longest condensed dependency-component chains | `-n, --limit <n>`<br>`-s, --scope <path>`<br>`--min-depth <n>`<br>`--full`<br>`--json` |
|
|
93
94
|
| `call-graph <symbol>` | Show incoming callers and outgoing callees for a symbol | `--full`<br>`--json` |
|
|
@@ -99,7 +100,7 @@ This syntax summary is generated from the CLI command descriptors. Keep workflow
|
|
|
99
100
|
| `affected <symbol>` | Transitive closure of symbols that could break if this symbol changes | `--max-depth <n>`<br>`-s, --scope <path>`<br>`--json` |
|
|
100
101
|
| `change-surface <file>` | Pre-change briefing: exports, consumers, and blast-radius risk | `--full`<br>`--json` |
|
|
101
102
|
| `co-change [file]` | Files that change together in git history without a dependency edge — hidden coupling candidates | `--min-together <n>`<br>`-n, --limit <n>`<br>`--all`<br>`--full`<br>`--json` |
|
|
102
|
-
| `diff-gate` | Gate the current diff:
|
|
103
|
+
| `diff-gate` | Gate the current diff: architecture regressions plus echo, migration, coordination, doc-drift, unused-param, and new-dead candidates; exit 1 on blocking findings | `--base <ref>`<br>`--min-together <n>`<br>`--max-echo-checks <n>`<br>`--max-helpers <n>`<br>`--baseline`<br>`--full`<br>`--skip <check>`<br>`--hook`<br>`--json` |
|
|
103
104
|
| `incomplete-migration` | Partially-completed extraction candidates: new helpers in the diff wired into some sites while similar un-migrated sites remain | `--base <ref>`<br>`--min-containment <n>`<br>`--max-helpers <n>`<br>`-n, --limit <n>`<br>`--full`<br>`--json` |
|
|
104
105
|
| `diff-impact` | Compute changed symbols and downstream consumers from current git diff | `--base <ref>`<br>`--json` |
|
|
105
106
|
|