codebaseiq 0.1.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 +481 -0
- package/LICENSE +202 -0
- package/README.md +349 -0
- package/dist/augment-vue-worker.js +2 -0
- package/dist/call-graph-evidence-gNsxjCW8.d.ts +16 -0
- package/dist/change-analysis-types-CCtoCHbC.d.ts +9 -0
- package/dist/chunk-2Q2LW5JW.js +14 -0
- package/dist/chunk-2X7V4HS4.js +88 -0
- package/dist/chunk-34WBMAYK.js +2 -0
- package/dist/chunk-35NLDRZC.js +2 -0
- package/dist/chunk-362QOSFD.js +3 -0
- package/dist/chunk-3IER7Q6H.js +12 -0
- package/dist/chunk-3JSXXYTZ.js +345 -0
- package/dist/chunk-3LCDIREB.js +4 -0
- package/dist/chunk-476NR5B7.js +2 -0
- package/dist/chunk-4FC325IF.js +30 -0
- package/dist/chunk-4WKDMDEW.js +9 -0
- package/dist/chunk-4XTAUQFD.js +2 -0
- package/dist/chunk-5PUWMSDU.js +26 -0
- package/dist/chunk-5VKBFZZU.js +3 -0
- package/dist/chunk-6BQ3DSPK.js +2 -0
- package/dist/chunk-6CS3UQTN.js +3 -0
- package/dist/chunk-6MUIJMVL.js +6 -0
- package/dist/chunk-6NW7MU72.js +40 -0
- package/dist/chunk-6OAHRI2D.js +6 -0
- package/dist/chunk-6YTSKJJ3.js +2 -0
- package/dist/chunk-7FND7D7N.js +2 -0
- package/dist/chunk-7MGU3HPH.js +2 -0
- package/dist/chunk-7NVGT435.js +2 -0
- package/dist/chunk-7XAN6GKB.js +2 -0
- package/dist/chunk-AAQQPKCU.js +2 -0
- package/dist/chunk-ADTBPVUZ.js +21 -0
- package/dist/chunk-AKB7V7TV.js +2 -0
- package/dist/chunk-ANFVSJWQ.js +11 -0
- package/dist/chunk-B2OB55RR.js +3 -0
- package/dist/chunk-B3UYV66Z.js +4 -0
- package/dist/chunk-B75HZHUP.js +2 -0
- package/dist/chunk-BFFZDZQV.js +2 -0
- package/dist/chunk-BGBBVSH4.js +2 -0
- package/dist/chunk-BH5F2Q4O.js +2 -0
- package/dist/chunk-BJ6SQAEN.js +2 -0
- package/dist/chunk-BMYOV5GP.js +77 -0
- package/dist/chunk-BVAJLC5A.js +7 -0
- package/dist/chunk-C6SBF2WH.js +4 -0
- package/dist/chunk-C74PPYLA.js +3 -0
- package/dist/chunk-C7QOQX32.js +8 -0
- package/dist/chunk-CAUCPUOF.js +7 -0
- package/dist/chunk-CO5R3UNA.js +2 -0
- package/dist/chunk-CQP3THUZ.js +7 -0
- package/dist/chunk-CVYSU6BX.js +16 -0
- package/dist/chunk-CWONGW6P.js +3 -0
- package/dist/chunk-DDZ7VHWV.js +20 -0
- package/dist/chunk-DGXRDLV5.js +2 -0
- package/dist/chunk-DO6WQD2T.js +3 -0
- package/dist/chunk-DQMDCD24.js +2 -0
- package/dist/chunk-DR2LURYU.js +3 -0
- package/dist/chunk-DRENNWRG.js +2 -0
- package/dist/chunk-ECQBG7PW.js +564 -0
- package/dist/chunk-EF2R3WNQ.js +2 -0
- package/dist/chunk-ELNRLMC5.js +29 -0
- package/dist/chunk-EMNIHCRB.js +18 -0
- package/dist/chunk-ENCCHKM6.js +5 -0
- package/dist/chunk-EZNMUY67.js +5 -0
- package/dist/chunk-FAJQ7LWY.js +3 -0
- package/dist/chunk-FDGD5AB5.js +2 -0
- package/dist/chunk-FETNQCFO.js +117 -0
- package/dist/chunk-FM5BPL4V.js +60 -0
- package/dist/chunk-FQKZWM4L.js +49 -0
- package/dist/chunk-FW53T7EB.js +2 -0
- package/dist/chunk-G6XFR4ZL.js +4 -0
- package/dist/chunk-GCHRX4YW.js +4 -0
- package/dist/chunk-GTIYTDRE.js +562 -0
- package/dist/chunk-GTXSJDCO.js +2 -0
- package/dist/chunk-GW6Z3WGY.js +2 -0
- package/dist/chunk-H3LGFZVK.js +2 -0
- package/dist/chunk-HKQUXIFO.js +2 -0
- package/dist/chunk-HOA5YGOH.js +3 -0
- package/dist/chunk-HPJRBHVT.js +3 -0
- package/dist/chunk-HRWGYWRJ.js +49 -0
- package/dist/chunk-I2T2LLK2.js +4 -0
- package/dist/chunk-ICFDQHAM.js +3 -0
- package/dist/chunk-ID63777H.js +4 -0
- package/dist/chunk-IJ4HMYBE.js +3 -0
- package/dist/chunk-ILMHV3KM.js +2 -0
- package/dist/chunk-IOP6FWIM.js +2 -0
- package/dist/chunk-IRQOAM5G.js +2 -0
- package/dist/chunk-J77SU6VA.js +38 -0
- package/dist/chunk-JE3WZ6II.js +2 -0
- package/dist/chunk-JEJLSICM.js +4 -0
- package/dist/chunk-JOIRNPPY.js +2 -0
- package/dist/chunk-JSOYNVWH.js +3 -0
- package/dist/chunk-KMITESMT.js +2 -0
- package/dist/chunk-KUW32IRO.js +2 -0
- package/dist/chunk-KWVHSKHK.js +31 -0
- package/dist/chunk-L4NRUAGJ.js +18 -0
- package/dist/chunk-L57ZKWVG.js +6 -0
- package/dist/chunk-LTA3BRZX.js +2 -0
- package/dist/chunk-LU3BMVH2.js +10 -0
- package/dist/chunk-LZYFLFEH.js +2 -0
- package/dist/chunk-MOVBWNIP.js +16 -0
- package/dist/chunk-MVB3DAEY.js +3 -0
- package/dist/chunk-N3IQCBCF.js +29 -0
- package/dist/chunk-NAUD7LCA.js +2 -0
- package/dist/chunk-NCZUNH3E.js +109 -0
- package/dist/chunk-NE6IU5ZD.js +5 -0
- package/dist/chunk-NEDP5RFQ.js +60 -0
- package/dist/chunk-NMTSZXCL.js +2 -0
- package/dist/chunk-NNJ2KZZG.js +4 -0
- package/dist/chunk-NNO6A2PO.js +2 -0
- package/dist/chunk-NNOKTMZT.js +20 -0
- package/dist/chunk-O6QTXQPJ.js +13 -0
- package/dist/chunk-OANDYLJQ.js +2 -0
- package/dist/chunk-OFBE4NGP.js +2 -0
- package/dist/chunk-OGTFJ3XD.js +2 -0
- package/dist/chunk-OL6KJP3N.js +16 -0
- package/dist/chunk-OLF4MA5W.js +8 -0
- package/dist/chunk-OTOKVOJ3.js +2 -0
- package/dist/chunk-OVTS4DKB.js +2 -0
- package/dist/chunk-OZYRSMSH.js +3 -0
- package/dist/chunk-P5XHIJHI.js +2 -0
- package/dist/chunk-PBI2LFKH.js +2 -0
- package/dist/chunk-PIOMTC27.js +2 -0
- package/dist/chunk-PTAWHLVJ.js +6 -0
- package/dist/chunk-PX4RYAAK.js +2 -0
- package/dist/chunk-PYAB5SM6.js +7 -0
- package/dist/chunk-Q5ELPRKQ.js +2 -0
- package/dist/chunk-Q65CQ4XL.js +2 -0
- package/dist/chunk-Q72QSKXC.js +308 -0
- package/dist/chunk-QCN62RTF.js +3 -0
- package/dist/chunk-QDCCHMVZ.js +2 -0
- package/dist/chunk-QHRNXP3C.js +3 -0
- package/dist/chunk-QKPLA6IC.js +2 -0
- package/dist/chunk-QOKYJ33H.js +2 -0
- package/dist/chunk-QW7EP6WI.js +21 -0
- package/dist/chunk-R2NOK63J.js +4 -0
- package/dist/chunk-RBAS5ZHI.js +2 -0
- package/dist/chunk-RDBI2RXU.js +9 -0
- package/dist/chunk-RKEJ6VTF.js +73 -0
- package/dist/chunk-RR7SX44N.js +35 -0
- package/dist/chunk-RU65DDUP.js +215 -0
- package/dist/chunk-SELM5MER.js +2 -0
- package/dist/chunk-SGX43S2L.js +2 -0
- package/dist/chunk-SMRBZ6EC.js +2 -0
- package/dist/chunk-SNNWPCN7.js +4 -0
- package/dist/chunk-ST7V3SKN.js +2 -0
- package/dist/chunk-SWHMHUKF.js +2 -0
- package/dist/chunk-SYDJMPES.js +2 -0
- package/dist/chunk-SZD2KF7Q.js +2 -0
- package/dist/chunk-T3DGWPXM.js +3 -0
- package/dist/chunk-TFZB6XTM.js +239 -0
- package/dist/chunk-TIIC3ZE7.js +2 -0
- package/dist/chunk-TRRC4ZJ7.js +2 -0
- package/dist/chunk-TXXOEMZJ.js +2 -0
- package/dist/chunk-UBGWN7I4.js +2 -0
- package/dist/chunk-UCD3H3UZ.js +5 -0
- package/dist/chunk-UDS562V4.js +5 -0
- package/dist/chunk-UNBY47BC.js +3 -0
- package/dist/chunk-UP3BUZR5.js +74 -0
- package/dist/chunk-UXM43C7T.js +3 -0
- package/dist/chunk-UZGZB3VB.js +3 -0
- package/dist/chunk-VE5AVNMP.js +2 -0
- package/dist/chunk-VEXUL62T.js +2 -0
- package/dist/chunk-VFY6Y2H6.js +61 -0
- package/dist/chunk-VUIYB2V3.js +2 -0
- package/dist/chunk-VXYS3FZD.js +23 -0
- package/dist/chunk-WE5RZHZ7.js +5 -0
- package/dist/chunk-WMPRTGH2.js +2 -0
- package/dist/chunk-WOQBZPIF.js +2 -0
- package/dist/chunk-XLQ3GLWZ.js +2 -0
- package/dist/chunk-XME3HPXZ.js +2 -0
- package/dist/chunk-XMQ23E27.js +2 -0
- package/dist/chunk-XWUOUWYI.js +2 -0
- package/dist/chunk-XZEE23VG.js +5 -0
- package/dist/chunk-Y6KHROC3.js +7 -0
- package/dist/chunk-YESXMKX3.js +3 -0
- package/dist/chunk-YMGZZEW4.js +2 -0
- package/dist/chunk-YSNONTJ2.js +2 -0
- package/dist/chunk-YUKYB54I.js +1 -0
- package/dist/chunk-YVCIMIOC.js +12 -0
- package/dist/chunk-Z54RD7VL.js +3 -0
- package/dist/chunk-ZKX2FRS6.js +15 -0
- package/dist/chunk-ZMI2JSX2.js +2 -0
- package/dist/chunk-ZV3JV5G5.js +8 -0
- package/dist/chunk-ZZ3MWF33.js +4 -0
- package/dist/chunk-ZZXSWSN6.js +2 -0
- package/dist/cli-context-3SNLDYBM.js +3 -0
- package/dist/cli-context-T3B7W6GG.js +2 -0
- package/dist/cli-program-YNOXO72B.js +7 -0
- package/dist/cli.js +3 -0
- package/dist/code-DlqpBDd0.d.ts +121 -0
- package/dist/command-descriptors-6AOUKWW7.js +346 -0
- package/dist/command-descriptors-ZFKJSRUP.js +344 -0
- package/dist/command-panels-SZONPMLJ.js +3 -0
- package/dist/config-types-BNoC96J3.d.ts +560 -0
- package/dist/db-D7sauVFH.d.ts +95 -0
- package/dist/direct-navigation-DP4LVMRX.js +3 -0
- package/dist/direct-navigation-FLUS3BT6.js +2 -0
- package/dist/exploration-topology-BG4v30HZ.d.ts +256 -0
- package/dist/file-dep-graph-Bqg3t3Px.d.ts +4 -0
- package/dist/file-kind-BKCVMNUf.d.ts +10 -0
- package/dist/frontend-behavior-evidence-EfM4_9bc.d.ts +4 -0
- package/dist/git-history-ChNHbfZQ.d.ts +13 -0
- package/dist/graph-evidence-BIFqyisO.d.ts +131 -0
- package/dist/health-DJaZXg8I.d.ts +340 -0
- package/dist/index.d.ts +183 -0
- package/dist/index.js +2 -0
- package/dist/invocation-command-descriptors-QT2JMY5J.js +3 -0
- package/dist/invocation-command-descriptors-YN4QJEAX.js +2 -0
- package/dist/next-anchor-candidates-BwMczMvX.d.ts +90 -0
- package/dist/output-continuation-command-2V2SL4TD.js +2 -0
- package/dist/output-continuation-command-65J5IP3O.js +3 -0
- package/dist/postinstall.js +3 -0
- package/dist/project-reindex-5JOKXAXT.js +2 -0
- package/dist/project-reindex-UQBIKO4M.js +3 -0
- package/dist/queries/affected.d.ts +40 -0
- package/dist/queries/affected.js +2 -0
- package/dist/queries/anchors.d.ts +123 -0
- package/dist/queries/anchors.js +2 -0
- package/dist/queries/architecture.d.ts +166 -0
- package/dist/queries/architecture.js +2 -0
- package/dist/queries/bottlenecks.d.ts +68 -0
- package/dist/queries/bottlenecks.js +2 -0
- package/dist/queries/by-kind.d.ts +27 -0
- package/dist/queries/by-kind.js +2 -0
- package/dist/queries/call-graph.d.ts +52 -0
- package/dist/queries/call-graph.js +2 -0
- package/dist/queries/change-surface.d.ts +55 -0
- package/dist/queries/change-surface.js +2 -0
- package/dist/queries/cleanup-plan.d.ts +66 -0
- package/dist/queries/cleanup-plan.js +2 -0
- package/dist/queries/co-change.d.ts +90 -0
- package/dist/queries/co-change.js +2 -0
- package/dist/queries/code.d.ts +6 -0
- package/dist/queries/code.js +2 -0
- package/dist/queries/complexity-hotspots.d.ts +61 -0
- package/dist/queries/complexity-hotspots.js +2 -0
- package/dist/queries/complexity.d.ts +74 -0
- package/dist/queries/complexity.js +2 -0
- package/dist/queries/context.d.ts +146 -0
- package/dist/queries/context.js +2 -0
- package/dist/queries/convergence.d.ts +33 -0
- package/dist/queries/convergence.js +2 -0
- package/dist/queries/coupling.d.ts +32 -0
- package/dist/queries/coupling.js +2 -0
- package/dist/queries/cycles.d.ts +66 -0
- package/dist/queries/cycles.js +2 -0
- package/dist/queries/dataflow.d.ts +77 -0
- package/dist/queries/dataflow.js +2 -0
- package/dist/queries/dead.d.ts +58 -0
- package/dist/queries/dead.js +2 -0
- package/dist/queries/decorative-checkers.d.ts +34 -0
- package/dist/queries/decorative-checkers.js +2 -0
- package/dist/queries/deep-chains.d.ts +5 -0
- package/dist/queries/deep-chains.js +2 -0
- package/dist/queries/dependence-slice.d.ts +46 -0
- package/dist/queries/dependence-slice.js +2 -0
- package/dist/queries/dependency-depth.d.ts +49 -0
- package/dist/queries/dependency-depth.js +2 -0
- package/dist/queries/deps.d.ts +15 -0
- package/dist/queries/deps.js +2 -0
- package/dist/queries/diff-impact.d.ts +165 -0
- package/dist/queries/diff-impact.js +2 -0
- package/dist/queries/doc-drift.d.ts +115 -0
- package/dist/queries/doc-drift.js +2 -0
- package/dist/queries/drift.d.ts +79 -0
- package/dist/queries/drift.js +2 -0
- package/dist/queries/duplicate-bodies.d.ts +55 -0
- package/dist/queries/duplicate-bodies.js +2 -0
- package/dist/queries/entry-map.d.ts +121 -0
- package/dist/queries/entry-map.js +2 -0
- package/dist/queries/evidence.d.ts +70 -0
- package/dist/queries/evidence.js +2 -0
- package/dist/queries/extract-candidates.d.ts +52 -0
- package/dist/queries/extract-candidates.js +2 -0
- package/dist/queries/fan.d.ts +53 -0
- package/dist/queries/fan.js +2 -0
- package/dist/queries/files.d.ts +20 -0
- package/dist/queries/files.js +2 -0
- package/dist/queries/health.d.ts +8 -0
- package/dist/queries/health.js +2 -0
- package/dist/queries/hierarchy.d.ts +21 -0
- package/dist/queries/hierarchy.js +2 -0
- package/dist/queries/hotspots.d.ts +42 -0
- package/dist/queries/hotspots.js +2 -0
- package/dist/queries/imports.d.ts +34 -0
- package/dist/queries/imports.js +2 -0
- package/dist/queries/incomplete-migration.d.ts +90 -0
- package/dist/queries/incomplete-migration.js +2 -0
- package/dist/queries/index.d.ts +180 -0
- package/dist/queries/index.js +2 -0
- package/dist/queries/isolated.d.ts +24 -0
- package/dist/queries/isolated.js +2 -0
- package/dist/queries/locality-candidates.d.ts +51 -0
- package/dist/queries/locality-candidates.js +2 -0
- package/dist/queries/members.d.ts +21 -0
- package/dist/queries/members.js +2 -0
- package/dist/queries/methods.d.ts +43 -0
- package/dist/queries/methods.js +2 -0
- package/dist/queries/not-implemented.d.ts +33 -0
- package/dist/queries/not-implemented.js +2 -0
- package/dist/queries/outline.d.ts +22 -0
- package/dist/queries/outline.js +2 -0
- package/dist/queries/passthrough-candidates.d.ts +41 -0
- package/dist/queries/passthrough-candidates.js +2 -0
- package/dist/queries/plan-context.d.ts +33 -0
- package/dist/queries/plan-context.js +2 -0
- package/dist/queries/react-component-duplicates.d.ts +39 -0
- package/dist/queries/react-component-duplicates.js +2 -0
- package/dist/queries/react-hook-candidates.d.ts +44 -0
- package/dist/queries/react-hook-candidates.js +2 -0
- package/dist/queries/react-large-component-pressure.d.ts +34 -0
- package/dist/queries/react-large-component-pressure.js +2 -0
- package/dist/queries/recent-duplicates.d.ts +79 -0
- package/dist/queries/recent-duplicates.js +2 -0
- package/dist/queries/redundant-reexports.d.ts +37 -0
- package/dist/queries/redundant-reexports.js +2 -0
- package/dist/queries/reference-neighborhood.d.ts +4 -0
- package/dist/queries/reference-neighborhood.js +2 -0
- package/dist/queries/reference-reachability.d.ts +48 -0
- package/dist/queries/reference-reachability.js +2 -0
- package/dist/queries/refs.d.ts +13 -0
- package/dist/queries/refs.js +2 -0
- package/dist/queries/self-audit.d.ts +65 -0
- package/dist/queries/self-audit.js +2 -0
- package/dist/queries/similar-chains.d.ts +48 -0
- package/dist/queries/similar-chains.js +2 -0
- package/dist/queries/similar-files.d.ts +35 -0
- package/dist/queries/similar-files.js +2 -0
- package/dist/queries/similar-signatures.d.ts +46 -0
- package/dist/queries/similar-signatures.js +2 -0
- package/dist/queries/similar.d.ts +187 -0
- package/dist/queries/similar.js +2 -0
- package/dist/queries/slice.d.ts +4 -0
- package/dist/queries/slice.js +2 -0
- package/dist/queries/source-inspection.d.ts +209 -0
- package/dist/queries/source-inspection.js +2 -0
- package/dist/queries/source-search.d.ts +85 -0
- package/dist/queries/source-search.js +2 -0
- package/dist/queries/stale-abstractions.d.ts +72 -0
- package/dist/queries/stale-abstractions.js +2 -0
- package/dist/queries/stats.d.ts +15 -0
- package/dist/queries/stats.js +2 -0
- package/dist/queries/surface.d.ts +22 -0
- package/dist/queries/surface.js +2 -0
- package/dist/queries/symbols.d.ts +14 -0
- package/dist/queries/symbols.js +2 -0
- package/dist/queries/system-map.d.ts +449 -0
- package/dist/queries/system-map.js +2 -0
- package/dist/queries/system.d.ts +21 -0
- package/dist/queries/system.js +2 -0
- package/dist/queries/test-quality.d.ts +56 -0
- package/dist/queries/test-quality.js +2 -0
- package/dist/queries/trace.d.ts +68 -0
- package/dist/queries/trace.js +2 -0
- package/dist/queries/twin-ab.d.ts +66 -0
- package/dist/queries/twin-ab.js +2 -0
- package/dist/queries/twin-drift.d.ts +119 -0
- package/dist/queries/twin-drift.js +2 -0
- package/dist/queries/unused-imports.d.ts +4 -0
- package/dist/queries/unused-imports.js +2 -0
- package/dist/queries/unused-params.d.ts +38 -0
- package/dist/queries/unused-params.js +2 -0
- package/dist/queries/value-flow.d.ts +42 -0
- package/dist/queries/value-flow.js +2 -0
- package/dist/queries/vue-component-duplicates.d.ts +43 -0
- package/dist/queries/vue-component-duplicates.js +2 -0
- package/dist/queries/vue-composable-candidates.d.ts +44 -0
- package/dist/queries/vue-composable-candidates.js +2 -0
- package/dist/queries/vue-large-view-pressure.d.ts +41 -0
- package/dist/queries/vue-large-view-pressure.js +2 -0
- package/dist/queries/wrapper-candidates.d.ts +34 -0
- package/dist/queries/wrapper-candidates.js +2 -0
- package/dist/reindex-worker.js +3 -0
- package/dist/reindex.d.ts +254 -0
- package/dist/reindex.js +298 -0
- package/dist/repository-text-C0Q8VYdN.d.ts +19 -0
- package/dist/runtime.d.ts +555 -0
- package/dist/runtime.js +4 -0
- package/dist/rust-semantic-session-server.js +2 -0
- package/dist/rust-semantic-session-worker.js +2 -0
- package/dist/rust-semantic-worker.js +2 -0
- package/dist/scip-cli-B7N3haxa.d.ts +67 -0
- package/dist/source-snippet-_wrcgmZc.d.ts +15 -0
- package/dist/symbol-types-BIQwfoAx.d.ts +74 -0
- package/dist/typescript-mailbox-worker.js +2 -0
- package/dist/watch-server.js +8 -0
- package/docs/AGENT_GUIDE.md +148 -0
- package/docs/AI_FAILURE_MODES.md +43 -0
- package/docs/API.md +40 -0
- package/docs/API_EVOLUTION.md +77 -0
- package/docs/CLI_JSON_OUTPUT.md +389 -0
- package/docs/COMMAND_REFERENCE.md +294 -0
- package/docs/CONFIGURATION_WRITE_SAFETY.md +131 -0
- package/docs/DETECTOR_GUIDE.md +46 -0
- package/docs/DURABILITY.md +159 -0
- package/docs/INDEX_GENERATIONS.md +167 -0
- package/docs/LOCK_PROTOCOL.md +133 -0
- package/docs/MAILBOX_LIFECYCLE.md +224 -0
- package/docs/REGEX_POLICY.md +36 -0
- package/docs/REINDEX_METADATA_COMPATIBILITY.md +104 -0
- package/docs/RUST_DURABLE_SESSION_PROTOCOL.md +126 -0
- package/docs/SECURITY_MODEL.md +125 -0
- package/docs/TELEMETRY_RETENTION.md +84 -0
- package/docs/TIME_SEMANTICS.md +77 -0
- package/docs/WATCH_REFRESH_REQUESTS.md +123 -0
- package/docs/WINDOWS_SIDECAR_RELEASE.md +424 -0
- package/docs/accuracy-audit-checklist.md +304 -0
- package/docs/accuracy-hardening-goal.md +500 -0
- package/docs/analyzer-inventory.md +78 -0
- package/docs/analyzer-validation-protocol.md +84 -0
- package/docs/architecture-coherence-vision.md +254 -0
- package/docs/assets/codebaseiq-logo-dark.svg +21 -0
- package/docs/assets/codebaseiq-logo.svg +24 -0
- package/docs/locality-analyzer-design.md +193 -0
- package/docs/schemas/cli-json-envelope.schema.json +237 -0
- package/docs/schemas/cli-output-page.schema.json +104 -0
- package/docs/schemas/npm-release-state.schema.json +146 -0
- package/docs/schemas/observation-receipt.schema.json +164 -0
- package/docs/schemas/project-config.schema.json +318 -0
- package/docs/schemas/suppression-record.schema.json +79 -0
- package/docs/schemas/windows-sidecar-provenance.schema.json +137 -0
- package/package.json +482 -0
- package/scripts/build-codebaseiq-windows.mjs +197 -0
- package/scripts/codebaseiq-windows-provenance.mjs +364 -0
- package/scripts/evidence-product-contract.mjs +197 -0
- package/scripts/verify-codebaseiq-windows.mjs +29 -0
- package/skills/codebaseiq/SKILL.md +75 -0
- package/skills/codebaseiq/agents/openai.yaml +4 -0
- package/skills/codebaseiq-explore/SKILL.md +34 -0
- package/skills/codebaseiq-explore/agents/openai.yaml +4 -0
- package/skills/concrete-plan/SKILL.md +79 -0
- package/skills/concrete-plan/agents/openai.yaml +4 -0
package/dist/reindex.js
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import{a as z}from"./chunk-DDZ7VHWV.js";import{a as oi,b as ai,c as dt,d as an,h as sn,i as li,j as pi,k as cn,m as dn,n as fi}from"./chunk-YVCIMIOC.js";import{a as ii}from"./chunk-NEDP5RFQ.js";import{e as si,f as ci,g as di,i as ui}from"./chunk-FQKZWM4L.js";import"./chunk-VE5AVNMP.js";import{A as Qr,B as Zt,E as en,F as Zr,G as tn,H as nn,I as ei,J as ti,K as rn,M as on,R as ni,T as ri,a as _r,b as N,c as jr,d as de,e as re,f as G,g as be,h as Mr,i as nt,j as qt,k as $,l as Nr,n as Gr,o as Ce,p as Ut,q as rt,s as ue,t as _e,u as Ie,v as Le,w as Pe,x as Xt,y as Qt,z as Xr}from"./chunk-UCD3H3UZ.js";import"./chunk-CVYSU6BX.js";import"./chunk-ELNRLMC5.js";import"./chunk-UZGZB3VB.js";import{a as Or,b as Ae,c as ee,d as te,e as I,f as Ze,g as Wt,h as Lr,i as F,j as tt,m as Kt,n as Kr}from"./chunk-ZKX2FRS6.js";import"./chunk-TIIC3ZE7.js";import"./chunk-YUKYB54I.js";import{a as ct}from"./chunk-NNOKTMZT.js";import"./chunk-FETNQCFO.js";import"./chunk-O6QTXQPJ.js";import{I as Jr,J as Yr,a as it}from"./chunk-ADTBPVUZ.js";import"./chunk-BMYOV5GP.js";import{a as xe,c as Hr,f as zr,j as st,k as Jt,l as Yt}from"./chunk-CWONGW6P.js";import{d as ot,e as Re}from"./chunk-3LCDIREB.js";import{A,B as H,C as _,F as D,G as w,H as L,K as Cr,L as Qe,P as et,Q as ne,R as Oe,S as $r,U as Vr,V as Br,W as Wr,X as qr,Z as Ht,_ as zt,ba as at,e as Er,ea as Ur,f as Se,g as $t,h as kr,i as Tr,k as Dr,l as Xe,m as O,u as Fe,v as Z,w as Vt,x as Fr,y as Bt,z as Ar}from"./chunk-NNJ2KZZG.js";import{createHash as np}from"crypto";import{existsSync as j,mkdirSync as jt,mkdtempSync as rp,readdirSync as ms,renameSync as hs,rmSync as Te,statSync as ip}from"fs";import{basename as Lt,dirname as S,extname as op,join as C,resolve as ss}from"path";import{platform as ap}from"os";import{execFileSync as Fs}from"child_process";import{constants as As,copyFileSync as gi,statSync as Os}from"fs";import{platform as Cs}from"os";var _s=Object.freeze({size:e=>Os(e).size,clone:js,copy:(e,t)=>gi(e,t)}),Ls=new Set(["ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL","EXDEV","ENOTTY"]);function le(e,t,n=_s){let r=n.size(e);try{return n.clone(e,t),{method:"reflink",bytes:r}}catch(i){if(!Ns(i))throw i}return n.copy(e,t),{method:"copy",bytes:r}}function js(e,t){if(Cs()!=="darwin"){gi(e,t,As.COPYFILE_FICLONE_FORCE);return}try{Fs("/bin/cp",["-c",e,t],{timeout:6e4,maxBuffer:64*1024,stdio:["ignore","ignore","pipe"],windowsHide:!0})}catch(n){throw Ms(n)}}function Ms(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 Ns(e){let t=e?.code;return t!==void 0&&Ls.has(t)}function mi(){return{reflinkedBytes:0,fallbackCopiedBytes:0}}function pe(e,t){t.method==="reflink"?e.reflinkedBytes+=t.bytes:e.fallbackCopiedBytes+=t.bytes}import Gs from"better-sqlite3";import{execFileSync as $s}from"child_process";import{existsSync as Vs,readdirSync as Bs}from"fs";import{extname as ut,join as Ws}from"path";function ie(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>hi({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function hi(e){let t=new Set((e.extensions??Jr).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Vs(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=ii(e.projectRoot),r=qs(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Gs(e.dbPath);try{let o=Hs(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
|
|
2
|
+
VALUES (?, ?, NULL, ?)`),c=i.transaction(u=>{let l=0;for(let p of u){if(o.has(p))continue;let g=zr(e.projectRoot,p,{inputKind:"auxiliary source file"}),f=a.run(zs(p),p,g);l+=Number(f.changes)}return l})(r),d={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${d.existing} already present).`),d}finally{i.close()}}function qs(e,t){let n=Us(e,t);if(n)return n;let r=[],i=o=>{let a=o?Ws(e,o):e,s;try{s=Bs(a,{withFileTypes:!0})}catch{return}for(let c of s){if(Yr.has(c.name))continue;let d=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(d);continue}t.has(ut(c.name).toLowerCase())&&r.push(d)}};return i(""),r.sort()}function Us(e,t){try{return $s("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:3e4,killSignal:"SIGKILL"}).split(`
|
|
3
|
+
`).filter(r=>r&&t.has(ut(r).toLowerCase())).sort()}catch{return null}}function Hs(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 zs(e){return ut(e).toLowerCase()===".vue"?"vue":ut(e).replace(/^\./,"").toLowerCase()||"source"}import{dirname as Js,join as Ys}from"path";function yi(e={}){return{id:"runtime-boundaries",facts:["runtime-boundary-observation","runtime-boundary-link"],run:({projectRoot:t,dbPath:n,onStatus:r})=>{let i=new z({projectRoot:t,dbPath:n,indexPath:e.indexPath??Ys(Js(n),"index.scip")}),o,a=!1,s=!1;try{let d=e.reuseExisting||e.affectedFiles?ui(i):null;e.reuseExisting&&d?.extractorVersion===si?(o=d,a=!0):(o=ci(i,{...d?{previousGraph:d}:{},...e.affectedFiles?{affectedFiles:e.affectedFiles}:{}}),s=(o.coverage.filesReused??0)>0)}finally{i.close()}a||di(n,o);let c={reused:a,incrementallyUpdated:s,observations:o.observations.length,links:o.links.length,frontiers:o.frontiers.length,filesScanned:o.coverage.filesScanned,errors:o.coverage.extractionErrors.length,phases:o.coverage.phases};return r?.(c.reused?`Reused ${c.observations} cached runtime-boundary observation(s) and ${c.links} link(s).`:c.incrementallyUpdated?`Incrementally refreshed runtime-boundary observations (${c.filesScanned-(o.coverage.filesReused??0)} file(s) extracted, ${o.coverage.filesReused??0} reused) and rebuilt ${c.links} link(s).`:`Extracted ${c.observations} runtime-boundary observation(s), ${c.links} link(s), and ${c.frontiers} unresolved frontier(s).`),!a&&o.coverage.phases&&r?.(`Runtime-boundary phases: ${o.coverage.phases.map(d=>`${d.id} ${d.durationMs.toFixed(0)}ms`).join(", ")}.`),c}}}import{createHash as Xs}from"crypto";import{existsSync as Qs}from"fs";import{dirname as Zs,join as bi}from"path";function un(e){let t=new Set;for(let n of e.uncertainty)t.add(n);e.projectIdentityChanged&&t.add("project-identity-changed");for(let n of e.changes)n.kind==="added"&&t.add("file-added"),n.kind==="deleted"&&t.add("file-deleted"),n.inputKind==="config"&&t.add("configuration-changed"),n.inputKind==="ambient"&&t.add("ambient-declaration-changed"),n.inputKind==="other"&&t.add("unclassified-input");return{fullProject:t.size>0,reasons:[...t].sort()}}function lt(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=un(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"),Si(r,i,a)):a.size>0?Si(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:Ks(r,t,i),reasons:[]}}function Si(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function Ks(e,t,n){let r=new Map;for(let[a,s]of t)if(n.has(a))for(let c of s){if(!n.has(c))continue;let d=r.get(c)??new Set;d.add(a),r.set(c,d)}let i=new Set(e),o=[...e];for(let a=0;a<o.length;a+=1){let s=o[a];if(s!==void 0)for(let c of r.get(s)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}var ec="<global-symbols>";function tc(e){let t=[];for(let n of e.all(`
|
|
4
|
+
SELECT relative_path, language, position_encoding, text
|
|
5
|
+
FROM documents
|
|
6
|
+
`))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
|
|
7
|
+
SELECT d.relative_path,
|
|
8
|
+
c.chunk_index,
|
|
9
|
+
c.start_line,
|
|
10
|
+
c.end_line,
|
|
11
|
+
hex(c.occurrences) AS occurrences_hex
|
|
12
|
+
FROM chunks c
|
|
13
|
+
JOIN documents d ON d.id = c.document_id
|
|
14
|
+
`))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(`
|
|
15
|
+
SELECT d.relative_path,
|
|
16
|
+
r.start_line,
|
|
17
|
+
r.start_char,
|
|
18
|
+
r.end_line,
|
|
19
|
+
r.end_char,
|
|
20
|
+
g.symbol,
|
|
21
|
+
g.display_name,
|
|
22
|
+
g.kind,
|
|
23
|
+
g.documentation,
|
|
24
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
25
|
+
g.enclosing_symbol,
|
|
26
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
27
|
+
FROM defn_enclosing_ranges r
|
|
28
|
+
JOIN documents d ON d.id = r.document_id
|
|
29
|
+
JOIN global_symbols g ON g.id = r.symbol_id
|
|
30
|
+
`))t.push({relativePath:n.relative_path,kind:"definition",values:ln(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
|
|
31
|
+
SELECT d.relative_path,
|
|
32
|
+
c.chunk_index,
|
|
33
|
+
m.role,
|
|
34
|
+
g.symbol,
|
|
35
|
+
g.display_name,
|
|
36
|
+
g.kind,
|
|
37
|
+
g.documentation,
|
|
38
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
39
|
+
g.enclosing_symbol,
|
|
40
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
41
|
+
FROM mentions m
|
|
42
|
+
JOIN chunks c ON c.id = m.chunk_id
|
|
43
|
+
JOIN documents d ON d.id = c.document_id
|
|
44
|
+
JOIN global_symbols g ON g.id = m.symbol_id
|
|
45
|
+
`))t.push({relativePath:n.relative_path,kind:"mention",values:ln(n,[n.chunk_index,n.role])});for(let n of e.all(`
|
|
46
|
+
SELECT g.symbol,
|
|
47
|
+
g.display_name,
|
|
48
|
+
g.kind,
|
|
49
|
+
g.documentation,
|
|
50
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
51
|
+
g.enclosing_symbol,
|
|
52
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
53
|
+
FROM global_symbols g
|
|
54
|
+
WHERE NOT EXISTS (
|
|
55
|
+
SELECT 1 FROM defn_enclosing_ranges r WHERE r.symbol_id = g.id
|
|
56
|
+
) AND NOT EXISTS (
|
|
57
|
+
SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
|
|
58
|
+
)
|
|
59
|
+
`))t.push({relativePath:ec,kind:"global-symbol",values:ln(n)});return nc(t)}function nc(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=Xs("sha256");for(let a of i.sort())o.update(String(Buffer.byteLength(a))),o.update(":"),o.update(a),o.update(`
|
|
60
|
+
`);n.set(r,o.digest("hex"))}return n}function rc(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),d=t.get(s);c===void 0?n.push(s):d===void 0?i.push(s):c!==d?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 fn(e,t=dc){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,i=t.wallNow??t.now,o=r(),a=(d,u)=>{let l=r();return Pi(e.refreshResult,d,n?l:i(),Math.max(0,l-o),u)};if(!t.databaseExists(e.previousDbPath))return a("prior-index-unavailable");if(!t.databaseExists(e.candidateDbPath))return a("candidate-index-unavailable");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 d=[...new Set([...t.indexedPaths(s),...t.indexedPaths(c)])].sort(),u=Xe(e.previousSnapshot,e.currentSnapshot),l=new Set(d),p=u.changes.length>0&&!un(u).fullProject&&u.changes.every(b=>l.has(b.path)),g=lt(u,p?t.dependencyGraph(s):new Map,d),f=rc(t.factDigests(s),t.factDigests(c)),h=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?h:i()).toISOString(),durationMs:Math.max(0,h-o),manifest:u,plan:g,comparison:f,evaluation:pn(g,f,d.length)}}catch(d){return a("oracle-error",d instanceof Error?d.message:String(d))}finally{Ri(s),Ri(c)}}function xi(e,t,n,r=Date.now()){return Pi(e,t,r,0,n)}function ic(e){let t=Zs(e);return{latestPath:bi(t,"affected-shadow-latest.json"),historyPath:bi(t,"affected-shadow.jsonl")}}function Ii(e,t,n=uc){let r=ic(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var oc=8*1024*1024,ac=li;function sc(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 cc(e,t,n=oc){pi(e,sc(t),{maxSegmentBytes:n,previousSuffix:ac})}function ln(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 dc={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:I,databaseExists:e=>Qs(e),openDatabase:(e,t,n)=>new z({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>it(e),dependencyGraph:e=>ct(e),factDigests:e=>tc(e)},uc={appendHistory:cc,writeLatest:(e,t)=>re(e,t,{spacing:2,trailingNewline:!0})};function Pi(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 Ri(e){try{e?.close()}catch{}}import{readdirSync as lc}from"fs";import{isAbsolute as vi,join as pc,resolve as fc}from"path";var pt="@sourcegraph/scip-typescript@0.4.0",wi="scip-python-plus@0.7.5",Ei="github.com/sourcegraph/scip-go@v0.2.7",ki="scip-dotnet@0.2.14",gc="scip_dart@1.6.2",Di={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",r]}:t?{binary:n,args:["index","--pnpm-workspaces","--output",e,"--no-progress-bar"]}:{binary:n,args:["index","--output",e,"--no-progress-bar"]},markerFiles:[...O.typescript],installMethods:[{label:"npm",identity:pt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",pt]}],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"]}),markerFiles:[...O.javascript],installMethods:[{label:"npm",identity:pt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",pt]}],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:[...O.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:[...O.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:[...O.kotlin],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:Ie.language,indexerBinary:Ie.indexerBinary,checkCommand:`${Ie.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:Ie.indexerBinary,args:["scip",".","--output",e]}),markerFiles:[...O.rust],installMethods:[],installUrl:Ie.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:[...O.python],installMethods:[{label:"npm",identity:wi,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",wi]}],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",vi(r)?r:fc(e,r)),{binary:n,args:i}},markerFiles:[...O.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:[...O.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:[...O.go],installMethods:[{label:"go install",identity:Ei,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",Ei]}],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:[...O.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:[...O.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",Ti(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...O.csharp],installMethods:[{label:"dotnet",identity:ki,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",Ti(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...O.vb],installMethods:[{label:"dotnet",identity:ki,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:[...O.dart],installMethods:[{label:"dart pub",identity:gc,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})=>vi(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:[...O.php],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Fi(e){if(!(e.projectPath||e.pnpmWorkspaces)){if(e.language==="typescript")return"{}";if(e.language==="javascript")return'{"compilerOptions":{"allowJs":true}}'}}function ft(e){return Di[e]}function Ti(e,t){let n;try{n=lc(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return pc(e,i);return null}import{writeFileSync as mn}from"fs";import{create as ve}from"@bufbuild/protobuf";import{deserializeSCIP as hn,serializeSCIP as yn,DocumentSchema as xc,IndexSchema as Ci,MetadataSchema as _i,SymbolInformationSchema as Ic}from"@c4312/scip";import{writeFileSync as mc}from"fs";import{create as Ai}from"@bufbuild/protobuf";import{deserializeSCIP as hc,DocumentSchema as yc,IndexSchema as Sc,serializeSCIP as bc,SymbolRole as Rc}from"@c4312/scip";function Oi(e){let t;try{t=hc(D(e,{inputKind:"SCIP sanitization input",maxBytes:_}))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=gn(t);return n.touchedDocuments>0&&mc(e,Buffer.from(bc(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function gn(e){let t=new Set,n=new Map;for(let a of e.documents){n.set(a,kr(a.relativePath));for(let s of a.symbols)s.symbol&&t.add(s.symbol)}for(let a of e.externalSymbols)a.symbol&&t.add(a.symbol);let r=0,i=0,o=[];for(let a of e.documents){let s=n.get(a),c=a.occurrences.filter(d=>(d.symbolRoles&Rc.Definition)===0||t.has(d.symbol)?!0:(r+=1,!1));if(s===a.relativePath&&c.length===a.occurrences.length){o.push(a);continue}i+=1,o.push(Ai(yc,{language:a.language,relativePath:s,occurrences:c,symbols:a.symbols,text:a.text,positionEncoding:a.positionEncoding}))}return{index:i===0?e:Ai(Sc,{metadata:e.metadata,documents:o,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:r,touchedDocuments:i}}function Sn(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=vc(e),n=wc(e.flatMap(i=>i.documents??[])),r=Mi(e.flatMap(i=>i.externalSymbols??[]));return ve(Ci,{metadata:t,documents:n,externalSymbols:r})}function bn(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>hn(D(i,{inputKind:"SCIP merge input",maxBytes:_}))),r=Sn(n);return mn(t,Buffer.from(yn(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function Li(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>hn(D(i,{inputKind:"SCIP merge input",maxBytes:_}))),r=gn(Sn(n));return mn(t,Buffer.from(yn(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function Pc(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(!Se(r.projectRoot,t))throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return ve(Ci,{metadata:ve(_i,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function ji(e,t,n){let r=hn(D(e,{inputKind:"SCIP normalization input",maxBytes:_})),i=Pc(r,t,n);mn(e,Buffer.from(yn(i)))}function vc(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let i of e.slice(1)){let o=i.metadata?.projectRoot;if(n&&o&&!Se(o,n))throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${o}`)}let r=n&&Er(n);return r===n?t:ve(_i,{...t,projectRoot:r})}function wc(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,ve(xc,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:Ec([...r.occurrences,...n.occurrences]),symbols:Mi([...r.symbols,...n.symbols]),text:Tc(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Ec(e){let t=new Set,n=[];for(let r of e){let i=JSON.stringify(r);t.has(i)||(t.add(i),n.push(r))}return n}function Mi(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,ve(Ic,{symbol:r.symbol,documentation:Dc([...r.documentation,...n.documentation]),relationships:kc([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function kc(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function Tc(e,t){return e?t?e.length>=t.length?e:t:e:t}function Dc(e){return[...new Set(e)]}import{createHash as Fc}from"crypto";import{existsSync as Ni,rmSync as Gi}from"fs";import{resolve as Ac}from"path";import Bi from"better-sqlite3";var Oc={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}]},Cc={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 Wi(e){let t=I(),n=_c(e.affectedFiles);if(Lc(e.previousDbPath,e.miniDbPath,e.candidateDbPath),Gi(e.candidateDbPath,{force:!0}),!Ni(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Ni(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");$i(e.previousDbPath,"previous SQLite generation",!1),$i(e.miniDbPath,"incremental SQLite mini database");let r=le(e.previousDbPath,e.candidateDbPath);e.writeTelemetry&&pe(e.writeTelemetry,r);let i=null;try{i=new Bi(e.candidateDbPath,{fileMustExist:!0}),i.pragma("busy_timeout = 5000"),i.pragma("foreign_keys = ON"),i.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Rn(i,"main","candidate SQLite generation"),Rn(i,"incremental","incremental SQLite mini database"),jc(i,n),Mc(i,n.length);let o=xn(i,"main",!0),a=oe(i,"SELECT COUNT(*) AS value FROM main.documents");i.transaction(()=>{Nc(i),Gc(i),$c(i),e.onStage?.("after-delete"),Vc(i),e.onStage?.("after-symbol-reconciliation"),Bc(i),e.onStage?.("after-insert"),Wc(i),qc(i,n.length,a),e.onStage?.("before-commit")}).immediate(),qi(i,"main","candidate SQLite generation");let d=[...Uc(i)].filter(([u,l])=>o.get(u)!==l).map(([u])=>u).sort();return i.exec("DETACH DATABASE incremental"),i.close(),i=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:d,durationMs:I()-t}}catch(o){try{i?.close()}finally{Gi(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}function _c(e){if(e.length===0)throw new Error("incremental SQLite publication requires affected documents");let t=[...e].sort();for(let n of t)if(!n||n.startsWith("/")||n.includes("\\")||n.split("/").includes(".."))throw new Error(`invalid affected document path: ${n}`);if(new Set(t).size!==t.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return t}function Lc(e,t,n){let r=[e,t,n].map(i=>Ac(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function $i(e,t,n=!0){let r=new Bi(e,{readonly:!0,fileMustExist:!0});try{Rn(r,"main",t),n&&qi(r,"main",t)}finally{r.close()}}function Rn(e,t,n){for(let[r,i]of Object.entries(Oc)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:d,pk:u})=>({name:s,type:c.toUpperCase(),notnull:d,pk:u}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(Cc)){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}`)}Vi(e,t,"documents",["relative_path"],n),Vi(e,t,"global_symbols",["symbol"],n)}function Vi(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(d=>d.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function qi(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 jc(e,t){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let n=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)");e.transaction(i=>{for(let o of i)n.run(o)})(t)}function Mc(e,t){let n=oe(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=oe(e,`SELECT COUNT(*) AS value
|
|
61
|
+
FROM main.documents d
|
|
62
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
|
|
63
|
+
FROM temp.incremental_affected_paths p
|
|
64
|
+
LEFT JOIN incremental.documents d ON d.relative_path = p.relative_path
|
|
65
|
+
WHERE d.id IS NULL
|
|
66
|
+
LIMIT 1`).pluck().get(),o=e.prepare(`SELECT d.relative_path
|
|
67
|
+
FROM incremental.documents d
|
|
68
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
69
|
+
WHERE p.relative_path IS NULL
|
|
70
|
+
LIMIT 1`).pluck().get();if(n!==t||r!==t||i!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function Nc(e){e.exec(`
|
|
71
|
+
CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
72
|
+
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
73
|
+
SELECT g.symbol
|
|
74
|
+
FROM main.defn_enclosing_ranges r
|
|
75
|
+
JOIN main.documents d ON d.id = r.document_id
|
|
76
|
+
JOIN main.global_symbols g ON g.id = r.symbol_id
|
|
77
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path;
|
|
78
|
+
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
79
|
+
SELECT g.symbol
|
|
80
|
+
FROM main.mentions m
|
|
81
|
+
JOIN main.chunks c ON c.id = m.chunk_id
|
|
82
|
+
JOIN main.documents d ON d.id = c.document_id
|
|
83
|
+
JOIN main.global_symbols g ON g.id = m.symbol_id
|
|
84
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
85
|
+
WHERE m.role = 1;
|
|
86
|
+
|
|
87
|
+
CREATE TEMP TABLE incremental_new_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
88
|
+
INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
|
|
89
|
+
SELECT g.symbol
|
|
90
|
+
FROM incremental.defn_enclosing_ranges r
|
|
91
|
+
JOIN incremental.global_symbols g ON g.id = r.symbol_id;
|
|
92
|
+
INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
|
|
93
|
+
SELECT g.symbol
|
|
94
|
+
FROM incremental.mentions m
|
|
95
|
+
JOIN incremental.global_symbols g ON g.id = m.symbol_id
|
|
96
|
+
WHERE m.role = 1;
|
|
97
|
+
`)}function Gc(e){let t=e.prepare(`WITH changed_symbols AS (
|
|
98
|
+
SELECT symbol FROM temp.incremental_old_defined_symbols
|
|
99
|
+
UNION
|
|
100
|
+
SELECT symbol FROM temp.incremental_new_defined_symbols
|
|
101
|
+
), unaffected_definitions AS (
|
|
102
|
+
SELECT g.symbol
|
|
103
|
+
FROM main.defn_enclosing_ranges r
|
|
104
|
+
JOIN main.documents d ON d.id = r.document_id
|
|
105
|
+
JOIN main.global_symbols g ON g.id = r.symbol_id
|
|
106
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
107
|
+
WHERE p.relative_path IS NULL
|
|
108
|
+
UNION
|
|
109
|
+
SELECT g.symbol
|
|
110
|
+
FROM main.mentions m
|
|
111
|
+
JOIN main.chunks c ON c.id = m.chunk_id
|
|
112
|
+
JOIN main.documents d ON d.id = c.document_id
|
|
113
|
+
JOIN main.global_symbols g ON g.id = m.symbol_id
|
|
114
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
115
|
+
WHERE m.role = 1 AND p.relative_path IS NULL
|
|
116
|
+
)
|
|
117
|
+
SELECT u.symbol
|
|
118
|
+
FROM unaffected_definitions u
|
|
119
|
+
JOIN changed_symbols c ON c.symbol = u.symbol
|
|
120
|
+
LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function $c(e){e.exec(`
|
|
121
|
+
DELETE FROM main.mentions
|
|
122
|
+
WHERE chunk_id IN (
|
|
123
|
+
SELECT c.id
|
|
124
|
+
FROM main.chunks c
|
|
125
|
+
JOIN main.documents d ON d.id = c.document_id
|
|
126
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
127
|
+
);
|
|
128
|
+
DELETE FROM main.chunks
|
|
129
|
+
WHERE document_id IN (
|
|
130
|
+
SELECT d.id
|
|
131
|
+
FROM main.documents d
|
|
132
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
133
|
+
);
|
|
134
|
+
DELETE FROM main.defn_enclosing_ranges
|
|
135
|
+
WHERE document_id IN (
|
|
136
|
+
SELECT d.id
|
|
137
|
+
FROM main.documents d
|
|
138
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
139
|
+
);
|
|
140
|
+
DELETE FROM main.documents
|
|
141
|
+
WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
|
|
142
|
+
`)}function Vc(e){e.exec(`
|
|
143
|
+
UPDATE main.global_symbols
|
|
144
|
+
SET display_name = NULL,
|
|
145
|
+
kind = NULL,
|
|
146
|
+
documentation = NULL,
|
|
147
|
+
signature = NULL,
|
|
148
|
+
enclosing_symbol = NULL,
|
|
149
|
+
relationships = NULL
|
|
150
|
+
WHERE symbol IN (SELECT symbol FROM temp.incremental_old_defined_symbols);
|
|
151
|
+
|
|
152
|
+
INSERT OR IGNORE INTO main.global_symbols(
|
|
153
|
+
symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
|
|
154
|
+
)
|
|
155
|
+
SELECT symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
|
|
156
|
+
FROM incremental.global_symbols;
|
|
157
|
+
|
|
158
|
+
UPDATE main.global_symbols
|
|
159
|
+
SET display_name = (
|
|
160
|
+
SELECT source.display_name FROM incremental.global_symbols source
|
|
161
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
162
|
+
),
|
|
163
|
+
kind = (
|
|
164
|
+
SELECT source.kind FROM incremental.global_symbols source
|
|
165
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
166
|
+
),
|
|
167
|
+
documentation = (
|
|
168
|
+
SELECT source.documentation FROM incremental.global_symbols source
|
|
169
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
170
|
+
),
|
|
171
|
+
signature = (
|
|
172
|
+
SELECT source.signature FROM incremental.global_symbols source
|
|
173
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
174
|
+
),
|
|
175
|
+
enclosing_symbol = (
|
|
176
|
+
SELECT source.enclosing_symbol FROM incremental.global_symbols source
|
|
177
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
178
|
+
),
|
|
179
|
+
relationships = (
|
|
180
|
+
SELECT source.relationships FROM incremental.global_symbols source
|
|
181
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
182
|
+
)
|
|
183
|
+
WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
|
|
184
|
+
`)}function Bc(e){let t=oe(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=oe(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=oe(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)
|
|
185
|
+
SELECT id + ?, language, relative_path, position_encoding, text
|
|
186
|
+
FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
|
|
187
|
+
SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
|
|
188
|
+
FROM incremental.chunks`).run(n,t),e.prepare(`INSERT INTO main.mentions(chunk_id, symbol_id, role)
|
|
189
|
+
SELECT m.chunk_id + ?, target.id, m.role
|
|
190
|
+
FROM incremental.mentions m
|
|
191
|
+
JOIN incremental.global_symbols source ON source.id = m.symbol_id
|
|
192
|
+
JOIN main.global_symbols target ON target.symbol = source.symbol`).run(n),e.prepare(`INSERT INTO main.defn_enclosing_ranges(
|
|
193
|
+
id, document_id, symbol_id, start_line, start_char, end_line, end_char
|
|
194
|
+
)
|
|
195
|
+
SELECT r.id + ?, r.document_id + ?, target.id,
|
|
196
|
+
r.start_line, r.start_char, r.end_line, r.end_char
|
|
197
|
+
FROM incremental.defn_enclosing_ranges r
|
|
198
|
+
JOIN incremental.global_symbols source ON source.id = r.symbol_id
|
|
199
|
+
JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function Wc(e){e.exec(`
|
|
200
|
+
DELETE FROM main.global_symbols
|
|
201
|
+
WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
|
|
202
|
+
AND NOT EXISTS (
|
|
203
|
+
SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
|
|
204
|
+
);
|
|
205
|
+
`)}function qc(e,t,n){let r=oe(e,"SELECT COUNT(*) AS value FROM main.documents"),i=oe(e,`SELECT COUNT(*) AS value
|
|
206
|
+
FROM main.documents d
|
|
207
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(r!==n||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly");let o=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),a=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(o!==void 0||a!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function Uc(e){let t=xn(e,"main",!0),n=xn(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 xn(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
|
|
208
|
+
FROM ${t}.documents d
|
|
209
|
+
${r}
|
|
210
|
+
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
|
|
211
|
+
FROM ${t}.chunks c
|
|
212
|
+
JOIN ${t}.documents d ON d.id = c.document_id
|
|
213
|
+
${r}
|
|
214
|
+
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,
|
|
215
|
+
g.symbol, g.display_name, g.kind, g.documentation,
|
|
216
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature,
|
|
217
|
+
g.enclosing_symbol,
|
|
218
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships
|
|
219
|
+
FROM ${t}.defn_enclosing_ranges r
|
|
220
|
+
JOIN ${t}.documents d ON d.id = r.document_id
|
|
221
|
+
JOIN ${t}.global_symbols g ON g.id = r.symbol_id
|
|
222
|
+
${r}
|
|
223
|
+
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
|
|
224
|
+
FROM ${t}.mentions m
|
|
225
|
+
JOIN ${t}.chunks c ON c.id = m.chunk_id
|
|
226
|
+
JOIN ${t}.documents d ON d.id = c.document_id
|
|
227
|
+
JOIN ${t}.global_symbols g ON g.id = m.symbol_id
|
|
228
|
+
${r}
|
|
229
|
+
ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[u,l]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let p of l){let g=JSON.stringify([u,p]),f=c.get(p.relative_path)??[];f.push(g),c.set(p.relative_path,f)}let d=new Map;for(let[u,l]of[...c].sort(([p],[g])=>p.localeCompare(g))){let p=Fc("sha256");for(let g of l.sort())p.update(g).update(`
|
|
230
|
+
`);d.set(u,p.digest("hex"))}return d}function oe(e,t){return e.prepare(t).get().value}import Hc from"better-sqlite3";var gt="idx_mentions_definitions",zc=["symbol_id","chunk_id"];function In(e){let t=new Hc(e),n=[],r=[],i=[];try{return t.transaction(()=>{Jc(t,n),mt(t,"idx_global_symbols_symbol")?.join("\0")==="symbol"&&Ui(t,"global_symbols").some(s=>s.name!=="idx_global_symbols_symbol"&&s.unique&&s.columns.join("\0")==="symbol")?(t.exec('DROP INDEX "idx_global_symbols_symbol"'),r.push("idx_global_symbols_symbol")):mt(t,"idx_global_symbols_symbol")&&i.push("idx_global_symbols_symbol");let o=mt(t,"idx_chunks_doc_id"),a=Ui(t,"chunks").some(s=>s.name!=="idx_chunks_doc_id"&&s.columns.length>1&&s.columns[0]==="document_id");o?.join("\0")==="document_id"&&a?(t.exec('DROP INDEX "idx_chunks_doc_id"'),r.push("idx_chunks_doc_id")):o&&i.push("idx_chunks_doc_id"),t.exec("ANALYZE")})(),{added:n,removed:r,retained:i,analyzed:!0}}catch(o){if(o.code==="SQLITE_NOTADB")return{added:[],removed:[],retained:[],analyzed:!1,skippedReason:"not-a-sqlite-database"};throw o}finally{t.close()}}function Jc(e,t){let n=Hi(e,gt);if(n){let r=n.columns.join("\0")===zc.join("\0"),i=/\bWHERE\s+role\s*=\s*1\b/iu.test(n.sql??"");if(!r||!i||n.table!=="mentions")throw new Error(`${gt} exists with an incompatible definition`);return}e.exec(`CREATE INDEX "${gt}" ON mentions(symbol_id, chunk_id) WHERE role = 1`),t.push(gt)}function Ui(e,t){return e.prepare(`PRAGMA index_list('${t.replaceAll("'","''")}')`).all().map(n=>({name:n.name,unique:n.unique===1,columns:mt(e,n.name)??[]}))}function mt(e,t){return Hi(e,t)?.columns??null}function Hi(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 Yc}from"fs";function B(e,t){let n=performance.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}function Ji(e){let t=e.readFingerprint(),n=Ki(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return Xi(e.cachePath,e.readFingerprint(),r),r}async function Yi(e){let t=e.readFingerprint(),n=Ki(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=await e.compute();return Xi(e.cachePath,e.readFingerprint(),r),r}function Ki(e,t){try{let n=JSON.parse(w(e,{maxBytes:A,inputKind:"post-index augmentation cache"}));return zi(n.fingerprint)===zi(t)?{result:n.result}:null}catch{return null}}function Xi(e,t,n){Yc(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
|
|
231
|
+
`)}function zi(e){return JSON.stringify(e)}import{createHash as Kc}from"crypto";import{existsSync as Pn,readdirSync as Xc}from"fs";import{dirname as vn,join as ht,relative as Qc,resolve as wn,sep as Qi}from"path";function Zi(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=ro(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function eo(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);if(!o||o.parseFailed){for(let s of e)s!==i&&a.add(s);continue}for(let s of o.dependencyNames){let c=n.get(s);c&&c!==i&&a.add(c)}for(let s of[...o.pathsTargets,...o.referencesPaths]){let c=ro(s,e);c&&c!==i&&a.add(c)}}return Zc(e,r)}function to(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 En(e){if(e===".")return"root";let t=Kc("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function no(e,t){let n=wn(e),r={};for(let i of t)r[i]=ed(n,i);return r}function ro(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 Zc(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 ed(e,t){let n=t==="."?e:ht(e,t),r=td(n),i=nd(n),o=i?rd(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 td(e){let t=ht(e,"package.json");if(!Pn(t))return{name:void 0,dependencyNames:[],failed:!1};let n=kn(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 nd(e){let t=ht(e,"tsconfig.json");if(Pn(t))return t;let n;try{n=Xc(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?ht(e,n[0]):void 0}function rd(e,t){let n=kn(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=id(n.value,e,t),i=io(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function id(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=vn(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=oo(s,i,n);c&&o.add(c)}return[...o]}function io(e,t,n,r){let i=od(t);if(i)return{pathsTargets:ad(i,vn(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=sd(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=kn(o);return a.ok?io(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function od(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 ad(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=oo(o,t,n);a&&r.add(a)}return[...r]}function sd(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=wn(vn(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Qi).includes("node_modules")&&$t(n,i)&&Pn(i))return i}function oo(e,t,n){let r=e.replace(/\/?\*+$/,""),i=wn(t,r===""?".":r);if(!$t(n,i))return;let a=Qc(n,i).split(Qi).join("/");return a===""?".":a}function cd(e){let t="",n=0,r=!1,i=e.length;for(;n<i;){let o=e[n];if(r){if(t+=o,o==="\\"&&n+1<i){t+=e[n+1],n+=2;continue}o==='"'&&(r=!1),n+=1;continue}if(o==='"'){r=!0,t+=o,n+=1;continue}if(o==="/"&&e[n+1]==="/"){for(n+=2;n<i&&e[n]!==`
|
|
232
|
+
`;)n+=1;continue}if(o==="/"&&e[n+1]==="*"){for(n+=2;n<i&&!(e[n]==="*"&&e[n+1]==="/");)n+=1;n+=2;continue}t+=o,n+=1}return t}function kn(e){try{let t=w(e,{maxBytes:A,inputKind:"TypeScript project manifest"}),n=JSON.parse(cd(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as Xo,randomUUID as Wd}from"crypto";import{existsSync as se,lstatSync as Jn,mkdirSync as Ee,mkdtempSync as Qo,readdirSync as Zo,realpathSync as ea,renameSync as me,rmSync as ae,statSync as wt}from"fs";import{dirname as Yn,join as m,resolve as Kn}from"path";import{setTimeout as qd}from"timers/promises";import{pathToFileURL as zo}from"url";import{deserializeSCIP as ta}from"@c4312/scip";import Ud from"better-sqlite3";import{lstatSync as Id,readdirSync as Pd}from"fs";import{join as vd,relative as wd,resolve as jn,sep as Ed}from"path";import{createHash as dd}from"crypto";import{existsSync as je,mkdirSync as ud,readdirSync as ao,renameSync as ld,rmSync as so,writeFileSync as pd}from"fs";import{join as J}from"path";import{create as uo,fromBinary as lo,toBinary as fd}from"@bufbuild/protobuf";import{deserializeSCIP as yt,DocumentSchema as Dn,IndexSchema as po,serializeSCIP as fo}from"@c4312/scip";var St=1,Me="typescript-scip-fragments";function go(e){if(e.length===0)throw new Error("affected TypeScript mini index requires documents");let t=new Set,n=[];for(let o of e){let a=fe(o.relativePath);if(t.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(t.add(a),o.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${a}`);let s=lo(Dn,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=fo(uo(po,{documents:n,externalSymbols:[]})),i=yt(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function Ne(e){let t=J(e,Me);return{rootDir:t,blobDir:J(t,"blobs"),generationDir:J(t,"generations")}}function gd(e){let t=yt(e.indexBytes);ko(t.metadata,To(e)),Eo(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let a=fe(o.relativePath);if(n.has(a))throw new Error(`duplicate TypeScript SCIP document path: ${a}`);n.add(a);let s=fd(Dn,o),c=e.documentIdentities.get(a)??(e.allowUntrackedDocuments?ge(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:a,contentHash:ge(s)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${a}`);r.push(Io(e.cacheDir,{relativePath:a,bytes:s,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=Po(e,r);return vo(e.cacheDir,i),i}function mo(e){let t=Ne(e.cacheDir);if(!je(An(t,e.generationIdentity)))return gd(e);let n=yo({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity});if(!e.allowUntrackedDocuments&&n.manifest.documents.length!==e.documentIdentities.size)throw new Error("TypeScript fragment generation document identities changed");for(let r of n.manifest.documents){let i=e.documentIdentities.get(r.relativePath);if(!(i===void 0&&e.allowUntrackedDocuments)&&i!==r.documentIdentity)throw new Error(`TypeScript fragment generation document identity changed: ${r.relativePath}`)}return n.manifest}function ho(e){let t=yo({cacheDir:e.cacheDir,generationIdentity:e.previousGenerationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity}).manifest,n=new Map(t.documents.map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let a=fe(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(r.add(a),!n.has(a))throw new Error(`TypeScript fragment replacement has no prior document: ${a}`);let s=e.documentIdentities.get(a);if(!s)throw new Error(`missing TypeScript document identity: ${a}`);o.bytes===null?n.delete(a):n.set(a,Io(e.cacheDir,o,s))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=Po(e,[...n.values()]);return vo(e.cacheDir,i),i}function yo(e){let t=Ne(e.cacheDir),n=An(t,e.generationIdentity),r;try{r=Fn(w(n,{maxBytes:A,inputKind:"TypeScript fragment manifest"}))}catch(o){throw new Error(`TypeScript fragment generation is unavailable: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(r.generationIdentity!==e.generationIdentity)throw new Error("TypeScript fragment generation identity does not match its manifest path");if(e.producerIdentity&&r.producerIdentity!==e.producerIdentity)throw new Error("TypeScript fragment producer identity changed");if(e.projectIdentity&&r.projectIdentity!==e.projectIdentity)throw new Error("TypeScript fragment project identity changed");let i=new Map;for(let o of r.documents){let a=J(t.blobDir,`${o.blobHash}.scipdoc`),s=D(a,{maxBytes:H,inputKind:"TypeScript fragment blob"});if(s.byteLength!==o.byteLength||ge(s)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,s)}return{manifest:r,fragments:i}}function So(e){let t=Ro(e);return Tn(t.baseIndex,t.completeDocuments,"assembled")}function bo(e){let t=Ro(e);return md(t.deletedAffectedPaths),{completeIndexBytes:Tn(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:Tn(t.baseIndex,t.affectedDocuments,"affected")}}function Ro(e){let t=yt(e.baseIndexBytes);ko(t.metadata,To(e)),Eo(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=fe(s.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);n.set(c,s)}if(n.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let r=new Set,i=[],o=[],a=[];for(let s of t.documents){let c=fe(s.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let d=n.get(c);if(!d){i.push(s);continue}if(n.delete(c),d.bytes===null){a.push(c);continue}let u=lo(Dn,d.bytes);if(u.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${u.relativePath}`);i.push(u),o.push(u)}if(n.size>0)throw new Error(`TypeScript fragment replacement has no prior document: ${[...n.keys()].sort()[0]}`);return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:a}}function Tn(e,t,n){let r=fo(uo(po,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=yt(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function md(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function xo(e,t){let n=Ne(e);if(!je(n.generationDir))return;let r=new Set(t.map(a=>wo(a))),i=ao(n.generationDir).filter(a=>a.endsWith(".json")),o=new Set;for(let a of i.filter(s=>r.has(s))){let s=Fn(w(J(n.generationDir,a),{maxBytes:A,inputKind:"TypeScript fragment manifest"}));for(let c of s.documents)o.add(`${c.blobHash}.scipdoc`)}for(let a of i)r.has(a)||so(J(n.generationDir,a),{force:!0});if(je(n.blobDir))for(let a of ao(n.blobDir))o.has(a)||so(J(n.blobDir,a),{force:!0})}function Io(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=fe(t.relativePath),i=Buffer.from(t.bytes),o=ge(i),a=Ne(e);ud(a.blobDir,{recursive:!0});let s=J(a.blobDir,`${o}.scipdoc`);if(je(s)){let c=D(s,{maxBytes:H,inputKind:"TypeScript fragment blob"});if(c.byteLength!==i.byteLength||ge(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${s}.${process.pid}.${Date.now()}.tmp`;pd(c,i),ld(c,s)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function Po(e,t){if(!e.producerIdentity||!e.projectIdentity||!e.generationIdentity)throw new Error("TypeScript fragment generation identities must be non-empty");let n=[...t].sort((r,i)=>r.relativePath.localeCompare(i.relativePath));if(new Set(n.map(r=>r.relativePath)).size!==n.length)throw new Error("TypeScript fragment generation contains duplicate document paths");return{version:St,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function vo(e,t){let n=Ne(e),r=An(n,t.generationIdentity);if(je(r)){let i=Fn(w(r,{maxBytes:A,inputKind:"TypeScript fragment manifest"}));if(co(i)!==co(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}re(r,t,{spacing:2,trailingNewline:!0})}function co(e){return ge(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function Fn(e){let t=JSON.parse(e);if(t.version!==St||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let n=new Set;for(let r of t.documents){if(!r||typeof r.relativePath!="string"||typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash)||typeof r.byteLength!="number"||!Number.isInteger(r.byteLength)||r.byteLength<0||typeof r.documentIdentity!="string"||!r.documentIdentity)throw new Error("invalid TypeScript fragment record");if(fe(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function An(e,t){return J(e.generationDir,wo(t))}function wo(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${ge(e)}.json`}function Eo(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function ko(e,t){if(!e||typeof e!="object")throw new Error("TypeScript SCIP shard has no producer metadata");let n=e,r=n.toolInfo??n.tool_info;if(!r||typeof r!="object")throw new Error("TypeScript SCIP shard has no producer tool identity");let i=r;if(i.name!=="scip-typescript"||i.version!==t)throw new Error("TypeScript SCIP shard producer identity changed")}function To(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function fe(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.includes("\\"))throw new Error(`invalid TypeScript SCIP document path: ${e}`);let t=e.split("/");if(t.includes("")||t.includes(".")||t.includes(".."))throw new Error(`invalid TypeScript SCIP document path: ${e}`);return e}function ge(e){return dd("sha256").update(e).digest("hex")}import{createHash as hd}from"crypto";import{existsSync as Ge,mkdirSync as yd,readdirSync as On,renameSync as Sd,rmSync as Do,writeFileSync as bd}from"fs";import{join as V}from"path";var bt=1,Ao=64*1024*1024,Ve="typescript-scip-overlays";function Oo(e){let t=Lo(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t&&(t.producerIdentity!==e.producerIdentity||t.projectIdentity!==e.projectIdentity))throw new Error("TypeScript overlay producer or project identity changed");let n=new Map((t?.overlays??[]).map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let a=Ln(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript overlay: ${a}`);r.add(a),n.set(a,Rd(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:bt,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...n.values()].sort((o,a)=>o.relativePath.localeCompare(a.relativePath))};return xd(e.cacheDir,i),i}function Co(e){let t=Lo(e.cacheDir,e.generationIdentity);if(!t)throw new Error("TypeScript overlay generation is unavailable");let n=t.overlays.map(r=>{if(r.blobHash===null)return{relativePath:r.relativePath,bytes:null,occurrences:0,symbols:0,referenceFragments:[]};let i=D(V(Be(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`),{maxBytes:H,inputKind:"TypeScript overlay blob"});if(i.byteLength!==r.byteLength||$e(i)!==r.blobHash)throw new Error(`TypeScript overlay blob is corrupt: ${r.relativePath}`);return{relativePath:r.relativePath,bytes:i,occurrences:0,symbols:0,referenceFragments:[]}});return So({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function _o(e,t){let n=Be(e),r=V(n,"generations");if(!Ge(r))return;let i=new Set(t.map(_n)),o=new Set;for(let s of On(r).filter(c=>i.has(c))){let c=Cn(w(V(r,s),{maxBytes:A,inputKind:"TypeScript overlay manifest"}));for(let d of c.overlays)d.blobHash&&o.add(`${d.blobHash}.scipdoc`)}for(let s of On(r))i.has(s)||Do(V(r,s),{force:!0});let a=V(n,"blobs");if(Ge(a))for(let s of On(a))o.has(s)||Do(V(a,s),{force:!0})}function Lo(e,t){let n=V(Be(e),"generations",_n(t));if(!Ge(n))return null;let r=Cn(w(n,{maxBytes:A,inputKind:"TypeScript overlay manifest"}));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function Rd(e,t){let n=Ln(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=$e(r),o=V(Be(e),"blobs");yd(o,{recursive:!0});let a=V(o,`${i}.scipdoc`);if(Ge(a)){let s=D(a,{maxBytes:H,inputKind:"TypeScript overlay blob"});if(s.byteLength!==r.byteLength||$e(s)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let s=`${a}.${process.pid}.${Date.now()}.tmp`;bd(s,r),Sd(s,a)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function xd(e,t){let n=V(Be(e),"generations",_n(t.generationIdentity));if(Ge(n)){let r=Cn(w(n,{maxBytes:A,inputKind:"TypeScript overlay manifest"}));if(Fo(r)!==Fo(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}re(n,t,{spacing:2,trailingNewline:!0})}function Cn(e){let t=JSON.parse(e);if(t.version!==bt||typeof t.producerIdentity!="string"||!t.producerIdentity||typeof t.projectIdentity!="string"||!t.projectIdentity||typeof t.baseGenerationIdentity!="string"||!t.baseGenerationIdentity||typeof t.generationIdentity!="string"||!t.generationIdentity||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.overlays))throw new Error("invalid TypeScript overlay manifest");let n=new Set;for(let r of t.overlays){if(!r||typeof r.relativePath!="string"||r.blobHash!==null&&(typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash))||!Number.isInteger(r.byteLength)||r.byteLength<0||r.blobHash===null&&r.byteLength!==0)throw new Error("invalid TypeScript overlay record");if(Ln(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function Be(e){return V(e,Ve)}function _n(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${$e(e)}.json`}function Fo(e){return $e(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function Ln(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}function $e(e){return hd("sha256").update(e).digest("hex")}var We=1,Mn="language-indexes",jo=["index.db","index.scip","meta.json"],Mo=[Mn,Me,Ve];function Rt(e){let t=[];for(let n of jo)kd(e,n),t.push(n);for(let n of Mo)No(e,n,t);return{version:We,files:t.sort()}}function xt(e){if(!e||e.includes("\0")||e.startsWith("/")||e.includes("\\"))throw new Error(`invalid index artifact path: ${e||"<empty>"}`);let t=e.split("/");if(t.some(r=>!r||r==="."||r===".."))throw new Error(`invalid index artifact path: ${e}`);let n=t[0];if(!jo.includes(e)&&!Mo.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function W(e,t){let n=xt(t),r=jn(e),i=jn(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${Ed}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function No(e,t,n){let r=vd(e,t),i;try{i=Pd(r,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(let o of i){let a=`${t}/${o.name}`;if(o.isSymbolicLink())throw new Error(`index artifact cannot be a symlink: ${a}`);o.isDirectory()?No(e,a,n):o.isFile()&&n.push(xt(a))}}function kd(e,t){let n=W(e,t),r;try{r=Id(n)}catch{throw new Error(`required index artifact is missing: ${t}`)}if(!r.isFile()||r.isSymbolicLink())throw new Error(`required index artifact is not a regular file: ${t}`);if(wd(jn(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{createHash as Bn}from"crypto";import{closeSync as Td,existsSync as E,mkdirSync as Dd,openSync as Fd,readSync as Ad,readdirSync as Wn,renameSync as Vn,rmSync as qe,statSync as we}from"fs";import{basename as Bo,dirname as q,join as R,relative as Go}from"path";var Od=Object.freeze({maxGenerations:2,maxLogicalBytes:2*1024*1024*1024});function Pt(e){let t=$(e.outputDb),n=jd(e);e.onStage?.("after-recovery-retained");let r=e.preserveOutputScip?e.outputScip:e.tempOutputScip,i=zn({generationRoot:t,databasePath:e.tempOutputDb,indexPath:E(r)?r:void 0,metadataPath:E(e.tempMetaPath)?e.tempMetaPath:void 0}),o=(e.now??(()=>new Date))().toISOString(),a={version:be,currentGeneration:i.identity,artifactSet:"immutable-v1",...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:o},s=G(R(t,"state.json"),a,{spacing:2,trailingNewline:!0});e.onStage?.("after-pointer-handoff"),e.preserveOutputScip||$n(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),$n(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),$n(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let c=i.identity,d={...a,stableMirrors:Hn(e.outputDb,e.outputScip)};G(R(t,"state.json"),d,{spacing:2,trailingNewline:!0});let u=Wo(e.outputDb,{now:e.now}),l=Oe(i.directorySync,s.directorySync);return{currentGeneration:c,...n?{previousGeneration:n}:{},retention:u,achievedDurability:l==="synced"?"directory-durable":"file-flushed",directorySync:l}}function qn(e,t,n,r=()=>new Date){if(!E(e))return null;let i=Ce(e),o=R($(e),"state.json");if(i?.artifactSet==="immutable-v1"&&Ut(e,i.currentGeneration))return i;let a=$(e),s=!i&&E(o)?Nd(n,e,t):void 0;if(s&&!rt(a,s))return null;let c=zn({generationRoot:a,databasePath:e,indexPath:E(t)?t:void 0,metadataPath:E(n)?n:void 0,forcedIdentity:i?.currentGeneration??s}),d={version:be,currentGeneration:c.identity,artifactSet:"immutable-v1",stableMirrors:Hn(e,t),...i?.previousGeneration?{previousGeneration:i.previousGeneration}:{},...i?.publication?{publication:i.publication}:{},publishedAt:i?.publishedAt??r().toISOString()};return G(R(a,"state.json"),d,{spacing:2,trailingNewline:!0}),d}function Un(e,t,n=()=>new Date){if(!E(e)||!E(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=Ce(e),i=$(e),o=zn({generationRoot:i,databasePath:e,indexPath:E(R(q(e),"index.scip"))?R(q(e),"index.scip"):void 0,metadataPath:t}),a=r&&r.currentGeneration!==o.identity?Uo(e,r.currentGeneration):void 0,s={version:be,currentGeneration:o.identity,artifactSet:"immutable-v1",stableMirrors:Hn(e,R(q(e),"index.scip")),...a?{previousGeneration:a}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return G(R($(e),"state.json"),s,{spacing:2,trailingNewline:!0}),Wo(e,{now:n}),s}function Wo(e,t={}){let n=Cd(t.limits),i=(t.now??(()=>new Date))().toISOString(),o=de(Nr(e),{waitMs:0});if(!o)return{state:"deferred",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,staleReaderLeasesRemoved:0,malformedReaderLeases:0,removedGenerations:0,removedLogicalBytes:0,limits:n,at:i,reason:"another process owns local generation retention"};try{let a=Ce(e),s=_d(e),c=Gr(e,s.map(b=>b.identity),{isProcessAlive:t.isProcessAlive??te,readProcessIdentity:t.readProcessIdentity??ee}),d=new Set(c.protectedGenerations);a?.currentGeneration&&d.add(a.currentGeneration),a?.previousGeneration?.generationIdentity&&d.add(a.previousGeneration.generationIdentity);let u=s.length,l=s.reduce((b,y)=>b+y.logicalBytes,0),p=0,g=0;for(let b of s){if(u<=n.maxGenerations&&l<=n.maxLogicalBytes)break;d.has(b.identity)||(t.onBeforeRemove?.(b.identity),qe(b.path,{recursive:!0,force:!0}),u-=1,l-=b.logicalBytes,p+=1,g+=b.logicalBytes)}let f=u>n.maxGenerations||l>n.maxLogicalBytes,h={state:f?"protected":p>0?"collected":"within-bounds",generationCount:u,logicalBytes:l,protectedGenerations:d.size,activeReaderLeases:c.activeLeases,staleReaderLeasesRemoved:c.staleLeasesRemoved,malformedReaderLeases:c.malformedLeases,removedGenerations:p,removedLogicalBytes:g,limits:n,at:i,...f?{reason:c.malformedLeases>0?"malformed reader ownership evidence fails closed":"retention bounds cannot be met without deleting a protected generation"}:{}};return $o(e,h),h}catch(a){let s={state:"error",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,staleReaderLeasesRemoved:0,malformedReaderLeases:0,removedGenerations:0,removedLogicalBytes:0,limits:n,at:i,reason:a instanceof Error?a.message:String(a)};try{$o(e,s)}catch{}return s}finally{o.release()}}function Cd(e={}){let t={...Od,...e};if(!Number.isSafeInteger(t.maxGenerations)||t.maxGenerations<2)throw new Error("Local SQLite generation retention must keep at least current and previous generations.");if(!Number.isSafeInteger(t.maxLogicalBytes)||t.maxLogicalBytes<=0)throw new Error("Local SQLite generation byte retention must be a positive safe integer.");return t}function _d(e){let t=$(e);return E(t)?Wn(t,{withFileTypes:!0}).filter(n=>n.isDirectory()&&/^[a-f0-9]{64}$/.test(n.name)).map(n=>{let r=R(t,n.name),i=rt(t,n.name),o=i?i.database.size+(i.index?.size??0)+(i.metadata?.size??0):qo(r);return{identity:n.name,path:r,logicalBytes:o,modifiedAtMs:we(r).mtimeMs}}).sort((n,r)=>n.modifiedAtMs-r.modifiedAtMs||n.identity.localeCompare(r.identity)):[]}function qo(e){let t=0;for(let n of Wn(e,{withFileTypes:!0})){let r=R(e,n.name);n.isDirectory()?t+=qo(r):n.isFile()&&(t+=we(r).size)}return t}function $o(e,t){re(R($(e),"gc.json"),t,{spacing:2,trailingNewline:!0})}function U(e,t=R(q(e),"meta.json")){let n=R($(e),"state.json");if(!E(n))return{state:"legacy",statePath:n};let r=Ce(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=Ut(e,r.currentGeneration),o=i!==null,a=i?Ld(e,t,i,r):!1,s=r.previousGeneration?E(R(q(e),r.previousGeneration.databasePath)):!0;return!a||!o||!s?{state:"drifted",statePath:n,currentMatches:a,recoveryExists:s,generation:r,reason:o?a?"retained recovery database is missing":"stable database or metadata no longer matches the published generation":"published immutable generation is missing"}:{state:"current",statePath:n,currentMatches:a,recoveryExists:s,generation:r}}catch(i){return{state:"drifted",statePath:n,currentMatches:!1,recoveryExists:!1,generation:r,reason:i instanceof Error?i.message:String(i)}}}function Ld(e,t,n,r){if(r.stableMirrors&&(r.stableMirrors.databaseFileIdentity!==_e(e)||r.stableMirrors.indexFileIdentity!==void 0&&r.stableMirrors.indexFileIdentity!==_e(R(q(e),"index.scip")))||!Vo(e,n.database))return!1;let i=R(q(e),"index.scip");if(n.index&&!Vo(i,n.index))return!1;if(!n.metadata)return!E(t);if(!E(t))return!1;let o=R($(e),n.identity,n.metadata.file);return E(o)&&ue(L(t,"reindex metadata"))===ue(L(o,"immutable reindex metadata"))}function Vo(e,t){return E(e)&&we(e).isFile()&&we(e).size===t.size}function jd(e){let t=qn(e.outputDb,e.outputScip,e.metaPath);return t?Uo(e.outputDb,t.currentGeneration):void 0}function Hn(e,t){return{databaseFileIdentity:_e(e),...E(t)?{indexFileIdentity:_e(t)}:{}}}function Uo(e,t){let n=R($(e),t),r=R(n,Bo(e)),i=R(n,"meta.json");return{generationIdentity:t,databasePath:Go(q(e),r),...E(i)?{metadataPath:Go(q(e),i)}:{}}}function Md(e){if(E(e)){for(let t of Wn(e,{withFileTypes:!0}))if(t.isDirectory()&&t.name.endsWith(".tmp"))try{qe(R(e,t.name),{recursive:!0,force:!0})}catch{}}}function Nd(e,t,n=R(q(t),"index.scip")){let r=Bn("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(It(t)),E(n)&&r.update(`\0${It(n)}`),E(e)&&r.update(`\0${ue(L(e,"reindex metadata"))}`),r.digest("hex")}function zn(e){let t=Nn(e.databasePath),n=e.indexPath?Nn(e.indexPath):void 0,r=e.metadataPath?Nn(e.metadataPath):void 0,i=e.forcedIdentity??Gd(t,n,e.metadataPath),o=R(e.generationRoot,i),a=R(o,qt);if(E(a)){let d=rt(e.generationRoot,i);if(d&&Ho(o,d.database,t)&&Vd(o,d.index,n)&&Bd(o,d.metadata,e.metadataPath))return{identity:i,directorySync:ne(e.generationRoot)};throw new Error(`SQLite generation ${i} already exists with different or corrupt artifacts.`)}let s=[et(e.generationRoot)];Md(e.generationRoot);let c=`${o}.${process.pid}.${Date.now()}.tmp`;qe(c,{recursive:!0,force:!0}),Dd(c,{recursive:!0});try{s.push(Gn(e.databasePath,R(c,t.file))),n&&e.indexPath&&s.push(Gn(e.indexPath,R(c,n.file))),r&&e.metadataPath&&s.push(Gn(e.metadataPath,R(c,r.file)));let d=G(R(c,qt),{version:Mr,identity:i,database:t,...n?{index:n}:{},...r?{metadata:r}:{}},{spacing:2,trailingNewline:!0});d.directorySync!=="not-requested"&&s.push(d.directorySync),s.push(ne(c)),F(()=>Vn(c,o)),s.push(ne(e.generationRoot))}finally{try{qe(c,{recursive:!0,force:!0})}catch{}}return{identity:i,directorySync:Oe(...s)}}function Gd(e,t,n){let r=Bn("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(e.sha256),t&&r.update(`\0${t.sha256}`),n&&r.update(`\0${ue(L(n,"reindex metadata"))}`),r.digest("hex")}function Nn(e){return{file:Bo(e),size:we(e).size,sha256:It(e)}}function It(e){let t=Bn("sha256"),n=Fd(e,"r"),r=Buffer.allocUnsafe(1024*1024);try{for(;;){let i=$d(n,r);if(i===0)break;t.update(r.subarray(0,i))}}finally{Td(n)}return t.digest("hex")}function $d(e,t){let n=0;for(;n<t.length;){let r=Ad(e,t,n,t.length-n,null);if(n+=r,r===0)break}return n}function Gn(e,t){return tt(e,t,{mode:292})}function Ho(e,t,n){let r=R(e,t.file);return t.file===n.file&&t.size===n.size&&t.sha256===n.sha256&&E(r)&&we(r).size===t.size&&It(r)===t.sha256}function Vd(e,t,n){return!t||!n?t===n:Ho(e,t,n)}function Bd(e,t,n){if(!t||!n)return t===void 0&&n===void 0;let r=R(e,t.file);return E(r)&&ue(L(r,"stored reindex metadata"))===ue(L(n,"candidate reindex metadata"))}function $n(e,t){F(()=>qe(`${t}.tmp-replace`,{force:!0})),F(()=>Vn(e,`${t}.tmp-replace`)),F(()=>Vn(`${t}.tmp-replace`,t))}var Xn=1,Jo="CODEBASEIQ_SHARED_CACHE",Hd=2,vt=JSON.stringify({cliVersion:$r,artifactCatalogVersion:We,postIndexAugmentationSchemaVersion:Hd,sqliteGenerationStoreVersion:be,typescriptFragmentStoreVersion:St,typescriptOverlayStoreVersion:bt}),Qn="manifest.json",zd="shared-cache.json",Zn=[Mn,Me,Ve];function Et(e,t){if(!e.clean||!e.treeOid)return;let n=pa(JSON.stringify({version:Xn,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:vt}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:vt,generationId:n,repositoryCacheDir:Wr(e.repositoryId)}}function na(e,t,n){if(process.env[Jo]==="0")return`${Jo}=0`;if(!qr(n))return"explicit cache or database override";if(zt(Yn(t))!==zt(Br(e))||t!==m(Yn(t),"index.db"))return"index database is outside the managed worktree cache"}function Y(e,t=!0){let n=tr(e),r;try{r=ca(w(m(n,Qn),{inputKind:"shared-generation manifest",maxBytes:A}))}catch{return null}if(r.generationId!==e.generationId||r.repositoryId!==e.repositoryId||r.treeOid!==e.treeOid||r.producerIdentity!==e.producerIdentity||JSON.stringify(r.fingerprint)!==JSON.stringify(e.fingerprint))return null;if(!t)return r;try{for(let i of r.artifacts){let o=W(n,i.path),a=wt(o);if(!a.isFile()||a.size!==i.size||Qe(o,{inputKind:"shared-generation artifact",maxBytes:_})!==i.sha256)return null}}catch{return null}return r}function ra(e,t,n){if(!e.treeOid)return null;let r=Yt(t,n),i=m(Vr(),"repositories",e.repositoryId),o;try{let c=Jn(i);if(!c.isDirectory()||c.isSymbolicLink())return null;o=ea(i)}catch{return null}let a=m(o,"generations"),s=[];try{for(let c of Zo(a)){if(!/^[a-f0-9]{64}$/.test(c))continue;let d=m(a,c),u;try{u=Jn(d)}catch{continue}if(!(!u.isDirectory()||u.isSymbolicLink()))try{let l=ca(w(m(d,Qn),{inputKind:"shared-generation baseline manifest",maxBytes:A}));l.generationId===c&&l.repositoryId===e.repositoryId&&l.treeOid===e.treeOid&&l.producerIdentity===vt&&Xd(l.fingerprint,r)&&s.push(l)}catch{continue}}}catch{return null}s.sort((c,d)=>Date.parse(d.createdAt)-Date.parse(c.createdAt)||c.generationId.localeCompare(d.generationId));for(let c of s){let d={repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:c.fingerprint,producerIdentity:c.producerIdentity,generationId:c.generationId,repositoryCacheDir:o},u=Y(d);if(u)return{snapshot:d,manifest:u}}return null}function ia(e){let t=de(m(e.snapshot.repositoryCacheDir,"locks",`${e.snapshot.generationId}.publish.lock`));if(!t)throw new Error(`shared generation publication is already in progress for ${e.snapshot.generationId}`);try{return Jd(e)}finally{t.release()}}function Jd(e){let t=Y(e.snapshot);if(t)return Yo(e.snapshot,t);if(!la(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=Ko(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=Rt(e.sourceCacheDir),i=m(e.snapshot.repositoryCacheDir,"generations"),o=[et(i)],a=Qo(m(i,`.tmp-${process.pid}-`));try{let s=[];for(let f of r.files){let h=W(e.sourceCacheDir,f),b=W(a,f);o.push(He(h,b,292)),e.onPublicationStage?.("after-artifact-flushed",f);let y=wt(b).size;s.push({path:f,size:y,sha256:Qe(b,{inputKind:"staged shared-generation artifact",maxBytes:_})})}let c=ta(D(m(a,"index.scip"),{inputKind:"staged shared SCIP index",maxBytes:_})).metadata?.projectRoot;if(!c)throw new Error("shared SCIP generation has no project root metadata");let d=nr(e.sourceProjectRoot);if(!Se(c,d))throw new Error("shared SCIP generation root does not match its source worktree");if(Ko(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let u={version:Xn,artifactCatalogVersion:We,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:c,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:s.sort((f,h)=>f.path.localeCompare(h.path))},l=G(m(a,Qn),u,{spacing:2,trailingNewline:!0});l.directorySync!=="not-requested"&&o.push(l.directorySync),e.onPublicationStage?.("after-manifest-flushed"),o.push(ne(a)),e.onPublicationStage?.("after-staging-directory-synced");let p=tr(e.snapshot);try{if(se(p)&&!Y(e.snapshot)){let f=`${p}.corrupt-${process.pid}-${Date.now()}`;F(()=>me(p,f)),ae(f,{recursive:!0,force:!0})}F(()=>me(a,p))}catch(f){let h=Y(e.snapshot);if(h)return Yo(e.snapshot,h);throw f}e.onPublicationStage?.("after-generation-renamed"),o.push(ne(i)),e.onPublicationStage?.("after-generations-directory-synced");let g=Oe(...o);return{kind:"published",manifest:u,achievedDurability:g==="synced"?"directory-durable":"file-flushed",directorySync:g}}finally{ae(a,{recursive:!0,force:!0})}}function Yo(e,t){let n=ne(m(e.repositoryCacheDir,"generations"));return{kind:"existing",manifest:t,achievedDurability:n==="synced"?"directory-durable":"file-flushed",directorySync:n}}function kt(e){let t=tr(e.snapshot);Ee(e.targetCacheDir,{recursive:!0});let n=de(m(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:3e4});if(!n)throw new Error("timed out waiting for another cache hydration");let r,i,o=!1;try{r=Qo(m(e.targetCacheDir,".shared-hydrate-")),tu(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let d=W(t,c.path),u=W(r,c.path);if(He(d,u),wt(u).size!==c.size||Qe(u,{inputKind:"hydrated shared-generation artifact",maxBytes:_})!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=nr(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&ji(W(r,c.path),e.manifest.scipProjectRoot,a);if(!la(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=Qd(e.targetCacheDir,r),o=!0,Zd(r,e.targetCacheDir,i),Pt({tempOutputScip:m(r,"index.scip"),tempOutputDb:m(r,"index.db"),tempMetaPath:m(r,"meta.json"),outputScip:m(e.targetCacheDir,"index.scip"),outputDb:m(e.targetCacheDir,"index.db"),metaPath:m(e.targetCacheDir,"meta.json"),now:e.now});let s=U(m(e.targetCacheDir,"index.db"),m(e.targetCacheDir,"meta.json"));if(s.state==="invalid"||s.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${s.reason}`);e.persistLease!==!1&&er(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&eu(e.targetCacheDir,i),a}finally{r&&ae(r,{recursive:!0,force:!0}),n.release()}}async function oa(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??I,o=i()+n,a=m(e.repositoryCacheDir,"locks"),s=m(a,`${e.generationId}.lock`),c=d=>{if(!d||typeof d!="object"||Array.isArray(d))return null;let u=d.pid;return typeof u=="number"&&Number.isSafeInteger(u)&&u>0?{pid:u}:null};for(;i()<=o;){if(Y(e))return{kind:"generation-ready"};let d=Ze(s,{kind:"shared-generation-build",detail:{generationId:e.generationId},parseLegacy:c});if(d.kind==="acquired")return{kind:"owner",release:()=>d.lock.release()};let u=o-i();if(u<=0)break;await qd(Math.min(r,u))}return Y(e)?{kind:"generation-ready"}:{kind:"timeout"}}function er(e,t,n,r=void 0){let i={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,activeGenerationId:e.generationId,lastAction:n,lastSeenAt:(r??(()=>new Date))().toISOString()},o={...i,ownershipChecksum:sa(i)};return da(e.repositoryCacheDir,o,!0),o}function aa(e,t,n=void 0){let r={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,lastAction:"overlay",lastReason:`private cache forked from shared baseline ${e.generationId}`,lastSeenAt:(n??(()=>new Date))().toISOString()},i={...r,ownershipChecksum:sa(r)};return da(e.repositoryCacheDir,i,!0),i}function sa(e){return pa(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:Kn(e.projectRoot),localCacheDir:Kn(e.localCacheDir)}))}function ca(e){let t=JSON.parse(e);if(t.version!==Xn||t.artifactCatalogVersion!==We||typeof t.generationId!="string"||!/^[a-f0-9]{64}$/.test(t.generationId)||typeof t.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(t.repositoryId)||typeof t.treeOid!="string"||!t.treeOid||typeof t.producerIdentity!="string"||t.producerIdentity!==vt||typeof t.sourceProjectRoot!="string"||typeof t.scipProjectRoot!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!t.fingerprint||!Array.isArray(t.artifacts))throw new Error("invalid shared generation manifest");let n=new Set;for(let r of t.artifacts){if(!r||typeof r.path!="string"||typeof r.size!="number"||r.size<0||typeof r.sha256!="string"||!/^[a-f0-9]{64}$/.test(r.sha256))throw new Error("invalid shared generation artifact");if(xt(r.path),n.has(r.path))throw new Error(`duplicate shared generation artifact: ${r.path}`);n.add(r.path)}for(let r of["index.db","index.scip","meta.json"])if(!n.has(r))throw new Error(`shared generation is missing ${r}`);return t}function He(e,t,n=384){return tt(e,t,{mode:n})}function Yd(e,t,n){Ee(e,{recursive:!0}),G(m(e,zd),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function Ko(e){try{let t=Rt(e),n=Xo("sha256");for(let r of t.files){let i=W(e,r),o=wt(i).size;n.update(r).update("\0").update(String(o)).update("\0"),Cr(i,{inputKind:"source-generation artifact",maxBytes:_},a=>n.update(a)),n.update("\0")}return n.digest("hex")}catch{return null}}function Kd(e){try{let t=Z(w(m(e,"meta.json"),{inputKind:"reindex metadata",maxBytes:A}));return(t.kind==="legacy"||t.kind==="supported")&&t.capabilities.publishableGeneration?t.metadata:void 0}catch{return}}function Xd(e,t){let n=Yt(e.languages,e);return JSON.stringify(n)===JSON.stringify(t)}function tr(e){return m(e.repositoryCacheDir,"generations",e.generationId)}function da(e,t,n){let r=jr(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId??t.baseGenerationId;if(!o||!se(m(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=m(e,"worktrees");Ee(i,{recursive:!0}),G(m(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),Yd(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function Qd(e,t){let n=m(t,".rollback"),r=new Map,i=new Map;Ee(n,{recursive:!0});for(let s of["index.scip","index.db","meta.json"]){let c=m(e,s),d=se(c);r.set(s,d),d&&He(c,m(n,"stable",s))}for(let s of Zn){let c=m(e,s),d=se(c);if(d){let u=Jn(c);if(!u.isDirectory()||u.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${s}`)}i.set(s,d)}let o=m(e,nt),a=se(o);return a&&ua(o,m(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:a}}function Zd(e,t,n){for(let r of Zn){let i=m(t,r);if(n.managedDirectories.get(r)){let a=m(n.root,"managed",r);Ee(Yn(a),{recursive:!0}),F(()=>me(i,a))}let o=m(e,r);se(o)&&F(()=>me(o,i))}}function eu(e,t){for(let i of Zn){let o=m(e,i),a=m(t.root,"managed",i);t.managedDirectories.get(i)?se(a)&&(ae(o,{recursive:!0,force:!0}),F(()=>me(a,o))):ae(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let a=m(e,i);if(!o){ae(a,{force:!0});continue}let s=`${a}.shared-restore-${Wd()}`;He(m(t.root,"stable",i),s),F(()=>ae(a,{force:!0})),F(()=>me(s,a))}let n=m(e,nt);ae(n,{recursive:!0,force:!0});let r=m(t.root,"sqlite-generations");t.generationStoreExisted&&se(r)&&F(()=>me(r,n))}function ua(e,t){Ee(t,{recursive:!0});for(let n of Zo(e,{withFileTypes:!0})){let r=m(e,n.name),i=m(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?ua(r,i):n.isFile()&&He(r,i)}}function tu(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||JSON.stringify(e.fingerprint)!==JSON.stringify(t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function la(e,t,n,r=!0,i=!0){try{let o=Kd(e);if(!o||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return Ue("source validation rejected metadata"),!1;let a=Rt(e),s=U(m(e,"index.db"),m(e,"meta.json"));if(r?s.state!=="current":s.state==="invalid"||s.state==="drifted")return Ue(`source validation rejected SQLite generation state ${s.state}`),!1;let c=new Ud(m(e,"index.db"),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let d=nr(t),l=(i?a.files.filter(p=>p.endsWith(".scip")):["index.scip"]).every(p=>{let g=ta(D(W(e,p),{inputKind:"shared SCIP validation artifact",maxBytes:_})).metadata?.projectRoot,f=g!==void 0&&Se(g,d);return f||Ue(`source validation rejected SCIP root for ${p}: ${String(g)}`),f});return l||Ue("source validation rejected SCIP project roots"),l}catch(o){return Ue(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function Ue(e){process.env.CODEBASEIQ_DEBUG&&console.error(`shared-cache: ${e}`)}function nr(e){try{return zo(ea(e)).href}catch{return zo(Kn(e)).href}}function pa(e){return Xo("sha256").update(e).digest("hex")}import{createHash as Ru}from"crypto";import{existsSync as ir,statSync as xu,writeFileSync as or}from"fs";import{join as Iu}from"path";import{createRequire as nu}from"module";import{dirname as ru,isAbsolute as dm,relative as um,resolve as lm,sep as pm}from"path";var fa=nu(import.meta.url),iu=1,ga="0.4.0";function rr(){let e=ou();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function ou(){try{let e=fa.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(L(e,"scip-typescript package manifest"));if(t.version!==ga)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${ga}`};let n=ru(e),r=fa.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(L(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:au(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function au(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${iu}`}import{createHash as su}from"crypto";import{dirname as cu,join as ma}from"path";var Tt=4;var du="typescript-index";function ha(e){let t=ma(e,du),n=Zr(t);return{...n,requestDir:n.legacyRequestDir}}function ya(e){try{let t=Fr(Z(L(ma(cu(e),"meta.json"),"reindex metadata")));return t?su("sha256").update(t).digest("hex"):null}catch{return null}}import{randomUUID as uu}from"crypto";import{existsSync as lu}from"fs";var pu=12e4,fu=5,Dt=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;constructor(t,n={}){this.projectRoot=Ur(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Su(),this.runtime=n.runtime??bu,this.mailboxLimits=n.mailboxLimits??{}}request(t){let n=ti(this.cacheDir),r=ha(this.cacheDir),i=rn(n.statePath);if(!Sa(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.now(),a=o+this.timeoutMs,s=(this.runtime.monotonicNow??I)()+this.timeoutMs,c=tn("typescript-index-v4",{baseGeneration:this.baseGeneration,request:t}),d=nn(c),u=ei(r,{mailboxVersion:en,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:a,protocolVersion:Tt,id:d,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??I)()<=s;){if(lu(u.responsePath))return gu(w(u.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),d,c,this.baseGeneration,t.producerIdentity,t.affectedFiles);let l=rn(n.statePath);if(!Sa(l,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(fu)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}};function Sa(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===Tt&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&Ae(e.processIdentity,r))}function gu(e,t,n,r,i,o){let a=JSON.parse(e);if(a.protocolVersion!==Tt||a.id!==t||a.operationKey!==n||a.ok===!0&&a.baseGeneration!==r)throw new Error("TypeScript index service wrote an incompatible response.");if(a.ok!==!0)throw new Error(typeof a.error=="string"?a.error:"TypeScript index service request failed.");let s=mu(a.response,i),c=[...new Set(o)].sort(),d=s.fragments.map(u=>u.relativePath).sort();if(JSON.stringify(d)!==JSON.stringify(c))throw new Error("TypeScript index service omitted or added an affected document.");return s}function mu(e,t){if(!e||typeof e!="object")throw new Error("TypeScript index service wrote an invalid response.");let n=e;if(n.producerIdentity!==t||typeof n.cold!="boolean"||typeof n.durationMs!="number"||!Number.isFinite(n.durationMs)||!Array.isArray(n.fragments))throw new Error("TypeScript index service wrote an invalid response.");let r=new Set,i=n.fragments.map(o=>{if(!o||typeof o.relativePath!="string"||o.bytesBase64!==null&&typeof o.bytesBase64!="string"||typeof o.occurrences!="number"||!Number.isInteger(o.occurrences)||o.occurrences<0||typeof o.symbols!="number"||!Number.isInteger(o.symbols)||o.symbols<0||!Array.isArray(o.referenceFragments)||!o.referenceFragments.every(hu)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:yu(o.bytesBase64);return{relativePath:o.relativePath,bytes:a,occurrences:o.occurrences,symbols:o.symbols,referenceFragments:o.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i}}function hu(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 yu(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Su(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:pu}var bu={now:Date.now,monotonicNow:I,randomId:uu,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:te,readProcessIdentity:ee};function Pu(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."];if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let n=Xe(e.previousSnapshot,e.currentSnapshot);if(n.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};if(n.changes.some(u=>u.kind!=="modified"||u.inputKind!=="source"||!on(u.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=lt(n,e.graph,e.projectFiles);if(r.mode!=="closure"||r.affectedFiles.length===0)return{eligible:!1,reason:r.reasons.length>0?`affected set widened: ${r.reasons.join(", ")}`:"empty affected set"};let i=vu(r,t,e.graph);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=ba(e.currentSnapshot,e.projectFiles,e.producerIdentity),a=ba(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==a)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let s=xa(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!s)return{eligible:!1,reason:"prior document identity unavailable"};let c=xa(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);if(!c)return{eligible:!1,reason:"next document identity unavailable"};let d=i.length===1?i[0]:void 0;return{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:Ra(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:Ra(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:s,nextDocumentIdentities:c,projects:i,...d?{tsconfigPath:d.tsconfigPath,projectArgument:d.projectArgument}:{}}}function vu(e,t,n){let r=new Map;for(let o of e.affectedFiles){let a=wu(o,t);if(!a)return null;let s=r.get(a)??[];s.push(o),r.set(a,s)}let i=[];for(let[o,a]of[...r].sort(([s],[c])=>s.localeCompare(c))){let s=new Set(a),c=e.changedFiles.filter(d=>s.has(d)||a.some(u=>Eu(u,d,n)));if(c.length===0)return null;i.push({projectArgument:o,tsconfigPath:o==="."?"tsconfig.json":`${o}/tsconfig.json`,modifiedFiles:c,affectedFiles:[...a].sort()})}return i}function wu(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)=>Ft(a)-Ft(o)||o.localeCompare(a)),i=r[0];return r[1]&&Ft(r[1])===Ft(i)?null:i}function Ft(e){return e==="."?0:e.split("/").filter(Boolean).length}function Eu(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 Ia(e){let t=I();try{if(!ir(e.previousDbPath)||!ir(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=rr();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new z({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a,s;try{a=it(o,{includeIgnored:!1}).filter(on).sort(),s=ct(o)}finally{o.close()}let c=performance.now()-n,d=Pu({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?xe(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:a,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:ir(Iu(e.projectRoot,"tsconfig.json"))});if(!d.eligible)throw new Error(d.reason);let u=ya(e.previousDbPath);if(!u)throw new Error("published TypeScript base generation unavailable");n=performance.now();let l=new Dt({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:u}),p=d.projects.map(v=>l.request({kind:"emit-documents",tsconfigPath:v.tsconfigPath,projectArgument:v.projectArgument,projectIdentity:d.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:v.modifiedFiles,affectedFiles:v.affectedFiles})),g=p.flatMap(v=>v.fragments),f=performance.now()-n,h=xu(e.previousShardPath).size>=Ao;n=performance.now();let b=h?null:D(e.previousShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:_}),y=h?{completeIndexBytes:null,affectedIndexBytes:go(g)}:bo({packageVersion:r.packageVersion,baseIndexBytes:b,fragments:g}),x=performance.now()-n;n=performance.now(),h?Oo({cacheDir:e.cacheDir,previousGenerationIdentity:d.previousFragmentGeneration,nextGenerationIdentity:d.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:d.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:g}):(mo({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:b,producerIdentity:r.producerIdentity,projectIdentity:d.projectIdentity,generationIdentity:d.previousFragmentGeneration,documentIdentities:d.previousDocumentIdentities,allowUntrackedDocuments:!0}),ho({cacheDir:e.cacheDir,previousGenerationIdentity:d.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:d.projectIdentity,generationIdentity:d.nextFragmentGeneration,fragments:g,documentIdentities:d.nextDocumentIdentities}));let P=performance.now()-n;n=performance.now(),y.completeIndexBytes&&or(e.candidateShardPath,y.completeIndexBytes),or(e.candidateAffectedScipPath,y.affectedIndexBytes);let T=performance.now()-n,k={scipPath:h?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!h,durationMs:I()-t,cold:p.some(v=>v.cold),changedFiles:d.plan.changedFiles,affectedFiles:d.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:d.previousFragmentGeneration,nextFragmentGeneration:d.nextFragmentGeneration,manifest:d.manifest,plan:d.plan,projectFileCount:a.length,referenceFragmentsByFile:new Map(g.map(v=>[v.relativePath,v.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:f,serviceMs:p.reduce((v,he)=>v+he.durationMs,0),assemblyMs:x,fragmentStoreMs:P,writeMs:T}};return e.onStatus(`Incremental TypeScript index emitted ${k.affectedFiles.length} affected document(s) across ${d.projects.length} project(s) in ${(k.durationMs/1e3).toFixed(3)}s (${k.cold?"cold":"warm"} service; ${h?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${f.toFixed(0)}ms, assembly ${x.toFixed(0)}ms, fragments ${P.toFixed(0)}ms, write ${T.toFixed(0)}ms).`),k}catch(n){return e.onStatus(`Incremental TypeScript index unavailable: ${n instanceof Error?n.message:String(n)}. Falling back to the whole-project indexer.`),null}}function Pa(e){let t=rr();if(!t.available)throw new Error(t.reason);let n=Co({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:D(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:_}),packageVersion:t.packageVersion});or(e.candidateShardPath,n)}function ba(e,t,n){let r=e.files.filter(i=>Tr(i.path,e.languages)!=="source").map(i=>({path:i.path,size:i.size,hash:i.hash})).sort((i,o)=>i.path.localeCompare(o.path));return ar(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function Ra(e,t){return ar(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function xa(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),a=ni({projectFiles:t.filter(c=>o.has(c)),snapshot:e,graph:n,engineIdentity:r}),s=new Map;for(let c of i){let d=a.identityFor(c,"typescript-scip-document-v1");if(d.key){s.set(c,d.key);continue}if(o.has(c))return null;s.set(c,ar(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function ar(e){return Ru("sha256").update(e).digest("hex")}import{closeSync as ku,existsSync as At,fstatSync as Tu,lstatSync as Du,openSync as Fu,renameSync as dr,rmSync as Ot,statSync as Au,writeSync as Ou}from"fs";import{cpus as Cu}from"os";import{join as ur}from"path";var sr=Symbol("no-error");async function va(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=sr,c=!0,d=Array.from({length:o},async()=>{for(;c&&a<e.length;){let u=a++;try{r[u]=await n(e[u])}catch(l){s===sr&&(s=l),c=!1}}});if(await Promise.all(d),s!==sr)throw s;return r}function _u(e,t){if(e.temporaryRootConfigContent===void 0)return null;let n=ur(t,"tsconfig.json"),r=Buffer.from(e.temporaryRootConfigContent,"utf8"),i;try{i=Fu(n,"wx",384)}catch(o){if(o.code==="EEXIST")return null;throw o}try{Ou(i,r);let o=Tu(i);return{path:n,content:r,device:o.dev,inode:o.ino}}finally{ku(i)}}function Lu(e){if(e)try{let t=Du(e.path);if(!t.isFile()||t.dev!==e.device||t.ino!==e.inode||t.size!==e.content.byteLength)return;let n;try{n=D(e.path,{maxBytes:e.content.byteLength,inputKind:"temporary TypeScript index configuration"})}catch{return}if(!n.equals(e.content))return;Ot(e.path)}catch(t){if(t.code!=="ENOENT")throw t}}function ju(e,t,n){if(!e.defaultOutputPath)return;let r=ur(t,e.defaultOutputPath);n!==r&&At(r)&&dr(r,n)}function Mu(e,t,n){if(!e.defaultOutputPath)return null;let r=ur(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Ot(i,{force:!0}),At(r)?(dr(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Nu(e){e&&(Ot(e.defaultOutputPath,{force:!0}),e.backupPath&&At(e.backupPath)&&dr(e.backupPath,e.defaultOutputPath))}function Gu(e,t){if(e<=1)return 1;let n=Number(process.env.CODEBASEIQ_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,Cu().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Ea(e,t,n,r,i){N(i,"Reindex cancelled by its owner.");let o=e.filter(u=>u.config.defaultOutputPath),a=e.filter(u=>!u.config.defaultOutputPath),s=[],c=Gu(a.length,r),d=await va(a,c,u=>cr(u,t,n,i));if(c>1){let u=new Map;for(let l of d.filter(p=>p.result.skipped&&p.retryable)){let p=a.find(g=>g.id===l.result.id);p&&(n(`Retrying ${p.label} indexer serially after parallel failure...`),N(i,"Reindex cancelled by its owner."),u.set(p.id,(await cr(p,t,n,i)).result))}s.push(...d.map(({result:l})=>u.get(l.id)??l))}else s.push(...d.map(({result:u})=>u));for(let u of o)N(i,"Reindex cancelled by its owner."),s.push((await cr(u,t,n,i)).result);return s.sort((u,l)=>e.findIndex(p=>p.id===u.id)-e.findIndex(p=>p.id===l.id))}async function cr(e,t,n,r){N(r,"Reindex cancelled by its owner."),n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Ot(e.scipPath,{force:!0});let i=Mu(e.config,t,e.scipPath),o=_u(e,t),a=[e.binary,...e.args].join(" "),s=I();try{e.trustedProjectTool&&Qr(t,e.trustedProjectTool);let d=Kr(e.binary,e.args),u=await dt({command:d.binary,args:d.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:$u(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,signal:r});if(u.status!==0){let l=u.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${u.status}${l?`:
|
|
233
|
+
${l}`:""}`)}ju(e.config,t,e.scipPath)}catch(d){if(r?.aborted)throw _r(r,"Reindex cancelled by its owner.");let u=d instanceof Error?d.message:String(d),l=`${e.resolvedBinary} indexer failed: ${u.split(`
|
|
234
|
+
`)[0]}`,p=e.label===e.language?l:`${e.label}: ${l}`;return n(`Skipping ${e.label}: ${l}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:I()-s,command:a,skipped:{language:e.language,reason:p}},retryable:Vu(d)}}finally{Nu(i),Lu(o)}if(!At(e.scipPath)){let d=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,u=e.label===e.language?d:`${e.label}: ${d}`;return n(`Skipping ${e.label}: ${d}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:I()-s,command:a,skipped:{language:e.language,reason:u}},retryable:!1}}let c;try{c=Au(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:I()-s,command:a,outputBytes:c},retryable:!1}}function $u(){let e=Number(process.env.CODEBASEIQ_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):oi.indexer}function Vu(e){return e instanceof ai?e.kind==="spawn"&&wa(e.cause):wa(e)}function wa(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}import{execFileSync as Ta}from"child_process";import{homedir as ka,platform as Bu}from"os";import{delimiter as Wu,join as Ct}from"path";function pr(e,t){let n=e.installMethods,r=Le(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(!Kt(i.prerequisite))continue;let o=qu(i);t(`Installing immutable ${i.identity} via ${i.label} into ${o}; expected executable: ${r}.`);try{Ta(i.binary,i.args,{stdio:"inherit",windowsHide:!0,timeout:3e5,env:process.env,shell:Bu()==="win32"});let a=Pe(e);if(a){let s=a===e.indexerBinary?"":` (using ${a})`;return t(`Successfully installed ${i.identity} via ${i.label}${s}; resolved executable: ${a}.`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(a){let s=a instanceof Error?a.message:String(a);t(`${i.label} install failed: ${s}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function qu(e){if(e.binary==="npm")return lr("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=lr("go",["env","GOBIN"]);if(t)return t;let n=lr("go",["env","GOPATH"]);if(n)return Ct(n.split(Wu)[0],"bin")}return e.binary==="dotnet"?Ct(process.env.DOTNET_CLI_HOME??ka(),".dotnet","tools"):e.binary==="dart"?Ct(process.env.PUB_CACHE??Ct(ka(),".pub-cache"),"bin"):e.destination}function lr(e,t){try{return Ta(e,t,{stdio:["ignore","pipe","ignore"],windowsHide:!0,encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}import Xa from"better-sqlite3";import{existsSync as Qa}from"fs";import{dirname as Za,join as es,resolve as ts}from"path";import{randomUUID as Hu}from"crypto";import{mkdtempSync as zu,rmSync as Ju,statSync as Fa}from"fs";import{tmpdir as Yu}from"os";import{join as Aa}from"path";import{Worker as Ku}from"worker_threads";function Uu(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function ke(){return{skippedReferences:0,skippedReferenceReasons:Uu(),skippedReferenceSamples:[]}}function _t(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 Xu=3e5,Oa=64*1024*1024,Qu={createResultDirectory:()=>zu(Aa(Yu(),"codebaseiq-vue-workers-")),spawn:(e,t)=>new Ku(e,{workerData:t}),resultSize:e=>Fa(e).size,readResult:e=>w(e,{maxBytes:Oa,inputKind:"Vue worker result"}),removeResultDirectory:e=>Ju(e,{recursive:!0,force:!0})};function Ca(e){return e.length>=8&&La(e.length)>1}async function _a(e,t=Qu){let n=La(e.vueFiles.length),r=ll(e.vueFiles),i=fl(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),a=e.timeoutMs??dl(),s=e.maxResultBytes??ul();Da("timeoutMs",a),Da("maxResultBytes",s);let c=Hu(),d=t.createResultDirectory(),u=[],l,p,g;try{for(let h=0;h<i.length;h++){let b=h,y=i[h]??[],x=y.map(k=>k.taskId),P=Aa(d,`${b}.json`),T=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:y,resultPath:P,runId:c,workerId:b,taskIds:x});u.push({workerId:b,taskIds:x,resultPath:P,handle:T,completion:Zu(T,b)})}await el(u,a);let f=u.sort((h,b)=>h.workerId-b.workerId).map(h=>nl(h,c,s,t));g={occurrences:f.flatMap(h=>h.occurrences),...ke()};for(let h of f)_t(g,h)}catch(f){l=f}finally{let f=await tl(u);if(f.length===0)try{t.removeResultDirectory(d)}catch(h){f.push(h)}if(f.length>0){let h=l===void 0?f:[l,...f];p=new AggregateError(h,`Vue worker cleanup failed: ${cl(h[0])}`)}}if(p)throw p;if(l!==void 0)throw l;if(!g)throw new Error("Vue workers completed without producing a merged result.");return g}function Zu(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 el(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 tl(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function nl(e,t,n,r){let i=r.resultSize(e.resultPath);if(!Number.isSafeInteger(i)||i<0||i>n)throw new Error(`Vue reference worker ${e.workerId} result is ${i} bytes; limit is ${n} bytes`);let o;try{o=JSON.parse(r.readResult(e.resultPath))}catch(a){throw new Error(`Vue reference worker ${e.workerId} produced invalid JSON`,{cause:a})}if(!ze(o)||o.version!==1||o.runId!==t||o.workerId!==e.workerId)throw new Error(`Vue reference worker ${e.workerId} result identity does not match its assignment`);if(!sl(o.taskIds,e.taskIds))throw new Error(`Vue reference worker ${e.workerId} result task identities do not match its assignment`);if(o.ok===!1)throw typeof o.error!="string"?new Error(`Vue reference worker ${e.workerId} failure payload is malformed`):new Error(`Vue reference worker ${e.workerId} failed: ${o.error}`);if(o.ok!==!0||!rl(o.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return o.result}function rl(e){if(!ze(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(il)||!K(e.skippedReferences)||!ze(e.skippedReferenceReasons))return!1;for(let t of["missing-source-file","missing-service-script","no-definition","same-file-definition","unindexed-definition"])if(!K(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(ol)}function il(e){return ze(e)&&typeof e.sourceFile=="string"&&K(e.sourceLine)&&K(e.sourceStartChar)&&K(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&K(e.symbolId)}function ol(e){return ze(e)&&typeof e.sourceFile=="string"&&K(e.sourceLine)&&K(e.sourceStartChar)&&K(e.sourceEndChar)&&typeof e.token=="string"&&al(e.reason)}function al(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function K(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sl(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function Da(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function cl(e){return e instanceof Error?e.message:String(e)}function La(e){let t=Number(process.env.CODEBASEIQ_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:1;return Math.max(1,Math.min(e,n))}function dl(){let e=Number(process.env.CODEBASEIQ_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:Xu}function ul(){let e=Number(process.env.CODEBASEIQ_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:Oa}function ll(e){let t=pl(),n=[];for(let r of e){let i=ja(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 pl(){return Number.POSITIVE_INFINITY}function fl(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:gl(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 gl(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,ja(e.fileName)-e.startOffset)}function ja(e){try{return Fa(e).size}catch{return 1}}import{createRequire as ml}from"module";import{existsSync as hl}from"fs";import{dirname as Ma,extname as yl,join as Na,relative as Sl,resolve as bl}from"path";import{pathToFileURL as Rl}from"url";function xl(e){e.transaction(()=>{e.prepare(`
|
|
235
|
+
DELETE FROM mentions
|
|
236
|
+
WHERE chunk_id IN (
|
|
237
|
+
SELECT c.id
|
|
238
|
+
FROM chunks c
|
|
239
|
+
JOIN documents d ON d.id = c.document_id
|
|
240
|
+
WHERE d.language = 'vue' OR d.relative_path LIKE '%.vue'
|
|
241
|
+
)
|
|
242
|
+
`).run(),e.prepare(`
|
|
243
|
+
DELETE FROM chunks
|
|
244
|
+
WHERE document_id IN (
|
|
245
|
+
SELECT id
|
|
246
|
+
FROM documents
|
|
247
|
+
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
248
|
+
)
|
|
249
|
+
`).run()})()}function gr(e,t){return e.prepare(`
|
|
250
|
+
SELECT relative_path AS relativePath
|
|
251
|
+
FROM documents
|
|
252
|
+
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
253
|
+
ORDER BY relative_path
|
|
254
|
+
`).all().map(r=>bl(t,r.relativePath))}function Ga(e,t){let{vueCore:n,ts:r,volarTs:i}=Il(e),{parsed:o,vueOptions:a}=Pl(n,r,t),s=Ma(t),c=n.createVueLanguagePlugin(r,o.options,a,g=>g),d=vl(n,r,c),u=wl(s,o),{languageServiceHost:l}=i.createLanguageServiceHost(r,r.sys,d,g=>g,u),p=r.createLanguageService(l);return{ts:r,language:d,languageService:p,fileNames:o.fileNames,configDir:s}}function Il(e){let t=ml(Rl(Na(e,"package.json")).href);return{vueCore:fr(t,"@vue/language-core",e),ts:fr(t,"typescript",e),volarTs:fr(t,"@volar/typescript",e)}}function Pl(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,Ma(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function vl(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!hl(o))return;let a=w(o,{maxBytes:H,inputKind:"Vue language-service source file"});r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??Al(o))});return r.current=i,i}function wl(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function fr(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 $a(e,t,n){let r=El(e);return i=>{if(!i.name)return null;let o=X(t,i.fileName),a=n.get(i.fileName);if(!a)return null;let s=n.positionAt(a,i.textSpan.start),c=r.get(o);if(!c)return null;let d=c.starts.find(l=>l.line===s.line&&l.displayName===i.name);if(d)return d.symbolId;let u=c.containingByLine.get(s.line);return u&&u.displayName===i.name?u.symbolId:kl(c.starts,s.line,2,i.name)}}function El(e){let t=e.prepare(`
|
|
255
|
+
SELECT
|
|
256
|
+
d.relative_path AS relativePath,
|
|
257
|
+
der.start_line AS startLine,
|
|
258
|
+
der.end_line AS endLine,
|
|
259
|
+
der.symbol_id AS symbolId,
|
|
260
|
+
gs.display_name AS displayName
|
|
261
|
+
FROM defn_enclosing_ranges der
|
|
262
|
+
JOIN documents d ON d.id = der.document_id
|
|
263
|
+
JOIN global_symbols gs ON gs.id = der.symbol_id
|
|
264
|
+
ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
|
|
265
|
+
`).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function kl(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let s=Math.floor((i+o)/2);e[s].line<t?i=s+1:o=s-1}let a=null;for(let s of[o,i]){let c=e[s];if(!c||c.displayName!==r)continue;let d=Math.abs(c.line-t);d>n||(!a||d<a.distance)&&(a={distance:d,symbolId:c.symbolId})}return a?.symbolId??null}function mr(e,t,n){let r=_l(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
|
|
266
|
+
INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
|
|
267
|
+
VALUES (?, ?, ?, ?)
|
|
268
|
+
`),a=0,s=new Map;return e.transaction(()=>{for(let d of n){let u=X(t,d),l=Ya(r.name,r.version,u);o.run(l,"default",7,`Vue component|${u}`);let p=Ll(i,r,t,d);p&&(a++,s.set(d,p))}})(),{get(d){return s.get(d)??null},syntheticSymbols:a}}function Va(e,t,n,r,i){return e.transaction(()=>(xl(e),Tl(e,t,n,r),Dl(e,i)))()}function Tl(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
|
|
269
|
+
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
270
|
+
VALUES (?, ?, ?, ?, X'00')
|
|
271
|
+
`),a=e.prepare(`
|
|
272
|
+
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
273
|
+
VALUES (?, ?, 1)
|
|
274
|
+
`);for(let s of n){let c=r.get(s);if(!c)continue;let d=X(t,s),u=i.get(d);if(!u)continue;let l=o.run(u.id,-1,0,0);a.run(Number(l.lastInsertRowid),c)}}function Ba(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(hr(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Wa(e){let t=new Set,n=[];for(let r of e){let i=qa(r);t.has(i)||(t.add(i),n.push(r))}return n}function qa(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function Dl(e,t){let n=Cl(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
|
|
275
|
+
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
276
|
+
VALUES (?, ?, ?, ?, X'00')
|
|
277
|
+
`),i=e.prepare(`
|
|
278
|
+
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
279
|
+
VALUES (?, ?, 0)
|
|
280
|
+
`),o=new Set,a=0,s=0;for(let c of t){let d=qa(c);if(o.has(d))continue;o.add(d);let u=n.get(c.sourceFile);if(!u)continue;let l=r.run(u,s++,c.sourceLine,c.sourceLine),p=i.run(Number(l.lastInsertRowid),c.symbolId);a+=Number(p.changes)}return a}function*Ua(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 Ha(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function hr(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Fl(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 za(e,t){return X(e,t).startsWith("node_modules/")}function X(e,t){return Sl(e,t).replaceAll("\\","/")}function Al(e){switch(yl(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function Ja(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=w(t,{maxBytes:H,inputKind:"Vue source file"}),r={text:n,lineStarts:Ol(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:Fl}}function Ol(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function Cl(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 _l(e){try{let t=JSON.parse(w(Na(e,"package.json"),{maxBytes:A,inputKind:"project package manifest"}));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function Ll(e,t,n,r){let i=X(n,r),o=Ya(t.name,t.version,i);return e.get(o)?.id??null}function Ya(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function ns(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>Gl({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Ml(e){return B(ie(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),B(ns({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}async function Nl(e){return B(ie(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),$l(e)}function Gl(e){let t=ts(e.projectRoot,e.tsconfig);if(!Qa(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Xa(e.dbPath);try{let r=gr(n,e.projectRoot),i=es(Za(e.dbPath),"augment-vue-meta.json");return Ji({cachePath:i,readFingerprint:()=>os(n,e.projectRoot,e.tsconfig),compute:()=>Vl({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 $l(e){let t=ts(e.projectRoot,e.tsconfig);if(!Qa(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Xa(e.dbPath);try{let r=gr(n,e.projectRoot),i=es(Za(e.dbPath),"augment-vue-meta.json");return await Yi({cachePath:i,readFingerprint:()=>os(n,e.projectRoot,e.tsconfig),compute:()=>Bl({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function Vl(e){let t=mr(e.db,e.projectRoot,e.vueFiles),n=is(e,t);return rs(e,t,n)}async function Bl(e){let t=mr(e.db,e.projectRoot,e.vueFiles),n=Ca(e.vueFiles)?await _a({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles}):is(e,t);return rs(e,t,n)}function rs(e,t,n){let r=Wa(n.occurrences),i=Va(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:Xl(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:Kl(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function is(e,t){let n=Wl({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return ql({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function os(e,t,n){let r=e.prepare(`
|
|
281
|
+
SELECT
|
|
282
|
+
(SELECT COUNT(*) FROM documents) AS documents,
|
|
283
|
+
(SELECT COUNT(*) FROM global_symbols) AS symbols,
|
|
284
|
+
(SELECT COUNT(*) FROM chunks) AS chunks,
|
|
285
|
+
(SELECT COUNT(*) FROM mentions) AS mentions,
|
|
286
|
+
(SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
|
|
287
|
+
(SELECT MAX(id) FROM chunks) AS maxChunkId,
|
|
288
|
+
(SELECT MAX(id) FROM global_symbols) AS maxSymbolId
|
|
289
|
+
`).get();return{version:3,tsconfig:n,files:st(t),db:r}}function Wl(e){let t=Ja();return{projectRoot:e.projectRoot,context:Ga(e.projectRoot,e.configPath),symbolLookup:$a(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function ql(e){let t=[],n=ke(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=Ul(e,i);t.push(...o.occurrences),_t(n,o)}return{occurrences:t,...n}}function Ul(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return Ka(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 Ka(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=X(e.projectRoot,t.fileName),s=[...Ua(n.text)],c={tokens:s.filter(d=>d.start>=t.startOffset&&d.start<t.endOffset),tokenByStart:new Map(s.map(d=>[d.start,d])),tokenTextCounts:Zl(s),processedStarts:new Set};return Hl({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function Hl(e){let t=[],n=ke();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||zl(e.sourceInfo.text,r.start))continue;let i=Ha(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(u=>!za(e.projectRoot,u.fileName));if(!a){yr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=X(e.projectRoot,a.fileName),c=Jl(e.sourceFile,r.text,s);if(c){yr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let d=Ba(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(d===null){yr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}as(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,d),e.tokenContext.processedStarts.add(r.start),Ql(t,e,r,i,s,d)}return{occurrences:t,...n}}function zl(e,t){let n=e.lastIndexOf(`
|
|
290
|
+
`,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function Jl(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Ka(e,t,n){let r=ke();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:X(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function yr(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 Sr(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 Yl(e,t){let n=Sr(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=Sr(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function Kl(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(...Sr(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function Xl(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return Yl(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function Ql(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of ep(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&&(as(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function as(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 Zl(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function ep(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 d of c.highlightSpans){let u=tp(r,d.textSpan.start,o,i.text);u!==null&&s.push(u)}return s}function tp(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=hr(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function Cy(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log}=e,i=e.skipAutoInstall===!0||e.installMissing!==!0,o=dp(e),a=Date.now(),s=I();jt(S(o.outputScip),{recursive:!0}),jt(S(o.outputDb),{recursive:!0});let c=e.languages??cn(t);if(c.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${c.join(", ")}`);let d=ot("reindex.fingerprint",()=>Jt(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:c.length}),u,l;if(e.skipIfUnchanged!==!1&&!na(t,o.outputDb)&&ss(o.outputScip)===ss(C(S(o.outputDb),"index.scip"))){let y=at(t);if(u=y?.clean?Et(y,d):void 0,y&&!y.clean&&!cp(o)){let x=ra(y,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath});if(x)try{kt({snapshot:x.snapshot,manifest:x.manifest,targetCacheDir:S(o.outputDb),targetProjectRoot:t,persistLease:!1}),aa(x.snapshot,S(o.outputDb)),r(`Forked shared baseline ${x.snapshot.generationId.slice(0,12)} for dirty worktree reindex`)}catch(P){r(`Shared baseline fork failed; continuing locally: ${ce(P)}`)}}else if(u){let x=Y(u);if(x){if(!sp(o,d))try{kt({snapshot:u,manifest:x,targetCacheDir:S(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${u.generationId.slice(0,12)}`)}catch(P){r(`Shared generation attach failed; continuing locally: ${ce(P)}`)}}else{let P=await oa(u);if(P.kind==="owner")l=P.release;else if(P.kind==="generation-ready"){let T=Y(u);if(T)try{kt({snapshot:u,manifest:T,targetCacheDir:S(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${u.generationId.slice(0,12)} after waiting`)}catch(k){r(`Shared generation attach failed after waiting; continuing locally: ${ce(k)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let g=de(C(S(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!g)throw l?.(),new Error(`Could not acquire codebaseiq cache lifecycle lock for ${S(o.outputDb)}.`);let f;try{f=await Re("reindex.lock",()=>jp(C(S(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:c.length})}catch(y){throw g.release(),l?.(),y}let h=null,b=mi();try{qn(o.outputDb,o.outputScip,o.metaPath);let y=fp(S(o.outputDb));y.removed>0&&r(`Removed ${y.removed} abandoned reindex workspace(s)`);for(let ye of y.errors)r(`Could not remove abandoned reindex workspace: ${ye}`);let x=null,P=ot("reindex.reuse-check",()=>(x=up({opts:e,paths:o,languages:c,fingerprint:d,start:a,monotonicStart:s,onStatus:r}),x),()=>({languages:c.length,reused:x!==null}));if(P){cs({snapshot:u,paths:o,projectRoot:t,fingerprint:d,onStatus:r});let ye=dn(o.outputDb,P);return ye.state==="failed"&&r(`Warning: reindex succeeded, but activity telemetry was not recorded: ${ye.reason}`),Ht(t,S(o.outputDb)),P}await Re("reindex.scip-cli-ready",()=>Tp(i,r));let T=pp(o);h=T.runDir;let k,v=await Re("reindex.fresh",async()=>(k=await gp({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:T,fingerprint:d,start:a,monotonicStart:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r,writeTelemetry:b}),k),()=>({languages:c.length,reused:k?.reused,skipped:k?.skipped.length}));cs({snapshot:u,paths:o,projectRoot:t,fingerprint:d,onStatus:r});let he=dn(o.outputDb,v);return he.state==="failed"&&r(`Warning: reindex succeeded, but activity telemetry was not recorded: ${he.reason}`),Ht(t,S(o.outputDb)),v}catch(y){let x=Gt({trigger:e.trigger,result:"failed",start:a,monotonicStart:s,error:y instanceof Error?y.message:String(y)});Ds(o.metaPath,x);let P=fi(o.outputDb,x);throw P.state==="failed"&&r(`Warning: failed reindex activity telemetry was not recorded: ${P.reason}`),y}finally{if(h){let y=h;try{F(()=>Te(y,{recursive:!0,force:!0}))}catch(x){r(`Warning: temporary reindex workspace was left behind: ${ce(x)}`)}}f(),g.release(),l?.()}}function cs(e){if(e.snapshot)try{let t=at(e.projectRoot),n=t?Et(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=ia({snapshot:e.snapshot,sourceCacheDir:S(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let i=at(e.projectRoot);return(i?Et(i,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}});er(e.snapshot,S(e.paths.outputDb),"built"),e.onStatus(r.kind==="published"?`Published shared generation ${e.snapshot.generationId.slice(0,12)} (${r.achievedDurability})`:`Shared generation ${e.snapshot.generationId.slice(0,12)} was already available (${r.achievedDurability})`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${ce(t)}`)}}function sp(e,t){if(!j(e.outputScip)||!j(e.outputDb)||!Ts(e.metaPath,t))return!1;let n=U(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function cp(e){if(!j(e.outputScip)||!j(e.outputDb)||!De(e.metaPath))return!1;let t=U(e.outputDb,e.metaPath);return t.state!=="invalid"&&t.state!=="drifted"}function ce(e){return e instanceof Error?e.message:String(e)}function xr(e,t,n,r,i,o){try{B(yi({indexPath:n,reuseExisting:i,affectedFiles:o}),{projectRoot:e,dbPath:t,onStatus:r})}catch(a){r(`Runtime-boundary extraction unavailable: ${a instanceof Error?a.message:String(a)}.`)}}function dp(e){let t=e.outputScip??C(e.projectRoot,"index.scip"),n=e.outputDb??C(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:C(S(n),"meta.json")}}function up(e){let t=U(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!j(e.paths.outputScip)||!j(e.paths.outputDb)||!Ts(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;B(ie(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),xr(e.opts.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0),U(e.paths.outputDb,e.paths.metaPath).state==="drifted"&&(Un(e.paths.outputDb,e.paths.metaPath),e.onStatus("Published refreshed SQLite generation after post-index augmentation"));let n=I()-e.monotonicStart,r=Gt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return Ds(e.paths.metaPath,r),e.onStatus(`Index unchanged; reused existing SQLite index in ${(n/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:n,reused:!0,skipped:[],lastRefresh:r,shards:lp(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function lp(e,t,n,r){let i=Es(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:Je(i[o]),outputBytes:Ye(Pr(e.outputDb,o)),durationMs:0}))}function pp(e){let t=rp(C(S(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:C(t,Lt(e.outputScip)),tempOutputDb:C(t,Lt(e.outputDb)),tempMetaPath:C(t,Lt(e.metaPath))}}function fp(e){let t=[],n;try{n=ms(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[ce(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{Te(C(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${ce(o)}`)}return{removed:r,errors:t}}async function gp(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await Re("reindex.language-indexers",async()=>(n=await hp(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:d,incrementalTypeScript:u}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),mp({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let g=ot("reindex.publish",()=>wp(e,i,o,a,s,d),{mode:"metadata-only",languages:i.length,reused:a.length}),f=g.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(f/1e3).toFixed(1)}s`),{languages:i.map(h=>h.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:f,reused:!0,skipped:o,lastRefresh:g,shards:c,writeTelemetry:e.writeTelemetry}}let l=await Re("reindex.publish",()=>vp(e,t,i,o,a,s,d,u),{mode:u?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),p=l.durationMs;return e.onStatus(`Done in ${(p/1e3).toFixed(1)}s`),{languages:i.map(g=>g.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:p,reused:!1,skipped:o,lastRefresh:l,shards:c,writeTelemetry:e.writeTelemetry}}function mp(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!j(e.run.paths.outputScip)||!j(e.run.paths.outputDb))return!1;let t=U(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 hp(e,t){let n=xp({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}),r=[],i=new Set;for(let[M,wr]of n)wr.reused&&(r.push({language:M,scipPath:wr.scipPath}),i.add(M));for(let M of i)e.onStatus(`Reusing cached ${M} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),a=U(e.paths.outputDb,e.paths.metaPath),s=De(e.paths.metaPath),c=a.state==="legacy"||a.state==="current",d=s?.scipCompanion!=="deferred"&&(a.state!=="current"||a.generation.publication?.scipCompanion!=="deferred"),u=o&&!o.reused&&c?Ia({projectRoot:e.projectRoot,cacheDir:S(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:Ke(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:Ke(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:d,previousSnapshot:Ir(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,l=new Set(u?["typescript"]:[]),p=u?void 0:yp(e,n),{preparedRuns:g,skippedLanguages:f,languageOutputScipPaths:h}=Dp({languages:e.languages.filter(M=>!i.has(M)&&!l.has(M)),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:p?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),b=p?g.filter(M=>M.language!=="typescript"||p.missedProjectIds.has(M.id)):g,y=await Ea(b,e.projectRoot,e.onStatus,e.opts.indexerConcurrency,e.opts.signal),x=[];if(p){bp(e.paths.outputDb,y,e.writeTelemetry);let M=h.typescript??e.tempPaths.tempOutputScip;x=Rp({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:M,reusedProjects:p.reusedProjects,writeTelemetry:e.writeTelemetry})}let P=[...y,...x],{indexedOutputs:T}=Ap(P,f),k=u?[{language:"typescript",scipPath:u.scipPath}]:[],v=[...r,...k,...T];Op(v,f,e.languages,e.opts.allowPartial,e.onStatus);let he=u?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:u.scipPath,outputScipPath:u.scipPath,durationMs:u.durationMs,command:"watch-service:typescript-index",outputBytes:Ye(u.scipPath)??void 0}]:[],ye=Ip(n,[...y,...he],p?{outputDb:e.paths.outputDb,classification:p.classification}:void 0);return{indexedOutputs:v,skippedLanguages:f,reusedLanguages:[...i],languageFingerprints:Pp(n,e.languages),shards:ye,typescriptProjectShardContext:p?{projects:p.allProjects,fingerprints:p.fingerprints}:void 0,incrementalTypeScript:u??void 0}}function yp(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=xe(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=no(e.projectRoot,r),o=Zi(n.fingerprint.files,r),a=eo(r,i),s=to(r,o,a),c=De(e.paths.metaPath),u=Sp(c,s,f=>j(Nt(e.paths.outputDb,f))),l=[...u.entries()].filter(([,f])=>f.reused).map(([f])=>f),p=new Set(l),g=new Set(r.filter(f=>!p.has(f)).map(f=>`typescript:${f}`));return{allProjects:r,fingerprints:s,classification:u,reusedProjects:l,missedProjectIds:g}}function Sp(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===Fe&&Bt(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(Q(a)!==Q(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 bp(e,t,n){for(let r of t){if(r.skipped||!r.id.startsWith("typescript:"))continue;let i=r.id.slice(11),o=Nt(e,i);jt(S(o),{recursive:!0}),pe(n,le(r.scipPath,o))}}function Rp(e){return e.reusedProjects.map((t,n)=>{let r=Nt(e.outputDb,t),i=Ke(e.tempOutputScip,"typescript-project-cached",n);return pe(e.writeTelemetry,le(r,i)),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Ye(i)??void 0}})}function xp(e){let t=De(e.paths.metaPath),n=Es(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Pr(e.paths.outputDb,i),a=n[i];if(!t){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:a,scipPath:o});continue}if(t.version!==Fe){r.set(i,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:a,scipPath:o});continue}if(i==="typescript"&&t.scipCompanion==="deferred"){r.set(i,{reused:!1,reason:"whole TypeScript SCIP companion is deferred behind changed-document overlays",fingerprint:a,scipPath:o});continue}if(!Bt(t).languageShardReuse||!t.languageFingerprints){r.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:a,scipPath:o});continue}let s=t.languageFingerprints[i];if(!s){r.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:a,scipPath:o});continue}if(!j(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:a,scipPath:o});continue}if(Q(s)!==Q(a)){r.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:a,scipPath:o});continue}r.set(i,{reused:!0,fingerprint:a,scipPath:o})}return r}function Ip(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:Je(o.fingerprint),outputBytes:Ye(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),a=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,s=a?n.classification.get(a):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:s?.reason??o?.reason??i.skipped?.reason,fingerprint:s?Je(s.fingerprint):o?Je(o.fingerprint):"unknown",outputBytes:i.outputBytes??null,durationMs:i.durationMs,command:i.command})}if(n)for(let[i,o]of n.classification)o.reused&&r.push({id:`typescript:${i}`,language:"typescript",reused:!0,fingerprint:Je(o.fingerprint),outputBytes:Ye(Nt(n.outputDb,i)),durationMs:0});return r}function Je(e){return np("sha256").update(Q(e)).digest("hex").slice(0,16)}function Ye(e){try{return ip(e).size}catch{return null}}function Pp(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}async function vp(e,t,n,r,i,o,a,s){N(e.opts.signal,"Reindex cancelled by its owner.");let c=!s||s.completeScipUpdated,d=!1;c&&(ds(e.paths.outputDb,n,e.writeTelemetry),d=us(n,e.tempPaths.tempOutputScip,e.onStatus));let u=await Cp({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:d,materializeFullFallback:async()=>{if(N(e.opts.signal,"Reindex cancelled by its owner."),!s||s.completeScipUpdated)return d;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),Pa({cacheDir:S(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let T=n.map(k=>k.language==="typescript"?{language:k.language,scipPath:s.candidateScipPath}:k);return ds(e.paths.outputDb,T,e.writeTelemetry),d=us(T,e.tempPaths.tempOutputScip,e.onStatus),d}});N(e.opts.signal,"Reindex cancelled by its owner."),B(ie(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),xr(e.projectRoot,e.tempPaths.tempOutputDb,e.tempPaths.tempOutputScip,e.onStatus,!1,s?.affectedFiles);let l=In(e.tempPaths.tempOutputDb);if(l.added.length>0&&e.onStatus(`Added SQLite query indexes: ${l.added.join(", ")}`),l.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${l.removed.join(", ")}`),u.mode==="incremental"&&s){let T=null,k=null;try{T=new z({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),k=new z({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let v=ri(T,e.fingerprint,s.referenceFragmentsByFile,k);e.onStatus(`Cached exact TypeScript reference fragments for ${v} affected document(s).`)}catch(v){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${v instanceof Error?v.message:String(v)}.`)}finally{T?.close(),k?.close()}}let p=Ir(e.paths.metaPath),g=u.mode==="incremental"&&s?Lp(s,u.changedDocumentPaths):fn({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:p,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),f=Gt({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(T=>T.language),skipped:[...r]}),h=u.mode==="incremental"&&u.scipCompanion==="deferred",b={...o};h&&delete b.typescript;let{metadata:y,pruneProjects:x}=Ss({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:b,typescriptProjectShardContext:a,lastRefresh:f});y.scipCompanion=h?"deferred":"current",bs(e.paths.outputDb,x),vr(e.tempPaths.tempMetaPath,y);let P=Pt({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:u.mode==="incremental"&&u.scipCompanion==="deferred",publication:u.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:u.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:u.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:u.patchDurationMs,scipCompanion:u.scipCompanion,...u.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:u.converterDurationMs,scipCompanion:"current",...u.fallbackReason?{fallbackReason:u.fallbackReason}:{}}});return P.achievedDurability==="file-flushed"&&e.onStatus(`Published local generation ${P.currentGeneration.slice(0,12)} (file-flushed; directory sync unsupported)`),_o(S(e.paths.outputDb),u.mode==="incremental"&&u.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),xo(S(e.paths.outputDb),s?.completeScipUpdated?[s.nextFragmentGeneration]:[]),ys(e.paths.outputDb,g,e.onStatus),f}function wp(e,t,n,r,i,o){let a=Ir(e.paths.metaPath),s=null;try{pe(e.writeTelemetry,le(e.paths.outputDb,e.tempPaths.tempOutputDb))}catch(p){s=xi("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}B(ie(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),xr(e.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0);let c=In(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(", ")}`),s??=fn({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 d=Gt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:u,pruneProjects:l}=Ss({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:d});return bs(e.paths.outputDb,l),vr(e.paths.metaPath,u),Un(e.paths.outputDb,e.paths.metaPath),ys(e.paths.outputDb,s,e.onStatus),d}function Ir(e){return Dr(De(e)?.fingerprint)}function ys(e,t,n){try{Ii(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 Ss(e){let t=Ep({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:Fe,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 Ep(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=De(e.metaPath),n=t?.version===Fe?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 bs(e,t){let n=ks(e);if(t===null){F(()=>Te(n,{recursive:!0,force:!0}));return}let r;try{r=ms(n)}catch{return}for(let i of kp(r,t))F(()=>Te(C(n,i),{force:!0}))}function kp(e,t){let n=new Set(t.map(r=>`${En(r)}.scip`));return e.filter(r=>!n.has(r))}function ds(e,t,n){for(let r of t){let i=Pr(e,r.language);jt(S(i),{recursive:!0}),r.scipPath!==i&&pe(n,le(r.scipPath,i))}}async function Tp(e,t){if(!an()){if(ap()==="win32")throw new Error("The scip CLI was not found. On Windows it ships via the npm sidecar package codebaseiq-windows (installed automatically with codebaseiq). Reinstall codebaseiq with optional dependencies enabled, or follow 'codebaseiq setup' guidance for the exact sidecar package version, or set CODEBASEIQ_SCIP_BIN to a local scip.exe path.");if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
291
|
+
To install the reviewed version, run: codebaseiq reindex --install-missing
|
|
292
|
+
Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!sn(t))throw new Error(`The scip CLI is required but could not be installed.
|
|
293
|
+
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function Dp(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?Ke(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=Fp({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?Rs(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function Fp(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[br({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??xe(e.projectRoot,e.typescriptProjects);return t.length===0?[br({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(e.onStatus(`Indexing TypeScript workspace as ${t.length} project shard(s).`),t.map((n,r)=>br({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:Ke(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function br(e){let t=ft(e.language),n=Le(t),r=Qt(t,e.projectRoot),i=e.trustProjectTools&&r?Xr(t,e.projectRoot):null,o=Pe(t);if(!i&&!o&&r){let u=`${n} is available only as repository-local code at ${r}. Review that exact tool and rerun with --trust-project-tools.`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}if(!i&&!o&&!Xt(t)){if(e.skipAutoInstall){let u=`${n} not found on PATH. To install the reviewed version, run: codebaseiq reindex --install-missing${t.installUrl?` (manual source: ${t.installUrl})`:""}`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!pr(t,e.onStatus)){let u=`${n} could not be auto-installed. ${t.installUrl?`Install manually from ${t.installUrl}`:`Install ${n} and put it on PATH.`}`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}}let a=i?.canonicalPath??Pe(t);if(!a){let u=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}let{binary:s,args:c}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:a,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0}),d=Fi({language:e.language,projectPath:e.projectPath,pnpmWorkspaces:e.pnpmWorkspaces});if(i&&!i.executable){let u=`${i.relativePath} is not executable; refusing project-local indexer.`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}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:a,binary:s,args:c,env:Zt(t,e.env,a),...d===void 0?{}:{temporaryRootConfigContent:d},...i?{trustedProjectTool:i}:{}}}}function Ap(e,t){let n=new Map;for(let i of e)if(i.skipped)Rs(t,i.skipped);else{let o=`${i.language}\0${i.outputScipPath}`,a=n.get(o)??{language:i.language,outputScipPath:i.outputScipPath,scipPaths:[]};a.scipPaths.push(i.scipPath),n.set(o,a)}let r=[];for(let i of n.values())if(i.scipPaths.length>1)bn(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&hs(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function Rs(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 Op(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
|
|
294
|
+
`);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
|
|
295
|
+
`+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.
|
|
296
|
+
`+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
|
|
297
|
+
`))}function us(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=Li(e.map(o=>o.scipPath),t);return Is(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&hs(e[0].scipPath,t);return!1}async function Cp(e){let t;if(_p(e)){let i=C(e.run.tempPaths.runDir,"typescript-affected.db");try{xs(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();await ls(e.incrementalTypeScript.affectedScipPath,i,e.env,e.run.onStatus,!1,e.run.opts.signal),e.run.onStatus(`Converted affected SCIP documents in ${(performance.now()-o).toFixed(0)}ms.`);let a=Wi({previousDbPath:e.run.paths.outputDb,miniDbPath:i,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:e.incrementalTypeScript.affectedFiles,writeTelemetry:e.run.writeTelemetry});return e.run.onStatus(`Patched ${a.affectedDocumentCount} SQLite document(s) in ${(a.durationMs/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:a.changedDocumentPaths,patchDurationMs:a.durationMs,converterDurationMs:performance.now()-o,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(o){N(e.run.opts.signal,"Reindex cancelled by its owner."),t=o instanceof Error?o.message:String(o),F(()=>Te(i,{force:!0})),F(()=>Te(e.run.tempPaths.tempOutputDb,{force:!0})),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 ls(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 _p(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!j(e.run.paths.outputDb)||!j(e.run.paths.outputScip))return!1;let t=new Set(e.reusedLanguages);return e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(n=>n==="typescript"||t.has(n))}function Lp(e,t){let n=I(),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:I()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:pn(e.plan,o,e.projectFileCount)}}async function ls(e,t,n,r,i=!1,o){if(N(o,"Reindex cancelled by its owner."),r("Converting to SQLite..."),!j(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||xs(e,r);let a=an();if(!a)throw new Error("scip CLI is not available");let s=await dt({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()}`:""}`)}catch(a){N(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 xs(e,t){let n=Oi(e);Is(n,t)}function Is(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function Ke(e,t,n){let r=op(e)||".scip",i=Lt(e,r);return C(S(e),`${i}.${n+1}.${t}${r}`)}async function jp(e,t){for(let n=0;n<2;n++){let r=Mp(e,t);if(r)return r;let i=Np(e);if(i&&ws(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await $p(i)}catch(s){throw new Error(`Could not verify the watcher's in-progress reindex owner (pid ${i.pid}); refusing to steal an active lock: ${ce(s)}`,{cause:s})}if(!o)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${S(e)}; refusing to steal an active lock.`);let a=Wt(e,{parseLegacy:Mt});if(!Lr(e,a,{parseLegacy:Mt}))throw new Error(`Reindex lock ownership changed before preemption completed for ${S(e)}.`);continue}throw new Error(`Another codebaseiq reindex is already running for ${S(e)}.`)}throw new Error(`Could not acquire codebaseiq reindex lock for ${S(e)}.`)}function Mp(e,t){let n=ee(process.pid),r=Ze(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:Mt});if(r.kind==="acquired"&&r.reclaimed){let i=Ps(r.reclaimed,e);i&&ws(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 ${S(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function Np(e){return Ps(Wt(e,{parseLegacy:Mt}),e)}var Mt=e=>{let t=vs(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function Ps(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:S(t),startedAt:e.record.startedAt,trigger:n.trigger}}return vs(e.parsed,t)}function vs(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=Or(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:S(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function ws(e,t){return e?.kind==="manual-cli"&&Gp(t?.trigger)}function Gp(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function $p(e){return!te(e.pid)||(Rr(e),ps(e,"SIGTERM"),await fs(e,2e3))?!0:(Rr(e),ps(e,"SIGKILL"),fs(e,1e3))}function ps(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!te(e.pid))return;Rr(e)}try{process.kill(e.pid,t)}catch{}}async function fs(e,t){let n=I()+t;for(;I()<n;){if(gs(e))return!0;await Vp(50)}return gs(e)}function Rr(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=ee(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!Ae(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function gs(e){if(!te(e.pid))return!0;if(!e.processIdentity)return!1;let t=ee(e.pid);return t!==null&&!Ae(e.processIdentity,t)}function Vp(e){return new Promise(t=>setTimeout(t,e))}function Es(e,t,n){return Object.fromEntries(t.map(r=>{let i=r==="typescript"?Hr(n.typescriptProjects):[],o=r==="clojure"?Bp(n.clojureConfigPath):void 0,a=[...ft(r).markerFiles,...i,...o?[o]:[]],s=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:i}:{typescriptProjectMode:"single",typescriptProjects:[]};return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&Wp(n),...s,clojureConfigPath:o,files:st(e,{language:r,markerFiles:a})}]}))}function Bp(e){return e?.trim()||void 0}function Wp(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Pr(e,t){return C(S(e),"language-indexes",`${t}.scip`)}function ks(e){return C(S(e),"language-indexes","typescript-projects")}function Nt(e,t){return C(ks(e),`${En(t)}.scip`)}function De(e){try{return Vt(Z(L(e,"reindex metadata")))}catch{return null}}function Ts(e,t){try{let n=Z(L(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return!1;let r=n.metadata;return n.capabilities.publishableGeneration&&Ar(r)&&Q(r.fingerprint)===Q(t)&&Q([...r.indexedLanguages??[]].sort())===Q(t.languages)}catch{return!1}}function vr(e,t){G(e,t,{spacing:2,trailingNewline:!0})}function Ds(e,t){try{let n=Vt(Z(L(e,"reindex metadata")));if(!n)return;vr(e,{...n,lastRefresh:t})}catch{}}function Gt(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:I()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function Q(e){return JSON.stringify(e)}export{Di as INDEXER_CONFIGS,hi as augmentAuxiliaryDocuments,Ml as augmentVueResolvedReferences,Nl as augmentVueResolvedReferencesAsync,ie as auxiliaryDocumentsAugmentationStage,Le as describeIndexerBinary,cn as detectLanguages,ft as getIndexerConfig,Zt as getIndexerExecutionEnv,Kt as isBinaryAvailable,Xt as isIndexerInstalled,bn as mergeScipFiles,Sn as mergeScipIndexes,Cy as reindex,Pe as resolveIndexerBinary,Qt as resolveProjectLocalIndexerBinary,B as runPostIndexAugmentation,pr as tryInstallIndexer,sn as tryInstallScipCli,ns as vueResolvedReferencesAugmentationStage};
|
|
298
|
+
//# sourceMappingURL=reindex.js.map
|