scip-query 0.19.6 → 0.19.10
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 +116 -0
- package/README.md +156 -44
- package/dist/augment-vue-worker.js +1 -1
- package/dist/chunk-26QA6FAI.js +8 -0
- package/dist/{chunk-J7VT2CRB.js → chunk-2HPVVXM5.js} +2 -2
- package/dist/chunk-2KAZEZ6M.js +2 -0
- package/dist/chunk-32LVLCLN.js +40 -0
- package/dist/{chunk-2CVXCGL4.js → chunk-3CLX5EOX.js} +2 -2
- package/dist/{chunk-5OC3HWP5.js → chunk-3G66UZBH.js} +2 -2
- package/dist/{chunk-S2GP3CU3.js → chunk-3ORVDL3H.js} +2 -2
- package/dist/chunk-46XGSFNI.js +2 -0
- package/dist/chunk-4MAK2HOY.js +6 -0
- package/dist/chunk-4TURLRL5.js +16 -0
- package/dist/chunk-4UQVNCQE.js +2 -0
- package/dist/chunk-55Q3WLZX.js +2 -0
- package/dist/{chunk-OQ2A4G2G.js → chunk-5E4WNAVD.js} +2 -2
- package/dist/{chunk-YGQN3XGZ.js → chunk-5I5G2QOX.js} +2 -2
- package/dist/chunk-6LDJQXAH.js +2 -0
- package/dist/{chunk-WXAAURU7.js → chunk-6O5TICIZ.js} +2 -2
- package/dist/{chunk-OBKDTVZ3.js → chunk-6SHPK5ZE.js} +2 -2
- package/dist/chunk-7BAVHKMJ.js +49 -0
- package/dist/chunk-7O5IKBTZ.js +16 -0
- package/dist/chunk-7PIO7NKH.js +60 -0
- package/dist/chunk-7S5E7KWT.js +2 -0
- package/dist/{chunk-GK3GRUJX.js → chunk-7SQQWSY3.js} +2 -2
- package/dist/chunk-7WPLAODU.js +5 -0
- package/dist/chunk-A73XVBCR.js +20 -0
- package/dist/chunk-AFHORGLH.js +42 -0
- package/dist/chunk-AIE7TFJW.js +9 -0
- package/dist/chunk-AQOFWNQJ.js +1 -0
- package/dist/{chunk-MGBJHRFB.js → chunk-AZJQQKDD.js} +2 -2
- package/dist/{chunk-IYAOX36F.js → chunk-B2PX5I6M.js} +2 -2
- package/dist/{chunk-EVOC5I5I.js → chunk-B7PBSLZN.js} +2 -2
- package/dist/{chunk-ZLJLE6LK.js → chunk-BBW6JFHN.js} +2 -2
- package/dist/{chunk-NBRUH7OE.js → chunk-BDCC2NPY.js} +2 -2
- package/dist/{chunk-DD5BOU5I.js → chunk-BNXCIFVY.js} +2 -2
- package/dist/{chunk-FHCTEANE.js → chunk-BPAPWKP6.js} +2 -2
- package/dist/chunk-BS2NMXQZ.js +4 -0
- package/dist/chunk-C3KV2II6.js +2 -0
- package/dist/chunk-C43RDDP4.js +20 -0
- package/dist/{chunk-QBYYWGAT.js → chunk-CJST5ETY.js} +2 -2
- package/dist/chunk-DAFAHMNB.js +42 -0
- package/dist/chunk-DHEQMPLW.js +2 -0
- package/dist/{chunk-336DC5NJ.js → chunk-DQGFVPUV.js} +2 -2
- package/dist/chunk-DQLPXMH6.js +8 -0
- package/dist/chunk-EKZTZXHZ.js +117 -0
- package/dist/{chunk-KLVJABXA.js → chunk-EN3O7VJA.js} +2 -2
- package/dist/{chunk-U5CNPPTZ.js → chunk-EW2NTSFA.js} +2 -2
- package/dist/chunk-F3Z4OUDS.js +8 -0
- package/dist/chunk-FJH2NW7J.js +66 -0
- package/dist/{chunk-3OIKRYU5.js → chunk-FKSELJQF.js} +2 -2
- package/dist/chunk-FTFP6O3L.js +11 -0
- package/dist/chunk-FYLK2DEJ.js +2 -0
- package/dist/chunk-GH74ASD6.js +11 -0
- package/dist/{chunk-NQLSSVOB.js → chunk-GMXWZP2B.js} +2 -2
- package/dist/chunk-GOUBFH5O.js +3 -0
- package/dist/{chunk-RJHCPSZ7.js → chunk-HLF2TX6R.js} +2 -2
- package/dist/{chunk-PC44K7RF.js → chunk-HX4GQPZP.js} +2 -2
- package/dist/chunk-HX7M4BDI.js +30 -0
- package/dist/chunk-HZ72SESS.js +128 -0
- package/dist/{chunk-YTUD45PU.js → chunk-IB2N4FIY.js} +2 -2
- package/dist/chunk-ILMHV3KM.js +2 -0
- package/dist/chunk-IZYYAFN5.js +2 -0
- package/dist/{chunk-A43URCQ3.js → chunk-JAYYFEQY.js} +2 -2
- package/dist/{chunk-RWRLUZ6U.js → chunk-JDOEX4E6.js} +2 -2
- package/dist/chunk-JFGGXWQF.js +947 -0
- package/dist/chunk-JN4NMBEX.js +8 -0
- package/dist/{chunk-JELJLXEE.js → chunk-JVYA47YU.js} +2 -2
- package/dist/{chunk-F42A3AKG.js → chunk-JW56N3KI.js} +2 -2
- package/dist/{chunk-FQTPPXNA.js → chunk-JZ2OXNWB.js} +2 -2
- package/dist/chunk-KFZNKUNT.js +2 -0
- package/dist/chunk-KMKTIO2G.js +8 -0
- package/dist/chunk-L5GJNV2T.js +8 -0
- package/dist/{chunk-RBFFD4V2.js → chunk-L7AW2QB5.js} +2 -2
- package/dist/chunk-L7JDSCDF.js +4 -0
- package/dist/chunk-LU47HG23.js +14 -0
- package/dist/chunk-LVY7NPF7.js +2 -0
- package/dist/chunk-LY4WC4AD.js +74 -0
- package/dist/{chunk-MLGTCX56.js → chunk-MKCDWWGV.js} +2 -2
- package/dist/chunk-MNE7YG56.js +2 -0
- package/dist/{chunk-YWB2EBNB.js → chunk-MRXBEXSY.js} +2 -2
- package/dist/chunk-MV7OWDUX.js +2 -0
- package/dist/{chunk-2GSQR6YA.js → chunk-N5W4YZMK.js} +2 -2
- package/dist/chunk-NGEXCJJW.js +11 -0
- package/dist/{chunk-CYJM7CYF.js → chunk-NIW6JDC5.js} +2 -2
- package/dist/{chunk-YHXBD52M.js → chunk-O64IZ6UX.js} +2 -2
- package/dist/chunk-PBUQFCNB.js +16 -0
- package/dist/{chunk-UQK5CRUK.js → chunk-POAVPHH7.js} +2 -2
- package/dist/{chunk-TYQ76QHQ.js → chunk-PQCI4SQX.js} +2 -2
- package/dist/chunk-PXY7F6Y4.js +5 -0
- package/dist/chunk-RDO52JGY.js +2 -0
- package/dist/chunk-RJT3TUUZ.js +2 -0
- package/dist/{chunk-OHWZKLVA.js → chunk-RUJURYSV.js} +2 -2
- package/dist/{chunk-CSTYYXKC.js → chunk-RVLDN63O.js} +2 -2
- package/dist/chunk-RXOXSKY3.js +2 -0
- package/dist/chunk-S7OYBOCK.js +2 -0
- package/dist/chunk-SMNXQT5Z.js +3 -0
- package/dist/{chunk-QQWOFXNW.js → chunk-SRAFT254.js} +2 -2
- package/dist/{chunk-6XHTISLI.js → chunk-SXP2MBJH.js} +2 -2
- package/dist/chunk-T7YQSHPQ.js +3 -0
- package/dist/{chunk-2EZSOTSY.js → chunk-TFRAYKN6.js} +2 -2
- package/dist/{chunk-XVJ3V7LM.js → chunk-UJCOIXDY.js} +2 -2
- package/dist/{chunk-7LABSJSR.js → chunk-UJPRPGCO.js} +5 -5
- package/dist/chunk-W4ETQAXM.js +2 -0
- package/dist/chunk-WCCFZ7V7.js +113 -0
- package/dist/chunk-WUPW3UN3.js +3 -0
- package/dist/{chunk-VP542C25.js → chunk-WXZLAAWK.js} +2 -2
- package/dist/{chunk-LMFVTUW2.js → chunk-X54AGLVX.js} +2 -2
- package/dist/chunk-XKWKXZKW.js +20 -0
- package/dist/{chunk-OP3MTFJR.js → chunk-XSRF6Q77.js} +2 -2
- package/dist/chunk-Y2MVPNKY.js +5 -0
- package/dist/{chunk-6XFC7PQ5.js → chunk-YKUU5AIC.js} +2 -2
- package/dist/chunk-YLCJLTPL.js +2 -0
- package/dist/{chunk-47X75ZKH.js → chunk-YTQVETEO.js} +2 -2
- package/dist/chunk-Z4N3MZYA.js +38 -0
- package/dist/chunk-ZHXX42OH.js +18 -0
- package/dist/chunk-ZJOOT3BG.js +2 -0
- package/dist/chunk-ZK26BAQL.js +2 -0
- package/dist/{chunk-UUJBLG6J.js → chunk-ZTETIQ35.js} +2 -2
- package/dist/cli.js +3 -3
- package/dist/command-descriptors-4A4HWV4F.js +642 -0
- package/dist/{config-types-BWQ5xPGI.d.ts → config-types-jVM3D7MA.d.ts} +72 -2
- package/dist/{db-B0r1o7Vt.d.ts → db-B5PM5yNk.d.ts} +20 -2
- package/dist/{diff-gate-types-C9BoYwYD.d.ts → diff-gate-types-B0QYpDv1.d.ts} +2 -1
- package/dist/direct-navigation-6YHV6IB5.js +3 -0
- package/dist/{health-CFnlCiTz.d.ts → health-Do5TKSJI.d.ts} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/postinstall.js +1 -1
- package/dist/queries/affected.d.ts +2 -2
- package/dist/queries/affected.js +1 -1
- package/dist/queries/architecture.d.ts +2 -2
- package/dist/queries/architecture.js +1 -1
- package/dist/queries/bottlenecks.d.ts +2 -2
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.d.ts +2 -2
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +2 -2
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +22 -3
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.d.ts +2 -2
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.d.ts +2 -2
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +2 -2
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +3 -3
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +3 -3
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.d.ts +2 -2
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +2 -2
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +2 -2
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +2 -2
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.d.ts +2 -2
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.d.ts +2 -2
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/deep-chains.d.ts +2 -2
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/deps.d.ts +2 -2
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-gate.d.ts +40 -7
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.d.ts +84 -6
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +3 -3
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +2 -2
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.d.ts +3 -3
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/extract-candidates.d.ts +2 -2
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +2 -2
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +12 -3
- package/dist/queries/files.js +1 -1
- package/dist/queries/health.d.ts +3 -3
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +2 -2
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +2 -2
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +2 -2
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +8 -6
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +141 -10
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.d.ts +2 -2
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.d.ts +2 -2
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.d.ts +2 -2
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.d.ts +34 -3
- package/dist/queries/methods.js +1 -1
- package/dist/queries/not-implemented.d.ts +2 -2
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.d.ts +2 -2
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.d.ts +3 -3
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.d.ts +3 -3
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/react-component-duplicates.d.ts +2 -2
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.d.ts +2 -2
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.d.ts +2 -2
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.d.ts +2 -2
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +2 -2
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.d.ts +2 -2
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.d.ts +2 -2
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-chains.d.ts +2 -2
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.d.ts +2 -2
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.d.ts +2 -2
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +2 -2
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.d.ts +2 -2
- package/dist/queries/slice.js +1 -1
- package/dist/queries/stale-abstractions.d.ts +2 -2
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/stats.d.ts +2 -2
- package/dist/queries/surface.d.ts +2 -2
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.d.ts +2 -2
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.d.ts +2 -2
- package/dist/queries/system.js +1 -1
- package/dist/queries/test-quality.d.ts +2 -2
- package/dist/queries/test-quality.js +1 -1
- package/dist/queries/trace.d.ts +2 -2
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.d.ts +14 -3
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/twin-drift.d.ts +2 -2
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.d.ts +2 -2
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.d.ts +2 -2
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/vue-component-duplicates.d.ts +2 -2
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.d.ts +2 -2
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.d.ts +2 -2
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/queries/wrapper-candidates.d.ts +2 -2
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/reindex-worker.js +26 -25
- package/dist/reindex.d.ts +7 -3
- package/dist/reindex.js +34 -33
- package/dist/runtime.d.ts +5 -10
- package/dist/runtime.js +3 -3
- package/dist/rust-semantic-session-server.js +1 -1
- package/dist/rust-semantic-session-worker.js +1 -1
- package/dist/rust-semantic-worker.js +1 -1
- package/dist/{scip-cli-DCvnlZCu.d.ts → scip-cli-BnEwZRLJ.d.ts} +2 -2
- package/dist/{symbol-types-BgWU6lhL.d.ts → symbol-types-BIQwfoAx.d.ts} +7 -1
- package/dist/typescript-mailbox-worker.js +2 -0
- package/dist/watch-server.js +2 -42
- package/docs/AGENT_GUIDE.md +28 -5
- package/docs/CLI_JSON_OUTPUT.md +176 -3
- package/docs/COMMAND_REFERENCE.md +89 -87
- package/docs/COMMITTED_RECORD_COMPATIBILITY.md +55 -18
- package/docs/DURABILITY.md +88 -38
- package/docs/INDEX_GENERATIONS.md +65 -19
- package/docs/MAILBOX_LIFECYCLE.md +28 -1
- package/docs/REINDEX_METADATA_COMPATIBILITY.md +18 -8
- package/docs/SECURITY_MODEL.md +146 -0
- package/docs/TELEMETRY_RETENTION.md +16 -4
- package/docs/WATCH_REFRESH_REQUESTS.md +34 -21
- package/docs/WINDOWS_SIDECAR_RELEASE.md +9 -4
- package/docs/analyzer-inventory.md +31 -22
- package/docs/analyzer-validation-ledger.md +8 -0
- package/docs/schemas/cli-output-page.schema.json +104 -0
- package/docs/schemas/outcome-event-record.schema.json +57 -1
- package/docs/schemas/project-config.schema.json +82 -1
- package/docs/schemas/suppression-record.schema.json +84 -3
- package/package.json +9 -8
- package/skills/_shared/SKILL.md +5 -3
- package/skills/_shared/references/agent-contract-catalog.md +1 -1
- package/skills/_shared/references/detector-precision-and-diffgate.md +1 -1
- package/skills/scip-audit/SKILL.md +9 -8
- package/skills/scip-audit/references/claims.md +1 -1
- package/skills/scip-audit/references/cleanup.md +19 -20
- package/skills/scip-audit/references/directory.md +4 -4
- package/skills/scip-audit/references/frontend.md +10 -10
- package/skills/scip-audit/references/twin-drift.md +2 -2
- package/skills/scip-diagnose/references/debug.md +8 -8
- package/skills/scip-diagnose/references/root-cause.md +3 -3
- package/skills/scip-diagnose/references/triage.md +10 -10
- package/skills/scip-explore/SKILL.md +4 -4
- package/skills/scip-improve/SKILL.md +10 -10
- package/skills/scip-improve/references/cleanup-batches.md +3 -3
- package/skills/scip-improve/references/directory-moves.md +3 -3
- package/skills/scip-improve/references/doc-reconcile.md +1 -1
- package/skills/scip-improve/references/frontend-extraction.md +2 -2
- package/skills/scip-improve/references/twin-drift.md +3 -3
- package/skills/scip-plan/SKILL.md +3 -3
- package/skills/scip-plan/references/api-impact.md +5 -5
- package/skills/scip-plan/references/conductor.md +2 -2
- package/skills/scip-plan/references/hyper-optimization.md +1 -1
- package/skills/scip-query/SKILL.md +15 -5
- package/skills/scip-setup/references/bootstrap-workflow.md +7 -8
- package/skills/scip-setup/references/language-verification.md +2 -2
- package/skills/scip-setup/references/per-repo-triage.md +1 -1
- package/skills/scip-verify/SKILL.md +16 -11
- package/skills/scip-verify/references/calibrate-detectors.md +7 -7
- package/dist/chunk-24QNP7MN.js +0 -2
- package/dist/chunk-26X7KCJR.js +0 -5
- package/dist/chunk-273W2U4Y.js +0 -40
- package/dist/chunk-2OXVAGGT.js +0 -3
- package/dist/chunk-2ZOCHAL2.js +0 -8
- package/dist/chunk-35SQLYCQ.js +0 -2
- package/dist/chunk-4CGVLUDP.js +0 -18
- package/dist/chunk-4RI4BJGT.js +0 -8
- package/dist/chunk-52HQTTPB.js +0 -2
- package/dist/chunk-64MNV6AB.js +0 -8
- package/dist/chunk-7E3TH5ZN.js +0 -33
- package/dist/chunk-7Q6VYYCH.js +0 -2
- package/dist/chunk-A63U2W3P.js +0 -3
- package/dist/chunk-ADFSIJP2.js +0 -16
- package/dist/chunk-AOLE4DYM.js +0 -6
- package/dist/chunk-APMMR5Y2.js +0 -2
- package/dist/chunk-B5MHCHP3.js +0 -107
- package/dist/chunk-DGAGY7RJ.js +0 -60
- package/dist/chunk-DGMCFMPG.js +0 -11
- package/dist/chunk-E2ZXPB7J.js +0 -38
- package/dist/chunk-FKGN4A4E.js +0 -61
- package/dist/chunk-G4UQL4CP.js +0 -2
- package/dist/chunk-GA64UPMI.js +0 -6
- package/dist/chunk-HEBAY673.js +0 -2
- package/dist/chunk-HELS7KFF.js +0 -2
- package/dist/chunk-IPDCSB6N.js +0 -6
- package/dist/chunk-JERWGHQT.js +0 -16
- package/dist/chunk-JJJCO4QC.js +0 -945
- package/dist/chunk-JZNLMHWY.js +0 -56
- package/dist/chunk-K42M2KWT.js +0 -2
- package/dist/chunk-KP4KBDVF.js +0 -3
- package/dist/chunk-LRTP3DKL.js +0 -3
- package/dist/chunk-N3SE646F.js +0 -2
- package/dist/chunk-NN4ZIRPK.js +0 -8
- package/dist/chunk-P6HBYNBE.js +0 -5
- package/dist/chunk-QHKUY4FW.js +0 -2
- package/dist/chunk-QHRL4LKM.js +0 -2
- package/dist/chunk-SHKZ7OVJ.js +0 -35
- package/dist/chunk-TFUU5MQQ.js +0 -2
- package/dist/chunk-UXP636P5.js +0 -144
- package/dist/chunk-VEVBIAOJ.js +0 -16
- package/dist/chunk-VKRQDBW5.js +0 -9
- package/dist/chunk-VOQFGC2W.js +0 -67
- package/dist/chunk-WMXRRBII.js +0 -8
- package/dist/chunk-X3NLZHPA.js +0 -20
- package/dist/chunk-XF3KLXN3.js +0 -11
- package/dist/chunk-YCPASUCX.js +0 -2
- package/dist/chunk-YLVE3SXZ.js +0 -20
- package/dist/chunk-Z2LHPIOM.js +0 -2
- package/dist/chunk-Z5QQPJ3U.js +0 -30
- package/dist/chunk-ZTTISZ7J.js +0 -112
- package/dist/command-descriptors-SJDZ7QGR.js +0 -617
- package/dist/direct-navigation-HTKOZEOM.js +0 -3
package/dist/reindex.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let l=0;for(let p of d){if(o.has(p))continue;let
|
|
3
|
-
`).filter(r=>r&&t.has(
|
|
1
|
+
import{a as oe}from"./chunk-A73XVBCR.js";import{a as Mr,b as Nr,c as Gr,d as $r,f as qt,g as Ut,h as Wt,l as Ht,m as Vr,n as Br,p as zt,q as qr,r as Ur,s as Wr,t as Hr}from"./chunk-JN4NMBEX.js";import{a as jr}from"./chunk-7PIO7NKH.js";import"./chunk-AQOFWNQJ.js";import{C as Nt,D as Fr,E as Gt,F as $t,G as Ar,H as _r,I as Vt,K as Bt,P as Or,R as Cr,a as Sr,b as ue,c as X,d as j,e as de,f as br,g as Ye,h as _t,i as M,j as Rr,l as xr,m as ve,n as Lt,o as Ke,q as ie,r as Pe,s as le,t as Ee,u as pe,v as Ct,w as jt,x as Tr,y as Dr,z as Mt}from"./chunk-7WPLAODU.js";import{a as mr,b as xe,c as J,d as Y,e as x,g as He,h as At,i as yr,k as ze,l as K,m as Ie,n as Je,q as Ot,r as Er,w as et,z as Lr}from"./chunk-BS2NMXQZ.js";import{a as Ze}from"./chunk-C43RDDP4.js";import"./chunk-UJPRPGCO.js";import{F as wr,G as kr}from"./chunk-GH74ASD6.js";import{B as Ir,E as vr,H as Qe,I as Pr,a as lr,b as pr,c as Ue,d as Re,e as z,f as Dt,g as gr,h as Ft,i as fr,v as we,w as ke}from"./chunk-WCCFZ7V7.js";import{a as Xe}from"./chunk-NGEXCJJW.js";import"./chunk-7S5E7KWT.js";import{f as A,g as B,h as _,k as w,l as v,m as k,p as hr,q as We}from"./chunk-2KAZEZ6M.js";import{e as be,f as dr}from"./chunk-C3KV2II6.js";import{execFileSync as Vl}from"child_process";import{createHash as Bl}from"crypto";import{copyFileSync as kt,existsSync as G,mkdirSync as Pt,mkdtempSync as ql,readdirSync as Wa,renameSync as Ha,rmSync as ye,statSync as Ul}from"fs";import{basename as vt,dirname as b,extname as Wl,join as D,resolve as Ma}from"path";import{platform as Hl}from"os";import cs from"better-sqlite3";import{execFileSync as us}from"child_process";import{existsSync as ds,readdirSync as ls}from"fs";import{extname as tt,join as ps}from"path";function Q(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>zr({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function zr(e){let t=new Set((e.extensions??wr).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!ds(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=jr(e.projectRoot),r=gs(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new cs(e.dbPath);try{let o=ms(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
|
|
2
|
+
VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let l=0;for(let p of d){if(o.has(p))continue;let m=vr(e.projectRoot,p,{inputKind:"auxiliary source file"}),g=a.run(hs(p),p,m);l+=Number(g.changes)}return l})(r),u={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${u.existing} already present).`),u}finally{i.close()}}function gs(e,t){let n=fs(e,t);if(n)return n;let r=[],i=o=>{let a=o?ps(e,o):e,s;try{s=ls(a,{withFileTypes:!0})}catch{return}for(let c of s){if(kr.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(tt(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function fs(e,t){try{return us("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}).split(`
|
|
3
|
+
`).filter(r=>r&&t.has(tt(r).toLowerCase())).sort()}catch{return null}}function ms(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 hs(e){return tt(e).toLowerCase()===".vue"?"vue":tt(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as Ss}from"crypto";import{existsSync as bs}from"fs";import{dirname as Rs,join as Yr}from"path";function Jt(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 nt(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=Jt(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"),Jr(r,i,a)):a.size>0?Jr(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:ys(r,t,i),reasons:[]}}function Jr(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function ys(e,t,n){let r=new Map;for(let[a,s]of t)if(n.has(a))for(let c of s){if(!n.has(c))continue;let u=r.get(c)??new Set;u.add(a),r.set(c,u)}let i=new Set(e),o=[...e];for(let a=0;a<o.length;a+=1){let s=o[a];if(s!==void 0)for(let c of r.get(s)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}var xs="<global-symbols>";function Is(e){let t=[];for(let n of e.all(`
|
|
4
4
|
SELECT relative_path, language, position_encoding, text
|
|
5
5
|
FROM documents
|
|
6
6
|
`))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
|
|
@@ -27,7 +27,7 @@ import{a as X}from"./chunk-X3NLZHPA.js";import{a as Ot,e as jt,f as oe,g as _t,h
|
|
|
27
27
|
FROM defn_enclosing_ranges r
|
|
28
28
|
JOIN documents d ON d.id = r.document_id
|
|
29
29
|
JOIN global_symbols g ON g.id = r.symbol_id
|
|
30
|
-
`))t.push({relativePath:n.relative_path,kind:"definition",values:
|
|
30
|
+
`))t.push({relativePath:n.relative_path,kind:"definition",values:Yt(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
|
|
31
31
|
SELECT d.relative_path,
|
|
32
32
|
c.chunk_index,
|
|
33
33
|
m.role,
|
|
@@ -42,7 +42,7 @@ import{a as X}from"./chunk-X3NLZHPA.js";import{a as Ot,e as jt,f as oe,g as _t,h
|
|
|
42
42
|
JOIN chunks c ON c.id = m.chunk_id
|
|
43
43
|
JOIN documents d ON d.id = c.document_id
|
|
44
44
|
JOIN global_symbols g ON g.id = m.symbol_id
|
|
45
|
-
`))t.push({relativePath:n.relative_path,kind:"mention",values:
|
|
45
|
+
`))t.push({relativePath:n.relative_path,kind:"mention",values:Yt(n,[n.chunk_index,n.role])});for(let n of e.all(`
|
|
46
46
|
SELECT g.symbol,
|
|
47
47
|
g.display_name,
|
|
48
48
|
g.kind,
|
|
@@ -56,9 +56,9 @@ import{a as X}from"./chunk-X3NLZHPA.js";import{a as Ot,e as jt,f as oe,g as _t,h
|
|
|
56
56
|
) AND NOT EXISTS (
|
|
57
57
|
SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
|
|
58
58
|
)
|
|
59
|
-
`))t.push({relativePath:
|
|
60
|
-
`);n.set(r,o.digest("hex"))}return n}function
|
|
61
|
-
`)){if(!r||r.split("/").some(o=>Lr.has(o)))continue;let i=Cr(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function bs(e,t){return t?.length?t.some(n=>e.has(n)):!1}function jr(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as Nr,readdirSync as Rs}from"fs";import{isAbsolute as xs,join as Gt,resolve as Is}from"path";var Vr={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>{let i=r?["index","--output",e,"--no-progress-bar",r]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!r&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],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","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],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:["pom.xml","build.gradle"],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:["build.sbt"],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:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:te.language,indexerBinary:te.indexerBinary,checkCommand:`${te.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:te.indexerBinary,args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:te.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:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],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",xs(r)?r:Is(e,r)),{binary:n,args:i}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],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:["Gemfile"],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:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],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:["CMakeLists.txt","Makefile"],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:["CMakeLists.txt","Makefile"],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",$r(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],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",$r(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],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:["pubspec.yaml"],installMethods:[{label:"dart pub",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart"]}],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:({projectRoot:e,indexerBinary:t})=>{let n=Gt(e,"vendor","bin","scip-php"),r=Gt(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",Nr(r)?r:Nr(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function ze(e){return Vr[e]}function $r(e,t){let n;try{n=Rs(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Gt(e,i);return null}import{readFileSync as Bt,writeFileSync as Wt}from"fs";import{create as Re}from"@bufbuild/protobuf";import{deserializeSCIP as qt,serializeSCIP as Ht,DocumentSchema as Ds,IndexSchema as Br,MetadataSchema as As,SymbolInformationSchema as Os}from"@c4312/scip";import{readFileSync as vs,writeFileSync as Ps}from"fs";import{create as Gr}from"@bufbuild/protobuf";import{deserializeSCIP as ws,DocumentSchema as ks,IndexSchema as Es,serializeSCIP as Ts,SymbolRole as Fs}from"@c4312/scip";function Ur(e){let t;try{t=ws(vs(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=Ut(t);return n.removedDefinitionOccurrences>0&&Ps(e,Buffer.from(Ts(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function Ut(e){let t=new Set;for(let o of e.documents)for(let a of o.symbols)a.symbol&&t.add(a.symbol);for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,r=0,i=[];for(let o of e.documents){let a=o.occurrences.filter(s=>(s.symbolRoles&Fs.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(Gr(ks,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:Gr(Es,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function zt(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=_s(e),n=Cs(e.flatMap(i=>i.documents??[])),r=Hr(e.flatMap(i=>i.externalSymbols??[]));return Re(Br,{metadata:t,documents:n,externalSymbols:r})}function Jt(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>qt(Bt(i))),r=zt(n);return Wt(t,Buffer.from(Ht(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function Wr(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>qt(Bt(i))),r=Ut(zt(n));return Wt(t,Buffer.from(Ht(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function js(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(r.projectRoot!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return Re(Br,{metadata:Re(As,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function qr(e,t,n){let r=qt(Bt(e)),i=js(r,t,n);Wt(e,Buffer.from(Ht(i)))}function _s(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function Cs(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,Re(Ds,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:Ms([...r.occurrences,...n.occurrences]),symbols:Hr([...r.symbols,...n.symbols]),text:Ns(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Ms(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 Hr(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,Re(Os,{symbol:r.symbol,documentation:$s([...r.documentation,...n.documentation]),relationships:Ls([...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 Ls(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 Ns(e,t){return e?t?e.length>=t.length?e:t:e:t}function $s(e){return[...new Set(e)]}import{createHash as Vs}from"crypto";import{copyFileSync as Gs,existsSync as zr,rmSync as Jr}from"fs";import{resolve as Us}from"path";import Qr from"better-sqlite3";var Bs={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}]},Ws={idx_chunks_doc_id:{table:"chunks",columns:["document_id"]},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_global_symbols_symbol:{table:"global_symbols",columns:["symbol"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Kr(e){let t=y(),n=qs(e.affectedFiles);if(Hs(e.previousDbPath,e.miniDbPath,e.candidateDbPath),Jr(e.candidateDbPath,{force:!0}),!zr(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!zr(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");Yr(e.previousDbPath,"previous SQLite generation",!1),Yr(e.miniDbPath,"incremental SQLite mini database"),Gs(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new Qr(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Yt(r,"main","candidate SQLite generation"),Yt(r,"incremental","incremental SQLite mini database"),zs(r,n),Js(r,n.length);let i=Xt(r,"main",!0),o=B(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{Ys(r),Xs(r),Qs(r),e.onStage?.("after-delete"),Ks(r),e.onStage?.("after-symbol-reconciliation"),Zs(r),e.onStage?.("after-insert"),ec(r),tc(r,n.length,o),e.onStage?.("before-commit")}).immediate(),Zr(r,"main","candidate SQLite generation");let c=[...nc(r)].filter(([u,d])=>i.get(u)!==d).map(([u])=>u).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:y()-t}}catch(i){try{r?.close()}finally{Jr(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function qs(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 Hs(e,t,n){let r=[e,t,n].map(i=>Us(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Yr(e,t,n=!0){let r=new Qr(e,{readonly:!0,fileMustExist:!0});try{Yt(r,"main",t),n&&Zr(r,"main",t)}finally{r.close()}}function Yt(e,t,n){for(let[r,i]of Object.entries(Bs)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:d})=>({name:s,type:c.toUpperCase(),notnull:u,pk:d}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(Ws)){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}`)}Xr(e,t,"documents",["relative_path"],n),Xr(e,t,"global_symbols",["symbol"],n)}function Xr(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(s=>{if(s.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${s.name}')`).all().map(u=>u.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function Zr(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 zs(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 Js(e,t){let n=B(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=B(e,`SELECT COUNT(*) AS value
|
|
59
|
+
`))t.push({relativePath:xs,kind:"global-symbol",values:Yt(n)});return vs(t)}function vs(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=Ss("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 Ps(e,t){let n=[],r=[],i=[],o=[],a=new Set([...e.keys(),...t.keys()]);for(let s of[...a].sort()){let c=e.get(s),u=t.get(s);c===void 0?n.push(s):u===void 0?i.push(s):c!==u?r.push(s):o.push(s)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function Kt(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 Xt(e,t=Fs){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,i=t.wallNow??t.now,o=r(),a=(u,d)=>{let l=r();return Zr(e.refreshResult,u,n?l:i(),Math.max(0,l-o),d)};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 u=[...new Set([...t.indexedPaths(s),...t.indexedPaths(c)])].sort(),d=Ue(e.previousSnapshot,e.currentSnapshot),l=new Set(u),p=d.changes.length>0&&!Jt(d).fullProject&&d.changes.every(y=>l.has(y.path)),m=nt(d,p?t.dependencyGraph(s):new Map,u),g=Ps(t.factDigests(s),t.factDigests(c)),f=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?f:i()).toISOString(),durationMs:Math.max(0,f-o),manifest:d,plan:m,comparison:g,evaluation:Kt(m,g,u.length)}}catch(u){return a("oracle-error",u instanceof Error?u.message:String(u))}finally{Kr(s),Kr(c)}}function Xr(e,t,n,r=Date.now()){return Zr(e,t,r,0,n)}function ws(e){let t=Rs(e);return{latestPath:Yr(t,"affected-shadow-latest.json"),historyPath:Yr(t,"affected-shadow.jsonl")}}function Qr(e,t,n=As){let r=ws(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var ks=8*1024*1024,Es=Vr;function Ts(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 Ds(e,t,n=ks){Br(e,Ts(t),{maxSegmentBytes:n,previousSuffix:Es})}function Yt(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 Fs={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:x,databaseExists:e=>bs(e),openDatabase:(e,t,n)=>new oe({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>Xe(e),dependencyGraph:e=>Ze(e),factDigests:e=>Is(e)},As={appendHistory:Ds,writeLatest:(e,t)=>X(e,t,{spacing:2,trailingNewline:!0})};function Zr(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 Kr(e){try{e?.close()}catch{}}import{execFileSync as _s}from"child_process";import{existsSync as Ls,readdirSync as ti}from"fs";import{extname as ni,join as ri}from"path";var ii=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),Os=[{language:"typescript",files:["tsconfig.json","tsconfig.base.json"],extensions:[".ts",".tsx",".mts",".cts"]},{language:"rust",files:["Cargo.toml"],extensions:[".rs"]},{language:"go",files:["go.mod"],extensions:[".go"]},{language:"java",files:["pom.xml","build.gradle","build.gradle.kts"],extensions:[".java"]},{language:"kotlin",files:["build.gradle.kts"],extensions:[".kt",".kts"]},{language:"scala",files:["build.sbt"],extensions:[".scala"]},{language:"clojure",files:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],extensions:[".clj",".cljs",".cljc"]},{language:"python",files:["pyproject.toml","setup.py","setup.cfg","Pipfile"],extensions:[".py",".pyi"]},{language:"ruby",files:["Gemfile"],extensions:[".rb"]},{language:"cpp",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"]},{language:"c",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".c",".h"]},{language:"csharp",globs:["*.csproj","*.sln"],extensions:[".cs"]},{language:"vb",globs:["*.vbproj"],extensions:[".vb"]},{language:"dart",files:["pubspec.yaml"],extensions:[".dart"]},{language:"php",files:["composer.json"],extensions:[".php"]},{language:"javascript",files:["package.json"],extensions:[".js",".jsx",".mjs",".cjs"]}];function Qt(e){let t=[],n=Cs(e),r=Gs(e);for(let i of Os){if(js(e,i.files)){t.push(i.language);continue}if(Ms(n,i.globs)){t.push(i.language);continue}Vs(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&ei(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&ei(t,"c"),t}function Cs(e){try{return ti(e)}catch{return[]}}function js(e,t){return t?.length?t.some(n=>Ls(ri(e,n))):!1}function Ms(e,t){return t?.length?e.some(n=>t.some(r=>Ns(n,r))):!1}function Ns(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,r]=t.split("*");return e.startsWith(n??"")&&e.endsWith(r??"")}function Gs(e){let t=$s(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let o;try{o=ti(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(a.name.startsWith(".")&&!a.name.endsWith("proj")&&!a.name.endsWith("sln")&&a.isDirectory())continue;let s=ri(i,a.name);if(a.isDirectory()){ii.has(a.name)||r.push(s);continue}let c=ni(a.name).toLowerCase();c&&n.add(c)}}return n}function $s(e){try{let t=_s("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}),n=new Set;for(let r of t.split(`
|
|
61
|
+
`)){if(!r||r.split("/").some(o=>ii.has(o)))continue;let i=ni(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Vs(e,t){return t?.length?t.some(n=>e.has(n)):!1}function ei(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{readdirSync as Bs}from"fs";import{isAbsolute as oi,join as qs,resolve as Us}from"path";var rt="@sourcegraph/scip-typescript@0.4.0",ai="scip-python-plus@0.7.5",si="github.com/sourcegraph/scip-go@v0.2.7",ci="scip-dotnet@0.2.14",Ws="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})=>{let i=r?["index","--output",e,"--no-progress-bar",r]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!r&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",identity:rt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",rt]}],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","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",identity:rt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",rt]}],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:["pom.xml","build.gradle"],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:["build.sbt"],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:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:le.language,indexerBinary:le.indexerBinary,checkCommand:`${le.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:le.indexerBinary,args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[],installUrl:le.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:["pyproject.toml","setup.py"],installMethods:[{label:"npm",identity:ai,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",ai]}],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",oi(r)?r:Us(e,r)),{binary:n,args:i}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],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:["Gemfile"],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:["go.mod"],installMethods:[{label:"go install",identity:si,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",si]}],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:["CMakeLists.txt","Makefile"],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:["CMakeLists.txt","Makefile"],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",ui(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",identity:ci,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",ui(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",identity:ci,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:["pubspec.yaml"],installMethods:[{label:"dart pub",identity:Ws,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})=>oi(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function it(e){return di[e]}function ui(e,t){let n;try{n=Bs(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return qs(e,i);return null}import{writeFileSync as en}from"fs";import{create as Te}from"@bufbuild/protobuf";import{deserializeSCIP as tn,serializeSCIP as nn,DocumentSchema as Qs,IndexSchema as gi,MetadataSchema as Zs,SymbolInformationSchema as ec}from"@c4312/scip";import{writeFileSync as Hs}from"fs";import{create as li}from"@bufbuild/protobuf";import{deserializeSCIP as zs,DocumentSchema as Js,IndexSchema as Ys,serializeSCIP as Ks,SymbolRole as Xs}from"@c4312/scip";function pi(e){let t;try{t=zs(w(e,{inputKind:"SCIP sanitization input",maxBytes:_}))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=Zt(t);return n.removedDefinitionOccurrences>0&&Hs(e,Buffer.from(Ks(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function Zt(e){let t=new Set;for(let o of e.documents){dr(o.relativePath);for(let a of o.symbols)a.symbol&&t.add(a.symbol)}for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,r=0,i=[];for(let o of e.documents){let a=o.occurrences.filter(s=>(s.symbolRoles&Xs.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(li(Js,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:li(Ys,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function rn(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=nc(e),n=rc(e.flatMap(i=>i.documents??[])),r=hi(e.flatMap(i=>i.externalSymbols??[]));return Te(gi,{metadata:t,documents:n,externalSymbols:r})}function on(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>tn(w(i,{inputKind:"SCIP merge input",maxBytes:_}))),r=rn(n);return en(t,Buffer.from(nn(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function fi(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>tn(w(i,{inputKind:"SCIP merge input",maxBytes:_}))),r=Zt(rn(n));return en(t,Buffer.from(nn(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function tc(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(r.projectRoot!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return Te(gi,{metadata:Te(Zs,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function mi(e,t,n){let r=tn(w(e,{inputKind:"SCIP normalization input",maxBytes:_})),i=tc(r,t,n);en(e,Buffer.from(nn(i)))}function nc(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function rc(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,Te(Qs,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:ic([...r.occurrences,...n.occurrences]),symbols:hi([...r.symbols,...n.symbols]),text:ac(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function ic(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 hi(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,Te(ec,{symbol:r.symbol,documentation:sc([...r.documentation,...n.documentation]),relationships:oc([...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 oc(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 ac(e,t){return e?t?e.length>=t.length?e:t:e:t}function sc(e){return[...new Set(e)]}import{createHash as cc}from"crypto";import{copyFileSync as uc,existsSync as yi,rmSync as Si}from"fs";import{resolve as dc}from"path";import xi from"better-sqlite3";var lc={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}]},pc={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 Ii(e){let t=x(),n=gc(e.affectedFiles);if(fc(e.previousDbPath,e.miniDbPath,e.candidateDbPath),Si(e.candidateDbPath,{force:!0}),!yi(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!yi(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");bi(e.previousDbPath,"previous SQLite generation",!1),bi(e.miniDbPath,"incremental SQLite mini database"),uc(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new xi(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),an(r,"main","candidate SQLite generation"),an(r,"incremental","incremental SQLite mini database"),mc(r,n),hc(r,n.length);let i=sn(r,"main",!0),o=Z(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{yc(r),Sc(r),bc(r),e.onStage?.("after-delete"),Rc(r),e.onStage?.("after-symbol-reconciliation"),xc(r),e.onStage?.("after-insert"),Ic(r),vc(r,n.length,o),e.onStage?.("before-commit")}).immediate(),vi(r,"main","candidate SQLite generation");let c=[...Pc(r)].filter(([u,d])=>i.get(u)!==d).map(([u])=>u).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:x()-t}}catch(i){try{r?.close()}finally{Si(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function gc(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 fc(e,t,n){let r=[e,t,n].map(i=>dc(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function bi(e,t,n=!0){let r=new xi(e,{readonly:!0,fileMustExist:!0});try{an(r,"main",t),n&&vi(r,"main",t)}finally{r.close()}}function an(e,t,n){for(let[r,i]of Object.entries(lc)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:d})=>({name:s,type:c.toUpperCase(),notnull:u,pk:d}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(pc)){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}`)}Ri(e,t,"documents",["relative_path"],n),Ri(e,t,"global_symbols",["symbol"],n)}function Ri(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(s=>{if(s.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${s.name}')`).all().map(u=>u.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function vi(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 mc(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 hc(e,t){let n=Z(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=Z(e,`SELECT COUNT(*) AS value
|
|
62
62
|
FROM main.documents d
|
|
63
63
|
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
|
|
64
64
|
FROM temp.incremental_affected_paths p
|
|
@@ -68,7 +68,7 @@ import{a as X}from"./chunk-X3NLZHPA.js";import{a as Ot,e as jt,f as oe,g as _t,h
|
|
|
68
68
|
FROM incremental.documents d
|
|
69
69
|
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
70
70
|
WHERE p.relative_path IS NULL
|
|
71
|
-
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
|
|
71
|
+
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 yc(e){e.exec(`
|
|
72
72
|
CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
73
73
|
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
74
74
|
SELECT g.symbol
|
|
@@ -95,7 +95,7 @@ import{a as X}from"./chunk-X3NLZHPA.js";import{a as Ot,e as jt,f as oe,g as _t,h
|
|
|
95
95
|
FROM incremental.mentions m
|
|
96
96
|
JOIN incremental.global_symbols g ON g.id = m.symbol_id
|
|
97
97
|
WHERE m.role = 1;
|
|
98
|
-
`)}function
|
|
98
|
+
`)}function Sc(e){let t=e.prepare(`WITH changed_symbols AS (
|
|
99
99
|
SELECT symbol FROM temp.incremental_old_defined_symbols
|
|
100
100
|
UNION
|
|
101
101
|
SELECT symbol FROM temp.incremental_new_defined_symbols
|
|
@@ -118,7 +118,7 @@ import{a as X}from"./chunk-X3NLZHPA.js";import{a as Ot,e as jt,f as oe,g as _t,h
|
|
|
118
118
|
SELECT u.symbol
|
|
119
119
|
FROM unaffected_definitions u
|
|
120
120
|
JOIN changed_symbols c ON c.symbol = u.symbol
|
|
121
|
-
LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function
|
|
121
|
+
LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function bc(e){e.exec(`
|
|
122
122
|
DELETE FROM main.mentions
|
|
123
123
|
WHERE chunk_id IN (
|
|
124
124
|
SELECT c.id
|
|
@@ -140,7 +140,7 @@ import{a as X}from"./chunk-X3NLZHPA.js";import{a as Ot,e as jt,f as oe,g as _t,h
|
|
|
140
140
|
);
|
|
141
141
|
DELETE FROM main.documents
|
|
142
142
|
WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
|
|
143
|
-
`)}function
|
|
143
|
+
`)}function Rc(e){e.exec(`
|
|
144
144
|
UPDATE main.global_symbols
|
|
145
145
|
SET display_name = NULL,
|
|
146
146
|
kind = NULL,
|
|
@@ -182,7 +182,7 @@ import{a as X}from"./chunk-X3NLZHPA.js";import{a as Ot,e as jt,f as oe,g as _t,h
|
|
|
182
182
|
WHERE source.symbol = main.global_symbols.symbol
|
|
183
183
|
)
|
|
184
184
|
WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
|
|
185
|
-
`)}function
|
|
185
|
+
`)}function xc(e){let t=Z(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=Z(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=Z(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
|
|
186
186
|
SELECT id + ?, language, relative_path, position_encoding, text
|
|
187
187
|
FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
|
|
188
188
|
SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
|
|
@@ -197,15 +197,15 @@ import{a as X}from"./chunk-X3NLZHPA.js";import{a as Ot,e as jt,f as oe,g as _t,h
|
|
|
197
197
|
r.start_line, r.start_char, r.end_line, r.end_char
|
|
198
198
|
FROM incremental.defn_enclosing_ranges r
|
|
199
199
|
JOIN incremental.global_symbols source ON source.id = r.symbol_id
|
|
200
|
-
JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function
|
|
200
|
+
JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function Ic(e){e.exec(`
|
|
201
201
|
DELETE FROM main.global_symbols
|
|
202
202
|
WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
|
|
203
203
|
AND NOT EXISTS (
|
|
204
204
|
SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
|
|
205
205
|
);
|
|
206
|
-
`)}function
|
|
206
|
+
`)}function vc(e,t,n){let r=Z(e,"SELECT COUNT(*) AS value FROM main.documents"),i=Z(e,`SELECT COUNT(*) AS value
|
|
207
207
|
FROM main.documents d
|
|
208
|
-
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
|
|
208
|
+
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 Pc(e){let t=sn(e,"main",!0),n=sn(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 sn(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
|
|
209
209
|
FROM ${t}.documents d
|
|
210
210
|
${r}
|
|
211
211
|
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
|
|
@@ -227,12 +227,12 @@ import{a as X}from"./chunk-X3NLZHPA.js";import{a as Ot,e as jt,f as oe,g as _t,h
|
|
|
227
227
|
JOIN ${t}.documents d ON d.id = c.document_id
|
|
228
228
|
JOIN ${t}.global_symbols g ON g.id = m.symbol_id
|
|
229
229
|
${r}
|
|
230
|
-
ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,l]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let p of l){let
|
|
231
|
-
`);u.set(d,p.digest("hex"))}return u}function
|
|
232
|
-
`)}function
|
|
233
|
-
`;)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 tn(e){try{let t=ac(e,"utf-8"),n=JSON.parse(Sc(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as no,randomUUID as nu}from"crypto";import{constants as ru,copyFileSync as Ki,existsSync as H,lstatSync as iu,mkdirSync as J,mkdtempSync as ro,readdirSync as ou,readFileSync as z,realpathSync as au,renameSync as Z,rmSync as q,statSync as su}from"fs";import{dirname as io,join as h,resolve as Fe}from"path";import{setTimeout as cu}from"timers/promises";import{pathToFileURL as Zi}from"url";import{deserializeSCIP as oo}from"@c4312/scip";import uu from"better-sqlite3";import{createRequire as bc}from"module";var Rc=bc(import.meta.url),gi=xc().version;function xc(){for(let e of["../package.json","../../package.json"])try{return Rc(e)}catch{}return{version:"0.0.0"}}import{lstatSync as Mc,readdirSync as Lc}from"fs";import{join as Nc,relative as $c,resolve as ln,sep as Vc}from"path";import{createHash as Ic}from"crypto";import{existsSync as rn,mkdirSync as vc,readFileSync as Ye,readdirSync as Rg,renameSync as Pc,rmSync as xg,writeFileSync as wc}from"fs";import{join as ae}from"path";import{create as mi,fromBinary as hi,toBinary as kc}from"@bufbuild/protobuf";import{deserializeSCIP as Xe,DocumentSchema as on,IndexSchema as yi,serializeSCIP as Si}from"@c4312/scip";var Qe=1,xe="typescript-scip-fragments";function bi(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=Q(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=hi(on,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=Si(mi(yi,{documents:n,externalSymbols:[]})),i=Xe(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function Ke(e){let t=ae(e,xe);return{rootDir:t,blobDir:ae(t,"blobs"),generationDir:ae(t,"generations")}}function Ec(e){let t=Xe(e.indexBytes);Ai(t.metadata,Oi(e)),Di(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let a=Q(o.relativePath);if(n.has(a))throw new Error(`duplicate TypeScript SCIP document path: ${a}`);n.add(a);let s=kc(on,o),c=e.documentIdentities.get(a)??(e.allowUntrackedDocuments?K(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:a,contentHash:K(s)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${a}`);r.push(ki(e.cacheDir,{relativePath:a,bytes:s,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=Ei(e,r);return Ti(e.cacheDir,i),i}function Ri(e){let t=Ke(e.cacheDir);if(!rn(an(t,e.generationIdentity)))return Ec(e);let n=Ii({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 xi(e){let t=Ii({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=Q(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,ki(e.cacheDir,o,s))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=Ei(e,[...n.values()]);return Ti(e.cacheDir,i),i}function Ii(e){let t=Ke(e.cacheDir),n=an(t,e.generationIdentity),r;try{r=Fi(Ye(n,"utf8"))}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=ae(t.blobDir,`${o.blobHash}.scipdoc`),s=Ye(a);if(s.byteLength!==o.byteLength||K(s)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,s)}return{manifest:r,fragments:i}}function vi(e){let t=wi(e);return nn(t.baseIndex,t.completeDocuments,"assembled")}function Pi(e){let t=wi(e);return Tc(t.deletedAffectedPaths),{completeIndexBytes:nn(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:nn(t.baseIndex,t.affectedDocuments,"affected")}}function wi(e){let t=Xe(e.baseIndexBytes);Ai(t.metadata,Oi(e)),Di(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=Q(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=Q(s.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let u=n.get(c);if(!u){i.push(s);continue}if(n.delete(c),u.bytes===null){a.push(c);continue}let d=hi(on,u.bytes);if(d.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${d.relativePath}`);i.push(d),o.push(d)}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 nn(e,t,n){let r=Si(mi(yi,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=Xe(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function Tc(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function ki(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=Q(t.relativePath),i=Buffer.from(t.bytes),o=K(i),a=Ke(e);vc(a.blobDir,{recursive:!0});let s=ae(a.blobDir,`${o}.scipdoc`);if(rn(s)){let c=Ye(s);if(c.byteLength!==i.byteLength||K(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${s}.${process.pid}.${Date.now()}.tmp`;wc(c,i),Pc(c,s)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function Ei(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:Qe,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function Ti(e,t){let n=Ke(e),r=an(n,t.generationIdentity);if(rn(r)){let i=Fi(Ye(r,"utf8"));if(fi(i)!==fi(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}ie(r,t,{spacing:2,trailingNewline:!0})}function fi(e){return K(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function Fi(e){let t=JSON.parse(e);if(t.version!==Qe||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(Q(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function an(e,t){return ae(e.generationDir,Fc(t))}function Fc(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${K(e)}.json`}function Di(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function Ai(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 Oi(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function Q(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 K(e){return Ic("sha256").update(e).digest("hex")}import{createHash as Dc}from"crypto";import{existsSync as Ie,mkdirSync as Ac,readFileSync as Pe,readdirSync as sn,renameSync as Oc,rmSync as ji,writeFileSync as jc}from"fs";import{join as D}from"path";var Ze=1,Ci=64*1024*1024,we="typescript-scip-overlays";function Mi(e){let t=$i(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=dn(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript overlay: ${a}`);r.add(a),n.set(a,_c(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:Ze,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 Cc(e.cacheDir,i),i}function Li(e){let t=$i(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=Pe(D(ke(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||ve(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 vi({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function Ni(e,t){let n=ke(e),r=D(n,"generations");if(!Ie(r))return;let i=new Set(t.map(un)),o=new Set;for(let s of sn(r).filter(c=>i.has(c))){let c=cn(Pe(D(r,s),"utf8"));for(let u of c.overlays)u.blobHash&&o.add(`${u.blobHash}.scipdoc`)}for(let s of sn(r))i.has(s)||ji(D(r,s),{force:!0});let a=D(n,"blobs");if(Ie(a))for(let s of sn(a))o.has(s)||ji(D(a,s),{force:!0})}function $i(e,t){let n=D(ke(e),"generations",un(t));if(!Ie(n))return null;let r=cn(Pe(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function _c(e,t){let n=dn(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=ve(r),o=D(ke(e),"blobs");Ac(o,{recursive:!0});let a=D(o,`${i}.scipdoc`);if(Ie(a)){let s=Pe(a);if(s.byteLength!==r.byteLength||ve(s)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let s=`${a}.${process.pid}.${Date.now()}.tmp`;jc(s,r),Oc(s,a)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function Cc(e,t){let n=D(ke(e),"generations",un(t.generationIdentity));if(Ie(n)){let r=cn(Pe(n,"utf8"));if(_i(r)!==_i(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}ie(n,t,{spacing:2,trailingNewline:!0})}function cn(e){let t=JSON.parse(e);if(t.version!==Ze||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(dn(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function ke(e){return D(e,we)}function un(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${ve(e)}.json`}function _i(e){return ve(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function dn(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 ve(e){return Dc("sha256").update(e).digest("hex")}var Ee=1,pn="language-indexes",Vi=["index.db","index.scip","meta.json"],Gi=[pn,xe,we];function et(e){let t=[];for(let n of Vi)Gc(e,n),t.push(n);for(let n of Gi)Ui(e,n,t);return{version:Ee,files:t.sort()}}function tt(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(!Vi.includes(e)&&!Gi.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function O(e,t){let n=tt(t),r=ln(e),i=ln(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${Vc}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function Ui(e,t,n){let r=Nc(e,t),i;try{i=Lc(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()?Ui(e,a,n):o.isFile()&&n.push(tt(a))}}function Gc(e,t){let n=O(e,t),r;try{r=Mc(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($c(ln(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{createHash as yn}from"crypto";import{closeSync as Hi,chmodSync as Uc,copyFileSync as Bc,constants as Wc,existsSync as I,fsyncSync as qc,mkdirSync as Bi,openSync as zi,readFileSync as se,readSync as Hc,readdirSync as zc,renameSync as hn,rmSync as nt,statSync as rt}from"fs";import{basename as Ji,dirname as j,join as R,relative as Wi}from"path";function ot(e){let t=_(e.outputDb),n=Yc(e);e.onStage?.("after-recovery-retained");let r=e.preserveOutputScip?e.outputScip:e.tempOutputScip,i=Rn({generationRoot:t,databasePath:e.tempOutputDb,indexPath:I(r)?r:void 0,metadataPath:I(e.tempMetaPath)?e.tempMetaPath:void 0}),o=(e.now??(()=>new Date))().toISOString(),a={version:ee,currentGeneration:i.identity,artifactSet:"immutable-v1",...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:o};F(R(t,"state.json"),a,{spacing:2,trailingNewline:!0}),e.onStage?.("after-pointer-handoff"),e.preserveOutputScip||mn(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),mn(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),mn(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let s=i.identity,c={...a,stableMirrors:bn(e.outputDb,e.outputScip)};return F(R(t,"state.json"),c,{spacing:2,trailingNewline:!0}),{currentGeneration:s,...n?{previousGeneration:n}:{}}}function Sn(e,t,n,r=()=>new Date){if(!I(e))return null;let i=Ve(e),o=R(_(e),"state.json");if(i?.artifactSet==="immutable-v1"&&xt(e,i.currentGeneration))return i;let a=_(e),s=!i&&I(o)?Qc(n,e,t):void 0;if(s&&!It(a,s))return null;let c=Rn({generationRoot:a,databasePath:e,indexPath:I(t)?t:void 0,metadataPath:I(n)?n:void 0,forcedIdentity:i?.currentGeneration??s}),u={version:ee,currentGeneration:c.identity,artifactSet:"immutable-v1",stableMirrors:bn(e,t),...i?.previousGeneration?{previousGeneration:i.previousGeneration}:{},...i?.publication?{publication:i.publication}:{},publishedAt:i?.publishedAt??r().toISOString()};return F(R(a,"state.json"),u,{spacing:2,trailingNewline:!0}),u}function Yi(e,t,n=()=>new Date){if(!I(e)||!I(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=Ve(e),i=_(e),o=Rn({generationRoot:i,databasePath:e,indexPath:I(R(j(e),"index.scip"))?R(j(e),"index.scip"):void 0,metadataPath:t}),a=r&&r.currentGeneration!==o.identity?Xi(e,r.currentGeneration):void 0,s={version:ee,currentGeneration:o.identity,artifactSet:"immutable-v1",stableMirrors:bn(e,R(j(e),"index.scip")),...a?{previousGeneration:a}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return F(R(_(e),"state.json"),s,{spacing:2,trailingNewline:!0}),s}function W(e,t=R(j(e),"meta.json")){let n=R(_(e),"state.json");if(!I(n))return{state:"legacy",statePath:n};let r=Ve(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=xt(e,r.currentGeneration),o=i!==null,a=i?Jc(e,t,i,r):!1,s=r.previousGeneration?I(R(j(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 Jc(e,t,n,r){if(r.stableMirrors&&(r.stableMirrors.databaseFileIdentity!==pe(e)||r.stableMirrors.indexFileIdentity!==void 0&&r.stableMirrors.indexFileIdentity!==pe(R(j(e),"index.scip")))||!qi(e,n.database))return!1;let i=R(j(e),"index.scip");if(n.index&&!qi(i,n.index))return!1;if(!n.metadata)return!I(t);if(!I(t))return!1;let o=R(_(e),n.identity,n.metadata.file);return I(o)&&Y(se(t,"utf8"))===Y(se(o,"utf8"))}function qi(e,t){return I(e)&&rt(e).isFile()&&rt(e).size===t.size}function Yc(e){let t=Sn(e.outputDb,e.outputScip,e.metaPath);return t?Xi(e.outputDb,t.currentGeneration):void 0}function bn(e,t){return{databaseFileIdentity:pe(e),...I(t)?{indexFileIdentity:pe(t)}:{}}}function Xi(e,t){let n=R(_(e),t),r=R(n,Ji(e)),i=R(n,"meta.json");return{generationIdentity:t,databasePath:Wi(j(e),r),...I(i)?{metadataPath:Wi(j(e),i)}:{}}}function Xc(e){if(I(e))for(let t of zc(e,{withFileTypes:!0}))t.isDirectory()&&t.name.endsWith(".tmp")&&nt(R(e,t.name),{recursive:!0,force:!0})}function Qc(e,t,n=R(j(t),"index.scip")){let r=yn("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(it(t)),I(n)&&r.update(`\0${it(n)}`),I(e)&&r.update(`\0${Y(se(e,"utf8"))}`),r.digest("hex")}function Rn(e){let t=gn(e.databasePath),n=e.indexPath?gn(e.indexPath):void 0,r=e.metadataPath?gn(e.metadataPath):void 0,i=e.forcedIdentity??Kc(t,n,e.metadataPath),o=R(e.generationRoot,i),a=R(o,Rt);if(I(a)){let c=It(e.generationRoot,i);if(c&&Qi(o,c.database,t)&&eu(o,c.index,n)&&tu(o,c.metadata,e.metadataPath))return{identity:i};throw new Error(`SQLite generation ${i} already exists with different or corrupt artifacts.`)}Bi(e.generationRoot,{recursive:!0}),Xc(e.generationRoot);let s=`${o}.${process.pid}.${Date.now()}.tmp`;nt(s,{recursive:!0,force:!0}),Bi(s,{recursive:!0});try{fn(e.databasePath,R(s,t.file)),n&&e.indexPath&&fn(e.indexPath,R(s,n.file)),r&&e.metadataPath&&fn(e.metadataPath,R(s,r.file)),F(R(s,Rt),{version:Zn,identity:i,database:t,...n?{index:n}:{},...r?{metadata:r}:{}},{spacing:2,trailingNewline:!0}),hn(s,o),ir(e.generationRoot)}finally{nt(s,{recursive:!0,force:!0})}return{identity:i}}function Kc(e,t,n){let r=yn("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(e.sha256),t&&r.update(`\0${t.sha256}`),n&&r.update(`\0${Y(se(n,"utf8"))}`),r.digest("hex")}function gn(e){return{file:Ji(e),size:rt(e).size,sha256:it(e)}}function it(e){let t=yn("sha256"),n=zi(e,"r"),r=Buffer.allocUnsafe(1024*1024);try{for(;;){let i=Zc(n,r);if(i===0)break;t.update(r.subarray(0,i))}}finally{Hi(n)}return t.digest("hex")}function Zc(e,t){let n=0;for(;n<t.length;){let r=Hc(e,t,n,t.length-n,null);if(n+=r,r===0)break}return n}function fn(e,t){Bc(e,t,Wc.COPYFILE_FICLONE);let n=zi(t,"r");try{qc(n)}finally{Hi(n)}Uc(t,292)}function Qi(e,t,n){let r=R(e,t.file);return t.file===n.file&&t.size===n.size&&t.sha256===n.sha256&&I(r)&&rt(r).size===t.size&&it(r)===t.sha256}function eu(e,t,n){return!t||!n?t===n:Qi(e,t,n)}function tu(e,t,n){if(!t||!n)return t===void 0&&n===void 0;let r=R(e,t.file);return I(r)&&Y(se(r,"utf8"))===Y(se(n,"utf8"))}function mn(e,t){nt(`${t}.tmp-replace`,{force:!0}),hn(e,`${t}.tmp-replace`),hn(`${t}.tmp-replace`,t)}var In=1,eo="SCIP_QUERY_SHARED_CACHE",xn=JSON.stringify({cliVersion:gi,artifactCatalogVersion:Ee,sqliteGenerationStoreVersion:ee,typescriptFragmentStoreVersion:Qe,typescriptOverlayStoreVersion:Ze}),ao="manifest.json",du="shared-cache.json",vn=[pn,xe,we];function at(e,t){if(!e.clean||!e.treeOid)return;let n=Ae(JSON.stringify({version:In,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:xn}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:xn,generationId:n,repositoryCacheDir:br(e.repositoryId)}}function so(e,t,n){if(process.env[eo]==="0")return`${eo}=0`;if(!Rr(n))return"explicit cache or database override";if(Fe(t)!==Fe(h(Sr(e),"index.db")))return"index database is outside the managed worktree cache"}function M(e,t=!0){let n=wn(e),r;try{r=pu(z(h(n,ao),"utf8"))}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=O(n,i.path),a=su(o);if(!a.isFile()||a.size!==i.size||Ae(z(o))!==i.sha256)return null}}catch{return null}return r}function co(e){let t=M(e.snapshot);if(t)return t;if(!po(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=to(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=et(e.sourceCacheDir),i=h(e.snapshot.repositoryCacheDir,"generations");J(i,{recursive:!0});let o=ro(h(i,`.tmp-${process.pid}-`));try{let a=[];for(let l of r.files){let p=O(e.sourceCacheDir,l),f=O(o,l);De(p,f);let g=z(f);a.push({path:l,size:g.byteLength,sha256:Ae(g)})}let s=oo(z(h(o,"index.scip"))).metadata?.projectRoot;if(!s)throw new Error("shared SCIP generation has no project root metadata");let c=kn(e.sourceProjectRoot);if(s!==c)throw new Error("shared SCIP generation root does not match its source worktree");if(to(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let u={version:In,artifactCatalogVersion:Ee,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:s,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:a.sort((l,p)=>l.path.localeCompare(p.path))};F(h(o,ao),u,{spacing:2,trailingNewline:!0});let d=wn(e.snapshot);try{if(H(d)&&!M(e.snapshot)){let l=`${d}.corrupt-${process.pid}-${Date.now()}`;Z(d,l),q(l,{recursive:!0,force:!0})}Z(o,d)}catch(l){let p=M(e.snapshot);if(p)return p;throw l}return u}finally{q(o,{recursive:!0,force:!0})}}function Pn(e){let t=wn(e.snapshot);J(e.targetCacheDir,{recursive:!0});let n=be(h(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=ro(h(e.targetCacheDir,".shared-hydrate-")),bu(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let u=O(t,c.path),d=O(r,c.path);De(u,d);let l=z(d);if(l.byteLength!==c.size||Ae(l)!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=kn(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&qr(O(r,c.path),e.manifest.scipProjectRoot,a);if(!po(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=hu(e.targetCacheDir,r),o=!0,yu(r,e.targetCacheDir,i),ot({tempOutputScip:h(r,"index.scip"),tempOutputDb:h(r,"index.db"),tempMetaPath:h(r,"meta.json"),outputScip:h(e.targetCacheDir,"index.scip"),outputDb:h(e.targetCacheDir,"index.db"),metaPath:h(e.targetCacheDir,"meta.json"),now:e.now});let s=W(h(e.targetCacheDir,"index.db"),h(e.targetCacheDir,"meta.json"));if(s.state==="invalid"||s.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${s.reason}`);st(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&Su(e.targetCacheDir,i),a}finally{r&&q(r,{recursive:!0,force:!0}),n.release()}}async function uo(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??y,o=i()+n,a=h(e.repositoryCacheDir,"locks"),s=h(a,`${e.generationId}.lock`),c=u=>{if(!u||typeof u!="object"||Array.isArray(u))return null;let d=u.pid;return typeof d=="number"&&Number.isSafeInteger(d)&&d>0?{pid:d}:null};for(;i()<=o;){if(M(e))return{kind:"generation-ready"};let u=oe(s,{kind:"shared-generation-build",detail:{generationId:e.generationId},parseLegacy:c});if(u.kind==="acquired")return{kind:"owner",release:()=>u.lock.release()};let d=o-i();if(d<=0)break;await cu(Math.min(r,d))}return M(e)?{kind:"generation-ready"}:{kind:"timeout"}}function st(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:lu(i)};return mu(e.repositoryCacheDir,o,!0),o}function lu(e){return Ae(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:Fe(e.projectRoot),localCacheDir:Fe(e.localCacheDir)}))}function pu(e){let t=JSON.parse(e);if(t.version!==In||t.artifactCatalogVersion!==Ee||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!==xn||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(tt(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 De(e,t){J(io(t),{recursive:!0});try{Ki(e,t,ru.COPYFILE_FICLONE)}catch{Ki(e,t)}}function gu(e,t,n){J(e,{recursive:!0}),F(h(e,du),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function to(e){try{let t=et(e),n=no("sha256");for(let r of t.files){let i=z(O(e,r));n.update(r).update("\0").update(String(i.byteLength)).update("\0").update(i).update("\0")}return n.digest("hex")}catch{return null}}function fu(e){try{let t=G(z(h(e,"meta.json"),"utf8"));return(t.kind==="legacy"||t.kind==="supported")&&t.capabilities.publishableGeneration?t.metadata:void 0}catch{return}}function wn(e){return h(e.repositoryCacheDir,"generations",e.generationId)}function mu(e,t,n){let r=Pr(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!H(h(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=h(e,"worktrees");J(i,{recursive:!0}),F(h(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),gu(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function hu(e,t){let n=h(t,".rollback"),r=new Map,i=new Map;J(n,{recursive:!0});for(let s of["index.scip","index.db","meta.json"]){let c=h(e,s),u=H(c);r.set(s,u),u&&De(c,h(n,"stable",s))}for(let s of vn){let c=h(e,s),u=H(c);if(u){let d=iu(c);if(!d.isDirectory()||d.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${s}`)}i.set(s,u)}let o=h(e,$e),a=H(o);return a&&lo(o,h(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:a}}function yu(e,t,n){for(let r of vn){let i=h(t,r);if(n.managedDirectories.get(r)){let a=h(n.root,"managed",r);J(io(a),{recursive:!0}),Z(i,a)}let o=h(e,r);H(o)&&Z(o,i)}}function Su(e,t){for(let i of vn){let o=h(e,i),a=h(t.root,"managed",i);t.managedDirectories.get(i)?H(a)&&(q(o,{recursive:!0,force:!0}),Z(a,o)):q(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let a=h(e,i);if(!o){q(a,{force:!0});continue}let s=`${a}.shared-restore-${nu()}`;De(h(t.root,"stable",i),s),q(a,{force:!0}),Z(s,a)}let n=h(e,$e);q(n,{recursive:!0,force:!0});let r=h(t.root,"sqlite-generations");t.generationStoreExisted&&H(r)&&Z(r,n)}function lo(e,t){J(t,{recursive:!0});for(let n of ou(e,{withFileTypes:!0})){let r=h(e,n.name),i=h(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?lo(r,i):n.isFile()&&De(r,i)}}function bu(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 po(e,t,n,r=!0,i=!0){try{let o=fu(e);if(!o||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return Te("source validation rejected metadata"),!1;let a=et(e),s=W(h(e,"index.db"),h(e,"meta.json"));if(r?s.state!=="current":s.state==="invalid"||s.state==="drifted")return Te(`source validation rejected SQLite generation state ${s.state}`),!1;let c=new uu(h(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 u=kn(t),l=(i?a.files.filter(p=>p.endsWith(".scip")):["index.scip"]).every(p=>{let f=oo(z(O(e,p))).metadata?.projectRoot;return f!==u&&Te(`source validation rejected SCIP root for ${p}: ${String(f)}`),f===u});return l||Te("source validation rejected SCIP project roots"),l}catch(o){return Te(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function Te(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function kn(e){try{return Zi(au(e)).href}catch{return Zi(Fe(e)).href}}function Ae(e){return no("sha256").update(e).digest("hex")}import{existsSync as Ru,readFileSync as xu,readdirSync as Iu,statSync as vu}from"fs";import E from"path";var Pu=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function Oe(e,t=[]){let n=E.resolve(e),r=t.flatMap(c=>ku(n,c));if(r.length>0)return go(n,fo(r));let i=wu(n),o=fo(i),a=Tu(n,o)?[n,...o]:o,s=a.length>0?a:[n];return go(n,s)}function go(e,t){return[...new Set(t.map(n=>Du(e,n)))].sort((n,r)=>n.localeCompare(r))}function wu(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=Iu(r,{withFileTypes:!0})}catch{continue}for(let o of i){let a=E.join(r,o.name);if(o.isDirectory()){!Pu.has(o.name)&&!o.name.startsWith(".")&&n.push(a);continue}o.isFile()&&Eu(a)&&t.push(E.dirname(a))}}return t}function ku(e,t){let n=t.trim();if(!n)return[];let r=E.resolve(e,n);if(!ge(e,r))return[];try{let i=vu(r);if(i.isDirectory())return[r];if(i.isFile()&&mo(E.basename(r)))return[E.dirname(r)]}catch{return[]}return[]}function Eu(e){if(!mo(E.basename(e)))return!1;let t=ho(e);return t?E.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function mo(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function fo(e){let t=[...new Set(e.map(n=>E.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&Au(n,r)))}function Tu(e,t){if(t.length===0||t.some(r=>E.resolve(r)===e))return!1;let n=E.join(e,"tsconfig.json");return Ru(n)&&Fu(n)}function Fu(e){let n=ho(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!E.extname(r))):!1}function ho(e){try{let t=JSON.parse(xu(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Du(e,t){let n=E.relative(e,t);return n?n.split(E.sep).join("/"):"."}function Au(e,t){let n=E.relative(e,t);return!!n&&!n.startsWith("..")&&!E.isAbsolute(n)}import{createHash as Ku}from"crypto";import{existsSync as Tn,readFileSync as Eo,statSync as Zu,writeFileSync as Fn}from"fs";import{join as ed}from"path";import{readFileSync as yo}from"fs";import{createRequire as Ou}from"module";import{dirname as ju,isAbsolute as bf,relative as Rf,resolve as xf,sep as If}from"path";var So=Ou(import.meta.url),_u=1,bo="0.4.0";function En(){let e=Cu();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Cu(){try{let e=So.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(yo(e,"utf8"));if(t.version!==bo)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${bo}`};let n=ju(e),r=So.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(yo(r,"utf8"));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:Mu(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Mu(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${_u}`}import{createHash as Lu}from"crypto";import{readFileSync as Nu}from"fs";import{dirname as $u,join as Ro}from"path";var ct=3;var Vu="typescript-index";function xo(e){let t=Ro(e,Vu),n=or(t);return{...n,requestDir:n.legacyRequestDir}}function Io(e){try{let t=Kn(G(Nu(Ro($u(e),"meta.json"),"utf8")));return t?Lu("sha256").update(t).digest("hex"):null}catch{return null}}import{randomUUID as Gu}from"crypto";import{existsSync as Uu,readFileSync as Bu}from"fs";var Wu=12e4,qu=5,ut=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;constructor(t,n={}){this.projectRoot=dr(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Xu(),this.runtime=n.runtime??Qu,this.mailboxLimits=n.mailboxLimits??{}}request(t){let n=ur(this.cacheDir),r=xo(this.cacheDir),i=Dt(n.statePath);if(!vo(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??y)()+this.timeoutMs,c=Tt("typescript-index-v3",{baseGeneration:this.baseGeneration,request:t}),u=Ft(c),d=ar(r,{mailboxVersion:Et,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:a,protocolVersion:ct,id:u,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??y)()<=s;){if(Uu(d.responsePath))return Hu(Bu(d.responsePath,"utf8"),u,c,this.baseGeneration,t.producerIdentity,t.affectedFiles);let l=Dt(n.statePath);if(!vo(l,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(qu)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}};function vo(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===ct&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&Se(e.processIdentity,r))}function Hu(e,t,n,r,i,o){let a=JSON.parse(e);if(a.protocolVersion!==ct||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=zu(a.response,i),c=[...new Set(o)].sort(),u=s.fragments.map(d=>d.relativePath).sort();if(JSON.stringify(u)!==JSON.stringify(c))throw new Error("TypeScript index service omitted or added an affected document.");return s}function zu(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(Ju)||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 Ju(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 Xu(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Wu}var Qu={now:Date.now,monotonicNow:y,randomId:Gu,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:ne,readProcessIdentity:re};function td(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=Ne(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"||!At(u.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=He(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=nd([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=Po(e.currentSnapshot,e.projectFiles,e.producerIdentity),a=Po(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==a)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let s=ko(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!s)return{eligible:!1,reason:"prior document identity unavailable"};let c=ko(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:wo(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:wo(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:s,nextDocumentIdentities:c,tsconfigPath:i==="."?"tsconfig.json":`${i}/tsconfig.json`,projectArgument:i}:{eligible:!1,reason:"next document identity unavailable"}}function nd(e,t){let n=null;for(let r of e){let i=t.filter(o=>o==="."||r===o||r.startsWith(`${o}/`));if(i.length!==1||n!==null&&n!==i[0])return null;n=i[0]}return n}function To(e){let t=y();try{if(!Tn(e.previousDbPath)||!Tn(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=En();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new X({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a,s;try{a=Ge(o,{includeIgnored:!1}).filter(At).sort(),s=Ue(o)}finally{o.close()}let c=performance.now()-n,u=td({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?Oe(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:a,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:Tn(ed(e.projectRoot,"tsconfig.json"))});if(!u.eligible)throw new Error(u.reason);let d=Io(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let p=new ut({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:d}).request({kind:"emit-documents",tsconfigPath:u.tsconfigPath,projectArgument:u.projectArgument,projectIdentity:u.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles}),f=performance.now()-n,g=Zu(e.previousShardPath).size>=Ci;n=performance.now();let m=g?null:Eo(e.previousShardPath),b=g?{completeIndexBytes:null,affectedIndexBytes:bi(p.fragments)}:Pi({packageVersion:r.packageVersion,baseIndexBytes:m,fragments:p.fragments}),P=performance.now()-n;n=performance.now(),g?Mi({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,nextGenerationIdentity:u.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:p.fragments}):(Ri({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:m,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.previousFragmentGeneration,documentIdentities:u.previousDocumentIdentities,allowUntrackedDocuments:!0}),xi({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.nextFragmentGeneration,fragments:p.fragments,documentIdentities:u.nextDocumentIdentities}));let x=performance.now()-n;n=performance.now(),b.completeIndexBytes&&Fn(e.candidateShardPath,b.completeIndexBytes),Fn(e.candidateAffectedScipPath,b.affectedIndexBytes);let v=performance.now()-n,w={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:y()-t,cold:p.cold,changedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:u.previousFragmentGeneration,nextFragmentGeneration:u.nextFragmentGeneration,manifest:u.manifest,plan:u.plan,projectFileCount:a.length,referenceFragmentsByFile:new Map(p.fragments.map(V=>[V.relativePath,V.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:f,serviceMs:p.durationMs,assemblyMs:P,fragmentStoreMs:x,writeMs:v}};return e.onStatus(`Incremental TypeScript index emitted ${w.affectedFiles.length} affected document(s) in ${(w.durationMs/1e3).toFixed(3)}s (${w.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${f.toFixed(0)}ms, assembly ${P.toFixed(0)}ms, fragments ${x.toFixed(0)}ms, write ${v.toFixed(0)}ms).`),w}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 Fo(e){let t=En();if(!t.available)throw new Error(t.reason);let n=Li({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:Eo(e.baseShardPath),packageVersion:t.packageVersion});Fn(e.candidateShardPath,n)}function Po(e,t,n){let r=e.files.filter(i=>Xn(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 Dn(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function wo(e,t){return Dn(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function ko(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),a=lr({projectFiles:t.filter(c=>o.has(c)),snapshot:e,graph:n,engineIdentity:r}),s=new Map;for(let c of i){let u=a.identityFor(c,"typescript-scip-document-v1");if(u.key){s.set(c,u.key);continue}if(o.has(c))return null;s.set(c,Dn(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function Dn(e){return Ku("sha256").update(e).digest("hex")}import{existsSync as dt,renameSync as On,rmSync as jn,statSync as rd}from"fs";import{cpus as id}from"os";import{join as Ao}from"path";function od(e,t,n){if(!e.defaultOutputPath)return;let r=Ao(t,e.defaultOutputPath);n!==r&&dt(r)&&On(r,n)}function ad(e,t,n){if(!e.defaultOutputPath)return null;let r=Ao(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return jn(i,{force:!0}),dt(r)?(On(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function sd(e){e&&(jn(e.defaultOutputPath,{force:!0}),e.backupPath&&dt(e.backupPath)&&On(e.backupPath,e.defaultOutputPath))}function cd(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,id().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Oo(e,t,n,r){let i=e.filter(u=>u.config.defaultOutputPath),o=e.filter(u=>!u.config.defaultOutputPath),a=[],s=cd(o.length,r),c=await ld(o,s,u=>An(u,t,n));if(s>1){let u=new Map;for(let d of c.filter(l=>l.result.skipped&&l.retryable)){let l=o.find(p=>p.id===d.result.id);l&&(n(`Retrying ${l.label} indexer serially after parallel failure...`),u.set(l.id,(await An(l,t,n)).result))}a.push(...c.map(({result:d})=>u.get(d.id)??d))}else a.push(...c.map(({result:u})=>u));for(let u of i)a.push((await An(u,t,n)).result);return a.sort((u,d)=>e.findIndex(l=>l.id===u.id)-e.findIndex(l=>l.id===d.id))}async function An(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),jn(e.scipPath,{force:!0});let r=ad(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=y();try{let s=nr(e.binary,e.args),c=await vr({command:s.binary,args:s.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:ud(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024});if(c.status!==0){let u=c.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${c.status}${u?`:
|
|
234
|
-
${u}`:""}`)}
|
|
235
|
-
`)[0]}`,d=e.label===e.language?u:`${e.label}: ${u}`;return n(`Skipping ${e.label}: ${u}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:
|
|
230
|
+
ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,l]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let p of l){let m=JSON.stringify([d,p]),g=c.get(p.relative_path)??[];g.push(m),c.set(p.relative_path,g)}let u=new Map;for(let[d,l]of[...c].sort(([p],[m])=>p.localeCompare(m))){let p=cc("sha256");for(let m of l.sort())p.update(m).update(`
|
|
231
|
+
`);u.set(d,p.digest("hex"))}return u}function Z(e,t){return e.prepare(t).get().value}import wc from"better-sqlite3";var ot="idx_mentions_definitions",kc=["symbol_id","chunk_id"];function cn(e){let t=new wc(e),n=[],r=[],i=[];try{return t.transaction(()=>{Ec(t,n),at(t,"idx_global_symbols_symbol")?.join("\0")==="symbol"&&Pi(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")):at(t,"idx_global_symbols_symbol")&&i.push("idx_global_symbols_symbol");let o=at(t,"idx_chunks_doc_id"),a=Pi(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 Ec(e,t){let n=wi(e,ot);if(n){let r=n.columns.join("\0")===kc.join("\0"),i=/\bWHERE\s+role\s*=\s*1\b/iu.test(n.sql??"");if(!r||!i||n.table!=="mentions")throw new Error(`${ot} exists with an incompatible definition`);return}e.exec(`CREATE INDEX "${ot}" ON mentions(symbol_id, chunk_id) WHERE role = 1`),t.push(ot)}function Pi(e,t){return e.prepare(`PRAGMA index_list('${t.replaceAll("'","''")}')`).all().map(n=>({name:n.name,unique:n.unique===1,columns:at(e,n.name)??[]}))}function at(e,t){return wi(e,t)?.columns??null}function wi(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 Tc}from"fs";function q(e,t){let n=performance.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}function Ei(e){let t=e.readFingerprint(),n=Di(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return Fi(e.cachePath,e.readFingerprint(),r),r}async function Ti(e){let t=e.readFingerprint(),n=Di(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=await e.compute();return Fi(e.cachePath,e.readFingerprint(),r),r}function Di(e,t){try{let n=JSON.parse(v(e,{maxBytes:A,inputKind:"post-index augmentation cache"}));return ki(n.fingerprint)===ki(t)?{result:n.result}:null}catch{return null}}function Fi(e,t,n){Tc(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
|
|
232
|
+
`)}function ki(e){return JSON.stringify(e)}import{createHash as Dc}from"crypto";import{existsSync as un,readdirSync as Fc}from"fs";import{dirname as dn,join as st,relative as Ac,resolve as ln,sep as Ai}from"path";function _i(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=ji(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Li(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=ji(s,e);c&&c!==i&&a.add(c)}}return _c(e,r)}function Oi(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 pn(e){if(e===".")return"root";let t=Dc("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Ci(e,t){let n=ln(e),r={};for(let i of t)r[i]=Lc(n,i);return r}function ji(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 _c(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 Lc(e,t){let n=t==="."?e:st(e,t),r=Oc(n),i=Cc(n),o=i?jc(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 Oc(e){let t=st(e,"package.json");if(!un(t))return{name:void 0,dependencyNames:[],failed:!1};let n=gn(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 Cc(e){let t=st(e,"tsconfig.json");if(un(t))return t;let n;try{n=Fc(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?st(e,n[0]):void 0}function jc(e,t){let n=gn(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=Mc(n.value,e,t),i=Mi(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function Mc(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=dn(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=Ni(s,i,n);c&&o.add(c)}return[...o]}function Mi(e,t,n,r){let i=Nc(t);if(i)return{pathsTargets:Gc(i,dn(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=$c(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=gn(o);return a.ok?Mi(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function Nc(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 Gc(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=Ni(o,t,n);a&&r.add(a)}return[...r]}function $c(e,t,n){let r=Array.isArray(e)?e.at(-1):e;if(typeof r!="string"||r.trim()===""||!r.startsWith(".")&&!r.startsWith("/"))return;let i=ln(dn(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Ai).includes("node_modules")&&be(n,i)&&un(i))return i}function Ni(e,t,n){let r=e.replace(/\/?\*+$/,""),i=ln(t,r===""?".":r);if(!be(n,i))return;let a=Ac(n,i).split(Ai).join("/");return a===""?".":a}function Vc(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]!==`
|
|
233
|
+
`;)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 gn(e){try{let t=v(e,{maxBytes:A,inputKind:"TypeScript project manifest"}),n=JSON.parse(Vc(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as To,randomUUID as vu}from"crypto";import{existsSync as ne,lstatSync as Pu,mkdirSync as me,mkdtempSync as Do,readdirSync as wu,realpathSync as ku,renameSync as ce,rmSync as te,statSync as ht}from"fs";import{dirname as Ln,join as h,resolve as On}from"path";import{setTimeout as Eu}from"timers/promises";import{pathToFileURL as Po}from"url";import{deserializeSCIP as Fo}from"@c4312/scip";import Tu from"better-sqlite3";import{lstatSync as nu,readdirSync as ru}from"fs";import{join as iu,relative as ou,resolve as In,sep as au}from"path";import{createHash as Bc}from"crypto";import{existsSync as mn,mkdirSync as qc,readdirSync as Cg,renameSync as Uc,rmSync as jg,writeFileSync as Wc}from"fs";import{join as ge}from"path";import{create as $i,fromBinary as Vi,toBinary as Hc}from"@bufbuild/protobuf";import{deserializeSCIP as ct,DocumentSchema as hn,IndexSchema as Bi,serializeSCIP as qi}from"@c4312/scip";var ut=1,De="typescript-scip-fragments";function Ui(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=ae(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=Vi(hn,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=qi($i(Bi,{documents:n,externalSymbols:[]})),i=ct(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function dt(e){let t=ge(e,De);return{rootDir:t,blobDir:ge(t,"blobs"),generationDir:ge(t,"generations")}}function zc(e){let t=ct(e.indexBytes);no(t.metadata,ro(e)),to(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let a=ae(o.relativePath);if(n.has(a))throw new Error(`duplicate TypeScript SCIP document path: ${a}`);n.add(a);let s=Hc(hn,o),c=e.documentIdentities.get(a)??(e.allowUntrackedDocuments?se(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:a,contentHash:se(s)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${a}`);r.push(Xi(e.cacheDir,{relativePath:a,bytes:s,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=Qi(e,r);return Zi(e.cacheDir,i),i}function Wi(e){let t=dt(e.cacheDir);if(!mn(yn(t,e.generationIdentity)))return zc(e);let n=zi({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 Hi(e){let t=zi({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=ae(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,Xi(e.cacheDir,o,s))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=Qi(e,[...n.values()]);return Zi(e.cacheDir,i),i}function zi(e){let t=dt(e.cacheDir),n=yn(t,e.generationIdentity),r;try{r=eo(v(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=ge(t.blobDir,`${o.blobHash}.scipdoc`),s=w(a,{maxBytes:B,inputKind:"TypeScript fragment blob"});if(s.byteLength!==o.byteLength||se(s)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,s)}return{manifest:r,fragments:i}}function Ji(e){let t=Ki(e);return fn(t.baseIndex,t.completeDocuments,"assembled")}function Yi(e){let t=Ki(e);return Jc(t.deletedAffectedPaths),{completeIndexBytes:fn(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:fn(t.baseIndex,t.affectedDocuments,"affected")}}function Ki(e){let t=ct(e.baseIndexBytes);no(t.metadata,ro(e)),to(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=ae(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=ae(s.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let u=n.get(c);if(!u){i.push(s);continue}if(n.delete(c),u.bytes===null){a.push(c);continue}let d=Vi(hn,u.bytes);if(d.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${d.relativePath}`);i.push(d),o.push(d)}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 fn(e,t,n){let r=qi($i(Bi,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=ct(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function Jc(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function Xi(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=ae(t.relativePath),i=Buffer.from(t.bytes),o=se(i),a=dt(e);qc(a.blobDir,{recursive:!0});let s=ge(a.blobDir,`${o}.scipdoc`);if(mn(s)){let c=w(s,{maxBytes:B,inputKind:"TypeScript fragment blob"});if(c.byteLength!==i.byteLength||se(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${s}.${process.pid}.${Date.now()}.tmp`;Wc(c,i),Uc(c,s)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function Qi(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:ut,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function Zi(e,t){let n=dt(e),r=yn(n,t.generationIdentity);if(mn(r)){let i=eo(v(r,{maxBytes:A,inputKind:"TypeScript fragment manifest"}));if(Gi(i)!==Gi(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}X(r,t,{spacing:2,trailingNewline:!0})}function Gi(e){return se(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function eo(e){let t=JSON.parse(e);if(t.version!==ut||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(ae(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function yn(e,t){return ge(e.generationDir,Yc(t))}function Yc(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${se(e)}.json`}function to(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function no(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 ro(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function ae(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 se(e){return Bc("sha256").update(e).digest("hex")}import{createHash as Kc}from"crypto";import{existsSync as Fe,mkdirSync as Xc,readdirSync as Sn,renameSync as Qc,rmSync as io,writeFileSync as Zc}from"fs";import{join as N}from"path";var lt=1,ao=64*1024*1024,_e="typescript-scip-overlays";function so(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=xn(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript overlay: ${a}`);r.add(a),n.set(a,eu(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:lt,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 tu(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=w(N(Le(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`),{maxBytes:B,inputKind:"TypeScript overlay blob"});if(i.byteLength!==r.byteLength||Ae(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 Ji({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function uo(e,t){let n=Le(e),r=N(n,"generations");if(!Fe(r))return;let i=new Set(t.map(Rn)),o=new Set;for(let s of Sn(r).filter(c=>i.has(c))){let c=bn(v(N(r,s),{maxBytes:A,inputKind:"TypeScript overlay manifest"}));for(let u of c.overlays)u.blobHash&&o.add(`${u.blobHash}.scipdoc`)}for(let s of Sn(r))i.has(s)||io(N(r,s),{force:!0});let a=N(n,"blobs");if(Fe(a))for(let s of Sn(a))o.has(s)||io(N(a,s),{force:!0})}function lo(e,t){let n=N(Le(e),"generations",Rn(t));if(!Fe(n))return null;let r=bn(v(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 eu(e,t){let n=xn(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=Ae(r),o=N(Le(e),"blobs");Xc(o,{recursive:!0});let a=N(o,`${i}.scipdoc`);if(Fe(a)){let s=w(a,{maxBytes:B,inputKind:"TypeScript overlay blob"});if(s.byteLength!==r.byteLength||Ae(s)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let s=`${a}.${process.pid}.${Date.now()}.tmp`;Zc(s,r),Qc(s,a)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function tu(e,t){let n=N(Le(e),"generations",Rn(t.generationIdentity));if(Fe(n)){let r=bn(v(n,{maxBytes:A,inputKind:"TypeScript overlay manifest"}));if(oo(r)!==oo(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}X(n,t,{spacing:2,trailingNewline:!0})}function bn(e){let t=JSON.parse(e);if(t.version!==lt||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(xn(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function Le(e){return N(e,_e)}function Rn(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${Ae(e)}.json`}function oo(e){return Ae(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function xn(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 Ae(e){return Kc("sha256").update(e).digest("hex")}var Oe=1,vn="language-indexes",po=["index.db","index.scip","meta.json"],go=[vn,De,_e];function pt(e){let t=[];for(let n of po)su(e,n),t.push(n);for(let n of go)fo(e,n,t);return{version:Oe,files:t.sort()}}function gt(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(!po.includes(e)&&!go.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function $(e,t){let n=gt(t),r=In(e),i=In(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${au}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function fo(e,t,n){let r=iu(e,t),i;try{i=ru(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()?fo(e,a,n):o.isFile()&&n.push(gt(a))}}function su(e,t){let n=$(e,t),r;try{r=nu(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(ou(In(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{createHash as Tn}from"crypto";import{closeSync as cu,existsSync as I,mkdirSync as uu,openSync as du,readSync as lu,readdirSync as Dn,renameSync as En,rmSync as Ce,statSync as fe}from"fs";import{basename as So,dirname as V,join as S,relative as mo}from"path";var pu=Object.freeze({maxGenerations:8,maxLogicalBytes:2*1024*1024*1024});function mt(e){let t=M(e.outputDb),n=hu(e);e.onStage?.("after-recovery-retained");let r=e.preserveOutputScip?e.outputScip:e.tempOutputScip,i=_n({generationRoot:t,databasePath:e.tempOutputDb,indexPath:I(r)?r:void 0,metadataPath:I(e.tempMetaPath)?e.tempMetaPath:void 0}),o=(e.now??(()=>new Date))().toISOString(),a={version:de,currentGeneration:i.identity,artifactSet:"immutable-v1",...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:o},s=j(S(t,"state.json"),a,{spacing:2,trailingNewline:!0});e.onStage?.("after-pointer-handoff"),e.preserveOutputScip||kn(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),kn(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),kn(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let c=i.identity,u={...a,stableMirrors:An(e.outputDb,e.outputScip)};j(S(t,"state.json"),u,{spacing:2,trailingNewline:!0});let d=Ro(e.outputDb,{now:e.now}),l=Ie(i.directorySync,s.directorySync);return{currentGeneration:c,...n?{previousGeneration:n}:{},retention:d,achievedDurability:l==="synced"?"directory-durable":"file-flushed",directorySync:l}}function Fn(e,t,n,r=()=>new Date){if(!I(e))return null;let i=ve(e),o=S(M(e),"state.json");if(i?.artifactSet==="immutable-v1"&&Lt(e,i.currentGeneration))return i;let a=M(e),s=!i&&I(o)?Su(n,e,t):void 0;if(s&&!Ke(a,s))return null;let c=_n({generationRoot:a,databasePath:e,indexPath:I(t)?t:void 0,metadataPath:I(n)?n:void 0,forcedIdentity:i?.currentGeneration??s}),u={version:de,currentGeneration:c.identity,artifactSet:"immutable-v1",stableMirrors:An(e,t),...i?.previousGeneration?{previousGeneration:i.previousGeneration}:{},...i?.publication?{publication:i.publication}:{},publishedAt:i?.publishedAt??r().toISOString()};return j(S(a,"state.json"),u,{spacing:2,trailingNewline:!0}),u}function bo(e,t,n=()=>new Date){if(!I(e)||!I(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=ve(e),i=M(e),o=_n({generationRoot:i,databasePath:e,indexPath:I(S(V(e),"index.scip"))?S(V(e),"index.scip"):void 0,metadataPath:t}),a=r&&r.currentGeneration!==o.identity?Io(e,r.currentGeneration):void 0,s={version:de,currentGeneration:o.identity,artifactSet:"immutable-v1",stableMirrors:An(e,S(V(e),"index.scip")),...a?{previousGeneration:a}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return j(S(M(e),"state.json"),s,{spacing:2,trailingNewline:!0}),Ro(e,{now:n}),s}function Ro(e,t={}){let n=gu(t.limits),i=(t.now??(()=>new Date))().toISOString(),o=ue(Rr(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=ve(e),s=fu(e),c=xr(e,s.map(y=>y.identity),{isProcessAlive:t.isProcessAlive??Y,readProcessIdentity:t.readProcessIdentity??J}),u=new Set(c.protectedGenerations);a?.currentGeneration&&u.add(a.currentGeneration),a?.previousGeneration?.generationIdentity&&u.add(a.previousGeneration.generationIdentity);let d=s.length,l=s.reduce((y,R)=>y+R.logicalBytes,0),p=0,m=0;for(let y of s){if(d<=n.maxGenerations&&l<=n.maxLogicalBytes)break;u.has(y.identity)||(t.onBeforeRemove?.(y.identity),Ce(y.path,{recursive:!0,force:!0}),d-=1,l-=y.logicalBytes,p+=1,m+=y.logicalBytes)}let g=d>n.maxGenerations||l>n.maxLogicalBytes,f={state:g?"protected":p>0?"collected":"within-bounds",generationCount:d,logicalBytes:l,protectedGenerations:u.size,activeReaderLeases:c.activeLeases,staleReaderLeasesRemoved:c.staleLeasesRemoved,malformedReaderLeases:c.malformedLeases,removedGenerations:p,removedLogicalBytes:m,limits:n,at:i,...g?{reason:c.malformedLeases>0?"malformed reader ownership evidence fails closed":"retention bounds cannot be met without deleting a protected generation"}:{}};return ho(e,f),f}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{ho(e,s)}catch{}return s}finally{o.release()}}function gu(e={}){let t={...pu,...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 fu(e){let t=M(e);return I(t)?Dn(t,{withFileTypes:!0}).filter(n=>n.isDirectory()&&/^[a-f0-9]{64}$/.test(n.name)).map(n=>{let r=S(t,n.name),i=Ke(t,n.name),o=i?i.database.size+(i.index?.size??0)+(i.metadata?.size??0):xo(r);return{identity:n.name,path:r,logicalBytes:o,modifiedAtMs:fe(r).mtimeMs}}).sort((n,r)=>n.modifiedAtMs-r.modifiedAtMs||n.identity.localeCompare(r.identity)):[]}function xo(e){let t=0;for(let n of Dn(e,{withFileTypes:!0})){let r=S(e,n.name);n.isDirectory()?t+=xo(r):n.isFile()&&(t+=fe(r).size)}return t}function ho(e,t){X(S(M(e),"gc.json"),t,{spacing:2,trailingNewline:!0})}function ee(e,t=S(V(e),"meta.json")){let n=S(M(e),"state.json");if(!I(n))return{state:"legacy",statePath:n};let r=ve(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=Lt(e,r.currentGeneration),o=i!==null,a=i?mu(e,t,i,r):!1,s=r.previousGeneration?I(S(V(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 mu(e,t,n,r){if(r.stableMirrors&&(r.stableMirrors.databaseFileIdentity!==Pe(e)||r.stableMirrors.indexFileIdentity!==void 0&&r.stableMirrors.indexFileIdentity!==Pe(S(V(e),"index.scip")))||!yo(e,n.database))return!1;let i=S(V(e),"index.scip");if(n.index&&!yo(i,n.index))return!1;if(!n.metadata)return!I(t);if(!I(t))return!1;let o=S(M(e),n.identity,n.metadata.file);return I(o)&&ie(k(t,"reindex metadata"))===ie(k(o,"immutable reindex metadata"))}function yo(e,t){return I(e)&&fe(e).isFile()&&fe(e).size===t.size}function hu(e){let t=Fn(e.outputDb,e.outputScip,e.metaPath);return t?Io(e.outputDb,t.currentGeneration):void 0}function An(e,t){return{databaseFileIdentity:Pe(e),...I(t)?{indexFileIdentity:Pe(t)}:{}}}function Io(e,t){let n=S(M(e),t),r=S(n,So(e)),i=S(n,"meta.json");return{generationIdentity:t,databasePath:mo(V(e),r),...I(i)?{metadataPath:mo(V(e),i)}:{}}}function yu(e){if(I(e))for(let t of Dn(e,{withFileTypes:!0}))t.isDirectory()&&t.name.endsWith(".tmp")&&Ce(S(e,t.name),{recursive:!0,force:!0})}function Su(e,t,n=S(V(t),"index.scip")){let r=Tn("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(ft(t)),I(n)&&r.update(`\0${ft(n)}`),I(e)&&r.update(`\0${ie(k(e,"reindex metadata"))}`),r.digest("hex")}function _n(e){let t=Pn(e.databasePath),n=e.indexPath?Pn(e.indexPath):void 0,r=e.metadataPath?Pn(e.metadataPath):void 0,i=e.forcedIdentity??bu(t,n,e.metadataPath),o=S(e.generationRoot,i),a=S(o,_t);if(I(a)){let u=Ke(e.generationRoot,i);if(u&&vo(o,u.database,t)&&xu(o,u.index,n)&&Iu(o,u.metadata,e.metadataPath))return{identity:i,directorySync:K(e.generationRoot)};throw new Error(`SQLite generation ${i} already exists with different or corrupt artifacts.`)}let s=[ze(e.generationRoot)];yu(e.generationRoot);let c=`${o}.${process.pid}.${Date.now()}.tmp`;Ce(c,{recursive:!0,force:!0}),uu(c,{recursive:!0});try{s.push(wn(e.databasePath,S(c,t.file))),n&&e.indexPath&&s.push(wn(e.indexPath,S(c,n.file))),r&&e.metadataPath&&s.push(wn(e.metadataPath,S(c,r.file)));let u=j(S(c,_t),{version:br,identity:i,database:t,...n?{index:n}:{},...r?{metadata:r}:{}},{spacing:2,trailingNewline:!0});u.directorySync!=="not-requested"&&s.push(u.directorySync),s.push(K(c)),En(c,o),s.push(K(e.generationRoot))}finally{Ce(c,{recursive:!0,force:!0})}return{identity:i,directorySync:Ie(...s)}}function bu(e,t,n){let r=Tn("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(e.sha256),t&&r.update(`\0${t.sha256}`),n&&r.update(`\0${ie(k(n,"reindex metadata"))}`),r.digest("hex")}function Pn(e){return{file:So(e),size:fe(e).size,sha256:ft(e)}}function ft(e){let t=Tn("sha256"),n=du(e,"r"),r=Buffer.allocUnsafe(1024*1024);try{for(;;){let i=Ru(n,r);if(i===0)break;t.update(r.subarray(0,i))}}finally{cu(n)}return t.digest("hex")}function Ru(e,t){let n=0;for(;n<t.length;){let r=lu(e,t,n,t.length-n,null);if(n+=r,r===0)break}return n}function wn(e,t){return Je(e,t,{mode:292})}function vo(e,t,n){let r=S(e,t.file);return t.file===n.file&&t.size===n.size&&t.sha256===n.sha256&&I(r)&&fe(r).size===t.size&&ft(r)===t.sha256}function xu(e,t,n){return!t||!n?t===n:vo(e,t,n)}function Iu(e,t,n){if(!t||!n)return t===void 0&&n===void 0;let r=S(e,t.file);return I(r)&&ie(k(r,"stored reindex metadata"))===ie(k(n,"candidate reindex metadata"))}function kn(e,t){Ce(`${t}.tmp-replace`,{force:!0}),En(e,`${t}.tmp-replace`),En(`${t}.tmp-replace`,t)}var jn=1,wo="SCIP_QUERY_SHARED_CACHE",Cn=JSON.stringify({cliVersion:Mr,artifactCatalogVersion:Oe,sqliteGenerationStoreVersion:de,typescriptFragmentStoreVersion:ut,typescriptOverlayStoreVersion:lt}),Ao="manifest.json",Du="shared-cache.json",Mn=[vn,De,_e];function yt(e,t){if(!e.clean||!e.treeOid)return;let n=Mo(JSON.stringify({version:jn,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:Cn}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:Cn,generationId:n,repositoryCacheDir:Gr(e.repositoryId)}}function _o(e,t,n){if(process.env[wo]==="0")return`${wo}=0`;if(!$r(n))return"explicit cache or database override";if(Ut(Ln(t))!==Ut(Nr(e))||t!==h(Ln(t),"index.db"))return"index database is outside the managed worktree cache"}function re(e,t=!0){let n=$n(e),r;try{r=Au(v(h(n,Ao),{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=$(n,i.path),a=ht(o);if(!a.isFile()||a.size!==i.size||We(o,{inputKind:"shared-generation artifact",maxBytes:_})!==i.sha256)return null}}catch{return null}return r}function Lo(e){let t=re(e.snapshot);if(t)return ko(e.snapshot,t);if(!jo(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=Eo(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=pt(e.sourceCacheDir),i=h(e.snapshot.repositoryCacheDir,"generations"),o=[ze(i)],a=Do(h(i,`.tmp-${process.pid}-`));try{let s=[];for(let g of r.files){let f=$(e.sourceCacheDir,g),y=$(a,g);o.push(Me(f,y,292)),e.onPublicationStage?.("after-artifact-flushed",g);let R=ht(y).size;s.push({path:g,size:R,sha256:We(y,{inputKind:"staged shared-generation artifact",maxBytes:_})})}let c=Fo(w(h(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 u=Vn(e.sourceProjectRoot);if(c!==u)throw new Error("shared SCIP generation root does not match its source worktree");if(Eo(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let d={version:jn,artifactCatalogVersion:Oe,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((g,f)=>g.path.localeCompare(f.path))},l=j(h(a,Ao),d,{spacing:2,trailingNewline:!0});l.directorySync!=="not-requested"&&o.push(l.directorySync),e.onPublicationStage?.("after-manifest-flushed"),o.push(K(a)),e.onPublicationStage?.("after-staging-directory-synced");let p=$n(e.snapshot);try{if(ne(p)&&!re(e.snapshot)){let g=`${p}.corrupt-${process.pid}-${Date.now()}`;ce(p,g),te(g,{recursive:!0,force:!0})}ce(a,p)}catch(g){let f=re(e.snapshot);if(f)return ko(e.snapshot,f);throw g}e.onPublicationStage?.("after-generation-renamed"),o.push(K(i)),e.onPublicationStage?.("after-generations-directory-synced");let m=Ie(...o);return{kind:"published",manifest:d,achievedDurability:m==="synced"?"directory-durable":"file-flushed",directorySync:m}}finally{te(a,{recursive:!0,force:!0})}}function ko(e,t){let n=K(h(e.repositoryCacheDir,"generations"));return{kind:"existing",manifest:t,achievedDurability:n==="synced"?"directory-durable":"file-flushed",directorySync:n}}function Nn(e){let t=$n(e.snapshot);me(e.targetCacheDir,{recursive:!0});let n=ue(h(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=Do(h(e.targetCacheDir,".shared-hydrate-")),Nu(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let u=$(t,c.path),d=$(r,c.path);if(Me(u,d),ht(d).size!==c.size||We(d,{inputKind:"hydrated shared-generation artifact",maxBytes:_})!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=Vn(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&mi($(r,c.path),e.manifest.scipProjectRoot,a);if(!jo(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=Cu(e.targetCacheDir,r),o=!0,ju(r,e.targetCacheDir,i),mt({tempOutputScip:h(r,"index.scip"),tempOutputDb:h(r,"index.db"),tempMetaPath:h(r,"meta.json"),outputScip:h(e.targetCacheDir,"index.scip"),outputDb:h(e.targetCacheDir,"index.db"),metaPath:h(e.targetCacheDir,"meta.json"),now:e.now});let s=ee(h(e.targetCacheDir,"index.db"),h(e.targetCacheDir,"meta.json"));if(s.state==="invalid"||s.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${s.reason}`);Gn(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&Mu(e.targetCacheDir,i),a}finally{r&&te(r,{recursive:!0,force:!0}),n.release()}}async function Oo(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??x,o=i()+n,a=h(e.repositoryCacheDir,"locks"),s=h(a,`${e.generationId}.lock`),c=u=>{if(!u||typeof u!="object"||Array.isArray(u))return null;let d=u.pid;return typeof d=="number"&&Number.isSafeInteger(d)&&d>0?{pid:d}:null};for(;i()<=o;){if(re(e))return{kind:"generation-ready"};let u=He(s,{kind:"shared-generation-build",detail:{generationId:e.generationId},parseLegacy:c});if(u.kind==="acquired")return{kind:"owner",release:()=>u.lock.release()};let d=o-i();if(d<=0)break;await Eu(Math.min(r,d))}return re(e)?{kind:"generation-ready"}:{kind:"timeout"}}function Gn(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:Fu(i)};return Ou(e.repositoryCacheDir,o,!0),o}function Fu(e){return Mo(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:On(e.projectRoot),localCacheDir:On(e.localCacheDir)}))}function Au(e){let t=JSON.parse(e);if(t.version!==jn||t.artifactCatalogVersion!==Oe||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!==Cn||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(gt(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 Me(e,t,n=384){return Je(e,t,{mode:n})}function _u(e,t,n){me(e,{recursive:!0}),j(h(e,Du),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function Eo(e){try{let t=pt(e),n=To("sha256");for(let r of t.files){let i=$(e,r),o=ht(i).size;n.update(r).update("\0").update(String(o)).update("\0"),hr(i,{inputKind:"source-generation artifact",maxBytes:_},a=>n.update(a)),n.update("\0")}return n.digest("hex")}catch{return null}}function Lu(e){try{let t=z(v(h(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 $n(e){return h(e.repositoryCacheDir,"generations",e.generationId)}function Ou(e,t,n){let r=Sr(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!ne(h(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=h(e,"worktrees");me(i,{recursive:!0}),j(h(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),_u(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function Cu(e,t){let n=h(t,".rollback"),r=new Map,i=new Map;me(n,{recursive:!0});for(let s of["index.scip","index.db","meta.json"]){let c=h(e,s),u=ne(c);r.set(s,u),u&&Me(c,h(n,"stable",s))}for(let s of Mn){let c=h(e,s),u=ne(c);if(u){let d=Pu(c);if(!d.isDirectory()||d.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${s}`)}i.set(s,u)}let o=h(e,Ye),a=ne(o);return a&&Co(o,h(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:a}}function ju(e,t,n){for(let r of Mn){let i=h(t,r);if(n.managedDirectories.get(r)){let a=h(n.root,"managed",r);me(Ln(a),{recursive:!0}),ce(i,a)}let o=h(e,r);ne(o)&&ce(o,i)}}function Mu(e,t){for(let i of Mn){let o=h(e,i),a=h(t.root,"managed",i);t.managedDirectories.get(i)?ne(a)&&(te(o,{recursive:!0,force:!0}),ce(a,o)):te(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let a=h(e,i);if(!o){te(a,{force:!0});continue}let s=`${a}.shared-restore-${vu()}`;Me(h(t.root,"stable",i),s),te(a,{force:!0}),ce(s,a)}let n=h(e,Ye);te(n,{recursive:!0,force:!0});let r=h(t.root,"sqlite-generations");t.generationStoreExisted&&ne(r)&&ce(r,n)}function Co(e,t){me(t,{recursive:!0});for(let n of wu(e,{withFileTypes:!0})){let r=h(e,n.name),i=h(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?Co(r,i):n.isFile()&&Me(r,i)}}function Nu(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 jo(e,t,n,r=!0,i=!0){try{let o=Lu(e);if(!o||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return je("source validation rejected metadata"),!1;let a=pt(e),s=ee(h(e,"index.db"),h(e,"meta.json"));if(r?s.state!=="current":s.state==="invalid"||s.state==="drifted")return je(`source validation rejected SQLite generation state ${s.state}`),!1;let c=new Tu(h(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 u=Vn(t),l=(i?a.files.filter(p=>p.endsWith(".scip")):["index.scip"]).every(p=>{let m=Fo(w($(e,p),{inputKind:"shared SCIP validation artifact",maxBytes:_})).metadata?.projectRoot;return m!==u&&je(`source validation rejected SCIP root for ${p}: ${String(m)}`),m===u});return l||je("source validation rejected SCIP project roots"),l}catch(o){return je(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function je(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function Vn(e){try{return Po(ku(e)).href}catch{return Po(On(e)).href}}function Mo(e){return To("sha256").update(e).digest("hex")}import{existsSync as Gu,readdirSync as $u,statSync as Vu}from"fs";import L from"path";var Bu=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function Ne(e,t=[]){let n=L.resolve(e),r=t.flatMap(c=>Uu(n,c));if(r.length>0)return No(n,Go(r));let i=qu(n),o=Go(i),a=Hu(n,o)?[n,...o]:o,s=a.length>0?a:[n];return No(n,s)}function No(e,t){return[...new Set(t.map(n=>Ju(e,n)))].sort((n,r)=>n.localeCompare(r))}function qu(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=$u(r,{withFileTypes:!0})}catch{continue}for(let o of i){let a=L.join(r,o.name);if(o.isDirectory()){!Bu.has(o.name)&&!o.name.startsWith(".")&&n.push(a);continue}o.isFile()&&Wu(a)&&t.push(L.dirname(a))}}return t}function Uu(e,t){let n=t.trim();if(!n)return[];let r=L.resolve(e,n);if(!be(e,r))return[];try{let i=Vu(r);if(i.isDirectory())return[r];if(i.isFile()&&$o(L.basename(r)))return[L.dirname(r)]}catch{return[]}return[]}function Wu(e){if(!$o(L.basename(e)))return!1;let t=Vo(e);return t?L.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function $o(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function Go(e){let t=[...new Set(e.map(n=>L.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&Yu(n,r)))}function Hu(e,t){if(t.length===0||t.some(r=>L.resolve(r)===e))return!1;let n=L.join(e,"tsconfig.json");return Gu(n)&&zu(n)}function zu(e){let n=Vo(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!L.extname(r))):!1}function Vo(e){try{let t=JSON.parse(k(e,"TypeScript project config"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Ju(e,t){let n=L.relative(e,t);return n?n.split(L.sep).join("/"):"."}function Yu(e,t){let n=L.relative(e,t);return!!n&&!n.startsWith("..")&&!L.isAbsolute(n)}import{createHash as fd}from"crypto";import{existsSync as qn,statSync as md,writeFileSync as Un}from"fs";import{join as hd}from"path";import{createRequire as Ku}from"module";import{dirname as Xu,isAbsolute as Bf,relative as qf,resolve as Uf,sep as Wf}from"path";var Bo=Ku(import.meta.url),Qu=1,qo="0.4.0";function Bn(){let e=Zu();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Zu(){try{let e=Bo.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(k(e,"scip-typescript package manifest"));if(t.version!==qo)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${qo}`};let n=Xu(e),r=Bo.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(k(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:ed(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function ed(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Qu}`}import{createHash as td}from"crypto";import{dirname as nd,join as Uo}from"path";var St=3;var rd="typescript-index";function Wo(e){let t=Uo(e,rd),n=Fr(t);return{...n,requestDir:n.legacyRequestDir}}function Ho(e){try{let t=gr(z(k(Uo(nd(e),"meta.json"),"reindex metadata")));return t?td("sha256").update(t).digest("hex"):null}catch{return null}}import{randomUUID as id}from"crypto";import{existsSync as od}from"fs";var ad=12e4,sd=5,bt=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;constructor(t,n={}){this.projectRoot=Lr(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??pd(),this.runtime=n.runtime??gd,this.mailboxLimits=n.mailboxLimits??{}}request(t){let n=_r(this.cacheDir),r=Wo(this.cacheDir),i=Vt(n.statePath);if(!zo(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??x)()+this.timeoutMs,c=Gt("typescript-index-v3",{baseGeneration:this.baseGeneration,request:t}),u=$t(c),d=Ar(r,{mailboxVersion:Nt,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:a,protocolVersion:St,id:u,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??x)()<=s;){if(od(d.responsePath))return cd(v(d.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t.producerIdentity,t.affectedFiles);let l=Vt(n.statePath);if(!zo(l,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(sd)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}};function zo(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===St&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&xe(e.processIdentity,r))}function cd(e,t,n,r,i,o){let a=JSON.parse(e);if(a.protocolVersion!==St||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=ud(a.response,i),c=[...new Set(o)].sort(),u=s.fragments.map(d=>d.relativePath).sort();if(JSON.stringify(u)!==JSON.stringify(c))throw new Error("TypeScript index service omitted or added an affected document.");return s}function ud(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(dd)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:ld(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 dd(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 ld(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function pd(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:ad}var gd={now:Date.now,monotonicNow:x,randomId:id,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:Y,readProcessIdentity:J};function yd(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=Ue(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"||!Bt(u.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=nt(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=Sd([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=Jo(e.currentSnapshot,e.projectFiles,e.producerIdentity),a=Jo(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==a)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let s=Ko(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!s)return{eligible:!1,reason:"prior document identity unavailable"};let c=Ko(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:Yo(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:Yo(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:s,nextDocumentIdentities:c,tsconfigPath:i==="."?"tsconfig.json":`${i}/tsconfig.json`,projectArgument:i}:{eligible:!1,reason:"next document identity unavailable"}}function Sd(e,t){let n=null;for(let r of e){let i=t.filter(o=>o==="."||r===o||r.startsWith(`${o}/`));if(i.length!==1||n!==null&&n!==i[0])return null;n=i[0]}return n}function Xo(e){let t=x();try{if(!qn(e.previousDbPath)||!qn(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=Bn();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new oe({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a,s;try{a=Xe(o,{includeIgnored:!1}).filter(Bt).sort(),s=Ze(o)}finally{o.close()}let c=performance.now()-n,u=yd({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?Ne(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:a,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:qn(hd(e.projectRoot,"tsconfig.json"))});if(!u.eligible)throw new Error(u.reason);let d=Ho(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let p=new bt({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:d}).request({kind:"emit-documents",tsconfigPath:u.tsconfigPath,projectArgument:u.projectArgument,projectIdentity:u.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles}),m=performance.now()-n,g=md(e.previousShardPath).size>=ao;n=performance.now();let f=g?null:w(e.previousShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:_}),y=g?{completeIndexBytes:null,affectedIndexBytes:Ui(p.fragments)}:Yi({packageVersion:r.packageVersion,baseIndexBytes:f,fragments:p.fragments}),R=performance.now()-n;n=performance.now(),g?so({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,nextGenerationIdentity:u.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:p.fragments}):(Wi({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:f,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.previousFragmentGeneration,documentIdentities:u.previousDocumentIdentities,allowUntrackedDocuments:!0}),Hi({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.nextFragmentGeneration,fragments:p.fragments,documentIdentities:u.nextDocumentIdentities}));let F=performance.now()-n;n=performance.now(),y.completeIndexBytes&&Un(e.candidateShardPath,y.completeIndexBytes),Un(e.candidateAffectedScipPath,y.affectedIndexBytes);let E=performance.now()-n,P={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:x()-t,cold:p.cold,changedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:u.previousFragmentGeneration,nextFragmentGeneration:u.nextFragmentGeneration,manifest:u.manifest,plan:u.plan,projectFileCount:a.length,referenceFragmentsByFile:new Map(p.fragments.map(T=>[T.relativePath,T.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:m,serviceMs:p.durationMs,assemblyMs:R,fragmentStoreMs:F,writeMs:E}};return e.onStatus(`Incremental TypeScript index emitted ${P.affectedFiles.length} affected document(s) in ${(P.durationMs/1e3).toFixed(3)}s (${P.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${m.toFixed(0)}ms, assembly ${R.toFixed(0)}ms, fragments ${F.toFixed(0)}ms, write ${E.toFixed(0)}ms).`),P}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 Qo(e){let t=Bn();if(!t.available)throw new Error(t.reason);let n=co({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:w(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:_}),packageVersion:t.packageVersion});Un(e.candidateShardPath,n)}function Jo(e,t,n){let r=e.files.filter(i=>lr(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 Wn(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function Yo(e,t){return Wn(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function Ko(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),a=Or({projectFiles:t.filter(c=>o.has(c)),snapshot:e,graph:n,engineIdentity:r}),s=new Map;for(let c of i){let u=a.identityFor(c,"typescript-scip-document-v1");if(u.key){s.set(c,u.key);continue}if(o.has(c))return null;s.set(c,Wn(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function Wn(e){return fd("sha256").update(e).digest("hex")}import{existsSync as Rt,renameSync as Jn,rmSync as Yn,statSync as bd}from"fs";import{cpus as Rd}from"os";import{join as ta}from"path";var Hn=Symbol("no-error");async function Zo(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=Hn,c=!0,u=Array.from({length:o},async()=>{for(;c&&a<e.length;){let d=a++;try{r[d]=await n(e[d])}catch(l){s===Hn&&(s=l),c=!1}}});if(await Promise.all(u),s!==Hn)throw s;return r}function xd(e,t,n){if(!e.defaultOutputPath)return;let r=ta(t,e.defaultOutputPath);n!==r&&Rt(r)&&Jn(r,n)}function Id(e,t,n){if(!e.defaultOutputPath)return null;let r=ta(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Yn(i,{force:!0}),Rt(r)?(Jn(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function vd(e){e&&(Yn(e.defaultOutputPath,{force:!0}),e.backupPath&&Rt(e.backupPath)&&Jn(e.backupPath,e.defaultOutputPath))}function Pd(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,Rd().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function na(e,t,n,r){let i=e.filter(u=>u.config.defaultOutputPath),o=e.filter(u=>!u.config.defaultOutputPath),a=[],s=Pd(o.length,r),c=await Zo(o,s,u=>zn(u,t,n));if(s>1){let u=new Map;for(let d of c.filter(l=>l.result.skipped&&l.retryable)){let l=o.find(p=>p.id===d.result.id);l&&(n(`Retrying ${l.label} indexer serially after parallel failure...`),u.set(l.id,(await zn(l,t,n)).result))}a.push(...c.map(({result:d})=>u.get(d.id)??d))}else a.push(...c.map(({result:u})=>u));for(let u of i)a.push((await zn(u,t,n)).result);return a.sort((u,d)=>e.findIndex(l=>l.id===u.id)-e.findIndex(l=>l.id===d.id))}async function zn(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Yn(e.scipPath,{force:!0});let r=Id(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=x();try{e.trustedProjectTool&&Dr(t,e.trustedProjectTool);let s=Er(e.binary,e.args),c=await Hr({command:s.binary,args:s.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:wd(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024});if(c.status!==0){let u=c.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${c.status}${u?`:
|
|
234
|
+
${u}`:""}`)}xd(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.message:String(s),u=`${e.resolvedBinary} indexer failed: ${c.split(`
|
|
235
|
+
`)[0]}`,d=e.label===e.language?u:`${e.label}: ${u}`;return n(`Skipping ${e.label}: ${u}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:x()-o,command:i,skipped:{language:e.language,reason:d}},retryable:kd(s)}}finally{vd(r)}if(!Rt(e.scipPath)){let s=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,c=e.label===e.language?s:`${e.label}: ${s}`;return n(`Skipping ${e.label}: ${s}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:x()-o,command:i,skipped:{language:e.language,reason:c}},retryable:!1}}let a;try{a=bd(e.scipPath).size}catch{a=void 0}return{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:x()-o,command:i,outputBytes:a},retryable:!1}}function wd(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):Ur.indexer}function kd(e){return e instanceof Wr?e.kind==="spawn"&&ea(e.cause):ea(e)}function ea(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}import{execFileSync as ia}from"child_process";import{homedir as ra,platform as Ed}from"os";import{delimiter as Td,join as xt}from"path";function Xn(e,t){let n=e.installMethods,r=Ee(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n){if(!i.identity||!i.destination){t(`Refusing ${i.label} installation for ${r}: the installer descriptor lacks an immutable identity or destination.`);continue}if(!Ot(i.prerequisite))continue;let o=Dd(i);t(`Installing immutable ${i.identity} via ${i.label} into ${o}; expected executable: ${r}.`);try{ia(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:Ed()==="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 Dd(e){if(e.binary==="npm")return Kn("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=Kn("go",["env","GOBIN"]);if(t)return t;let n=Kn("go",["env","GOPATH"]);if(n)return xt(n.split(Td)[0],"bin")}return e.binary==="dotnet"?xt(process.env.DOTNET_CLI_HOME??ra(),".dotnet","tools"):e.binary==="dart"?xt(process.env.PUB_CACHE??xt(ra(),".pub-cache"),"bin"):e.destination}function Kn(e,t){try{return ia(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}import Ea from"better-sqlite3";import{existsSync as Ta}from"fs";import{dirname as Da,join as Fa,resolve as Aa}from"path";import{randomUUID as Ad}from"crypto";import{mkdtempSync as _d,rmSync as Ld,statSync as aa}from"fs";import{tmpdir as Od}from"os";import{join as sa}from"path";import{Worker as Cd}from"worker_threads";function Fd(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function he(){return{skippedReferences:0,skippedReferenceReasons:Fd(),skippedReferenceSamples:[]}}function It(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 jd=3e5,ca=64*1024*1024,Md={createResultDirectory:()=>_d(sa(Od(),"scip-query-vue-workers-")),spawn:(e,t)=>new Cd(e,{workerData:t}),resultSize:e=>aa(e).size,readResult:e=>v(e,{maxBytes:ca,inputKind:"Vue worker result"}),removeResultDirectory:e=>Ld(e,{recursive:!0,force:!0})};function ua(e){return e.length>=8&&la(e.length)>1}async function da(e,t=Md){let n=la(e.vueFiles.length),r=Kd(e.vueFiles),i=Qd(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),a=e.timeoutMs??Jd(),s=e.maxResultBytes??Yd();oa("timeoutMs",a),oa("maxResultBytes",s);let c=Ad(),u=t.createResultDirectory(),d=[],l,p,m;try{for(let f=0;f<i.length;f++){let y=f,R=i[f]??[],F=R.map(T=>T.taskId),E=sa(u,`${y}.json`),P=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:R,resultPath:E,runId:c,workerId:y,taskIds:F});d.push({workerId:y,taskIds:F,resultPath:E,handle:P,completion:Nd(P,y)})}await Gd(d,a);let g=d.sort((f,y)=>f.workerId-y.workerId).map(f=>Vd(f,c,s,t));m={occurrences:g.flatMap(f=>f.occurrences),...he()};for(let f of g)It(m,f)}catch(g){l=g}finally{let g=await $d(d);if(g.length===0)try{t.removeResultDirectory(u)}catch(f){g.push(f)}if(g.length>0){let f=l===void 0?g:[l,...g];p=new AggregateError(f,`Vue worker cleanup failed: ${zd(f[0])}`)}}if(p)throw p;if(l!==void 0)throw l;if(!m)throw new Error("Vue workers completed without producing a merged result.");return m}function Nd(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 Gd(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 $d(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function Vd(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(!Ge(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(!Hd(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||!Bd(o.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return o.result}function Bd(e){if(!Ge(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(qd)||!U(e.skippedReferences)||!Ge(e.skippedReferenceReasons))return!1;for(let t of["missing-source-file","missing-service-script","no-definition","same-file-definition","unindexed-definition"])if(!U(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(Ud)}function qd(e){return Ge(e)&&typeof e.sourceFile=="string"&&U(e.sourceLine)&&U(e.sourceStartChar)&&U(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&U(e.symbolId)}function Ud(e){return Ge(e)&&typeof e.sourceFile=="string"&&U(e.sourceLine)&&U(e.sourceStartChar)&&U(e.sourceEndChar)&&typeof e.token=="string"&&Wd(e.reason)}function Wd(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function U(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hd(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function oa(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function zd(e){return e instanceof Error?e.message:String(e)}function la(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:1;return Math.max(1,Math.min(e,n))}function Jd(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:jd}function Yd(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:ca}function Kd(e){let t=Xd(),n=[];for(let r of e){let i=pa(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 Xd(){return Number.POSITIVE_INFINITY}function Qd(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Zd(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 Zd(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,pa(e.fileName)-e.startOffset)}function pa(e){try{return aa(e).size}catch{return 1}}import{createRequire as el}from"module";import{existsSync as tl}from"fs";import{dirname as ga,extname as nl,join as fa,relative as rl,resolve as il}from"path";import{pathToFileURL as ol}from"url";function al(e){e.transaction(()=>{e.prepare(`
|
|
236
236
|
DELETE FROM mentions
|
|
237
237
|
WHERE chunk_id IN (
|
|
238
238
|
SELECT c.id
|
|
@@ -247,12 +247,12 @@ ${u}`:""}`)}od(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.messag
|
|
|
247
247
|
FROM documents
|
|
248
248
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
249
249
|
)
|
|
250
|
-
`).run()})()}function
|
|
250
|
+
`).run()})()}function Zn(e,t){return e.prepare(`
|
|
251
251
|
SELECT relative_path AS relativePath
|
|
252
252
|
FROM documents
|
|
253
253
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
254
254
|
ORDER BY relative_path
|
|
255
|
-
`).all().map(r=>
|
|
255
|
+
`).all().map(r=>il(t,r.relativePath))}function ma(e,t){let{vueCore:n,ts:r,volarTs:i}=sl(e),{parsed:o,vueOptions:a}=cl(n,r,t),s=ga(t),c=n.createVueLanguagePlugin(r,o.options,a,m=>m),u=ul(n,r,c),d=dl(s,o),{languageServiceHost:l}=i.createLanguageServiceHost(r,r.sys,u,m=>m,d),p=r.createLanguageService(l);return{ts:r,language:u,languageService:p,fileNames:o.fileNames,configDir:s}}function sl(e){let t=el(ol(fa(e,"package.json")).href);return{vueCore:Qn(t,"@vue/language-core",e),ts:Qn(t,"typescript",e),volarTs:Qn(t,"@volar/typescript",e)}}function cl(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,ga(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function ul(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!tl(o))return;let a=v(o,{maxBytes:B,inputKind:"Vue language-service source file"});r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??hl(o))});return r.current=i,i}function dl(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Qn(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 ha(e,t,n){let r=ll(e);return i=>{if(!i.name)return null;let o=W(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 u=c.starts.find(l=>l.line===s.line&&l.displayName===i.name);if(u)return u.symbolId;let d=c.containingByLine.get(s.line);return d&&d.displayName===i.name?d.symbolId:pl(c.starts,s.line,2,i.name)}}function ll(e){let t=e.prepare(`
|
|
256
256
|
SELECT
|
|
257
257
|
d.relative_path AS relativePath,
|
|
258
258
|
der.start_line AS startLine,
|
|
@@ -263,22 +263,22 @@ ${u}`:""}`)}od(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.messag
|
|
|
263
263
|
JOIN documents d ON d.id = der.document_id
|
|
264
264
|
JOIN global_symbols gs ON gs.id = der.symbol_id
|
|
265
265
|
ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
|
|
266
|
-
`).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
|
|
266
|
+
`).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 pl(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let s=Math.floor((i+o)/2);e[s].line<t?i=s+1:o=s-1}let a=null;for(let s of[o,i]){let c=e[s];if(!c||c.displayName!==r)continue;let u=Math.abs(c.line-t);u>n||(!a||u<a.distance)&&(a={distance:u,symbolId:c.symbolId})}return a?.symbolId??null}function er(e,t,n){let r=bl(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
|
|
267
267
|
INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
|
|
268
268
|
VALUES (?, ?, ?, ?)
|
|
269
|
-
`),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let d=
|
|
269
|
+
`),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let d=W(t,u),l=wa(r.name,r.version,d);o.run(l,"default",7,`Vue component|${d}`);let p=Rl(i,r,t,u);p&&(a++,s.set(u,p))}})(),{get(u){return s.get(u)??null},syntheticSymbols:a}}function ya(e,t,n,r,i){return e.transaction(()=>(al(e),gl(e,t,n,r),fl(e,i)))()}function gl(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
|
|
270
270
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
271
271
|
VALUES (?, ?, ?, ?, X'00')
|
|
272
272
|
`),a=e.prepare(`
|
|
273
273
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
274
274
|
VALUES (?, ?, 1)
|
|
275
|
-
`);for(let s of n){let c=r.get(s);if(!c)continue;let u=
|
|
275
|
+
`);for(let s of n){let c=r.get(s);if(!c)continue;let u=W(t,s),d=i.get(u);if(!d)continue;let l=o.run(d.id,-1,0,0);a.run(Number(l.lastInsertRowid),c)}}function Sa(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(tr(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function ba(e){let t=new Set,n=[];for(let r of e){let i=Ra(r);t.has(i)||(t.add(i),n.push(r))}return n}function Ra(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function fl(e,t){let n=Sl(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
|
|
276
276
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
277
277
|
VALUES (?, ?, ?, ?, X'00')
|
|
278
278
|
`),i=e.prepare(`
|
|
279
279
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
280
280
|
VALUES (?, ?, 0)
|
|
281
|
-
`),o=new Set,a=0,s=0;for(let c of t){let u=
|
|
281
|
+
`),o=new Set,a=0,s=0;for(let c of t){let u=Ra(c);if(o.has(u))continue;o.add(u);let d=n.get(c.sourceFile);if(!d)continue;let l=r.run(d,s++,c.sourceLine,c.sourceLine),p=i.run(Number(l.lastInsertRowid),c.symbolId);a+=Number(p.changes)}return a}function*xa(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 Ia(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function tr(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function ml(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 va(e,t){return W(e,t).startsWith("node_modules/")}function W(e,t){return rl(e,t).replaceAll("\\","/")}function hl(e){switch(nl(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 Pa(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=v(t,{maxBytes:B,inputKind:"Vue source file"}),r={text:n,lineStarts:yl(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:ml}}function yl(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function Sl(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 bl(e){try{let t=JSON.parse(v(fa(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 Rl(e,t,n,r){let i=W(n,r),o=wa(t.name,t.version,i);return e.get(o)?.id??null}function wa(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function _a(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>Pl({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Il(e){return q(Q(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),q(_a({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}async function vl(e){return q(Q(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),wl(e)}function Pl(e){let t=Aa(e.projectRoot,e.tsconfig);if(!Ta(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Ea(e.dbPath);try{let r=Zn(n,e.projectRoot),i=Fa(Da(e.dbPath),"augment-vue-meta.json");return Ei({cachePath:i,readFingerprint:()=>Ca(n,e.projectRoot,e.tsconfig),compute:()=>kl({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 wl(e){let t=Aa(e.projectRoot,e.tsconfig);if(!Ta(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Ea(e.dbPath);try{let r=Zn(n,e.projectRoot),i=Fa(Da(e.dbPath),"augment-vue-meta.json");return await Ti({cachePath:i,readFingerprint:()=>Ca(n,e.projectRoot,e.tsconfig),compute:()=>El({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 kl(e){let t=er(e.db,e.projectRoot,e.vueFiles),n=Oa(e,t);return La(e,t,n)}async function El(e){let t=er(e.db,e.projectRoot,e.vueFiles),n=ua(e.vueFiles)?await da({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles}):Oa(e,t);return La(e,t,n)}function La(e,t,n){let r=ba(n.occurrences),i=ya(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:jl(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:Cl(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function Oa(e,t){let n=Tl({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return Dl({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function Ca(e,t,n){let r=e.prepare(`
|
|
282
282
|
SELECT
|
|
283
283
|
(SELECT COUNT(*) FROM documents) AS documents,
|
|
284
284
|
(SELECT COUNT(*) FROM global_symbols) AS symbols,
|
|
@@ -287,12 +287,13 @@ ${u}`:""}`)}od(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.messag
|
|
|
287
287
|
(SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
|
|
288
288
|
(SELECT MAX(id) FROM chunks) AS maxChunkId,
|
|
289
289
|
(SELECT MAX(id) FROM global_symbols) AS maxSymbolId
|
|
290
|
-
`).get();return{version:3,tsconfig:n,files:
|
|
291
|
-
`,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function bl(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Zo(e,t,n){let r=ce();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:N(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Vn(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 Gn(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 Rl(e,t){let n=Gn(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=Gn(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function xl(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(...Gn(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function Il(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return Rl(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function vl(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of wl(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&&(ua(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function ua(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 Pl(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function wl(e,t,n,r,i,o){let a=e.getDocumentHighlights?.(t,n,[t])??[],s=[];for(let c of a)if(c.fileName===t)for(let u of c.highlightSpans){let d=kl(r,u.textSpan.start,o,i.text);d!==null&&s.push(d)}return s}function kl(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=$n(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function vh(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=_l(e),a=Date.now(),s=y();gt(S(o.outputScip),{recursive:!0}),gt(S(o.outputDb),{recursive:!0});let c=e.languages??Vt(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 u=fe("reindex.fingerprint",()=>cr(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:c.length}),d,l;if(e.skipIfUnchanged!==!1&&!so(t,o.outputDb)&&da(o.outputScip)===da(k(S(o.outputDb),"index.scip"))){let m=We(t);if(d=m?at(m,u):void 0,d){let b=M(d);if(b){if(!jl(o,u))try{Pn({snapshot:d,manifest:b,targetCacheDir:S(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${d.generationId.slice(0,12)}`)}catch(P){r(`Shared generation attach failed; continuing locally: ${de(P)}`)}}else{let P=await uo(d);if(P.kind==="owner")l=P.release;else if(P.kind==="generation-ready"){let x=M(d);if(x)try{Pn({snapshot:d,manifest:x,targetCacheDir:S(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${d.generationId.slice(0,12)} after waiting`)}catch(v){r(`Shared generation attach failed after waiting; continuing locally: ${de(v)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let p=be(k(S(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!p)throw l?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${S(o.outputDb)}.`);let f;try{f=await me("reindex.lock",()=>sp(k(S(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:c.length})}catch(m){throw p.release(),l?.(),m}let g=null;try{Sn(o.outputDb,o.outputScip,o.metaPath);let m=Nl(S(o.outputDb));m.removed>0&&r(`Removed ${m.removed} abandoned reindex workspace(s)`);for(let V of m.errors)r(`Could not remove abandoned reindex workspace: ${V}`);let b=null,P=fe("reindex.reuse-check",()=>(b=Cl({opts:e,paths:o,languages:c,fingerprint:u,start:a,monotonicStart:s,onStatus:r}),b),()=>({languages:c.length,reused:b!==null}));if(P)return la({snapshot:d,paths:o,projectRoot:t,fingerprint:u,onStatus:r}),Ct(o.outputDb,P),P;await me("reindex.scip-cli-ready",()=>Zl(i,r));let x=Ll(o);g=x.runDir;let v,w=await me("reindex.fresh",async()=>(v=await $l({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:x,fingerprint:u,start:a,monotonicStart:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),v),()=>({languages:c.length,reused:v?.reused,skipped:v?.skipped.length}));return la({snapshot:d,paths:o,projectRoot:t,fingerprint:u,onStatus:r}),Ct(o.outputDb,w),w}catch(m){let b=yt({trigger:e.trigger,result:"failed",start:a,monotonicStart:s,error:m instanceof Error?m.message:String(m)});throw Oa(o.metaPath,b),yr(o.outputDb,b),m}finally{g&&ue(g,{recursive:!0,force:!0}),f(),p.release(),l?.()}}function la(e){if(e.snapshot){if(M(e.snapshot)){st(e.snapshot,S(e.paths.outputDb),"local-fresh");return}try{let t=We(e.projectRoot),n=t?at(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}co({snapshot:e.snapshot,sourceCacheDir:S(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=We(e.projectRoot);return(r?at(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),st(e.snapshot,S(e.paths.outputDb),"built"),e.onStatus(`Published shared generation ${e.snapshot.generationId.slice(0,12)}`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${de(t)}`)}}}function jl(e,t){if(!A(e.outputScip)||!A(e.outputDb)||!Aa(e.metaPath,t))return!1;let n=W(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function de(e){return e instanceof Error?e.message:String(e)}function _l(e){let t=e.outputScip??k(e.projectRoot,"index.scip"),n=e.outputDb??k(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:k(S(n),"meta.json")}}function Cl(e){let t=W(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!A(e.paths.outputScip)||!A(e.paths.outputDb)||!Aa(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;C(U(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=y()-e.monotonicStart,r=yt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return Oa(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:Ml(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function Ml(e,t,n,r){let i=Fa(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:_e(i[o]),outputBytes:Ce(Hn(e.outputDb,o)),durationMs:0}))}function Ll(e){let t=Fl(k(S(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:k(t,pt(e.outputScip)),tempOutputDb:k(t,pt(e.outputDb)),tempMetaPath:k(t,pt(e.metaPath))}}function Nl(e){let t=[],n;try{n=Sa(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[de(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{ue(k(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${de(o)}`)}return{removed:r,errors:t}}async function $l(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await me("reindex.language-indexers",async()=>(n=await Gl(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:a,languageFingerprints:s,shards:c,typescriptProjectShardContext:u,incrementalTypeScript:d}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),Vl({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let f=fe("reindex.publish",()=>Xl(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),g=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(m=>m.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:f,shards:c}}let l=fe("reindex.publish",()=>Yl(e,t,i,o,a,s,u,d),{mode:d?"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(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:p,reused:!1,skipped:o,lastRefresh:l,shards:c}}function Vl(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!A(e.run.paths.outputScip)||!A(e.run.paths.outputDb))return!1;let t=W(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 Gl(e,t){let n=Hl({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[T,Yn]of n)Yn.reused&&(r.push({language:T,scipPath:Yn.scipPath}),i.add(T));for(let T of i)e.onStatus(`Reusing cached ${T} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),a=W(e.paths.outputDb,e.paths.metaPath),s=Le(e.paths.metaPath),c=a.state==="legacy"||a.state==="current",u=s?.scipCompanion!=="deferred"&&(a.state!=="current"||a.generation.publication?.scipCompanion!=="deferred"),d=o&&!o.reused&&c?To({projectRoot:e.projectRoot,cacheDir:S(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:Me(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:Me(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:u,previousSnapshot:qn(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,l=new Set(d?["typescript"]:[]),p=d?void 0:Ul(e,n),{preparedRuns:f,skippedLanguages:g,languageOutputScipPaths:m}=ep({languages:e.languages.filter(T=>!i.has(T)&&!l.has(T)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:p?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),b=p?f.filter(T=>T.language!=="typescript"||p.missedProjectIds.has(T.id)):f,P=await Oo(b,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),x=[];if(p){Wl(e.paths.outputDb,P);let T=m.typescript??e.tempPaths.tempOutputScip;x=ql({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:T,reusedProjects:p.reusedProjects})}let v=[...P,...x],{indexedOutputs:w}=np(v,g),V=d?[{language:"typescript",scipPath:d.scipPath}]:[],Jn=[...r,...V,...w];rp(Jn,g,e.languages,e.opts.allowPartial,e.onStatus);let ja=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:Ce(d.scipPath)??void 0}]:[],_a=zl(n,[...P,...ja],p?{outputDb:e.paths.outputDb,classification:p.classification}:void 0);return{indexedOutputs:Jn,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:Jl(n,e.languages),shards:_a,typescriptProjectShardContext:p?{projects:p.allProjects,fingerprints:p.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function Ul(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=Oe(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=ui(e.projectRoot,r),o=ai(n.fingerprint.files,r),a=si(r,i),s=ci(r,o,a),c=Le(e.paths.metaPath),d=Bl(c,s,g=>A(ht(e.paths.outputDb,g))),l=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),p=new Set(l),f=new Set(r.filter(g=>!p.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:s,classification:d,reusedProjects:l,missedProjectIds:f}}function Bl(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===le&&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($(a)!==$(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 Wl(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=ht(e,r);gt(S(i),{recursive:!0}),mt(n.scipPath,i)}}function ql(e){return e.reusedProjects.map((t,n)=>{let r=ht(e.outputDb,t),i=Me(e.tempOutputScip,"typescript-project-cached",n);return mt(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Ce(i)??void 0}})}function Hl(e){let t=Le(e.paths.metaPath),n=Fa(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Hn(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!==le){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(!A(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:a,scipPath:o});continue}if($(s)!==$(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 zl(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:_e(o.fingerprint),outputBytes:Ce(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?_e(s.fingerprint):o?_e(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:_e(o.fingerprint),outputBytes:Ce(ht(n.outputDb,i)),durationMs:0});return r}function _e(e){return Tl("sha256").update($(e)).digest("hex").slice(0,16)}function Ce(e){try{return Dl(e).size}catch{return null}}function Jl(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function Yl(e,t,n,r,i,o,a,s){let c=!s||s.completeScipUpdated,u=!1;c&&(pa(e.paths.outputDb,n),u=ga(n,e.tempPaths.tempOutputScip,e.onStatus));let d=ip({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:u,materializeFullFallback:()=>{if(!s||s.completeScipUpdated)return u;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),Fo({cacheDir:S(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let x=n.map(v=>v.language==="typescript"?{language:v.language,scipPath:s.candidateScipPath}:v);return pa(e.paths.outputDb,x),u=ga(x,e.tempPaths.tempOutputScip,e.onStatus),u}});if(C(U(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&s){let x=null,v=null;try{x=new X({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),v=new X({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let w=pr(x,e.fingerprint,s.referenceFragmentsByFile,v);e.onStatus(`Cached exact TypeScript reference fragments for ${w} affected document(s).`)}catch(w){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${w instanceof Error?w.message:String(w)}.`)}finally{x?.close(),v?.close()}}let l=qn(e.paths.metaPath),p=d.mode==="incremental"&&s?ap(s,d.changedDocumentPaths):$t({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:l,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),f=yt({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(x=>x.language),skipped:[...r]}),g=d.mode==="incremental"&&d.scipCompanion==="deferred",m={...o};g&&delete m.typescript;let{metadata:b,pruneProjects:P}=xa({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:m,typescriptProjectShardContext:a,lastRefresh:f});return b.scipCompanion=g?"deferred":"current",Ia(e.paths.outputDb,P),zn(e.tempPaths.tempMetaPath,b),ot({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:d.mode==="incremental"&&d.scipCompanion==="deferred",publication:d.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:d.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:d.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:d.patchDurationMs,scipCompanion:d.scipCompanion,...d.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:d.converterDurationMs,scipCompanion:"current",...d.fallbackReason?{fallbackReason:d.fallbackReason}:{}}}),Ni(S(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),Ra(e.paths.outputDb,p,e.onStatus),f}function Xl(e,t,n,r,i,o){let a=qn(e.paths.metaPath),s=null;try{mt(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(l){s=Dr("reused","oracle-error",`Could not snapshot the prior database: ${l instanceof Error?l.message:String(l)}`)}C(U(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),s??=$t({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 c=yt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(l=>l.language),skipped:[...n]}),{metadata:u,pruneProjects:d}=xa({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return Ia(e.paths.outputDb,d),zn(e.paths.metaPath,u),Yi(e.paths.outputDb,e.paths.metaPath),Ra(e.paths.outputDb,s,e.onStatus),c}function qn(e){return Qn(Le(e)?.fingerprint)}function Ra(e,t,n){try{Ar(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 xa(e){let t=Ql({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:le,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,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 Ql(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=Le(e.metaPath),n=t?.version===le?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 Ia(e,t){let n=Da(e);if(t===null){ue(n,{recursive:!0,force:!0});return}let r;try{r=Sa(n)}catch{return}for(let i of Kl(r,t))ue(k(n,i),{force:!0})}function Kl(e,t){let n=new Set(t.map(r=>`${en(r)}.scip`));return e.filter(r=>!n.has(r))}function pa(e,t){for(let n of t){let r=Hn(e,n.language);gt(S(r),{recursive:!0}),n.scipPath!==r&&mt(n.scipPath,r)}}async function Zl(e,t){if(!Ot()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
292
|
-
|
|
293
|
-
|
|
290
|
+
`).get();return{version:3,tsconfig:n,files:Qe(t),db:r}}function Tl(e){let t=Pa();return{projectRoot:e.projectRoot,context:ma(e.projectRoot,e.configPath),symbolLookup:ha(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function Dl(e){let t=[],n=he(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=Fl(e,i);t.push(...o.occurrences),It(n,o)}return{occurrences:t,...n}}function Fl(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=W(e.projectRoot,t.fileName),s=[...xa(n.text)],c={tokens:s.filter(u=>u.start>=t.startOffset&&u.start<t.endOffset),tokenByStart:new Map(s.map(u=>[u.start,u])),tokenTextCounts:Nl(s),processedStarts:new Set};return Al({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function Al(e){let t=[],n=he();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||_l(e.sourceInfo.text,r.start))continue;let i=Ia(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!va(e.projectRoot,d.fileName));if(!a){nr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=W(e.projectRoot,a.fileName),c=Ll(e.sourceFile,r.text,s);if(c){nr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=Sa(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){nr(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}ja(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),Ml(t,e,r,i,s,u)}return{occurrences:t,...n}}function _l(e,t){let n=e.lastIndexOf(`
|
|
291
|
+
`,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function Ll(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=he();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:W(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function nr(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 rr(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 Ol(e,t){let n=rr(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=rr(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function Cl(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(...rr(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function jl(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return Ol(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function Ml(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of Gl(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&&(ja(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function ja(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 Nl(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function Gl(e,t,n,r,i,o){let a=e.getDocumentHighlights?.(t,n,[t])??[],s=[];for(let c of a)if(c.fileName===t)for(let u of c.highlightSpans){let d=$l(r,u.textSpan.start,o,i.text);d!==null&&s.push(d)}return s}function $l(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=tr(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function oy(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log}=e,i=e.skipAutoInstall===!0||e.installMissing!==!0,o=Jl(e),a=Date.now(),s=x();Pt(b(o.outputScip),{recursive:!0}),Pt(b(o.outputDb),{recursive:!0});let c=e.languages??Qt(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 u=we("reindex.fingerprint",()=>Pr(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:c.length}),d,l;if(e.skipIfUnchanged!==!1&&!_o(t,o.outputDb)&&Ma(o.outputScip)===Ma(D(b(o.outputDb),"index.scip"))){let f=et(t);if(d=f?yt(f,u):void 0,d){let y=re(d);if(y){if(!zl(o,u))try{Nn({snapshot:d,manifest:y,targetCacheDir:b(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${d.generationId.slice(0,12)}`)}catch(R){r(`Shared generation attach failed; continuing locally: ${Se(R)}`)}}else{let R=await Oo(d);if(R.kind==="owner")l=R.release;else if(R.kind==="generation-ready"){let F=re(d);if(F)try{Nn({snapshot:d,manifest:F,targetCacheDir:b(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${d.generationId.slice(0,12)} after waiting`)}catch(E){r(`Shared generation attach failed after waiting; continuing locally: ${Se(E)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let p=ue(D(b(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!p)throw l?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${b(o.outputDb)}.`);let m;try{m=await ke("reindex.lock",()=>xp(D(b(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:c.length})}catch(f){throw p.release(),l?.(),f}let g=null;try{Fn(o.outputDb,o.outputScip,o.metaPath);let f=Ql(b(o.outputDb));f.removed>0&&r(`Removed ${f.removed} abandoned reindex workspace(s)`);for(let O of f.errors)r(`Could not remove abandoned reindex workspace: ${O}`);let y=null,R=we("reindex.reuse-check",()=>(y=Yl({opts:e,paths:o,languages:c,fingerprint:u,start:a,monotonicStart:s,onStatus:r}),y),()=>({languages:c.length,reused:y!==null}));if(R){Na({snapshot:d,paths:o,projectRoot:t,fingerprint:u,onStatus:r});let O=zt(o.outputDb,R);return O.state==="failed"&&r(`Warning: reindex succeeded, but activity telemetry was not recorded: ${O.reason}`),qt(t,b(o.outputDb)),R}await ke("reindex.scip-cli-ready",()=>gp(i,r));let F=Xl(o);g=F.runDir;let E,P=await ke("reindex.fresh",async()=>(E=await Zl({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:F,fingerprint:u,start:a,monotonicStart:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),E),()=>({languages:c.length,reused:E?.reused,skipped:E?.skipped.length}));Na({snapshot:d,paths:o,projectRoot:t,fingerprint:u,onStatus:r});let T=zt(o.outputDb,P);return T.state==="failed"&&r(`Warning: reindex succeeded, but activity telemetry was not recorded: ${T.reason}`),qt(t,b(o.outputDb)),P}catch(f){let y=Tt({trigger:e.trigger,result:"failed",start:a,monotonicStart:s,error:f instanceof Error?f.message:String(f)});os(o.metaPath,y);let R=qr(o.outputDb,y);throw R.state==="failed"&&r(`Warning: failed reindex activity telemetry was not recorded: ${R.reason}`),f}finally{g&&ye(g,{recursive:!0,force:!0}),m(),p.release(),l?.()}}function Na(e){if(e.snapshot)try{let t=et(e.projectRoot),n=t?yt(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=Lo({snapshot:e.snapshot,sourceCacheDir:b(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let i=et(e.projectRoot);return(i?yt(i,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}});Gn(e.snapshot,b(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: ${Se(t)}`)}}function zl(e,t){if(!G(e.outputScip)||!G(e.outputDb)||!is(e.metaPath,t))return!1;let n=ee(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function Se(e){return e instanceof Error?e.message:String(e)}function Jl(e){let t=e.outputScip??D(e.projectRoot,"index.scip"),n=e.outputDb??D(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:D(b(n),"meta.json")}}function Yl(e){let t=ee(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!G(e.paths.outputScip)||!G(e.paths.outputDb)||!is(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;q(Q(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=x()-e.monotonicStart,r=Tt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return os(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:Kl(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function Kl(e,t,n,r){let i=ns(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:$e(i[o]),outputBytes:Ve(sr(e.outputDb,o)),durationMs:0}))}function Xl(e){let t=ql(D(b(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:D(t,vt(e.outputScip)),tempOutputDb:D(t,vt(e.outputDb)),tempMetaPath:D(t,vt(e.metaPath))}}function Ql(e){let t=[],n;try{n=Wa(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[Se(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{ye(D(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${Se(o)}`)}return{removed:r,errors:t}}async function Zl(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await ke("reindex.language-indexers",async()=>(n=await tp(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:a,languageFingerprints:s,shards:c,typescriptProjectShardContext:u,incrementalTypeScript:d}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),ep({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let m=we("reindex.publish",()=>dp(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),g=m.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:m,shards:c}}let l=we("reindex.publish",()=>up(e,t,i,o,a,s,u,d),{mode:d?"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(m=>m.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:p,reused:!1,skipped:o,lastRefresh:l,shards:c}}function ep(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!G(e.run.paths.outputScip)||!G(e.run.paths.outputDb))return!1;let t=ee(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 tp(e,t){let n=ap({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[C,ur]of n)ur.reused&&(r.push({language:C,scipPath:ur.scipPath}),i.add(C));for(let C of i)e.onStatus(`Reusing cached ${C} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),a=ee(e.paths.outputDb,e.paths.metaPath),s=qe(e.paths.metaPath),c=a.state==="legacy"||a.state==="current",u=s?.scipCompanion!=="deferred"&&(a.state!=="current"||a.generation.publication?.scipCompanion!=="deferred"),d=o&&!o.reused&&c?Xo({projectRoot:e.projectRoot,cacheDir:b(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:Be(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:Be(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:u,previousSnapshot:ar(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,l=new Set(d?["typescript"]:[]),p=d?void 0:np(e,n),{preparedRuns:m,skippedLanguages:g,languageOutputScipPaths:f}=fp({languages:e.languages.filter(C=>!i.has(C)&&!l.has(C)),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}),y=p?m.filter(C=>C.language!=="typescript"||p.missedProjectIds.has(C.id)):m,R=await na(y,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),F=[];if(p){ip(e.paths.outputDb,R);let C=f.typescript??e.tempPaths.tempOutputScip;F=op({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:C,reusedProjects:p.reusedProjects})}let E=[...R,...F],{indexedOutputs:P}=hp(E,g),T=d?[{language:"typescript",scipPath:d.scipPath}]:[],O=[...r,...T,...P];yp(O,g,e.languages,e.opts.allowPartial,e.onStatus);let as=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:Ve(d.scipPath)??void 0}]:[],ss=sp(n,[...R,...as],p?{outputDb:e.paths.outputDb,classification:p.classification}:void 0);return{indexedOutputs:O,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:cp(n,e.languages),shards:ss,typescriptProjectShardContext:p?{projects:p.allProjects,fingerprints:p.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function np(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=Ne(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Ci(e.projectRoot,r),o=_i(n.fingerprint.files,r),a=Li(r,i),s=Oi(r,o,a),c=qe(e.paths.metaPath),d=rp(c,s,g=>G(Et(e.paths.outputDb,g))),l=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),p=new Set(l),m=new Set(r.filter(g=>!p.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:s,classification:d,reusedProjects:l,missedProjectIds:m}}function rp(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===Re&&Ft(e).typescriptProjectShardReuse?e.typescriptProjectShards?.[i]:void 0;if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:o});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o});continue}if(H(a)!==H(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 ip(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=Et(e,r);Pt(b(i),{recursive:!0}),kt(n.scipPath,i)}}function op(e){return e.reusedProjects.map((t,n)=>{let r=Et(e.outputDb,t),i=Be(e.tempOutputScip,"typescript-project-cached",n);return kt(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Ve(i)??void 0}})}function ap(e){let t=qe(e.paths.metaPath),n=ns(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=sr(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!==Re){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(!Ft(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(!G(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:a,scipPath:o});continue}if(H(s)!==H(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 sp(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:$e(o.fingerprint),outputBytes:Ve(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?$e(s.fingerprint):o?$e(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:$e(o.fingerprint),outputBytes:Ve(Et(n.outputDb,i)),durationMs:0});return r}function $e(e){return Bl("sha256").update(H(e)).digest("hex").slice(0,16)}function Ve(e){try{return Ul(e).size}catch{return null}}function cp(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function up(e,t,n,r,i,o,a,s){let c=!s||s.completeScipUpdated,u=!1;c&&(Ga(e.paths.outputDb,n),u=$a(n,e.tempPaths.tempOutputScip,e.onStatus));let d=Sp({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:u,materializeFullFallback:()=>{if(!s||s.completeScipUpdated)return u;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),Qo({cacheDir:b(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let P=n.map(T=>T.language==="typescript"?{language:T.language,scipPath:s.candidateScipPath}:T);return Ga(e.paths.outputDb,P),u=$a(P,e.tempPaths.tempOutputScip,e.onStatus),u}});q(Q(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus});let l=cn(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(", ")}`),d.mode==="incremental"&&s){let P=null,T=null;try{P=new oe({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),T=new oe({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let O=Cr(P,e.fingerprint,s.referenceFragmentsByFile,T);e.onStatus(`Cached exact TypeScript reference fragments for ${O} affected document(s).`)}catch(O){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${O instanceof Error?O.message:String(O)}.`)}finally{P?.close(),T?.close()}}let p=ar(e.paths.metaPath),m=d.mode==="incremental"&&s?Rp(s,d.changedDocumentPaths):Xt({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"}),g=Tt({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(P=>P.language),skipped:[...r]}),f=d.mode==="incremental"&&d.scipCompanion==="deferred",y={...o};f&&delete y.typescript;let{metadata:R,pruneProjects:F}=Ja({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:y,typescriptProjectShardContext:a,lastRefresh:g});R.scipCompanion=f?"deferred":"current",Ya(e.paths.outputDb,F),cr(e.tempPaths.tempMetaPath,R);let E=mt({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:d.mode==="incremental"&&d.scipCompanion==="deferred",publication:d.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:d.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:d.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:d.patchDurationMs,scipCompanion:d.scipCompanion,...d.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:d.converterDurationMs,scipCompanion:"current",...d.fallbackReason?{fallbackReason:d.fallbackReason}:{}}});return E.achievedDurability==="file-flushed"&&e.onStatus(`Published local generation ${E.currentGeneration.slice(0,12)} (file-flushed; directory sync unsupported)`),uo(b(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),za(e.paths.outputDb,m,e.onStatus),g}function dp(e,t,n,r,i,o){let a=ar(e.paths.metaPath),s=null;try{kt(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(p){s=Xr("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}q(Q(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let c=cn(e.paths.outputDb);c.added.length>0&&e.onStatus(`Added SQLite query indexes: ${c.added.join(", ")}`),c.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${c.removed.join(", ")}`),s??=Xt({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,refreshResult:"reused"});let u=Tt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:d,pruneProjects:l}=Ja({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:u});return Ya(e.paths.outputDb,l),cr(e.paths.metaPath,d),bo(e.paths.outputDb,e.paths.metaPath),za(e.paths.outputDb,s,e.onStatus),u}function ar(e){return pr(qe(e)?.fingerprint)}function za(e,t,n){try{Qr(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 Ja(e){let t=lp({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:Re,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 lp(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=qe(e.metaPath),n=t?.version===Re?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 Ya(e,t){let n=rs(e);if(t===null){ye(n,{recursive:!0,force:!0});return}let r;try{r=Wa(n)}catch{return}for(let i of pp(r,t))ye(D(n,i),{force:!0})}function pp(e,t){let n=new Set(t.map(r=>`${pn(r)}.scip`));return e.filter(r=>!n.has(r))}function Ga(e,t){for(let n of t){let r=sr(e,n.language);Pt(b(r),{recursive:!0}),n.scipPath!==r&&kt(n.scipPath,r)}}async function gp(e,t){if(!Wt()){if(Hl()==="win32")throw new Error("The scip CLI was not found. On Windows it ships via the npm sidecar package scip-query-scip-windows (installed automatically with scip-query). Reinstall scip-query with optional dependencies enabled, or follow 'scip-query setup' guidance for the exact sidecar package version, or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
292
|
+
To install the reviewed version, run: scip-query reindex --install-missing
|
|
293
|
+
Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!Ht(t))throw new Error(`The scip CLI is required but could not be installed.
|
|
294
|
+
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function fp(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?Be(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=mp({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?Ka(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function mp(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[ir({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??Ne(e.projectRoot,e.typescriptProjects);return t.length===0?[ir({...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)=>ir({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:Be(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function ir(e){let t=it(e.language),n=Ee(t),r=jt(t,e.projectRoot),i=e.trustProjectTools&&r?Tr(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&&!Ct(t)){if(e.skipAutoInstall){let u=`${n} not found on PATH. To install the reviewed version, run: scip-query 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...`),!Xn(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});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:Mt(t,e.env,a),...i?{trustedProjectTool:i}:{}}}}function hp(e,t){let n=new Map;for(let i of e)if(i.skipped)Ka(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)on(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&Ha(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function Ka(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 yp(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
|
|
294
295
|
`);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
|
|
295
296
|
`+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
297
|
`+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
|
|
297
|
-
`))}function
|
|
298
|
+
`))}function $a(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=fi(e.map(o=>o.scipPath),t);return Qa(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Ha(e[0].scipPath,t);return!1}function Sp(e){let t;if(bp(e)){let i=D(e.run.tempPaths.runDir,"typescript-affected.db");try{Xa(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();Va(e.incrementalTypeScript.affectedScipPath,i,e.env,e.run.onStatus),e.run.onStatus(`Converted affected SCIP documents in ${(performance.now()-o).toFixed(0)}ms.`);let a=Ii({previousDbPath:e.run.paths.outputDb,miniDbPath:i,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:e.incrementalTypeScript.affectedFiles});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){t=o instanceof Error?o.message:String(o),ye(i,{force:!0}),ye(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=e.materializeFullFallback());let r=performance.now();return Va(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function bp(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!G(e.run.paths.outputDb)||!G(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 Rp(e,t){let n=x(),r=[...t].sort(),i=new Set(r),o={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(a=>!i.has(a)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:x()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:Kt(e.plan,o,e.projectFileCount)}}function Va(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!G(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||Xa(e,r);let o=Wt();if(!o)throw new Error("scip CLI is not available");Vl(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024,timeout:3e5,killSignal:"SIGKILL"})}catch(o){let a=o instanceof Error?o.message:String(o);throw new Error(`Failed to convert SCIP index to SQLite: ${a}`,{cause:o})}}function Xa(e,t){let n=pi(e);Qa(n,t)}function Qa(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function Be(e,t,n){let r=Wl(e)||".scip",i=vt(e,r);return D(b(e),`${i}.${n+1}.${t}${r}`)}async function xp(e,t){for(let n=0;n<2;n++){let r=Ip(e,t);if(r)return r;let i=vp(e);if(i&&ts(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await wp(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: ${Se(s)}`,{cause:s})}if(!o)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${b(e)}; refusing to steal an active lock.`);let a=At(e,{parseLegacy:wt});if(!yr(e,a,{parseLegacy:wt}))throw new Error(`Reindex lock ownership changed before preemption completed for ${b(e)}.`);continue}throw new Error(`Another scip-query reindex is already running for ${b(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${b(e)}.`)}function Ip(e,t){let n=J(process.pid),r=He(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:wt});if(r.kind==="acquired"&&r.reclaimed){let i=Za(r.reclaimed,e);i&&ts(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 ${b(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function vp(e){return Za(At(e,{parseLegacy:wt}),e)}var wt=e=>{let t=es(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function Za(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:b(t),startedAt:e.record.startedAt,trigger:n.trigger}}return es(e.parsed,t)}function es(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=mr(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:b(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function ts(e,t){return e?.kind==="manual-cli"&&Pp(t?.trigger)}function Pp(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function wp(e){return!Y(e.pid)||(or(e),Ba(e,"SIGTERM"),await qa(e,2e3))?!0:(or(e),Ba(e,"SIGKILL"),qa(e,1e3))}function Ba(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!Y(e.pid))return;or(e)}try{process.kill(e.pid,t)}catch{}}async function qa(e,t){let n=x()+t;for(;x()<n;){if(Ua(e))return!0;await kp(50)}return Ua(e)}function or(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=J(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!xe(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function Ua(e){if(!Y(e.pid))return!0;if(!e.processIdentity)return!1;let t=J(e.pid);return t!==null&&!xe(e.processIdentity,t)}function kp(e){return new Promise(t=>setTimeout(t,e))}function ns(e,t,n){return Object.fromEntries(t.map(r=>{let i=it(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Ir(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},a=r==="clojure"?Ep(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&Tp(n),...o,clojureConfigPath:a,files:Qe(e,{language:r,markerFiles:i})}]}))}function Ep(e){return e?.trim()||void 0}function Tp(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function sr(e,t){return D(b(e),"language-indexes",`${t}.scip`)}function rs(e){return D(b(e),"language-indexes","typescript-projects")}function Et(e,t){return D(rs(e),`${pn(t)}.scip`)}function qe(e){try{return Dt(z(k(e,"reindex metadata")))}catch{return null}}function is(e,t){try{let n=z(k(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return!1;let r=n.metadata;return n.capabilities.publishableGeneration&&fr(r)&&H(r.fingerprint)===H(t)&&H([...r.indexedLanguages??[]].sort())===H(t.languages)}catch{return!1}}function cr(e,t){j(e,t,{spacing:2,trailingNewline:!0})}function os(e,t){try{let n=Dt(z(k(e,"reindex metadata")));if(!n)return;cr(e,{...n,lastRefresh:t})}catch{}}function Tt(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:x()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function H(e){return JSON.stringify(e)}export{di as INDEXER_CONFIGS,zr as augmentAuxiliaryDocuments,Il as augmentVueResolvedReferences,vl as augmentVueResolvedReferencesAsync,Q as auxiliaryDocumentsAugmentationStage,Ee as describeIndexerBinary,Qt as detectLanguages,it as getIndexerConfig,Mt as getIndexerExecutionEnv,Ot as isBinaryAvailable,Ct as isIndexerInstalled,on as mergeScipFiles,rn as mergeScipIndexes,oy as reindex,pe as resolveIndexerBinary,jt as resolveProjectLocalIndexerBinary,q as runPostIndexAugmentation,Xn as tryInstallIndexer,Ht as tryInstallScipCli,_a as vueResolvedReferencesAugmentationStage};
|
|
298
299
|
//# sourceMappingURL=reindex.js.map
|