scip-query 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (386) hide show
  1. package/CHANGELOG.md +257 -0
  2. package/README.md +11 -0
  3. package/dist/augment-vue-worker.js +1 -1
  4. package/dist/by-kind-XI2CSWEY.js +2 -0
  5. package/dist/call-graph-UONR6JR5.js +2 -0
  6. package/dist/{chunk-FGNCOQUX.js → chunk-2E7CX53V.js} +2 -2
  7. package/dist/chunk-2GRUZAQF.js +43 -0
  8. package/dist/{chunk-DPWKKNKI.js → chunk-2LDBDR6J.js} +2 -2
  9. package/dist/{chunk-JHH5SCZ3.js → chunk-2OOY75BW.js} +2 -2
  10. package/dist/{chunk-XGGBK66W.js → chunk-2R3V3PSD.js} +2 -2
  11. package/dist/chunk-2WC2OEDO.js +4 -0
  12. package/dist/{chunk-57N6LN2A.js → chunk-3AF4TUFK.js} +2 -2
  13. package/dist/{chunk-2RE5OCHZ.js → chunk-3D3QG236.js} +2 -2
  14. package/dist/{chunk-D2MVJSP4.js → chunk-3FHOF22C.js} +2 -2
  15. package/dist/{chunk-7XZGZBSQ.js → chunk-3JKSW6LJ.js} +2 -2
  16. package/dist/chunk-3L2ZBPEX.js +133 -0
  17. package/dist/{chunk-NVSZNESQ.js → chunk-3PJABJSU.js} +2 -2
  18. package/dist/{chunk-WOOAY3PA.js → chunk-3SVF22I5.js} +2 -2
  19. package/dist/{chunk-YAGYMBEX.js → chunk-3WR4E3A3.js} +2 -2
  20. package/dist/chunk-4FTZ4P5G.js +2 -0
  21. package/dist/{chunk-F24G5NBE.js → chunk-4ILJCCXV.js} +2 -2
  22. package/dist/chunk-4UX2F3JX.js +2 -0
  23. package/dist/chunk-4WNW27SX.js +2 -0
  24. package/dist/chunk-5ENOG4VP.js +61 -0
  25. package/dist/{chunk-RHHCLWQ6.js → chunk-64BFSI5I.js} +2 -2
  26. package/dist/chunk-66DVSJQG.js +455 -0
  27. package/dist/{chunk-ISWFRGJ6.js → chunk-6HFCYNYE.js} +2 -2
  28. package/dist/{chunk-Y2VM4CJC.js → chunk-6I6L7Z62.js} +2 -2
  29. package/dist/{chunk-CKRWA452.js → chunk-6PQNKL3G.js} +2 -2
  30. package/dist/{chunk-GPGRZJ3R.js → chunk-6V5CNXL6.js} +2 -2
  31. package/dist/chunk-6VVV4WRR.js +4 -0
  32. package/dist/{chunk-BDGTPN27.js → chunk-7BWFZPPZ.js} +2 -2
  33. package/dist/{chunk-25GWKRUZ.js → chunk-7CYG22FH.js} +2 -2
  34. package/dist/chunk-7F45LJKI.js +2 -0
  35. package/dist/{chunk-4TQU4TX2.js → chunk-7IWV2EG3.js} +2 -2
  36. package/dist/{chunk-UDY7MIAW.js → chunk-AFHTBORT.js} +2 -2
  37. package/dist/chunk-AVRYW5OZ.js +2 -0
  38. package/dist/chunk-B3PYOSCX.js +2 -0
  39. package/dist/{chunk-RNKPYYYE.js → chunk-B5D7QPBE.js} +2 -2
  40. package/dist/{chunk-FFJQZG6J.js → chunk-BBCIS4DX.js} +2 -2
  41. package/dist/chunk-BDUVI7TO.js +3 -0
  42. package/dist/{chunk-BVFYEEBH.js → chunk-BE7ZZTMC.js} +2 -2
  43. package/dist/{chunk-NEIQPFBI.js → chunk-BHVUJOCQ.js} +2 -2
  44. package/dist/chunk-BKVWUP7Y.js +2 -0
  45. package/dist/{chunk-IJMD6BRI.js → chunk-BQGB4HBD.js} +2 -2
  46. package/dist/{chunk-ERCYGVAM.js → chunk-BRV7PIFF.js} +2 -2
  47. package/dist/chunk-CEEZJXEF.js +2 -0
  48. package/dist/{chunk-BTVKZGWT.js → chunk-CIYLO6SI.js} +2 -2
  49. package/dist/chunk-CJZXN4NU.js +2 -0
  50. package/dist/{chunk-VXJJTQYE.js → chunk-CNO7TOKL.js} +2 -2
  51. package/dist/{chunk-ZZ3Z7D56.js → chunk-COF23M5F.js} +2 -2
  52. package/dist/{chunk-ZGW4HLPD.js → chunk-CWFP7GM5.js} +2 -2
  53. package/dist/chunk-D2DHWI3D.js +2 -0
  54. package/dist/{chunk-Q55NF3ZG.js → chunk-D4N5SQ2M.js} +2 -2
  55. package/dist/{chunk-LXQUF2RP.js → chunk-DBRSYFXR.js} +2 -2
  56. package/dist/{chunk-PXXYQK55.js → chunk-DHUIOLDT.js} +2 -2
  57. package/dist/{chunk-KZYID5KV.js → chunk-DIRJWYBM.js} +2 -2
  58. package/dist/{chunk-IKVNEGTW.js → chunk-DIUFNHRJ.js} +2 -2
  59. package/dist/{chunk-CLG6DWVS.js → chunk-DTZCKZEU.js} +2 -2
  60. package/dist/{chunk-Z2PZVKPR.js → chunk-DULC3QFP.js} +2 -2
  61. package/dist/{chunk-AYPDH2LU.js → chunk-DYGHBZ2N.js} +2 -2
  62. package/dist/{chunk-JJ62MTQH.js → chunk-E5R6AQ73.js} +2 -2
  63. package/dist/{chunk-BWVQP3LB.js → chunk-E73UNJTF.js} +2 -2
  64. package/dist/{chunk-GVOMSPGL.js → chunk-EG2CPZMJ.js} +2 -2
  65. package/dist/{chunk-56NQAEPJ.js → chunk-EKV5HX33.js} +2 -2
  66. package/dist/{chunk-GDRJB3SB.js → chunk-EQHFIL6T.js} +2 -2
  67. package/dist/{chunk-EWWY2ZFL.js → chunk-ESIQ66Z7.js} +2 -2
  68. package/dist/chunk-EVFUMY4R.js +3 -0
  69. package/dist/{chunk-ZYM4HOFA.js → chunk-F7DY272B.js} +2 -2
  70. package/dist/chunk-FBN2FGXG.js +2 -0
  71. package/dist/{chunk-AZS7YPCB.js → chunk-FDLOBR6P.js} +2 -2
  72. package/dist/chunk-FESCRNVV.js +5 -0
  73. package/dist/{chunk-URSGGIZX.js → chunk-FFRKR4EQ.js} +2 -2
  74. package/dist/chunk-FGA2U4OR.js +8 -0
  75. package/dist/{chunk-7YQOCABQ.js → chunk-FIQRSHVM.js} +2 -2
  76. package/dist/{chunk-KFVSJX25.js → chunk-FPYLNQPT.js} +2 -2
  77. package/dist/{chunk-FELGD32K.js → chunk-FRUSVINH.js} +2 -2
  78. package/dist/chunk-GAS2LJMP.js +3 -0
  79. package/dist/{chunk-OTSPRVNW.js → chunk-GSP44ENC.js} +2 -2
  80. package/dist/{chunk-K3XFWJI2.js → chunk-GUFSG5TX.js} +2 -2
  81. package/dist/chunk-GYIZ4NXB.js +2 -0
  82. package/dist/{chunk-2OXVP5U5.js → chunk-GZIUDL6G.js} +2 -2
  83. package/dist/chunk-HCXEQRFF.js +18 -0
  84. package/dist/{chunk-LO5JSW2C.js → chunk-HEHOQQKH.js} +2 -2
  85. package/dist/{chunk-U2N2KE7A.js → chunk-HKGFPJ4T.js} +2 -2
  86. package/dist/chunk-HLZTEXRA.js +2 -0
  87. package/dist/{chunk-EELPBR7E.js → chunk-HOENASQM.js} +2 -2
  88. package/dist/{chunk-VTCIYFEK.js → chunk-HVF5VBG6.js} +2 -2
  89. package/dist/{chunk-TH6IC56G.js → chunk-HYO3NP5Q.js} +2 -2
  90. package/dist/{chunk-OPSAW5DT.js → chunk-I55I7XXP.js} +2 -2
  91. package/dist/{chunk-DEAB5TGT.js → chunk-IDFEUFKS.js} +2 -2
  92. package/dist/{chunk-DJAO2OZJ.js → chunk-IHGQTTVW.js} +2 -2
  93. package/dist/{chunk-XU75YQN4.js → chunk-IICPE7B2.js} +2 -2
  94. package/dist/{chunk-GY7CCCEZ.js → chunk-IL676XCC.js} +2 -2
  95. package/dist/{chunk-4HE7MVWD.js → chunk-ILTDAWEF.js} +2 -2
  96. package/dist/chunk-IZDPJ2QI.js +2 -0
  97. package/dist/{chunk-5YRQIE2B.js → chunk-J66VOFW6.js} +2 -2
  98. package/dist/{chunk-SB25YMEQ.js → chunk-JFMEXGFE.js} +2 -2
  99. package/dist/{chunk-QLBSG7U5.js → chunk-JGKUET5J.js} +2 -2
  100. package/dist/{chunk-VZ7NXSHV.js → chunk-JS4PGXMV.js} +2 -2
  101. package/dist/{chunk-ZAZGGSM3.js → chunk-JTQVMR42.js} +2 -2
  102. package/dist/chunk-JWTGMPIT.js +80 -0
  103. package/dist/{chunk-5ZMBRQFC.js → chunk-JYR66JN5.js} +2 -2
  104. package/dist/chunk-KLFEXGQA.js +2 -0
  105. package/dist/chunk-KYSDI3GE.js +5 -0
  106. package/dist/{chunk-MSR2QRUE.js → chunk-L6PJPETJ.js} +2 -2
  107. package/dist/{chunk-VU6LIWHT.js → chunk-LDVT66YM.js} +2 -2
  108. package/dist/chunk-LEECKFCJ.js +2 -0
  109. package/dist/{chunk-H7CG6LOE.js → chunk-LMZ5PRUV.js} +2 -2
  110. package/dist/{chunk-ZPASRBLF.js → chunk-LQRQN2XA.js} +2 -2
  111. package/dist/{chunk-HISEUIL2.js → chunk-LXABEJX3.js} +2 -2
  112. package/dist/{chunk-WHADK6OS.js → chunk-M2O5NY6W.js} +2 -2
  113. package/dist/{chunk-Y334QQU5.js → chunk-MNV5FSBW.js} +2 -2
  114. package/dist/{chunk-RYOYJMGF.js → chunk-MPQ4OTBM.js} +2 -2
  115. package/dist/{chunk-6NC3YSPY.js → chunk-MV3CDXPI.js} +2 -2
  116. package/dist/{chunk-NRBNAECH.js → chunk-MWN53KRN.js} +2 -2
  117. package/dist/chunk-N2ZSIIGR.js +117 -0
  118. package/dist/chunk-N5B2NILC.js +5 -0
  119. package/dist/{chunk-Q6T2CAJL.js → chunk-NJITK2GP.js} +2 -2
  120. package/dist/{chunk-ENWQWA2R.js → chunk-NOGJXYFO.js} +2 -2
  121. package/dist/{chunk-V4NG5OMS.js → chunk-NOYBFVJA.js} +106 -106
  122. package/dist/chunk-NWQXSFFU.js +3 -0
  123. package/dist/chunk-ODDUPDP7.js +13 -0
  124. package/dist/{chunk-A77SCPW2.js → chunk-OLIWTZI3.js} +2 -2
  125. package/dist/{chunk-XFMVKFSF.js → chunk-OLNV6I6U.js} +2 -2
  126. package/dist/{chunk-QKT4UI2Y.js → chunk-OR2E3AGZ.js} +2 -2
  127. package/dist/chunk-OSR2GEHQ.js +2 -0
  128. package/dist/{chunk-5H5WTJSD.js → chunk-OSSESPDX.js} +2 -2
  129. package/dist/{chunk-KQHJEU6V.js → chunk-OWOOWNJ5.js} +2 -2
  130. package/dist/{chunk-GRX7JOXQ.js → chunk-P42EIXTA.js} +2 -2
  131. package/dist/{chunk-AQ2PORIO.js → chunk-PJFGPYTU.js} +2 -2
  132. package/dist/{chunk-LRI5OMPE.js → chunk-PP7KNN7L.js} +2 -2
  133. package/dist/{chunk-PLJUQFQN.js → chunk-PU7T5QYQ.js} +2 -2
  134. package/dist/{chunk-JUN5DOAK.js → chunk-PWWAJSKV.js} +2 -2
  135. package/dist/{chunk-7IQXARSQ.js → chunk-PZL5T7SU.js} +2 -2
  136. package/dist/{chunk-UAQ4T73O.js → chunk-QBE3YX64.js} +2 -2
  137. package/dist/{chunk-3TJY6M3B.js → chunk-QGVTFRY2.js} +2 -2
  138. package/dist/chunk-QOJONDS7.js +2 -0
  139. package/dist/chunk-QU5XRYB5.js +4 -0
  140. package/dist/{chunk-2KVU55CW.js → chunk-QUU5OBVK.js} +2 -2
  141. package/dist/{chunk-Q5TA4OY4.js → chunk-RBLQNW26.js} +2 -2
  142. package/dist/chunk-RTQ7NEKG.js +81 -0
  143. package/dist/{chunk-F24QUEQP.js → chunk-SQXRS7BG.js} +2 -2
  144. package/dist/chunk-SSK6LDPC.js +2 -0
  145. package/dist/chunk-SZHGTCPP.js +7 -0
  146. package/dist/chunk-T4N4P2K5.js +16 -0
  147. package/dist/chunk-TA3QKLLU.js +2 -0
  148. package/dist/chunk-TEBQMNVI.js +43 -0
  149. package/dist/{chunk-NK3JMP22.js → chunk-TPFHAQ2G.js} +2 -2
  150. package/dist/chunk-TQPCBMWT.js +5 -0
  151. package/dist/{chunk-HG722PO7.js → chunk-TRNAEQ6P.js} +2 -2
  152. package/dist/chunk-TY7CRN3Z.js +2 -0
  153. package/dist/{chunk-7XA3OM44.js → chunk-UHFYCMZO.js} +2 -2
  154. package/dist/{chunk-ARVO6TTW.js → chunk-UICY4GTQ.js} +2 -2
  155. package/dist/{chunk-SWK4XPUS.js → chunk-UVGEWT4Y.js} +2 -2
  156. package/dist/{chunk-GIQ6CSL4.js → chunk-UXW33INU.js} +2 -2
  157. package/dist/{chunk-RDULNRSJ.js → chunk-VMPRET3I.js} +2 -2
  158. package/dist/{chunk-I6UTXNHU.js → chunk-VNLGKHS6.js} +2 -2
  159. package/dist/{chunk-44T4DUAA.js → chunk-VQILFTEH.js} +2 -2
  160. package/dist/{chunk-N7FP5H5U.js → chunk-VUPHCS7Y.js} +8 -8
  161. package/dist/{chunk-JAT6C3VX.js → chunk-VVZSBTSU.js} +2 -2
  162. package/dist/{chunk-FBCVASUG.js → chunk-VZRNID6A.js} +2 -2
  163. package/dist/{chunk-TUQIPUDS.js → chunk-W5OXRYGE.js} +2 -2
  164. package/dist/chunk-W6STWDQI.js +57 -0
  165. package/dist/chunk-W7CXK74K.js +2 -0
  166. package/dist/chunk-WB3WYIRE.js +4 -0
  167. package/dist/{chunk-C76O5MDS.js → chunk-WDNVY4E7.js} +2 -2
  168. package/dist/{chunk-TAYD3AE7.js → chunk-WIWY3CRX.js} +2 -2
  169. package/dist/chunk-WK46TNUM.js +3 -0
  170. package/dist/chunk-WNTFFKAX.js +12 -0
  171. package/dist/{chunk-JFQBRL3J.js → chunk-WOIKCX6A.js} +2 -2
  172. package/dist/{chunk-PIFTZEEM.js → chunk-WUN6KBHV.js} +2 -2
  173. package/dist/chunk-WYCTJDVR.js +2 -0
  174. package/dist/chunk-WYPL7GF7.js +2 -0
  175. package/dist/{chunk-XN22RGSR.js → chunk-XBGWL66K.js} +2 -2
  176. package/dist/{chunk-R6M456QG.js → chunk-XDQMU3BT.js} +2 -2
  177. package/dist/{chunk-XJX6LGHL.js → chunk-XFA4SSO3.js} +2 -2
  178. package/dist/{chunk-2YC7YNKT.js → chunk-XGZEP6GR.js} +2 -2
  179. package/dist/chunk-XPDPNWTQ.js +368 -0
  180. package/dist/chunk-XRYABF57.js +8 -0
  181. package/dist/{chunk-YIHNPKWD.js → chunk-YBGKCQIS.js} +2 -2
  182. package/dist/{chunk-2XCGSDIT.js → chunk-YEN6CYC7.js} +2 -2
  183. package/dist/{chunk-VMWUV6WB.js → chunk-YF5IB2LF.js} +2 -2
  184. package/dist/{chunk-TNG2FYS5.js → chunk-YI2AWIHC.js} +2 -2
  185. package/dist/{chunk-EELG7D3Q.js → chunk-YPWBKGFU.js} +2 -2
  186. package/dist/{chunk-GQIDEID3.js → chunk-YPWHBBIS.js} +2 -2
  187. package/dist/{chunk-TKDNDQA7.js → chunk-YSH6U3L4.js} +2 -2
  188. package/dist/{chunk-BUTEIZKP.js → chunk-YU5DZUZI.js} +2 -2
  189. package/dist/chunk-YWO5DDRC.js +16 -0
  190. package/dist/{chunk-6HRZQLOI.js → chunk-Z4CDXYNQ.js} +2 -2
  191. package/dist/{chunk-XSWYJCAK.js → chunk-ZF5KHH7C.js} +2 -2
  192. package/dist/chunk-ZOHS7AQV.js +21 -0
  193. package/dist/{chunk-7U2YQSDE.js → chunk-ZTI4SBFV.js} +2 -2
  194. package/dist/cli-main.js +2 -2
  195. package/dist/code-MI6F2TTU.js +2 -0
  196. package/dist/code-result-json-FXALY4HE.js +2 -0
  197. package/dist/{command-descriptors-ORNTVNYV.js → command-descriptors-P34VABY5.js} +136 -135
  198. package/dist/dataflow-4KEMJPC6.js +2 -0
  199. package/dist/dependence-slice-R7FPWD5M.js +2 -0
  200. package/dist/deps-7EMQUYUT.js +2 -0
  201. package/dist/direct-navigation-6YO234F2.js +3 -0
  202. package/dist/entry-map-KOOLR26E.js +2 -0
  203. package/dist/files-OPIPJIGZ.js +2 -0
  204. package/dist/hierarchy-QPD2CAER.js +2 -0
  205. package/dist/imports-M6HUXRXC.js +2 -0
  206. package/dist/index.js +1 -1
  207. package/dist/members-I5MEFOCT.js +2 -0
  208. package/dist/methods-5JYGGHXA.js +2 -0
  209. package/dist/output-continuation-command-UPQAAKBP.js +3 -0
  210. package/dist/postinstall.js +1 -1
  211. package/dist/project-reindex-UKKQ5PLS.js +3 -0
  212. package/dist/queries/affected.js +1 -1
  213. package/dist/queries/anchors.js +1 -1
  214. package/dist/queries/architecture.js +1 -1
  215. package/dist/queries/bottlenecks.js +1 -1
  216. package/dist/queries/by-kind.js +1 -1
  217. package/dist/queries/call-graph.js +1 -1
  218. package/dist/queries/change-surface.js +1 -1
  219. package/dist/queries/cleanup-plan.js +1 -1
  220. package/dist/queries/co-change.js +1 -1
  221. package/dist/queries/code.js +1 -1
  222. package/dist/queries/complexity-hotspots.js +1 -1
  223. package/dist/queries/complexity.js +1 -1
  224. package/dist/queries/context.js +1 -1
  225. package/dist/queries/convergence.js +1 -1
  226. package/dist/queries/coupling.js +1 -1
  227. package/dist/queries/cycles.js +1 -1
  228. package/dist/queries/dataflow.js +1 -1
  229. package/dist/queries/dead.js +1 -1
  230. package/dist/queries/decorative-checkers.js +1 -1
  231. package/dist/queries/deep-chains.js +1 -1
  232. package/dist/queries/dependence-slice.js +1 -1
  233. package/dist/queries/dependency-depth.js +1 -1
  234. package/dist/queries/deps.js +1 -1
  235. package/dist/queries/diff-impact.d.ts +9 -0
  236. package/dist/queries/diff-impact.js +1 -1
  237. package/dist/queries/doc-drift.js +1 -1
  238. package/dist/queries/drift.js +1 -1
  239. package/dist/queries/duplicate-bodies.js +1 -1
  240. package/dist/queries/entry-map.js +1 -1
  241. package/dist/queries/evidence.js +1 -1
  242. package/dist/queries/extract-candidates.js +1 -1
  243. package/dist/queries/fan.js +1 -1
  244. package/dist/queries/files.js +1 -1
  245. package/dist/queries/health.js +1 -1
  246. package/dist/queries/hierarchy.js +1 -1
  247. package/dist/queries/hotspots.js +1 -1
  248. package/dist/queries/imports.js +1 -1
  249. package/dist/queries/incomplete-migration.js +1 -1
  250. package/dist/queries/index.js +1 -1
  251. package/dist/queries/isolated.js +1 -1
  252. package/dist/queries/locality-candidates.js +1 -1
  253. package/dist/queries/members.js +1 -1
  254. package/dist/queries/methods.js +1 -1
  255. package/dist/queries/not-implemented.js +1 -1
  256. package/dist/queries/outline.js +1 -1
  257. package/dist/queries/passthrough-candidates.js +1 -1
  258. package/dist/queries/plan-context.js +1 -1
  259. package/dist/queries/react-component-duplicates.js +1 -1
  260. package/dist/queries/react-hook-candidates.js +1 -1
  261. package/dist/queries/react-large-component-pressure.js +1 -1
  262. package/dist/queries/recent-duplicates.js +1 -1
  263. package/dist/queries/redundant-reexports.js +1 -1
  264. package/dist/queries/reference-neighborhood.js +1 -1
  265. package/dist/queries/reference-reachability.js +1 -1
  266. package/dist/queries/refs.js +1 -1
  267. package/dist/queries/self-audit.js +1 -1
  268. package/dist/queries/similar-chains.js +1 -1
  269. package/dist/queries/similar-files.js +1 -1
  270. package/dist/queries/similar-signatures.js +1 -1
  271. package/dist/queries/similar.js +1 -1
  272. package/dist/queries/slice.js +1 -1
  273. package/dist/queries/source-inspection.js +1 -1
  274. package/dist/queries/source-search.js +1 -1
  275. package/dist/queries/stale-abstractions.js +1 -1
  276. package/dist/queries/surface.js +1 -1
  277. package/dist/queries/symbols.js +1 -1
  278. package/dist/queries/system-map.js +1 -1
  279. package/dist/queries/system.js +1 -1
  280. package/dist/queries/test-quality.js +1 -1
  281. package/dist/queries/trace.js +1 -1
  282. package/dist/queries/twin-ab.js +1 -1
  283. package/dist/queries/twin-drift.js +1 -1
  284. package/dist/queries/unused-imports.js +1 -1
  285. package/dist/queries/unused-params.js +1 -1
  286. package/dist/queries/value-flow.js +1 -1
  287. package/dist/queries/vue-component-duplicates.js +1 -1
  288. package/dist/queries/vue-composable-candidates.js +1 -1
  289. package/dist/queries/vue-large-view-pressure.js +1 -1
  290. package/dist/queries/wrapper-candidates.js +1 -1
  291. package/dist/query-service-server.js +3 -3
  292. package/dist/refs-PSU4JZZW.js +2 -0
  293. package/dist/refs-pagination-JG6CJMRC.js +2 -0
  294. package/dist/reindex-worker.js +25 -25
  295. package/dist/reindex.d.ts +3 -2
  296. package/dist/reindex.js +35 -35
  297. package/dist/runtime.d.ts +34 -2
  298. package/dist/runtime.js +4 -4
  299. package/dist/rust-semantic-session-server.js +1 -1
  300. package/dist/rust-semantic-session-worker.js +1 -1
  301. package/dist/rust-semantic-worker.js +1 -1
  302. package/dist/{scip-cli-H-n59izO.d.ts → scip-cli-DOerTq-R.d.ts} +42 -4
  303. package/dist/slice-HYRATV64.js +2 -0
  304. package/dist/surface-VTGDYWF5.js +2 -0
  305. package/dist/symbol-resolution-WD5EU5JE.js +2 -0
  306. package/dist/system-LRQNFOR2.js +2 -0
  307. package/dist/trace-F4B6OLL4.js +2 -0
  308. package/dist/typescript-mailbox-worker.js +1 -1
  309. package/dist/value-flow-VRPZY72V.js +2 -0
  310. package/dist/watch-server.js +3 -3
  311. package/package.json +1 -1
  312. package/dist/by-kind-4IYG2SKW.js +0 -2
  313. package/dist/call-graph-WQNXMNNN.js +0 -2
  314. package/dist/chunk-2BTJALUS.js +0 -454
  315. package/dist/chunk-3QXC54FQ.js +0 -3
  316. package/dist/chunk-42W3LFUK.js +0 -13
  317. package/dist/chunk-4GAQ6FI4.js +0 -43
  318. package/dist/chunk-6VEFRPTD.js +0 -5
  319. package/dist/chunk-7C26EKLZ.js +0 -4
  320. package/dist/chunk-7JYHQAH2.js +0 -22
  321. package/dist/chunk-7KSO2OAP.js +0 -2
  322. package/dist/chunk-AK3PYTIK.js +0 -5
  323. package/dist/chunk-AMIMMNA4.js +0 -11
  324. package/dist/chunk-AUY5BL74.js +0 -2
  325. package/dist/chunk-BDHFVH2M.js +0 -18
  326. package/dist/chunk-BECZLYNU.js +0 -8
  327. package/dist/chunk-BYDAFMSR.js +0 -57
  328. package/dist/chunk-BZYSGZRK.js +0 -2
  329. package/dist/chunk-C7IJMOFP.js +0 -134
  330. package/dist/chunk-CBBHFNLX.js +0 -2
  331. package/dist/chunk-D35XIZGN.js +0 -2
  332. package/dist/chunk-DKM723YF.js +0 -79
  333. package/dist/chunk-E44IVWIJ.js +0 -367
  334. package/dist/chunk-EDMB6SSO.js +0 -7
  335. package/dist/chunk-EETGXQY7.js +0 -3
  336. package/dist/chunk-FKGQOTKD.js +0 -2
  337. package/dist/chunk-GH5YSGZL.js +0 -5
  338. package/dist/chunk-HCVJR2V4.js +0 -3
  339. package/dist/chunk-HXOU4XNH.js +0 -3
  340. package/dist/chunk-IMKZEXZG.js +0 -2
  341. package/dist/chunk-ISIQLPJ2.js +0 -61
  342. package/dist/chunk-IXESDH3J.js +0 -2
  343. package/dist/chunk-JT6XX7QY.js +0 -8
  344. package/dist/chunk-MHIEP7EG.js +0 -4
  345. package/dist/chunk-OJNK5ALA.js +0 -2
  346. package/dist/chunk-OXYAWIEA.js +0 -2
  347. package/dist/chunk-OZETODHH.js +0 -2
  348. package/dist/chunk-PBUH2P5S.js +0 -3
  349. package/dist/chunk-PLYUVM4F.js +0 -2
  350. package/dist/chunk-Q7GBK5T7.js +0 -81
  351. package/dist/chunk-QWKHW6VZ.js +0 -2
  352. package/dist/chunk-RPL3ARU7.js +0 -16
  353. package/dist/chunk-SVHTMVA4.js +0 -4
  354. package/dist/chunk-T6QD2ZQB.js +0 -43
  355. package/dist/chunk-TD7VKJ2Y.js +0 -117
  356. package/dist/chunk-TUSPIVZ3.js +0 -4
  357. package/dist/chunk-UT7TADJX.js +0 -2
  358. package/dist/chunk-VUSKPCUB.js +0 -2
  359. package/dist/chunk-WN3TCGJ4.js +0 -2
  360. package/dist/chunk-WSLEJSFR.js +0 -2
  361. package/dist/chunk-WYZIHUPZ.js +0 -16
  362. package/dist/chunk-XE33FV5W.js +0 -2
  363. package/dist/chunk-Z2AWCTN6.js +0 -2
  364. package/dist/chunk-ZOXKSQQB.js +0 -2
  365. package/dist/code-EQJFDT6I.js +0 -2
  366. package/dist/code-result-json-7UWIWBOO.js +0 -2
  367. package/dist/dataflow-6VL54GX5.js +0 -2
  368. package/dist/dependence-slice-DT2NUHD2.js +0 -2
  369. package/dist/deps-DB7H5IKC.js +0 -2
  370. package/dist/direct-navigation-O3LUAYWQ.js +0 -3
  371. package/dist/entry-map-6K62RV3D.js +0 -2
  372. package/dist/files-MSLD7MO6.js +0 -2
  373. package/dist/hierarchy-IVBXAKFA.js +0 -2
  374. package/dist/imports-FRAVZ3Y2.js +0 -2
  375. package/dist/members-KJOJDYGO.js +0 -2
  376. package/dist/methods-2AYABBT3.js +0 -2
  377. package/dist/output-continuation-command-JHMPH6NC.js +0 -3
  378. package/dist/project-reindex-HYO4WD7Z.js +0 -3
  379. package/dist/refs-ARMA6XUJ.js +0 -2
  380. package/dist/refs-pagination-VUGIWN6U.js +0 -2
  381. package/dist/slice-YOB5YFAM.js +0 -2
  382. package/dist/surface-VY5EFWTW.js +0 -2
  383. package/dist/symbol-resolution-DGQN4XIV.js +0 -2
  384. package/dist/system-2KQ3QD2P.js +0 -2
  385. package/dist/trace-HTIPTXAE.js +0 -2
  386. package/dist/value-flow-5FV3VQI7.js +0 -2
