scip-query 0.23.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +491 -2
- package/README.md +111 -122
- package/dist/augment-vue-worker.js +1 -1
- package/dist/by-kind-PRVFAGTQ.js +2 -0
- package/dist/call-graph-DVPAQV2F.js +2 -0
- package/dist/call-graph-evidence-CUtj8V2I.d.ts +19 -0
- package/dist/chunk-2FSBGL5P.js +2 -0
- package/dist/chunk-2HLAFUCY.js +2 -0
- package/dist/chunk-2IWUT6CJ.js +3 -0
- package/dist/chunk-2KNN7GTQ.js +2 -0
- package/dist/chunk-2LHXRE2B.js +8 -0
- package/dist/{chunk-EG2CPZMJ.js → chunk-2YXE77TJ.js} +2 -2
- package/dist/chunk-36SGVCGX.js +2 -0
- package/dist/chunk-3ABBFPTP.js +2 -0
- package/dist/chunk-3IVFU4FD.js +3 -0
- package/dist/chunk-3JIQS44J.js +7 -0
- package/dist/chunk-3ZRB6DNK.js +7 -0
- package/dist/{chunk-6YTSKJJ3.js → chunk-42EOW5VI.js} +1 -1
- package/dist/{chunk-6I6L7Z62.js → chunk-4BHGBMNO.js} +2 -2
- package/dist/chunk-4BP3UBDG.js +2 -0
- package/dist/chunk-4D6RO7G4.js +2 -0
- package/dist/chunk-4FEWQ6RH.js +2 -0
- package/dist/chunk-4IGEOBG7.js +2 -0
- package/dist/chunk-4QZXBUKC.js +2 -0
- package/dist/chunk-4WBDEVX2.js +4 -0
- package/dist/chunk-4WCUBZU3.js +8 -0
- package/dist/chunk-4WTUBQ36.js +40 -0
- package/dist/chunk-4XQ4O6IM.js +3 -0
- package/dist/chunk-55UQAMZO.js +4 -0
- package/dist/chunk-5D2LVK7O.js +125 -0
- package/dist/chunk-5IYJ56TT.js +2 -0
- package/dist/chunk-5PLMJC7Q.js +2 -0
- package/dist/chunk-5TNQJUR2.js +5 -0
- package/dist/chunk-62BDNPMI.js +2 -0
- package/dist/chunk-64DZ5TXR.js +7 -0
- package/dist/chunk-65245JCM.js +2 -0
- package/dist/chunk-6FFVZZL4.js +2 -0
- package/dist/chunk-6KO5JHAR.js +2 -0
- package/dist/chunk-6LRXOOSX.js +2 -0
- package/dist/chunk-6LSEIIF7.js +2 -0
- package/dist/chunk-6YMNWD3H.js +6 -0
- package/dist/chunk-72AD6ZRR.js +5 -0
- package/dist/chunk-73AAKPUC.js +4 -0
- package/dist/chunk-76CZ77DF.js +2 -0
- package/dist/chunk-7VPEEAAG.js +2 -0
- package/dist/chunk-7WTPQ4NX.js +14 -0
- package/dist/chunk-7Y5T6XDP.js +2 -0
- package/dist/chunk-A2IIGFMJ.js +5 -0
- package/dist/chunk-AB5KCTEV.js +2 -0
- package/dist/chunk-AC566WBP.js +6 -0
- package/dist/chunk-AGWFSTXC.js +3 -0
- package/dist/chunk-AOSIYPTA.js +2 -0
- package/dist/chunk-AUVEWPIF.js +2 -0
- package/dist/chunk-B56T42J3.js +25 -0
- package/dist/chunk-BIQEF5NE.js +2 -0
- package/dist/chunk-BL6XJKTA.js +3 -0
- package/dist/chunk-BMKOQJRI.js +2 -0
- package/dist/chunk-BOZ4EXBB.js +3 -0
- package/dist/chunk-BUTWYEPH.js +2 -0
- package/dist/chunk-BZB4QPIP.js +2 -0
- package/dist/{chunk-ILTDAWEF.js → chunk-CE357GEE.js} +4 -4
- package/dist/chunk-CFN45HFP.js +2 -0
- package/dist/chunk-CFYMZFXT.js +368 -0
- package/dist/chunk-CN5EH7O3.js +2 -0
- package/dist/chunk-D254DNNQ.js +4 -0
- package/dist/chunk-D3FDISIC.js +2 -0
- package/dist/chunk-D3NX5XIE.js +3 -0
- package/dist/chunk-DA7RPPDF.js +3 -0
- package/dist/chunk-DDMC3FON.js +3 -0
- package/dist/chunk-DIO3FUSG.js +2 -0
- package/dist/chunk-DJ2NNSUK.js +3 -0
- package/dist/chunk-DKYQIM3C.js +18 -0
- package/dist/{chunk-JTQVMR42.js → chunk-DOOEL2IV.js} +2 -2
- package/dist/chunk-DVFP6PZI.js +2 -0
- package/dist/chunk-E3FDPXZK.js +2 -0
- package/dist/chunk-E7YNJLCB.js +2 -0
- package/dist/chunk-EFGW5JPH.js +2 -0
- package/dist/chunk-EJVTR244.js +13 -0
- package/dist/chunk-EOV7RTRZ.js +2 -0
- package/dist/chunk-ETOIKRHO.js +2 -0
- package/dist/chunk-EYK3ZAO2.js +3 -0
- package/dist/chunk-F2V2LPET.js +52 -0
- package/dist/chunk-F4LUHJTF.js +2 -0
- package/dist/chunk-F4PUT6IT.js +2 -0
- package/dist/chunk-F56GCXXS.js +5 -0
- package/dist/chunk-FC2EVQRM.js +2 -0
- package/dist/chunk-FL7NBMHP.js +3 -0
- package/dist/chunk-FMRN2TRL.js +3 -0
- package/dist/chunk-FVULPZDF.js +20 -0
- package/dist/chunk-GCKCF5FL.js +43 -0
- package/dist/chunk-GH2PYF46.js +2 -0
- package/dist/chunk-GHJAGXIP.js +2 -0
- package/dist/{chunk-WIWY3CRX.js → chunk-GMVSHUKZ.js} +2 -2
- package/dist/chunk-GS6KDO4R.js +2 -0
- package/dist/chunk-GUUBXNN7.js +2 -0
- package/dist/chunk-GVWX5T43.js +80 -0
- package/dist/chunk-GZKFETP5.js +2 -0
- package/dist/chunk-H4EQHO6J.js +9 -0
- package/dist/chunk-H73WY2RM.js +2 -0
- package/dist/chunk-H75GSPRV.js +60 -0
- package/dist/chunk-HDR3AHSV.js +61 -0
- package/dist/chunk-HQBSL74Y.js +2 -0
- package/dist/chunk-HRRFKWPZ.js +2 -0
- package/dist/chunk-HXENDJC6.js +2 -0
- package/dist/chunk-IIBAZNSW.js +21 -0
- package/dist/chunk-INLMWEUU.js +12 -0
- package/dist/chunk-IWQPAF4F.js +2 -0
- package/dist/chunk-IZJ6YUKP.js +35 -0
- package/dist/chunk-J2TMAIN5.js +60 -0
- package/dist/chunk-J5FJMODQ.js +142 -0
- package/dist/chunk-J7HZPIO3.js +2 -0
- package/dist/chunk-JEVRKFRL.js +2 -0
- package/dist/chunk-JFXSGAEB.js +30 -0
- package/dist/chunk-JVRTHGFS.js +3 -0
- package/dist/chunk-JYWEX7RR.js +360 -0
- package/dist/chunk-K3YL22N6.js +2 -0
- package/dist/chunk-K4CN7GXK.js +12 -0
- package/dist/chunk-K5TBVXU4.js +30 -0
- package/dist/chunk-KDDIE2DP.js +9 -0
- package/dist/chunk-KHWRRPV4.js +2 -0
- package/dist/chunk-KI6NBKDY.js +14 -0
- package/dist/chunk-KU3QRSTH.js +2 -0
- package/dist/chunk-KZBJWZJB.js +2 -0
- package/dist/chunk-L7GFM3NP.js +3 -0
- package/dist/chunk-LMO6PK3V.js +35 -0
- package/dist/chunk-LN4YXJJU.js +2 -0
- package/dist/chunk-LOVIZBJ4.js +43 -0
- package/dist/chunk-LPCRK4A2.js +11 -0
- package/dist/chunk-MMHZKBFA.js +2 -0
- package/dist/{chunk-M2O5NY6W.js → chunk-MOQQBQRD.js} +2 -2
- package/dist/chunk-N2WN6I3L.js +2 -0
- package/dist/chunk-N3ORQT7L.js +2 -0
- package/dist/chunk-NAZ3RAIW.js +2 -0
- package/dist/chunk-NDUNO5JQ.js +2 -0
- package/dist/chunk-NEIWRNAZ.js +4 -0
- package/dist/chunk-NJJMVD65.js +2 -0
- package/dist/chunk-NLOQOBXI.js +20 -0
- package/dist/chunk-NOLZOVCU.js +2 -0
- package/dist/chunk-NOWINRRN.js +2 -0
- package/dist/chunk-NZAXKGRL.js +16 -0
- package/dist/chunk-O2C4UILI.js +2 -0
- package/dist/chunk-O3RHA6ZT.js +3 -0
- package/dist/chunk-O4UZSPPI.js +3 -0
- package/dist/chunk-OGFV2BUX.js +2 -0
- package/dist/chunk-OZCJXZK6.js +499 -0
- package/dist/chunk-P6ODM7BY.js +2 -0
- package/dist/{chunk-XBGWL66K.js → chunk-PAVGPRHJ.js} +2 -2
- package/dist/chunk-PH52RA7D.js +2 -0
- package/dist/chunk-PKN354TH.js +3 -0
- package/dist/chunk-PWOASWEG.js +11 -0
- package/dist/chunk-QIWXRW72.js +2 -0
- package/dist/chunk-QJRMOK5N.js +2 -0
- package/dist/{chunk-YXPUP5G2.js → chunk-QOIXNWQR.js} +2 -2
- package/dist/chunk-QXEUDXBT.js +3 -0
- package/dist/chunk-QYUVVBMR.js +6 -0
- package/dist/chunk-QZ7KQZRN.js +2 -0
- package/dist/chunk-R6LQBUDH.js +2 -0
- package/dist/chunk-RBS42E55.js +20 -0
- package/dist/chunk-RSJKPCFX.js +26 -0
- package/dist/chunk-S6CZA3MV.js +2 -0
- package/dist/chunk-STMVAHJP.js +2 -0
- package/dist/chunk-SYVPTTVW.js +2 -0
- package/dist/chunk-T3I6NHBH.js +2 -0
- package/dist/chunk-T6DK3ZP7.js +2 -0
- package/dist/chunk-TKD34PHN.js +4 -0
- package/dist/chunk-TNNQFH7W.js +2 -0
- package/dist/chunk-TNV7SSUF.js +2 -0
- package/dist/chunk-TO7ZR3EH.js +8 -0
- package/dist/chunk-TOU3CHK4.js +2 -0
- package/dist/chunk-TRBI4UKT.js +2 -0
- package/dist/chunk-TZCVNCAN.js +4 -0
- package/dist/chunk-U4LZA5LL.js +3 -0
- package/dist/chunk-U5RIG3JP.js +3 -0
- package/dist/chunk-UP5KXN2I.js +2 -0
- package/dist/chunk-UQFR3NDH.js +5 -0
- package/dist/chunk-UXYXF7GV.js +2 -0
- package/dist/chunk-VB3GOKOS.js +2 -0
- package/dist/chunk-VF5JZICY.js +2 -0
- package/dist/chunk-VTY3VK6E.js +2 -0
- package/dist/chunk-VX2O4RIS.js +2 -0
- package/dist/chunk-WKPV2TDZ.js +2 -0
- package/dist/chunk-WOFQ5DTB.js +2 -0
- package/dist/chunk-WS4C6TCK.js +2 -0
- package/dist/chunk-WXU3DGPU.js +2 -0
- package/dist/chunk-X6RMKHJQ.js +81 -0
- package/dist/{chunk-4ILJCCXV.js → chunk-XHMN6ZX7.js} +2 -2
- package/dist/chunk-XHTVFLWW.js +2 -0
- package/dist/chunk-XKIDJCIK.js +2 -0
- package/dist/chunk-XTYTYZPT.js +2 -0
- package/dist/chunk-Y2JHHTTA.js +2 -0
- package/dist/chunk-YGVRMGYN.js +4 -0
- package/dist/chunk-YNQCGEQE.js +2 -0
- package/dist/chunk-YOQVEXVE.js +14 -0
- package/dist/chunk-YRT2WLYY.js +2 -0
- package/dist/chunk-YTAP5Y2G.js +2 -0
- package/dist/chunk-YTYWI7VB.js +2 -0
- package/dist/chunk-YULZRALL.js +2 -0
- package/dist/chunk-Z33WQG4Q.js +2 -0
- package/dist/chunk-ZGTYGDMF.js +16 -0
- package/dist/chunk-ZHMRSZFD.js +43 -0
- package/dist/chunk-ZHSP366W.js +10 -0
- package/dist/chunk-ZIBYCYKK.js +7 -0
- package/dist/{chunk-GAS2LJMP.js → chunk-ZLADLUE6.js} +3 -3
- package/dist/chunk-ZO4YXUT6.js +4 -0
- package/dist/{chunk-HYO3NP5Q.js → chunk-ZR4HBC2H.js} +2 -2
- package/dist/cli-main.js +6 -6
- package/dist/cli.js +1 -1
- package/dist/{code-B17qEMbt.d.ts → code-BNyrCF3_.d.ts} +3 -2
- package/dist/code-IL5WH3NZ.js +2 -0
- package/dist/code-result-json-ANTBEDFP.js +4 -0
- package/dist/command-descriptors-HEEMDHTU.js +222 -0
- package/dist/deps-EOWFC6FD.js +2 -0
- package/dist/direct-navigation-Y5B6OSIQ.js +3 -0
- package/dist/{exploration-topology-BG4v30HZ.d.ts → exploration-topology-CSgEyAz-.d.ts} +3 -1
- package/dist/files-K4AI3JUM.js +2 -0
- package/dist/frontend-profile-roles-D7eCum8P.d.ts +10 -0
- package/dist/{health-CPp2Jf1Z.d.ts → health-BtfmNrfa.d.ts} +58 -74
- package/dist/hierarchy-6W5NDIFI.js +2 -0
- package/dist/imports-WH365QY4.js +2 -0
- package/dist/index.d.ts +13 -1
- package/dist/index.js +1 -1
- package/dist/members-K3PHMF5S.js +2 -0
- package/dist/methods-E7KVMBX4.js +2 -0
- package/dist/output-continuation-command-BJSY67SN.js +3 -0
- package/dist/output-pagination-UZJ5ACIX.js +24 -0
- package/dist/postinstall.js +1 -1
- package/dist/project-reindex-EP24WT4X.js +3 -0
- package/dist/queries/affected.js +1 -1
- package/dist/queries/architecture.d.ts +15 -4
- package/dist/queries/architecture.js +1 -1
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +3 -1
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +1 -0
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.d.ts +3 -3
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.d.ts +20 -2
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +1 -1
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity.d.ts +6 -3
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/context.d.ts +1 -7
- package/dist/queries/context.js +1 -1
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dead.d.ts +2 -0
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/dependence-slice.d.ts +46 -22
- package/dist/queries/dependence-slice.js +1 -1
- package/dist/queries/dependency-depth.d.ts +1 -7
- package/dist/queries/dependency-depth.js +1 -1
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-impact.d.ts +3 -1
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +1 -1
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.d.ts +29 -2
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/entry-map.d.ts +2 -4
- package/dist/queries/entry-map.js +1 -1
- package/dist/queries/evidence.d.ts +121 -61
- package/dist/queries/evidence.js +1 -1
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.js +1 -1
- package/dist/queries/health.d.ts +1 -1
- 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 +1 -1
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +1 -0
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +3 -3
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +17 -65
- package/dist/queries/index.js +1 -1
- package/dist/queries/locality-candidates.d.ts +4 -4
- 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.js +1 -1
- package/dist/queries/not-implemented.d.ts +2 -6
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.d.ts +9 -1
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/react-component-duplicates.d.ts +19 -3
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.d.ts +22 -3
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.d.ts +17 -3
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +4 -14
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.d.ts +4 -1
- package/dist/queries/refs.js +1 -1
- package/dist/queries/review.d.ts +188 -0
- package/dist/queries/review.js +2 -0
- package/dist/queries/similar-files.d.ts +7 -10
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +19 -1
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice-cohesion.d.ts +205 -0
- package/dist/queries/slice-cohesion.js +2 -0
- package/dist/queries/source-inspection.d.ts +6 -202
- package/dist/queries/source-inspection.js +1 -1
- package/dist/queries/source-search.d.ts +2 -3
- package/dist/queries/source-search.js +1 -1
- package/dist/queries/stats.d.ts +1 -0
- package/dist/queries/stats.js +1 -1
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.d.ts +4 -2
- package/dist/queries/system.js +1 -1
- package/dist/queries/test-quality.d.ts +1 -1
- package/dist/queries/test-quality.js +1 -1
- package/dist/queries/twin-drift.d.ts +23 -7
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.d.ts +3 -15
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/query-service-fastpath.js +5 -5
- package/dist/query-service-server.js +4 -4
- package/dist/refs-CCBJG7WK.js +2 -0
- package/dist/refs-pagination-DRNLVU4S.js +2 -0
- package/dist/reindex-worker.js +79 -29
- package/dist/reindex.js +45 -45
- package/dist/repository-cache-worker.js +2 -0
- package/dist/runtime.d.ts +8 -8
- package/dist/runtime.js +3 -4
- 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/service-queries-2WAJI7R6.js +6 -0
- package/dist/source-inspection-91U9zdO3.d.ts +341 -0
- package/dist/{source-search-types-Dwz8KeuW.d.ts → source-search-types-DWGYNg8M.d.ts} +15 -2
- package/dist/stats-G7DIV6VU.js +2 -0
- package/dist/surface-IO55UALI.js +2 -0
- package/dist/system-ZBMSHJXU.js +2 -0
- package/dist/{queries/trace.d.ts → trace-BMjw3prn.d.ts} +1 -18
- package/dist/typescript-indexer.js +2 -0
- package/dist/typescript-mailbox-worker.js +1 -1
- package/dist/watch-server.js +3 -3
- package/docs/AGENT_GUIDE.md +19 -128
- package/docs/CLI_JSON_OUTPUT.md +21 -17
- package/docs/COMMAND_REFERENCE.md +34 -49
- package/docs/CURRENT_COMMANDS.md +123 -0
- package/docs/DETECTOR_EVIDENCE_CONTRACTS.md +0 -40
- package/docs/DETECTOR_GUIDE.md +55 -12
- package/docs/PRODUCT_VISION.md +135 -0
- package/docs/PROPERTY_TESTING.md +73 -0
- package/docs/REVIEW.md +76 -0
- package/docs/SKILLS.md +51 -0
- package/docs/WINDOWS_SIDECAR_RELEASE.md +12 -3
- package/docs/accuracy-audit-checklist.md +70 -13
- package/docs/analyzer-inventory.md +2 -2
- package/docs/locality-analyzer-design.md +9 -9
- package/package.json +18 -80
- package/scripts/evidence-product-contract.mjs +7 -3
- package/scripts/record-review-coverage.mjs +118 -0
- package/scripts/scip-windows-provenance.mjs +29 -19
- package/skills/scip-architecture-review/SKILL.md +57 -0
- package/skills/scip-architecture-review/agents/openai.yaml +4 -0
- package/skills/scip-architecture-review/references/design-checks.md +17 -0
- package/skills/scip-explore/SKILL.md +15 -59
- package/skills/scip-explore/agents/openai.yaml +3 -3
- package/skills/scip-explore/references/external-evidence.md +2 -2
- package/skills/scip-explore/references/information-model.md +26 -29
- package/skills/scip-explore/scripts/capture-evidence.mjs +68 -34
- package/skills/scip-integrity-audit/SKILL.md +53 -181
- package/skills/scip-integrity-audit/agents/openai.yaml +3 -3
- package/skills/scip-integrity-audit/references/integrity-probes.md +27 -0
- package/skills/scip-plan/SKILL.md +39 -65
- package/skills/scip-plan/agents/openai.yaml +2 -2
- package/skills/scip-query/SKILL.md +28 -81
- package/skills/scip-query/agents/openai.yaml +2 -2
- package/skills/scip-query/references/command-guide.md +169 -0
- package/skills/scip-setup/SKILL.md +4 -2
- package/skills/scip-setup/agents/openai.yaml +3 -3
- package/dist/by-kind-XI2CSWEY.js +0 -2
- package/dist/call-graph-UONR6JR5.js +0 -2
- package/dist/call-graph-evidence-lZa2dwQA.d.ts +0 -11
- package/dist/chunk-26CT72HM.js +0 -2
- package/dist/chunk-2E7CX53V.js +0 -2
- package/dist/chunk-2GRUZAQF.js +0 -43
- package/dist/chunk-2LDBDR6J.js +0 -29
- package/dist/chunk-2OOY75BW.js +0 -2
- package/dist/chunk-2R3V3PSD.js +0 -4
- package/dist/chunk-2WC2OEDO.js +0 -4
- package/dist/chunk-35NLDRZC.js +0 -2
- package/dist/chunk-3AF4TUFK.js +0 -3
- package/dist/chunk-3D3QG236.js +0 -2
- package/dist/chunk-3FHOF22C.js +0 -21
- package/dist/chunk-3JKSW6LJ.js +0 -2
- package/dist/chunk-3L2ZBPEX.js +0 -133
- package/dist/chunk-3PJABJSU.js +0 -2
- package/dist/chunk-3SVF22I5.js +0 -2
- package/dist/chunk-3WR4E3A3.js +0 -3
- package/dist/chunk-4FTZ4P5G.js +0 -2
- package/dist/chunk-4UX2F3JX.js +0 -2
- package/dist/chunk-4WNW27SX.js +0 -2
- package/dist/chunk-5ENOG4VP.js +0 -61
- package/dist/chunk-64BFSI5I.js +0 -2
- package/dist/chunk-66DVSJQG.js +0 -455
- package/dist/chunk-6HFCYNYE.js +0 -9
- package/dist/chunk-6PQNKL3G.js +0 -3
- package/dist/chunk-6V5CNXL6.js +0 -2
- package/dist/chunk-6VVV4WRR.js +0 -4
- package/dist/chunk-7BWFZPPZ.js +0 -2
- package/dist/chunk-7CYG22FH.js +0 -2
- package/dist/chunk-7F45LJKI.js +0 -2
- package/dist/chunk-7IWV2EG3.js +0 -3
- package/dist/chunk-7KCZELVM.js +0 -2
- package/dist/chunk-AFHTBORT.js +0 -2
- package/dist/chunk-AVRYW5OZ.js +0 -2
- package/dist/chunk-B3X6KU75.js +0 -2
- package/dist/chunk-B5D7QPBE.js +0 -4
- package/dist/chunk-BBCIS4DX.js +0 -16
- package/dist/chunk-BDUVI7TO.js +0 -3
- package/dist/chunk-BE7ZZTMC.js +0 -2
- package/dist/chunk-BHVUJOCQ.js +0 -3
- package/dist/chunk-BJT7LSPK.js +0 -3
- package/dist/chunk-BKVWUP7Y.js +0 -2
- package/dist/chunk-BQGB4HBD.js +0 -2
- package/dist/chunk-BRV7PIFF.js +0 -2
- package/dist/chunk-CEEZJXEF.js +0 -2
- package/dist/chunk-CIYLO6SI.js +0 -7
- package/dist/chunk-CJZXN4NU.js +0 -2
- package/dist/chunk-CNO7TOKL.js +0 -2
- package/dist/chunk-COF23M5F.js +0 -2
- package/dist/chunk-CWFP7GM5.js +0 -2
- package/dist/chunk-D2DHWI3D.js +0 -2
- package/dist/chunk-D4N5SQ2M.js +0 -4
- package/dist/chunk-DBRSYFXR.js +0 -2
- package/dist/chunk-DHUIOLDT.js +0 -2
- package/dist/chunk-DIRJWYBM.js +0 -6
- package/dist/chunk-DIUFNHRJ.js +0 -35
- package/dist/chunk-DRENNWRG.js +0 -2
- package/dist/chunk-DTZCKZEU.js +0 -4
- package/dist/chunk-DULC3QFP.js +0 -5
- package/dist/chunk-DYGHBZ2N.js +0 -16
- package/dist/chunk-E5R6AQ73.js +0 -40
- package/dist/chunk-E73UNJTF.js +0 -38
- package/dist/chunk-EKV5HX33.js +0 -2
- package/dist/chunk-EQHFIL6T.js +0 -3
- package/dist/chunk-ESIQ66Z7.js +0 -2
- package/dist/chunk-EVFUMY4R.js +0 -3
- package/dist/chunk-F7DY272B.js +0 -2
- package/dist/chunk-FBN2FGXG.js +0 -2
- package/dist/chunk-FDLOBR6P.js +0 -4
- package/dist/chunk-FESCRNVV.js +0 -5
- package/dist/chunk-FFRKR4EQ.js +0 -2
- package/dist/chunk-FGA2U4OR.js +0 -8
- package/dist/chunk-FIQRSHVM.js +0 -2
- package/dist/chunk-FPYLNQPT.js +0 -2
- package/dist/chunk-FRUSVINH.js +0 -2
- package/dist/chunk-GSP44ENC.js +0 -2
- package/dist/chunk-GUFSG5TX.js +0 -2
- package/dist/chunk-GYIZ4NXB.js +0 -2
- package/dist/chunk-GZIUDL6G.js +0 -2
- package/dist/chunk-H5EXS3HM.js +0 -2
- package/dist/chunk-HCXEQRFF.js +0 -18
- package/dist/chunk-HEHOQQKH.js +0 -2
- package/dist/chunk-HKGFPJ4T.js +0 -4
- package/dist/chunk-HLZTEXRA.js +0 -2
- package/dist/chunk-HOENASQM.js +0 -3
- package/dist/chunk-HVF5VBG6.js +0 -2
- package/dist/chunk-I55I7XXP.js +0 -2
- package/dist/chunk-IDFEUFKS.js +0 -2
- package/dist/chunk-IHGQTTVW.js +0 -2
- package/dist/chunk-IICPE7B2.js +0 -20
- package/dist/chunk-IL676XCC.js +0 -18
- package/dist/chunk-IW5XQG5G.js +0 -2
- package/dist/chunk-IZDPJ2QI.js +0 -2
- package/dist/chunk-J66VOFW6.js +0 -5
- package/dist/chunk-JFMEXGFE.js +0 -2
- package/dist/chunk-JGKUET5J.js +0 -3
- package/dist/chunk-JS4PGXMV.js +0 -3
- package/dist/chunk-JWTGMPIT.js +0 -80
- package/dist/chunk-JYR66JN5.js +0 -5
- package/dist/chunk-KFOYCQAJ.js +0 -9
- package/dist/chunk-KLFEXGQA.js +0 -2
- package/dist/chunk-KMVGRIO2.js +0 -2
- package/dist/chunk-KYSDI3GE.js +0 -5
- package/dist/chunk-L6PJPETJ.js +0 -29
- package/dist/chunk-LDVT66YM.js +0 -2
- package/dist/chunk-LEECKFCJ.js +0 -2
- package/dist/chunk-LMZ5PRUV.js +0 -2
- package/dist/chunk-LQRQN2XA.js +0 -2
- package/dist/chunk-LXABEJX3.js +0 -2
- package/dist/chunk-MNV5FSBW.js +0 -3
- package/dist/chunk-MPQ4OTBM.js +0 -2
- package/dist/chunk-MTDBHTSF.js +0 -2
- package/dist/chunk-MV3CDXPI.js +0 -38
- package/dist/chunk-MWN53KRN.js +0 -60
- package/dist/chunk-MXNGIEPU.js +0 -3
- package/dist/chunk-N2ZSIIGR.js +0 -117
- package/dist/chunk-N5B2NILC.js +0 -5
- package/dist/chunk-NJITK2GP.js +0 -2
- package/dist/chunk-NOGJXYFO.js +0 -2
- package/dist/chunk-NOYBFVJA.js +0 -554
- package/dist/chunk-NWQXSFFU.js +0 -3
- package/dist/chunk-ODDUPDP7.js +0 -13
- package/dist/chunk-OLIWTZI3.js +0 -3
- package/dist/chunk-OLNV6I6U.js +0 -2
- package/dist/chunk-OR2E3AGZ.js +0 -2
- package/dist/chunk-OSR2GEHQ.js +0 -2
- package/dist/chunk-OSSESPDX.js +0 -3
- package/dist/chunk-OWOOWNJ5.js +0 -7
- package/dist/chunk-P42EIXTA.js +0 -2
- package/dist/chunk-PJFGPYTU.js +0 -2
- package/dist/chunk-PP7KNN7L.js +0 -2
- package/dist/chunk-PU7T5QYQ.js +0 -2
- package/dist/chunk-PWWAJSKV.js +0 -74
- package/dist/chunk-PZL5T7SU.js +0 -73
- package/dist/chunk-QBE3YX64.js +0 -23
- package/dist/chunk-QGVTFRY2.js +0 -7
- package/dist/chunk-QOJONDS7.js +0 -2
- package/dist/chunk-QU5XRYB5.js +0 -4
- package/dist/chunk-QUU5OBVK.js +0 -11
- package/dist/chunk-RBLQNW26.js +0 -20
- package/dist/chunk-RTQ7NEKG.js +0 -81
- package/dist/chunk-SQXRS7BG.js +0 -4
- package/dist/chunk-SSK6LDPC.js +0 -2
- package/dist/chunk-SZHGTCPP.js +0 -7
- package/dist/chunk-T4N4P2K5.js +0 -16
- package/dist/chunk-TA3QKLLU.js +0 -2
- package/dist/chunk-TEBQMNVI.js +0 -43
- package/dist/chunk-TPFHAQ2G.js +0 -2
- package/dist/chunk-TQPCBMWT.js +0 -5
- package/dist/chunk-TQZV7KV4.js +0 -2
- package/dist/chunk-TRNAEQ6P.js +0 -3
- package/dist/chunk-TY7CRN3Z.js +0 -2
- package/dist/chunk-UHFYCMZO.js +0 -35
- package/dist/chunk-UICY4GTQ.js +0 -7
- package/dist/chunk-UVGEWT4Y.js +0 -26
- package/dist/chunk-UXW33INU.js +0 -29
- package/dist/chunk-VMPRET3I.js +0 -5
- package/dist/chunk-VNLGKHS6.js +0 -6
- package/dist/chunk-VQILFTEH.js +0 -2
- package/dist/chunk-VUPHCS7Y.js +0 -57
- package/dist/chunk-VVZSBTSU.js +0 -23
- package/dist/chunk-VZRNID6A.js +0 -2
- package/dist/chunk-W5OXRYGE.js +0 -7
- package/dist/chunk-W6STWDQI.js +0 -57
- package/dist/chunk-W7CXK74K.js +0 -2
- package/dist/chunk-WB3WYIRE.js +0 -4
- package/dist/chunk-WDNVY4E7.js +0 -20
- package/dist/chunk-WK46TNUM.js +0 -3
- package/dist/chunk-WNTFFKAX.js +0 -12
- package/dist/chunk-WOIKCX6A.js +0 -2
- package/dist/chunk-WUN6KBHV.js +0 -2
- package/dist/chunk-WYCTJDVR.js +0 -2
- package/dist/chunk-WYPL7GF7.js +0 -2
- package/dist/chunk-XDAUYDFT.js +0 -2
- package/dist/chunk-XDQMU3BT.js +0 -2
- package/dist/chunk-XFA4SSO3.js +0 -3
- package/dist/chunk-XGZEP6GR.js +0 -8
- package/dist/chunk-XPDPNWTQ.js +0 -368
- package/dist/chunk-XRYABF57.js +0 -8
- package/dist/chunk-YBGKCQIS.js +0 -2
- package/dist/chunk-YEN6CYC7.js +0 -16
- package/dist/chunk-YF5IB2LF.js +0 -2
- package/dist/chunk-YI2AWIHC.js +0 -3
- package/dist/chunk-YPWBKGFU.js +0 -2
- package/dist/chunk-YPWHBBIS.js +0 -2
- package/dist/chunk-YSH6U3L4.js +0 -3
- package/dist/chunk-YU5DZUZI.js +0 -10
- package/dist/chunk-YWO5DDRC.js +0 -16
- package/dist/chunk-Z4CDXYNQ.js +0 -2
- package/dist/chunk-ZF5KHH7C.js +0 -2
- package/dist/chunk-ZOHS7AQV.js +0 -21
- package/dist/chunk-ZTI4SBFV.js +0 -3
- package/dist/code-MI6F2TTU.js +0 -2
- package/dist/code-result-json-FXALY4HE.js +0 -2
- package/dist/command-descriptors-P34VABY5.js +0 -343
- package/dist/dataflow-4KEMJPC6.js +0 -2
- package/dist/dependence-slice-R7FPWD5M.js +0 -2
- package/dist/deps-7EMQUYUT.js +0 -2
- package/dist/direct-navigation-6YO234F2.js +0 -3
- package/dist/entry-map-KOOLR26E.js +0 -2
- package/dist/files-OPIPJIGZ.js +0 -2
- package/dist/graph-evidence-Bjyky2V4.d.ts +0 -126
- package/dist/hierarchy-QPD2CAER.js +0 -2
- package/dist/imports-M6HUXRXC.js +0 -2
- package/dist/members-I5MEFOCT.js +0 -2
- package/dist/methods-5JYGGHXA.js +0 -2
- package/dist/next-anchor-candidates-BwMczMvX.d.ts +0 -90
- package/dist/output-continuation-command-UPQAAKBP.js +0 -3
- package/dist/output-pagination-3OFL2MJV.js +0 -19
- package/dist/project-reindex-UKKQ5PLS.js +0 -3
- package/dist/queries/anchors.d.ts +0 -123
- package/dist/queries/anchors.js +0 -2
- package/dist/queries/complexity-hotspots.d.ts +0 -40
- package/dist/queries/complexity-hotspots.js +0 -2
- package/dist/queries/convergence.d.ts +0 -33
- package/dist/queries/convergence.js +0 -2
- package/dist/queries/dataflow.d.ts +0 -77
- package/dist/queries/dataflow.js +0 -2
- package/dist/queries/deep-chains.d.ts +0 -5
- package/dist/queries/deep-chains.js +0 -2
- package/dist/queries/extract-candidates.d.ts +0 -52
- package/dist/queries/extract-candidates.js +0 -2
- package/dist/queries/isolated.d.ts +0 -24
- package/dist/queries/isolated.js +0 -2
- package/dist/queries/plan-context.d.ts +0 -33
- package/dist/queries/plan-context.js +0 -2
- package/dist/queries/reference-neighborhood.d.ts +0 -4
- package/dist/queries/reference-neighborhood.js +0 -2
- package/dist/queries/reference-reachability.d.ts +0 -48
- package/dist/queries/reference-reachability.js +0 -2
- package/dist/queries/self-audit.d.ts +0 -63
- package/dist/queries/self-audit.js +0 -2
- package/dist/queries/similar-chains.d.ts +0 -48
- package/dist/queries/similar-chains.js +0 -2
- package/dist/queries/slice.d.ts +0 -4
- package/dist/queries/slice.js +0 -2
- package/dist/queries/stale-abstractions.d.ts +0 -72
- package/dist/queries/stale-abstractions.js +0 -2
- package/dist/queries/system-map.d.ts +0 -449
- package/dist/queries/system-map.js +0 -2
- package/dist/queries/trace.js +0 -2
- package/dist/queries/twin-ab.d.ts +0 -66
- package/dist/queries/twin-ab.js +0 -2
- package/dist/queries/value-flow.d.ts +0 -43
- package/dist/queries/value-flow.js +0 -2
- package/dist/queries/wrapper-candidates.d.ts +0 -34
- package/dist/queries/wrapper-candidates.js +0 -2
- package/dist/refs-PSU4JZZW.js +0 -2
- package/dist/refs-pagination-JG6CJMRC.js +0 -2
- package/dist/slice-HYRATV64.js +0 -2
- package/dist/source-snippet-_wrcgmZc.d.ts +0 -15
- package/dist/stats-OOJ74B32.js +0 -2
- package/dist/surface-VTGDYWF5.js +0 -2
- package/dist/symbol-resolution-WD5EU5JE.js +0 -2
- package/dist/system-LRQNFOR2.js +0 -2
- package/dist/trace-F4B6OLL4.js +0 -2
- package/dist/value-flow-VRPZY72V.js +0 -2
- package/skills/concrete-plan/SKILL.md +0 -8
- package/skills/concrete-plan/agents/openai.yaml +0 -4
package/dist/reindex.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
VALUES (?, ?, NULL, ?)`),c=i.transaction(l=>{let d=0;for(let
|
|
3
|
-
`).filter(r=>r&&t.has(et(r).toLowerCase())).sort()}catch{return null}}function vs(e,t){let n=new Set,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),a=e.prepare(`SELECT relative_path FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let s of a)n.add(s.relative_path)}return n}function Is(e){return et(e).toLowerCase()===".vue"?"vue":et(e).replace(/^\./,"").toLowerCase()||"source"}import{dirname as Es,join as Ts}from"path";function ci(e={}){return{id:"runtime-boundaries",facts:["runtime-boundary-observation","runtime-boundary-link"],run:async({projectRoot:t,dbPath:n,onStatus:r})=>{let i=new V({projectRoot:t,dbPath:n,indexPath:e.indexPath??Ts(Es(n),"index.scip"),...e.evidenceDbPath?{evidenceDbPath:e.evidenceDbPath}:{}}),o,a=!1,s=!1;try{let u=e.reuseExisting||e.affectedFiles?jr(i):null;e.reuseExisting&&u?.extractorVersion===Ar?(o=u,a=!0):(o=await Mr(i,{...u?{previousGraph:u}:{},...e.affectedFiles?{affectedFiles:e.affectedFiles}:{},...e.forceDerivedRebuild?{forceDerivedRebuild:!0}:{},profileSpan:I}),s=(o.coverage.filesReused??0)>0)}finally{i.close()}a||Lr(n,o);let c={reused:a,incrementallyUpdated:s,observations:o.observations.length,links:o.links.length,frontiers:o.frontiers.length,filesScanned:o.coverage.filesScanned,errors:o.coverage.extractionErrors.length,phases:o.coverage.phases};return r?.(c.reused?`Reused ${c.observations} cached runtime-boundary observation(s) and ${c.links} link(s).`:c.incrementallyUpdated?`Incrementally refreshed runtime-boundary observations (${c.filesScanned-(o.coverage.filesReused??0)} file(s) extracted, ${o.coverage.filesReused??0} reused) and rebuilt ${c.links} link(s).`:`Extracted ${c.observations} runtime-boundary observation(s), ${c.links} link(s), and ${c.frontiers} unresolved frontier(s).`),!a&&o.coverage.phases&&r?.(`Runtime-boundary phases: ${o.coverage.phases.map(u=>`${u.id} ${u.durationMs.toFixed(0)}ms`).join(", ")}.`),c}}}function _e(e){let t=new Set;for(let n of e.uncertainty)t.add(n);e.projectIdentityChanged&&t.add("project-identity-changed");for(let n of e.changes)n.kind==="added"&&t.add("file-added"),n.kind==="deleted"&&t.add("file-deleted"),n.inputKind==="config"&&t.add("configuration-changed"),n.inputKind==="ambient"&&t.add("ambient-declaration-changed"),n.inputKind==="other"&&t.add("unclassified-input");return{fullProject:t.size>0,reasons:[...t].sort()}}function Fe(e,t,n){let r=e.changes.map(s=>s.path).sort();if(r.length===0&&!e.projectIdentityChanged&&e.uncertainty.length===0)return{mode:"none",changedFiles:r,affectedFiles:[],reasons:[]};let i=new Set(n),o=_e(e),a=new Set(o.reasons);return r.some(s=>!i.has(s))&&a.add("changed-file-outside-project"),t===null?(a.add("dependency-graph-unavailable"),ui(r,i,a)):a.size>0?ui(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:ws(r,t,i),reasons:[]}}function ui(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function ws(e,t,n){let r=new Map;for(let[a,s]of t)if(n.has(a))for(let c of s){if(!n.has(c))continue;let u=r.get(c)??new Set;u.add(a),r.set(c,u)}let i=new Set(e),o=[...e];for(let a=0;a<o.length;a+=1){let s=o[a];if(s!==void 0)for(let c of r.get(s)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}import{createHash as ks}from"crypto";import{existsSync as _s}from"fs";import{dirname as Fs,join as li}from"path";var Cs="<global-symbols>";function Os(e){let t=[];for(let n of e.all(`
|
|
1
|
+
import{e as Yr,f as Kr,g as Xr,i as Qr,j as fi}from"./chunk-F2V2LPET.js";import{a as A}from"./chunk-NLOQOBXI.js";import{$ as pi,A as Ut,B as Qe,C as Zr,D as ei,E as Gt,F as ti,G as Cs,H as qt,I as ni,J as ri,L as ii,M as oi,O as Ze,P as ai,Q as si,R as et,S as G,T as tt,V as ci,W as Wt,X as ui,Y as li,Z as nt,_ as di,a as ye,aa as mi,b as Mr,c as Ar,d as Bt,e as we,f as Se,g as oe,h as Je,i as Lr,j as jr,k as Nr,l as $r,m as Vr,n as Ye,o as Br,p as Ur,q as Ke,r as Xe,s as Gr,t as qr,u as Wr,v as Hr,x as zr,z as Jr}from"./chunk-K4CN7GXK.js";import{a as _r}from"./chunk-J2TMAIN5.js";import{a as Jn,b as M,d as Yn,e as Dt,f as Kn,h as Xn,p as er,r as tr,v as Ot}from"./chunk-PKN354TH.js";import{a as fe,b as Ee,c as ge,d as At,e as ze,f as Er,g as wr,h as Lt,k as jt,l as kr,m as Nt,n as $t,o as Fr,p as Cr,q as Dr,r as Vt,u as Or}from"./chunk-73AAKPUC.js";import{b as he}from"./chunk-KZBJWZJB.js";import{g as Tr}from"./chunk-4WTUBQ36.js";import"./chunk-NZAXKGRL.js";import"./chunk-KK7GPALL.js";import"./chunk-YNQCGEQE.js";import"./chunk-FMRN2TRL.js";import{a as zn,b as Pe,c as Y,d as me,e as x,i as Qn,j as Zn,k as Mt,l as Ir}from"./chunk-DA7RPPDF.js";import"./chunk-E3FDPXZK.js";import"./chunk-KHWRRPV4.js";import"./chunk-72AD6ZRR.js";import"./chunk-YUKYB54I.js";import{b as br,c as We,d as He,e as Rr,f as xr,g as vr}from"./chunk-GCKCF5FL.js";import"./chunk-DVFP6PZI.js";import{e as Pr}from"./chunk-5D2LVK7O.js";import"./chunk-7WTPQ4NX.js";import{X as yr,Y as Sr,a as qe}from"./chunk-FVULPZDF.js";import"./chunk-D3FDISIC.js";import"./chunk-A2IIGFMJ.js";import"./chunk-PH52RA7D.js";import{a as mr,e as _t,l as fr,q as gr,t as g,u as L,v as hr}from"./chunk-GVWX5T43.js";import{l as de,m as V,n as pe,o as Ne,p as Ft,q as Hn}from"./chunk-T6DK3ZP7.js";import{L as $e,Q as nr,R as U,S as Ie,T as Ve,U as rr,V as ir,W as or,Z as Be,e as kt,g as je,h as Wn,ha as ar,i as re,ja as Ue,l as ie,la as sr,n as k,na as cr,o as z,p as Ct,q as Te,qa as ur,t as B,u as _,ua as lr,v as J,va as Ge,wa as dr,xa as pr}from"./chunk-5TNQJUR2.js";import gi from"better-sqlite3";import{createHash as hi}from"crypto";import{dirname as rt,join as Ds}from"path";function yi(e){if(!e.request.modifiedFiles.length||e.request.removedFiles.length)return null;let t;try{t=er({projectRoot:e.projectRoot,dbPath:e.dbPath,indexPath:Ds(rt(e.dbPath),"index.scip")});let n=Os(e,t.generation);if(!n||!Ms(e,n.snapshot))return null;let r=As(t.generation.databasePath,n.snapshot,e.request.modifiedFiles);if(!r)return null;let i=new ye,o=new Set(n.snapshot.files.map(s=>s.path)),a=rt(e.dbPath);for(let s of n.overlay.overlays)s.blobHash===null||!o.has(s.relativePath)||i.setReference({...s,blobHash:s.blobHash},()=>$r(a,s));return{sources:r,documents:i}}catch{return null}finally{t?.release()}}function Os(e,t){let n=tr(e.dbPath);if(t.source!=="immutable"||n?.currentGeneration!==t.identity)return null;let r=V(t.metadataRaw),i=Ne(r);if(!i||Si(i)!==e.baseGeneration)return null;let o=re(pe(r)?.fingerprint);if(!o||!_s(e,o))return null;let a=n.publication?.typescriptOverlayGeneration??we(o,e.request.producerIdentity),s=Ye(rt(e.dbPath),a);return s?.producerIdentity!==e.request.producerIdentity||s.projectIdentity!==e.request.projectIdentity?null:{snapshot:o,overlay:s}}function _s(e,t){if(t.typescriptProjectMode!=="single"&&t.typescriptProjectMode!=="workspace")return!1;let n=t.typescriptProjectMode==="workspace"?U(e.projectRoot,t.typescriptProjects):["."];return n.length!==1||n[0]!==e.request.projectArgument?!1:e.request.tsconfigPath===(n[0]==="."?"tsconfig.json":`${n[0]}/tsconfig.json`)}function Ms(e,t){let n=Ue(e.projectRoot,rt(e.dbPath),()=>Ge(e.projectRoot,t.languages,{...t,typescriptProjectMode:t.typescriptProjectMode})),r=new Map(t.files.map(o=>[o.path,o])),i=new Set(e.request.modifiedFiles);if(r.size!==n.files.length||i.size!==e.request.modifiedFiles.length)return!1;for(let o of i)if(!r.has(o)||je(o,t.languages)!=="source")return!1;return n.files.every(o=>{let a=r.get(o.path);return!!a&&(i.has(o.path)||o.hash===a.hash&&o.size===a.size)})}function As(e,t,n){let r=new Map(t.files.map(o=>[o.path,o])),i=new gi(e,{readonly:!0,fileMustExist:!0});try{let o=new Map,a=i.prepare("SELECT text FROM documents WHERE relative_path = ?");for(let s of n){let c=a.get(s),u=r.get(s);if(typeof c?.text!="string"||Buffer.byteLength(c.text)!==u.size||Si(c.text)!==u.hash)return null;o.set(s,c.text)}return o}finally{i.close()}}function Si(e){return hi("sha256").update(e).digest("hex")}function Ht(e){let t=re(e.fingerprint);if(!t)return 0;let n=new Map(t.files.map(i=>[i.path,i])),r=new gi(e.dbPath);try{let i=r.prepare("SELECT relative_path FROM documents WHERE text IS NULL").all(),o=new Set([...i.map(s=>s.relative_path),...e.changedFiles??[]]),a=r.prepare("UPDATE documents SET text = ? WHERE relative_path = ? AND (text IS NULL OR text != ?)");return r.transaction(()=>{let s=0;for(let c of o){let u=n.get(c);if(!u||!/\.[cm]?[jt]sx?$/.test(c))continue;let l;try{l=cr(e.projectRoot,c)}catch{continue}let d=l.toString("utf8");!Buffer.from(d,"utf8").equals(l)||l.length!==u.size||hi("sha256").update(l).digest("hex")!==u.hash||(s+=a.run(d,c,d).changes)}return s})()}finally{r.close()}}import{createHash as Kp}from"crypto";import{existsSync as C,mkdirSync as Pt,mkdtempSync as Xp,readdirSync as rs,renameSync as is,rmSync as se,statSync as os}from"fs";import{basename as xt,dirname as h,extname as Qp,join as w,resolve as Ja}from"path";import{platform as as}from"os";function bi(e){let t=e?.match(/--max[-_]old[-_]space[-_]size(?:=|\s+)(\d+)/u);if(!t)return;let n=Number.parseInt(t[1],10);return Number.isInteger(n)&&n>0?n:void 0}function Ri(e,t){return[(e??"").replace(/(?:^|\s)--max[-_]old[-_]space[-_]size(?:=|\s+)\d+/gu," ").trim(),`--max-old-space-size=${t}`].filter(Boolean).join(" ")}import{execFileSync as Ls}from"child_process";import{constants as js,copyFileSync as xi,linkSync as Ns,rmSync as $s,statSync as Vs}from"fs";import{platform as Bs}from"os";var Us=Object.freeze({size:e=>Vs(e).size,clone:Hs,copy:(e,t)=>xi(e,t),link:(e,t)=>Ns(e,t),remove:e=>$s(e,{force:!0})}),Gs=new Set(["EXDEV","EPERM","EMLINK","ENOTSUP","EOPNOTSUPP","ENOSYS","EINVAL"]),qs=new Set(["ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL","EXDEV","ENOTTY"]);function K(e,t,n=Us,r={}){let i=n.size(e);n.remove?.(t);try{return n.clone(e,t),{method:"reflink",bytes:i}}catch(o){if(!Js(o))throw o}if(r.shareImmutable&&n.link)try{return n.link(e,t),{method:"link",bytes:i}}catch(o){if(!Ws(o))throw o}return n.copy(e,t),{method:"copy",bytes:i}}function Ws(e){let t=e?.code;return typeof t=="string"&&Gs.has(t)}function Hs(e,t){if(Bs()!=="darwin"){xi(e,t,js.COPYFILE_FICLONE_FORCE);return}try{Ls("/bin/cp",["-c",e,t],{timeout:6e4,maxBuffer:64*1024,stdio:["ignore","ignore","pipe"]})}catch(n){throw zs(n)}}function zs(e){let t=e?.stderr,n=Buffer.isBuffer(t)?t.toString("utf8"):t??"";return/operation not supported|not supported/i.test(n)?Object.assign(e instanceof Error?e:new Error(String(e)),{code:"ENOTSUP"}):/cross-device link/i.test(n)?Object.assign(e instanceof Error?e:new Error(String(e)),{code:"EXDEV"}):e}function Js(e){let t=e?.code;return t!==void 0&&qs.has(t)}function vi(){return{reflinkedBytes:0,fallbackCopiedBytes:0,incrementalWrittenBytes:0}}function X(e,t){t.method==="reflink"||t.method==="link"?e.reflinkedBytes+=t.bytes:e.fallbackCopiedBytes+=t.bytes}function it(e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error("incremental write bytes must be a non-negative integer");e.incrementalWrittenBytes=(e.incrementalWrittenBytes??0)+t}import Ys from"better-sqlite3";import{execFileSync as Ks}from"child_process";import{existsSync as Xs,readdirSync as Qs}from"fs";import{extname as ot,join as Zs}from"path";function Q(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Pi({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Pi(e){let t=new Set((e.extensions??yr).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Xs(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=_r(e.projectRoot),r=ec(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Ys(e.dbPath);try{let o=nc(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
|
|
2
|
+
VALUES (?, ?, NULL, ?)`),c=i.transaction(l=>{let d=0;for(let p of l){if(o.has(p))continue;let m=ur(e.projectRoot,p,{inputKind:"auxiliary source file"}),f=a.run(rc(p),p,m);d+=Number(f.changes)}return d})(r),u={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${u.existing} already present).`),u}finally{i.close()}}function ec(e,t){let n=tc(e,t);if(n)return n;let r=[],i=o=>{let a=o?Zs(e,o):e,s;try{s=Qs(a,{withFileTypes:!0})}catch{return}for(let c of s){if(Sr.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(ot(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function tc(e,t){try{return Ks("git",["-C",e,"ls-files","-z","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}).split("\0").filter(r=>r&&t.has(ot(r).toLowerCase())).sort()}catch{return null}}function nc(e,t){let n=new Set,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),a=e.prepare(`SELECT relative_path FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let s of a)n.add(s.relative_path)}return n}function rc(e){return ot(e).toLowerCase()===".vue"?"vue":ot(e).replace(/^\./,"").toLowerCase()||"source"}import{dirname as ic,join as oc}from"path";function Ti(e={}){return{id:"runtime-boundaries",facts:["runtime-boundary-observation","runtime-boundary-link"],run:async({projectRoot:t,dbPath:n,onStatus:r})=>{let i=new A({projectRoot:t,dbPath:n,indexPath:e.indexPath??oc(ic(n),"index.scip"),...e.evidenceDbPath?{evidenceDbPath:e.evidenceDbPath}:{}}),o,a=!1,s=!1;try{let u=e.reuseExisting||e.affectedFiles?Qr(i):null;e.reuseExisting&&u?.extractorVersion===Yr?(o=u,a=!0):(o=await sc(i,u,e),s=(o.coverage.filesReused??0)>0)}finally{i.close()}a||Xr(n,o);let c={reused:a,incrementallyUpdated:s,observations:o.observations.length,links:o.links.length,frontiers:o.frontiers.length,filesScanned:o.coverage.filesScanned,errors:o.coverage.extractionErrors.length,phases:o.coverage.phases};return ac(c,o,r),c}}}function ac(e,t,n){n?.(e.reused?`Reused ${e.observations} cached runtime-boundary observation(s) and ${e.links} link(s).`:e.incrementallyUpdated?`Incrementally refreshed runtime-boundary observations (${e.filesScanned-(t.coverage.filesReused??0)} file(s) extracted, ${t.coverage.filesReused??0} reused) and rebuilt ${e.links} link(s).`:`Extracted ${e.observations} runtime-boundary observation(s), ${e.links} link(s), and ${e.frontiers} unresolved frontier(s).`),!e.reused&&t.coverage.phases&&n?.(`Runtime-boundary phases: ${t.coverage.phases.map(r=>`${r.id} ${r.durationMs.toFixed(0)}ms`).join(", ")}.`)}function sc(e,t,n){return Kr(e,{...t?{previousGraph:t}:{},...n.affectedFiles?{affectedFiles:n.affectedFiles}:{},...n.forceDerivedRebuild?{forceDerivedRebuild:!0}:{},...n.compilerFactsUnchanged?{compilerFactsUnchanged:!0}:{},profileSpan:g})}var cc={config:"configuration-changed",ambient:"ambient-declaration-changed",other:"unclassified-input"};function ae(e,t={}){let n=new Set;for(let r of e.uncertainty)n.add(r);e.projectIdentityChanged&&n.add("project-identity-changed"),t.maxChanges!==void 0&&e.changes.length>t.maxChanges&&n.add("change-limit-exceeded");for(let r of e.changes){r.kind==="added"&&n.add("file-added"),r.kind==="deleted"&&t.deletedFiles!=="closure"&&n.add("file-deleted");let i=cc[r.inputKind];i&&n.add(i)}return{fullProject:n.size>0,reasons:[...n].sort()}}function st(e,t,n){let r=e.changes.map(s=>s.path).sort();if(r.length===0&&!e.projectIdentityChanged&&e.uncertainty.length===0)return{mode:"none",changedFiles:r,affectedFiles:[],reasons:[]};let i=new Set(n),o=ae(e),a=new Set(o.reasons);return r.some(s=>!i.has(s))&&a.add("changed-file-outside-project"),t===null?(a.add("dependency-graph-unavailable"),at(r,i,a)):a.size>0?at(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:uc(r,t,i),reasons:[]}}function at(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function uc(e,t,n){let r=lc(t,n),i=new Set(e),o=[...e];for(let a=0;a<o.length;a+=1){let s=o[a];if(s!==void 0)for(let c of r.get(s)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}function lc(e,t){let n=new Map;for(let[r,i]of e)if(t.has(r))for(let o of i){if(!t.has(o))continue;let a=n.get(o)??new Set;a.add(r),n.set(o,a)}return n}import{createHash as dc}from"crypto";import{existsSync as pc}from"fs";import{dirname as mc,join as Ii}from"path";var fc="<global-symbols>";function gc(e){let t=[];for(let n of e.all(`
|
|
4
3
|
SELECT relative_path, language, position_encoding, text
|
|
5
4
|
FROM documents
|
|
6
5
|
`))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
|
|
@@ -27,7 +26,7 @@ import{a as V}from"./chunk-WDNVY4E7.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F
|
|
|
27
26
|
FROM defn_enclosing_ranges r
|
|
28
27
|
JOIN documents d ON d.id = r.document_id
|
|
29
28
|
JOIN global_symbols g ON g.id = r.symbol_id
|
|
30
|
-
`))t.push({relativePath:n.relative_path,kind:"definition",values:
|
|
29
|
+
`))t.push({relativePath:n.relative_path,kind:"definition",values:zt(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
|
|
31
30
|
SELECT d.relative_path,
|
|
32
31
|
c.chunk_index,
|
|
33
32
|
m.role,
|
|
@@ -42,7 +41,7 @@ import{a as V}from"./chunk-WDNVY4E7.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F
|
|
|
42
41
|
JOIN chunks c ON c.id = m.chunk_id
|
|
43
42
|
JOIN documents d ON d.id = c.document_id
|
|
44
43
|
JOIN global_symbols g ON g.id = m.symbol_id
|
|
45
|
-
`))t.push({relativePath:n.relative_path,kind:"mention",values:
|
|
44
|
+
`))t.push({relativePath:n.relative_path,kind:"mention",values:zt(n,[n.chunk_index,n.role])});for(let n of e.all(`
|
|
46
45
|
SELECT g.symbol,
|
|
47
46
|
g.display_name,
|
|
48
47
|
g.kind,
|
|
@@ -56,8 +55,8 @@ import{a as V}from"./chunk-WDNVY4E7.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F
|
|
|
56
55
|
) AND NOT EXISTS (
|
|
57
56
|
SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
|
|
58
57
|
)
|
|
59
|
-
`))t.push({relativePath:
|
|
60
|
-
`);n.set(r,o.digest("hex"))}return n}function As(e,t){let n=[],r=[],i=[],o=[],a=new Set([...e.keys(),...t.keys()]);for(let s of[...a].sort()){let c=e.get(s),u=t.get(s);c===void 0?n.push(s):u===void 0?i.push(s):c!==u?r.push(s):o.push(s)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function zt(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),o=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),a=e.affectedFiles.filter(c=>!i.has(c)).sort(),s=t.changedFiles.length-o.length;return{passed:o.length===0,recall:t.changedFiles.length===0?1:s/t.changedFiles.length,affectedRatio:n===0?0:e.affectedFiles.length/n,predictedFiles:[...e.affectedFiles].sort(),actualFiles:[...t.changedFiles],missingFiles:o,extraFiles:a}}function Jt(e,t=Vs){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,i=t.wallNow??t.now,o=r(),a=(u,l)=>{let d=r();return fi(e.refreshResult,u,n?d:i(),Math.max(0,d-o),l)};if(!t.databaseExists(e.previousDbPath))return a("prior-index-unavailable");if(!t.databaseExists(e.candidateDbPath))return a("candidate-index-unavailable");if(e.refreshResult==="rebuilt"&&z(e.previousSnapshot,e.currentSnapshot).changes.length===0)return a("no-input-changes");let s=null,c=null;try{s=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),c=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let u=[...new Set([...t.indexedPaths(s),...t.indexedPaths(c)])].sort(),l=z(e.previousSnapshot,e.currentSnapshot),d=new Set(u),m=l.changes.length>0&&!_e(l).fullProject&&l.changes.every(k=>d.has(k.path)),f=Fe(l,m?t.dependencyGraph(s):new Map,u),y=As(t.factDigests(s),t.factDigests(c)),b=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?b:i()).toISOString(),durationMs:Math.max(0,b-o),manifest:l,plan:f,comparison:y,evaluation:zt(f,y,u.length)}}catch(u){return a("oracle-error",u instanceof Error?u.message:String(u))}finally{di(s),di(c)}}function pi(e,t,n,r=Date.now()){return fi(e,t,r,0,n)}function Ms(e){let t=Fs(e);return{latestPath:li(t,"affected-shadow-latest.json"),historyPath:li(t,"affected-shadow.jsonl")}}function mi(e,t,n=Bs){let r=Ms(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var Ls=8*1024*1024,js=Nr;function Ns(e){let t={historyVersion:1,sourceVersion:e.version,refreshResult:e.refreshResult,recordedAt:e.recordedAt,durationMs:e.durationMs};return e.status==="unavailable"?{...t,status:"unavailable",reason:e.reason,...e.error?{error:e.error}:{}}:{...t,status:"evaluated",mode:e.plan.mode,passed:e.evaluation.passed,recall:e.evaluation.recall,affectedRatio:e.evaluation.affectedRatio,predictedFileCount:e.evaluation.predictedFiles.length,actualFileCount:e.evaluation.actualFiles.length,missingFileCount:e.evaluation.missingFiles.length,fallbackReasons:[...e.plan.reasons]}}function $s(e,t,n=Ls){$r(e,Ns(t),{maxSegmentBytes:n,previousSuffix:js})}function Ht(e,t=[]){let n=[];for(let r of t)n.push(r);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var Vs={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:F,databaseExists:e=>_s(e),openDatabase:(e,t,n)=>new V({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>Ue(e),dependencyGraph:e=>mr(e),factDigests:e=>Os(e)},Bs={appendHistory:$s,writeLatest:(e,t)=>$e(e,t,{spacing:2,trailingNewline:!0})};function fi(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(n).toISOString(),durationMs:r,reason:t,...i?{error:i}:{}}}function di(e){try{e?.close()}catch{}}import{readdirSync as Us}from"fs";import{isAbsolute as gi,join as Gs,resolve as Ws}from"path";var tt="@sourcegraph/scip-typescript@0.4.0",hi="scip-python-plus@0.7.5",yi="github.com/sourcegraph/scip-go@v0.2.7",Si="scip-dotnet@0.2.14",qs="scip_dart@1.6.2",Ri={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>r?{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches",r]}:t?{binary:n,args:["index","--pnpm-workspaces","--output",e,"--no-progress-bar","--no-global-caches"]}:{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]},markerFiles:[...M.typescript],installMethods:[{label:"npm",identity:tt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",tt]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]}),markerFiles:[...M.javascript],installMethods:[{label:"npm",identity:tt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",tt]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...M.java],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...M.scala],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...M.kotlin],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:Se.language,indexerBinary:Se.indexerBinary,checkCommand:`${Se.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:Se.indexerBinary,args:["scip",".","--output",e]}),markerFiles:[...M.rust],installMethods:[],installUrl:Se.installUrl},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:[...M.python],installMethods:[{label:"npm",identity:hi,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",hi]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",gi(r)?r:Ws(e,r)),{binary:n,args:i}},markerFiles:[...M.clojure],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:[...M.ruby],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:[...M.go],installMethods:[{label:"go install",identity:yi,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",yi]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:[...M.cpp],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:[...M.c],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",bi(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...M.csharp],installMethods:[{label:"dotnet",identity:Si,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",bi(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...M.vb],installMethods:[{label:"dotnet",identity:Si,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:[...M.dart],installMethods:[{label:"dart pub",identity:qs,destination:"Dart pub global cache",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart","1.6.2"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({indexerBinary:e})=>gi(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:[...M.php],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function xi(e){if(!(e.projectPath||e.pnpmWorkspaces)){if(e.language==="typescript")return"{}";if(e.language==="javascript")return'{"compilerOptions":{"allowJs":true}}'}}function nt(e){return Ri[e]}function bi(e,t){let n;try{n=Us(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Gs(e,i);return null}import{createHash as Hs}from"crypto";import{existsSync as Xt,rmSync as Pi,statSync as zs}from"fs";import{resolve as Js}from"path";import Ei from"better-sqlite3";var Ys={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},Xs={idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Ti(e){let t=F(),n=vi(e.affectedFiles),r=vi(e.deletedFiles??[],!0),i=new Set(n);if(r.some(s=>!i.has(s)))throw new Error("deleted incremental documents must be included in the affected document set");let o=n.length-r.length;if(Qs(e.previousDbPath,e.miniDbPath,e.candidateDbPath),!Xt(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Xt(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");I("reindex.publish.sqlite-patch.validate-inputs",()=>{Yt(e.previousDbPath,"previous SQLite generation",!1),Yt(e.miniDbPath,"incremental SQLite mini database")}),e.reuseCandidate?I("reindex.publish.sqlite-patch.reuse-candidate",()=>Yt(e.candidateDbPath,"incremental SQLite candidate",!1)):I("reindex.publish.sqlite-patch.clone",()=>{Pi(e.candidateDbPath,{force:!0});let s=oe(e.previousDbPath,e.candidateDbPath);e.writeTelemetry&&ae(e.writeTelemetry,s)});let a=null;try{a=I("reindex.publish.sqlite-patch.open",()=>{let f=new Ei(e.candidateDbPath,{fileMustExist:!0});return f.pragma("busy_timeout = 5000"),f.pragma("foreign_keys = ON"),f.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Kt(f,"main","candidate SQLite generation"),Kt(f,"incremental","incremental SQLite mini database"),f});let{priorAffectedCount:s,previousFactDigests:c}=I("reindex.publish.sqlite-patch.prepare",()=>(tc(a,n,r),{...nc(a,n.length,r.length),previousFactDigests:Qt(a,"main",!0)})),u=K(a,"SELECT COUNT(*) AS value FROM main.documents"),l=a.transaction(()=>{I("reindex.publish.sqlite-patch.transaction.symbol-ownership",()=>rc(a)),I("reindex.publish.sqlite-patch.transaction.shared-definitions",()=>ic(a)),I("reindex.publish.sqlite-patch.transaction.delete",()=>oc(a)),e.onStage?.("after-delete"),I("reindex.publish.sqlite-patch.transaction.reconcile-symbols",()=>ac(a)),e.onStage?.("after-symbol-reconciliation"),I("reindex.publish.sqlite-patch.transaction.insert",()=>sc(a)),e.onStage?.("after-insert"),I("reindex.publish.sqlite-patch.transaction.prune-symbols",()=>cc(a,e.trustedPriorGeneration===!0)),I("reindex.publish.sqlite-patch.transaction.validate",()=>uc(a,o,u,s)),e.onStage?.("before-commit")});I("reindex.publish.sqlite-patch.transaction",()=>l.immediate()),e.writeTelemetry&&Ze(e.writeTelemetry,2*Ks(e.candidateDbPath)),I("reindex.publish.sqlite-patch.integrity",()=>ec(a,"candidate SQLite generation",!e.deferIntegrity&&e.trustedPriorGeneration!==!0));let d=I("reindex.publish.sqlite-patch.validate-facts",()=>lc(a)),m=[...new Set([...c.keys(),...d.keys()])].filter(f=>c.get(f)!==d.get(f)).sort();return a.exec("DETACH DATABASE incremental"),a.close(),a=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:m,durationMs:F()-t}}catch(s){try{a?.close()}finally{Pi(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}function Ks(e){let t=0;for(let n of["-wal","-journal"]){let r=`${e}${n}`;Xt(r)&&(t+=zs(r).size)}return t}function vi(e,t=!1){if(!t&&e.length===0)throw new Error("incremental SQLite publication requires affected documents");let n=[...e].sort();for(let r of n)if(!r||r.startsWith("/")||r.includes("\\")||r.split("/").includes(".."))throw new Error(`invalid affected document path: ${r}`);if(new Set(n).size!==n.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return n}function Qs(e,t,n){let r=[e,t,n].map(i=>Js(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Yt(e,t,n=!0){let r=new Ei(e,{readonly:!0,fileMustExist:!0});try{Kt(r,"main",t),n&&Zs(r,"main",t)}finally{r.close()}}function Kt(e,t,n){for(let[r,i]of Object.entries(Ys)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:l})=>({name:s,type:c.toUpperCase(),notnull:u,pk:l}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(Xs)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),a=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(s=>s.name);if(o?.tbl_name!==i.table||JSON.stringify(a)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}Ii(e,t,"documents",["relative_path"],n),Ii(e,t,"global_symbols",["symbol"],n)}function Ii(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(s=>{if(s.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${s.name}')`).all().map(u=>u.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function Zs(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function ec(e,t,n){if(e.pragma("foreign_keys",{simple:!0})!==1)throw new Error(`${t} lost foreign-key enforcement`);if(!n)return;let r=e.prepare("PRAGMA main.quick_check").pluck().get();if(r!=="ok")throw new Error(`${t} failed quick_check: ${String(r)}`)}function tc(e,t,n){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID"),e.exec("CREATE TEMP TABLE incremental_deleted_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let r=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)"),i=e.prepare("INSERT INTO temp.incremental_deleted_paths(relative_path) VALUES (?)");e.transaction(a=>{for(let s of a)r.run(s);for(let s of n)i.run(s)})(t)}function nc(e,t,n){let r=K(e,"SELECT COUNT(*) AS value FROM incremental.documents"),i=K(e,`SELECT COUNT(*) AS value
|
|
58
|
+
`))t.push({relativePath:fc,kind:"global-symbol",values:zt(n)});return hc(t)}function hc(e){let t=new Map;for(let r of e){let i=JSON.stringify([r.kind,r.values]),o=t.get(r.relativePath)??[];o.push(i),t.set(r.relativePath,o)}let n=new Map;for(let[r,i]of[...t].sort(([o],[a])=>o.localeCompare(a))){let o=dc("sha256");for(let a of i.sort())o.update(String(Buffer.byteLength(a))),o.update(":"),o.update(a),o.update(`
|
|
59
|
+
`);n.set(r,o.digest("hex"))}return n}function yc(e,t){let n=[],r=[],i=[],o=[],a=new Set([...e.keys(),...t.keys()]);for(let s of[...a].sort()){let c=e.get(s),u=t.get(s);c===void 0?n.push(s):u===void 0?i.push(s):c!==u?r.push(s):o.push(s)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function Jt(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),o=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),a=e.affectedFiles.filter(c=>!i.has(c)).sort(),s=t.changedFiles.length-o.length;return{passed:o.length===0,recall:t.changedFiles.length===0?1:s/t.changedFiles.length,affectedRatio:n===0?0:e.affectedFiles.length/n,predictedFiles:[...e.affectedFiles].sort(),actualFiles:[...t.changedFiles],missingFiles:o,extraFiles:a}}function Yt(e,t=Pc){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,i=t.wallNow??t.now,o=r(),a=(u,l)=>{let d=r();return Fi(e.refreshResult,u,n?d:i(),Math.max(0,d-o),l)};if(!t.databaseExists(e.previousDbPath))return a("prior-index-unavailable");if(!t.databaseExists(e.candidateDbPath))return a("candidate-index-unavailable");if(Ec(e))return a("no-input-changes");let s=null,c=null;try{s=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),c=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let u=[...new Set([...t.indexedPaths(s),...t.indexedPaths(c)])].sort(),l=ie(e.previousSnapshot,e.currentSnapshot),d=Ic(l,u,s,t),p=yc(t.factDigests(s),t.factDigests(c)),m=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?m:i()).toISOString(),durationMs:Math.max(0,m-o),manifest:l,plan:d,comparison:p,evaluation:Jt(d,p,u.length)}}catch(u){return a("oracle-error",u instanceof Error?u.message:String(u))}finally{Ei(s),Ei(c)}}function wi(e,t,n,r=Date.now()){return Fi(e,t,r,0,n)}function Sc(e){let t=mc(e);return{latestPath:Ii(t,"affected-shadow-latest.json"),historyPath:Ii(t,"affected-shadow.jsonl")}}function ki(e,t,n=Tc){let r=Sc(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var bc=8*1024*1024,Rc=Zr;function xc(e){let t={historyVersion:1,sourceVersion:e.version,refreshResult:e.refreshResult,recordedAt:e.recordedAt,durationMs:e.durationMs};return e.status==="unavailable"?{...t,status:"unavailable",reason:e.reason,...e.error?{error:e.error}:{}}:{...t,status:"evaluated",mode:e.plan.mode,passed:e.evaluation.passed,recall:e.evaluation.recall,affectedRatio:e.evaluation.affectedRatio,predictedFileCount:e.evaluation.predictedFiles.length,actualFileCount:e.evaluation.actualFiles.length,missingFileCount:e.evaluation.missingFiles.length,fallbackReasons:[...e.plan.reasons]}}function vc(e,t,n=bc){ei(e,xc(t),{maxSegmentBytes:n,previousSuffix:Rc})}function zt(e,t=[]){let n=[];for(let r of t)n.push(r);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var Pc={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:x,databaseExists:e=>pc(e),openDatabase:(e,t,n)=>new A({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>qe(e),dependencyGraph:e=>br(e),factDigests:e=>gc(e)},Tc={appendHistory:vc,writeLatest:(e,t)=>Qn(e,t,{spacing:2,trailingNewline:!0})};function Fi(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(n).toISOString(),durationMs:r,reason:t,...i?{error:i}:{}}}function Ei(e){try{e?.close()}catch{}}function Ic(e,t,n,r){let i=new Set(t),o=e.changes.length>0&&!ae(e).fullProject&&e.changes.every(s=>i.has(s.path));return st(e,o?r.dependencyGraph(n):new Map,t)}function Ec(e){return e.refreshResult!=="rebuilt"?!1:ie(e.previousSnapshot,e.currentSnapshot).changes.length===0}import{readdirSync as wc}from"fs";import{isAbsolute as Ci,join as kc,resolve as Fc}from"path";var ct="@sourcegraph/scip-typescript@0.4.0",Di="scip-python-plus@0.7.5",Oi="github.com/sourcegraph/scip-go@v0.2.7",_i="scip-dotnet@0.2.14",Cc="scip_dart@1.6.2",Ai={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>r?{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches",r]}:t?{binary:n,args:["index","--pnpm-workspaces","--output",e,"--no-progress-bar","--no-global-caches"]}:{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]},markerFiles:[...k.typescript],installMethods:[{label:"npm",identity:ct,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",ct]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]}),markerFiles:[...k.javascript],installMethods:[{label:"npm",identity:ct,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",ct]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...k.java],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...k.scala],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...k.kotlin],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:fe.language,indexerBinary:fe.indexerBinary,checkCommand:`${fe.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:fe.indexerBinary,args:["scip",".","--output",e]}),markerFiles:[...k.rust],installMethods:[],installUrl:fe.installUrl},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:[...k.python],installMethods:[{label:"npm",identity:Di,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",Di]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",Ci(r)?r:Fc(e,r)),{binary:n,args:i}},markerFiles:[...k.clojure],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:[...k.ruby],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:[...k.go],installMethods:[{label:"go install",identity:Oi,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",Oi]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:[...k.cpp],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:[...k.c],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Mi(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...k.csharp],installMethods:[{label:"dotnet",identity:_i,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",Mi(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...k.vb],installMethods:[{label:"dotnet",identity:_i,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:[...k.dart],installMethods:[{label:"dart pub",identity:Cc,destination:"Dart pub global cache",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart","1.6.2"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({indexerBinary:e})=>Ci(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:[...k.php],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Li(e){if(!(e.projectPath||e.pnpmWorkspaces)){if(e.language==="typescript")return"{}";if(e.language==="javascript")return'{"compilerOptions":{"allowJs":true}}'}}function ke(e){return Ai[e]}function Mi(e,t){let n;try{n=wc(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return kc(e,i);return null}import{createHash as Dc}from"crypto";import{existsSync as Xt,rmSync as ji,statSync as Oc}from"fs";import{resolve as _c}from"path";import Vi from"better-sqlite3";var Mc={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},Ac={idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Bi(e){let t=x(),n=Ni(e.affectedFiles),r=Ni(e.deletedFiles??[],!0),i=new Set(n);if(r.some(s=>!i.has(s)))throw new Error("deleted incremental documents must be included in the affected document set");let o=n.length-r.length;if(jc(e.previousDbPath,e.miniDbPath,e.candidateDbPath),!Xt(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Xt(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");g("reindex.publish.sqlite-patch.validate-inputs",()=>{Kt(e.previousDbPath,"previous SQLite generation",!1),Kt(e.miniDbPath,"incremental SQLite mini database")}),e.reuseCandidate?g("reindex.publish.sqlite-patch.reuse-candidate",()=>Kt(e.candidateDbPath,"incremental SQLite candidate",!1)):g("reindex.publish.sqlite-patch.clone",()=>{ji(e.candidateDbPath,{force:!0});let s=K(e.previousDbPath,e.candidateDbPath);e.writeTelemetry&&X(e.writeTelemetry,s)});let a=null;try{a=g("reindex.publish.sqlite-patch.open",()=>{let m=new Vi(e.candidateDbPath,{fileMustExist:!0});return m.pragma("busy_timeout = 5000"),m.pragma("foreign_keys = ON"),m.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Qt(m,"main","candidate SQLite generation"),Qt(m,"incremental","incremental SQLite mini database"),m});let{priorAffectedCount:s,previousFactDigests:c}=g("reindex.publish.sqlite-patch.prepare",()=>(Vc(a,n,r),{...Bc(a,n.length,r.length),previousFactDigests:Zt(a,"main",!0)})),u=Z(a,"SELECT COUNT(*) AS value FROM main.documents"),l=a.transaction(()=>{g("reindex.publish.sqlite-patch.transaction.symbol-ownership",()=>Uc(a)),g("reindex.publish.sqlite-patch.transaction.shared-definitions",()=>Gc(a)),g("reindex.publish.sqlite-patch.transaction.delete",()=>qc(a)),e.onStage?.("after-delete"),g("reindex.publish.sqlite-patch.transaction.reconcile-symbols",()=>Wc(a)),e.onStage?.("after-symbol-reconciliation"),g("reindex.publish.sqlite-patch.transaction.insert",()=>Hc(a)),e.onStage?.("after-insert"),g("reindex.publish.sqlite-patch.transaction.prune-symbols",()=>zc(a,e.trustedPriorGeneration===!0)),g("reindex.publish.sqlite-patch.transaction.validate",()=>Jc(a,o,u,s)),e.onStage?.("before-commit")});g("reindex.publish.sqlite-patch.transaction",()=>l.immediate()),e.writeTelemetry&&it(e.writeTelemetry,2*Lc(e.candidateDbPath)),g("reindex.publish.sqlite-patch.integrity",()=>$c(a,"candidate SQLite generation",!e.deferIntegrity&&e.trustedPriorGeneration!==!0));let d=g("reindex.publish.sqlite-patch.validate-facts",()=>Yc(a)),p=[...new Set([...c.keys(),...d.keys()])].filter(m=>c.get(m)!==d.get(m)).sort();return a.exec("DETACH DATABASE incremental"),a.close(),a=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:p,durationMs:x()-t}}catch(s){try{a?.close()}finally{ji(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}function Lc(e){let t=0;for(let n of["-wal","-journal"]){let r=`${e}${n}`;Xt(r)&&(t+=Oc(r).size)}return t}function Ni(e,t=!1){if(!t&&e.length===0)throw new Error("incremental SQLite publication requires affected documents");let n=[...e].sort();for(let r of n)if(!r||r.startsWith("/")||r.includes("\\")||r.split("/").includes(".."))throw new Error(`invalid affected document path: ${r}`);if(new Set(n).size!==n.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return n}function jc(e,t,n){let r=[e,t,n].map(i=>_c(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Kt(e,t,n=!0){let r=new Vi(e,{readonly:!0,fileMustExist:!0});try{Qt(r,"main",t),n&&Nc(r,"main",t)}finally{r.close()}}function Qt(e,t,n){for(let[r,i]of Object.entries(Mc)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:l})=>({name:s,type:c.toUpperCase(),notnull:u,pk:l}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(Ac)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),a=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(s=>s.name);if(o?.tbl_name!==i.table||JSON.stringify(a)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}$i(e,t,"documents",["relative_path"],n),$i(e,t,"global_symbols",["symbol"],n)}function $i(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(s=>{if(s.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${s.name}')`).all().map(u=>u.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function Nc(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function $c(e,t,n){if(e.pragma("foreign_keys",{simple:!0})!==1)throw new Error(`${t} lost foreign-key enforcement`);if(!n)return;let r=e.prepare("PRAGMA main.quick_check").pluck().get();if(r!=="ok")throw new Error(`${t} failed quick_check: ${String(r)}`)}function Vc(e,t,n){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID"),e.exec("CREATE TEMP TABLE incremental_deleted_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let r=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)"),i=e.prepare("INSERT INTO temp.incremental_deleted_paths(relative_path) VALUES (?)");e.transaction(a=>{for(let s of a)r.run(s);for(let s of n)i.run(s)})(t)}function Bc(e,t,n){let r=Z(e,"SELECT COUNT(*) AS value FROM incremental.documents"),i=Z(e,`SELECT COUNT(*) AS value
|
|
61
60
|
FROM main.documents d
|
|
62
61
|
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),o=e.prepare(`SELECT p.relative_path
|
|
63
62
|
FROM temp.incremental_affected_paths p
|
|
@@ -71,7 +70,7 @@ import{a as V}from"./chunk-WDNVY4E7.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F
|
|
|
71
70
|
LIMIT 1`).pluck().get(),s=e.prepare(`SELECT d.relative_path
|
|
72
71
|
FROM incremental.documents d
|
|
73
72
|
JOIN temp.incremental_deleted_paths deleted ON deleted.relative_path = d.relative_path
|
|
74
|
-
LIMIT 1`).pluck().get();if(r!==t-n||o!==void 0||a!==void 0||s!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set");return{priorAffectedCount:i}}function
|
|
73
|
+
LIMIT 1`).pluck().get();if(r!==t-n||o!==void 0||a!==void 0||s!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set");return{priorAffectedCount:i}}function Uc(e){e.exec(`
|
|
75
74
|
CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
76
75
|
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
77
76
|
SELECT g.symbol
|
|
@@ -111,7 +110,7 @@ import{a as V}from"./chunk-WDNVY4E7.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F
|
|
|
111
110
|
CROSS JOIN main.global_symbols g ON g.id = m.symbol_id;
|
|
112
111
|
INSERT OR IGNORE INTO temp.incremental_touched_symbols(symbol)
|
|
113
112
|
SELECT symbol FROM incremental.global_symbols;
|
|
114
|
-
`)}function
|
|
113
|
+
`)}function Gc(e){let t=e.prepare(`WITH changed_symbols AS (
|
|
115
114
|
SELECT symbol FROM temp.incremental_old_defined_symbols
|
|
116
115
|
UNION
|
|
117
116
|
SELECT symbol FROM temp.incremental_new_defined_symbols
|
|
@@ -133,7 +132,7 @@ import{a as V}from"./chunk-WDNVY4E7.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F
|
|
|
133
132
|
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
134
133
|
WHERE m.symbol_id = g.id AND m.role = 1 AND p.relative_path IS NULL
|
|
135
134
|
)
|
|
136
|
-
LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function
|
|
135
|
+
LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function qc(e){e.exec(`
|
|
137
136
|
DELETE FROM main.mentions
|
|
138
137
|
WHERE chunk_id IN (
|
|
139
138
|
SELECT c.id
|
|
@@ -155,7 +154,7 @@ import{a as V}from"./chunk-WDNVY4E7.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F
|
|
|
155
154
|
);
|
|
156
155
|
DELETE FROM main.documents
|
|
157
156
|
WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
|
|
158
|
-
`)}function
|
|
157
|
+
`)}function Wc(e){e.exec(`
|
|
159
158
|
UPDATE main.global_symbols
|
|
160
159
|
SET display_name = NULL,
|
|
161
160
|
kind = NULL,
|
|
@@ -197,7 +196,7 @@ import{a as V}from"./chunk-WDNVY4E7.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F
|
|
|
197
196
|
WHERE source.symbol = main.global_symbols.symbol
|
|
198
197
|
)
|
|
199
198
|
WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
|
|
200
|
-
`)}function
|
|
199
|
+
`)}function Hc(e){let t=Z(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=Z(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=Z(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
|
|
201
200
|
SELECT id + ?, language, relative_path, position_encoding, text
|
|
202
201
|
FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
|
|
203
202
|
SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
|
|
@@ -212,16 +211,16 @@ import{a as V}from"./chunk-WDNVY4E7.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F
|
|
|
212
211
|
r.start_line, r.start_char, r.end_line, r.end_char
|
|
213
212
|
FROM incremental.defn_enclosing_ranges r
|
|
214
213
|
CROSS JOIN incremental.global_symbols source ON source.id = r.symbol_id
|
|
215
|
-
CROSS JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function
|
|
214
|
+
CROSS JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function zc(e,t){let n=t?"symbol IN (SELECT symbol FROM temp.incremental_touched_symbols) AND":"";e.exec(`
|
|
216
215
|
DELETE FROM main.global_symbols
|
|
217
216
|
WHERE ${n}
|
|
218
217
|
NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
|
|
219
218
|
AND NOT EXISTS (
|
|
220
219
|
SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
|
|
221
220
|
);
|
|
222
|
-
`)}function
|
|
221
|
+
`)}function Jc(e,t,n,r){let i=Z(e,"SELECT COUNT(*) AS value FROM main.documents"),o=Z(e,`SELECT COUNT(*) AS value
|
|
223
222
|
FROM main.documents d
|
|
224
|
-
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),a=n-r+t;if(i!==a||o!==t)throw new Error("candidate SQLite document counts changed unexpectedly")}function
|
|
223
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),a=n-r+t;if(i!==a||o!==t)throw new Error("candidate SQLite document counts changed unexpectedly")}function Yc(e){let t=Zt(e,"main",!0),n=Zt(e,"incremental",!1);if(JSON.stringify([...t])!==JSON.stringify([...n]))throw new Error("candidate SQLite affected document facts differ from the mini database");return t}function Zt(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
|
|
225
224
|
FROM ${t}.documents d
|
|
226
225
|
${r}
|
|
227
226
|
ORDER BY d.relative_path`).all(),o=e.prepare(`SELECT d.relative_path, c.chunk_index, c.start_line, c.end_line, hex(c.occurrences) AS occurrences
|
|
@@ -243,10 +242,10 @@ import{a as V}from"./chunk-WDNVY4E7.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F
|
|
|
243
242
|
JOIN ${t}.documents d ON d.id = c.document_id
|
|
244
243
|
JOIN ${t}.global_symbols g ON g.id = m.symbol_id
|
|
245
244
|
${r}
|
|
246
|
-
ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[l,d]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let
|
|
247
|
-
`);u.set(l,
|
|
248
|
-
`)}function
|
|
249
|
-
`;)
|
|
245
|
+
ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[l,d]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let p of d){let m=JSON.stringify([l,p]),f=c.get(p.relative_path)??[];f.push(m),c.set(p.relative_path,f)}let u=new Map;for(let[l,d]of[...c].sort(([p],[m])=>p.localeCompare(m))){let p=Dc("sha256");for(let m of d.sort())p.update(m).update(`
|
|
246
|
+
`);u.set(l,p.digest("hex"))}return u}function Z(e,t){return e.prepare(t).get().value}import Kc from"better-sqlite3";var ut="idx_mentions_definitions",Xc=["symbol_id","chunk_id"];function en(e,t={}){let n=new Kc(e),r=[],i=[],o=[];try{return n.transaction(()=>{Qc(n,r),lt(n,"idx_global_symbols_symbol")?.join("\0")==="symbol"&&Ui(n,"global_symbols").some(c=>c.name!=="idx_global_symbols_symbol"&&c.unique&&c.columns.join("\0")==="symbol")?(n.exec('DROP INDEX "idx_global_symbols_symbol"'),i.push("idx_global_symbols_symbol")):lt(n,"idx_global_symbols_symbol")&&o.push("idx_global_symbols_symbol");let a=lt(n,"idx_chunks_doc_id"),s=Ui(n,"chunks").some(c=>c.name!=="idx_chunks_doc_id"&&c.columns.length>1&&c.columns[0]==="document_id");a?.join("\0")==="document_id"&&s?(n.exec('DROP INDEX "idx_chunks_doc_id"'),i.push("idx_chunks_doc_id")):a&&o.push("idx_chunks_doc_id"),t.analyze!==!1&&n.exec("ANALYZE")})(),{added:r,removed:i,retained:o,analyzed:t.analyze!==!1}}catch(a){if(a.code==="SQLITE_NOTADB")return{added:[],removed:[],retained:[],analyzed:!1,skippedReason:"not-a-sqlite-database"};throw a}finally{n.close()}}function Qc(e,t){let n=Gi(e,ut);if(n){let r=n.columns.join("\0")===Xc.join("\0"),i=/\bWHERE\s+role\s*=\s*1\b/iu.test(n.sql??"");if(!r||!i||n.table!=="mentions")throw new Error(`${ut} exists with an incompatible definition`);return}e.exec(`CREATE INDEX "${ut}" ON mentions(symbol_id, chunk_id) WHERE role = 1`),t.push(ut)}function Ui(e,t){return e.prepare(`PRAGMA index_list('${t.replaceAll("'","''")}')`).all().map(n=>({name:n.name,unique:n.unique===1,columns:lt(e,n.name)??[]}))}function lt(e,t){return Gi(e,t)?.columns??null}function Gi(e,t){let n=e.prepare("SELECT tbl_name, sql FROM sqlite_master WHERE type = 'index' AND name = ?").get(t);if(!n)return null;let r=e.prepare(`PRAGMA index_info('${t.replaceAll("'","''")}')`).all().map(i=>i.name);return{table:n.tbl_name,sql:n.sql,columns:r}}import{writeFileSync as Zc}from"fs";function q(e,t){let n=performance.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}async function Wi(e,t){let n=performance.now(),r=await e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}function Hi(e){let t=e.readFingerprint(),n=Ji(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return Yi(e.cachePath,e.readFingerprint(),r),r}async function zi(e){let t=e.readFingerprint(),n=Ji(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=await e.compute();return Yi(e.cachePath,e.readFingerprint(),r),r}function Ji(e,t){try{let n=JSON.parse(_(e,{maxBytes:z,inputKind:"post-index augmentation cache"}));return qi(n.fingerprint)===qi(t)?{result:n.result}:null}catch{return null}}function Yi(e,t,n){Zc(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
|
|
247
|
+
`)}function qi(e){return JSON.stringify(e)}import{createHash as eu}from"crypto";import{existsSync as tn,readdirSync as tu}from"fs";import{dirname as nn,join as dt,relative as nu,resolve as rn,sep as Ki}from"path";function Xi(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=to(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Qi(e,t){let n=new Map;for(let i of e){let o=t[i]?.packageName;o&&n.set(o,i)}let r=new Map;for(let i of e)r.set(i,new Set);for(let i of e){let o=t[i],a=r.get(i);ru(i,e,o,n,a)}return ou(e,r)}function ru(e,t,n,r,i){if(!n||n.parseFailed){for(let o of t)o!==e&&i.add(o);return}for(let o of n.dependencyNames){let a=r.get(o);a&&a!==e&&i.add(a)}iu(e,t,n,i)}function iu(e,t,n,r){for(let i of[...n.pathsTargets,...n.referencesPaths]){let o=to(i,t);o&&o!==e&&r.add(o)}}function Zi(e,t,n){let r={};for(let i of e){let o=new Map;for(let a of t.files[i]??[])o.set(a.path,a);for(let a of n[i]??[])for(let s of t.files[a]??[])o.set(s.path,s);for(let a of t.shared)o.set(a.path,a);r[i]={files:[...o.values()].sort((a,s)=>a.path.localeCompare(s.path))}}return r}function on(e){if(e===".")return"root";let t=eu("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function eo(e,t){let n=rn(e),r={};for(let i of t)r[i]=au(n,i);return r}function to(e,t){let n;for(let r of t)r!=="."&&(e===r||e.startsWith(`${r}/`))&&(!n||r.length>n.length)&&(n=r);return n}function ou(e,t){let n={};for(let r of e){let i=new Set,o=[...t.get(r)??[]];for(;o.length>0;){let a=o.pop();if(!(a===r||i.has(a))){i.add(a);for(let s of t.get(a)??[])s!==r&&!i.has(s)&&o.push(s)}}n[r]=[...i].sort((a,s)=>a.localeCompare(s))}return n}function au(e,t){let n=t==="."?e:dt(e,t),r=su(n),i=cu(n),o=i?uu(i,e):{pathsTargets:[],referencesPaths:[],failed:!1};return{packageName:r.name,dependencyNames:r.dependencyNames,pathsTargets:o.pathsTargets,referencesPaths:o.referencesPaths,parseFailed:r.failed||o.failed}}function su(e){let t=dt(e,"package.json");if(!tn(t))return{name:void 0,dependencyNames:[],failed:!1};let n=an(t);if(!n.ok)return{name:void 0,dependencyNames:[],failed:!0};let r=typeof n.value.name=="string"?n.value.name:void 0,i=new Set;for(let o of["dependencies","devDependencies","peerDependencies"]){let a=n.value[o];if(a&&typeof a=="object"&&!Array.isArray(a))for(let s of Object.keys(a))i.add(s)}return{name:r,dependencyNames:[...i],failed:!1}}function cu(e){let t=dt(e,"tsconfig.json");if(tn(t))return t;let n;try{n=tu(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?dt(e,n[0]):void 0}function uu(e,t){let n=an(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=lu(n.value,e,t),i=no(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function lu(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=nn(t),o=new Set;for(let a of r){if(!a||typeof a!="object")continue;let s=a.path;if(typeof s!="string"||s.trim()==="")continue;let c=ro(s,i,n);c&&o.add(c)}return[...o]}function no(e,t,n,r){let i=du(t);if(i)return{pathsTargets:pu(i,nn(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=mu(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=an(o);return a.ok?no(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function du(e){let t=e.compilerOptions;if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.paths;return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function pu(e,t,n){let r=new Set;for(let i of Object.values(e))if(Array.isArray(i))for(let o of i){if(typeof o!="string")continue;let a=ro(o,t,n);a&&r.add(a)}return[...r]}function mu(e,t,n){let r=Array.isArray(e)?e.at(-1):e;if(typeof r!="string"||r.trim()===""||!r.startsWith(".")&&!r.startsWith("/"))return;let i=rn(nn(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Ki).includes("node_modules")&&kt(n,i)&&tn(i))return i}function ro(e,t,n){let r=e.replace(/\/?\*+$/,""),i=rn(t,r===""?".":r);if(!kt(n,i))return;let a=nu(n,i).split(Ki).join("/");return a===""?".":a}function fu(e){let t="",n=0,r=!1,i=e.length;for(;n<i;){let o=e[n];if(r){t+=o;let a=gu(e,n);t+=e.slice(n+1,a),o==='"'&&(r=!1),n=a;continue}if(o==='"'){r=!0,t+=o,n+=1;continue}if(o==="/"&&e[n+1]==="/"){n=hu(e,n+2);continue}if(o==="/"&&e[n+1]==="*"){n=yu(e,n+2);continue}t+=o,n+=1}return t}function gu(e,t){return e[t]==="\\"&&t+1<e.length?t+2:t+1}function hu(e,t){for(;t<e.length&&e[t]!==`
|
|
248
|
+
`;)t+=1;return t}function yu(e,t){for(;t<e.length&&!(e[t]==="*"&&e[t+1]==="/");)t+=1;return t+2}function an(e){try{let t=_(e,{maxBytes:z,inputKind:"TypeScript project manifest"}),n=JSON.parse(fu(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import Su from"better-sqlite3";import{zstdCompressSync as bu}from"zlib";import{setImmediate as Ru}from"timers/promises";var ee=class extends Error{},xu=200,so=2,co=1,vu=2,Pu=3,Tu=4,Iu=5,Eu=6,uo=1,lo=2,po=3,wu=7,ku=1,Fu=3,Cu=5,Du=6,Ou=8,_u=1,Mu=64,Au=[`CREATE TABLE documents (
|
|
250
249
|
id INTEGER PRIMARY KEY,
|
|
251
250
|
language TEXT,
|
|
252
251
|
relative_path TEXT NOT NULL UNIQUE,
|
|
@@ -286,11 +285,23 @@ import{a as V}from"./chunk-WDNVY4E7.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F
|
|
|
286
285
|
end_char INTEGER NOT NULL,
|
|
287
286
|
FOREIGN KEY (document_id) REFERENCES documents(id),
|
|
288
287
|
FOREIGN KEY (symbol_id) REFERENCES global_symbols(id)
|
|
289
|
-
)`],
|
|
290
|
-
`),
|
|
291
|
-
`;return{configPath:o,content:a,inputPaths:r}})}var ro="typescript-shard-costs.json",Zi=4;function io(e){let t;try{t=JSON.parse(Hn(at(e,ro),"shard cost model"))}catch{return null}if(typeof t!="object"||t===null||t.version!==1)return null;let n=t.samples;return Array.isArray(n)&&n.every(i=>typeof i=="object"&&i!==null&&typeof i.firstPath=="string"&&typeof i.lastPath=="string"&&Number.isFinite(i.totalBytes)&&i.totalBytes>0&&Number.isFinite(i.durationMs)&&i.durationMs>0)?{version:1,samples:n}:null}function oo(e,t){$e(at(e,ro),t)}function ao(e){let t=(e?.samples??[]).filter(o=>o.totalBytes>0&&o.durationMs>0);if(t.length<2)return(o,a)=>a;let n=t.map(o=>o.durationMs/o.totalBytes).sort((o,a)=>o-a),r=n[Math.floor(n.length/2)];if(!(r>0))return(o,a)=>a;let i=[...t].sort((o,a)=>o.firstPath.localeCompare(a.firstPath));return(o,a)=>{for(let s of i){if(o.localeCompare(s.firstPath)<0)break;if(o.localeCompare(s.lastPath)>0)continue;let c=s.durationMs/s.totalBytes/r;return a*Math.min(Zi,Math.max(1/Zi,c))}return a}}function so(e,t){let n=[];for(let r of e){let i=r.inputPaths[0],o=r.inputPaths[r.inputPaths.length-1];if(i===void 0||o===void 0||!(r.durationMs>0))return null;let a=r.inputPaths.reduce((s,c)=>s+Math.max(1,t(c)),0);n.push({firstPath:i,lastPath:o,totalBytes:a,durationMs:r.durationMs})}return n.length>0?{version:1,samples:n}:null}function co(e=process.env,t={totalmemBytes:tu(),cpuCount:eu().length}){let n=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_CONCURRENCY??"",10);if(Number.isSafeInteger(n)&&n>0)return n;let r=Math.floor(t.totalmemBytes/2/ru),i=Math.floor(t.cpuCount/2);return Math.max(1,Math.min(iu,r,i))}function uo(e){let t;try{t=Qc(e)}catch{return}for(let n of t)if(er(n))try{Zc(at(e,n))}catch{}}import{createHash as bn}from"crypto";import{existsSync as Sn,writeFileSync as ko}from"fs";import{join as _u}from"path";import{createRequire as su}from"module";import{dirname as mn,isAbsolute as cu,relative as mo,resolve as ee,sep as ln}from"path";var Z=su(import.meta.url),uu=1,lo="0.4.0";function lu(){try{let e=fo();if(!e.available)return e;let{packageRoot:t}=e,n=Z.resolve("typescript",{paths:[t]}),r=Z(n),{FileIndexer:i}=Z(ee(t,"dist/src/FileIndexer.js")),{Input:o}=Z(ee(t,"dist/src/Input.js")),{Packages:a}=Z(ee(t,"dist/src/Packages.js")),s=Z(ee(t,"dist/src/scip.js"));if(!i||!o||!a||!s.scip?.Document||!s.scip.Index)return{available:!1,reason:"scip-typescript document runtime has an unsupported module shape"};let c={packageVersion:e.packageVersion,typescript:r,Document:s.scip.Document,Index:s.scip.Index,FileIndexer:i,Input:o,Packages:a};return{available:!0,runtime:c,producerIdentity:gn(c)}}catch(e){return{available:!1,reason:`scip-typescript document runtime unavailable: ${e instanceof Error?e.message:String(e)}`}}}function fn(){let e=fo();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function fo(){try{let e=Z.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(U(e,"scip-typescript package manifest"));if(t.version!==lo)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${lo}`};let n=mn(e),r=Z.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(U(r,"TypeScript package manifest"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:ho(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function go(e){let t=e.runtime===void 0?lu():e.runtime===null?{available:!1,reason:"scip-typescript document runtime unavailable"}:{available:!0,runtime:e.runtime,producerIdentity:gn(e.runtime)};return t.available?{available:!0,emitter:new dn(e,t.runtime)}:t}var dn=class{producerIdentity;workspaceRoot;tsconfigPath;projectRoot;maxFileByteSize;runtime;host;config=null;includedFiles=new Set;program=null;checker=null;symbolTable=new Map;constructorTable=new Map;packages;fragments=new Map;stats={initializations:0,programUpdates:0,documentsEmitted:0,documentsRemoved:0,sourceNodesReused:0,sourceNodesReplaced:0,symbolEntriesPruned:0};constructor(t,n){this.workspaceRoot=ee(t.workspaceRoot),this.tsconfigPath=ee(this.workspaceRoot,t.tsconfigPath),this.projectRoot=t.projectRoot??pu(this.workspaceRoot,mn(this.tsconfigPath)),this.maxFileByteSize=t.maxFileByteSize??1024*1024,this.runtime=n,this.producerIdentity=gn(n);let r=un(n.typescript,this.tsconfigPath);this.config=r,this.host=new pn(n.typescript,r.options,this.workspaceRoot),this.packages=new n.Packages(this.projectRoot)}initialize(){let t=performance.now();this.initializeProgram();let n=[];for(let r of this.program.getSourceFiles())this.includedFiles.has(Ie(r.fileName))&&n.push(this.emitSourceFile(r));return this.result(n,t)}advance(t){if(!this.program||!this.checker||!this.config)return this.initializeAndAdvance(t);let n=performance.now(),r=ve(t.modifiedFiles),i=ve(t.removedFiles??[]),o=ve(t.affectedFiles);if(this.fragments.clear(),r.length===0&&i.length===0)return this.validateAffectedPaths(o),this.result(this.emitAffectedFiles(o),n);let a=un(this.runtime.typescript,this.tsconfigPath);this.config=a,this.includedFiles=new Set(a.fileNames.map(Ie));let s=this.program,c=new Map;for(let u of[...r,...i]){let l=Pe(this.workspaceRoot,u),d=s.getSourceFile(l);d&&(c.set(u,d),this.stats.symbolEntriesPruned+=po(this.symbolTable,d),this.stats.symbolEntriesPruned+=po(this.constructorTable,d)),this.host.invalidate(l)}this.program=this.runtime.typescript.createProgram(a.fileNames,a.options,this.host.compilerHost,s),this.checker=this.program.getTypeChecker(),this.stats.programUpdates+=1,this.validateIncrementalPaths(r,i,o),this.stats.documentsRemoved+=i.length;for(let[u,l]of c)this.program.getSourceFile(Pe(this.workspaceRoot,u))===l?this.stats.sourceNodesReused+=1:this.stats.sourceNodesReplaced+=1;return this.result(this.emitAffectedFiles(o),n)}fragment(t){return this.fragments.get(st(t))??null}snapshotStats(){return{...this.stats}}initializeAndAdvance(t){let n=performance.now();this.initializeProgram();let r=ve(t.modifiedFiles),i=ve(t.removedFiles??[]),o=ve(t.affectedFiles);return this.fragments.clear(),this.validateIncrementalPaths(r,i,o,!0),this.stats.documentsRemoved+=i.length,this.result(this.emitAffectedFiles(o),n)}initializeProgram(){let t=this.config??un(this.runtime.typescript,this.tsconfigPath);this.includedFiles=new Set(t.fileNames.map(Ie)),this.program=this.runtime.typescript.createProgram(t.fileNames,t.options,this.host.compilerHost),this.checker=this.program.getTypeChecker(),this.stats.initializations+=1}validateIncrementalPaths(t,n,r,i=!1){if(!i&&t.length===0&&n.length===0)throw new Error("incremental TypeScript document update requires a modified or removed file");if(r.length===0&&n.length===0)throw new Error("incremental TypeScript document update requires an affected or removed file");for(let o of t){let a=Pe(this.workspaceRoot,o);if(!this.program?.getSourceFile(a))throw new Error(`modified TypeScript dependency is unavailable to the configured project: ${o}`)}for(let o of n){let a=Pe(this.workspaceRoot,o);if(this.program?.getSourceFile(a))throw new Error(`removed TypeScript source is still present in the configured project: ${o}`)}this.validateAffectedPaths(r)}validateAffectedPaths(t){for(let n of t){let r=Pe(this.workspaceRoot,n);if(!this.includedFiles.has(Ie(r)))throw new Error(`affected TypeScript file is outside the configured project: ${n}`)}}emitAffectedFiles(t){return t.map(n=>{let r=this.program.getSourceFile(Pe(this.workspaceRoot,n));if(!r)throw new Error(`affected TypeScript source is unavailable: ${n}`);return this.emitSourceFile(r)})}emitSourceFile(t){if(!this.checker)throw new Error("TypeScript document emitter is not initialized");let n=st(mo(this.workspaceRoot,t.fileName)),r=new this.runtime.Document({relative_path:n,occurrences:[]});if(new this.runtime.FileIndexer(this.checker,{cwd:this.workspaceRoot,projectRoot:this.projectRoot,projectDisplayName:this.projectRoot,maxFileByteSizeNumber:this.maxFileByteSize},new this.runtime.Input(t.fileName,t.getText()),r,this.symbolTable,this.constructorTable,this.packages,t).index(),this.stats.documentsEmitted+=1,r.occurrences.length===0)return this.fragments.delete(n),this.stats.documentsRemoved+=1,{relativePath:n,bytes:null,occurrences:0,symbols:r.symbols.length,referenceFragments:[]};let o=r.serializeBinary();return this.fragments.set(n,o),{relativePath:n,bytes:o,occurrences:r.occurrences.length,symbols:r.symbols.length,referenceFragments:du(n,r)}}result(t,n){return{producerIdentity:this.producerIdentity,fragments:t,durationMs:performance.now()-n,stats:this.snapshotStats()}}};function du(e,t){let n=new Map;for(let r of t.occurrences){if(!r.symbol||(r.symbol_roles&1)!==0||r.range.length<3)continue;let i=r.range[0],o=r.range[1];if(!Number.isInteger(i)||!Number.isInteger(o))continue;let a={targetSymbol:r.symbol,location:{file:e,line:i,column:o}};n.set(`${r.symbol}\0${i}\0${o}`,a)}return[...n.values()].sort((r,i)=>r.targetSymbol.localeCompare(i.targetSymbol)||r.location.line-i.location.line||r.location.column-i.location.column)}var pn=class{compilerHost;sourceFiles=new Map;constructor(t,n,r){let i=t.createCompilerHost(n),o=i.getSourceFile.bind(i);this.compilerHost={...i,getCurrentDirectory:()=>r,getSourceFile:(a,s,c,u)=>{let l=Ie(a);if(this.sourceFiles.has(l))return this.sourceFiles.get(l);let d=o(a,s,c,u);return this.sourceFiles.set(l,d),d}}}invalidate(t){this.sourceFiles.delete(Ie(t))}};function un(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(e.formatDiagnostics([n.error],e.createCompilerHost({})));let r=e.parseJsonConfigFileContent(n.config,e.sys,mn(t)),i=r.errors.filter(o=>o.code!==18003);if(i.length>0)throw new Error(e.formatDiagnostics(i,e.createCompilerHost({})));return r}function gn(e){return ho(e.packageVersion,e.typescript.version)}function ho(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${uu}`}function pu(e,t){return st(mo(e,t))||"."}function Pe(e,t){if(cu(t))throw new Error(`expected a project-relative path: ${t}`);let n=ee(e,t),r=e.endsWith(ln)?e:`${e}${ln}`;if(n!==e&&!n.startsWith(r))throw new Error(`path escapes the project root: ${t}`);return n}function ve(e){return[...new Set(e.map(st))].sort()}function st(e){return e.split(ln).join("/").replace(/^\.\//,"")}function Ie(e){return ee(e)}function po(e,t){let n=0;for(let r of e.keys())if(mu(r)){try{if(r.getSourceFile()!==t)continue}catch{continue}e.delete(r),n+=1}return n}function mu(e){return!!(e&&typeof e=="object"&&"kind"in e&&"getSourceFile"in e)}import{createHash as fu}from"crypto";import{dirname as gu,join as yo}from"path";var Ee=5;var hu="typescript-index";function So(e){let t=yo(e,hu),n=Rr(t);return{...n,requestDir:n.legacyRequestDir}}function bo(e){try{let t=Gn(te(U(yo(gu(e),"meta.json"),"reindex metadata")));return t?fu("sha256").update(t).digest("hex"):null}catch{return null}}import{randomUUID as Ru}from"crypto";import{existsSync as xo,rmSync as hn}from"fs";import{join as xu}from"path";import{randomUUID as yu}from"crypto";import{getHeapStatistics as Su}from"v8";import{resolve as bu}from"path";var ct=class{projectRoot;currentGeneration;createEmitter;wallNow;monotonicNow;maxActiveSessions;softMemoryLimitBytes;memoryUsage;active=new Map;requests=0;sessionsCreated=0;sessionsReplaced=0;sessionsEvicted=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(t){if(this.projectRoot=bu(t.projectRoot),this.currentGeneration=t.currentGeneration,this.createEmitter=t.createEmitter??go,this.wallNow=t.wallNow??t.now??Date.now,this.monotonicNow=t.monotonicNow??t.now??F,t.maxActiveSessions!==void 0&&(!Number.isInteger(t.maxActiveSessions)||t.maxActiveSessions<1))throw new Error("TypeScript index maxActiveSessions must be a positive integer.");if(this.maxActiveSessions=t.maxActiveSessions??8,t.softMemoryLimitMb!==void 0&&(!Number.isInteger(t.softMemoryLimitMb)||t.softMemoryLimitMb<1))throw new Error("TypeScript index softMemoryLimitMb must be a positive integer.");this.softMemoryLimitBytes=t.softMemoryLimitMb===void 0?null:t.softMemoryLimitMb*1024*1024,this.memoryUsage=t.memoryUsage??(()=>({heapUsedBytes:process.memoryUsage().heapUsed,heapLimitBytes:Su().heap_size_limit}))}handle(t,n){let r=this.monotonicNow();try{if(this.currentGeneration()!==t)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(n);if(i.emitter.producerIdentity!==n.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),a=i.emitter.advance({modifiedFiles:n.modifiedFiles,removedFiles:n.removedFiles,affectedFiles:n.affectedFiles}),s=this.monotonicNow()-r;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(t){let n=[...this.active.values()].map(a=>a.emitter.snapshotStats()),r=a=>n.reduce((s,c)=>s+c[a],0),i=this.memoryUsage(),o=this.softMemoryLimitBytes!==null&&i.heapUsedBytes>=this.softMemoryLimitBytes;return{protocolVersion:Ee,state:this.unavailable?"unavailable":this.lastError?"error":this.active.size>0?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,sessionsEvicted:this.sessionsEvicted,activeSessions:this.active.size,maxActiveSessions:this.maxActiveSessions,heapUsedBytes:i.heapUsedBytes,heapLimitBytes:i.heapLimitBytes,...this.softMemoryLimitBytes===null?{}:{softMemoryLimitBytes:this.softMemoryLimitBytes},retireRequested:o,initializations:r("initializations"),programUpdates:r("programUpdates"),documentsEmitted:r("documentsEmitted"),documentsRemoved:r("documentsRemoved"),...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{},...t?{mailbox:t}:{}}}close(){this.active.clear()}emitterFor(t){let n=`${t.tsconfigPath}\0${t.projectArgument}`,r=this.active.get(n);if(r?.projectIdentity===t.projectIdentity)return this.active.delete(n),this.active.set(n,r),r;if(r)this.active.delete(n);else if(this.active.size>=this.maxActiveSessions){let a=this.active.keys().next().value;a!==void 0&&(this.active.delete(a),this.sessionsEvicted+=1)}let i=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:t.tsconfigPath,projectRoot:t.projectArgument});if(!i.available)throw this.unavailable=!0,new Error(i.reason);r&&(this.sessionsReplaced+=1);let o={projectIdentity:t.projectIdentity,emitter:i.emitter};return this.active.set(n,o),this.sessionsCreated+=1,o}};var Nm=`typescript-index-${process.pid}-${yu()}`,Ro=J(process.pid),$m={pid:process.pid,...Ro?{processIdentity:Ro}:{}};var Pu=12e4,vu=5,Ce=class extends Error{name="TypeScriptIndexMemoryPressureError"},ut=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;emitLocally;requireService;localHost=null;constructor(t,n={}){this.projectRoot=Qn(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??wu(),this.runtime=n.runtime??ku,this.mailboxLimits=n.mailboxLimits??{},this.emitLocally=n.emitLocally,this.requireService=n.requireService===!0}request(t){let n=vr(this.cacheDir),r=So(this.cacheDir),i=Vt(n.statePath);if(!Po(i,this.projectRoot,this.runtime))return this.requestLocally(t);let o=this.runtime.now(),a=o+this.timeoutMs,s=(this.runtime.monotonicNow??F)()+this.timeoutMs,c=Nt("typescript-index-v5",{baseGeneration:this.baseGeneration,request:t}),u=$t(c),l=xr(r,{mailboxVersion:jt,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:a,protocolVersion:Ee,id:u,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??F)()<=s;){if(xo(l.responsePath))try{return vo(N(l.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t.producerIdentity,t.affectedFiles)}finally{hn(l.responsePath,{force:!0})}let d=Vt(n.statePath);if(!Po(d,this.projectRoot,this.runtime))return this.abandonPendingRequest(r,u),this.requestLocally(t);this.runtime.sleep(vu)}if(xo(l.responsePath))try{return vo(N(l.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t.producerIdentity,t.affectedFiles)}finally{hn(l.responsePath,{force:!0})}return this.abandonPendingRequest(r,u),this.requestLocally(t)}abandonPendingRequest(t,n){try{hn(xu(t.pendingDir,`${n}.json`),{force:!0})}catch{}}requestLocally(t){if(this.requireService)throw new Error("TypeScript incremental index service unavailable; refusing to load the whole compiler graph inside the reindex process");return this.emitLocally?yn(this.emitLocally(t),t.producerIdentity,t.affectedFiles):(this.localHost??=new ct({projectRoot:this.projectRoot,currentGeneration:()=>this.baseGeneration}),yn(Io(this.localHost.handle(this.baseGeneration,t),t.producerIdentity),t.producerIdentity,t.affectedFiles))}};function Po(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null,i=e?Date.parse(e.heartbeatAt):Number.NaN;return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===Ee&&n.isProcessAlive(e.pid)&&Number.isFinite(i)&&n.now()-i<=Pr&&(!e.processIdentity||r!=null&&we(e.processIdentity,r))}function vo(e,t,n,r,i,o){let a=JSON.parse(e);if(a.protocolVersion!==Ee||a.id!==t||a.operationKey!==n||a.ok===!0&&a.baseGeneration!==r)throw new Error("TypeScript index service wrote an incompatible response.");if(a.ok!==!0){let s=typeof a.error=="string"?a.error:"TypeScript index service request failed.";throw Iu(s)?new Ce(s):new Error(s)}return yn(Io(a.response,i),i,o)}function Iu(e){let t=e.toLowerCase();return t.includes("out of memory")||t.includes("memory limit")||t.includes("allocation failed")||t.includes("err_worker_out_of_memory")}function yn(e,t,n){if(e.producerIdentity!==t)throw new Error("TypeScript index service wrote an invalid response.");let r=[...new Set(n)].sort(),i=e.fragments.map(o=>o.relativePath).sort();if(JSON.stringify(i)!==JSON.stringify(r))throw new Error("TypeScript index service omitted or added an affected document.");return e}function Io(e,t){if(!e||typeof e!="object")throw new Error("TypeScript index service wrote an invalid response.");let n=e;if(n.producerIdentity!==t||typeof n.cold!="boolean"||typeof n.durationMs!="number"||!Number.isFinite(n.durationMs)||!Array.isArray(n.fragments))throw new Error("TypeScript index service wrote an invalid response.");let r=new Set,i=n.fragments.map(o=>{if(!o||typeof o.relativePath!="string"||o.bytesBase64!==null&&typeof o.bytesBase64!="string"||typeof o.occurrences!="number"||!Number.isInteger(o.occurrences)||o.occurrences<0||typeof o.symbols!="number"||!Number.isInteger(o.symbols)||o.symbols<0||!Array.isArray(o.referenceFragments)||!o.referenceFragments.every(Eu)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:Tu(o.bytesBase64);return{relativePath:o.relativePath,bytes:a,occurrences:o.occurrences,symbols:o.symbols,referenceFragments:o.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i}}function Eu(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.targetSymbol=="string"&&!!t.location&&typeof t.location.file=="string"&&Number.isInteger(t.location.line)&&Number.isInteger(t.location.column)}function Tu(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function wu(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Pu}var ku={now:Date.now,monotonicNow:F,randomId:Ru,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:ge,readProcessIdentity:J};var Fu=128,Cu=256;function Ou(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."],n=he(t);if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let r=z(e.previousSnapshot,e.currentSnapshot);if(r.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};let i=r.changes.filter(g=>g.inputKind==="source"&&Re(g.path)),o=_o(r,n),a={...r,changes:o},s=i.filter(g=>g.kind==="added").map(g=>g.path),c=i.filter(g=>g.kind==="deleted").map(g=>g.path),u=i.filter(g=>g.kind==="modified"),l=dt(e.currentSnapshot,e.producerIdentity,n),d=dt(e.previousSnapshot,e.producerIdentity,n),m=Fo(r,o,l,d),f=!m&&Oo(r);if(i.length===0&&!m)return{eligible:!1,reason:"change does not affect the configured TypeScript project"};let y=e.currentSnapshot.files.filter(g=>Le(g.path,e.currentSnapshot.languages)==="source"&&Re(g.path)).map(g=>g.path).sort(),b=new Set(y),k=m?e.projectFiles.filter(g=>!b.has(g)).sort():[...c].sort(),O=m?a:{...r,changes:i},E=m?{eligible:!0,plan:{...Fe(a,e.graph,[...new Set([...y,...k])]),mode:"full-project"}}:Au(u,s,k,e.graph,e.projectFiles);if(!E.eligible)return E;let C=E.plan,w=new Set(k),h=Mu(C,t,e.graph,w);if(!h)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let S=h.length===1?h[0]:void 0;return{eligible:!0,manifest:O,plan:C,projectIdentity:l,previousFragmentGeneration:wo(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:wo(e.currentSnapshot,e.producerIdentity),projects:h,deletedFiles:k,replaceProject:m,dependencyGraphUnchanged:f,...S?{tsconfigPath:S.tsconfigPath,projectArgument:S.projectArgument}:{}}}function _o(e,t){return e.changes.filter(n=>n.inputKind==="source"&&Re(n.path)||n.inputKind==="config"&&(!ye(n.path)||t.has(n.path))&&Du(n)||n.inputKind==="ambient")}function Du(e){return e.kind!=="modified"||e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function Fo(e,t,n,r){return n!==r||e.projectIdentityChanged||e.uncertainty.length>0||t.length>Cu||t.some(i=>i.inputKind==="config"||i.inputKind==="ambient")}function Au(e,t,n,r,i){if(e.length===0)return t.length===0&&n.length===0?{eligible:!1,reason:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...t,...n])].sort(),affectedFiles:[...new Set([...t,...Eo(n,r,i)])].sort(),reasons:[]}};let o=Fe({version:1,changes:e.filter(Co),projectIdentityChanged:!1,uncertainty:[]},r,i);return o.mode==="full-project"?{eligible:!1,reason:o.reasons.length>0?`affected set widened: ${o.reasons.join(", ")}`:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...e.map(a=>a.path),...t,...n])].sort(),affectedFiles:[...new Set([...o.affectedFiles,...e.map(a=>a.path),...t,...Eo(n,r,i)])].sort(),reasons:[]}}}function Co(e){return e.kind!=="modified"?!0:e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function Oo(e){let t=e.changes.filter(n=>n.inputKind==="source"&&Re(n.path));return t.length>0&&t.every(n=>n.kind==="modified"&&!Co(n))}function Mu(e,t,n,r){let i=new Map;for(let a of e.affectedFiles){let s=Lu(a,t);if(!s)return null;let c=i.get(s)??[];c.push(a),i.set(s,c)}let o=[];for(let[a,s]of[...i].sort(([c],[u])=>c.localeCompare(u))){let c=new Set(s),u=e.changedFiles.filter(m=>!r.has(m)&&(c.has(m)||s.some(f=>To(f,m,n)))),l=e.changedFiles.filter(m=>r.has(m)&&(c.has(m)||s.some(f=>To(f,m,n)))),d=s.filter(m=>!r.has(m));if(u.length===0&&l.length===0&&d.length===0)return null;o.push({projectArgument:a,tsconfigPath:a==="."?"tsconfig.json":`${a}/tsconfig.json`,modifiedFiles:u,removedFiles:l,affectedFiles:[...d].sort()})}return o}function Eo(e,t,n){let r=new Set(n),i=new Map;for(let[s,c]of t)if(r.has(s))for(let u of c){let l=i.get(u)??new Set;l.add(s),i.set(u,l)}let o=new Set(e),a=[...e];for(let s=0;s<a.length;s+=1){let c=a[s];if(c)for(let u of i.get(c)??[])o.has(u)||(o.add(u),a.push(u))}return[...o].sort()}function Lu(e,t){let n=t.filter(o=>o==="."||e===o||e.startsWith(`${o}/`));if(n.length===0)return null;let r=[...new Set(n)].sort((o,a)=>lt(a)-lt(o)||o.localeCompare(a)),i=r[0];return r[1]&<(r[1])===lt(i)?null:i}function lt(e){return e==="."?0:e.split("/").filter(Boolean).length}function To(e,t,n){let r=new Set,i=[e];for(let o=0;o<i.length;o+=1){let a=i[o];if(!(!a||r.has(a))){r.add(a);for(let s of n.get(a)??[]){if(s===t)return!0;r.has(s)||i.push(s)}}}return!1}function Do(e){let t=F();try{if(!Sn(e.previousDbPath)||!Sn(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=fn();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new V({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a=Nu(e.projectRoot,e.previousSnapshot,e.currentSnapshot),s=e.projectMode==="workspace"?ne(e.projectRoot,e.currentSnapshot.typescriptProjects):["."],c=he(s),u,l,d;try{u=Ue(o,{includeIgnored:!1}).filter(Re).sort();let T=a?z(a,e.currentSnapshot):null,p=T&&a&&Fo(T,_o(T,c),dt(e.currentSnapshot,r.producerIdentity,c),dt(a,r.producerIdentity,c)),x=T!==null&&!p&&Oo(T);p?(d=We(o,"none")??void 0,l=new Map):x?l=new Map:(d=Ge(o),l=d.graph)}finally{o.close()}let m=performance.now()-n,f=Ou({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?s:void 0,previousSnapshot:a,currentSnapshot:e.currentSnapshot,projectFiles:u,graph:l,producerIdentity:r.producerIdentity,rootTsconfigExists:Sn(_u(e.projectRoot,"tsconfig.json"))});if(!f.eligible)throw new Error(f.reason);let y=bo(e.previousDbPath);if(!y)throw new Error("published TypeScript base generation unavailable");n=performance.now();let b=new ut({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:y},{requireService:!0}),k=f.projects.flatMap(T=>{let p=ju(T.affectedFiles,Fu);return(p.length>0?p:[[]]).map((A,H)=>({project:T,affectedFiles:A,removedFiles:H===0?T.removedFiles:[],firstForProject:H===0}))}),O=[],E=new Map,C=[],w=!1,h=0,S=0,g=0,_=f.previousFragmentGeneration;for(let[T,p]of k.entries()){let x=b.request({kind:"emit-documents",tsconfigPath:p.project.tsconfigPath,projectArgument:p.project.projectArgument,projectIdentity:f.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:p.firstForProject?p.project.modifiedFiles:[],removedFiles:p.firstForProject?p.project.removedFiles:[],affectedFiles:p.affectedFiles});w||=x.cold,C.push(x.durationMs);let A=p.removedFiles.map(Me=>({relativePath:Me,bytes:null,occurrences:0,symbols:0,referenceFragments:[]})),H=[...x.fragments,...A];if(!f.replaceProject)for(let Me of H)E.set(Me.relativePath,Me.referenceFragments);let vt=performance.now(),Za=Wr(x.fragments);h+=performance.now()-vt;let $n=T===0?e.candidateAffectedScipPath:`${e.candidateAffectedScipPath}.batch-${T}.scip`,es=performance.now();ko($n,Za),g+=performance.now()-es;let ts=performance.now(),Vn=T===k.length-1?f.nextFragmentGeneration:$u({previousGenerationIdentity:_,targetGenerationIdentity:f.nextFragmentGeneration,fragments:H});Hr({cacheDir:e.cacheDir,previousGenerationIdentity:_,nextGenerationIdentity:Vn,producerIdentity:r.producerIdentity,projectIdentity:f.projectIdentity,baseShardCurrent:T===0?e.baseShardCurrent:!1,fragments:H,allowProjectIdentityChange:f.replaceProject&&T===0,allowLegacyProjectIdentityMigration:!0}),S+=performance.now()-ts,_=Vn,O.push({scipPath:$n,affectedFiles:[...p.affectedFiles,...p.removedFiles].sort(),deletedFiles:[...p.removedFiles].sort()})}let R=performance.now()-n,P={scipPath:e.previousShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,affectedBatches:O,completeScipUpdated:!1,durationMs:F()-t,cold:w,changedFiles:f.plan.changedFiles,affectedFiles:f.plan.affectedFiles,deletedFiles:f.deletedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:f.previousFragmentGeneration,nextFragmentGeneration:f.nextFragmentGeneration,manifest:f.manifest,plan:f.plan,projectFileCount:u.length,dependencyGraphSnapshot:d,dependencyGraphUnchanged:f.dependencyGraphUnchanged,referenceFragmentsByFile:E,timings:{runtimeMs:i,graphMs:m,requestMs:R,serviceMs:C.reduce((T,p)=>T+p,0),assemblyMs:h,fragmentStoreMs:S,writeMs:g}};return e.onStatus(`${f.replaceProject?"Bounded TypeScript project refresh":"Incremental TypeScript index"} emitted ${P.affectedFiles.length-P.deletedFiles.length} document(s), removed ${P.deletedFiles.length}, and produced ${O.length} bounded batch(es) across ${f.projects.length} project(s) in ${(P.durationMs/1e3).toFixed(3)}s (${P.cold?"cold":"warm"} service; whole SCIP deferred; runtime ${i.toFixed(0)}ms, graph ${m.toFixed(0)}ms, request ${R.toFixed(0)}ms, assembly ${h.toFixed(0)}ms, fragments ${S.toFixed(0)}ms, write ${g.toFixed(0)}ms).`),P}catch(n){let r=n instanceof Error?n.message:String(n);if(e.onUnavailable?.(r),n instanceof Ce)throw e.onStatus(`Incremental TypeScript index stopped after memory pressure survived one cold Worker retry: ${r}. Preserving the accepted index instead of starting a memory-heavier whole-project rebuild.`),n;return e.onStatus(`Incremental TypeScript index unavailable: ${r}.`),null}}function ju(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Nu(e,t,n){if(!t)return null;let r=new Map(n.files.map(a=>[a.path,a])),i=!1,o=t.files.map(a=>{let s=r.get(a.path);if(a.semanticHash!==void 0||s?.semanticHash===void 0)return a;let c=Be(e,a.path,a.hash);return c===void 0?a:(i=!0,{...a,semanticHash:c})});return i?{...t,files:o}:t}function $u(e){let t=bn("sha256");t.update("typescript-overlay-batch-v1\0"),t.update(e.previousGenerationIdentity),t.update("\0"),t.update(e.targetGenerationIdentity);for(let n of[...e.fragments].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)))t.update("\0path\0"),t.update(n.relativePath),n.bytes===null?t.update("\0deleted"):(t.update("\0bytes\0"),t.update(bn("sha256").update(n.bytes).digest()));return t.digest("hex")}function Rn(e){let t=fn();if(!t.available)throw new Error(t.reason);let n=zr({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:fe(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:Ne}),packageVersion:t.packageVersion});ko(e.candidateShardPath,n)}function dt(e,t,n){let r=e.files.filter(i=>{let o=Le(i.path,e.languages);return o==="ambient"||o==="config"&&(!ye(i.path)||n.has(i.path))}).map(i=>{let a=Le(i.path,e.languages)==="config"?i.semanticHash:void 0;return{path:i.path,size:a===void 0?i.size:0,hash:a??i.hash}}).sort((i,o)=>i.path.localeCompare(o.path));return`typescript-project-v3:${Ao(JSON.stringify({version:3,producerIdentity:t,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),nonSourceInputs:r}))}`}function wo(e,t){return Ao(JSON.stringify({version:1,producerIdentity:t,snapshot:Un(e)}))}function Ao(e){return bn("sha256").update(e).digest("hex")}import{closeSync as Vu,existsSync as pt,fstatSync as Bu,lstatSync as Uu,openSync as Gu,renameSync as vn,rmSync as Oe,statSync as Wu,writeSync as qu}from"fs";import{cpus as Hu}from"os";import{join as In}from"path";var xn=Symbol("no-error");async function Mo(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=Number.isFinite(t)?Math.max(1,Math.floor(t)):1,o=Math.min(e.length,i),a=0,s=xn,c=!0,u=Array.from({length:o},async()=>{for(;c&&a<e.length;){let l=a++;try{r[l]=await n(e[l])}catch(d){s===xn&&(s=d),c=!1}}});if(await Promise.all(u),s!==xn)throw s;return r}var Lo=8*1024;function jo(e,t,n){let r=Buffer.from(t,"utf8"),i=()=>Gu(e,"wx",384),o;try{o=i()}catch(a){if(a.code!=="EEXIST")throw a;if(n==="skip")return null;Oe(e,{force:!0}),o=i()}try{qu(o,r);let a=Bu(o);return{path:e,content:r,device:a.dev,inode:a.ino}}finally{Vu(o)}}function zu(e,t){let n=[];try{if(e.temporaryRootConfigContent!==void 0){let r=jo(In(t,"tsconfig.json"),e.temporaryRootConfigContent,"skip");r&&n.push(r)}for(let r of e.temporaryProjectConfigs??[]){let i=jo(r.path,r.content,"replace");i&&n.push(i)}return n}catch(r){for(let i of n.reverse())Vo(i);throw r}}function Vo(e){if(e)try{let t=Uu(e.path);if(!t.isFile()||t.dev!==e.device||t.ino!==e.inode||t.size!==e.content.byteLength)return;let n;try{n=fe(e.path,{maxBytes:e.content.byteLength,inputKind:"temporary TypeScript index configuration"})}catch{return}if(!n.equals(e.content))return;Oe(e.path)}catch(t){if(t.code!=="ENOENT")throw t}}function Ju(e,t,n){if(!e.defaultOutputPath)return;let r=In(t,e.defaultOutputPath);n!==r&&pt(r)&&vn(r,n)}function Yu(e,t,n){if(!e.defaultOutputPath)return null;let r=In(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Oe(i,{force:!0}),pt(r)?(vn(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Xu(e){e&&(Oe(e.defaultOutputPath,{force:!0}),e.backupPath&&pt(e.backupPath)&&vn(e.backupPath,e.defaultOutputPath))}function Ku(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,Hu().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Bo(e,t,n,r,i){$(i,"Reindex cancelled by its owner.");let o=e.filter(u=>u.config.defaultOutputPath),a=e.filter(u=>!u.config.defaultOutputPath&&u.boundedConcurrency!==void 0),s=e.filter(u=>!u.config.defaultOutputPath&&u.boundedConcurrency===void 0),c=[];if(c.push(...await No(s,Ku(s.length,r),t,n,i)),a.length>0){let u=Math.max(1,Math.min(...a.map(l=>l.boundedConcurrency)));c.push(...await No(a,u,t,n,i))}for(let u of o)$(i,"Reindex cancelled by its owner."),c.push((await Pn(u,t,n,i)).result);return c.sort((u,l)=>e.findIndex(d=>d.id===u.id)-e.findIndex(d=>d.id===l.id))}async function No(e,t,n,r,i){let o=await Mo(e,Math.max(1,t),s=>Pn(s,n,r,i));if(t<=1)return o.map(({result:s})=>s);let a=new Map;for(let s of o.filter(c=>c.result.skipped&&c.retryable)){let c=e.find(u=>u.id===s.result.id);c&&(r(`Retrying ${c.label} indexer serially after parallel failure...`),$(i,"Reindex cancelled by its owner."),a.set(c.id,(await Pn(c,n,r,i)).result))}return o.map(({result:s})=>a.get(s.id)??s)}async function Pn(e,t,n,r){$(r,"Reindex cancelled by its owner."),n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Oe(e.scipPath,{force:!0});let i=Yu(e.config,t,e.scipPath),o=[],a=[e.binary,...e.args].join(" "),s=F();try{o=zu(e,t),e.trustedProjectTool&&br(t,e.trustedProjectTool);let u=yr(e.binary,e.args),l=await qe({command:u.binary,args:u.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:Qu(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,signal:r});if(l.status!==0){let d=l.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${l.status}${d?`:
|
|
292
|
-
${
|
|
293
|
-
[indexer failure detail truncated]`,m=`${e.resolvedBinary} indexer failed: ${d}`,f=e.label===e.language?m:`${e.label}: ${m}`;return n(`Skipping ${e.label}: ${m}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:F()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:f}},retryable:Zu(u)}}finally{Xu(i);for(let u of o.reverse())Vo(u)}if(!pt(e.scipPath)){let u=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,l=e.label===e.language?u:`${e.label}: ${u}`;return n(`Skipping ${e.label}: ${u}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:F()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:l}},retryable:!1}}let c;try{c=Wu(e.scipPath).size}catch{c=void 0}return{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:F()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},outputBytes:c},retryable:!1}}function Qu(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):Tr.indexer}function Zu(e){return e instanceof wr?e.kind==="spawn"&&$o(e.cause):$o(e)}function $o(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}import{execFileSync as Go}from"child_process";import{homedir as Uo,platform as el}from"os";import{delimiter as tl,join as mt}from"path";function Tn(e,t){let n=e.installMethods,r=ke(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n){if(!i.identity||!i.destination){t(`Refusing ${i.label} installation for ${r}: the installer descriptor lacks an immutable identity or destination.`);continue}if(!Dt(i.prerequisite))continue;let o=nl(i);t(`Installing immutable ${i.identity} via ${i.label} into ${o}; expected executable: ${r}.`);try{Go(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:el()==="win32"});let a=be(e);if(a){let s=a===e.indexerBinary?"":` (using ${a})`;return t(`Successfully installed ${i.identity} via ${i.label}${s}; resolved executable: ${a}.`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(a){let s=a instanceof Error?a.message:String(a);t(`${i.label} install failed: ${s}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function nl(e){if(e.binary==="npm")return En("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=En("go",["env","GOBIN"]);if(t)return t;let n=En("go",["env","GOPATH"]);if(n)return mt(n.split(tl)[0],"bin")}return e.binary==="dotnet"?mt(process.env.DOTNET_CLI_HOME??Uo(),".dotnet","tools"):e.binary==="dart"?mt(process.env.PUB_CACHE??mt(Uo(),".pub-cache"),"bin"):e.destination}function En(e,t){try{return Go(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}import pa from"better-sqlite3";import{existsSync as ma}from"fs";import{dirname as fa,join as ga,resolve as ha}from"path";import{randomUUID as il}from"crypto";import{mkdtempSync as ol,rmSync as al,statSync as qo}from"fs";import{tmpdir as sl}from"os";import{join as Ho}from"path";import{Worker as cl}from"worker_threads";function rl(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function Te(){return{skippedReferences:0,skippedReferenceReasons:rl(),skippedReferenceSamples:[]}}function ft(e,t){e.skippedReferences+=t.skippedReferences;for(let n of Object.keys(e.skippedReferenceReasons)){e.skippedReferenceReasons[n]+=t.skippedReferenceReasons[n];for(let r of t.skippedReferenceSamples.filter(i=>i.reason===n))e.skippedReferenceSamples.filter(o=>o.reason===n&&o.sourceFile===r.sourceFile).length<2&&e.skippedReferenceSamples.push(r)}}var ul=3e5,zo=64*1024*1024,ll={createResultDirectory:()=>ol(Ho(sl(),"scip-query-vue-workers-")),spawn:(e,t)=>new cl(e,{workerData:t}),resultSize:e=>qo(e).size,readResult:e=>N(e,{maxBytes:zo,inputKind:"Vue worker result"}),removeResultDirectory:e=>al(e,{recursive:!0,force:!0})};function Jo(e){return e.length>=8&&Xo(e.length)>1}async function Yo(e,t=ll){let n=Xo(e.vueFiles.length),r=vl(e.vueFiles),i=El(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),a=e.timeoutMs??xl(),s=e.maxResultBytes??Pl();Wo("timeoutMs",a),Wo("maxResultBytes",s);let c=il(),u=t.createResultDirectory(),l=[],d,m,f;try{for(let b=0;b<i.length;b++){let k=b,O=i[b]??[],E=O.map(h=>h.taskId),C=Ho(u,`${k}.json`),w=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:O,resultPath:C,runId:c,workerId:k,taskIds:E});l.push({workerId:k,taskIds:E,resultPath:C,handle:w,completion:dl(w,k)})}await pl(l,a);let y=l.sort((b,k)=>b.workerId-k.workerId).map(b=>fl(b,c,s,t));f={occurrences:y.flatMap(b=>b.occurrences),...Te()};for(let b of y)ft(f,b)}catch(y){d=y}finally{let y=await ml(l);if(y.length===0)try{t.removeResultDirectory(u)}catch(b){y.push(b)}if(y.length>0){let b=d===void 0?y:[d,...y];m=new AggregateError(b,`Vue worker cleanup failed: ${Rl(b[0])}`)}}if(m)throw m;if(d!==void 0)throw d;if(!f)throw new Error("Vue workers completed without producing a merged result.");return f}function dl(e,t){return new Promise((n,r)=>{let i=!1,o=c=>{i||(i=!0,e.off("error",a),e.off("exit",s),c?r(c):n())},a=c=>{o(new Error(`Vue reference worker ${t} failed: ${c.message}`,{cause:c}))},s=c=>{o(c===0?void 0:new Error(`Vue reference worker ${t} exited with code ${c}`))};e.once("error",a),e.once("exit",s)})}async function pl(e,t){let n;try{await Promise.race([Promise.all(e.map(r=>r.completion)),new Promise((r,i)=>{n=setTimeout(()=>i(new Error(`Vue reference workers timed out after ${(t/1e3).toFixed(3)}s`)),t),n.unref()})])}finally{n&&clearTimeout(n)}}async function ml(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function fl(e,t,n,r){let i=r.resultSize(e.resultPath);if(!Number.isSafeInteger(i)||i<0||i>n)throw new Error(`Vue reference worker ${e.workerId} result is ${i} bytes; limit is ${n} bytes`);let o;try{o=JSON.parse(r.readResult(e.resultPath))}catch(a){throw new Error(`Vue reference worker ${e.workerId} produced invalid JSON`,{cause:a})}if(!De(o)||o.version!==1||o.runId!==t||o.workerId!==e.workerId)throw new Error(`Vue reference worker ${e.workerId} result identity does not match its assignment`);if(!bl(o.taskIds,e.taskIds))throw new Error(`Vue reference worker ${e.workerId} result task identities do not match its assignment`);if(o.ok===!1)throw typeof o.error!="string"?new Error(`Vue reference worker ${e.workerId} failure payload is malformed`):new Error(`Vue reference worker ${e.workerId} failed: ${o.error}`);if(o.ok!==!0||!gl(o.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return o.result}function gl(e){if(!De(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(hl)||!W(e.skippedReferences)||!De(e.skippedReferenceReasons))return!1;for(let t of["missing-source-file","missing-service-script","no-definition","same-file-definition","unindexed-definition"])if(!W(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(yl)}function hl(e){return De(e)&&typeof e.sourceFile=="string"&&W(e.sourceLine)&&W(e.sourceStartChar)&&W(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&W(e.symbolId)}function yl(e){return De(e)&&typeof e.sourceFile=="string"&&W(e.sourceLine)&&W(e.sourceStartChar)&&W(e.sourceEndChar)&&typeof e.token=="string"&&Sl(e.reason)}function Sl(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function W(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function De(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bl(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function Wo(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function Rl(e){return e instanceof Error?e.message:String(e)}function Xo(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:1;return Math.max(1,Math.min(e,n))}function xl(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:ul}function Pl(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:zo}function vl(e){let t=Il(),n=[];for(let r of e){let i=Ko(r),o=Math.max(1,Math.ceil(i/t));for(let a=0;a<o;a++)n.push({taskId:`${n.length}:${r}:${a}`,fileName:r,startOffset:Math.floor(i*a/o),endOffset:a===o-1?Number.POSITIVE_INFINITY:Math.floor(i*(a+1)/o),countFileSkip:a===0})}return n}function Il(){return Number.POSITIVE_INFINITY}function El(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Tl(i)})).sort((i,o)=>o.weight-i.weight);for(let i of r){let o=n.reduce((a,s)=>s.weight<a.weight?s:a);o.tasks.push(i.task),o.weight+=i.weight}return n.map(i=>i.tasks).filter(i=>i.length>0)}function Tl(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Ko(e.fileName)-e.startOffset)}function Ko(e){try{return qo(e).size}catch{return 1}}import{createRequire as wl}from"module";import{existsSync as kl}from"fs";import{dirname as Qo,extname as _l,join as Zo,relative as Fl,resolve as Cl}from"path";import{pathToFileURL as Ol}from"url";function Dl(e){e.transaction(()=>{e.prepare(`
|
|
288
|
+
)`],Lu=["CREATE INDEX idx_chunks_line_range ON chunks(document_id, start_line, end_line)","CREATE INDEX idx_mentions_symbol_id_role ON mentions(symbol_id, role)","CREATE INDEX idx_defn_enclosing_ranges_symbol_id ON defn_enclosing_ranges(symbol_id)","CREATE INDEX idx_defn_enclosing_ranges_document ON defn_enclosing_ranges(document_id, start_line, end_line)","CREATE INDEX idx_chunks_doc_id ON chunks(document_id)","CREATE INDEX idx_global_symbols_symbol ON global_symbols(symbol)"];function sn(e){return e.startsWith("local ")}function ju(e,t,n,r){let i=t,o=0,a=0;for(;i<n;){let s=e[i];i+=1,a<53&&(o+=(s&127)*2**a),(s&128)===0?(r.push(o),o=0,a=0):a+=7}}function io(e){return e.length===3?[e[0],e[1],e[0],e[2]]:e.length===4?[e[0],e[1],e[2],e[3]]:null}function Nu(e,t){return e.startLine!==t.startLine?e.startLine-t.startLine:e.startChar!==t.startChar?e.startChar-t.startChar:e.endLine!==t.endLine?e.endLine-t.endLine:e.endChar!==t.endChar?e.endChar-t.endChar:e.symbol<t.symbol?-1:e.symbol>t.symbol?1:0}function $u(e,t,n,r){let i=[],o=[],a="",s=0;for(let u of Se(e,n,r))u.fieldNumber===uo?ao(e,u,i):u.fieldNumber===lo&&u.wireType===2?a=be.decode(e.subarray(u.valueStart,u.valueEnd)):u.fieldNumber===po&&u.wireType===0?s=u.varint:u.fieldNumber===wu&&ao(e,u,o);let c=io(i);return c?{startLine:c[0],startChar:c[1],endLine:c[2],endChar:c[3],symbol:a,roles:s,frameStart:t,frameEnd:r,merged:!1,enclosing:io(o)}:null}function Vu(e,t,n){let r={symbol:"",displayName:null,kind:null,documentation:[],enclosingSymbol:null};for(let i of Se(e,t,n))if(i.wireType===2){let o=()=>be.decode(e.subarray(i.valueStart,i.valueEnd));i.fieldNumber===ku?r.symbol=o():i.fieldNumber===Fu?r.documentation.push(o()):i.fieldNumber===Du?r.displayName=o():i.fieldNumber===Ou&&(r.enclosingSymbol=o())}else i.fieldNumber===Cu&&i.wireType===0&&(r.kind=i.varint);return r}var be=new TextDecoder;function Bu(e,t){if(e.length===0)return[];let n=[],r=Math.min(e.length,t);for(let i=0;i<r&&r<=e.length;){for(;r<=e.length-1&&e[r-1].startLine===e[r].startLine;)r+=1;n.push(e.slice(i,r)),i=r,r=Math.min(e.length,r+t)}return n}function Uu(e){let t=e.startLine===e.endLine?[e.startLine,e.startChar,e.endChar]:[e.startLine,e.startChar,e.endLine,e.endChar],n=[],r=Buffer.concat(t.map(a=>oe(a)));n.push(Je(uo),oe(r.length),r);let i=Buffer.from(e.symbol,"utf8");n.push(Je(lo),oe(i.length),i),e.roles!==0&&n.push(oe(po*8),oe(e.roles));let o=Buffer.concat(n);return Buffer.concat([Je(so),oe(o.length),o])}function Gu(e,t){let n=[];for(let r of t)r.merged?n.push(Uu(r)):n.push(e.subarray(r.frameStart,r.frameEnd));return bu(Buffer.concat(n))}function qu(e,t,n){let r="",i=null,o=null,a=null,s=[];for(let c of Se(e,t,n))c.wireType===2?c.fieldNumber===co?r=be.decode(e.subarray(c.valueStart,c.valueEnd)):c.fieldNumber===Pu?s.push(Vu(e,c.valueStart,c.valueEnd)):c.fieldNumber===Tu?i=be.decode(e.subarray(c.valueStart,c.valueEnd)):c.fieldNumber===Iu&&(o=be.decode(e.subarray(c.valueStart,c.valueEnd))):c.fieldNumber===Eu&&c.wireType===0&&(a=Yu(c.varint));return{relativePath:r,language:i,text:o,positionEncoding:a,declaredSymbols:s}}function Wu(e,t){let n=new Map;for(let r of e){if(r.symbol==="")throw new ee(`empty symbol in SymbolInformation for document ${t}`);let i=n.get(r.symbol);if(!i){n.set(r.symbol,r);continue}for(let o of r.documentation)i.documentation.includes(o)||i.documentation.push(o)}return[...n.values()].sort((r,i)=>r.symbol<i.symbol?-1:r.symbol>i.symbol?1:0)}function Hu(e,t,n,r){let i="",o=[];for(let a of Se(e,t,n))if(a.wireType===2){if(a.fieldNumber===co)i=be.decode(e.subarray(a.valueStart,a.valueEnd));else if(a.fieldNumber===vu){let s=$u(e,a.fieldStart,a.valueStart,a.valueEnd);s?o.push(s):r.illegalOccurrencesDropped+=1}}return{relativePath:i,records:o}}function zu(e,t){e.sort(Nu);let n=[];for(let r of e){let i=n[n.length-1];if(i&&i.startLine===r.startLine&&i.startChar===r.startChar&&i.endLine===r.endLine&&i.endChar===r.endChar&&i.symbol===r.symbol){i.roles|=r.roles,i.merged=!0,t.mergedOccurrences+=1;continue}n.push(r)}return t.occurrences+=n.length,n}function Ju(e,t,n){let[r,i,o,a]=e;if(r<0||i<0||o<r||o===r&&a<i)throw new ee(`bad enclosing range for symbol ${t} in ${n}`)}var cn=class{constructor(t,n){this.stats=n;this.insertDocument=t.prepare("INSERT INTO documents (id, language, relative_path, position_encoding, text) VALUES (?, ?, ?, ?, ?)"),this.insertChunk=t.prepare("INSERT INTO chunks (id, document_id, chunk_index, start_line, end_line, occurrences) VALUES (?, ?, ?, ?, ?, ?)"),this.insertEnclosing=t.prepare("INSERT INTO defn_enclosing_ranges (document_id, symbol_id, start_line, start_char, end_line, end_char) VALUES (?, ?, ?, ?, ?, ?)"),this.insertSymbol=t.prepare("INSERT INTO global_symbols (id, symbol, display_name, kind, documentation, enclosing_symbol) VALUES (?, ?, ?, ?, ?, ?)"),this.insertMention=t.prepare("INSERT INTO mentions (chunk_id, symbol_id, role) VALUES (?, ?, ?)")}stats;insertDocument;insertChunk;insertEnclosing;insertSymbol;insertMention;documentIds=new Map;symbolIds=new Map;nextDocumentId=1;nextChunkId=1;nextSymbolId=1;addSymbol(t,n,r,i,o){let a=this.nextSymbolId;return this.nextSymbolId+=1,this.symbolIds.set(t,a),this.insertSymbol.run(a,t,n,r,i,o),this.stats.globalSymbols+=1,a}writeDeclarations(t){let{relativePath:n,language:r,text:i,positionEncoding:o,declaredSymbols:a}=t;if(n==="")throw new ee("relative path must not be empty");if(this.documentIds.has(n)){this.stats.duplicateDocumentsSkipped+=1;return}let s=this.nextDocumentId;this.nextDocumentId+=1,this.insertDocument.run(s,r===""?null:r,n,o,i===""?null:i),this.documentIds.set(n,s),this.stats.documents+=1,this.writeDeclaredSymbols(Wu(a,n))}writeDeclaredSymbols(t){for(let n of t)sn(n.symbol)||this.symbolIds.has(n.symbol)||this.addSymbol(n.symbol,n.displayName===""?null:n.displayName,n.kind===0?null:n.kind,n.documentation.length===0?null:n.documentation.join(`
|
|
289
|
+
`),n.enclosingSymbol===""?null:n.enclosingSymbol)}writeEnclosingRanges(t,n,r){for(let i of r){if((i.roles&_u)===0||sn(i.symbol)||!i.enclosing)continue;let[o,a,s,c]=i.enclosing;Ju(i.enclosing,i.symbol,n);let u=this.symbolIds.get(i.symbol);if(u===void 0)throw new ee(`symbol ${i.symbol} has definition occurrence, but no SymbolInformation`);this.insertEnclosing.run(t,u,o,a,s,c),this.stats.enclosingRanges+=1}}writeChunks(t,n,r,i){for(let[o,a]of Bu(r,i).entries()){let s=this.nextChunkId;this.nextChunkId+=1,this.insertChunk.run(s,n,o,a[0].startLine,a[a.length-1].startLine,Gu(t,a)),this.stats.chunks+=1,this.writeMentions(s,a)}}writeMentions(t,n){let r=new Map;for(let i of n){if(sn(i.symbol))continue;let o=r.get(i.symbol);o||r.set(i.symbol,o=new Set),o.add(i.roles),this.symbolIds.has(i.symbol)||this.addSymbol(i.symbol,null,null,null,null)}for(let[i,o]of r){let a=this.symbolIds.get(i);for(let s of o)this.insertMention.run(t,a,s),this.stats.mentions+=1}}};async function oo(e,t,n){let r=0;for(let i of Se(e))i.fieldNumber!==so||i.wireType!==2||(Ku(t),r+=1,r>=Mu&&(r=0,await Ru()),n(i.valueStart,i.valueEnd))}async function mo(e,t,n={}){let r=n.chunkSize??xu,i={documents:0,duplicateDocumentsSkipped:0,occurrences:0,illegalOccurrencesDropped:0,mergedOccurrences:0,chunks:0,mentions:0,globalSymbols:0,enclosingRanges:0},o=new Su(t);try{o.pragma("synchronous = normal"),o.pragma("temp_store = memory"),o.pragma("foreign_keys = ON"),o.pragma("journal_mode = WAL");for(let c of Au)o.exec(c);let a=new cn(o,i);o.exec("BEGIN IMMEDIATE");let s=!1;try{await oo(e,n.signal,(u,l)=>{a.writeDeclarations(qu(e,u,l))});let c=new Set;await oo(e,n.signal,(u,l)=>{let{relativePath:d,records:p}=Hu(e,u,l,i);if(c.has(d))return;c.add(d);let m=a.documentIds.get(d);if(m===void 0)return;let f=zu(p,i);a.writeEnclosingRanges(m,d,f),a.writeChunks(e,m,f,r)}),o.exec("COMMIT"),s=!0}finally{if(!s)try{o.exec("ROLLBACK")}catch{}}o.exec("BEGIN IMMEDIATE");for(let c of Lu)o.exec(c);o.exec("COMMIT"),o.pragma("wal_checkpoint(TRUNCATE)")}finally{o.close()}return i}function Yu(e){if(e===0)return null;if(e===1)return"UTF-8";if(e===2)return"UTF-16";if(e===3)return"UTF-32";throw new ee(`unknown position encoding ${e}`)}function Ku(e){if(e?.aborted)throw new ee("SCIP SQLite conversion aborted")}function ao(e,t,n){t.wireType===2?ju(e,t.valueStart,t.valueEnd,n):t.wireType===0&&n.push(t.varint)}import{readdirSync as Xu,rmSync as Qu}from"fs";import{cpus as Zu,totalmem as el}from"os";import{join as fo}from"path";function go(e,t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Invalid compiler worker count");let n=Math.min(e.length,t);return Array.from({length:n},(r,i)=>e.slice(Math.floor(e.length*i/n),Math.floor(e.length*(i+1)/n)))}var tl=2048,nl=6*1024**3,rl=2;function un(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_FILES??"",10);return Number.isSafeInteger(t)&&t>0?t:tl}function ho(e,t){return e>Math.floor(t*1.5)}function il(e,t,n=()=>1){if(!Number.isSafeInteger(t)||t<1)throw new Error(`TypeScript compiler shard count must be a positive safe integer; received ${t}.`);let r=[...new Set(e)].sort((u,l)=>u.localeCompare(l));if(t===1||r.length<=t)return ol(r,t);let i=r.map(u=>Math.max(1,n(u))),o=i.reduce((u,l)=>u+l,0),a=[],s=[],c=0;for(let u=0;u<r.length;u+=1){s.push(r[u]),c+=i[u];let l=t-a.length-1,d=r.length-u-1;al(l,d,c,o,a.length,t)&&(a.push(s),s=[])}return s.length>0&&a.push(s),a}function yo(e){let t=e.targetFiles??un(),n=e.shardCount??Math.max(1,Math.ceil(new Set(e.inputPaths).size/Math.max(1,t)));return il(e.inputPaths,n,e.weightOf).map((r,i)=>{let o=fo(e.projectRoot,rr(i)),a=`${JSON.stringify({extends:`./${e.rootConfigPath}`,compilerOptions:{incremental:!1},scipQueryEmissionFiles:r},null,2)}
|
|
290
|
+
`;return{configPath:o,content:a,inputPaths:r}})}function So(e=process.env,t={totalmemBytes:el(),cpuCount:Zu().length}){let n=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_CONCURRENCY??"",10);if(Number.isSafeInteger(n)&&n>0)return n;let r=Math.floor(t.totalmemBytes/2/nl),i=Math.floor(t.cpuCount/2);return Math.max(1,Math.min(rl,r,i))}function bo(e){let t;try{t=Xu(e)}catch{return}for(let n of t)if(ir(n))try{Qu(fo(e,n))}catch{}}function ol(e,t){return e.length<=t&&t>1?e.map(n=>[n]):e.length>0?[e]:[]}function al(e,t,n,r,i,o){return e>0&&t>=e&&(n>=r*(i+1)/o||t===e)}import{createHash as ta}from"crypto";import{existsSync as Tn,writeFileSync as ia}from"fs";import{join as Jl}from"path";import{createRequire as Tl}from"module";import{dirname as bn,isAbsolute as Il,relative as gn,resolve as N,sep as hn}from"path";import{PositionEncoding as sl}from"@c4312/scip";var Ro=new WeakSet,xo=sl.UTF16CodeUnitOffsetFromLineStart;function vo(e){if(Ro.has(e))return;let t=e.serialize;if(typeof t!="function")throw new Error("scip-typescript document serializer is unavailable");e.serialize=function(n){let r=t.call(this,n);if(n){n.writeEnum(6,xo);return}if(!r)throw new Error("scip-typescript document serializer returned no bytes");let i=new Uint8Array(r.length+2);return i.set(r),i.set([48,xo],r.length),i},Ro.add(e)}import{createHash as cl}from"crypto";var Po=new WeakSet;function wo(e,t,n){if(Po.has(e))return;let r=e.scipSymbol,i=e.descriptor;if(typeof r!="function"||typeof i!="function"||typeof e.cached!="function")throw new Error("scip-typescript symbol runtime has an unsupported module shape");e.scipSymbol=function(o){if(mt(o,t))return this.globalSymbolTable.get(o)??this.cached(o,n.global(this.scipSymbol(o.getSourceFile()),n.methodDescriptor("default")));if(!t.isPropertyAssignment(o)&&!t.isShorthandPropertyAssignment(o)&&!t.isObjectLiteralExpression(o))return r.call(this,o);let a=this.globalSymbolTable.get(o);if(a)return a;let s=this.scipSymbol(o.getSourceFile()),c=t.isObjectLiteralExpression(o)?"objectLiteral":o.name.getText(),u=n.metaDescriptor(`${c}$${o.getStart()}`);return this.cached(o,n.global(s,u))},e.descriptor=function(o){return t.isTypeLiteralNode(o)?n.metaDescriptor(`typeLiteral$${o.getStart()}`):i.call(this,o)},Po.add(e)}function mt(e,t){if(t.isFunctionDeclaration(e))return ul(e,t)?e:null;if(t.isExportAssignment(e)){if(e.isExportEquals||!t.isSourceFile(e.parent))return null;let r=pt(e.expression,t);return t.isArrowFunction(r)||t.isFunctionExpression(r)?r:null}if(!t.isArrowFunction(e)&&!t.isFunctionExpression(e))return null;let n=e;for(;n.parent&&pt(n.parent,t)===e;)n=n.parent;return n.parent&&t.isExportAssignment(n.parent)?mt(n.parent,t):null}function ul(e,t){return!e.name&&t.isSourceFile(e.parent)&&!!t.getModifiers(e)?.some(n=>n.kind===t.SyntaxKind.DefaultKeyword)}function pt(e,t){for(;t.isParenthesizedExpression(e)||t.isAsExpression(e)||t.isSatisfiesExpression(e)||t.isNonNullExpression(e)||t.isTypeAssertionExpression(e);)e=e.expression;return e}function ko(e,t,n,r,i=new Set){if(e.version!=="5.9.3"||!dl(e,t,n))return null;let o=e.BuilderState?.computeDtsSignature;if(!o)return null;try{let a=[];if(o(ll(e,t,i),n,void 0,{createHash:Io},c=>a.push(c)),a.length!==1)return null;let s=new dn(e,t.getTypeChecker(),r,n).capture(i);return Io(JSON.stringify([a[0],s]))}catch{return null}}function ll(e,t,n){if(!n.size)return t;let r=()=>i=>{if(!e.isSourceFile(i))throw new Error("Unsupported bundled declaration boundary");return e.factory.updateSourceFile(i,i.statements.filter(o=>!e.isFunctionDeclaration(o)||!o.name||!n.has(o.name.text)))};return{...t,emit:(...i)=>{let o=[...i];return o[4]={afterDeclarations:[r]},t.emit(...o)}}}function dl(e,t,n){return!n.isDeclarationFile&&/\.[cm]?tsx?$/.test(n.fileName)&&e.isExternalModule(n)&&!t.getCompilerOptions().outFile&&t.getSyntacticDiagnostics(n).length===0&&!pn(e,n)}function pn(e,t){return e.isModuleDeclaration(t)||e.isExportAssignment(t)&&t.isExportEquals?!0:e.forEachChild(t,n=>pn(e,n)||void 0)===!0}var dn=class{constructor(t,n,r,i){this.ts=t;this.checker=n;this.indexer=r;this.source=i}ts;checker;indexer;source;visited=new Map;nodes=[];capture(t){let n=this.checker.getSymbolAtLocation(this.source);if(!n)throw new Error("Module symbol unavailable");return{roots:this.checker.getExportsOfModule(n).filter(i=>!t.has(i.name)).map(i=>{let o=i.flags&this.ts.SymbolFlags.Alias?this.checker.getAliasedSymbol(i):i;return[i.name,this.origins(o),o.flags&this.ts.SymbolFlags.Value?this.walk(this.checker.getTypeOfSymbol(o)):null,o.flags&this.ts.SymbolFlags.Type?this.walk(this.checker.getDeclaredTypeOfSymbol(o)):null]}),types:this.nodes}}origins(t){if(!t)return null;let r=(t.getDeclarations()??[]).map(i=>{let o=this.indexer.scipSymbol(i).value;if(o&&!o.startsWith("local "))return o;let a=i.getSourceFile();if(!a||i.pos<0)throw new Error("Declaration identity unavailable");return[a.fileName,i.kind,i.getStart(a),i.getText(a)]});return[t.name,r,t.getDocumentationComment(this.checker),t.getJsDocTags(this.checker)]}walk(t){let n=this.visited.get(t);if(n!==void 0)return n;if(this.nodes.length>=2e3)throw new Error("Exported type traversal exceeds its budget");let r=this.nodes.length;this.visited.set(t,r);let i={flags:t.flags};if(this.nodes.push(i),i.symbol=this.origins(t.symbol),i.alias=this.origins(t.aliasSymbol),i.aliasArguments=t.aliasTypeArguments?.map(o=>this.walk(o)),pl(this.ts,t))return r;if(t.isUnionOrIntersection())return i.parts=t.types.map(o=>this.walk(o)),r;if(!(t.flags&this.ts.TypeFlags.Object))throw new Error("Unsupported exported type");return this.object(t,i),r}object(t,n){if(t.objectFlags&this.ts.ObjectFlags.Reference){let r=t;if(n.arguments=this.checker.getTypeArguments(r).map(i=>this.walk(i)),To(r.target.symbol)){n.externalTarget=this.origins(r.target.symbol);return}if(this.checker.isTupleType(t)){n.tuple=!0;return}}if(t.objectFlags&this.ts.ObjectFlags.ClassOrInterface){if(To(t.symbol)){n.externalTarget=this.origins(t.symbol);return}throw new Error("Unsupported exported class or interface")}n.properties=this.checker.getPropertiesOfType(t).map(r=>[r.name,this.origins(r),this.walk(this.checker.getTypeOfSymbol(r))]),n.calls=this.checker.getSignaturesOfType(t,this.ts.SignatureKind.Call).map(r=>this.signature(r)),n.constructors=this.checker.getSignaturesOfType(t,this.ts.SignatureKind.Construct).map(r=>this.signature(r)),n.indexes=this.checker.getIndexInfosOfType(t).map(r=>[this.walk(r.keyType),this.walk(r.type)])}signature(t){if(t.typeParameters?.length||this.checker.getTypePredicateOfSignature(t))throw new Error("Unsupported generic or predicate signature");return{parameters:t.parameters.map(n=>[n.name,this.origins(n),this.walk(this.checker.getTypeOfSymbol(n))]),thisParameter:t.thisParameter?this.walk(this.checker.getTypeOfSymbol(t.thisParameter)):null,returns:this.walk(this.checker.getReturnTypeOfSignature(t))}}};function To(e){let t=e?.getDeclarations();return!!t?.length&&t.every(n=>n.getSourceFile().isDeclarationFile)}function pl(e,t){let n=e.TypeFlags.Unknown|e.TypeFlags.String|e.TypeFlags.Number|e.TypeFlags.Boolean|e.TypeFlags.BooleanLiteral|e.TypeFlags.StringLiteral|e.TypeFlags.NumberLiteral|e.TypeFlags.BigInt|e.TypeFlags.BigIntLiteral|e.TypeFlags.ESSymbol|e.TypeFlags.Void|e.TypeFlags.Undefined|e.TypeFlags.Null|e.TypeFlags.Never;return(t.flags&~n)===0}function Io(e){return cl("sha256").update(e).digest("hex")}var ln=new WeakMap;function Fo(e,t,n){ln.has(t)||ln.set(t,fl(e,t));let r=ln.get(t);if(!r)return null;let i=ml(r,n);for(let o of i){if(pn(e,o))return null;for(let a of r.get(o.fileName)??[])i.add(a.source)}return i}function ml(e,t){let n=new Set;for(let[r,i]of t)for(let o of e.get(r)??[])(o.names===null||o.names.some(a=>i.has(a)))&&n.add(o.source);return n}function mn(e,t,n){let r=Eo(e,t),i=Eo(e,n),o=new Set([...r.keys(),...i.keys()].filter(u=>r.has(u)!==i.has(u)));if(!o.size)return null;for(let u of o){let l=r.get(u)??i.get(u);if(l?.length!==1||!l[0]?.body)return null}let a=new Set([...o].flatMap(u=>[...r.get(u)??[],...i.get(u)??[]])),s=u=>e.isIdentifier(u)&&o.has(u.text)||e.forEachChild(u,l=>s(l)||void 0)===!0,c=u=>u.statements.filter(l=>!a.has(l));return c(t).some(s)||c(n).some(s)?null:o}function Eo(e,t){let n=new Map;for(let r of t.statements){if(!e.isFunctionDeclaration(r)||!r.name)continue;let i=e.getModifiers(r);if(!i?.some(a=>a.kind===e.SyntaxKind.ExportKeyword)||i.some(a=>a.kind===e.SyntaxKind.DefaultKeyword||a.kind===e.SyntaxKind.DeclareKeyword))continue;let o=n.get(r.name.text)??[];o.push(r),n.set(r.name.text,o)}return n}function fl(e,t){let n=t;if(e.version!=="5.9.3"||!n.getResolvedModuleFromModuleSpecifier)return null;let r=new Map,i=!0,o=(a,s)=>{if(!i)return;let c=hl(e,a);if(c)try{let u=n.getResolvedModuleFromModuleSpecifier(c,s)?.resolvedModule,l=u&&t.getSourceFile(u.resolvedFileName);if(l){let d=r.get(l.fileName)??[];d.push({source:s,names:gl(e,a)}),r.set(l.fileName,d)}}catch{i=!1}e.forEachChild(a,u=>o(u,s))};for(let a of t.getSourceFiles())o(a,a);return i?r:null}function gl(e,t){if(e.isImportDeclaration(t)){let n=t.importClause;return n?n.namedBindings&&!e.isNamedImports(n.namedBindings)?null:[...n.name?["default"]:[],...n.namedBindings?.elements.map(r=>(r.propertyName??r.name).text)??[]]:[]}return e.isExportDeclaration(t)&&t.exportClause&&e.isNamedExports(t.exportClause)?t.exportClause.elements.map(n=>(n.propertyName??n.name).text):null}function hl(e,t){let n;return e.isImportDeclaration(t)||e.isExportDeclaration(t)?n=t.moduleSpecifier:e.isExternalModuleReference(t)?n=t.expression:e.isImportTypeNode(t)&&e.isLiteralTypeNode(t.argument)?n=t.argument.literal:e.isCallExpression(t)&&yl(e,t.expression)&&(n=t.arguments[0]),n&&e.isStringLiteralLike(n)?n:null}function yl(e,t){return t.kind===e.SyntaxKind.ImportKeyword||e.isIdentifier(t)&&t.text==="require"}var Co=new WeakSet;function Do(e,t,n){if(Co.has(e))return;let r=e.visit;if(typeof r!="function"||typeof e.pushOccurrence!="function")throw new Error("scip-typescript call visitor has an unsupported module shape");e.visit=function(i){if(t.isCallExpression(i)&&i.expression.kind===t.SyntaxKind.SuperKeyword){let o=Sl(this.checker,i,t),a=o?this.scipSymbol(o).value:"";if(a){let s=i.getSourceFile(),c=s.getLineAndCharacterOfPosition(i.expression.getStart(s)),u=s.getLineAndCharacterOfPosition(i.expression.getEnd());this.pushOccurrence(new n({range:[c.line,c.character,u.character],symbol:a,symbol_roles:0}))}}r.call(this,i)},Co.add(e)}function Sl(e,t,n){let r=t.parent;for(;r&&!n.isClassDeclaration(r)&&!n.isClassExpression(r);)r=r.parent;if(!r)return null;let i=Oo(e,r,n);if(!i)return null;let o=e.getResolvedSignature(t)?.declaration;return o&&n.isConstructorDeclaration(o)?bl(e,i,o.parent,n)?o:null:i.members.some(a=>n.isConstructorDeclaration(a))?null:i}function bl(e,t,n,r){let i=t,o=new Set;for(;i&&!o.has(i);){if(i===n)return!0;o.add(i),i=Oo(e,i,r)}return!1}function Oo(e,t,n){let i=t.heritageClauses?.find(o=>o.token===n.SyntaxKind.ExtendsKeyword)?.types[0]?.expression;return i?_o(e,i,n,new Set):null}function _o(e,t,n,r){for(;n.isParenthesizedExpression(t);)t=t.expression;if(r.has(t))return null;if(r.add(t),n.isClassExpression(t))return t;if(!n.isIdentifier(t)&&!n.isPropertyAccessExpression(t))return null;let i=Rl(e,t,n);return i?n.isClassDeclaration(i)||n.isClassExpression(i)?i:n.isVariableDeclaration(i)&&i.initializer&&i.parent.flags&n.NodeFlags.Const?_o(e,i.initializer,n,r):null:null}function Rl(e,t,n){let r=e.getSymbolAtLocation(t);r&&(r.flags&n.SymbolFlags.Alias)!==0&&(r=e.getAliasedSymbol(r));let i=r?.declarations??[];return i.length===1?i[0]:null}var Mo=new WeakSet;function Ao(e,t,n){if(Mo.has(e))return;let r=e.getDeclarationsForPropertyAssignment;if(typeof r!="function")throw new Error("scip-typescript contextual property runtime is unavailable");e.getDeclarationsForPropertyAssignment=function(o){return r.call(this,o)?.filter(a=>a.parent?.kind!==t.SyntaxKind.ObjectLiteralExpression)};let i=e.index;e.index=function(){if(i.call(this),!this.document.occurrences.length)return;let o=new Map;for(let s of this.document.occurrences){if((s.symbol_roles&1)===0)continue;let c=o.get(s.symbol)??[];c.push(s),o.set(s.symbol,c)}let a=s=>{Pl(this,s,o,t);let c=mt(s,t);c&&(t.isExportAssignment(s)||t.isFunctionDeclaration(s))&&xl(this,s,c,n,t),(t.isCallExpression(s)||t.isNewExpression(s))&&vl(this,s,n,t),t.forEachChild(s,a)};a(this.sourceFile)},Mo.add(e)}function xl(e,t,n,r,i){let o=e.scipSymbol(t).value;if(!o||e.document.occurrences.some(s=>s.symbol===o&&(s.symbol_roles&1)!==0))return;let a=t.getChildren().find(s=>s.kind===i.SyntaxKind.DefaultKeyword)??n.getFirstToken()??n;e.pushOccurrence(new r.Occurrence({symbol:o,symbol_roles:1,range:Fe(a),enclosing_range:Fe(n)})),e.document.symbols.some(s=>s.symbol===o)||e.document.symbols.push(new r.SymbolInformation({symbol:o,documentation:[`\`\`\`ts
|
|
291
|
+
${n.getText()}
|
|
292
|
+
\`\`\``]}))}function vl(e,t,n,r){let i=t.expression;if(!r.isElementAccessExpression(i))return;let o=pt(i.argumentExpression,r);if(o===i.argumentExpression||!(r.isStringLiteralLike(o)||r.isNumericLiteral(o)))return;let s=e.checker.getTypeAtLocation(i.expression).getProperty(o.text)?.declarations??[];if(s.length!==1)return;let c=e.scipSymbol(s[0]).value,u=Fe(o);c&&!e.document.occurrences.some(l=>l.symbol===c&&Lo(l.range,u))&&e.pushOccurrence(new n.Occurrence({symbol:c,symbol_roles:0,range:u}))}function Fe(e){let t=e.getSourceFile(),n=t.getLineAndCharacterOfPosition(e.getStart(t)),r=t.getLineAndCharacterOfPosition(e.end);return n.line===r.line?[n.line,n.character,r.character]:[n.line,n.character,r.line,r.character]}function Lo(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Pl(e,t,n,r){if(r.isPropertyDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)||r.isPropertySignature(t)){let i=e.scipSymbol(t).value,o=Fe(t.name);for(let a of n.get(i)??[])!a.enclosing_range?.length&&Lo(a.range,o)&&(a.enclosing_range=Fe(t))}}var $=Tl(import.meta.url),El=7,jo="0.4.0";function wl(){try{let e=No();if(!e.available)return e;let{packageRoot:t}=e,n=$.resolve("typescript",{paths:[t]}),r=$(n),{FileIndexer:i}=$(N(t,"dist/src/FileIndexer.js")),{Input:o}=$(N(t,"dist/src/Input.js")),{Packages:a}=$(N(t,"dist/src/Packages.js")),s=$(N(t,"dist/src/scip.js"));if(!i||!o||!a||!s.scip?.Document||!s.scip.Index||!s.scip.Occurrence||!s.scip.SymbolInformation)return{available:!1,reason:"scip-typescript document runtime has an unsupported module shape"};let{ScipSymbol:c}=$(N(t,"dist/src/ScipSymbol.js")),{metaDescriptor:u,methodDescriptor:l}=$(N(t,"dist/src/Descriptor.js"));wo(i.prototype,r,{global:c.global,metaDescriptor:u,methodDescriptor:l}),vo(s.scip.Document.prototype),Do(i.prototype,r,s.scip.Occurrence),Ao(i.prototype,r,{Occurrence:s.scip.Occurrence,SymbolInformation:s.scip.SymbolInformation});let d={packageVersion:e.packageVersion,typescript:r,Document:s.scip.Document,Index:s.scip.Index,FileIndexer:i,Input:o,Packages:a};return{available:!0,runtime:d,producerIdentity:Rn(d)}}catch(e){return{available:!1,reason:`scip-typescript document runtime unavailable: ${e instanceof Error?e.message:String(e)}`}}}function ft(){let e=No();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function No(){try{let e=$.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(J(e,"scip-typescript package manifest"));if(t.version!==jo)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${jo}`};let n=bn(e),r=$.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(J(r,"TypeScript package manifest"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:Bo(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function $o(e){let t=e.runtime===void 0?wl():e.runtime===null?{available:!1,reason:"scip-typescript document runtime unavailable"}:{available:!0,runtime:e.runtime,producerIdentity:Rn(e.runtime)};return t.available?{available:!0,emitter:new yn(e,t.runtime)}:t}var yn=class{producerIdentity;workspaceRoot;tsconfigPath;projectRoot;maxFileByteSize;runtime;host;config=null;includedFiles=new Set;program=null;checker=null;symbolTable=new Map;constructorTable=new Map;packages;fragments=new Map;documentCache=new ye;stats={initializations:0,programUpdates:0,documentsEmitted:0,documentsReused:0,documentsRemoved:0,sourceNodesReused:0,sourceNodesReplaced:0,symbolEntriesPruned:0};constructor(t,n){this.workspaceRoot=N(t.workspaceRoot),this.tsconfigPath=N(this.workspaceRoot,t.tsconfigPath),this.projectRoot=t.projectRoot??Dl(this.workspaceRoot,bn(this.tsconfigPath)),this.maxFileByteSize=t.maxFileByteSize??1024*1024,this.runtime=n,this.producerIdentity=Rn(n);let r=fn(n.typescript,this.tsconfigPath);this.config=r,this.host=new Sn(n.typescript,r.options,this.workspaceRoot),this.packages=new n.Packages(this.projectRoot)}initialize(){let t=performance.now();this.initializeProgram();let n=[];for(let r of this.program.getSourceFiles())this.includedFiles.has(W(r.fileName))&&n.push(this.emitSourceFile(r));return this.result(n,t)}advance(t){if(!this.program||!this.checker||!this.config)return this.initializeAndAdvance(t);let n=performance.now(),{modifiedFiles:r,removedFiles:i,affectedFiles:o}=Ol(t);if(this.fragments.clear(),r.length===0&&i.length===0)return this.validateAffectedPaths(o),this.result(this.emitAffectedFiles(o),n);let a=this.detachConsumerDocuments(r,i),s=fn(this.runtime.typescript,this.tsconfigPath);this.config=s,this.includedFiles=new Set(s.fileNames.map(W));let c=this.program,u=this.invalidateSourceNodes([...r,...i]);return this.program=this.runtime.typescript.createProgram(s.fileNames,s.options,this.host.compilerHost,c),this.checker=this.program.getTypeChecker(),this.stats.programUpdates+=1,this.validateIncrementalPaths(r,i,o),this.stats.documentsRemoved+=i.length,this.recordSourceNodeUpdates(u),this.restoreConsumerDocuments(a,r),this.result(this.emitAffectedFiles(o),n)}restoreCheckpoint(t){if(this.program)throw new Error("TypeScript compiler checkpoint requires a cold emitter");this.host.setSourceOverrides(t.sources,this.workspaceRoot);try{this.initializeProgram(),this.documentCache=t.documents}finally{this.host.setSourceOverrides(new Map,this.workspaceRoot)}}fragment(t){return this.fragments.get(Ce(t))?.bytes??null}snapshotStats(){return{...this.stats}}initializeAndAdvance(t){let n=performance.now();this.initializeProgram();let r=Re(t.modifiedFiles),i=Re(t.removedFiles??[]),o=Re(t.affectedFiles);return this.fragments.clear(),this.validateIncrementalPaths(r,i,o,!0),this.stats.documentsRemoved+=i.length,this.result(this.emitAffectedFiles(o),n)}initializeProgram(){this.documentCache=new ye,this.symbolTable=new Map,this.constructorTable.clear();let t=this.config??fn(this.runtime.typescript,this.tsconfigPath);this.includedFiles=new Set(t.fileNames.map(W)),this.program=this.runtime.typescript.createProgram(t.fileNames,t.options,this.host.compilerHost),this.checker=this.program.getTypeChecker(),this.stats.initializations+=1}validateIncrementalPaths(t,n,r,i=!1){if(!i&&t.length===0&&n.length===0)throw new Error("incremental TypeScript document update requires a modified or removed file");if(r.length===0&&n.length===0)throw new Error("incremental TypeScript document update requires an affected or removed file");for(let o of t){let a=j(this.workspaceRoot,o);if(!this.program?.getSourceFile(a))throw new Error(`modified TypeScript dependency is unavailable to the configured project: ${o}`)}for(let o of n){let a=j(this.workspaceRoot,o);if(this.program?.getSourceFile(a))throw new Error(`removed TypeScript source is still present in the configured project: ${o}`)}this.validateAffectedPaths(r)}validateAffectedPaths(t){for(let n of t){let r=j(this.workspaceRoot,n);if(!this.includedFiles.has(W(r)))throw new Error(`affected TypeScript file is outside the configured project: ${n}`)}}emitAffectedFiles(t){return this.stats.symbolEntriesPruned+=this.symbolTable.size+this.constructorTable.size,this.symbolTable=new Map,this.constructorTable.clear(),t.map(n=>{let r=this.program.getSourceFile(j(this.workspaceRoot,n));if(!r)throw new Error(`affected TypeScript source is unavailable: ${n}`);return this.emitSourceFile(r)})}emitSourceFile(t){if(!this.checker)throw new Error("TypeScript document emitter is not initialized");let n=Ce(gn(this.workspaceRoot,t.fileName)),r=this.documentCache.lookup(n);if(r!==void 0){this.stats.documentsReused+=1;let c=kl(n,r,this.runtime);return this.fragments.set(n,c),c}let i=new this.runtime.Document({relative_path:n,occurrences:[]});if(this.fileIndexer(t,i).index(),this.stats.documentsEmitted+=1,i.occurrences.length===0)return this.fragments.delete(n),this.stats.documentsRemoved+=1,{relativePath:n,bytes:null,occurrences:0,symbols:i.symbols.length,referenceFragments:[]};let a=i.serializeBinary();this.documentCache.set(n,a);let s={relativePath:n,blobHash:this.documentCache.lookup(n)?.blobHash,byteLength:a.byteLength,bytes:a,occurrences:i.occurrences.length,symbols:i.symbols.length,referenceFragments:Vo(n,i)};return this.fragments.set(n,s),s}fileIndexer(t,n){return new this.runtime.FileIndexer(this.checker,{cwd:this.workspaceRoot,projectRoot:this.projectRoot,projectDisplayName:this.projectRoot,maxFileByteSizeNumber:this.maxFileByteSize},new this.runtime.Input(t.fileName,t.getText()),n,this.symbolTable,this.constructorTable,this.packages,t)}captureBoundaries(t,n){let r=new Map;this.symbolTable=new Map,this.constructorTable.clear();for(let i of t){let o=this.program?.getSourceFile(j(this.workspaceRoot,i));if(!o||!this.program)return null;let a=this.fileIndexer(o,new this.runtime.Document({relative_path:i,occurrences:[]})),s=ko(this.runtime.typescript,this.program,o,a,n?.get(i));if(s===null)return null;r.set(i,s)}return r}detachConsumerDocuments(t,n){let r=this.documentCache;this.documentCache=new ye;let i=this.isolatedChangesFromDisk(t),o=n.length?null:this.captureBoundaries(t,i);return o?{documents:r,boundaries:o,isolatedChanges:i,program:this.program,options:JSON.stringify(this.config.options)}:null}restoreConsumerDocuments(t,n){if(!t||t.options!==JSON.stringify(this.config.options)||!Fl(t.program,this.program,n,this.workspaceRoot)||!Cl(t.boundaries,this.captureBoundaries(n,t.isolatedChanges)))return;let r=[...n];if(t.isolatedChanges.size){let i=this.verifiedIsolatedChanges(t);if(!i)return;let o=Fo(this.runtime.typescript,this.program,i);if(!o||[...o].some(a=>!this.includedFiles.has(W(a.fileName))))return;r.push(...[...o].map(a=>Ce(gn(this.workspaceRoot,a.fileName))))}for(let i of r)t.documents.delete(i);t.documents.protectForGeneration(),this.documentCache=t.documents}isolatedChangesFromDisk(t){let n=new Map,r=this.runtime.typescript;for(let i of t){let o=j(this.workspaceRoot,i),a=this.program.getSourceFile(o),s=this.host.compilerHost.readFile(o);if(!a||s===void 0)continue;let c=r.createSourceFile(o,s,r.ScriptTarget.Latest),u=mn(r,a,c);u&&n.set(i,u)}return n}verifiedIsolatedChanges(t){let n=new Map;for(let[r,i]of t.isolatedChanges){let o=j(this.workspaceRoot,r),a=t.program.getSourceFile(o),s=this.program.getSourceFile(o),c=mn(this.runtime.typescript,a,s);if(!c||c.size!==i.size||[...c].some(u=>!i.has(u)))return null;n.set(s.fileName,c)}return n}invalidateSourceNodes(t){let n=new Map;for(let r of t){let i=j(this.workspaceRoot,r),o=this.program.getSourceFile(i);o&&n.set(r,o),this.host.invalidate(i)}return n}recordSourceNodeUpdates(t){for(let[n,r]of t)this.program.getSourceFile(j(this.workspaceRoot,n))===r?this.stats.sourceNodesReused+=1:this.stats.sourceNodesReplaced+=1}result(t,n){return{producerIdentity:this.producerIdentity,fragments:t,durationMs:performance.now()-n,stats:this.snapshotStats()}}};function kl(e,t,n){let r,i,o,a=()=>{if(i!==void 0)return i;let s=t.read();return r=s,i=s===null?null:n.Document.deserializeBinary(s)};return{relativePath:e,blobHash:t.blobHash,byteLength:t.byteLength,get bytes(){return a(),r},get occurrences(){return a()?.occurrences.length??0},get symbols(){return a()?.symbols.length??0},get referenceFragments(){let s=a();return o??=s?Vo(e,s):[]}}}function Vo(e,t){let n=new Map;for(let r of t.occurrences){if(!r.symbol||(r.symbol_roles&1)!==0||r.range.length<3)continue;let i=r.range[0],o=r.range[1];if(!Number.isInteger(i)||!Number.isInteger(o))continue;let a={targetSymbol:r.symbol,location:{file:e,line:i,column:o}};n.set(`${r.symbol}\0${i}\0${o}`,a)}return[...n.values()].sort((r,i)=>r.targetSymbol.localeCompare(i.targetSymbol)||r.location.line-i.location.line||r.location.column-i.location.column)}var Sn=class{compilerHost;sourceFiles=new Map;sourceOverrides=new Map;constructor(t,n,r){let i=t.createCompilerHost(n),o=i.readFile.bind(i);i.readFile=s=>this.sourceOverrides.get(W(s))??o(s);let a=i.getSourceFile.bind(i);this.compilerHost={...i,getCurrentDirectory:()=>r,getSourceFile:(s,c,u,l)=>{let d=W(s);if(this.sourceFiles.has(d))return this.sourceFiles.get(d);let p=a(s,c,u,l);return this.sourceFiles.set(d,p),p}}}setSourceOverrides(t,n){this.sourceOverrides.clear();for(let[r,i]of t)this.sourceOverrides.set(W(j(n,r)),i.charCodeAt(0)===65279?i.slice(1):i)}invalidate(t){this.sourceFiles.delete(W(t))}};function Fl(e,t,n,r){if(e.getSourceFiles().length!==t.getSourceFiles().length||JSON.stringify(e.getRootFileNames())!==JSON.stringify(t.getRootFileNames()))return!1;let i=new Set(n.map(o=>j(r,o)));return e.getSourceFiles().every((o,a)=>{let s=t.getSourceFiles()[a];return s?.fileName===o.fileName&&(i.has(N(o.fileName))||o===s)})}function Cl(e,t){return t!==null&&e.size===t.size&&[...e].every(([n,r])=>t.get(n)===r)}function fn(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(e.formatDiagnostics([n.error],e.createCompilerHost({})));let r=e.parseJsonConfigFileContent(n.config,e.sys,bn(t)),i=r.errors.filter(o=>o.code!==18003);if(i.length>0)throw new Error(e.formatDiagnostics(i,e.createCompilerHost({})));return r}function Rn(e){return Bo(e.packageVersion,e.typescript.version)}function Bo(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${El}`}function Dl(e,t){return Ce(gn(e,t))||"."}function j(e,t){if(Il(t))throw new Error(`expected a project-relative path: ${t}`);let n=N(e,t),r=e.endsWith(hn)?e:`${e}${hn}`;if(n!==e&&!n.startsWith(r))throw new Error(`path escapes the project root: ${t}`);return n}function Re(e){return[...new Set(e.map(Ce))].sort()}function Ce(e){return e.split(hn).join("/").replace(/^\.\//,"")}function W(e){return N(e)}function Ol(e){let t=Re(e.modifiedFiles),n=Re(e.removedFiles??[]),r=Re(e.affectedFiles);return{modifiedFiles:t,removedFiles:n,affectedFiles:r}}import{createHash as Uo}from"crypto";import{dirname as _l,join as Go}from"path";var xe=6;var Ml="typescript-index";function qo(e){let t=Go(e,Ml),n=kr(t);return{...n,requestDir:n.legacyRequestDir}}var xn;function Wo(e){try{let t=B(Go(_l(e),"meta.json"),{inputKind:"reindex metadata",maxBytes:z}),n=Uo("sha256").update(t).digest("hex");if(xn?.bytesHash===n)return xn.generation;let r=Ne(V(t.toString("utf8"))),i=r?Uo("sha256").update(r).digest("hex"):null;return xn={bytesHash:n,generation:i},i}catch{return null}}function Ho(e,t){if(e===void 0)return!0;if(!Array.isArray(e))return!1;let n=new Set,r=new Set(t);return e.every(i=>!i||typeof i.relativePath!="string"||!r.has(i.relativePath)||n.has(i.relativePath)||typeof i.blobHash!="string"||!/^[a-f0-9]{64}$/.test(i.blobHash)||!Number.isSafeInteger(i.byteLength)||i.byteLength<=0?!1:(n.add(i.relativePath),!0))}import{randomUUID as Nl}from"crypto";import{existsSync as Yo,rmSync as vn}from"fs";import{join as Ko}from"path";import{randomUUID as Al}from"crypto";import{getHeapStatistics as Ll}from"v8";import{resolve as jl}from"path";var gt=class{projectRoot;dbPath;currentGeneration;createEmitter;wallNow;monotonicNow;maxActiveSessions;softMemoryLimitBytes;memoryUsage;active=new Map;requests=0;sessionsCreated=0;sessionsReplaced=0;sessionsEvicted=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(t){this.projectRoot=jl(t.projectRoot),this.dbPath=t.dbPath,this.currentGeneration=t.currentGeneration,this.createEmitter=t.createEmitter??$o,this.wallNow=t.wallNow??t.now??Date.now,this.monotonicNow=t.monotonicNow??t.now??x,Jo(t.maxActiveSessions,"maxActiveSessions"),this.maxActiveSessions=t.maxActiveSessions??8,Jo(t.softMemoryLimitMb,"softMemoryLimitMb"),this.softMemoryLimitBytes=t.softMemoryLimitMb===void 0?null:t.softMemoryLimitMb*1024*1024,this.memoryUsage=t.memoryUsage??(()=>({heapUsedBytes:process.memoryUsage().heapUsed,heapLimitBytes:Ll().heap_size_limit}))}handle(t,n){let r=this.monotonicNow();try{if(this.currentGeneration()!==t)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(n);if(i.emitter.producerIdentity!==n.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats();if(this.dbPath&&o.initializations===0){let d=yi({projectRoot:this.projectRoot,dbPath:this.dbPath,baseGeneration:t,request:n});d&&i.emitter.restoreCheckpoint(d)}let a=i.emitter.advance({modifiedFiles:n.modifiedFiles,removedFiles:n.removedFiles,affectedFiles:n.affectedFiles}),s=this.monotonicNow()-r;this.requests+=1,this.lastRequestAtMs=this.wallNow(),this.lastDurationMs=s,this.lastError=null,this.unavailable=!1;let c=new Map(n.knownDocuments?.map(d=>[d.relativePath,d])),u=[],l=a.fragments.filter(d=>{let p=c.get(d.relativePath);return!p||d.blobHash!==p.blobHash||d.byteLength!==p.byteLength?!0:(u.push(p),!1)});return{producerIdentity:a.producerIdentity,cold:a.stats.initializations>o.initializations,durationMs:s,...u.length?{retainedDocuments:u}:{},fragments:l.map(d=>({relativePath:d.relativePath,bytesBase64:d.bytes===null?null:Buffer.from(d.bytes).toString("base64"),occurrences:d.occurrences,symbols:d.symbols,referenceFragments:d.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(t){let n=[...this.active.values()].map(a=>a.emitter.snapshotStats()),r=a=>n.reduce((s,c)=>s+c[a],0),i=this.memoryUsage(),o=this.softMemoryLimitBytes!==null&&i.heapUsedBytes>=this.softMemoryLimitBytes;return{protocolVersion:xe,state:this.unavailable?"unavailable":this.lastError?"error":this.active.size>0?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,sessionsEvicted:this.sessionsEvicted,activeSessions:this.active.size,maxActiveSessions:this.maxActiveSessions,heapUsedBytes:i.heapUsedBytes,heapLimitBytes:i.heapLimitBytes,...this.softMemoryLimitBytes===null?{}:{softMemoryLimitBytes:this.softMemoryLimitBytes},retireRequested:o,initializations:r("initializations"),programUpdates:r("programUpdates"),documentsEmitted:r("documentsEmitted"),documentsRemoved:r("documentsRemoved"),...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{},...t?{mailbox:t}:{}}}close(){this.active.clear()}emitterFor(t){let n=`${t.tsconfigPath}\0${t.projectArgument}`,r=this.active.get(n);if(r?.projectIdentity===t.projectIdentity)return this.active.delete(n),this.active.set(n,r),r;if(r)this.active.delete(n);else if(this.active.size>=this.maxActiveSessions){let a=this.active.keys().next().value;a!==void 0&&(this.active.delete(a),this.sessionsEvicted+=1)}let i=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:t.tsconfigPath,projectRoot:t.projectArgument});if(!i.available)throw this.unavailable=!0,new Error(i.reason);r&&(this.sessionsReplaced+=1);let o={projectIdentity:t.projectIdentity,emitter:i.emitter};return this.active.set(n,o),this.sessionsCreated+=1,o}};var Th=`typescript-index-${process.pid}-${Al()}`,zo=Y(process.pid),Ih={pid:process.pid,...zo?{processIdentity:zo}:{}};function Jo(e,t){if(e!==void 0&&(!Number.isInteger(e)||e<1))throw new Error(`TypeScript index ${t} must be a positive integer.`)}var $l=12e4,Vl=5,De=class extends Error{name="TypeScriptIndexMemoryPressureError"},ht=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;emitLocally;requireService;localHost=null;constructor(t,n={}){this.projectRoot=nr(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??ql(),this.runtime=n.runtime??Wl,this.mailboxLimits=n.mailboxLimits??{},this.emitLocally=n.emitLocally,this.requireService=n.requireService===!0}request(t){let n=Dr(this.cacheDir),r=qo(this.cacheDir),i=Vt(n.statePath);if(!Xo(i,this.projectRoot,this.runtime))return this.requestLocally(t);let o=this.runtime.now(),a=o+this.timeoutMs,s=(this.runtime.monotonicNow??x)()+this.timeoutMs,c=Nt("typescript-index-v6",{baseGeneration:this.baseGeneration,request:t}),u=$t(c),l=Fr(r,{mailboxVersion:jt,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:a,protocolVersion:xe,id:u,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??x)()<=s;){if(Yo(l.responsePath))try{return Qo(_(l.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t)}finally{vn(l.responsePath,{force:!0})}let d=Vt(n.statePath);if(!Xo(d,this.projectRoot,this.runtime))return this.abandonPendingRequest(r,u),this.requestLocally(t);this.runtime.sleep(Vl)}if(Yo(l.responsePath))try{return Qo(_(l.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t)}finally{vn(l.responsePath,{force:!0})}return this.abandonPendingRequest(r,u),this.requestLocally(t)}abandonPendingRequest(t,n){try{vn(Ko(t.pendingDir,`${n}.json`),{force:!0})}catch{}}requestLocally(t){if(this.requireService)throw new Error("TypeScript incremental index service unavailable; refusing to load the whole compiler graph inside the reindex process. Check scip-query watch --status; run scip-query watch --daemon to start the service explicitly, then retry scip-query reindex");return this.emitLocally?Pn(this.emitLocally(t),t):(this.localHost??=new gt({projectRoot:this.projectRoot,dbPath:Ko(this.cacheDir,"index.db"),currentGeneration:()=>this.baseGeneration}),Pn(ea(this.localHost.handle(this.baseGeneration,t),t.producerIdentity),t))}};function Xo(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null,i=e?Date.parse(e.heartbeatAt):Number.NaN;return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===xe&&n.isProcessAlive(e.pid)&&zl(i,n)&&(!e.processIdentity||r!=null&&Pe(e.processIdentity,r))}function Qo(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==xe||o.id!==t||o.operationKey!==n||o.ok===!0&&o.baseGeneration!==r)throw new Error("TypeScript index service wrote an incompatible response.");if(o.ok!==!0){let a=typeof o.error=="string"?o.error:"TypeScript index service request failed.";throw Bl(a)?new De(a):new Error(a)}return Pn(ea(o.response,i.producerIdentity),i)}function Bl(e){let t=e.toLowerCase();return t.includes("out of memory")||t.includes("memory limit")||t.includes("allocation failed")||t.includes("err_worker_out_of_memory")}function Pn(e,t){if(e.producerIdentity!==t.producerIdentity)throw new Error("TypeScript index service wrote an invalid response.");if(!Ho(e.retainedDocuments,t.affectedFiles))throw new Error("TypeScript index service wrote invalid retained documents.");let n=new Map(t.knownDocuments?.map(o=>[o.relativePath,o]));for(let o of e.retainedDocuments??[]){let a=n.get(o.relativePath);if(!a||a.blobHash!==o.blobHash||a.byteLength!==o.byteLength)throw new Error("TypeScript index service retained a document the requester does not hold.")}let r=[...new Set(t.affectedFiles)].sort(),i=[...e.fragments,...e.retainedDocuments??[]].map(o=>o.relativePath).sort();if(JSON.stringify(i)!==JSON.stringify(r))throw new Error("TypeScript index service omitted or added an affected document.");return e}function Zo(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function ea(e,t){if(!e||typeof e!="object")throw new Error("TypeScript index service wrote an invalid response.");let n=e;if(n.producerIdentity!==t||typeof n.cold!="boolean"||typeof n.durationMs!="number"||!Number.isFinite(n.durationMs)||!Array.isArray(n.fragments))throw new Error("TypeScript index service wrote an invalid response.");let r=new Set,i=n.fragments.map(o=>{if(!o||typeof o.relativePath!="string"||!Hl(o.bytesBase64)||!Zo(o.occurrences)||!Zo(o.symbols)||!Array.isArray(o.referenceFragments)||!o.referenceFragments.every(Ul)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:Gl(o.bytesBase64);return{relativePath:o.relativePath,bytes:a,occurrences:o.occurrences,symbols:o.symbols,referenceFragments:o.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i,...n.retainedDocuments===void 0?{}:{retainedDocuments:n.retainedDocuments}}}function Ul(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.targetSymbol=="string"&&!!t.location&&typeof t.location.file=="string"&&Number.isInteger(t.location.line)&&Number.isInteger(t.location.column)}function Gl(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function ql(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:$l}var Wl={now:Date.now,monotonicNow:x,randomId:Nl,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:me,readProcessIdentity:Y};function Hl(e){return e===null||typeof e=="string"}function zl(e,t){return Number.isFinite(e)&&t.now()-e<=Cr}var Yl=128,Kl=256;function Xl(e,t,n){let r=Zl(e,t);if(!r.eligible)return r;let{previousSnapshot:i,graph:o}=r,a=n??oa(i,e.currentSnapshot,e.producerIdentity,Ie(t)),{manifest:s,compilerManifest:c,sourceChanges:u,projectIdentity:l,dependencyGraphUnchanged:d}=a;if(s.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};let p=u.filter(v=>v.kind==="deleted").map(v=>v.path),m=u.filter(v=>v.kind==="modified"),f=a.fallback.fullProject;if(u.length===0&&!f)return{eligible:!1,reason:"change does not affect the configured TypeScript project"};let{effectiveDeletedPaths:S,incrementalManifest:P,affected:y}=ed(e,o,s,c,u,m,p,a.fallback);if(!y.eligible)return y;let T=y.plan,b=new Set(S),I=od(T,t,o,b);return I?Ql(e,i,P,T,l,I,S,f,d):{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"}}function Ql(e,t,n,r,i,o,a,s,c){let u=o.length===1?o[0]:void 0;return{eligible:!0,manifest:n,plan:r,projectIdentity:i,previousFragmentGeneration:e.previousOverlayGeneration??we(t,e.producerIdentity),nextFragmentGeneration:we(e.currentSnapshot,e.producerIdentity),projects:o,deletedFiles:a,replaceProject:s,dependencyGraphUnchanged:c,...u?{tsconfigPath:u.tsconfigPath,projectArgument:u.projectArgument}:{}}}function Zl(e,t){return t.length===0?{eligible:!1,reason:"workspace project roots unavailable"}:t.length===1&&t[0]==="."&&!e.rootTsconfigExists?{eligible:!1,reason:"root tsconfig unavailable"}:e.previousSnapshot?e.graph===null?{eligible:!1,reason:"dependency graph unavailable"}:e.projectFiles.length===0?{eligible:!1,reason:"prior TypeScript documents unavailable"}:{eligible:!0,previousSnapshot:e.previousSnapshot,graph:e.graph}:{eligible:!1,reason:"prior project snapshot unavailable"}}function ed(e,t,n,r,i,o,a,s){let c=s.fullProject,u=e.currentSnapshot.files.filter(f=>je(f.path,e.currentSnapshot.languages)==="source"&&he(f.path)).map(f=>f.path).sort(),l=new Set(u),d=c?e.projectFiles.filter(f=>!l.has(f)).sort():[...a].sort(),p=c?r:{...n,changes:i},m=c?{eligible:!0,plan:at(r.changes.map(f=>f.path).sort(),new Set([...u,...d]),new Set(s.reasons))}:rd(o,d,t,e.projectFiles);return{effectiveDeletedPaths:d,incrementalManifest:p,affected:m}}function td(e,t){return e.changes.filter(n=>n.inputKind==="source"&&he(n.path)||n.inputKind==="config"&&(!Ve(n.path)||t.has(n.path))&&nd(n)||n.inputKind==="ambient")}function nd(e){return e.kind!=="modified"||e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function oa(e,t,n,r){let i=ie(e,t),o=Bt(t,n,r),a=Bt(e,n,r),s={...i,changes:td(i,r)},c=ae({...s,projectIdentityChanged:i.projectIdentityChanged||o!==a},{deletedFiles:"closure",maxChanges:Kl});return{manifest:i,compilerManifest:s,sourceChanges:i.changes.filter(u=>u.inputKind==="source"&&he(u.path)),projectIdentity:o,fallback:c,dependencyGraphUnchanged:!c.fullProject&&id(i)}}function rd(e,t,n,r){if(e.length===0)return t.length===0?{eligible:!1,reason:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set(t)].sort(),affectedFiles:na(t,n,r),reasons:[]}};let i=st({version:1,changes:e.filter(aa),projectIdentityChanged:!1,uncertainty:[]},n,r);return i.mode==="full-project"?{eligible:!1,reason:i.reasons.length>0?`affected set widened: ${i.reasons.join(", ")}`:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...e.map(o=>o.path),...t])].sort(),affectedFiles:[...new Set([...i.affectedFiles,...e.map(o=>o.path),...na(t,n,r)])].sort(),reasons:[]}}}function aa(e){return e.kind!=="modified"?!0:e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function id(e){let t=e.changes.filter(n=>n.inputKind==="source"&&he(n.path));return t.length>0&&t.every(n=>n.kind==="modified"&&!aa(n))}function od(e,t,n,r){let i=new Map;for(let a of e.affectedFiles){let s=ad(a,t);if(!s)return null;let c=i.get(s)??[];c.push(a),i.set(s,c)}let o=[];for(let[a,s]of[...i].sort(([c],[u])=>c.localeCompare(u))){let c=new Set(s),u=e.changedFiles.filter(p=>!r.has(p)&&(c.has(p)||s.some(m=>ra(m,p,n)))),l=e.changedFiles.filter(p=>r.has(p)&&(c.has(p)||s.some(m=>ra(m,p,n)))),d=s.filter(p=>!r.has(p));if(u.length===0&&l.length===0&&d.length===0)return null;o.push({projectArgument:a,tsconfigPath:a==="."?"tsconfig.json":`${a}/tsconfig.json`,modifiedFiles:u,removedFiles:l,affectedFiles:[...d].sort()})}return o}function na(e,t,n){let r=new Set(n),i=new Map;for(let[s,c]of t)if(r.has(s))for(let u of c){let l=i.get(u)??new Set;l.add(s),i.set(u,l)}let o=new Set(e),a=[...e];for(let s=0;s<a.length;s+=1){let c=a[s];if(c)for(let u of i.get(c)??[])o.has(u)||(o.add(u),a.push(u))}return[...o].sort()}function ad(e,t){let n=t.filter(o=>o==="."||e===o||e.startsWith(`${o}/`));if(n.length===0)return null;let r=[...new Set(n)].sort((o,a)=>yt(a)-yt(o)||o.localeCompare(a)),i=r[0];return r[1]&&yt(r[1])===yt(i)?null:i}function yt(e){return e==="."?0:e.split("/").filter(Boolean).length}function ra(e,t,n){let r=new Set,i=[e];for(let o=0;o<i.length;o+=1){let a=i[o];if(!(!a||r.has(a))){r.add(a);for(let s of n.get(a)??[]){if(s===t)return!0;r.has(s)||i.push(s)}}}return!1}function sa(e){let t=x();try{if(!Tn(e.previousDbPath)||!Tn(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=ft();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let{eligibility:o,baseGeneration:a,projectFiles:s,dependencyGraphSnapshot:c,graphMs:u}=sd(e,r.producerIdentity,n);n=performance.now();let{affectedBatches:l,referenceFragmentsByFile:d,responseDurations:p,anyCold:m,assemblyMs:f,fragmentStoreMs:S,writeMs:P,retainedDocumentCount:y}=ld(e,o,r.producerIdentity,a),T=performance.now()-n,b={scipPath:e.previousShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,affectedBatches:l,retainedDocumentCount:y,completeScipUpdated:!1,durationMs:x()-t,cold:m,changedFiles:o.plan.changedFiles,affectedFiles:o.plan.affectedFiles,deletedFiles:o.deletedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:o.previousFragmentGeneration,nextFragmentGeneration:o.nextFragmentGeneration,manifest:o.manifest,plan:o.plan,projectFileCount:s.length,dependencyGraphSnapshot:c,dependencyGraphUnchanged:o.dependencyGraphUnchanged,referenceFragmentsByFile:d,timings:{runtimeMs:i,graphMs:u,requestMs:T,serviceMs:p.reduce((I,v)=>I+v,0),assemblyMs:f,fragmentStoreMs:S,writeMs:P}};return e.onStatus(`${o.replaceProject?"Bounded TypeScript project refresh":"Incremental TypeScript index"} emitted ${b.affectedFiles.length-b.deletedFiles.length-y} document(s), retained ${y}, removed ${b.deletedFiles.length}, and produced ${l.length} bounded batch(es) across ${o.projects.length} project(s) in ${(b.durationMs/1e3).toFixed(3)}s (${b.cold?"cold":"warm"} service; whole SCIP deferred; runtime ${i.toFixed(0)}ms, graph ${u.toFixed(0)}ms, request ${T.toFixed(0)}ms, assembly ${f.toFixed(0)}ms, fragments ${S.toFixed(0)}ms, write ${P.toFixed(0)}ms).`),b}catch(n){let r=n instanceof Error?n.message:String(n);if(e.onUnavailable?.(r),n instanceof De)throw e.onStatus(`Incremental TypeScript index stopped after memory pressure survived one cold Worker retry: ${r}. Preserving the accepted index instead of starting a memory-heavier whole-project rebuild.`),n;return e.onStatus(`Incremental TypeScript index unavailable: ${r}.`),null}}function sd(e,t,n){let r=fd(e.projectRoot,e.previousSnapshot,e.currentSnapshot),i=e.projectMode==="workspace"?U(e.projectRoot,e.currentSnapshot.typescriptProjects):["."],o=Ie(i),a=r?oa(r,e.currentSnapshot,t,o):void 0,s,c,u,l=new A({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath});try{s=qe(l,{includeIgnored:!1}).filter(he).sort();let f=cd(l,a);c=f.graph,u=f.dependencyGraphSnapshot}finally{l.close()}let d=performance.now()-n,p=Xl({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?i:void 0,previousSnapshot:r,currentSnapshot:e.currentSnapshot,projectFiles:s,graph:c,producerIdentity:t,rootTsconfigExists:Tn(Jl(e.projectRoot,"tsconfig.json")),...e.previousOverlayGeneration===void 0?{}:{previousOverlayGeneration:e.previousOverlayGeneration}},i,a);if(!p.eligible)throw new Error(p.reason);let m=Wo(e.previousDbPath);if(!m)throw new Error("published TypeScript base generation unavailable");return{eligibility:p,baseGeneration:m,projectFiles:s,dependencyGraphSnapshot:u,graphMs:d}}function cd(e,t){let n,r;return t?.fallback.fullProject?(r=He(e,"none")??void 0,n=new Map):t?.dependencyGraphUnchanged?n=new Map:(r=We(e),n=r.graph),{graph:n,dependencyGraphSnapshot:r}}function ud(e){return e.flatMap(t=>{let n=fi(t.affectedFiles,Yl);return(n.length>0?n:[[]]).map((i,o)=>({project:t,affectedFiles:i,removedFiles:o===0?t.removedFiles:[],firstForProject:o===0}))})}function ld(e,t,n,r){let i=new ht({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:r},{requireService:!0}),o=ud(t.projects),a=dd(e,t,n),s=[],c=new Map,u=[],l=!1,d=0,p=0,m=0,f=0,S=t.previousFragmentGeneration;for(let[P,y]of o.entries()){let T=i.request({kind:"emit-documents",tsconfigPath:y.project.tsconfigPath,projectArgument:y.project.projectArgument,projectIdentity:t.projectIdentity,producerIdentity:n,modifiedFiles:y.firstForProject?y.project.modifiedFiles:[],removedFiles:y.firstForProject?y.project.removedFiles:[],affectedFiles:y.affectedFiles,knownDocuments:y.affectedFiles.flatMap(E=>a.get(E)??[])});l||=T.cold,d+=T.retainedDocuments?.length??0,u.push(T.durationMs);let b=y.removedFiles.map(E=>({relativePath:E,bytes:null,occurrences:0,symbols:0,referenceFragments:[]})),I=[...T.fragments,...b];if(!t.replaceProject)for(let E of I)c.set(E.relativePath,E.referenceFragments);let v=md({input:e,eligibility:t,producerIdentity:n,response:T,fragments:I,batch:y,batchIndex:P,lastBatch:P===o.length-1,previousOverlayGeneration:S});p+=v.assemblyMs,f+=v.writeMs,m+=v.fragmentStoreMs,S=v.nextOverlayGeneration,v.affectedBatch.affectedFiles.length&&s.push(v.affectedBatch)}return{affectedBatches:s,referenceFragmentsByFile:c,responseDurations:u,anyCold:l,retainedDocumentCount:d,assemblyMs:p,fragmentStoreMs:m,writeMs:f}}function dd(e,t,n){let r=new Map;if(t.replaceProject||t.projects.length!==1||e.projectMode==="workspace"&&U(e.projectRoot,e.currentSnapshot.typescriptProjects).length!==1)return r;let i=pd(e,t,n);if(i?.producerIdentity!==n||i.projectIdentity!==t.projectIdentity)return r;for(let o of i.overlays)o.blobHash!==null&&r.set(o.relativePath,{...o,blobHash:o.blobHash});return r}function pd(e,t,n){let r=Ye(e.cacheDir,t.previousFragmentGeneration);if(!r&&e.baseShardCurrent&&e.currentSnapshot.languages.length===1&&e.currentSnapshot.languages[0]==="typescript"){let i=ft();i.available&&i.producerIdentity===n&&(r=jr({cacheDir:e.cacheDir,generationIdentity:t.previousFragmentGeneration,producerIdentity:n,projectIdentity:t.projectIdentity,packageVersion:i.packageVersion,indexBytes:B(e.previousIndexPath,{inputKind:"accepted TypeScript index",maxBytes:Te})}))}return r}function md(e){let{input:t,eligibility:n,producerIdentity:r,response:i,fragments:o,batch:a,batchIndex:s,lastBatch:c,previousOverlayGeneration:u}=e,l=performance.now(),d=o.length?Mr(i.fragments):null,p=performance.now()-l,m=s===0?t.candidateAffectedScipPath:`${t.candidateAffectedScipPath}.batch-${s}.scip`,f=performance.now();d&&ia(m,d);let S=performance.now()-f,P=performance.now(),y=c?n.nextFragmentGeneration:gd({previousGenerationIdentity:u,targetGenerationIdentity:n.nextFragmentGeneration,fragments:o,retainedDocuments:i.retainedDocuments});Lr({cacheDir:t.cacheDir,previousGenerationIdentity:u,nextGenerationIdentity:y,producerIdentity:r,projectIdentity:n.projectIdentity,baseShardCurrent:s===0?t.baseShardCurrent:!1,fragments:o,retainedDocuments:i.retainedDocuments,allowProjectIdentityChange:n.replaceProject&&s===0,allowLegacyProjectIdentityMigration:!0});let T=performance.now()-P,b={scipPath:m,affectedFiles:o.map(I=>I.relativePath).sort(),deletedFiles:[...a.removedFiles].sort()};return{assemblyMs:p,writeMs:S,fragmentStoreMs:T,nextOverlayGeneration:y,affectedBatch:b}}function fd(e,t,n){if(!t)return null;let r=new Map(n.files.map(a=>[a.path,a])),i=!1,o=t.files.map(a=>{let s=r.get(a.path);if(a.semanticHash!==void 0||s?.semanticHash===void 0)return a;let c=Be(e,a.path,a.hash);return c===void 0?a:(i=!0,{...a,semanticHash:c})});return i?{...t,files:o}:t}function gd(e){let t=ta("sha256");t.update("typescript-overlay-batch-v1\0"),t.update(e.previousGenerationIdentity),t.update("\0"),t.update(e.targetGenerationIdentity);for(let n of[...e.fragments].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)))t.update("\0path\0"),t.update(n.relativePath),n.bytes===null?t.update("\0deleted"):(t.update("\0bytes\0"),t.update(ta("sha256").update(n.bytes).digest()));for(let n of[...e.retainedDocuments??[]].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)))t.update("\0retained\0").update(JSON.stringify([n.relativePath,n.blobHash,n.byteLength]));return t.digest("hex")}function In(e){let t=ft();if(!t.available)throw new Error(t.reason);let n=Nr({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:B(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:Te}),packageVersion:t.packageVersion});ia(e.candidateShardPath,n)}import{closeSync as hd,existsSync as St,fstatSync as yd,lstatSync as Sd,openSync as bd,renameSync as kn,rmSync as Oe,statSync as Rd,writeSync as xd}from"fs";import{cpus as vd}from"os";import{join as Fn}from"path";var En=Symbol("no-error");async function ca(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=Number.isFinite(t)?Math.max(1,Math.floor(t)):1,o=Math.min(e.length,i),a=0,s=En,c=!0,u=Array.from({length:o},async()=>{for(;c&&a<e.length;){let l=a++;try{r[l]=await n(e[l])}catch(d){s===En&&(s=d),c=!1}}});if(await Promise.all(u),s!==En)throw s;return r}var ua=8*1024;function la(e,t,n){let r=Buffer.from(t,"utf8"),i=()=>bd(e,"wx",384),o;try{o=i()}catch(a){if(a.code!=="EEXIST")throw a;if(n==="skip")return null;Oe(e,{force:!0}),o=i()}try{xd(o,r);let a=yd(o);return{path:e,content:r,device:a.dev,inode:a.ino}}finally{hd(o)}}function Pd(e,t){let n=[];try{if(e.temporaryRootConfigContent!==void 0){let r=la(Fn(t,"tsconfig.json"),e.temporaryRootConfigContent,"skip");r&&n.push(r)}for(let r of e.temporaryProjectConfigs??[]){let i=la(r.path,r.content,"replace");i&&n.push(i)}return n}catch(r){for(let i of n.reverse())ma(i);throw r}}function ma(e){if(e)try{let t=Sd(e.path);if(!t.isFile()||t.dev!==e.device||t.ino!==e.inode||t.size!==e.content.byteLength)return;let n;try{n=B(e.path,{maxBytes:e.content.byteLength,inputKind:"temporary TypeScript index configuration"})}catch{return}if(!n.equals(e.content))return;Oe(e.path)}catch(t){if(t.code!=="ENOENT")throw t}}function Td(e,t,n){if(!e.defaultOutputPath)return;let r=Fn(t,e.defaultOutputPath);n!==r&&St(r)&&kn(r,n)}function Id(e,t,n){if(!e.defaultOutputPath)return null;let r=Fn(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Oe(i,{force:!0}),St(r)?(kn(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Ed(e){e&&(Oe(e.defaultOutputPath,{force:!0}),e.backupPath&&St(e.backupPath)&&kn(e.backupPath,e.defaultOutputPath))}function wd(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,vd().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function fa(e,t,n,r,i){M(i,"Reindex cancelled by its owner.");let o=e.filter(u=>u.config.defaultOutputPath),a=e.filter(u=>!u.config.defaultOutputPath&&u.boundedConcurrency!==void 0),s=e.filter(u=>!u.config.defaultOutputPath&&u.boundedConcurrency===void 0),c=[];if(c.push(...await da(s,wd(s.length,r),t,n,i)),a.length>0){let u=Math.max(1,Math.min(...a.map(l=>l.boundedConcurrency)));c.push(...await da(a,u,t,n,i))}for(let u of o)M(i,"Reindex cancelled by its owner."),c.push((await wn(u,t,n,i)).result);return c.sort((u,l)=>e.findIndex(d=>d.id===u.id)-e.findIndex(d=>d.id===l.id))}async function da(e,t,n,r,i){let o=await ca(e,Math.max(1,t),s=>wn(s,n,r,i));if(t<=1)return o.map(({result:s})=>s);let a=new Map;for(let s of o.filter(c=>c.result.skipped&&c.retryable)){let c=e.find(u=>u.id===s.result.id);c&&(r(`Retrying ${c.label} indexer serially after parallel failure...`),M(i,"Reindex cancelled by its owner."),a.set(c.id,(await wn(c,n,r,i)).result))}return o.map(({result:s})=>a.get(s.id)??s)}async function wn(e,t,n,r){M(r,"Reindex cancelled by its owner."),n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Oe(e.scipPath,{force:!0});let i=Id(e.config,t,e.scipPath),o=[],a=[e.binary,...e.args].join(" "),s=x();try{o=Pd(e,t),e.trustedProjectTool&&wr(t,e.trustedProjectTool);let u=Ir(e.binary,e.args),l=await Ke({command:u.binary,args:u.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:Cd(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,signal:r});if(l.status!==0){let d=l.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${l.status}${d?`:
|
|
293
|
+
${d}`:""}`)}Td(e.config,t,e.scipPath)}catch(u){if(r?.aborted)throw Jn(r,"Reindex cancelled by its owner.");return Fd(e,u,n,s,a)}finally{Ed(i);for(let u of o.reverse())ma(u)}if(!St(e.scipPath))return kd(e,n,s,a);let c;try{c=Rd(e.scipPath).size}catch{c=void 0}return{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:x()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},outputBytes:c},retryable:!1}}function kd(e,t,n,r){let i=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,o=e.label===e.language?i:`${e.label}: ${i}`;return t(`Skipping ${e.label}: ${i}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:x()-n,command:r,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:o}},retryable:!1}}function Fd(e,t,n,r,i){let o=t instanceof Error?t.message:String(t),a=o.length<=ua?o:`${o.slice(0,ua)}
|
|
294
|
+
[indexer failure detail truncated]`,s=`${e.resolvedBinary} indexer failed: ${a}`,c=e.label===e.language?s:`${e.label}: ${s}`;return n(`Skipping ${e.label}: ${s}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:x()-r,command:i,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:c}},retryable:Dd(t)}}function Cd(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):Br.indexer}function Dd(e){return e instanceof Ur?e.kind==="spawn"&&pa(e.cause):pa(e)}function pa(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}import{execFileSync as ha}from"child_process";import{homedir as ga,platform as Od}from"os";import{delimiter as _d,join as bt}from"path";function Dn(e,t){let n=e.installMethods,r=Ee(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n){if(!i.identity||!i.destination){t(`Refusing ${i.label} installation for ${r}: the installer descriptor lacks an immutable identity or destination.`);continue}if(!Mt(i.prerequisite))continue;let o=Md(i);if(t(`Installing immutable ${i.identity} via ${i.label} into ${o}; expected executable: ${r}.`),Ad(e,i,r,t))return!0}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function Md(e){if(e.binary==="npm")return Cn("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=Cn("go",["env","GOBIN"]);if(t)return t;let n=Cn("go",["env","GOPATH"]);if(n)return bt(n.split(_d)[0],"bin")}return e.binary==="dotnet"?bt(process.env.DOTNET_CLI_HOME??ga(),".dotnet","tools"):e.binary==="dart"?bt(process.env.PUB_CACHE??bt(ga(),".pub-cache"),"bin"):e.destination}function Cn(e,t){try{return ha(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}function Ad(e,t,n,r){try{ha(t.binary,t.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:Od()==="win32"});let i=ge(e);if(i){let o=i===e.indexerBinary?"":` (using ${i})`;return r(`Successfully installed ${t.identity} via ${t.label}${o}; resolved executable: ${i}.`),!0}r(`${t.label} command completed but ${n} was not found on PATH`)}catch(i){let o=i instanceof Error?i.message:String(i);r(`${t.label} install failed: ${o}`)}return!1}import Na from"better-sqlite3";import{existsSync as $a}from"fs";import{dirname as Va,join as Ba,resolve as Ua}from"path";import{randomUUID as jd}from"crypto";import{mkdtempSync as Nd,rmSync as $d,statSync as Sa}from"fs";import{tmpdir as Vd}from"os";import{join as ba}from"path";import{Worker as Bd}from"worker_threads";function Ld(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function ve(){return{skippedReferences:0,skippedReferenceReasons:Ld(),skippedReferenceSamples:[]}}function Rt(e,t){e.skippedReferences+=t.skippedReferences;for(let n of Object.keys(e.skippedReferenceReasons)){e.skippedReferenceReasons[n]+=t.skippedReferenceReasons[n];for(let r of t.skippedReferenceSamples.filter(i=>i.reason===n))e.skippedReferenceSamples.filter(o=>o.reason===n&&o.sourceFile===r.sourceFile).length<2&&e.skippedReferenceSamples.push(r)}}var Ud=3e5,Ra=64*1024*1024,Gd={createResultDirectory:()=>Nd(ba(Vd(),"scip-query-vue-workers-")),spawn:(e,t)=>new Bd(e,{workerData:t}),resultSize:e=>Sa(e).size,readResult:e=>_(e,{maxBytes:Ra,inputKind:"Vue worker result"}),removeResultDirectory:e=>$d(e,{recursive:!0,force:!0})};function xa(e){return e.length>=8&&Pa(e.length)>1}async function va(e,t=Gd){let n=Pa(e.vueFiles.length),r=np(e.vueFiles),i=ip(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),a=e.timeoutMs??ep(),s=e.maxResultBytes??tp();ya("timeoutMs",a),ya("maxResultBytes",s);let c=jd(),u=t.createResultDirectory(),l=[],d,p,m;try{for(let S=0;S<i.length;S++){let P=S,y=i[S]??[],T=y.map(v=>v.taskId),b=ba(u,`${P}.json`),I=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:y,resultPath:b,runId:c,workerId:P,taskIds:T});l.push({workerId:P,taskIds:T,resultPath:b,handle:I,completion:qd(I,P)})}await Wd(l,a);let f=l.sort((S,P)=>S.workerId-P.workerId).map(S=>zd(S,c,s,t));m={occurrences:f.flatMap(S=>S.occurrences),...ve()};for(let S of f)Rt(m,S)}catch(f){d=f}finally{p=await ap(l,t,u,d)}if(p)throw p;if(d!==void 0)throw d;if(!m)throw new Error("Vue workers completed without producing a merged result.");return m}function qd(e,t){return new Promise((n,r)=>{let i=!1,o=c=>{i||(i=!0,e.off("error",a),e.off("exit",s),c?r(c):n())},a=c=>{o(new Error(`Vue reference worker ${t} failed: ${c.message}`,{cause:c}))},s=c=>{o(c===0?void 0:new Error(`Vue reference worker ${t} exited with code ${c}`))};e.once("error",a),e.once("exit",s)})}async function Wd(e,t){let n;try{await Promise.race([Promise.all(e.map(r=>r.completion)),new Promise((r,i)=>{n=setTimeout(()=>i(new Error(`Vue reference workers timed out after ${(t/1e3).toFixed(3)}s`)),t),n.unref()})])}finally{n&&clearTimeout(n)}}async function Hd(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function zd(e,t,n,r){let i=sp(e,n,r);if(!_e(i)||i.version!==1||i.runId!==t||i.workerId!==e.workerId)throw new Error(`Vue reference worker ${e.workerId} result identity does not match its assignment`);if(!Qd(i.taskIds,e.taskIds))throw new Error(`Vue reference worker ${e.workerId} result task identities do not match its assignment`);if(i.ok===!1)throw typeof i.error!="string"?new Error(`Vue reference worker ${e.workerId} failure payload is malformed`):new Error(`Vue reference worker ${e.workerId} failed: ${i.error}`);if(i.ok!==!0||!Jd(i.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return i.result}function Jd(e){if(!_e(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(Yd)||!H(e.skippedReferences)||!_e(e.skippedReferenceReasons))return!1;for(let t of["missing-source-file","missing-service-script","no-definition","same-file-definition","unindexed-definition"])if(!H(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(Kd)}function Yd(e){return _e(e)&&typeof e.sourceFile=="string"&&H(e.sourceLine)&&H(e.sourceStartChar)&&H(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&H(e.symbolId)}function Kd(e){return _e(e)&&typeof e.sourceFile=="string"&&H(e.sourceLine)&&H(e.sourceStartChar)&&H(e.sourceEndChar)&&typeof e.token=="string"&&Xd(e.reason)}function Xd(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function H(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function _e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qd(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function ya(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function Zd(e){return e instanceof Error?e.message:String(e)}function Pa(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:1;return Math.max(1,Math.min(e,n))}function ep(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:Ud}function tp(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:Ra}function np(e){let t=rp(),n=[];for(let r of e){let i=Ta(r),o=Math.max(1,Math.ceil(i/t));for(let a=0;a<o;a++)n.push({taskId:`${n.length}:${r}:${a}`,fileName:r,startOffset:Math.floor(i*a/o),endOffset:a===o-1?Number.POSITIVE_INFINITY:Math.floor(i*(a+1)/o),countFileSkip:a===0})}return n}function rp(){return Number.POSITIVE_INFINITY}function ip(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:op(i)})).sort((i,o)=>o.weight-i.weight);for(let i of r){let o=n.reduce((a,s)=>s.weight<a.weight?s:a);o.tasks.push(i.task),o.weight+=i.weight}return n.map(i=>i.tasks).filter(i=>i.length>0)}function op(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Ta(e.fileName)-e.startOffset)}function Ta(e){try{return Sa(e).size}catch{return 1}}async function ap(e,t,n,r){let i=await Hd(e);if(i.length===0)try{t.removeResultDirectory(n)}catch(o){i.push(o)}if(i.length>0){let o=r===void 0?i:[r,...i];return new AggregateError(o,`Vue worker cleanup failed: ${Zd(o[0])}`)}}function sp(e,t,n){let r=n.resultSize(e.resultPath);if(!Number.isSafeInteger(r)||r<0||r>t)throw new Error(`Vue reference worker ${e.workerId} result is ${r} bytes; limit is ${t} bytes`);let i;try{i=JSON.parse(n.readResult(e.resultPath))}catch(o){throw new Error(`Vue reference worker ${e.workerId} produced invalid JSON`,{cause:o})}return i}import{relative as cp}from"path";function On(e,t,n){let r=up(e);return i=>{if(!i.name)return null;let o=n.get(i.fileName);if(!o)return null;let a=n.positionAt(o,i.textSpan.start),s=n.positionAt(o,i.textSpan.start+i.textSpan.length),c=o.text.split(`
|
|
295
|
+
`),u=(r.get(cp(t,i.fileName).replaceAll("\\","/"))??[]).filter(d=>{if(d.name!==i.name)return!1;let p=Tr([d.startLine,d.startChar,d.endLine,d.endChar],d.encoding,c);return p?(a.line>p.startLine||a.line===p.startLine&&a.character>=p.startColumn)&&(s.line<p.endLine||s.line===p.endLine&&s.character<=p.endColumn):!1}),l=new Set(u.map(d=>d.symbolId));return l.size===1?[...l][0]:null}}function up(e){let t=e.prepare(`
|
|
296
|
+
SELECT d.relative_path AS relativePath, d.position_encoding AS encoding,
|
|
297
|
+
der.start_line AS startLine, der.start_char AS startChar,
|
|
298
|
+
der.end_line AS endLine, der.end_char AS endChar,
|
|
299
|
+
der.symbol_id AS symbolId, gs.display_name AS displayName, gs.symbol AS symbol
|
|
300
|
+
FROM defn_enclosing_ranges der
|
|
301
|
+
JOIN documents d ON d.id = der.document_id
|
|
302
|
+
JOIN global_symbols gs ON gs.id = der.symbol_id
|
|
303
|
+
ORDER BY d.relative_path, der.start_line, der.start_char, der.symbol_id
|
|
304
|
+
`).all(),n=new Map;for(let r of t){let i=r.displayName??Pr(r.symbol),o=n.get(r.relativePath)??[];o.push({...r,name:i}),n.set(r.relativePath,o)}return n}import{createRequire as lp}from"module";import{existsSync as dp}from"fs";import{dirname as Ia,extname as pp,join as Ea,relative as mp,resolve as fp}from"path";import{pathToFileURL as gp}from"url";function hp(e){e.transaction(()=>{e.prepare(`
|
|
294
305
|
DELETE FROM mentions
|
|
295
306
|
WHERE chunk_id IN (
|
|
296
307
|
SELECT c.id
|
|
@@ -305,38 +316,27 @@ ${d}`:""}`)}Ju(e.config,t,e.scipPath)}catch(u){if(r?.aborted)throw zn(r,"Reindex
|
|
|
305
316
|
FROM documents
|
|
306
317
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
307
318
|
)
|
|
308
|
-
`).run()})()}function
|
|
319
|
+
`).run()})()}function Mn(e,t){return e.prepare(`
|
|
309
320
|
SELECT relative_path AS relativePath
|
|
310
321
|
FROM documents
|
|
311
322
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
312
323
|
ORDER BY relative_path
|
|
313
|
-
`).all().map(r=>
|
|
314
|
-
SELECT
|
|
315
|
-
d.relative_path AS relativePath,
|
|
316
|
-
der.start_line AS startLine,
|
|
317
|
-
der.end_line AS endLine,
|
|
318
|
-
der.symbol_id AS symbolId,
|
|
319
|
-
gs.display_name AS displayName
|
|
320
|
-
FROM defn_enclosing_ranges der
|
|
321
|
-
JOIN documents d ON d.id = der.document_id
|
|
322
|
-
JOIN global_symbols gs ON gs.id = der.symbol_id
|
|
323
|
-
ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
|
|
324
|
-
`).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function $l(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let s=Math.floor((i+o)/2);e[s].line<t?i=s+1:o=s-1}let a=null;for(let s of[o,i]){let c=e[s];if(!c||c.displayName!==r)continue;let u=Math.abs(c.line-t);u>n||(!a||u<a.distance)&&(a={distance:u,symbolId:c.symbolId})}return a?.symbolId??null}function _n(e,t,n){let r=Hl(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
|
|
324
|
+
`).all().map(r=>fp(t,r.relativePath))}function wa(e,t){let{vueCore:n,ts:r,volarTs:i}=yp(e),{parsed:o,vueOptions:a}=Sp(n,r,t),s=Ia(t),c=n.createVueLanguagePlugin(r,o.options,a,m=>m),u=bp(n,r,c),l=Rp(s,o),{languageServiceHost:d}=i.createLanguageServiceHost(r,r.sys,u,m=>m,l),p=r.createLanguageService(d);return{ts:r,language:u,languageService:p,fileNames:o.fileNames,configDir:s}}function yp(e){let t=lp(gp(Ea(e,"package.json")).href);return{vueCore:_n(t,"@vue/language-core",e),ts:_n(t,"typescript",e),volarTs:_n(t,"@volar/typescript",e)}}function Sp(e,t,n){let r=t.readConfigFile(n,t.sys.readFile);if(r.error||!r.config)throw new Error(`Failed to read ${n}`);let o=e.createParsedCommandLine(t,t.sys,n).vueOptions;return typeof e.createGlobalTypesWriter=="function"&&(o.globalTypesPath=e.createGlobalTypesWriter(o,t.sys.writeFile)),{parsed:t.parseJsonConfigFileContent(r.config,t.sys,Ia(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function bp(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!dp(o))return;let a=_(o,{maxBytes:Ct,inputKind:"Vue language-service source file"});r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??Tp(o))});return r.current=i,i}function Rp(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function _n(e,t,n){try{return e(t)}catch(r){throw(typeof r=="object"&&r!==null&&"code"in r?r.code:null)==="MODULE_NOT_FOUND"?new Error(`Vue augmentation requires ${t} to be installed in ${n}. Install Vue/Volar dependencies for that project, then rerun augment-vue.`,{cause:r}):r}}function An(e,t,n){let r=wp(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
|
|
325
325
|
INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
|
|
326
326
|
VALUES (?, ?, ?, ?)
|
|
327
|
-
`),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let l=
|
|
327
|
+
`),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let l=te(t,u),d=La(r.name,r.version,l);o.run(d,"default",7,`Vue component|${l}`);let p=kp(i,r,t,u);p&&(a++,s.set(u,p))}})(),{get(u){return s.get(u)??null},syntheticSymbols:a}}function ka(e,t,n,r,i){return e.transaction(()=>(hp(e),xp(e,t,n,r),vp(e,i)))()}function xp(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
|
|
328
328
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
329
329
|
VALUES (?, ?, ?, ?, X'00')
|
|
330
330
|
`),a=e.prepare(`
|
|
331
331
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
332
332
|
VALUES (?, ?, 1)
|
|
333
|
-
`);for(let s of n){let c=r.get(s);if(!c)continue;let u=
|
|
333
|
+
`);for(let s of n){let c=r.get(s);if(!c)continue;let u=te(t,s),l=i.get(u);if(!l)continue;let d=o.run(l.id,-1,0,0);a.run(Number(d.lastInsertRowid),c)}}function Fa(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let o=r.language.scripts.get(e.fileName),a=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&a){let s=r.language.maps.get(a,o);if(Ln(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Ca(e){let t=new Set,n=[];for(let r of e){let i=Da(r);t.has(i)||(t.add(i),n.push(r))}return n}function Da(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function vp(e,t){let n=Ep(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
|
|
334
334
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
335
335
|
VALUES (?, ?, ?, ?, X'00')
|
|
336
336
|
`),i=e.prepare(`
|
|
337
337
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
338
338
|
VALUES (?, ?, 0)
|
|
339
|
-
`),o=new Set,a=0,s=0;for(let c of t){let u=
|
|
339
|
+
`),o=new Set,a=0,s=0;for(let c of t){let u=Da(c);if(o.has(u))continue;o.add(u);let l=n.get(c.sourceFile);if(!l)continue;let d=r.run(l,s++,c.sourceLine,c.sourceLine),p=i.run(Number(d.lastInsertRowid),c.symbolId);a+=Number(p.changes)}return a}function*Oa(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function _a(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Ln(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Pp(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let o=Math.floor((n+r)/2);e.lineStarts[o]<=t?n=o+1:r=o-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function Ma(e,t){return te(e,t).startsWith("node_modules/")}function te(e,t){return mp(e,t).replaceAll("\\","/")}function Tp(e){switch(pp(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function Aa(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=_(t,{maxBytes:Ct,inputKind:"Vue source file"}),r={text:n,lineStarts:Ip(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:Pp}}function Ip(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function Ep(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),a=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let s of a)n.set(s.relativePath,s.id)}return n}function wp(e){try{let t=JSON.parse(_(Ea(e,"package.json"),{maxBytes:z,inputKind:"project package manifest"}));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function kp(e,t,n,r){let i=te(n,r),o=La(t.name,t.version,i);return e.get(o)?.id??null}function La(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function Ga(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>Op({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Cp(e){return q(Q(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),q(Ga({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}async function Dp(e){return q(Q(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),_p(e)}function Op(e){let t=Ua(e.projectRoot,e.tsconfig);if(!$a(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Na(e.dbPath);try{let r=Mn(n,e.projectRoot),i=Ba(Va(e.dbPath),"augment-vue-meta.json");return Hi({cachePath:i,readFingerprint:()=>Ha(n,e.projectRoot,e.tsconfig),compute:()=>Mp({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}async function _p(e){let t=Ua(e.projectRoot,e.tsconfig);if(!$a(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Na(e.dbPath);try{let r=Mn(n,e.projectRoot),i=Ba(Va(e.dbPath),"augment-vue-meta.json");return await zi({cachePath:i,readFingerprint:()=>Ha(n,e.projectRoot,e.tsconfig),compute:()=>Ap({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function Mp(e){let t=An(e.db,e.projectRoot,e.vueFiles),n=Wa(e,t);return qa(e,t,n)}async function Ap(e){let t=An(e.db,e.projectRoot,e.vueFiles),n=xa(e.vueFiles)?await va({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles}):Wa(e,t);return qa(e,t,n)}function qa(e,t,n){let r=Ca(n.occurrences),i=ka(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:qp(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:Gp(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function Wa(e,t){let n=Lp({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return jp({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function Ha(e,t,n){let r=e.prepare(`
|
|
340
340
|
SELECT
|
|
341
341
|
(SELECT COUNT(*) FROM documents) AS documents,
|
|
342
342
|
(SELECT COUNT(*) FROM global_symbols) AS symbols,
|
|
@@ -345,13 +345,13 @@ ${d}`:""}`)}Ju(e.config,t,e.scipPath)}catch(u){if(r?.aborted)throw zn(r,"Reindex
|
|
|
345
345
|
(SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
|
|
346
346
|
(SELECT MAX(id) FROM chunks) AS maxChunkId,
|
|
347
347
|
(SELECT MAX(id) FROM global_symbols) AS maxSymbolId
|
|
348
|
-
`).get();return{version:
|
|
349
|
-
`,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function ad(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function da(e,t,n){let r=Te();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:q(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Cn(e,t,n,r,i,o){if(e.skippedReferences++,e.skippedReferenceReasons[o]++,e.skippedReferenceSamples.filter(s=>s.reason===o&&s.sourceFile===r).length>=2)return;let a=t.positionAt(n,i.start);e.skippedReferenceSamples.push({sourceFile:r,sourceLine:a.line,sourceStartChar:a.character,sourceEndChar:a.character+i.text.length,token:i.text,reason:o})}function On(e,t){let n=new Map;for(let o of e){let a=n.get(o.sourceFile)??[];a.push(o),n.set(o.sourceFile,a)}let r=[...n.keys()].sort(),i=[];for(let o=0;i.length<t;o++){let a=!1;for(let s of r){let c=n.get(s)?.[o];if(c&&(i.push(c),a=!0,i.length===t))break}if(!a)break}return i}function sd(e,t){let n=On(e.filter(o=>o.sourceFile!==o.definitionFile),Math.ceil(t/2)),r=new Set(n.map(o=>`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),i=On(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function cd(e,t){let n=[...new Set(e.map(i=>i.reason))].sort(),r=[];for(let[i,o]of n.entries()){let a=n.length-i,s=Math.ceil((t-r.length)/a);r.push(...On(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function ud(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return sd(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function ld(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of pd(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(a))continue;let s=t.tokenContext.tokenByStart.get(a);s&&(xa(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function xa(e,t,n,r,i,o,a){let s=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,sourceToken:i.text,definitionFile:o,symbolId:a})}function dd(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function pd(e,t,n,r,i,o){let a=e.getDocumentHighlights?.(t,n,[t])??[],s=[];for(let c of a)if(c.fileName===t)for(let u of c.highlightSpans){let l=md(r,u.textSpan.start,o,i.text);l!==null&&s.push(l)}return s}function md(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Fn(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function ph(e){let{projectRoot:t,onStatus:n=console.log}=e,r=e.maxHeapMb??ri(process.env.NODE_OPTIONS)??8192,i=e.skipAutoInstall===!0||e.installMissing!==!0,o=bd(e),a=Date.now(),s=F();yt(v(o.outputScip),{recursive:!0}),yt(v(o.outputDb),{recursive:!0});let c=e.languages??Ut(t);if(c.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");n(`Detected languages: ${c.join(", ")}`);let u=bt(o.metaPath),l=I("reindex.fingerprint",()=>ar(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath},u,e.changeJournal,_t(o.outputDb)),{languages:c.length}),d=l.fingerprint,m=l.mode==="delta"?e.changeJournal?.entries.filter(S=>S.kind!=="add").length??0:0,f=Math.max(0,(u?.files.length??0)-m);n(l.mode==="delta"?`Project fingerprint revalidated ${l.changedPaths.length} changed path(s), reused ${f} accepted file fingerprint(s), and accepted ${d.files.length} input(s)`:`Project fingerprint used full scan: ${l.reason}`);let y=await yd({opts:e,paths:o,languages:c,fingerprint:d,onStatus:n}),b=y.snapshot,k=y.releaseBuildLock,O=Ja(e.trigger),E=Xn(D(v(o.outputDb),"cache-lifecycle.lock"),{waitMs:O?1e3:3e4});if(!E)throw k?.(),new ze(O?`Could not acquire scip-query cache lifecycle lock for ${v(o.outputDb)}; another refresh is publishing, so the watcher will retry.`:`Could not acquire scip-query cache lifecycle lock for ${v(o.outputDb)}. A watch daemon or another reindex may hold it. Run "scip-query watch --stop", retry the reindex, then restart with "scip-query watch --daemon".`);let C;try{C=await B("reindex.lock",()=>Xd(D(v(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:n}),{languages:c.length})}catch(S){throw E.release(),k?.(),S}let w=null,h=ai();try{l.mode==="delta"&&_t(o.outputDb)!==e.changeJournal?.baseGeneration&&(d=ir(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),l={mode:"full",fingerprint:d,reason:"accepted-generation-changed-before-lock"},b=void 0,k?.(),k=void 0,n("Project fingerprint used full scan: accepted-generation-changed-before-lock")),Xr(o.outputDb,o.outputScip,o.metaPath);let S=vd(v(o.outputDb));S.removed>0&&n(`Removed ${S.removed} abandoned reindex workspace(s)`);for(let x of S.errors)n(`Could not remove abandoned reindex workspace: ${x}`);let g=null,_=await B("reindex.reuse-check",async()=>(g=await Rd({opts:e,paths:o,languages:c,fingerprint:d,start:a,monotonicStart:s,onStatus:n}),g),()=>({languages:c.length,reused:g!==null}));if(_){Ea({snapshot:b,paths:o,projectRoot:t,fingerprint:d,onStatus:n});let x=Wt(o.outputDb,_);return x.state==="failed"&&n(`Warning: reindex succeeded, but activity telemetry was not recorded: ${x.reason}`),Ct(t,v(o.outputDb)),_}kr()&&await B("reindex.scip-cli-ready",()=>Vd(i,n));let R=Pd(o);w=R.runDir;let P,T=await B("reindex.fresh",async()=>(P=await Id({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:R,fingerprint:d,start:a,monotonicStart:s,maxHeapMb:r,skipAutoInstall:i,onStatus:n,writeTelemetry:h}),P),()=>({languages:c.length,reused:P?.reused,skipped:P?.skipped.length}));Ea({snapshot:b,paths:o,projectRoot:t,fingerprint:d,onStatus:n});let p=Wt(o.outputDb,T);return p.state==="failed"&&n(`Warning: reindex succeeded, but activity telemetry was not recorded: ${p.reason}`),Ct(t,v(o.outputDb)),T}catch(S){let g=Pt({trigger:e.trigger,result:"failed",start:a,monotonicStart:s,error:S instanceof Error?S.message:String(S)});Qa(o.metaPath,g);let _=Gr(o.outputDb,g);throw _.state==="failed"&&n(`Warning: failed reindex activity telemetry was not recorded: ${_.reason}`),S}finally{w&&se(w,{recursive:!0,force:!0}),C(),E.release(),k?.()}}async function yd(e){let{opts:t,paths:n,languages:r,fingerprint:i,onStatus:o}=e,a=t.projectRoot;if(!(t.skipIfUnchanged!==!1&&!Kr(a,n.outputDb)&&Pa(n.outputScip)===Pa(D(v(n.outputDb),"index.scip"))))return{snapshot:void 0,releaseBuildLock:void 0};let c=Ve(a),u=c?.clean?Ke(c,i):void 0;if(c&&!c.clean&&!Ta(n))return Ia({context:c,languages:r,opts:t,paths:n,fingerprint:i,projectRoot:a,onStatus:o,successMessage:"dirty worktree reindex",failurePrefix:"Shared baseline fork failed"}),{snapshot:u,releaseBuildLock:void 0};if(!u)return{snapshot:void 0,releaseBuildLock:void 0};let l=qt(u);if(l){if(!Sd(n,i))try{Qe({snapshot:u,manifest:l,targetCacheDir:v(n.outputDb),targetProjectRoot:a}),o(`Attached shared generation ${u.generationId.slice(0,12)}`)}catch(m){o(`Shared generation attach failed; continuing locally: ${ce(m)}`)}return{snapshot:u,releaseBuildLock:void 0}}c&&!Ta(n)&&Ia({context:c,languages:r,opts:t,paths:n,fingerprint:i,projectRoot:a,onStatus:o,successMessage:"cold worktree reindex",failurePrefix:"Compatible shared baseline fork failed",compatible:!0});let d=await ei(u);if(d.kind==="owner")return{snapshot:u,releaseBuildLock:d.release};if(d.kind==="generation-ready"){let m=qt(u);if(m)try{Qe({snapshot:u,manifest:m,targetCacheDir:v(n.outputDb),targetProjectRoot:a,action:"waited"}),o(`Attached shared generation ${u.generationId.slice(0,12)} after waiting`)}catch(f){o(`Shared generation attach failed after waiting; continuing locally: ${ce(f)}`)}}else o("Shared generation build lock timed out; continuing with an isolated local reindex");return{snapshot:u,releaseBuildLock:void 0}}function Ia(e){let t=Qr(e.context,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath},e.fingerprint);if(t)try{Qe({snapshot:t.snapshot,manifest:t.manifest,targetCacheDir:v(e.paths.outputDb),targetProjectRoot:e.projectRoot,persistLease:!1}),ni(t.snapshot,v(e.paths.outputDb)),e.onStatus(`Forked ${e.compatible?"compatible ":""}shared baseline ${t.snapshot.generationId.slice(0,12)} for ${e.successMessage}`)}catch(n){e.onStatus(`${e.failurePrefix}; continuing locally: ${ce(n)}`)}}function Ea(e){if(e.snapshot)try{let t=Ve(e.projectRoot),n=t?Ke(t,e.fingerprint):void 0;if(!n||n.generationId!==e.snapshot.generationId){e.onStatus("Skipped shared generation publication because the worktree changed during indexing");return}let r=Zr({snapshot:e.snapshot,sourceCacheDir:v(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let i=Ve(e.projectRoot);return(i?Ke(i,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}});ti(e.snapshot,v(e.paths.outputDb),"built"),e.onStatus(r.kind==="published"?`Published shared generation ${e.snapshot.generationId.slice(0,12)} (${r.achievedDurability})`:`Shared generation ${e.snapshot.generationId.slice(0,12)} was already available (${r.achievedDurability})`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${ce(t)}`)}}function Sd(e,t){if(!j(e.outputScip)||!j(e.outputDb)||Ka(e.metaPath,t)===null)return!1;let n=Y(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function Ta(e){if(!j(e.outputScip)||!j(e.outputDb)||!de(e.metaPath))return!1;let t=Y(e.outputDb,e.metaPath);return t.state!=="invalid"&&t.state!=="drifted"}function ce(e){return e instanceof Error?e.message:String(e)}async function Mn(e,t,n,r,i,o,a,s=!1){try{await Fi(ci({indexPath:n,evidenceDbPath:a,reuseExisting:i,affectedFiles:o,forceDerivedRebuild:s}),{projectRoot:e,dbPath:t,onStatus:r})}catch(c){r(`Runtime-boundary extraction unavailable: ${c instanceof Error?c.message:String(c)}.`)}}function bd(e){let t=e.outputScip??D(e.projectRoot,"index.scip"),n=e.outputDb??D(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:D(v(n),"meta.json")}}async function Rd(e){let t=Y(e.paths.outputDb,e.paths.metaPath),n=Ka(e.paths.metaPath,e.fingerprint);if(e.opts.skipIfUnchanged===!1||!j(e.paths.outputScip)||!j(e.paths.outputDb)||n===null||t.state==="invalid"||t.state==="drifted")return null;let r=Ye(e.paths.outputDb,e.fingerprint,e.languages);if(r.state!=="complete")return e.onStatus(Ln("Accepted SQLite index",r)),null;G(X(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await Mn(e.opts.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0),Y(e.paths.outputDb,e.paths.metaPath).state==="drifted"&&(Xe(e.paths.outputDb,e.paths.metaPath),e.onStatus("Published refreshed SQLite generation after post-index augmentation")),n==="operational-config-compatible"&&(ip(e.paths.metaPath,e.fingerprint,e.languages,e.opts),Xe(e.paths.outputDb,e.paths.metaPath),e.onStatus("Migrated operational .scipquery.json metadata without rerunning language indexers."));let i=F()-e.monotonicStart,o=Pt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return Qa(e.paths.metaPath,o),e.onStatus(`Index unchanged; reused existing SQLite index in ${(i/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:i,reused:!0,skipped:[],lastRefresh:o,shards:xd(e.paths,e.languages,e.opts,e.fingerprint)}}function xd(e,t,n,r){let i=jn(r,t,n);return t.map(o=>({id:o,language:o,reused:!0,strategy:"reused",fingerprint:Ae(i[o]),outputBytes:ue(Nn(e.outputDb,o)),durationMs:0}))}function Pd(e){let t=gd(D(v(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:D(t,gt(e.outputScip)),tempOutputDb:D(t,gt(e.outputDb)),tempMetaPath:D(t,gt(e.metaPath))}}function vd(e){let t=[],n;try{n=Aa(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[ce(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{se(D(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${ce(o)}`)}return{removed:r,errors:t}}async function Id(e){let t={...process.env,NODE_OPTIONS:ii(process.env.NODE_OPTIONS,e.maxHeapMb)},n,r=await B("reindex.language-indexers",async()=>(n=await Td(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:a,languageFingerprints:s,shards:c,typescriptProjectShardContext:u,incrementalTypeScript:l}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),Ed({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let f=await B("reindex.publish",()=>Ld(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),y=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(y/1e3).toFixed(1)}s`),{languages:i.map(b=>b.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:y,reused:!0,skipped:o,lastRefresh:f,shards:c,writeTelemetry:e.writeTelemetry}}let d=await B("reindex.publish",()=>Ad(e,t,i,o,a,s,u,l),{mode:l?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),m=d.durationMs;return e.onStatus(`Done in ${(m/1e3).toFixed(1)}s`),{languages:i.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:m,reused:!1,skipped:o,lastRefresh:d,shards:c,writeTelemetry:e.writeTelemetry}}function Ed(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!j(e.run.paths.outputScip)||!j(e.run.paths.outputDb))return!1;let t=Y(e.run.paths.outputDb,e.run.paths.metaPath);if(t.state==="invalid"||t.state==="drifted")return!1;let n=new Set(e.reusedLanguages),r=new Set(e.indexedOutputs.map(i=>i.language));return e.run.languages.length>0&&r.size===e.run.languages.length&&e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(i=>n.has(i)&&r.has(i))}async function Td(e,t){let n=e.opts.skipIfUnchanged===!1,r=Cd({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath,projectFingerprint:e.fingerprint});if(n)for(let[p,x]of r)x.reused&&r.set(p,{...x,reused:!1,reason:"forced reindex requested"});let i=[],o=new Set;for(let[p,x]of r)x.reused&&(i.push({language:p,scipPath:x.scipPath}),o.add(p));for(let p of o)e.onStatus(`Reusing cached ${p} SCIP shard (language inputs unchanged).`);let a=r.get("typescript"),s=Y(e.paths.outputDb,e.paths.metaPath),c=de(e.paths.metaPath),u=s.state==="legacy"||s.state==="current",l=c?.scipCompanion!=="deferred"&&(s.state!=="current"||s.generation.publication?.scipCompanion!=="deferred"),d;n&&a&&!a.reused&&(d="forced reindex rebuilds from the compilers");let m=!n&&a&&!a.reused&&u?Do({projectRoot:e.projectRoot,cacheDir:v(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:a.scipPath,candidateShardPath:le(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:le(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:bt(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus,onUnavailable:p=>{d=p}}):null,f=new Set(m?["typescript"]:[]);if(e.opts.allowExpensiveRebuild===!1){let p=e.languages.filter(x=>!o.has(x)&&!f.has(x));if(p.length>0){let x=p.length===1&&p[0]==="typescript"&&d?`: ${d}`:"";throw new Error(`Incremental indexing is unavailable for ${p.join(", ")}${x}. The accepted index was preserved because whole-project rebuilds are disabled; run scip-query reindex --allow-expensive-rebuild only when you explicitly want that fallback.`)}}let y=m||o.has("typescript")?void 0:wd(e,r),b=y&&n?{...y,classification:new Map([...y.classification].map(([p,x])=>[p,x.reused?{...x,reused:!1,reason:"forced reindex requested"}:x])),reusedProjects:[],missedProjectIds:new Set(y.allProjects.map(p=>`typescript:${p}`))}:y,{preparedRuns:k,skippedLanguages:O,languageOutputScipPaths:E}=Bd({languages:e.languages.filter(p=>!o.has(p)&&!f.has(p)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,trustProjectTools:e.opts.trustProjectTools===!0,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:b?.allProjects,typescriptShardCostDir:v(e.paths.outputDb),clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),C=b?k.filter(p=>p.language!=="typescript"||b.missedProjectIds.has(p.id)):k,w=await Bo(C,e.projectRoot,e.onStatus,e.opts.indexerConcurrency,e.opts.signal);if(ur())for(let p of w)lr({type:"span",name:`reindex.language-indexer.${p.id}`,durationMs:Math.round(p.durationMs),ok:!p.skipped,language:p.language,indexerCommand:p.command,outputBytes:p.outputBytes,measurement:"indexer-run-result"});Gd(v(e.paths.outputDb),e.projectRoot,C,w);let h=[];if(b){_d(e.paths.outputDb,w,e.writeTelemetry);let p=E.typescript??e.tempPaths.tempOutputScip;h=Fd({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:p,reusedProjects:b.reusedProjects,writeTelemetry:e.writeTelemetry})}let S=[...w,...h],{indexedOutputs:g}=qd(S,O),_=m?[{language:"typescript",scipPath:m.scipPath}]:[],R=[...i,..._,...g];Hd(R,O,e.languages,e.opts.allowPartial,e.onStatus);let P=m?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:m.scipPath,outputScipPath:m.scipPath,durationMs:m.durationMs,command:"watch-service:typescript-index",outputBytes:ue(m.scipPath)??void 0,producedOutputBytes:ue(m.affectedScipPath)??void 0}]:[],T=Od(r,[...w,...P],b?{outputDb:e.paths.outputDb,classification:b.classification}:void 0,d);return{indexedOutputs:R,skippedLanguages:O,reusedLanguages:[...o],languageFingerprints:Dd(r,e.languages),shards:T,typescriptProjectShardContext:b?{projects:b.allProjects,fingerprints:b.fingerprints}:void 0,incrementalTypeScript:m??void 0}}function wd(e,t){let n=t.get("typescript");if(!n||n.reused||n.cacheIntegrityFailed||e.opts.typescriptProjectMode!=="workspace")return;let r=ne(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=$i(e.projectRoot,r),o=Li(n.fingerprint.files,r),a=ji(r,i),s=Ni(r,o,a),c=de(e.paths.metaPath),l=kd(c,s,y=>j(Rt(e.paths.outputDb,y))),d=[...l.entries()].filter(([,y])=>y.reused).map(([y])=>y),m=new Set(d),f=new Set(r.filter(y=>!m.has(y)).map(y=>`typescript:${y}`));return{allProjects:r,fingerprints:s,classification:l,reusedProjects:d,missedProjectIds:f}}function kd(e,t,n){let r=new Map;for(let i of Object.keys(t)){let o=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:o});continue}let a=e.version===pe&&Tt(e).typescriptProjectShardReuse?e.typescriptProjectShards?.[i]:void 0;if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:o});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o});continue}if(L(a)!==L(o)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:o});continue}r.set(i,{reused:!0,fingerprint:o})}return r}function _d(e,t,n){for(let r of t){if(r.skipped||!r.id.startsWith("typescript:"))continue;let i=r.id.slice(11),o=Rt(e,i);yt(v(o),{recursive:!0}),ae(n,oe(r.scipPath,o,void 0,{shareImmutable:!0}))}}function Fd(e){return e.reusedProjects.map((t,n)=>{let r=Rt(e.outputDb,t),i=le(e.tempOutputScip,"typescript-project-cached",n);return ae(e.writeTelemetry,oe(r,i,void 0,{shareImmutable:!0})),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:ue(i)??void 0}})}function Cd(e){let t=de(e.paths.metaPath),n=jn(e.projectFingerprint,e.languages,e),r=t&&j(e.paths.outputDb)?Ye(e.paths.outputDb,e.projectFingerprint,e.languages):null,i=new Map;for(let o of e.languages){let a=Nn(e.paths.outputDb,o),s=n[o];if(!t){i.set(o,{reused:!1,reason:"no reindex metadata found",fingerprint:s,scipPath:a});continue}if(t.version!==pe){i.set(o,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:s,scipPath:a});continue}if(!Tt(t).languageShardReuse||!t.languageFingerprints){i.set(o,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:s,scipPath:a});continue}let c=t.languageFingerprints[o];if(!c){i.set(o,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:s,scipPath:a});continue}if(!j(a)){i.set(o,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:a});continue}let u=o==="typescript"?tp(e.projectRoot,c):c;if(L(u)!==L(s)){i.set(o,{reused:!1,reason:"language inputs changed since last index",fingerprint:s,scipPath:a});continue}if(r?.state==="unavailable"||r?.state==="incomplete"&&r.affectedLanguages.includes(o)){i.set(o,{reused:!1,reason:Ln("accepted SQLite index",r),cacheIntegrityFailed:!0,fingerprint:s,scipPath:a});continue}i.set(o,{reused:!0,fingerprint:s,scipPath:a})}return i}function Od(e,t,n,r){let i=[];for(let[o,a]of e)a.reused&&i.push({id:o,language:o,reused:!0,strategy:"reused",fingerprint:Ae(a.fingerprint),outputBytes:ue(a.scipPath),durationMs:0});for(let o of t){let a=e.get(o.language),s=n&&o.id.startsWith("typescript:")?o.id.slice(11):null,c=s?n.classification.get(s):void 0;i.push({id:o.id,language:o.language,reused:!1,strategy:o.command==="watch-service:typescript-index"?"incremental":"full",missReason:c?.reason??a?.reason??o.skipped?.reason,fallbackReason:o.language==="typescript"?r:void 0,fingerprint:c?Ae(c.fingerprint):a?Ae(a.fingerprint):"unknown",outputBytes:o.outputBytes??null,producedOutputBytes:o.producedOutputBytes,durationMs:o.durationMs,command:o.command})}if(n)for(let[o,a]of n.classification)a.reused&&i.push({id:`typescript:${o}`,language:"typescript",reused:!0,strategy:"reused",fingerprint:Ae(a.fingerprint),outputBytes:ue(Rt(n.outputDb,o)),durationMs:0});return i}function Ae(e){return fd("sha256").update(L(e)).digest("hex").slice(0,16)}function ue(e){try{return An(e).size}catch{return null}}function Dd(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}async function Ad(e,t,n,r,i,o,a,s){$(e.opts.signal,"Reindex cancelled by its owner.");let c=!s||s.completeScipUpdated,u=!1;c&&(u=I("reindex.publish.scip-output",()=>{let h=$d({run:e,indexedOutputs:n,incrementalTypeScript:s,typescriptReused:i.includes("typescript")});return wa(e.paths.outputDb,h,e.writeTelemetry),ka(h,e.tempPaths.tempOutputScip,e.onStatus)}));let l=await B("reindex.publish.sqlite-output",()=>zd({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:u,materializeFullFallback:async()=>{if($(e.opts.signal,"Reindex cancelled by its owner."),!s||s.completeScipUpdated)return u;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),Rn({cacheDir:v(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let h=n.map(S=>S.language==="typescript"?{language:S.language,scipPath:s.candidateScipPath}:S);return wa(e.paths.outputDb,h,e.writeTelemetry),u=ka(h,e.tempPaths.tempOutputScip,e.onStatus),u}}));$(e.opts.signal,"Reindex cancelled by its owner."),I("reindex.publish.auxiliary-documents",()=>{G(X(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus})}),await B("reindex.publish.runtime-boundaries",async()=>{let h=s?.plan.mode==="full-project",S=s?.dependencyGraphUnchanged===!0;h?e.onStatus("Rebuilding compiler-derived runtime-boundary relationships while retaining unchanged per-file extraction facts."):S&&e.onStatus("Reusing runtime-boundary relationships because TypeScript semantics are unchanged."),await Mn(e.projectRoot,e.tempPaths.tempOutputDb,e.tempPaths.tempOutputScip,e.onStatus,S,S?void 0:h?s?.changedFiles:s?.affectedFiles,D(v(e.paths.outputDb),sr),h)});let d=I("reindex.publish.sqlite-layout",()=>Zt(e.tempPaths.tempOutputDb,{analyze:Md(s,l.mode)}));d.added.length>0&&e.onStatus(`Added SQLite query indexes: ${d.added.join(", ")}`),d.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${d.removed.join(", ")}`),I("reindex.publish.coverage",()=>Va(e,e.tempPaths.tempOutputDb,n.map(h=>h.language)));let m,f=null;l.mode==="incremental"&&s&&I("reindex.publish.reference-fragments",()=>{if(s.dependencyGraphUnchanged){let g=new V({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});try{f=Ot(g),e.onStatus("Preserved exact TypeScript reference fragments and dependency relationships because only trivia changed.")}finally{g.close()}return}let h=null,S=null;try{h=I("reindex.publish.reference-fragments.open-candidate",()=>new V({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip})),S=I("reindex.publish.reference-fragments.open-evidence",()=>new V({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip})),m=s.dependencyGraphSnapshot?I("reindex.publish.reference-fragments.dependency-graph",()=>gr(h,s.dependencyGraphSnapshot,s.affectedFiles,s.deletedFiles))??void 0:void 0;let g=new Set(s.deletedFiles),_=g.size===0?s.referenceFragmentsByFile:new Map([...s.referenceFragmentsByFile].filter(([P])=>!g.has(P))),R=I("reindex.publish.reference-fragments.seed",()=>Ir(h,e.fingerprint,_,S,m,new Set(s.affectedFiles)));e.onStatus(`Cached exact TypeScript reference fragments for ${R.affectedFiles} affected document(s) and carried ${R.carriedFiles} unaffected document(s) forward.`),R.skippedAffectedFiles>0&&e.onStatus(`Skipped exact TypeScript reference fragment prefill for ${R.skippedAffectedFiles} affected document(s) whose semantic identity was unavailable.`)}catch(g){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${g instanceof Error?g.message:String(g)}.`)}finally{h?.close(),S?.close()}});let y=bt(e.paths.metaPath);l.mode==="incremental"&&s||await La({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousSnapshot:y,currentSnapshot:e.fingerprint,onStatus:e.onStatus});let b=I("reindex.publish.affected-shadow",()=>l.mode==="incremental"&&s?Yd(s,l.changedDocumentPaths):Jt({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:y,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"})),k=Pt({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(h=>h.language),skipped:[...r]}),O=l.mode==="incremental"&&l.scipCompanion==="deferred",{metadata:E,pruneProjects:C}=Na({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:o,typescriptProjectShardContext:a,lastRefresh:k});E.scipCompanion=O?"deferred":"current",I("reindex.publish.metadata",()=>{$a(e),Ba(e.paths.outputDb,C),xt(e.tempPaths.tempMetaPath,E)});let w=I("reindex.publish.generation-handoff",()=>Yr({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:l.mode==="incremental"&&l.scipCompanion==="deferred",publication:l.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:l.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:l.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:l.patchDurationMs,scipCompanion:l.scipCompanion,...l.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:l.converterDurationMs,scipCompanion:"current",...l.fallbackReason?{fallbackReason:l.fallbackReason}:{}}}));return w.achievedDurability==="file-flushed"&&e.onStatus(`Published local generation ${w.currentGeneration.slice(0,12)} (file-flushed; directory sync unsupported)`),l.mode==="incremental"&&s&&I("reindex.publish.dependency-graph",()=>{let h=null;try{h=new V({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let S=s.plan.mode==="full-project"&&s.plan.reasons.length===0?s.changedFiles:s.affectedFiles,g=!1;if(s.dependencyGraphUnchanged){let _=Ot(h),R=f&&_?cr(h,"file-dependency-graph",f,_):0;g=R>0,e.onStatus(g?`Carried ${R} unchanged dependency graph product(s) forward without rebuilding them.`:"No persisted dependency graph product required rekeying; the next graph consumer can materialize it.")}else s.dependencyGraphSnapshot?g=fr(h,s.dependencyGraphSnapshot,S,m):Ge(h);s.dependencyGraphUnchanged||e.onStatus(g?`Carried the dependency graph forward by replacing ${S.length} changed dependency owner(s).`:"Materialized a fresh dependency graph for the accepted generation because no compatible prior graph was available.")}catch(S){e.onStatus(`Dependency graph carry-forward unavailable: ${S instanceof Error?S.message:String(S)}. The next graph consumer will rebuild it.`)}finally{h?.close()}}),I("reindex.publish.cleanup",()=>{Jr(v(e.paths.outputDb),l.mode==="incremental"&&l.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),qr(v(e.paths.outputDb),s?.completeScipUpdated?[s.nextFragmentGeneration]:[])}),I("reindex.publish.shadow-telemetry",()=>ja(e.paths.outputDb,b,e.onStatus)),k}function Md(e,t){return t!=="incremental"||!e||e.plan.mode==="full-project"?!0:e.affectedFiles.length*20>=e.projectFileCount}async function Ld(e,t,n,r,i,o){let a=bt(e.paths.metaPath),s=null;try{ae(e.writeTelemetry,oe(e.paths.outputDb,e.tempPaths.tempOutputDb))}catch(m){s=pi("reused","oracle-error",`Could not snapshot the prior database: ${m instanceof Error?m.message:String(m)}`)}G(X(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await Mn(e.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0);let c=Zt(e.paths.outputDb);c.added.length>0&&e.onStatus(`Added SQLite query indexes: ${c.added.join(", ")}`),c.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${c.removed.join(", ")}`),Va(e,e.paths.outputDb,t.map(m=>m.language)),s==null&&await La({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,onStatus:e.onStatus}),s??=Jt({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,refreshResult:"reused"});let u=Pt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(m=>m.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=Na({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:u});return $a(e),Ba(e.paths.outputDb,d),xt(e.paths.metaPath,l),Xe(e.paths.outputDb,e.paths.metaPath),ja(e.paths.outputDb,s,e.onStatus),u}async function La(e){if(!j(e.previousDbPath))return;let t=z(e.previousSnapshot,e.currentSnapshot);if(t.changes.length===0||_e(t).fullProject)return;let n=null;try{if(n=new V({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),We(n))return;let r=await B("reindex.publish.affected-shadow.warm-sources",()=>hr(n,{yieldToEventLoop:()=>new Promise(i=>setImmediate(i))}));e.onStatus(`Persisted import products for ${r.files} document(s) before the affected-set shadow.`)}catch(r){e.onStatus(`Affected-set shadow import warm-up unavailable: ${r instanceof Error?r.message:String(r)}.`)}finally{n?.close()}}function bt(e){return Et(de(e)?.fingerprint)}function ja(e,t,n){try{mi(e,t),t.status==="evaluated"?n(`Affected-set shadow: ${(t.evaluation.recall*100).toFixed(1)}% recall; ${t.plan.affectedFiles.length} predicted, ${t.comparison.changedFiles.length} changed.`):n(`Affected-set shadow unavailable: ${t.reason}.`)}catch(r){n(`Affected-set shadow telemetry unavailable: ${r instanceof Error?r.message:String(r)}`)}}function Na(e){let t=jd({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:pe,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,sqliteLayoutVersion:1,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function $a(e){$(e.opts.signal,"Reindex cancelled by its owner.");let t=or(e.projectRoot,e.fingerprint);if(L(t)===L(e.fingerprint))return;let n=new Map(e.fingerprint.files.map(o=>[o.path,o])),r=new Map(t.files.map(o=>[o.path,o])),i=[...new Set([...n.keys(),...r.keys()])].filter(o=>L(n.get(o))!==L(r.get(o))).slice(0,5);throw new Error(`Project inputs changed during reindex (${i.join(", ")||"unknown path"}); refusing to publish artifacts built from a different filesystem snapshot.`)}function Va(e,t,n){let r=Ye(t,e.fingerprint,n);if(r.state!=="complete")throw new Error(`${Ln("Candidate SQLite index",r)} Refusing to publish it.`)}function Ln(e,t){if(t.state==="unavailable")return`${e} document coverage could not be verified (${t.reason}); rebuilding cached language shards.`;let n=t.missingPaths.length>0?` First missing path: ${t.missingPaths[0]}.`:"";return`${e} is missing ${t.missingDocumentCount} fingerprinted source document${t.missingDocumentCount===1?"":"s"}; rebuilding affected language shards.${n}`}function jd(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=de(e.metaPath),n=t?.version===pe?t.typescriptProjectShards:void 0;return{field:n,pruneProjects:n?Object.keys(n):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function Ba(e,t){let n=Xa(e);if(t===null){se(n,{recursive:!0,force:!0});return}let r;try{r=Aa(n)}catch{return}for(let i of Nd(r,t))se(D(n,i),{force:!0})}function Nd(e,t){let n=new Set(t.map(r=>`${rn(r)}.scip`));return e.filter(r=>!n.has(r))}function $d(e){if(e.incrementalTypeScript?.completeScipUpdated)return[...e.indexedOutputs];let t=e.indexedOutputs.find(a=>a.language==="typescript");if(!t)return[...e.indexedOutputs];if(!e.typescriptReused)return[...e.indexedOutputs];let n=Y(e.run.paths.outputDb,e.run.paths.metaPath),r=n.state==="current"?n.generation.publication?.typescriptOverlayGeneration:void 0;if(!(n.state==="current"?n.generation.publication?.scipCompanion==="deferred":de(e.run.paths.metaPath)?.scipCompanion==="deferred")||!r)return[...e.indexedOutputs];let o=le(e.run.tempPaths.tempOutputScip,"typescript-deferred",0);return e.run.onStatus("Materializing the deferred whole TypeScript SCIP companion for complete publication..."),Rn({cacheDir:v(e.run.paths.outputDb),generationIdentity:r,baseShardPath:t.scipPath,candidateShardPath:o}),e.indexedOutputs.map(a=>a.language==="typescript"?{language:a.language,scipPath:o}:a)}function wa(e,t,n){for(let r of t){let i=Nn(e,r.language);yt(v(i),{recursive:!0}),r.scipPath!==i&&ae(n,oe(r.scipPath,i,void 0,{shareImmutable:!0}))}}async function Vd(e,t){let n=Fr();if(n){if(n.source==="path"&&va()!=="win32"){let r=Or();Cr(r)||(e?t(`scip on PATH reports ${r??"an unknown version"}; the reviewed version is ${He} and compatibility is unverified. Run scip-query setup --install-missing to install the reviewed release.`):(t(`scip on PATH reports ${r??"an unknown version"}; installing the reviewed ${He}.`),await Dr(t)))}return}if(va()==="win32")throw new Error("The scip CLI was not found. On Windows it ships via the npm sidecar package scip-query-scip-windows (installed automatically with scip-query). Reinstall scip-query with optional dependencies enabled, or follow 'scip-query setup' guidance for the exact sidecar package version, or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
348
|
+
`).get();return{version:4,tsconfig:n,files:lr(t),db:r}}function Lp(e){let t=Aa();return{projectRoot:e.projectRoot,context:wa(e.projectRoot,e.configPath),symbolLookup:On(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function jp(e){let t=[],n=ve(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=Np(e,i);t.push(...o.occurrences),Rt(n,o)}return{occurrences:t,...n}}function Np(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return ja(e.projectRoot,t,"missing-source-file");let r=e.context.language.scripts.get(t.fileName),i=r?.generated?.languagePlugin.typescript?.getServiceScript(r.generated.root)?.code;if(!r||!i)return ja(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=te(e.projectRoot,t.fileName),s=[...Oa(n.text)],c={tokens:s.filter(u=>u.start>=t.startOffset&&u.start<t.endOffset),tokenByStart:new Map(s.map(u=>[u.start,u])),tokenTextCounts:Hp(s),processedStarts:new Set};return $p({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function $p(e){let t=[],n=ve();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||Vp(e.sourceInfo.text,r.start))continue;let i=_a(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(l=>!Ma(e.projectRoot,l.fileName));if(!a){jn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=te(e.projectRoot,a.fileName),c=Bp(e.sourceFile,r.text,s);if(c){jn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=Fa(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){jn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}za(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),Wp(t,e,r,i,s,u)}return{occurrences:t,...n}}function Vp(e,t){let n=e.lastIndexOf(`
|
|
349
|
+
`,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function Bp(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function ja(e,t,n){let r=ve();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:te(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function jn(e,t,n,r,i,o){if(e.skippedReferences++,e.skippedReferenceReasons[o]++,e.skippedReferenceSamples.filter(s=>s.reason===o&&s.sourceFile===r).length>=2)return;let a=t.positionAt(n,i.start);e.skippedReferenceSamples.push({sourceFile:r,sourceLine:a.line,sourceStartChar:a.character,sourceEndChar:a.character+i.text.length,token:i.text,reason:o})}function Nn(e,t){let n=new Map;for(let o of e){let a=n.get(o.sourceFile)??[];a.push(o),n.set(o.sourceFile,a)}let r=[...n.keys()].sort(),i=[];for(let o=0;i.length<t;o++){let a=!1;for(let s of r){let c=n.get(s)?.[o];if(c&&(i.push(c),a=!0,i.length===t))break}if(!a)break}return i}function Up(e,t){let n=Nn(e.filter(o=>o.sourceFile!==o.definitionFile),Math.ceil(t/2)),r=new Set(n.map(o=>`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),i=Nn(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function Gp(e,t){let n=[...new Set(e.map(i=>i.reason))].sort(),r=[];for(let[i,o]of n.entries()){let a=n.length-i,s=Math.ceil((t-r.length)/a);r.push(...Nn(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function qp(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return Up(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function Wp(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of zp(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(a))continue;let s=t.tokenContext.tokenByStart.get(a);s&&(za(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function za(e,t,n,r,i,o,a){let s=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,sourceToken:i.text,definitionFile:o,symbolId:a})}function Hp(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function zp(e,t,n,r,i,o){let a=e.getDocumentHighlights?.(t,n,[t])??[],s=[];for(let c of a)if(c.fileName===t)for(let u of c.highlightSpans){let l=Jp(r,u.textSpan.start,o,i.text);l!==null&&s.push(l)}return s}function Jp(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Ln(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}function Zp(e,t,n,r){let i=t.mode==="delta"?e.changeJournal?.entries.filter(a=>a.kind!=="add").length??0:0,o=Math.max(0,(n?.files.length??0)-i);r(t.mode==="delta"?`Project fingerprint revalidated ${t.changedPaths.length} changed path(s), reused ${o} accepted file fingerprint(s), and accepted ${t.fingerprint.files.length} input(s)`:`Project fingerprint used full scan: ${t.reason}`)}function em(e,t,n){let r=Ps(t),i=Xn(w(h(e),"cache-lifecycle.lock"),{waitMs:r?1e3:3e4});if(!i)throw n?.(),new Qe(r?`Could not acquire scip-query cache lifecycle lock for ${h(e)}; another refresh is publishing, so the watcher will retry.`:`Could not acquire scip-query cache lifecycle lock for ${h(e)}. A watch daemon or another reindex may hold it. Run "scip-query watch --stop", retry the reindex, then restart with "scip-query watch --daemon".`);return i}function tm(e,t){let n=hm(h(e));n.removed>0&&t(`Removed ${n.removed} abandoned reindex workspace(s)`);for(let r of n.errors)t(`Could not remove abandoned reindex workspace: ${r}`)}function Ya(e,t){dm(e);let n=ii(e.paths.outputDb,t);n.state==="failed"&&e.onStatus(`Warning: reindex succeeded, but activity telemetry was not recorded: ${n.reason}`),ar(e.projectRoot,h(e.paths.outputDb))}function nm(e,t,n,r,i,o){let a=wt({trigger:e.trigger,result:"failed",start:n,monotonicStart:r,error:i instanceof Error?i.message:String(i)});ws(t.metaPath,a);let s=oi(t.outputDb,a);s.state==="failed"&&o(`Warning: failed reindex activity telemetry was not recorded: ${s.reason}`)}function rm(e,t){let n=e.languages??Gt(e.projectRoot);if(n.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");return t(`Detected languages: ${n.join(", ")}`),n}function im(e){return e.maxHeapMb??bi(process.env.NODE_OPTIONS)??8192}async function ab(e){let t=us(e);return Ue(e.projectRoot,h(t.outputDb),()=>om(e))}async function om(e){let{projectRoot:t,onStatus:n=console.log}=e,r=im(e),i=e.skipAutoInstall===!0||e.installMissing!==!0,o=us(e),a=Date.now(),s=x();Pt(h(o.outputScip),{recursive:!0}),Pt(h(o.outputDb),{recursive:!0});let c=rm(e,n),u=It(o.metaPath),l=g("reindex.fingerprint",()=>pr(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath},u,e.changeJournal,Ot(o.outputDb)),{languages:c.length}),d=l.fingerprint;Zp(e,l,u,n);let p=await am({opts:e,paths:o,languages:c,fingerprint:d,onStatus:n}),m=p.snapshot,f=p.releaseBuildLock,S=em(o.outputDb,e.trigger,f),P;try{P=await L("reindex.lock",()=>af(w(h(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:n}),{languages:c.length})}catch(b){throw S.release(),f?.(),b}let y=null,T=vi();try{l.mode==="delta"&&Ot(o.outputDb)!==e.changeJournal?.baseGeneration&&(d=Ge(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),l={mode:"full",fingerprint:d,reason:"accepted-generation-changed-before-lock"},m=void 0,f?.(),f=void 0,n("Project fingerprint used full scan: accepted-generation-changed-before-lock")),si(o.outputDb,o.outputScip,o.metaPath),tm(o.outputDb,n);let b=null,I=await L("reindex.reuse-check",async()=>(b=await mm({opts:e,paths:o,languages:c,fingerprint:d,start:a,monotonicStart:s,onStatus:n}),b),()=>({languages:c.length,reused:b!==null}));if(I)return Ya({snapshot:m,paths:o,projectRoot:t,fingerprint:d,onStatus:n},I),I;Gr()&&await L("reindex.scip-cli-ready",()=>Hm(i,n));let v=gm(o);y=v.runDir;let E,R=await L("reindex.fresh",async()=>(E=await ym({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:v,fingerprint:d,start:a,monotonicStart:s,maxHeapMb:r,skipAutoInstall:i,onStatus:n,writeTelemetry:T}),E),()=>({languages:c.length,reused:E?.reused,skipped:E?.skipped.length}));return Ya({snapshot:m,paths:o,projectRoot:t,fingerprint:d,onStatus:n},R),R}catch(b){throw nm(e,o,a,s,b,n),b}finally{y&&se(y,{recursive:!0,force:!0}),P(),S.release(),f?.()}}async function am(e){let{opts:t,paths:n,languages:r,fingerprint:i,onStatus:o}=e,a=t.projectRoot;if(!cm(t,n,a))return{snapshot:void 0,releaseBuildLock:void 0};let c=$e(a),u=c?.clean?tt(c,i):void 0;if(c&&!c.clean&&!cs(n))return ss({context:c,languages:r,opts:t,paths:n,fingerprint:i,projectRoot:a,onStatus:o,successMessage:"dirty worktree reindex",failurePrefix:"Shared baseline fork failed"}),{snapshot:u,releaseBuildLock:void 0};if(!u)return{snapshot:void 0,releaseBuildLock:void 0};let l=Wt(u);if(l)return um(l,u,n,i,a,o),{snapshot:u,releaseBuildLock:void 0};sm(c,r,t,n,i,a,o);let d=await di(u);return d.kind==="owner"?{snapshot:u,releaseBuildLock:d.release}:(lm(d,u,n,a,o),{snapshot:u,releaseBuildLock:void 0})}function sm(e,t,n,r,i,o,a){e&&!cs(r)&&ss({context:e,languages:t,opts:n,paths:r,fingerprint:i,projectRoot:o,onStatus:a,successMessage:"cold worktree reindex",failurePrefix:"Compatible shared baseline fork failed",compatible:!0})}function cm(e,t,n){return e.skipIfUnchanged!==!1&&!ci(n,t.outputDb)&&Ja(t.outputScip)===Ja(w(h(t.outputDb),"index.scip"))}function um(e,t,n,r,i,o){if(!pm(n,r))try{nt({snapshot:t,manifest:e,targetCacheDir:h(n.outputDb),targetProjectRoot:i}),o(`Attached shared generation ${t.generationId.slice(0,12)}`)}catch(a){o(`Shared generation attach failed; continuing locally: ${ce(a)}`)}}function lm(e,t,n,r,i){if(e.kind==="generation-ready"){let o=Wt(t);if(o)try{nt({snapshot:t,manifest:o,targetCacheDir:h(n.outputDb),targetProjectRoot:r,action:"waited"}),i(`Attached shared generation ${t.generationId.slice(0,12)} after waiting`)}catch(a){i(`Shared generation attach failed after waiting; continuing locally: ${ce(a)}`)}}else i("Shared generation build lock timed out; continuing with an isolated local reindex")}function ss(e){let t=ui(e.context,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath},e.fingerprint);if(t)try{nt({snapshot:t.snapshot,manifest:t.manifest,targetCacheDir:h(e.paths.outputDb),targetProjectRoot:e.projectRoot,persistLease:!1}),mi(t.snapshot,h(e.paths.outputDb)),e.onStatus(`Forked ${e.compatible?"compatible ":""}shared baseline ${t.snapshot.generationId.slice(0,12)} for ${e.successMessage}`)}catch(n){e.onStatus(`${e.failurePrefix}; continuing locally: ${ce(n)}`)}}function dm(e){if(e.snapshot)try{let t=$e(e.projectRoot),n=t?tt(t,e.fingerprint):void 0;if(!n||n.generationId!==e.snapshot.generationId){e.onStatus("Skipped shared generation publication because the worktree changed during indexing");return}let r=li({snapshot:e.snapshot,sourceCacheDir:h(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let i=$e(e.projectRoot);return(i?tt(i,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}});pi(e.snapshot,h(e.paths.outputDb),"built"),e.onStatus(r.kind==="published"?`Published shared generation ${e.snapshot.generationId.slice(0,12)} (${r.achievedDurability})`:`Shared generation ${e.snapshot.generationId.slice(0,12)} was already available (${r.achievedDurability})`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${ce(t)}`)}}function pm(e,t){if(!C(e.outputScip)||!C(e.outputDb)||Es(e.metaPath,t)===null)return!1;let n=G(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function cs(e){if(!C(e.outputScip)||!C(e.outputDb)||!ne(e.metaPath))return!1;let t=G(e.outputDb,e.metaPath);return t.state!=="invalid"&&t.state!=="drifted"}function ce(e){return e instanceof Error?e.message:String(e)}async function Bn(e,t,n,r,i,o,a,s=!1,c=!1){try{await Wi(Ti({indexPath:n,evidenceDbPath:a,reuseExisting:i,affectedFiles:o,forceDerivedRebuild:s,compilerFactsUnchanged:c}),{projectRoot:e,dbPath:t,onStatus:r})}catch(u){r(`Runtime-boundary extraction unavailable: ${u instanceof Error?u.message:String(u)}.`)}}function us(e){let t=e.outputScip??w(e.projectRoot,"index.scip"),n=e.outputDb??w(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:w(h(n),"meta.json")}}async function mm(e){let t=G(e.paths.outputDb,e.paths.metaPath),n=Es(e.paths.metaPath,e.fingerprint);if(e.opts.skipIfUnchanged===!1||!C(e.paths.outputScip)||!C(e.paths.outputDb)||n===null||t.state==="invalid"||t.state==="drifted")return null;let r=Ze(e.paths.outputDb,e.fingerprint,e.languages);if(r.state!=="complete")return e.onStatus(Un("Accepted SQLite index",r)),null;q(Q(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),Ht({projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,fingerprint:e.fingerprint}),await Bn(e.opts.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0),G(e.paths.outputDb,e.paths.metaPath).state==="drifted"&&(et(e.paths.outputDb,e.paths.metaPath),e.onStatus("Published refreshed SQLite generation after post-index augmentation")),n==="operational-config-compatible"&&(ff(e.paths.metaPath,e.fingerprint,e.languages,e.opts),et(e.paths.outputDb,e.paths.metaPath),e.onStatus("Migrated operational .scipquery.json metadata without rerunning language indexers."));let i=x()-e.monotonicStart,o=wt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return ws(e.paths.metaPath,o),e.onStatus(`Index unchanged; reused existing SQLite index in ${(i/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:i,reused:!0,skipped:[],lastRefresh:o,shards:fm(e.paths,e.languages,e.opts,e.fingerprint)}}function fm(e,t,n,r){let i=Gn(r,t,n);return t.map(o=>({id:o,language:o,reused:!0,strategy:"reused",fingerprint:Me(i[o]),outputBytes:ue(qn(e.outputDb,o)),durationMs:0}))}function gm(e){let t=Xp(w(h(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:w(t,xt(e.outputScip)),tempOutputDb:w(t,xt(e.outputDb)),tempMetaPath:w(t,xt(e.metaPath))}}function hm(e){let t=[],n;try{n=rs(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[ce(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{se(w(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${ce(o)}`)}return{removed:r,errors:t}}async function ym(e){let t={...process.env,NODE_OPTIONS:Ri(process.env.NODE_OPTIONS,e.maxHeapMb)},n,r=await L("reindex.language-indexers",async()=>(n=await bm(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:a,languageFingerprints:s,shards:c,typescriptProjectShardContext:u,incrementalTypeScript:l}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),Sm({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let m=await L("reindex.publish",()=>Bm(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),f=m.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(f/1e3).toFixed(1)}s`),{languages:i.map(S=>S.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:f,reused:!0,skipped:o,lastRefresh:m,shards:c,writeTelemetry:e.writeTelemetry}}let d=await L("reindex.publish",()=>$m(e,t,i,o,a,s,u,l),{mode:l?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),p=d.durationMs;return e.onStatus(`Done in ${(p/1e3).toFixed(1)}s`),{languages:i.map(m=>m.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:p,reused:!1,skipped:o,lastRefresh:d,shards:c,writeTelemetry:e.writeTelemetry}}function Sm(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!C(e.run.paths.outputScip)||!C(e.run.paths.outputDb))return!1;let t=G(e.run.paths.outputDb,e.run.paths.metaPath);if(t.state==="invalid"||t.state==="drifted")return!1;let n=new Set(e.reusedLanguages),r=new Set(e.indexedOutputs.map(i=>i.language));return e.run.languages.length>0&&r.size===e.run.languages.length&&e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(i=>n.has(i)&&r.has(i))}async function bm(e,t){let n=e.opts.skipIfUnchanged===!1,{classification:r,reusableOutputs:i,reused:o}=Rm(e,n),{incrementalTypeScript:a,typescriptIncrementalUnavailableReason:s}=xm(e,r,n),c=new Set(a?["typescript"]:[]);Pm(e,o,c,s);let u=Tm(e,r,!!a||o.has("typescript"),n),{preparedRuns:l,skippedLanguages:d,languageOutputScipPaths:p}=zm({languages:e.languages.filter(E=>!o.has(E)&&!c.has(E)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,trustProjectTools:e.opts.trustProjectTools===!0,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:u?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),m=u?l.filter(E=>E.language!=="typescript"||u.missedProjectIds.has(E.id)):l,f=await fa(m,e.projectRoot,e.onStatus,e.opts.indexerConcurrency,e.opts.signal);Im(e,m,f);let S=Em(e,u,f,p),P=[...f,...S],{indexedOutputs:y}=ef(P,d),T=a?[{language:"typescript",scipPath:a.scipPath}]:[],b=[...i,...T,...y];tf(b,d,e.languages,e.opts.allowPartial,e.onStatus);let I=wm(a),v=Am(r,[...f,...I],u?{outputDb:e.paths.outputDb,classification:u.classification}:void 0,s);return{indexedOutputs:b,skippedLanguages:d,reusedLanguages:[...o],languageFingerprints:Nm(r,e.languages),shards:v,typescriptProjectShardContext:u?{projects:u.allProjects,fingerprints:u.fingerprints}:void 0,incrementalTypeScript:a??void 0}}function Rm(e,t){let n=Om({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath,projectFingerprint:e.fingerprint});if(t)for(let[o,a]of n)a.reused&&n.set(o,{...a,reused:!1,reason:"forced reindex requested"});let r=[],i=new Set;for(let[o,a]of n)a.reused&&(r.push({language:o,scipPath:a.scipPath}),i.add(o));for(let o of i)e.onStatus(`Reusing cached ${o} SCIP shard (language inputs unchanged).`);return{classification:n,reusableOutputs:r,reused:i}}function xm(e,t,n){let r=t.get("typescript"),{incrementalGenerationUsable:i,baseShardCurrent:o,previousOverlay:a}=vm(e.paths),s;return n&&r&&!r.reused&&(s="forced reindex rebuilds from the compilers"),{incrementalTypeScript:!n&&r&&!r.reused&&i?sa({projectRoot:e.projectRoot,cacheDir:h(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:r.scipPath,candidateShardPath:le(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:le(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:o,previousSnapshot:It(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,...a,onStatus:e.onStatus,onUnavailable:u=>{s=u}}):null,typescriptIncrementalUnavailableReason:s}}function vm(e){let t=G(e.outputDb,e.metaPath),n=ne(e.metaPath),r=t.state==="legacy"||t.state==="current",i=n?.scipCompanion!=="deferred"&&(t.state!=="current"||t.generation.publication?.scipCompanion!=="deferred"),o=t.state==="current"&&t.generation.publication?.scipCompanion==="deferred"&&t.generation.publication.typescriptOverlayGeneration?{previousOverlayGeneration:t.generation.publication.typescriptOverlayGeneration}:{};return{incrementalGenerationUsable:r,baseShardCurrent:i,previousOverlay:o}}function Pm(e,t,n,r){if(e.opts.allowExpensiveRebuild===!1){let i=e.languages.filter(o=>!t.has(o)&&!n.has(o));if(i.length>0){let o=i.length===1&&i[0]==="typescript"&&r?`: ${r}`:"";throw new Error(`Incremental indexing is unavailable for ${i.join(", ")}${o}. The accepted index was preserved because whole-project rebuilds are disabled; run scip-query reindex --allow-expensive-rebuild only when you explicitly want that fallback.`)}}}function Tm(e,t,n,r){let i=n?void 0:km(e,t);return i&&r?{...i,classification:new Map([...i.classification].map(([a,s])=>[a,s.reused?{...s,reused:!1,reason:"forced reindex requested"}:s])),reusedProjects:[],missedProjectIds:new Set(i.allProjects.map(a=>`typescript:${a}`))}:i}function Im(e,t,n){if(gr())for(let r of n)hr({type:"span",name:`reindex.language-indexer.${r.id}`,durationMs:Math.round(r.durationMs),ok:!r.skipped,language:r.language,indexerCommand:r.command,outputBytes:r.outputBytes,measurement:"indexer-run-result"})}function Em(e,t,n,r){let i=[];if(t){Cm(e.paths.outputDb,n,e.writeTelemetry);let o=r.typescript??e.tempPaths.tempOutputScip;i=Dm({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:o,reusedProjects:t.reusedProjects,writeTelemetry:e.writeTelemetry})}return i}function wm(e){return e?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:e.scipPath,outputScipPath:e.scipPath,durationMs:e.durationMs,command:"watch-service:typescript-index",outputBytes:ue(e.scipPath)??void 0,producedOutputBytes:ue(e.affectedScipPath)??void 0}]:[]}function km(e,t){let n=t.get("typescript");if(!n||n.reused||n.cacheIntegrityFailed||e.opts.typescriptProjectMode!=="workspace")return;let r=U(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=eo(e.projectRoot,r),o=Xi(n.fingerprint.files,r),a=Qi(r,i),s=Zi(r,o,a),c=ne(e.paths.metaPath),l=Fm(c,s,f=>C(Et(e.paths.outputDb,f))),d=[...l.entries()].filter(([,f])=>f.reused).map(([f])=>f),p=new Set(d),m=new Set(r.filter(f=>!p.has(f)).map(f=>`typescript:${f}`));return{allProjects:r,fingerprints:s,classification:l,reusedProjects:d,missedProjectIds:m}}function Fm(e,t,n){let r=new Map;for(let i of Object.keys(t)){let o=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:o});continue}let a=e.version===de&&re(e.fingerprint)?.typescriptSymbolIdentityVersion===6&&Ft(e).typescriptProjectShardReuse?e.typescriptProjectShards?.[i]:void 0;if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:o});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o});continue}if(F(a)!==F(o)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:o});continue}r.set(i,{reused:!0,fingerprint:o})}return r}function Cm(e,t,n){for(let r of t){if(r.skipped||!r.id.startsWith("typescript:"))continue;let i=r.id.slice(11),o=Et(e,i);Pt(h(o),{recursive:!0}),X(n,K(r.scipPath,o,void 0,{shareImmutable:!0}))}}function Dm(e){return e.reusedProjects.map((t,n)=>{let r=Et(e.outputDb,t),i=le(e.tempOutputScip,"typescript-project-cached",n);return X(e.writeTelemetry,K(r,i,void 0,{shareImmutable:!0})),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:ue(i)??void 0}})}function Om(e){let t=ne(e.paths.metaPath),n=Gn(e.projectFingerprint,e.languages,e),r=t&&C(e.paths.outputDb)?Ze(e.paths.outputDb,e.projectFingerprint,e.languages):null,i=new Map;for(let o of e.languages){let a=qn(e.paths.outputDb,o),s=n[o];i.set(o,_m(e.projectRoot,o,s,a,t,r))}return i}function _m(e,t,n,r,i,o){return i?i.version!==de?{reused:!1,reason:`metadata version ${String(i.version??"unknown")} predates per-language shard caching`,fingerprint:n,scipPath:r}:!Ft(i).languageShardReuse||!i.languageFingerprints?{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:n,scipPath:r}:Mm(e,t,n,r,i.languageFingerprints[t],o):{reused:!1,reason:"no reindex metadata found",fingerprint:n,scipPath:r}}function Mm(e,t,n,r,i,o){if(!i)return{reused:!1,reason:"no cached fingerprint for this language",fingerprint:n,scipPath:r};if(!C(r))return{reused:!1,reason:"cached shard file missing on disk",fingerprint:n,scipPath:r};let a=t==="typescript"?df(e,i):i;return F(a)!==F(n)?{reused:!1,reason:"language inputs changed since last index",fingerprint:n,scipPath:r}:o?.state==="unavailable"||o?.state==="incomplete"&&o.affectedLanguages.includes(t)?{reused:!1,reason:Un("accepted SQLite index",o),cacheIntegrityFailed:!0,fingerprint:n,scipPath:r}:{reused:!0,fingerprint:n,scipPath:r}}function Am(e,t,n,r){let i=[];for(let[o,a]of e)a.reused&&i.push({id:o,language:o,reused:!0,strategy:"reused",fingerprint:Me(a.fingerprint),outputBytes:ue(a.scipPath),durationMs:0});if(Lm(i,e,t,n,r),n)for(let[o,a]of n.classification)a.reused&&i.push({id:`typescript:${o}`,language:"typescript",reused:!0,strategy:"reused",fingerprint:Me(a.fingerprint),outputBytes:ue(Et(n.outputDb,o)),durationMs:0});return i}function Lm(e,t,n,r,i){for(let o of n){let a=t.get(o.language),s=r&&o.id.startsWith("typescript:")?o.id.slice(11):null,c=s?r.classification.get(s):void 0;e.push({id:o.id,language:o.language,reused:!1,strategy:o.command==="watch-service:typescript-index"?"incremental":"full",missReason:c?.reason??a?.reason??o.skipped?.reason,fallbackReason:o.language==="typescript"?i:void 0,fingerprint:jm(c,a),outputBytes:o.outputBytes??null,producedOutputBytes:o.producedOutputBytes,durationMs:o.durationMs,command:o.command})}}function jm(e,t){return e?Me(e.fingerprint):t?Me(t.fingerprint):"unknown"}function Me(e){return Kp("sha256").update(F(e)).digest("hex").slice(0,16)}function ue(e){try{return os(e).size}catch{return null}}function Nm(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}async function $m(e,t,n,r,i,o,a,s){M(e.opts.signal,"Reindex cancelled by its owner.");let c=!s||s.completeScipUpdated,u=!1;c&&(u=g("reindex.publish.scip-output",()=>{let R=Wm({run:e,indexedOutputs:n,incrementalTypeScript:s,typescriptReused:i.includes("typescript")});return Xa(e.paths.outputDb,R,e.writeTelemetry),Qa(R,e.tempPaths.tempOutputScip,e.onStatus)}));let l=await L("reindex.publish.sqlite-output",()=>nf({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:u,materializeFullFallback:async()=>{if(M(e.opts.signal,"Reindex cancelled by its owner."),!s||s.completeScipUpdated)return u;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),In({cacheDir:h(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let R=n.map(D=>D.language==="typescript"?{language:D.language,scipPath:s.candidateScipPath}:D);return Xa(e.paths.outputDb,R,e.writeTelemetry),u=Qa(R,e.tempPaths.tempOutputScip,e.onStatus),u}}));M(e.opts.signal,"Reindex cancelled by its owner.");let d=Sf(l),{metadata:p,pruneProjects:m}=ps({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:o,typescriptProjectShardContext:a});p.scipCompanion=d?"deferred":"current",Ae(e.tempPaths.tempMetaPath,p);let f=g("reindex.publish.auxiliary-documents",()=>q(Q(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus})),S=g("reindex.publish.source-checkpoints",()=>Ht({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,fingerprint:e.fingerprint,changedFiles:s?.changedFiles}));await L("reindex.publish.runtime-boundaries",async()=>{let R=s?.plan.mode==="full-project";R&&e.onStatus("Rebuilding compiler-derived runtime-boundary relationships while retaining unchanged per-file extraction facts."),await Bn(e.projectRoot,e.tempPaths.tempOutputDb,e.tempPaths.tempOutputScip,e.onStatus,!1,R?s?.changedFiles:s?.affectedFiles,w(h(e.paths.outputDb),mr),R,l.mode==="incremental"&&l.compilerFactsUnchanged===!0&&f.result.inserted===0&&S===0)});let P=g("reindex.publish.sqlite-layout",()=>en(e.tempPaths.tempOutputDb,{analyze:Vm(s,l.mode)}));hf(P,e),g("reindex.publish.coverage",()=>fs(e,e.tempPaths.tempOutputDb,n.map(R=>R.language)));let y,T=null;l.mode==="incremental"&&s&&g("reindex.publish.reference-fragments",()=>{if(s.dependencyGraphUnchanged){let O=new A({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});try{T=_t(O),e.onStatus("Preserved exact TypeScript reference fragments and dependency relationships because only trivia changed.")}finally{O.close()}return}let R=null,D=null;try{R=g("reindex.publish.reference-fragments.open-candidate",()=>new A({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip})),D=g("reindex.publish.reference-fragments.open-evidence",()=>new A({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip})),y=s.dependencyGraphSnapshot?g("reindex.publish.reference-fragments.dependency-graph",()=>xr(R,s.dependencyGraphSnapshot,Ka(s,l),s.deletedFiles))??void 0:void 0;let O=new Set(s.deletedFiles),ks=O.size===0?s.referenceFragmentsByFile:new Map([...s.referenceFragmentsByFile].filter(([Fs])=>!O.has(Fs))),Le=g("reindex.publish.reference-fragments.seed",()=>Or(R,e.fingerprint,ks,D,y,new Set(s.affectedFiles)));e.onStatus(`Cached exact TypeScript reference fragments for ${Le.affectedFiles} affected document(s) and carried ${Le.carriedFiles} unaffected document(s) forward.`),Le.skippedAffectedFiles>0&&e.onStatus(`Skipped exact TypeScript reference fragment prefill for ${Le.skippedAffectedFiles} affected document(s) whose semantic identity was unavailable.`)}catch(O){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${O instanceof Error?O.message:String(O)}.`)}finally{R?.close(),D?.close()}});let b=It(e.paths.metaPath);l.mode==="incremental"&&s||await ls({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousSnapshot:b,currentSnapshot:e.fingerprint,onStatus:e.onStatus});let I=g("reindex.publish.affected-shadow",()=>l.mode==="incremental"&&s?of(s,l.changedDocumentPaths):Yt({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:b,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"})),v=wt({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(R=>R.language),skipped:[...r]});p.lastRefresh=v,p.updatedAt=v.completedAt,g("reindex.publish.metadata",()=>{ms(e),gs(e.paths.outputDb,m),Ae(e.tempPaths.tempMetaPath,p)});let E=g("reindex.publish.generation-handoff",()=>ai({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:l.mode==="incremental"&&l.scipCompanion==="deferred",publication:l.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:l.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:l.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:l.patchDurationMs,scipCompanion:l.scipCompanion,...l.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:l.converterDurationMs,scipCompanion:"current",...l.fallbackReason?{fallbackReason:l.fallbackReason}:{}}}));return yf(E,e),l.mode==="incremental"&&s&&g("reindex.publish.dependency-graph",()=>{let R=null;try{R=new A({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let D=Ka(s,l),O=!1;s.dependencyGraphUnchanged?O=xf(R,T,e):s.dependencyGraphSnapshot?O=Rr(R,s.dependencyGraphSnapshot,D,y):We(R),s.dependencyGraphUnchanged||e.onStatus(O?`Carried the dependency graph forward by replacing ${D.length} changed dependency owner(s).`:"Materialized a fresh dependency graph for the accepted generation because no compatible prior graph was available.")}catch(D){e.onStatus(`Dependency graph carry-forward unavailable: ${D instanceof Error?D.message:String(D)}. The next graph consumer will rebuild it.`)}finally{R?.close()}}),g("reindex.publish.cleanup",()=>{Vr(h(e.paths.outputDb),l.mode==="incremental"&&l.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),Ar(h(e.paths.outputDb),s?.completeScipUpdated?[s.nextFragmentGeneration]:[])}),g("reindex.publish.shadow-telemetry",()=>ds(e.paths.outputDb,I,e.onStatus)),v}function Ka(e,t){return t.mode==="incremental"&&t.compilerFactsUnchanged&&e.dependencyGraphSnapshot?.sourceEdges==="none"?[]:e.plan.mode==="full-project"&&e.plan.reasons.length===0?e.changedFiles:e.affectedFiles}function Vm(e,t){return t!=="incremental"||!e||e.plan.mode==="full-project"?!0:e.affectedFiles.length*20>=e.projectFileCount}async function Bm(e,t,n,r,i,o){let a=It(e.paths.metaPath),s=null;try{X(e.writeTelemetry,K(e.paths.outputDb,e.tempPaths.tempOutputDb))}catch(p){s=wi("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}q(Q(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await Bn(e.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0);let c=en(e.paths.outputDb);c.added.length>0&&e.onStatus(`Added SQLite query indexes: ${c.added.join(", ")}`),c.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${c.removed.join(", ")}`),fs(e,e.paths.outputDb,t.map(p=>p.language)),s==null&&await ls({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,onStatus:e.onStatus}),s??=Yt({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,refreshResult:"reused"});let u=wt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=ps({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:u});return l.scipCompanion=Um(e.paths),ms(e),gs(e.paths.outputDb,d),Ae(e.paths.metaPath,l),et(e.paths.outputDb,e.paths.metaPath),ds(e.paths.outputDb,s,e.onStatus),u}function Um(e){let t=ne(e.metaPath)?.scipCompanion;if(t)return t;let n=G(e.outputDb,e.metaPath);return n.state==="current"&&n.generation.publication?.scipCompanion==="deferred"?"deferred":"current"}async function ls(e){if(!C(e.previousDbPath))return;let t=ie(e.previousSnapshot,e.currentSnapshot);if(t.changes.length===0||ae(t).fullProject)return;let n=null;try{if(n=new A({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),He(n))return;let r=await L("reindex.publish.affected-shadow.warm-sources",()=>vr(n,{yieldToEventLoop:()=>new Promise(i=>setImmediate(i))}));e.onStatus(`Persisted import products for ${r.files} document(s) before the affected-set shadow.`)}catch(r){e.onStatus(`Affected-set shadow import warm-up unavailable: ${r instanceof Error?r.message:String(r)}.`)}finally{n?.close()}}function It(e){return re(ne(e)?.fingerprint)}function ds(e,t,n){try{ki(e,t),t.status==="evaluated"?n(`Affected-set shadow: ${(t.evaluation.recall*100).toFixed(1)}% recall; ${t.plan.affectedFiles.length} predicted, ${t.comparison.changedFiles.length} changed.`):n(`Affected-set shadow unavailable: ${t.reason}.`)}catch(r){n(`Affected-set shadow telemetry unavailable: ${r instanceof Error?r.message:String(r)}`)}}function ps(e){let t=Gm({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:de,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,sqliteLayoutVersion:1,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function ms(e){M(e.opts.signal,"Reindex cancelled by its owner.");let t=dr(e.projectRoot,e.fingerprint);if(F(t)===F(e.fingerprint))return;let n=new Map(e.fingerprint.files.map(o=>[o.path,o])),r=new Map(t.files.map(o=>[o.path,o])),i=[...new Set([...n.keys(),...r.keys()])].filter(o=>F(n.get(o))!==F(r.get(o))).slice(0,5);throw new Error(`Project inputs changed during reindex (${i.join(", ")||"unknown path"}); refusing to publish artifacts built from a different filesystem snapshot.`)}function fs(e,t,n){let r=Ze(t,e.fingerprint,n);if(r.state!=="complete")throw new Error(`${Un("Candidate SQLite index",r)} Refusing to publish it.`)}function Un(e,t){if(t.state==="unavailable")return`${e} document coverage could not be verified (${t.reason}); rebuilding cached language shards.`;let n=t.missingPaths.length>0?` First missing path: ${t.missingPaths[0]}.`:"";return`${e} is missing ${t.missingDocumentCount} fingerprinted source document${t.missingDocumentCount===1?"":"s"}; rebuilding affected language shards.${n}`}function Gm(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=ne(e.metaPath),n=t?.version===de?t.typescriptProjectShards:void 0;return{field:n,pruneProjects:n?Object.keys(n):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function gs(e,t){let n=Is(e);if(t===null){se(n,{recursive:!0,force:!0});return}let r;try{r=rs(n)}catch{return}for(let i of qm(r,t))se(w(n,i),{force:!0})}function qm(e,t){let n=new Set(t.map(r=>`${on(r)}.scip`));return e.filter(r=>!n.has(r))}function Wm(e){if(e.incrementalTypeScript?.completeScipUpdated)return[...e.indexedOutputs];let t=e.indexedOutputs.find(a=>a.language==="typescript");if(!t)return[...e.indexedOutputs];if(!e.typescriptReused)return[...e.indexedOutputs];let n=G(e.run.paths.outputDb,e.run.paths.metaPath),r=n.state==="current"?n.generation.publication?.typescriptOverlayGeneration:void 0;if(!(n.state==="current"?n.generation.publication?.scipCompanion==="deferred":ne(e.run.paths.metaPath)?.scipCompanion==="deferred")||!r)return[...e.indexedOutputs];let o=le(e.run.tempPaths.tempOutputScip,"typescript-deferred",0);return e.run.onStatus("Materializing the deferred whole TypeScript SCIP companion for complete publication..."),In({cacheDir:h(e.run.paths.outputDb),generationIdentity:r,baseShardPath:t.scipPath,candidateShardPath:o}),e.indexedOutputs.map(a=>a.language==="typescript"?{language:a.language,scipPath:o}:a)}function Xa(e,t,n){for(let r of t){let i=qn(e,r.language);Pt(h(i),{recursive:!0}),r.scipPath!==i&&X(n,K(r.scipPath,i,void 0,{shareImmutable:!0}))}}async function Hm(e,t){let n=Wr();if(n){let r=Rf(n,e,t);r&&await r;return}if(as()==="win32")throw new Error("The scip CLI was not found. On Windows it ships via the npm sidecar package scip-query-scip-windows (installed automatically with scip-query). Reinstall scip-query with optional dependencies enabled, or follow 'scip-query setup' guidance for the exact sidecar package version, or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
350
350
|
To install the reviewed version, run: scip-query reindex --install-missing
|
|
351
|
-
Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!await
|
|
352
|
-
Install manually from: https://github.com/sourcegraph/scip/releases/tag/${
|
|
351
|
+
Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!await Ut(t))throw new Error(`The scip CLI is required but could not be installed.
|
|
352
|
+
Install manually from: https://github.com/sourcegraph/scip/releases/tag/${Xe}`)}function zm(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?le(e.tempOutputScip,o,a):e.tempOutputScip})),i=Object.fromEntries(r.map(({language:o,scipPath:a})=>[o,a]));for(let{language:o,scipPath:a}of r){let s=Jm({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?hs(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function Jm(e){if(e.language!=="typescript")return[vt({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.typescriptProjectMode==="workspace",n=t?e.preDiscoveredTypeScriptProjects??U(e.projectRoot,e.typescriptProjects):["."];return n.length===0?[vt({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(t&&e.onStatus(`Indexing TypeScript workspace as ${n.length} project shard(s).`),n.flatMap((r,i)=>{let o=t?`typescript:${r}`:"typescript",a=t?`typescript (${r})`:"typescript",s=t?le(e.tempOutputScip,"typescript-project",i):e.scipPath,c={...e,id:o,label:a,scipPath:s,outputScipPath:e.scipPath,pnpmWorkspaces:!1};if(!t&&r==="."&&!e.pnpmWorkspaces){let u=Ym(e,c);if(u)return u}return[vt({...c,...t?{projectPath:r}:{}})]}))}function Ym(e,t){if(e.trustProjectTools&&ze(ke("typescript"),e.projectRoot))return null;let n=un(),r=or(e.projectRoot,"single");if(!r||!ho(r.size,n))return null;bo(e.projectRoot);let i=So(),o=yo({projectRoot:e.projectRoot,rootConfigPath:"tsconfig.json",inputPaths:[...r],targetFiles:n,weightOf:s=>{let c=1;try{c=os(w(e.projectRoot,s)).size}catch{}return c}}),a=Math.min(i,o.length);return e.onStatus(`Indexing ${r.size} TypeScript inputs as ${o.length} byte-balanced compiler shard(s), ${a} at a time.`),go(o,a).map((s,c)=>{let u=vt({...t,id:`typescript-compiler-worker:${c}`,label:`typescript compiler worker ${c+1}/${a} (${s.length} emission batches)`,scipPath:le(e.tempOutputScip,"typescript-compiler-shard",c),projectPath:s[0].configPath,temporaryProjectConfigs:s.map(l=>({path:l.configPath,content:l.content})),boundedConcurrency:a,outputComposition:"protobuf-concatenate"});return"prepared"in u&&s.length>1&&(u.prepared.args=u.prepared.args.filter(l=>l!=="--no-global-caches"),u.prepared.args.push(...s.slice(1).map(l=>l.configPath))),u})}function $n(e,t){return e.onStatus(`Skipping ${e.language}: ${t}`),{skipped:{language:e.language,reason:t}}}function Km(e,t,n){return At(e)?null:n.skipAutoInstall?`${t} not found on PATH. To install the reviewed version, run: scip-query reindex --install-missing${e.installUrl?` (manual source: ${e.installUrl})`:""}`:(n.onStatus(`${t} not found. Attempting auto-install...`),Dn(e,n.onStatus)?null:`${t} could not be auto-installed. ${e.installUrl?`Install manually from ${e.installUrl}`:`Install ${t} and put it on PATH.`}`)}function Xm(e,t,n){return e.trustProjectTools&&n?Er(t,e.projectRoot):null}function Qm(e,t){let n=Ee(t),r=ze(t,e.projectRoot),i=Xm(e,t,r),o=ge(t);if(!i&&!o&&r){let s=`${n} is available only as repository-local code at ${r}. Review that exact tool and rerun with --trust-project-tools.`;return $n(e,s)}if(!i&&!o){let s=Km(t,n,e);if(s!==null)return $n(e,s)}let a=i?.canonicalPath??ge(t);if(!a){let s=`${n} was not found after installation checks.`;return $n(e,s)}return{resolvedBinary:a,trustedProjectTool:i}}function Zm(e,t){return{...t===void 0?{}:{temporaryRootConfigContent:t},...e.temporaryProjectConfigs===void 0?{}:{temporaryProjectConfigs:e.temporaryProjectConfigs},...e.boundedConcurrency===void 0?{}:{boundedConcurrency:e.boundedConcurrency},...e.outputComposition?{outputComposition:e.outputComposition}:{}}}function vt(e){let t=ke(e.language),n=Qm(e,t);if("skipped"in n)return n;let{resolvedBinary:r,trustedProjectTool:i}=n,{binary:o,args:a}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:r,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0}),s=Li({language:e.language,projectPath:e.projectPath,pnpmWorkspaces:e.pnpmWorkspaces});if(i&&!i.executable){let c=`${i.relativePath} is not executable; refusing project-local indexer.`;return e.onStatus(`Skipping ${e.language}: ${c}`),{skipped:{language:e.language,reason:c}}}return i&&e.onStatus(`Trusted project-local ${e.language} indexer ${i.relativePath} (${i.sha256.slice(0,12)}\u2026, ${i.canonicalPath}).`),{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:r,binary:o,args:a,env:Lt(t,e.env,r),...Zm(e,s),...i?{trustedProjectTool:i}:{}}}}function ef(e,t){let n=new Set(e.filter(o=>o.skipped&&o.outputComposition).map(o=>`${o.language}\0${o.outputScipPath}`)),r=new Map;for(let o of e)if(o.skipped)hs(t,o.skipped);else{let a=`${o.language}\0${o.outputScipPath}`;if(n.has(a))continue;let s=r.get(a)??{language:o.language,outputScipPath:o.outputScipPath,scipPaths:[],concatenate:!0};s.scipPaths.push(o.scipPath),o.outputComposition!=="protobuf-concatenate"&&(s.concatenate=!1),r.set(a,s)}return{indexedOutputs:gf(r)}}function hs(e,t){let n=e.find(r=>r.language===t.language);if(!n){e.push(t);return}n.reason.includes(t.reason)||(n.reason=`${n.reason}; ${t.reason}`)}function tf(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
|
|
353
353
|
`);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
|
|
354
354
|
`+o)}if(t.length!==0&&(i(`Indexed ${e.length} language output(s); skipped or incomplete: ${t.map(o=>o.language).join(", ")}.`),!r))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
|
|
355
355
|
`+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
|
|
356
|
-
`))}function ka(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=Ur(e.map(o=>o.scipPath),t);return Wa(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Ma(e[0].scipPath,t);return!1}async function zd(e){let t;if(Jd(e))try{let i=e.incrementalTypeScript.affectedBatches.length>0?e.incrementalTypeScript.affectedBatches:[{scipPath:e.incrementalTypeScript.affectedScipPath,affectedFiles:e.incrementalTypeScript.affectedFiles,deletedFiles:e.incrementalTypeScript.deletedFiles}],o=new Set,a=0,s=0;for(let[c,u]of i.entries()){let l=D(e.run.tempPaths.runDir,`typescript-affected-${c}.db`);Ga(u.scipPath,e.run.onStatus),e.run.onStatus(`Converting bounded TypeScript batch ${c+1}/${i.length} (${u.affectedFiles.length-u.deletedFiles.length} emitted, ${u.deletedFiles.length} removed) to SQLite...`);let d=performance.now();await _a(u.scipPath,l,e.env,e.run.onStatus,!0,e.run.opts.signal),a+=performance.now()-d,Ze(e.run.writeTelemetry,ue(l)??0);let m=Ti({previousDbPath:e.run.paths.outputDb,miniDbPath:l,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:u.affectedFiles,deletedFiles:u.deletedFiles,reuseCandidate:c>0,deferIntegrity:c<i.length-1,trustedPriorGeneration:!0,writeTelemetry:e.run.writeTelemetry});s+=m.durationMs;for(let f of m.changedDocumentPaths)o.add(f);se(l,{force:!0})}return e.run.onStatus(`Patched ${e.incrementalTypeScript.affectedFiles.length} SQLite document path(s) across ${i.length} bounded batch(es) in ${(s/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:[...o].sort(),patchDurationMs:s,converterDurationMs:a,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(i){if($(e.run.opts.signal,"Reindex cancelled by its owner."),t=i instanceof Error?i.message:String(i),se(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.opts.allowExpensiveRebuild===!1)throw new Error(`Bounded incremental SQLite publication failed and the whole-project fallback is disabled: ${t}`,{cause:i});e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}let n=e.completeScipSanitized;e.completeScipAvailable||(n=await e.materializeFullFallback());let r=performance.now();return await _a(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n,e.run.opts.signal),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function Jd(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!j(e.run.paths.outputDb)||!j(e.run.paths.outputScip))return!1;let t=new Set(e.reusedLanguages);return e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(n=>n==="typescript"||t.has(n))}function Yd(e,t){let n=F(),r=[...t].sort(),i=new Set(r),o={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(a=>!i.has(a)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:F()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:zt(e.plan,o,e.projectFileCount)}}async function _a(e,t,n,r,i=!1,o){if($(o,"Reindex cancelled by its owner."),r("Converting to SQLite..."),!j(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{if(i||Ga(e,r),n.SCIP_QUERY_SQLITE_CONVERTER==="scip-cli"){let a=_r();if(!a)throw new Error("scip CLI is not available");let s=await qe({command:a,args:["expt-convert","--output",t,e],label:"SCIP SQLite conversion",env:n,maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,timeoutMs:3e5,signal:o});if(s.status!==0)throw new Error(`scip expt-convert exited with ${s.status}${s.stderr.trim()?`: ${s.stderr.trim()}`:""}`)}else se(t,{force:!0}),await Qi(fe(e,{maxBytes:Ne,inputKind:"SCIP index"}),t,{signal:o})}catch(a){$(o,"Reindex cancelled by its owner.");let s=a instanceof Error?a.message:String(a);throw new Error(`Failed to convert SCIP index to SQLite: ${s}`,{cause:a})}}function Ga(e,t){let n=Vr(e);Wa(n,t)}function Wa(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function le(e,t,n){let r=hd(e)||".scip",i=gt(e,r);return D(v(e),`${i}.${n+1}.${t}${r}`)}async function Xd(e,t){for(let n=0;n<2;n++){let r=Kd(e,t);if(r)return r;let i=Qd(e);if(i&&za(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await Zd(i)}catch(s){throw new Error(`Could not verify the watcher's in-progress reindex owner (pid ${i.pid}); refusing to steal an active lock: ${ce(s)}`,{cause:s})}if(!o)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${v(e)}; refusing to steal an active lock.`);let a=kt(e,{parseLegacy:St});if(!Yn(e,a,{parseLegacy:St}))throw new Error(`Reindex lock ownership changed before preemption completed for ${v(e)}.`);continue}throw new ze(`Another scip-query reindex is already running for ${v(e)}.`)}throw new ze(`Could not acquire scip-query reindex lock for ${v(e)}.`)}function Kd(e,t){let n=J(process.pid),r=Jn(e,{kind:"reindex",processIdentity:n,detail:{projectRoot:t.projectRoot,...process.env.SCIP_REINDEX_PROCESS_GROUP_LEADER==="1"?{processGroupLeader:!0}:{},...t.trigger?{trigger:t.trigger}:{}},parseLegacy:St});if(r.kind==="acquired"&&r.reclaimed){let i=qa(r.reclaimed,e);i&&za(t.trigger,i)?t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}; its prior owner was already stale.`):t.onStatus(`Recovered an abandoned or incomplete reindex lock for ${v(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function Qd(e){return qa(kt(e,{parseLegacy:St}),e)}var St=e=>{let t=Ha(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function qa(e,t){if(e.state==="valid"&&e.record?.kind==="reindex"){let n=e.record.detail??{};return{version:2,pid:e.record.pid,...e.record.processIdentity?{processIdentity:e.record.processIdentity}:{},...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:v(t),startedAt:e.record.startedAt,trigger:n.trigger}}return Ha(e.parsed,t)}function Ha(e,t){try{let n=e;return typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=0?null:{version:n.version===2?2:1,pid:n.pid,...n.processIdentity===void 0?{}:(()=>{let r=qn(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:v(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function za(e,t){return e?.kind==="manual-cli"&&Ja(t?.trigger)}function Ja(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function Zd(e){return!ge(e.pid)||(Dn(e),Fa(e,"SIGTERM"),await Ca(e,2e3))?!0:(Dn(e),Fa(e,"SIGKILL"),Ca(e,1e3))}function Fa(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!ge(e.pid))return;Dn(e)}try{process.kill(e.pid,t)}catch{}}async function Ca(e,t){let n=F()+t;for(;F()<n;){if(Oa(e))return!0;await ep(50)}return Oa(e)}function Dn(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=J(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!we(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function Oa(e){if(!ge(e.pid))return!0;if(!e.processIdentity)return!1;let t=J(e.pid);return t!==null&&!we(e.processIdentity,t)}function ep(e){return new Promise(t=>setTimeout(t,e))}function jn(e,t,n){return Object.fromEntries(t.map(r=>{let i=r==="typescript"?tr(n.typescriptProjects):[],o=r==="clojure"?np(n.clojureConfigPath):void 0,a=[...nt(r).markerFiles,...i,...o?[o]:[]],s=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:i}:{typescriptProjectMode:"single",typescriptProjects:[]};return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&rp(n),...s,clojureConfigPath:o,files:e.files.filter(c=>Bn(c.path,r,a)).map(c=>Ya(c,r))}]}))}function Ya(e,t){let n=t==="typescript"&&/(?:^|\/)package\.json$/iu.test(e.path)?e.semanticHash:void 0;return{path:e.path,size:n===void 0?e.size:0,hash:n??e.hash}}function tp(e,t){let n=Et(t);if(!n)return t;let r=n.typescriptProjectMode==="workspace"?ne(e,n.typescriptProjects):["."],i=he(r);return{...n,files:n.files.filter(o=>!ye(o.path)||i.has(o.path)).map(o=>{let a=o.semanticHash??Be(e,o.path,o.hash);return Ya(a===void 0?o:{...o,semanticHash:a},"typescript")})}}function np(e){return e?.trim()||void 0}function rp(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Nn(e,t){return D(v(e),"language-indexes",`${t}.scip`)}function Xa(e){return D(v(e),"language-indexes","typescript-projects")}function Rt(e,t){return D(Xa(e),`${rn(t)}.scip`)}function de(e){try{return je(te(U(e,"reindex metadata")))}catch{return null}}function Ka(e,t){try{let n=te(U(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return null;let r=n.metadata;return!n.capabilities.publishableGeneration||!Wn(r)||L([...r.indexedLanguages??[]].sort())!==L(t.languages)?null:L(r.fingerprint)===L(t)?"exact":L(Da(r.fingerprint))===L(Da(t))?"operational-config-compatible":null}catch{return null}}function Da(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return Array.isArray(t.files)?{...t,files:t.files.filter(n=>typeof n!="object"||n===null||Array.isArray(n)||n.path!==".scipquery.json")}:e}function ip(e,t,n,r){let i=je(te(U(e,"reindex metadata")));i&&xt(e,{...i,fingerprint:t,...i.version===pe?{languageFingerprints:jn(t,n,r)}:{}})}function xt(e,t){Kn(e,t,{spacing:2,trailingNewline:!0})}function Qa(e,t){try{let n=je(te(U(e,"reindex metadata")));if(!n)return;xt(e,{...n,lastRefresh:t})}catch{}}function Pt(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:F()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function L(e){return JSON.stringify(e)}export{Ri as INDEXER_CONFIGS,si as augmentAuxiliaryDocuments,Yl as augmentVueResolvedReferences,Xl as augmentVueResolvedReferencesAsync,X as auxiliaryDocumentsAugmentationStage,ke as describeIndexerBinary,Ut as detectLanguages,nt as getIndexerConfig,Lt as getIndexerExecutionEnv,Dt as isBinaryAvailable,At as isIndexerInstalled,Gt as mergeScipFiles,ns as mergeScipIndexes,ph as reindex,be as resolveIndexerBinary,Mt as resolveProjectLocalIndexerBinary,G as runPostIndexAugmentation,Tn as tryInstallIndexer,Bt as tryInstallScipCli,ya as vueResolvedReferencesAugmentationStage};
|
|
356
|
+
`))}function Qa(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=ri(e.map(o=>o.scipPath),t);return bs(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&is(e[0].scipPath,t);return!1}async function nf(e){let t;if(rf(e))try{return await bf(e)}catch(i){if(M(e.run.opts.signal,"Reindex cancelled by its owner."),t=i instanceof Error?i.message:String(i),se(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.opts.allowExpensiveRebuild===!1)throw new Error(`Bounded incremental SQLite publication failed and the whole-project fallback is disabled: ${t}`,{cause:i});e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}let n=e.completeScipSanitized;e.completeScipAvailable||(n=await e.materializeFullFallback());let r=performance.now();return await ys(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n,e.run.opts.signal),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function rf(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!C(e.run.paths.outputDb)||!C(e.run.paths.outputScip))return!1;let t=new Set(e.reusedLanguages);return e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(n=>n==="typescript"||t.has(n))}function of(e,t){let n=x(),r=[...t].sort(),i=new Set(r),o={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(a=>!i.has(a)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:x()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:Jt(e.plan,o,e.projectFileCount)}}async function ys(e,t,n,r,i=!1,o){if(M(o,"Reindex cancelled by its owner."),r("Converting to SQLite..."),!C(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{if(i||Ss(e,r),n.SCIP_QUERY_SQLITE_CONVERTER==="scip-cli"){let a=qr();if(!a)throw new Error("scip CLI is not available");let s=await Ke({command:a,args:["expt-convert","--output",t,e],label:"SCIP SQLite conversion",env:n,maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,timeoutMs:3e5,signal:o});if(s.status!==0)throw new Error(`scip expt-convert exited with ${s.status}${s.stderr.trim()?`: ${s.stderr.trim()}`:""}`)}else se(t,{force:!0}),await mo(B(e,{maxBytes:Te,inputKind:"SCIP index"}),t,{signal:o})}catch(a){M(o,"Reindex cancelled by its owner.");let s=a instanceof Error?a.message:String(a);throw new Error(`Failed to convert SCIP index to SQLite: ${s}`,{cause:a})}}function Ss(e,t){let n=ti(e);bs(n,t)}function bs(e,t){e.recoveredDefinitionSymbols&&t(`Preserved definition occurrences and recovered ${e.recoveredDefinitionSymbols} missing symbol metadata record(s); kind and documentation remain unknown.`),e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function le(e,t,n){let r=Qp(e)||".scip",i=xt(e,r);return w(h(e),`${i}.${n+1}.${t}${r}`)}async function af(e,t){for(let n=0;n<2;n++){let r=sf(e,t);if(r)return r;let i=cf(e);if(i&&vs(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await uf(i)}catch(s){throw new Error(`Could not verify the watcher's in-progress reindex owner (pid ${i.pid}); refusing to steal an active lock: ${ce(s)}`,{cause:s})}if(!o)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${h(e)}; refusing to steal an active lock.`);let a=Dt(e,{parseLegacy:Tt});if(!Kn(e,a,{parseLegacy:Tt}))throw new Error(`Reindex lock ownership changed before preemption completed for ${h(e)}.`);continue}throw new Qe(`Another scip-query reindex is already running for ${h(e)}.`)}throw new Qe(`Could not acquire scip-query reindex lock for ${h(e)}.`)}function sf(e,t){let n=Y(process.pid),r=Yn(e,{kind:"reindex",processIdentity:n,detail:{projectRoot:t.projectRoot,...process.env.SCIP_REINDEX_PROCESS_GROUP_LEADER==="1"?{processGroupLeader:!0}:{},...t.trigger?{trigger:t.trigger}:{}},parseLegacy:Tt});if(r.kind==="acquired"&&r.reclaimed){let i=Rs(r.reclaimed,e);i&&vs(t.trigger,i)?t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}; its prior owner was already stale.`):t.onStatus(`Recovered an abandoned or incomplete reindex lock for ${h(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function cf(e){return Rs(Dt(e,{parseLegacy:Tt}),e)}var Tt=e=>{let t=xs(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function Rs(e,t){if(e.state==="valid"&&e.record?.kind==="reindex"){let n=e.record.detail??{};return{version:2,pid:e.record.pid,...e.record.processIdentity?{processIdentity:e.record.processIdentity}:{},...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:h(t),startedAt:e.record.startedAt,trigger:n.trigger}}return xs(e.parsed,t)}function xs(e,t){try{let n=e;return typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=0?null:{version:n.version===2?2:1,pid:n.pid,...n.processIdentity===void 0?{}:(()=>{let r=zn(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:h(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function vs(e,t){return e?.kind==="manual-cli"&&Ps(t?.trigger)}function Ps(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function uf(e){return!me(e.pid)||(Vn(e),Za(e,"SIGTERM"),await es(e,2e3))?!0:(Vn(e),Za(e,"SIGKILL"),es(e,1e3))}function Za(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!me(e.pid))return;Vn(e)}try{process.kill(e.pid,t)}catch{}}async function es(e,t){let n=x()+t;for(;x()<n;){if(ts(e))return!0;await lf(50)}return ts(e)}function Vn(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=Y(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!Pe(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function ts(e){if(!me(e.pid))return!0;if(!e.processIdentity)return!1;let t=Y(e.pid);return t!==null&&!Pe(e.processIdentity,t)}function lf(e){return new Promise(t=>setTimeout(t,e))}function Gn(e,t,n){return Object.fromEntries(t.map(r=>{let i=r==="typescript"?sr(n.typescriptProjects):[],o=r==="clojure"?pf(n.clojureConfigPath):void 0,a=[...ke(r).markerFiles,...i,...o?[o]:[]],s=r==="typescript"?{typescriptSymbolIdentityVersion:6,typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:i}:{typescriptProjectMode:"single",typescriptProjects:[]};return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&mf(n),...s,clojureConfigPath:o,files:e.files.filter(c=>Wn(c.path,r,a)).map(c=>Ts(c,r))}]}))}function Ts(e,t){let n=t==="typescript"&&/(?:^|\/)package\.json$/iu.test(e.path)?e.semanticHash:void 0;return{path:e.path,size:n===void 0?e.size:0,hash:n??e.hash}}function df(e,t){let n=re(t);if(!n)return t;let r=n.typescriptProjectMode==="workspace"?U(e,n.typescriptProjects):["."],i=Ie(r);return{...n,files:n.files.filter(o=>!Ve(o.path)||i.has(o.path)).map(o=>{let a=o.semanticHash??Be(e,o.path,o.hash);return Ts(a===void 0?o:{...o,semanticHash:a},"typescript")})}}function pf(e){return e?.trim()||void 0}function mf(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function qn(e,t){return w(h(e),"language-indexes",`${t}.scip`)}function Is(e){return w(h(e),"language-indexes","typescript-projects")}function Et(e,t){return w(Is(e),`${on(t)}.scip`)}function ne(e){try{return pe(V(J(e,"reindex metadata")))}catch{return null}}function Es(e,t){try{let n=V(J(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return null;let r=n.metadata;return!n.capabilities.publishableGeneration||!Hn(r)||F([...r.indexedLanguages??[]].sort())!==F(t.languages)?null:F(r.fingerprint)===F(t)?"exact":F(ns(r.fingerprint))===F(ns(t))?"operational-config-compatible":null}catch{return null}}function ns(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return Array.isArray(t.files)?{...t,files:t.files.filter(n=>typeof n!="object"||n===null||Array.isArray(n)||n.path!==".scipquery.json")}:e}function ff(e,t,n,r){let i=pe(V(J(e,"reindex metadata")));i&&Ae(e,{...i,fingerprint:t,...i.version===de?{languageFingerprints:Gn(t,n,r)}:{}})}function Ae(e,t){Zn(e,t,{spacing:2,trailingNewline:!0})}function ws(e,t){try{let n=pe(V(J(e,"reindex metadata")));if(!n)return;Ae(e,{...n,lastRefresh:t})}catch{}}function wt(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:x()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function F(e){return JSON.stringify(e)}function gf(e){let t=[];for(let n of e.values())if(n.scipPaths.length>1)n.concatenate?ni(n.scipPaths,n.outputScipPath):qt(n.scipPaths,n.outputScipPath),t.push({language:n.language,scipPath:n.outputScipPath});else{let r=n.scipPaths[0];r!==n.outputScipPath&&is(r,n.outputScipPath),t.push({language:n.language,scipPath:n.outputScipPath})}return t}function hf(e,t){e.added.length>0&&t.onStatus(`Added SQLite query indexes: ${e.added.join(", ")}`),e.removed.length>0&&t.onStatus(`Removed redundant SQLite indexes: ${e.removed.join(", ")}`)}function yf(e,t){e.achievedDurability==="file-flushed"&&t.onStatus(`Published local generation ${e.currentGeneration.slice(0,12)} (file-flushed; directory sync unsupported)`)}function Sf(e){return e.mode==="incremental"&&e.scipCompanion==="deferred"}async function bf(e){if(e.incrementalTypeScript.affectedBatches.length===0&&e.incrementalTypeScript.retainedDocumentCount===e.incrementalTypeScript.affectedFiles.length&&e.incrementalTypeScript.retainedDocumentCount>0){let o=performance.now();return X(e.run.writeTelemetry,K(e.run.paths.outputDb,e.run.tempPaths.tempOutputDb)),e.run.onStatus(`Retained all ${e.incrementalTypeScript.retainedDocumentCount} verified TypeScript documents; SQLite conversion is unnecessary.`),{mode:"incremental",changedDocumentPaths:[],compilerFactsUnchanged:!0,patchDurationMs:performance.now()-o,converterDurationMs:0,scipCompanion:"deferred"}}let t=e.incrementalTypeScript.affectedBatches.length>0?e.incrementalTypeScript.affectedBatches:[{scipPath:e.incrementalTypeScript.affectedScipPath,affectedFiles:e.incrementalTypeScript.affectedFiles,deletedFiles:e.incrementalTypeScript.deletedFiles}],n=new Set,r=0,i=0;for(let[o,a]of t.entries()){let s=w(e.run.tempPaths.runDir,`typescript-affected-${o}.db`);Ss(a.scipPath,e.run.onStatus),e.run.onStatus(`Converting bounded TypeScript batch ${o+1}/${t.length} (${a.affectedFiles.length-a.deletedFiles.length} emitted, ${a.deletedFiles.length} removed) to SQLite...`);let c=performance.now();await ys(a.scipPath,s,e.env,e.run.onStatus,!0,e.run.opts.signal),r+=performance.now()-c,it(e.run.writeTelemetry,ue(s)??0);let u=Bi({previousDbPath:e.run.paths.outputDb,miniDbPath:s,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:a.affectedFiles,deletedFiles:a.deletedFiles,reuseCandidate:o>0,deferIntegrity:o<t.length-1,trustedPriorGeneration:!0,writeTelemetry:e.run.writeTelemetry});i+=u.durationMs;for(let l of u.changedDocumentPaths)n.add(l);se(s,{force:!0})}return e.run.onStatus(`Patched ${t.reduce((o,a)=>o+a.affectedFiles.length,0)} SQLite document path(s) across ${t.length} bounded batch(es) in ${(i/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:[...n].sort(),patchDurationMs:i,converterDurationMs:r,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}function Rf(e,t,n){if(e.source==="path"&&as()!=="win32"){let r=zr();if(!Hr(r))if(t)n(`scip on PATH reports ${r??"an unknown version"}; the reviewed version is ${Xe} and compatibility is unverified. Run scip-query setup --install-missing to install the reviewed release.`);else return n(`scip on PATH reports ${r??"an unknown version"}; installing the reviewed ${Xe}.`),Jr(n)}}function xf(e,t,n){let r=_t(e),i=t&&r?fr(e,"file-dependency-graph",t,r):0,o=i>0;return n.onStatus(o?`Carried ${i} unchanged dependency graph product(s) forward without rebuilding them.`:"No persisted dependency graph product required rekeying; the next graph consumer can materialize it."),o}export{Ai as INDEXER_CONFIGS,Pi as augmentAuxiliaryDocuments,Cp as augmentVueResolvedReferences,Dp as augmentVueResolvedReferencesAsync,Q as auxiliaryDocumentsAugmentationStage,Ee as describeIndexerBinary,Gt as detectLanguages,ke as getIndexerConfig,Lt as getIndexerExecutionEnv,Mt as isBinaryAvailable,At as isIndexerInstalled,qt as mergeScipFiles,Cs as mergeScipIndexes,ab as reindex,ge as resolveIndexerBinary,ze as resolveProjectLocalIndexerBinary,q as runPostIndexAugmentation,Dn as tryInstallIndexer,Ut as tryInstallScipCli,Ga as vueResolvedReferencesAugmentationStage};
|
|
357
357
|
//# sourceMappingURL=reindex.js.map
|