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
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{$f as Di,Ae as Ne,Af as gi,B as Xe,Bf as hi,Ce as ri,Cf as yi,Da as Le,Ee as je,Ef as Si,Fa as tn,Fe as st,Ff as bi,Ge as ii,Gf as Ri,Ha as ye,Hf as xi,Ia as q,If as vi,Ja as Se,Jf as un,Ka as nt,Kf as ut,L as vr,La as nn,Lf as Pe,M as W,Ma as _r,Mf as Pi,N as Oe,Nf as Ti,O as Qe,Od as Hr,Oe as oi,Of as ln,P as Pr,Pf as Be,Q as Tr,Qe as ai,Qf as Te,R as Ir,Re as si,Rf as ue,Se as an,Sf as lt,Ta as Mr,Tf as Ii,U as Ze,Uf as wi,V as wr,Ve as ve,Vf as Ei,W as Zt,Wa as rn,Wf as ki,Xf as Ci,Ya as Nr,Yf as dt,_f as Fi,a as Ye,ac as $r,ag as Ai,b as Rr,bb as rt,bc as Vr,bg as Oi,c as oe,ce as be,de as Jr,df as ci,dg as Li,e as ae,ee as Yr,eg as _i,f as F,fe as Re,fg as pt,ge as at,ha as Er,he as _e,hg as z,ib as se,ie as Kr,if as ui,ig as ft,ja as et,jb as ce,je as on,jf as M,k as Kt,ka as kr,kb as jr,ke as Xr,kg as Mi,le as Qr,m as K,ma as Cr,me as Zr,mf as ct,mg as dn,n as Xt,na as Fr,nf as sn,ng as Ni,o as Ae,oc as Ur,oe as xe,of as li,og as ji,p as Ke,pc as it,pe as ei,pg as mt,q as Qt,qb as g,qc as ot,qe as Me,qf as di,r as j,ra as Dr,rb as B,rc as Gr,re as X,rf as pi,s as _,sa as tt,sb as Br,sc as Wr,se as R,sf as fi,sg as Bi,t as U,ta as Ar,tc as qr,tf as mi,tg as $i,u as xr,ua as Or,uf as cn,ug as Vi,vf as N,wg as Ui,xa as Lr,xg as Gi,yc as zr,ye as ti,yg as gt,za as en,ze as ni}from"./chunk-OZCJXZK6.js";import Wi from"better-sqlite3";import{createHash as qi}from"crypto";import{dirname as ht,join as Tc}from"path";function zi(e){if(!e.request.modifiedFiles.length||e.request.removedFiles.length)return null;let t;try{t=fi({projectRoot:e.projectRoot,dbPath:e.dbPath,indexPath:Tc(ht(e.dbPath),"index.scip")});let n=Ic(e,t.generation);if(!n||!Ec(e,n.snapshot))return null;let r=kc(t.generation.databasePath,n.snapshot,e.request.modifiedFiles);if(!r)return null;let i=new Pe,o=new Set(n.snapshot.files.map(s=>s.path)),a=ht(e.dbPath);for(let s of n.overlay.overlays)s.blobHash===null||!o.has(s.relativePath)||i.setReference({...s,blobHash:s.blobHash},()=>ki(a,s));return{sources:r,documents:i}}catch{return null}finally{t?.release()}}function Ic(e,t){let n=mi(e.dbPath);if(t.source!=="immutable"||n?.currentGeneration!==t.identity)return null;let r=q(t.metadataRaw),i=nt(r);if(!i||Hi(i)!==e.baseGeneration)return null;let o=oe(Se(r)?.fingerprint);if(!o||!wc(e,o))return null;let a=n.publication?.typescriptOverlayGeneration??Be(o,e.request.producerIdentity),s=dt(ht(e.dbPath),a);return s?.producerIdentity!==e.request.producerIdentity||s.projectIdentity!==e.request.projectIdentity?null:{snapshot:o,overlay:s}}function wc(e,t){if(t.typescriptProjectMode!=="single"&&t.typescriptProjectMode!=="workspace")return!1;let n=t.typescriptProjectMode==="workspace"?W(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 Ec(e,t){let n=et(e.projectRoot,ht(e.dbPath),()=>tt(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)||Ye(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 kc(e,t,n){let r=new Map(t.files.map(o=>[o.path,o])),i=new Wi(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||Hi(c.text)!==u.hash)return null;o.set(s,c.text)}return o}finally{i.close()}}function Hi(e){return qi("sha256").update(e).digest("hex")}function pn(e){let t=oe(e.fingerprint);if(!t)return 0;let n=new Map(t.files.map(i=>[i.path,i])),r=new Wi(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||qi("sha256").update(l).digest("hex")!==u.hash||(s+=a.run(d,c,d).changes)}return s})()}finally{r.close()}}import{createHash as Hg}from"crypto";import{existsSync as A,mkdirSync as qt,mkdtempSync as Jg,readdirSync as Ks,renameSync as Xs,rmSync as fe,statSync as Qs}from"fs";import{basename as Gt,dirname as h,extname as Yg,join as k,resolve as Vs}from"path";import{platform as Zs}from"os";import{execFileSync as bt}from"child_process";import{createRequire as Qc}from"module";import{chmodSync as Zc,existsSync as to}from"fs";import{platform as Q,arch as Rt}from"os";import{dirname as eu,join as no}from"path";import{createHash as Yi,randomUUID as Cc}from"crypto";import{closeSync as yt,createReadStream as Fc,existsSync as Dc,fsyncSync as Ac,mkdirSync as Oc,openSync as mn,renameSync as Lc,unlinkSync as _c,writeSync as Mc}from"fs";import{homedir as Nc}from"os";import{dirname as Ki,join as fn}from"path";var jc=3e5,Bc=256*1024*1024;function Xi(e,t=process.env){let n=t.SCIP_QUERY_CACHE_DIR??(t.XDG_CACHE_HOME?fn(t.XDG_CACHE_HOME,"scip-query"):fn(Nc(),".cache","scip-query"));return fn(n,e)}var I=class extends Error{constructor(n,r,i={}){super(r,i.cause===void 0?void 0:{cause:i.cause});this.kind=n;this.name="VerifiedBinaryFetchError"}kind};async function Qi(e){let{cachePath:t,url:n,expectedSha256:r}=e,i=e.timeoutMs??jc,o=e.maxBytes??Bc,a=e.lockWaitMs??i;$c(i,o,a);let s=Vc(n,i,e.signal);try{let c=await Ji(t,r,o,s.controller.signal);if(c)return{status:"cached",path:t,sha256:c};Oc(Ki(t),{recursive:!0});let u=await pi(`${t}.fetch.lock`,{waitMs:a,pollMs:25,signal:s.controller.signal});if(!u)throw new I("lock-timeout",`timed out waiting ${a}ms for verified binary cache ownership at ${t}`);try{let l=await Ji(t,r,o,s.controller.signal);return l?{status:"cached",path:t,sha256:l}:await Uc(e,s.controller,o)}finally{u.release()}}catch(c){return Xc(c,s.controller.signal,n)}finally{clearTimeout(s.timeout),s.detachExternalAbort(),s.controller.signal.aborted||s.controller.abort()}}function $c(e,t,n){if(!Number.isFinite(e)||e<=0)throw new TypeError("timeoutMs must be a positive finite number.");if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("maxBytes must be a positive safe integer.");if(!Number.isFinite(n)||n<0)throw new TypeError("lockWaitMs must be a non-negative finite number.")}function Vc(e,t,n){let r=new AbortController,i=()=>{r.abort(new I("aborted",`download of ${e} was aborted`,{cause:n?.reason}))};n?.addEventListener("abort",i,{once:!0}),n?.aborted&&i();let o=setTimeout(()=>{r.abort(new I("timeout",`download of ${e} timed out after ${t}ms`))},t);return o.unref(),{controller:r,timeout:o,detachExternalAbort:()=>n?.removeEventListener("abort",i)}}async function Ji(e,t,n,r){if(!Dc(e))return null;let i=Yi("sha256"),o=0;try{for await(let s of Fc(e,{signal:r})){let c=Buffer.isBuffer(s)?s:Buffer.from(s);if(o+=c.length,o>n)return null;i.update(c)}}catch{if(r.aborted)throw Ie(r,e);return null}let a=i.digest("hex");return a===t?a:null}async function Uc(e,t,n){let r=await Gc(e,t),i=Hc(r,n,e.url);if(!r.body)throw new I("stream",`downloaded ${e.url} response has no readable body`);let o=`${e.cachePath}.tmp-${process.pid}-${Cc()}`,a,s=!1;try{a=mn(o,"wx",384),s=!0;let c=await qc(r.body,a,e,t,n,i);yt(a),a=void 0;try{Jc(o,e.cachePath,e.renameImpl??Lc,e.syncImpl??Ac)}catch(u){throw new I("install",`failed to install verified binary at ${e.cachePath}`,{cause:u})}return s=!1,{status:"downloaded",path:e.cachePath,sha256:c}}catch(c){throw t.signal.aborted?Ie(t.signal,e.url):c instanceof I?c:new I("install",`failed to stage verified binary at ${e.cachePath}`,{cause:c})}finally{zc(a,o,s)}}async function Gc(e,t){let n=e.fetchImpl??fetch,r;try{r=await Zi(n(e.url,{signal:t.signal}),t.signal)}catch(i){throw t.signal.aborted?Ie(t.signal,e.url):new I("stream",`failed to download ${e.url}: ${eo(i)}`,{cause:i})}if(!r.ok){let i=new I("http",`failed to download ${e.url}: HTTP ${r.status}`);throw t.abort(i),i}return r}function Wc(e,t,n,r,i){if(e>n||t!==void 0&&e>t){let o=new I("length",`downloaded ${r} exceeded its ${t??n} byte limit`);throw i.abort(o),o}}async function qc(e,t,n,r,i,o){let a=e.getReader(),s=Yi("sha256"),c=0;for(;;){let{done:l,value:d}=await Zi(a.read(),r.signal);if(l)break;if(!(d instanceof Uint8Array))throw new I("stream",`downloaded ${n.url} produced a non-byte stream chunk`);c+=d.byteLength,Wc(c,o,i,n.url,r);let p=Buffer.from(d.buffer,d.byteOffset,d.byteLength);s.update(p),wr(t,p,{writeFile:n.writeImpl??Mc},"verified binary staging")}if(o!==void 0&&c!==o)throw new I("length",`downloaded ${n.url} length mismatch: declared ${o} bytes, received ${c}`);let u=s.digest("hex");if(u!==n.expectedSha256)throw new I("checksum",`downloaded ${n.url} checksum mismatch: expected ${n.expectedSha256}, got ${u}`);return u}function zc(e,t,n){if(e!==void 0)try{yt(e)}catch{}if(n)try{_c(t)}catch{}}function Hc(e,t,n){let r=e.headers?.get("content-length");if(r==null)return;if(!/^\d+$/.test(r))throw new I("length",`downloaded ${n} has an invalid Content-Length header`);let i=Number(r);if(!Number.isSafeInteger(i)||i<0)throw new I("length",`downloaded ${n} has an invalid Content-Length header`);if(i>t)throw new I("length",`downloaded ${n} declares ${i} bytes, above the ${t} byte limit`);return i}function Jc(e,t,n,r){Yc(e,r),n(e,t),Kc(Ki(t),r)}function Yc(e,t){let n=mn(e,"r");try{t(n)}finally{yt(n)}}function Kc(e,t){let n;try{n=mn(e,"r")}catch(r){if(Zt(r,process.platform))return;throw r}try{t(n)}catch(r){if(!Zt(r,process.platform))throw r}finally{yt(n)}}function Zi(e,t){return t.aborted?Promise.reject(Ie(t,"operation")):new Promise((n,r)=>{let i=()=>{t.removeEventListener("abort",i),r(Ie(t,"operation"))};t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),n(o)},o=>{t.removeEventListener("abort",i),r(o)})})}function Ie(e,t){return e.reason instanceof Error?e.reason:new I("aborted",`verified binary operation for ${t} was aborted`)}function eo(e){return e instanceof Error?e.message:String(e)}function Xc(e,t,n){throw t.aborted?Ie(t,n):e instanceof I?e:new I("stream",`failed to download ${n}: ${eo(e)}`,{cause:e})}var C="v0.8.1",gn="https://github.com/sourcegraph/scip",St=`github.com/sourcegraph/scip/cmd/scip@${C}`,ro=Qc(import.meta.url),tu={"scip-darwin-amd64.tar.gz":"39f18be957d350bcd9ed5cb12d7781b0e237a5cb2429a107feaf9ce2d1dcd5d5","scip-darwin-arm64.tar.gz":"5b3f4a2fb1dc10c599cb3422ed0406a739060e4ac0b1222c0f43630dd0dd8221","scip-linux-amd64.tar.gz":"16b79ed98f893abd530cfa63f333527f1351008b4a23e02b9e522e34d1da6596","scip-linux-arm64.tar.gz":"876dfb680119dd6e5713077c49b27701102d598bdeba94c809173276d399c7e2"},io="SCIP_QUERY_SCIP_BIN";function oo(e=process.env){return e.SCIP_QUERY_SQLITE_CONVERTER==="scip-cli"}function nu(e){let t=e.env[io];if(t&&e.fileExists(t))return{source:"env",path:t};let n=e.resolveCached?.()??null;if(n)return{source:"cache",path:n};if(e.isOnPath("scip"))return{source:"path",path:"scip"};if(e.platform==="win32"){let r=e.resolveSidecar(e.arch);if(r&&e.fileExists(r))return{source:"sidecar",path:r}}return null}function ru(e){for(let t of e==="arm64"?["arm64","x64"]:[e])try{return ro.resolve(`scip-query-scip-windows/scip-win32-${t}.exe`)}catch{}return null}function $e(e=process.env){return hn(e)?.path??null}function hn(e=process.env){let t=nu({platform:Q(),arch:Rt(),env:e,isOnPath:be,fileExists:to,resolveSidecar:ru,resolveCached:()=>iu(e)});return t?.source==="path"?{source:"path",path:Yr("scip")??t.path}:t}function ao(e=process.env){return Xi(no("scip",C,"scip"),e)}function iu(e){let t=ao(e);return to(t)?t:null}function yn(e){return e!==null&&e.includes(C.replace(/^v/,""))}function qy(){return $e()!==null}function Sn(){let e=$e();if(!e)return null;try{return bt(e,["--version"],{stdio:"pipe",timeout:1e4,killSignal:"SIGKILL"}).toString().trim()}catch{return null}}function ou(e=Q(),t=Rt()){let n=so(e,t);if(!n)return null;let r=tu[n.filename];return r?{...n,sha256:r}:null}function so(e=Q(),t=Rt()){let n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";break;default:return null}switch(t){case"arm64":r="arm64";break;case"x64":r="amd64";break;default:return null}let o=`scip-${n}-${r}.${i}`;return{url:`${gn}/releases/download/${C}/${o}`,filename:o}}function zy(){let e=so();if(console.log("\nThe `scip` CLI is required but not found on PATH.\n"),Q()==="darwin"||Q()==="linux")console.log(`Let scip-query install the reviewed release (${C}, digest-verified) into its cache:`),console.log(` scip-query setup --install-missing
|
|
3
|
+
`),console.log("Or install it with Go:"),console.log(` go install ${St}
|
|
4
|
+
`),console.log("Or download that exact release manually:");else if(Q()==="win32"){let t=au();console.log("On Windows the scip binary ships via the npm sidecar package scip-query-scip-windows,"),console.log("installed automatically with scip-query. If it is missing:"),console.log(` npm install -g ${t}`),console.log(`Or set ${io} to a local scip.exe path.
|
|
5
|
+
`),console.log("Upstream release page:")}else console.log("Download from:");console.log(e?` ${e.url}
|
|
6
|
+
`:` ${gn}/releases/tag/${C}
|
|
7
|
+
`),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function au(){let t=ro("../../package.json").optionalDependencies?.["scip-query-scip-windows"];if(!t||!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(t))throw new Error("scip-query package metadata does not declare an exact Windows sidecar version.");return`scip-query-scip-windows@${t}`}var su={fetch:Qi,extract:(e,t)=>{bt("tar",["-xzf",e,"-C",t,"scip"],{stdio:"pipe",timeout:12e4,killSignal:"SIGKILL"})},markExecutable:e=>Zc(e,493),probeVersion:e=>cu(e),env:process.env};async function bn(e,t={}){let n={...su,...t},r=ou();if(!r)return e(`No reviewed scip ${C} release archive is published for ${Q()}/${Rt()}.`),null;let i=ao(n.env),o=eu(i),a=no(o,r.filename);e(`Downloading reviewed scip ${C} (${r.filename}, sha256 ${r.sha256.slice(0,12)}\u2026).`);try{let c=await n.fetch({cachePath:a,url:r.url,expectedSha256:r.sha256});n.extract(c.path,o),n.markExecutable(i)}catch(c){return e(`Could not install scip ${C}: ${c instanceof Error?c.message:String(c)}`),null}let s=n.probeVersion(i);return yn(s)?(e(`Installed reviewed scip ${C} at ${i}.`),i):(e(`Installed scip at ${i} did not report ${C} (reported: ${s??"unavailable"}).`),null)}function cu(e){try{return bt(e,["--version"],{stdio:"pipe",timeout:1e4,killSignal:"SIGKILL"}).toString().trim()}catch{return null}}async function co(e,t={}){if(Q()!=="win32"&&await bn(e,t)!==null)return!0;if(be("go")){e(`Installing immutable ${St} via go install into the Go bin directory (GOBIN or GOPATH/bin); expected executable: scip.`);try{if(bt("go",["install",St],{stdio:"inherit",timeout:3e5,env:process.env}),uu(e))return!0}catch(n){let r=n instanceof Error?n.message:String(n);e(`go install failed: ${r}`)}}return e("Could not auto-install scip CLI."),e(`Install manually from: ${gn}/releases/tag/${C}`),!1}function uu(e){if(be("scip")){let t=$e(),n=Sn();if(t&&n&&n.includes(C))return e(`Successfully installed ${St}; resolved executable: ${t}; reported version: ${n}.`),!0;e(`go install completed, but the resolved scip executable did not report ${C} (executable: ${t??"unresolved"}; version: ${n??"unavailable"}).`)}return!1}var we=class extends Error{constructor(t){super(t),this.name="ReindexLockUnavailableError"}};import{execFileSync as lu}from"child_process";import{constants as du,copyFileSync as uo,linkSync as pu,rmSync as fu,statSync as mu}from"fs";import{platform as gu}from"os";var hu=Object.freeze({size:e=>mu(e).size,clone:Ru,copy:(e,t)=>uo(e,t),link:(e,t)=>pu(e,t),remove:e=>fu(e,{force:!0})}),yu=new Set(["EXDEV","EPERM","EMLINK","ENOTSUP","EOPNOTSUPP","ENOSYS","EINVAL"]),Su=new Set(["ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL","EXDEV","ENOTTY"]);function Z(e,t,n=hu,r={}){let i=n.size(e);n.remove?.(t);try{return n.clone(e,t),{method:"reflink",bytes:i}}catch(o){if(!vu(o))throw o}if(r.shareImmutable&&n.link)try{return n.link(e,t),{method:"link",bytes:i}}catch(o){if(!bu(o))throw o}return n.copy(e,t),{method:"copy",bytes:i}}function bu(e){let t=e?.code;return typeof t=="string"&&yu.has(t)}function Ru(e,t){if(gu()!=="darwin"){uo(e,t,du.COPYFILE_FICLONE_FORCE);return}try{lu("/bin/cp",["-c",e,t],{timeout:6e4,maxBuffer:64*1024,stdio:["ignore","ignore","pipe"]})}catch(n){throw xu(n)}}function xu(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 vu(e){let t=e?.code;return t!==void 0&&Su.has(t)}function lo(){return{reflinkedBytes:0,fallbackCopiedBytes:0,incrementalWrittenBytes:0}}function ee(e,t){t.method==="reflink"||t.method==="link"?e.reflinkedBytes+=t.bytes:e.fallbackCopiedBytes+=t.bytes}function xt(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 Pu from"better-sqlite3";import{execFileSync as Tu}from"child_process";import{existsSync as Iu,readdirSync as wu}from"fs";import{extname as vt,join as Eu}from"path";function le(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>po({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function po(e){let t=new Set((e.extensions??$r).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Iu(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=vi(e.projectRoot),r=ku(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Pu(e.dbPath);try{let o=Fu(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
|
|
8
|
+
VALUES (?, ?, NULL, ?)`),c=i.transaction(l=>{let d=0;for(let p of l){if(o.has(p))continue;let f=Fr(e.projectRoot,p,{inputKind:"auxiliary source file"}),m=a.run(Du(p),p,f);d+=Number(m.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 ku(e,t){let n=Cu(e,t);if(n)return n;let r=[],i=o=>{let a=o?Eu(e,o):e,s;try{s=wu(a,{withFileTypes:!0})}catch{return}for(let c of s){if(Vr.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(vt(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function Cu(e,t){try{return Tu("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(vt(r).toLowerCase())).sort()}catch{return null}}function Fu(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 Du(e){return vt(e).toLowerCase()===".vue"?"vue":vt(e).replace(/^\./,"").toLowerCase()||"source"}import{dirname as Au,join as Ou}from"path";function fo(e={}){return{id:"runtime-boundaries",facts:["runtime-boundary-observation","runtime-boundary-link"],run:async({projectRoot:t,dbPath:n,onStatus:r})=>{let i=new N({projectRoot:t,dbPath:n,indexPath:e.indexPath??Ou(Au(n),"index.scip"),...e.evidenceDbPath?{evidenceDbPath:e.evidenceDbPath}:{}}),o,a=!1,s=!1;try{let u=e.reuseExisting||e.affectedFiles?Si(i):null;e.reuseExisting&&u?.extractorVersion===gi?(o=u,a=!0):(o=await _u(i,u,e),s=(o.coverage.filesReused??0)>0)}finally{i.close()}a||yi(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 Lu(c,o,r),c}}}function Lu(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 _u(e,t,n){return hi(e,{...t?{previousGraph:t}:{},...n.affectedFiles?{affectedFiles:n.affectedFiles}:{},...n.forceDerivedRebuild?{forceDerivedRebuild:!0}:{},...n.compilerFactsUnchanged?{compilerFactsUnchanged:!0}:{},profileSpan:g})}var Mu={config:"configuration-changed",ambient:"ambient-declaration-changed",other:"unclassified-input"};function de(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=Mu[r.inputKind];i&&n.add(i)}return{fullProject:n.size>0,reasons:[...n].sort()}}function Tt(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=de(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"),Pt(r,i,a)):a.size>0?Pt(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:Nu(r,t,i),reasons:[]}}function Pt(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function Nu(e,t,n){let r=ju(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 ju(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 Zu}from"crypto";import{existsSync as el}from"fs";import{dirname as tl,join as So}from"path";import{appendFileSync as Bu,existsSync as $u,mkdirSync as Vu,renameSync as Uu,rmSync as Gu,statSync as Wu,truncateSync as qu}from"fs";import{basename as zu,dirname as Hu}from"path";var Ee=".previous",Ju=".rotation.lock",Yu=2e3,Rn=class extends Error{constructor(n,r){super(`Timed out after ${r}ms waiting for rotating JSONL lock: ${n}`);this.lockPath=n;this.timeoutMs=r;this.name="RotatingJsonlLockTimeoutError"}lockPath;timeoutMs;code="ROTATING_JSONL_LOCK_TIMEOUT"},xn=class extends Error{constructor(n){super(`Rotating JSONL lock ownership changed before release: ${n}`);this.lockPath=n;this.name="RotatingJsonlLockReleaseError"}lockPath;code="ROTATING_JSONL_LOCK_RELEASE_FAILED"},mo=Object.freeze({monotonicNow:R,wait(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},tryAcquireLock(e,t){let n=ct(e,{kind:"rotating-jsonl",detail:{target:zu(t)}});return n.kind==="acquired"?{kind:"acquired",lock:n.lock}:{kind:"contended"}},makeDirectory(e){Vu(e,{recursive:!0})},exists:$u,readBytes(e){return j(e,{maxBytes:Ke,inputKind:"rotating JSONL segment"})},size(e){return Wu(e).size},truncate:qu,remove(e){Gu(e,{force:!0})},rename:Uu,append:Bu});function It(e,t,n){let r=n.runtime??mo,i=JSON.stringify(t);if(i===void 0)throw new TypeError("Rotating JSONL records must be JSON-serializable values.");let o=Buffer.from(`${i}
|
|
9
|
+
`),a=Math.max(1,Math.floor(n.maxSegmentBytes),o.length);return ho(e,n.lockTimeoutMs,r,()=>{r.makeDirectory(Hu(e));let s=Ku(e,Ke,r);n.onPhase?.("tail-repaired");let c=`${e}${n.previousSuffix??Ee}`,u=!1,l=!1;return r.exists(e)&&r.size(e)+o.length>a&&(r.exists(c)&&(r.remove(c),l=!0),n.onPhase?.("previous-pruned"),r.rename(e,c),u=!0,n.onPhase?.("current-rotated")),r.append(e,o),n.onPhase?.("record-appended"),{lineBytes:o.length,segmentLimitBytes:a,repairedTailBytes:s,rotated:u,prunedPrevious:l}})}function go(e,t={}){let n=t.runtime??mo,r=Xu(t.maxSegmentBytes);return ho(e,t.lockTimeoutMs,n,()=>{let i=[],o=0,a=`${e}${t.previousSuffix??Ee}`;for(let s of[a,e]){if(!n.exists(s))continue;let c=Qu(yo(s,r,n));i.push(...c.lines),o+=c.partialTailBytes}return{lines:i,ignoredPartialTailBytes:o}})}function ho(e,t,n,r){let i=`${e}${Ju}`,o=Math.max(0,t??Yu),a=n.monotonicNow()+o,s;for(;;){let p=n.tryAcquireLock(i,e);if(p.kind==="acquired"){s=p.lock;break}let f=a-n.monotonicNow();if(f<=0)throw new Rn(i,o);n.wait(Math.min(5,f))}let c=!1,u,l;try{l=r()}catch(p){c=!0,u=p}let d=!1;try{d=s.release()}catch(p){if(!c)throw p}if(c)throw u;if(!d)throw new xn(i);return l}function Ku(e,t,n){if(!n.exists(e))return 0;let r=yo(e,t,n);if(r.length===0||r[r.length-1]===10)return 0;let i=r.lastIndexOf(10),o=i<0?0:i+1;return n.truncate(e,o),r.length-o}function Xu(e){let t=e??Ke;if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`maxSegmentBytes must be a positive safe integer; received ${t}`);return t}function yo(e,t,n){let r=n.size(e);if(r>t)throw new Qt("rotating JSONL segment",e,"too-large",r,t);let i=n.readBytes(e),o=n.size(e);if(o!==r||i.byteLength!==r)throw new Qt("rotating JSONL segment",e,"changed-during-read",o,t);return i}function Qu(e){let t=e.lastIndexOf(10),n=t<0?0:t+1;return{lines:e.subarray(0,n).toString("utf8").split(`
|
|
10
|
+
`).filter(i=>i.length>0),partialTailBytes:e.length-n}}var nl="<global-symbols>";function rl(e){let t=[];for(let n of e.all(`
|
|
11
|
+
SELECT relative_path, language, position_encoding, text
|
|
12
|
+
FROM documents
|
|
13
|
+
`))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
|
|
14
|
+
SELECT d.relative_path,
|
|
15
|
+
c.chunk_index,
|
|
16
|
+
c.start_line,
|
|
17
|
+
c.end_line,
|
|
18
|
+
hex(c.occurrences) AS occurrences_hex
|
|
19
|
+
FROM chunks c
|
|
20
|
+
JOIN documents d ON d.id = c.document_id
|
|
21
|
+
`))t.push({relativePath:n.relative_path,kind:"chunk",values:[n.chunk_index,n.start_line,n.end_line,n.occurrences_hex]});for(let n of e.all(`
|
|
22
|
+
SELECT d.relative_path,
|
|
23
|
+
r.start_line,
|
|
24
|
+
r.start_char,
|
|
25
|
+
r.end_line,
|
|
26
|
+
r.end_char,
|
|
27
|
+
g.symbol,
|
|
28
|
+
g.display_name,
|
|
29
|
+
g.kind,
|
|
30
|
+
g.documentation,
|
|
31
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
32
|
+
g.enclosing_symbol,
|
|
33
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
34
|
+
FROM defn_enclosing_ranges r
|
|
35
|
+
JOIN documents d ON d.id = r.document_id
|
|
36
|
+
JOIN global_symbols g ON g.id = r.symbol_id
|
|
37
|
+
`))t.push({relativePath:n.relative_path,kind:"definition",values:vn(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
|
|
38
|
+
SELECT d.relative_path,
|
|
39
|
+
c.chunk_index,
|
|
40
|
+
m.role,
|
|
41
|
+
g.symbol,
|
|
42
|
+
g.display_name,
|
|
43
|
+
g.kind,
|
|
44
|
+
g.documentation,
|
|
45
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
46
|
+
g.enclosing_symbol,
|
|
47
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
48
|
+
FROM mentions m
|
|
49
|
+
JOIN chunks c ON c.id = m.chunk_id
|
|
50
|
+
JOIN documents d ON d.id = c.document_id
|
|
51
|
+
JOIN global_symbols g ON g.id = m.symbol_id
|
|
52
|
+
`))t.push({relativePath:n.relative_path,kind:"mention",values:vn(n,[n.chunk_index,n.role])});for(let n of e.all(`
|
|
53
|
+
SELECT g.symbol,
|
|
54
|
+
g.display_name,
|
|
55
|
+
g.kind,
|
|
56
|
+
g.documentation,
|
|
57
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
58
|
+
g.enclosing_symbol,
|
|
59
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
60
|
+
FROM global_symbols g
|
|
61
|
+
WHERE NOT EXISTS (
|
|
62
|
+
SELECT 1 FROM defn_enclosing_ranges r WHERE r.symbol_id = g.id
|
|
63
|
+
) AND NOT EXISTS (
|
|
64
|
+
SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
|
|
65
|
+
)
|
|
66
|
+
`))t.push({relativePath:nl,kind:"global-symbol",values:vn(n)});return il(t)}function il(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=Zu("sha256");for(let a of i.sort())o.update(String(Buffer.byteLength(a))),o.update(":"),o.update(a),o.update(`
|
|
67
|
+
`);n.set(r,o.digest("hex"))}return n}function ol(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 Pn(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 Tn(e,t=hl){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 To(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(Tl(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=ae(e.previousSnapshot,e.currentSnapshot),d=Pl(l,u,s,t),p=ol(t.factDigests(s),t.factDigests(c)),f=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?f:i()).toISOString(),durationMs:Math.max(0,f-o),manifest:l,plan:d,comparison:p,evaluation:Pn(d,p,u.length)}}catch(u){return a("oracle-error",u instanceof Error?u.message:String(u))}finally{bo(s),bo(c)}}function xo(e,t,n,r=Date.now()){return To(e,t,r,0,n)}function vo(e){let t=tl(e);return{latestPath:So(t,"affected-shadow-latest.json"),historyPath:So(t,"affected-shadow.jsonl")}}function AS(e,t=n=>xr(n,"affected-shadow source file")){let n=vo(e),r;try{r=JSON.parse(t(n.latestPath))}catch(i){let o=vl(i),a=o?"telemetry-missing":xl(i);return pe(n,a,o?void 0:i instanceof Error?i.message:String(i))}return al(r,n)}function al(e,t){return se(e)&&typeof e.version=="number"&&e.version!==1?pe(t,"unsupported-record-version",`Unsupported version ${e.version}.`):Sl(e)?e.status==="unavailable"?sl(e,t):e.status!=="evaluated"?pe(t,"telemetry-malformed"):dl(e,t):pe(t,"telemetry-malformed")}function sl(e,t){return bl(e.reason)?{state:"unavailable",...t,reason:e.reason,recordedAt:e.recordedAt,refreshResult:e.refreshResult,durationMs:e.durationMs,...typeof e.error=="string"?{error:e.error}:{}}:pe(t,"telemetry-malformed")}function cl(e){let t=e.mode,n=ce(e.affectedFiles),r=ce(e.reasons);return t!=="none"&&t!=="closure"&&t!=="full-project"||n===null||r===null?null:{mode:t,affectedFiles:n,fallbackReasons:r}}function ul(e){let t=ce(e.predictedFiles),n=ce(e.actualFiles),r=ce(e.missingFiles),i=e.recall,o=e.affectedRatio,a=e.passed;return t===null||n===null||r===null||typeof a!="boolean"||!Rl(i)||!Io(o)?null:{predictedFiles:t,actualFiles:n,missingFiles:r,recall:i,affectedRatio:o,passed:a}}function ll(e,t,n){let{predictedFiles:r,actualFiles:i,missingFiles:o,recall:a,passed:s}=t,c=i.length===0?1:(i.length-o.length)/i.length;return Ro(e.affectedFiles,r)&&Ro(n,i)&&s===(o.length===0)&&Math.abs(a-c)<=Number.EPSILON&&!o.some(u=>!i.includes(u)||r.includes(u))}function dl(e,t){let n=e.plan,r=e.comparison,i=e.evaluation;if(!se(e.manifest)||!se(n)||!se(r)||!se(i))return pe(t,"telemetry-malformed");let o=cl(n),a=ul(i),s=ce(r.changedFiles);if(!o||!a||s===null||!ll(o,a,s))return pe(t,"telemetry-malformed");let{mode:c,fallbackReasons:u}=o,{recall:l,affectedRatio:d,predictedFiles:p,actualFiles:f,missingFiles:m,passed:y}=a;return{state:y?"passing":"failing",...t,recordedAt:e.recordedAt,refreshResult:e.refreshResult,durationMs:e.durationMs,mode:c,recall:l,affectedRatio:d,predictedFiles:p,actualFiles:f,missingFiles:m,fallbackReasons:u}}function OS(e){if(e.state==="unavailable")return`unavailable (${e.reason})`;let t=e.missingFiles.length>0?`, ${e.missingFiles.length} missed`:"",n=e.fallbackReasons.length>0?`; fallback: ${e.fallbackReasons.join(", ")}`:"";return`${e.state}, ${(e.recall*100).toFixed(1)}% recall, ${e.predictedFiles.length} predicted / ${e.actualFiles.length} changed, ${(e.affectedRatio*100).toFixed(1)}% of project${t}${n}`}function Po(e,t,n=yl){let r=vo(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var pl=8*1024*1024,fl=Ee;function ml(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 gl(e,t,n=pl){It(e,ml(t),{maxSegmentBytes:n,previousSuffix:fl})}function vn(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 hl={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:R,databaseExists:e=>el(e),openDatabase:(e,t,n)=>new N({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>rt(e),dependencyGraph:e=>Ur(e),factDigests:e=>rl(e)},yl={appendHistory:gl,writeLatest:(e,t)=>ti(e,t,{spacing:2,trailingNewline:!0})};function To(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 bo(e){try{e?.close()}catch{}}function Sl(e){return se(e)&&e.version===1&&typeof e.recordedAt=="string"&&(e.refreshResult==="rebuilt"||e.refreshResult==="reused")&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0}function bl(e){return e==="prior-index-unavailable"||e==="candidate-index-unavailable"||e==="no-input-changes"||e==="oracle-error"}function Rl(e){return Io(e)&&e<=1}function Io(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Ro(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function pe(e,t,n){return{state:"unavailable",...e,reason:t,...n?{error:n}:{}}}function xl(e){return e instanceof SyntaxError?"telemetry-malformed":"telemetry-unreadable"}function vl(e){return e instanceof Error&&e.code==="ENOENT"}function Pl(e,t,n,r){let i=new Set(t),o=e.changes.length>0&&!de(e).fullProject&&e.changes.every(s=>i.has(s.path));return Tt(e,o?r.dependencyGraph(n):new Map,t)}function Tl(e){return e.refreshResult!=="rebuilt"?!1:ae(e.previousSnapshot,e.currentSnapshot).changes.length===0}import{readdirSync as Il}from"fs";import{isAbsolute as wo,join as wl,resolve as El}from"path";var wt="@sourcegraph/scip-typescript@0.4.0",Eo="scip-python-plus@0.7.5",ko="github.com/sourcegraph/scip-go@v0.2.7",Co="scip-dotnet@0.2.14",kl="scip_dart@1.6.2",Cl={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:[...F.typescript],installMethods:[{label:"npm",identity:wt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",wt]}],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:[...F.javascript],installMethods:[{label:"npm",identity:wt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",wt]}],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:[...F.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:[...F.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:[...F.kotlin],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:Re.language,indexerBinary:Re.indexerBinary,checkCommand:`${Re.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:Re.indexerBinary,args:["scip",".","--output",e]}),markerFiles:[...F.rust],installMethods:[],installUrl:Re.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:[...F.python],installMethods:[{label:"npm",identity:Eo,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",Eo]}],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",wo(r)?r:El(e,r)),{binary:n,args:i}},markerFiles:[...F.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:[...F.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:[...F.go],installMethods:[{label:"go install",identity:ko,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",ko]}],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:[...F.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:[...F.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",Fo(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...F.csharp],installMethods:[{label:"dotnet",identity:Co,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",Fo(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...F.vb],installMethods:[{label:"dotnet",identity:Co,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:[...F.dart],installMethods:[{label:"dart pub",identity:kl,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})=>wo(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:[...F.php],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Do(e){if(!(e.projectPath||e.pnpmWorkspaces)){if(e.language==="typescript")return"{}";if(e.language==="javascript")return'{"compilerOptions":{"allowJs":true}}'}}function Et(e){return Cl[e]}function Fo(e,t){let n;try{n=Il(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return wl(e,i);return null}import{createHash as Fl}from"crypto";import{existsSync as wn,rmSync as Ao,statSync as Dl}from"fs";import{resolve as Al}from"path";import _o from"better-sqlite3";var Ol={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}]},Ll={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 Mo(e){let t=R(),n=Oo(e.affectedFiles),r=Oo(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(Ml(e.previousDbPath,e.miniDbPath,e.candidateDbPath),!wn(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!wn(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");g("reindex.publish.sqlite-patch.validate-inputs",()=>{In(e.previousDbPath,"previous SQLite generation",!1),In(e.miniDbPath,"incremental SQLite mini database")}),e.reuseCandidate?g("reindex.publish.sqlite-patch.reuse-candidate",()=>In(e.candidateDbPath,"incremental SQLite candidate",!1)):g("reindex.publish.sqlite-patch.clone",()=>{Ao(e.candidateDbPath,{force:!0});let s=Z(e.previousDbPath,e.candidateDbPath);e.writeTelemetry&&ee(e.writeTelemetry,s)});let a=null;try{a=g("reindex.publish.sqlite-patch.open",()=>{let f=new _o(e.candidateDbPath,{fileMustExist:!0});return f.pragma("busy_timeout = 5000"),f.pragma("foreign_keys = ON"),f.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),En(f,"main","candidate SQLite generation"),En(f,"incremental","incremental SQLite mini database"),f});let{priorAffectedCount:s,previousFactDigests:c}=g("reindex.publish.sqlite-patch.prepare",()=>(Bl(a,n,r),{...$l(a,n.length,r.length),previousFactDigests:kn(a,"main",!0)})),u=te(a,"SELECT COUNT(*) AS value FROM main.documents"),l=a.transaction(()=>{g("reindex.publish.sqlite-patch.transaction.symbol-ownership",()=>Vl(a)),g("reindex.publish.sqlite-patch.transaction.shared-definitions",()=>Ul(a)),g("reindex.publish.sqlite-patch.transaction.delete",()=>Gl(a)),e.onStage?.("after-delete"),g("reindex.publish.sqlite-patch.transaction.reconcile-symbols",()=>Wl(a)),e.onStage?.("after-symbol-reconciliation"),g("reindex.publish.sqlite-patch.transaction.insert",()=>ql(a)),e.onStage?.("after-insert"),g("reindex.publish.sqlite-patch.transaction.prune-symbols",()=>zl(a,e.trustedPriorGeneration===!0)),g("reindex.publish.sqlite-patch.transaction.validate",()=>Hl(a,o,u,s)),e.onStage?.("before-commit")});g("reindex.publish.sqlite-patch.transaction",()=>l.immediate()),e.writeTelemetry&&xt(e.writeTelemetry,2*_l(e.candidateDbPath)),g("reindex.publish.sqlite-patch.integrity",()=>jl(a,"candidate SQLite generation",!e.deferIntegrity&&e.trustedPriorGeneration!==!0));let d=g("reindex.publish.sqlite-patch.validate-facts",()=>Jl(a)),p=[...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:p,durationMs:R()-t}}catch(s){try{a?.close()}finally{Ao(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}function _l(e){let t=0;for(let n of["-wal","-journal"]){let r=`${e}${n}`;wn(r)&&(t+=Dl(r).size)}return t}function Oo(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 Ml(e,t,n){let r=[e,t,n].map(i=>Al(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function In(e,t,n=!0){let r=new _o(e,{readonly:!0,fileMustExist:!0});try{En(r,"main",t),n&&Nl(r,"main",t)}finally{r.close()}}function En(e,t,n){for(let[r,i]of Object.entries(Ol)){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(Ll)){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}`)}Lo(e,t,"documents",["relative_path"],n),Lo(e,t,"global_symbols",["symbol"],n)}function Lo(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 Nl(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 jl(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 Bl(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 $l(e,t,n){let r=te(e,"SELECT COUNT(*) AS value FROM incremental.documents"),i=te(e,`SELECT COUNT(*) AS value
|
|
68
|
+
FROM main.documents d
|
|
69
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),o=e.prepare(`SELECT p.relative_path
|
|
70
|
+
FROM temp.incremental_affected_paths p
|
|
71
|
+
LEFT JOIN incremental.documents d ON d.relative_path = p.relative_path
|
|
72
|
+
LEFT JOIN temp.incremental_deleted_paths deleted ON deleted.relative_path = p.relative_path
|
|
73
|
+
WHERE d.id IS NULL AND deleted.relative_path IS NULL
|
|
74
|
+
LIMIT 1`).pluck().get(),a=e.prepare(`SELECT d.relative_path
|
|
75
|
+
FROM incremental.documents d
|
|
76
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
77
|
+
WHERE p.relative_path IS NULL
|
|
78
|
+
LIMIT 1`).pluck().get(),s=e.prepare(`SELECT d.relative_path
|
|
79
|
+
FROM incremental.documents d
|
|
80
|
+
JOIN temp.incremental_deleted_paths deleted ON deleted.relative_path = d.relative_path
|
|
81
|
+
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 Vl(e){e.exec(`
|
|
82
|
+
CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
83
|
+
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
84
|
+
SELECT g.symbol
|
|
85
|
+
FROM temp.incremental_affected_paths p
|
|
86
|
+
CROSS JOIN main.documents d ON d.relative_path = p.relative_path
|
|
87
|
+
CROSS JOIN main.defn_enclosing_ranges r ON r.document_id = d.id
|
|
88
|
+
CROSS JOIN main.global_symbols g ON g.id = r.symbol_id;
|
|
89
|
+
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
90
|
+
SELECT g.symbol
|
|
91
|
+
FROM temp.incremental_affected_paths p
|
|
92
|
+
CROSS JOIN main.documents d ON d.relative_path = p.relative_path
|
|
93
|
+
CROSS JOIN main.chunks c ON c.document_id = d.id
|
|
94
|
+
CROSS JOIN main.mentions m ON m.chunk_id = c.id
|
|
95
|
+
CROSS JOIN main.global_symbols g ON g.id = m.symbol_id
|
|
96
|
+
WHERE m.role = 1;
|
|
97
|
+
|
|
98
|
+
CREATE TEMP TABLE incremental_new_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
99
|
+
INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
|
|
100
|
+
SELECT g.symbol
|
|
101
|
+
FROM incremental.defn_enclosing_ranges r
|
|
102
|
+
JOIN incremental.global_symbols g ON g.id = r.symbol_id;
|
|
103
|
+
INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
|
|
104
|
+
SELECT g.symbol
|
|
105
|
+
FROM incremental.mentions m
|
|
106
|
+
JOIN incremental.global_symbols g ON g.id = m.symbol_id
|
|
107
|
+
WHERE m.role = 1;
|
|
108
|
+
|
|
109
|
+
CREATE TEMP TABLE incremental_touched_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
110
|
+
INSERT OR IGNORE INTO temp.incremental_touched_symbols(symbol)
|
|
111
|
+
SELECT symbol FROM temp.incremental_old_defined_symbols;
|
|
112
|
+
INSERT OR IGNORE INTO temp.incremental_touched_symbols(symbol)
|
|
113
|
+
SELECT g.symbol
|
|
114
|
+
FROM temp.incremental_affected_paths p
|
|
115
|
+
CROSS JOIN main.documents d ON d.relative_path = p.relative_path
|
|
116
|
+
CROSS JOIN main.chunks c ON c.document_id = d.id
|
|
117
|
+
CROSS JOIN main.mentions m ON m.chunk_id = c.id
|
|
118
|
+
CROSS JOIN main.global_symbols g ON g.id = m.symbol_id;
|
|
119
|
+
INSERT OR IGNORE INTO temp.incremental_touched_symbols(symbol)
|
|
120
|
+
SELECT symbol FROM incremental.global_symbols;
|
|
121
|
+
`)}function Ul(e){let t=e.prepare(`WITH changed_symbols AS (
|
|
122
|
+
SELECT symbol FROM temp.incremental_old_defined_symbols
|
|
123
|
+
UNION
|
|
124
|
+
SELECT symbol FROM temp.incremental_new_defined_symbols
|
|
125
|
+
)
|
|
126
|
+
SELECT c.symbol
|
|
127
|
+
FROM changed_symbols c
|
|
128
|
+
CROSS JOIN main.global_symbols g ON g.symbol = c.symbol
|
|
129
|
+
WHERE EXISTS (
|
|
130
|
+
SELECT 1
|
|
131
|
+
FROM main.defn_enclosing_ranges r
|
|
132
|
+
JOIN main.documents d ON d.id = r.document_id
|
|
133
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
134
|
+
WHERE r.symbol_id = g.id AND p.relative_path IS NULL
|
|
135
|
+
) OR EXISTS (
|
|
136
|
+
SELECT 1
|
|
137
|
+
FROM main.mentions m
|
|
138
|
+
JOIN main.chunks chunk ON chunk.id = m.chunk_id
|
|
139
|
+
JOIN main.documents d ON d.id = chunk.document_id
|
|
140
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
141
|
+
WHERE m.symbol_id = g.id AND m.role = 1 AND p.relative_path IS NULL
|
|
142
|
+
)
|
|
143
|
+
LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function Gl(e){e.exec(`
|
|
144
|
+
DELETE FROM main.mentions
|
|
145
|
+
WHERE chunk_id IN (
|
|
146
|
+
SELECT c.id
|
|
147
|
+
FROM main.chunks c
|
|
148
|
+
JOIN main.documents d ON d.id = c.document_id
|
|
149
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
150
|
+
);
|
|
151
|
+
DELETE FROM main.chunks
|
|
152
|
+
WHERE document_id IN (
|
|
153
|
+
SELECT d.id
|
|
154
|
+
FROM main.documents d
|
|
155
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
156
|
+
);
|
|
157
|
+
DELETE FROM main.defn_enclosing_ranges
|
|
158
|
+
WHERE document_id IN (
|
|
159
|
+
SELECT d.id
|
|
160
|
+
FROM main.documents d
|
|
161
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
162
|
+
);
|
|
163
|
+
DELETE FROM main.documents
|
|
164
|
+
WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
|
|
165
|
+
`)}function Wl(e){e.exec(`
|
|
166
|
+
UPDATE main.global_symbols
|
|
167
|
+
SET display_name = NULL,
|
|
168
|
+
kind = NULL,
|
|
169
|
+
documentation = NULL,
|
|
170
|
+
signature = NULL,
|
|
171
|
+
enclosing_symbol = NULL,
|
|
172
|
+
relationships = NULL
|
|
173
|
+
WHERE symbol IN (SELECT symbol FROM temp.incremental_old_defined_symbols);
|
|
174
|
+
|
|
175
|
+
INSERT OR IGNORE INTO main.global_symbols(
|
|
176
|
+
symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
|
|
177
|
+
)
|
|
178
|
+
SELECT symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
|
|
179
|
+
FROM incremental.global_symbols;
|
|
180
|
+
|
|
181
|
+
UPDATE main.global_symbols
|
|
182
|
+
SET display_name = (
|
|
183
|
+
SELECT source.display_name FROM incremental.global_symbols source
|
|
184
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
185
|
+
),
|
|
186
|
+
kind = (
|
|
187
|
+
SELECT source.kind FROM incremental.global_symbols source
|
|
188
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
189
|
+
),
|
|
190
|
+
documentation = (
|
|
191
|
+
SELECT source.documentation FROM incremental.global_symbols source
|
|
192
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
193
|
+
),
|
|
194
|
+
signature = (
|
|
195
|
+
SELECT source.signature FROM incremental.global_symbols source
|
|
196
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
197
|
+
),
|
|
198
|
+
enclosing_symbol = (
|
|
199
|
+
SELECT source.enclosing_symbol FROM incremental.global_symbols source
|
|
200
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
201
|
+
),
|
|
202
|
+
relationships = (
|
|
203
|
+
SELECT source.relationships FROM incremental.global_symbols source
|
|
204
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
205
|
+
)
|
|
206
|
+
WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
|
|
207
|
+
`)}function ql(e){let t=te(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=te(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=te(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)
|
|
208
|
+
SELECT id + ?, language, relative_path, position_encoding, text
|
|
209
|
+
FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
|
|
210
|
+
SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
|
|
211
|
+
FROM incremental.chunks`).run(n,t),e.prepare(`INSERT INTO main.mentions(chunk_id, symbol_id, role)
|
|
212
|
+
SELECT m.chunk_id + ?, target.id, m.role
|
|
213
|
+
FROM incremental.mentions m
|
|
214
|
+
CROSS JOIN incremental.global_symbols source ON source.id = m.symbol_id
|
|
215
|
+
CROSS JOIN main.global_symbols target ON target.symbol = source.symbol`).run(n),e.prepare(`INSERT INTO main.defn_enclosing_ranges(
|
|
216
|
+
id, document_id, symbol_id, start_line, start_char, end_line, end_char
|
|
217
|
+
)
|
|
218
|
+
SELECT r.id + ?, r.document_id + ?, target.id,
|
|
219
|
+
r.start_line, r.start_char, r.end_line, r.end_char
|
|
220
|
+
FROM incremental.defn_enclosing_ranges r
|
|
221
|
+
CROSS JOIN incremental.global_symbols source ON source.id = r.symbol_id
|
|
222
|
+
CROSS JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function zl(e,t){let n=t?"symbol IN (SELECT symbol FROM temp.incremental_touched_symbols) AND":"";e.exec(`
|
|
223
|
+
DELETE FROM main.global_symbols
|
|
224
|
+
WHERE ${n}
|
|
225
|
+
NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
|
|
226
|
+
AND NOT EXISTS (
|
|
227
|
+
SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
|
|
228
|
+
);
|
|
229
|
+
`)}function Hl(e,t,n,r){let i=te(e,"SELECT COUNT(*) AS value FROM main.documents"),o=te(e,`SELECT COUNT(*) AS value
|
|
230
|
+
FROM main.documents d
|
|
231
|
+
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 Jl(e){let t=kn(e,"main",!0),n=kn(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 kn(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
|
|
232
|
+
FROM ${t}.documents d
|
|
233
|
+
${r}
|
|
234
|
+
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
|
|
235
|
+
FROM ${t}.chunks c
|
|
236
|
+
JOIN ${t}.documents d ON d.id = c.document_id
|
|
237
|
+
${r}
|
|
238
|
+
ORDER BY d.relative_path, c.chunk_index, c.start_line, c.end_line, c.id`).all(),a=e.prepare(`SELECT d.relative_path, r.start_line, r.start_char, r.end_line, r.end_char,
|
|
239
|
+
g.symbol, g.display_name, g.kind, g.documentation,
|
|
240
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature,
|
|
241
|
+
g.enclosing_symbol,
|
|
242
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships
|
|
243
|
+
FROM ${t}.defn_enclosing_ranges r
|
|
244
|
+
JOIN ${t}.documents d ON d.id = r.document_id
|
|
245
|
+
JOIN ${t}.global_symbols g ON g.id = r.symbol_id
|
|
246
|
+
${r}
|
|
247
|
+
ORDER BY d.relative_path, r.start_line, r.start_char, r.end_line, r.end_char, g.symbol`).all(),s=e.prepare(`SELECT d.relative_path, c.chunk_index, m.role, g.symbol
|
|
248
|
+
FROM ${t}.mentions m
|
|
249
|
+
JOIN ${t}.chunks c ON c.id = m.chunk_id
|
|
250
|
+
JOIN ${t}.documents d ON d.id = c.document_id
|
|
251
|
+
JOIN ${t}.global_symbols g ON g.id = m.symbol_id
|
|
252
|
+
${r}
|
|
253
|
+
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 f=JSON.stringify([l,p]),m=c.get(p.relative_path)??[];m.push(f),c.set(p.relative_path,m)}let u=new Map;for(let[l,d]of[...c].sort(([p],[f])=>p.localeCompare(f))){let p=Fl("sha256");for(let f of d.sort())p.update(f).update(`
|
|
254
|
+
`);u.set(l,p.digest("hex"))}return u}function te(e,t){return e.prepare(t).get().value}import Yl from"better-sqlite3";var kt="idx_mentions_definitions",Kl=["symbol_id","chunk_id"];function Cn(e,t={}){let n=new Yl(e),r=[],i=[],o=[];try{return n.transaction(()=>{Xl(n,r),Ct(n,"idx_global_symbols_symbol")?.join("\0")==="symbol"&&No(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")):Ct(n,"idx_global_symbols_symbol")&&o.push("idx_global_symbols_symbol");let a=Ct(n,"idx_chunks_doc_id"),s=No(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 Xl(e,t){let n=jo(e,kt);if(n){let r=n.columns.join("\0")===Kl.join("\0"),i=/\bWHERE\s+role\s*=\s*1\b/iu.test(n.sql??"");if(!r||!i||n.table!=="mentions")throw new Error(`${kt} exists with an incompatible definition`);return}e.exec(`CREATE INDEX "${kt}" ON mentions(symbol_id, chunk_id) WHERE role = 1`),t.push(kt)}function No(e,t){return e.prepare(`PRAGMA index_list('${t.replaceAll("'","''")}')`).all().map(n=>({name:n.name,unique:n.unique===1,columns:Ct(e,n.name)??[]}))}function Ct(e,t){return jo(e,t)?.columns??null}function jo(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 Ql}from"fs";function ke(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 $o(e,t){let n=performance.now(),r=await e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}async function Vo(e){let t=e.readFingerprint(),n=Zl(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=await e.compute();return ed(e.cachePath,e.readFingerprint(),r),r}function Zl(e,t){try{let n=JSON.parse(_(e,{maxBytes:K,inputKind:"post-index augmentation cache"}));return Bo(n.fingerprint)===Bo(t)?{result:n.result}:null}catch{return null}}function ed(e,t,n){Ql(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
|
|
255
|
+
`)}function Bo(e){return JSON.stringify(e)}import{existsSync as Uo,statSync as td}from"fs";import{dirname as Wo,join as qo}from"path";var nd="reindex-activity.jsonl",Ft=Ee,rd=1024*1024,id=1440*60*1e3,zo=e=>U(e,"reindex activity segment");function Dt(e){return qo(Wo(e),nd)}function Ho(e){if(e.reused)return 0;let n=(e.shards?.some(r=>!r.reused&&r.strategy==="incremental")??!1?0:Fn(e.indexPath))+Fn(e.dbPath);for(let r of e.shards??[]){if(r.reused)continue;let i=r.producedOutputBytes??r.outputBytes;i!==null&&(n+=i)}return n}function od(e){let t=Ho(e),n=e.writeTelemetry;return n?Math.max(0,t-n.reflinkedBytes)+n.fallbackCopiedBytes+(n.incrementalWrittenBytes??0):t}function Jo(e,t){let n=t.lastRefresh;if(!n)return{state:"failed",reason:"reindex result has no refresh metadata"};let r=Ho(t);return Dn(Dt(e),{version:1,event:"run",recordedAt:n.completedAt,trigger:n.trigger,result:n.result,durationMs:n.durationMs,estimatedLogicalOutputBytes:r,estimatedWriteBytes:od(t),reflinkedBytes:t.writeTelemetry?.reflinkedBytes??0,fallbackCopiedBytes:t.writeTelemetry?.fallbackCopiedBytes??0,incrementalWrittenBytes:t.writeTelemetry?.incrementalWrittenBytes??0,byLanguage:xd(t)})}function Yo(e,t){return Dn(Dt(e),{version:1,event:"run",recordedAt:t.completedAt,trigger:t.trigger,result:"failed",durationMs:t.durationMs,estimatedLogicalOutputBytes:0})}function ab(e,t,n=new Date){return Dn(Dt(e),{version:1,event:"suppressed",recordedAt:n.toISOString(),trigger:t,reason:"completed-index-is-fresh"})}function ad(e,t,n=rd,r){It(e,t,{maxSegmentBytes:n,previousSuffix:Ft,...r?{runtime:r}:{}})}function sd(e,t=new Date,n=id,r=zo){let i=t.getTime(),o=i-n,a=cd(o,t),s=ud(Dt(e),r,a);if(s===null)return a;for(let c of s){let u=ld(c,o,i,a);if(!u)continue;let{record:l}=u;if(a.invalidLanguageDetails+=u.invalidLanguageDetails,a.byTrigger[l.trigger.kind]=(a.byTrigger[l.trigger.kind]??0)+1,l.event==="suppressed"){a.suppressed+=1;continue}dd(a,u,l)}return a.ignoredPartialTailBytes>0&&a.confidence!=="unavailable"&&(a.confidence="partial"),a.languageAttribution=Ad(a),a}function cd(e,t){return{confidence:"complete",recordsRead:0,invalidRecords:0,skippedRecords:0,readErrors:0,ignoredPartialTailBytes:0,windowStartedAt:new Date(e).toISOString(),windowEndedAt:t.toISOString(),runs:0,rebuilt:0,fullRebuilds:0,reused:0,failed:0,suppressed:0,estimatedLogicalOutputBytes:0,estimatedWriteBytes:0,reflinkedBytes:0,fallbackCopiedBytes:0,languageAttribution:"complete",attributedRuns:0,unattributedRuns:0,invalidLanguageDetails:0,byLanguage:{},byTrigger:{},automatic:{runs:0,rebuilt:0,fullRebuilds:0,estimatedWriteBytes:0}}}function ud(e,t,n){let r=[];if(t===zo){if(!Uo(e)&&!Uo(`${e}${Ft}`))return null;try{let i=go(e,{previousSuffix:Ft});r=i.lines,n.ignoredPartialTailBytes=i.ignoredPartialTailBytes}catch{n.readErrors+=1,n.confidence="unavailable"}}else{let i=0;for(let o of[`${e}${Ft}`,e])try{r.push(...Od(t(o))),i+=1}catch{n.readErrors+=1}i===0?n.confidence="unavailable":n.readErrors>0&&(n.confidence="partial")}return r}function ld(e,t,n,r){r.recordsRead+=1;let i=md(e);if(!i)return r.invalidRecords+=1,r.confidence!=="unavailable"&&(r.confidence="partial"),null;let{record:o}=i,a=Date.parse(o.recordedAt);return a<t||a>n?(r.skippedRecords+=1,null):i}function dd(e,t,n){e.runs+=1,e[n.result]+=1,e.estimatedLogicalOutputBytes+=n.estimatedLogicalOutputBytes;let r=yd(n);e.estimatedWriteBytes+=r,e.reflinkedBytes+=n.reflinkedBytes??0,e.fallbackCopiedBytes+=n.fallbackCopiedBytes??0,pd(e,t,n);let i=Rd(n);i&&e.oldestRebuildAt===void 0&&(e.oldestRebuildAt=n.recordedAt),i&&(e.fullRebuilds+=1),r>0&&e.oldestWriteAt===void 0&&(e.oldestWriteAt=n.recordedAt),fd(e.automatic,n,i,r)}function pd(e,t,n){n.result!=="failed"&&(t.hasLanguageDetails?e.attributedRuns+=1:e.unattributedRuns+=1);for(let[r,i]of Ko(n.byLanguage)){let o=e.byLanguage[r]??=Dd();o.runs+=1,o[i.result]+=1,o.producedOutputBytes+=i.producedOutputBytes,o.durationMs+=i.durationMs}}function fd(e,t,n,r){Sd(t.trigger)&&(e.runs+=1,t.result==="rebuilt"&&(e.rebuilt+=1),n&&(e.fullRebuilds+=1,e.oldestRebuildAt??=t.recordedAt),e.estimatedWriteBytes+=r,r>0&&(e.oldestWriteAt??=t.recordedAt))}function Dn(e,t){try{return ad(e,t),{state:"recorded"}}catch(n){return{state:"failed",reason:n instanceof Error?n.message:String(n)}}}function md(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;if(!gd(n))return null;if(n.event==="suppressed")return n.reason==="completed-index-is-fresh"?{record:n,hasLanguageDetails:!1,invalidLanguageDetails:0}:null;if(!hd(n))return null;let r=n,{byLanguage:i,...o}=r,a=wd(i);return{record:{...o,...a.byLanguage?{byLanguage:a.byLanguage}:{}},hasLanguageDetails:a.hasLanguageDetails,invalidLanguageDetails:a.invalidLanguageDetails}}catch{return null}}function gd(e){return e.version===1&&Lr(e.recordedAt)&&!!e.trigger&&oi(e.trigger.kind)}function hd(e){return e.event!=="run"||e.result!=="rebuilt"&&e.result!=="reused"&&e.result!=="failed"||!Le(e.durationMs)||!Le(e.estimatedLogicalOutputBytes)?!1:[e.estimatedWriteBytes,e.reflinkedBytes,e.fallbackCopiedBytes,e.incrementalWrittenBytes].every(t=>t===void 0||Le(t))}function yd(e){return e.reflinkedBytes===void 0?e.estimatedWriteBytes??e.estimatedLogicalOutputBytes:Math.max(0,e.estimatedLogicalOutputBytes-e.reflinkedBytes)+(e.fallbackCopiedBytes??0)+(e.incrementalWrittenBytes??0)}function sb(e,t,n=new Date){return t.enabled?bd(sd(e,n,t.windowMs),t,n.getTime()):{state:"allowed",rebuilt:0,estimatedWriteBytes:0}}function Sd(e){return e.kind.startsWith("watch-")}function bd(e,t,n){let r=e.automatic??{fullRebuilds:e.fullRebuilds??e.rebuilt,estimatedWriteBytes:e.estimatedWriteBytes??e.estimatedLogicalOutputBytes,oldestRebuildAt:e.oldestRebuildAt,oldestWriteAt:e.oldestWriteAt},i=r.estimatedWriteBytes,o=r.fullRebuilds,a={rebuilt:o,estimatedWriteBytes:i};return t.enabled?e.confidence!==void 0&&e.confidence!=="complete"?{state:"paused",reason:"activity-evidence",until:n+t.windowMs,...a,detail:`reindex activity evidence is ${e.confidence}`}:o>=t.maxRebuilds?{state:"paused",reason:"rebuild-count",until:Go(r.oldestRebuildAt,t.windowMs,n),...a,detail:`${o}/${t.maxRebuilds} expensive full rebuild slots consumed by automatic refreshes`}:i>=t.maxEstimatedWriteBytes?{state:"paused",reason:"estimated-write-bytes",until:Go(r.oldestWriteAt,t.windowMs,n),...a,detail:`${i}/${t.maxEstimatedWriteBytes} estimated write bytes consumed by automatic refreshes`}:{state:"allowed",...a}:{state:"allowed",...a}}function Rd(e){if(e.result!=="rebuilt")return!1;let t=Ko(e.byLanguage);return t.length===0?!0:t.some(([,n])=>n.result==="rebuilt"&&n.strategy!=="incremental"&&n.strategy!=="reused")}function Go(e,t,n){let r=e?Date.parse(e):Number.NaN;return Number.isFinite(r)&&r+t>n?r+t:n+t}function Fn(e){try{return td(e).size}catch{return 0}}function xd(e){let t={};for(let n of e.languages)t[n]=vd(e,n);return t}function vd(e,t){let n=(e.shards??[]).filter(c=>c.language===t),r=n.find(c=>c.id===t),i=Td(e.reused,n,r),o=Fn(qo(Wo(e.dbPath),"language-indexes",`${t}.scip`)),a=o>0?o:r?.outputBytes??o,s=Id(i,n,r);return{result:i?"reused":"rebuilt",strategy:i?"reused":r?.strategy??"full",...Pd(r),outputBytes:a,producedOutputBytes:i?0:r?.producedOutputBytes??a,durationMs:s}}function Pd(e){return e?.strategy==="full"&&(e.fallbackReason??e.missReason)?{fallbackReason:e.fallbackReason??e.missReason}:{}}function Td(e,t,n){return e||(n?n.reused:t.length>0&&t.every(r=>r.reused))}function Id(e,t,n){return e?0:n?.durationMs??t.filter(r=>!r.reused).reduce((r,i)=>r+i.durationMs,0)}function wd(e){if(e===void 0)return{hasLanguageDetails:!1,invalidLanguageDetails:0};if(!e||typeof e!="object"||Array.isArray(e))return{hasLanguageDetails:!1,invalidLanguageDetails:1};let t={},n=0;for(let[i,o]of Object.entries(e)){if(!Fd(i)||!Ed(o)){n+=1;continue}t[i]=o}let r=Object.keys(t).length>0;return{...r?{byLanguage:t}:{},hasLanguageDetails:r,invalidLanguageDetails:n}}function Ed(e){if(!e||typeof e!="object")return!1;let t=e;return kd(t)&&Cd(t)}function kd(e){return(e.result==="rebuilt"||e.result==="reused")&&(e.strategy===void 0||e.strategy==="reused"||e.strategy==="incremental"||e.strategy==="full")&&(e.fallbackReason===void 0||typeof e.fallbackReason=="string")}function Cd(e){return en(e.outputBytes)&&en(e.producedOutputBytes)&&Le(e.durationMs)&&(e.result!=="reused"||e.producedOutputBytes===0&&e.durationMs===0)&&e.producedOutputBytes<=e.outputBytes}function Fd(e){return tn.includes(e)}function Ko(e){return e?tn.flatMap(t=>{let n=e[t];return n?[[t,n]]:[]}):[]}function Dd(){return{runs:0,rebuilt:0,reused:0,producedOutputBytes:0,durationMs:0}}function Ad(e){let t=e.invalidLanguageDetails??0,n=e.attributedRuns??0;return(e.unattributedRuns??0)===0&&t===0?"complete":n===0?"unavailable":"partial"}function Od(e){return e.endsWith(`
|
|
256
|
+
`)||(e=e.slice(0,Math.max(0,e.lastIndexOf(`
|
|
257
|
+
`)+1))),e.split(`
|
|
258
|
+
`).filter(t=>t.length>0)}import{createHash as Ld}from"crypto";import{existsSync as An,readdirSync as _d}from"fs";import{dirname as On,join as At,relative as Md,resolve as Ln,sep as Xo}from"path";function Qo(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=na(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Zo(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);Nd(i,e,o,n,a)}return Bd(e,r)}function Nd(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)}jd(e,t,n,i)}function jd(e,t,n,r){for(let i of[...n.pathsTargets,...n.referencesPaths]){let o=na(i,t);o&&o!==e&&r.add(o)}}function ea(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 _n(e){if(e===".")return"root";let t=Ld("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function ta(e,t){let n=Ln(e),r={};for(let i of t)r[i]=$d(n,i);return r}function na(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 Bd(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 $d(e,t){let n=t==="."?e:At(e,t),r=Vd(n),i=Ud(n),o=i?Gd(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 Vd(e){let t=At(e,"package.json");if(!An(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Mn(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 Ud(e){let t=At(e,"tsconfig.json");if(An(t))return t;let n;try{n=_d(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?At(e,n[0]):void 0}function Gd(e,t){let n=Mn(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=Wd(n.value,e,t),i=ra(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function Wd(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=On(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=ia(s,i,n);c&&o.add(c)}return[...o]}function ra(e,t,n,r){let i=qd(t);if(i)return{pathsTargets:zd(i,On(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=Hd(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=Mn(o);return a.ok?ra(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function qd(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 zd(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=ia(o,t,n);a&&r.add(a)}return[...r]}function Hd(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=Ln(On(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Xo).includes("node_modules")&&Kt(n,i)&&An(i))return i}function ia(e,t,n){let r=e.replace(/\/?\*+$/,""),i=Ln(t,r===""?".":r);if(!Kt(n,i))return;let a=Md(n,i).split(Xo).join("/");return a===""?".":a}function Jd(e){let t="",n=0,r=!1,i=e.length;for(;n<i;){let o=e[n];if(r){t+=o;let a=Yd(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=Kd(e,n+2);continue}if(o==="/"&&e[n+1]==="*"){n=Xd(e,n+2);continue}t+=o,n+=1}return t}function Yd(e,t){return e[t]==="\\"&&t+1<e.length?t+2:t+1}function Kd(e,t){for(;t<e.length&&e[t]!==`
|
|
259
|
+
`;)t+=1;return t}function Xd(e,t){for(;t<e.length&&!(e[t]==="*"&&e[t+1]==="/");)t+=1;return t+2}function Mn(e){try{let t=_(e,{maxBytes:K,inputKind:"TypeScript project manifest"}),n=JSON.parse(Jd(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import Qd from"better-sqlite3";import{zstdCompressSync as Zd}from"zlib";import{setImmediate as ep}from"timers/promises";var ne=class extends Error{},tp=200,ca=2,ua=1,np=2,rp=3,ip=4,op=5,ap=6,la=1,da=2,pa=3,sp=7,cp=1,up=3,lp=5,dp=6,pp=8,fp=1,mp=64,gp=[`CREATE TABLE documents (
|
|
260
|
+
id INTEGER PRIMARY KEY,
|
|
261
|
+
language TEXT,
|
|
262
|
+
relative_path TEXT NOT NULL UNIQUE,
|
|
263
|
+
position_encoding TEXT,
|
|
264
|
+
text TEXT
|
|
265
|
+
)`,`CREATE TABLE chunks (
|
|
266
|
+
id INTEGER PRIMARY KEY,
|
|
267
|
+
document_id INTEGER NOT NULL,
|
|
268
|
+
chunk_index INTEGER NOT NULL,
|
|
269
|
+
start_line INTEGER NOT NULL,
|
|
270
|
+
end_line INTEGER NOT NULL,
|
|
271
|
+
occurrences BLOB NOT NULL,
|
|
272
|
+
FOREIGN KEY (document_id) REFERENCES documents(id)
|
|
273
|
+
)`,`CREATE TABLE global_symbols (
|
|
274
|
+
id INTEGER PRIMARY KEY,
|
|
275
|
+
symbol TEXT NOT NULL UNIQUE,
|
|
276
|
+
display_name TEXT,
|
|
277
|
+
kind INTEGER,
|
|
278
|
+
documentation TEXT,
|
|
279
|
+
signature BLOB,
|
|
280
|
+
enclosing_symbol TEXT,
|
|
281
|
+
relationships BLOB
|
|
282
|
+
)`,`CREATE TABLE mentions (
|
|
283
|
+
chunk_id INTEGER NOT NULL,
|
|
284
|
+
symbol_id INTEGER NOT NULL,
|
|
285
|
+
role INTEGER NOT NULL,
|
|
286
|
+
PRIMARY KEY (chunk_id, symbol_id, role),
|
|
287
|
+
FOREIGN KEY (chunk_id) REFERENCES chunks(id),
|
|
288
|
+
FOREIGN KEY (symbol_id) REFERENCES global_symbols(id)
|
|
289
|
+
)`,`CREATE TABLE defn_enclosing_ranges (
|
|
290
|
+
id INTEGER PRIMARY KEY,
|
|
291
|
+
document_id INTEGER NOT NULL,
|
|
292
|
+
symbol_id INTEGER NOT NULL,
|
|
293
|
+
start_line INTEGER NOT NULL,
|
|
294
|
+
start_char INTEGER NOT NULL,
|
|
295
|
+
end_line INTEGER NOT NULL,
|
|
296
|
+
end_char INTEGER NOT NULL,
|
|
297
|
+
FOREIGN KEY (document_id) REFERENCES documents(id),
|
|
298
|
+
FOREIGN KEY (symbol_id) REFERENCES global_symbols(id)
|
|
299
|
+
)`],hp=["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 Nn(e){return e.startsWith("local ")}function yp(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 oa(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 Sp(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 bp(e,t,n,r){let i=[],o=[],a="",s=0;for(let u of Te(e,n,r))u.fieldNumber===la?sa(e,u,i):u.fieldNumber===da&&u.wireType===2?a=Ce.decode(e.subarray(u.valueStart,u.valueEnd)):u.fieldNumber===pa&&u.wireType===0?s=u.varint:u.fieldNumber===sp&&sa(e,u,o);let c=oa(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:oa(o)}:null}function Rp(e,t,n){let r={symbol:"",displayName:null,kind:null,documentation:[],enclosingSymbol:null};for(let i of Te(e,t,n))if(i.wireType===2){let o=()=>Ce.decode(e.subarray(i.valueStart,i.valueEnd));i.fieldNumber===cp?r.symbol=o():i.fieldNumber===up?r.documentation.push(o()):i.fieldNumber===dp?r.displayName=o():i.fieldNumber===pp&&(r.enclosingSymbol=o())}else i.fieldNumber===lp&&i.wireType===0&&(r.kind=i.varint);return r}var Ce=new TextDecoder;function xp(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 vp(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=>ue(a)));n.push(lt(la),ue(r.length),r);let i=Buffer.from(e.symbol,"utf8");n.push(lt(da),ue(i.length),i),e.roles!==0&&n.push(ue(pa*8),ue(e.roles));let o=Buffer.concat(n);return Buffer.concat([lt(ca),ue(o.length),o])}function Pp(e,t){let n=[];for(let r of t)r.merged?n.push(vp(r)):n.push(e.subarray(r.frameStart,r.frameEnd));return Zd(Buffer.concat(n))}function Tp(e,t,n){let r="",i=null,o=null,a=null,s=[];for(let c of Te(e,t,n))c.wireType===2?c.fieldNumber===ua?r=Ce.decode(e.subarray(c.valueStart,c.valueEnd)):c.fieldNumber===rp?s.push(Rp(e,c.valueStart,c.valueEnd)):c.fieldNumber===ip?i=Ce.decode(e.subarray(c.valueStart,c.valueEnd)):c.fieldNumber===op&&(o=Ce.decode(e.subarray(c.valueStart,c.valueEnd))):c.fieldNumber===ap&&c.wireType===0&&(a=Cp(c.varint));return{relativePath:r,language:i,text:o,positionEncoding:a,declaredSymbols:s}}function Ip(e,t){let n=new Map;for(let r of e){if(r.symbol==="")throw new ne(`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 wp(e,t,n,r){let i="",o=[];for(let a of Te(e,t,n))if(a.wireType===2){if(a.fieldNumber===ua)i=Ce.decode(e.subarray(a.valueStart,a.valueEnd));else if(a.fieldNumber===np){let s=bp(e,a.fieldStart,a.valueStart,a.valueEnd);s?o.push(s):r.illegalOccurrencesDropped+=1}}return{relativePath:i,records:o}}function Ep(e,t){e.sort(Sp);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 kp(e,t,n){let[r,i,o,a]=e;if(r<0||i<0||o<r||o===r&&a<i)throw new ne(`bad enclosing range for symbol ${t} in ${n}`)}var jn=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 ne("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(Ip(a,n))}writeDeclaredSymbols(t){for(let n of t)Nn(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(`
|
|
300
|
+
`),n.enclosingSymbol===""?null:n.enclosingSymbol)}writeEnclosingRanges(t,n,r){for(let i of r){if((i.roles&fp)===0||Nn(i.symbol)||!i.enclosing)continue;let[o,a,s,c]=i.enclosing;kp(i.enclosing,i.symbol,n);let u=this.symbolIds.get(i.symbol);if(u===void 0)throw new ne(`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 xp(r,i).entries()){let s=this.nextChunkId;this.nextChunkId+=1,this.insertChunk.run(s,n,o,a[0].startLine,a[a.length-1].startLine,Pp(t,a)),this.stats.chunks+=1,this.writeMentions(s,a)}}writeMentions(t,n){let r=new Map;for(let i of n){if(Nn(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 aa(e,t,n){let r=0;for(let i of Te(e))i.fieldNumber!==ca||i.wireType!==2||(Fp(t),r+=1,r>=mp&&(r=0,await ep()),n(i.valueStart,i.valueEnd))}async function fa(e,t,n={}){let r=n.chunkSize??tp,i={documents:0,duplicateDocumentsSkipped:0,occurrences:0,illegalOccurrencesDropped:0,mergedOccurrences:0,chunks:0,mentions:0,globalSymbols:0,enclosingRanges:0},o=new Qd(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 gp)o.exec(c);let a=new jn(o,i);o.exec("BEGIN IMMEDIATE");let s=!1;try{await aa(e,n.signal,(u,l)=>{a.writeDeclarations(Tp(e,u,l))});let c=new Set;await aa(e,n.signal,(u,l)=>{let{relativePath:d,records:p}=wp(e,u,l,i);if(c.has(d))return;c.add(d);let f=a.documentIds.get(d);if(f===void 0)return;let m=Ep(p,i);a.writeEnclosingRanges(f,d,m),a.writeChunks(e,f,m,r)}),o.exec("COMMIT"),s=!0}finally{if(!s)try{o.exec("ROLLBACK")}catch{}}o.exec("BEGIN IMMEDIATE");for(let c of hp)o.exec(c);o.exec("COMMIT"),o.pragma("wal_checkpoint(TRUNCATE)")}finally{o.close()}return i}function Cp(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 ne(`unknown position encoding ${e}`)}function Fp(e){if(e?.aborted)throw new ne("SCIP SQLite conversion aborted")}function sa(e,t,n){t.wireType===2?yp(e,t.valueStart,t.valueEnd,n):t.wireType===0&&n.push(t.varint)}import{readdirSync as Dp,rmSync as Ap}from"fs";import{cpus as Op,totalmem as Lp}from"os";import{join as ma}from"path";function ga(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 _p=2048,Mp=6*1024**3,Np=2;function Bn(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_FILES??"",10);return Number.isSafeInteger(t)&&t>0?t:_p}function ha(e,t){return e>Math.floor(t*1.5)}function jp(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 Bp(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;$p(l,d,c,o,a.length,t)&&(a.push(s),s=[])}return s.length>0&&a.push(s),a}function ya(e){let t=e.targetFiles??Bn(),n=e.shardCount??Math.max(1,Math.ceil(new Set(e.inputPaths).size/Math.max(1,t)));return jp(e.inputPaths,n,e.weightOf).map((r,i)=>{let o=ma(e.projectRoot,Pr(i)),a=`${JSON.stringify({extends:`./${e.rootConfigPath}`,compilerOptions:{incremental:!1},scipQueryEmissionFiles:r},null,2)}
|
|
301
|
+
`;return{configPath:o,content:a,inputPaths:r}})}function Sa(e=process.env,t={totalmemBytes:Lp(),cpuCount:Op().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/Mp),i=Math.floor(t.cpuCount/2);return Math.max(1,Math.min(Np,r,i))}function ba(e){let t;try{t=Dp(e)}catch{return}for(let n of t)if(Tr(n))try{Ap(ma(e,n))}catch{}}function Bp(e,t){return e.length<=t&&t>1?e.map(n=>[n]):e.length>0?[e]:[]}function $p(e,t,n,r,i,o){return e>0&&t>=e&&(n>=r*(i+1)/o||t===e)}import{createHash as es}from"crypto";import{existsSync as nr,writeFileSync as rs}from"fs";import{join as $f}from"path";import{createRequire as of}from"module";import{dirname as Yn,isAbsolute as af,relative as qn,resolve as V,sep as zn}from"path";import{PositionEncoding as Vp}from"@c4312/scip";var Ra=new WeakSet,xa=Vp.UTF16CodeUnitOffsetFromLineStart;function va(e){if(Ra.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,xa);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,xa],r.length),i},Ra.add(e)}import{createHash as Up}from"crypto";var Pa=new WeakSet;function Ea(e,t,n){if(Pa.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(Lt(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)},Pa.add(e)}function Lt(e,t){if(t.isFunctionDeclaration(e))return Gp(e,t)?e:null;if(t.isExportAssignment(e)){if(e.isExportEquals||!t.isSourceFile(e.parent))return null;let r=Ot(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&&Ot(n.parent,t)===e;)n=n.parent;return n.parent&&t.isExportAssignment(n.parent)?Lt(n.parent,t):null}function Gp(e,t){return!e.name&&t.isSourceFile(e.parent)&&!!t.getModifiers(e)?.some(n=>n.kind===t.SyntaxKind.DefaultKeyword)}function Ot(e,t){for(;t.isParenthesizedExpression(e)||t.isAsExpression(e)||t.isSatisfiesExpression(e)||t.isNonNullExpression(e)||t.isTypeAssertionExpression(e);)e=e.expression;return e}function ka(e,t,n,r,i=new Set){if(e.version!=="5.9.3"||!qp(e,t,n))return null;let o=e.BuilderState?.computeDtsSignature;if(!o)return null;try{let a=[];if(o(Wp(e,t,i),n,void 0,{createHash:Ia},c=>a.push(c)),a.length!==1)return null;let s=new Vn(e,t.getTypeChecker(),r,n).capture(i);return Ia(JSON.stringify([a[0],s]))}catch{return null}}function Wp(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 qp(e,t,n){return!n.isDeclarationFile&&/\.[cm]?tsx?$/.test(n.fileName)&&e.isExternalModule(n)&&!t.getCompilerOptions().outFile&&t.getSyntacticDiagnostics(n).length===0&&!Un(e,n)}function Un(e,t){return e.isModuleDeclaration(t)||e.isExportAssignment(t)&&t.isExportEquals?!0:e.forEachChild(t,n=>Un(e,n)||void 0)===!0}var Vn=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)),zp(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)),Ta(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(Ta(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 Ta(e){let t=e?.getDeclarations();return!!t?.length&&t.every(n=>n.getSourceFile().isDeclarationFile)}function zp(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 Ia(e){return Up("sha256").update(e).digest("hex")}var $n=new WeakMap;function Ca(e,t,n){$n.has(t)||$n.set(t,Jp(e,t));let r=$n.get(t);if(!r)return null;let i=Hp(r,n);for(let o of i){if(Un(e,o))return null;for(let a of r.get(o.fileName)??[])i.add(a.source)}return i}function Hp(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 Gn(e,t,n){let r=wa(e,t),i=wa(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 wa(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 Jp(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=Kp(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:Yp(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 Yp(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 Kp(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)&&Xp(e,t.expression)&&(n=t.arguments[0]),n&&e.isStringLiteralLike(n)?n:null}function Xp(e,t){return t.kind===e.SyntaxKind.ImportKeyword||e.isIdentifier(t)&&t.text==="require"}var Fa=new WeakSet;function Da(e,t,n){if(Fa.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=Qp(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)},Fa.add(e)}function Qp(e,t,n){let r=t.parent;for(;r&&!n.isClassDeclaration(r)&&!n.isClassExpression(r);)r=r.parent;if(!r)return null;let i=Aa(e,r,n);if(!i)return null;let o=e.getResolvedSignature(t)?.declaration;return o&&n.isConstructorDeclaration(o)?Zp(e,i,o.parent,n)?o:null:i.members.some(a=>n.isConstructorDeclaration(a))?null:i}function Zp(e,t,n,r){let i=t,o=new Set;for(;i&&!o.has(i);){if(i===n)return!0;o.add(i),i=Aa(e,i,r)}return!1}function Aa(e,t,n){let i=t.heritageClauses?.find(o=>o.token===n.SyntaxKind.ExtendsKeyword)?.types[0]?.expression;return i?Oa(e,i,n,new Set):null}function Oa(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=ef(e,t,n);return i?n.isClassDeclaration(i)||n.isClassExpression(i)?i:n.isVariableDeclaration(i)&&i.initializer&&i.parent.flags&n.NodeFlags.Const?Oa(e,i.initializer,n,r):null:null}function ef(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 La=new WeakSet;function _a(e,t,n){if(La.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=>{rf(this,s,o,t);let c=Lt(s,t);c&&(t.isExportAssignment(s)||t.isFunctionDeclaration(s))&&tf(this,s,c,n,t),(t.isCallExpression(s)||t.isNewExpression(s))&&nf(this,s,n,t),t.forEachChild(s,a)};a(this.sourceFile)},La.add(e)}function tf(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:Ve(a),enclosing_range:Ve(n)})),e.document.symbols.some(s=>s.symbol===o)||e.document.symbols.push(new r.SymbolInformation({symbol:o,documentation:[`\`\`\`ts
|
|
302
|
+
${n.getText()}
|
|
303
|
+
\`\`\``]}))}function nf(e,t,n,r){let i=t.expression;if(!r.isElementAccessExpression(i))return;let o=Ot(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=Ve(o);c&&!e.document.occurrences.some(l=>l.symbol===c&&Ma(l.range,u))&&e.pushOccurrence(new n.Occurrence({symbol:c,symbol_roles:0,range:u}))}function Ve(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 Ma(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function rf(e,t,n,r){if(r.isPropertyDeclaration(t)||r.isGetAccessorDeclaration(t)||r.isSetAccessorDeclaration(t)||r.isPropertySignature(t)){let i=e.scipSymbol(t).value,o=Ve(t.name);for(let a of n.get(i)??[])!a.enclosing_range?.length&&Ma(a.range,o)&&(a.enclosing_range=Ve(t))}}var G=of(import.meta.url),sf=7,Na="0.4.0";function cf(){try{let e=ja();if(!e.available)return e;let{packageRoot:t}=e,n=G.resolve("typescript",{paths:[t]}),r=G(n),{FileIndexer:i}=G(V(t,"dist/src/FileIndexer.js")),{Input:o}=G(V(t,"dist/src/Input.js")),{Packages:a}=G(V(t,"dist/src/Packages.js")),s=G(V(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}=G(V(t,"dist/src/ScipSymbol.js")),{metaDescriptor:u,methodDescriptor:l}=G(V(t,"dist/src/Descriptor.js"));Ea(i.prototype,r,{global:c.global,metaDescriptor:u,methodDescriptor:l}),va(s.scip.Document.prototype),Da(i.prototype,r,s.scip.Occurrence),_a(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:Kn(d)}}catch(e){return{available:!1,reason:`scip-typescript document runtime unavailable: ${e instanceof Error?e.message:String(e)}`}}}function _t(){let e=ja();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function ja(){try{let e=G.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(U(e,"scip-typescript package manifest"));if(t.version!==Na)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${Na}`};let n=Yn(e),r=G.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:Va(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Ba(e){let t=e.runtime===void 0?cf():e.runtime===null?{available:!1,reason:"scip-typescript document runtime unavailable"}:{available:!0,runtime:e.runtime,producerIdentity:Kn(e.runtime)};return t.available?{available:!0,emitter:new Hn(e,t.runtime)}:t}var Hn=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 Pe;stats={initializations:0,programUpdates:0,documentsEmitted:0,documentsReused:0,documentsRemoved:0,sourceNodesReused:0,sourceNodesReplaced:0,symbolEntriesPruned:0};constructor(t,n){this.workspaceRoot=V(t.workspaceRoot),this.tsconfigPath=V(this.workspaceRoot,t.tsconfigPath),this.projectRoot=t.projectRoot??pf(this.workspaceRoot,Yn(this.tsconfigPath)),this.maxFileByteSize=t.maxFileByteSize??1024*1024,this.runtime=n,this.producerIdentity=Kn(n);let r=Wn(n.typescript,this.tsconfigPath);this.config=r,this.host=new Jn(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(H(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}=ff(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=Wn(this.runtime.typescript,this.tsconfigPath);this.config=s,this.includedFiles=new Set(s.fileNames.map(H));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(Ue(t))?.bytes??null}snapshotStats(){return{...this.stats}}initializeAndAdvance(t){let n=performance.now();this.initializeProgram();let r=Fe(t.modifiedFiles),i=Fe(t.removedFiles??[]),o=Fe(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 Pe,this.symbolTable=new Map,this.constructorTable.clear();let t=this.config??Wn(this.runtime.typescript,this.tsconfigPath);this.includedFiles=new Set(t.fileNames.map(H)),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=$(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=$(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=$(this.workspaceRoot,n);if(!this.includedFiles.has(H(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($(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=Ue(qn(this.workspaceRoot,t.fileName)),r=this.documentCache.lookup(n);if(r!==void 0){this.stats.documentsReused+=1;let c=uf(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:$a(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($(this.workspaceRoot,i));if(!o||!this.program)return null;let a=this.fileIndexer(o,new this.runtime.Document({relative_path:i,occurrences:[]})),s=ka(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 Pe;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)||!lf(t.program,this.program,n,this.workspaceRoot)||!df(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=Ca(this.runtime.typescript,this.program,i);if(!o||[...o].some(a=>!this.includedFiles.has(H(a.fileName))))return;r.push(...[...o].map(a=>Ue(qn(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=$(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=Gn(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=$(this.workspaceRoot,r),a=t.program.getSourceFile(o),s=this.program.getSourceFile(o),c=Gn(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=$(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($(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 uf(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?$a(e,s):[]}}}function $a(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 Jn=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(H(s))??o(s);let a=i.getSourceFile.bind(i);this.compilerHost={...i,getCurrentDirectory:()=>r,getSourceFile:(s,c,u,l)=>{let d=H(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(H($(n,r)),i.charCodeAt(0)===65279?i.slice(1):i)}invalidate(t){this.sourceFiles.delete(H(t))}};function lf(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=>$(r,o)));return e.getSourceFiles().every((o,a)=>{let s=t.getSourceFiles()[a];return s?.fileName===o.fileName&&(i.has(V(o.fileName))||o===s)})}function df(e,t){return t!==null&&e.size===t.size&&[...e].every(([n,r])=>t.get(n)===r)}function Wn(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,Yn(t)),i=r.errors.filter(o=>o.code!==18003);if(i.length>0)throw new Error(e.formatDiagnostics(i,e.createCompilerHost({})));return r}function Kn(e){return Va(e.packageVersion,e.typescript.version)}function Va(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${sf}`}function pf(e,t){return Ue(qn(e,t))||"."}function $(e,t){if(af(t))throw new Error(`expected a project-relative path: ${t}`);let n=V(e,t),r=e.endsWith(zn)?e:`${e}${zn}`;if(n!==e&&!n.startsWith(r))throw new Error(`path escapes the project root: ${t}`);return n}function Fe(e){return[...new Set(e.map(Ue))].sort()}function Ue(e){return e.split(zn).join("/").replace(/^\.\//,"")}function H(e){return V(e)}function ff(e){let t=Fe(e.modifiedFiles),n=Fe(e.removedFiles??[]),r=Fe(e.affectedFiles);return{modifiedFiles:t,removedFiles:n,affectedFiles:r}}import{createHash as Ua}from"crypto";import{dirname as mf,join as Ga}from"path";var J=6,gf=5,hf=2,yf="typescript-index";function Wa(e){let t=Ga(e,yf),n=ri(t);return{...n,requestDir:n.legacyRequestDir}}function Sf(e){let t=JSON.parse(e),n=t.protocolVersion,r=n===hf,i=[4,gf].includes(n),o=t.request,a=Rf(o,r||i);if(!(r||i||n===J)||!xf(t)||!Tf(a))throw new Error("TypeScript index service received an invalid mailbox request.");if(!r&&!vf(t))throw new Error("TypeScript index service received an invalid mailbox request.");if(!r)return bf(t,o,a,n);let c=je("typescript-index-v2",{id:t.id,baseGeneration:t.baseGeneration,request:o});return{protocolVersion:J,mailboxVersion:Ne,id:t.id,operationKey:c,clientId:"legacy-v2",enqueuedAtMs:t.deadlineAtMs,deadlineAtMs:t.deadlineAtMs,baseGeneration:t.baseGeneration,request:a}}function bf(e,t,n,r){let i=je(`typescript-index-v${r}`,{baseGeneration:e.baseGeneration,request:t});if(e.operationKey!==i)throw new Error("TypeScript index service received a mismatched mailbox operation identity.");return{...e,protocolVersion:J,request:n}}function Rf(e,t){return t&&e&&typeof e=="object"&&!Array.isArray(e)?{...e,removedFiles:e.removedFiles??[]}:e}function xf(e){return typeof e.id=="string"&&!!e.id&&typeof e.baseGeneration=="string"&&!!e.baseGeneration&&typeof e.deadlineAtMs=="number"&&Number.isFinite(e.deadlineAtMs)}function vf(e){return e.mailboxVersion===Ne&&Pf(e)&&typeof e.clientId=="string"&&!!e.clientId&&typeof e.enqueuedAtMs=="number"&&Number.isFinite(e.enqueuedAtMs)&&e.deadlineAtMs>=e.enqueuedAtMs}function Pf(e){return typeof e.operationKey=="string"&&/^[a-f0-9]{64}$/.test(e.operationKey)&&e.id===st(e.operationKey)}var Xn;function qa(e){try{let t=j(Ga(mf(e),"meta.json"),{inputKind:"reindex metadata",maxBytes:K}),n=Ua("sha256").update(t).digest("hex");if(Xn?.bytesHash===n)return Xn.generation;let r=nt(q(t.toString("utf8"))),i=r?Ua("sha256").update(r).digest("hex"):null;return Xn={bytesHash:n,generation:i},i}catch{return null}}function Tf(e){if(!e||typeof e!="object")return!1;let t=e,n=Qn(t.modifiedFiles)?t.modifiedFiles:null,r=Qn(t.removedFiles)?t.removedFiles:null,i=Qn(t.affectedFiles)?t.affectedFiles:null;return If(t)&&wf(n,r,i)&&Zn(t.knownDocuments,i??[])}function Zn(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))}function If(e){return e.kind==="emit-documents"&&Mt(e.tsconfigPath)&&Mt(e.projectArgument)&&Mt(e.projectIdentity)&&Mt(e.producerIdentity)}function Mt(e){return typeof e=="string"&&!!e}function wf(e,t,n){return e!==null&&new Set(e).size===e.length&&t!==null&&new Set(t).size===t.length&&n!==null&&(n.length>0||t.length>0)&&new Set(n).size===n.length}function Qn(e){return Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0)}import{randomUUID as Ff}from"crypto";import{existsSync as Ja,rmSync as er}from"fs";import{join as Ya}from"path";import{randomUUID as Ef}from"crypto";import{getHeapStatistics as kf}from"v8";import{resolve as Cf}from"path";var Nt=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=Cf(t.projectRoot),this.dbPath=t.dbPath,this.currentGeneration=t.currentGeneration,this.createEmitter=t.createEmitter??Ba,this.wallNow=t.wallNow??t.now??Date.now,this.monotonicNow=t.monotonicNow??t.now??R,Ha(t.maxActiveSessions,"maxActiveSessions"),this.maxActiveSessions=t.maxActiveSessions??8,Ha(t.softMemoryLimitMb,"softMemoryLimitMb"),this.softMemoryLimitBytes=t.softMemoryLimitMb===void 0?null:t.softMemoryLimitMb*1024*1024,this.memoryUsage=t.memoryUsage??(()=>({heapUsedBytes:process.memoryUsage().heapUsed,heapLimitBytes:kf().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=zi({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:J,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 nR=`typescript-index-${process.pid}-${Ef()}`,za=X(process.pid),rR={pid:process.pid,...za?{processIdentity:za}:{}};function Ha(e,t){if(e!==void 0&&(!Number.isInteger(e)||e<1))throw new Error(`TypeScript index ${t} must be a positive integer.`)}var Df=12e4,Af=5,Ge=class extends Error{name="TypeScriptIndexMemoryPressureError"},jt=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;emitLocally;requireService;localHost=null;constructor(t,n={}){this.projectRoot=vr(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Mf(),this.runtime=n.runtime??Nf,this.mailboxLimits=n.mailboxLimits??{},this.emitLocally=n.emitLocally,this.requireService=n.requireService===!0}request(t){let n=si(this.cacheDir),r=Wa(this.cacheDir),i=an(n.statePath);if(!Ka(i,this.projectRoot,this.runtime))return this.requestLocally(t);let o=this.runtime.now(),a=o+this.timeoutMs,s=(this.runtime.monotonicNow??R)()+this.timeoutMs,c=je("typescript-index-v6",{baseGeneration:this.baseGeneration,request:t}),u=st(c),l=ii(r,{mailboxVersion:Ne,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:a,protocolVersion:J,id:u,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??R)()<=s;){if(Ja(l.responsePath))try{return Xa(_(l.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t)}finally{er(l.responsePath,{force:!0})}let d=an(n.statePath);if(!Ka(d,this.projectRoot,this.runtime))return this.abandonPendingRequest(r,u),this.requestLocally(t);this.runtime.sleep(Af)}if(Ja(l.responsePath))try{return Xa(_(l.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t)}finally{er(l.responsePath,{force:!0})}return this.abandonPendingRequest(r,u),this.requestLocally(t)}abandonPendingRequest(t,n){try{er(Ya(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?tr(this.emitLocally(t),t):(this.localHost??=new Nt({projectRoot:this.projectRoot,dbPath:Ya(this.cacheDir,"index.db"),currentGeneration:()=>this.baseGeneration}),tr(Za(this.localHost.handle(this.baseGeneration,t),t.producerIdentity),t))}};function Ka(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===J&&n.isProcessAlive(e.pid)&&Bf(i,n)&&(!e.processIdentity||r!=null&&Me(e.processIdentity,r))}function Xa(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==J||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 Of(a)?new Ge(a):new Error(a)}return tr(Za(o.response,i.producerIdentity),i)}function Of(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 tr(e,t){if(e.producerIdentity!==t.producerIdentity)throw new Error("TypeScript index service wrote an invalid response.");if(!Zn(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 Qa(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Za(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"||!jf(o.bytesBase64)||!Qa(o.occurrences)||!Qa(o.symbols)||!Array.isArray(o.referenceFragments)||!o.referenceFragments.every(Lf)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:_f(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 Lf(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 _f(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Mf(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Df}var Nf={now:Date.now,monotonicNow:R,randomId:Ff,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:xe,readProcessIdentity:X};function jf(e){return e===null||typeof e=="string"}function Bf(e,t){return Number.isFinite(e)&&t.now()-e<=ai}var Vf=128,Uf=256;function Gf(e,t,n){let r=qf(e,t);if(!r.eligible)return r;let{previousSnapshot:i,graph:o}=r,a=n??is(i,e.currentSnapshot,e.producerIdentity,Oe(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),f=u.filter(v=>v.kind==="modified"),m=a.fallback.fullProject;if(u.length===0&&!m)return{eligible:!1,reason:"change does not affect the configured TypeScript project"};let{effectiveDeletedPaths:y,incrementalManifest:P,affected:S}=zf(e,o,s,c,u,f,p,a.fallback);if(!S.eligible)return S;let T=S.plan,b=new Set(y),w=Xf(T,t,o,b);return w?Wf(e,i,P,T,l,w,y,m,d):{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"}}function Wf(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??Be(t,e.producerIdentity),nextFragmentGeneration:Be(e.currentSnapshot,e.producerIdentity),projects:o,deletedFiles:a,replaceProject:s,dependencyGraphUnchanged:c,...u?{tsconfigPath:u.tsconfigPath,projectArgument:u.projectArgument}:{}}}function qf(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 zf(e,t,n,r,i,o,a,s){let c=s.fullProject,u=e.currentSnapshot.files.filter(m=>Ye(m.path,e.currentSnapshot.languages)==="source"&&ve(m.path)).map(m=>m.path).sort(),l=new Set(u),d=c?e.projectFiles.filter(m=>!l.has(m)).sort():[...a].sort(),p=c?r:{...n,changes:i},f=c?{eligible:!0,plan:Pt(r.changes.map(m=>m.path).sort(),new Set([...u,...d]),new Set(s.reasons))}:Yf(o,d,t,e.projectFiles);return{effectiveDeletedPaths:d,incrementalManifest:p,affected:f}}function Hf(e,t){return e.changes.filter(n=>n.inputKind==="source"&&ve(n.path)||n.inputKind==="config"&&(!Qe(n.path)||t.has(n.path))&&Jf(n)||n.inputKind==="ambient")}function Jf(e){return e.kind!=="modified"||e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function is(e,t,n,r){let i=ae(e,t),o=ln(t,n,r),a=ln(e,n,r),s={...i,changes:Hf(i,r)},c=de({...s,projectIdentityChanged:i.projectIdentityChanged||o!==a},{deletedFiles:"closure",maxChanges:Uf});return{manifest:i,compilerManifest:s,sourceChanges:i.changes.filter(u=>u.inputKind==="source"&&ve(u.path)),projectIdentity:o,fallback:c,dependencyGraphUnchanged:!c.fullProject&&Kf(i)}}function Yf(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:ts(t,n,r),reasons:[]}};let i=Tt({version:1,changes:e.filter(os),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),...ts(t,n,r)])].sort(),reasons:[]}}}function os(e){return e.kind!=="modified"?!0:e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function Kf(e){let t=e.changes.filter(n=>n.inputKind==="source"&&ve(n.path));return t.length>0&&t.every(n=>n.kind==="modified"&&!os(n))}function Xf(e,t,n,r){let i=new Map;for(let a of e.affectedFiles){let s=Qf(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(f=>ns(f,p,n)))),l=e.changedFiles.filter(p=>r.has(p)&&(c.has(p)||s.some(f=>ns(f,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 ts(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 Qf(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)=>Bt(a)-Bt(o)||o.localeCompare(a)),i=r[0];return r[1]&&Bt(r[1])===Bt(i)?null:i}function Bt(e){return e==="."?0:e.split("/").filter(Boolean).length}function ns(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 as(e){let t=R();try{if(!nr(e.previousDbPath)||!nr(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=_t();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}=Zf(e,r.producerIdentity,n);n=performance.now();let{affectedBatches:l,referenceFragmentsByFile:d,responseDurations:p,anyCold:f,assemblyMs:m,fragmentStoreMs:y,writeMs:P,retainedDocumentCount:S}=nm(e,o,r.producerIdentity,a),T=performance.now()-n,b={scipPath:e.previousShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,affectedBatches:l,retainedDocumentCount:S,completeScipUpdated:!1,durationMs:R()-t,cold:f,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((w,v)=>w+v,0),assemblyMs:m,fragmentStoreMs:y,writeMs:P}};return e.onStatus(`${o.replaceProject?"Bounded TypeScript project refresh":"Incremental TypeScript index"} emitted ${b.affectedFiles.length-b.deletedFiles.length-S} document(s), retained ${S}, 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 ${m.toFixed(0)}ms, fragments ${y.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 Ge)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 Zf(e,t,n){let r=am(e.projectRoot,e.previousSnapshot,e.currentSnapshot),i=e.projectMode==="workspace"?W(e.projectRoot,e.currentSnapshot.typescriptProjects):["."],o=Oe(i),a=r?is(r,e.currentSnapshot,t,o):void 0,s,c,u,l=new N({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath});try{s=rt(l,{includeIgnored:!1}).filter(ve).sort();let m=em(l,a);c=m.graph,u=m.dependencyGraphSnapshot}finally{l.close()}let d=performance.now()-n,p=Gf({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?i:void 0,previousSnapshot:r,currentSnapshot:e.currentSnapshot,projectFiles:s,graph:c,producerIdentity:t,rootTsconfigExists:nr($f(e.projectRoot,"tsconfig.json")),...e.previousOverlayGeneration===void 0?{}:{previousOverlayGeneration:e.previousOverlayGeneration}},i,a);if(!p.eligible)throw new Error(p.reason);let f=qa(e.previousDbPath);if(!f)throw new Error("published TypeScript base generation unavailable");return{eligibility:p,baseGeneration:f,projectFiles:s,dependencyGraphSnapshot:u,graphMs:d}}function em(e,t){let n,r;return t?.fallback.fullProject?(r=ot(e,"none")??void 0,n=new Map):t?.dependencyGraphUnchanged?n=new Map:(r=it(e),n=r.graph),{graph:n,dependencyGraphSnapshot:r}}function tm(e){return e.flatMap(t=>{let n=bi(t.affectedFiles,Vf);return(n.length>0?n:[[]]).map((i,o)=>({project:t,affectedFiles:i,removedFiles:o===0?t.removedFiles:[],firstForProject:o===0}))})}function nm(e,t,n,r){let i=new jt({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:r},{requireService:!0}),o=tm(t.projects),a=rm(e,t,n),s=[],c=new Map,u=[],l=!1,d=0,p=0,f=0,m=0,y=t.previousFragmentGeneration;for(let[P,S]of o.entries()){let T=i.request({kind:"emit-documents",tsconfigPath:S.project.tsconfigPath,projectArgument:S.project.projectArgument,projectIdentity:t.projectIdentity,producerIdentity:n,modifiedFiles:S.firstForProject?S.project.modifiedFiles:[],removedFiles:S.firstForProject?S.project.removedFiles:[],affectedFiles:S.affectedFiles,knownDocuments:S.affectedFiles.flatMap(E=>a.get(E)??[])});l||=T.cold,d+=T.retainedDocuments?.length??0,u.push(T.durationMs);let b=S.removedFiles.map(E=>({relativePath:E,bytes:null,occurrences:0,symbols:0,referenceFragments:[]})),w=[...T.fragments,...b];if(!t.replaceProject)for(let E of w)c.set(E.relativePath,E.referenceFragments);let v=om({input:e,eligibility:t,producerIdentity:n,response:T,fragments:w,batch:S,batchIndex:P,lastBatch:P===o.length-1,previousOverlayGeneration:y});p+=v.assemblyMs,m+=v.writeMs,f+=v.fragmentStoreMs,y=v.nextOverlayGeneration,v.affectedBatch.affectedFiles.length&&s.push(v.affectedBatch)}return{affectedBatches:s,referenceFragmentsByFile:c,responseDurations:u,anyCold:l,retainedDocumentCount:d,assemblyMs:p,fragmentStoreMs:f,writeMs:m}}function rm(e,t,n){let r=new Map;if(t.replaceProject||t.projects.length!==1||e.projectMode==="workspace"&&W(e.projectRoot,e.currentSnapshot.typescriptProjects).length!==1)return r;let i=im(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 im(e,t,n){let r=dt(e.cacheDir,t.previousFragmentGeneration);if(!r&&e.baseShardCurrent&&e.currentSnapshot.languages.length===1&&e.currentSnapshot.languages[0]==="typescript"){let i=_t();i.available&&i.producerIdentity===n&&(r=wi({cacheDir:e.cacheDir,generationIdentity:t.previousFragmentGeneration,producerIdentity:n,projectIdentity:t.projectIdentity,packageVersion:i.packageVersion,indexBytes:j(e.previousIndexPath,{inputKind:"accepted TypeScript index",maxBytes:Ae})}))}return r}function om(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?Pi(i.fragments):null,p=performance.now()-l,f=s===0?t.candidateAffectedScipPath:`${t.candidateAffectedScipPath}.batch-${s}.scip`,m=performance.now();d&&rs(f,d);let y=performance.now()-m,P=performance.now(),S=c?n.nextFragmentGeneration:sm({previousGenerationIdentity:u,targetGenerationIdentity:n.nextFragmentGeneration,fragments:o,retainedDocuments:i.retainedDocuments});Ii({cacheDir:t.cacheDir,previousGenerationIdentity:u,nextGenerationIdentity:S,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:f,affectedFiles:o.map(w=>w.relativePath).sort(),deletedFiles:[...a.removedFiles].sort()};return{assemblyMs:p,writeMs:y,fragmentStoreMs:T,nextOverlayGeneration:S,affectedBatch:b}}function am(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=Ze(e,a.path,a.hash);return c===void 0?a:(i=!0,{...a,semanticHash:c})});return i?{...t,files:o}:t}function sm(e){let t=es("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(es("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 rr(e){let t=_t();if(!t.available)throw new Error(t.reason);let n=Ei({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:j(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:Ae}),packageVersion:t.packageVersion});rs(e.candidateShardPath,n)}import{closeSync as cm,existsSync as $t,fstatSync as um,lstatSync as lm,openSync as dm,renameSync as ar,rmSync as We,statSync as pm,writeSync as fm}from"fs";import{cpus as mm}from"os";import{join as sr}from"path";var ir=Symbol("no-error");async function ss(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=ir,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===ir&&(s=d),c=!1}}});if(await Promise.all(u),s!==ir)throw s;return r}var cs=8*1024;function us(e,t,n){let r=Buffer.from(t,"utf8"),i=()=>dm(e,"wx",384),o;try{o=i()}catch(a){if(a.code!=="EEXIST")throw a;if(n==="skip")return null;We(e,{force:!0}),o=i()}try{fm(o,r);let a=um(o);return{path:e,content:r,device:a.dev,inode:a.ino}}finally{cm(o)}}function gm(e,t){let n=[];try{if(e.temporaryRootConfigContent!==void 0){let r=us(sr(t,"tsconfig.json"),e.temporaryRootConfigContent,"skip");r&&n.push(r)}for(let r of e.temporaryProjectConfigs??[]){let i=us(r.path,r.content,"replace");i&&n.push(i)}return n}catch(r){for(let i of n.reverse())ps(i);throw r}}function ps(e){if(e)try{let t=lm(e.path);if(!t.isFile()||t.dev!==e.device||t.ino!==e.inode||t.size!==e.content.byteLength)return;let n;try{n=j(e.path,{maxBytes:e.content.byteLength,inputKind:"temporary TypeScript index configuration"})}catch{return}if(!n.equals(e.content))return;We(e.path)}catch(t){if(t.code!=="ENOENT")throw t}}function hm(e,t,n){if(!e.defaultOutputPath)return;let r=sr(t,e.defaultOutputPath);n!==r&&$t(r)&&ar(r,n)}function ym(e,t,n){if(!e.defaultOutputPath)return null;let r=sr(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return We(i,{force:!0}),$t(r)?(ar(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Sm(e){e&&(We(e.defaultOutputPath,{force:!0}),e.backupPath&&$t(e.backupPath)&&ar(e.backupPath,e.defaultOutputPath))}function bm(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,mm().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function fs(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 ls(s,bm(s.length,r),t,n,i)),a.length>0){let u=Math.max(1,Math.min(...a.map(l=>l.boundedConcurrency)));c.push(...await ls(a,u,t,n,i))}for(let u of o)M(i,"Reindex cancelled by its owner."),c.push((await or(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 ls(e,t,n,r,i){let o=await ss(e,Math.max(1,t),s=>or(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 or(c,n,r,i)).result))}return o.map(({result:s})=>a.get(s.id)??s)}async function or(e,t,n,r){M(r,"Reindex cancelled by its owner."),n(`Indexing ${e.label} with ${e.resolvedBinary}...`),We(e.scipPath,{force:!0});let i=ym(e.config,t,e.scipPath),o=[],a=[e.binary,...e.args].join(" "),s=R();try{o=gm(e,t),e.trustedProjectTool&&Qr(t,e.trustedProjectTool);let u=Jr(e.binary,e.args),l=await gt({command:u.binary,args:u.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:vm(),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?`:
|
|
304
|
+
${d}`:""}`)}hm(e.config,t,e.scipPath)}catch(u){if(r?.aborted)throw ui(r,"Reindex cancelled by its owner.");return xm(e,u,n,s,a)}finally{Sm(i);for(let u of o.reverse())ps(u)}if(!$t(e.scipPath))return Rm(e,n,s,a);let c;try{c=pm(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:R()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},outputBytes:c},retryable:!1}}function Rm(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:R()-n,command:r,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:o}},retryable:!1}}function xm(e,t,n,r,i){let o=t instanceof Error?t.message:String(t),a=o.length<=cs?o:`${o.slice(0,cs)}
|
|
305
|
+
[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:R()-r,command:i,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:c}},retryable:Pm(t)}}function vm(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):Ui.indexer}function Pm(e){return e instanceof Gi?e.kind==="spawn"&&ds(e.cause):ds(e)}function ds(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}import{execFileSync as gs}from"child_process";import{homedir as ms,platform as Tm}from"os";import{delimiter as Im,join as Vt}from"path";function hs(e,t){let n=e.installMethods,r=at(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(!be(i.prerequisite))continue;let o=wm(i);if(t(`Installing immutable ${i.identity} via ${i.label} into ${o}; expected executable: ${r}.`),Em(e,i,r,t))return!0}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function wm(e){if(e.binary==="npm")return cr("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=cr("go",["env","GOBIN"]);if(t)return t;let n=cr("go",["env","GOPATH"]);if(n)return Vt(n.split(Im)[0],"bin")}return e.binary==="dotnet"?Vt(process.env.DOTNET_CLI_HOME??ms(),".dotnet","tools"):e.binary==="dart"?Vt(process.env.PUB_CACHE??Vt(ms(),".pub-cache"),"bin"):e.destination}function cr(e,t){try{return gs(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}function Em(e,t,n,r){try{gs(t.binary,t.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:Tm()==="win32"});let i=_e(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 vg from"better-sqlite3";import{existsSync as Pg}from"fs";import{dirname as Tg,join as Ig,resolve as wg}from"path";import{randomUUID as Cm}from"crypto";import{mkdtempSync as Fm,rmSync as Dm,statSync as Ss}from"fs";import{tmpdir as Am}from"os";import{join as bs}from"path";import{Worker as Om}from"worker_threads";function km(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function De(){return{skippedReferences:0,skippedReferenceReasons:km(),skippedReferenceSamples:[]}}function Ut(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 Lm=3e5,Rs=64*1024*1024,_m={createResultDirectory:()=>Fm(bs(Am(),"scip-query-vue-workers-")),spawn:(e,t)=>new Om(e,{workerData:t}),resultSize:e=>Ss(e).size,readResult:e=>_(e,{maxBytes:Rs,inputKind:"Vue worker result"}),removeResultDirectory:e=>Dm(e,{recursive:!0,force:!0})};function xs(e){return e.length>=8&&Ps(e.length)>1}async function vs(e,t=_m){let n=Ps(e.vueFiles.length),r=Jm(e.vueFiles),i=Km(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),a=e.timeoutMs??zm(),s=e.maxResultBytes??Hm();ys("timeoutMs",a),ys("maxResultBytes",s);let c=Cm(),u=t.createResultDirectory(),l=[],d,p,f;try{for(let y=0;y<i.length;y++){let P=y,S=i[y]??[],T=S.map(v=>v.taskId),b=bs(u,`${P}.json`),w=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:S,resultPath:b,runId:c,workerId:P,taskIds:T});l.push({workerId:P,taskIds:T,resultPath:b,handle:w,completion:Mm(w,P)})}await Nm(l,a);let m=l.sort((y,P)=>y.workerId-P.workerId).map(y=>Bm(y,c,s,t));f={occurrences:m.flatMap(y=>y.occurrences),...De()};for(let y of m)Ut(f,y)}catch(m){d=m}finally{p=await Qm(l,t,u,d)}if(p)throw p;if(d!==void 0)throw d;if(!f)throw new Error("Vue workers completed without producing a merged result.");return f}function Mm(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 Nm(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 jm(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function Bm(e,t,n,r){let i=Zm(e,n,r);if(!qe(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(!Wm(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||!$m(i.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return i.result}function $m(e){if(!qe(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(Vm)||!Y(e.skippedReferences)||!qe(e.skippedReferenceReasons))return!1;for(let t of["missing-source-file","missing-service-script","no-definition","same-file-definition","unindexed-definition"])if(!Y(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(Um)}function Vm(e){return qe(e)&&typeof e.sourceFile=="string"&&Y(e.sourceLine)&&Y(e.sourceStartChar)&&Y(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&Y(e.symbolId)}function Um(e){return qe(e)&&typeof e.sourceFile=="string"&&Y(e.sourceLine)&&Y(e.sourceStartChar)&&Y(e.sourceEndChar)&&typeof e.token=="string"&&Gm(e.reason)}function Gm(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function Y(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wm(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function ys(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function qm(e){return e instanceof Error?e.message:String(e)}function Ps(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 zm(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:Lm}function Hm(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:Rs}function Jm(e){let t=Ym(),n=[];for(let r of e){let i=Ts(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 Ym(){return Number.POSITIVE_INFINITY}function Km(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Xm(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 Xm(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Ts(e.fileName)-e.startOffset)}function Ts(e){try{return Ss(e).size}catch{return 1}}async function Qm(e,t,n,r){let i=await jm(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: ${qm(o[0])}`)}}function Zm(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 eg}from"path";function ur(e,t,n){let r=tg(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(`
|
|
306
|
+
`),u=(r.get(eg(t,i.fileName).replaceAll("\\","/"))??[]).filter(d=>{if(d.name!==i.name)return!1;let p=Hr([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 tg(e){let t=e.prepare(`
|
|
307
|
+
SELECT d.relative_path AS relativePath, d.position_encoding AS encoding,
|
|
308
|
+
der.start_line AS startLine, der.start_char AS startChar,
|
|
309
|
+
der.end_line AS endLine, der.end_char AS endChar,
|
|
310
|
+
der.symbol_id AS symbolId, gs.display_name AS displayName, gs.symbol AS symbol
|
|
311
|
+
FROM defn_enclosing_ranges der
|
|
312
|
+
JOIN documents d ON d.id = der.document_id
|
|
313
|
+
JOIN global_symbols gs ON gs.id = der.symbol_id
|
|
314
|
+
ORDER BY d.relative_path, der.start_line, der.start_char, der.symbol_id
|
|
315
|
+
`).all(),n=new Map;for(let r of t){let i=r.displayName??zr(r.symbol),o=n.get(r.relativePath)??[];o.push({...r,name:i}),n.set(r.relativePath,o)}return n}import{createRequire as ng}from"module";import{existsSync as rg}from"fs";import{dirname as Is,extname as ig,join as ws,relative as og,resolve as ag}from"path";import{pathToFileURL as sg}from"url";function cg(e){e.transaction(()=>{e.prepare(`
|
|
316
|
+
DELETE FROM mentions
|
|
317
|
+
WHERE chunk_id IN (
|
|
318
|
+
SELECT c.id
|
|
319
|
+
FROM chunks c
|
|
320
|
+
JOIN documents d ON d.id = c.document_id
|
|
321
|
+
WHERE d.language = 'vue' OR d.relative_path LIKE '%.vue'
|
|
322
|
+
)
|
|
323
|
+
`).run(),e.prepare(`
|
|
324
|
+
DELETE FROM chunks
|
|
325
|
+
WHERE document_id IN (
|
|
326
|
+
SELECT id
|
|
327
|
+
FROM documents
|
|
328
|
+
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
329
|
+
)
|
|
330
|
+
`).run()})()}function Es(e,t){return e.prepare(`
|
|
331
|
+
SELECT relative_path AS relativePath
|
|
332
|
+
FROM documents
|
|
333
|
+
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
334
|
+
ORDER BY relative_path
|
|
335
|
+
`).all().map(r=>ag(t,r.relativePath))}function ks(e,t){let{vueCore:n,ts:r,volarTs:i}=ug(e),{parsed:o,vueOptions:a}=lg(n,r,t),s=Is(t),c=n.createVueLanguagePlugin(r,o.options,a,f=>f),u=dg(n,r,c),l=pg(s,o),{languageServiceHost:d}=i.createLanguageServiceHost(r,r.sys,u,f=>f,l),p=r.createLanguageService(d);return{ts:r,language:u,languageService:p,fileNames:o.fileNames,configDir:s}}function ug(e){let t=ng(sg(ws(e,"package.json")).href);return{vueCore:lr(t,"@vue/language-core",e),ts:lr(t,"typescript",e),volarTs:lr(t,"@volar/typescript",e)}}function lg(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,Is(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function dg(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!rg(o))return;let a=_(o,{maxBytes:Xt,inputKind:"Vue language-service source file"});r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??hg(o))});return r.current=i,i}function pg(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function lr(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 Cs(e,t,n){let r=bg(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
|
|
336
|
+
INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
|
|
337
|
+
VALUES (?, ?, ?, ?)
|
|
338
|
+
`),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let l=re(t,u),d=js(r.name,r.version,l);o.run(d,"default",7,`Vue component|${l}`);let p=Rg(i,r,t,u);p&&(a++,s.set(u,p))}})(),{get(u){return s.get(u)??null},syntheticSymbols:a}}function Fs(e,t,n,r,i){return e.transaction(()=>(cg(e),fg(e,t,n,r),mg(e,i)))()}function fg(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
|
|
339
|
+
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
340
|
+
VALUES (?, ?, ?, ?, X'00')
|
|
341
|
+
`),a=e.prepare(`
|
|
342
|
+
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
343
|
+
VALUES (?, ?, 1)
|
|
344
|
+
`);for(let s of n){let c=r.get(s);if(!c)continue;let u=re(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 Ds(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(dr(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function As(e){let t=new Set,n=[];for(let r of e){let i=Os(r);t.has(i)||(t.add(i),n.push(r))}return n}function Os(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function mg(e,t){let n=Sg(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
|
|
345
|
+
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
346
|
+
VALUES (?, ?, ?, ?, X'00')
|
|
347
|
+
`),i=e.prepare(`
|
|
348
|
+
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
349
|
+
VALUES (?, ?, 0)
|
|
350
|
+
`),o=new Set,a=0,s=0;for(let c of t){let u=Os(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*Ls(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 _s(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function dr(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function gg(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 Ms(e,t){return re(e,t).startsWith("node_modules/")}function re(e,t){return og(e,t).replaceAll("\\","/")}function hg(e){switch(ig(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 Ns(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=_(t,{maxBytes:Xt,inputKind:"Vue source file"}),r={text:n,lineStarts:yg(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:gg}}function yg(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function Sg(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 bg(e){try{let t=JSON.parse(_(ws(e,"package.json"),{maxBytes:K,inputKind:"project package manifest"}));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function Rg(e,t,n,r){let i=re(n,r),o=js(t.name,t.version,i);return e.get(o)?.id??null}function js(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}async function Eg(e){return ke(le(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),kg(e)}async function kg(e){let t=wg(e.projectRoot,e.tsconfig);if(!Pg(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new vg(e.dbPath);try{let r=Es(n,e.projectRoot),i=Ig(Tg(e.dbPath),"augment-vue-meta.json");return await Vo({cachePath:i,readFingerprint:()=>Ag(n,e.projectRoot,e.tsconfig),compute:()=>Cg({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 Cg(e){let t=Cs(e.db,e.projectRoot,e.vueFiles),n=xs(e.vueFiles)?await vs({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles}):Dg(e,t);return Fg(e,t,n)}function Fg(e,t,n){let r=As(n.occurrences),i=Fs(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:Vg(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:$g(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function Dg(e,t){let n=Og({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return Lg({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function Ag(e,t,n){let r=e.prepare(`
|
|
351
|
+
SELECT
|
|
352
|
+
(SELECT COUNT(*) FROM documents) AS documents,
|
|
353
|
+
(SELECT COUNT(*) FROM global_symbols) AS symbols,
|
|
354
|
+
(SELECT COUNT(*) FROM chunks) AS chunks,
|
|
355
|
+
(SELECT COUNT(*) FROM mentions) AS mentions,
|
|
356
|
+
(SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
|
|
357
|
+
(SELECT MAX(id) FROM chunks) AS maxChunkId,
|
|
358
|
+
(SELECT MAX(id) FROM global_symbols) AS maxSymbolId
|
|
359
|
+
`).get();return{version:4,tsconfig:n,files:Dr(t),db:r}}function Og(e){let t=Ns();return{projectRoot:e.projectRoot,context:ks(e.projectRoot,e.configPath),symbolLookup:ur(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function Lg(e){let t=[],n=De(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=_g(e,i);t.push(...o.occurrences),Ut(n,o)}return{occurrences:t,...n}}function _g(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return Bs(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 Bs(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=re(e.projectRoot,t.fileName),s=[...Ls(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:Gg(s),processedStarts:new Set};return Mg({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function Mg(e){let t=[],n=De();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||Ng(e.sourceInfo.text,r.start))continue;let i=_s(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(l=>!Ms(e.projectRoot,l.fileName));if(!a){pr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=re(e.projectRoot,a.fileName),c=jg(e.sourceFile,r.text,s);if(c){pr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=Ds(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){pr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}$s(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),Ug(t,e,r,i,s,u)}return{occurrences:t,...n}}function Ng(e,t){let n=e.lastIndexOf(`
|
|
360
|
+
`,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function jg(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Bs(e,t,n){let r=De();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:re(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function pr(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 fr(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 Bg(e,t){let n=fr(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=fr(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function $g(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(...fr(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function Vg(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return Bg(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function Ug(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of Wg(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&&($s(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function $s(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 Gg(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function Wg(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=qg(r,u.textSpan.start,o,i.text);l!==null&&s.push(l)}return s}function qg(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=dr(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}function Kg(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 Xg(e,t,n){let r=yc(t),i=di(k(h(e),"cache-lifecycle.lock"),{waitMs:r?1e3:3e4});if(!i)throw n?.(),new we(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 Qg(e,t){let n=fh(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 Us(e,t){ch(e);let n=Jo(e.paths.outputDb,t);n.state==="failed"&&e.onStatus(`Warning: reindex succeeded, but activity telemetry was not recorded: ${n.reason}`),Er(e.projectRoot,h(e.paths.outputDb))}function Zg(e,t,n,r,i,o){let a=Yt({trigger:e.trigger,result:"failed",start:n,monotonicStart:r,error:i instanceof Error?i.message:String(i)});xc(t.metaPath,a);let s=Yo(t.outputDb,a);s.state==="failed"&&o(`Warning: failed reindex activity telemetry was not recorded: ${s.reason}`)}function eh(e,t){let n=e.languages??un(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 th(e){return e.maxHeapMb??Ri(process.env.NODE_OPTIONS)??8192}async function ec(e){let t=rc(e);return et(e.projectRoot,h(t.outputDb),()=>nh(e))}async function nh(e){let{projectRoot:t,onStatus:n=console.log}=e,r=th(e),i=e.skipAutoInstall===!0||e.installMissing!==!0,o=rc(e),a=Date.now(),s=R();qt(h(o.outputScip),{recursive:!0}),qt(h(o.outputDb),{recursive:!0});let c=eh(e,n),u=Ht(o.metaPath),l=g("reindex.fingerprint",()=>Or(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath},u,e.changeJournal,cn(o.outputDb)),{languages:c.length}),d=l.fingerprint;Kg(e,l,u,n);let p=await rh({opts:e,paths:o,languages:c,fingerprint:d,onStatus:n}),f=p.snapshot,m=p.releaseBuildLock,y=Xg(o.outputDb,e.trigger,m),P;try{P=await B("reindex.lock",()=>ny(k(h(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:n}),{languages:c.length})}catch(b){throw y.release(),m?.(),b}let S=null,T=lo();try{l.mode==="delta"&&cn(o.outputDb)!==e.changeJournal?.baseGeneration&&(d=tt(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"},f=void 0,m?.(),m=void 0,n("Project fingerprint used full scan: accepted-generation-changed-before-lock")),_i(o.outputDb,o.outputScip,o.metaPath),Qg(o.outputDb,n);let b=null,w=await B("reindex.reuse-check",async()=>(b=await lh({opts:e,paths:o,languages:c,fingerprint:d,start:a,monotonicStart:s,onStatus:n}),b),()=>({languages:c.length,reused:b!==null}));if(w)return Us({snapshot:f,paths:o,projectRoot:t,fingerprint:d,onStatus:n},w),w;oo()&&await B("reindex.scip-cli-ready",()=>Gh(i,n));let v=ph(o);S=v.runDir;let E,x=await B("reindex.fresh",async()=>(E=await mh({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 Us({snapshot:f,paths:o,projectRoot:t,fingerprint:d,onStatus:n},x),x}catch(b){throw Zg(e,o,a,s,b,n),b}finally{S&&fe(S,{recursive:!0,force:!0}),P(),y.release(),m?.()}}async function rh(e){let{opts:t,paths:n,languages:r,fingerprint:i,onStatus:o}=e,a=t.projectRoot;if(!oh(t,n,a))return{snapshot:void 0,releaseBuildLock:void 0};let c=Xe(a),u=c?.clean?ft(c,i):void 0;if(c&&!c.clean&&!nc(n))return tc({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=dn(u);if(l)return ah(l,u,n,i,a,o),{snapshot:u,releaseBuildLock:void 0};ih(c,r,t,n,i,a,o);let d=await Bi(u);return d.kind==="owner"?{snapshot:u,releaseBuildLock:d.release}:(sh(d,u,n,a,o),{snapshot:u,releaseBuildLock:void 0})}function ih(e,t,n,r,i,o,a){e&&!nc(r)&&tc({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 oh(e,t,n){return e.skipIfUnchanged!==!1&&!Mi(n,t.outputDb)&&Vs(t.outputScip)===Vs(k(h(t.outputDb),"index.scip"))}function ah(e,t,n,r,i,o){if(!uh(n,r))try{mt({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: ${me(a)}`)}}function sh(e,t,n,r,i){if(e.kind==="generation-ready"){let o=dn(t);if(o)try{mt({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: ${me(a)}`)}}else i("Shared generation build lock timed out; continuing with an isolated local reindex")}function tc(e){let t=Ni(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{mt({snapshot:t.snapshot,manifest:t.manifest,targetCacheDir:h(e.paths.outputDb),targetProjectRoot:e.projectRoot,persistLease:!1}),Vi(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: ${me(n)}`)}}function ch(e){if(e.snapshot)try{let t=Xe(e.projectRoot),n=t?ft(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=ji({snapshot:e.snapshot,sourceCacheDir:h(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let i=Xe(e.projectRoot);return(i?ft(i,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}});$i(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: ${me(t)}`)}}function uh(e,t){if(!A(e.outputScip)||!A(e.outputDb)||Rc(e.metaPath,t)===null)return!1;let n=z(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function nc(e){if(!A(e.outputScip)||!A(e.outputDb)||!ie(e.metaPath))return!1;let t=z(e.outputDb,e.metaPath);return t.state!=="invalid"&&t.state!=="drifted"}function me(e){return e instanceof Error?e.message:String(e)}async function hr(e,t,n,r,i,o,a,s=!1,c=!1){try{await $o(fo({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 rc(e){let t=e.outputScip??k(e.projectRoot,"index.scip"),n=e.outputDb??k(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:k(h(n),"meta.json")}}async function lh(e){let t=z(e.paths.outputDb,e.paths.metaPath),n=Rc(e.paths.metaPath,e.fingerprint);if(e.opts.skipIfUnchanged===!1||!A(e.paths.outputScip)||!A(e.paths.outputDb)||n===null||t.state==="invalid"||t.state==="drifted")return null;let r=ut(e.paths.outputDb,e.fingerprint,e.languages);if(r.state!=="complete")return e.onStatus(yr("Accepted SQLite index",r)),null;ke(le(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),pn({projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,fingerprint:e.fingerprint}),await hr(e.opts.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0),z(e.paths.outputDb,e.paths.metaPath).state==="drifted"&&(pt(e.paths.outputDb,e.paths.metaPath),e.onStatus("Published refreshed SQLite generation after post-index augmentation")),n==="operational-config-compatible"&&(ly(e.paths.metaPath,e.fingerprint,e.languages,e.opts),pt(e.paths.outputDb,e.paths.metaPath),e.onStatus("Migrated operational .scipquery.json metadata without rerunning language indexers."));let i=R()-e.monotonicStart,o=Yt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return xc(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:dh(e.paths,e.languages,e.opts,e.fingerprint)}}function dh(e,t,n,r){let i=Sr(r,t,n);return t.map(o=>({id:o,language:o,reused:!0,strategy:"reused",fingerprint:ze(i[o]),outputBytes:ge(br(e.outputDb,o)),durationMs:0}))}function ph(e){let t=Jg(k(h(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:k(t,Gt(e.outputScip)),tempOutputDb:k(t,Gt(e.outputDb)),tempMetaPath:k(t,Gt(e.metaPath))}}function fh(e){let t=[],n;try{n=Ks(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[me(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{fe(k(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${me(o)}`)}return{removed:r,errors:t}}async function mh(e){let t={...process.env,NODE_OPTIONS:xi(process.env.NODE_OPTIONS,e.maxHeapMb)},n,r=await B("reindex.language-indexers",async()=>(n=await hh(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(", ")}`),gh({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let f=await B("reindex.publish",()=>jh(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),m=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(m/1e3).toFixed(1)}s`),{languages:i.map(y=>y.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:m,reused:!0,skipped:o,lastRefresh:f,shards:c,writeTelemetry:e.writeTelemetry}}let d=await B("reindex.publish",()=>Mh(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(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:p,reused:!1,skipped:o,lastRefresh:d,shards:c,writeTelemetry:e.writeTelemetry}}function gh(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!A(e.run.paths.outputScip)||!A(e.run.paths.outputDb))return!1;let t=z(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 hh(e,t){let n=e.opts.skipIfUnchanged===!1,{classification:r,reusableOutputs:i,reused:o}=yh(e,n),{incrementalTypeScript:a,typescriptIncrementalUnavailableReason:s}=Sh(e,r,n),c=new Set(a?["typescript"]:[]);Rh(e,o,c,s);let u=xh(e,r,!!a||o.has("typescript"),n),{preparedRuns:l,skippedLanguages:d,languageOutputScipPaths:p}=Wh({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}),f=u?l.filter(E=>E.language!=="typescript"||u.missedProjectIds.has(E.id)):l,m=await fs(f,e.projectRoot,e.onStatus,e.opts.indexerConcurrency,e.opts.signal);vh(e,f,m);let y=Ph(e,u,m,p),P=[...m,...y],{indexedOutputs:S}=Xh(P,d),T=a?[{language:"typescript",scipPath:a.scipPath}]:[],b=[...i,...T,...S];Qh(b,d,e.languages,e.opts.allowPartial,e.onStatus);let w=Th(a),v=Ah(r,[...m,...w],u?{outputDb:e.paths.outputDb,classification:u.classification}:void 0,s);return{indexedOutputs:b,skippedLanguages:d,reusedLanguages:[...o],languageFingerprints:_h(r,e.languages),shards:v,typescriptProjectShardContext:u?{projects:u.allProjects,fingerprints:u.fingerprints}:void 0,incrementalTypeScript:a??void 0}}function yh(e,t){let n=Ch({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 Sh(e,t,n){let r=t.get("typescript"),{incrementalGenerationUsable:i,baseShardCurrent:o,previousOverlay:a}=bh(e.paths),s;return n&&r&&!r.reused&&(s="forced reindex rebuilds from the compilers"),{incrementalTypeScript:!n&&r&&!r.reused&&i?as({projectRoot:e.projectRoot,cacheDir:h(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:r.scipPath,candidateShardPath:he(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:he(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:o,previousSnapshot:Ht(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,...a,onStatus:e.onStatus,onUnavailable:u=>{s=u}}):null,typescriptIncrementalUnavailableReason:s}}function bh(e){let t=z(e.outputDb,e.metaPath),n=ie(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 Rh(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 xh(e,t,n,r){let i=n?void 0:Ih(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 vh(e,t,n){if(jr())for(let r of n)Br({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 Ph(e,t,n,r){let i=[];if(t){Eh(e.paths.outputDb,n,e.writeTelemetry);let o=r.typescript??e.tempPaths.tempOutputScip;i=kh({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:o,reusedProjects:t.reusedProjects,writeTelemetry:e.writeTelemetry})}return i}function Th(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:ge(e.scipPath)??void 0,producedOutputBytes:ge(e.affectedScipPath)??void 0}]:[]}function Ih(e,t){let n=t.get("typescript");if(!n||n.reused||n.cacheIntegrityFailed||e.opts.typescriptProjectMode!=="workspace")return;let r=W(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=ta(e.projectRoot,r),o=Qo(n.fingerprint.files,r),a=Zo(r,i),s=ea(r,o,a),c=ie(e.paths.metaPath),l=wh(c,s,m=>A(Jt(e.paths.outputDb,m))),d=[...l.entries()].filter(([,m])=>m.reused).map(([m])=>m),p=new Set(d),f=new Set(r.filter(m=>!p.has(m)).map(m=>`typescript:${m}`));return{allProjects:r,fingerprints:s,classification:l,reusedProjects:d,missedProjectIds:f}}function wh(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===ye&&oe(e.fingerprint)?.typescriptSymbolIdentityVersion===6&&nn(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(D(a)!==D(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 Eh(e,t,n){for(let r of t){if(r.skipped||!r.id.startsWith("typescript:"))continue;let i=r.id.slice(11),o=Jt(e,i);qt(h(o),{recursive:!0}),ee(n,Z(r.scipPath,o,void 0,{shareImmutable:!0}))}}function kh(e){return e.reusedProjects.map((t,n)=>{let r=Jt(e.outputDb,t),i=he(e.tempOutputScip,"typescript-project-cached",n);return ee(e.writeTelemetry,Z(r,i,void 0,{shareImmutable:!0})),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:ge(i)??void 0}})}function Ch(e){let t=ie(e.paths.metaPath),n=Sr(e.projectFingerprint,e.languages,e),r=t&&A(e.paths.outputDb)?ut(e.paths.outputDb,e.projectFingerprint,e.languages):null,i=new Map;for(let o of e.languages){let a=br(e.paths.outputDb,o),s=n[o];i.set(o,Fh(e.projectRoot,o,s,a,t,r))}return i}function Fh(e,t,n,r,i,o){return i?i.version!==ye?{reused:!1,reason:`metadata version ${String(i.version??"unknown")} predates per-language shard caching`,fingerprint:n,scipPath:r}:!nn(i).languageShardReuse||!i.languageFingerprints?{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:n,scipPath:r}:Dh(e,t,n,r,i.languageFingerprints[t],o):{reused:!1,reason:"no reindex metadata found",fingerprint:n,scipPath:r}}function Dh(e,t,n,r,i,o){if(!i)return{reused:!1,reason:"no cached fingerprint for this language",fingerprint:n,scipPath:r};if(!A(r))return{reused:!1,reason:"cached shard file missing on disk",fingerprint:n,scipPath:r};let a=t==="typescript"?sy(e,i):i;return D(a)!==D(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:yr("accepted SQLite index",o),cacheIntegrityFailed:!0,fingerprint:n,scipPath:r}:{reused:!0,fingerprint:n,scipPath:r}}function Ah(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:ze(a.fingerprint),outputBytes:ge(a.scipPath),durationMs:0});if(Oh(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:ze(a.fingerprint),outputBytes:ge(Jt(n.outputDb,o)),durationMs:0});return i}function Oh(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:Lh(c,a),outputBytes:o.outputBytes??null,producedOutputBytes:o.producedOutputBytes,durationMs:o.durationMs,command:o.command})}}function Lh(e,t){return e?ze(e.fingerprint):t?ze(t.fingerprint):"unknown"}function ze(e){return Hg("sha256").update(D(e)).digest("hex").slice(0,16)}function ge(e){try{return Qs(e).size}catch{return null}}function _h(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}async function Mh(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 x=Uh({run:e,indexedOutputs:n,incrementalTypeScript:s,typescriptReused:i.includes("typescript")});return Ws(e.paths.outputDb,x,e.writeTelemetry),qs(x,e.tempPaths.tempOutputScip,e.onStatus)}));let l=await B("reindex.publish.sqlite-output",()=>Zh({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..."),rr({cacheDir:h(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let x=n.map(O=>O.language==="typescript"?{language:O.language,scipPath:s.candidateScipPath}:O);return Ws(e.paths.outputDb,x,e.writeTelemetry),u=qs(x,e.tempPaths.tempOutputScip,e.onStatus),u}}));M(e.opts.signal,"Reindex cancelled by its owner.");let d=my(l),{metadata:p,pruneProjects:f}=ac({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:o,typescriptProjectShardContext:a});p.scipCompanion=d?"deferred":"current",He(e.tempPaths.tempMetaPath,p);let m=g("reindex.publish.auxiliary-documents",()=>ke(le(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus})),y=g("reindex.publish.source-checkpoints",()=>pn({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,fingerprint:e.fingerprint,changedFiles:s?.changedFiles}));await B("reindex.publish.runtime-boundaries",async()=>{let x=s?.plan.mode==="full-project";x&&e.onStatus("Rebuilding compiler-derived runtime-boundary relationships while retaining unchanged per-file extraction facts."),await hr(e.projectRoot,e.tempPaths.tempOutputDb,e.tempPaths.tempOutputScip,e.onStatus,!1,x?s?.changedFiles:s?.affectedFiles,k(h(e.paths.outputDb),Mr),x,l.mode==="incremental"&&l.compilerFactsUnchanged===!0&&m.result.inserted===0&&y===0)});let P=g("reindex.publish.sqlite-layout",()=>Cn(e.tempPaths.tempOutputDb,{analyze:Nh(s,l.mode)}));py(P,e),g("reindex.publish.coverage",()=>cc(e,e.tempPaths.tempOutputDb,n.map(x=>x.language)));let S,T=null;l.mode==="incremental"&&s&&g("reindex.publish.reference-fragments",()=>{if(s.dependencyGraphUnchanged){let L=new N({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});try{T=rn(L),e.onStatus("Preserved exact TypeScript reference fragments and dependency relationships because only trivia changed.")}finally{L.close()}return}let x=null,O=null;try{x=g("reindex.publish.reference-fragments.open-candidate",()=>new N({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip})),O=g("reindex.publish.reference-fragments.open-evidence",()=>new N({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip})),S=s.dependencyGraphSnapshot?g("reindex.publish.reference-fragments.dependency-graph",()=>Wr(x,s.dependencyGraphSnapshot,Gs(s,l),s.deletedFiles))??void 0:void 0;let L=new Set(s.deletedFiles),vc=L.size===0?s.referenceFragmentsByFile:new Map([...s.referenceFragmentsByFile].filter(([Pc])=>!L.has(Pc))),Je=g("reindex.publish.reference-fragments.seed",()=>ci(x,e.fingerprint,vc,O,S,new Set(s.affectedFiles)));e.onStatus(`Cached exact TypeScript reference fragments for ${Je.affectedFiles} affected document(s) and carried ${Je.carriedFiles} unaffected document(s) forward.`),Je.skippedAffectedFiles>0&&e.onStatus(`Skipped exact TypeScript reference fragment prefill for ${Je.skippedAffectedFiles} affected document(s) whose semantic identity was unavailable.`)}catch(L){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${L instanceof Error?L.message:String(L)}.`)}finally{x?.close(),O?.close()}});let b=Ht(e.paths.metaPath);l.mode==="incremental"&&s||await ic({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousSnapshot:b,currentSnapshot:e.fingerprint,onStatus:e.onStatus});let w=g("reindex.publish.affected-shadow",()=>l.mode==="incremental"&&s?ty(s,l.changedDocumentPaths):Tn({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=Yt({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(x=>x.language),skipped:[...r]});p.lastRefresh=v,p.updatedAt=v.completedAt,g("reindex.publish.metadata",()=>{sc(e),uc(e.paths.outputDb,f),He(e.tempPaths.tempMetaPath,p)});let E=g("reindex.publish.generation-handoff",()=>Li({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 fy(E,e),l.mode==="incremental"&&s&&g("reindex.publish.dependency-graph",()=>{let x=null;try{x=new N({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let O=Gs(s,l),L=!1;s.dependencyGraphUnchanged?L=yy(x,T,e):s.dependencyGraphSnapshot?L=Gr(x,s.dependencyGraphSnapshot,O,S):it(x),s.dependencyGraphUnchanged||e.onStatus(L?`Carried the dependency graph forward by replacing ${O.length} changed dependency owner(s).`:"Materialized a fresh dependency graph for the accepted generation because no compatible prior graph was available.")}catch(O){e.onStatus(`Dependency graph carry-forward unavailable: ${O instanceof Error?O.message:String(O)}. The next graph consumer will rebuild it.`)}finally{x?.close()}}),g("reindex.publish.cleanup",()=>{Ci(h(e.paths.outputDb),l.mode==="incremental"&&l.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),Ti(h(e.paths.outputDb),s?.completeScipUpdated?[s.nextFragmentGeneration]:[])}),g("reindex.publish.shadow-telemetry",()=>oc(e.paths.outputDb,w,e.onStatus)),v}function Gs(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 Nh(e,t){return t!=="incremental"||!e||e.plan.mode==="full-project"?!0:e.affectedFiles.length*20>=e.projectFileCount}async function jh(e,t,n,r,i,o){let a=Ht(e.paths.metaPath),s=null;try{ee(e.writeTelemetry,Z(e.paths.outputDb,e.tempPaths.tempOutputDb))}catch(p){s=xo("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}ke(le(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await hr(e.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0);let c=Cn(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(", ")}`),cc(e,e.paths.outputDb,t.map(p=>p.language)),s==null&&await ic({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,onStatus:e.onStatus}),s??=Tn({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=Yt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=ac({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:u});return l.scipCompanion=Bh(e.paths),sc(e),uc(e.paths.outputDb,d),He(e.paths.metaPath,l),pt(e.paths.outputDb,e.paths.metaPath),oc(e.paths.outputDb,s,e.onStatus),u}function Bh(e){let t=ie(e.metaPath)?.scipCompanion;if(t)return t;let n=z(e.outputDb,e.metaPath);return n.state==="current"&&n.generation.publication?.scipCompanion==="deferred"?"deferred":"current"}async function ic(e){if(!A(e.previousDbPath))return;let t=ae(e.previousSnapshot,e.currentSnapshot);if(t.changes.length===0||de(t).fullProject)return;let n=null;try{if(n=new N({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),ot(n))return;let r=await B("reindex.publish.affected-shadow.warm-sources",()=>qr(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 Ht(e){return oe(ie(e)?.fingerprint)}function oc(e,t,n){try{Po(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 ac(e){let t=$h({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:ye,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 sc(e){M(e.opts.signal,"Reindex cancelled by its owner.");let t=Ar(e.projectRoot,e.fingerprint);if(D(t)===D(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=>D(n.get(o))!==D(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 cc(e,t,n){let r=ut(t,e.fingerprint,n);if(r.state!=="complete")throw new Error(`${yr("Candidate SQLite index",r)} Refusing to publish it.`)}function yr(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 $h(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=ie(e.metaPath),n=t?.version===ye?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 uc(e,t){let n=bc(e);if(t===null){fe(n,{recursive:!0,force:!0});return}let r;try{r=Ks(n)}catch{return}for(let i of Vh(r,t))fe(k(n,i),{force:!0})}function Vh(e,t){let n=new Set(t.map(r=>`${_n(r)}.scip`));return e.filter(r=>!n.has(r))}function Uh(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=z(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":ie(e.run.paths.metaPath)?.scipCompanion==="deferred")||!r)return[...e.indexedOutputs];let o=he(e.run.tempPaths.tempOutputScip,"typescript-deferred",0);return e.run.onStatus("Materializing the deferred whole TypeScript SCIP companion for complete publication..."),rr({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 Ws(e,t,n){for(let r of t){let i=br(e,r.language);qt(h(i),{recursive:!0}),r.scipPath!==i&&ee(n,Z(r.scipPath,i,void 0,{shareImmutable:!0}))}}async function Gh(e,t){let n=hn();if(n){let r=hy(n,e,t);r&&await r;return}if(Zs()==="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.
|
|
361
|
+
To install the reviewed version, run: scip-query reindex --install-missing
|
|
362
|
+
Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!await co(t))throw new Error(`The scip CLI is required but could not be installed.
|
|
363
|
+
Install manually from: https://github.com/sourcegraph/scip/releases/tag/${C}`)}function Wh(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?he(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=qh({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?lc(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function qh(e){if(e.language!=="typescript")return[Wt({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.typescriptProjectMode==="workspace",n=t?e.preDiscoveredTypeScriptProjects??W(e.projectRoot,e.typescriptProjects):["."];return n.length===0?[Wt({...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?he(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=zh(e,c);if(u)return u}return[Wt({...c,...t?{projectPath:r}:{}})]}))}function zh(e,t){if(e.trustProjectTools&&on(Et("typescript"),e.projectRoot))return null;let n=Bn(),r=Ir(e.projectRoot,"single");if(!r||!ha(r.size,n))return null;ba(e.projectRoot);let i=Sa(),o=ya({projectRoot:e.projectRoot,rootConfigPath:"tsconfig.json",inputPaths:[...r],targetFiles:n,weightOf:s=>{let c=1;try{c=Qs(k(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.`),ga(o,a).map((s,c)=>{let u=Wt({...t,id:`typescript-compiler-worker:${c}`,label:`typescript compiler worker ${c+1}/${a} (${s.length} emission batches)`,scipPath:he(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 mr(e,t){return e.onStatus(`Skipping ${e.language}: ${t}`),{skipped:{language:e.language,reason:t}}}function Hh(e,t,n){return Kr(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...`),hs(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 Jh(e,t,n){return e.trustProjectTools&&n?Xr(t,e.projectRoot):null}function Yh(e,t){let n=at(t),r=on(t,e.projectRoot),i=Jh(e,t,r),o=_e(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 mr(e,s)}if(!i&&!o){let s=Hh(t,n,e);if(s!==null)return mr(e,s)}let a=i?.canonicalPath??_e(t);if(!a){let s=`${n} was not found after installation checks.`;return mr(e,s)}return{resolvedBinary:a,trustedProjectTool:i}}function Kh(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 Wt(e){let t=Et(e.language),n=Yh(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=Do({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:Zr(t,e.env,r),...Kh(e,s),...i?{trustedProjectTool:i}:{}}}}function Xh(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)lc(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:dy(r)}}function lc(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 Qh(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
|
|
364
|
+
`);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
|
|
365
|
+
`+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.
|
|
366
|
+
`+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
|
|
367
|
+
`))}function qs(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=Oi(e.map(o=>o.scipPath),t);return fc(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Xs(e[0].scipPath,t);return!1}async function Zh(e){let t;if(ey(e))try{return await gy(e)}catch(i){if(M(e.run.opts.signal,"Reindex cancelled by its owner."),t=i instanceof Error?i.message:String(i),fe(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 dc(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 ey(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!A(e.run.paths.outputDb)||!A(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 ty(e,t){let n=R(),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:R()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:Pn(e.plan,o,e.projectFileCount)}}async function dc(e,t,n,r,i=!1,o){if(M(o,"Reindex cancelled by its owner."),r("Converting to SQLite..."),!A(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{if(i||pc(e,r),n.SCIP_QUERY_SQLITE_CONVERTER==="scip-cli"){let a=$e();if(!a)throw new Error("scip CLI is not available");let s=await gt({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 fe(t,{force:!0}),await fa(j(e,{maxBytes:Ae,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 pc(e,t){let n=Fi(e);fc(n,t)}function fc(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 he(e,t,n){let r=Yg(e)||".scip",i=Gt(e,r);return k(h(e),`${i}.${n+1}.${t}${r}`)}async function ny(e,t){for(let n=0;n<2;n++){let r=ry(e,t);if(r)return r;let i=iy(e);if(i&&hc(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await oy(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: ${me(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=sn(e,{parseLegacy:zt});if(!li(e,a,{parseLegacy:zt}))throw new Error(`Reindex lock ownership changed before preemption completed for ${h(e)}.`);continue}throw new we(`Another scip-query reindex is already running for ${h(e)}.`)}throw new we(`Could not acquire scip-query reindex lock for ${h(e)}.`)}function ry(e,t){let n=X(process.pid),r=ct(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:zt});if(r.kind==="acquired"&&r.reclaimed){let i=mc(r.reclaimed,e);i&&hc(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 iy(e){return mc(sn(e,{parseLegacy:zt}),e)}var zt=e=>{let t=gc(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function mc(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 gc(e.parsed,t)}function gc(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=ei(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 hc(e,t){return e?.kind==="manual-cli"&&yc(t?.trigger)}function yc(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function oy(e){return!xe(e.pid)||(gr(e),zs(e,"SIGTERM"),await Hs(e,2e3))?!0:(gr(e),zs(e,"SIGKILL"),Hs(e,1e3))}function zs(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!xe(e.pid))return;gr(e)}try{process.kill(e.pid,t)}catch{}}async function Hs(e,t){let n=R()+t;for(;R()<n;){if(Js(e))return!0;await ay(50)}return Js(e)}function gr(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=X(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!Me(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function Js(e){if(!xe(e.pid))return!0;if(!e.processIdentity)return!1;let t=X(e.pid);return t!==null&&!Me(e.processIdentity,t)}function ay(e){return new Promise(t=>setTimeout(t,e))}function Sr(e,t,n){return Object.fromEntries(t.map(r=>{let i=r==="typescript"?kr(n.typescriptProjects):[],o=r==="clojure"?cy(n.clojureConfigPath):void 0,a=[...Et(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"&&uy(n),...s,clojureConfigPath:o,files:e.files.filter(c=>Rr(c.path,r,a)).map(c=>Sc(c,r))}]}))}function Sc(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 sy(e,t){let n=oe(t);if(!n)return t;let r=n.typescriptProjectMode==="workspace"?W(e,n.typescriptProjects):["."],i=Oe(r);return{...n,files:n.files.filter(o=>!Qe(o.path)||i.has(o.path)).map(o=>{let a=o.semanticHash??Ze(e,o.path,o.hash);return Sc(a===void 0?o:{...o,semanticHash:a},"typescript")})}}function cy(e){return e?.trim()||void 0}function uy(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function br(e,t){return k(h(e),"language-indexes",`${t}.scip`)}function bc(e){return k(h(e),"language-indexes","typescript-projects")}function Jt(e,t){return k(bc(e),`${_n(t)}.scip`)}function ie(e){try{return Se(q(U(e,"reindex metadata")))}catch{return null}}function Rc(e,t){try{let n=q(U(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return null;let r=n.metadata;return!n.capabilities.publishableGeneration||!_r(r)||D([...r.indexedLanguages??[]].sort())!==D(t.languages)?null:D(r.fingerprint)===D(t)?"exact":D(Ys(r.fingerprint))===D(Ys(t))?"operational-config-compatible":null}catch{return null}}function Ys(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 ly(e,t,n,r){let i=Se(q(U(e,"reindex metadata")));i&&He(e,{...i,fingerprint:t,...i.version===ye?{languageFingerprints:Sr(t,n,r)}:{}})}function He(e,t){ni(e,t,{spacing:2,trailingNewline:!0})}function xc(e,t){try{let n=Se(q(U(e,"reindex metadata")));if(!n)return;He(e,{...n,lastRefresh:t})}catch{}}function Yt(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:R()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function D(e){return JSON.stringify(e)}function dy(e){let t=[];for(let n of e.values())if(n.scipPaths.length>1)n.concatenate?Ai(n.scipPaths,n.outputScipPath):Di(n.scipPaths,n.outputScipPath),t.push({language:n.language,scipPath:n.outputScipPath});else{let r=n.scipPaths[0];r!==n.outputScipPath&&Xs(r,n.outputScipPath),t.push({language:n.language,scipPath:n.outputScipPath})}return t}function py(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 fy(e,t){e.achievedDurability==="file-flushed"&&t.onStatus(`Published local generation ${e.currentGeneration.slice(0,12)} (file-flushed; directory sync unsupported)`)}function my(e){return e.mode==="incremental"&&e.scipCompanion==="deferred"}async function gy(e){if(e.incrementalTypeScript.affectedBatches.length===0&&e.incrementalTypeScript.retainedDocumentCount===e.incrementalTypeScript.affectedFiles.length&&e.incrementalTypeScript.retainedDocumentCount>0){let o=performance.now();return ee(e.run.writeTelemetry,Z(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=k(e.run.tempPaths.runDir,`typescript-affected-${o}.db`);pc(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 dc(a.scipPath,s,e.env,e.run.onStatus,!0,e.run.opts.signal),r+=performance.now()-c,xt(e.run.writeTelemetry,ge(s)??0);let u=Mo({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);fe(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 hy(e,t,n){if(e.source==="path"&&Zs()!=="win32"){let r=Sn();if(!yn(r))if(t)n(`scip on PATH reports ${r??"an unknown version"}; the reviewed version is ${C} 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 ${C}.`),bn(n)}}function yy(e,t,n){let r=rn(e),i=t&&r?Nr(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}function zv(e,t,n,r){return ec({projectRoot:e,languages:r.languages?.length?r.languages:t.languages,outputScip:n.indexPath,outputDb:n.dbPath,pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,maxHeapMb:t.indexer?.typescript?.maxHeapMb,clojureConfigPath:t.indexer?.clojure?.configPath,skipIfUnchanged:r.force!==!0,allowPartial:r.allowPartial===!0,allowExpensiveRebuild:r.allowExpensiveRebuild===!0||r.force===!0,skipAutoInstall:r.skipAutoInstall===!0,installMissing:r.installMissing===!0,trustProjectTools:r.trustProjectTools===!0,indexerConcurrency:r.indexerConcurrency??t.indexerConcurrency,trigger:r.trigger,...r.onStatus?{onStatus:r.onStatus}:{}})}export{oo as a,qy as b,zy as c,po as d,AS as e,OS as f,Et as g,nd as h,ab as i,sd as j,sb as k,J as l,Wa as m,Sf as n,hs as o,Eg as p,ec as q,zv as r};
|
|
368
|
+
//# sourceMappingURL=chunk-CFYMZFXT.js.map
|