scip-query 0.19.4 → 0.19.6
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 +75 -1
- package/README.md +242 -49
- package/dist/augment-vue-worker.js +1 -1
- package/dist/{chunk-2YU7I3QO.js → chunk-24QNP7MN.js} +2 -2
- package/dist/{chunk-CNKAGUPL.js → chunk-26X7KCJR.js} +2 -2
- package/dist/{chunk-GPBBJ5Y4.js → chunk-273W2U4Y.js} +3 -3
- package/dist/{chunk-7GXM52MI.js → chunk-2CVXCGL4.js} +2 -2
- package/dist/{chunk-ABMYA4TN.js → chunk-2EZSOTSY.js} +2 -2
- package/dist/{chunk-HKEHS2AS.js → chunk-2GSQR6YA.js} +2 -2
- package/dist/{chunk-FECYOO5O.js → chunk-2OXVAGGT.js} +2 -2
- package/dist/chunk-2ZOCHAL2.js +8 -0
- package/dist/{chunk-QGXBRIM5.js → chunk-336DC5NJ.js} +2 -2
- package/dist/chunk-35SQLYCQ.js +2 -0
- package/dist/{chunk-VXQNNXJE.js → chunk-3OIKRYU5.js} +2 -2
- package/dist/{chunk-52ZYCAEO.js → chunk-47X75ZKH.js} +2 -2
- package/dist/{chunk-NPKYOIFM.js → chunk-4CGVLUDP.js} +2 -2
- package/dist/chunk-4RI4BJGT.js +8 -0
- package/dist/{chunk-P2PC2WGR.js → chunk-52HQTTPB.js} +2 -2
- package/dist/{chunk-YNRNA5LK.js → chunk-5OC3HWP5.js} +2 -2
- package/dist/{chunk-STOL2BTL.js → chunk-6XFC7PQ5.js} +2 -2
- package/dist/{chunk-J77UIT3I.js → chunk-6XHTISLI.js} +2 -2
- package/dist/chunk-6YTSKJJ3.js +2 -0
- package/dist/{chunk-BTEE5NZQ.js → chunk-7E3TH5ZN.js} +2 -2
- package/dist/{chunk-X6D5IC6I.js → chunk-7LABSJSR.js} +2 -2
- package/dist/chunk-7Q6VYYCH.js +2 -0
- package/dist/{chunk-FWUUZTIO.js → chunk-A43URCQ3.js} +2 -2
- package/dist/chunk-A63U2W3P.js +3 -0
- package/dist/{chunk-3MJ5YA4Y.js → chunk-ADFSIJP2.js} +2 -2
- package/dist/chunk-AOLE4DYM.js +6 -0
- package/dist/chunk-APMMR5Y2.js +2 -0
- package/dist/chunk-B5MHCHP3.js +107 -0
- package/dist/{chunk-4RSI5EMG.js → chunk-CSTYYXKC.js} +2 -2
- package/dist/{chunk-25LPM4DG.js → chunk-CYJM7CYF.js} +2 -2
- package/dist/{chunk-S44IULR6.js → chunk-DD5BOU5I.js} +2 -2
- package/dist/{chunk-YGAGTIDK.js → chunk-DGMCFMPG.js} +7 -7
- package/dist/{chunk-UOAV44HR.js → chunk-E2ZXPB7J.js} +2 -2
- package/dist/{chunk-IZKFSVBV.js → chunk-EVOC5I5I.js} +2 -2
- package/dist/{chunk-XTX6QHOF.js → chunk-F42A3AKG.js} +2 -2
- package/dist/{chunk-Q4IIEGXJ.js → chunk-FHCTEANE.js} +2 -2
- package/dist/{chunk-3SVWW4PN.js → chunk-FKGN4A4E.js} +2 -2
- package/dist/{chunk-IG7N5ZIK.js → chunk-FQTPPXNA.js} +2 -2
- package/dist/{chunk-F6O7AAC3.js → chunk-G4UQL4CP.js} +2 -2
- package/dist/chunk-GA64UPMI.js +6 -0
- package/dist/{chunk-ZXJYMGD3.js → chunk-GK3GRUJX.js} +2 -2
- package/dist/chunk-HEBAY673.js +2 -0
- package/dist/chunk-HELS7KFF.js +2 -0
- package/dist/{chunk-B5NLK2B3.js → chunk-IPDCSB6N.js} +2 -2
- package/dist/{chunk-M7MTH5NR.js → chunk-IYAOX36F.js} +2 -2
- package/dist/{chunk-YVVCVR2L.js → chunk-J7VT2CRB.js} +2 -2
- package/dist/{chunk-4333ETTV.js → chunk-JELJLXEE.js} +2 -2
- package/dist/{chunk-LBMJEAEW.js → chunk-JERWGHQT.js} +2 -2
- package/dist/chunk-JJJCO4QC.js +945 -0
- package/dist/{chunk-6E7UTQY7.js → chunk-JZNLMHWY.js} +2 -2
- package/dist/{chunk-R4FQGQ4X.js → chunk-K42M2KWT.js} +2 -2
- package/dist/{chunk-H7UKLTWJ.js → chunk-KLVJABXA.js} +2 -2
- package/dist/chunk-KP4KBDVF.js +3 -0
- package/dist/{chunk-RV2FQIX3.js → chunk-LMFVTUW2.js} +2 -2
- package/dist/chunk-LRTP3DKL.js +3 -0
- package/dist/{chunk-U6WNH5GC.js → chunk-MGBJHRFB.js} +2 -2
- package/dist/{chunk-QDV6RDCP.js → chunk-MLGTCX56.js} +2 -2
- package/dist/{chunk-54HA4ZXH.js → chunk-N3SE646F.js} +2 -2
- package/dist/{chunk-KP6XRY5Z.js → chunk-NBRUH7OE.js} +2 -2
- package/dist/{chunk-M7AIS73L.js → chunk-NN4ZIRPK.js} +2 -2
- package/dist/{chunk-I5RJM53C.js → chunk-NQLSSVOB.js} +2 -2
- package/dist/{chunk-4SALD7RU.js → chunk-OBKDTVZ3.js} +2 -2
- package/dist/{chunk-GBQ5NYPR.js → chunk-OHWZKLVA.js} +6 -6
- package/dist/{chunk-6NSFJYRC.js → chunk-OP3MTFJR.js} +2 -2
- package/dist/{chunk-EOOJGLDU.js → chunk-OQ2A4G2G.js} +2 -2
- package/dist/{chunk-DLWR3NUU.js → chunk-P6HBYNBE.js} +2 -2
- package/dist/{chunk-QVWS2VWZ.js → chunk-PC44K7RF.js} +2 -2
- package/dist/{chunk-A2EZV2UM.js → chunk-QBYYWGAT.js} +2 -2
- package/dist/{chunk-QRGV2F7L.js → chunk-QHKUY4FW.js} +2 -2
- package/dist/chunk-QHRL4LKM.js +2 -0
- package/dist/{chunk-I5AWSI2G.js → chunk-QQWOFXNW.js} +2 -2
- package/dist/{chunk-WQTAC523.js → chunk-RBFFD4V2.js} +2 -2
- package/dist/{chunk-SOAT6NLA.js → chunk-RJHCPSZ7.js} +2 -2
- package/dist/{chunk-VGRICIQI.js → chunk-RWRLUZ6U.js} +2 -2
- package/dist/{chunk-4T3LTWUS.js → chunk-S2GP3CU3.js} +2 -2
- package/dist/{chunk-HEXVUYFQ.js → chunk-SHKZ7OVJ.js} +2 -2
- package/dist/{chunk-NSS46APD.js → chunk-TFUU5MQQ.js} +2 -2
- package/dist/{chunk-IUFDSKGG.js → chunk-TYQ76QHQ.js} +2 -2
- package/dist/{chunk-NRCXJDHL.js → chunk-U5CNPPTZ.js} +2 -2
- package/dist/{chunk-MITTUCEH.js → chunk-UQK5CRUK.js} +2 -2
- package/dist/{chunk-XLTP42QA.js → chunk-UUJBLG6J.js} +2 -2
- package/dist/chunk-UXP636P5.js +144 -0
- package/dist/{chunk-64RFXJT5.js → chunk-VEVBIAOJ.js} +6 -6
- package/dist/chunk-VKRQDBW5.js +9 -0
- package/dist/{chunk-C7NIYIQ4.js → chunk-VOQFGC2W.js} +4 -4
- package/dist/{chunk-DZ74OMG6.js → chunk-VP542C25.js} +2 -2
- package/dist/{chunk-Q3AFUTGB.js → chunk-WMXRRBII.js} +2 -2
- package/dist/{chunk-ZGZUZ7XE.js → chunk-WXAAURU7.js} +2 -2
- package/dist/chunk-X3NLZHPA.js +20 -0
- package/dist/{chunk-WER3B7MI.js → chunk-XF3KLXN3.js} +2 -2
- package/dist/{chunk-NH5ALKPW.js → chunk-XVJ3V7LM.js} +2 -2
- package/dist/{chunk-4XTA5OMB.js → chunk-YGQN3XGZ.js} +2 -2
- package/dist/{chunk-CFMXJPHH.js → chunk-YHXBD52M.js} +2 -2
- package/dist/{chunk-7B3UPBVA.js → chunk-YLVE3SXZ.js} +2 -2
- package/dist/{chunk-YIJ7ZAA4.js → chunk-YTUD45PU.js} +2 -2
- package/dist/{chunk-VTKGCT3V.js → chunk-YWB2EBNB.js} +2 -2
- package/dist/{chunk-UKZBVX4U.js → chunk-Z2LHPIOM.js} +2 -2
- package/dist/chunk-Z5QQPJ3U.js +30 -0
- package/dist/{chunk-NZL2DBT7.js → chunk-ZLJLE6LK.js} +2 -2
- package/dist/{chunk-XYADIZHU.js → chunk-ZTTISZ7J.js} +2 -2
- package/dist/cli.js +3 -3
- package/dist/command-descriptors-SJDZ7QGR.js +617 -0
- package/dist/{config-types-D20KuvvZ.d.ts → config-types-BWQ5xPGI.d.ts} +4 -0
- package/dist/{db-G_II8yXU.d.ts → db-B0r1o7Vt.d.ts} +18 -1
- package/dist/direct-navigation-HTKOZEOM.js +3 -0
- package/dist/{health-oblXYgkF.d.ts → health-CFnlCiTz.d.ts} +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/postinstall.js +1 -1
- package/dist/queries/affected.d.ts +2 -2
- package/dist/queries/affected.js +1 -1
- package/dist/queries/architecture.d.ts +2 -2
- package/dist/queries/architecture.js +1 -1
- package/dist/queries/bottlenecks.d.ts +2 -2
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.d.ts +2 -2
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +2 -2
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +2 -2
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.d.ts +2 -2
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.d.ts +2 -2
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +2 -2
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +2 -2
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +2 -2
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.d.ts +2 -2
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +2 -2
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +2 -2
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +2 -2
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.d.ts +2 -2
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.d.ts +3 -3
- 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 +30 -2
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.d.ts +2 -2
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +2 -2
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +2 -2
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.d.ts +2 -2
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/extract-candidates.d.ts +2 -2
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +2 -2
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +2 -2
- package/dist/queries/health.d.ts +3 -3
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +2 -2
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +2 -2
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +2 -2
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +2 -2
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +17 -3
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.d.ts +2 -2
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.d.ts +2 -2
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.d.ts +2 -2
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.d.ts +2 -2
- package/dist/queries/methods.js +1 -1
- package/dist/queries/not-implemented.d.ts +3 -3
- 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/stats.js +1 -1
- 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 +3 -3
- 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 +23 -24
- package/dist/reindex.d.ts +10 -4
- package/dist/reindex.js +33 -38
- package/dist/runtime.d.ts +167 -11
- package/dist/runtime.js +3 -2
- package/dist/rust-semantic-session-server.js +1 -1
- package/dist/rust-semantic-session-worker.js +1 -1
- package/dist/rust-semantic-worker.js +1 -1
- package/dist/{scip-cli-kRpaexVJ.d.ts → scip-cli-DCvnlZCu.d.ts} +5 -1
- package/dist/watch-server.js +5 -5
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/AI_FAILURE_MODES.md +18 -18
- package/docs/API_EVOLUTION.md +71 -0
- package/docs/CLI_JSON_OUTPUT.md +83 -0
- package/docs/COMMAND_REFERENCE.md +10 -8
- package/docs/COMMITTED_RECORD_COMPATIBILITY.md +117 -0
- package/docs/CONFIGURATION_WRITE_SAFETY.md +130 -0
- package/docs/DETECTOR_GUIDE.md +47 -47
- package/docs/DURABILITY.md +103 -0
- package/docs/INDEX_GENERATIONS.md +121 -0
- package/docs/LOCK_PROTOCOL.md +133 -0
- package/docs/MAILBOX_LIFECYCLE.md +197 -0
- package/docs/REINDEX_METADATA_COMPATIBILITY.md +84 -0
- package/docs/RUST_DURABLE_SESSION_PROTOCOL.md +126 -0
- package/docs/TELEMETRY_RETENTION.md +72 -0
- package/docs/TIME_SEMANTICS.md +77 -0
- package/docs/WATCH_REFRESH_REQUESTS.md +110 -0
- package/docs/WINDOWS_SIDECAR_RELEASE.md +298 -0
- package/docs/analyzer-validation-ledger.md +24 -23
- package/docs/schemas/cli-json-envelope.schema.json +53 -0
- package/docs/schemas/npm-release-state.schema.json +146 -0
- package/docs/schemas/outcome-event-record.schema.json +39 -0
- package/docs/schemas/project-config.schema.json +247 -0
- package/docs/schemas/suppression-record.schema.json +31 -0
- package/docs/schemas/windows-sidecar-provenance.schema.json +137 -0
- package/package.json +15 -5
- package/scripts/build-scip-windows.mjs +180 -61
- package/scripts/scip-windows-provenance.mjs +364 -0
- package/scripts/verify-scip-windows.mjs +29 -0
- package/skills/_shared/SKILL.md +91 -242
- package/skills/_shared/agents/openai.yaml +1 -1
- package/skills/_shared/references/agent-contract-catalog.md +105 -0
- package/skills/_shared/references/command-catalog.md +118 -0
- package/skills/_shared/references/detector-precision-and-diffgate.md +59 -0
- package/skills/_shared/references/evidence-and-dead-code.md +25 -0
- package/skills/scip-audit/SKILL.md +76 -0
- package/skills/scip-audit/agents/openai.yaml +4 -0
- package/skills/scip-audit/references/claims.md +98 -0
- package/skills/scip-audit/references/cleanup.md +101 -0
- package/skills/scip-audit/references/directory.md +222 -0
- package/skills/scip-audit/references/frontend.md +130 -0
- package/skills/scip-audit/references/integrity.md +154 -0
- package/skills/scip-audit/references/maintainability.md +162 -0
- package/skills/scip-audit/references/twin-drift.md +104 -0
- package/skills/scip-diagnose/SKILL.md +52 -0
- package/skills/scip-diagnose/agents/openai.yaml +4 -0
- package/skills/scip-diagnose/references/debug.md +117 -0
- package/skills/{scip-probe-reachability/SKILL.md → scip-diagnose/references/probe-reachability.md} +12 -27
- package/skills/scip-diagnose/references/root-cause.md +145 -0
- package/skills/scip-diagnose/references/triage.md +119 -0
- package/skills/scip-explore/SKILL.md +53 -84
- package/skills/scip-explore/agents/openai.yaml +2 -2
- package/skills/scip-explore/references/diagrams.md +40 -0
- package/skills/scip-explore/references/language-playbook.md +49 -0
- package/skills/scip-improve/SKILL.md +56 -0
- package/skills/scip-improve/agents/openai.yaml +4 -0
- package/skills/scip-improve/references/cleanup-batches.md +53 -0
- package/skills/scip-improve/references/directory-moves.md +53 -0
- package/skills/scip-improve/references/doc-reconcile.md +30 -0
- package/skills/scip-improve/references/frontend-extraction.md +39 -0
- package/skills/scip-improve/references/maintainability-mechanism.md +43 -0
- package/skills/scip-improve/references/twin-drift.md +35 -0
- package/skills/scip-plan/SKILL.md +68 -0
- package/skills/scip-plan/agents/openai.yaml +4 -0
- package/skills/scip-plan/references/api-impact.md +19 -0
- package/skills/scip-plan/references/conductor.md +41 -0
- package/skills/scip-plan/references/high-assurance.md +43 -0
- package/skills/scip-plan/references/hyper-optimization.md +50 -0
- package/skills/scip-plan/references/tla-model.md +88 -0
- package/skills/scip-query/SKILL.md +52 -97
- package/skills/scip-query/agents/openai.yaml +2 -2
- package/skills/scip-setup/SKILL.md +65 -176
- package/skills/scip-setup/agents/openai.yaml +3 -3
- package/skills/scip-setup/references/bootstrap-workflow.md +120 -0
- package/skills/scip-setup/references/language-verification.md +61 -0
- package/skills/scip-setup/references/lifecycle-commands.md +119 -0
- package/skills/scip-setup/references/per-repo-triage.md +24 -0
- package/skills/scip-verify/SKILL.md +123 -70
- package/skills/scip-verify/agents/openai.yaml +2 -2
- package/skills/scip-verify/references/calibrate-detectors.md +170 -0
- package/dist/chunk-2CTX5CMX.js +0 -4
- package/dist/chunk-2Y373BDD.js +0 -2
- package/dist/chunk-C2QSK7E7.js +0 -2
- package/dist/chunk-D4U5Q3FT.js +0 -7
- package/dist/chunk-K2ERX4UT.js +0 -3
- package/dist/chunk-KHE7J5ZN.js +0 -3
- package/dist/chunk-L7SPDE73.js +0 -84
- package/dist/chunk-LHMNRHGV.js +0 -3
- package/dist/chunk-LM72NQ7T.js +0 -3
- package/dist/chunk-MSWVMDAH.js +0 -122
- package/dist/chunk-NH7WNNQC.js +0 -20
- package/dist/chunk-OMPZHGHO.js +0 -2
- package/dist/chunk-SVLTAG5O.js +0 -927
- package/dist/chunk-U7DSEKOM.js +0 -30
- package/dist/chunk-V27BEQJN.js +0 -7
- package/dist/chunk-VMNZB6WI.js +0 -4
- package/dist/chunk-XBN5VO53.js +0 -2
- package/dist/chunk-ZAIILQNP.js +0 -5
- package/dist/command-descriptors-MFU4BCJ7.js +0 -612
- package/dist/direct-navigation-MRMQFIRB.js +0 -3
- package/skills/scip-api-impact/SKILL.md +0 -139
- package/skills/scip-api-impact/agents/openai.yaml +0 -4
- package/skills/scip-calibrate/SKILL.md +0 -131
- package/skills/scip-calibrate/agents/openai.yaml +0 -4
- package/skills/scip-claim-audit/SKILL.md +0 -106
- package/skills/scip-claim-audit/agents/openai.yaml +0 -4
- package/skills/scip-cleanup-audit/SKILL.md +0 -126
- package/skills/scip-cleanup-audit/agents/openai.yaml +0 -4
- package/skills/scip-cleanup-improve/SKILL.md +0 -84
- package/skills/scip-cleanup-improve/agents/openai.yaml +0 -4
- package/skills/scip-concrete-plan/SKILL.md +0 -262
- package/skills/scip-concrete-plan/agents/openai.yaml +0 -4
- package/skills/scip-conductor/SKILL.md +0 -133
- package/skills/scip-conductor/agents/openai.yaml +0 -4
- package/skills/scip-debug/SKILL.md +0 -130
- package/skills/scip-debug/agents/openai.yaml +0 -4
- package/skills/scip-diagram/SKILL.md +0 -110
- package/skills/scip-diagram/agents/openai.yaml +0 -4
- package/skills/scip-directory-architecture/SKILL.md +0 -254
- package/skills/scip-directory-architecture/agents/openai.yaml +0 -4
- package/skills/scip-doc-reconcile/SKILL.md +0 -89
- package/skills/scip-doc-reconcile/agents/openai.yaml +0 -4
- package/skills/scip-hyper-optimization/SKILL.md +0 -156
- package/skills/scip-hyper-optimization/agents/openai.yaml +0 -4
- package/skills/scip-integrity-audit/SKILL.md +0 -152
- package/skills/scip-integrity-audit/agents/openai.yaml +0 -4
- package/skills/scip-language-playbook/SKILL.md +0 -106
- package/skills/scip-language-playbook/agents/openai.yaml +0 -4
- package/skills/scip-maintainability/SKILL.md +0 -158
- package/skills/scip-maintainability/agents/openai.yaml +0 -4
- package/skills/scip-probe-reachability/agents/openai.yaml +0 -4
- package/skills/scip-react-maintainability/SKILL.md +0 -101
- package/skills/scip-react-maintainability/agents/openai.yaml +0 -4
- package/skills/scip-root-cause/SKILL.md +0 -150
- package/skills/scip-root-cause/agents/openai.yaml +0 -4
- package/skills/scip-tla-model-system/SKILL.md +0 -148
- package/skills/scip-tla-model-system/agents/openai.yaml +0 -4
- package/skills/scip-triage-issue/SKILL.md +0 -126
- package/skills/scip-triage-issue/agents/openai.yaml +0 -4
- package/skills/scip-twin-drift/SKILL.md +0 -107
- package/skills/scip-twin-drift/agents/openai.yaml +0 -4
- package/skills/scip-vue-maintainability/SKILL.md +0 -107
- package/skills/scip-vue-maintainability/agents/openai.yaml +0 -4
package/dist/watch-server.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import{A as At,Aa as me,B as Lt,C as Nt,D as jt,E as le,F as de,G as _t,I as Ot,J as _e,K as Wt,L as $t,P as Oe,S as Gt,T as pe,U as We,V as qt,W as Ut,X as H,a as gt,b as yt,c as St,d as Ee,e as bt,f as Fe,g as vt,ga as Ht,h as xt,i as Rt,ja as $e,k as Ae,l as Le,m as Ct,n as Mt,p as wt,pa as Bt,r as kt,ra as Vt,s as Pt,sa as fe,t as Ne,ta as Kt,u as je,ua as zt,v as Tt,va as Yt,w as Dt,wa as Ge,x as Et,y as Q,ya as B,z as Ft,za as Jt}from"./chunk-MSWVMDAH.js";import{b as ft,c as mt,f as It,h as J,l as U,m as ue}from"./chunk-C7NIYIQ4.js";import{a as j,b as F}from"./chunk-KHE7J5ZN.js";import{a as ce,c as ht,d as De,e as N}from"./chunk-HGFDYOVB.js";import k from"process";import{rmSync as Zr}from"fs";import{resolve as ao}from"path";import{pathToFileURL as co}from"url";import{readFileSync as rn,writeFileSync as bo,existsSync as nn}from"fs";import{isAbsolute as xo,join as on,relative as Io,resolve as Ro}from"path";var qe=".scipquery.json",sn=250,an=0,cn=10*6e4,ln={enabled:!1,debounceMs:sn,cooldownMs:an,gitPollMs:2e3,idleTimeoutMs:cn,autoRefresh:!0,ignore:[]},dn=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"];var Co=new Set(dn);function V(r){let e=on(r,qe);if(!nn(e))return{};try{let t=rn(e,"utf-8");return JSON.parse(t)}catch(t){let n=t instanceof Error?t.message:String(t);throw t instanceof SyntaxError?new Error(`invalid ${qe} at ${e}: ${n}`,{cause:t}):new Error(`unable to read ${qe} at ${e}: ${n}`,{cause:t})}}function he(r){return{...ln,...r.watch}}import{existsSync as Qt,readFileSync as un}from"fs";function Ue(r,e,t){let n=new Date().toISOString();if(!Qt(t.dbPath))return{state:"missing",checkedAt:n,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Qt(t.metaPath))return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=JSON.parse(un(t.metaPath,"utf-8")),o=e.languages??$t(r),a=pn(r,o,e),s=Array.isArray(i.indexedLanguages)?[...i.indexedLanguages].sort():[],c=(i.version===2||i.version===3)&&i.status==="complete"&&JSON.stringify(i.fingerprint)===JSON.stringify(a)&&JSON.stringify(s)===JSON.stringify(a.languages),l=Ht(t.dbPath,t.metaPath),d=l.state==="invalid"||l.state==="drifted",u=c&&!d;return{state:u?"fresh":"stale",checkedAt:n,metaPath:t.metaPath,updatedAt:i.updatedAt,lastRefresh:i.lastRefresh,reason:d?`SQLite generation requires repair: ${l.reason}`:c?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:u?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function pn(r,e,t){return It(r,e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{fork as fn}from"child_process";import{statSync as mn}from"fs";import{isAbsolute as hn,join as gn,relative as yn}from"path";import{watch as Sn}from"chokidar";import bn from"ignore";var ge=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onRefreshSuppressed;onError;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=he(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onRefreshSuppressed=e.onRefreshSuppressed??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.gitignoreFilter=ue(e.projectRoot),this.extraIgnore=bn(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){this.stopped=!1,this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(e){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}}stop(){this.stopped=!0;for(let e of this.fsWatchers)e.close();this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer(),this.setStatus({state:"idle"})}requestRefresh(e,t={}){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=Xt(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}startSourceWatcher(e=!1){let t=Sn(this.projectRoot,{ignoreInitial:!0,ignored:(n,i)=>this.isIgnoredWatchPath(n,i?.isDirectory()??!1),usePolling:e,...e?{interval:500,binaryInterval:1e3}:{}});t.on("all",(n,i)=>{this.stopped||this.handleFileChange(i)}),t.on("error",n=>this.handleSourceWatcherError(t,n,e)),this.fsWatchers.push(t)}handleSourceWatcherError(e,t,n){if(n||this.sourcePollingFallbackStarted||!vn(t)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(i=>i!==e),e.close();try{this.startSourceWatcher(!0)}catch(i){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(i)}`))}}isIgnoredWatchPath(e,t){let n=this.relativeWatchPath(e);if(!n)return!1;let i=t?`${n}/`:n;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(e){let t=this.relativeWatchPath(e);!t||t===".."||t.startsWith("../")||t===".git"||t.startsWith(".git/")||this.gitignoreFilter.isIgnored(t)||this.extraIgnore.ignores(t)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||t.endsWith(Oe)||t.endsWith(`${Oe}.previous`)||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=hn(e)?e:gn(this.projectRoot,e);return yn(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=Xt(this.pendingTrigger,e),this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let t=Date.now()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=Date.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let i=this.watchConfig.cooldownMs-e;this.dirty=!0;let o=Date.now()+i;this.setStatus({state:"cooldown",until:o,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},i);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let n=Date.now();this.setStatus({state:"indexing",startedAt:n}),this.runReindex(t).then(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now();let o=!1;try{o=this.onReindexComplete(i)===!0}catch(a){this.onError(a instanceof Error?a:new Error(String(a)))}if(this.dirty&&!this.stopped){if(o){let s=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(s),this.setStatus({state:"idle"});return}let a=Date.now()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(i=>{this.reindexInFlight=!1,this.lastReindexEnd=Date.now(),this.onError(i instanceof Error?i:new Error(String(i))),this.setStatus({state:"idle"})})}runReindex(e){return new Promise((t,n)=>{let i=Date.now(),o=V(this.projectRoot),a=Object.keys(o).length>0?o:this.config,s=H(this.projectRoot,a),c=a.indexer?.typescript,l=a.indexer?.clojure,d=fn(new URL("./reindex-worker.js",import.meta.url).pathname,[],{detached:!0,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:this.projectRoot,SCIP_REINDEX_OUTPUT_SCIP:s.indexPath,SCIP_REINDEX_OUTPUT_DB:s.dbPath,SCIP_REINDEX_LANGUAGES:(a.languages??this.languages)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(a.indexerConcurrency??this.indexerConcurrency??""),SCIP_REINDEX_PNPM_WORKSPACES:c?.pnpmWorkspaces??this.pnpmWorkspaces?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:c?.projectMode??this.typescriptProjectMode,projects:c?.projects??this.typescriptProjects??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:l?.configPath??this.clojureConfigPath??"",SCIP_REINDEX_TRIGGER_KIND:e.kind,SCIP_REINDEX_TRIGGER_DETAIL:e.detail??""},stdio:"pipe"});d.on("exit",u=>{u===0?t(Date.now()-i):n(new Error(`Reindex worker exited with code ${u}`))}),d.on("error",n)})}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,t=this.readGitState();if(!e||!t||this.stopped){this.lastGitState=t;return}this.lastGitState=t;let n=e.head!==t.head,i=e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize;n&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):n?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:t.indexPath??"index changed"})}readGitState(){let e=Ee(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=bt(this.projectRoot,e),n={head:Ee(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=mn(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}clearGitPollTimer(){this.gitPollTimer&&(clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function Xt(r,e){return r?r.kind===e.kind?r.detail===e.detail?r:{kind:r.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${r.kind}, ${e.kind}`}:e}function vn(r){return r instanceof Error&&"code"in r&&r.code==="EMFILE"||String(r).includes("EMFILE: too many open files")}import{existsSync as ir,statSync as kn}from"fs";import{join as Pn}from"path";import{createHash as xn}from"crypto";import{readFileSync as In}from"fs";import{dirname as Rn,join as ye}from"path";var X=2,Cn="typescript-semantic";function er(r){let e=ye(r,Cn);return{rootDir:e,requestDir:ye(e,"requests"),responseDir:ye(e,"responses")}}function Z(r){try{let e=JSON.parse(In(ye(Rn(r),"meta.json"),"utf8"));return e.version!==2&&e.version!==3||typeof e.status!="string"||typeof e.updatedAt!="string"||e.fingerprint===void 0?null:xn("sha256").update(JSON.stringify({version:e.version,status:e.status,updatedAt:e.updatedAt,fingerprint:e.fingerprint,indexedLanguages:e.indexedLanguages})).digest("hex")}catch{return null}}function tr(r){let e=JSON.parse(r);if(e.protocolVersion!==X||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||e.profileEnvironment!==void 0&&!Mn(e.profileEnvironment)||!e.request||!wn(e.request))throw new Error("TypeScript semantic service received an invalid mailbox request.");return e}function Mn(r){return!!r&&typeof r=="object"&&!Array.isArray(r)&&Object.values(r).every(e=>typeof e=="string"||e===null)}function wn(r){if(!r||typeof r!="object"||!("kind"in r))return!1;let e=r;switch(e.kind){case"availability":return!0;case"import-usage":return typeof e.file=="string";case"reference-fragments":return Tt(e.files)!==null;case"references":return Zt(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return Zt(e.definitions);case"signature":return rr(e.definition);default:return!1}}function Zt(r){return Array.isArray(r)&&r.every(rr)}function rr(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.symbolId=="number"&&typeof e.documentId=="number"&&typeof e.symbol=="string"&&typeof e.relativePath=="string"&&typeof e.leaf=="string"&&typeof e.startLine=="number"&&typeof e.endLine=="number"}function Tn(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var nr;function Dn(r=Tn(),e=void 0){if(e===void 0&&nr?.projectRoot===r)return nr;let t=V(r),n=H(r,t),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:r,config:t,paths:n,dbPath:i,dbPathSource:"env",gitContext:e};if(ir(n.dbPath))return{projectRoot:r,config:t,paths:n,dbPath:n.dbPath,dbPathSource:"configured",gitContext:e};let o=Pn(r,"index.db");return{projectRoot:r,config:t,paths:n,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:En(o,n.dbPath),gitContext:e}}function or(r,e={}){let{config:t,paths:n,dbPath:i,dbPathSource:o,rootFallbackWarning:a,gitContext:s}=Dn(r);if(!ir(i))throw new Error("No index.db found. Run: scip-query reindex");e.warnOnRootFallback&&o==="root-fallback"&&a&&console.error(a);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:r,sharedEvidenceDbPath:$e(r,t,s),entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality,architecture:t.architecture,coverageContracts:t.coverageContracts,docs:t.docs},l=ue(r);return new Rt(c,l)}function En(r,e){let t="unknown time";try{t=kn(r).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${r}, modified ${t}) because the configured index was not found at ${e}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}import{mkdirSync as Fr,readFileSync as Ar,readdirSync as Di,rmSync as Ei}from"fs";import{resolve as Re}from"path";import{resolve as Er}from"path";import{performance as y}from"perf_hooks";function Se(r){return{forFile(e,t){return sr(r,e,t)},forFiles(e,t){let n=new Map;for(let i of e)n.set(i,sr(r,i,t));return n}}}function sr(r,e,t){let n={file:e},i=t.facts||t.identifiers;if(t.text&&(n.text=Dt(r,e)),t.lines&&(n.lines=Et(r,e)),t.ast&&(n.ast=Ft(r,e)),t.imports&&(n.imports=jt(r,e)),t.reexports&&(n.reexports=Nt(r,e)),i){let o=At(r,e),a=o.facts;t.facts&&(n.facts=a),o.unavailable&&(n.sourceFactsUnavailable=o.unavailable),t.identifiers&&a&&(n.identifiers=a.fileIdentifiers,n.identifierLineMap=a.identifierLineMap)}return n}var Fn={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function be(r){if(r.startsWith("local "))return{kind:"local",id:r.slice(6),raw:r};let e=r.split(" ");if(e.length<4)return{scheme:e[0]??"",manager:e[1]??"",packageName:e[2]??"",version:"",descriptors:[],raw:r};let t=e[0],n=e[1],i=r.slice(t.length+1+n.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let a,s=i.indexOf(" ");s===-1?(a=i,i=""):(a=i.slice(0,s),i=i.slice(s+1));let c=An(i);return{scheme:t,manager:n,packageName:o,version:a,descriptors:c,raw:r}}function K(r){let e=be(r);if("kind"in e)return null;for(let t=e.descriptors.length-2;t>=0;t--){let n=e.descriptors[t];if(n?.suffix==="type")return n.name}return null}function An(r){let e=[],t=0;for(;t<r.length;){if(r[t]==="["){let o=r.indexOf("]",t+1);if(o===-1){e.push({name:r.slice(t+1),suffix:"type-param"});break}e.push({name:r.slice(t+1,o),suffix:"type-param"}),t=o+1;continue}if(r[t]==="("&&(e.length===0||t===0||ar(r[t-1]))){let o=r.indexOf(")",t+1);if(o!==-1&&r[o+1]!=="."){e.push({name:r.slice(t+1,o),suffix:"parameter"}),t=o+1;continue}}let n;if(r[t]==="`"){let o=r.indexOf("`",t+1);if(o===-1){n=r.slice(t+1),e.push({name:n,suffix:"term"});break}n=r.slice(t+1,o),t=o+1}else{let o=t;for(;t<r.length&&!ar(r[t]);)t++;n=r.slice(o,t)}if(t>=r.length){n&&e.push({name:n,suffix:"term"});break}let i=r[t];if(i==="("){let o=r.indexOf(")",t+1);o!==-1&&r[o+1]==="."?(e.push({name:n,suffix:"method"}),t=o+2):o!==-1?(e.push({name:n,suffix:"method"}),t=o+1):(e.push({name:n,suffix:"term"}),t++)}else{let o=Fn[i];o&&e.push({name:n,suffix:o}),t+=1}}return e}function ar(r){return r==="/"||r==="#"||r==="."||r==="("||r==="["||r===":"||r==="!"}function _(r){let e=be(r);if("kind"in e&&e.kind==="local")return e.id;let t=e;return t.descriptors.length===0?"":t.descriptors[t.descriptors.length-1].name}function O(r){let e=be(r);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function cr(r){let e=O(r);return e==="method"?!0:e!=="term"?!1:r.endsWith("().")?!0:r.startsWith("rust-analyzer ")&&r.includes("#")?!1:r.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(r):!0}function Ln(r,e={}){if(K(r.symbol)!==null)return e.includeClassMemberFallbacks===!0;let i=(r.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function lr(r,e,t={}){let n=new Map;for(let o of e)r.length>0&&!Ln(o,{includeClassMemberFallbacks:t.includeClassMemberFallbacks})||n.set(o.id,o);for(let o of r)n.set(o.id,o);let i=[...n.values()];return t.sort?i.sort((o,a)=>o.start_line-a.start_line||o.end_line-a.end_line||o.symbol.localeCompare(a.symbol)):i}var Nn=J("file-definitions",{clearGroups:["definition-catalog"]}),Rs=J("file-function-like-definitions",{clearGroups:["definition-catalog"]});function W(r,e,t={}){return t.includeClassMemberFallbacks?dr(r,e,void 0,{includeClassMemberFallbacks:!0}):Nn.get(r,e,()=>{let n=jn(r,e);if(n)return n;let i=dr(r,e),o=Le(r),a=Se(r).forFile(e,{text:!0}).text;return o&&a&&pr.write(r,e,Ae(r,e,a),{projectFingerprint:o,definitions:i.map(s=>({...s}))}),i})}var pr=Mt({kind:"file-definitions",invalidation:wt("file-definitions"),serialize:_n,deserialize:On});function jn(r,e){let t=Le(r);if(!t)return null;let n=Se(r).forFile(e,{text:!0}).text;if(!n)return null;let i=pr.read(r,e,Ae(r,e,n));return i?Wn(i,t,e):null}function _n(r){return JSON.stringify(r)}function On(r){try{let e=JSON.parse(r);return!je(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function Wn(r,e,t){if(r.projectFingerprint!==e)return null;let n=[];for(let i of r.definitions){let o=$n(i,t);if(!o)return null;n.push(o)}return n}function $n(r,e){return!je(r)||typeof r.symbolId!="number"||typeof r.symbol!="string"||typeof r.documentId!="number"||typeof r.startLine!="number"||typeof r.startChar!="number"&&r.startChar!==void 0||typeof r.endLine!="number"||typeof r.endChar!="number"&&r.endChar!==void 0||r.relativePath!==e||typeof r.leaf!="string"||typeof r.parentTypeName!="string"&&r.parentTypeName!==null||typeof r.isFunctionLike!="boolean"||typeof r.isTypeLike!="boolean"||typeof r.kind!="number"&&r.kind!==null||typeof r.documentation!="string"&&r.documentation!==null||typeof r.enclosingSymbol!="string"&&r.enclosingSymbol!==null?null:{symbolId:r.symbolId,symbol:r.symbol,documentId:r.documentId,startLine:r.startLine,startChar:r.startChar,endLine:r.endLine,endChar:r.endChar,relativePath:r.relativePath,leaf:r.leaf,parentTypeName:r.parentTypeName,isFunctionLike:r.isFunctionLike,isTypeLike:r.isTypeLike,kind:r.kind,documentation:r.documentation,enclosingSymbol:r.enclosingSymbol}}function dr(r,e,t,n={}){let i=lr(Gn(r,e),qn(r,e),{sort:!0,includeClassMemberFallbacks:n.includeClassMemberFallbacks}).map(Un);return t&&(i=i.filter(t)),Bn(r,e,i)}function Gn(r,e){return r.all(`SELECT
|
|
1
|
+
import{$ as Pe,A as ft,Aa as Or,B as vr,Ba as Ae,C as xr,Ca as $r,D as Ir,Da as Gr,E as ce,Ea as Br,F as Rr,Fa as bt,G as Cr,Ga as J,H as wr,Ha as Hr,I as Pr,Ia as Ne,J as Mr,K as Re,Ka as Ur,L as Ce,La as Vr,M as Tr,O as kr,P as mt,Q as Er,T as Dr,X as Fr,_ as Ar,a as er,aa as ht,ba as Nr,c as ve,ca as _r,da as z,f as ir,g as or,h as sr,i as ot,j as ar,k as st,l as dr,m as ur,n as fr,o as mr,pa as Lr,q as dt,r as ut,s as hr,sa as gt,t as gr,v as yr,x as Sr,y as br,ya as jr,z as pt}from"./chunk-UXP636P5.js";import{b as Jt,c as Xt,g as pr,i as ae,m as Y,n as we}from"./chunk-VOQFGC2W.js";import{A as Ee,B as De,C as Fe,a as Qt,b as se,c as Zt,g as rr,h as nr,i as D,j as F,k as at,l as cr,m as ct,n as lr,o as K,p as lt,q as Ie,s as yt,t as Wr,u as Me,v as St,w as qr,y as Te,z as ke}from"./chunk-VKRQDBW5.js";import{a as xe,c as tr,d as it,e as O}from"./chunk-HGFDYOVB.js";import{a as T}from"./chunk-APMMR5Y2.js";import P from"process";import{rmSync as Si}from"fs";import{resolve as zs}from"path";import{pathToFileURL as Js}from"url";import{existsSync as Ii,readFileSync as Ri}from"fs";import{isAbsolute as da,join as Ci,relative as ua,resolve as pa}from"path";var W=1,X=2,xi="./node_modules/scip-query/docs/schemas/project-config.schema.json";function Kr(r){let e=r;if(typeof r=="string")try{e=JSON.parse(r)}catch(s){return{kind:"malformed",reason:`invalid JSON: ${s instanceof Error?s.message:String(s)}`}}if(!Qt(e))return{kind:"malformed",reason:"project config must be a JSON object"};let t=e.schemaVersion;if(t!==void 0&&!Number.isInteger(t))return{kind:"malformed",reason:"schemaVersion must be an integer"};let n=t===void 0?W:t;if(n!==W&&n!==X)return{kind:"unsupported",schemaVersion:n,direction:n<W?"older":"future"};let i=e.$schema;if(i!==void 0&&(typeof i!="string"||i.trim()===""))return{kind:"malformed",reason:"$schema must be a non-empty string when present"};let o=Yr(e),a=n!==X||typeof e.$schema!="string";return n===W?{kind:"legacy",sourceVersion:W,config:o,needsMigration:a}:{kind:"supported",sourceVersion:X,config:o,needsMigration:a}}function Yr(r){let e=r,{$schema:t,schemaVersion:n,...i}=e;return{$schema:typeof t=="string"&&t.trim()!==""?t:xi,schemaVersion:X,...i}}var _e=".scipquery.json",wi=250,Pi=0,Mi=10*6e4,Ti={enabled:!1,debounceMs:wi,cooldownMs:Pi,gitPollMs:2e3,idleTimeoutMs:Mi,autoRefresh:!0,ignore:[]};var ha=new Set(er);function Q(r){let e=Ci(r,_e);if(!Ii(e))return{};let t;try{t=Ri(e,"utf-8")}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`unable to read ${_e} at ${e}: ${i}`,{cause:n})}return ki(Kr(t),e,"read").config}function Le(r){return{...Ti,...r.watch}}function ki(r,e,t){if(r.kind==="legacy"||r.kind==="supported")return r;if(r.kind==="malformed"){let i=t==="read"?`invalid ${_e} at ${e}: ${r.reason}`:`Cannot update ${e}: the latest project config is ${r.reason}.`;throw new Error(`${i} The file was left untouched.`)}let n=t==="read"?`invalid ${_e} at ${e}`:`Cannot update ${e}: the latest project config is invalid`;throw new Error(`${n} (unsupported ${r.direction} schemaVersion ${r.schemaVersion}; this scip-query reads legacy v${W} and current v${X}). Upgrade scip-query before retrying; the file was left untouched.`)}import{existsSync as zr,readFileSync as Ei}from"fs";function vt(r,e,t){let n=new Date().toISOString();if(!zr(t.dbPath))return{state:"missing",checkedAt:n,metaPath:t.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!zr(t.metaPath))return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=ve(Ei(t.metaPath,"utf-8"));if(i.kind==="unsupported")return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Reindex metadata version ${i.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(i.kind==="malformed")return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Could not decode reindex metadata: ${i.reason}`,remedy:"Run: scip-query reindex"};let o=i.metadata,a=e.languages??Dr(r),s=Di(r,a,e),c=[...o.indexedLanguages??[]].sort(),l=i.capabilities.publishableGeneration&&JSON.stringify(o.fingerprint)===JSON.stringify(s)&&JSON.stringify(c)===JSON.stringify(s.languages),d=Lr(t.dbPath,t.metaPath),u=d.state==="invalid"||d.state==="drifted",p=l&&!u;return{state:p?"fresh":"stale",checkedAt:n,metaPath:t.metaPath,updatedAt:o.updatedAt,lastRefresh:o.lastRefresh,reason:u?`SQLite generation requires repair: ${d.reason}`:l?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:p?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:n,metaPath:t.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function Di(r,e,t){return pr(r,e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{statSync as Fi}from"fs";import{basename as Ai,isAbsolute as Ni,join as _i,relative as Li}from"path";import{watch as ji}from"chokidar";import Oi from"ignore";var je=class{projectRoot;config;watchConfig;languages;pnpmWorkspaces;typescriptProjectMode;typescriptProjects;clojureConfigPath;indexerConcurrency;onStatus;onReindexComplete;onReindexError;onRefreshSuppressed;onError;reindexRunner;subscriptionFactory;clock;activeOperation=null;stopPromise=null;stopInProgress=!1;status={state:"idle"};debounceTimer=null;cooldownTimer=null;dirty=!1;changedFiles=0;pendingTrigger=null;reindexInFlight=!1;lastReindexEnd=0;fsWatchers=[];sourcePollingFallbackStarted=!1;gitPollTimer=null;lastGitState=null;gitignoreFilter;extraIgnore;stopped=!1;constructor(e){this.projectRoot=e.projectRoot,this.config=e.config,this.watchConfig=Le(e.config),this.languages=e.languages,this.pnpmWorkspaces=e.config.indexer?.typescript?.pnpmWorkspaces??!1,this.typescriptProjectMode=e.config.indexer?.typescript?.projectMode,this.typescriptProjects=e.config.indexer?.typescript?.projects,this.clojureConfigPath=e.config.indexer?.clojure?.configPath,this.indexerConcurrency=e.config.indexerConcurrency,this.onStatus=e.onStatus??(()=>{}),this.onReindexComplete=e.onReindexComplete??(()=>{}),this.onReindexError=e.onReindexError??(()=>{}),this.onRefreshSuppressed=e.onRefreshSuppressed??(()=>{}),this.onError=e.onError??(t=>console.error(t.message)),this.clock=e.clock??qi,this.reindexRunner=e.reindexRunner??Vi(),this.subscriptionFactory=e.subscriptionFactory??$i,this.gitignoreFilter=we(e.projectRoot),this.extraIgnore=Oi(),this.watchConfig.ignore.length>0&&this.extraIgnore.add(this.watchConfig.ignore)}start(){if(this.stopInProgress)throw new Error("Cannot restart a watcher while its previous ownership is still draining.");this.stopped=!1,this.stopPromise=null,this.sourcePollingFallbackStarted=!1,this.setStatus({state:"idle"}),this.startGitStatePolling();try{this.startSourceWatcher()}catch(e){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(e)}`))}}stop(){if(this.stopPromise)return this.stopPromise;this.stopped=!0,this.stopInProgress=!0;let e=this.fsWatchers;this.fsWatchers=[],this.clearDebounceTimer(),this.clearCooldownTimer(),this.clearGitPollTimer();let t=this.activeOperation;return t&&this.setStatus({state:"draining",startedAt:this.wallNow(),reason:"waiting for the active reindex worker to exit"}),this.stopPromise=this.finishStop(e,t).finally(()=>{this.stopInProgress=!1}),this.stopPromise}requestRefresh(e,t={}){if(!this.stopped){if(!t.immediate||this.reindexInFlight||this.status.state==="cooldown"){this.scheduleReindex(e);return}this.pendingTrigger=Xr(this.pendingTrigger,e),this.changedFiles+=1,this.clearDebounceTimer(),this.triggerReindex()}}startSourceWatcher(e=!1){let t=this.subscriptionFactory(this.projectRoot,{ignoreInitial:!0,ignored:(n,i)=>this.isIgnoredWatchPath(n,i?.isDirectory()??!1),usePolling:e,...e?{interval:500,binaryInterval:1e3}:{}});t.on("all",(n,i)=>{this.stopped||this.handleFileChange(i)}),t.on("error",n=>this.handleSourceWatcherError(t,n,e)),this.fsWatchers.push(t)}handleSourceWatcherError(e,t,n){if(n||this.sourcePollingFallbackStarted||!Ki(t)||this.stopped){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(t)}`));return}this.sourcePollingFallbackStarted=!0,this.fsWatchers=this.fsWatchers.filter(i=>i!==e),e.close();try{this.startSourceWatcher(!0)}catch(i){this.onError(new Error(`Failed to watch ${this.projectRoot}: ${String(i)}`))}}isIgnoredWatchPath(e,t){let n=this.relativeWatchPath(e);if(!n)return!1;let i=t?`${n}/`:n;return i===".git/"||i.startsWith(".git/")?!0:this.gitignoreFilter.isIgnored(i)||this.extraIgnore.ignores(i)}handleFileChange(e){let t=this.relativeWatchPath(e);!t||t===".."||t.startsWith("../")||t===".git"||t.startsWith(".git/")||this.gitignoreFilter.isIgnored(t)||this.extraIgnore.ignores(t)||t.endsWith("index.db")||t.endsWith("index.scip")||t.endsWith("index.db.tmp")||Ai(t).startsWith(Fr)||this.scheduleReindex({kind:"watch-source",detail:t})}relativeWatchPath(e){let t=Ni(e)?e:_i(this.projectRoot,e);return Li(this.projectRoot,t).replaceAll("\\","/")}scheduleReindex(e){if(this.pendingTrigger=Xr(this.pendingTrigger,e),this.changedFiles++,this.reindexInFlight){this.dirty=!0,this.setStatus({state:"indexing",startedAt:this.status.startedAt});return}if(this.status.state==="cooldown"){this.dirty=!0,this.setStatus({state:"cooldown",until:this.status.until,dirty:!0});return}this.clearDebounceTimer();let t=this.wallNow()+this.watchConfig.debounceMs;this.setStatus({state:"waiting",changedFiles:this.changedFiles,reindexAt:t}),this.debounceTimer=this.clock.setTimeout(()=>{this.debounceTimer=null,this.triggerReindex()},this.watchConfig.debounceMs)}triggerReindex(){if(this.reindexInFlight||this.stopped)return;let e=this.clock.now()-this.lastReindexEnd;if(this.lastReindexEnd>0&&e<this.watchConfig.cooldownMs){let o=this.watchConfig.cooldownMs-e;this.dirty=!0;let a=this.wallNow()+o;this.setStatus({state:"cooldown",until:a,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped&&(this.dirty=!1,this.triggerReindex())},o);return}this.reindexInFlight=!0,this.dirty=!1,this.changedFiles=0;let t=this.pendingTrigger??{kind:"watch-source"};this.pendingTrigger=null;let n=this.wallNow();this.setStatus({state:"indexing",startedAt:n});let i=this.reindexRunner.start(this.reindexRequest(t));this.activeOperation=i,i.completion.then(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let a=!1;try{a=this.onReindexComplete(o,t)===!0}catch(s){this.onError(s instanceof Error?s:new Error(String(s)))}if(this.dirty&&!this.stopped){if(a){let c=this.pendingTrigger??{kind:"unknown"};this.dirty=!1,this.changedFiles=0,this.pendingTrigger=null,this.onRefreshSuppressed(c),this.setStatus({state:"idle"});return}let s=this.wallNow()+this.watchConfig.cooldownMs;this.setStatus({state:"cooldown",until:s,dirty:!0}),this.cooldownTimer=this.clock.setTimeout(()=>{this.cooldownTimer=null,this.dirty&&!this.stopped?(this.dirty=!1,this.triggerReindex()):this.setStatus({state:"idle"})},this.watchConfig.cooldownMs)}else this.setStatus({state:"idle"})}).catch(o=>{if(this.reindexInFlight=!1,this.lastReindexEnd=this.clock.now(),this.stopped)return;let a=o instanceof Error?o:new Error(String(o));this.onReindexError(a,t),this.onError(a),this.setStatus({state:"idle"})}).finally(()=>{this.activeOperation===i&&(this.activeOperation=null)})}async finishStop(e,t){let n=[],i=t?t.cancel():null,o=await Promise.allSettled(e.map(a=>Promise.resolve().then(()=>a.close())));for(let a of o)a.status==="rejected"&&n.push(`watch subscription close failed: ${String(a.reason)}`);if(i)try{let a=await i;a.state==="degraded"&&n.push(a.reason)}catch(a){n.push(`reindex cancellation failed: ${a instanceof Error?a.message:String(a)}`)}return n.length>0?(this.setStatus({state:"draining",startedAt:this.wallNow(),reason:n.join("; ")}),{state:"degraded",reasons:n}):(this.setStatus({state:"idle"}),{state:"stopped"})}wallNow(){return this.clock.wallNow?.()??this.clock.now()}reindexRequest(e){return{projectRoot:this.projectRoot,config:this.config,languages:this.languages,pnpmWorkspaces:this.pnpmWorkspaces,typescriptProjectMode:this.typescriptProjectMode,typescriptProjects:this.typescriptProjects,clojureConfigPath:this.clojureConfigPath,indexerConcurrency:this.indexerConcurrency,trigger:e}}setStatus(e){this.status=e,this.onStatus(e)}clearDebounceTimer(){this.debounceTimer&&(this.clock.clearTimeout(this.debounceTimer),this.debounceTimer=null)}clearCooldownTimer(){this.cooldownTimer&&(this.clock.clearTimeout(this.cooldownTimer),this.cooldownTimer=null)}startGitStatePolling(){this.lastGitState=this.readGitState(),this.lastGitState&&(this.gitPollTimer=this.clock.setInterval(()=>this.pollGitState(),this.watchConfig.gitPollMs),this.gitPollTimer.unref?.())}pollGitState(){let e=this.lastGitState,t=this.readGitState();if(!e||!t||this.stopped){this.lastGitState=t;return}this.lastGitState=t;let n=e.head!==t.head,i=e.indexPath!==t.indexPath||e.indexMtimeMs!==t.indexMtimeMs||e.indexSize!==t.indexSize;n&&i?this.scheduleReindex({kind:"watch-git-state",detail:"HEAD and index changed"}):n?this.scheduleReindex({kind:"watch-git-head",detail:"HEAD changed"}):i&&this.scheduleReindex({kind:"watch-git-index",detail:t.indexPath??"index changed"})}readGitState(){let e=ot(this.projectRoot,["rev-parse","--git-path","index"]);if(!e)return null;let t=ar(this.projectRoot,e),n={head:ot(this.projectRoot,["rev-parse","--verify","HEAD"]),indexPath:t};try{let i=Fi(t);n.indexMtimeMs=i.mtimeMs,n.indexSize=i.size}catch{n.indexMtimeMs=void 0,n.indexSize=void 0}return n}clearGitPollTimer(){this.gitPollTimer&&(this.clock.clearInterval(this.gitPollTimer),this.gitPollTimer=null)}};function Wi(r){let{projectRoot:e,config:t,languages:n,pnpmWorkspaces:i,typescriptProjectMode:o,typescriptProjects:a,clojureConfigPath:s,indexerConcurrency:c,trigger:l}=r,d=Q(e),u=Object.keys(d).length>0?d:t,p=z(e,u),y=u.indexer?.typescript,f=u.indexer?.clojure;return{workerPath:new URL("./reindex-worker.js",import.meta.url).pathname,env:{...process.env,SCIP_REINDEX_PROJECT_ROOT:e,SCIP_REINDEX_OUTPUT_SCIP:p.indexPath,SCIP_REINDEX_OUTPUT_DB:p.dbPath,SCIP_REINDEX_LANGUAGES:(u.languages??n)?.join(",")??"",SCIP_REINDEX_INDEXER_CONCURRENCY:String(u.indexerConcurrency??c??""),SCIP_REINDEX_PNPM_WORKSPACES:y?.pnpmWorkspaces??i?"1":"",SCIP_REINDEX_TYPESCRIPT_CONFIG:JSON.stringify({projectMode:y?.projectMode??o,projects:y?.projects??a??[]}),SCIP_REINDEX_CLOJURE_CONFIG_PATH:f?.configPath??s??"",SCIP_REINDEX_TRIGGER_KIND:l.kind,SCIP_REINDEX_TRIGGER_DETAIL:l.detail??"",SCIP_REINDEX_PROCESS_GROUP_LEADER:"1"}}}var qi={now:T,wallNow:()=>Date.now(),setTimeout:(r,e)=>setTimeout(r,e),clearTimeout:r=>clearTimeout(r),setInterval:(r,e)=>setInterval(r,e),clearInterval:r=>clearInterval(r)},$i=(r,e)=>ji(r,e),Gi=15*6e4,Bi=1e3,Hi=64*1024;function Ui(){return{stdoutTail:"",stderrTail:"",stdoutTruncated:!1,stderrTruncated:!1}}function Jr(r,e){let t=r instanceof Error?r.message:String(r),n=e.stderrTail.trim()||e.stdoutTail.trim();return n?`${t}
|
|
2
|
+
${n}`:t}function Vi(r={}){let e=r.timeoutMs??Gi,t=r.terminationGraceMs??Bi,n=r.maxOutputBytes??Hi,i=r.resolveLaunch??Wi;return{start(o){let a=i(o),s=new AbortController,c=Ui(),l=!1,d=Vr({command:process.execPath,args:[...process.execArgv,a.workerPath],label:"watch reindex worker",env:a.env,timeoutMs:e,terminationGraceMs:t,maxStdoutBytes:n,maxStderrBytes:n,outputLimitBehavior:"truncate-tail",signal:s.signal,detached:!0}).then(u=>{if(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated},u.status!==0)throw new Error(Jr(new Error(`Reindex worker exited with ${u.signal?`signal ${u.signal}`:`code ${u.status}`}`),c));return u.durationMs}).catch(u=>{throw u instanceof Ur&&(c={stdoutTail:u.stdout,stderrTail:u.stderr,stdoutTruncated:u.stdoutTruncated,stderrTruncated:u.stderrTruncated}),new Error(Jr(u,c),{cause:u})}).finally(()=>{l=!0});return{completion:d,async cancel(){l||s.abort();try{await d}catch{}return{state:"exited",diagnostics:c}},diagnostics:()=>c}}}}function Xr(r,e){return r?r.kind===e.kind?r.detail===e.detail?r:{kind:r.kind,detail:"multiple changes"}:{kind:"watch-git-state",detail:`${r.kind}, ${e.kind}`}:e}function Ki(r){return r instanceof Error&&"code"in r&&r.code==="EMFILE"||String(r).includes("EMFILE: too many open files")}import{existsSync as nn,statSync as Qi}from"fs";import{join as Zi}from"path";import{join as Yi}from"path";var Z=3,zi=2,Ji="typescript-semantic";function Zr(r){let e=Yi(r,Ji),t=Wr(e);return{...t,requestDir:t.legacyRequestDir}}function xt(r){return fr(r)}function en(r){let e=JSON.parse(r),t=e.protocolVersion,n=t===zi;if(!n&&t!==Z||typeof e.id!="string"||typeof e.generation!="string"||typeof e.deadlineAtMs!="number"||!Number.isFinite(e.deadlineAtMs)||e.profileEnvironment!==void 0&&!Zt(e.profileEnvironment)||!e.request||!Xi(e.request)||!n&&(e.mailboxVersion!==yt||typeof e.operationKey!="string"||!/^[a-f0-9]{64}$/.test(e.operationKey)||e.id!==qr(e.operationKey)||typeof e.clientId!="string"||!e.clientId||typeof e.enqueuedAtMs!="number"||!Number.isFinite(e.enqueuedAtMs)||e.deadlineAtMs<e.enqueuedAtMs))throw new Error("TypeScript semantic service received an invalid mailbox request.");if(!n){let o=e,a=St("typescript-semantic-v3",{generation:o.generation,profileEnvironment:o.profileEnvironment,request:o.request});if(o.operationKey!==a)throw new Error("TypeScript semantic service received a mismatched mailbox operation identity.");return o}let i=St("typescript-semantic-v2",{id:e.id,generation:e.generation,request:e.request});return{protocolVersion:Z,mailboxVersion:yt,id:e.id,operationKey:i,clientId:"legacy-v2",enqueuedAtMs:e.deadlineAtMs,deadlineAtMs:e.deadlineAtMs,generation:e.generation,...e.profileEnvironment?{profileEnvironment:e.profileEnvironment}:{},request:e.request}}function Xi(r){if(!r||typeof r!="object"||!("kind"in r))return!1;let e=r;switch(e.kind){case"availability":return!0;case"import-usage":return typeof e.file=="string";case"reference-fragments":return vr(e.files)!==null;case"references":return Qr(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean");case"callees":return Qr(e.definitions);case"signature":return tn(e.definition);default:return!1}}function Qr(r){return Array.isArray(r)&&r.every(tn)}function tn(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.symbolId=="number"&&typeof e.documentId=="number"&&typeof e.symbol=="string"&&typeof e.relativePath=="string"&&typeof e.leaf=="string"&&typeof e.startLine=="number"&&typeof e.endLine=="number"}function eo(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var rn;function to(r=eo(),e=void 0){if(e===void 0&&rn?.projectRoot===r)return rn;let t=Q(r),n=z(r,t),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:r,config:t,paths:n,dbPath:i,dbPathSource:"env",gitContext:e};if(nn(n.dbPath))return{projectRoot:r,config:t,paths:n,dbPath:n.dbPath,dbPathSource:"configured",gitContext:e};let o=Zi(r,"index.db");return{projectRoot:r,config:t,paths:n,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:ro(o,n.dbPath),gitContext:e}}function on(r,e={}){let{config:t,paths:n,dbPath:i,dbPathSource:o,rootFallbackWarning:a,gitContext:s}=to(r);if(!nn(i))throw new Error("No index.db found. Run: scip-query reindex");e.warnOnRootFallback&&o==="root-fallback"&&a&&console.error(a);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??n.indexPath,projectRoot:r,sharedEvidenceDbPath:gt(r,t,s),entryRoots:t.entryRoots,semantic:t.semantic,suppressions:t.suppressions,declaredCouplings:t.declaredCouplings,locality:t.locality,architecture:t.architecture,coverageContracts:t.coverageContracts,docs:t.docs},l=we(r);return new mr(c,l)}function ro(r,e){let t="unknown time";try{t=Qi(r).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${r}, modified ${t}) because the configured index was not found at ${e}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}import{randomUUID as rs}from"crypto";import{resolve as Dn}from"path";import{performance as S}from"perf_hooks";function Oe(r){return{forFile(e,t){return sn(r,e,t)},forFiles(e,t){let n=new Map;for(let i of e)n.set(i,sn(r,i,t));return n}}}function sn(r,e,t){let n={file:e},i=t.facts||t.identifiers;if(t.text&&(n.text=xr(r,e)),t.lines&&(n.lines=Ir(r,e)),t.ast&&(n.ast=Rr(r,e)),t.imports&&(n.imports=Mr(r,e)),t.reexports&&(n.reexports=Pr(r,e)),i){let o=Cr(r,e),a=o.facts;t.facts&&(n.facts=a),o.unavailable&&(n.sourceFactsUnavailable=o.unavailable),t.identifiers&&a&&(n.identifiers=a.fileIdentifiers,n.identifierLineMap=a.identifierLineMap)}return n}var no={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function We(r){if(r.startsWith("local "))return{kind:"local",id:r.slice(6),raw:r};let e=r.split(" ");if(e.length<4)return{scheme:e[0]??"",manager:e[1]??"",packageName:e[2]??"",version:"",descriptors:[],raw:r};let t=e[0],n=e[1],i=r.slice(t.length+1+n.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let a,s=i.indexOf(" ");s===-1?(a=i,i=""):(a=i.slice(0,s),i=i.slice(s+1));let c=io(i);return{scheme:t,manager:n,packageName:o,version:a,descriptors:c,raw:r}}function ee(r){let e=We(r);if("kind"in e)return null;for(let t=e.descriptors.length-2;t>=0;t--){let n=e.descriptors[t];if(n?.suffix==="type")return n.name}return null}function io(r){let e=[],t=0;for(;t<r.length;){if(r[t]==="["){let o=r.indexOf("]",t+1);if(o===-1){e.push({name:r.slice(t+1),suffix:"type-param"});break}e.push({name:r.slice(t+1,o),suffix:"type-param"}),t=o+1;continue}if(r[t]==="("&&(e.length===0||t===0||an(r[t-1]))){let o=r.indexOf(")",t+1);if(o!==-1&&r[o+1]!=="."){e.push({name:r.slice(t+1,o),suffix:"parameter"}),t=o+1;continue}}let n;if(r[t]==="`"){let o=r.indexOf("`",t+1);if(o===-1){n=r.slice(t+1),e.push({name:n,suffix:"term"});break}n=r.slice(t+1,o),t=o+1}else{let o=t;for(;t<r.length&&!an(r[t]);)t++;n=r.slice(o,t)}if(t>=r.length){n&&e.push({name:n,suffix:"term"});break}let i=r[t];if(i==="("){let o=r.indexOf(")",t+1);o!==-1&&r[o+1]==="."?(e.push({name:n,suffix:"method"}),t=o+2):o!==-1?(e.push({name:n,suffix:"method"}),t=o+1):(e.push({name:n,suffix:"term"}),t++)}else{let o=no[i];o&&e.push({name:n,suffix:o}),t+=1}}return e}function an(r){return r==="/"||r==="#"||r==="."||r==="("||r==="["||r===":"||r==="!"}function q(r){let e=We(r);if("kind"in e&&e.kind==="local")return e.id;let t=e;return t.descriptors.length===0?"":t.descriptors[t.descriptors.length-1].name}function $(r){let e=We(r);if("kind"in e&&e.kind==="local")return null;let t=e;return t.descriptors[t.descriptors.length-1]?.suffix??null}function cn(r){let e=$(r);return e==="method"?!0:e!=="term"?!1:r.endsWith("().")?!0:r.startsWith("rust-analyzer ")&&r.includes("#")?!1:r.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(r):!0}function oo(r,e={}){if(ee(r.symbol)!==null)return e.includeClassMemberFallbacks===!0;let i=(r.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function ln(r,e,t={}){let n=new Map;for(let o of e)r.length>0&&!oo(o,{includeClassMemberFallbacks:t.includeClassMemberFallbacks})||n.set(o.id,o);for(let o of r)n.set(o.id,o);let i=[...n.values()];return t.sort?i.sort((o,a)=>o.start_line-a.start_line||o.end_line-a.end_line||o.symbol.localeCompare(a.symbol)):i}var so=ae("file-definitions",{clearGroups:["definition-catalog"]}),yc=ae("file-function-like-definitions",{clearGroups:["definition-catalog"]});function G(r,e,t={}){return t.includeClassMemberFallbacks?dn(r,e,void 0,{includeClassMemberFallbacks:!0}):so.get(r,e,()=>{let n=ao(r,e);if(n)return n;let i=dn(r,e),o=ut(r),a=Oe(r).forFile(e,{text:!0}).text;return o&&a&&pn.write(r,e,dt(r,e,a),{projectFingerprint:o,definitions:i.map(s=>({...s}))}),i})}var pn=gr({kind:"file-definitions",invalidation:yr("file-definitions"),serialize:co,deserialize:lo});function ao(r,e){let t=ut(r);if(!t)return null;let n=Oe(r).forFile(e,{text:!0}).text;if(!n)return null;let i=pn.read(r,e,dt(r,e,n));return i?uo(i,t,e):null}function co(r){return JSON.stringify(r)}function lo(r){try{let e=JSON.parse(r);return!ft(e)||typeof e.projectFingerprint!="string"||!Array.isArray(e.definitions)?null:{projectFingerprint:e.projectFingerprint,definitions:e.definitions}}catch{return null}}function uo(r,e,t){if(r.projectFingerprint!==e)return null;let n=[];for(let i of r.definitions){let o=po(i,t);if(!o)return null;n.push(o)}return n}function po(r,e){return!ft(r)||typeof r.symbolId!="number"||typeof r.symbol!="string"||typeof r.documentId!="number"||typeof r.startLine!="number"||typeof r.startChar!="number"&&r.startChar!==void 0||typeof r.endLine!="number"||typeof r.endChar!="number"&&r.endChar!==void 0||r.relativePath!==e||typeof r.leaf!="string"||typeof r.parentTypeName!="string"&&r.parentTypeName!==null||typeof r.isFunctionLike!="boolean"||typeof r.isTypeLike!="boolean"||typeof r.kind!="number"&&r.kind!==null||typeof r.documentation!="string"&&r.documentation!==null||typeof r.enclosingSymbol!="string"&&r.enclosingSymbol!==null?null:{symbolId:r.symbolId,symbol:r.symbol,documentId:r.documentId,startLine:r.startLine,startChar:r.startChar,endLine:r.endLine,endChar:r.endChar,relativePath:r.relativePath,leaf:r.leaf,parentTypeName:r.parentTypeName,isFunctionLike:r.isFunctionLike,isTypeLike:r.isTypeLike,kind:r.kind,documentation:r.documentation,enclosingSymbol:r.enclosingSymbol}}function dn(r,e,t,n={}){let i=ln(fo(r,e),mo(r,e),{sort:!0,includeClassMemberFallbacks:n.includeClassMemberFallbacks}).map(ho);return t&&(i=i.filter(t)),yo(r,e,i)}function fo(r,e){return r.all(`SELECT
|
|
2
3
|
gs.id,
|
|
3
4
|
gs.symbol,
|
|
4
5
|
der.document_id,
|
|
@@ -16,7 +17,7 @@ import{A as At,Aa as me,B as Lt,C as Nt,D as jt,E as le,F as de,G as _t,I as Ot,
|
|
|
16
17
|
JOIN documents d ON der.document_id = d.id
|
|
17
18
|
WHERE d.relative_path = ?
|
|
18
19
|
${r.symbolNoiseFor("gs")}
|
|
19
|
-
ORDER BY der.start_line, der.end_line`,e)}function
|
|
20
|
+
ORDER BY der.start_line, der.end_line`,e)}function mo(r,e){return r.all(`SELECT
|
|
20
21
|
gs.id,
|
|
21
22
|
gs.symbol,
|
|
22
23
|
c.document_id,
|
|
@@ -37,7 +38,6 @@ import{A as At,Aa as me,B as Lt,C as Nt,D as jt,E as le,F as de,G as _t,I as Ot,
|
|
|
37
38
|
AND m.role = 1
|
|
38
39
|
${r.symbolNoiseFor("gs")}
|
|
39
40
|
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 u;for(;(u=a.exec(d))!==null;)c.push({file:e,line:l,column:u.index})}return z(c.filter(l=>Y(t,mr.join(t,l.file))===e))}function He(r){for(let e=r;e;e=e.getParent()){let t=e.getKindName();if(t.includes("Type")||t==="InterfaceDeclaration"||t==="TypeAliasDeclaration")return!0;if(t==="CallExpression"||t==="NewExpression"||t==="ExpressionStatement")return!1}return!1}function Be(r,e){return r.getLineAndColumnAtPos(e.getStart()).line-1}function z(r){let e=new Set,t=[];for(let n of r){let i=`${n.file}:${n.line}:${n.column}`;e.has(i)||(e.add(i),t.push(n))}return t}function Y(r,e){let t=mr.relative(r||process.cwd(),e).replace(/\\/g,"/");return!t||t.startsWith("..")?null:t}function Sr(r,e,t,n){let i=li(e,n);return i.size===0?new Map:di(r,t,i)}function li(r,e){let t=new Map;for(let n of W(r,e)){let i=_(n.symbol)??n.leaf;if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push(n)}return t}function di(r,e,t){let n=new Map,i=new Map;return e.forEachDescendant(o=>{for(let a of ui(r,o)){let s=t.get(a);if(!s)continue;let c=Be(e,o);for(let l of s){if(c<l.startLine-1||c>l.endLine+1)continue;let d=Math.abs(c-l.startLine),u=i.get(l.symbolId);u!==void 0&&u<=d||(i.set(l.symbolId,d),n.set(l.symbolId,o))}}}),n}function ui(r,e){let t=[],n=i=>{i&&!t.includes(i)&&t.push(i)};if("getNameNode"in e&&typeof e.getNameNode=="function"){let i=e.getNameNode();n(i?.getText())}if("getName"in e&&typeof e.getName=="function"){let i=e.getName();n(i)}return r.Node.isIdentifier(e)&&n(e.getText()),t}var pi=J("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function br(r,e,t,n){let i=ze(r,e),o=Ve(i.get(n)??[],t);if(o)return o;let a=[];for(let s of i.values())for(let c of s)((c.leaf||_(c.symbol)||"").includes(n)||c.symbol.includes(n))&&a.push(c);return Ve(a,t)}function Ke(r,e,t,n){return Ve(ze(r,e).get(n)??[],t)}function vr(r,e){let t=new Map;for(let[n,i]of ze(r,e)){let o=i[0];o&&t.set(n,o)}return t}function ze(r,e){return pi.get(r,e,()=>{let t=new Map;for(let n of W(r,e)){let i=n.leaf||_(n.symbol);if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push({...n,leaf:i})}for(let n of t.values())n.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return t})}function Ve(r,e){let t=null,n=Number.POSITIVE_INFINITY;for(let i of r){let o=Math.abs(i.startLine-e);(o<n||o===n&&t&&i.startLine<t.startLine)&&(t=i,n=o)}return t}import Ye from"path";function xr(r,e){let t=new Map,n=null,i=null,o=()=>(i??=U(r,{extensions:le}),i),a=()=>(n??=N("typescript.source-file-index",()=>fi(r.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),n),s=c=>de(c)?w(t,c,()=>{let l=ee(Ye.resolve(r.config.projectRoot,c));for(let{project:d,sourceFiles:u}of a()){let p=u.get(l)??null;if(p||(p=d.addSourceFileAtPathIfExists(l)??null,p&&u.set(ee(p.getFilePath()),p)),p)return{project:d,sourceFile:p}}return null}):null;return{sourceFile:c=>s(c)?.sourceFile??null,sourceFileMatch:s,indexedTypeScriptLikeDocuments:o}}function fi(r,e,t){let n=e.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[ee(o.getFilePath()),o]))}));for(let i of t){let o=ee(Ye.resolve(r,i));for(let a of n){if(a.sourceFiles.has(o))break;let s=a.project.addSourceFileAtPathIfExists(o)??null;if(s){a.sourceFiles.set(ee(s.getFilePath()),s);break}}}return n}function ee(r){return Ye.resolve(r)}function Je(r,e){for(let t of r)if(e===t.name||e.startsWith(`${t.name}/`))return t.name;return null}function Ir(r){let e=`${r.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as te,readFileSync as mi}from"fs";import x from"path";var Qe=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Xe(r,e){let n=e?x.dirname(x.join(r,e)):r,i=x.resolve(r);for(;n.startsWith(i);){for(let a of Qe){let s=x.join(n,a);if(te(s))return s}let o=x.dirname(n);if(o===n)break;n=o}for(let o of Qe){let a=x.join(r,o);if(te(a))return a}return null}function Rr(r){let e=r.config.projectRoot,t=new Set(hi(e,r.config.semantic?.typescript?.tsconfigs)),n=U(r,{includeIgnored:!1,extensions:le});for(let i of n){let o=Xe(e,i);o&&t.add(x.resolve(o))}if(t.size===0){let i=Xe(e);i&&t.add(x.resolve(i))}return[...t].filter(i=>!Cr(e,i)).sort((i,o)=>i.localeCompare(o))}function hi(r,e=[]){let t=new Set;for(let n of e){let i=x.isAbsolute(n)?n:x.join(r,n);te(i)&&t.add(x.resolve(i))}for(let n of gi(r))for(let i of Qe){let o=x.join(n,i);te(o)&&t.add(x.resolve(o))}if(t.size===0){let n=Xe(r);n&&t.add(x.resolve(n))}return[...t].filter(n=>!Cr(r,n)).sort((n,i)=>n.localeCompare(i))}function gi(r){let e=x.join(r,"package.json");if(!te(e))return[];let t;try{t=JSON.parse(mi(e,"utf8"))}catch{return[]}return(Array.isArray(t.workspaces)?t.workspaces:t.workspaces?.packages??[]).flatMap(i=>Pt(r,i))}function Cr(r,e){let t=x.relative(r,e).replace(/\\/g,"/");return t.startsWith("..")||t.includes("/node_modules/")||t.startsWith("node_modules/")||t.includes("/dist/")||t.startsWith("dist/")}var yi=32;function Dr(r,e,t,n={}){return N("typescript.provider.construct",()=>new et(r,e,t),()=>({tsconfigs:t.length,reusedProjects:n.reusedProjects===!0}))}var et=class{constructor(e,t,n){this.db=e;this.tsMorph=t;this.projects=n;this.workspacePackages=kt(e.config.projectRoot),this.sourceFiles=xr(e,n)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(e=>e.tsconfigPath)}}importUsage(e){return w(this.importUsageCache,e,()=>{let t=this.sourceFiles.sourceFile(e);if(!t)return[];let n=bi();return N("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,t,n),()=>({file:e,...n}))})}referencesFor(e){return w(this.referencesCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,t)})}referencesForDefinitions(e,t={}){let n=new Map,i=ce(),o=[];for(let d of e){let u=this.referencesCache.get(d.symbolId);u?n.set(d.symbolId,u):o.push(d)}if(o.length===0)return n;let a=o,s=t.exact?[]:o.filter(d=>!wr(d));if(s.length>=yi){let d=this.referencesForDefinitionsBySymbolScan(s);for(let u of s){let p=d.get(u.symbolId)??[];this.referencesCache.set(u.symbolId,p),n.set(u.symbolId,p)}if(a=o.filter(u=>wr(u)),a.length===0)return n}let c=new Map;for(let d of a){let u=c.get(d.relativePath);u?u.push(d):c.set(d.relativePath,[d])}let l=[];for(let[d,u]of c){let p=kr();N("typescript.references-map.file",()=>{let g=this.definitionNodesForFile(d);for(let f of u){i&&(p.cacheMisses+=1);let m=g.get(f.symbolId)??null;i&&(m?p.nodeHits+=1:p.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(f,m,i?p:void 0);this.referencesCache.set(f.symbolId,h),n.set(f.symbolId,h)}catch{p.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:d,definitions:u.length,...Pr(p)}))}if(l.length>0){let d=this.referencesForDefinitionsBySymbolScan(l);for(let u of l){let p=d.get(u.symbolId)??[];this.referencesCache.set(u.symbolId,p),n.set(u.symbolId,p)}}return n}referenceFragmentsForFiles(e){let t=fr(this.db).filter(o=>de(o.relativePath)),n=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,n);return Wt(t,i,n)}referencesForDefinitionsBySymbolScan(e,t){let n=ce(),i=kr(),o=new Map,a=new Set(e.map(c=>c.symbolId)),s=new Map(e.map(c=>[c.symbolId,c]));for(let c of e)o.set(c.symbolId,[]);return N("typescript.references-map.inverted-scan",()=>{let c=n?y.now():0,l=t?this.packageImportReferencesForFiles(t):this.packageImportReferences();for(let h of e){let S=l.get(h.symbolId)??[];if(S.length>0){let M=o.get(h.symbolId)??[];M.push(...S),o.set(h.symbolId,M)}n&&(i.packageReferenceCount+=S.length)}n&&(i.packageRefsMs+=y.now()-c);let d=new Map,u=new Map,p=this.hierarchyTargetsForDefinitions(e),g=new Set(e.map(h=>h.leaf).filter(Boolean)),f=n?y.now():0;for(let h of t??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(h))continue;let S=this.sourceFiles.sourceFile(h);S&&(n&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(S,h,a,s,p,g,d,u,o,n?i:void 0))}n&&(i.scanMs+=y.now()-f);let m=n?y.now():0;this.addHierarchyMemberReferences(e,o,n?i:void 0),n&&(i.hierarchyMs+=y.now()-m);for(let[h,S]of o){let M=z(S);o.set(h,M),n&&(i.referenceCount+=M.length)}},()=>({definitions:e.length,...Pr(i)})),o}addReferencesFromSourceFileScan(e,t,n,i,o,a,s,c,l,d){let u=this.compilerCheckerForSourceFile(e),p=e.compilerNode,g=Ii(e),f=m=>{if(this.tsMorph.ts.isIdentifier(m)){if(d&&(d.identifiers+=1),!a.has(m.text)&&!g.has(m.text)){this.tsMorph.ts.forEachChild(m,f);return}let h=this.compilerReferenceSymbol(u,m,d);if(h){let S;s.has(h)?S=s.get(h)??null:(S=this.referenceDefinitionFromCompilerSymbol(h),s.set(h,S)),d&&(S?d.targetHits+=1:d.targetMisses+=1);let M=w(c,h,()=>this.compilerSymbolKeys(h)),A=null,P=null,L=S&&n.has(S.symbolId)?i.get(S.symbolId):void 0;if(L&&(A=Ze(p,m),!Mr(L,t,A))){let D=p.getLineAndCharacterOfPosition(m.getStart(p));P={file:t,line:D.line,column:D.character};let C=l.get(L.symbolId)??[];C.push(P),l.set(L.symbolId,C),d&&(d.requestedHits+=1)}for(let D of M)for(let C of o.get(D)?.values()??[]){if(A??=Ze(p,m),Mr(C,t,A))continue;if(!P){let I=p.getLineAndCharacterOfPosition(m.getStart(p));P={file:t,line:I.line,column:I.character}}let b=l.get(C.symbolId)??[];b.push(P),l.set(C.symbolId,b),d&&(d.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(m,f)};f(p)}hierarchyTargetsForDefinitions(e){let t=new Map;for(let n of e){let i=this.nodeForDefinition(n),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let a=o.parent;if(!this.isHierarchyContainer(a))continue;let s=this.compilerCheckerForSourceFile(i.getSourceFile()),c=s.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(s,a,c))for(let d of this.compilerSymbolKeys(l)){let u=t.get(d)??new Map;u.set(n.symbolId,n),t.set(d,u)}}return t}hierarchyMemberSymbols(e,t,n){let i=new Set,o=new Set,a=(s,c,l)=>{if(!o.has(s)){o.add(s),i.add(c);for(let d of l){let u=d.getProperty(n.name);u&&a(d,u,this.hierarchyAncestorTypesForType(e,d))}}};return a(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}addHierarchyMemberReferences(e,t,n){let i=new Map;for(let o of e){let a=this.nodeForDefinition(o),s=a?.compilerNode;if(!s||!this.isHierarchyMethod(s))continue;let c=s.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(a.getSourceFile()),d=l.getSymbolAtLocation(s.name);if(!d)continue;let u=s.getSourceFile(),p=u.getLineAndCharacterOfPosition(s.name.getStart(u)),g={definition:o,location:{file:o.relativePath,line:p.line,column:p.character}},f=t.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(l,c,d))if(h!==d)for(let S of this.compilerSymbolLocations(h))f.push(S),n&&(n.hierarchyReferences+=1);t.set(o.symbolId,f);let m=this.hierarchyRootMemberSymbols(l,c,d);for(let h of m){let S=i.get(h)??new Map;S.set(o.symbolId,g),i.set(h,S)}n&&(n.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){n&&(n.hierarchyFamilies+=1);for(let{definition:a}of o.values()){let s=t.get(a.symbolId)??[];for(let c of o.values())c.definition.symbolId!==a.symbolId&&(s.push(c.location),n&&(n.hierarchyReferences+=1));t.set(a.symbolId,s)}}}hierarchyRootMemberSymbols(e,t,n){let i=new Set,o=new Set,a=(s,c,l)=>{if(o.has(s))return;o.add(s);let d=!1;for(let u of l){let p=u.getProperty(n.name);p&&(d=!0,a(u,p,this.hierarchyAncestorTypesForType(e,u)))}if(!d)for(let u of this.compilerSymbolKeys(c))i.add(u)};return a(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}compilerSymbolKeys(e){return(e.declarations??[]).map(t=>{let n=t.getSourceFile();return`${n.fileName}\0${t.getStart(n)}\0${e.name}`})}compilerSymbolLocations(e){let t=[];for(let n of e.declarations??[]){let i=n.getSourceFile(),o=Y(this.db.config.projectRoot,i.fileName);if(!o)continue;let a=n.name,s=i.getLineAndCharacterOfPosition((a??n).getStart(i));t.push({file:o,line:s.line,column:s.character})}return t}baseTypes(e,t){try{return e.getBaseTypes(t)??[]}catch{return[]}}hierarchyAncestorTypes(e,t){let n=new Set(this.hierarchyAncestorTypesForType(e,e.getTypeAtLocation(t)));for(let i of t.heritageClauses??[])for(let o of i.types)n.add(e.getTypeAtLocation(o));return[...n]}hierarchyAncestorTypesForType(e,t){let n=new Set(this.baseTypes(e,t));for(let i of t.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let a of o.types)n.add(e.getTypeAtLocation(a));return[...n]}isHierarchyMethod(e){return this.tsMorph.ts.isMethodDeclaration(e)||this.tsMorph.ts.isMethodSignature(e)}isHierarchyContainer(e){return this.tsMorph.ts.isClassDeclaration(e)||this.tsMorph.ts.isClassExpression(e)||this.tsMorph.ts.isInterfaceDeclaration(e)}compilerReferenceSymbol(e,t,n){n&&(n.symbolLookups+=1);let i=e.getSymbolAtLocation(t);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return n&&(n.aliasResolutions+=1),e.getAliasedSymbol(i)}catch{return i}}}calleesFor(e){return w(this.calleesCache,e.symbolId,()=>w(this.fileCalleesCache,e.relativePath,()=>this.calleeMapForFile(e.relativePath)).get(e.symbolId)??[])}calleesForDefinitions(e){let t=new Map,n=new Map;for(let i of e){let o=n.get(i.relativePath);o?o.push(i):n.set(i.relativePath,[i])}for(let[i,o]of n){let a=this.fileCalleesCache.get(i),s=new Set(o.map(l=>l.symbolId)),c=a??this.calleeMapForFile(i,s);for(let l of o){let d=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,d),t.set(l.symbolId,d)}}return t}referencesForDefinitionNode(e,t,n){let i=n?y.now():0,o=this.packageImportReferencesForDefinition(e);if(n&&(n.packageRefsMs+=y.now()-i,n.packageReferenceCount+=o.length),!t)return o;let a=n?y.now():0,s=hr(t,e,o,this.db.config.projectRoot);return n&&(n.semanticRefsMs+=y.now()-a,n.referenceCount+=s.length),s}signatureFor(e){return w(this.signatureCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);if(!t||!this.tsMorph.Node.isFunctionDeclaration(t)&&!this.tsMorph.Node.isMethodDeclaration(t)&&!this.tsMorph.Node.isArrowFunction(t)&&!this.tsMorph.Node.isFunctionExpression(t)&&!this.tsMorph.Node.isConstructorDeclaration(t))return null;let n=t.getType().getCallSignatures()[0];if(!n)return null;let i=n.getParameters().map(a=>{let s=a.getDeclarations()[0],c=s?a.getTypeAtLocation(s).getText(s):a.getValueDeclaration()?.getType().getText()??"unknown";return Tr(c)}),o=n.getReturnType().getText(t);return`(${i.join(",")})=>${Tr(o)}`})}importUsageForSourceFile(e,t,n){let i=[],o=new Map;for(let a of t.getImportDeclarations()){n.declarations+=1;let s=Ne(this.db,e,a.getModuleSpecifierValue()),c=a.getImportClause()?.isTypeOnly()??!1;for(let l of tt(a)){n.entries+=1;let d=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(d?n.bindingSymbols+=1:n.missingBindingSymbols+=1);let u={sourcePath:s,entry:l,typeOnlyDeclaration:c,bindingSymbol:d,references:[]};if(i.push(u),c||!l.localName||!d)continue;let p=o.get(l.localName);p?p.push(u):o.set(l.localName,[u])}}return o.size>0&&t.forEachDescendant(a=>{if(a.getKindName()!=="Identifier")return;let s=o.get(a.getText());if(!s||vi(a))return;n.scannedIdentifiers+=1;let c=a.getSymbol()?.compilerSymbol;if(n.symbolLookups+=1,!!c){for(let l of s)if(l.bindingSymbol===c){l.references.push({location:xe(a,this.db.config.projectRoot),node:a}),n.matchedReferences+=1;break}}}),i.map(a=>a.typeOnlyDeclaration?Si(e,a.sourcePath,a.entry):a.entry.identifier&&!a.bindingSymbol?(n.fallbackEntries+=1,this.valueImportUsageForEntry(e,a.sourcePath,a.entry)):this.valueImportUsageFromLocations(e,a.sourcePath,a.entry,a.references))}valueImportUsageForEntry(e,t,n){let i=n.identifier?n.identifier.findReferences():[],o=[];for(let a of i)for(let s of gr(a,e,n.identifier,this.db.config.projectRoot))o.push(s);return this.valueImportUsageFromLocations(e,t,n,o)}valueImportUsageFromLocations(e,t,n,i){let o=i.some(c=>!He(c.node)),a=i.some(c=>He(c.node)),s=n.isTypeOnly;return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:s,isUsed:s||i.length>0,isTypeUsed:s||a,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(e){return this.packageImportReferences().get(e.symbolId)??[]}packageImportReferencesForFiles(e){let t=new Map,n=new Set;for(let o of e){let a=this.sourceFiles.sourceFile(o);if(a)for(let s of a.getImportDeclarations()){let c=Je(this.workspacePackages,s.getModuleSpecifierValue());c&&n.add(c)}}if(n.size===0)return t;let i=this.packageExportsForNames(n);for(let o of e)this.addPackageImportReferencesForDocument(t,i,o);for(let[o,a]of t)t.set(o,z(a));return t}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let e=new Map,t=this.packageExports();for(let n of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(e,t,n);for(let[n,i]of e)e.set(n,z(i));return this.packageImportReferenceIndex=e,e}addPackageImportReferencesForDocument(e,t,n){if(this.db.isIgnored(n))return;let i=this.sourceFiles.sourceFileMatch(n);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(e,t,n,o)}addPackageImportReferencesForDeclaration(e,t,n,i){let o=Je(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let a=t.get(o);if(a)for(let s of tt(i)){if(s.kind!=="named"||!s.identifier)continue;let c=a.get(s.importedName);if(!c||c.size===0)continue;let l=yr(s.identifier,n,this.db.config.projectRoot);l.length>0&&wi(e,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(e=>e.name))),this.packageExportIndex)}packageExportsForNames(e){let t=new Map;for(let n of this.workspacePackages){if(!e.has(n.name))continue;let i=new Map;for(let o of Ir(n))this.collectPackageExports(n,o,i,new Set);i.size>0&&t.set(n.name,i)}return t}collectPackageExports(e,t,n,i){if(i.has(t))return;i.add(t);let o=this.sourceFiles.sourceFile(t);if(o)for(let a of o.getExportDeclarations()){let s=a.getModuleSpecifierValue(),c=s?Ne(this.db,t,s):t;if(!c||!c.startsWith(`${e.relativeDir}/src/`))continue;let l=a.getNamedExports();if(l.length===0){if(a.isNamespaceExport())continue;this.collectPackageExports(e,c,n,i);continue}for(let d of l){let u=d.getNameNode().getText(),p=d.getAliasNode()?.getText()??u,g=this.indexedDefinitionByLeaf(c,u);if(!g)continue;let f=n.get(p);f||(f=new Set,n.set(p,f)),f.add(g.symbolId)}}}indexedDefinitionByLeaf(e,t){return w(this.indexedDefinitionLeafCache,e,()=>vr(this.db,e)).get(t)??null}nodeForDefinition(e){return w(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return w(this.fileDefinitionNodeCache,e,()=>{let t=this.sourceFiles.sourceFile(e);return t?Sr(this.tsMorph,this.db,t,e):new Map})}referenceDefinitionFromCompilerSymbol(e){return this.definitionFromCompilerSymbol(e,void 0,!0)}definitionFromCompilerSymbol(e,t,n=!1){let i=e.name,o=t?y.now():0,a=e.declarations??[];t&&(t.declarationsMs+=y.now()-o,t.declarationChecks+=a.length);for(let s of a){let c=t?y.now():0,l=s.getSourceFile(),d=Y(this.db.config.projectRoot,l.fileName),u=l.getLineAndCharacterOfPosition(s.getStart(l)).line;if(t&&(t.declarationLocationMs+=y.now()-c),!d||this.db.isIgnored(d))continue;let p=t?y.now():0,g=this.compilerDeclarationName(s),f=n?Ke(this.db,d,u,i)??(g&&g!==i?Ke(this.db,d,u,g):null):br(this.db,d,u,i);if(t&&(t.indexedLookupMs+=y.now()-p),f)return{symbolId:f.symbolId,symbol:f.symbol,file:f.relativePath,line:f.startLine}}return null}compilerDeclarationName(e){let t=e.name;return t&&this.tsMorph.ts.isIdentifier(t)?t.text:null}calleeMapForFile(e,t){let n=ce(),i=0,o=0,a=0,s=0,c=0,l=0,d=0,u=0,p=n?Ci():void 0;return N("typescript.callee-map.file",()=>{let g=n?y.now():0,f=this.sourceFiles.sourceFile(e);if(n&&(c=Math.round(y.now()-g)),!f)return new Map;let m=n?y.now():0,h=W(this.db,e).sort((b,I)=>b.startLine-I.startLine||I.endLine-b.endLine);if(n&&(l=Math.round(y.now()-m)),i=h.length,h.length===0)return new Map;let S=new Map,M=n?y.now():0,A=this.compilerCheckerForSourceFile(f),P=f.compilerNode;n&&(d=Math.round(y.now()-M));let L=new Map,D=b=>{if(this.tsMorph.ts.isCallExpression(b)||this.tsMorph.ts.isNewExpression(b)){n&&(o+=1);let I=this.semanticCalleeForCallNode(A,P,h,b,L,t,p);I&&(n&&(a+=1),xi(S,I.callerId,I.target))}this.tsMorph.ts.forEachChild(b,D)},C=n?y.now():0;D(P),n&&(u=Math.round(y.now()-C));for(let[b,I]of S)S.set(b,ki(I));return s=S.size,S},()=>({relativePath:e,definitions:i,callNodes:o,resolvedCallees:a,outputRows:s,requestedDefinitions:t?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:u,...p?Mi(p):{}}))}semanticCalleeForCallNode(e,t,n,i,o,a,s){let c=s?y.now():0,l=Ri(n,Ze(t,i));if(s&&(s.callerLookupMs+=y.now()-c),!l)return null;if(a&&!a.has(l.symbolId))return s&&(s.skippedUnrequestedCallers+=1),null;let d=i.expression,u=this.compilerSymbolForExpression(e,d,s),p=null;if(u)if(s&&(s.targetSymbolHits+=1),o.has(u))s&&(s.compilerSymbolCacheHits+=1),p=o.get(u)??null;else{s&&(s.compilerSymbolCacheMisses+=1);let g=s?y.now():0;p=this.definitionFromCompilerSymbol(u,s),s&&(s.targetLookupMs+=y.now()-g),o.set(u,p)}else s&&(s.targetMisses+=1);return p?{callerId:l.symbolId,target:{symbol:p.symbol,file:p.file,line:p.line}}:null}compilerSymbolForExpression(e,t,n){let i=n?y.now():0,o=e.getSymbolAtLocation(t);if(n&&(n.expressionSymbolMs+=y.now()-i),o)return o;n&&(n.typeFallbacks+=1);let a=n?y.now():0,s=e.getTypeAtLocation(t).getSymbol();return n&&(n.typeSymbolMs+=y.now()-a),s}compilerCheckerForSourceFile(e){let t=e.getProject(),n=this.compilerCheckerCache.get(t);return n||(n=t.getTypeChecker().compilerObject,this.compilerCheckerCache.set(t,n)),n}};function tt(r){let e=[],t=r.getDefaultImport();t&&e.push({identifier:t,importedName:"default",localName:t.getText(),kind:"default",isTypeOnly:r.getImportClause()?.isTypeOnly()??!1});let n=r.getNamespaceImport();n&&e.push({identifier:n,importedName:"*",localName:n.getText(),kind:"namespace",isTypeOnly:r.getImportClause()?.isTypeOnly()??!1});for(let i of r.getNamedImports()){let o=i.getNameNode(),s=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);e.push({identifier:s,importedName:o.getText(),localName:s?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(r.getImportClause()?.isTypeOnly()??!1)})}return e.length===0&&e.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),e}function Si(r,e,t){return{importer:r,sourcePath:e,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function bi(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function vi(r){for(let e=r;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function xi(r,e,t){let n=r.get(e);n||(n=[],r.set(e,n)),n.push(t)}function Ii(r){let e=new Set;for(let t of r.getImportDeclarations())for(let n of tt(t))n.localName&&e.add(n.localName);return e}function Ri(r,e){let t=null;for(let n of r)e<n.startLine||e>n.endLine||(!t||n.startLine>=t.startLine)&&(t=n);return t}function Ze(r,e){return r.getLineAndCharacterOfPosition(e.getStart(r)).line}function Mr(r,e,t){return e===r.relativePath&&t>=r.startLine&&t<=r.endLine}function wr(r){return r.symbol.includes("#")?O(r.symbol)==="type"&&r.relativePath.endsWith(".d.ts"):!1}function Ci(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function Mi(r){return{...r,callerLookupMs:Math.round(r.callerLookupMs),expressionSymbolMs:Math.round(r.expressionSymbolMs),typeSymbolMs:Math.round(r.typeSymbolMs),targetLookupMs:Math.round(r.targetLookupMs),declarationsMs:Math.round(r.declarationsMs),declarationLocationMs:Math.round(r.declarationLocationMs),indexedLookupMs:Math.round(r.indexedLookupMs)}}function kr(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function Pr(r){return{...r,scanMs:Math.round(r.scanMs),packageRefsMs:Math.round(r.packageRefsMs),semanticRefsMs:Math.round(r.semanticRefsMs),hierarchyMs:Math.round(r.hierarchyMs)}}function wi(r,e,t){for(let n of e){let i=r.get(n)??[];i.push(...t),r.set(n,i)}}function ki(r){let e=new Set,t=[];for(let n of r){let i=`${n.symbol}|${n.file}|${n.line}`;e.has(i)||(e.add(i),t.push(n))}return t}function Tr(r){return r.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Ie=class{loadModule;discoverTsconfigs;createProjects;createProvider;db;module=null;projects=null;provider=null;stats={providerRequests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0};constructor(e,t={}){this.db=e,this.loadModule=t.loadModule??_t,this.discoverTsconfigs=t.discoverTsconfigs??Rr,this.createProjects=t.createProjects??Ot,this.createProvider=t.createProvider??((n,i,o)=>Dr(n,i,o,{reusedProjects:!0}))}semanticProvider(){return this.stats.providerRequests+=1,this.provider?(this.stats.sessionsReused+=1,this.provider):this.createSession()}advanceGeneration(e,t){let n=Pi(t);return this.provider?.dispose?.(),this.provider=null,this.db=e,this.projects?n.mode==="replace"?(this.projects=null,this.module=null,this.stats.sessionsReplaced+=1,n):(n.mode==="refresh"&&(Ti(this.projects,e.config.projectRoot,n),this.stats.sessionsRefreshed+=1),n):n}snapshotStats(){return{...this.stats}}dispose(){this.provider?.dispose?.(),this.provider=null,this.projects=null,this.module=null}createSession(){let e=this.module??this.loadModule();if(!e)return this.provider=_e("ts-morph is not installed"),this.provider;if(this.module=e,!this.projects){let t=this.discoverTsconfigs(this.db);if(t.length===0)return this.provider=_e("no tsconfig found"),this.provider;this.projects=this.createProjects(e,t),this.stats.projectsCreated+=this.projects.length}return this.provider=this.createProvider(this.db,e,this.projects),this.stats.sessionsCreated+=1,this.provider}};function Pi(r){let e=new Set;r.projectIdentityChanged&&e.add("project-identity-changed");for(let o of r.uncertainty)e.add(o);for(let o of r.changes)o.inputKind!=="source"&&e.add(`${o.inputKind}-input-changed`);if(e.size>0)return{mode:"replace",addedFiles:[],modifiedFiles:[],deletedFiles:[],reasons:[...e].sort()};let t=rt(r.changes,"added"),n=rt(r.changes,"modified"),i=rt(r.changes,"deleted");return{mode:t.length+n.length+i.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:n,deletedFiles:i,reasons:[]}}function rt(r,e){return r.filter(t=>t.kind===e).map(t=>t.path).sort()}function Ti(r,e,t){for(let n of r){for(let i of t.deletedFiles)n.project.getSourceFile(Er(e,i))?.forget();for(let i of t.modifiedFiles){let o=n.project.getSourceFile(Er(e,i));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&n.project.addSourceFilesFromTsConfig(n.tsconfigPath)}}var Ce=class{openDb;createHost;generationIdentity;readSnapshot;now;db=null;host=null;generation=null;snapshot=null;requests=0;lastRequestAtMs=null;lastError=null;available=null;constructor(e){this.openDb=e.openDb,this.createHost=e.createHost??(t=>new Ie(t)),this.generationIdentity=e.generationIdentity??Z,this.readSnapshot=e.readSnapshot??Li,this.now=e.now??Date.now}handle(e,t){try{this.syncGeneration(e);let n=this.host.semanticProvider();switch(this.available=n.availability().available,this.requests+=1,this.lastRequestAtMs=this.now(),this.lastError=null,t.kind){case"availability":return n.availability();case"import-usage":return n.importUsage(t.file);case"references":return[...Fi(n,t.definitions,{exact:t.exact===!0})];case"reference-fragments":if(!n.referenceFragmentsForFiles)throw new Error("TypeScript provider does not support reference fragments.");return[...n.referenceFragmentsForFiles(t.files)];case"callees":return[...Ai(n,t.definitions)];case"signature":return n.signatureFor(t.definition);default:return ji(t)}}catch(n){throw this.lastError=n instanceof Error?n.message:String(n),n}}status(){let e=this.host?.snapshotStats();return{protocolVersion:X,state:this.lastError?"error":this.host?this.available?"ready":"unavailable":"idle",requests:this.requests,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastError?{lastError:this.lastError}:{},sessionsCreated:e?.sessionsCreated??0,sessionsReused:e?.sessionsReused??0,sessionsRefreshed:e?.sessionsRefreshed??0,sessionsReplaced:e?.sessionsReplaced??0,projectsCreated:e?.projectsCreated??0}}closeTypeScriptService(){this.host?.dispose(),this.db?.close(),this.host=null,this.db=null,this.generation=null,this.snapshot=null,this.available=null}syncGeneration(e){if(this.generation===e&&this.host&&this.db)return;let t=this.openDb(),n=this.generationIdentity(t.config.dbPath);if(!n||n!==e)throw t.close(),new Error("TypeScript semantic request does not match the currently published index generation.");let i=this.readSnapshot(t.config.dbPath);if(!this.host||!this.db)this.db=t,this.host=this.createHost(t);else{let o=this.db;this.host.advanceGeneration(t,Ni(this.snapshot,i)),this.db=t,o.close()}this.generation=n,this.snapshot=i,this.available=null}};function nt(r){Fr(r.requestDir,{recursive:!0}),Fr(r.responseDir,{recursive:!0})}function Lr(r,e,t={}){nt(r);let n=0;for(let i of Di(r.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=Re(r.requestDir,i),a=i.slice(0,-5),s=null;try{let c=tr(Ar(o,"utf8"));if(a=c.id,c.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript semantic request expired before processing.");s=ht(),De(c.profileEnvironment??{}),t.beforeRequest?.(c.deadlineAtMs);let l=e.handle(c.generation,c.request);F(Re(r.responseDir,`${a}.json`),{ok:!0,protocolVersion:X,id:a,generation:c.generation,response:l})}catch(c){F(Re(r.responseDir,`${a}.json`),{ok:!1,protocolVersion:X,id:a,error:c instanceof Error?c.message:String(c)})}finally{s&&De(s),t.afterRequest?.(),Ei(o,{force:!0}),n+=1}}return n}function Fi(r,e,t){return r.referencesForDefinitions?.(e,t)??new Map(e.map(n=>[n.symbolId,r.referencesFor(n)]))}function Ai(r,e){return r.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,r.calleesFor(t)]))}function Li(r){try{let e=JSON.parse(Ar(Re(r,"..","meta.json"),"utf8"));return ft(e.fingerprint)}catch{return null}}function Ni(r,e){return e?mt(r,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function ji(r){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(r)}`)}import{mkdirSync as Nr,readFileSync as _i,readdirSync as Oi,rmSync as Wi}from"fs";import{resolve as Me}from"path";var we=class{projectRoot;currentGeneration;createEmitter;now;active=null;requests=0;sessionsCreated=0;sessionsReplaced=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(e){this.projectRoot=Me(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??Vt,this.now=e.now??Date.now}handle(e,t){let n=this.now();try{if(this.currentGeneration()!==e)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(t);if(i.emitter.producerIdentity!==t.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),a=i.emitter.advance({modifiedFiles:t.modifiedFiles,affectedFiles:t.affectedFiles}),s=this.now()-n;return this.requests+=1,this.lastRequestAtMs=this.now(),this.lastDurationMs=s,this.lastError=null,this.unavailable=!1,{producerIdentity:a.producerIdentity,cold:a.stats.initializations>o.initializations,durationMs:s,fragments:a.fragments.map(c=>({relativePath:c.relativePath,bytesBase64:c.bytes===null?null:Buffer.from(c.bytes).toString("base64"),occurrences:c.occurrences,symbols:c.symbols,referenceFragments:c.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(){let e=this.active?.emitter.snapshotStats();return{protocolVersion:fe,state:this.unavailable?"unavailable":this.lastError?"error":this.active?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,initializations:e?.initializations??0,programUpdates:e?.programUpdates??0,documentsEmitted:e?.documentsEmitted??0,documentsRemoved:e?.documentsRemoved??0,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{}}}close(){this.active=null}emitterFor(e){let t=`${e.tsconfigPath}\0${e.projectArgument}`;if(this.active&&this.active.sessionKey===t&&this.active.projectIdentity===e.projectIdentity)return this.active;let n=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:e.tsconfigPath,projectRoot:e.projectArgument});if(!n.available)throw this.unavailable=!0,new Error(n.reason);return this.active&&(this.sessionsReplaced+=1),this.active={sessionKey:t,projectIdentity:e.projectIdentity,emitter:n.emitter},this.sessionsCreated+=1,this.active}};function it(r){Nr(r.requestDir,{recursive:!0}),Nr(r.responseDir,{recursive:!0})}function jr(r,e,t={}){it(r);let n=0;for(let i of Oi(r.requestDir).filter(o=>o.endsWith(".json")).sort()){let o=Me(r.requestDir,i),a=i.slice(0,-5);try{let s=zt(_i(o,"utf8"));if(a=s.id,s.deadlineAtMs<(t.nowMs??Date.now()))throw new Error("TypeScript index request expired before processing.");t.beforeRequest?.(s.deadlineAtMs);let c=e.handle(s.baseGeneration,s.request);F(Me(r.responseDir,`${a}.json`),{ok:!0,protocolVersion:fe,id:a,baseGeneration:s.baseGeneration,response:c})}catch(s){F(Me(r.responseDir,`${a}.json`),{ok:!1,protocolVersion:fe,id:a,error:s instanceof Error?s.message:String(s)})}finally{t.afterRequest?.(),Wi(o,{force:!0}),n+=1}}return n}import{spawn as $i}from"child_process";import{closeSync as Gi,existsSync as qi,mkdirSync as Ui,openSync as Hi,readFileSync as Wr,rmSync as re,writeFileSync as Bi}from"fs";import{dirname as Vi,resolve as at}from"path";import{fileURLToPath as Na}from"url";var Ki=2e3,zi=10;function $r(r,e,t){let n=Fe(at(r));if(t&&Fe(t.projectRoot)===n)return{projectRoot:n,worktreeKind:"git",worktreeId:t.worktreeId,cliVersion:e};let i=yt(n);if(i.kind==="error")throw new Error(`Could not establish Git worktree identity for ${n}: ${i.message}`);return i.kind==="non-git"?{projectRoot:n,worktreeKind:"non-git",cliVersion:e}:{projectRoot:n,worktreeKind:"git",worktreeId:i.identity.worktreeId,cliVersion:e}}function Gr(r){let e=r.runtime??Qi,t=B(r.cacheDir),n=Jt(t.statePath),i=n?e.isProcessAlive(n.pid)?{kind:"live",state:n}:{kind:"stale",state:n,reason:"dead-process"}:{kind:"stopped"},o=Yi("stop",i);if(o.kind==="signal-stop")return _r(o.state.pid,r,e),ot(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};if(o.kind==="clean-stale")return ot(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};let a=ne(t.lockPath);return o.kind==="already-stopped"&&a&&e.isProcessAlive(a.pid)?(_r(a.pid,r,e),ot(t,a.pid,e),{disposition:"stopped",pid:a.pid}):{disposition:"already-stopped"}}function qr(r,e){F(r,e)}function Ur(r){try{let e=JSON.parse(Wr(r,"utf8"));return e.version!==1||!me(e.at)||e.refreshRequestedAt!==void 0&&!me(e.refreshRequestedAt)||e.refreshDetail!==void 0&&typeof e.refreshDetail!="string"?null:{atMs:Date.parse(e.at),...e.refreshRequestedAt===void 0?{}:{refreshRequestedAtMs:Date.parse(e.refreshRequestedAt)},...e.refreshDetail===void 0?{}:{refreshDetail:e.refreshDetail}}}catch{return null}}function Hr(r,e,t={}){let n=t.pid??process.pid,i=t.isProcessAlive??j,o=()=>{},a=ne(r);if(a&&i(a.pid))return{acquired:!1,lockPath:r,message:Or(r,e,a),release:o};a&&re(r,{force:!0}),Ui(Vi(r),{recursive:!0});let s;try{s=Hi(r,"wx")}catch(d){if(Ji(d)==="EEXIST")return{acquired:!1,lockPath:r,message:Or(r,e,ne(r)),release:o};throw d}let c={version:1,pid:n,projectRoot:at(e),startedAt:(t.now??(()=>new Date))().toISOString()};Bi(s,`${JSON.stringify(c)}
|
|
42
|
-
`);let l=!1;return{acquired:!0,lockPath:r,message:"",release:()=>{if(l)return;l=!0,Gi(s);let d=ne(r);d?.pid===c.pid&&d.startedAt===c.startedAt&&re(r,{force:!0})}}}function ne(r){try{let e=JSON.parse(Wr(r,"utf-8"));return e.version!==1||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.projectRoot!="string"||!me(e.startedAt)?null:e}catch{return null}}function Yi(r,e){switch(r){case"status":return{kind:"report",classification:e};case"ensure":switch(e.kind){case"stopped":return{kind:"start"};case"stale":return e.reason==="old-heartbeat"?{kind:"replace",state:e.state}:{kind:"start"};case"live":return{kind:"reuse",state:e.state};case"incompatible":return{kind:"replace",state:e.state};default:return st(e)}case"stop":switch(e.kind){case"stopped":return{kind:"already-stopped"};case"stale":return e.reason==="old-heartbeat"?{kind:"signal-stop",state:e.state}:{kind:"clean-stale",state:e.state};case"live":case"incompatible":return{kind:"signal-stop",state:e.state};default:return st(e)}default:return st(r)}}function Br(r){return r.idleTimeoutMs===0||r.watcher.state!=="idle"?!1:r.nowMs-r.lastActivityAtMs>=r.idleTimeoutMs}function _r(r,e,t){if(!t.isProcessAlive(r))return;t.signalProcess(r);let n=e.stopTimeoutMs??Ki,i=t.now()+n;for(;t.now()<=i;){if(!t.isProcessAlive(r))return;t.sleep(zi)}throw new Error(`scip-query watch service pid ${r} did not stop within ${n}ms.`)}function ot(r,e,t){re(r.statePath,{force:!0}),re(r.activityPath,{force:!0}),ne(r.lockPath)?.pid===e&&!t.isProcessAlive(e)&&re(r.lockPath,{force:!0})}function Or(r,e,t){return`error: scip-query watch is already running for ${at(e)}${t?` (pid ${t.pid}, started ${t.startedAt}; lock: ${r})`:` (lock: ${r})`}. Stop that watcher before starting another.`}function Ji(r){return typeof r=="object"&&r&&"code"in r?r.code:void 0}var Qi={now:Date.now,isProcessAlive:j,spawnServer(r,e,t,n){if(!qi(r))throw new Error(`Watch service helper was not found at ${r}. Run npm run build first.`);$i(process.execPath,[r,e,t,JSON.stringify(n)],{detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"}}).unref()},signalProcess(r){process.kill(r,"SIGTERM")},sleep(r){let e=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(e,0,0,r)}};function st(r){throw new Error(`Unhandled watch service value: ${JSON.stringify(r)}`)}import{existsSync as Yr,lstatSync as ke,readFileSync as ut,readdirSync as Jr,realpathSync as Vr,rmSync as ie,statSync as Xi}from"fs";import{join as R,resolve as $,sep as Kr}from"path";var Zi=3600*1e3,eo=2*1024*1024*1024,to=300*1e3;function ro(r){let e=r.leases.filter(s=>s.managed&&!s.live&&!s.busy),t=no(r.leases,r.locks),n={};for(let s of r.generations)t.has(s.generationId)||(n[s.generationId]=s.unreferencedAt??r.nowMs);let i=r.generations.filter(s=>!t.has(s.generationId)).sort((s,c)=>n[s.generationId]-n[c.generationId]||s.generationId.localeCompare(c.generationId)),o=new Set;for(let s of i)r.nowMs-n[s.generationId]>=r.policy.generationTtlMs&&o.add(s.generationId);let a=r.generations.filter(s=>!o.has(s.generationId)).reduce((s,c)=>s+c.size,0);for(let s of i){if(a<=r.policy.budgetBytes)break;o.has(s.generationId)||(o.add(s.generationId),a-=s.size)}for(let s of o)delete n[s];return{deleteWorktrees:e,deleteGenerations:r.generations.filter(s=>o.has(s.generationId)),deleteLocks:r.locks.filter(s=>!s.live),deleteTemporaries:r.temporaries.filter(s=>!s.live),protectedGenerationIds:[...t].sort(),unreferencedSince:n}}function no(r,e){let t=new Set(r.filter(n=>n.managed&&(n.live||n.busy)).flatMap(n=>[n.lease.baseGenerationId,n.lease.activeGenerationId]).filter(n=>n!==void 0));for(let n of e)n.live&&t.add(n.generationId);return t}function Qr(r,e,t={}){if(!Ut())return{kind:"disabled"};let n=gt(r);if(!n)return{kind:"unavailable"};let i=R(We(),"repositories",n.repositoryId);if(!Yr(i))return{kind:"unavailable"};let o=(t.now??Date.now)(),a=R(i,"gc-state.json"),s=so(a);if(!t.force&&s&&o-Date.parse(s.lastSweepAt)<to)return{kind:"throttled",sweptAt:s.lastSweepAt};let c=vt(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=io(r,i,n.repositoryId,s?.unreferencedSince??{}),d=ro({nowMs:o,...l,policy:{generationTtlMs:t.policy?.generationTtlMs??Zi,budgetBytes:t.policy?.budgetBytes??eo}}),u=0,p=0;for(let m of d.deleteWorktrees){if(!Xr(m.lease))continue;let h=xt(R(m.lease.localCacheDir,"cache-lifecycle.lock"));if(h)try{if(lt(m.lease,!0))continue;try{Gr({projectRoot:m.lease.projectRoot,cacheDir:m.lease.localCacheDir,cliVersion:e})}catch{continue}if(lt(m.lease,!0))continue;ie(m.lease.localCacheDir,{recursive:!0,force:!0}),ie(m.leasePath,{force:!0}),p+=1}finally{h.release()}}for(let m of d.deleteLocks)ie(m.path,{force:!0});for(let m of d.deleteTemporaries)ie(m.path,{recursive:!0,force:!0});for(let m of d.deleteGenerations)ie(m.path,{recursive:!0,force:!0}),u+=m.size;Ct(R(i,"evidence.db"));let g={kind:"swept",sweptAt:new Date(o).toISOString(),deletedWorktrees:p,deletedGenerations:d.deleteGenerations.length,deletedBytes:u,protectedGenerations:d.protectedGenerationIds.length},f={version:1,lastSweepAt:g.sweptAt,unreferencedSince:d.unreferencedSince,lastResult:g};return F(a,f,{spacing:2,trailingNewline:!0}),g}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function io(r,e,t,n){let i=new Set(St(r).map(l=>$(l.path))),o=[];for(let l of ct(R(e,"worktrees"))){if(!l.endsWith(".json"))continue;let d=R(e,"worktrees",l),u=oo(d);if(!u)continue;let p=$(u.projectRoot);o.push({leasePath:d,lease:u,managed:u.repositoryId===t&&Xr(u),live:i.has(p)||Yr(p),busy:lt(u)})}let a=[];for(let l of ct(R(e,"locks"))){let d=/^([a-f0-9]{64})\.lock$/.exec(l);if(!d)continue;let u=R(e,"locks",l),p=dt(u),g=p!==void 0&&j(p),f=d[1];a.push({generationId:f,path:u,live:g})}let s=[],c=[];for(let l of ct(R(e,"generations"))){let d=/^\.tmp-(\d+)-/.exec(l);if(d){let g=R(e,"generations",l),f=Number(d[1]);try{c.push({path:g,size:zr(g),live:Number.isSafeInteger(f)&&j(f)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let u=R(e,"generations",l),p;try{p=ke(u)}catch{continue}!p.isDirectory()||p.isSymbolicLink()||s.push({generationId:l,path:u,size:zr(u),...n[l]===void 0?{}:{unreferencedAt:n[l]}})}return{leases:o,generations:s,locks:a,temporaries:c}}function Xr(r){if(r.ownershipChecksum!==Bt(r)||$(r.localCacheDir)!==$(qt(r.projectRoot)))return!1;let e=$(We()),t=$(R(e,"projects")),n=$(r.localCacheDir);if(!n.startsWith(`${t}${Kr}`))return!1;try{let i=ke(e),o=ke(t),a=ke(n);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink())return!1;let s=Vr(t);return Vr(n).startsWith(`${s}${Kr}`)}catch{return!1}}function lt(r,e=!1){for(let n of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=dt(R(r.localCacheDir,n));if(i!==void 0&&j(i))return!0}let t=dt(B(r.localCacheDir).lockPath);return t!==void 0&&j(t)}function oo(r){try{let e=JSON.parse(ut(r,"utf8"));return e.version!==1||typeof e.repositoryId!="string"||typeof e.worktreeId!="string"||typeof e.projectRoot!="string"||e.treeOid!==void 0&&typeof e.treeOid!="string"||typeof e.localCacheDir!="string"||e.baseGenerationId!==void 0&&typeof e.baseGenerationId!="string"||e.activeGenerationId!==void 0&&typeof e.activeGenerationId!="string"||typeof e.ownershipChecksum!="string"||!/^[a-f0-9]{64}$/.test(e.ownershipChecksum)||typeof e.lastAction!="string"||e.lastReason!==void 0&&typeof e.lastReason!="string"||typeof e.lastSeenAt!="string"?null:e}catch{return null}}function dt(r){try{let e=JSON.parse(ut(r,"utf8"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function so(r){try{let e=JSON.parse(ut(r,"utf8"));return e.version!==1||typeof e.lastSweepAt!="string"||!Number.isFinite(Date.parse(e.lastSweepAt))||!e.unreferencedSince||typeof e.unreferencedSince!="object"||!e.lastResult?null:e}catch{return null}}function ct(r){try{return Jr(r)}catch{return[]}}function zr(r){let e=0,t=[r];for(;t.length>0;){let n=t.pop();for(let i of Jr(n,{withFileTypes:!0})){let o=R(n,i.name);i.isDirectory()?t.push(o):i.isFile()&&(e+=Xi(o).size)}}return e}var lo=1e3,uo=250,po=10;function fo(r){return r==="fresh"?null:{kind:"watch-startup",detail:`index ${r} when watch service started`}}async function mo(r,e,t={}){let n=$r(r,e),i=n.projectRoot,o=V(i);o.watch={...o.watch,...t};let a=he(o);if(!a.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let s=H(i,o),c=B(s.cacheDir),l=Hr(c.lockPath,i);if(!l.acquired)return;let d=Date.now(),u=d,p={state:"idle"},g,f,m,h=pe(s.dbPath),S=!1,M=!1,A=0,P=0,L=0,D=0,C,b,I=er(s.cacheDir),pt=Kt(s.cacheDir);nt(I),it(pt);let Pe=new Ce({openDb:()=>or(i)}),Te=new we({projectRoot:i,currentGeneration:()=>Yt(s.dbPath)}),E=(v=!1)=>{if(!M)return;let q=Date.now();!v&&q-P<lo||(P=q,qr(c.statePath,{version:1,protocolVersion:Ge,pid:k.pid,projectRoot:i,...n.worktreeId?{worktreeId:n.worktreeId}:{},cliVersion:e,startedAt:new Date(d).toISOString(),heartbeatAt:new Date(q).toISOString(),lastActivityAt:new Date(u).toISOString(),...a.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(u+a.idleTimeoutMs).toISOString()},watcher:p,...p.state==="idle"&&g?{indexGeneration:g}:{},...f?{lastRefresh:f}:{},...m?{lastError:m}:{},reindexActivity:h,typescriptSemantic:{...Pe.status(),...C===void 0?{}:{busyUntil:new Date(C).toISOString()}},typescriptIndex:{...Te.status(),...b===void 0?{}:{busyUntil:new Date(b).toISOString()}}}))},G=()=>{u=Date.now()},oe=new ge({projectRoot:i,config:{...o,watch:a},languages:o.languages,onStatus(v){p=v,v.state!=="idle"&&(g=void 0),v.state!=="idle"&&G(),E(!0)},onReindexComplete(){G();let v=Ue(i,o,s);return f=v.lastRefresh,g=v.state==="fresh"?Z(s.dbPath)??void 0:void 0,h=pe(s.dbPath),m=void 0,E(!0),v.state==="fresh"},onRefreshSuppressed(v){Gt(s.dbPath,v),h=pe(s.dbPath)},onError(v){G(),g=void 0,m={at:new Date().toISOString(),message:v.message},E(!0)}}),se=()=>{S=!0};k.once("SIGINT",se),k.once("SIGTERM",se);try{oe.start();let v=Ue(i,o,s);f=v.lastRefresh,g=v.state==="fresh"?Z(s.dbPath)??void 0:void 0;let q=fo(v.state);for(q&&oe.requestRefresh(q,{immediate:!0}),G(),M=!0,E(!0);!S;){let en=jr(pt,Te,{beforeRequest(T){b=T+5e3,E(!0)},afterRequest(){b=void 0,E(!0)}}),tn=Lr(I,Pe,{beforeRequest(T){C=T+5e3,E(!0)},afterRequest(){C=void 0,E(!0)}}),ae=Date.now();if(ae-D>=6e4&&(D=ae,Qr(i,e)),ae-L>=uo){L=ae;let T=Ur(c.activityPath);T&&T.atMs>u&&(u=T.atMs),T?.refreshRequestedAtMs!==void 0&&T.refreshRequestedAtMs>A&&(A=T.refreshRequestedAtMs,G(),oe.requestRefresh({kind:"watch-demand",detail:T.refreshDetail??"stale index observed by a command"},{immediate:!0}))}if((tn>0||en>0)&&(G(),E(!0)),E(),Br({watcher:p,lastActivityAtMs:u,nowMs:Date.now(),idleTimeoutMs:a.idleTimeoutMs}))break;await ho(po)}}finally{k.off("SIGINT",se),k.off("SIGTERM",se),Pe.closeTypeScriptService(),Te.close(),oe.stop(),Zr(c.statePath,{force:!0}),Zr(c.activityPath,{force:!0}),l.release()}}function ho(r){return new Promise(e=>setTimeout(e,r))}var go=k.argv[1]?co(ao(k.argv[1])).href:null;if(go===import.meta.url){let r=k.argv[2],e=k.argv[3],t=yo(k.argv[4]);if(!r||!e)console.error("watch-service: expected <project-root> <cli-version>"),k.exitCode=1;else try{await mo(r,e,t)}catch(n){console.error(`watch-service: ${n instanceof Error?n.message:String(n)}`),k.exitCode=1}}function yo(r){if(!r)return{};try{let e=JSON.parse(r);return e&&typeof e=="object"?e:{}}catch{return{}}}export{mo as runWatchServiceServer,fo as startupRefreshTrigger};
|
|
41
|
+
ORDER BY start_line, end_line`,e)}function ho(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:q(r.symbol),parentTypeName:ee(r.symbol),isFunctionLike:cn(r.symbol),isTypeLike:$(r.symbol)==="type",kind:r.kind??null,documentation:r.documentation??null,enclosingSymbol:r.enclosing_symbol??null}}function fn(r,e={}){return go(r,e.scope)}function go(r,e){return Y(r,{scope:e,includeIgnored:!1}).flatMap(t=>G(r,t)).filter(t=>!r.isIgnored(t.relativePath))}function yo(r,e,t){let n=Oe(r).forFile(e,{text:!0}).text,i=wr(r,e);return i?Ro(t,i,n):n?So(t,n):t}function So(r,e){let t=e.split(/\r?\n/),n=bo(r,t),i=vo(r,n),o=xo(i,t);return Io(r,o)}function bo(r,e){let t=r.some(i=>qe(i.symbol))?Eo(e):null,n=new Map;for(let i of r)n.set(i.symbolId,ko(e,t,i));return n}function vo(r,e){return r.filter(t=>qe(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 xo(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:Do(e,i.definition,i.startLine,a)})}return t}function Io(r,e){return r.map(t=>{let n=e.get(t.symbolId);return n?{...t,startLine:n.startLine,endLine:n.endLine}:t})}function Ro(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(!To(i)||!i.leaf)return un(i,t);let o=n.get(i.leaf);if(!o||o.length===0)return un(i,t);let a=t?Co(i,o,t):null;if(a)return{...i,startLine:a.startLine,endLine:a.endLine};let s=o[0],c=Math.abs(s.startLine-i.startLine);for(let l=1;l<o.length;l+=1){let d=o[l],u=Math.abs(d.startLine-i.startLine);u<c&&(s=d,c=u)}return{...i,startLine:s.startLine,endLine:s.endLine}})}function Co(r,e,t){let n=wo(r.symbol);if(!n)return null;let i=t.split(/\r?\n/),o=new RegExp(`\\b${ce(n)}\\b`);for(let a of e){let s=Po(i,a.startLine);if(s&&o.test(s))return a}return null}function wo(r){return r.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function Po(r,e){for(let t=e;t>=0;t-=1){let n=r[t]?.trim()??"";if(n){if(/^impl\b/.test(n))return Mo(r,t,e);if(/^(?:struct|enum|trait|mod)\b/.test(n))return null}}return null}function Mo(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 To(r){return qe(r.symbol)?!0:$(r.symbol)==="term"&&ee(r.symbol)===null}function un(r,e){if(!e||!r.leaf||$(r.symbol)!=="term"||ee(r.symbol)!==null)return r;let t=ce(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 ko(r,e,t){if(!qe(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 Eo(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 Do(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=Fo(r[l]??"");for(let u of d)u==="{"?(a+=1,c=!0):u==="}"?a=Math.max(0,a-1):u==="("?s+=1:u===")"&&(s=Math.max(0,s-1));if(c&&a===0||!c&&s===0&&l>=o)return l}return o}function Fo(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 qe(r){return r.includes("().")}function A(r,e,t){if(r.has(e))return r.get(e);let n=t();return r.set(e,n),n}import mn from"path";function Ao(r,e){return r.getReferences().map(t=>{let n=t.getNode();return $e(n,e)})}function No(r){let e=r;return typeof e.findReferences=="function"?e.findReferences():[]}function hn(r,e,t,n){let i=[];for(let o of No(r))for(let a of Ao(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 te(i)}function gn(r,e,t,n){let i=[],o=t?.getStart();for(let a of r.getReferences()){let s=a.getNode();re(n,s.getSourceFile().getFilePath())===e&&(o!==void 0&&s.getStart()===o||i.push({location:$e(s,n),node:s}))}return i}function $e(r,e){let t=r.getSourceFile(),n=t.getLineAndColumnAtPos(r.getStart());return{file:re(e,t.getFilePath())??t.getBaseName(),line:n.line-1,column:n.column-1}}function yn(r,e,t){let n=r.getSourceFile(),i=Rt(n,r),o=r.getText(),a=new RegExp(`\\b${ce(o)}\\b`,"g"),s=n.getFullText().split(`
|
|
42
|
+
`),c=[];for(let l=0;l<s.length;l++){if(l===i)continue;let d=s[l]??"";a.lastIndex=0;let u;for(;(u=a.exec(d))!==null;)c.push({file:e,line:l,column:u.index})}return te(c.filter(l=>re(t,mn.join(t,l.file))===e))}function It(r){for(let e=r;e;e=e.getParent()){let t=e.getKindName();if(t.includes("Type")||t==="InterfaceDeclaration"||t==="TypeAliasDeclaration")return!0;if(t==="CallExpression"||t==="NewExpression"||t==="ExpressionStatement")return!1}return!1}function Rt(r,e){return r.getLineAndColumnAtPos(e.getStart()).line-1}function te(r){let e=new Set,t=[];for(let n of r){let i=`${n.file}:${n.line}:${n.column}`;e.has(i)||(e.add(i),t.push(n))}return t}function re(r,e){let t=mn.relative(r||process.cwd(),e).replace(/\\/g,"/");return!t||t.startsWith("..")?null:t}function Sn(r,e,t,n){let i=_o(e,n);return i.size===0?new Map:Lo(r,t,i)}function _o(r,e){let t=new Map;for(let n of G(r,e)){let i=q(n.symbol)??n.leaf;if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push(n)}return t}function Lo(r,e,t){let n=new Map,i=new Map;return e.forEachDescendant(o=>{for(let a of jo(r,o)){let s=t.get(a);if(!s)continue;let c=Rt(e,o);for(let l of s){if(c<l.startLine-1||c>l.endLine+1)continue;let d=Math.abs(c-l.startLine),u=i.get(l.symbolId);u!==void 0&&u<=d||(i.set(l.symbolId,d),n.set(l.symbolId,o))}}}),n}function jo(r,e){let t=[],n=i=>{i&&!t.includes(i)&&t.push(i)};if("getNameNode"in e&&typeof e.getNameNode=="function"){let i=e.getNameNode();n(i?.getText())}if("getName"in e&&typeof e.getName=="function"){let i=e.getName();n(i)}return r.Node.isIdentifier(e)&&n(e.getText()),t}var Oo=ae("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function bn(r,e,t,n){let i=Pt(r,e),o=Ct(i.get(n)??[],t);if(o)return o;let a=[];for(let s of i.values())for(let c of s)((c.leaf||q(c.symbol)||"").includes(n)||c.symbol.includes(n))&&a.push(c);return Ct(a,t)}function wt(r,e,t,n){return Ct(Pt(r,e).get(n)??[],t)}function vn(r,e){let t=new Map;for(let[n,i]of Pt(r,e)){let o=i[0];o&&t.set(n,o)}return t}function Pt(r,e){return Oo.get(r,e,()=>{let t=new Map;for(let n of G(r,e)){let i=n.leaf||q(n.symbol);if(!i)continue;let o=t.get(i);o||(o=[],t.set(i,o)),o.push({...n,leaf:i})}for(let n of t.values())n.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return t})}function Ct(r,e){let t=null,n=Number.POSITIVE_INFINITY;for(let i of r){let o=Math.abs(i.startLine-e);(o<n||o===n&&t&&i.startLine<t.startLine)&&(t=i,n=o)}return t}import Mt from"path";function xn(r,e){let t=new Map,n=null,i=null,o=()=>(i??=Y(r,{extensions:Re}),i),a=()=>(n??=O("typescript.source-file-index",()=>Wo(r.config.projectRoot,e,o()),()=>({projects:e.length,indexedDocuments:o().length})),n),s=c=>Ce(c)?A(t,c,()=>{let l=le(Mt.resolve(r.config.projectRoot,c));for(let{project:d,sourceFiles:u}of a()){let p=u.get(l)??null;if(p||(p=d.addSourceFileAtPathIfExists(l)??null,p&&u.set(le(p.getFilePath()),p)),p)return{project:d,sourceFile:p}}return null}):null;return{sourceFile:c=>s(c)?.sourceFile??null,sourceFileMatch:s,indexedTypeScriptLikeDocuments:o}}function Wo(r,e,t){let n=e.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[le(o.getFilePath()),o]))}));for(let i of t){let o=le(Mt.resolve(r,i));for(let a of n){if(a.sourceFiles.has(o))break;let s=a.project.addSourceFileAtPathIfExists(o)??null;if(s){a.sourceFiles.set(le(s.getFilePath()),s);break}}}return n}function le(r){return Mt.resolve(r)}function Tt(r,e){for(let t of r)if(e===t.name||e.startsWith(`${t.name}/`))return t.name;return null}function In(r){let e=`${r.relativeDir}/src`;return[`${e}/index.ts`,`${e}/index.tsx`,`${e}/index.mts`,`${e}/index.cts`]}import{existsSync as de,readFileSync as qo}from"fs";import x from"path";var kt=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Et(r,e){let n=e?x.dirname(x.join(r,e)):r,i=x.resolve(r);for(;n.startsWith(i);){for(let a of kt){let s=x.join(n,a);if(de(s))return s}let o=x.dirname(n);if(o===n)break;n=o}for(let o of kt){let a=x.join(r,o);if(de(a))return a}return null}function Rn(r){let e=r.config.projectRoot,t=new Set($o(e,r.config.semantic?.typescript?.tsconfigs)),n=Y(r,{includeIgnored:!1,extensions:Re});for(let i of n){let o=Et(e,i);o&&t.add(x.resolve(o))}if(t.size===0){let i=Et(e);i&&t.add(x.resolve(i))}return[...t].filter(i=>!Cn(e,i)).sort((i,o)=>i.localeCompare(o))}function $o(r,e=[]){let t=new Set;for(let n of e){let i=x.isAbsolute(n)?n:x.join(r,n);de(i)&&t.add(x.resolve(i))}for(let n of Go(r))for(let i of kt){let o=x.join(n,i);de(o)&&t.add(x.resolve(o))}if(t.size===0){let n=Et(r);n&&t.add(x.resolve(n))}return[...t].filter(n=>!Cn(r,n)).sort((n,i)=>n.localeCompare(i))}function Go(r){let e=x.join(r,"package.json");if(!de(e))return[];let t;try{t=JSON.parse(qo(e,"utf8"))}catch{return[]}return(Array.isArray(t.workspaces)?t.workspaces:t.workspaces?.packages??[]).flatMap(i=>br(r,i))}function Cn(r,e){let t=x.relative(r,e).replace(/\\/g,"/");return t.startsWith("..")||t.includes("/node_modules/")||t.startsWith("node_modules/")||t.includes("/dist/")||t.startsWith("dist/")}var Bo=32;function En(r,e,t,n={}){return O("typescript.provider.construct",()=>new Ft(r,e,t),()=>({tsconfigs:t.length,reusedProjects:n.reusedProjects===!0}))}var Ft=class{constructor(e,t,n){this.db=e;this.tsMorph=t;this.projects=n;this.workspacePackages=Sr(e.config.projectRoot),this.sourceFiles=xn(e,n)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(e=>e.tsconfigPath)}}importUsage(e){return A(this.importUsageCache,e,()=>{let t=this.sourceFiles.sourceFile(e);if(!t)return[];let n=Uo();return O("typescript.import-usage.file",()=>this.importUsageForSourceFile(e,t,n),()=>({file:e,...n}))})}referencesFor(e){return A(this.referencesCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);return this.referencesForDefinitionNode(e,t)})}referencesForDefinitions(e,t={}){let n=new Map,i=xe(),o=[];for(let d of e){let u=this.referencesCache.get(d.symbolId);u?n.set(d.symbolId,u):o.push(d)}if(o.length===0)return n;let a=o,s=t.exact?[]:o.filter(d=>!Pn(d));if(s.length>=Bo){let d=this.referencesForDefinitionsBySymbolScan(s);for(let u of s){let p=d.get(u.symbolId)??[];this.referencesCache.set(u.symbolId,p),n.set(u.symbolId,p)}if(a=o.filter(u=>Pn(u)),a.length===0)return n}let c=new Map;for(let d of a){let u=c.get(d.relativePath);u?u.push(d):c.set(d.relativePath,[d])}let l=[];for(let[d,u]of c){let p=Mn();O("typescript.references-map.file",()=>{let y=this.definitionNodesForFile(d);for(let f of u){i&&(p.cacheMisses+=1);let h=y.get(f.symbolId)??null;i&&(h?p.nodeHits+=1:p.nodeMisses+=1);try{let m=this.referencesForDefinitionNode(f,h,i?p:void 0);this.referencesCache.set(f.symbolId,m),n.set(f.symbolId,m)}catch{p.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:d,definitions:u.length,...Tn(p)}))}if(l.length>0){let d=this.referencesForDefinitionsBySymbolScan(l);for(let u of l){let p=d.get(u.symbolId)??[];this.referencesCache.set(u.symbolId,p),n.set(u.symbolId,p)}}return n}referenceFragmentsForFiles(e){let t=fn(this.db).filter(o=>Ce(o.relativePath)),n=e.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(t,n);return Er(t,i,n)}referencesForDefinitionsBySymbolScan(e,t){let n=xe(),i=Mn(),o=new Map,a=new Set(e.map(c=>c.symbolId)),s=new Map(e.map(c=>[c.symbolId,c]));for(let c of e)o.set(c.symbolId,[]);return O("typescript.references-map.inverted-scan",()=>{let c=n?S.now():0,l=t?this.packageImportReferencesForFiles(t):this.packageImportReferences();for(let m of e){let g=l.get(m.symbolId)??[];if(g.length>0){let R=o.get(m.symbolId)??[];R.push(...g),o.set(m.symbolId,R)}n&&(i.packageReferenceCount+=g.length)}n&&(i.packageRefsMs+=S.now()-c);let d=new Map,u=new Map,p=this.hierarchyTargetsForDefinitions(e),y=new Set(e.map(m=>m.leaf).filter(Boolean)),f=n?S.now():0;for(let m of t??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(m))continue;let g=this.sourceFiles.sourceFile(m);g&&(n&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(g,m,a,s,p,y,d,u,o,n?i:void 0))}n&&(i.scanMs+=S.now()-f);let h=n?S.now():0;this.addHierarchyMemberReferences(e,o,n?i:void 0),n&&(i.hierarchyMs+=S.now()-h);for(let[m,g]of o){let R=te(g);o.set(m,R),n&&(i.referenceCount+=R.length)}},()=>({definitions:e.length,...Tn(i)})),o}addReferencesFromSourceFileScan(e,t,n,i,o,a,s,c,l,d){let u=this.compilerCheckerForSourceFile(e),p=e.compilerNode,y=Yo(e),f=h=>{if(this.tsMorph.ts.isIdentifier(h)){if(d&&(d.identifiers+=1),!a.has(h.text)&&!y.has(h.text)){this.tsMorph.ts.forEachChild(h,f);return}let m=this.compilerReferenceSymbol(u,h,d);if(m){let g;s.has(m)?g=s.get(m)??null:(g=this.referenceDefinitionFromCompilerSymbol(m),s.set(m,g)),d&&(g?d.targetHits+=1:d.targetMisses+=1);let R=A(c,m,()=>this.compilerSymbolKeys(m)),M=null,k=null,j=g&&n.has(g.symbolId)?i.get(g.symbolId):void 0;if(j&&(M=Dt(p,h),!wn(j,t,M))){let L=p.getLineAndCharacterOfPosition(h.getStart(p));k={file:t,line:L.line,column:L.character};let N=l.get(j.symbolId)??[];N.push(k),l.set(j.symbolId,N),d&&(d.requestedHits+=1)}for(let L of R)for(let N of o.get(L)?.values()??[]){if(M??=Dt(p,h),wn(N,t,M))continue;if(!k){let C=p.getLineAndCharacterOfPosition(h.getStart(p));k={file:t,line:C.line,column:C.character}}let I=l.get(N.symbolId)??[];I.push(k),l.set(N.symbolId,I),d&&(d.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(h,f)};f(p)}hierarchyTargetsForDefinitions(e){let t=new Map;for(let n of e){let i=this.nodeForDefinition(n),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let a=o.parent;if(!this.isHierarchyContainer(a))continue;let s=this.compilerCheckerForSourceFile(i.getSourceFile()),c=s.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(s,a,c))for(let d of this.compilerSymbolKeys(l)){let u=t.get(d)??new Map;u.set(n.symbolId,n),t.set(d,u)}}return t}hierarchyMemberSymbols(e,t,n){let i=new Set,o=new Set,a=(s,c,l)=>{if(!o.has(s)){o.add(s),i.add(c);for(let d of l){let u=d.getProperty(n.name);u&&a(d,u,this.hierarchyAncestorTypesForType(e,d))}}};return a(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}addHierarchyMemberReferences(e,t,n){let i=new Map;for(let o of e){let a=this.nodeForDefinition(o),s=a?.compilerNode;if(!s||!this.isHierarchyMethod(s))continue;let c=s.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(a.getSourceFile()),d=l.getSymbolAtLocation(s.name);if(!d)continue;let u=s.getSourceFile(),p=u.getLineAndCharacterOfPosition(s.name.getStart(u)),y={definition:o,location:{file:o.relativePath,line:p.line,column:p.character}},f=t.get(o.symbolId)??[];for(let m of this.hierarchyMemberSymbols(l,c,d))if(m!==d)for(let g of this.compilerSymbolLocations(m))f.push(g),n&&(n.hierarchyReferences+=1);t.set(o.symbolId,f);let h=this.hierarchyRootMemberSymbols(l,c,d);for(let m of h){let g=i.get(m)??new Map;g.set(o.symbolId,y),i.set(m,g)}n&&(n.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){n&&(n.hierarchyFamilies+=1);for(let{definition:a}of o.values()){let s=t.get(a.symbolId)??[];for(let c of o.values())c.definition.symbolId!==a.symbolId&&(s.push(c.location),n&&(n.hierarchyReferences+=1));t.set(a.symbolId,s)}}}hierarchyRootMemberSymbols(e,t,n){let i=new Set,o=new Set,a=(s,c,l)=>{if(o.has(s))return;o.add(s);let d=!1;for(let u of l){let p=u.getProperty(n.name);p&&(d=!0,a(u,p,this.hierarchyAncestorTypesForType(e,u)))}if(!d)for(let u of this.compilerSymbolKeys(c))i.add(u)};return a(e.getTypeAtLocation(t),n,this.hierarchyAncestorTypes(e,t)),i}compilerSymbolKeys(e){return(e.declarations??[]).map(t=>{let n=t.getSourceFile();return`${n.fileName}\0${t.getStart(n)}\0${e.name}`})}compilerSymbolLocations(e){let t=[];for(let n of e.declarations??[]){let i=n.getSourceFile(),o=re(this.db.config.projectRoot,i.fileName);if(!o)continue;let a=n.name,s=i.getLineAndCharacterOfPosition((a??n).getStart(i));t.push({file:o,line:s.line,column:s.character})}return t}baseTypes(e,t){try{return e.getBaseTypes(t)??[]}catch{return[]}}hierarchyAncestorTypes(e,t){let n=new Set(this.hierarchyAncestorTypesForType(e,e.getTypeAtLocation(t)));for(let i of t.heritageClauses??[])for(let o of i.types)n.add(e.getTypeAtLocation(o));return[...n]}hierarchyAncestorTypesForType(e,t){let n=new Set(this.baseTypes(e,t));for(let i of t.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let a of o.types)n.add(e.getTypeAtLocation(a));return[...n]}isHierarchyMethod(e){return this.tsMorph.ts.isMethodDeclaration(e)||this.tsMorph.ts.isMethodSignature(e)}isHierarchyContainer(e){return this.tsMorph.ts.isClassDeclaration(e)||this.tsMorph.ts.isClassExpression(e)||this.tsMorph.ts.isInterfaceDeclaration(e)}compilerReferenceSymbol(e,t,n){n&&(n.symbolLookups+=1);let i=e.getSymbolAtLocation(t);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return n&&(n.aliasResolutions+=1),e.getAliasedSymbol(i)}catch{return i}}}calleesFor(e){return A(this.calleesCache,e.symbolId,()=>A(this.fileCalleesCache,e.relativePath,()=>this.calleeMapForFile(e.relativePath)).get(e.symbolId)??[])}calleesForDefinitions(e){let t=new Map,n=new Map;for(let i of e){let o=n.get(i.relativePath);o?o.push(i):n.set(i.relativePath,[i])}for(let[i,o]of n){let a=this.fileCalleesCache.get(i),s=new Set(o.map(l=>l.symbolId)),c=a??this.calleeMapForFile(i,s);for(let l of o){let d=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,d),t.set(l.symbolId,d)}}return t}referencesForDefinitionNode(e,t,n){let i=n?S.now():0,o=this.packageImportReferencesForDefinition(e);if(n&&(n.packageRefsMs+=S.now()-i,n.packageReferenceCount+=o.length),!t)return o;let a=n?S.now():0,s=hn(t,e,o,this.db.config.projectRoot);return n&&(n.semanticRefsMs+=S.now()-a,n.referenceCount+=s.length),s}signatureFor(e){return A(this.signatureCache,e.symbolId,()=>{let t=this.nodeForDefinition(e);if(!t||!this.tsMorph.Node.isFunctionDeclaration(t)&&!this.tsMorph.Node.isMethodDeclaration(t)&&!this.tsMorph.Node.isArrowFunction(t)&&!this.tsMorph.Node.isFunctionExpression(t)&&!this.tsMorph.Node.isConstructorDeclaration(t))return null;let n=t.getType().getCallSignatures()[0];if(!n)return null;let i=n.getParameters().map(a=>{let s=a.getDeclarations()[0],c=s?a.getTypeAtLocation(s).getText(s):a.getValueDeclaration()?.getType().getText()??"unknown";return kn(c)}),o=n.getReturnType().getText(t);return`(${i.join(",")})=>${kn(o)}`})}importUsageForSourceFile(e,t,n){let i=[],o=new Map;for(let a of t.getImportDeclarations()){n.declarations+=1;let s=pt(this.db,e,a.getModuleSpecifierValue()),c=a.getImportClause()?.isTypeOnly()??!1;for(let l of At(a)){n.entries+=1;let d=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(d?n.bindingSymbols+=1:n.missingBindingSymbols+=1);let u={sourcePath:s,entry:l,typeOnlyDeclaration:c,bindingSymbol:d,references:[]};if(i.push(u),c||!l.localName||!d)continue;let p=o.get(l.localName);p?p.push(u):o.set(l.localName,[u])}}return o.size>0&&t.forEachDescendant(a=>{if(a.getKindName()!=="Identifier")return;let s=o.get(a.getText());if(!s||Vo(a))return;n.scannedIdentifiers+=1;let c=a.getSymbol()?.compilerSymbol;if(n.symbolLookups+=1,!!c){for(let l of s)if(l.bindingSymbol===c){l.references.push({location:$e(a,this.db.config.projectRoot),node:a}),n.matchedReferences+=1;break}}}),i.map(a=>a.typeOnlyDeclaration?Ho(e,a.sourcePath,a.entry):a.entry.identifier&&!a.bindingSymbol?(n.fallbackEntries+=1,this.valueImportUsageForEntry(e,a.sourcePath,a.entry)):this.valueImportUsageFromLocations(e,a.sourcePath,a.entry,a.references))}valueImportUsageForEntry(e,t,n){let i=n.identifier?n.identifier.findReferences():[],o=[];for(let a of i)for(let s of gn(a,e,n.identifier,this.db.config.projectRoot))o.push(s);return this.valueImportUsageFromLocations(e,t,n,o)}valueImportUsageFromLocations(e,t,n,i){let o=i.some(c=>!It(c.node)),a=i.some(c=>It(c.node)),s=n.isTypeOnly;return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:s,isUsed:s||i.length>0,isTypeUsed:s||a,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(e){return this.packageImportReferences().get(e.symbolId)??[]}packageImportReferencesForFiles(e){let t=new Map,n=new Set;for(let o of e){let a=this.sourceFiles.sourceFile(o);if(a)for(let s of a.getImportDeclarations()){let c=Tt(this.workspacePackages,s.getModuleSpecifierValue());c&&n.add(c)}}if(n.size===0)return t;let i=this.packageExportsForNames(n);for(let o of e)this.addPackageImportReferencesForDocument(t,i,o);for(let[o,a]of t)t.set(o,te(a));return t}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let e=new Map,t=this.packageExports();for(let n of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(e,t,n);for(let[n,i]of e)e.set(n,te(i));return this.packageImportReferenceIndex=e,e}addPackageImportReferencesForDocument(e,t,n){if(this.db.isIgnored(n))return;let i=this.sourceFiles.sourceFileMatch(n);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(e,t,n,o)}addPackageImportReferencesForDeclaration(e,t,n,i){let o=Tt(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let a=t.get(o);if(a)for(let s of At(i)){if(s.kind!=="named"||!s.identifier)continue;let c=a.get(s.importedName);if(!c||c.size===0)continue;let l=yn(s.identifier,n,this.db.config.projectRoot);l.length>0&&Qo(e,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(e=>e.name))),this.packageExportIndex)}packageExportsForNames(e){let t=new Map;for(let n of this.workspacePackages){if(!e.has(n.name))continue;let i=new Map;for(let o of In(n))this.collectPackageExports(n,o,i,new Set);i.size>0&&t.set(n.name,i)}return t}collectPackageExports(e,t,n,i){if(i.has(t))return;i.add(t);let o=this.sourceFiles.sourceFile(t);if(o)for(let a of o.getExportDeclarations()){let s=a.getModuleSpecifierValue(),c=s?pt(this.db,t,s):t;if(!c||!c.startsWith(`${e.relativeDir}/src/`))continue;let l=a.getNamedExports();if(l.length===0){if(a.isNamespaceExport())continue;this.collectPackageExports(e,c,n,i);continue}for(let d of l){let u=d.getNameNode().getText(),p=d.getAliasNode()?.getText()??u,y=this.indexedDefinitionByLeaf(c,u);if(!y)continue;let f=n.get(p);f||(f=new Set,n.set(p,f)),f.add(y.symbolId)}}}indexedDefinitionByLeaf(e,t){return A(this.indexedDefinitionLeafCache,e,()=>vn(this.db,e)).get(t)??null}nodeForDefinition(e){return A(this.definitionNodeCache,e.symbolId,()=>this.definitionNodesForFile(e.relativePath).get(e.symbolId)??null)}definitionNodesForFile(e){return A(this.fileDefinitionNodeCache,e,()=>{let t=this.sourceFiles.sourceFile(e);return t?Sn(this.tsMorph,this.db,t,e):new Map})}referenceDefinitionFromCompilerSymbol(e){return this.definitionFromCompilerSymbol(e,void 0,!0)}definitionFromCompilerSymbol(e,t,n=!1){let i=e.name,o=t?S.now():0,a=e.declarations??[];t&&(t.declarationsMs+=S.now()-o,t.declarationChecks+=a.length);for(let s of a){let c=t?S.now():0,l=s.getSourceFile(),d=re(this.db.config.projectRoot,l.fileName),u=l.getLineAndCharacterOfPosition(s.getStart(l)).line;if(t&&(t.declarationLocationMs+=S.now()-c),!d||this.db.isIgnored(d))continue;let p=t?S.now():0,y=this.compilerDeclarationName(s),f=n?wt(this.db,d,u,i)??(y&&y!==i?wt(this.db,d,u,y):null):bn(this.db,d,u,i);if(t&&(t.indexedLookupMs+=S.now()-p),f)return{symbolId:f.symbolId,symbol:f.symbol,file:f.relativePath,line:f.startLine}}return null}compilerDeclarationName(e){let t=e.name;return t&&this.tsMorph.ts.isIdentifier(t)?t.text:null}calleeMapForFile(e,t){let n=xe(),i=0,o=0,a=0,s=0,c=0,l=0,d=0,u=0,p=n?Jo():void 0;return O("typescript.callee-map.file",()=>{let y=n?S.now():0,f=this.sourceFiles.sourceFile(e);if(n&&(c=Math.round(S.now()-y)),!f)return new Map;let h=n?S.now():0,m=G(this.db,e).sort((I,C)=>I.startLine-C.startLine||C.endLine-I.endLine);if(n&&(l=Math.round(S.now()-h)),i=m.length,m.length===0)return new Map;let g=new Map,R=n?S.now():0,M=this.compilerCheckerForSourceFile(f),k=f.compilerNode;n&&(d=Math.round(S.now()-R));let j=new Map,L=I=>{if(this.tsMorph.ts.isCallExpression(I)||this.tsMorph.ts.isNewExpression(I)){n&&(o+=1);let C=this.semanticCalleeForCallNode(M,k,m,I,j,t,p);C&&(n&&(a+=1),Ko(g,C.callerId,C.target))}this.tsMorph.ts.forEachChild(I,L)},N=n?S.now():0;L(k),n&&(u=Math.round(S.now()-N));for(let[I,C]of g)g.set(I,Zo(C));return s=g.size,g},()=>({relativePath:e,definitions:i,callNodes:o,resolvedCallees:a,outputRows:s,requestedDefinitions:t?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:d,traversalMs:u,...p?Xo(p):{}}))}semanticCalleeForCallNode(e,t,n,i,o,a,s){let c=s?S.now():0,l=zo(n,Dt(t,i));if(s&&(s.callerLookupMs+=S.now()-c),!l)return null;if(a&&!a.has(l.symbolId))return s&&(s.skippedUnrequestedCallers+=1),null;let d=i.expression,u=this.compilerSymbolForExpression(e,d,s),p=null;if(u)if(s&&(s.targetSymbolHits+=1),o.has(u))s&&(s.compilerSymbolCacheHits+=1),p=o.get(u)??null;else{s&&(s.compilerSymbolCacheMisses+=1);let y=s?S.now():0;p=this.definitionFromCompilerSymbol(u,s),s&&(s.targetLookupMs+=S.now()-y),o.set(u,p)}else s&&(s.targetMisses+=1);return p?{callerId:l.symbolId,target:{symbol:p.symbol,file:p.file,line:p.line}}:null}compilerSymbolForExpression(e,t,n){let i=n?S.now():0,o=e.getSymbolAtLocation(t);if(n&&(n.expressionSymbolMs+=S.now()-i),o)return o;n&&(n.typeFallbacks+=1);let a=n?S.now():0,s=e.getTypeAtLocation(t).getSymbol();return n&&(n.typeSymbolMs+=S.now()-a),s}compilerCheckerForSourceFile(e){let t=e.getProject(),n=this.compilerCheckerCache.get(t);return n||(n=t.getTypeChecker().compilerObject,this.compilerCheckerCache.set(t,n)),n}};function At(r){let e=[],t=r.getDefaultImport();t&&e.push({identifier:t,importedName:"default",localName:t.getText(),kind:"default",isTypeOnly:r.getImportClause()?.isTypeOnly()??!1});let n=r.getNamespaceImport();n&&e.push({identifier:n,importedName:"*",localName:n.getText(),kind:"namespace",isTypeOnly:r.getImportClause()?.isTypeOnly()??!1});for(let i of r.getNamedImports()){let o=i.getNameNode(),s=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);e.push({identifier:s,importedName:o.getText(),localName:s?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(r.getImportClause()?.isTypeOnly()??!1)})}return e.length===0&&e.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),e}function Ho(r,e,t){return{importer:r,sourcePath:e,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function Uo(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function Vo(r){for(let e=r;e;e=e.getParent())if(e.getKindName()==="ImportDeclaration")return!0;return!1}function Ko(r,e,t){let n=r.get(e);n||(n=[],r.set(e,n)),n.push(t)}function Yo(r){let e=new Set;for(let t of r.getImportDeclarations())for(let n of At(t))n.localName&&e.add(n.localName);return e}function zo(r,e){let t=null;for(let n of r)e<n.startLine||e>n.endLine||(!t||n.startLine>=t.startLine)&&(t=n);return t}function Dt(r,e){return r.getLineAndCharacterOfPosition(e.getStart(r)).line}function wn(r,e,t){return e===r.relativePath&&t>=r.startLine&&t<=r.endLine}function Pn(r){return r.symbol.includes("#")?$(r.symbol)==="type"&&r.relativePath.endsWith(".d.ts"):!1}function Jo(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function Xo(r){return{...r,callerLookupMs:Math.round(r.callerLookupMs),expressionSymbolMs:Math.round(r.expressionSymbolMs),typeSymbolMs:Math.round(r.typeSymbolMs),targetLookupMs:Math.round(r.targetLookupMs),declarationsMs:Math.round(r.declarationsMs),declarationLocationMs:Math.round(r.declarationLocationMs),indexedLookupMs:Math.round(r.indexedLookupMs)}}function Mn(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function Tn(r){return{...r,scanMs:Math.round(r.scanMs),packageRefsMs:Math.round(r.packageRefsMs),semanticRefsMs:Math.round(r.semanticRefsMs),hierarchyMs:Math.round(r.hierarchyMs)}}function Qo(r,e,t){for(let n of e){let i=r.get(n)??[];i.push(...t),r.set(n,i)}}function Zo(r){let e=new Set,t=[];for(let n of r){let i=`${n.symbol}|${n.file}|${n.line}`;e.has(i)||(e.add(i),t.push(n))}return t}function kn(r){return r.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}var Ge=class{loadModule;discoverTsconfigs;createProjects;createProvider;db;module=null;projects=null;provider=null;stats={providerRequests:0,sessionsCreated:0,sessionsReused:0,sessionsRefreshed:0,sessionsReplaced:0,projectsCreated:0};constructor(e,t={}){this.db=e,this.loadModule=t.loadModule??Tr,this.discoverTsconfigs=t.discoverTsconfigs??Rn,this.createProjects=t.createProjects??kr,this.createProvider=t.createProvider??((n,i,o)=>En(n,i,o,{reusedProjects:!0}))}semanticProvider(){return this.stats.providerRequests+=1,this.provider?(this.stats.sessionsReused+=1,this.provider):this.createSession()}advanceGeneration(e,t){let n=es(t);return this.provider?.dispose?.(),this.provider=null,this.db=e,this.projects?n.mode==="replace"?(this.projects=null,this.module=null,this.stats.sessionsReplaced+=1,n):(n.mode==="refresh"&&(ts(this.projects,e.config.projectRoot,n),this.stats.sessionsRefreshed+=1),n):n}snapshotStats(){return{...this.stats}}dispose(){this.provider?.dispose?.(),this.provider=null,this.projects=null,this.module=null}createSession(){let e=this.module??this.loadModule();if(!e)return this.provider=mt("ts-morph is not installed"),this.provider;if(this.module=e,!this.projects){let t=this.discoverTsconfigs(this.db);if(t.length===0)return this.provider=mt("no tsconfig found"),this.provider;this.projects=this.createProjects(e,t),this.stats.projectsCreated+=this.projects.length}return this.provider=this.createProvider(this.db,e,this.projects),this.stats.sessionsCreated+=1,this.provider}};function es(r){let e=new Set;r.projectIdentityChanged&&e.add("project-identity-changed");for(let o of r.uncertainty)e.add(o);for(let o of r.changes)o.inputKind!=="source"&&e.add(`${o.inputKind}-input-changed`);if(e.size>0)return{mode:"replace",addedFiles:[],modifiedFiles:[],deletedFiles:[],reasons:[...e].sort()};let t=Nt(r.changes,"added"),n=Nt(r.changes,"modified"),i=Nt(r.changes,"deleted");return{mode:t.length+n.length+i.length===0?"reuse":"refresh",addedFiles:t,modifiedFiles:n,deletedFiles:i,reasons:[]}}function Nt(r,e){return r.filter(t=>t.kind===e).map(t=>t.path).sort()}function ts(r,e,t){for(let n of r){for(let i of t.deletedFiles)n.project.getSourceFile(Dn(e,i))?.forget();for(let i of t.modifiedFiles){let o=n.project.getSourceFile(Dn(e,i));o&&o.refreshFromFileSystemSync()}t.addedFiles.length>0&&n.project.addSourceFilesFromTsConfig(n.tsconfigPath)}}var Be=class{openDb;createHost;generationIdentity;readSnapshot;now;db=null;host=null;generation=null;snapshot=null;requests=0;lastRequestAtMs=null;lastError=null;available=null;constructor(e){this.openDb=e.openDb,this.createHost=e.createHost??(t=>new Ge(t)),this.generationIdentity=e.generationIdentity?t=>e.generationIdentity(t.config.dbPath):t=>t.generation.identity,this.readSnapshot=e.readSnapshot?t=>e.readSnapshot(t.config.dbPath):os,this.now=e.now??Date.now}handle(e,t){try{this.syncGeneration(e);let n=this.host.semanticProvider();switch(this.available=n.availability().available,this.requests+=1,this.lastRequestAtMs=this.now(),this.lastError=null,t.kind){case"availability":return n.availability();case"import-usage":return n.importUsage(t.file);case"references":return[...ns(n,t.definitions,{exact:t.exact===!0})];case"reference-fragments":if(!n.referenceFragmentsForFiles)throw new Error("TypeScript provider does not support reference fragments.");return[...n.referenceFragmentsForFiles(t.files)];case"callees":return[...is(n,t.definitions)];case"signature":return n.signatureFor(t.definition);default:return as(t)}}catch(n){throw this.lastError=n instanceof Error?n.message:String(n),n}}status(e){let t=this.host?.snapshotStats();return{protocolVersion:Z,state:this.lastError?"error":this.host?this.available?"ready":"unavailable":"idle",requests:this.requests,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastError?{lastError:this.lastError}:{},sessionsCreated:t?.sessionsCreated??0,sessionsReused:t?.sessionsReused??0,sessionsRefreshed:t?.sessionsRefreshed??0,sessionsReplaced:t?.sessionsReplaced??0,projectsCreated:t?.projectsCreated??0,...e?{mailbox:e}:{}}}closeTypeScriptService(){this.host?.dispose(),this.db?.close(),this.host=null,this.db=null,this.generation=null,this.snapshot=null,this.available=null}syncGeneration(e){if(this.generation===e&&this.host&&this.db)return;let t=this.openDb(),n=this.generationIdentity(t);if(!n||n!==e)throw t.close(),new Error("TypeScript semantic request does not match the currently published index generation.");let i=this.readSnapshot(t);if(!this.host||!this.db)this.db=t,this.host=this.createHost(t);else{let o=this.db;this.host.advanceGeneration(t,ss(this.snapshot,i)),this.db=t,o.close()}this.generation=n,this.snapshot=i,this.available=null}};function _t(r){Me(r)}function An(r,e,t={}){_t(r);let n=t.nowMs??Date.now(),i=Te(r,{ownerId:t.ownerId??cs,nowMs:n,limits:t.limits,owner:ls,liveness:ds}),o=0;for(let a of i){let s=a.requestId,c=null;try{let l=en(ke(a,t.limits));if(s=l.id,s!==a.requestId)throw new Error("TypeScript semantic request identity does not match its mailbox path.");if(l.deadlineAtMs<n)throw new Error("TypeScript semantic request expired before processing.");c=tr(),it(l.profileEnvironment??{}),t.beforeRequest?.(l.deadlineAtMs);let d=e.handle(l.generation,l.request);Ee(r,a,{ok:!0,protocolVersion:Z,id:s,generation:l.generation,response:d},{nowMs:n,limits:t.limits})}catch(l){let d=l instanceof Error?l.message:String(l);De(r,a,{ok:!1,protocolVersion:Z,id:s,error:d},d,{nowMs:n,limits:t.limits})}finally{c&&it(c),t.afterRequest?.(),o+=1}}return o}function Nn(r){return Fe(r)}function ns(r,e,t){return r.referencesForDefinitions?.(e,t)??new Map(e.map(n=>[n.symbolId,r.referencesFor(n)]))}function is(r,e){return r.calleesForDefinitions?.(e)??new Map(e.map(t=>[t.symbolId,r.calleesFor(t)]))}function os(r){if(!r.generation.metadataRaw)return null;let e=ve(r.generation.metadataRaw);return e.kind!=="legacy"&&e.kind!=="supported"||!e.capabilities.usableForEvidenceCache?null:Jt(e.metadata.fingerprint)}function ss(r,e){return e?Xt(r,e):{version:1,changes:[],projectIdentityChanged:!0,uncertainty:["prior-snapshot-unavailable"]}}function as(r){throw new Error(`Unhandled TypeScript semantic request: ${JSON.stringify(r)}`)}var cs=`typescript-semantic-${process.pid}-${rs()}`,Fn=D(process.pid),ls={pid:process.pid,...Fn?{processIdentity:Fn}:{}},ds={isProcessAlive:F,readProcessIdentity:D};import{randomUUID as us}from"crypto";import{resolve as ps}from"path";var He=class{projectRoot;currentGeneration;createEmitter;wallNow;monotonicNow;active=null;requests=0;sessionsCreated=0;sessionsReplaced=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(e){this.projectRoot=ps(e.projectRoot),this.currentGeneration=e.currentGeneration,this.createEmitter=e.createEmitter??Or,this.wallNow=e.wallNow??e.now??Date.now,this.monotonicNow=e.monotonicNow??e.now??T}handle(e,t){let n=this.monotonicNow();try{if(this.currentGeneration()!==e)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(t);if(i.emitter.producerIdentity!==t.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),a=i.emitter.advance({modifiedFiles:t.modifiedFiles,affectedFiles:t.affectedFiles}),s=this.monotonicNow()-n;return this.requests+=1,this.lastRequestAtMs=this.wallNow(),this.lastDurationMs=s,this.lastError=null,this.unavailable=!1,{producerIdentity:a.producerIdentity,cold:a.stats.initializations>o.initializations,durationMs:s,fragments:a.fragments.map(c=>({relativePath:c.relativePath,bytesBase64:c.bytes===null?null:Buffer.from(c.bytes).toString("base64"),occurrences:c.occurrences,symbols:c.symbols,referenceFragments:c.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(e){let t=this.active?.emitter.snapshotStats();return{protocolVersion:Ae,state:this.unavailable?"unavailable":this.lastError?"error":this.active?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,initializations:t?.initializations??0,programUpdates:t?.programUpdates??0,documentsEmitted:t?.documentsEmitted??0,documentsRemoved:t?.documentsRemoved??0,...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{},...e?{mailbox:e}:{}}}close(){this.active=null}emitterFor(e){let t=`${e.tsconfigPath}\0${e.projectArgument}`;if(this.active&&this.active.sessionKey===t&&this.active.projectIdentity===e.projectIdentity)return this.active;let n=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:e.tsconfigPath,projectRoot:e.projectArgument});if(!n.available)throw this.unavailable=!0,new Error(n.reason);return this.active&&(this.sessionsReplaced+=1),this.active={sessionKey:t,projectIdentity:e.projectIdentity,emitter:n.emitter},this.sessionsCreated+=1,this.active}};function Lt(r){Me(r)}function Ln(r,e,t={}){Lt(r);let n=t.nowMs??Date.now(),i=Te(r,{ownerId:t.ownerId??fs,nowMs:n,limits:t.limits,owner:ms,liveness:hs}),o=0;for(let a of i){let s=a.requestId;try{let c=Gr(ke(a,t.limits));if(s=c.id,s!==a.requestId)throw new Error("TypeScript index request identity does not match its mailbox path.");if(c.deadlineAtMs<n)throw new Error("TypeScript index request expired before processing.");t.beforeRequest?.(c.deadlineAtMs);let l=e.handle(c.baseGeneration,c.request);Ee(r,a,{ok:!0,protocolVersion:Ae,id:s,baseGeneration:c.baseGeneration,response:l},{nowMs:n,limits:t.limits})}catch(c){let l=c instanceof Error?c.message:String(c);De(r,a,{ok:!1,protocolVersion:Ae,id:s,error:l},l,{nowMs:n,limits:t.limits})}finally{t.afterRequest?.(),o+=1}}return o}function jn(r){return Fe(r)}var fs=`typescript-index-${process.pid}-${us()}`,_n=D(process.pid),ms={pid:process.pid,..._n?{processIdentity:_n}:{}},hs={isProcessAlive:F,readProcessIdentity:D};import{spawn as Es}from"child_process";import{existsSync as Ds,readFileSync as Fs,rmSync as ei}from"fs";import{dirname as ql,resolve as Ht}from"path";import{fileURLToPath as Gl}from"url";import{createHash as gs,randomUUID as jt}from"crypto";import{existsSync as ys,linkSync as Ss,mkdirSync as On,readFileSync as bs,readdirSync as vs,rmSync as ne}from"fs";import{basename as xs,dirname as Is,join as v}from"path";var B=1,Rs=10*6e4,Cs=10080*6e4,Ve="requests",ue="claims",Ue="completions",qn="staging";function $n(r,e,t={}){let n=t.now?.()??new Date,i=Ps(t.ttlMs),o=Ms(t.idempotencyKey),a=o?`key-${gs("sha256").update(o).digest("hex")}`:`request-${(t.randomId??jt)()}`,s={version:B,requestId:a,...o?{idempotencyKey:o}:{},createdAt:n.toISOString(),deadlineAt:new Date(n.getTime()+i).toISOString(),detail:e.trim().slice(0,2048)||"stale index observed by a command"},c=Xn(r,a);if(qt(r,c,s,t.onStage))return{disposition:"accepted",request:s};let d=Wt(c);if(!d)throw new Error(`Watch refresh request identity ${a} exists but is malformed.`);return{disposition:"duplicate",request:d}}function Gn(r,e={}){let t=e.now?.()??new Date,n=`claim-${(e.randomId??jt)()}`,i=Math.max(1,Math.floor(e.limit??64)),o=Yn(r).sort(Ts),a=[];for(let s of o){if(a.length>=i)break;if(Wn(r,s.requestId))continue;if(Date.parse(s.deadlineAt)<=t.getTime()){Kn(r,{version:B,requestId:s.requestId,outcome:"expired",completedAt:t.toISOString()});continue}let c={version:B,requestId:s.requestId,claimId:n,claimedAt:t.toISOString()};if(qt(r,Qn(r,s.requestId),c)){if(Wn(r,s.requestId)){zn(r,s.requestId,n);continue}a.push(s)}}return{claimId:n,requests:a}}function Bn(r,e,t=()=>new Date,n){let i=t().toISOString();for(let o of e.requests)Kn(r,{version:B,requestId:o.requestId,claimId:e.claimId,outcome:"completed",completedAt:i});n?.("after-completion"),Ke(r,e),n?.("after-claim-release")}function Ke(r,e){for(let t of e.requests)zn(r,t.requestId,e.claimId)}function Hn(r){let e=0;for(let t of H(v(r,ue)))ne(t,{force:!0}),e++;return e>0&&K(v(r,ue)),Jn(r),e}function Ot(r){let e=Yn(r),t=new Map,n=ws(v(r,Ve),Wt);for(let c of H(v(r,Ue))){let l=Ye(c);if(!l){n++;continue}t.set(l.requestId,l)}let i=new Set;for(let c of H(v(r,ue))){let l=Vn(c);if(!l){n++;continue}i.add(l.requestId)}let o=e.filter(c=>!t.has(c.requestId)&&!i.has(c.requestId)),a=[...t.values()].filter(c=>c.outcome==="completed").length,s=[...t.values()].filter(c=>c.outcome==="expired").length;return{pending:o.length,claimed:e.filter(c=>!t.has(c.requestId)&&i.has(c.requestId)).length,completed:a,expired:s,invalid:n,...o.length>0?{oldestPendingAt:o.map(c=>c.createdAt).reduce((c,l)=>ks(c,l))}:{}}}function Un(r,e={}){let t=(e.now?.()??new Date).getTime(),n=Math.max(0,e.retentionMs??Cs),i=0;for(let o of H(v(r,Ue))){let a=Ye(o);!a||t-Date.parse(a.completedAt)<n||(ne(o,{force:!0}),ne(Xn(r,a.requestId),{force:!0}),i++)}return i>0&&(K(v(r,Ue)),K(v(r,Ve))),Jn(r),i}function Wt(r){return $t(r,e=>{let t=e;return t.version===B&&pe(t.requestId)&&(t.idempotencyKey===void 0||typeof t.idempotencyKey=="string")&&se(t.createdAt)&&se(t.deadlineAt)&&Date.parse(t.deadlineAt)>=Date.parse(t.createdAt)&&typeof t.detail=="string"&&t.detail.length>0})}function Vn(r){return $t(r,e=>{let t=e;return t.version===B&&pe(t.requestId)&&pe(t.claimId)&&se(t.claimedAt)})}function Ye(r){return $t(r,e=>{let t=e;return t.version===B&&pe(t.requestId)&&(t.claimId===void 0||pe(t.claimId))&&(t.outcome==="completed"||t.outcome==="expired")&&se(t.completedAt)})}function Kn(r,e){let t=Zn(r,e.requestId);if(qt(r,t,e))return;let n=Ye(t);if(!n||n.requestId!==e.requestId||n.outcome!==e.outcome)throw new Error(`Watch refresh completion ${e.requestId} conflicts with an existing record.`)}function qt(r,e,t,n){let i=v(r,qn),o=Is(e);On(i,{recursive:!0}),On(o,{recursive:!0});let a=v(i,`${xs(e)}.${process.pid}.${jt()}.tmp`);try{Ie(a,t,{spacing:2,trailingNewline:!0}),n?.("after-staged");try{Ss(a,e)}catch(s){if(s.code==="EEXIST")return!1;throw s}return K(o),n?.("after-published"),!0}finally{ne(a,{force:!0})}}function Yn(r){let e=[];for(let t of H(v(r,Ve))){let n=Wt(t);n&&e.push(n)}return e}function zn(r,e,t){let n=Qn(r,e),i=Vn(n);!i||i.claimId!==t||(ne(n,{force:!0}),K(v(r,ue)))}function Jn(r){for(let e of H(v(r,qn),".tmp"))ne(e,{force:!0})}function ws(r,e){return H(r).filter(t=>!e(t)).length}function H(r,e=".json"){return ys(r)?vs(r,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(e)).map(t=>v(r,t.name)).sort():[]}function $t(r,e){try{let t=JSON.parse(bs(r,"utf8"));return e(t)?t:null}catch{return null}}function Xn(r,e){return v(r,Ve,`${e}.json`)}function Qn(r,e){return v(r,ue,`${e}.json`)}function Zn(r,e){return v(r,Ue,`${e}.json`)}function Wn(r,e){return Ye(Zn(r,e))!==null}function Ps(r){if(r===void 0)return Rs;if(!Number.isFinite(r)||r<=0)throw new Error("Watch refresh request ttlMs must be positive.");return Math.floor(r)}function Ms(r){let e=r?.trim();return e?e.slice(0,512):void 0}function pe(r){return typeof r=="string"&&/^[a-z0-9][a-z0-9-]{0,127}$/i.test(r)}function Ts(r,e){return Date.parse(r.createdAt)-Date.parse(e.createdAt)||r.requestId.localeCompare(e.requestId)}function ks(r,e){return Date.parse(e)<Date.parse(r)?e:r}var As=2e3,Ns=10;function ri(r,e,t){let n=st(Ht(r));if(t&&st(t.projectRoot)===n)return{projectRoot:n,worktreeKind:"git",worktreeId:t.worktreeId,cliVersion:e};let i=or(n);if(i.kind==="error")throw new Error(`Could not establish Git worktree identity for ${n}: ${i.message}`);return i.kind==="non-git"?{projectRoot:n,worktreeKind:"non-git",cliVersion:e}:{projectRoot:n,worktreeKind:"git",worktreeId:i.identity.worktreeId,cliVersion:e}}function ni(r){let e=r.runtime??js,t=J(r.cacheDir),n=Hr(t.statePath),i=n?e.isProcessAlive(n.pid)?{kind:"live",state:n}:{kind:"stale",state:n,reason:"dead-process"}:{kind:"stopped"},o=_s("stop",i);if(o.kind==="signal-stop")return ti(o.state,r,e),Gt(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};if(o.kind==="clean-stale")return Gt(t,o.state.pid,e),{disposition:"stopped",pid:o.state.pid};let a=ai(t.lockPath);return o.kind==="already-stopped"&&a&&e.isProcessAlive(a.pid)?(ti(a,r,e),Gt(t,a.pid,e),{disposition:"stopped",pid:a.pid}):{disposition:"already-stopped"}}function ii(r,e){Ie(r,e)}function oi(r){try{let e=JSON.parse(Fs(r,"utf8"));return e.version!==1||!Ne(e.at)||e.refreshRequestedAt!==void 0&&!Ne(e.refreshRequestedAt)||e.refreshDetail!==void 0&&typeof e.refreshDetail!="string"?null:{atMs:Date.parse(e.at),...e.refreshRequestedAt===void 0?{}:{refreshRequestedAtMs:Date.parse(e.refreshRequestedAt)},...e.refreshDetail===void 0?{}:{refreshDetail:e.refreshDetail}}}catch{return null}}function si(r,e,t={}){let n=t.pid??process.pid,i=t.isProcessAlive??F,o=()=>{},a=t.readProcessIdentity??D,s=t.now??(()=>new Date),c={...at,wallNow:()=>s().getTime(),isProcessAlive:i,readProcessIdentity:a},l=cr(r,{kind:"watch",pid:n,processIdentity:a(n),detail:{projectRoot:Ht(e)},parseLegacy:ze,runtime:c});if(l.kind==="contended"){let d=ci(l.observation);return{acquired:!1,lockPath:r,message:Ls(r,e,d),release:o}}return{acquired:!0,lockPath:r,message:"",release:()=>{l.lock.release()}}}function ai(r){return ci(ct(r,{parseLegacy:ze}))}var ze=r=>{let e=li(r);return e?{pid:e.pid,...e.processIdentity?{processIdentity:e.processIdentity}:{}}:null};function ci(r){if(r.state==="valid"&&r.record?.kind==="watch"){let e=r.record.detail?.projectRoot;return typeof e!="string"?null:{version:1,pid:r.record.pid,...r.record.processIdentity?{processIdentity:r.record.processIdentity}:{},projectRoot:e,startedAt:r.record.startedAt}}return li(r.parsed)}function li(r){try{let e=r;if(e.version!==1||typeof e.pid!="number"||!Number.isInteger(e.pid)||e.pid<=0||typeof e.projectRoot!="string"||!Ne(e.startedAt))return null;let t=e.processIdentity===void 0?null:rr(e.processIdentity);return e.processIdentity!==void 0&&(!t||t.pid!==e.pid)?null:{version:1,pid:e.pid,...t?{processIdentity:t}:{},projectRoot:e.projectRoot,startedAt:e.startedAt}}catch{return null}}function _s(r,e){switch(r){case"status":return{kind:"report",classification:e};case"ensure":switch(e.kind){case"stopped":return{kind:"start"};case"stale":return e.reason==="old-heartbeat"?{kind:"refuse-replace",state:e.state,reason:"old-heartbeat"}:{kind:"start"};case"live":return{kind:"reuse",state:e.state};case"incompatible":return{kind:"replace",state:e.state};default:return Bt(e)}case"stop":switch(e.kind){case"stopped":return{kind:"already-stopped"};case"stale":return e.reason==="old-heartbeat"?{kind:"signal-stop",state:e.state}:{kind:"clean-stale",state:e.state};case"live":case"incompatible":return{kind:"signal-stop",state:e.state};default:return Bt(e)}default:return Bt(r)}}function di(r){return r.idleTimeoutMs===0||r.watcher.state!=="idle"?!1:r.nowMs-r.lastActivityAtMs>=r.idleTimeoutMs}function ti(r,e,t){let{pid:n}=r;if(!t.isProcessAlive(n))return;Os(r,t),t.signalProcess(n);let i=e.stopTimeoutMs??As,o=t.monotonicNow??T,a=o()+i;for(;o()<=a;){if(!t.isProcessAlive(n))return;t.sleep(Ns)}throw new Error(`scip-query watch service pid ${n} did not stop within ${i}ms.`)}function Gt(r,e,t){if(ei(r.statePath,{force:!0}),ei(r.activityPath,{force:!0}),ai(r.lockPath)?.pid===e&&!t.isProcessAlive(e)){let i={...at,wallNow:t.now,isProcessAlive:t.isProcessAlive,readProcessIdentity:t.readProcessIdentity},o=ct(r.lockPath,{parseLegacy:ze,runtime:i});lr(r.lockPath,o,{parseLegacy:ze,runtime:i})}}function Ls(r,e,t){return`error: scip-query watch is already running for ${Ht(e)}${t?` (pid ${t.pid}, started ${t.startedAt}; lock: ${r})`:` (lock: ${r})`}. Stop that watcher before starting another.`}var js={now:Date.now,monotonicNow:T,isProcessAlive:F,readProcessIdentity:D,spawnServer(r,e,t,n){if(!Ds(r))throw new Error(`Watch service helper was not found at ${r}. Run npm run build first.`);Es(process.execPath,[r,e,t,JSON.stringify(n)],{detached:!0,stdio:"ignore",env:{...process.env,SCIP_QUERY_SKIP_WATCH_SERVICE:"1"}}).unref()},signalProcess(r){process.kill(r,"SIGTERM")},sleep(r){let e=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(e,0,0,r)}};function Os(r,e){if(!r.processIdentity)throw new Error(`Refusing to signal scip-query watch pid ${r.pid}: its ownership record has no process identity.`);let t=e.readProcessIdentity(r.pid);if(!t)throw new Error(`Refusing to signal scip-query watch pid ${r.pid}: its process identity is unavailable.`);if(!nr(r.processIdentity,t))throw new Error(`Refusing to signal scip-query watch pid ${r.pid}: its process identity does not match the ownership record.`)}function Bt(r){throw new Error(`Unhandled watch service value: ${JSON.stringify(r)}`)}import{existsSync as mi,lstatSync as Je,readFileSync as Yt,readdirSync as hi,realpathSync as ui,rmSync as fe,statSync as Ws}from"fs";import{join as w,resolve as U,sep as pi}from"path";var qs=3600*1e3,$s=2*1024*1024*1024,Gs=300*1e3;function Bs(r){let e=r.leases.filter(s=>s.managed&&!s.live&&!s.busy),t=Hs(r.leases,r.locks),n={};for(let s of r.generations)t.has(s.generationId)||(n[s.generationId]=s.unreferencedAt??r.nowMs);let i=r.generations.filter(s=>!t.has(s.generationId)).sort((s,c)=>n[s.generationId]-n[c.generationId]||s.generationId.localeCompare(c.generationId)),o=new Set;for(let s of i)r.nowMs-n[s.generationId]>=r.policy.generationTtlMs&&o.add(s.generationId);let a=r.generations.filter(s=>!o.has(s.generationId)).reduce((s,c)=>s+c.size,0);for(let s of i){if(a<=r.policy.budgetBytes)break;o.has(s.generationId)||(o.add(s.generationId),a-=s.size)}for(let s of o)delete n[s];return{deleteWorktrees:e,deleteGenerations:r.generations.filter(s=>o.has(s.generationId)),deleteLocks:r.locks.filter(s=>!s.live),deleteTemporaries:r.temporaries.filter(s=>!s.live),protectedGenerationIds:[...t].sort(),unreferencedSince:n}}function Hs(r,e){let t=new Set(r.filter(n=>n.managed&&(n.live||n.busy)).flatMap(n=>[n.lease.baseGenerationId,n.lease.activeGenerationId]).filter(n=>n!==void 0));for(let n of e)n.live&&t.add(n.generationId);return t}function gi(r,e,t={}){if(!_r())return{kind:"disabled"};let n=ir(r);if(!n)return{kind:"unavailable"};let i=w(ht(),"repositories",n.repositoryId);if(!mi(i))return{kind:"unavailable"};let o=(t.now??Date.now)(),a=w(i,"gc-state.json"),s=Ks(a);if(!t.force&&s&&o-Date.parse(s.lastSweepAt)<Gs)return{kind:"throttled",sweptAt:s.lastSweepAt};let c=dr(i,{now:()=>o});if(!c)return{kind:"busy"};try{let l=Us(r,i,n.repositoryId,s?.unreferencedSince??{}),d=Bs({nowMs:o,...l,policy:{generationTtlMs:t.policy?.generationTtlMs??qs,budgetBytes:t.policy?.budgetBytes??$s}}),u=0,p=0;for(let h of d.deleteWorktrees){if(!yi(h.lease))continue;let m=ur(w(h.lease.localCacheDir,"cache-lifecycle.lock"));if(m)try{if(Vt(h.lease,!0))continue;try{ni({projectRoot:h.lease.projectRoot,cacheDir:h.lease.localCacheDir,cliVersion:e})}catch{continue}if(Vt(h.lease,!0))continue;fe(h.lease.localCacheDir,{recursive:!0,force:!0}),fe(h.leasePath,{force:!0}),p+=1}finally{m.release()}}for(let h of d.deleteLocks)fe(h.path,{force:!0});for(let h of d.deleteTemporaries)fe(h.path,{recursive:!0,force:!0});for(let h of d.deleteGenerations)fe(h.path,{recursive:!0,force:!0}),u+=h.size;hr(w(i,"evidence.db"));let y={kind:"swept",sweptAt:new Date(o).toISOString(),deletedWorktrees:p,deletedGenerations:d.deleteGenerations.length,deletedBytes:u,protectedGenerations:d.protectedGenerationIds.length},f={version:1,lastSweepAt:y.sweptAt,unreferencedSince:d.unreferencedSince,lastResult:y};return lt(a,f,{spacing:2,trailingNewline:!0}),y}catch(l){return{kind:"failed",error:l instanceof Error?l.message:String(l)}}finally{c.release()}}function Us(r,e,t,n){let i=new Set(sr(r).map(l=>U(l.path))),o=[];for(let l of Ut(w(e,"worktrees"))){if(!l.endsWith(".json"))continue;let d=w(e,"worktrees",l),u=Vs(d);if(!u)continue;let p=U(u.projectRoot);o.push({leasePath:d,lease:u,managed:u.repositoryId===t&&yi(u),live:i.has(p)||mi(p),busy:Vt(u)})}let a=[];for(let l of Ut(w(e,"locks"))){let d=/^([a-f0-9]{64})\.lock$/.exec(l);if(!d)continue;let u=w(e,"locks",l),p=Kt(u),y=p!==void 0&&F(p),f=d[1];a.push({generationId:f,path:u,live:y})}let s=[],c=[];for(let l of Ut(w(e,"generations"))){let d=/^\.tmp-(\d+)-/.exec(l);if(d){let y=w(e,"generations",l),f=Number(d[1]);try{c.push({path:y,size:fi(y),live:Number.isSafeInteger(f)&&F(f)})}catch{}continue}if(!/^[a-f0-9]{64}$/.test(l))continue;let u=w(e,"generations",l),p;try{p=Je(u)}catch{continue}!p.isDirectory()||p.isSymbolicLink()||s.push({generationId:l,path:u,size:fi(u),...n[l]===void 0?{}:{unreferencedAt:n[l]}})}return{leases:o,generations:s,locks:a,temporaries:c}}function yi(r){if(r.ownershipChecksum!==jr(r)||U(r.localCacheDir)!==U(Nr(r.projectRoot)))return!1;let e=U(ht()),t=U(w(e,"projects")),n=U(r.localCacheDir);if(!n.startsWith(`${t}${pi}`))return!1;try{let i=Je(e),o=Je(t),a=Je(n);if(!i.isDirectory()||i.isSymbolicLink()||!o.isDirectory()||o.isSymbolicLink()||!a.isDirectory()||a.isSymbolicLink())return!1;let s=ui(t);return ui(n).startsWith(`${s}${pi}`)}catch{return!1}}function Vt(r,e=!1){for(let n of e?["index.lock"]:["index.lock","cache-lifecycle.lock"]){let i=Kt(w(r.localCacheDir,n));if(i!==void 0&&F(i))return!0}let t=Kt(J(r.localCacheDir).lockPath);return t!==void 0&&F(t)}function Vs(r){try{let e=JSON.parse(Yt(r,"utf8"));return e.version!==1||typeof e.repositoryId!="string"||typeof e.worktreeId!="string"||typeof e.projectRoot!="string"||e.treeOid!==void 0&&typeof e.treeOid!="string"||typeof e.localCacheDir!="string"||e.baseGenerationId!==void 0&&typeof e.baseGenerationId!="string"||e.activeGenerationId!==void 0&&typeof e.activeGenerationId!="string"||typeof e.ownershipChecksum!="string"||!/^[a-f0-9]{64}$/.test(e.ownershipChecksum)||typeof e.lastAction!="string"||e.lastReason!==void 0&&typeof e.lastReason!="string"||typeof e.lastSeenAt!="string"?null:e}catch{return null}}function Kt(r){try{let e=JSON.parse(Yt(r,"utf8"));return typeof e.pid=="number"&&Number.isSafeInteger(e.pid)&&e.pid>0?e.pid:void 0}catch{return}}function Ks(r){try{let e=JSON.parse(Yt(r,"utf8"));return e.version!==1||typeof e.lastSweepAt!="string"||!Number.isFinite(Date.parse(e.lastSweepAt))||!e.unreferencedSince||typeof e.unreferencedSince!="object"||!e.lastResult?null:e}catch{return null}}function Ut(r){try{return hi(r)}catch{return[]}}function fi(r){let e=0,t=[r];for(;t.length>0;){let n=t.pop();for(let i of hi(n,{withFileTypes:!0})){let o=w(n,i.name);i.isDirectory()?t.push(o):i.isFile()&&(e+=Ws(o).size)}}return e}var Xe=class{root;now;randomId;retryDelayMs;active;retryNotBeforeMs=0;currentStatus;constructor(e,t={}){this.root=e,this.now=t.now??Date.now,this.randomId=t.randomId,this.retryDelayMs=Math.max(1,Math.floor(t.retryDelayMs??1e3)),this.currentStatus=Ot(e)}initializeAfterOwnershipAcquired(){let e=Hn(this.root),t=Un(this.root,{now:()=>new Date(this.now())});return this.refreshStatus(),{recoveredClaims:e,prunedHistory:t}}observeLegacyRequest(e,t){$n(this.root,t??"stale index observed by a legacy command",{idempotencyKey:`legacy-activity:${e}`,now:()=>new Date(e)}),this.refreshStatus()}poll(e,t){if(this.active||e.state!=="idle"||this.now()<this.retryNotBeforeMs)return!1;let n=Gn(this.root,{now:()=>new Date(this.now()),...this.randomId?{randomId:this.randomId}:{}});if(this.refreshStatus(),n.requests.length===0)return!1;this.active=n;try{return t(Ys(n)),!0}catch(i){throw Ke(this.root,n),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),i}}completeActive(){return this.active?(Bn(this.root,this.active,()=>new Date(this.now())),this.active=void 0,this.retryNotBeforeMs=0,this.refreshStatus(),!0):!1}failActive(){return this.active?(Ke(this.root,this.active),this.active=void 0,this.retryNotBeforeMs=this.now()+this.retryDelayMs,this.refreshStatus(),!0):!1}status(){return{...this.currentStatus}}refreshStatus(){this.currentStatus=Ot(this.root)}};function Ys(r){if(r.requests.length===1)return r.requests[0].detail;let t=[...new Set(r.requests.map(n=>n.detail))].slice(0,3).join("; ");return`${r.requests.length} coalesced refresh requests${t?`: ${t}`:""}`.slice(0,2048)}var Xs=1e3,Qs=250,Zs=10;function ea(r){return r==="fresh"?null:{kind:"watch-startup",detail:`index ${r} when watch service started`}}async function ta(r,e,t={}){let n=ri(r,e),i=n.projectRoot,o=Q(i);o.watch={...o.watch,...t};let a=Le(o);if(!a.enabled)throw new Error('watch mode is disabled; set "watch.enabled": true before starting the service');let s=z(i,o),c=J(s.cacheDir),l=D(P.pid),d=si(c.lockPath,i,{readProcessIdentity:b=>b===P.pid?l:D(b)});if(!d.acquired)return;let u=new Xe(c.refreshRequestsPath,{retryDelayMs:Math.max(1e3,a.cooldownMs)});u.initializeAfterOwnershipAcquired();let p=Date.now(),y=T(),f=p,h=y,m={state:"idle"},g,R,M,k=Pe(s.dbPath),j=!1,L=!1,N=0,I=Number.NEGATIVE_INFINITY,C=Number.NEGATIVE_INFINITY,zt=Number.NEGATIVE_INFINITY,me,he,Qe=Zr(s.cacheDir),Ze=$r(s.cacheDir);_t(Qe),Lt(Ze);let et=new Be({openDb:()=>on(i)}),tt=new He({projectRoot:i,currentGeneration:()=>Br(s.dbPath)}),_=(b=!1)=>{if(!L)return;let Se=Date.now(),be=T();!b&&be-I<Xs||(I=be,ii(c.statePath,{version:1,protocolVersion:bt,pid:P.pid,...l?{processIdentity:l}:{},projectRoot:i,...n.worktreeId?{worktreeId:n.worktreeId}:{},cliVersion:e,startedAt:new Date(p).toISOString(),heartbeatAt:new Date(Se).toISOString(),lastActivityAt:new Date(f).toISOString(),...a.idleTimeoutMs===0?{}:{idleDeadlineAt:new Date(f+a.idleTimeoutMs).toISOString()},watcher:m,...m.state==="idle"&&g?{indexGeneration:g}:{},...R?{lastRefresh:R}:{},...M?{lastError:M}:{},reindexActivity:k,refreshRequests:u.status(),typescriptSemantic:{...et.status(Nn(Qe)),...me===void 0?{}:{busyUntil:new Date(me).toISOString()}},typescriptIndex:{...tt.status(jn(Ze)),...he===void 0?{}:{busyUntil:new Date(he).toISOString()}}}))},V=()=>{f=Date.now(),h=T()},ge=new je({projectRoot:i,config:{...o,watch:a},languages:o.languages,onStatus(b){m=b,b.state!=="idle"&&(g=void 0),b.state!=="idle"&&V(),_(!0)},onReindexComplete(){V();let b=vt(i,o,s);return R=b.lastRefresh,g=b.state==="fresh"?xt(s.dbPath)??void 0:void 0,k=Pe(s.dbPath),u.completeActive(),M=void 0,_(!0),b.state==="fresh"},onReindexError(){u.failActive()},onRefreshSuppressed(b){Ar(s.dbPath,b),k=Pe(s.dbPath)},onError(b){V(),g=void 0,M={at:new Date().toISOString(),message:b.message},_(!0)}}),ye=()=>{j=!0};P.once("SIGINT",ye),P.once("SIGTERM",ye);let rt=!1,nt,ie;try{ge.start();let b=vt(i,o,s);R=b.lastRefresh,g=b.state==="fresh"?xt(s.dbPath)??void 0:void 0;let Se=ea(b.state);for(Se&&ge.requestRefresh(Se,{immediate:!0}),V(),L=!0,_(!0);!j;){let be=Ln(Ze,tt,{beforeRequest(E){he=E+5e3,_(!0)},afterRequest(){he=void 0,_(!0)}}),bi=An(Qe,et,{beforeRequest(E){me=E+5e3,_(!0)},afterRequest(){me=void 0,_(!0)}}),oe=T();if(oe-zt>=6e4&&(zt=oe,gi(i,e)),oe-C>=Qs){C=oe;let E=oi(c.activityPath);E&&E.atMs>f&&(f=E.atMs,h=oe),E?.refreshRequestedAtMs!==void 0&&E.refreshRequestedAtMs>N&&(N=E.refreshRequestedAtMs,u.observeLegacyRequest(E.refreshRequestedAtMs,E.refreshDetail??"stale index observed by a legacy command")),u.poll(m,vi=>{V(),ge.requestRefresh({kind:"watch-demand",detail:vi},{immediate:!0})})}if((bi>0||be>0)&&(V(),_(!0)),_(),di({watcher:m,lastActivityAtMs:h,nowMs:T(),idleTimeoutMs:a.idleTimeoutMs}))break;await ra(Zs)}}catch(b){rt=!0,nt=b}finally{P.off("SIGINT",ye),P.off("SIGTERM",ye),et.closeTypeScriptService(),tt.close();let b=await ge.stop();b.state==="stopped"?(Si(c.statePath,{force:!0}),Si(c.activityPath,{force:!0}),d.release()):(M={at:new Date().toISOString(),message:`Watch service shutdown is degraded: ${b.reasons.join("; ")}`},_(!0),ie=new Error(M.message))}if(rt&&ie)throw new AggregateError([nt,ie],"Watch service execution and shutdown both failed.");if(rt)throw nt;if(ie)throw ie}function ra(r){return new Promise(e=>setTimeout(e,r))}var na=P.argv[1]?Js(zs(P.argv[1])).href:null;if(na===import.meta.url){let r=P.argv[2],e=P.argv[3],t=ia(P.argv[4]);if(!r||!e)console.error("watch-service: expected <project-root> <cli-version>"),P.exitCode=1;else try{await ta(r,e,t)}catch(n){console.error(`watch-service: ${n instanceof Error?n.message:String(n)}`),P.exitCode=1}}function ia(r){if(!r)return{};try{let e=JSON.parse(r);return e&&typeof e=="object"?e:{}}catch{return{}}}export{ta as runWatchServiceServer,ea as startupRefreshTrigger};
|
|
43
43
|
//# sourceMappingURL=watch-server.js.map
|
package/docs/AGENT_GUIDE.md
CHANGED
|
@@ -54,7 +54,7 @@ For analyzer implementation work, follow [Regex Policy](REGEX_POLICY.md): regex
|
|
|
54
54
|
scip-query health --json
|
|
55
55
|
scip-query diff-gate --json
|
|
56
56
|
```
|
|
57
|
-
Before cleanup, tell the user the health score, confirmed items, unavailable checks, and recommended first cleanup batch. Use `scip-
|
|
57
|
+
Before cleanup, tell the user the health score, confirmed items, unavailable checks, and recommended first cleanup batch. Use `scip-audit` for confirmation and `scip-improve` when the user wants autonomous score improvement.
|
|
58
58
|
|
|
59
59
|
### What you should know after this workflow
|
|
60
60
|
|
package/docs/AI_FAILURE_MODES.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# The Ways AI Coding Rots a Codebase — and the Detector Built for Each
|
|
2
2
|
|
|
3
|
-
AI-assisted development fails in
|
|
3
|
+
AI-assisted development fails in _specific, repeatable_ ways. None of them are
|
|
4
4
|
visible in a single file, which is why linters and code review miss them: every
|
|
5
5
|
one lives in the relationships between files — the reference graph, the git
|
|
6
6
|
change graph, or the gap between docs and code. Each failure mode below names
|
|
@@ -19,7 +19,7 @@ hook, composable, or frontend component that already exists - a date formatter,
|
|
|
19
19
|
a retry wrapper, a validation guard, a table toolbar. Now there are two implementations that drift independently until they
|
|
20
20
|
contradict each other.
|
|
21
21
|
|
|
22
|
-
**The detector:** `recent-duplicates` makes similarity
|
|
22
|
+
**The detector:** `recent-duplicates` makes similarity _directional_ using git
|
|
23
23
|
file ages - which side is the established original, which is the freshly-added
|
|
24
24
|
echo.
|
|
25
25
|
|
|
@@ -61,11 +61,11 @@ inside the recency window) and tells you to pick one before they drift:
|
|
|
61
61
|
**What the agent does:** creates an abstraction, rewires one or two call
|
|
62
62
|
sites into it, and abandons the rest — the extracted logic survives inline at
|
|
63
63
|
every site it missed. The codebase ends up with the worst of both worlds: an
|
|
64
|
-
abstraction
|
|
64
|
+
abstraction _and_ the duplication it was meant to remove.
|
|
65
65
|
|
|
66
66
|
**The detector:** `incomplete-migration` finds symbols that are new at the
|
|
67
67
|
base ref, confirms they were wired into at least one site, then reports
|
|
68
|
-
established untouched functions whose callee sets
|
|
68
|
+
established untouched functions whose callee sets _contain_ the helper's
|
|
69
69
|
(containment scoring, because a missed site holds the helper's logic plus its
|
|
70
70
|
own — symmetric similarity under-scores exactly these):
|
|
71
71
|
|
|
@@ -88,11 +88,11 @@ scip-query incomplete-migration --base origin/main # gate a whole branch
|
|
|
88
88
|
## 4. Writing code that never gets wired up
|
|
89
89
|
|
|
90
90
|
**What the agent does:** builds the function, the type, the handler — and
|
|
91
|
-
never connects it. Or it
|
|
91
|
+
never connects it. Or it _was_ connected, then a later session rewired the
|
|
92
92
|
flow and left the original dangling. Dead code that looks intentional.
|
|
93
93
|
|
|
94
94
|
**The detectors:** `dead` (evidence-ranked, entrypoint-aware), and the
|
|
95
|
-
`new-dead` check in `diff-gate` that catches it
|
|
95
|
+
`new-dead` check in `diff-gate` that catches it _at the moment of creation_:
|
|
96
96
|
|
|
97
97
|
```
|
|
98
98
|
[new-dead] resolveTheme (src/theme.ts) was changed but has zero indexed consumers
|
|
@@ -114,7 +114,7 @@ every future reader has to understand.
|
|
|
114
114
|
|
|
115
115
|
**The detectors:** `unused-params` (trailing parameters no body uses, scoped
|
|
116
116
|
to removals that are type-safe by construction), plus the abstraction-level
|
|
117
|
-
versions: `wrapper-candidates` (functions that only forward),
|
|
117
|
+
versions: `wrapper-candidates` (functions that only forward),
|
|
118
118
|
`passthrough-candidates` (layers that add nothing), and `stale-abstractions`
|
|
119
119
|
(interfaces/bases with a single implementation).
|
|
120
120
|
|
|
@@ -131,11 +131,11 @@ scip-query stale-abstractions
|
|
|
131
131
|
## 6. Letting the standards docs lie
|
|
132
132
|
|
|
133
133
|
**What the agent does:** nothing — that's the problem. You write in-repo
|
|
134
|
-
standards
|
|
134
|
+
standards _for_ agents; the code moves on; the doc doesn't. The next agent
|
|
135
135
|
reads the doc and faithfully implements against a dead spec. A stale standard
|
|
136
136
|
is worse than none.
|
|
137
137
|
|
|
138
|
-
**The detector:** `doc-drift` reads every doc's file citations
|
|
138
|
+
**The detector:** `doc-drift` reads every doc's file citations _and_ its
|
|
139
139
|
co-change history, and flags docs whose referenced code kept changing after
|
|
140
140
|
the doc stopped — including broken references to files that no longer exist.
|
|
141
141
|
|
|
@@ -147,8 +147,8 @@ staleness 94 product/domain-model.md
|
|
|
147
147
|
22 change(s) since doc update src/workflows/serviceTasks.ts
|
|
148
148
|
```
|
|
149
149
|
|
|
150
|
-
**Use it:** `scip-query doc-drift`, then run the `scip-
|
|
151
|
-
drive staleness to zero (it updates descriptive claims and
|
|
150
|
+
**Use it:** `scip-query doc-drift`, then run the `scip-improve` documentation-reconciliation scenario to
|
|
151
|
+
drive staleness to zero (it updates descriptive claims and _escalates_
|
|
152
152
|
normative violations instead of silently blessing them).
|
|
153
153
|
|
|
154
154
|
**Caught automatically by:** the `doc-reference` check in `diff-gate` — a doc
|
|
@@ -162,7 +162,7 @@ store. The reference graph can't see these pairs — no import connects them —
|
|
|
162
162
|
but git history can: they've changed together in 12 of the last 14 commits.
|
|
163
163
|
|
|
164
164
|
**The detector:** `co-change` finds file pairs that repeatedly change in the
|
|
165
|
-
same commits with
|
|
165
|
+
same commits with _no_ dependency edge.
|
|
166
166
|
|
|
167
167
|
**Use it:**
|
|
168
168
|
|
|
@@ -183,7 +183,7 @@ scip-query co-change src/db/schema.prisma # partners of one file
|
|
|
183
183
|
path still references, or it hoards code because it can't prove anything is
|
|
184
184
|
safe to remove.
|
|
185
185
|
|
|
186
|
-
**The detector:** `cleanup-plan` runs dead-code analysis to a
|
|
186
|
+
**The detector:** `cleanup-plan` runs dead-code analysis to a _fixpoint_ —
|
|
187
187
|
deleting batch 0 makes batch 1 dead, and the plan shows the cascade. Then
|
|
188
188
|
`--verify` applies each batch in a throwaway git worktree and runs **your own
|
|
189
189
|
compiler** (tsc, cargo, go, python oracles — differentially, so pre-existing
|
|
@@ -222,7 +222,7 @@ scip-query plan-context <symbol-or-file> # before the edit
|
|
|
222
222
|
scip-query diff-impact --json # after the edit
|
|
223
223
|
```
|
|
224
224
|
|
|
225
|
-
The `scip-
|
|
225
|
+
The `scip-plan` skill enforces this end-to-end: every step in a plan must
|
|
226
226
|
cite the scip-query command that verified it.
|
|
227
227
|
|
|
228
228
|
## 10. Slow quality decay nobody notices
|
|
@@ -231,7 +231,7 @@ cite the scip-query command that verified it.
|
|
|
231
231
|
alarming; six weeks later the repo is unrecognizable.
|
|
232
232
|
|
|
233
233
|
**The detector:** the ratchet. `health --write-baseline` snapshots finding
|
|
234
|
-
identities into a committable file; `health --baseline` exits 1 on any
|
|
234
|
+
identities into a committable file; `health --baseline` exits 1 on any _new_
|
|
235
235
|
finding. "Don't get worse" becomes an objective gate no score arithmetic can
|
|
236
236
|
game.
|
|
237
237
|
|
|
@@ -281,8 +281,8 @@ The generated guidance distinguishes shared repository records from local
|
|
|
281
281
|
preferences. Commit suppression files and `.scipquery/ledger/` outcome events
|
|
282
282
|
with the change that produced them. Never commit the checkout hook files.
|
|
283
283
|
|
|
284
|
-
After setup, use `scip-
|
|
285
|
-
`scip-
|
|
284
|
+
After setup, use `scip-audit` to confirm raw signals and
|
|
285
|
+
`scip-improve` when the user wants the agent to fix the worst confirmed
|
|
286
286
|
items until the health score is as high as reasonably possible.
|
|
287
287
|
|
|
288
288
|
**3. The gate (enforcement).**
|
|
@@ -301,7 +301,7 @@ scip-query setup-agent --git-hook # pre-commit backstop: fires whoever wrote
|
|
|
301
301
|
| `co-change-partner` | Historically coupled files that usually change together but are missing from this diff. | Default diff gate. |
|
|
302
302
|
| `twin-partner` | A changed symbol has a same-(near-)name twin (identical or already-divergent) elsewhere that this diff left untouched. | Default diff gate. Advisory: findings print but never cause a nonzero exit by themselves. |
|
|
303
303
|
| `coverage-contract` | A configured `coverageContracts` entry (.scipquery.json) drifted: its declared key set no longer matches its ground-truth source. | Default diff gate, only when either side of a configured contract changed. |
|
|
304
|
-
| `architecture` | A declared architecture boundary rule has a violation absent from the committed health baseline. | Default diff gate when closed dependency rows, requireCompletePolicy, requireAcyclic, requireResolvedBoundaries, requireMinimalPolicy, maxBoundaryFanOut
|
|
304
|
+
| `architecture` | A declared architecture boundary rule has a violation absent from the committed health baseline. | Default diff gate when closed dependency rows, requireCompletePolicy, requireAcyclic, requireResolvedBoundaries, requireMinimalPolicy, maxBoundaryFanOut/maxBoundaryFiles, or testPaths are configured and a baseline exists. |
|
|
305
305
|
| `doc-reference` | Docs that cite changed files and may need a matching update. Dated snapshot docs (docs.snapshotPaths) are excluded by policy. | Default diff gate. Advisory (21.2) for bare file-mention citations; blocking when the citation has a line anchor or the cited file was deleted/renamed. |
|
|
306
306
|
| `unused-params` | Fresh trailing parameters or options that no changed body uses. | Default diff gate. |
|
|
307
307
|
| `new-dead` | Changed production symbols with zero indexed consumers. | Default diff gate. |
|