@@ -1,367 +0,0 @@
1
- #!/usr/bin/env node
2
- import{$e as ii,Aa as qt,Ad as Y,Bd as C,Be as qr,C as Xe,De as Kt,Ea as z,Ee as V,Fa as Ht,Fe as Hr,Ge as Qt,Ha as Re,Hd as nt,He as ot,Ia as re,Id as Lr,Ie as Jr,Ja as Qe,Jd as Me,Je as zr,Ka as gr,Ke as Yr,La as Jt,Ld as Or,Le as Xr,M as rr,Ma as fr,Me as Kr,N as ne,Nd as Ne,Ne as ae,O as be,Od as rt,Oe as se,P as Se,Pd as Dr,Pe as at,Q as ir,Qe as Qr,R as or,Re as Zr,S as Gt,Sa as mr,Se as ei,Te as ti,U as Ke,Ue as ni,Va as zt,Vb as Sr,Ve as ri,Wb as Rr,We as st,Xa as hr,Yd as Mr,Ye as X,Zd as Nr,Ze as ct,_d as Yt,a as He,ab as Ze,b as tr,be as Ie,bf as Zt,c as Bt,cf as oi,d as nr,df as ai,ef as ut,f as he,g as D,ga as Wt,gb as ie,gc as xr,hb as oe,hc as et,he as jr,hf as si,ib as yr,ic as vr,if as ci,ja as ar,jc as Pr,jf as ui,kc as Ir,l as $t,ld as xe,lf as li,md as Er,mf as di,n as ye,nd as Tr,nf as lt,o as Vt,oa as sr,ob as T,od as ve,p as Je,pb as U,pd as tt,pe as Br,q as ze,qb as br,qd as Oe,qe as $r,r as Ut,rd as wr,re as Vr,s as J,sa as cr,sd as kr,t as j,ta as ur,td as _r,te as Ur,u as $,ua as lr,ud as Cr,ue as Gr,v as Ye,va as dr,vd as Fr,ve as B,xd as Pe,xe as it,ya as pr,yd as Ar,ye as Xt,zd as De,ze as Wr}from"./chunk-2BTJALUS.js";import{createHash as Tp}from"crypto";import{existsSync as N,mkdirSync as At,mkdtempSync as wp,readdirSync as Ka,renameSync as Qa,rmSync as de,statSync as zn}from"fs";import{basename as Ct,dirname as I,extname as kp,join as L,resolve as $a}from"path";import{platform as _p}from"os";import{execFileSync as pi}from"child_process";import{createRequire as Ss}from"module";import{existsSync as Rs}from"fs";import{platform as je,arch as gi}from"os";var Be="v0.8.1",en="https://github.com/sourcegraph/scip",dt=`github.com/sourcegraph/scip/cmd/scip@${Be}`,fi=Ss(import.meta.url),mi="SCIP_QUERY_SCIP_BIN";function xs(e){if(e.isOnPath("scip"))return{source:"path",path:"scip"};let t=e.env[mi];if(t&&e.fileExists(t))return{source:"env",path:t};if(e.platform==="win32"){let n=e.resolveSidecar(e.arch);if(n&&e.fileExists(n))return{source:"sidecar",path:n}}return null}function vs(e){for(let t of e==="arm64"?["arm64","x64"]:[e])try{return fi.resolve(`scip-query-scip-windows/scip-win32-${t}.exe`)}catch{}return null}function Ee(e=process.env){let t=xs({platform:je(),arch:gi(),env:e,isOnPath:xe,fileExists:Rs,resolveSidecar:vs});return t?.source==="path"?Tr("scip")??t.path:t?.path??null}function Eg(){return Ee()!==null}function Ps(){let e=Ee();if(!e)return null;try{return pi(e,["--version"],{stdio:"pipe",timeout:1e4,killSignal:"SIGKILL"}).toString().trim()}catch{return null}}function Is(){let e=je(),t=gi(),n,r,i;switch(e){case"darwin":n="darwin",i="tar.gz";break;case"linux":n="linux",i="tar.gz";break;default:return null}switch(t){case"arm64":r="arm64";break;case"x64":r="amd64";break;default:return null}let o=`scip-${n}-${r}.${i}`;return{url:`${en}/releases/download/${Be}/${o}`,filename:o}}function Tg(){let e=Is();if(console.log("\nThe `scip` CLI is required but not found on PATH.\n"),je()==="darwin"||je()==="linux")console.log("Install the reviewed version with Go:"),console.log(` go install ${dt}
3
- `),console.log("Or download that exact release manually:");else if(je()==="win32"){let t=Es();console.log("On Windows the scip binary ships via the npm sidecar package scip-query-scip-windows,"),console.log("installed automatically with scip-query. If it is missing:"),console.log(` npm install -g ${t}`),console.log(`Or set ${mi} to a local scip.exe path.
4
- `),console.log("Upstream release page:")}else console.log("Download from:");console.log(e?` ${e.url}
5
- `:` ${en}/releases/tag/${Be}
6
- `),console.log("After installing, ensure `scip` is on your PATH and run `scip-query reindex`.")}function Es(){let t=fi("../../package.json").optionalDependencies?.["scip-query-scip-windows"];if(!t||!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(t))throw new Error("scip-query package metadata does not declare an exact Windows sidecar version.");return`scip-query-scip-windows@${t}`}function hi(e){if(xe("go")){e(`Installing immutable ${dt} via go install into the Go bin directory (GOBIN or GOPATH/bin); expected executable: scip.`);try{if(pi("go",["install",dt],{stdio:"inherit",timeout:3e5,env:process.env}),xe("scip")){let t=Ee(),n=Ps();if(t&&n&&n.includes(Be))return e(`Successfully installed ${dt}; resolved executable: ${t}; reported version: ${n}.`),!0;e(`go install completed, but the resolved scip executable did not report ${Be} (executable: ${t??"unresolved"}; version: ${n??"unavailable"}).`)}}catch(t){let n=t instanceof Error?t.message:String(t);e(`go install failed: ${n}`)}}return e("Could not auto-install scip CLI."),e(`Install manually from: ${en}/releases`),!1}var Te=class extends Error{constructor(t){super(t),this.name="ReindexLockUnavailableError"}};import{execFileSync as Ts}from"child_process";import{constants as ws,copyFileSync as yi,statSync as ks}from"fs";import{platform as _s}from"os";var Cs=Object.freeze({size:e=>ks(e).size,clone:As,copy:(e,t)=>yi(e,t)}),Fs=new Set(["ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL","EXDEV","ENOTTY"]);function ce(e,t,n=Cs){let r=n.size(e);try{return n.clone(e,t),{method:"reflink",bytes:r}}catch(i){if(!Os(i))throw i}return n.copy(e,t),{method:"copy",bytes:r}}function As(e,t){if(_s()!=="darwin"){yi(e,t,ws.COPYFILE_FICLONE_FORCE);return}try{Ts("/bin/cp",["-c",e,t],{timeout:6e4,maxBuffer:64*1024,stdio:["ignore","ignore","pipe"]})}catch(n){throw Ls(n)}}function Ls(e){let t=e?.stderr,n=Buffer.isBuffer(t)?t.toString("utf8"):t??"";return/operation not supported|not supported/i.test(n)?Object.assign(e instanceof Error?e:new Error(String(e)),{code:"ENOTSUP"}):/cross-device link/i.test(n)?Object.assign(e instanceof Error?e:new Error(String(e)),{code:"EXDEV"}):e}function Os(e){let t=e?.code;return t!==void 0&&Fs.has(t)}function bi(){return{reflinkedBytes:0,fallbackCopiedBytes:0,incrementalWrittenBytes:0}}function ue(e,t){t.method==="reflink"?e.reflinkedBytes+=t.bytes:e.fallbackCopiedBytes+=t.bytes}function pt(e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error("incremental write bytes must be a non-negative integer");e.incrementalWrittenBytes=(e.incrementalWrittenBytes??0)+t}import Ds from"better-sqlite3";import{execFileSync as Ms}from"child_process";import{existsSync as Ns,readdirSync as js}from"fs";import{extname as gt,join as Bs}from"path";function le(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Si({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Si(e){let t=new Set((e.extensions??Sr).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Ns(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Hr(e.projectRoot),r=$s(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Ds(e.dbPath);try{let o=Us(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
7
- VALUES (?, ?, NULL, ?)`),c=i.transaction(l=>{let d=0;for(let p of l){if(o.has(p))continue;let f=sr(e.projectRoot,p,{inputKind:"auxiliary source file"}),h=a.run(Gs(p),p,f);d+=Number(h.changes)}return d})(r),u={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${u.existing} already present).`),u}finally{i.close()}}function $s(e,t){let n=Vs(e,t);if(n)return n;let r=[],i=o=>{let a=o?Bs(e,o):e,s;try{s=js(a,{withFileTypes:!0})}catch{return}for(let c of s){if(Rr.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(gt(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function Vs(e,t){try{return Ms("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}).split(`
8
- `).filter(r=>r&&t.has(gt(r).toLowerCase())).sort()}catch{return null}}function Us(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 Gs(e){return gt(e).toLowerCase()===".vue"?"vue":gt(e).replace(/^\./,"").toLowerCase()||"source"}import{dirname as Ws,join as qs}from"path";function Ri(e={}){return{id:"runtime-boundaries",facts:["runtime-boundary-observation","runtime-boundary-link"],run:async({projectRoot:t,dbPath:n,onStatus:r})=>{let i=new V({projectRoot:t,dbPath:n,indexPath:e.indexPath??qs(Ws(n),"index.scip"),...e.evidenceDbPath?{evidenceDbPath:e.evidenceDbPath}:{}}),o,a=!1,s=!1;try{let u=e.reuseExisting||e.affectedFiles?Ur(i):null;e.reuseExisting&&u?.extractorVersion===Br?(o=u,a=!0):(o=await $r(i,{...u?{previousGraph:u}:{},...e.affectedFiles?{affectedFiles:e.affectedFiles}:{},...e.forceDerivedRebuild?{forceDerivedRebuild:!0}:{},profileSpan:T}),s=(o.coverage.filesReused??0)>0)}finally{i.close()}a||Vr(n,o);let c={reused:a,incrementallyUpdated:s,observations:o.observations.length,links:o.links.length,frontiers:o.frontiers.length,filesScanned:o.coverage.filesScanned,errors:o.coverage.extractionErrors.length,phases:o.coverage.phases};return r?.(c.reused?`Reused ${c.observations} cached runtime-boundary observation(s) and ${c.links} link(s).`:c.incrementallyUpdated?`Incrementally refreshed runtime-boundary observations (${c.filesScanned-(o.coverage.filesReused??0)} file(s) extracted, ${o.coverage.filesReused??0} reused) and rebuilt ${c.links} link(s).`:`Extracted ${c.observations} runtime-boundary observation(s), ${c.links} link(s), and ${c.frontiers} unresolved frontier(s).`),!a&&o.coverage.phases&&r?.(`Runtime-boundary phases: ${o.coverage.phases.map(u=>`${u.id} ${u.durationMs.toFixed(0)}ms`).join(", ")}.`),c}}}import{createHash as sc}from"crypto";import{existsSync as cc}from"fs";import{dirname as uc,join as Ti}from"path";function tn(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 $e(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=tn(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"),xi(r,i,a)):a.size>0?xi(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:Hs(r,t,i),reasons:[]}}function xi(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function Hs(e,t,n){let r=new Map;for(let[a,s]of t)if(n.has(a))for(let c of s){if(!n.has(c))continue;let u=r.get(c)??new Set;u.add(a),r.set(c,u)}let i=new Set(e),o=[...e];for(let a=0;a<o.length;a+=1){let s=o[a];if(s!==void 0)for(let c of r.get(s)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}import{appendFileSync as Js,existsSync as zs,mkdirSync as Ys,renameSync as Xs,rmSync as Ks,statSync as Qs,truncateSync as Zs}from"fs";import{basename as ec,dirname as tc}from"path";var we=".previous",nc=".rotation.lock",rc=2e3,nn=class extends Error{constructor(n,r){super(`Timed out after ${r}ms waiting for rotating JSONL lock: ${n}`);this.lockPath=n;this.timeoutMs=r;this.name="RotatingJsonlLockTimeoutError"}lockPath;timeoutMs;code="ROTATING_JSONL_LOCK_TIMEOUT"},rn=class extends Error{constructor(n){super(`Rotating JSONL lock ownership changed before release: ${n}`);this.lockPath=n;this.name="RotatingJsonlLockReleaseError"}lockPath;code="ROTATING_JSONL_LOCK_RELEASE_FAILED"},vi=Object.freeze({monotonicNow:C,wait(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},tryAcquireLock(e,t){let n=it(e,{kind:"rotating-jsonl",detail:{target:ec(t)}});return n.kind==="acquired"?{kind:"acquired",lock:n.lock}:{kind:"contended"}},makeDirectory(e){Ys(e,{recursive:!0})},exists:zs,readBytes(e){return J(e,{maxBytes:ze,inputKind:"rotating JSONL segment"})},size(e){return Qs(e).size},truncate:Zs,remove(e){Ks(e,{force:!0})},rename:Xs,append:Js});function ft(e,t,n){let r=n.runtime??vi,i=JSON.stringify(t);if(i===void 0)throw new TypeError("Rotating JSONL records must be JSON-serializable values.");let o=Buffer.from(`${i}
9
- `),a=Math.max(1,Math.floor(n.maxSegmentBytes),o.length);return Ii(e,n.lockTimeoutMs,r,()=>{r.makeDirectory(tc(e));let s=ic(e,ze,r);n.onPhase?.("tail-repaired");let c=`${e}${n.previousSuffix??we}`,u=!1,l=!1;return r.exists(e)&&r.size(e)+o.length>a&&(r.exists(c)&&(r.remove(c),l=!0),n.onPhase?.("previous-pruned"),r.rename(e,c),u=!0,n.onPhase?.("current-rotated")),r.append(e,o),n.onPhase?.("record-appended"),{lineBytes:o.length,segmentLimitBytes:a,repairedTailBytes:s,rotated:u,prunedPrevious:l}})}function Pi(e,t={}){let n=t.runtime??vi,r=oc(t.maxSegmentBytes);return Ii(e,t.lockTimeoutMs,n,()=>{let i=[],o=0,a=`${e}${t.previousSuffix??we}`;for(let s of[a,e]){if(!n.exists(s))continue;let c=ac(Ei(s,r,n));i.push(...c.lines),o+=c.partialTailBytes}return{lines:i,ignoredPartialTailBytes:o}})}function Ii(e,t,n,r){let i=`${e}${nc}`,o=Math.max(0,t??rc),a=n.monotonicNow()+o,s;for(;;){let p=n.tryAcquireLock(i,e);if(p.kind==="acquired"){s=p.lock;break}let f=a-n.monotonicNow();if(f<=0)throw new nn(i,o);n.wait(Math.min(5,f))}let c=!1,u,l;try{l=r()}catch(p){c=!0,u=p}let d=!1;try{d=s.release()}catch(p){if(!c)throw p}if(c)throw u;if(!d)throw new rn(i);return l}function ic(e,t,n){if(!n.exists(e))return 0;let r=Ei(e,t,n);if(r.length===0||r[r.length-1]===10)return 0;let i=r.lastIndexOf(10),o=i<0?0:i+1;return n.truncate(e,o),r.length-o}function oc(e){let t=e??ze;if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`maxSegmentBytes must be a positive safe integer; received ${t}`);return t}function Ei(e,t,n){let r=n.size(e);if(r>t)throw new Ut("rotating JSONL segment",e,"too-large",r,t);let i=n.readBytes(e),o=n.size(e);if(o!==r||i.byteLength!==r)throw new Ut("rotating JSONL segment",e,"changed-during-read",o,t);return i}function ac(e){let t=e.lastIndexOf(10),n=t<0?0:t+1;return{lines:e.subarray(0,n).toString("utf8").split(`
10
- `).filter(i=>i.length>0),partialTailBytes:e.length-n}}var lc="<global-symbols>";function dc(e){let t=[];for(let n of e.all(`
11
- SELECT relative_path, language, position_encoding, text
12
- FROM documents
13
- `))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
14
- SELECT d.relative_path,
15
- c.chunk_index,
16
- c.start_line,
17
- c.end_line,
18
- hex(c.occurrences) AS occurrences_hex
19
- FROM chunks c
20
- JOIN documents d ON d.id = c.document_id
21
- `))t.push({relativePath:n.relative_path,kind:"chunk",values:[n.chunk_index,n.start_line,n.end_line,n.occurrences_hex]});for(let n of e.all(`
22
- SELECT d.relative_path,
23
- r.start_line,
24
- r.start_char,
25
- r.end_line,
26
- r.end_char,
27
- g.symbol,
28
- g.display_name,
29
- g.kind,
30
- g.documentation,
31
- CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
32
- g.enclosing_symbol,
33
- CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
34
- FROM defn_enclosing_ranges r
35
- JOIN documents d ON d.id = r.document_id
36
- JOIN global_symbols g ON g.id = r.symbol_id
37
- `))t.push({relativePath:n.relative_path,kind:"definition",values:on(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
38
- SELECT d.relative_path,
39
- c.chunk_index,
40
- m.role,
41
- g.symbol,
42
- g.display_name,
43
- g.kind,
44
- g.documentation,
45
- CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
46
- g.enclosing_symbol,
47
- CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
48
- FROM mentions m
49
- JOIN chunks c ON c.id = m.chunk_id
50
- JOIN documents d ON d.id = c.document_id
51
- JOIN global_symbols g ON g.id = m.symbol_id
52
- `))t.push({relativePath:n.relative_path,kind:"mention",values:on(n,[n.chunk_index,n.role])});for(let n of e.all(`
53
- SELECT g.symbol,
54
- g.display_name,
55
- g.kind,
56
- g.documentation,
57
- CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
58
- g.enclosing_symbol,
59
- CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
60
- FROM global_symbols g
61
- WHERE NOT EXISTS (
62
- SELECT 1 FROM defn_enclosing_ranges r WHERE r.symbol_id = g.id
63
- ) AND NOT EXISTS (
64
- SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
65
- )
66
- `))t.push({relativePath:lc,kind:"global-symbol",values:on(n)});return pc(t)}function pc(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=sc("sha256");for(let a of i.sort())o.update(String(Buffer.byteLength(a))),o.update(":"),o.update(a),o.update(`
67
- `);n.set(r,o.digest("hex"))}return n}function gc(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 an(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 sn(e,t=bc){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,i=t.wallNow??t.now,o=r(),a=(u,l)=>{let d=r();return Li(e.refreshResult,u,n?d:i(),Math.max(0,d-o),l)};if(!t.databaseExists(e.previousDbPath))return a("prior-index-unavailable");if(!t.databaseExists(e.candidateDbPath))return a("candidate-index-unavailable");if(e.refreshResult==="rebuilt"&&he(e.previousSnapshot,e.currentSnapshot).changes.length===0)return a("no-input-changes");let s=null,c=null;try{s=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),c=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let u=[...new Set([...t.indexedPaths(s),...t.indexedPaths(c)])].sort(),l=he(e.previousSnapshot,e.currentSnapshot),d=new Set(u),p=l.changes.length>0&&!tn(l).fullProject&&l.changes.every(P=>d.has(P.path)),f=$e(l,p?t.dependencyGraph(s):new Map,u),h=gc(t.factDigests(s),t.factDigests(c)),b=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?b:i()).toISOString(),durationMs:Math.max(0,b-o),manifest:l,plan:f,comparison:h,evaluation:an(f,h,u.length)}}catch(u){return a("oracle-error",u instanceof Error?u.message:String(u))}finally{wi(s),wi(c)}}function Ci(e,t,n,r=Date.now()){return Li(e,t,r,0,n)}function Fi(e){let t=uc(e);return{latestPath:Ti(t,"affected-shadow-latest.json"),historyPath:Ti(t,"affected-shadow.jsonl")}}function gf(e,t=n=>Ye(n,"affected-shadow source file")){let n=Fi(e),r;try{r=JSON.parse(t(n.latestPath))}catch(_){let E=Pc(_),A=E?"telemetry-missing":vc(_);return K(n,A,E?void 0:_ instanceof Error?_.message:String(_))}if(ie(r)&&typeof r.version=="number"&&r.version!==1)return K(n,"unsupported-record-version",`Unsupported version ${r.version}.`);if(!Rc(r))return K(n,"telemetry-malformed");if(r.status==="unavailable")return xc(r.reason)?{state:"unavailable",...n,reason:r.reason,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,...typeof r.error=="string"?{error:r.error}:{}}:K(n,"telemetry-malformed");if(r.status!=="evaluated")return K(n,"telemetry-malformed");let i=r.plan,o=r.comparison,a=r.evaluation;if(!ie(r.manifest)||!ie(i)||!ie(o)||!ie(a))return K(n,"telemetry-malformed");let s=i.mode,c=oe(i.affectedFiles),u=oe(i.reasons),l=oe(o.changedFiles),d=oe(a.predictedFiles),p=oe(a.actualFiles),f=oe(a.missingFiles),h=a.recall,b=a.affectedRatio;if(s!=="none"&&s!=="closure"&&s!=="full-project"||c===null||u===null||l===null||d===null||p===null||f===null||typeof a.passed!="boolean"||!ki(h)||!ki(b))return K(n,"telemetry-malformed");let P=p.length===0?1:(p.length-f.length)/p.length;return!_i(c,d)||!_i(l,p)||a.passed!==(f.length===0)||Math.abs(h-P)>Number.EPSILON||f.some(_=>!p.includes(_)||d.includes(_))?K(n,"telemetry-malformed"):{state:a.passed?"passing":"failing",...n,recordedAt:r.recordedAt,refreshResult:r.refreshResult,durationMs:r.durationMs,mode:s,recall:h,affectedRatio:b,predictedFiles:d,actualFiles:p,missingFiles:f,fallbackReasons:u}}function ff(e){if(e.state==="unavailable")return`unavailable (${e.reason})`;let t=e.missingFiles.length>0?`, ${e.missingFiles.length} missed`:"",n=e.fallbackReasons.length>0?`; fallback: ${e.fallbackReasons.join(", ")}`:"";return`${e.state}, ${(e.recall*100).toFixed(1)}% recall, ${e.predictedFiles.length} predicted / ${e.actualFiles.length} changed, ${(e.affectedRatio*100).toFixed(1)}% of project${t}${n}`}function Ai(e,t,n=Sc){let r=Fi(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var fc=8*1024*1024,mc=we;function hc(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 yc(e,t,n=fc){ft(e,hc(t),{maxSegmentBytes:n,previousSuffix:mc})}function on(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 bc={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:C,databaseExists:e=>cc(e),openDatabase:(e,t,n)=>new V({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>Ze(e),dependencyGraph:e=>xr(e),factDigests:e=>dc(e)},Sc={appendHistory:yc,writeLatest:(e,t)=>nt(e,t,{spacing:2,trailingNewline:!0})};function Li(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 wi(e){try{e?.close()}catch{}}function Rc(e){return ie(e)&&e.version===1&&typeof e.recordedAt=="string"&&(e.refreshResult==="rebuilt"||e.refreshResult==="reused")&&typeof e.durationMs=="number"&&Number.isFinite(e.durationMs)&&e.durationMs>=0}function xc(e){return e==="prior-index-unavailable"||e==="candidate-index-unavailable"||e==="no-input-changes"||e==="oracle-error"}function ki(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function _i(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function K(e,t,n){return{state:"unavailable",...e,reason:t,...n?{error:n}:{}}}function vc(e){return e instanceof SyntaxError?"telemetry-malformed":"telemetry-unreadable"}function Pc(e){return e instanceof Error&&e.code==="ENOENT"}import{readdirSync as Ic}from"fs";import{isAbsolute as Oi,join as Ec,resolve as Tc}from"path";var mt="@sourcegraph/scip-typescript@0.4.0",Di="scip-python-plus@0.7.5",Mi="github.com/sourcegraph/scip-go@v0.2.7",Ni="scip-dotnet@0.2.14",wc="scip_dart@1.6.2",kc={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>r?{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches",r]}:t?{binary:n,args:["index","--pnpm-workspaces","--output",e,"--no-progress-bar","--no-global-caches"]}:{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]},markerFiles:[...D.typescript],installMethods:[{label:"npm",identity:mt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",mt]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]}),markerFiles:[...D.javascript],installMethods:[{label:"npm",identity:mt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",mt]}],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:[...D.java],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...D.scala],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...D.kotlin],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:ve.language,indexerBinary:ve.indexerBinary,checkCommand:`${ve.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:ve.indexerBinary,args:["scip",".","--output",e]}),markerFiles:[...D.rust],installMethods:[],installUrl:ve.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:[...D.python],installMethods:[{label:"npm",identity:Di,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",Di]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",Oi(r)?r:Tc(e,r)),{binary:n,args:i}},markerFiles:[...D.clojure],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:[...D.ruby],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:[...D.go],installMethods:[{label:"go install",identity:Mi,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",Mi]}],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:[...D.cpp],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:[...D.c],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",ji(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...D.csharp],installMethods:[{label:"dotnet",identity:Ni,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",ji(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...D.vb],installMethods:[{label:"dotnet",identity:Ni,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:[...D.dart],installMethods:[{label:"dart pub",identity:wc,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:[...D.php],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Bi(e){if(!(e.projectPath||e.pnpmWorkspaces)){if(e.language==="typescript")return"{}";if(e.language==="javascript")return'{"compilerOptions":{"allowJs":true}}'}}function cn(e){return kc[e]}function ji(e,t){let n;try{n=Ic(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Ec(e,i);return null}import{createHash as _c}from"crypto";import{existsSync as ln,rmSync as $i,statSync as Cc}from"fs";import{resolve as Fc}from"path";import Gi from"better-sqlite3";var Ac={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}]},Lc={idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Wi(e){let t=C(),n=Vi(e.affectedFiles),r=Vi(e.deletedFiles??[],!0),i=new Set(n);if(r.some(s=>!i.has(s)))throw new Error("deleted incremental documents must be included in the affected document set");let o=n.length-r.length;if(Dc(e.previousDbPath,e.miniDbPath,e.candidateDbPath),!ln(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!ln(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");T("reindex.publish.sqlite-patch.validate-inputs",()=>{un(e.previousDbPath,"previous SQLite generation",!1),un(e.miniDbPath,"incremental SQLite mini database")}),e.reuseCandidate?T("reindex.publish.sqlite-patch.reuse-candidate",()=>un(e.candidateDbPath,"incremental SQLite candidate",!1)):T("reindex.publish.sqlite-patch.clone",()=>{$i(e.candidateDbPath,{force:!0});let s=ce(e.previousDbPath,e.candidateDbPath);e.writeTelemetry&&ue(e.writeTelemetry,s)});let a=null;try{a=T("reindex.publish.sqlite-patch.open",()=>{let f=new Gi(e.candidateDbPath,{fileMustExist:!0});return f.pragma("busy_timeout = 5000"),f.pragma("foreign_keys = ON"),f.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),dn(f,"main","candidate SQLite generation"),dn(f,"incremental","incremental SQLite mini database"),f});let{priorAffectedCount:s,previousFactDigests:c}=T("reindex.publish.sqlite-patch.prepare",()=>(jc(a,n,r),{...Bc(a,n.length,r.length),previousFactDigests:pn(a,"main",!0)})),u=Q(a,"SELECT COUNT(*) AS value FROM main.documents"),l=a.transaction(()=>{T("reindex.publish.sqlite-patch.transaction.symbol-ownership",()=>$c(a)),T("reindex.publish.sqlite-patch.transaction.shared-definitions",()=>Vc(a)),T("reindex.publish.sqlite-patch.transaction.delete",()=>Uc(a)),e.onStage?.("after-delete"),T("reindex.publish.sqlite-patch.transaction.reconcile-symbols",()=>Gc(a)),e.onStage?.("after-symbol-reconciliation"),T("reindex.publish.sqlite-patch.transaction.insert",()=>Wc(a)),e.onStage?.("after-insert"),T("reindex.publish.sqlite-patch.transaction.prune-symbols",()=>qc(a,e.trustedPriorGeneration===!0)),T("reindex.publish.sqlite-patch.transaction.validate",()=>Hc(a,o,u,s)),e.onStage?.("before-commit")});T("reindex.publish.sqlite-patch.transaction",()=>l.immediate()),e.writeTelemetry&&pt(e.writeTelemetry,2*Oc(e.candidateDbPath)),T("reindex.publish.sqlite-patch.integrity",()=>Nc(a,"candidate SQLite generation",!e.deferIntegrity&&e.trustedPriorGeneration!==!0));let d=T("reindex.publish.sqlite-patch.validate-facts",()=>Jc(a)),p=[...new Set([...c.keys(),...d.keys()])].filter(f=>c.get(f)!==d.get(f)).sort();return a.exec("DETACH DATABASE incremental"),a.close(),a=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:p,durationMs:C()-t}}catch(s){try{a?.close()}finally{$i(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}function Oc(e){let t=0;for(let n of["-wal","-journal"]){let r=`${e}${n}`;ln(r)&&(t+=Cc(r).size)}return t}function Vi(e,t=!1){if(!t&&e.length===0)throw new Error("incremental SQLite publication requires affected documents");let n=[...e].sort();for(let r of n)if(!r||r.startsWith("/")||r.includes("\\")||r.split("/").includes(".."))throw new Error(`invalid affected document path: ${r}`);if(new Set(n).size!==n.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return n}function Dc(e,t,n){let r=[e,t,n].map(i=>Fc(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function un(e,t,n=!0){let r=new Gi(e,{readonly:!0,fileMustExist:!0});try{dn(r,"main",t),n&&Mc(r,"main",t)}finally{r.close()}}function dn(e,t,n){for(let[r,i]of Object.entries(Ac)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:l})=>({name:s,type:c.toUpperCase(),notnull:u,pk:l}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(Lc)){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}`)}Ui(e,t,"documents",["relative_path"],n),Ui(e,t,"global_symbols",["symbol"],n)}function Ui(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 Mc(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 Nc(e,t,n){if(e.pragma("foreign_keys",{simple:!0})!==1)throw new Error(`${t} lost foreign-key enforcement`);if(!n)return;let r=e.prepare("PRAGMA main.quick_check").pluck().get();if(r!=="ok")throw new Error(`${t} failed quick_check: ${String(r)}`)}function jc(e,t,n){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID"),e.exec("CREATE TEMP TABLE incremental_deleted_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let r=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)"),i=e.prepare("INSERT INTO temp.incremental_deleted_paths(relative_path) VALUES (?)");e.transaction(a=>{for(let s of a)r.run(s);for(let s of n)i.run(s)})(t)}function Bc(e,t,n){let r=Q(e,"SELECT COUNT(*) AS value FROM incremental.documents"),i=Q(e,`SELECT COUNT(*) AS value
68
- FROM main.documents d
69
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),o=e.prepare(`SELECT p.relative_path
70
- FROM temp.incremental_affected_paths p
71
- LEFT JOIN incremental.documents d ON d.relative_path = p.relative_path
72
- LEFT JOIN temp.incremental_deleted_paths deleted ON deleted.relative_path = p.relative_path
73
- WHERE d.id IS NULL AND deleted.relative_path IS NULL
74
- LIMIT 1`).pluck().get(),a=e.prepare(`SELECT d.relative_path
75
- FROM incremental.documents d
76
- LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
77
- WHERE p.relative_path IS NULL
78
- LIMIT 1`).pluck().get(),s=e.prepare(`SELECT d.relative_path
79
- FROM incremental.documents d
80
- JOIN temp.incremental_deleted_paths deleted ON deleted.relative_path = d.relative_path
81
- LIMIT 1`).pluck().get();if(r!==t-n||o!==void 0||a!==void 0||s!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set");return{priorAffectedCount:i}}function $c(e){e.exec(`
82
- CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
83
- INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
84
- SELECT g.symbol
85
- FROM temp.incremental_affected_paths p
86
- CROSS JOIN main.documents d ON d.relative_path = p.relative_path
87
- CROSS JOIN main.defn_enclosing_ranges r ON r.document_id = d.id
88
- CROSS JOIN main.global_symbols g ON g.id = r.symbol_id;
89
- INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
90
- SELECT g.symbol
91
- FROM temp.incremental_affected_paths p
92
- CROSS JOIN main.documents d ON d.relative_path = p.relative_path
93
- CROSS JOIN main.chunks c ON c.document_id = d.id
94
- CROSS JOIN main.mentions m ON m.chunk_id = c.id
95
- CROSS JOIN main.global_symbols g ON g.id = m.symbol_id
96
- WHERE m.role = 1;
97
-
98
- CREATE TEMP TABLE incremental_new_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
99
- INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
100
- SELECT g.symbol
101
- FROM incremental.defn_enclosing_ranges r
102
- JOIN incremental.global_symbols g ON g.id = r.symbol_id;
103
- INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
104
- SELECT g.symbol
105
- FROM incremental.mentions m
106
- JOIN incremental.global_symbols g ON g.id = m.symbol_id
107
- WHERE m.role = 1;
108
-
109
- CREATE TEMP TABLE incremental_touched_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
110
- INSERT OR IGNORE INTO temp.incremental_touched_symbols(symbol)
111
- SELECT symbol FROM temp.incremental_old_defined_symbols;
112
- INSERT OR IGNORE INTO temp.incremental_touched_symbols(symbol)
113
- SELECT g.symbol
114
- FROM temp.incremental_affected_paths p
115
- CROSS JOIN main.documents d ON d.relative_path = p.relative_path
116
- CROSS JOIN main.chunks c ON c.document_id = d.id
117
- CROSS JOIN main.mentions m ON m.chunk_id = c.id
118
- CROSS JOIN main.global_symbols g ON g.id = m.symbol_id;
119
- INSERT OR IGNORE INTO temp.incremental_touched_symbols(symbol)
120
- SELECT symbol FROM incremental.global_symbols;
121
- `)}function Vc(e){let t=e.prepare(`WITH changed_symbols AS (
122
- SELECT symbol FROM temp.incremental_old_defined_symbols
123
- UNION
124
- SELECT symbol FROM temp.incremental_new_defined_symbols
125
- )
126
- SELECT c.symbol
127
- FROM changed_symbols c
128
- CROSS JOIN main.global_symbols g ON g.symbol = c.symbol
129
- WHERE EXISTS (
130
- SELECT 1
131
- FROM main.defn_enclosing_ranges r
132
- JOIN main.documents d ON d.id = r.document_id
133
- LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
134
- WHERE r.symbol_id = g.id AND p.relative_path IS NULL
135
- ) OR EXISTS (
136
- SELECT 1
137
- FROM main.mentions m
138
- JOIN main.chunks chunk ON chunk.id = m.chunk_id
139
- JOIN main.documents d ON d.id = chunk.document_id
140
- LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
141
- WHERE m.symbol_id = g.id AND m.role = 1 AND p.relative_path IS NULL
142
- )
143
- LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function Uc(e){e.exec(`
144
- DELETE FROM main.mentions
145
- WHERE chunk_id IN (
146
- SELECT c.id
147
- FROM main.chunks c
148
- JOIN main.documents d ON d.id = c.document_id
149
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
150
- );
151
- DELETE FROM main.chunks
152
- WHERE document_id IN (
153
- SELECT d.id
154
- FROM main.documents d
155
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
156
- );
157
- DELETE FROM main.defn_enclosing_ranges
158
- WHERE document_id IN (
159
- SELECT d.id
160
- FROM main.documents d
161
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
162
- );
163
- DELETE FROM main.documents
164
- WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
165
- `)}function Gc(e){e.exec(`
166
- UPDATE main.global_symbols
167
- SET display_name = NULL,
168
- kind = NULL,
169
- documentation = NULL,
170
- signature = NULL,
171
- enclosing_symbol = NULL,
172
- relationships = NULL
173
- WHERE symbol IN (SELECT symbol FROM temp.incremental_old_defined_symbols);
174
-
175
- INSERT OR IGNORE INTO main.global_symbols(
176
- symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
177
- )
178
- SELECT symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
179
- FROM incremental.global_symbols;
180
-
181
- UPDATE main.global_symbols
182
- SET display_name = (
183
- SELECT source.display_name FROM incremental.global_symbols source
184
- WHERE source.symbol = main.global_symbols.symbol
185
- ),
186
- kind = (
187
- SELECT source.kind FROM incremental.global_symbols source
188
- WHERE source.symbol = main.global_symbols.symbol
189
- ),
190
- documentation = (
191
- SELECT source.documentation FROM incremental.global_symbols source
192
- WHERE source.symbol = main.global_symbols.symbol
193
- ),
194
- signature = (
195
- SELECT source.signature FROM incremental.global_symbols source
196
- WHERE source.symbol = main.global_symbols.symbol
197
- ),
198
- enclosing_symbol = (
199
- SELECT source.enclosing_symbol FROM incremental.global_symbols source
200
- WHERE source.symbol = main.global_symbols.symbol
201
- ),
202
- relationships = (
203
- SELECT source.relationships FROM incremental.global_symbols source
204
- WHERE source.symbol = main.global_symbols.symbol
205
- )
206
- WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
207
- `)}function Wc(e){let t=Q(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=Q(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=Q(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
208
- SELECT id + ?, language, relative_path, position_encoding, text
209
- FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
210
- SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
211
- FROM incremental.chunks`).run(n,t),e.prepare(`INSERT INTO main.mentions(chunk_id, symbol_id, role)
212
- SELECT m.chunk_id + ?, target.id, m.role
213
- FROM incremental.mentions m
214
- CROSS JOIN incremental.global_symbols source ON source.id = m.symbol_id
215
- CROSS JOIN main.global_symbols target ON target.symbol = source.symbol`).run(n),e.prepare(`INSERT INTO main.defn_enclosing_ranges(
216
- id, document_id, symbol_id, start_line, start_char, end_line, end_char
217
- )
218
- SELECT r.id + ?, r.document_id + ?, target.id,
219
- r.start_line, r.start_char, r.end_line, r.end_char
220
- FROM incremental.defn_enclosing_ranges r
221
- CROSS JOIN incremental.global_symbols source ON source.id = r.symbol_id
222
- CROSS JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function qc(e,t){let n=t?"symbol IN (SELECT symbol FROM temp.incremental_touched_symbols) AND":"";e.exec(`
223
- DELETE FROM main.global_symbols
224
- WHERE ${n}
225
- NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
226
- AND NOT EXISTS (
227
- SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
228
- );
229
- `)}function Hc(e,t,n,r){let i=Q(e,"SELECT COUNT(*) AS value FROM main.documents"),o=Q(e,`SELECT COUNT(*) AS value
230
- FROM main.documents d
231
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),a=n-r+t;if(i!==a||o!==t)throw new Error("candidate SQLite document counts changed unexpectedly")}function Jc(e){let t=pn(e,"main",!0),n=pn(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 pn(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
232
- FROM ${t}.documents d
233
- ${r}
234
- ORDER BY d.relative_path`).all(),o=e.prepare(`SELECT d.relative_path, c.chunk_index, c.start_line, c.end_line, hex(c.occurrences) AS occurrences
235
- FROM ${t}.chunks c
236
- JOIN ${t}.documents d ON d.id = c.document_id
237
- ${r}
238
- ORDER BY d.relative_path, c.chunk_index, c.start_line, c.end_line, c.id`).all(),a=e.prepare(`SELECT d.relative_path, r.start_line, r.start_char, r.end_line, r.end_char,
239
- g.symbol, g.display_name, g.kind, g.documentation,
240
- CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature,
241
- g.enclosing_symbol,
242
- CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships
243
- FROM ${t}.defn_enclosing_ranges r
244
- JOIN ${t}.documents d ON d.id = r.document_id
245
- JOIN ${t}.global_symbols g ON g.id = r.symbol_id
246
- ${r}
247
- ORDER BY d.relative_path, r.start_line, r.start_char, r.end_line, r.end_char, g.symbol`).all(),s=e.prepare(`SELECT d.relative_path, c.chunk_index, m.role, g.symbol
248
- FROM ${t}.mentions m
249
- JOIN ${t}.chunks c ON c.id = m.chunk_id
250
- JOIN ${t}.documents d ON d.id = c.document_id
251
- JOIN ${t}.global_symbols g ON g.id = m.symbol_id
252
- ${r}
253
- ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[l,d]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let p of d){let f=JSON.stringify([l,p]),h=c.get(p.relative_path)??[];h.push(f),c.set(p.relative_path,h)}let u=new Map;for(let[l,d]of[...c].sort(([p],[f])=>p.localeCompare(f))){let p=_c("sha256");for(let f of d.sort())p.update(f).update(`
254
- `);u.set(l,p.digest("hex"))}return u}function Q(e,t){return e.prepare(t).get().value}import zc from"better-sqlite3";var ht="idx_mentions_definitions",Yc=["symbol_id","chunk_id"];function gn(e,t={}){let n=new zc(e),r=[],i=[],o=[];try{return n.transaction(()=>{Xc(n,r),yt(n,"idx_global_symbols_symbol")?.join("\0")==="symbol"&&qi(n,"global_symbols").some(c=>c.name!=="idx_global_symbols_symbol"&&c.unique&&c.columns.join("\0")==="symbol")?(n.exec('DROP INDEX "idx_global_symbols_symbol"'),i.push("idx_global_symbols_symbol")):yt(n,"idx_global_symbols_symbol")&&o.push("idx_global_symbols_symbol");let a=yt(n,"idx_chunks_doc_id"),s=qi(n,"chunks").some(c=>c.name!=="idx_chunks_doc_id"&&c.columns.length>1&&c.columns[0]==="document_id");a?.join("\0")==="document_id"&&s?(n.exec('DROP INDEX "idx_chunks_doc_id"'),i.push("idx_chunks_doc_id")):a&&o.push("idx_chunks_doc_id"),t.analyze!==!1&&n.exec("ANALYZE")})(),{added:r,removed:i,retained:o,analyzed:t.analyze!==!1}}catch(a){if(a.code==="SQLITE_NOTADB")return{added:[],removed:[],retained:[],analyzed:!1,skippedReason:"not-a-sqlite-database"};throw a}finally{n.close()}}function Xc(e,t){let n=Hi(e,ht);if(n){let r=n.columns.join("\0")===Yc.join("\0"),i=/\bWHERE\s+role\s*=\s*1\b/iu.test(n.sql??"");if(!r||!i||n.table!=="mentions")throw new Error(`${ht} exists with an incompatible definition`);return}e.exec(`CREATE INDEX "${ht}" ON mentions(symbol_id, chunk_id) WHERE role = 1`),t.push(ht)}function qi(e,t){return e.prepare(`PRAGMA index_list('${t.replaceAll("'","''")}')`).all().map(n=>({name:n.name,unique:n.unique===1,columns:yt(e,n.name)??[]}))}function yt(e,t){return Hi(e,t)?.columns??null}function Hi(e,t){let n=e.prepare("SELECT tbl_name, sql FROM sqlite_master WHERE type = 'index' AND name = ?").get(t);if(!n)return null;let r=e.prepare(`PRAGMA index_info('${t.replaceAll("'","''")}')`).all().map(i=>i.name);return{table:n.tbl_name,sql:n.sql,columns:r}}import{writeFileSync as Kc}from"fs";function ke(e,t){let n=performance.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}async function zi(e,t){let n=performance.now(),r=await e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}async function Yi(e){let t=e.readFingerprint(),n=Qc(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=await e.compute();return Zc(e.cachePath,e.readFingerprint(),r),r}function Qc(e,t){try{let n=JSON.parse(j(e,{maxBytes:ye,inputKind:"post-index augmentation cache"}));return Ji(n.fingerprint)===Ji(t)?{result:n.result}:null}catch{return null}}function Zc(e,t,n){Kc(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
255
- `)}function Ji(e){return JSON.stringify(e)}import{existsSync as Xi,statSync as eu}from"fs";import{dirname as eo,join as to}from"path";var tu="reindex-activity.jsonl",bt=we,nu=1024*1024,ru=1440*60*1e3,Ki=e=>$(e,"reindex activity segment");function St(e){return to(eo(e),tu)}function no(e){if(e.reused)return 0;let n=(e.shards?.some(r=>!r.reused&&r.strategy==="incremental")??!1?0:fn(e.indexPath))+fn(e.dbPath);for(let r of e.shards??[]){if(r.reused)continue;let i=r.producedOutputBytes??r.outputBytes;i!==null&&(n+=i)}return n}function iu(e){let t=no(e),n=e.writeTelemetry;return n?Math.max(0,t-n.reflinkedBytes)+n.fallbackCopiedBytes+(n.incrementalWrittenBytes??0):t}function mn(e,t){let n=t.lastRefresh;if(!n)return{state:"failed",reason:"reindex result has no refresh metadata"};let r=no(t);return hn(St(e),{version:1,event:"run",recordedAt:n.completedAt,trigger:n.trigger,result:n.result,durationMs:n.durationMs,estimatedLogicalOutputBytes:r,estimatedWriteBytes:iu(t),reflinkedBytes:t.writeTelemetry?.reflinkedBytes??0,fallbackCopiedBytes:t.writeTelemetry?.fallbackCopiedBytes??0,incrementalWrittenBytes:t.writeTelemetry?.incrementalWrittenBytes??0,byLanguage:du(t)})}function ro(e,t){return hn(St(e),{version:1,event:"run",recordedAt:t.completedAt,trigger:t.trigger,result:"failed",durationMs:t.durationMs,estimatedLogicalOutputBytes:0})}function $f(e,t,n=new Date){return hn(St(e),{version:1,event:"suppressed",recordedAt:n.toISOString(),trigger:t,reason:"completed-index-is-fresh"})}function ou(e,t,n=nu,r){ft(e,t,{maxSegmentBytes:n,previousSuffix:bt,...r?{runtime:r}:{}})}function au(e,t=new Date,n=ru,r=Ki){let i=t.getTime(),o=i-n,a={confidence:"complete",recordsRead:0,invalidRecords:0,skippedRecords:0,readErrors:0,ignoredPartialTailBytes:0,windowStartedAt:new Date(o).toISOString(),windowEndedAt:t.toISOString(),runs:0,rebuilt:0,fullRebuilds:0,reused:0,failed:0,suppressed:0,estimatedLogicalOutputBytes:0,estimatedWriteBytes:0,reflinkedBytes:0,fallbackCopiedBytes:0,languageAttribution:"complete",attributedRuns:0,unattributedRuns:0,invalidLanguageDetails:0,byLanguage:{},byTrigger:{}},s=St(e),c=[];if(r===Ki){if(!Xi(s)&&!Xi(`${s}${bt}`))return a;try{let u=Pi(s,{previousSuffix:bt});c=u.lines,a.ignoredPartialTailBytes=u.ignoredPartialTailBytes}catch{a.readErrors+=1,a.confidence="unavailable"}}else{let u=0;for(let l of[`${s}${bt}`,s])try{c.push(...yu(r(l))),u+=1}catch{a.readErrors+=1}u===0?a.confidence="unavailable":a.readErrors>0&&(a.confidence="partial")}for(let u of c){a.recordsRead+=1;let l=su(u);if(!l){a.invalidRecords+=1,a.confidence!=="unavailable"&&(a.confidence="partial");continue}let{record:d}=l,p=Date.parse(d.recordedAt);if(p<o||p>i){a.skippedRecords+=1;continue}if(a.invalidLanguageDetails=(a.invalidLanguageDetails??0)+l.invalidLanguageDetails,a.byTrigger[d.trigger.kind]=(a.byTrigger[d.trigger.kind]??0)+1,d.event==="suppressed"){a.suppressed+=1;continue}a.runs+=1,a[d.result]+=1,a.estimatedLogicalOutputBytes+=d.estimatedLogicalOutputBytes;let f=cu(d);a.estimatedWriteBytes=(a.estimatedWriteBytes??0)+f,a.reflinkedBytes=(a.reflinkedBytes??0)+(d.reflinkedBytes??0),a.fallbackCopiedBytes=(a.fallbackCopiedBytes??0)+(d.fallbackCopiedBytes??0),d.result!=="failed"&&(l.hasLanguageDetails?a.attributedRuns=(a.attributedRuns??0)+1:a.unattributedRuns=(a.unattributedRuns??0)+1);for(let[h,b]of io(d.byLanguage)){let P=(a.byLanguage??={})[h]??=mu();P.runs+=1,P[b.result]+=1,P.producedOutputBytes+=b.producedOutputBytes,P.durationMs+=b.durationMs}Qi(d)&&a.oldestRebuildAt===void 0&&(a.oldestRebuildAt=d.recordedAt),Qi(d)&&(a.fullRebuilds=(a.fullRebuilds??0)+1),f>0&&a.oldestWriteAt===void 0&&(a.oldestWriteAt=d.recordedAt)}return a.ignoredPartialTailBytes>0&&a.confidence!=="unavailable"&&(a.confidence="partial"),a.languageAttribution=hu(a),a}function hn(e,t){try{return ou(e,t),{state:"recorded"}}catch(n){return{state:"failed",reason:n instanceof Error?n.message:String(n)}}}function su(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;if(n.version!==1||!pr(n.recordedAt)||!n.trigger||!lu(n.trigger.kind))return null;if(n.event==="suppressed")return n.reason==="completed-index-is-fresh"?{record:n,hasLanguageDetails:!1,invalidLanguageDetails:0}:null;if(n.event!=="run"||n.result!=="rebuilt"&&n.result!=="reused"&&n.result!=="failed"||!z(n.durationMs)||!z(n.estimatedLogicalOutputBytes)||n.estimatedWriteBytes!==void 0&&!z(n.estimatedWriteBytes)||n.reflinkedBytes!==void 0&&!z(n.reflinkedBytes)||n.fallbackCopiedBytes!==void 0&&!z(n.fallbackCopiedBytes)||n.incrementalWrittenBytes!==void 0&&!z(n.incrementalWrittenBytes))return null;let r=n,{byLanguage:i,...o}=r,a=pu(i);return{record:{...o,...a.byLanguage?{byLanguage:a.byLanguage}:{}},hasLanguageDetails:a.hasLanguageDetails,invalidLanguageDetails:a.invalidLanguageDetails}}catch{return null}}function cu(e){return e.reflinkedBytes===void 0?e.estimatedWriteBytes??e.estimatedLogicalOutputBytes:Math.max(0,e.estimatedLogicalOutputBytes-e.reflinkedBytes)+(e.fallbackCopiedBytes??0)+(e.incrementalWrittenBytes??0)}function Vf(e,t,n=new Date){return t.enabled?uu(au(e,n,t.windowMs),t,n.getTime()):{state:"allowed",rebuilt:0,estimatedWriteBytes:0}}function uu(e,t,n){let r=e.estimatedWriteBytes??e.estimatedLogicalOutputBytes,i=e.fullRebuilds??e.rebuilt,o={rebuilt:i,estimatedWriteBytes:r};return t.enabled?e.confidence!==void 0&&e.confidence!=="complete"?{state:"paused",reason:"activity-evidence",until:n+t.windowMs,...o,detail:`reindex activity evidence is ${e.confidence}`}:i>=t.maxRebuilds?{state:"paused",reason:"rebuild-count",until:Zi(e.oldestRebuildAt,t.windowMs,n),...o,detail:`${i}/${t.maxRebuilds} expensive full rebuild slots consumed`}:r>=t.maxEstimatedWriteBytes?{state:"paused",reason:"estimated-write-bytes",until:Zi(e.oldestWriteAt,t.windowMs,n),...o,detail:`${r}/${t.maxEstimatedWriteBytes} estimated write bytes consumed`}:{state:"allowed",...o}:{state:"allowed",...o}}function Qi(e){if(e.result!=="rebuilt")return!1;let t=io(e.byLanguage);return t.length===0?!0:t.some(([,n])=>n.result==="rebuilt"&&n.strategy!=="incremental"&&n.strategy!=="reused")}function Zi(e,t,n){let r=e?Date.parse(e):Number.NaN;return Number.isFinite(r)&&r+t>n?r+t:n+t}function lu(e){return e==="manual-cli"||e==="setup"||e==="watch-source"||e==="watch-startup"||e==="watch-demand"||e==="watch-git-head"||e==="watch-git-index"||e==="watch-git-state"||e==="unknown"}function fn(e){try{return eu(e).size}catch{return 0}}function du(e){let t={};for(let n of e.languages){let r=(e.shards??[]).filter(u=>u.language===n),i=r.find(u=>u.id===n),o=e.reused||(i?i.reused:r.length>0&&r.every(u=>u.reused)),a=fn(to(eo(e.dbPath),"language-indexes",`${n}.scip`)),s=a>0?a:i?.outputBytes??a,c=o?0:i?.durationMs??r.filter(u=>!u.reused).reduce((u,l)=>u+l.durationMs,0);t[n]={result:o?"reused":"rebuilt",strategy:o?"reused":i?.strategy??"full",...i?.strategy==="full"&&(i.fallbackReason??i.missReason)?{fallbackReason:i.fallbackReason??i.missReason}:{},outputBytes:s,producedOutputBytes:o?0:i?.producedOutputBytes??s,durationMs:c}}return t}function pu(e){if(e===void 0)return{hasLanguageDetails:!1,invalidLanguageDetails:0};if(!e||typeof e!="object"||Array.isArray(e))return{hasLanguageDetails:!1,invalidLanguageDetails:1};let t={},n=0;for(let[i,o]of Object.entries(e)){if(!fu(i)||!gu(o)){n+=1;continue}t[i]=o}let r=Object.keys(t).length>0;return{...r?{byLanguage:t}:{},hasLanguageDetails:r,invalidLanguageDetails:n}}function gu(e){if(!e||typeof e!="object")return!1;let t=e;return(t.result==="rebuilt"||t.result==="reused")&&(t.strategy===void 0||t.strategy==="reused"||t.strategy==="incremental"||t.strategy==="full")&&(t.fallbackReason===void 0||typeof t.fallbackReason=="string")&&qt(t.outputBytes)&&qt(t.producedOutputBytes)&&z(t.durationMs)&&(t.result!=="reused"||t.producedOutputBytes===0&&t.durationMs===0)&&t.producedOutputBytes<=t.outputBytes}function fu(e){return Ht.includes(e)}function io(e){return e?Ht.flatMap(t=>{let n=e[t];return n?[[t,n]]:[]}):[]}function mu(){return{runs:0,rebuilt:0,reused:0,producedOutputBytes:0,durationMs:0}}function hu(e){let t=e.invalidLanguageDetails??0,n=e.attributedRuns??0;return(e.unattributedRuns??0)===0&&t===0?"complete":n===0?"unavailable":"partial"}function yu(e){return e.endsWith(`
256
- `)||(e=e.slice(0,Math.max(0,e.lastIndexOf(`
257
- `)+1))),e.split(`
258
- `).filter(t=>t.length>0)}import{createHash as bu}from"crypto";import{existsSync as yn,readdirSync as Su}from"fs";import{dirname as bn,join as Rt,relative as Ru,resolve as Sn,sep as oo}from"path";function ao(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=lo(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function so(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=lo(s,e);c&&c!==i&&a.add(c)}}return xu(e,r)}function co(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 Rn(e){if(e===".")return"root";let t=bu("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function uo(e,t){let n=Sn(e),r={};for(let i of t)r[i]=vu(n,i);return r}function lo(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 xu(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 vu(e,t){let n=t==="."?e:Rt(e,t),r=Pu(n),i=Iu(n),o=i?Eu(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 Pu(e){let t=Rt(e,"package.json");if(!yn(t))return{name:void 0,dependencyNames:[],failed:!1};let n=xn(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 Iu(e){let t=Rt(e,"tsconfig.json");if(yn(t))return t;let n;try{n=Su(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?Rt(e,n[0]):void 0}function Eu(e,t){let n=xn(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=Tu(n.value,e,t),i=po(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function Tu(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=bn(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=go(s,i,n);c&&o.add(c)}return[...o]}function po(e,t,n,r){let i=wu(t);if(i)return{pathsTargets:ku(i,bn(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=_u(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=xn(o);return a.ok?po(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function wu(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 ku(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=go(o,t,n);a&&r.add(a)}return[...r]}function _u(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=Sn(bn(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(oo).includes("node_modules")&&$t(n,i)&&yn(i))return i}function go(e,t,n){let r=e.replace(/\/?\*+$/,""),i=Sn(t,r===""?".":r);if(!$t(n,i))return;let a=Ru(n,i).split(oo).join("/");return a===""?".":a}function Cu(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]!==`
259
- `;)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 xn(e){try{let t=j(e,{maxBytes:ye,inputKind:"TypeScript project manifest"}),n=JSON.parse(Cu(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import Fu from"better-sqlite3";import{zstdCompressSync as Au}from"zlib";import{setImmediate as fo}from"timers/promises";var Z=class extends Error{},Lu=200,Pn=2,mo=1,Ou=2,Du=3,Mu=4,Nu=5,ju=6,Ro=1,xo=2,vo=3,Bu=7,$u=1,Vu=3,Uu=5,Gu=6,Wu=8,qu=1,ho=64,Hu=[`CREATE TABLE documents (
260
- id INTEGER PRIMARY KEY,
261
- language TEXT,
262
- relative_path TEXT NOT NULL UNIQUE,
263
- position_encoding TEXT,
264
- text TEXT
265
- )`,`CREATE TABLE chunks (
266
- id INTEGER PRIMARY KEY,
267
- document_id INTEGER NOT NULL,
268
- chunk_index INTEGER NOT NULL,
269
- start_line INTEGER NOT NULL,
270
- end_line INTEGER NOT NULL,
271
- occurrences BLOB NOT NULL,
272
- FOREIGN KEY (document_id) REFERENCES documents(id)
273
- )`,`CREATE TABLE global_symbols (
274
- id INTEGER PRIMARY KEY,
275
- symbol TEXT NOT NULL UNIQUE,
276
- display_name TEXT,
277
- kind INTEGER,
278
- documentation TEXT,
279
- signature BLOB,
280
- enclosing_symbol TEXT,
281
- relationships BLOB
282
- )`,`CREATE TABLE mentions (
283
- chunk_id INTEGER NOT NULL,
284
- symbol_id INTEGER NOT NULL,
285
- role INTEGER NOT NULL,
286
- PRIMARY KEY (chunk_id, symbol_id, role),
287
- FOREIGN KEY (chunk_id) REFERENCES chunks(id),
288
- FOREIGN KEY (symbol_id) REFERENCES global_symbols(id)
289
- )`,`CREATE TABLE defn_enclosing_ranges (
290
- id INTEGER PRIMARY KEY,
291
- document_id INTEGER NOT NULL,
292
- symbol_id INTEGER NOT NULL,
293
- start_line INTEGER NOT NULL,
294
- start_char INTEGER NOT NULL,
295
- end_line INTEGER NOT NULL,
296
- end_char INTEGER NOT NULL,
297
- FOREIGN KEY (document_id) REFERENCES documents(id),
298
- FOREIGN KEY (symbol_id) REFERENCES global_symbols(id)
299
- )`],Ju=["CREATE INDEX idx_chunks_line_range ON chunks(document_id, start_line, end_line)","CREATE INDEX idx_mentions_symbol_id_role ON mentions(symbol_id, role)","CREATE INDEX idx_defn_enclosing_ranges_symbol_id ON defn_enclosing_ranges(symbol_id)","CREATE INDEX idx_defn_enclosing_ranges_document ON defn_enclosing_ranges(document_id, start_line, end_line)","CREATE INDEX idx_chunks_doc_id ON chunks(document_id)","CREATE INDEX idx_global_symbols_symbol ON global_symbols(symbol)"];function vn(e){return e.startsWith("local ")}function yo(e,t,n,r){let i=t,o=0,a=0;for(;i<n;){let s=e[i];i+=1,a<53&&(o+=(s&127)*2**a),(s&128)===0?(r.push(o),o=0,a=0):a+=7}}function bo(e){return e.length===3?[e[0],e[1],e[0],e[2]]:e.length===4?[e[0],e[1],e[2],e[3]]:null}function zu(e,t){return e.startLine!==t.startLine?e.startLine-t.startLine:e.startChar!==t.startChar?e.startChar-t.startChar:e.endLine!==t.endLine?e.endLine-t.endLine:e.endChar!==t.endChar?e.endChar-t.endChar:e.symbol<t.symbol?-1:e.symbol>t.symbol?1:0}function Yu(e,t,n,r){let i=[],o=[],a="",s=0;for(let u of ae(e,n,r))u.fieldNumber===Ro?u.wireType===2?yo(e,u.valueStart,u.valueEnd,i):u.wireType===0&&i.push(u.varint):u.fieldNumber===xo&&u.wireType===2?a=_e.decode(e.subarray(u.valueStart,u.valueEnd)):u.fieldNumber===vo&&u.wireType===0?s=u.varint:u.fieldNumber===Bu&&(u.wireType===2?yo(e,u.valueStart,u.valueEnd,o):u.wireType===0&&o.push(u.varint));let c=bo(i);return c?{startLine:c[0],startChar:c[1],endLine:c[2],endChar:c[3],symbol:a,roles:s,frameStart:t,frameEnd:r,merged:!1,enclosing:bo(o)}:null}function Xu(e,t,n){let r={symbol:"",displayName:null,kind:null,documentation:[],enclosingSymbol:null};for(let i of ae(e,t,n))if(i.wireType===2){let o=()=>_e.decode(e.subarray(i.valueStart,i.valueEnd));i.fieldNumber===$u?r.symbol=o():i.fieldNumber===Vu?r.documentation.push(o()):i.fieldNumber===Gu?r.displayName=o():i.fieldNumber===Wu&&(r.enclosingSymbol=o())}else i.fieldNumber===Uu&&i.wireType===0&&(r.kind=i.varint);return r}var _e=new TextDecoder;function Ku(e,t){if(e.length===0)return[];let n=[],r=Math.min(e.length,t);for(let i=0;i<r&&r<=e.length;){for(;r<=e.length-1&&e[r-1].startLine===e[r].startLine;)r+=1;n.push(e.slice(i,r)),i=r,r=Math.min(e.length,r+t)}return n}function Qu(e){let t=e.startLine===e.endLine?[e.startLine,e.startChar,e.endChar]:[e.startLine,e.startChar,e.endLine,e.endChar],n=[],r=Buffer.concat(t.map(a=>se(a)));n.push(at(Ro),se(r.length),r);let i=Buffer.from(e.symbol,"utf8");n.push(at(xo),se(i.length),i),e.roles!==0&&n.push(se(vo*8),se(e.roles));let o=Buffer.concat(n);return Buffer.concat([at(Pn),se(o.length),o])}function Zu(e,t){let n=[];for(let r of t)r.merged?n.push(Qu(r)):n.push(e.subarray(r.frameStart,r.frameEnd));return Au(Buffer.concat(n))}async function Po(e,t,n={}){let r=n.chunkSize??Lu,i={documents:0,duplicateDocumentsSkipped:0,occurrences:0,illegalOccurrencesDropped:0,mergedOccurrences:0,chunks:0,mentions:0,globalSymbols:0,enclosingRanges:0},o=new Fu(t);try{o.pragma("synchronous = normal"),o.pragma("temp_store = memory"),o.pragma("foreign_keys = ON"),o.pragma("journal_mode = WAL");for(let E of Hu)o.exec(E);let a=o.prepare("INSERT INTO documents (id, language, relative_path, position_encoding, text) VALUES (?, ?, ?, ?, ?)"),s=o.prepare("INSERT INTO chunks (id, document_id, chunk_index, start_line, end_line, occurrences) VALUES (?, ?, ?, ?, ?, ?)"),c=o.prepare("INSERT INTO defn_enclosing_ranges (document_id, symbol_id, start_line, start_char, end_line, end_char) VALUES (?, ?, ?, ?, ?, ?)"),u=o.prepare("INSERT INTO global_symbols (id, symbol, display_name, kind, documentation, enclosing_symbol) VALUES (?, ?, ?, ?, ?, ?)"),l=o.prepare("INSERT INTO mentions (chunk_id, symbol_id, role) VALUES (?, ?, ?)"),d=new Map,p=new Map,f=1,h=1,b=1,P=(E,A,k,y,S)=>{let m=b;return b+=1,p.set(E,m),u.run(m,E,A,k,y,S),i.globalSymbols+=1,m};o.exec("BEGIN IMMEDIATE");let _=!1;try{let E=0;for(let k of ae(e)){if(k.fieldNumber!==Pn||k.wireType!==2)continue;So(n.signal),E+=1,E>=ho&&(E=0,await fo());let y="",S=null,m=null,F=null,R=[];for(let g of ae(e,k.valueStart,k.valueEnd))g.wireType===2?g.fieldNumber===mo?y=_e.decode(e.subarray(g.valueStart,g.valueEnd)):g.fieldNumber===Du?R.push(Xu(e,g.valueStart,g.valueEnd)):g.fieldNumber===Mu?S=_e.decode(e.subarray(g.valueStart,g.valueEnd)):g.fieldNumber===Nu&&(m=_e.decode(e.subarray(g.valueStart,g.valueEnd))):g.fieldNumber===ju&&g.wireType===0&&(F=el(g.varint));if(y==="")throw new Z("relative path must not be empty");if(d.has(y)){i.duplicateDocumentsSkipped+=1;continue}let v=f;f+=1,a.run(v,S===""?null:S,y,F,m===""?null:m),d.set(y,v),i.documents+=1;let w=new Map;for(let g of R){if(g.symbol==="")throw new Z(`empty symbol in SymbolInformation for document ${y}`);let x=w.get(g.symbol);if(!x){w.set(g.symbol,g);continue}for(let O of g.documentation)x.documentation.includes(O)||x.documentation.push(O)}for(let g of[...w.values()].sort((x,O)=>x.symbol<O.symbol?-1:x.symbol>O.symbol?1:0))vn(g.symbol)||p.has(g.symbol)||P(g.symbol,g.displayName===""?null:g.displayName,g.kind===0?null:g.kind,g.documentation.length===0?null:g.documentation.join(`
300
- `),g.enclosingSymbol===""?null:g.enclosingSymbol)}let A=new Set;E=0;for(let k of ae(e)){if(k.fieldNumber!==Pn||k.wireType!==2)continue;So(n.signal),E+=1,E>=ho&&(E=0,await fo());let y="",S=[];for(let R of ae(e,k.valueStart,k.valueEnd))if(R.wireType===2){if(R.fieldNumber===mo)y=_e.decode(e.subarray(R.valueStart,R.valueEnd));else if(R.fieldNumber===Ou){let v=Yu(e,R.fieldStart,R.valueStart,R.valueEnd);v?S.push(v):i.illegalOccurrencesDropped+=1}}if(A.has(y))continue;A.add(y);let m=d.get(y);if(m===void 0)continue;S.sort(zu);let F=[];for(let R of S){let v=F[F.length-1];if(v&&v.startLine===R.startLine&&v.startChar===R.startChar&&v.endLine===R.endLine&&v.endChar===R.endChar&&v.symbol===R.symbol){v.roles|=R.roles,v.merged=!0,i.mergedOccurrences+=1;continue}F.push(R)}i.occurrences+=F.length;for(let R of F){if((R.roles&qu)===0||vn(R.symbol)||!R.enclosing)continue;let[v,w,g,x]=R.enclosing;if(v<0||w<0||g<v||g===v&&x<w)throw new Z(`bad enclosing range for symbol ${R.symbol} in ${y}`);let O=p.get(R.symbol);if(O===void 0)throw new Z(`symbol ${R.symbol} has definition occurrence, but no SymbolInformation`);c.run(m,O,v,w,g,x),i.enclosingRanges+=1}for(let[R,v]of Ku(F,r).entries()){let w=h;h+=1,s.run(w,m,R,v[0].startLine,v[v.length-1].startLine,Zu(e,v)),i.chunks+=1;let g=new Map;for(let x of v){if(vn(x.symbol))continue;let O=g.get(x.symbol);O||g.set(x.symbol,O=new Set),O.add(x.roles),p.has(x.symbol)||P(x.symbol,null,null,null,null)}for(let[x,O]of g){let H=p.get(x);for(let jt of O)l.run(w,H,jt),i.mentions+=1}}}o.exec("COMMIT"),_=!0}finally{if(!_)try{o.exec("ROLLBACK")}catch{}}o.exec("BEGIN IMMEDIATE");for(let E of Ju)o.exec(E);o.exec("COMMIT"),o.pragma("wal_checkpoint(TRUNCATE)")}finally{o.close()}return i}function el(e){if(e===0)return null;if(e===1)return"UTF-8";if(e===2)return"UTF-16";if(e===3)return"UTF-32";throw new Z(`unknown position encoding ${e}`)}function So(e){if(e?.aborted)throw new Z("SCIP SQLite conversion aborted")}import{readdirSync as tl,rmSync as nl}from"fs";import{cpus as rl,totalmem as il}from"os";import{join as xt}from"path";var ol=2048,al=6*1024**3,sl=4;function In(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_FILES??"",10);return Number.isSafeInteger(t)&&t>0?t:ol}function Eo(e,t){return e>Math.floor(t*1.5)}var cl=1.25;function To(e,t,n){if(!Number.isSafeInteger(t)||t<1)throw new Error(`TypeScript compiler shard targetFiles must be a positive safe integer; received ${t}.`);let r=Math.max(1,Math.ceil(e/t));if(r<=1||n<=1)return r;let i=Math.floor(t*cl),o=new Set([r,n*Math.floor(r/n),n*Math.ceil(r/n)]),a=c=>Math.ceil(c/n)*Math.ceil(e/c),s=r;for(let c of o)c<1||Math.ceil(e/c)>i||(a(c)<a(s)||a(c)===a(s)&&c<s)&&(s=c);return s}function ul(e,t,n=()=>1){if(!Number.isSafeInteger(t)||t<1)throw new Error(`TypeScript compiler shard count must be a positive safe integer; received ${t}.`);let r=[...new Set(e)].sort((u,l)=>u.localeCompare(l));if(t===1||r.length<=t)return r.length<=t&&t>1?r.map(u=>[u]):r.length>0?[r]:[];let i=r.map(u=>Math.max(1,n(u))),o=i.reduce((u,l)=>u+l,0),a=[],s=[],c=0;for(let u=0;u<r.length;u+=1){s.push(r[u]),c+=i[u];let l=t-a.length-1,d=r.length-u-1;l>0&&d>=l&&(c>=o*(a.length+1)/t||d===l)&&(a.push(s),s=[])}return s.length>0&&a.push(s),a}function wo(e){let t=e.targetFiles??In(),n=e.shardCount??Math.max(1,Math.ceil(new Set(e.inputPaths).size/Math.max(1,t)));return ul(e.inputPaths,n,e.weightOf).map((r,i)=>{let o=xt(e.projectRoot,ir(i)),a=`${JSON.stringify({extends:`./${e.rootConfigPath}`,compilerOptions:{incremental:!1},files:r.map(s=>`./${s}`),include:[],exclude:[]},null,2)}
301
- `;return{configPath:o,content:a,inputPaths:r}})}var ko="typescript-shard-costs.json",Io=4;function _o(e){let t;try{t=JSON.parse(Ye(xt(e,ko),"shard cost model"))}catch{return null}if(typeof t!="object"||t===null||t.version!==1)return null;let n=t.samples;return Array.isArray(n)&&n.every(i=>typeof i=="object"&&i!==null&&typeof i.firstPath=="string"&&typeof i.lastPath=="string"&&Number.isFinite(i.totalBytes)&&i.totalBytes>0&&Number.isFinite(i.durationMs)&&i.durationMs>0)?{version:1,samples:n}:null}function Co(e,t){nt(xt(e,ko),t)}function Fo(e){let t=(e?.samples??[]).filter(o=>o.totalBytes>0&&o.durationMs>0);if(t.length<2)return(o,a)=>a;let n=t.map(o=>o.durationMs/o.totalBytes).sort((o,a)=>o-a),r=n[Math.floor(n.length/2)];if(!(r>0))return(o,a)=>a;let i=[...t].sort((o,a)=>o.firstPath.localeCompare(a.firstPath));return(o,a)=>{for(let s of i){if(o.localeCompare(s.firstPath)<0)break;if(o.localeCompare(s.lastPath)>0)continue;let c=s.durationMs/s.totalBytes/r;return a*Math.min(Io,Math.max(1/Io,c))}return a}}function Ao(e,t){let n=[];for(let r of e){let i=r.inputPaths[0],o=r.inputPaths[r.inputPaths.length-1];if(i===void 0||o===void 0||!(r.durationMs>0))return null;let a=r.inputPaths.reduce((s,c)=>s+Math.max(1,t(c)),0);n.push({firstPath:i,lastPath:o,totalBytes:a,durationMs:r.durationMs})}return n.length>0?{version:1,samples:n}:null}function Lo(e=process.env,t={totalmemBytes:il(),cpuCount:rl().length}){let n=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_CONCURRENCY??"",10);if(Number.isSafeInteger(n)&&n>0)return n;let r=Math.floor(t.totalmemBytes/2/al),i=Math.floor(t.cpuCount/2);return Math.max(1,Math.min(sl,r,i))}function Oo(e){let t;try{t=tl(e)}catch{return}for(let n of t)if(or(n))try{nl(xt(e,n))}catch{}}import{createHash as Mn}from"crypto";import{existsSync as Dn,writeFileSync as Qo}from"fs";import{join as Ml}from"path";import{createRequire as ll}from"module";import{dirname as _n,isAbsolute as dl,relative as No,resolve as te,sep as Tn}from"path";var ee=ll(import.meta.url),pl=1,Do="0.4.0";function gl(){try{let e=jo();if(!e.available)return e;let{packageRoot:t}=e,n=ee.resolve("typescript",{paths:[t]}),r=ee(n),{FileIndexer:i}=ee(te(t,"dist/src/FileIndexer.js")),{Input:o}=ee(te(t,"dist/src/Input.js")),{Packages:a}=ee(te(t,"dist/src/Packages.js")),s=ee(te(t,"dist/src/scip.js"));if(!i||!o||!a||!s.scip?.Document||!s.scip.Index)return{available:!1,reason:"scip-typescript document runtime has an unsupported module shape"};let c={packageVersion:e.packageVersion,typescript:r,Document:s.scip.Document,Index:s.scip.Index,FileIndexer:i,Input:o,Packages:a};return{available:!0,runtime:c,producerIdentity:Fn(c)}}catch(e){return{available:!1,reason:`scip-typescript document runtime unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Cn(){let e=jo();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function jo(){try{let e=ee.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse($(e,"scip-typescript package manifest"));if(t.version!==Do)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${Do}`};let n=_n(e),r=ee.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse($(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:$o(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Bo(e){let t=e.runtime===void 0?gl():e.runtime===null?{available:!1,reason:"scip-typescript document runtime unavailable"}:{available:!0,runtime:e.runtime,producerIdentity:Fn(e.runtime)};return t.available?{available:!0,emitter:new wn(e,t.runtime)}:t}var wn=class{producerIdentity;workspaceRoot;tsconfigPath;projectRoot;maxFileByteSize;runtime;host;config=null;includedFiles=new Set;program=null;checker=null;symbolTable=new Map;constructorTable=new Map;packages;fragments=new Map;stats={initializations:0,programUpdates:0,documentsEmitted:0,documentsRemoved:0,sourceNodesReused:0,sourceNodesReplaced:0,symbolEntriesPruned:0};constructor(t,n){this.workspaceRoot=te(t.workspaceRoot),this.tsconfigPath=te(this.workspaceRoot,t.tsconfigPath),this.projectRoot=t.projectRoot??ml(this.workspaceRoot,_n(this.tsconfigPath)),this.maxFileByteSize=t.maxFileByteSize??1024*1024,this.runtime=n,this.producerIdentity=Fn(n);let r=En(n.typescript,this.tsconfigPath);this.config=r,this.host=new kn(n.typescript,r.options,this.workspaceRoot),this.packages=new n.Packages(this.projectRoot)}initialize(){let t=performance.now();this.initializeProgram();let n=[];for(let r of this.program.getSourceFiles())this.includedFiles.has(Ae(r.fileName))&&n.push(this.emitSourceFile(r));return this.result(n,t)}advance(t){if(!this.program||!this.checker||!this.config)return this.initializeAndAdvance(t);let n=performance.now(),r=Fe(t.modifiedFiles),i=Fe(t.removedFiles??[]),o=Fe(t.affectedFiles);if(this.fragments.clear(),r.length===0&&i.length===0)return this.validateAffectedPaths(o),this.result(this.emitAffectedFiles(o),n);let a=En(this.runtime.typescript,this.tsconfigPath);this.config=a,this.includedFiles=new Set(a.fileNames.map(Ae));let s=this.program,c=new Map;for(let u of[...r,...i]){let l=Ce(this.workspaceRoot,u),d=s.getSourceFile(l);d&&(c.set(u,d),this.stats.symbolEntriesPruned+=Mo(this.symbolTable,d),this.stats.symbolEntriesPruned+=Mo(this.constructorTable,d)),this.host.invalidate(l)}this.program=this.runtime.typescript.createProgram(a.fileNames,a.options,this.host.compilerHost,s),this.checker=this.program.getTypeChecker(),this.stats.programUpdates+=1,this.validateIncrementalPaths(r,i,o),this.stats.documentsRemoved+=i.length;for(let[u,l]of c)this.program.getSourceFile(Ce(this.workspaceRoot,u))===l?this.stats.sourceNodesReused+=1:this.stats.sourceNodesReplaced+=1;return this.result(this.emitAffectedFiles(o),n)}fragment(t){return this.fragments.get(vt(t))??null}snapshotStats(){return{...this.stats}}initializeAndAdvance(t){let n=performance.now();this.initializeProgram();let r=Fe(t.modifiedFiles),i=Fe(t.removedFiles??[]),o=Fe(t.affectedFiles);return this.fragments.clear(),this.validateIncrementalPaths(r,i,o,!0),this.stats.documentsRemoved+=i.length,this.result(this.emitAffectedFiles(o),n)}initializeProgram(){let t=this.config??En(this.runtime.typescript,this.tsconfigPath);this.includedFiles=new Set(t.fileNames.map(Ae)),this.program=this.runtime.typescript.createProgram(t.fileNames,t.options,this.host.compilerHost),this.checker=this.program.getTypeChecker(),this.stats.initializations+=1}validateIncrementalPaths(t,n,r,i=!1){if(!i&&t.length===0&&n.length===0)throw new Error("incremental TypeScript document update requires a modified or removed file");if(r.length===0&&n.length===0)throw new Error("incremental TypeScript document update requires an affected or removed file");for(let o of t){let a=Ce(this.workspaceRoot,o);if(!this.program?.getSourceFile(a))throw new Error(`modified TypeScript dependency is unavailable to the configured project: ${o}`)}for(let o of n){let a=Ce(this.workspaceRoot,o);if(this.program?.getSourceFile(a))throw new Error(`removed TypeScript source is still present in the configured project: ${o}`)}this.validateAffectedPaths(r)}validateAffectedPaths(t){for(let n of t){let r=Ce(this.workspaceRoot,n);if(!this.includedFiles.has(Ae(r)))throw new Error(`affected TypeScript file is outside the configured project: ${n}`)}}emitAffectedFiles(t){return t.map(n=>{let r=this.program.getSourceFile(Ce(this.workspaceRoot,n));if(!r)throw new Error(`affected TypeScript source is unavailable: ${n}`);return this.emitSourceFile(r)})}emitSourceFile(t){if(!this.checker)throw new Error("TypeScript document emitter is not initialized");let n=vt(No(this.workspaceRoot,t.fileName)),r=new this.runtime.Document({relative_path:n,occurrences:[]});if(new this.runtime.FileIndexer(this.checker,{cwd:this.workspaceRoot,projectRoot:this.projectRoot,projectDisplayName:this.projectRoot,maxFileByteSizeNumber:this.maxFileByteSize},new this.runtime.Input(t.fileName,t.getText()),r,this.symbolTable,this.constructorTable,this.packages,t).index(),this.stats.documentsEmitted+=1,r.occurrences.length===0)return this.fragments.delete(n),this.stats.documentsRemoved+=1,{relativePath:n,bytes:null,occurrences:0,symbols:r.symbols.length,referenceFragments:[]};let o=r.serializeBinary();return this.fragments.set(n,o),{relativePath:n,bytes:o,occurrences:r.occurrences.length,symbols:r.symbols.length,referenceFragments:fl(n,r)}}result(t,n){return{producerIdentity:this.producerIdentity,fragments:t,durationMs:performance.now()-n,stats:this.snapshotStats()}}};function fl(e,t){let n=new Map;for(let r of t.occurrences){if(!r.symbol||(r.symbol_roles&1)!==0||r.range.length<3)continue;let i=r.range[0],o=r.range[1];if(!Number.isInteger(i)||!Number.isInteger(o))continue;let a={targetSymbol:r.symbol,location:{file:e,line:i,column:o}};n.set(`${r.symbol}\0${i}\0${o}`,a)}return[...n.values()].sort((r,i)=>r.targetSymbol.localeCompare(i.targetSymbol)||r.location.line-i.location.line||r.location.column-i.location.column)}var kn=class{compilerHost;sourceFiles=new Map;constructor(t,n,r){let i=t.createCompilerHost(n),o=i.getSourceFile.bind(i);this.compilerHost={...i,getCurrentDirectory:()=>r,getSourceFile:(a,s,c,u)=>{let l=Ae(a);if(this.sourceFiles.has(l))return this.sourceFiles.get(l);let d=o(a,s,c,u);return this.sourceFiles.set(l,d),d}}}invalidate(t){this.sourceFiles.delete(Ae(t))}};function En(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(e.formatDiagnostics([n.error],e.createCompilerHost({})));let r=e.parseJsonConfigFileContent(n.config,e.sys,_n(t)),i=r.errors.filter(o=>o.code!==18003);if(i.length>0)throw new Error(e.formatDiagnostics(i,e.createCompilerHost({})));return r}function Fn(e){return $o(e.packageVersion,e.typescript.version)}function $o(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${pl}`}function ml(e,t){return vt(No(e,t))||"."}function Ce(e,t){if(dl(t))throw new Error(`expected a project-relative path: ${t}`);let n=te(e,t),r=e.endsWith(Tn)?e:`${e}${Tn}`;if(n!==e&&!n.startsWith(r))throw new Error(`path escapes the project root: ${t}`);return n}function Fe(e){return[...new Set(e.map(vt))].sort()}function vt(e){return e.split(Tn).join("/").replace(/^\.\//,"")}function Ae(e){return te(e)}function Mo(e,t){let n=0;for(let r of e.keys())if(hl(r)){try{if(r.getSourceFile()!==t)continue}catch{continue}e.delete(r),n+=1}return n}function hl(e){return!!(e&&typeof e=="object"&&"kind"in e&&"getSourceFile"in e)}import{createHash as yl}from"crypto";import{dirname as bl,join as Vo}from"path";var G=5,Sl=4,Rl=2,xl="typescript-index";function Uo(e){let t=Vo(e,xl),n=Or(t);return{...n,requestDir:n.legacyRequestDir}}function vl(e){let t=JSON.parse(e),n=t.protocolVersion,r=n===Rl,i=n===Sl,o=t.request,a=(r||i)&&o&&typeof o=="object"&&!Array.isArray(o)?{...o,removedFiles:o.removedFiles??[]}:o;if(!r&&!i&&n!==G||typeof t.id!="string"||!t.id||typeof t.baseGeneration!="string"||!t.baseGeneration||typeof t.deadlineAtMs!="number"||!Number.isFinite(t.deadlineAtMs)||!Pl(a)||!r&&(t.mailboxVersion!==Me||typeof t.operationKey!="string"||!/^[a-f0-9]{64}$/.test(t.operationKey)||t.id!==rt(t.operationKey)||typeof t.clientId!="string"||!t.clientId||typeof t.enqueuedAtMs!="number"||!Number.isFinite(t.enqueuedAtMs)||t.deadlineAtMs<t.enqueuedAtMs))throw new Error("TypeScript index service received an invalid mailbox request.");if(!r){let c=t,u=Ne(i?"typescript-index-v4":"typescript-index-v5",{baseGeneration:c.baseGeneration,request:o});if(c.operationKey!==u)throw new Error("TypeScript index service received a mismatched mailbox operation identity.");return{...c,protocolVersion:G,request:a}}let s=Ne("typescript-index-v2",{id:t.id,baseGeneration:t.baseGeneration,request:o});return{protocolVersion:G,mailboxVersion:Me,id:t.id,operationKey:s,clientId:"legacy-v2",enqueuedAtMs:t.deadlineAtMs,deadlineAtMs:t.deadlineAtMs,baseGeneration:t.baseGeneration,request:a}}function Go(e){try{let t=gr(re($(Vo(bl(e),"meta.json"),"reindex metadata")));return t?yl("sha256").update(t).digest("hex"):null}catch{return null}}function Pl(e){if(!e||typeof e!="object")return!1;let t=e,n=An(t.modifiedFiles)?t.modifiedFiles:null,r=An(t.removedFiles)?t.removedFiles:null,i=An(t.affectedFiles)?t.affectedFiles:null;return t.kind==="emit-documents"&&typeof t.tsconfigPath=="string"&&!!t.tsconfigPath&&typeof t.projectArgument=="string"&&!!t.projectArgument&&typeof t.projectIdentity=="string"&&!!t.projectIdentity&&typeof t.producerIdentity=="string"&&!!t.producerIdentity&&n!==null&&new Set(n).size===n.length&&r!==null&&new Set(r).size===r.length&&i!==null&&(i.length>0||r.length>0)&&new Set(i).size===i.length}function An(e){return Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0)}import{randomUUID as wl}from"crypto";import{existsSync as qo,rmSync as Ln}from"fs";import{join as kl}from"path";import{randomUUID as Il}from"crypto";import{getHeapStatistics as El}from"v8";import{resolve as Tl}from"path";var Pt=class{projectRoot;currentGeneration;createEmitter;wallNow;monotonicNow;maxActiveSessions;softMemoryLimitBytes;memoryUsage;active=new Map;requests=0;sessionsCreated=0;sessionsReplaced=0;sessionsEvicted=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(t){if(this.projectRoot=Tl(t.projectRoot),this.currentGeneration=t.currentGeneration,this.createEmitter=t.createEmitter??Bo,this.wallNow=t.wallNow??t.now??Date.now,this.monotonicNow=t.monotonicNow??t.now??C,t.maxActiveSessions!==void 0&&(!Number.isInteger(t.maxActiveSessions)||t.maxActiveSessions<1))throw new Error("TypeScript index maxActiveSessions must be a positive integer.");if(this.maxActiveSessions=t.maxActiveSessions??8,t.softMemoryLimitMb!==void 0&&(!Number.isInteger(t.softMemoryLimitMb)||t.softMemoryLimitMb<1))throw new Error("TypeScript index softMemoryLimitMb must be a positive integer.");this.softMemoryLimitBytes=t.softMemoryLimitMb===void 0?null:t.softMemoryLimitMb*1024*1024,this.memoryUsage=t.memoryUsage??(()=>({heapUsedBytes:process.memoryUsage().heapUsed,heapLimitBytes:El().heap_size_limit}))}handle(t,n){let r=this.monotonicNow();try{if(this.currentGeneration()!==t)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(n);if(i.emitter.producerIdentity!==n.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),a=i.emitter.advance({modifiedFiles:n.modifiedFiles,removedFiles:n.removedFiles,affectedFiles:n.affectedFiles}),s=this.monotonicNow()-r;return this.requests+=1,this.lastRequestAtMs=this.wallNow(),this.lastDurationMs=s,this.lastError=null,this.unavailable=!1,{producerIdentity:a.producerIdentity,cold:a.stats.initializations>o.initializations,durationMs:s,fragments:a.fragments.map(c=>({relativePath:c.relativePath,bytesBase64:c.bytes===null?null:Buffer.from(c.bytes).toString("base64"),occurrences:c.occurrences,symbols:c.symbols,referenceFragments:c.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(t){let n=[...this.active.values()].map(a=>a.emitter.snapshotStats()),r=a=>n.reduce((s,c)=>s+c[a],0),i=this.memoryUsage(),o=this.softMemoryLimitBytes!==null&&i.heapUsedBytes>=this.softMemoryLimitBytes;return{protocolVersion:G,state:this.unavailable?"unavailable":this.lastError?"error":this.active.size>0?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,sessionsEvicted:this.sessionsEvicted,activeSessions:this.active.size,maxActiveSessions:this.maxActiveSessions,heapUsedBytes:i.heapUsedBytes,heapLimitBytes:i.heapLimitBytes,...this.softMemoryLimitBytes===null?{}:{softMemoryLimitBytes:this.softMemoryLimitBytes},retireRequested:o,initializations:r("initializations"),programUpdates:r("programUpdates"),documentsEmitted:r("documentsEmitted"),documentsRemoved:r("documentsRemoved"),...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{},...t?{mailbox:t}:{}}}close(){this.active.clear()}emitterFor(t){let n=`${t.tsconfigPath}\0${t.projectArgument}`,r=this.active.get(n);if(r?.projectIdentity===t.projectIdentity)return this.active.delete(n),this.active.set(n,r),r;if(r)this.active.delete(n);else if(this.active.size>=this.maxActiveSessions){let a=this.active.keys().next().value;a!==void 0&&(this.active.delete(a),this.sessionsEvicted+=1)}let i=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:t.tsconfigPath,projectRoot:t.projectArgument});if(!i.available)throw this.unavailable=!0,new Error(i.reason);r&&(this.sessionsReplaced+=1);let o={projectIdentity:t.projectIdentity,emitter:i.emitter};return this.active.set(n,o),this.sessionsCreated+=1,o}};var Tm=`typescript-index-${process.pid}-${Il()}`,Wo=Y(process.pid),wm={pid:process.pid,...Wo?{processIdentity:Wo}:{}};var _l=12e4,Cl=5,Ve=class extends Error{name="TypeScriptIndexMemoryPressureError"},It=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;emitLocally;requireService;localHost=null;constructor(t,n={}){this.projectRoot=rr(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Ol(),this.runtime=n.runtime??Dl,this.mailboxLimits=n.mailboxLimits??{},this.emitLocally=n.emitLocally,this.requireService=n.requireService===!0}request(t){let n=Nr(this.cacheDir),r=Uo(this.cacheDir),i=Yt(n.statePath);if(!Ho(i,this.projectRoot,this.runtime))return this.requestLocally(t);let o=this.runtime.now(),a=o+this.timeoutMs,s=(this.runtime.monotonicNow??C)()+this.timeoutMs,c=Ne("typescript-index-v5",{baseGeneration:this.baseGeneration,request:t}),u=rt(c),l=Dr(r,{mailboxVersion:Me,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:a,protocolVersion:G,id:u,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??C)()<=s;){if(qo(l.responsePath))try{return Jo(j(l.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t.producerIdentity,t.affectedFiles)}finally{Ln(l.responsePath,{force:!0})}let d=Yt(n.statePath);if(!Ho(d,this.projectRoot,this.runtime))return this.abandonPendingRequest(r,u),this.requestLocally(t);this.runtime.sleep(Cl)}if(qo(l.responsePath))try{return Jo(j(l.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t.producerIdentity,t.affectedFiles)}finally{Ln(l.responsePath,{force:!0})}return this.abandonPendingRequest(r,u),this.requestLocally(t)}abandonPendingRequest(t,n){try{Ln(kl(t.pendingDir,`${n}.json`),{force:!0})}catch{}}requestLocally(t){if(this.requireService)throw new Error("TypeScript incremental index service unavailable; refusing to load the whole compiler graph inside the reindex process");return this.emitLocally?On(this.emitLocally(t),t.producerIdentity,t.affectedFiles):(this.localHost??=new Pt({projectRoot:this.projectRoot,currentGeneration:()=>this.baseGeneration}),On(zo(this.localHost.handle(this.baseGeneration,t),t.producerIdentity),t.producerIdentity,t.affectedFiles))}};function Ho(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null,i=e?Date.parse(e.heartbeatAt):Number.NaN;return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===G&&n.isProcessAlive(e.pid)&&Number.isFinite(i)&&n.now()-i<=Mr&&(!e.processIdentity||r!=null&&De(e.processIdentity,r))}function Jo(e,t,n,r,i,o){let a=JSON.parse(e);if(a.protocolVersion!==G||a.id!==t||a.operationKey!==n||a.ok===!0&&a.baseGeneration!==r)throw new Error("TypeScript index service wrote an incompatible response.");if(a.ok!==!0){let s=typeof a.error=="string"?a.error:"TypeScript index service request failed.";throw Fl(s)?new Ve(s):new Error(s)}return On(zo(a.response,i),i,o)}function Fl(e){let t=e.toLowerCase();return t.includes("out of memory")||t.includes("memory limit")||t.includes("allocation failed")||t.includes("err_worker_out_of_memory")}function On(e,t,n){if(e.producerIdentity!==t)throw new Error("TypeScript index service wrote an invalid response.");let r=[...new Set(n)].sort(),i=e.fragments.map(o=>o.relativePath).sort();if(JSON.stringify(i)!==JSON.stringify(r))throw new Error("TypeScript index service omitted or added an affected document.");return e}function zo(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(Al)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:Ll(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 Al(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 Ll(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Ol(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:_l}var Dl={now:Date.now,monotonicNow:C,randomId:wl,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:Pe,readProcessIdentity:Y};var Nl=128,jl=256;function Bl(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."],n=be(t);if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let r=he(e.previousSnapshot,e.currentSnapshot);if(r.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};let i=r.changes.filter(m=>m.inputKind==="source"&&Ie(m.path)),o=Zo(r,n),a={...r,changes:o},s=i.filter(m=>m.kind==="added").map(m=>m.path),c=i.filter(m=>m.kind==="deleted").map(m=>m.path),u=i.filter(m=>m.kind==="modified"),l=Tt(e.currentSnapshot,e.producerIdentity,n),d=Tt(e.previousSnapshot,e.producerIdentity,n),p=ea(r,o,l,d),f=!p&&na(r);if(i.length===0&&!p)return{eligible:!1,reason:"change does not affect the configured TypeScript project"};let h=e.currentSnapshot.files.filter(m=>He(m.path,e.currentSnapshot.languages)==="source"&&Ie(m.path)).map(m=>m.path).sort(),b=new Set(h),P=p?e.projectFiles.filter(m=>!b.has(m)).sort():[...c].sort(),_=p?a:{...r,changes:i},E=p?{eligible:!0,plan:{...$e(a,e.graph,[...new Set([...h,...P])]),mode:"full-project"}}:Vl(u,s,P,e.graph,e.projectFiles);if(!E.eligible)return E;let A=E.plan,k=new Set(P),y=Ul(A,t,e.graph,k);if(!y)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let S=y.length===1?y[0]:void 0;return{eligible:!0,manifest:_,plan:A,projectIdentity:l,previousFragmentGeneration:Ko(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:Ko(e.currentSnapshot,e.producerIdentity),projects:y,deletedFiles:P,replaceProject:p,dependencyGraphUnchanged:f,...S?{tsconfigPath:S.tsconfigPath,projectArgument:S.projectArgument}:{}}}function Zo(e,t){return e.changes.filter(n=>n.inputKind==="source"&&Ie(n.path)||n.inputKind==="config"&&(!Se(n.path)||t.has(n.path))&&$l(n)||n.inputKind==="ambient")}function $l(e){return e.kind!=="modified"||e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function ea(e,t,n,r){return n!==r||e.projectIdentityChanged||e.uncertainty.length>0||t.length>jl||t.some(i=>i.inputKind==="config"||i.inputKind==="ambient")}function Vl(e,t,n,r,i){if(e.length===0)return t.length===0&&n.length===0?{eligible:!1,reason:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...t,...n])].sort(),affectedFiles:[...new Set([...t,...Yo(n,r,i)])].sort(),reasons:[]}};let o=$e({version:1,changes:e.filter(ta),projectIdentityChanged:!1,uncertainty:[]},r,i);return o.mode==="full-project"?{eligible:!1,reason:o.reasons.length>0?`affected set widened: ${o.reasons.join(", ")}`:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...e.map(a=>a.path),...t,...n])].sort(),affectedFiles:[...new Set([...o.affectedFiles,...e.map(a=>a.path),...t,...Yo(n,r,i)])].sort(),reasons:[]}}}function ta(e){return e.kind!=="modified"?!0:e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function na(e){let t=e.changes.filter(n=>n.inputKind==="source"&&Ie(n.path));return t.length>0&&t.every(n=>n.kind==="modified"&&!ta(n))}function Ul(e,t,n,r){let i=new Map;for(let a of e.affectedFiles){let s=Gl(a,t);if(!s)return null;let c=i.get(s)??[];c.push(a),i.set(s,c)}let o=[];for(let[a,s]of[...i].sort(([c],[u])=>c.localeCompare(u))){let c=new Set(s),u=e.changedFiles.filter(p=>!r.has(p)&&(c.has(p)||s.some(f=>Xo(f,p,n)))),l=e.changedFiles.filter(p=>r.has(p)&&(c.has(p)||s.some(f=>Xo(f,p,n)))),d=s.filter(p=>!r.has(p));if(u.length===0&&l.length===0&&d.length===0)return null;o.push({projectArgument:a,tsconfigPath:a==="."?"tsconfig.json":`${a}/tsconfig.json`,modifiedFiles:u,removedFiles:l,affectedFiles:[...d].sort()})}return o}function Yo(e,t,n){let r=new Set(n),i=new Map;for(let[s,c]of t)if(r.has(s))for(let u of c){let l=i.get(u)??new Set;l.add(s),i.set(u,l)}let o=new Set(e),a=[...e];for(let s=0;s<a.length;s+=1){let c=a[s];if(c)for(let u of i.get(c)??[])o.has(u)||(o.add(u),a.push(u))}return[...o].sort()}function Gl(e,t){let n=t.filter(o=>o==="."||e===o||e.startsWith(`${o}/`));if(n.length===0)return null;let r=[...new Set(n)].sort((o,a)=>Et(a)-Et(o)||o.localeCompare(a)),i=r[0];return r[1]&&Et(r[1])===Et(i)?null:i}function Et(e){return e==="."?0:e.split("/").filter(Boolean).length}function Xo(e,t,n){let r=new Set,i=[e];for(let o=0;o<i.length;o+=1){let a=i[o];if(!(!a||r.has(a))){r.add(a);for(let s of n.get(a)??[]){if(s===t)return!0;r.has(s)||i.push(s)}}}return!1}function ra(e){let t=C();try{if(!Dn(e.previousDbPath)||!Dn(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=Cn();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new V({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a=ql(e.projectRoot,e.previousSnapshot,e.currentSnapshot),s=e.projectMode==="workspace"?ne(e.projectRoot,e.currentSnapshot.typescriptProjects):["."],c=be(s),u,l,d;try{u=Ze(o,{includeIgnored:!1}).filter(Ie).sort();let w=a?he(a,e.currentSnapshot):null,g=w&&a&&ea(w,Zo(w,c),Tt(e.currentSnapshot,r.producerIdentity,c),Tt(a,r.producerIdentity,c)),x=w!==null&&!g&&na(w);g?(d=vr(o,"none")??void 0,l=new Map):x?l=new Map:(d=et(o),l=d.graph)}finally{o.close()}let p=performance.now()-n,f=Bl({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?s:void 0,previousSnapshot:a,currentSnapshot:e.currentSnapshot,projectFiles:u,graph:l,producerIdentity:r.producerIdentity,rootTsconfigExists:Dn(Ml(e.projectRoot,"tsconfig.json"))});if(!f.eligible)throw new Error(f.reason);let h=Go(e.previousDbPath);if(!h)throw new Error("published TypeScript base generation unavailable");n=performance.now();let b=new It({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:h},{requireService:!0}),P=f.projects.flatMap(w=>{let g=Wl(w.affectedFiles,Nl);return(g.length>0?g:[[]]).map((O,H)=>({project:w,affectedFiles:O,removedFiles:H===0?w.removedFiles:[],firstForProject:H===0}))}),_=[],E=new Map,A=[],k=!1,y=0,S=0,m=0,F=f.previousFragmentGeneration;for(let[w,g]of P.entries()){let x=b.request({kind:"emit-documents",tsconfigPath:g.project.tsconfigPath,projectArgument:g.project.projectArgument,projectIdentity:f.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:g.firstForProject?g.project.modifiedFiles:[],removedFiles:g.firstForProject?g.project.removedFiles:[],affectedFiles:g.affectedFiles});k||=x.cold,A.push(x.durationMs);let O=g.removedFiles.map(qe=>({relativePath:qe,bytes:null,occurrences:0,symbols:0,referenceFragments:[]})),H=[...x.fragments,...O];if(!f.replaceProject)for(let qe of H)E.set(qe.relativePath,qe.referenceFragments);let jt=performance.now(),hs=Jr(x.fragments);y+=performance.now()-jt;let Zn=w===0?e.candidateAffectedScipPath:`${e.candidateAffectedScipPath}.batch-${w}.scip`,ys=performance.now();Qo(Zn,hs),m+=performance.now()-ys;let bs=performance.now(),er=w===P.length-1?f.nextFragmentGeneration:Hl({previousGenerationIdentity:F,targetGenerationIdentity:f.nextFragmentGeneration,fragments:H});Yr({cacheDir:e.cacheDir,previousGenerationIdentity:F,nextGenerationIdentity:er,producerIdentity:r.producerIdentity,projectIdentity:f.projectIdentity,baseShardCurrent:w===0?e.baseShardCurrent:!1,fragments:H,allowProjectIdentityChange:f.replaceProject&&w===0,allowLegacyProjectIdentityMigration:!0}),S+=performance.now()-bs,F=er,_.push({scipPath:Zn,affectedFiles:[...g.affectedFiles,...g.removedFiles].sort(),deletedFiles:[...g.removedFiles].sort()})}let R=performance.now()-n,v={scipPath:e.previousShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,affectedBatches:_,completeScipUpdated:!1,durationMs:C()-t,cold:k,changedFiles:f.plan.changedFiles,affectedFiles:f.plan.affectedFiles,deletedFiles:f.deletedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:f.previousFragmentGeneration,nextFragmentGeneration:f.nextFragmentGeneration,manifest:f.manifest,plan:f.plan,projectFileCount:u.length,dependencyGraphSnapshot:d,dependencyGraphUnchanged:f.dependencyGraphUnchanged,referenceFragmentsByFile:E,timings:{runtimeMs:i,graphMs:p,requestMs:R,serviceMs:A.reduce((w,g)=>w+g,0),assemblyMs:y,fragmentStoreMs:S,writeMs:m}};return e.onStatus(`${f.replaceProject?"Bounded TypeScript project refresh":"Incremental TypeScript index"} emitted ${v.affectedFiles.length-v.deletedFiles.length} document(s), removed ${v.deletedFiles.length}, and produced ${_.length} bounded batch(es) across ${f.projects.length} project(s) in ${(v.durationMs/1e3).toFixed(3)}s (${v.cold?"cold":"warm"} service; whole SCIP deferred; runtime ${i.toFixed(0)}ms, graph ${p.toFixed(0)}ms, request ${R.toFixed(0)}ms, assembly ${y.toFixed(0)}ms, fragments ${S.toFixed(0)}ms, write ${m.toFixed(0)}ms).`),v}catch(n){let r=n instanceof Error?n.message:String(n);if(e.onUnavailable?.(r),n instanceof Ve)throw e.onStatus(`Incremental TypeScript index stopped after memory pressure survived one cold Worker retry: ${r}. Preserving the accepted index instead of starting a memory-heavier whole-project rebuild.`),n;return e.onStatus(`Incremental TypeScript index unavailable: ${r}.`),null}}function Wl(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ql(e,t,n){if(!t)return null;let r=new Map(n.files.map(a=>[a.path,a])),i=!1,o=t.files.map(a=>{let s=r.get(a.path);if(a.semanticHash!==void 0||s?.semanticHash===void 0)return a;let c=Ke(e,a.path,a.hash);return c===void 0?a:(i=!0,{...a,semanticHash:c})});return i?{...t,files:o}:t}function Hl(e){let t=Mn("sha256");t.update("typescript-overlay-batch-v1\0"),t.update(e.previousGenerationIdentity),t.update("\0"),t.update(e.targetGenerationIdentity);for(let n of[...e.fragments].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)))t.update("\0path\0"),t.update(n.relativePath),n.bytes===null?t.update("\0deleted"):(t.update("\0bytes\0"),t.update(Mn("sha256").update(n.bytes).digest()));return t.digest("hex")}function Nn(e){let t=Cn();if(!t.available)throw new Error(t.reason);let n=Xr({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:J(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:Je}),packageVersion:t.packageVersion});Qo(e.candidateShardPath,n)}function Tt(e,t,n){let r=e.files.filter(i=>{let o=He(i.path,e.languages);return o==="ambient"||o==="config"&&(!Se(i.path)||n.has(i.path))}).map(i=>{let a=He(i.path,e.languages)==="config"?i.semanticHash:void 0;return{path:i.path,size:a===void 0?i.size:0,hash:a??i.hash}}).sort((i,o)=>i.path.localeCompare(o.path));return`typescript-project-v3:${ia(JSON.stringify({version:3,producerIdentity:t,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),nonSourceInputs:r}))}`}function Ko(e,t){return ia(JSON.stringify({version:1,producerIdentity:t,snapshot:nr(e)}))}function ia(e){return Mn("sha256").update(e).digest("hex")}import{closeSync as Jl,existsSync as wt,fstatSync as zl,lstatSync as Yl,openSync as Xl,renameSync as $n,rmSync as Ue,statSync as Kl,writeSync as Ql}from"fs";import{cpus as Zl}from"os";import{join as Vn}from"path";var jn=Symbol("no-error");async function oa(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=jn,c=!0,u=Array.from({length:o},async()=>{for(;c&&a<e.length;){let l=a++;try{r[l]=await n(e[l])}catch(d){s===jn&&(s=d),c=!1}}});if(await Promise.all(u),s!==jn)throw s;return r}var aa=8*1024;function sa(e,t,n){let r=Buffer.from(t,"utf8"),i=()=>Xl(e,"wx",384),o;try{o=i()}catch(a){if(a.code!=="EEXIST")throw a;if(n==="skip")return null;Ue(e,{force:!0}),o=i()}try{Ql(o,r);let a=zl(o);return{path:e,content:r,device:a.dev,inode:a.ino}}finally{Jl(o)}}function ed(e,t){let n=[];try{if(e.temporaryRootConfigContent!==void 0){let r=sa(Vn(t,"tsconfig.json"),e.temporaryRootConfigContent,"skip");r&&n.push(r)}for(let r of e.temporaryProjectConfigs??[]){let i=sa(r.path,r.content,"replace");i&&n.push(i)}return n}catch(r){for(let i of n.reverse())la(i);throw r}}function la(e){if(e)try{let t=Yl(e.path);if(!t.isFile()||t.dev!==e.device||t.ino!==e.inode||t.size!==e.content.byteLength)return;let n;try{n=J(e.path,{maxBytes:e.content.byteLength,inputKind:"temporary TypeScript index configuration"})}catch{return}if(!n.equals(e.content))return;Ue(e.path)}catch(t){if(t.code!=="ENOENT")throw t}}function td(e,t,n){if(!e.defaultOutputPath)return;let r=Vn(t,e.defaultOutputPath);n!==r&&wt(r)&&$n(r,n)}function nd(e,t,n){if(!e.defaultOutputPath)return null;let r=Vn(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Ue(i,{force:!0}),wt(r)?($n(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function rd(e){e&&(Ue(e.defaultOutputPath,{force:!0}),e.backupPath&&wt(e.backupPath)&&$n(e.backupPath,e.defaultOutputPath))}function id(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,Zl().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function da(e,t,n,r,i){B(i,"Reindex cancelled by its owner.");let o=e.filter(u=>u.config.defaultOutputPath),a=e.filter(u=>!u.config.defaultOutputPath&&u.boundedConcurrency!==void 0),s=e.filter(u=>!u.config.defaultOutputPath&&u.boundedConcurrency===void 0),c=[];if(c.push(...await ca(s,id(s.length,r),t,n,i)),a.length>0){let u=Math.max(1,Math.min(...a.map(l=>l.boundedConcurrency)));c.push(...await ca(a,u,t,n,i))}for(let u of o)B(i,"Reindex cancelled by its owner."),c.push((await Bn(u,t,n,i)).result);return c.sort((u,l)=>e.findIndex(d=>d.id===u.id)-e.findIndex(d=>d.id===l.id))}async function ca(e,t,n,r,i){let o=await oa(e,Math.max(1,t),s=>Bn(s,n,r,i));if(t<=1)return o.map(({result:s})=>s);let a=new Map;for(let s of o.filter(c=>c.result.skipped&&c.retryable)){let c=e.find(u=>u.id===s.result.id);c&&(r(`Retrying ${c.label} indexer serially after parallel failure...`),B(i,"Reindex cancelled by its owner."),a.set(c.id,(await Bn(c,n,r,i)).result))}return o.map(({result:s})=>a.get(s.id)??s)}async function Bn(e,t,n,r){B(r,"Reindex cancelled by its owner."),n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Ue(e.scipPath,{force:!0});let i=nd(e.config,t,e.scipPath),o=[],a=[e.binary,...e.args].join(" "),s=C();try{o=ed(e,t),e.trustedProjectTool&&Cr(t,e.trustedProjectTool);let u=Er(e.binary,e.args),l=await lt({command:u.binary,args:u.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:od(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,signal:r});if(l.status!==0){let d=l.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${l.status}${d?`:
302
- ${d}`:""}`)}td(e.config,t,e.scipPath)}catch(u){if(r?.aborted)throw Gr(r,"Reindex cancelled by its owner.");let l=u instanceof Error?u.message:String(u),d=l.length<=aa?l:`${l.slice(0,aa)}
303
- [indexer failure detail truncated]`,p=`${e.resolvedBinary} indexer failed: ${d}`,f=e.label===e.language?p:`${e.label}: ${p}`;return n(`Skipping ${e.label}: ${p}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:C()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:f}},retryable:ad(u)}}finally{rd(i);for(let u of o.reverse())la(u)}if(!wt(e.scipPath)){let u=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,l=e.label===e.language?u:`${e.label}: ${u}`;return n(`Skipping ${e.label}: ${u}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:C()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:l}},retryable:!1}}let c;try{c=Kl(e.scipPath).size}catch{c=void 0}return{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:C()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},outputBytes:c},retryable:!1}}function od(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):li.indexer}function ad(e){return e instanceof di?e.kind==="spawn"&&ua(e.cause):ua(e)}function ua(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}import{execFileSync as ga}from"child_process";import{homedir as pa,platform as sd}from"os";import{delimiter as cd,join as kt}from"path";function fa(e,t){let n=e.installMethods,r=tt(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(!xe(i.prerequisite))continue;let o=ud(i);t(`Installing immutable ${i.identity} via ${i.label} into ${o}; expected executable: ${r}.`);try{ga(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:sd()==="win32"});let a=Oe(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 ud(e){if(e.binary==="npm")return Un("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=Un("go",["env","GOBIN"]);if(t)return t;let n=Un("go",["env","GOPATH"]);if(n)return kt(n.split(cd)[0],"bin")}return e.binary==="dotnet"?kt(process.env.DOTNET_CLI_HOME??pa(),".dotnet","tools"):e.binary==="dart"?kt(process.env.PUB_CACHE??kt(pa(),".pub-cache"),"bin"):e.destination}function Un(e,t){try{return ga(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}import np from"better-sqlite3";import{existsSync as rp}from"fs";import{dirname as ip,join as op,resolve as ap}from"path";import{randomUUID as dd}from"crypto";import{mkdtempSync as pd,rmSync as gd,statSync as ha}from"fs";import{tmpdir as fd}from"os";import{join as ya}from"path";import{Worker as md}from"worker_threads";function ld(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function Le(){return{skippedReferences:0,skippedReferenceReasons:ld(),skippedReferenceSamples:[]}}function _t(e,t){e.skippedReferences+=t.skippedReferences;for(let n of Object.keys(e.skippedReferenceReasons)){e.skippedReferenceReasons[n]+=t.skippedReferenceReasons[n];for(let r of t.skippedReferenceSamples.filter(i=>i.reason===n))e.skippedReferenceSamples.filter(o=>o.reason===n&&o.sourceFile===r.sourceFile).length<2&&e.skippedReferenceSamples.push(r)}}var hd=3e5,ba=64*1024*1024,yd={createResultDirectory:()=>pd(ya(fd(),"scip-query-vue-workers-")),spawn:(e,t)=>new md(e,{workerData:t}),resultSize:e=>ha(e).size,readResult:e=>j(e,{maxBytes:ba,inputKind:"Vue worker result"}),removeResultDirectory:e=>gd(e,{recursive:!0,force:!0})};function Sa(e){return e.length>=8&&xa(e.length)>1}async function Ra(e,t=yd){let n=xa(e.vueFiles.length),r=Cd(e.vueFiles),i=Ad(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),a=e.timeoutMs??kd(),s=e.maxResultBytes??_d();ma("timeoutMs",a),ma("maxResultBytes",s);let c=dd(),u=t.createResultDirectory(),l=[],d,p,f;try{for(let b=0;b<i.length;b++){let P=b,_=i[b]??[],E=_.map(y=>y.taskId),A=ya(u,`${P}.json`),k=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:_,resultPath:A,runId:c,workerId:P,taskIds:E});l.push({workerId:P,taskIds:E,resultPath:A,handle:k,completion:bd(k,P)})}await Sd(l,a);let h=l.sort((b,P)=>b.workerId-P.workerId).map(b=>xd(b,c,s,t));f={occurrences:h.flatMap(b=>b.occurrences),...Le()};for(let b of h)_t(f,b)}catch(h){d=h}finally{let h=await Rd(l);if(h.length===0)try{t.removeResultDirectory(u)}catch(b){h.push(b)}if(h.length>0){let b=d===void 0?h:[d,...h];p=new AggregateError(b,`Vue worker cleanup failed: ${wd(b[0])}`)}}if(p)throw p;if(d!==void 0)throw d;if(!f)throw new Error("Vue workers completed without producing a merged result.");return f}function bd(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 Sd(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 Rd(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function xd(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(!Td(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||!vd(o.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return o.result}function vd(e){if(!Ge(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(Pd)||!W(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(!W(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(Id)}function Pd(e){return Ge(e)&&typeof e.sourceFile=="string"&&W(e.sourceLine)&&W(e.sourceStartChar)&&W(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&W(e.symbolId)}function Id(e){return Ge(e)&&typeof e.sourceFile=="string"&&W(e.sourceLine)&&W(e.sourceStartChar)&&W(e.sourceEndChar)&&typeof e.token=="string"&&Ed(e.reason)}function Ed(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function W(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Td(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function ma(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function wd(e){return e instanceof Error?e.message:String(e)}function xa(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 kd(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:hd}function _d(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:ba}function Cd(e){let t=Fd(),n=[];for(let r of e){let i=va(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 Fd(){return Number.POSITIVE_INFINITY}function Ad(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Ld(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 Ld(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,va(e.fileName)-e.startOffset)}function va(e){try{return ha(e).size}catch{return 1}}import{createRequire as Od}from"module";import{existsSync as Dd}from"fs";import{dirname as Pa,extname as Md,join as Ia,relative as Nd,resolve as jd}from"path";import{pathToFileURL as Bd}from"url";function $d(e){e.transaction(()=>{e.prepare(`
304
- DELETE FROM mentions
305
- WHERE chunk_id IN (
306
- SELECT c.id
307
- FROM chunks c
308
- JOIN documents d ON d.id = c.document_id
309
- WHERE d.language = 'vue' OR d.relative_path LIKE '%.vue'
310
- )
311
- `).run(),e.prepare(`
312
- DELETE FROM chunks
313
- WHERE document_id IN (
314
- SELECT id
315
- FROM documents
316
- WHERE language = 'vue' OR relative_path LIKE '%.vue'
317
- )
318
- `).run()})()}function Ea(e,t){return e.prepare(`
319
- SELECT relative_path AS relativePath
320
- FROM documents
321
- WHERE language = 'vue' OR relative_path LIKE '%.vue'
322
- ORDER BY relative_path
323
- `).all().map(r=>jd(t,r.relativePath))}function Ta(e,t){let{vueCore:n,ts:r,volarTs:i}=Vd(e),{parsed:o,vueOptions:a}=Ud(n,r,t),s=Pa(t),c=n.createVueLanguagePlugin(r,o.options,a,f=>f),u=Gd(n,r,c),l=Wd(s,o),{languageServiceHost:d}=i.createLanguageServiceHost(r,r.sys,u,f=>f,l),p=r.createLanguageService(d);return{ts:r,language:u,languageService:p,fileNames:o.fileNames,configDir:s}}function Vd(e){let t=Od(Bd(Ia(e,"package.json")).href);return{vueCore:Gn(t,"@vue/language-core",e),ts:Gn(t,"typescript",e),volarTs:Gn(t,"@volar/typescript",e)}}function Ud(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,Pa(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Gd(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!Dd(o))return;let a=j(o,{maxBytes:Vt,inputKind:"Vue language-service source file"});r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??Xd(o))});return r.current=i,i}function Wd(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function Gn(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 wa(e,t,n){let r=qd(e);return i=>{if(!i.name)return null;let o=q(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(d=>d.line===s.line&&d.displayName===i.name);if(u)return u.symbolId;let l=c.containingByLine.get(s.line);return l&&l.displayName===i.name?l.symbolId:Hd(c.starts,s.line,2,i.name)}}function qd(e){let t=e.prepare(`
324
- SELECT
325
- d.relative_path AS relativePath,
326
- der.start_line AS startLine,
327
- der.end_line AS endLine,
328
- der.symbol_id AS symbolId,
329
- gs.display_name AS displayName
330
- FROM defn_enclosing_ranges der
331
- JOIN documents d ON d.id = der.document_id
332
- JOIN global_symbols gs ON gs.id = der.symbol_id
333
- ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
334
- `).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 Hd(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 ka(e,t,n){let r=Zd(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
335
- INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
336
- VALUES (?, ?, ?, ?)
337
- `),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let l=q(t,u),d=Na(r.name,r.version,l);o.run(d,"default",7,`Vue component|${l}`);let p=ep(i,r,t,u);p&&(a++,s.set(u,p))}})(),{get(u){return s.get(u)??null},syntheticSymbols:a}}function _a(e,t,n,r,i){return e.transaction(()=>($d(e),Jd(e,t,n,r),zd(e,i)))()}function Jd(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
338
- INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
339
- VALUES (?, ?, ?, ?, X'00')
340
- `),a=e.prepare(`
341
- INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
342
- VALUES (?, ?, 1)
343
- `);for(let s of n){let c=r.get(s);if(!c)continue;let u=q(t,s),l=i.get(u);if(!l)continue;let d=o.run(l.id,-1,0,0);a.run(Number(d.lastInsertRowid),c)}}function Ca(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(Wn(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Fa(e){let t=new Set,n=[];for(let r of e){let i=Aa(r);t.has(i)||(t.add(i),n.push(r))}return n}function Aa(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function zd(e,t){let n=Qd(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
344
- INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
345
- VALUES (?, ?, ?, ?, X'00')
346
- `),i=e.prepare(`
347
- INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
348
- VALUES (?, ?, 0)
349
- `),o=new Set,a=0,s=0;for(let c of t){let u=Aa(c);if(o.has(u))continue;o.add(u);let l=n.get(c.sourceFile);if(!l)continue;let d=r.run(l,s++,c.sourceLine,c.sourceLine),p=i.run(Number(d.lastInsertRowid),c.symbolId);a+=Number(p.changes)}return a}function*La(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 Oa(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Wn(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Yd(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 Da(e,t){return q(e,t).startsWith("node_modules/")}function q(e,t){return Nd(e,t).replaceAll("\\","/")}function Xd(e){switch(Md(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 Ma(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=j(t,{maxBytes:Vt,inputKind:"Vue source file"}),r={text:n,lineStarts:Kd(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:Yd}}function Kd(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function Qd(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 Zd(e){try{let t=JSON.parse(j(Ia(e,"package.json"),{maxBytes:ye,inputKind:"project package manifest"}));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function ep(e,t,n,r){let i=q(n,r),o=Na(t.name,t.version,i);return e.get(o)?.id??null}function Na(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}async function sp(e){return ke(le(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),cp(e)}async function cp(e){let t=ap(e.projectRoot,e.tsconfig);if(!rp(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new np(e.dbPath);try{let r=Ea(n,e.projectRoot),i=op(ip(e.dbPath),"augment-vue-meta.json");return await Yi({cachePath:i,readFingerprint:()=>pp(n,e.projectRoot,e.tsconfig),compute:()=>up({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 up(e){let t=ka(e.db,e.projectRoot,e.vueFiles),n=Sa(e.vueFiles)?await Ra({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles}):dp(e,t);return lp(e,t,n)}function lp(e,t,n){let r=Fa(n.occurrences),i=_a(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:xp(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:Rp(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function dp(e,t){let n=gp({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return fp({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function pp(e,t,n){let r=e.prepare(`
350
- SELECT
351
- (SELECT COUNT(*) FROM documents) AS documents,
352
- (SELECT COUNT(*) FROM global_symbols) AS symbols,
353
- (SELECT COUNT(*) FROM chunks) AS chunks,
354
- (SELECT COUNT(*) FROM mentions) AS mentions,
355
- (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
356
- (SELECT MAX(id) FROM chunks) AS maxChunkId,
357
- (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
358
- `).get();return{version:3,tsconfig:n,files:cr(t),db:r}}function gp(e){let t=Ma();return{projectRoot:e.projectRoot,context:Ta(e.projectRoot,e.configPath),symbolLookup:wa(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function fp(e){let t=[],n=Le(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=mp(e,i);t.push(...o.occurrences),_t(n,o)}return{occurrences:t,...n}}function mp(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return ja(e.projectRoot,t,"missing-source-file");let r=e.context.language.scripts.get(t.fileName),i=r?.generated?.languagePlugin.typescript?.getServiceScript(r.generated.root)?.code;if(!r||!i)return ja(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=q(e.projectRoot,t.fileName),s=[...La(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:Pp(s),processedStarts:new Set};return hp({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function hp(e){let t=[],n=Le();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||yp(e.sourceInfo.text,r.start))continue;let i=Oa(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(l=>!Da(e.projectRoot,l.fileName));if(!a){qn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=q(e.projectRoot,a.fileName),c=bp(e.sourceFile,r.text,s);if(c){qn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=Ca(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){qn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}Ba(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),vp(t,e,r,i,s,u)}return{occurrences:t,...n}}function yp(e,t){let n=e.lastIndexOf(`
359
- `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function bp(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function ja(e,t,n){let r=Le();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:q(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function qn(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 Hn(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 Sp(e,t){let n=Hn(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=Hn(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function Rp(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(...Hn(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function xp(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return Sp(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function vp(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of Ip(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&&(Ba(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function Ba(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 Pp(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function Ip(e,t,n,r,i,o){let a=e.getDocumentHighlights?.(t,n,[t])??[],s=[];for(let c of a)if(c.fileName===t)for(let u of c.highlightSpans){let l=Ep(r,u.textSpan.start,o,i.text);l!==null&&s.push(l)}return s}function Ep(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Wn(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function Za(e){let{projectRoot:t,onStatus:n=console.log}=e,r=e.maxHeapMb??Ap(process.env.NODE_OPTIONS)??8192,i=e.skipAutoInstall===!0||e.installMissing!==!0,o=Op(e),a=Date.now(),s=C();At(I(o.outputScip),{recursive:!0}),At(I(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.");n(`Detected languages: ${c.join(", ")}`);let u=Ot(o.metaPath),l=T("reindex.fingerprint",()=>dr(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath},u,e.changeJournal,Kt(o.outputDb)),{languages:c.length}),d=l.fingerprint,p=l.mode==="delta"?e.changeJournal?.entries.filter(S=>S.kind!=="add").length??0:0,f=Math.max(0,(u?.files.length??0)-p);n(l.mode==="delta"?`Project fingerprint revalidated ${l.changedPaths.length} changed path(s), reused ${f} accepted file fingerprint(s), and accepted ${d.files.length} input(s)`:`Project fingerprint used full scan: ${l.reason}`);let h=await Cp({opts:e,paths:o,languages:c,fingerprint:d,onStatus:n}),b=h.snapshot,P=h.releaseBuildLock,_=ds(e.trigger),E=qr(L(I(o.outputDb),"cache-lifecycle.lock"),{waitMs:_?1e3:3e4});if(!E)throw P?.(),new Te(_?`Could not acquire scip-query cache lifecycle lock for ${I(o.outputDb)}; another refresh is publishing, so the watcher will retry.`:`Could not acquire scip-query cache lifecycle lock for ${I(o.outputDb)}. A watch daemon or another reindex may hold it. Run "scip-query watch --stop", retry the reindex, then restart with "scip-query watch --daemon".`);let A;try{A=await U("reindex.lock",()=>dg(L(I(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:n}),{languages:c.length})}catch(S){throw E.release(),P?.(),S}let k=null,y=bi();try{l.mode==="delta"&&Kt(o.outputDb)!==e.changeJournal?.baseGeneration&&(d=ur(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),l={mode:"full",fingerprint:d,reason:"accepted-generation-changed-before-lock"},b=void 0,P?.(),P=void 0,n("Project fingerprint used full scan: accepted-generation-changed-before-lock")),ri(o.outputDb,o.outputScip,o.metaPath);let S=jp(I(o.outputDb));S.removed>0&&n(`Removed ${S.removed} abandoned reindex workspace(s)`);for(let x of S.errors)n(`Could not remove abandoned reindex workspace: ${x}`);let m=null,F=await U("reindex.reuse-check",async()=>(m=await Dp({opts:e,paths:o,languages:c,fingerprint:d,start:a,monotonicStart:s,onStatus:n}),m),()=>({languages:c.length,reused:m!==null}));if(F){Ua({snapshot:b,paths:o,projectRoot:t,fingerprint:d,onStatus:n});let x=mn(o.outputDb,F);return x.state==="failed"&&n(`Warning: reindex succeeded, but activity telemetry was not recorded: ${x.reason}`),Wt(t,I(o.outputDb)),F}await U("reindex.scip-cli-ready",()=>tg(i,n));let R=Np(o);k=R.runDir;let v,w=await U("reindex.fresh",async()=>(v=await Bp({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:R,fingerprint:d,start:a,monotonicStart:s,maxHeapMb:r,skipAutoInstall:i,onStatus:n,writeTelemetry:y}),v),()=>({languages:c.length,reused:v?.reused,skipped:v?.skipped.length}));Ua({snapshot:b,paths:o,projectRoot:t,fingerprint:d,onStatus:n});let g=mn(o.outputDb,w);return g.state==="failed"&&n(`Warning: reindex succeeded, but activity telemetry was not recorded: ${g.reason}`),Wt(t,I(o.outputDb)),w}catch(S){let m=Nt({trigger:e.trigger,result:"failed",start:a,monotonicStart:s,error:S instanceof Error?S.message:String(S)});ms(o.metaPath,m);let F=ro(o.outputDb,m);throw F.state==="failed"&&n(`Warning: failed reindex activity telemetry was not recorded: ${F.reason}`),S}finally{k&&de(k,{recursive:!0,force:!0}),A(),E.release(),P?.()}}async function Cp(e){let{opts:t,paths:n,languages:r,fingerprint:i,onStatus:o}=e,a=t.projectRoot;if(!(t.skipIfUnchanged!==!1&&!ii(a,n.outputDb)&&$a(n.outputScip)===$a(L(I(n.outputDb),"index.scip"))))return{snapshot:void 0,releaseBuildLock:void 0};let c=Xe(a),u=c?.clean?ct(c,i):void 0;if(c&&!c.clean&&!Ga(n))return Va({context:c,languages:r,opts:t,paths:n,fingerprint:i,projectRoot:a,onStatus:o,successMessage:"dirty worktree reindex",failurePrefix:"Shared baseline fork failed"}),{snapshot:u,releaseBuildLock:void 0};if(!u)return{snapshot:void 0,releaseBuildLock:void 0};let l=Zt(u);if(l){if(!Fp(n,i))try{ut({snapshot:u,manifest:l,targetCacheDir:I(n.outputDb),targetProjectRoot:a}),o(`Attached shared generation ${u.generationId.slice(0,12)}`)}catch(p){o(`Shared generation attach failed; continuing locally: ${pe(p)}`)}return{snapshot:u,releaseBuildLock:void 0}}c&&!Ga(n)&&Va({context:c,languages:r,opts:t,paths:n,fingerprint:i,projectRoot:a,onStatus:o,successMessage:"cold worktree reindex",failurePrefix:"Compatible shared baseline fork failed",compatible:!0});let d=await si(u);if(d.kind==="owner")return{snapshot:u,releaseBuildLock:d.release};if(d.kind==="generation-ready"){let p=Zt(u);if(p)try{ut({snapshot:u,manifest:p,targetCacheDir:I(n.outputDb),targetProjectRoot:a,action:"waited"}),o(`Attached shared generation ${u.generationId.slice(0,12)} after waiting`)}catch(f){o(`Shared generation attach failed after waiting; continuing locally: ${pe(f)}`)}}else o("Shared generation build lock timed out; continuing with an isolated local reindex");return{snapshot:u,releaseBuildLock:void 0}}function Va(e){let t=oi(e.context,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath},e.fingerprint);if(t)try{ut({snapshot:t.snapshot,manifest:t.manifest,targetCacheDir:I(e.paths.outputDb),targetProjectRoot:e.projectRoot,persistLease:!1}),ui(t.snapshot,I(e.paths.outputDb)),e.onStatus(`Forked ${e.compatible?"compatible ":""}shared baseline ${t.snapshot.generationId.slice(0,12)} for ${e.successMessage}`)}catch(n){e.onStatus(`${e.failurePrefix}; continuing locally: ${pe(n)}`)}}function Ua(e){if(e.snapshot)try{let t=Xe(e.projectRoot),n=t?ct(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=ai({snapshot:e.snapshot,sourceCacheDir:I(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let i=Xe(e.projectRoot);return(i?ct(i,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}});ci(e.snapshot,I(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: ${pe(t)}`)}}function Fp(e,t){if(!N(e.outputScip)||!N(e.outputDb)||fs(e.metaPath,t)===null)return!1;let n=X(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function Ga(e){if(!N(e.outputScip)||!N(e.outputDb)||!me(e.metaPath))return!1;let t=X(e.outputDb,e.metaPath);return t.state!=="invalid"&&t.state!=="drifted"}function pe(e){return e instanceof Error?e.message:String(e)}function Ap(e){let t=e?.match(/--max[-_]old[-_]space[-_]size(?:=|\s+)(\d+)/u);if(!t)return;let n=Number.parseInt(t[1],10);return Number.isInteger(n)&&n>0?n:void 0}function Lp(e,t){return[(e??"").replace(/(?:^|\s)--max[-_]old[-_]space[-_]size(?:=|\s+)\d+/gu," ").trim(),`--max-old-space-size=${t}`].filter(Boolean).join(" ")}async function Yn(e,t,n,r,i,o,a,s=!1){try{await zi(Ri({indexPath:n,evidenceDbPath:a,reuseExisting:i,affectedFiles:o,forceDerivedRebuild:s}),{projectRoot:e,dbPath:t,onStatus:r})}catch(c){r(`Runtime-boundary extraction unavailable: ${c instanceof Error?c.message:String(c)}.`)}}function Op(e){let t=e.outputScip??L(e.projectRoot,"index.scip"),n=e.outputDb??L(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:L(I(n),"meta.json")}}async function Dp(e){let t=X(e.paths.outputDb,e.paths.metaPath),n=fs(e.paths.metaPath,e.fingerprint);if(e.opts.skipIfUnchanged===!1||!N(e.paths.outputScip)||!N(e.paths.outputDb)||n===null||t.state==="invalid"||t.state==="drifted")return null;let r=ot(e.paths.outputDb,e.fingerprint,e.languages);if(r.state!=="complete")return e.onStatus(Xn("Accepted SQLite index",r)),null;ke(le(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await Yn(e.opts.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0),X(e.paths.outputDb,e.paths.metaPath).state==="drifted"&&(st(e.paths.outputDb,e.paths.metaPath),e.onStatus("Published refreshed SQLite generation after post-index augmentation")),n==="operational-config-compatible"&&(Sg(e.paths.metaPath,e.fingerprint,e.languages,e.opts),st(e.paths.outputDb,e.paths.metaPath),e.onStatus("Migrated operational .scipquery.json metadata without rerunning language indexers."));let i=C()-e.monotonicStart,o=Nt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return ms(e.paths.metaPath,o),e.onStatus(`Index unchanged; reused existing SQLite index in ${(i/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:i,reused:!0,skipped:[],lastRefresh:o,shards:Mp(e.paths,e.languages,e.opts,e.fingerprint)}}function Mp(e,t,n,r){let i=Kn(r,t,n);return t.map(o=>({id:o,language:o,reused:!0,strategy:"reused",fingerprint:We(i[o]),outputBytes:ge(Qn(e.outputDb,o)),durationMs:0}))}function Np(e){let t=wp(L(I(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:L(t,Ct(e.outputScip)),tempOutputDb:L(t,Ct(e.outputDb)),tempMetaPath:L(t,Ct(e.metaPath))}}function jp(e){let t=[],n;try{n=Ka(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[pe(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{de(L(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${pe(o)}`)}return{removed:r,errors:t}}async function Bp(e){let t={...process.env,NODE_OPTIONS:Lp(process.env.NODE_OPTIONS,e.maxHeapMb)},n,r=await U("reindex.language-indexers",async()=>(n=await Vp(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:a,languageFingerprints:s,shards:c,typescriptProjectShardContext:u,incrementalTypeScript:l}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),$p({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let f=await U("reindex.publish",()=>Kp(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),h=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(h/1e3).toFixed(1)}s`),{languages:i.map(b=>b.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:h,reused:!0,skipped:o,lastRefresh:f,shards:c,writeTelemetry:e.writeTelemetry}}let d=await U("reindex.publish",()=>Yp(e,t,i,o,a,s,u,l),{mode:l?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),p=d.durationMs;return e.onStatus(`Done in ${(p/1e3).toFixed(1)}s`),{languages:i.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:p,reused:!1,skipped:o,lastRefresh:d,shards:c,writeTelemetry:e.writeTelemetry}}function $p(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!N(e.run.paths.outputScip)||!N(e.run.paths.outputDb))return!1;let t=X(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 Vp(e,t){let n=e.opts.skipIfUnchanged===!1,r=Hp({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath,projectFingerprint:e.fingerprint});if(n)for(let[g,x]of r)x.reused&&r.set(g,{...x,reused:!1,reason:"forced reindex requested"});let i=[],o=new Set;for(let[g,x]of r)x.reused&&(i.push({language:g,scipPath:x.scipPath}),o.add(g));for(let g of o)e.onStatus(`Reusing cached ${g} SCIP shard (language inputs unchanged).`);let a=r.get("typescript"),s=X(e.paths.outputDb,e.paths.metaPath),c=me(e.paths.metaPath),u=s.state==="legacy"||s.state==="current",l=c?.scipCompanion!=="deferred"&&(s.state!=="current"||s.generation.publication?.scipCompanion!=="deferred"),d;n&&a&&!a.reused&&(d="forced reindex rebuilds from the compilers");let p=!n&&a&&!a.reused&&u?ra({projectRoot:e.projectRoot,cacheDir:I(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:a.scipPath,candidateShardPath:fe(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:fe(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:Ot(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus,onUnavailable:g=>{d=g}}):null,f=new Set(p?["typescript"]:[]);if(e.opts.allowExpensiveRebuild===!1){let g=e.languages.filter(x=>!o.has(x)&&!f.has(x));if(g.length>0){let x=g.length===1&&g[0]==="typescript"&&d?`: ${d}`:"";throw new Error(`Incremental indexing is unavailable for ${g.join(", ")}${x}. The accepted index was preserved because whole-project rebuilds are disabled; run scip-query reindex --allow-expensive-rebuild only when you explicitly want that fallback.`)}}let h=p||o.has("typescript")?void 0:Up(e,r),b=h&&n?{...h,classification:new Map([...h.classification].map(([g,x])=>[g,x.reused?{...x,reused:!1,reason:"forced reindex requested"}:x])),reusedProjects:[],missedProjectIds:new Set(h.allProjects.map(g=>`typescript:${g}`))}:h,{preparedRuns:P,skippedLanguages:_,languageOutputScipPaths:E}=ng({languages:e.languages.filter(g=>!o.has(g)&&!f.has(g)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,trustProjectTools:e.opts.trustProjectTools===!0,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:b?.allProjects,typescriptShardCostDir:I(e.paths.outputDb),clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),A=b?P.filter(g=>g.language!=="typescript"||b.missedProjectIds.has(g.id)):P,k=await da(A,e.projectRoot,e.onStatus,e.opts.indexerConcurrency,e.opts.signal);if(yr())for(let g of k)br({type:"span",name:`reindex.language-indexer.${g.id}`,durationMs:Math.round(g.durationMs),ok:!g.skipped,language:g.language,indexerCommand:g.command,outputBytes:g.outputBytes,measurement:"indexer-run-result"});ig(I(e.paths.outputDb),e.projectRoot,A,k);let y=[];if(b){Wp(e.paths.outputDb,k,e.writeTelemetry);let g=E.typescript??e.tempPaths.tempOutputScip;y=qp({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:g,reusedProjects:b.reusedProjects,writeTelemetry:e.writeTelemetry})}let S=[...k,...y],{indexedOutputs:m}=ag(S,_),F=p?[{language:"typescript",scipPath:p.scipPath}]:[],R=[...i,...F,...m];sg(R,_,e.languages,e.opts.allowPartial,e.onStatus);let v=p?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:p.scipPath,outputScipPath:p.scipPath,durationMs:p.durationMs,command:"watch-service:typescript-index",outputBytes:ge(p.scipPath)??void 0,producedOutputBytes:ge(p.affectedScipPath)??void 0}]:[],w=Jp(r,[...k,...v],b?{outputDb:e.paths.outputDb,classification:b.classification}:void 0,d);return{indexedOutputs:R,skippedLanguages:_,reusedLanguages:[...o],languageFingerprints:zp(r,e.languages),shards:w,typescriptProjectShardContext:b?{projects:b.allProjects,fingerprints:b.fingerprints}:void 0,incrementalTypeScript:p??void 0}}function Up(e,t){let n=t.get("typescript");if(!n||n.reused||n.cacheIntegrityFailed||e.opts.typescriptProjectMode!=="workspace")return;let r=ne(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=uo(e.projectRoot,r),o=ao(n.fingerprint.files,r),a=so(r,i),s=co(r,o,a),c=me(e.paths.metaPath),l=Gp(c,s,h=>N(Dt(e.paths.outputDb,h))),d=[...l.entries()].filter(([,h])=>h.reused).map(([h])=>h),p=new Set(d),f=new Set(r.filter(h=>!p.has(h)).map(h=>`typescript:${h}`));return{allProjects:r,fingerprints:s,classification:l,reusedProjects:d,missedProjectIds:f}}function Gp(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&&Jt(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(M(a)!==M(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 Wp(e,t,n){for(let r of t){if(r.skipped||!r.id.startsWith("typescript:"))continue;let i=r.id.slice(11),o=Dt(e,i);At(I(o),{recursive:!0}),ue(n,ce(r.scipPath,o))}}function qp(e){return e.reusedProjects.map((t,n)=>{let r=Dt(e.outputDb,t),i=fe(e.tempOutputScip,"typescript-project-cached",n);return ue(e.writeTelemetry,ce(r,i)),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:ge(i)??void 0}})}function Hp(e){let t=me(e.paths.metaPath),n=Kn(e.projectFingerprint,e.languages,e),r=t&&N(e.paths.outputDb)?ot(e.paths.outputDb,e.projectFingerprint,e.languages):null,i=new Map;for(let o of e.languages){let a=Qn(e.paths.outputDb,o),s=n[o];if(!t){i.set(o,{reused:!1,reason:"no reindex metadata found",fingerprint:s,scipPath:a});continue}if(t.version!==Re){i.set(o,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:s,scipPath:a});continue}if(!Jt(t).languageShardReuse||!t.languageFingerprints){i.set(o,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:s,scipPath:a});continue}let c=t.languageFingerprints[o];if(!c){i.set(o,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:s,scipPath:a});continue}if(!N(a)){i.set(o,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:a});continue}let u=o==="typescript"?hg(e.projectRoot,c):c;if(M(u)!==M(s)){i.set(o,{reused:!1,reason:"language inputs changed since last index",fingerprint:s,scipPath:a});continue}if(r?.state==="unavailable"||r?.state==="incomplete"&&r.affectedLanguages.includes(o)){i.set(o,{reused:!1,reason:Xn("accepted SQLite index",r),cacheIntegrityFailed:!0,fingerprint:s,scipPath:a});continue}i.set(o,{reused:!0,fingerprint:s,scipPath:a})}return i}function Jp(e,t,n,r){let i=[];for(let[o,a]of e)a.reused&&i.push({id:o,language:o,reused:!0,strategy:"reused",fingerprint:We(a.fingerprint),outputBytes:ge(a.scipPath),durationMs:0});for(let o of t){let a=e.get(o.language),s=n&&o.id.startsWith("typescript:")?o.id.slice(11):null,c=s?n.classification.get(s):void 0;i.push({id:o.id,language:o.language,reused:!1,strategy:o.command==="watch-service:typescript-index"?"incremental":"full",missReason:c?.reason??a?.reason??o.skipped?.reason,fallbackReason:o.language==="typescript"?r:void 0,fingerprint:c?We(c.fingerprint):a?We(a.fingerprint):"unknown",outputBytes:o.outputBytes??null,producedOutputBytes:o.producedOutputBytes,durationMs:o.durationMs,command:o.command})}if(n)for(let[o,a]of n.classification)a.reused&&i.push({id:`typescript:${o}`,language:"typescript",reused:!0,strategy:"reused",fingerprint:We(a.fingerprint),outputBytes:ge(Dt(n.outputDb,o)),durationMs:0});return i}function We(e){return Tp("sha256").update(M(e)).digest("hex").slice(0,16)}function ge(e){try{return zn(e).size}catch{return null}}function zp(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}async function Yp(e,t,n,r,i,o,a,s){B(e.opts.signal,"Reindex cancelled by its owner.");let c=!s||s.completeScipUpdated,u=!1;c&&(u=T("reindex.publish.scip-output",()=>{let y=eg({run:e,indexedOutputs:n,incrementalTypeScript:s,typescriptReused:i.includes("typescript")});return Wa(e.paths.outputDb,y,e.writeTelemetry),qa(y,e.tempPaths.tempOutputScip,e.onStatus)}));let l=await U("reindex.publish.sqlite-output",()=>cg({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:u,materializeFullFallback:async()=>{if(B(e.opts.signal,"Reindex cancelled by its owner."),!s||s.completeScipUpdated)return u;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),Nn({cacheDir:I(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let y=n.map(S=>S.language==="typescript"?{language:S.language,scipPath:s.candidateScipPath}:S);return Wa(e.paths.outputDb,y,e.writeTelemetry),u=qa(y,e.tempPaths.tempOutputScip,e.onStatus),u}}));B(e.opts.signal,"Reindex cancelled by its owner."),T("reindex.publish.auxiliary-documents",()=>{ke(le(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus})}),await U("reindex.publish.runtime-boundaries",async()=>{let y=s?.plan.mode==="full-project",S=s?.dependencyGraphUnchanged===!0;y?e.onStatus("Rebuilding compiler-derived runtime-boundary relationships while retaining unchanged per-file extraction facts."):S&&e.onStatus("Reusing runtime-boundary relationships because TypeScript semantics are unchanged."),await Yn(e.projectRoot,e.tempPaths.tempOutputDb,e.tempPaths.tempOutputScip,e.onStatus,S,S?void 0:y?s?.changedFiles:s?.affectedFiles,L(I(e.paths.outputDb),mr),y)});let d=T("reindex.publish.sqlite-layout",()=>gn(e.tempPaths.tempOutputDb,{analyze:Xp(s,l.mode)}));d.added.length>0&&e.onStatus(`Added SQLite query indexes: ${d.added.join(", ")}`),d.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${d.removed.join(", ")}`),T("reindex.publish.coverage",()=>rs(e,e.tempPaths.tempOutputDb,n.map(y=>y.language)));let p,f=null;l.mode==="incremental"&&s&&T("reindex.publish.reference-fragments",()=>{if(s.dependencyGraphUnchanged){let m=new V({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});try{f=zt(m),e.onStatus("Preserved exact TypeScript reference fragments and dependency relationships because only trivia changed.")}finally{m.close()}return}let y=null,S=null;try{y=T("reindex.publish.reference-fragments.open-candidate",()=>new V({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip})),S=T("reindex.publish.reference-fragments.open-evidence",()=>new V({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip})),p=s.dependencyGraphSnapshot?T("reindex.publish.reference-fragments.dependency-graph",()=>Ir(y,s.dependencyGraphSnapshot,s.affectedFiles,s.deletedFiles))??void 0:void 0;let m=new Set(s.deletedFiles),F=m.size===0?s.referenceFragmentsByFile:new Map([...s.referenceFragmentsByFile].filter(([v])=>!m.has(v))),R=T("reindex.publish.reference-fragments.seed",()=>jr(y,e.fingerprint,F,S,p,new Set(s.affectedFiles)));e.onStatus(`Cached exact TypeScript reference fragments for ${R.affectedFiles} affected document(s) and carried ${R.carriedFiles} unaffected document(s) forward.`),R.skippedAffectedFiles>0&&e.onStatus(`Skipped exact TypeScript reference fragment prefill for ${R.skippedAffectedFiles} affected document(s) whose semantic identity was unavailable.`)}catch(m){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${m instanceof Error?m.message:String(m)}.`)}finally{y?.close(),S?.close()}});let h=Ot(e.paths.metaPath),b=T("reindex.publish.affected-shadow",()=>l.mode==="incremental"&&s?lg(s,l.changedDocumentPaths):sn({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:h,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"})),P=Nt({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(y=>y.language),skipped:[...r]}),_=l.mode==="incremental"&&l.scipCompanion==="deferred",{metadata:E,pruneProjects:A}=ts({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:o,typescriptProjectShardContext:a,lastRefresh:P});E.scipCompanion=_?"deferred":"current",T("reindex.publish.metadata",()=>{ns(e),is(e.paths.outputDb,A),Mt(e.tempPaths.tempMetaPath,E)});let k=T("reindex.publish.generation-handoff",()=>ni({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:l.mode==="incremental"&&l.scipCompanion==="deferred",publication:l.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:l.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:l.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:l.patchDurationMs,scipCompanion:l.scipCompanion,...l.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:l.converterDurationMs,scipCompanion:"current",...l.fallbackReason?{fallbackReason:l.fallbackReason}:{}}}));return k.achievedDurability==="file-flushed"&&e.onStatus(`Published local generation ${k.currentGeneration.slice(0,12)} (file-flushed; directory sync unsupported)`),l.mode==="incremental"&&s&&T("reindex.publish.dependency-graph",()=>{let y=null;try{y=new V({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let S=s.plan.mode==="full-project"&&s.plan.reasons.length===0?s.changedFiles:s.affectedFiles,m=!1;if(s.dependencyGraphUnchanged){let F=zt(y),R=f&&F?hr(y,"file-dependency-graph",f,F):0;m=R>0,e.onStatus(m?`Carried ${R} unchanged dependency graph product(s) forward without rebuilding them.`:"No persisted dependency graph product required rekeying; the next graph consumer can materialize it.")}else s.dependencyGraphSnapshot?m=Pr(y,s.dependencyGraphSnapshot,S,p):et(y);s.dependencyGraphUnchanged||e.onStatus(m?`Carried the dependency graph forward by replacing ${S.length} changed dependency owner(s).`:"Materialized a fresh dependency graph for the accepted generation because no compatible prior graph was available.")}catch(S){e.onStatus(`Dependency graph carry-forward unavailable: ${S instanceof Error?S.message:String(S)}. The next graph consumer will rebuild it.`)}finally{y?.close()}}),T("reindex.publish.cleanup",()=>{Kr(I(e.paths.outputDb),l.mode==="incremental"&&l.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),zr(I(e.paths.outputDb),s?.completeScipUpdated?[s.nextFragmentGeneration]:[])}),T("reindex.publish.shadow-telemetry",()=>es(e.paths.outputDb,b,e.onStatus)),P}function Xp(e,t){return t!=="incremental"||!e||e.plan.mode==="full-project"?!0:e.affectedFiles.length*20>=e.projectFileCount}async function Kp(e,t,n,r,i,o){let a=Ot(e.paths.metaPath),s=null;try{ue(e.writeTelemetry,ce(e.paths.outputDb,e.tempPaths.tempOutputDb))}catch(p){s=Ci("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}ke(le(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await Yn(e.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0);let c=gn(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(", ")}`),rs(e,e.paths.outputDb,t.map(p=>p.language)),s??=sn({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=Nt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=ts({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:u});return ns(e),is(e.paths.outputDb,d),Mt(e.paths.metaPath,l),st(e.paths.outputDb,e.paths.metaPath),es(e.paths.outputDb,s,e.onStatus),u}function Ot(e){return Bt(me(e)?.fingerprint)}function es(e,t,n){try{Ai(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 ts(e){let t=Qp({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 ns(e){B(e.opts.signal,"Reindex cancelled by its owner.");let t=lr(e.projectRoot,e.fingerprint);if(M(t)===M(e.fingerprint))return;let n=new Map(e.fingerprint.files.map(o=>[o.path,o])),r=new Map(t.files.map(o=>[o.path,o])),i=[...new Set([...n.keys(),...r.keys()])].filter(o=>M(n.get(o))!==M(r.get(o))).slice(0,5);throw new Error(`Project inputs changed during reindex (${i.join(", ")||"unknown path"}); refusing to publish artifacts built from a different filesystem snapshot.`)}function rs(e,t,n){let r=ot(t,e.fingerprint,n);if(r.state!=="complete")throw new Error(`${Xn("Candidate SQLite index",r)} Refusing to publish it.`)}function Xn(e,t){if(t.state==="unavailable")return`${e} document coverage could not be verified (${t.reason}); rebuilding cached language shards.`;let n=t.missingPaths.length>0?` First missing path: ${t.missingPaths[0]}.`:"";return`${e} is missing ${t.missingDocumentCount} fingerprinted source document${t.missingDocumentCount===1?"":"s"}; rebuilding affected language shards.${n}`}function Qp(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=me(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 is(e,t){let n=gs(e);if(t===null){de(n,{recursive:!0,force:!0});return}let r;try{r=Ka(n)}catch{return}for(let i of Zp(r,t))de(L(n,i),{force:!0})}function Zp(e,t){let n=new Set(t.map(r=>`${Rn(r)}.scip`));return e.filter(r=>!n.has(r))}function eg(e){if(e.incrementalTypeScript?.completeScipUpdated)return[...e.indexedOutputs];let t=e.indexedOutputs.find(a=>a.language==="typescript");if(!t)return[...e.indexedOutputs];if(!e.typescriptReused)return[...e.indexedOutputs];let n=X(e.run.paths.outputDb,e.run.paths.metaPath),r=n.state==="current"?n.generation.publication?.typescriptOverlayGeneration:void 0;if(!(n.state==="current"?n.generation.publication?.scipCompanion==="deferred":me(e.run.paths.metaPath)?.scipCompanion==="deferred")||!r)return[...e.indexedOutputs];let o=fe(e.run.tempPaths.tempOutputScip,"typescript-deferred",0);return e.run.onStatus("Materializing the deferred whole TypeScript SCIP companion for complete publication..."),Nn({cacheDir:I(e.run.paths.outputDb),generationIdentity:r,baseShardPath:t.scipPath,candidateShardPath:o}),e.indexedOutputs.map(a=>a.language==="typescript"?{language:a.language,scipPath:o}:a)}function Wa(e,t,n){for(let r of t){let i=Qn(e,r.language);At(I(i),{recursive:!0}),r.scipPath!==i&&ue(n,ce(r.scipPath,i))}}async function tg(e,t){if(!Ee()){if(_p()==="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.
360
- To install the reviewed version, run: scip-query reindex --install-missing
361
- Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!hi(t))throw new Error(`The scip CLI is required but could not be installed.
362
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function ng(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?fe(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=rg({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?os(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function rg(e){if(e.language!=="typescript")return[Ft({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.typescriptProjectMode==="workspace",n=t?e.preDiscoveredTypeScriptProjects??ne(e.projectRoot,e.typescriptProjects):["."];return n.length===0?[Ft({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(t&&e.onStatus(`Indexing TypeScript workspace as ${n.length} project shard(s).`),n.flatMap((r,i)=>{let o=t?`typescript:${r}`:"typescript",a=t?`typescript (${r})`:"typescript",s=t?fe(e.tempOutputScip,"typescript-project",i):e.scipPath,c={...e,id:o,label:a,scipPath:s,outputScipPath:e.scipPath,pnpmWorkspaces:!1};if(!t&&r==="."&&!e.pnpmWorkspaces){let u=og(e,c);if(u)return u}return[Ft({...c,...t?{projectPath:r}:{}})]}))}function ig(e,t,n,r){let i=n.filter(s=>s.shardInputPaths!==void 0);if(i.length===0)return;let o=new Map(r.filter(s=>!s.skipped).map(s=>[s.id,s.durationMs])),a=[];for(let s of i){let c=o.get(s.id);if(c===void 0||!(c>0))return;a.push({inputPaths:s.shardInputPaths,durationMs:c})}try{let s=Ao(a,c=>{try{return zn(L(t,c)).size}catch{return 1}});s&&Co(e,s)}catch{}}function og(e,t){let n=In(),r=Gt(e.projectRoot,"single");if(!r||!Eo(r.size,n))return null;Oo(e.projectRoot);let i=Lo(),o=To(r.size,n,i),a=e.typescriptShardCostDir?_o(e.typescriptShardCostDir):null,s=Fo(a),c=wo({projectRoot:e.projectRoot,rootConfigPath:"tsconfig.json",inputPaths:[...r],targetFiles:n,shardCount:o,weightOf:l=>{let d=1;try{d=zn(L(e.projectRoot,l)).size}catch{}return s(l,d)}}),u=Math.min(i,c.length);return e.onStatus(`Indexing ${r.size} TypeScript inputs as ${c.length} ${a?"cost-balanced":"byte-balanced"} compiler shard(s), ${u} at a time.`),c.map((l,d)=>Ft({...t,id:`typescript-compiler-shard:${d}`,label:`typescript compiler shard ${d+1}/${c.length}`,scipPath:fe(e.tempOutputScip,"typescript-compiler-shard",d),projectPath:l.configPath,temporaryProjectConfigs:[{path:l.configPath,content:l.content}],boundedConcurrency:u,outputComposition:"protobuf-concatenate",shardInputPaths:l.inputPaths}))}function Ft(e){let t=cn(e.language),n=tt(t),r=kr(t,e.projectRoot),i=e.trustProjectTools&&r?_r(t,e.projectRoot):null,o=Oe(t);if(!i&&!o&&r){let l=`${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}: ${l}`),{skipped:{language:e.language,reason:l}}}if(!i&&!o&&!wr(t)){if(e.skipAutoInstall){let l=`${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}: ${l}`),{skipped:{language:e.language,reason:l}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!fa(t,e.onStatus)){let l=`${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}: ${l}`),{skipped:{language:e.language,reason:l}}}}let a=i?.canonicalPath??Oe(t);if(!a){let l=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}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}),u=Bi({language:e.language,projectPath:e.projectPath,pnpmWorkspaces:e.pnpmWorkspaces});if(i&&!i.executable){let l=`${i.relativePath} is not executable; refusing project-local indexer.`;return e.onStatus(`Skipping ${e.language}: ${l}`),{skipped:{language:e.language,reason:l}}}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:Fr(t,e.env,a),...u===void 0?{}:{temporaryRootConfigContent:u},...e.temporaryProjectConfigs===void 0?{}:{temporaryProjectConfigs:e.temporaryProjectConfigs},...e.boundedConcurrency===void 0?{}:{boundedConcurrency:e.boundedConcurrency},...e.outputComposition?{outputComposition:e.outputComposition}:{},...e.shardInputPaths===void 0?{}:{shardInputPaths:e.shardInputPaths},...i?{trustedProjectTool:i}:{}}}}function ag(e,t){let n=new Set(e.filter(o=>o.skipped&&o.outputComposition).map(o=>`${o.language}\0${o.outputScipPath}`)),r=new Map;for(let o of e)if(o.skipped)os(t,o.skipped);else{let a=`${o.language}\0${o.outputScipPath}`;if(n.has(a))continue;let s=r.get(a)??{language:o.language,outputScipPath:o.outputScipPath,scipPaths:[],concatenate:!0};s.scipPaths.push(o.scipPath),o.outputComposition!=="protobuf-concatenate"&&(s.concatenate=!1),r.set(a,s)}let i=[];for(let o of r.values())if(o.scipPaths.length>1)o.concatenate?ei(o.scipPaths,o.outputScipPath):Zr(o.scipPaths,o.outputScipPath),i.push({language:o.language,scipPath:o.outputScipPath});else{let a=o.scipPaths[0];a!==o.outputScipPath&&Qa(a,o.outputScipPath),i.push({language:o.language,scipPath:o.outputScipPath})}return{indexedOutputs:i}}function os(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 sg(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
363
- `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
364
- `+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.
365
- `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
366
- `))}function qa(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=ti(e.map(o=>o.scipPath),t);return ss(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Qa(e[0].scipPath,t);return!1}async function cg(e){let t;if(ug(e))try{let i=e.incrementalTypeScript.affectedBatches.length>0?e.incrementalTypeScript.affectedBatches:[{scipPath:e.incrementalTypeScript.affectedScipPath,affectedFiles:e.incrementalTypeScript.affectedFiles,deletedFiles:e.incrementalTypeScript.deletedFiles}],o=new Set,a=0,s=0;for(let[c,u]of i.entries()){let l=L(e.run.tempPaths.runDir,`typescript-affected-${c}.db`);as(u.scipPath,e.run.onStatus),e.run.onStatus(`Converting bounded TypeScript batch ${c+1}/${i.length} (${u.affectedFiles.length-u.deletedFiles.length} emitted, ${u.deletedFiles.length} removed) to SQLite...`);let d=performance.now();await Ha(u.scipPath,l,e.env,e.run.onStatus,!0,e.run.opts.signal),a+=performance.now()-d,pt(e.run.writeTelemetry,ge(l)??0);let p=Wi({previousDbPath:e.run.paths.outputDb,miniDbPath:l,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:u.affectedFiles,deletedFiles:u.deletedFiles,reuseCandidate:c>0,deferIntegrity:c<i.length-1,trustedPriorGeneration:!0,writeTelemetry:e.run.writeTelemetry});s+=p.durationMs;for(let f of p.changedDocumentPaths)o.add(f);de(l,{force:!0})}return e.run.onStatus(`Patched ${e.incrementalTypeScript.affectedFiles.length} SQLite document path(s) across ${i.length} bounded batch(es) in ${(s/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:[...o].sort(),patchDurationMs:s,converterDurationMs:a,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(i){if(B(e.run.opts.signal,"Reindex cancelled by its owner."),t=i instanceof Error?i.message:String(i),de(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.opts.allowExpensiveRebuild===!1)throw new Error(`Bounded incremental SQLite publication failed and the whole-project fallback is disabled: ${t}`,{cause:i});e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}let n=e.completeScipSanitized;e.completeScipAvailable||(n=await e.materializeFullFallback());let r=performance.now();return await Ha(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n,e.run.opts.signal),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function ug(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!N(e.run.paths.outputDb)||!N(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 lg(e,t){let n=C(),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:C()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:an(e.plan,o,e.projectFileCount)}}async function Ha(e,t,n,r,i=!1,o){if(B(o,"Reindex cancelled by its owner."),r("Converting to SQLite..."),!N(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{if(i||as(e,r),n.SCIP_QUERY_SQLITE_CONVERTER==="scip-cli"){let a=Ee();if(!a)throw new Error("scip CLI is not available");let s=await lt({command:a,args:["expt-convert","--output",t,e],label:"SCIP SQLite conversion",env:n,maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,timeoutMs:3e5,signal:o});if(s.status!==0)throw new Error(`scip expt-convert exited with ${s.status}${s.stderr.trim()?`: ${s.stderr.trim()}`:""}`)}else de(t,{force:!0}),await Po(J(e,{maxBytes:Je,inputKind:"SCIP index"}),t,{signal:o})}catch(a){B(o,"Reindex cancelled by its owner.");let s=a instanceof Error?a.message:String(a);throw new Error(`Failed to convert SCIP index to SQLite: ${s}`,{cause:a})}}function as(e,t){let n=Qr(e);ss(n,t)}function ss(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function fe(e,t,n){let r=kp(e)||".scip",i=Ct(e,r);return L(I(e),`${i}.${n+1}.${t}${r}`)}async function dg(e,t){for(let n=0;n<2;n++){let r=pg(e,t);if(r)return r;let i=gg(e);if(i&&ls(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await fg(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: ${pe(s)}`,{cause:s})}if(!o)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${I(e)}; refusing to steal an active lock.`);let a=Xt(e,{parseLegacy:Lt});if(!Wr(e,a,{parseLegacy:Lt}))throw new Error(`Reindex lock ownership changed before preemption completed for ${I(e)}.`);continue}throw new Te(`Another scip-query reindex is already running for ${I(e)}.`)}throw new Te(`Could not acquire scip-query reindex lock for ${I(e)}.`)}function pg(e,t){let n=Y(process.pid),r=it(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:Lt});if(r.kind==="acquired"&&r.reclaimed){let i=cs(r.reclaimed,e);i&&ls(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 ${I(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function gg(e){return cs(Xt(e,{parseLegacy:Lt}),e)}var Lt=e=>{let t=us(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function cs(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:I(t),startedAt:e.record.startedAt,trigger:n.trigger}}return us(e.parsed,t)}function us(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=Ar(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:I(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function ls(e,t){return e?.kind==="manual-cli"&&ds(t?.trigger)}function ds(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function fg(e){return!Pe(e.pid)||(Jn(e),Ja(e,"SIGTERM"),await za(e,2e3))?!0:(Jn(e),Ja(e,"SIGKILL"),za(e,1e3))}function Ja(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!Pe(e.pid))return;Jn(e)}try{process.kill(e.pid,t)}catch{}}async function za(e,t){let n=C()+t;for(;C()<n;){if(Ya(e))return!0;await mg(50)}return Ya(e)}function Jn(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=Y(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!De(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function Ya(e){if(!Pe(e.pid))return!0;if(!e.processIdentity)return!1;let t=Y(e.pid);return t!==null&&!De(e.processIdentity,t)}function mg(e){return new Promise(t=>setTimeout(t,e))}function Kn(e,t,n){return Object.fromEntries(t.map(r=>{let i=r==="typescript"?ar(n.typescriptProjects):[],o=r==="clojure"?yg(n.clojureConfigPath):void 0,a=[...cn(r).markerFiles,...i,...o?[o]:[]],s=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:i}:{typescriptProjectMode:"single",typescriptProjects:[]};return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&bg(n),...s,clojureConfigPath:o,files:e.files.filter(c=>tr(c.path,r,a)).map(c=>ps(c,r))}]}))}function ps(e,t){let n=t==="typescript"&&/(?:^|\/)package\.json$/iu.test(e.path)?e.semanticHash:void 0;return{path:e.path,size:n===void 0?e.size:0,hash:n??e.hash}}function hg(e,t){let n=Bt(t);if(!n)return t;let r=n.typescriptProjectMode==="workspace"?ne(e,n.typescriptProjects):["."],i=be(r);return{...n,files:n.files.filter(o=>!Se(o.path)||i.has(o.path)).map(o=>{let a=o.semanticHash??Ke(e,o.path,o.hash);return ps(a===void 0?o:{...o,semanticHash:a},"typescript")})}}function yg(e){return e?.trim()||void 0}function bg(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Qn(e,t){return L(I(e),"language-indexes",`${t}.scip`)}function gs(e){return L(I(e),"language-indexes","typescript-projects")}function Dt(e,t){return L(gs(e),`${Rn(t)}.scip`)}function me(e){try{return Qe(re($(e,"reindex metadata")))}catch{return null}}function fs(e,t){try{let n=re($(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return null;let r=n.metadata;return!n.capabilities.publishableGeneration||!fr(r)||M([...r.indexedLanguages??[]].sort())!==M(t.languages)?null:M(r.fingerprint)===M(t)?"exact":M(Xa(r.fingerprint))===M(Xa(t))?"operational-config-compatible":null}catch{return null}}function Xa(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return Array.isArray(t.files)?{...t,files:t.files.filter(n=>typeof n!="object"||n===null||Array.isArray(n)||n.path!==".scipquery.json")}:e}function Sg(e,t,n,r){let i=Qe(re($(e,"reindex metadata")));i&&Mt(e,{...i,fingerprint:t,...i.version===Re?{languageFingerprints:Kn(t,n,r)}:{}})}function Mt(e,t){Lr(e,t,{spacing:2,trailingNewline:!0})}function ms(e,t){try{let n=Qe(re($(e,"reindex metadata")));if(!n)return;Mt(e,{...n,lastRefresh:t})}catch{}}function Nt(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:C()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function M(e){return JSON.stringify(e)}function ob(e,t,n,r){return Za({projectRoot:e,languages:r.languages?.length?r.languages:t.languages,outputScip:n.indexPath,outputDb:n.dbPath,pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,maxHeapMb:t.indexer?.typescript?.maxHeapMb,clojureConfigPath:t.indexer?.clojure?.configPath,skipIfUnchanged:r.force!==!0,allowPartial:r.allowPartial===!0,allowExpensiveRebuild:r.allowExpensiveRebuild===!0||r.force===!0,skipAutoInstall:r.skipAutoInstall===!0,installMissing:r.installMissing===!0,trustProjectTools:r.trustProjectTools===!0,indexerConcurrency:r.indexerConcurrency??t.indexerConcurrency,trigger:r.trigger,...r.onStatus?{onStatus:r.onStatus}:{}})}export{Eg as a,Tg as b,Si as c,gf as d,ff as e,cn as f,tu as g,$f as h,au as i,Vf as j,G as k,Uo as l,vl as m,fa as n,sp as o,Za as p,ob as q};
367
- //# sourceMappingURL=chunk-E44IVWIJ.js.map