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
package/dist/reindex.js CHANGED
@@ -1,6 +1,6 @@
1
- import{a as Z}from"./chunk-XU75YQN4.js";import{a as bo,b as Ro,c as Mt,d as qn,h as Wn,i as jt,j as wo,k as Eo,m as Hn,n as To}from"./chunk-AMIMMNA4.js";import{a as Fi,b as z,c as Et,d as Tn,e as Ai,f as Oi,g as Pe,h as Ge,i as Li,j as Ct,k as kn,l as Q,m as Mi,o as ji,p as nt,q as Dt,r as _t,t as Cn,u as we,v as rt,w as So}from"./chunk-ISIQLPJ2.js";import{e as xo,f as Io,g as vo,i as Po}from"./chunk-N7FP5H5U.js";import"./chunk-JFQBRL3J.js";import{a as Ve,b as it,c as Ue,d as jn,e as Nn,f as lo,g as po,h as Gn,k as $n,l as fo,m as Bn,n as Vn,o as mo,p as go,q as ho,r as Un,t as qe,z as yo}from"./chunk-TUSPIVZ3.js";import"./chunk-AYPDH2LU.js";import"./chunk-KK7GPALL.js";import"./chunk-5H5WTJSD.js";import{a as Ci,b as et,c as ee,d as fe,e as _,f as kt,i as ge,j as Y,k as Mn,l as uo}from"./chunk-HG722PO7.js";import"./chunk-Q6T2CAJL.js";import"./chunk-YUKYB54I.js";import{b as oo,c as Lt,d as ao,e as so,f as co}from"./chunk-4GAQ6FI4.js";import"./chunk-TD7VKJ2Y.js";import"./chunk-42W3LFUK.js";import{L as ro,M as io,a as Ot}from"./chunk-7JYHQAH2.js";import{g as Zi,h as ae,j as Ln,k as eo,r as to,t as w,u as te,v as no}from"./chunk-Q7GBK5T7.js";import{A as En,B as ki,Ba as Xi,C as q,Ca as An,D as pe,Da as Ki,E as G,Ea as Qi,Fa as On,H as j,I as L,J as U,K as Di,N as _i,O as wt,S as Tt,T as me,U as tt,V as Ni,W as Gi,Z as Ft,aa as $i,b as vn,ba as Ee,ca as $e,da as Be,e as Pn,ea as Bi,f as wn,fa as Vi,g as Me,ga as Dn,h as Ei,ha as At,i as Ze,ia as Ui,j as It,k as vt,ka as qi,l as je,la as Wi,m as V,ma as Hi,na as zi,pa as _n,qa as Fn,sa as Yi,w as Ne,x as oe,xa as Ji,y as Pt,z as Ti}from"./chunk-GH5YSGZL.js";import{createHash as $g}from"crypto";import{existsSync as H,mkdirSync as hn,mkdtempSync as Bg,readdirSync as Sd,renameSync as bd,rmSync as _e,statSync as bi}from"fs";import{basename as mn,dirname as E,extname as Vg,join as N,resolve as sd}from"path";import{platform as Ug}from"os";import{execFileSync as Gd}from"child_process";import{constants as $d,copyFileSync as ko,statSync as Bd}from"fs";import{platform as Vd}from"os";var Ud=Object.freeze({size:e=>Bd(e).size,clone:Wd,copy:(e,t)=>ko(e,t)}),qd=new Set(["ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL","EXDEV","ENOTTY"]);function Te(e,t,n=Ud){let r=n.size(e);try{return n.clone(e,t),{method:"reflink",bytes:r}}catch(i){if(!zd(i))throw i}return n.copy(e,t),{method:"copy",bytes:r}}function Wd(e,t){if(Vd()!=="darwin"){ko(e,t,$d.COPYFILE_FICLONE_FORCE);return}try{Gd("/bin/cp",["-c",e,t],{timeout:6e4,maxBuffer:64*1024,stdio:["ignore","ignore","pipe"]})}catch(n){throw Hd(n)}}function Hd(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 zd(e){let t=e?.code;return t!==void 0&&qd.has(t)}function Co(){return{reflinkedBytes:0,fallbackCopiedBytes:0,incrementalWrittenBytes:0}}function ke(e,t){t.method==="reflink"?e.reflinkedBytes+=t.bytes:e.fallbackCopiedBytes+=t.bytes}function Nt(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 Yd from"better-sqlite3";import{execFileSync as Jd}from"child_process";import{existsSync as Xd,readdirSync as Kd}from"fs";import{extname as Gt,join as Qd}from"path";function he(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Do({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Do(e){let t=new Set((e.extensions??ro).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Xd(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=So(e.projectRoot),r=Zd(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Yd(e.dbPath);try{let o=tu(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
2
- VALUES (?, ?, NULL, ?)`),c=i.transaction(u=>{let l=0;for(let p of u){if(o.has(p))continue;let m=Ji(e.projectRoot,p,{inputKind:"auxiliary source file"}),g=a.run(nu(p),p,m);l+=Number(g.changes)}return l})(r),d={scanned:r.length,inserted:c,existing:r.length-c};return e.onStatus?.(`Augmented SQLite documents with ${c} auxiliary source file${c===1?"":"s"} (${d.existing} already present).`),d}finally{i.close()}}function Zd(e,t){let n=eu(e,t);if(n)return n;let r=[],i=o=>{let a=o?Qd(e,o):e,s;try{s=Kd(a,{withFileTypes:!0})}catch{return}for(let c of s){if(io.has(c.name))continue;let d=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(d);continue}t.has(Gt(c.name).toLowerCase())&&r.push(d)}};return i(""),r.sort()}function eu(e,t){try{return Jd("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}).split(`
3
- `).filter(r=>r&&t.has(Gt(r).toLowerCase())).sort()}catch{return null}}function tu(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 nu(e){return Gt(e).toLowerCase()===".vue"?"vue":Gt(e).replace(/^\./,"").toLowerCase()||"source"}import{dirname as ru,join as iu}from"path";function _o(e={}){return{id:"runtime-boundaries",facts:["runtime-boundary-observation","runtime-boundary-link"],run:async({projectRoot:t,dbPath:n,onStatus:r})=>{let i=new Z({projectRoot:t,dbPath:n,indexPath:e.indexPath??iu(ru(n),"index.scip"),...e.evidenceDbPath?{evidenceDbPath:e.evidenceDbPath}:{}}),o,a=!1,s=!1;try{let d=e.reuseExisting||e.affectedFiles?Po(i):null;e.reuseExisting&&d?.extractorVersion===xo?(o=d,a=!0):(o=await Io(i,{...d?{previousGraph:d}:{},...e.affectedFiles?{affectedFiles:e.affectedFiles}:{},...e.forceDerivedRebuild?{forceDerivedRebuild:!0}:{},profileSpan:w}),s=(o.coverage.filesReused??0)>0)}finally{i.close()}a||vo(n,o);let c={reused:a,incrementallyUpdated:s,observations:o.observations.length,links:o.links.length,frontiers:o.frontiers.length,filesScanned:o.coverage.filesScanned,errors:o.coverage.extractionErrors.length,phases:o.coverage.phases};return r?.(c.reused?`Reused ${c.observations} cached runtime-boundary observation(s) and ${c.links} link(s).`:c.incrementallyUpdated?`Incrementally refreshed runtime-boundary observations (${c.filesScanned-(o.coverage.filesReused??0)} file(s) extracted, ${o.coverage.filesReused??0} reused) and rebuilt ${c.links} link(s).`:`Extracted ${c.observations} runtime-boundary observation(s), ${c.links} link(s), and ${c.frontiers} unresolved frontier(s).`),!a&&o.coverage.phases&&r?.(`Runtime-boundary phases: ${o.coverage.phases.map(d=>`${d.id} ${d.durationMs.toFixed(0)}ms`).join(", ")}.`),c}}}import{createHash as au}from"crypto";import{existsSync as su}from"fs";import{dirname as cu,join as Ao}from"path";function zn(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 ot(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=zn(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"),Fo(r,i,a)):a.size>0?Fo(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:ou(r,t,i),reasons:[]}}function Fo(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function ou(e,t,n){let r=new Map;for(let[a,s]of t)if(n.has(a))for(let c of s){if(!n.has(c))continue;let d=r.get(c)??new Set;d.add(a),r.set(c,d)}let i=new Set(e),o=[...e];for(let a=0;a<o.length;a+=1){let s=o[a];if(s!==void 0)for(let c of r.get(s)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}var du="<global-symbols>";function uu(e){let t=[];for(let n of e.all(`
1
+ import{a as V}from"./chunk-WDNVY4E7.js";import{A as Wt,B as Gr,D as Ye,E as Wr,F as qr,G as Hr,H as zr,I as Jr,J as Yr,K as Xr,L as Xe,M as Y,N as Ke,P as Kr,Q as qt,R as Qr,S as Zr,T as Qe,U as ei,V as ti,W as ni,a as Tr,b as wr,c as qe,d as He,e as kr,f as _r,g as Fr,h as Cr,j as Or,l as Dr,m as Bt,n as ze,o as Nr,p as $r,q as Ut,r as re,s as ie,t as Je,u as Vr,v as ns,w as Gt,x as Br,y as Ur}from"./chunk-WNTFFKAX.js";import{a as zn,b as $,c as Jn,d as kt,e as Yn,g as Xn,u as _t,x as Er}from"./chunk-5ENOG4VP.js";import{e as Ar,f as Mr,g as Lr,i as jr}from"./chunk-VUPHCS7Y.js";import"./chunk-WOIKCX6A.js";import{a as Se,b as ke,c as be,d as At,e as Mt,f as Sr,g as br,h as Lt,k as jt,l as Rr,m as Nt,n as $t,o as xr,p as Pr,q as vr,r as Vt,t as Re,z as Ir}from"./chunk-WB3WYIRE.js";import"./chunk-DYGHBZ2N.js";import"./chunk-KK7GPALL.js";import"./chunk-OSSESPDX.js";import{a as qn,b as we,c as J,d as ge,e as F,i as $e,j as Kn,k as Dt,l as yr}from"./chunk-TRNAEQ6P.js";import"./chunk-NJITK2GP.js";import"./chunk-YUKYB54I.js";import{b as mr,c as Ge,d as We,e as fr,f as gr,g as hr}from"./chunk-TEBQMNVI.js";import"./chunk-N2ZSIIGR.js";import"./chunk-ODDUPDP7.js";import{L as dr,M as pr,a as Ue}from"./chunk-ZOHS7AQV.js";import"./chunk-FESCRNVV.js";import{A as lr,g as sr,j as Ot,q as cr,v as ur,y as I,z as B}from"./chunk-JWTGMPIT.js";import{A as Tt,Aa as nr,B as Wn,C as me,D as wt,E as Ne,Ea as rr,Fa as ir,Ga as or,H as fe,Ha as ar,I as N,J as U,K as Hn,Z as Ve,ca as Qn,da as ne,e as It,ea as he,fa as ye,g as Le,ga as Zn,h as Bn,ha as er,i as Et,ia as Ft,j as Un,ka as Be,l as z,m as M,sa as Ct,va as tr,w as pe,x as te,y as je,z as Gn}from"./chunk-N5B2NILC.js";import{createHash as fd}from"crypto";import{existsSync as j,mkdirSync as yt,mkdtempSync as gd,readdirSync as Aa,renameSync as Ma,rmSync as se,statSync as An}from"fs";import{basename as gt,dirname as v,extname as hd,join as D,resolve as Pa}from"path";import{platform as va}from"os";function ri(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 ii(e,t){return[(e??"").replace(/(?:^|\s)--max[-_]old[-_]space[-_]size(?:=|\s+)\d+/gu," ").trim(),`--max-old-space-size=${t}`].filter(Boolean).join(" ")}import{execFileSync as rs}from"child_process";import{constants as is,copyFileSync as oi,linkSync as os,rmSync as as,statSync as ss}from"fs";import{platform as cs}from"os";var us=Object.freeze({size:e=>ss(e).size,clone:ms,copy:(e,t)=>oi(e,t),link:(e,t)=>os(e,t),remove:e=>as(e,{force:!0})}),ls=new Set(["EXDEV","EPERM","EMLINK","ENOTSUP","EOPNOTSUPP","ENOSYS","EINVAL"]),ds=new Set(["ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL","EXDEV","ENOTTY"]);function oe(e,t,n=us,r={}){let i=n.size(e);n.remove?.(t);try{return n.clone(e,t),{method:"reflink",bytes:i}}catch(o){if(!gs(o))throw o}if(r.shareImmutable&&n.link)try{return n.link(e,t),{method:"link",bytes:i}}catch(o){if(!ps(o))throw o}return n.copy(e,t),{method:"copy",bytes:i}}function ps(e){let t=e?.code;return typeof t=="string"&&ls.has(t)}function ms(e,t){if(cs()!=="darwin"){oi(e,t,is.COPYFILE_FICLONE_FORCE);return}try{rs("/bin/cp",["-c",e,t],{timeout:6e4,maxBuffer:64*1024,stdio:["ignore","ignore","pipe"]})}catch(n){throw fs(n)}}function fs(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 gs(e){let t=e?.code;return t!==void 0&&ds.has(t)}function ai(){return{reflinkedBytes:0,fallbackCopiedBytes:0,incrementalWrittenBytes:0}}function ae(e,t){t.method==="reflink"||t.method==="link"?e.reflinkedBytes+=t.bytes:e.fallbackCopiedBytes+=t.bytes}function Ze(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 hs from"better-sqlite3";import{execFileSync as ys}from"child_process";import{existsSync as Ss,readdirSync as bs}from"fs";import{extname as et,join as Rs}from"path";function X(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??dr).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Ss(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Er(e.projectRoot),r=xs(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new hs(e.dbPath);try{let o=vs(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
2
+ VALUES (?, ?, NULL, ?)`),c=i.transaction(l=>{let d=0;for(let m of l){if(o.has(m))continue;let f=nr(e.projectRoot,m,{inputKind:"auxiliary source file"}),y=a.run(Is(m),m,f);d+=Number(y.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 xs(e,t){let n=Ps(e,t);if(n)return n;let r=[],i=o=>{let a=o?Rs(e,o):e,s;try{s=bs(a,{withFileTypes:!0})}catch{return}for(let c of s){if(pr.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(et(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function Ps(e,t){try{return ys("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}).split(`
3
+ `).filter(r=>r&&t.has(et(r).toLowerCase())).sort()}catch{return null}}function vs(e,t){let n=new Set,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),a=e.prepare(`SELECT relative_path FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let s of a)n.add(s.relative_path)}return n}function Is(e){return et(e).toLowerCase()===".vue"?"vue":et(e).replace(/^\./,"").toLowerCase()||"source"}import{dirname as Es,join as Ts}from"path";function ci(e={}){return{id:"runtime-boundaries",facts:["runtime-boundary-observation","runtime-boundary-link"],run:async({projectRoot:t,dbPath:n,onStatus:r})=>{let i=new V({projectRoot:t,dbPath:n,indexPath:e.indexPath??Ts(Es(n),"index.scip"),...e.evidenceDbPath?{evidenceDbPath:e.evidenceDbPath}:{}}),o,a=!1,s=!1;try{let u=e.reuseExisting||e.affectedFiles?jr(i):null;e.reuseExisting&&u?.extractorVersion===Ar?(o=u,a=!0):(o=await Mr(i,{...u?{previousGraph:u}:{},...e.affectedFiles?{affectedFiles:e.affectedFiles}:{},...e.forceDerivedRebuild?{forceDerivedRebuild:!0}:{},profileSpan:I}),s=(o.coverage.filesReused??0)>0)}finally{i.close()}a||Lr(n,o);let c={reused:a,incrementallyUpdated:s,observations:o.observations.length,links:o.links.length,frontiers:o.frontiers.length,filesScanned:o.coverage.filesScanned,errors:o.coverage.extractionErrors.length,phases:o.coverage.phases};return r?.(c.reused?`Reused ${c.observations} cached runtime-boundary observation(s) and ${c.links} link(s).`:c.incrementallyUpdated?`Incrementally refreshed runtime-boundary observations (${c.filesScanned-(o.coverage.filesReused??0)} file(s) extracted, ${o.coverage.filesReused??0} reused) and rebuilt ${c.links} link(s).`:`Extracted ${c.observations} runtime-boundary observation(s), ${c.links} link(s), and ${c.frontiers} unresolved frontier(s).`),!a&&o.coverage.phases&&r?.(`Runtime-boundary phases: ${o.coverage.phases.map(u=>`${u.id} ${u.durationMs.toFixed(0)}ms`).join(", ")}.`),c}}}function _e(e){let t=new Set;for(let n of e.uncertainty)t.add(n);e.projectIdentityChanged&&t.add("project-identity-changed");for(let n of e.changes)n.kind==="added"&&t.add("file-added"),n.kind==="deleted"&&t.add("file-deleted"),n.inputKind==="config"&&t.add("configuration-changed"),n.inputKind==="ambient"&&t.add("ambient-declaration-changed"),n.inputKind==="other"&&t.add("unclassified-input");return{fullProject:t.size>0,reasons:[...t].sort()}}function Fe(e,t,n){let r=e.changes.map(s=>s.path).sort();if(r.length===0&&!e.projectIdentityChanged&&e.uncertainty.length===0)return{mode:"none",changedFiles:r,affectedFiles:[],reasons:[]};let i=new Set(n),o=_e(e),a=new Set(o.reasons);return r.some(s=>!i.has(s))&&a.add("changed-file-outside-project"),t===null?(a.add("dependency-graph-unavailable"),ui(r,i,a)):a.size>0?ui(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:ws(r,t,i),reasons:[]}}function ui(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function ws(e,t,n){let r=new Map;for(let[a,s]of t)if(n.has(a))for(let c of s){if(!n.has(c))continue;let u=r.get(c)??new Set;u.add(a),r.set(c,u)}let i=new Set(e),o=[...e];for(let a=0;a<o.length;a+=1){let s=o[a];if(s!==void 0)for(let c of r.get(s)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}import{createHash as ks}from"crypto";import{existsSync as _s}from"fs";import{dirname as Fs,join as li}from"path";var Cs="<global-symbols>";function Os(e){let t=[];for(let n of e.all(`
4
4
  SELECT relative_path, language, position_encoding, text
5
5
  FROM documents
6
6
  `))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
@@ -27,7 +27,7 @@ import{a as Z}from"./chunk-XU75YQN4.js";import{a as bo,b as Ro,c as Mt,d as qn,h
27
27
  FROM defn_enclosing_ranges r
28
28
  JOIN documents d ON d.id = r.document_id
29
29
  JOIN global_symbols g ON g.id = r.symbol_id
30
- `))t.push({relativePath:n.relative_path,kind:"definition",values:Yn(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
30
+ `))t.push({relativePath:n.relative_path,kind:"definition",values:Ht(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
31
31
  SELECT d.relative_path,
32
32
  c.chunk_index,
33
33
  m.role,
@@ -42,7 +42,7 @@ import{a as Z}from"./chunk-XU75YQN4.js";import{a as bo,b as Ro,c as Mt,d as qn,h
42
42
  JOIN chunks c ON c.id = m.chunk_id
43
43
  JOIN documents d ON d.id = c.document_id
44
44
  JOIN global_symbols g ON g.id = m.symbol_id
45
- `))t.push({relativePath:n.relative_path,kind:"mention",values:Yn(n,[n.chunk_index,n.role])});for(let n of e.all(`
45
+ `))t.push({relativePath:n.relative_path,kind:"mention",values:Ht(n,[n.chunk_index,n.role])});for(let n of e.all(`
46
46
  SELECT g.symbol,
47
47
  g.display_name,
48
48
  g.kind,
@@ -56,8 +56,8 @@ import{a as Z}from"./chunk-XU75YQN4.js";import{a as bo,b as Ro,c as Mt,d as qn,h
56
56
  ) AND NOT EXISTS (
57
57
  SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
58
58
  )
59
- `))t.push({relativePath:du,kind:"global-symbol",values:Yn(n)});return lu(t)}function lu(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=au("sha256");for(let a of i.sort())o.update(String(Buffer.byteLength(a))),o.update(":"),o.update(a),o.update(`
60
- `);n.set(r,o.digest("hex"))}return n}function pu(e,t){let n=[],r=[],i=[],o=[],a=new Set([...e.keys(),...t.keys()]);for(let s of[...a].sort()){let c=e.get(s),d=t.get(s);c===void 0?n.push(s):d===void 0?i.push(s):c!==d?r.push(s):o.push(s)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function Jn(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 Xn(e,t=Su){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,i=t.wallNow??t.now,o=r(),a=(d,u)=>{let l=r();return jo(e.refreshResult,d,n?l:i(),Math.max(0,l-o),u)};if(!t.databaseExists(e.previousDbPath))return a("prior-index-unavailable");if(!t.databaseExists(e.candidateDbPath))return a("candidate-index-unavailable");if(e.refreshResult==="rebuilt"&&je(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 d=[...new Set([...t.indexedPaths(s),...t.indexedPaths(c)])].sort(),u=je(e.previousSnapshot,e.currentSnapshot),l=new Set(d),p=u.changes.length>0&&!zn(u).fullProject&&u.changes.every(v=>l.has(v.path)),m=ot(u,p?t.dependencyGraph(s):new Map,d),g=pu(t.factDigests(s),t.factDigests(c)),y=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?y:i()).toISOString(),durationMs:Math.max(0,y-o),manifest:u,plan:m,comparison:g,evaluation:Jn(m,g,d.length)}}catch(d){return a("oracle-error",d instanceof Error?d.message:String(d))}finally{Oo(s),Oo(c)}}function Lo(e,t,n,r=Date.now()){return jo(e,t,r,0,n)}function fu(e){let t=cu(e);return{latestPath:Ao(t,"affected-shadow-latest.json"),historyPath:Ao(t,"affected-shadow.jsonl")}}function Mo(e,t,n=bu){let r=fu(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var mu=8*1024*1024,gu=wo;function hu(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 yu(e,t,n=mu){Eo(e,hu(t),{maxSegmentBytes:n,previousSuffix:gu})}function Yn(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 Su={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:_,databaseExists:e=>su(e),openDatabase:(e,t,n)=>new Z({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>Ot(e),dependencyGraph:e=>oo(e),factDigests:e=>uu(e)},bu={appendHistory:yu,writeLatest:(e,t)=>ge(e,t,{spacing:2,trailingNewline:!0})};function jo(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 Oo(e){try{e?.close()}catch{}}import{execFileSync as Ru}from"child_process";import{existsSync as xu,readdirSync as No}from"fs";import{extname as Go,join as $o}from"path";var Bo=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),Iu=[{language:"typescript",files:["tsconfig.json","tsconfig.base.json"],extensions:[".ts",".tsx",".mts",".cts"]},{language:"rust",files:["Cargo.toml"],extensions:[".rs"]},{language:"go",files:["go.mod"],extensions:[".go"]},{language:"java",files:["pom.xml","build.gradle","build.gradle.kts"],extensions:[".java"]},{language:"kotlin",files:["build.gradle.kts"],extensions:[".kt",".kts"]},{language:"scala",files:["build.sbt"],extensions:[".scala"]},{language:"clojure",files:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],extensions:[".clj",".cljs",".cljc"]},{language:"python",files:["pyproject.toml","setup.py","setup.cfg","Pipfile"],extensions:[".py",".pyi"]},{language:"ruby",files:["Gemfile"],extensions:[".rb"]},{language:"cpp",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"]},{language:"c",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".c",".h"]},{language:"csharp",globs:["*.csproj","*.sln"],extensions:[".cs"]},{language:"vb",globs:["*.vbproj"],extensions:[".vb"]},{language:"dart",files:["pubspec.yaml"],extensions:[".dart"]},{language:"php",files:["composer.json"],extensions:[".php"]},{language:"javascript",files:["package.json"],extensions:[".js",".jsx",".mjs",".cjs"]}];function Qn(e){let t=[],n=vu(e),r=Tu(e);for(let i of Iu){if(Pu(e,i.files)){t.push(i.language);continue}if(wu(n,i.globs)){t.push(i.language);continue}Cu(r,i.extensions)&&t.push(i.language)}if(t.includes("typescript")&&Kn(t,"javascript"),t.includes("cpp")&&t.includes("c")){let i=r.has(".c"),o=[".cc",".cpp",".cxx"].some(a=>r.has(a));i&&!o?Kn(t,"cpp"):i||Kn(t,"c")}return t}function vu(e){try{return No(e)}catch{return[]}}function Pu(e,t){return t?.length?t.some(n=>xu($o(e,n))):!1}function wu(e,t){return t?.length?e.some(n=>t.some(r=>Eu(n,r))):!1}function Eu(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,r]=t.split("*");return e.startsWith(n??"")&&e.endsWith(r??"")}function Tu(e){let t=ku(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let o;try{o=No(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(a.name.startsWith(".")&&!a.name.endsWith("proj")&&!a.name.endsWith("sln")&&a.isDirectory())continue;let s=$o(i,a.name);if(a.isDirectory()){Bo.has(a.name)||r.push(s);continue}let c=Go(a.name).toLowerCase();c&&n.add(c)}}return n}function ku(e){try{let t=Ni(e,26214400,()=>Ru("git",["-C",e,"ls-files","-co","-v","-z","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:52428800,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"})),n=new Set;for(let r of Gi(t)){if(r.split("/").some(o=>Bo.has(o)))continue;let i=Go(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Cu(e,t){return t?.length?t.some(n=>e.has(n)):!1}function Kn(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{readdirSync as Du}from"fs";import{isAbsolute as Vo,join as _u,resolve as Fu}from"path";var $t="@sourcegraph/scip-typescript@0.4.0",Uo="scip-python-plus@0.7.5",qo="github.com/sourcegraph/scip-go@v0.2.7",Wo="scip-dotnet@0.2.14",Au="scip_dart@1.6.2",zo={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:[...V.typescript],installMethods:[{label:"npm",identity:$t,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",$t]}],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:[...V.javascript],installMethods:[{label:"npm",identity:$t,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",$t]}],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:[...V.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:[...V.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:[...V.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:[...V.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:[...V.python],installMethods:[{label:"npm",identity:Uo,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",Uo]}],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",Vo(r)?r:Fu(e,r)),{binary:n,args:i}},markerFiles:[...V.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:[...V.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:[...V.go],installMethods:[{label:"go install",identity:qo,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",qo]}],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:[...V.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:[...V.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",Ho(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...V.csharp],installMethods:[{label:"dotnet",identity:Wo,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",Ho(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...V.vb],installMethods:[{label:"dotnet",identity:Wo,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:[...V.dart],installMethods:[{label:"dart pub",identity:Au,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})=>Vo(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:[...V.php],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Yo(e){if(!(e.projectPath||e.pnpmWorkspaces)){if(e.language==="typescript")return"{}";if(e.language==="javascript")return'{"compilerOptions":{"allowJs":true}}'}}function Bt(e){return zo[e]}function Ho(e,t){let n;try{n=Du(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return _u(e,i);return null}import{closeSync as dt,openSync as rr,readSync as nl,renameSync as rl,rmSync as ra,statSync as il,writeFileSync as ia,writeSync as oa}from"fs";import{create as ir,fromBinary as ol,toBinary as al}from"@bufbuild/protobuf";import{deserializeSCIP as aa,serializeSCIP as sa,DocumentSchema as sl,IndexSchema as cl,MetadataSchema as ta,SymbolInformationSchema as dl}from"@c4312/scip";var J=class extends Error{},Ou=0,Lu=1,Jo=2,Mu=5;function Zn(e,t,n){let r=0,i=0;for(;t<n;){let o=e[t];if(t+=1,i<53)r+=(o&127)*2**i;else if((o&127)!==0)throw new J("varint exceeds the safe integer range");if((o&128)===0)return{value:r,pos:t};if(i+=7,i>63)throw new J("varint is longer than 64 bits")}throw new J("varint runs past the end of the buffer")}function*B(e,t=0,n=e.length){let r=t;for(;r<n;){let i=r,o=Zn(e,r,n);r=o.pos;let a=Math.floor(o.value/8),s=o.value%8;if(a===0)throw new J("field number 0 is invalid");let c=r,d=0;if(s===Ou){let u=Zn(e,r,n);d=u.value,r=u.pos}else if(s===Jo){let u=Zn(e,r,n);if(c=u.pos,r=u.pos+u.value,r>n)throw new J("length-delimited field runs past the end of the buffer")}else if(s===Lu)r+=8;else if(s===Mu)r+=4;else throw new J(`unsupported wire type ${s}`);if(r>n)throw new J("field value runs past the end of the buffer");yield{fieldNumber:a,wireType:s,fieldStart:i,valueStart:c,valueEnd:r,fieldEnd:r,varint:d}}}function X(e){if(!Number.isSafeInteger(e)||e<0)throw new J(`cannot encode varint ${e}`);let t=[],n=e;do{let r=n%128;n=Math.floor(n/128),n>0&&(r|=128),t.push(r)}while(n>0);return Uint8Array.from(t)}function ye(e){return X(e*8+Jo)}var ju=1,Nu=3;function at(e){let t=new TextDecoder,n;for(let r of B(e))if(!(r.fieldNumber!==ju||r.wireType!==2))for(let i of B(e,r.valueStart,r.valueEnd)){if(i.fieldNumber!==Nu||i.wireType!==2)continue;let o=t.decode(e.subarray(i.valueStart,i.valueEnd));o&&(n=o)}return n}import{closeSync as Xo,openSync as Gu,renameSync as $u,rmSync as Bu,writeSync as Vu}from"fs";import{create as Ko,fromBinary as Uu,toBinary as qu}from"@bufbuild/protobuf";import{DocumentSchema as er,IndexSchema as Wu,SymbolRole as nr}from"@c4312/scip";var tr=2,Hu=3,zu=1,Yu=2,Ju=3,Xu=1,Ku=2,Qu=3;function Zo(e){let t;try{t=j(e,{inputKind:"SCIP sanitization input",maxBytes:G})}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}try{return Zu(t,e)}catch(n){if(n instanceof J)return{removedDefinitionOccurrences:0,touchedDocuments:0};throw n}}function Zu(e,t){let n=new TextDecoder,r=new Set;for(let a of B(e))if(a.wireType===2)if(a.fieldNumber===tr)for(let s of B(e,a.valueStart,a.valueEnd))s.wireType===2&&(s.fieldNumber===zu?wn(n.decode(e.subarray(s.valueStart,s.valueEnd))):s.fieldNumber===Ju&&Qo(e,s,n,r));else a.fieldNumber===Hu&&Qo(e,a,n,r);let i=0,o=[];for(let a of B(e)){if(a.wireType!==2||a.fieldNumber!==tr)continue;let s=el(e,a,n,r);s>0&&(i+=s,o.push(a))}return i===0?{removedDefinitionOccurrences:0,touchedDocuments:0}:(tl(e,t,o,r),{removedDefinitionOccurrences:i,touchedDocuments:o.length})}function Qo(e,t,n,r){for(let i of B(e,t.valueStart,t.valueEnd)){if(i.wireType!==2||i.fieldNumber!==Xu)continue;let o=n.decode(e.subarray(i.valueStart,i.valueEnd));o&&r.add(o)}}function el(e,t,n,r){let i=0;for(let o of B(e,t.valueStart,t.valueEnd)){if(o.wireType!==2||o.fieldNumber!==Yu)continue;let a="",s=0;for(let c of B(e,o.valueStart,o.valueEnd))c.fieldNumber===Ku&&c.wireType===2?a=n.decode(e.subarray(c.valueStart,c.valueEnd)):c.fieldNumber===Qu&&c.wireType===0&&(s=c.varint);(s&nr.Definition)!==0&&!r.has(a)&&(i+=1)}return i}function tl(e,t,n,r){let i=`${t}.sanitize-tmp`,o=Gu(i,"w",384);try{let a=0;for(let s of n){st(o,e.subarray(a,s.fieldStart));let c=Uu(er,e.subarray(s.valueStart,s.valueEnd));c.occurrences=c.occurrences.filter(u=>(u.symbolRoles&nr.Definition)===0||r.has(u.symbol));let d=qu(er,c);st(o,ye(tr)),st(o,X(d.byteLength)),st(o,d),a=s.fieldEnd}st(o,e.subarray(a))}catch(a){throw Xo(o),Bu(i,{force:!0}),a}Xo(o),$u(i,t)}function st(e,t){let n=0;for(;n<t.byteLength;)n+=Vu(e,t,n,t.byteLength-n)}function ea(e){let t=new Set;for(let o of e.documents){wn(o.relativePath);for(let a of o.symbols)a.symbol&&t.add(a.symbol)}for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,r=0,i=[];for(let o of e.documents){let a=o.occurrences.filter(s=>(s.symbolRoles&nr.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(Ko(er,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:Ko(Wu,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function or(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=ul(e),n=ll(e.flatMap(i=>i.documents??[])),r=la(e.flatMap(i=>i.externalSymbols??[]));return ir(cl,{metadata:t,documents:n,externalSymbols:r})}function ar(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>aa(j(i,{inputKind:"SCIP merge input",maxBytes:G}))),r=or(n);return ia(t,sa(r)),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function ca(e,t){if(e.length===0)throw new Error("Cannot concatenate zero SCIP files");let n=0;for(let o of e)if(n+=il(o).size,n>G)throw new Error(`Concatenated SCIP output exceeds the ${G}-byte artifact limit. Reduce the indexed project scope or use compatible cached generations.`);let r=Buffer.allocUnsafe(1024*1024),i=rr(t,"w",384);try{for(let o of e){let a=rr(o,"r");try{let s=0;for(;(s=nl(a,r,0,r.byteLength,null))>0;){let c=0;for(;c<s;)c+=oa(i,r,c,s-c)}}finally{dt(a)}}}catch(o){throw dt(i),ra(t,{force:!0}),o}dt(i)}function da(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=w("reindex.publish.scip-output.deserialize",()=>e.map(o=>aa(j(o,{inputKind:"SCIP merge input",maxBytes:G})))),r=w("reindex.publish.scip-output.merge",()=>or(n)),i=w("reindex.publish.scip-output.sanitize",()=>ea(r));return w("reindex.publish.scip-output.serialize",()=>ia(t,sa(i.index))),{documentCount:i.index.documents.length,externalSymbolCount:i.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:i.removedDefinitionOccurrences,touchedDocuments:i.touchedDocuments}}var na=1;function ua(e,t,n){let r=j(e,{inputKind:"SCIP normalization input",maxBytes:G}),i=at(r),o=[];for(let c of B(r))c.fieldNumber===na&&c.wireType===2&&o.push(c);if(o.length===0)throw new Error("Cannot rebase a SCIP index without metadata");if((i??"")!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${i??""}`);let a=`${e}.rebase-tmp`,s=rr(a,"w",384);try{let c=0;for(let d of o){ct(s,r.subarray(c,d.fieldStart));let u=ol(ta,r.subarray(d.valueStart,d.valueEnd));u.projectRoot=n;let l=al(ta,u);ct(s,ye(na)),ct(s,X(l.byteLength)),ct(s,l),c=d.fieldEnd}ct(s,r.subarray(c))}catch(c){throw dt(s),ra(a,{force:!0}),c}dt(s),rl(a,e)}function ct(e,t){let n=0;for(;n<t.byteLength;)n+=oa(e,t,n,t.byteLength-n)}function ul(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function ll(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,ir(sl,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:pl([...r.occurrences,...n.occurrences]),symbols:la([...r.symbols,...n.symbols]),text:ml(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function pl(e){let t=new Set,n=[];for(let r of e){let i=JSON.stringify(r);t.has(i)||(t.add(i),n.push(r))}return n}function la(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,ir(dl,{symbol:r.symbol,documentation:gl([...r.documentation,...n.documentation]),relationships:fl([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function fl(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function ml(e,t){return e?t?e.length>=t.length?e:t:e:t}function gl(e){return[...new Set(e)]}import{createHash as hl}from"crypto";import{existsSync as cr,rmSync as pa,statSync as yl}from"fs";import{resolve as Sl}from"path";import ga from"better-sqlite3";var bl={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}]},Rl={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 ha(e){let t=_(),n=fa(e.affectedFiles),r=fa(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(Il(e.previousDbPath,e.miniDbPath,e.candidateDbPath),!cr(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!cr(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");w("reindex.publish.sqlite-patch.validate-inputs",()=>{sr(e.previousDbPath,"previous SQLite generation",!1),sr(e.miniDbPath,"incremental SQLite mini database")}),e.reuseCandidate?w("reindex.publish.sqlite-patch.reuse-candidate",()=>sr(e.candidateDbPath,"incremental SQLite candidate",!1)):w("reindex.publish.sqlite-patch.clone",()=>{pa(e.candidateDbPath,{force:!0});let s=Te(e.previousDbPath,e.candidateDbPath);e.writeTelemetry&&ke(e.writeTelemetry,s)});let a=null;try{a=w("reindex.publish.sqlite-patch.open",()=>{let m=new ga(e.candidateDbPath,{fileMustExist:!0});return m.pragma("busy_timeout = 5000"),m.pragma("foreign_keys = ON"),m.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),dr(m,"main","candidate SQLite generation"),dr(m,"incremental","incremental SQLite mini database"),m});let{priorAffectedCount:s,previousFactDigests:c}=w("reindex.publish.sqlite-patch.prepare",()=>(wl(a,n,r),{...El(a,n.length,r.length),previousFactDigests:ur(a,"main",!0)})),d=Se(a,"SELECT COUNT(*) AS value FROM main.documents"),u=a.transaction(()=>{w("reindex.publish.sqlite-patch.transaction.symbol-ownership",()=>Tl(a)),w("reindex.publish.sqlite-patch.transaction.shared-definitions",()=>kl(a)),w("reindex.publish.sqlite-patch.transaction.delete",()=>Cl(a)),e.onStage?.("after-delete"),w("reindex.publish.sqlite-patch.transaction.reconcile-symbols",()=>Dl(a)),e.onStage?.("after-symbol-reconciliation"),w("reindex.publish.sqlite-patch.transaction.insert",()=>_l(a)),e.onStage?.("after-insert"),w("reindex.publish.sqlite-patch.transaction.prune-symbols",()=>Fl(a,e.trustedPriorGeneration===!0)),w("reindex.publish.sqlite-patch.transaction.validate",()=>Al(a,o,d,s)),e.onStage?.("before-commit")});w("reindex.publish.sqlite-patch.transaction",()=>u.immediate()),e.writeTelemetry&&Nt(e.writeTelemetry,2*xl(e.candidateDbPath)),w("reindex.publish.sqlite-patch.integrity",()=>Pl(a,"candidate SQLite generation",!e.deferIntegrity&&e.trustedPriorGeneration!==!0));let l=w("reindex.publish.sqlite-patch.validate-facts",()=>Ol(a)),p=[...new Set([...c.keys(),...l.keys()])].filter(m=>c.get(m)!==l.get(m)).sort();return a.exec("DETACH DATABASE incremental"),a.close(),a=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:p,durationMs:_()-t}}catch(s){try{a?.close()}finally{pa(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}function xl(e){let t=0;for(let n of["-wal","-journal"]){let r=`${e}${n}`;cr(r)&&(t+=yl(r).size)}return t}function fa(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 Il(e,t,n){let r=[e,t,n].map(i=>Sl(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function sr(e,t,n=!0){let r=new ga(e,{readonly:!0,fileMustExist:!0});try{dr(r,"main",t),n&&vl(r,"main",t)}finally{r.close()}}function dr(e,t,n){for(let[r,i]of Object.entries(bl)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:d,pk:u})=>({name:s,type:c.toUpperCase(),notnull:d,pk:u}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(Rl)){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}`)}ma(e,t,"documents",["relative_path"],n),ma(e,t,"global_symbols",["symbol"],n)}function ma(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(s=>{if(s.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${s.name}')`).all().map(d=>d.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function vl(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 Pl(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 wl(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 El(e,t,n){let r=Se(e,"SELECT COUNT(*) AS value FROM incremental.documents"),i=Se(e,`SELECT COUNT(*) AS value
59
+ `))t.push({relativePath:Cs,kind:"global-symbol",values:Ht(n)});return Ds(t)}function Ds(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=ks("sha256");for(let a of i.sort())o.update(String(Buffer.byteLength(a))),o.update(":"),o.update(a),o.update(`
60
+ `);n.set(r,o.digest("hex"))}return n}function As(e,t){let n=[],r=[],i=[],o=[],a=new Set([...e.keys(),...t.keys()]);for(let s of[...a].sort()){let c=e.get(s),u=t.get(s);c===void 0?n.push(s):u===void 0?i.push(s):c!==u?r.push(s):o.push(s)}return{addedFiles:n,modifiedFiles:r,deletedFiles:i,changedFiles:[...n,...r,...i].sort(),unchangedFiles:o}}function zt(e,t,n){let r=new Set(e.affectedFiles),i=new Set(t.changedFiles),o=e.mode==="full-project"?[]:t.changedFiles.filter(c=>!r.has(c)),a=e.affectedFiles.filter(c=>!i.has(c)).sort(),s=t.changedFiles.length-o.length;return{passed:o.length===0,recall:t.changedFiles.length===0?1:s/t.changedFiles.length,affectedRatio:n===0?0:e.affectedFiles.length/n,predictedFiles:[...e.affectedFiles].sort(),actualFiles:[...t.changedFiles],missingFiles:o,extraFiles:a}}function Jt(e,t=Vs){let n=t.wallNow===void 0&&t.monotonicNow===void 0,r=t.monotonicNow??t.now,i=t.wallNow??t.now,o=r(),a=(u,l)=>{let d=r();return fi(e.refreshResult,u,n?d:i(),Math.max(0,d-o),l)};if(!t.databaseExists(e.previousDbPath))return a("prior-index-unavailable");if(!t.databaseExists(e.candidateDbPath))return a("candidate-index-unavailable");if(e.refreshResult==="rebuilt"&&z(e.previousSnapshot,e.currentSnapshot).changes.length===0)return a("no-input-changes");let s=null,c=null;try{s=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),c=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let u=[...new Set([...t.indexedPaths(s),...t.indexedPaths(c)])].sort(),l=z(e.previousSnapshot,e.currentSnapshot),d=new Set(u),m=l.changes.length>0&&!_e(l).fullProject&&l.changes.every(k=>d.has(k.path)),f=Fe(l,m?t.dependencyGraph(s):new Map,u),y=As(t.factDigests(s),t.factDigests(c)),b=r();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(n?b:i()).toISOString(),durationMs:Math.max(0,b-o),manifest:l,plan:f,comparison:y,evaluation:zt(f,y,u.length)}}catch(u){return a("oracle-error",u instanceof Error?u.message:String(u))}finally{di(s),di(c)}}function pi(e,t,n,r=Date.now()){return fi(e,t,r,0,n)}function Ms(e){let t=Fs(e);return{latestPath:li(t,"affected-shadow-latest.json"),historyPath:li(t,"affected-shadow.jsonl")}}function mi(e,t,n=Bs){let r=Ms(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}var Ls=8*1024*1024,js=Nr;function Ns(e){let t={historyVersion:1,sourceVersion:e.version,refreshResult:e.refreshResult,recordedAt:e.recordedAt,durationMs:e.durationMs};return e.status==="unavailable"?{...t,status:"unavailable",reason:e.reason,...e.error?{error:e.error}:{}}:{...t,status:"evaluated",mode:e.plan.mode,passed:e.evaluation.passed,recall:e.evaluation.recall,affectedRatio:e.evaluation.affectedRatio,predictedFileCount:e.evaluation.predictedFiles.length,actualFileCount:e.evaluation.actualFiles.length,missingFileCount:e.evaluation.missingFiles.length,fallbackReasons:[...e.plan.reasons]}}function $s(e,t,n=Ls){$r(e,Ns(t),{maxSegmentBytes:n,previousSuffix:js})}function Ht(e,t=[]){let n=[];for(let r of t)n.push(r);return n.push(e.symbol,e.display_name,e.kind,e.documentation,e.signature_hex,e.enclosing_symbol,e.relationships_hex),n}var Vs={now:()=>Date.now(),wallNow:()=>Date.now(),monotonicNow:F,databaseExists:e=>_s(e),openDatabase:(e,t,n)=>new V({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>Ue(e),dependencyGraph:e=>mr(e),factDigests:e=>Os(e)},Bs={appendHistory:$s,writeLatest:(e,t)=>$e(e,t,{spacing:2,trailingNewline:!0})};function fi(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(n).toISOString(),durationMs:r,reason:t,...i?{error:i}:{}}}function di(e){try{e?.close()}catch{}}import{readdirSync as Us}from"fs";import{isAbsolute as gi,join as Gs,resolve as Ws}from"path";var tt="@sourcegraph/scip-typescript@0.4.0",hi="scip-python-plus@0.7.5",yi="github.com/sourcegraph/scip-go@v0.2.7",Si="scip-dotnet@0.2.14",qs="scip_dart@1.6.2",Ri={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>r?{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches",r]}:t?{binary:n,args:["index","--pnpm-workspaces","--output",e,"--no-progress-bar","--no-global-caches"]}:{binary:n,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]},markerFiles:[...M.typescript],installMethods:[{label:"npm",identity:tt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",tt]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--no-progress-bar","--no-global-caches"]}),markerFiles:[...M.javascript],installMethods:[{label:"npm",identity:tt,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",tt]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...M.java],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...M.scala],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:[...M.kotlin],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:Se.language,indexerBinary:Se.indexerBinary,checkCommand:`${Se.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:Se.indexerBinary,args:["scip",".","--output",e]}),markerFiles:[...M.rust],installMethods:[],installUrl:Se.installUrl},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:[...M.python],installMethods:[{label:"npm",identity:hi,destination:"npm global prefix",prerequisite:"npm",binary:"npm",args:["install","-g",hi]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",gi(r)?r:Ws(e,r)),{binary:n,args:i}},markerFiles:[...M.clojure],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:[...M.ruby],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:[...M.go],installMethods:[{label:"go install",identity:yi,destination:"Go bin directory (GOBIN or GOPATH/bin)",prerequisite:"go",binary:"go",args:["install",yi]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:[...M.cpp],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:[...M.c],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",bi(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...M.csharp],installMethods:[{label:"dotnet",identity:Si,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",bi(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:[...M.vb],installMethods:[{label:"dotnet",identity:Si,destination:"dotnet global tool directory",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet","--version","0.2.14"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:[...M.dart],installMethods:[{label:"dart pub",identity:qs,destination:"Dart pub global cache",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart","1.6.2"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({indexerBinary:e})=>gi(e)?{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",e]}:{binary:e,args:[]},defaultOutputPath:"index.scip",markerFiles:[...M.php],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function xi(e){if(!(e.projectPath||e.pnpmWorkspaces)){if(e.language==="typescript")return"{}";if(e.language==="javascript")return'{"compilerOptions":{"allowJs":true}}'}}function nt(e){return Ri[e]}function bi(e,t){let n;try{n=Us(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return Gs(e,i);return null}import{createHash as Hs}from"crypto";import{existsSync as Xt,rmSync as Pi,statSync as zs}from"fs";import{resolve as Js}from"path";import Ei from"better-sqlite3";var Ys={documents:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"language",type:"TEXT",notnull:0,pk:0},{name:"relative_path",type:"TEXT",notnull:1,pk:0},{name:"position_encoding",type:"TEXT",notnull:0,pk:0},{name:"text",type:"TEXT",notnull:0,pk:0}],chunks:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"chunk_index",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"occurrences",type:"BLOB",notnull:1,pk:0}],global_symbols:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"symbol",type:"TEXT",notnull:1,pk:0},{name:"display_name",type:"TEXT",notnull:0,pk:0},{name:"kind",type:"INTEGER",notnull:0,pk:0},{name:"documentation",type:"TEXT",notnull:0,pk:0},{name:"signature",type:"BLOB",notnull:0,pk:0},{name:"enclosing_symbol",type:"TEXT",notnull:0,pk:0},{name:"relationships",type:"BLOB",notnull:0,pk:0}],mentions:[{name:"chunk_id",type:"INTEGER",notnull:1,pk:1},{name:"symbol_id",type:"INTEGER",notnull:1,pk:2},{name:"role",type:"INTEGER",notnull:1,pk:3}],defn_enclosing_ranges:[{name:"id",type:"INTEGER",notnull:0,pk:1},{name:"document_id",type:"INTEGER",notnull:1,pk:0},{name:"symbol_id",type:"INTEGER",notnull:1,pk:0},{name:"start_line",type:"INTEGER",notnull:1,pk:0},{name:"start_char",type:"INTEGER",notnull:1,pk:0},{name:"end_line",type:"INTEGER",notnull:1,pk:0},{name:"end_char",type:"INTEGER",notnull:1,pk:0}]},Xs={idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Ti(e){let t=F(),n=vi(e.affectedFiles),r=vi(e.deletedFiles??[],!0),i=new Set(n);if(r.some(s=>!i.has(s)))throw new Error("deleted incremental documents must be included in the affected document set");let o=n.length-r.length;if(Qs(e.previousDbPath,e.miniDbPath,e.candidateDbPath),!Xt(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!Xt(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");I("reindex.publish.sqlite-patch.validate-inputs",()=>{Yt(e.previousDbPath,"previous SQLite generation",!1),Yt(e.miniDbPath,"incremental SQLite mini database")}),e.reuseCandidate?I("reindex.publish.sqlite-patch.reuse-candidate",()=>Yt(e.candidateDbPath,"incremental SQLite candidate",!1)):I("reindex.publish.sqlite-patch.clone",()=>{Pi(e.candidateDbPath,{force:!0});let s=oe(e.previousDbPath,e.candidateDbPath);e.writeTelemetry&&ae(e.writeTelemetry,s)});let a=null;try{a=I("reindex.publish.sqlite-patch.open",()=>{let f=new Ei(e.candidateDbPath,{fileMustExist:!0});return f.pragma("busy_timeout = 5000"),f.pragma("foreign_keys = ON"),f.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Kt(f,"main","candidate SQLite generation"),Kt(f,"incremental","incremental SQLite mini database"),f});let{priorAffectedCount:s,previousFactDigests:c}=I("reindex.publish.sqlite-patch.prepare",()=>(tc(a,n,r),{...nc(a,n.length,r.length),previousFactDigests:Qt(a,"main",!0)})),u=K(a,"SELECT COUNT(*) AS value FROM main.documents"),l=a.transaction(()=>{I("reindex.publish.sqlite-patch.transaction.symbol-ownership",()=>rc(a)),I("reindex.publish.sqlite-patch.transaction.shared-definitions",()=>ic(a)),I("reindex.publish.sqlite-patch.transaction.delete",()=>oc(a)),e.onStage?.("after-delete"),I("reindex.publish.sqlite-patch.transaction.reconcile-symbols",()=>ac(a)),e.onStage?.("after-symbol-reconciliation"),I("reindex.publish.sqlite-patch.transaction.insert",()=>sc(a)),e.onStage?.("after-insert"),I("reindex.publish.sqlite-patch.transaction.prune-symbols",()=>cc(a,e.trustedPriorGeneration===!0)),I("reindex.publish.sqlite-patch.transaction.validate",()=>uc(a,o,u,s)),e.onStage?.("before-commit")});I("reindex.publish.sqlite-patch.transaction",()=>l.immediate()),e.writeTelemetry&&Ze(e.writeTelemetry,2*Ks(e.candidateDbPath)),I("reindex.publish.sqlite-patch.integrity",()=>ec(a,"candidate SQLite generation",!e.deferIntegrity&&e.trustedPriorGeneration!==!0));let d=I("reindex.publish.sqlite-patch.validate-facts",()=>lc(a)),m=[...new Set([...c.keys(),...d.keys()])].filter(f=>c.get(f)!==d.get(f)).sort();return a.exec("DETACH DATABASE incremental"),a.close(),a=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:m,durationMs:F()-t}}catch(s){try{a?.close()}finally{Pi(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}function Ks(e){let t=0;for(let n of["-wal","-journal"]){let r=`${e}${n}`;Xt(r)&&(t+=zs(r).size)}return t}function vi(e,t=!1){if(!t&&e.length===0)throw new Error("incremental SQLite publication requires affected documents");let n=[...e].sort();for(let r of n)if(!r||r.startsWith("/")||r.includes("\\")||r.split("/").includes(".."))throw new Error(`invalid affected document path: ${r}`);if(new Set(n).size!==n.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return n}function Qs(e,t,n){let r=[e,t,n].map(i=>Js(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function Yt(e,t,n=!0){let r=new Ei(e,{readonly:!0,fileMustExist:!0});try{Kt(r,"main",t),n&&Zs(r,"main",t)}finally{r.close()}}function Kt(e,t,n){for(let[r,i]of Object.entries(Ys)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:l})=>({name:s,type:c.toUpperCase(),notnull:u,pk:l}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(Xs)){let o=e.prepare(`SELECT tbl_name FROM ${t}.sqlite_master WHERE type = 'index' AND name = ?`).get(r),a=e.prepare(`PRAGMA ${t}.index_info('${r}')`).all().map(s=>s.name);if(o?.tbl_name!==i.table||JSON.stringify(a)!==JSON.stringify(i.columns))throw new Error(`${n} schema changed for index ${r}`)}Ii(e,t,"documents",["relative_path"],n),Ii(e,t,"global_symbols",["symbol"],n)}function Ii(e,t,n,r,i){if(!e.prepare(`PRAGMA ${t}.index_list('${n}')`).all().some(s=>{if(s.unique!==1)return!1;let c=e.prepare(`PRAGMA ${t}.index_info('${s.name}')`).all().map(u=>u.name);return JSON.stringify(c)===JSON.stringify(r)}))throw new Error(`${i} lost the unique ${n}(${r.join(", ")}) constraint`)}function Zs(e,t,n){let r=e.prepare(`PRAGMA ${t}.integrity_check`).pluck().get();if(r!=="ok")throw new Error(`${n} failed integrity_check: ${String(r)}`);if(e.prepare(`PRAGMA ${t}.foreign_key_check`).all().length>0)throw new Error(`${n} failed foreign_key_check`)}function ec(e,t,n){if(e.pragma("foreign_keys",{simple:!0})!==1)throw new Error(`${t} lost foreign-key enforcement`);if(!n)return;let r=e.prepare("PRAGMA main.quick_check").pluck().get();if(r!=="ok")throw new Error(`${t} failed quick_check: ${String(r)}`)}function tc(e,t,n){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID"),e.exec("CREATE TEMP TABLE incremental_deleted_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let r=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)"),i=e.prepare("INSERT INTO temp.incremental_deleted_paths(relative_path) VALUES (?)");e.transaction(a=>{for(let s of a)r.run(s);for(let s of n)i.run(s)})(t)}function nc(e,t,n){let r=K(e,"SELECT COUNT(*) AS value FROM incremental.documents"),i=K(e,`SELECT COUNT(*) AS value
61
61
  FROM main.documents d
62
62
  JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),o=e.prepare(`SELECT p.relative_path
63
63
  FROM temp.incremental_affected_paths p
@@ -71,7 +71,7 @@ import{a as Z}from"./chunk-XU75YQN4.js";import{a as bo,b as Ro,c as Mt,d as qn,h
71
71
  LIMIT 1`).pluck().get(),s=e.prepare(`SELECT d.relative_path
72
72
  FROM incremental.documents d
73
73
  JOIN temp.incremental_deleted_paths deleted ON deleted.relative_path = d.relative_path
74
- LIMIT 1`).pluck().get();if(r!==t-n||o!==void 0||a!==void 0||s!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set");return{priorAffectedCount:i}}function Tl(e){e.exec(`
74
+ LIMIT 1`).pluck().get();if(r!==t-n||o!==void 0||a!==void 0||s!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set");return{priorAffectedCount:i}}function rc(e){e.exec(`
75
75
  CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
76
76
  INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
77
77
  SELECT g.symbol
@@ -111,7 +111,7 @@ import{a as Z}from"./chunk-XU75YQN4.js";import{a as bo,b as Ro,c as Mt,d as qn,h
111
111
  CROSS JOIN main.global_symbols g ON g.id = m.symbol_id;
112
112
  INSERT OR IGNORE INTO temp.incremental_touched_symbols(symbol)
113
113
  SELECT symbol FROM incremental.global_symbols;
114
- `)}function kl(e){let t=e.prepare(`WITH changed_symbols AS (
114
+ `)}function ic(e){let t=e.prepare(`WITH changed_symbols AS (
115
115
  SELECT symbol FROM temp.incremental_old_defined_symbols
116
116
  UNION
117
117
  SELECT symbol FROM temp.incremental_new_defined_symbols
@@ -133,7 +133,7 @@ import{a as Z}from"./chunk-XU75YQN4.js";import{a as bo,b as Ro,c as Mt,d as qn,h
133
133
  LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
134
134
  WHERE m.symbol_id = g.id AND m.role = 1 AND p.relative_path IS NULL
135
135
  )
136
- LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function Cl(e){e.exec(`
136
+ LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function oc(e){e.exec(`
137
137
  DELETE FROM main.mentions
138
138
  WHERE chunk_id IN (
139
139
  SELECT c.id
@@ -155,7 +155,7 @@ import{a as Z}from"./chunk-XU75YQN4.js";import{a as bo,b as Ro,c as Mt,d as qn,h
155
155
  );
156
156
  DELETE FROM main.documents
157
157
  WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
158
- `)}function Dl(e){e.exec(`
158
+ `)}function ac(e){e.exec(`
159
159
  UPDATE main.global_symbols
160
160
  SET display_name = NULL,
161
161
  kind = NULL,
@@ -197,7 +197,7 @@ import{a as Z}from"./chunk-XU75YQN4.js";import{a as bo,b as Ro,c as Mt,d as qn,h
197
197
  WHERE source.symbol = main.global_symbols.symbol
198
198
  )
199
199
  WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
200
- `)}function _l(e){let t=Se(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=Se(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=Se(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)
200
+ `)}function sc(e){let t=K(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=K(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=K(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
201
201
  SELECT id + ?, language, relative_path, position_encoding, text
202
202
  FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
203
203
  SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
@@ -212,16 +212,16 @@ import{a as Z}from"./chunk-XU75YQN4.js";import{a as bo,b as Ro,c as Mt,d as qn,h
212
212
  r.start_line, r.start_char, r.end_line, r.end_char
213
213
  FROM incremental.defn_enclosing_ranges r
214
214
  CROSS JOIN incremental.global_symbols source ON source.id = r.symbol_id
215
- CROSS JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function Fl(e,t){let n=t?"symbol IN (SELECT symbol FROM temp.incremental_touched_symbols) AND":"";e.exec(`
215
+ CROSS JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function cc(e,t){let n=t?"symbol IN (SELECT symbol FROM temp.incremental_touched_symbols) AND":"";e.exec(`
216
216
  DELETE FROM main.global_symbols
217
217
  WHERE ${n}
218
218
  NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
219
219
  AND NOT EXISTS (
220
220
  SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
221
221
  );
222
- `)}function Al(e,t,n,r){let i=Se(e,"SELECT COUNT(*) AS value FROM main.documents"),o=Se(e,`SELECT COUNT(*) AS value
222
+ `)}function uc(e,t,n,r){let i=K(e,"SELECT COUNT(*) AS value FROM main.documents"),o=K(e,`SELECT COUNT(*) AS value
223
223
  FROM main.documents d
224
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),a=n-r+t;if(i!==a||o!==t)throw new Error("candidate SQLite document counts changed unexpectedly")}function Ol(e){let t=ur(e,"main",!0),n=ur(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 ur(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
224
+ JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),a=n-r+t;if(i!==a||o!==t)throw new Error("candidate SQLite document counts changed unexpectedly")}function lc(e){let t=Qt(e,"main",!0),n=Qt(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 Qt(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
225
225
  FROM ${t}.documents d
226
226
  ${r}
227
227
  ORDER BY d.relative_path`).all(),o=e.prepare(`SELECT d.relative_path, c.chunk_index, c.start_line, c.end_line, hex(c.occurrences) AS occurrences
@@ -243,10 +243,10 @@ import{a as Z}from"./chunk-XU75YQN4.js";import{a as bo,b as Ro,c as Mt,d as qn,h
243
243
  JOIN ${t}.documents d ON d.id = c.document_id
244
244
  JOIN ${t}.global_symbols g ON g.id = m.symbol_id
245
245
  ${r}
246
- ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[u,l]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let p of l){let m=JSON.stringify([u,p]),g=c.get(p.relative_path)??[];g.push(m),c.set(p.relative_path,g)}let d=new Map;for(let[u,l]of[...c].sort(([p],[m])=>p.localeCompare(m))){let p=hl("sha256");for(let m of l.sort())p.update(m).update(`
247
- `);d.set(u,p.digest("hex"))}return d}function Se(e,t){return e.prepare(t).get().value}import Ll from"better-sqlite3";var Vt="idx_mentions_definitions",Ml=["symbol_id","chunk_id"];function lr(e,t={}){let n=new Ll(e),r=[],i=[],o=[];try{return n.transaction(()=>{jl(n,r),Ut(n,"idx_global_symbols_symbol")?.join("\0")==="symbol"&&ya(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")):Ut(n,"idx_global_symbols_symbol")&&o.push("idx_global_symbols_symbol");let a=Ut(n,"idx_chunks_doc_id"),s=ya(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 jl(e,t){let n=Sa(e,Vt);if(n){let r=n.columns.join("\0")===Ml.join("\0"),i=/\bWHERE\s+role\s*=\s*1\b/iu.test(n.sql??"");if(!r||!i||n.table!=="mentions")throw new Error(`${Vt} exists with an incompatible definition`);return}e.exec(`CREATE INDEX "${Vt}" ON mentions(symbol_id, chunk_id) WHERE role = 1`),t.push(Vt)}function ya(e,t){return e.prepare(`PRAGMA index_list('${t.replaceAll("'","''")}')`).all().map(n=>({name:n.name,unique:n.unique===1,columns:Ut(e,n.name)??[]}))}function Ut(e,t){return Sa(e,t)?.columns??null}function Sa(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 Nl}from"fs";function se(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 Ra(e,t){let n=performance.now(),r=await e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}function xa(e){let t=e.readFingerprint(),n=va(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return Pa(e.cachePath,e.readFingerprint(),r),r}async function Ia(e){let t=e.readFingerprint(),n=va(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=await e.compute();return Pa(e.cachePath,e.readFingerprint(),r),r}function va(e,t){try{let n=JSON.parse(L(e,{maxBytes:q,inputKind:"post-index augmentation cache"}));return ba(n.fingerprint)===ba(t)?{result:n.result}:null}catch{return null}}function Pa(e,t,n){Nl(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
248
- `)}function ba(e){return JSON.stringify(e)}import Gl from"better-sqlite3";var $l=25,Bl=new Set(["typescript","javascript"]);function qt(e,t,n){let r=null;try{r=new Gl(e,{readonly:!0,fileMustExist:!0});let i=new Set(r.prepare("SELECT relative_path FROM documents").pluck().all().map(vn)),o=Vl(t,n),a=new Set([...o.values()].flatMap(u=>[...u])),s=[...a].filter(u=>!i.has(u)).sort();if(s.length===0)return{state:"complete",expectedDocumentCount:a.size,actualDocumentCount:i.size};let c=new Set(s),d=n.filter(u=>[...o.get(u)??[]].some(l=>c.has(l)));return{state:"incomplete",expectedDocumentCount:a.size,actualDocumentCount:i.size,missingDocumentCount:s.length,missingPaths:s.slice(0,$l),affectedLanguages:d}}catch(i){return{state:"unavailable",reason:i instanceof Error?i.message:String(i)}}finally{r?.close()}}function Vl(e,t){let n=new Map,r=t.filter(i=>Bl.has(i));for(let i of r)n.set(i,new Set);for(let i of e.files){let o=vn(i.path);for(let a of r)Me(o,[a])==="source"&&n.get(a).add(o)}return n}import{createHash as Ul}from"crypto";import{existsSync as pr,readdirSync as ql}from"fs";import{dirname as fr,join as Wt,relative as Wl,resolve as mr,sep as wa}from"path";function Ea(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=Da(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Ta(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=Da(s,e);c&&c!==i&&a.add(c)}}return Hl(e,r)}function ka(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 gr(e){if(e===".")return"root";let t=Ul("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Ca(e,t){let n=mr(e),r={};for(let i of t)r[i]=zl(n,i);return r}function Da(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 Hl(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 zl(e,t){let n=t==="."?e:Wt(e,t),r=Yl(n),i=Jl(n),o=i?Xl(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 Yl(e){let t=Wt(e,"package.json");if(!pr(t))return{name:void 0,dependencyNames:[],failed:!1};let n=hr(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 Jl(e){let t=Wt(e,"tsconfig.json");if(pr(t))return t;let n;try{n=ql(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?Wt(e,n[0]):void 0}function Xl(e,t){let n=hr(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=Kl(n.value,e,t),i=_a(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function Kl(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=fr(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=Fa(s,i,n);c&&o.add(c)}return[...o]}function _a(e,t,n,r){let i=Ql(t);if(i)return{pathsTargets:Zl(i,fr(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=ep(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=hr(o);return a.ok?_a(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function Ql(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 Zl(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=Fa(o,t,n);a&&r.add(a)}return[...r]}function ep(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=mr(fr(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(wa).includes("node_modules")&&Pn(n,i)&&pr(i))return i}function Fa(e,t,n){let r=e.replace(/\/?\*+$/,""),i=mr(t,r===""?".":r);if(!Pn(n,i))return;let a=Wl(n,i).split(wa).join("/");return a===""?".":a}function tp(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]!==`
249
- `;)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 hr(e){try{let t=L(e,{maxBytes:q,inputKind:"TypeScript project manifest"}),n=JSON.parse(tp(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import np from"better-sqlite3";import{zstdCompressSync as rp}from"zlib";import{setImmediate as Aa}from"timers/promises";var be=class extends Error{},ip=200,Sr=2,Oa=1,op=2,ap=3,sp=4,cp=5,dp=6,Ga=1,$a=2,Ba=3,up=7,lp=1,pp=3,fp=5,mp=6,gp=8,hp=1,La=64,yp=[`CREATE TABLE documents (
246
+ ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[l,d]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let m of d){let f=JSON.stringify([l,m]),y=c.get(m.relative_path)??[];y.push(f),c.set(m.relative_path,y)}let u=new Map;for(let[l,d]of[...c].sort(([m],[f])=>m.localeCompare(f))){let m=Hs("sha256");for(let f of d.sort())m.update(f).update(`
247
+ `);u.set(l,m.digest("hex"))}return u}function K(e,t){return e.prepare(t).get().value}import dc from"better-sqlite3";var rt="idx_mentions_definitions",pc=["symbol_id","chunk_id"];function Zt(e,t={}){let n=new dc(e),r=[],i=[],o=[];try{return n.transaction(()=>{mc(n,r),it(n,"idx_global_symbols_symbol")?.join("\0")==="symbol"&&wi(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")):it(n,"idx_global_symbols_symbol")&&o.push("idx_global_symbols_symbol");let a=it(n,"idx_chunks_doc_id"),s=wi(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 mc(e,t){let n=ki(e,rt);if(n){let r=n.columns.join("\0")===pc.join("\0"),i=/\bWHERE\s+role\s*=\s*1\b/iu.test(n.sql??"");if(!r||!i||n.table!=="mentions")throw new Error(`${rt} exists with an incompatible definition`);return}e.exec(`CREATE INDEX "${rt}" ON mentions(symbol_id, chunk_id) WHERE role = 1`),t.push(rt)}function wi(e,t){return e.prepare(`PRAGMA index_list('${t.replaceAll("'","''")}')`).all().map(n=>({name:n.name,unique:n.unique===1,columns:it(e,n.name)??[]}))}function it(e,t){return ki(e,t)?.columns??null}function ki(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 fc}from"fs";function G(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 Fi(e,t){let n=performance.now(),r=await e.run(t);return{stageId:e.id,facts:e.facts,durationMs:performance.now()-n,result:r}}function Ci(e){let t=e.readFingerprint(),n=Di(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return Ai(e.cachePath,e.readFingerprint(),r),r}async function Oi(e){let t=e.readFingerprint(),n=Di(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=await e.compute();return Ai(e.cachePath,e.readFingerprint(),r),r}function Di(e,t){try{let n=JSON.parse(N(e,{maxBytes:me,inputKind:"post-index augmentation cache"}));return _i(n.fingerprint)===_i(t)?{result:n.result}:null}catch{return null}}function Ai(e,t,n){fc(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
248
+ `)}function _i(e){return JSON.stringify(e)}import{createHash as gc}from"crypto";import{existsSync as en,readdirSync as hc}from"fs";import{dirname as tn,join as ot,relative as yc,resolve as nn,sep as Mi}from"path";function Li(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=Vi(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function ji(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=Vi(s,e);c&&c!==i&&a.add(c)}}return Sc(e,r)}function Ni(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=gc("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function $i(e,t){let n=nn(e),r={};for(let i of t)r[i]=bc(n,i);return r}function Vi(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 Sc(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 bc(e,t){let n=t==="."?e:ot(e,t),r=Rc(n),i=xc(n),o=i?Pc(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 Rc(e){let t=ot(e,"package.json");if(!en(t))return{name:void 0,dependencyNames:[],failed:!1};let n=on(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 xc(e){let t=ot(e,"tsconfig.json");if(en(t))return t;let n;try{n=hc(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?ot(e,n[0]):void 0}function Pc(e,t){let n=on(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=vc(n.value,e,t),i=Bi(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function vc(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=tn(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=Ui(s,i,n);c&&o.add(c)}return[...o]}function Bi(e,t,n,r){let i=Ic(t);if(i)return{pathsTargets:Ec(i,tn(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=Tc(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=on(o);return a.ok?Bi(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function Ic(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 Ec(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=Ui(o,t,n);a&&r.add(a)}return[...r]}function Tc(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=nn(tn(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Mi).includes("node_modules")&&It(n,i)&&en(i))return i}function Ui(e,t,n){let r=e.replace(/\/?\*+$/,""),i=nn(t,r===""?".":r);if(!It(n,i))return;let a=yc(n,i).split(Mi).join("/");return a===""?".":a}function wc(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]!==`
249
+ `;)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 on(e){try{let t=N(e,{maxBytes:me,inputKind:"TypeScript project manifest"}),n=JSON.parse(wc(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import kc from"better-sqlite3";import{zstdCompressSync as _c}from"zlib";import{setImmediate as Gi}from"timers/promises";var Q=class extends Error{},Fc=200,sn=2,Wi=1,Cc=2,Oc=3,Dc=4,Ac=5,Mc=6,Yi=1,Xi=2,Ki=3,Lc=7,jc=1,Nc=3,$c=5,Vc=6,Bc=8,Uc=1,qi=64,Gc=[`CREATE TABLE documents (
250
250
  id INTEGER PRIMARY KEY,
251
251
  language TEXT,
252
252
  relative_path TEXT NOT NULL UNIQUE,
@@ -286,11 +286,11 @@ import{a as Z}from"./chunk-XU75YQN4.js";import{a as bo,b as Ro,c as Mt,d as qn,h
286
286
  end_char INTEGER NOT NULL,
287
287
  FOREIGN KEY (document_id) REFERENCES documents(id),
288
288
  FOREIGN KEY (symbol_id) REFERENCES global_symbols(id)
289
- )`],Sp=["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 yr(e){return e.startsWith("local ")}function Ma(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 ja(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 bp(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 Rp(e,t,n,r){let i=[],o=[],a="",s=0;for(let d of B(e,n,r))d.fieldNumber===Ga?d.wireType===2?Ma(e,d.valueStart,d.valueEnd,i):d.wireType===0&&i.push(d.varint):d.fieldNumber===$a&&d.wireType===2?a=We.decode(e.subarray(d.valueStart,d.valueEnd)):d.fieldNumber===Ba&&d.wireType===0?s=d.varint:d.fieldNumber===up&&(d.wireType===2?Ma(e,d.valueStart,d.valueEnd,o):d.wireType===0&&o.push(d.varint));let c=ja(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:ja(o)}:null}function xp(e,t,n){let r={symbol:"",displayName:null,kind:null,documentation:[],enclosingSymbol:null};for(let i of B(e,t,n))if(i.wireType===2){let o=()=>We.decode(e.subarray(i.valueStart,i.valueEnd));i.fieldNumber===lp?r.symbol=o():i.fieldNumber===pp?r.documentation.push(o()):i.fieldNumber===mp?r.displayName=o():i.fieldNumber===gp&&(r.enclosingSymbol=o())}else i.fieldNumber===fp&&i.wireType===0&&(r.kind=i.varint);return r}var We=new TextDecoder;function Ip(e,t){if(e.length===0)return[];let n=[],r=Math.min(e.length,t);for(let i=0;i<r&&r<=e.length;){for(;r<=e.length-1&&e[r-1].startLine===e[r].startLine;)r+=1;n.push(e.slice(i,r)),i=r,r=Math.min(e.length,r+t)}return n}function vp(e){let t=e.startLine===e.endLine?[e.startLine,e.startChar,e.endChar]:[e.startLine,e.startChar,e.endLine,e.endChar],n=[],r=Buffer.concat(t.map(a=>X(a)));n.push(ye(Ga),X(r.length),r);let i=Buffer.from(e.symbol,"utf8");n.push(ye($a),X(i.length),i),e.roles!==0&&n.push(X(Ba*8),X(e.roles));let o=Buffer.concat(n);return Buffer.concat([ye(Sr),X(o.length),o])}function Pp(e,t){let n=[];for(let r of t)r.merged?n.push(vp(r)):n.push(e.subarray(r.frameStart,r.frameEnd));return rp(Buffer.concat(n))}async function Va(e,t,n={}){let r=n.chunkSize??ip,i={documents:0,duplicateDocumentsSkipped:0,occurrences:0,illegalOccurrencesDropped:0,mergedOccurrences:0,chunks:0,mentions:0,globalSymbols:0,enclosingRanges:0},o=new np(t);try{o.pragma("synchronous = normal"),o.pragma("temp_store = memory"),o.pragma("foreign_keys = ON"),o.pragma("journal_mode = WAL");for(let T of yp)o.exec(T);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 (?, ?, ?, ?, ?, ?)"),d=o.prepare("INSERT INTO global_symbols (id, symbol, display_name, kind, documentation, enclosing_symbol) VALUES (?, ?, ?, ?, ?, ?)"),u=o.prepare("INSERT INTO mentions (chunk_id, symbol_id, role) VALUES (?, ?, ?)"),l=new Map,p=new Map,m=1,g=1,y=1,v=(T,M,C,S,b)=>{let h=y;return y+=1,p.set(T,h),d.run(h,T,M,C,S,b),i.globalSymbols+=1,h};o.exec("BEGIN IMMEDIATE");let A=!1;try{let T=0;for(let C of B(e)){if(C.fieldNumber!==Sr||C.wireType!==2)continue;Na(n.signal),T+=1,T>=La&&(T=0,await Aa());let S="",b=null,h=null,F=null,x=[];for(let f of B(e,C.valueStart,C.valueEnd))f.wireType===2?f.fieldNumber===Oa?S=We.decode(e.subarray(f.valueStart,f.valueEnd)):f.fieldNumber===ap?x.push(xp(e,f.valueStart,f.valueEnd)):f.fieldNumber===sp?b=We.decode(e.subarray(f.valueStart,f.valueEnd)):f.fieldNumber===cp&&(h=We.decode(e.subarray(f.valueStart,f.valueEnd))):f.fieldNumber===dp&&f.wireType===0&&(F=wp(f.varint));if(S==="")throw new be("relative path must not be empty");if(l.has(S)){i.duplicateDocumentsSkipped+=1;continue}let P=m;m+=1,a.run(P,b===""?null:b,S,F,h===""?null:h),l.set(S,P),i.documents+=1;let k=new Map;for(let f of x){if(f.symbol==="")throw new be(`empty symbol in SymbolInformation for document ${S}`);let I=k.get(f.symbol);if(!I){k.set(f.symbol,f);continue}for(let $ of f.documentation)I.documentation.includes($)||I.documentation.push($)}for(let f of[...k.values()].sort((I,$)=>I.symbol<$.symbol?-1:I.symbol>$.symbol?1:0))yr(f.symbol)||p.has(f.symbol)||v(f.symbol,f.displayName===""?null:f.displayName,f.kind===0?null:f.kind,f.documentation.length===0?null:f.documentation.join(`
290
- `),f.enclosingSymbol===""?null:f.enclosingSymbol)}let M=new Set;T=0;for(let C of B(e)){if(C.fieldNumber!==Sr||C.wireType!==2)continue;Na(n.signal),T+=1,T>=La&&(T=0,await Aa());let S="",b=[];for(let x of B(e,C.valueStart,C.valueEnd))if(x.wireType===2){if(x.fieldNumber===Oa)S=We.decode(e.subarray(x.valueStart,x.valueEnd));else if(x.fieldNumber===op){let P=Rp(e,x.fieldStart,x.valueStart,x.valueEnd);P?b.push(P):i.illegalOccurrencesDropped+=1}}if(M.has(S))continue;M.add(S);let h=l.get(S);if(h===void 0)continue;b.sort(bp);let F=[];for(let x of b){let P=F[F.length-1];if(P&&P.startLine===x.startLine&&P.startChar===x.startChar&&P.endLine===x.endLine&&P.endChar===x.endChar&&P.symbol===x.symbol){P.roles|=x.roles,P.merged=!0,i.mergedOccurrences+=1;continue}F.push(x)}i.occurrences+=F.length;for(let x of F){if((x.roles&hp)===0||yr(x.symbol)||!x.enclosing)continue;let[P,k,f,I]=x.enclosing;if(P<0||k<0||f<P||f===P&&I<k)throw new be(`bad enclosing range for symbol ${x.symbol} in ${S}`);let $=p.get(x.symbol);if($===void 0)throw new be(`symbol ${x.symbol} has definition occurrence, but no SymbolInformation`);c.run(h,$,P,k,f,I),i.enclosingRanges+=1}for(let[x,P]of Ip(F,r).entries()){let k=g;g+=1,s.run(k,h,x,P[0].startLine,P[P.length-1].startLine,Pp(e,P)),i.chunks+=1;let f=new Map;for(let I of P){if(yr(I.symbol))continue;let $=f.get(I.symbol);$||f.set(I.symbol,$=new Set),$.add(I.roles),p.has(I.symbol)||v(I.symbol,null,null,null,null)}for(let[I,$]of f){let le=p.get(I);for(let In of $)u.run(k,le,In),i.mentions+=1}}}o.exec("COMMIT"),A=!0}finally{if(!A)try{o.exec("ROLLBACK")}catch{}}o.exec("BEGIN IMMEDIATE");for(let T of Sp)o.exec(T);o.exec("COMMIT"),o.pragma("wal_checkpoint(TRUNCATE)")}finally{o.close()}return i}function wp(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 be(`unknown position encoding ${e}`)}function Na(e){if(e?.aborted)throw new be("SCIP SQLite conversion aborted")}import{createHash as vs,randomUUID as lf}from"crypto";import{existsSync as xe,lstatSync as Nr,mkdirSync as ze,mkdtempSync as Ps,readdirSync as ws,realpathSync as Es,renameSync as De,rmSync as Re,statSync as tn}from"fs";import{dirname as Gr,join as R,resolve as $r}from"path";import{setTimeout as pf}from"timers/promises";import{pathToFileURL as Ss}from"url";import ff from"better-sqlite3";import{lstatSync as Bp,readdirSync as Vp}from"fs";import{join as Up,relative as qp,resolve as wr,sep as Wp}from"path";import{existsSync as qa,readdirSync as Wa,rmSync as Ha}from"fs";import{join as He}from"path";import{create as Ya,fromBinary as Ja,toBinary as SS}from"@bufbuild/protobuf";import{deserializeSCIP as br,DocumentSchema as Xa,IndexSchema as Ka,serializeSCIP as Qa}from"@c4312/scip";import{existsSync as Ep,mkdirSync as Tp,renameSync as kp,writeFileSync as Cp}from"fs";import{join as Dp}from"path";function Ua(e){Tp(e.blobDir,{recursive:!0});let t=Dp(e.blobDir,`${e.blobHash}.scipdoc`);if(Ep(t)){let r=j(t,{maxBytes:pe,inputKind:e.inputKind});if(r.byteLength!==e.bytes.byteLength||ae(r)!==e.blobHash)throw new Error(`existing ${e.inputKind} is corrupt: ${e.relativePath}`);return}let n=`${t}.${process.pid}.${Date.now()}.tmp`;Cp(n,e.bytes),kp(n,t)}var Rr=1,ut="typescript-scip-fragments";function Za(e){let t=new Set,n=[];for(let o of e){let a=Ht(o.relativePath);if(t.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(t.add(a),o.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${a}`);let s=Ja(Xa,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=Qa(Ya(Ka,{documents:n,externalSymbols:[]})),i=br(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function _p(e){let t=He(e,ut);return{rootDir:t,blobDir:He(t,"blobs"),generationDir:He(t,"generations")}}function es(e){let t=Fp(e);return Ap(t.baseIndex,t.completeDocuments,"assembled")}function Fp(e){let t=br(e.baseIndexBytes);jp(t.metadata,Np(e)),Mp(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=Ht(s.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);n.set(c,s)}if(n.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let r=new Set,i=[],o=[],a=[];for(let s of t.documents){let c=Ht(s.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let d=n.get(c);if(!d){i.push(s);continue}if(n.delete(c),d.bytes===null){a.push(c);continue}let u=za(c,d.bytes);i.push(u),o.push(u)}for(let s of[...n.keys()].sort()){let c=n.get(s);if(c.bytes===null)continue;if(r.has(s))throw new Error(`duplicate TypeScript SCIP document path: ${s}`);r.add(s);let d=za(s,c.bytes);i.push(d),o.push(d)}return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:a}}function za(e,t){let n=Ja(Xa,t);if(n.relativePath!==e)throw new Error(`TypeScript fragment path mismatch: expected ${e}, got ${n.relativePath}`);return n}function Ap(e,t,n){let r=Qa(Ya(Ka,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=br(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function ts(e,t){let n=_p(e);if(!qa(n.generationDir))return;let r=new Set(t.map(a=>Lp(a))),i=Wa(n.generationDir).filter(a=>a.endsWith(".json")),o=new Set;for(let a of i.filter(s=>r.has(s))){let s=Op(L(He(n.generationDir,a),{maxBytes:q,inputKind:"TypeScript fragment manifest"}));for(let c of s.documents)o.add(`${c.blobHash}.scipdoc`)}for(let a of i)r.has(a)||Ha(He(n.generationDir,a),{force:!0});if(qa(n.blobDir))for(let a of Wa(n.blobDir))o.has(a)||Ha(He(n.blobDir,a),{force:!0})}function Op(e){let t=JSON.parse(e);if(t.version!==Rr||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let n=new Set;for(let r of t.documents){if(!r||typeof r.relativePath!="string"||typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash)||typeof r.byteLength!="number"||!Number.isInteger(r.byteLength)||r.byteLength<0||typeof r.documentIdentity!="string"||!r.documentIdentity)throw new Error("invalid TypeScript fragment record");if(Ht(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function Lp(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${ae(e)}.json`}function Mp(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function jp(e,t){if(!e||typeof e!="object")throw new Error("TypeScript SCIP shard has no producer metadata");let n=e,r=n.toolInfo??n.tool_info;if(!r||typeof r!="object")throw new Error("TypeScript SCIP shard has no producer tool identity");let i=r;if(i.name!=="scip-typescript"||i.version!==t)throw new Error("TypeScript SCIP shard producer identity changed")}function Np(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function Ht(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.includes("\\"))throw new Error(`invalid TypeScript SCIP document path: ${e}`);let t=e.split("/");if(t.includes("")||t.includes(".")||t.includes(".."))throw new Error(`invalid TypeScript SCIP document path: ${e}`);return e}import{existsSync as zt,readdirSync as xr,rmSync as ns}from"fs";import{join as ne}from"path";var Yt=1,lt="typescript-scip-overlays",rs="typescript-project-v3:";function os(e){let t=cs(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t?.producerIdentity!==void 0&&t.producerIdentity!==e.producerIdentity)throw new Error("TypeScript overlay producer identity changed");let n=e.allowLegacyProjectIdentityMigration===!0&&t!==null&&!t.projectIdentity.startsWith(rs)&&e.projectIdentity.startsWith(rs);if(t&&t.projectIdentity!==e.projectIdentity&&!e.allowProjectIdentityChange&&!n)throw new Error("TypeScript overlay project identity changed");let r=new Map((t?.overlays??[]).map(a=>[a.relativePath,a])),i=new Set;for(let a of e.fragments){let s=Pr(a.relativePath);if(i.has(s))throw new Error(`duplicate TypeScript overlay: ${s}`);i.add(s),r.set(s,Gp(e.cacheDir,a))}if(i.size===0)throw new Error("TypeScript overlay generation requires affected documents");let o={version:Yt,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...r.values()].sort((a,s)=>a.relativePath.localeCompare(s.relativePath))};return $p(e.cacheDir,o),o}function as(e){let t=cs(e.cacheDir,e.generationIdentity);if(!t)throw new Error("TypeScript overlay generation is unavailable");let n=t.overlays.map(r=>{if(r.blobHash===null)return{relativePath:r.relativePath,bytes:null,occurrences:0,symbols:0,referenceFragments:[]};let i=j(ne(pt(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`),{maxBytes:pe,inputKind:"TypeScript overlay blob"});if(i.byteLength!==r.byteLength||ae(i)!==r.blobHash)throw new Error(`TypeScript overlay blob is corrupt: ${r.relativePath}`);return{relativePath:r.relativePath,bytes:i,occurrences:0,symbols:0,referenceFragments:[]}});return es({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function ss(e,t){let n=pt(e),r=ne(n,"generations");if(!zt(r))return;let i=new Set(t.map(vr)),o=new Set;for(let s of xr(r).filter(c=>i.has(c))){let c=Ir(L(ne(r,s),{maxBytes:q,inputKind:"TypeScript overlay manifest"}));for(let d of c.overlays)d.blobHash&&o.add(`${d.blobHash}.scipdoc`)}for(let s of xr(r))i.has(s)||ns(ne(r,s),{force:!0});let a=ne(n,"blobs");if(zt(a))for(let s of xr(a))o.has(s)||ns(ne(a,s),{force:!0})}function cs(e,t){let n=ne(pt(e),"generations",vr(t));if(!zt(n))return null;let r=Ir(L(n,{maxBytes:q,inputKind:"TypeScript overlay manifest"}));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function Gp(e,t){let n=Pr(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=ae(r);return Ua({blobDir:ne(pt(e),"blobs"),blobHash:i,bytes:r,relativePath:n,inputKind:"TypeScript overlay blob"}),{relativePath:n,blobHash:i,byteLength:r.byteLength}}function $p(e,t){let n=ne(pt(e),"generations",vr(t.generationIdentity));if(zt(n)){let r=Ir(L(n,{maxBytes:q,inputKind:"TypeScript overlay manifest"}));if(is(r)!==is(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}ge(n,t,{spacing:2,trailingNewline:!0})}function Ir(e){let t=JSON.parse(e);if(t.version!==Yt||typeof t.producerIdentity!="string"||!t.producerIdentity||typeof t.projectIdentity!="string"||!t.projectIdentity||typeof t.baseGenerationIdentity!="string"||!t.baseGenerationIdentity||typeof t.generationIdentity!="string"||!t.generationIdentity||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.overlays))throw new Error("invalid TypeScript overlay manifest");let n=new Set;for(let r of t.overlays){if(!r||typeof r.relativePath!="string"||r.blobHash!==null&&(typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash))||!Number.isInteger(r.byteLength)||r.byteLength<0||r.blobHash===null&&r.byteLength!==0)throw new Error("invalid TypeScript overlay record");if(Pr(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function pt(e){return ne(e,lt)}function vr(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${ae(e)}.json`}function is(e){return ae(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function Pr(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}var ft=1,Er="language-indexes",ds=["index.db","index.scip","meta.json"],us=[Er,ut,lt];function Jt(e){let t=[];for(let n of ds)Hp(e,n),t.push(n);for(let n of us)ls(e,n,t);return{version:ft,files:t.sort()}}function Xt(e){if(!e||e.includes("\0")||e.startsWith("/")||e.includes("\\"))throw new Error(`invalid index artifact path: ${e||"<empty>"}`);let t=e.split("/");if(t.some(r=>!r||r==="."||r===".."))throw new Error(`invalid index artifact path: ${e}`);let n=t[0];if(!ds.includes(e)&&!us.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function re(e,t){let n=Xt(t),r=wr(e),i=wr(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${Wp}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function ls(e,t,n){let r=Up(e,t),i;try{i=Vp(r,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(let o of i){let a=`${t}/${o.name}`;if(o.isSymbolicLink())throw new Error(`index artifact cannot be a symlink: ${a}`);o.isDirectory()?ls(e,a,n):o.isFile()&&n.push(Xt(a))}}function Hp(e,t){let n=re(e,t),r;try{r=Bp(n)}catch{throw new Error(`required index artifact is missing: ${t}`)}if(!r.isFile()||r.isSymbolicLink())throw new Error(`required index artifact is not a regular file: ${t}`);if(qp(wr(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{createHash as Fr}from"crypto";import{closeSync as zp,existsSync as O,mkdirSync as Yp,openSync as Jp,readSync as Xp,readdirSync as Ar,renameSync as Dr,rmSync as mt,statSync as Ce}from"fs";import{basename as Or,dirname as ie,join as D,relative as ps}from"path";var Kp=Object.freeze({maxGenerations:2,maxLogicalBytes:2*1024*1024*1024});function Qt(e){let t=Q(e.outputDb),n=tf(e);e.onStage?.("after-recovery-retained");let r=e.preserveOutputScip?e.outputScip:e.tempOutputScip,i=nf(e,n),o=jr({generationRoot:t,databasePath:e.tempOutputDb,indexPath:O(r)?r:void 0,verifiedIndexArtifact:i,metadataPath:O(e.tempMetaPath)?e.tempMetaPath:void 0}),a=(e.now??(()=>new Date))().toISOString(),s={version:Ge,currentGeneration:o.identity,artifactSet:"immutable-v1",...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:a},c=Y(D(t,"state.json"),s,{spacing:2,trailingNewline:!0});e.onStage?.("after-pointer-handoff"),e.preserveOutputScip||Cr(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),Cr(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),Cr(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let d=o.identity,u={...s,stableMirrors:Mr(e.outputDb,e.outputScip)};Y(D(t,"state.json"),u,{spacing:2,trailingNewline:!0});let l=ms(e.outputDb,{now:e.now}),p=tt(o.directorySync,c.directorySync);return{currentGeneration:d,...n?{previousGeneration:n}:{},retention:l,achievedDurability:p==="synced"?"directory-durable":"file-flushed",directorySync:p}}function Lr(e,t,n,r=()=>new Date){if(!O(e))return null;let i=nt(e),o=D(Q(e),"state.json");if(i?.artifactSet==="immutable-v1"&&Dt(e,i.currentGeneration))return i;let a=Q(e),s=!i&&O(o)?of(n,e,t):void 0;if(s&&!_t(a,s))return null;let c=jr({generationRoot:a,databasePath:e,indexPath:O(t)?t:void 0,metadataPath:O(n)?n:void 0,forcedIdentity:i?.currentGeneration??s}),d={version:Ge,currentGeneration:c.identity,artifactSet:"immutable-v1",stableMirrors:Mr(e,t),...i?.previousGeneration?{previousGeneration:i.previousGeneration}:{},...i?.publication?{publication:i.publication}:{},publishedAt:i?.publishedAt??r().toISOString()};return Y(D(a,"state.json"),d,{spacing:2,trailingNewline:!0}),d}function Zt(e,t,n=()=>new Date){if(!O(e)||!O(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=nt(e),i=Q(e),o=jr({generationRoot:i,databasePath:e,indexPath:O(D(ie(e),"index.scip"))?D(ie(e),"index.scip"):void 0,metadataPath:t}),a=r&&r.currentGeneration!==o.identity?hs(e,r.currentGeneration):void 0,s={version:Ge,currentGeneration:o.identity,artifactSet:"immutable-v1",stableMirrors:Mr(e,D(ie(e),"index.scip")),...a?{previousGeneration:a}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return Y(D(Q(e),"state.json"),s,{spacing:2,trailingNewline:!0}),ms(e,{now:n}),s}function ms(e,t={}){let n=Qp(t.limits),i=(t.now??(()=>new Date))().toISOString(),o=Pe(Mi(e),{waitMs:0});if(!o)return{state:"deferred",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,staleReaderLeasesRemoved:0,malformedReaderLeases:0,removedGenerations:0,removedLogicalBytes:0,limits:n,at:i,reason:"another process owns local generation retention"};try{let a=nt(e),s=Zp(e),c=ji(e,s.map(v=>v.identity),{isProcessAlive:t.isProcessAlive??fe,readProcessIdentity:t.readProcessIdentity??ee}),d=new Set(c.protectedGenerations);a?.currentGeneration&&d.add(a.currentGeneration),a?.previousGeneration?.generationIdentity&&d.add(a.previousGeneration.generationIdentity);let u=s.length,l=s.reduce((v,A)=>v+A.logicalBytes,0),p=0,m=0;for(let v of s){if(u<=n.maxGenerations&&l<=n.maxLogicalBytes)break;d.has(v.identity)||(t.onBeforeRemove?.(v.identity),mt(v.path,{recursive:!0,force:!0}),u-=1,l-=v.logicalBytes,p+=1,m+=v.logicalBytes)}let g=u>n.maxGenerations||l>n.maxLogicalBytes,y={state:g?"protected":p>0?"collected":"within-bounds",generationCount:u,logicalBytes:l,protectedGenerations:d.size,activeReaderLeases:c.activeLeases,staleReaderLeasesRemoved:c.staleLeasesRemoved,malformedReaderLeases:c.malformedLeases,removedGenerations:p,removedLogicalBytes:m,limits:n,at:i,...g?{reason:c.malformedLeases>0?"malformed reader ownership evidence fails closed":"retention bounds cannot be met without deleting a protected generation"}:{}};return fs(e,y),y}catch(a){let s={state:"error",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,staleReaderLeasesRemoved:0,malformedReaderLeases:0,removedGenerations:0,removedLogicalBytes:0,limits:n,at:i,reason:a instanceof Error?a.message:String(a)};try{fs(e,s)}catch{}return s}finally{o.release()}}function Qp(e={}){let t={...Kp,...e};if(!Number.isSafeInteger(t.maxGenerations)||t.maxGenerations<2)throw new Error("Local SQLite generation retention must keep at least current and previous generations.");if(!Number.isSafeInteger(t.maxLogicalBytes)||t.maxLogicalBytes<=0)throw new Error("Local SQLite generation byte retention must be a positive safe integer.");return t}function Zp(e){let t=Q(e);return O(t)?Ar(t,{withFileTypes:!0}).filter(n=>n.isDirectory()&&/^[a-f0-9]{64}$/.test(n.name)).map(n=>{let r=D(t,n.name),i=_t(t,n.name),o=i?i.database.size+(i.index?.size??0)+(i.metadata?.size??0):gs(r);return{identity:n.name,path:r,logicalBytes:o,modifiedAtMs:Ce(r).mtimeMs}}).sort((n,r)=>n.modifiedAtMs-r.modifiedAtMs||n.identity.localeCompare(r.identity)):[]}function gs(e){let t=0;for(let n of Ar(e,{withFileTypes:!0})){let r=D(e,n.name);n.isDirectory()?t+=gs(r):n.isFile()&&(t+=Ce(r).size)}return t}function fs(e,t){ge(D(Q(e),"gc.json"),t,{spacing:2,trailingNewline:!0})}function K(e,t=D(ie(e),"meta.json")){let n=D(Q(e),"state.json");if(!O(n))return{state:"legacy",statePath:n};let r=nt(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=Dt(e,r.currentGeneration),o=i!==null,a=i?ef(e,t,i,r):!1,s=r.previousGeneration?O(D(ie(e),r.previousGeneration.databasePath)):!0;return!a||!o||!s?{state:"drifted",statePath:n,currentMatches:a,recoveryExists:s,generation:r,reason:o?a?"retained recovery database is missing":"stable database or metadata no longer matches the published generation":"published immutable generation is missing"}:{state:"current",statePath:n,currentMatches:a,recoveryExists:s,generation:r}}catch(i){return{state:"drifted",statePath:n,currentMatches:!1,recoveryExists:!1,generation:r,reason:i instanceof Error?i.message:String(i)}}}function ef(e,t,n,r){if(r.stableMirrors&&(r.stableMirrors.databaseFileIdentity!==rt(e)||r.stableMirrors.indexFileIdentity!==void 0&&r.stableMirrors.indexFileIdentity!==rt(D(ie(e),"index.scip")))||!_r(e,n.database))return!1;let i=D(ie(e),"index.scip");if(n.index&&!_r(i,n.index))return!1;if(!n.metadata)return!O(t);if(!O(t))return!1;let o=D(Q(e),n.identity,n.metadata.file);return O(o)&&we(U(t,"reindex metadata"))===we(U(o,"immutable reindex metadata"))}function _r(e,t){return O(e)&&Ce(e).isFile()&&Ce(e).size===t.size}function tf(e){let t=Lr(e.outputDb,e.outputScip,e.metaPath);return t?hs(e.outputDb,t.currentGeneration):void 0}function nf(e,t){if(!e.preserveOutputScip)return;if(!t)throw new Error("deferred SCIP publication requires an accepted immutable generation");let n=K(e.outputDb,e.metaPath);if(n.state!=="current"||n.generation.currentGeneration!==t.generationIdentity){let i=n.state==="current"?"generation identity changed":"reason"in n?n.reason:`generation state is ${n.state}`;throw new Error(`deferred SCIP publication requires a verified accepted companion: ${i}`)}let r=Dt(e.outputDb,t.generationIdentity);if(!r?.index||!_r(e.outputScip,r.index))throw new Error("deferred SCIP publication requires the verified accepted index artifact");return r.index}function Mr(e,t){return{databaseFileIdentity:rt(e),...O(t)?{indexFileIdentity:rt(t)}:{}}}function hs(e,t){let n=D(Q(e),t),r=D(n,Or(e)),i=D(n,"meta.json");return{generationIdentity:t,databasePath:ps(ie(e),r),...O(i)?{metadataPath:ps(ie(e),i)}:{}}}function rf(e){if(O(e))for(let t of Ar(e,{withFileTypes:!0}))t.isDirectory()&&t.name.endsWith(".tmp")&&mt(D(e,t.name),{recursive:!0,force:!0})}function of(e,t,n=D(ie(t),"index.scip")){let r=Fr("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(Kt(t)),O(n)&&r.update(`\0${Kt(n)}`),O(e)&&r.update(`\0${we(U(e,"reindex metadata"))}`),r.digest("hex")}function jr(e){let t=Tr(e.databasePath),n=e.indexPath?e.verifiedIndexArtifact?sf(e.indexPath,e.verifiedIndexArtifact):Tr(e.indexPath):void 0,r=e.metadataPath?Tr(e.metadataPath):void 0,i=e.forcedIdentity??af(t,n,e.metadataPath),o=D(e.generationRoot,i),a=D(o,kn);if(O(a)){let d=_t(e.generationRoot,i);if(d&&ys(o,d.database,t)&&df(o,d.index,n)&&uf(o,d.metadata,e.metadataPath))return{identity:i,directorySync:me(e.generationRoot)};throw new Error(`SQLite generation ${i} already exists with different or corrupt artifacts.`)}let s=[Tt(e.generationRoot)];rf(e.generationRoot);let c=`${o}.${process.pid}.${Date.now()}.tmp`;mt(c,{recursive:!0,force:!0}),Yp(c,{recursive:!0});try{s.push(kr(e.databasePath,D(c,t.file))),n&&e.indexPath&&s.push(kr(e.indexPath,D(c,n.file))),r&&e.metadataPath&&s.push(kr(e.metadataPath,D(c,r.file)));let d=Y(D(c,kn),{version:Li,identity:i,database:t,...n?{index:n}:{},...r?{metadata:r}:{}},{spacing:2,trailingNewline:!0});d.directorySync!=="not-requested"&&s.push(d.directorySync),s.push(me(c)),Dr(c,o),s.push(me(e.generationRoot))}finally{mt(c,{recursive:!0,force:!0})}return{identity:i,directorySync:tt(...s)}}function af(e,t,n){let r=Fr("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(e.sha256),t&&r.update(`\0${t.sha256}`),n&&r.update(`\0${we(U(n,"reindex metadata"))}`),r.digest("hex")}function Tr(e){return{file:Or(e),size:Ce(e).size,sha256:Kt(e)}}function sf(e,t){if(t.file!==Or(e)||Ce(e).size!==t.size)throw new Error(`verified SQLite generation artifact changed before publication: ${e}`);return t}function Kt(e){let t=Fr("sha256"),n=Jp(e,"r"),r=Buffer.allocUnsafe(1024*1024);try{for(;;){let i=cf(n,r);if(i===0)break;t.update(r.subarray(0,i))}}finally{zp(n)}return t.digest("hex")}function cf(e,t){let n=0;for(;n<t.length;){let r=Xp(e,t,n,t.length-n,null);if(n+=r,r===0)break}return n}function kr(e,t){return kt(e,t,{mode:292})}function ys(e,t,n){let r=D(e,t.file);return t.file===n.file&&t.size===n.size&&t.sha256===n.sha256&&O(r)&&Ce(r).size===t.size&&Kt(r)===t.sha256}function df(e,t,n){return!t||!n?t===n:ys(e,t,n)}function uf(e,t,n){if(!t||!n)return t===void 0&&n===void 0;let r=D(e,t.file);return O(r)&&we(U(r,"stored reindex metadata"))===we(U(n,"candidate reindex metadata"))}function Cr(e,t){mt(`${t}.tmp-replace`,{force:!0}),Dr(e,`${t}.tmp-replace`),Dr(`${t}.tmp-replace`,t)}var Br=1,bs="SCIP_QUERY_SHARED_CACHE",mf=2,en=JSON.stringify({cliVersion:Ui,artifactCatalogVersion:ft,postIndexAugmentationSchemaVersion:mf,sqliteGenerationStoreVersion:Ge,typescriptFragmentStoreVersion:Rr,typescriptOverlayStoreVersion:Yt}),Vr="manifest.json",gf="shared-cache.json";var Ur=[Er,ut,lt];function nn(e,t){if(!e.clean||!e.treeOid)return;let n=Ns(JSON.stringify({version:Br,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:It(t),producerIdentity:en}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:en,generationId:n,repositoryCacheDir:Hi(e.repositoryId)}}function Ts(e,t,n){if(process.env[bs]==="0")return`${bs}=0`;if(!zi(n))return"explicit cache or database override";if(Fn(Gr(t))!==Fn(Wi(e))||t!==R(Gr(t),"index.db"))return"index database is outside the managed worktree cache"}function ce(e,t=!0){let n=Wr(e),r;try{r=As(L(R(n,Vr),{inputKind:"shared-generation manifest",maxBytes:q}))}catch{return null}if(r.generationId!==e.generationId||r.repositoryId!==e.repositoryId||r.treeOid!==e.treeOid||r.producerIdentity!==e.producerIdentity||!vt(r.fingerprint,e.fingerprint)||!Sf(n))return null;if(!t)return r;try{for(let i of r.artifacts){let o=re(n,i.path),a=tn(o);if(!a.isFile()||a.size!==i.size||wt(o,{inputKind:"shared-generation artifact",maxBytes:G})!==i.sha256)return null}}catch{return null}return r}function ks(e,t,n,r){if(!e.treeOid)return null;let i=On(t,n),o=R(qi(),"repositories",e.repositoryId),a;try{let d=Nr(o);if(!d.isDirectory()||d.isSymbolicLink())return null;a=Es(o)}catch{return null}let s=R(a,"generations"),c=[];try{for(let d of ws(s)){if(!/^[a-f0-9]{64}$/.test(d))continue;let u=R(s,d),l;try{l=Nr(u)}catch{continue}if(!(!l.isDirectory()||l.isSymbolicLink()))try{let p=As(L(R(u,Vr),{inputKind:"shared-generation baseline manifest",maxBytes:q}));p.generationId===d&&p.repositoryId===e.repositoryId&&p.producerIdentity===en&&bf(p.fingerprint,i)&&c.push(p)}catch{continue}}}catch{return null}c.sort((d,u)=>{let l=d.treeOid===e.treeOid?0:1,p=u.treeOid===e.treeOid?0:1;if(l!==p)return l-p;if(r){let g=Is(d.fingerprint,r)-Is(u.fingerprint,r);if(g!==0)return g}return Date.parse(u.createdAt)-Date.parse(d.createdAt)||d.generationId.localeCompare(u.generationId)});for(let d of c){let u={repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:d.treeOid,fingerprint:d.fingerprint,producerIdentity:d.producerIdentity,generationId:d.generationId,repositoryCacheDir:a},l=ce(u);if(l)return{snapshot:u,manifest:l}}return null}function Cs(e){let t=Pe(R(e.snapshot.repositoryCacheDir,"locks",`${e.snapshot.generationId}.publish.lock`));if(!t)throw new Error(`shared generation publication is already in progress for ${e.snapshot.generationId}`);try{return hf(e)}finally{t.release()}}function hf(e){let t=ce(e.snapshot);if(t)return Rs(e.snapshot,t);if(!js(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=xs(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=Jt(e.sourceCacheDir),i=R(e.snapshot.repositoryCacheDir,"generations"),o=[Tt(i)],a=Ps(R(i,`.tmp-${process.pid}-`));try{let s=[];for(let g of r.files){let y=re(e.sourceCacheDir,g),v=re(a,g);o.push(ht(y,v,292)),e.onPublicationStage?.("after-artifact-flushed",g);let A=tn(v).size;s.push({path:g,size:A,sha256:wt(v,{inputKind:"staged shared-generation artifact",maxBytes:G})})}let c=at(j(R(a,"index.scip"),{inputKind:"staged shared SCIP index",maxBytes:G}));if(!c)throw new Error("shared SCIP generation has no project root metadata");let d=Hr(e.sourceProjectRoot);if(c!==d)throw new Error("shared SCIP generation root does not match its source worktree");if(xs(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let u={version:Br,artifactCatalogVersion:ft,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:c,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:s.sort((g,y)=>g.path.localeCompare(y.path))},l=Y(R(a,Vr),u,{spacing:2,trailingNewline:!0});l.directorySync!=="not-requested"&&o.push(l.directorySync),e.onPublicationStage?.("after-manifest-flushed"),o.push(me(a)),e.onPublicationStage?.("after-staging-directory-synced");let p=Wr(e.snapshot);try{if(xe(p)&&!ce(e.snapshot)){let g=`${p}.corrupt-${process.pid}-${Date.now()}`;De(p,g),Re(g,{recursive:!0,force:!0})}De(a,p)}catch(g){let y=ce(e.snapshot);if(y)return Rs(e.snapshot,y);throw g}e.onPublicationStage?.("after-generation-renamed"),o.push(me(i)),e.onPublicationStage?.("after-generations-directory-synced");let m=tt(...o);return{kind:"published",manifest:u,achievedDurability:m==="synced"?"directory-durable":"file-flushed",directorySync:m}}finally{Re(a,{recursive:!0,force:!0})}}function Rs(e,t){let n=me(R(e.repositoryCacheDir,"generations"));return{kind:"existing",manifest:t,achievedDurability:n==="synced"?"directory-durable":"file-flushed",directorySync:n}}function rn(e){let t=Wr(e.snapshot);ze(e.targetCacheDir,{recursive:!0});let n=Pe(R(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:e.lockWaitMs??3e4});if(!n)throw new Error("timed out waiting for another cache hydration");let r,i,o=!1;try{r=Ps(R(e.targetCacheDir,".shared-hydrate-")),vf(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let d=re(t,c.path),u=re(r,c.path);if(ht(d,u),tn(u).size!==c.size||wt(u,{inputKind:"hydrated shared-generation artifact",maxBytes:G})!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=Hr(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&ua(re(r,c.path),e.manifest.scipProjectRoot,a);if(!js(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=Rf(e.targetCacheDir,r),o=!0,xf(r,e.targetCacheDir,i),Qt({tempOutputScip:R(r,"index.scip"),tempOutputDb:R(r,"index.db"),tempMetaPath:R(r,"meta.json"),outputScip:R(e.targetCacheDir,"index.scip"),outputDb:R(e.targetCacheDir,"index.db"),metaPath:R(e.targetCacheDir,"meta.json"),now:e.now});let s=K(R(e.targetCacheDir,"index.db"),R(e.targetCacheDir,"meta.json"));if(s.state==="invalid"||s.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${s.reason}`);e.persistLease!==!1&&qr(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&If(e.targetCacheDir,i),a}finally{r&&Re(r,{recursive:!0,force:!0}),n.release()}}async function Ds(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??_,o=i()+n,a=R(e.repositoryCacheDir,"locks"),s=R(a,`${e.generationId}.lock`),c=d=>{if(!d||typeof d!="object"||Array.isArray(d))return null;let u=d.pid;return typeof u=="number"&&Number.isSafeInteger(u)&&u>0?{pid:u}:null};for(;i()<=o;){if(ce(e))return{kind:"generation-ready"};let d=Et(s,{kind:"shared-generation-build",detail:{generationId:e.generationId},parseLegacy:c});if(d.kind==="acquired")return{kind:"owner",release:()=>d.lock.release()};let u=o-i();if(u<=0)break;await pf(Math.min(r,u))}return ce(e)?{kind:"generation-ready"}:{kind:"timeout"}}function qr(e,t,n,r=void 0){let i={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,activeGenerationId:e.generationId,lastAction:n,lastSeenAt:(r??(()=>new Date))().toISOString()},o={...i,ownershipChecksum:Fs(i)};return Ls(e.repositoryCacheDir,o,!0),o}function _s(e,t,n=void 0){let r={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,lastAction:"overlay",lastReason:`private cache forked from shared baseline ${e.generationId}`,lastSeenAt:(n??(()=>new Date))().toISOString()},i={...r,ownershipChecksum:Fs(r)};return Ls(e.repositoryCacheDir,i,!0),i}function Fs(e){return Ns(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:$r(e.projectRoot),localCacheDir:$r(e.localCacheDir)}))}function As(e){let t=JSON.parse(e);if(t.version!==Br||t.artifactCatalogVersion!==ft||typeof t.generationId!="string"||!/^[a-f0-9]{64}$/.test(t.generationId)||typeof t.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(t.repositoryId)||typeof t.treeOid!="string"||!t.treeOid||typeof t.producerIdentity!="string"||t.producerIdentity!==en||typeof t.sourceProjectRoot!="string"||typeof t.scipProjectRoot!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!t.fingerprint||!Array.isArray(t.artifacts))throw new Error("invalid shared generation manifest");let n=new Set;for(let r of t.artifacts){if(!r||typeof r.path!="string"||typeof r.size!="number"||r.size<0||typeof r.sha256!="string"||!/^[a-f0-9]{64}$/.test(r.sha256))throw new Error("invalid shared generation artifact");if(Xt(r.path),n.has(r.path))throw new Error(`duplicate shared generation artifact: ${r.path}`);n.add(r.path)}for(let r of["index.db","index.scip","meta.json"])if(!n.has(r))throw new Error(`shared generation is missing ${r}`);return t}function ht(e,t,n=384){return kt(e,t,{mode:n})}function yf(e,t,n){ze(e,{recursive:!0}),Y(R(e,gf),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function xs(e){try{let t=Jt(e),n=vs("sha256");for(let r of t.files){let i=re(e,r),o=tn(i).size;n.update(r).update("\0").update(String(o)).update("\0"),_i(i,{inputKind:"source-generation artifact",maxBytes:G},a=>n.update(a)),n.update("\0")}return n.digest("hex")}catch{return null}}function Os(e){try{let t=oe(L(R(e,"meta.json"),{inputKind:"reindex metadata",maxBytes:q}));return(t.kind==="legacy"||t.kind==="supported")&&t.capabilities.publishableGeneration?t.metadata:void 0}catch{return}}function Sf(e){return Os(e)?.scipCompanion!=="deferred"}function bf(e,t){let n=On(e.languages,e);return JSON.stringify(n)===JSON.stringify(t)}function Is(e,t){let n=new Map(e.files.map(o=>[o.path,`${o.size}\0${o.hash}`])),r=new Map(t.files.map(o=>[o.path,`${o.size}\0${o.hash}`])),i=0;for(let[o,a]of n)r.get(o)!==a&&(i+=1);for(let o of r.keys())n.has(o)||(i+=1);return i}function Wr(e){return R(e.repositoryCacheDir,"generations",e.generationId)}function Ls(e,t,n){let r=Oi(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId??t.baseGenerationId;if(!o||!xe(R(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=R(e,"worktrees");ze(i,{recursive:!0}),Y(R(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),yf(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function Rf(e,t){let n=R(t,".rollback"),r=new Map,i=new Map;ze(n,{recursive:!0});for(let s of["index.scip","index.db","meta.json"]){let c=R(e,s),d=xe(c);r.set(s,d),d&&ht(c,R(n,"stable",s))}for(let s of Ur){let c=R(e,s),d=xe(c);if(d){let u=Nr(c);if(!u.isDirectory()||u.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${s}`)}i.set(s,d)}let o=R(e,Ct),a=xe(o);return a&&Ms(o,R(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:a}}function xf(e,t,n){for(let r of Ur){let i=R(t,r);if(n.managedDirectories.get(r)){let a=R(n.root,"managed",r);ze(Gr(a),{recursive:!0}),De(i,a)}let o=R(e,r);xe(o)&&De(o,i)}}function If(e,t){for(let i of Ur){let o=R(e,i),a=R(t.root,"managed",i);t.managedDirectories.get(i)?xe(a)&&(Re(o,{recursive:!0,force:!0}),De(a,o)):Re(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let a=R(e,i);if(!o){Re(a,{force:!0});continue}let s=`${a}.shared-restore-${lf()}`;ht(R(t.root,"stable",i),s),Re(a,{force:!0}),De(s,a)}let n=R(e,Ct);Re(n,{recursive:!0,force:!0});let r=R(t.root,"sqlite-generations");t.generationStoreExisted&&xe(r)&&De(r,n)}function Ms(e,t){ze(t,{recursive:!0});for(let n of ws(e,{withFileTypes:!0})){let r=R(e,n.name),i=R(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?Ms(r,i):n.isFile()&&ht(r,i)}}function vf(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||!vt(e.fingerprint,t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function js(e,t,n,r=!0,i=!0){try{let o=Os(e);if(!o||o.scipCompanion==="deferred"||!vt(Ze(o.fingerprint),n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return gt("source validation rejected metadata"),!1;let a=Jt(e),s=K(R(e,"index.db"),R(e,"meta.json"));if(r?s.state!=="current":s.state==="invalid"||s.state==="drifted")return gt(`source validation rejected SQLite generation state ${s.state}`),!1;let c=new ff(R(e,"index.db"),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let d=Hr(t),l=(i?a.files.filter(p=>p.endsWith(".scip")):["index.scip"]).every(p=>{let m=at(j(re(e,p),{inputKind:"shared SCIP validation artifact",maxBytes:G}));return m!==d&&gt(`source validation rejected SCIP root for ${p}: ${String(m)}`),m===d});return l||gt("source validation rejected SCIP project roots"),l}catch(o){return gt(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function gt(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function Hr(e){try{return Ss(Es(e)).href}catch{return Ss($r(e)).href}}function Ns(e){return vs("sha256").update(e).digest("hex")}import{readdirSync as Pf,rmSync as wf}from"fs";import{cpus as Ef,totalmem as Tf}from"os";import{join as on}from"path";var kf=2048,Cf=6*1024**3,Df=4;function zr(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_FILES??"",10);return Number.isSafeInteger(t)&&t>0?t:kf}function $s(e,t){return e>Math.floor(t*1.5)}var _f=1.25;function Bs(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*_f),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 Ff(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((d,u)=>d.localeCompare(u));if(t===1||r.length<=t)return r.length<=t&&t>1?r.map(d=>[d]):r.length>0?[r]:[];let i=r.map(d=>Math.max(1,n(d))),o=i.reduce((d,u)=>d+u,0),a=[],s=[],c=0;for(let d=0;d<r.length;d+=1){s.push(r[d]),c+=i[d];let u=t-a.length-1,l=r.length-d-1;u>0&&l>=u&&(c>=o*(a.length+1)/t||l===u)&&(a.push(s),s=[])}return s.length>0&&a.push(s),a}function Vs(e){let t=e.targetFiles??zr(),n=e.shardCount??Math.max(1,Math.ceil(new Set(e.inputPaths).size/Math.max(1,t)));return Ff(e.inputPaths,n,e.weightOf).map((r,i)=>{let o=on(e.projectRoot,Bi(i)),a=`${JSON.stringify({extends:`./${e.rootConfigPath}`,compilerOptions:{incremental:!1},files:r.map(s=>`./${s}`),include:[],exclude:[]},null,2)}
291
- `;return{configPath:o,content:a,inputPaths:r}})}var Us="typescript-shard-costs.json",Gs=4;function qs(e){let t;try{t=JSON.parse(Di(on(e,Us),"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 Ws(e,t){ge(on(e,Us),t)}function Hs(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(Gs,Math.max(1/Gs,c))}return a}}function zs(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 Ys(e=process.env,t={totalmemBytes:Tf(),cpuCount:Ef().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/Cf),i=Math.floor(t.cpuCount/2);return Math.max(1,Math.min(Df,r,i))}function Js(e){let t;try{t=Pf(e)}catch{return}for(let n of t)if(Vi(n))try{wf(on(e,n))}catch{}}import{createHash as ii}from"crypto";import{existsSync as ri,writeFileSync as fc}from"fs";import{join as tm}from"path";import{createRequire as Af}from"module";import{dirname as Qr,isAbsolute as Of,relative as Qs,resolve as ve,sep as Jr}from"path";var Ie=Af(import.meta.url),Lf=1,Xs="0.4.0";function Mf(){try{let e=Zs();if(!e.available)return e;let{packageRoot:t}=e,n=Ie.resolve("typescript",{paths:[t]}),r=Ie(n),{FileIndexer:i}=Ie(ve(t,"dist/src/FileIndexer.js")),{Input:o}=Ie(ve(t,"dist/src/Input.js")),{Packages:a}=Ie(ve(t,"dist/src/Packages.js")),s=Ie(ve(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:ei(c)}}catch(e){return{available:!1,reason:`scip-typescript document runtime unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Zr(){let e=Zs();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Zs(){try{let e=Ie.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(U(e,"scip-typescript package manifest"));if(t.version!==Xs)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${Xs}`};let n=Qr(e),r=Ie.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(U(r,"TypeScript package manifest"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:tc(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function ec(e){let t=e.runtime===void 0?Mf():e.runtime===null?{available:!1,reason:"scip-typescript document runtime unavailable"}:{available:!0,runtime:e.runtime,producerIdentity:ei(e.runtime)};return t.available?{available:!0,emitter:new Xr(e,t.runtime)}:t}var Xr=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=ve(t.workspaceRoot),this.tsconfigPath=ve(this.workspaceRoot,t.tsconfigPath),this.projectRoot=t.projectRoot??Nf(this.workspaceRoot,Qr(this.tsconfigPath)),this.maxFileByteSize=t.maxFileByteSize??1024*1024,this.runtime=n,this.producerIdentity=ei(n);let r=Yr(n.typescript,this.tsconfigPath);this.config=r,this.host=new Kr(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(Xe(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=Je(t.modifiedFiles),i=Je(t.removedFiles??[]),o=Je(t.affectedFiles);if(this.fragments.clear(),r.length===0&&i.length===0)return this.validateAffectedPaths(o),this.result(this.emitAffectedFiles(o),n);let a=Yr(this.runtime.typescript,this.tsconfigPath);this.config=a,this.includedFiles=new Set(a.fileNames.map(Xe));let s=this.program,c=new Map;for(let d of[...r,...i]){let u=Ye(this.workspaceRoot,d),l=s.getSourceFile(u);l&&(c.set(d,l),this.stats.symbolEntriesPruned+=Ks(this.symbolTable,l),this.stats.symbolEntriesPruned+=Ks(this.constructorTable,l)),this.host.invalidate(u)}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[d,u]of c)this.program.getSourceFile(Ye(this.workspaceRoot,d))===u?this.stats.sourceNodesReused+=1:this.stats.sourceNodesReplaced+=1;return this.result(this.emitAffectedFiles(o),n)}fragment(t){return this.fragments.get(an(t))??null}snapshotStats(){return{...this.stats}}initializeAndAdvance(t){let n=performance.now();this.initializeProgram();let r=Je(t.modifiedFiles),i=Je(t.removedFiles??[]),o=Je(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??Yr(this.runtime.typescript,this.tsconfigPath);this.includedFiles=new Set(t.fileNames.map(Xe)),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=Ye(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=Ye(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=Ye(this.workspaceRoot,n);if(!this.includedFiles.has(Xe(r)))throw new Error(`affected TypeScript file is outside the configured project: ${n}`)}}emitAffectedFiles(t){return t.map(n=>{let r=this.program.getSourceFile(Ye(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=an(Qs(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:jf(n,r)}}result(t,n){return{producerIdentity:this.producerIdentity,fragments:t,durationMs:performance.now()-n,stats:this.snapshotStats()}}};function jf(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 Kr=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,d)=>{let u=Xe(a);if(this.sourceFiles.has(u))return this.sourceFiles.get(u);let l=o(a,s,c,d);return this.sourceFiles.set(u,l),l}}}invalidate(t){this.sourceFiles.delete(Xe(t))}};function Yr(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,Qr(t)),i=r.errors.filter(o=>o.code!==18003);if(i.length>0)throw new Error(e.formatDiagnostics(i,e.createCompilerHost({})));return r}function ei(e){return tc(e.packageVersion,e.typescript.version)}function tc(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Lf}`}function Nf(e,t){return an(Qs(e,t))||"."}function Ye(e,t){if(Of(t))throw new Error(`expected a project-relative path: ${t}`);let n=ve(e,t),r=e.endsWith(Jr)?e:`${e}${Jr}`;if(n!==e&&!n.startsWith(r))throw new Error(`path escapes the project root: ${t}`);return n}function Je(e){return[...new Set(e.map(an))].sort()}function an(e){return e.split(Jr).join("/").replace(/^\.\//,"")}function Xe(e){return ve(e)}function Ks(e,t){let n=0;for(let r of e.keys())if(Gf(r)){try{if(r.getSourceFile()!==t)continue}catch{continue}e.delete(r),n+=1}return n}function Gf(e){return!!(e&&typeof e=="object"&&"kind"in e&&"getSourceFile"in e)}import{createHash as $f}from"crypto";import{dirname as Bf,join as nc}from"path";var Ke=5;var Vf="typescript-index";function rc(e){let t=nc(e,Vf),n=fo(t);return{...n,requestDir:n.legacyRequestDir}}function ic(e){try{let t=Ti(oe(U(nc(Bf(e),"meta.json"),"reindex metadata")));return t?$f("sha256").update(t).digest("hex"):null}catch{return null}}import{randomUUID as Hf}from"crypto";import{existsSync as ac,rmSync as ti}from"fs";import{join as zf}from"path";import{randomUUID as Uf}from"crypto";import{getHeapStatistics as qf}from"v8";import{resolve as Wf}from"path";var sn=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=Wf(t.projectRoot),this.currentGeneration=t.currentGeneration,this.createEmitter=t.createEmitter??ec,this.wallNow=t.wallNow??t.now??Date.now,this.monotonicNow=t.monotonicNow??t.now??_,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:qf().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:Ke,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 qb=`typescript-index-${process.pid}-${Uf()}`,oc=ee(process.pid),Wb={pid:process.pid,...oc?{processIdentity:oc}:{}};var Yf=12e4,Jf=5,yt=class extends Error{name="TypeScriptIndexMemoryPressureError"},cn=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;emitLocally;requireService;localHost=null;constructor(t,n={}){this.projectRoot=$i(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Zf(),this.runtime=n.runtime??em,this.mailboxLimits=n.mailboxLimits??{},this.emitLocally=n.emitLocally,this.requireService=n.requireService===!0}request(t){let n=ho(this.cacheDir),r=rc(this.cacheDir),i=Un(n.statePath);if(!sc(i,this.projectRoot,this.runtime))return this.requestLocally(t);let o=this.runtime.now(),a=o+this.timeoutMs,s=(this.runtime.monotonicNow??_)()+this.timeoutMs,c=Bn("typescript-index-v5",{baseGeneration:this.baseGeneration,request:t}),d=Vn(c),u=mo(r,{mailboxVersion:$n,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:a,protocolVersion:Ke,id:d,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??_)()<=s;){if(ac(u.responsePath))try{return cc(L(u.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),d,c,this.baseGeneration,t.producerIdentity,t.affectedFiles)}finally{ti(u.responsePath,{force:!0})}let l=Un(n.statePath);if(!sc(l,this.projectRoot,this.runtime))return this.abandonPendingRequest(r,d),this.requestLocally(t);this.runtime.sleep(Jf)}if(ac(u.responsePath))try{return cc(L(u.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),d,c,this.baseGeneration,t.producerIdentity,t.affectedFiles)}finally{ti(u.responsePath,{force:!0})}return this.abandonPendingRequest(r,d),this.requestLocally(t)}abandonPendingRequest(t,n){try{ti(zf(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?ni(this.emitLocally(t),t.producerIdentity,t.affectedFiles):(this.localHost??=new sn({projectRoot:this.projectRoot,currentGeneration:()=>this.baseGeneration}),ni(dc(this.localHost.handle(this.baseGeneration,t),t.producerIdentity),t.producerIdentity,t.affectedFiles))}};function sc(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===Ke&&n.isProcessAlive(e.pid)&&Number.isFinite(i)&&n.now()-i<=go&&(!e.processIdentity||r!=null&&et(e.processIdentity,r))}function cc(e,t,n,r,i,o){let a=JSON.parse(e);if(a.protocolVersion!==Ke||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 Xf(s)?new yt(s):new Error(s)}return ni(dc(a.response,i),i,o)}function Xf(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 ni(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 dc(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(Kf)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:Qf(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 Kf(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 Qf(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Zf(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Yf}var em={now:Date.now,monotonicNow:_,randomId:Hf,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:fe,readProcessIdentity:ee};var nm=128,rm=256;function im(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."],n=$e(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=je(e.previousSnapshot,e.currentSnapshot);if(r.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};let i=r.changes.filter(h=>h.inputKind==="source"&&qe(h.path)),o=mc(r,n),a={...r,changes:o},s=i.filter(h=>h.kind==="added").map(h=>h.path),c=i.filter(h=>h.kind==="deleted").map(h=>h.path),d=i.filter(h=>h.kind==="modified"),u=un(e.currentSnapshot,e.producerIdentity,n),l=un(e.previousSnapshot,e.producerIdentity,n),p=gc(r,o,u,l),m=!p&&yc(r);if(i.length===0&&!p)return{eligible:!1,reason:"change does not affect the configured TypeScript project"};let g=e.currentSnapshot.files.filter(h=>Me(h.path,e.currentSnapshot.languages)==="source"&&qe(h.path)).map(h=>h.path).sort(),y=new Set(g),v=p?e.projectFiles.filter(h=>!y.has(h)).sort():[...c].sort(),A=p?a:{...r,changes:i},T=p?{eligible:!0,plan:{...ot(a,e.graph,[...new Set([...g,...v])]),mode:"full-project"}}:am(d,s,v,e.graph,e.projectFiles);if(!T.eligible)return T;let M=T.plan,C=new Set(v),S=sm(M,t,e.graph,C);if(!S)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let b=S.length===1?S[0]:void 0;return{eligible:!0,manifest:A,plan:M,projectIdentity:u,previousFragmentGeneration:pc(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:pc(e.currentSnapshot,e.producerIdentity),projects:S,deletedFiles:v,replaceProject:p,dependencyGraphUnchanged:m,...b?{tsconfigPath:b.tsconfigPath,projectArgument:b.projectArgument}:{}}}function mc(e,t){return e.changes.filter(n=>n.inputKind==="source"&&qe(n.path)||n.inputKind==="config"&&(!Be(n.path)||t.has(n.path))&&om(n)||n.inputKind==="ambient")}function om(e){return e.kind!=="modified"||e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function gc(e,t,n,r){return n!==r||e.projectIdentityChanged||e.uncertainty.length>0||t.length>rm||t.some(i=>i.inputKind==="config"||i.inputKind==="ambient")}function am(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,...uc(n,r,i)])].sort(),reasons:[]}};let o=ot({version:1,changes:e.filter(hc),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,...uc(n,r,i)])].sort(),reasons:[]}}}function hc(e){return e.kind!=="modified"?!0:e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function yc(e){let t=e.changes.filter(n=>n.inputKind==="source"&&qe(n.path));return t.length>0&&t.every(n=>n.kind==="modified"&&!hc(n))}function sm(e,t,n,r){let i=new Map;for(let a of e.affectedFiles){let s=cm(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],[d])=>c.localeCompare(d))){let c=new Set(s),d=e.changedFiles.filter(p=>!r.has(p)&&(c.has(p)||s.some(m=>lc(m,p,n)))),u=e.changedFiles.filter(p=>r.has(p)&&(c.has(p)||s.some(m=>lc(m,p,n)))),l=s.filter(p=>!r.has(p));if(d.length===0&&u.length===0&&l.length===0)return null;o.push({projectArgument:a,tsconfigPath:a==="."?"tsconfig.json":`${a}/tsconfig.json`,modifiedFiles:d,removedFiles:u,affectedFiles:[...l].sort()})}return o}function uc(e,t,n){let r=new Set(n),i=new Map;for(let[s,c]of t)if(r.has(s))for(let d of c){let u=i.get(d)??new Set;u.add(s),i.set(d,u)}let o=new Set(e),a=[...e];for(let s=0;s<a.length;s+=1){let c=a[s];if(c)for(let d of i.get(c)??[])o.has(d)||(o.add(d),a.push(d))}return[...o].sort()}function cm(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)=>dn(a)-dn(o)||o.localeCompare(a)),i=r[0];return r[1]&&dn(r[1])===dn(i)?null:i}function dn(e){return e==="."?0:e.split("/").filter(Boolean).length}function lc(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 Sc(e){let t=_();try{if(!ri(e.previousDbPath)||!ri(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=Zr();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new Z({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a=um(e.projectRoot,e.previousSnapshot,e.currentSnapshot),s=e.projectMode==="workspace"?Ee(e.projectRoot,e.currentSnapshot.typescriptProjects):["."],c=$e(s),d,u,l;try{d=Ot(o,{includeIgnored:!1}).filter(qe).sort();let k=a?je(a,e.currentSnapshot):null,f=k&&a&&gc(k,mc(k,c),un(e.currentSnapshot,r.producerIdentity,c),un(a,r.producerIdentity,c)),I=k!==null&&!f&&yc(k);f?(l=ao(o,"none")??void 0,u=new Map):I?u=new Map:(l=Lt(o),u=l.graph)}finally{o.close()}let p=performance.now()-n,m=im({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?s:void 0,previousSnapshot:a,currentSnapshot:e.currentSnapshot,projectFiles:d,graph:u,producerIdentity:r.producerIdentity,rootTsconfigExists:ri(tm(e.projectRoot,"tsconfig.json"))});if(!m.eligible)throw new Error(m.reason);let g=ic(e.previousDbPath);if(!g)throw new Error("published TypeScript base generation unavailable");n=performance.now();let y=new cn({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:g},{requireService:!0}),v=m.projects.flatMap(k=>{let f=dm(k.affectedFiles,nm);return(f.length>0?f:[[]]).map(($,le)=>({project:k,affectedFiles:$,removedFiles:le===0?k.removedFiles:[],firstForProject:le===0}))}),A=[],T=new Map,M=[],C=!1,S=0,b=0,h=0,F=m.previousFragmentGeneration;for(let[k,f]of v.entries()){let I=y.request({kind:"emit-documents",tsconfigPath:f.project.tsconfigPath,projectArgument:f.project.projectArgument,projectIdentity:m.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:f.firstForProject?f.project.modifiedFiles:[],removedFiles:f.firstForProject?f.project.removedFiles:[],affectedFiles:f.affectedFiles});C||=I.cold,M.push(I.durationMs);let $=f.removedFiles.map(xt=>({relativePath:xt,bytes:null,occurrences:0,symbols:0,referenceFragments:[]})),le=[...I.fragments,...$];if(!m.replaceProject)for(let xt of le)T.set(xt.relativePath,xt.referenceFragments);let In=performance.now(),Md=Za(I.fragments);S+=performance.now()-In;let Pi=k===0?e.candidateAffectedScipPath:`${e.candidateAffectedScipPath}.batch-${k}.scip`,jd=performance.now();fc(Pi,Md),h+=performance.now()-jd;let Nd=performance.now(),wi=k===v.length-1?m.nextFragmentGeneration:lm({previousGenerationIdentity:F,targetGenerationIdentity:m.nextFragmentGeneration,fragments:le});os({cacheDir:e.cacheDir,previousGenerationIdentity:F,nextGenerationIdentity:wi,producerIdentity:r.producerIdentity,projectIdentity:m.projectIdentity,baseShardCurrent:k===0?e.baseShardCurrent:!1,fragments:le,allowProjectIdentityChange:m.replaceProject&&k===0,allowLegacyProjectIdentityMigration:!0}),b+=performance.now()-Nd,F=wi,A.push({scipPath:Pi,affectedFiles:[...f.affectedFiles,...f.removedFiles].sort(),deletedFiles:[...f.removedFiles].sort()})}let x=performance.now()-n,P={scipPath:e.previousShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,affectedBatches:A,completeScipUpdated:!1,durationMs:_()-t,cold:C,changedFiles:m.plan.changedFiles,affectedFiles:m.plan.affectedFiles,deletedFiles:m.deletedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:m.previousFragmentGeneration,nextFragmentGeneration:m.nextFragmentGeneration,manifest:m.manifest,plan:m.plan,projectFileCount:d.length,dependencyGraphSnapshot:l,dependencyGraphUnchanged:m.dependencyGraphUnchanged,referenceFragmentsByFile:T,timings:{runtimeMs:i,graphMs:p,requestMs:x,serviceMs:M.reduce((k,f)=>k+f,0),assemblyMs:S,fragmentStoreMs:b,writeMs:h}};return e.onStatus(`${m.replaceProject?"Bounded TypeScript project refresh":"Incremental TypeScript index"} emitted ${P.affectedFiles.length-P.deletedFiles.length} document(s), removed ${P.deletedFiles.length}, and produced ${A.length} bounded batch(es) across ${m.projects.length} project(s) in ${(P.durationMs/1e3).toFixed(3)}s (${P.cold?"cold":"warm"} service; whole SCIP deferred; runtime ${i.toFixed(0)}ms, graph ${p.toFixed(0)}ms, request ${x.toFixed(0)}ms, assembly ${S.toFixed(0)}ms, fragments ${b.toFixed(0)}ms, write ${h.toFixed(0)}ms).`),P}catch(n){let r=n instanceof Error?n.message:String(n);if(e.onUnavailable?.(r),n instanceof yt)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 dm(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function um(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=At(e,a.path,a.hash);return c===void 0?a:(i=!0,{...a,semanticHash:c})});return i?{...t,files:o}:t}function lm(e){let t=ii("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(ii("sha256").update(n.bytes).digest()));return t.digest("hex")}function oi(e){let t=Zr();if(!t.available)throw new Error(t.reason);let n=as({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:j(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:G}),packageVersion:t.packageVersion});fc(e.candidateShardPath,n)}function un(e,t,n){let r=e.files.filter(i=>{let o=Me(i.path,e.languages);return o==="ambient"||o==="config"&&(!Be(i.path)||n.has(i.path))}).map(i=>{let a=Me(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:${bc(JSON.stringify({version:3,producerIdentity:t,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),nonSourceInputs:r}))}`}function pc(e,t){return bc(JSON.stringify({version:1,producerIdentity:t,snapshot:It(e)}))}function bc(e){return ii("sha256").update(e).digest("hex")}import{closeSync as pm,existsSync as ln,fstatSync as fm,lstatSync as mm,openSync as gm,renameSync as ci,rmSync as St,statSync as hm,writeSync as ym}from"fs";import{cpus as Sm}from"os";import{join as di}from"path";var ai=Symbol("no-error");async function Rc(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=ai,c=!0,d=Array.from({length:o},async()=>{for(;c&&a<e.length;){let u=a++;try{r[u]=await n(e[u])}catch(l){s===ai&&(s=l),c=!1}}});if(await Promise.all(d),s!==ai)throw s;return r}var xc=8*1024;function Ic(e,t,n){let r=Buffer.from(t,"utf8"),i=()=>gm(e,"wx",384),o;try{o=i()}catch(a){if(a.code!=="EEXIST")throw a;if(n==="skip")return null;St(e,{force:!0}),o=i()}try{ym(o,r);let a=fm(o);return{path:e,content:r,device:a.dev,inode:a.ino}}finally{pm(o)}}function bm(e,t){let n=[];try{if(e.temporaryRootConfigContent!==void 0){let r=Ic(di(t,"tsconfig.json"),e.temporaryRootConfigContent,"skip");r&&n.push(r)}for(let r of e.temporaryProjectConfigs??[]){let i=Ic(r.path,r.content,"replace");i&&n.push(i)}return n}catch(r){for(let i of n.reverse())wc(i);throw r}}function wc(e){if(e)try{let t=mm(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;St(e.path)}catch(t){if(t.code!=="ENOENT")throw t}}function Rm(e,t,n){if(!e.defaultOutputPath)return;let r=di(t,e.defaultOutputPath);n!==r&&ln(r)&&ci(r,n)}function xm(e,t,n){if(!e.defaultOutputPath)return null;let r=di(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return St(i,{force:!0}),ln(r)?(ci(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Im(e){e&&(St(e.defaultOutputPath,{force:!0}),e.backupPath&&ln(e.backupPath)&&ci(e.backupPath,e.defaultOutputPath))}function vm(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,Sm().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Ec(e,t,n,r,i){z(i,"Reindex cancelled by its owner.");let o=e.filter(d=>d.config.defaultOutputPath),a=e.filter(d=>!d.config.defaultOutputPath&&d.boundedConcurrency!==void 0),s=e.filter(d=>!d.config.defaultOutputPath&&d.boundedConcurrency===void 0),c=[];if(c.push(...await vc(s,vm(s.length,r),t,n,i)),a.length>0){let d=Math.max(1,Math.min(...a.map(u=>u.boundedConcurrency)));c.push(...await vc(a,d,t,n,i))}for(let d of o)z(i,"Reindex cancelled by its owner."),c.push((await si(d,t,n,i)).result);return c.sort((d,u)=>e.findIndex(l=>l.id===d.id)-e.findIndex(l=>l.id===u.id))}async function vc(e,t,n,r,i){let o=await Rc(e,Math.max(1,t),s=>si(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(d=>d.id===s.result.id);c&&(r(`Retrying ${c.label} indexer serially after parallel failure...`),z(i,"Reindex cancelled by its owner."),a.set(c.id,(await si(c,n,r,i)).result))}return o.map(({result:s})=>a.get(s.id)??s)}async function si(e,t,n,r){z(r,"Reindex cancelled by its owner."),n(`Indexing ${e.label} with ${e.resolvedBinary}...`),St(e.scipPath,{force:!0});let i=xm(e.config,t,e.scipPath),o=[],a=[e.binary,...e.args].join(" "),s=_();try{o=bm(e,t),e.trustedProjectTool&&po(t,e.trustedProjectTool);let d=uo(e.binary,e.args),u=await Mt({command:d.binary,args:d.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:Pm(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,signal:r});if(u.status!==0){let l=u.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${u.status}${l?`:
292
- ${l}`:""}`)}Rm(e.config,t,e.scipPath)}catch(d){if(r?.aborted)throw Fi(r,"Reindex cancelled by its owner.");let u=d instanceof Error?d.message:String(d),l=u.length<=xc?u:`${u.slice(0,xc)}
293
- [indexer failure detail truncated]`,p=`${e.resolvedBinary} indexer failed: ${l}`,m=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:_()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:m}},retryable:wm(d)}}finally{Im(i);for(let d of o.reverse())wc(d)}if(!ln(e.scipPath)){let d=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,u=e.label===e.language?d:`${e.label}: ${d}`;return n(`Skipping ${e.label}: ${d}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:_()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:u}},retryable:!1}}let c;try{c=hm(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:_()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},outputBytes:c},retryable:!1}}function Pm(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):bo.indexer}function wm(e){return e instanceof Ro?e.kind==="spawn"&&Pc(e.cause):Pc(e)}function Pc(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}import{execFileSync as kc}from"child_process";import{homedir as Tc,platform as Em}from"os";import{delimiter as Tm,join as pn}from"path";function li(e,t){let n=e.installMethods,r=it(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(!Mn(i.prerequisite))continue;let o=km(i);t(`Installing immutable ${i.identity} via ${i.label} into ${o}; expected executable: ${r}.`);try{kc(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:Em()==="win32"});let a=Ue(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 km(e){if(e.binary==="npm")return ui("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=ui("go",["env","GOBIN"]);if(t)return t;let n=ui("go",["env","GOPATH"]);if(n)return pn(n.split(Tm)[0],"bin")}return e.binary==="dotnet"?pn(process.env.DOTNET_CLI_HOME??Tc(),".dotnet","tools"):e.binary==="dart"?pn(process.env.PUB_CACHE??pn(Tc(),".pub-cache"),"bin"):e.destination}function ui(e,t){try{return kc(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}import Kc from"better-sqlite3";import{existsSync as Qc}from"fs";import{dirname as Zc,join as ed,resolve as td}from"path";import{randomUUID as Dm}from"crypto";import{mkdtempSync as _m,rmSync as Fm,statSync as Dc}from"fs";import{tmpdir as Am}from"os";import{join as _c}from"path";import{Worker as Om}from"worker_threads";function Cm(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function Qe(){return{skippedReferences:0,skippedReferenceReasons:Cm(),skippedReferenceSamples:[]}}function fn(e,t){e.skippedReferences+=t.skippedReferences;for(let n of Object.keys(e.skippedReferenceReasons)){e.skippedReferenceReasons[n]+=t.skippedReferenceReasons[n];for(let r of t.skippedReferenceSamples.filter(i=>i.reason===n))e.skippedReferenceSamples.filter(o=>o.reason===n&&o.sourceFile===r.sourceFile).length<2&&e.skippedReferenceSamples.push(r)}}var Lm=3e5,Fc=64*1024*1024,Mm={createResultDirectory:()=>_m(_c(Am(),"scip-query-vue-workers-")),spawn:(e,t)=>new Om(e,{workerData:t}),resultSize:e=>Dc(e).size,readResult:e=>L(e,{maxBytes:Fc,inputKind:"Vue worker result"}),removeResultDirectory:e=>Fm(e,{recursive:!0,force:!0})};function Ac(e){return e.length>=8&&Lc(e.length)>1}async function Oc(e,t=Mm){let n=Lc(e.vueFiles.length),r=Jm(e.vueFiles),i=Km(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),a=e.timeoutMs??zm(),s=e.maxResultBytes??Ym();Cc("timeoutMs",a),Cc("maxResultBytes",s);let c=Dm(),d=t.createResultDirectory(),u=[],l,p,m;try{for(let y=0;y<i.length;y++){let v=y,A=i[y]??[],T=A.map(S=>S.taskId),M=_c(d,`${v}.json`),C=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:A,resultPath:M,runId:c,workerId:v,taskIds:T});u.push({workerId:v,taskIds:T,resultPath:M,handle:C,completion:jm(C,v)})}await Nm(u,a);let g=u.sort((y,v)=>y.workerId-v.workerId).map(y=>$m(y,c,s,t));m={occurrences:g.flatMap(y=>y.occurrences),...Qe()};for(let y of g)fn(m,y)}catch(g){l=g}finally{let g=await Gm(u);if(g.length===0)try{t.removeResultDirectory(d)}catch(y){g.push(y)}if(g.length>0){let y=l===void 0?g:[l,...g];p=new AggregateError(y,`Vue worker cleanup failed: ${Hm(y[0])}`)}}if(p)throw p;if(l!==void 0)throw l;if(!m)throw new Error("Vue workers completed without producing a merged result.");return m}function jm(e,t){return new Promise((n,r)=>{let i=!1,o=c=>{i||(i=!0,e.off("error",a),e.off("exit",s),c?r(c):n())},a=c=>{o(new Error(`Vue reference worker ${t} failed: ${c.message}`,{cause:c}))},s=c=>{o(c===0?void 0:new Error(`Vue reference worker ${t} exited with code ${c}`))};e.once("error",a),e.once("exit",s)})}async function Nm(e,t){let n;try{await Promise.race([Promise.all(e.map(r=>r.completion)),new Promise((r,i)=>{n=setTimeout(()=>i(new Error(`Vue reference workers timed out after ${(t/1e3).toFixed(3)}s`)),t),n.unref()})])}finally{n&&clearTimeout(n)}}async function Gm(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function $m(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(!bt(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(!Wm(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||!Bm(o.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return o.result}function Bm(e){if(!bt(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(Vm)||!de(e.skippedReferences)||!bt(e.skippedReferenceReasons))return!1;for(let t of["missing-source-file","missing-service-script","no-definition","same-file-definition","unindexed-definition"])if(!de(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(Um)}function Vm(e){return bt(e)&&typeof e.sourceFile=="string"&&de(e.sourceLine)&&de(e.sourceStartChar)&&de(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&de(e.symbolId)}function Um(e){return bt(e)&&typeof e.sourceFile=="string"&&de(e.sourceLine)&&de(e.sourceStartChar)&&de(e.sourceEndChar)&&typeof e.token=="string"&&qm(e.reason)}function qm(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function de(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function bt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wm(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function Cc(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function Hm(e){return e instanceof Error?e.message:String(e)}function Lc(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:1;return Math.max(1,Math.min(e,n))}function zm(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:Lm}function Ym(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:Fc}function Jm(e){let t=Xm(),n=[];for(let r of e){let i=Mc(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 Xm(){return Number.POSITIVE_INFINITY}function Km(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Qm(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 Qm(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Mc(e.fileName)-e.startOffset)}function Mc(e){try{return Dc(e).size}catch{return 1}}import{createRequire as Zm}from"module";import{existsSync as eg}from"fs";import{dirname as jc,extname as tg,join as Nc,relative as ng,resolve as rg}from"path";import{pathToFileURL as ig}from"url";function og(e){e.transaction(()=>{e.prepare(`
289
+ )`],Wc=["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 an(e){return e.startsWith("local ")}function Hi(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 zi(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 qc(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 Hc(e,t,n,r){let i=[],o=[],a="",s=0;for(let u of re(e,n,r))u.fieldNumber===Yi?u.wireType===2?Hi(e,u.valueStart,u.valueEnd,i):u.wireType===0&&i.push(u.varint):u.fieldNumber===Xi&&u.wireType===2?a=xe.decode(e.subarray(u.valueStart,u.valueEnd)):u.fieldNumber===Ki&&u.wireType===0?s=u.varint:u.fieldNumber===Lc&&(u.wireType===2?Hi(e,u.valueStart,u.valueEnd,o):u.wireType===0&&o.push(u.varint));let c=zi(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:zi(o)}:null}function zc(e,t,n){let r={symbol:"",displayName:null,kind:null,documentation:[],enclosingSymbol:null};for(let i of re(e,t,n))if(i.wireType===2){let o=()=>xe.decode(e.subarray(i.valueStart,i.valueEnd));i.fieldNumber===jc?r.symbol=o():i.fieldNumber===Nc?r.documentation.push(o()):i.fieldNumber===Vc?r.displayName=o():i.fieldNumber===Bc&&(r.enclosingSymbol=o())}else i.fieldNumber===$c&&i.wireType===0&&(r.kind=i.varint);return r}var xe=new TextDecoder;function Jc(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 Yc(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=>ie(a)));n.push(Je(Yi),ie(r.length),r);let i=Buffer.from(e.symbol,"utf8");n.push(Je(Xi),ie(i.length),i),e.roles!==0&&n.push(ie(Ki*8),ie(e.roles));let o=Buffer.concat(n);return Buffer.concat([Je(sn),ie(o.length),o])}function Xc(e,t){let n=[];for(let r of t)r.merged?n.push(Yc(r)):n.push(e.subarray(r.frameStart,r.frameEnd));return _c(Buffer.concat(n))}async function Qi(e,t,n={}){let r=n.chunkSize??Fc,i={documents:0,duplicateDocumentsSkipped:0,occurrences:0,illegalOccurrencesDropped:0,mergedOccurrences:0,chunks:0,mentions:0,globalSymbols:0,enclosingRanges:0},o=new kc(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 Gc)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,m=new Map,f=1,y=1,b=1,k=(E,C,w,h,S)=>{let g=b;return b+=1,m.set(E,g),u.run(g,E,C,w,h,S),i.globalSymbols+=1,g};o.exec("BEGIN IMMEDIATE");let O=!1;try{let E=0;for(let w of re(e)){if(w.fieldNumber!==sn||w.wireType!==2)continue;Ji(n.signal),E+=1,E>=qi&&(E=0,await Gi());let h="",S=null,g=null,_=null,R=[];for(let p of re(e,w.valueStart,w.valueEnd))p.wireType===2?p.fieldNumber===Wi?h=xe.decode(e.subarray(p.valueStart,p.valueEnd)):p.fieldNumber===Oc?R.push(zc(e,p.valueStart,p.valueEnd)):p.fieldNumber===Dc?S=xe.decode(e.subarray(p.valueStart,p.valueEnd)):p.fieldNumber===Ac&&(g=xe.decode(e.subarray(p.valueStart,p.valueEnd))):p.fieldNumber===Mc&&p.wireType===0&&(_=Kc(p.varint));if(h==="")throw new Q("relative path must not be empty");if(d.has(h)){i.duplicateDocumentsSkipped+=1;continue}let P=f;f+=1,a.run(P,S===""?null:S,h,_,g===""?null:g),d.set(h,P),i.documents+=1;let T=new Map;for(let p of R){if(p.symbol==="")throw new Q(`empty symbol in SymbolInformation for document ${h}`);let x=T.get(p.symbol);if(!x){T.set(p.symbol,p);continue}for(let A of p.documentation)x.documentation.includes(A)||x.documentation.push(A)}for(let p of[...T.values()].sort((x,A)=>x.symbol<A.symbol?-1:x.symbol>A.symbol?1:0))an(p.symbol)||m.has(p.symbol)||k(p.symbol,p.displayName===""?null:p.displayName,p.kind===0?null:p.kind,p.documentation.length===0?null:p.documentation.join(`
290
+ `),p.enclosingSymbol===""?null:p.enclosingSymbol)}let C=new Set;E=0;for(let w of re(e)){if(w.fieldNumber!==sn||w.wireType!==2)continue;Ji(n.signal),E+=1,E>=qi&&(E=0,await Gi());let h="",S=[];for(let R of re(e,w.valueStart,w.valueEnd))if(R.wireType===2){if(R.fieldNumber===Wi)h=xe.decode(e.subarray(R.valueStart,R.valueEnd));else if(R.fieldNumber===Cc){let P=Hc(e,R.fieldStart,R.valueStart,R.valueEnd);P?S.push(P):i.illegalOccurrencesDropped+=1}}if(C.has(h))continue;C.add(h);let g=d.get(h);if(g===void 0)continue;S.sort(qc);let _=[];for(let R of S){let P=_[_.length-1];if(P&&P.startLine===R.startLine&&P.startChar===R.startChar&&P.endLine===R.endLine&&P.endChar===R.endChar&&P.symbol===R.symbol){P.roles|=R.roles,P.merged=!0,i.mergedOccurrences+=1;continue}_.push(R)}i.occurrences+=_.length;for(let R of _){if((R.roles&Uc)===0||an(R.symbol)||!R.enclosing)continue;let[P,T,p,x]=R.enclosing;if(P<0||T<0||p<P||p===P&&x<T)throw new Q(`bad enclosing range for symbol ${R.symbol} in ${h}`);let A=m.get(R.symbol);if(A===void 0)throw new Q(`symbol ${R.symbol} has definition occurrence, but no SymbolInformation`);c.run(g,A,P,T,p,x),i.enclosingRanges+=1}for(let[R,P]of Jc(_,r).entries()){let T=y;y+=1,s.run(T,g,R,P[0].startLine,P[P.length-1].startLine,Xc(e,P)),i.chunks+=1;let p=new Map;for(let x of P){if(an(x.symbol))continue;let A=p.get(x.symbol);A||p.set(x.symbol,A=new Set),A.add(x.roles),m.has(x.symbol)||k(x.symbol,null,null,null,null)}for(let[x,A]of p){let H=m.get(x);for(let vt of A)l.run(T,H,vt),i.mentions+=1}}}o.exec("COMMIT"),O=!0}finally{if(!O)try{o.exec("ROLLBACK")}catch{}}o.exec("BEGIN IMMEDIATE");for(let E of Wc)o.exec(E);o.exec("COMMIT"),o.pragma("wal_checkpoint(TRUNCATE)")}finally{o.close()}return i}function Kc(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 Q(`unknown position encoding ${e}`)}function Ji(e){if(e?.aborted)throw new Q("SCIP SQLite conversion aborted")}import{readdirSync as Qc,rmSync as Zc}from"fs";import{cpus as eu,totalmem as tu}from"os";import{join as at}from"path";var nu=2048,ru=6*1024**3,iu=4;function cn(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_FILES??"",10);return Number.isSafeInteger(t)&&t>0?t:nu}function eo(e,t){return e>Math.floor(t*1.5)}var ou=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*ou),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 au(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 no(e){let t=e.targetFiles??cn(),n=e.shardCount??Math.max(1,Math.ceil(new Set(e.inputPaths).size/Math.max(1,t)));return au(e.inputPaths,n,e.weightOf).map((r,i)=>{let o=at(e.projectRoot,Zn(i)),a=`${JSON.stringify({extends:`./${e.rootConfigPath}`,compilerOptions:{incremental:!1},files:r.map(s=>`./${s}`),include:[],exclude:[]},null,2)}
291
+ `;return{configPath:o,content:a,inputPaths:r}})}var ro="typescript-shard-costs.json",Zi=4;function io(e){let t;try{t=JSON.parse(Hn(at(e,ro),"shard cost model"))}catch{return null}if(typeof t!="object"||t===null||t.version!==1)return null;let n=t.samples;return Array.isArray(n)&&n.every(i=>typeof i=="object"&&i!==null&&typeof i.firstPath=="string"&&typeof i.lastPath=="string"&&Number.isFinite(i.totalBytes)&&i.totalBytes>0&&Number.isFinite(i.durationMs)&&i.durationMs>0)?{version:1,samples:n}:null}function oo(e,t){$e(at(e,ro),t)}function ao(e){let t=(e?.samples??[]).filter(o=>o.totalBytes>0&&o.durationMs>0);if(t.length<2)return(o,a)=>a;let n=t.map(o=>o.durationMs/o.totalBytes).sort((o,a)=>o-a),r=n[Math.floor(n.length/2)];if(!(r>0))return(o,a)=>a;let i=[...t].sort((o,a)=>o.firstPath.localeCompare(a.firstPath));return(o,a)=>{for(let s of i){if(o.localeCompare(s.firstPath)<0)break;if(o.localeCompare(s.lastPath)>0)continue;let c=s.durationMs/s.totalBytes/r;return a*Math.min(Zi,Math.max(1/Zi,c))}return a}}function so(e,t){let n=[];for(let r of e){let i=r.inputPaths[0],o=r.inputPaths[r.inputPaths.length-1];if(i===void 0||o===void 0||!(r.durationMs>0))return null;let a=r.inputPaths.reduce((s,c)=>s+Math.max(1,t(c)),0);n.push({firstPath:i,lastPath:o,totalBytes:a,durationMs:r.durationMs})}return n.length>0?{version:1,samples:n}:null}function co(e=process.env,t={totalmemBytes:tu(),cpuCount:eu().length}){let n=Number.parseInt(e.SCIP_QUERY_TS_COMPILER_SHARD_CONCURRENCY??"",10);if(Number.isSafeInteger(n)&&n>0)return n;let r=Math.floor(t.totalmemBytes/2/ru),i=Math.floor(t.cpuCount/2);return Math.max(1,Math.min(iu,r,i))}function uo(e){let t;try{t=Qc(e)}catch{return}for(let n of t)if(er(n))try{Zc(at(e,n))}catch{}}import{createHash as bn}from"crypto";import{existsSync as Sn,writeFileSync as ko}from"fs";import{join as _u}from"path";import{createRequire as su}from"module";import{dirname as mn,isAbsolute as cu,relative as mo,resolve as ee,sep as ln}from"path";var Z=su(import.meta.url),uu=1,lo="0.4.0";function lu(){try{let e=fo();if(!e.available)return e;let{packageRoot:t}=e,n=Z.resolve("typescript",{paths:[t]}),r=Z(n),{FileIndexer:i}=Z(ee(t,"dist/src/FileIndexer.js")),{Input:o}=Z(ee(t,"dist/src/Input.js")),{Packages:a}=Z(ee(t,"dist/src/Packages.js")),s=Z(ee(t,"dist/src/scip.js"));if(!i||!o||!a||!s.scip?.Document||!s.scip.Index)return{available:!1,reason:"scip-typescript document runtime has an unsupported module shape"};let c={packageVersion:e.packageVersion,typescript:r,Document:s.scip.Document,Index:s.scip.Index,FileIndexer:i,Input:o,Packages:a};return{available:!0,runtime:c,producerIdentity:gn(c)}}catch(e){return{available:!1,reason:`scip-typescript document runtime unavailable: ${e instanceof Error?e.message:String(e)}`}}}function fn(){let e=fo();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function fo(){try{let e=Z.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(U(e,"scip-typescript package manifest"));if(t.version!==lo)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${lo}`};let n=mn(e),r=Z.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(U(r,"TypeScript package manifest"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:ho(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function go(e){let t=e.runtime===void 0?lu():e.runtime===null?{available:!1,reason:"scip-typescript document runtime unavailable"}:{available:!0,runtime:e.runtime,producerIdentity:gn(e.runtime)};return t.available?{available:!0,emitter:new dn(e,t.runtime)}:t}var dn=class{producerIdentity;workspaceRoot;tsconfigPath;projectRoot;maxFileByteSize;runtime;host;config=null;includedFiles=new Set;program=null;checker=null;symbolTable=new Map;constructorTable=new Map;packages;fragments=new Map;stats={initializations:0,programUpdates:0,documentsEmitted:0,documentsRemoved:0,sourceNodesReused:0,sourceNodesReplaced:0,symbolEntriesPruned:0};constructor(t,n){this.workspaceRoot=ee(t.workspaceRoot),this.tsconfigPath=ee(this.workspaceRoot,t.tsconfigPath),this.projectRoot=t.projectRoot??pu(this.workspaceRoot,mn(this.tsconfigPath)),this.maxFileByteSize=t.maxFileByteSize??1024*1024,this.runtime=n,this.producerIdentity=gn(n);let r=un(n.typescript,this.tsconfigPath);this.config=r,this.host=new pn(n.typescript,r.options,this.workspaceRoot),this.packages=new n.Packages(this.projectRoot)}initialize(){let t=performance.now();this.initializeProgram();let n=[];for(let r of this.program.getSourceFiles())this.includedFiles.has(Ie(r.fileName))&&n.push(this.emitSourceFile(r));return this.result(n,t)}advance(t){if(!this.program||!this.checker||!this.config)return this.initializeAndAdvance(t);let n=performance.now(),r=ve(t.modifiedFiles),i=ve(t.removedFiles??[]),o=ve(t.affectedFiles);if(this.fragments.clear(),r.length===0&&i.length===0)return this.validateAffectedPaths(o),this.result(this.emitAffectedFiles(o),n);let a=un(this.runtime.typescript,this.tsconfigPath);this.config=a,this.includedFiles=new Set(a.fileNames.map(Ie));let s=this.program,c=new Map;for(let u of[...r,...i]){let l=Pe(this.workspaceRoot,u),d=s.getSourceFile(l);d&&(c.set(u,d),this.stats.symbolEntriesPruned+=po(this.symbolTable,d),this.stats.symbolEntriesPruned+=po(this.constructorTable,d)),this.host.invalidate(l)}this.program=this.runtime.typescript.createProgram(a.fileNames,a.options,this.host.compilerHost,s),this.checker=this.program.getTypeChecker(),this.stats.programUpdates+=1,this.validateIncrementalPaths(r,i,o),this.stats.documentsRemoved+=i.length;for(let[u,l]of c)this.program.getSourceFile(Pe(this.workspaceRoot,u))===l?this.stats.sourceNodesReused+=1:this.stats.sourceNodesReplaced+=1;return this.result(this.emitAffectedFiles(o),n)}fragment(t){return this.fragments.get(st(t))??null}snapshotStats(){return{...this.stats}}initializeAndAdvance(t){let n=performance.now();this.initializeProgram();let r=ve(t.modifiedFiles),i=ve(t.removedFiles??[]),o=ve(t.affectedFiles);return this.fragments.clear(),this.validateIncrementalPaths(r,i,o,!0),this.stats.documentsRemoved+=i.length,this.result(this.emitAffectedFiles(o),n)}initializeProgram(){let t=this.config??un(this.runtime.typescript,this.tsconfigPath);this.includedFiles=new Set(t.fileNames.map(Ie)),this.program=this.runtime.typescript.createProgram(t.fileNames,t.options,this.host.compilerHost),this.checker=this.program.getTypeChecker(),this.stats.initializations+=1}validateIncrementalPaths(t,n,r,i=!1){if(!i&&t.length===0&&n.length===0)throw new Error("incremental TypeScript document update requires a modified or removed file");if(r.length===0&&n.length===0)throw new Error("incremental TypeScript document update requires an affected or removed file");for(let o of t){let a=Pe(this.workspaceRoot,o);if(!this.program?.getSourceFile(a))throw new Error(`modified TypeScript dependency is unavailable to the configured project: ${o}`)}for(let o of n){let a=Pe(this.workspaceRoot,o);if(this.program?.getSourceFile(a))throw new Error(`removed TypeScript source is still present in the configured project: ${o}`)}this.validateAffectedPaths(r)}validateAffectedPaths(t){for(let n of t){let r=Pe(this.workspaceRoot,n);if(!this.includedFiles.has(Ie(r)))throw new Error(`affected TypeScript file is outside the configured project: ${n}`)}}emitAffectedFiles(t){return t.map(n=>{let r=this.program.getSourceFile(Pe(this.workspaceRoot,n));if(!r)throw new Error(`affected TypeScript source is unavailable: ${n}`);return this.emitSourceFile(r)})}emitSourceFile(t){if(!this.checker)throw new Error("TypeScript document emitter is not initialized");let n=st(mo(this.workspaceRoot,t.fileName)),r=new this.runtime.Document({relative_path:n,occurrences:[]});if(new this.runtime.FileIndexer(this.checker,{cwd:this.workspaceRoot,projectRoot:this.projectRoot,projectDisplayName:this.projectRoot,maxFileByteSizeNumber:this.maxFileByteSize},new this.runtime.Input(t.fileName,t.getText()),r,this.symbolTable,this.constructorTable,this.packages,t).index(),this.stats.documentsEmitted+=1,r.occurrences.length===0)return this.fragments.delete(n),this.stats.documentsRemoved+=1,{relativePath:n,bytes:null,occurrences:0,symbols:r.symbols.length,referenceFragments:[]};let o=r.serializeBinary();return this.fragments.set(n,o),{relativePath:n,bytes:o,occurrences:r.occurrences.length,symbols:r.symbols.length,referenceFragments:du(n,r)}}result(t,n){return{producerIdentity:this.producerIdentity,fragments:t,durationMs:performance.now()-n,stats:this.snapshotStats()}}};function du(e,t){let n=new Map;for(let r of t.occurrences){if(!r.symbol||(r.symbol_roles&1)!==0||r.range.length<3)continue;let i=r.range[0],o=r.range[1];if(!Number.isInteger(i)||!Number.isInteger(o))continue;let a={targetSymbol:r.symbol,location:{file:e,line:i,column:o}};n.set(`${r.symbol}\0${i}\0${o}`,a)}return[...n.values()].sort((r,i)=>r.targetSymbol.localeCompare(i.targetSymbol)||r.location.line-i.location.line||r.location.column-i.location.column)}var pn=class{compilerHost;sourceFiles=new Map;constructor(t,n,r){let i=t.createCompilerHost(n),o=i.getSourceFile.bind(i);this.compilerHost={...i,getCurrentDirectory:()=>r,getSourceFile:(a,s,c,u)=>{let l=Ie(a);if(this.sourceFiles.has(l))return this.sourceFiles.get(l);let d=o(a,s,c,u);return this.sourceFiles.set(l,d),d}}}invalidate(t){this.sourceFiles.delete(Ie(t))}};function un(e,t){let n=e.readConfigFile(t,e.sys.readFile);if(n.error)throw new Error(e.formatDiagnostics([n.error],e.createCompilerHost({})));let r=e.parseJsonConfigFileContent(n.config,e.sys,mn(t)),i=r.errors.filter(o=>o.code!==18003);if(i.length>0)throw new Error(e.formatDiagnostics(i,e.createCompilerHost({})));return r}function gn(e){return ho(e.packageVersion,e.typescript.version)}function ho(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${uu}`}function pu(e,t){return st(mo(e,t))||"."}function Pe(e,t){if(cu(t))throw new Error(`expected a project-relative path: ${t}`);let n=ee(e,t),r=e.endsWith(ln)?e:`${e}${ln}`;if(n!==e&&!n.startsWith(r))throw new Error(`path escapes the project root: ${t}`);return n}function ve(e){return[...new Set(e.map(st))].sort()}function st(e){return e.split(ln).join("/").replace(/^\.\//,"")}function Ie(e){return ee(e)}function po(e,t){let n=0;for(let r of e.keys())if(mu(r)){try{if(r.getSourceFile()!==t)continue}catch{continue}e.delete(r),n+=1}return n}function mu(e){return!!(e&&typeof e=="object"&&"kind"in e&&"getSourceFile"in e)}import{createHash as fu}from"crypto";import{dirname as gu,join as yo}from"path";var Ee=5;var hu="typescript-index";function So(e){let t=yo(e,hu),n=Rr(t);return{...n,requestDir:n.legacyRequestDir}}function bo(e){try{let t=Gn(te(U(yo(gu(e),"meta.json"),"reindex metadata")));return t?fu("sha256").update(t).digest("hex"):null}catch{return null}}import{randomUUID as Ru}from"crypto";import{existsSync as xo,rmSync as hn}from"fs";import{join as xu}from"path";import{randomUUID as yu}from"crypto";import{getHeapStatistics as Su}from"v8";import{resolve as bu}from"path";var ct=class{projectRoot;currentGeneration;createEmitter;wallNow;monotonicNow;maxActiveSessions;softMemoryLimitBytes;memoryUsage;active=new Map;requests=0;sessionsCreated=0;sessionsReplaced=0;sessionsEvicted=0;lastRequestAtMs=null;lastDurationMs=null;lastError=null;unavailable=!1;constructor(t){if(this.projectRoot=bu(t.projectRoot),this.currentGeneration=t.currentGeneration,this.createEmitter=t.createEmitter??go,this.wallNow=t.wallNow??t.now??Date.now,this.monotonicNow=t.monotonicNow??t.now??F,t.maxActiveSessions!==void 0&&(!Number.isInteger(t.maxActiveSessions)||t.maxActiveSessions<1))throw new Error("TypeScript index maxActiveSessions must be a positive integer.");if(this.maxActiveSessions=t.maxActiveSessions??8,t.softMemoryLimitMb!==void 0&&(!Number.isInteger(t.softMemoryLimitMb)||t.softMemoryLimitMb<1))throw new Error("TypeScript index softMemoryLimitMb must be a positive integer.");this.softMemoryLimitBytes=t.softMemoryLimitMb===void 0?null:t.softMemoryLimitMb*1024*1024,this.memoryUsage=t.memoryUsage??(()=>({heapUsedBytes:process.memoryUsage().heapUsed,heapLimitBytes:Su().heap_size_limit}))}handle(t,n){let r=this.monotonicNow();try{if(this.currentGeneration()!==t)throw new Error("TypeScript index request does not match the currently published generation.");let i=this.emitterFor(n);if(i.emitter.producerIdentity!==n.producerIdentity)throw new Error("TypeScript index producer identity changed.");let o=i.emitter.snapshotStats(),a=i.emitter.advance({modifiedFiles:n.modifiedFiles,removedFiles:n.removedFiles,affectedFiles:n.affectedFiles}),s=this.monotonicNow()-r;return this.requests+=1,this.lastRequestAtMs=this.wallNow(),this.lastDurationMs=s,this.lastError=null,this.unavailable=!1,{producerIdentity:a.producerIdentity,cold:a.stats.initializations>o.initializations,durationMs:s,fragments:a.fragments.map(c=>({relativePath:c.relativePath,bytesBase64:c.bytes===null?null:Buffer.from(c.bytes).toString("base64"),occurrences:c.occurrences,symbols:c.symbols,referenceFragments:c.referenceFragments}))}}catch(i){throw this.lastError=i instanceof Error?i.message:String(i),i}}status(t){let n=[...this.active.values()].map(a=>a.emitter.snapshotStats()),r=a=>n.reduce((s,c)=>s+c[a],0),i=this.memoryUsage(),o=this.softMemoryLimitBytes!==null&&i.heapUsedBytes>=this.softMemoryLimitBytes;return{protocolVersion:Ee,state:this.unavailable?"unavailable":this.lastError?"error":this.active.size>0?"ready":"idle",requests:this.requests,sessionsCreated:this.sessionsCreated,sessionsReplaced:this.sessionsReplaced,sessionsEvicted:this.sessionsEvicted,activeSessions:this.active.size,maxActiveSessions:this.maxActiveSessions,heapUsedBytes:i.heapUsedBytes,heapLimitBytes:i.heapLimitBytes,...this.softMemoryLimitBytes===null?{}:{softMemoryLimitBytes:this.softMemoryLimitBytes},retireRequested:o,initializations:r("initializations"),programUpdates:r("programUpdates"),documentsEmitted:r("documentsEmitted"),documentsRemoved:r("documentsRemoved"),...this.lastRequestAtMs===null?{}:{lastRequestAt:new Date(this.lastRequestAtMs).toISOString()},...this.lastDurationMs===null?{}:{lastDurationMs:this.lastDurationMs},...this.lastError?{lastError:this.lastError}:{},...t?{mailbox:t}:{}}}close(){this.active.clear()}emitterFor(t){let n=`${t.tsconfigPath}\0${t.projectArgument}`,r=this.active.get(n);if(r?.projectIdentity===t.projectIdentity)return this.active.delete(n),this.active.set(n,r),r;if(r)this.active.delete(n);else if(this.active.size>=this.maxActiveSessions){let a=this.active.keys().next().value;a!==void 0&&(this.active.delete(a),this.sessionsEvicted+=1)}let i=this.createEmitter({workspaceRoot:this.projectRoot,tsconfigPath:t.tsconfigPath,projectRoot:t.projectArgument});if(!i.available)throw this.unavailable=!0,new Error(i.reason);r&&(this.sessionsReplaced+=1);let o={projectIdentity:t.projectIdentity,emitter:i.emitter};return this.active.set(n,o),this.sessionsCreated+=1,o}};var Nm=`typescript-index-${process.pid}-${yu()}`,Ro=J(process.pid),$m={pid:process.pid,...Ro?{processIdentity:Ro}:{}};var Pu=12e4,vu=5,Ce=class extends Error{name="TypeScriptIndexMemoryPressureError"},ut=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;mailboxLimits;emitLocally;requireService;localHost=null;constructor(t,n={}){this.projectRoot=Qn(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??wu(),this.runtime=n.runtime??ku,this.mailboxLimits=n.mailboxLimits??{},this.emitLocally=n.emitLocally,this.requireService=n.requireService===!0}request(t){let n=vr(this.cacheDir),r=So(this.cacheDir),i=Vt(n.statePath);if(!Po(i,this.projectRoot,this.runtime))return this.requestLocally(t);let o=this.runtime.now(),a=o+this.timeoutMs,s=(this.runtime.monotonicNow??F)()+this.timeoutMs,c=Nt("typescript-index-v5",{baseGeneration:this.baseGeneration,request:t}),u=$t(c),l=xr(r,{mailboxVersion:jt,operationKey:c,clientId:this.runtime.randomId(),enqueuedAtMs:o,deadlineAtMs:a,protocolVersion:Ee,id:u,baseGeneration:this.baseGeneration,request:t},{nowMs:o,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??F)()<=s;){if(xo(l.responsePath))try{return vo(N(l.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t.producerIdentity,t.affectedFiles)}finally{hn(l.responsePath,{force:!0})}let d=Vt(n.statePath);if(!Po(d,this.projectRoot,this.runtime))return this.abandonPendingRequest(r,u),this.requestLocally(t);this.runtime.sleep(vu)}if(xo(l.responsePath))try{return vo(N(l.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript index mailbox response"}),u,c,this.baseGeneration,t.producerIdentity,t.affectedFiles)}finally{hn(l.responsePath,{force:!0})}return this.abandonPendingRequest(r,u),this.requestLocally(t)}abandonPendingRequest(t,n){try{hn(xu(t.pendingDir,`${n}.json`),{force:!0})}catch{}}requestLocally(t){if(this.requireService)throw new Error("TypeScript incremental index service unavailable; refusing to load the whole compiler graph inside the reindex process");return this.emitLocally?yn(this.emitLocally(t),t.producerIdentity,t.affectedFiles):(this.localHost??=new ct({projectRoot:this.projectRoot,currentGeneration:()=>this.baseGeneration}),yn(Io(this.localHost.handle(this.baseGeneration,t),t.producerIdentity),t.producerIdentity,t.affectedFiles))}};function Po(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null,i=e?Date.parse(e.heartbeatAt):Number.NaN;return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===Ee&&n.isProcessAlive(e.pid)&&Number.isFinite(i)&&n.now()-i<=Pr&&(!e.processIdentity||r!=null&&we(e.processIdentity,r))}function vo(e,t,n,r,i,o){let a=JSON.parse(e);if(a.protocolVersion!==Ee||a.id!==t||a.operationKey!==n||a.ok===!0&&a.baseGeneration!==r)throw new Error("TypeScript index service wrote an incompatible response.");if(a.ok!==!0){let s=typeof a.error=="string"?a.error:"TypeScript index service request failed.";throw Iu(s)?new Ce(s):new Error(s)}return yn(Io(a.response,i),i,o)}function Iu(e){let t=e.toLowerCase();return t.includes("out of memory")||t.includes("memory limit")||t.includes("allocation failed")||t.includes("err_worker_out_of_memory")}function yn(e,t,n){if(e.producerIdentity!==t)throw new Error("TypeScript index service wrote an invalid response.");let r=[...new Set(n)].sort(),i=e.fragments.map(o=>o.relativePath).sort();if(JSON.stringify(i)!==JSON.stringify(r))throw new Error("TypeScript index service omitted or added an affected document.");return e}function Io(e,t){if(!e||typeof e!="object")throw new Error("TypeScript index service wrote an invalid response.");let n=e;if(n.producerIdentity!==t||typeof n.cold!="boolean"||typeof n.durationMs!="number"||!Number.isFinite(n.durationMs)||!Array.isArray(n.fragments))throw new Error("TypeScript index service wrote an invalid response.");let r=new Set,i=n.fragments.map(o=>{if(!o||typeof o.relativePath!="string"||o.bytesBase64!==null&&typeof o.bytesBase64!="string"||typeof o.occurrences!="number"||!Number.isInteger(o.occurrences)||o.occurrences<0||typeof o.symbols!="number"||!Number.isInteger(o.symbols)||o.symbols<0||!Array.isArray(o.referenceFragments)||!o.referenceFragments.every(Eu)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:Tu(o.bytesBase64);return{relativePath:o.relativePath,bytes:a,occurrences:o.occurrences,symbols:o.symbols,referenceFragments:o.referenceFragments}});return{producerIdentity:n.producerIdentity,cold:n.cold,durationMs:n.durationMs,fragments:i}}function Eu(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.targetSymbol=="string"&&!!t.location&&typeof t.location.file=="string"&&Number.isInteger(t.location.line)&&Number.isInteger(t.location.column)}function Tu(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function wu(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Pu}var ku={now:Date.now,monotonicNow:F,randomId:Ru,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:ge,readProcessIdentity:J};var Fu=128,Cu=256;function Ou(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."],n=he(t);if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let r=z(e.previousSnapshot,e.currentSnapshot);if(r.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};let i=r.changes.filter(g=>g.inputKind==="source"&&Re(g.path)),o=_o(r,n),a={...r,changes:o},s=i.filter(g=>g.kind==="added").map(g=>g.path),c=i.filter(g=>g.kind==="deleted").map(g=>g.path),u=i.filter(g=>g.kind==="modified"),l=dt(e.currentSnapshot,e.producerIdentity,n),d=dt(e.previousSnapshot,e.producerIdentity,n),m=Fo(r,o,l,d),f=!m&&Oo(r);if(i.length===0&&!m)return{eligible:!1,reason:"change does not affect the configured TypeScript project"};let y=e.currentSnapshot.files.filter(g=>Le(g.path,e.currentSnapshot.languages)==="source"&&Re(g.path)).map(g=>g.path).sort(),b=new Set(y),k=m?e.projectFiles.filter(g=>!b.has(g)).sort():[...c].sort(),O=m?a:{...r,changes:i},E=m?{eligible:!0,plan:{...Fe(a,e.graph,[...new Set([...y,...k])]),mode:"full-project"}}:Au(u,s,k,e.graph,e.projectFiles);if(!E.eligible)return E;let C=E.plan,w=new Set(k),h=Mu(C,t,e.graph,w);if(!h)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let S=h.length===1?h[0]:void 0;return{eligible:!0,manifest:O,plan:C,projectIdentity:l,previousFragmentGeneration:wo(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:wo(e.currentSnapshot,e.producerIdentity),projects:h,deletedFiles:k,replaceProject:m,dependencyGraphUnchanged:f,...S?{tsconfigPath:S.tsconfigPath,projectArgument:S.projectArgument}:{}}}function _o(e,t){return e.changes.filter(n=>n.inputKind==="source"&&Re(n.path)||n.inputKind==="config"&&(!ye(n.path)||t.has(n.path))&&Du(n)||n.inputKind==="ambient")}function Du(e){return e.kind!=="modified"||e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function Fo(e,t,n,r){return n!==r||e.projectIdentityChanged||e.uncertainty.length>0||t.length>Cu||t.some(i=>i.inputKind==="config"||i.inputKind==="ambient")}function Au(e,t,n,r,i){if(e.length===0)return t.length===0&&n.length===0?{eligible:!1,reason:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...t,...n])].sort(),affectedFiles:[...new Set([...t,...Eo(n,r,i)])].sort(),reasons:[]}};let o=Fe({version:1,changes:e.filter(Co),projectIdentityChanged:!1,uncertainty:[]},r,i);return o.mode==="full-project"?{eligible:!1,reason:o.reasons.length>0?`affected set widened: ${o.reasons.join(", ")}`:"empty affected set"}:{eligible:!0,plan:{mode:"closure",changedFiles:[...new Set([...e.map(a=>a.path),...t,...n])].sort(),affectedFiles:[...new Set([...o.affectedFiles,...e.map(a=>a.path),...t,...Eo(n,r,i)])].sort(),reasons:[]}}}function Co(e){return e.kind!=="modified"?!0:e.before.semanticHash===void 0||e.after.semanticHash===void 0||e.before.semanticHash!==e.after.semanticHash}function Oo(e){let t=e.changes.filter(n=>n.inputKind==="source"&&Re(n.path));return t.length>0&&t.every(n=>n.kind==="modified"&&!Co(n))}function Mu(e,t,n,r){let i=new Map;for(let a of e.affectedFiles){let s=Lu(a,t);if(!s)return null;let c=i.get(s)??[];c.push(a),i.set(s,c)}let o=[];for(let[a,s]of[...i].sort(([c],[u])=>c.localeCompare(u))){let c=new Set(s),u=e.changedFiles.filter(m=>!r.has(m)&&(c.has(m)||s.some(f=>To(f,m,n)))),l=e.changedFiles.filter(m=>r.has(m)&&(c.has(m)||s.some(f=>To(f,m,n)))),d=s.filter(m=>!r.has(m));if(u.length===0&&l.length===0&&d.length===0)return null;o.push({projectArgument:a,tsconfigPath:a==="."?"tsconfig.json":`${a}/tsconfig.json`,modifiedFiles:u,removedFiles:l,affectedFiles:[...d].sort()})}return o}function Eo(e,t,n){let r=new Set(n),i=new Map;for(let[s,c]of t)if(r.has(s))for(let u of c){let l=i.get(u)??new Set;l.add(s),i.set(u,l)}let o=new Set(e),a=[...e];for(let s=0;s<a.length;s+=1){let c=a[s];if(c)for(let u of i.get(c)??[])o.has(u)||(o.add(u),a.push(u))}return[...o].sort()}function Lu(e,t){let n=t.filter(o=>o==="."||e===o||e.startsWith(`${o}/`));if(n.length===0)return null;let r=[...new Set(n)].sort((o,a)=>lt(a)-lt(o)||o.localeCompare(a)),i=r[0];return r[1]&&lt(r[1])===lt(i)?null:i}function lt(e){return e==="."?0:e.split("/").filter(Boolean).length}function To(e,t,n){let r=new Set,i=[e];for(let o=0;o<i.length;o+=1){let a=i[o];if(!(!a||r.has(a))){r.add(a);for(let s of n.get(a)??[]){if(s===t)return!0;r.has(s)||i.push(s)}}}return!1}function Do(e){let t=F();try{if(!Sn(e.previousDbPath)||!Sn(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=fn();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new V({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a=Nu(e.projectRoot,e.previousSnapshot,e.currentSnapshot),s=e.projectMode==="workspace"?ne(e.projectRoot,e.currentSnapshot.typescriptProjects):["."],c=he(s),u,l,d;try{u=Ue(o,{includeIgnored:!1}).filter(Re).sort();let T=a?z(a,e.currentSnapshot):null,p=T&&a&&Fo(T,_o(T,c),dt(e.currentSnapshot,r.producerIdentity,c),dt(a,r.producerIdentity,c)),x=T!==null&&!p&&Oo(T);p?(d=We(o,"none")??void 0,l=new Map):x?l=new Map:(d=Ge(o),l=d.graph)}finally{o.close()}let m=performance.now()-n,f=Ou({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?s:void 0,previousSnapshot:a,currentSnapshot:e.currentSnapshot,projectFiles:u,graph:l,producerIdentity:r.producerIdentity,rootTsconfigExists:Sn(_u(e.projectRoot,"tsconfig.json"))});if(!f.eligible)throw new Error(f.reason);let y=bo(e.previousDbPath);if(!y)throw new Error("published TypeScript base generation unavailable");n=performance.now();let b=new ut({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:y},{requireService:!0}),k=f.projects.flatMap(T=>{let p=ju(T.affectedFiles,Fu);return(p.length>0?p:[[]]).map((A,H)=>({project:T,affectedFiles:A,removedFiles:H===0?T.removedFiles:[],firstForProject:H===0}))}),O=[],E=new Map,C=[],w=!1,h=0,S=0,g=0,_=f.previousFragmentGeneration;for(let[T,p]of k.entries()){let x=b.request({kind:"emit-documents",tsconfigPath:p.project.tsconfigPath,projectArgument:p.project.projectArgument,projectIdentity:f.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:p.firstForProject?p.project.modifiedFiles:[],removedFiles:p.firstForProject?p.project.removedFiles:[],affectedFiles:p.affectedFiles});w||=x.cold,C.push(x.durationMs);let A=p.removedFiles.map(Me=>({relativePath:Me,bytes:null,occurrences:0,symbols:0,referenceFragments:[]})),H=[...x.fragments,...A];if(!f.replaceProject)for(let Me of H)E.set(Me.relativePath,Me.referenceFragments);let vt=performance.now(),Za=Wr(x.fragments);h+=performance.now()-vt;let $n=T===0?e.candidateAffectedScipPath:`${e.candidateAffectedScipPath}.batch-${T}.scip`,es=performance.now();ko($n,Za),g+=performance.now()-es;let ts=performance.now(),Vn=T===k.length-1?f.nextFragmentGeneration:$u({previousGenerationIdentity:_,targetGenerationIdentity:f.nextFragmentGeneration,fragments:H});Hr({cacheDir:e.cacheDir,previousGenerationIdentity:_,nextGenerationIdentity:Vn,producerIdentity:r.producerIdentity,projectIdentity:f.projectIdentity,baseShardCurrent:T===0?e.baseShardCurrent:!1,fragments:H,allowProjectIdentityChange:f.replaceProject&&T===0,allowLegacyProjectIdentityMigration:!0}),S+=performance.now()-ts,_=Vn,O.push({scipPath:$n,affectedFiles:[...p.affectedFiles,...p.removedFiles].sort(),deletedFiles:[...p.removedFiles].sort()})}let R=performance.now()-n,P={scipPath:e.previousShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,affectedBatches:O,completeScipUpdated:!1,durationMs:F()-t,cold:w,changedFiles:f.plan.changedFiles,affectedFiles:f.plan.affectedFiles,deletedFiles:f.deletedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:f.previousFragmentGeneration,nextFragmentGeneration:f.nextFragmentGeneration,manifest:f.manifest,plan:f.plan,projectFileCount:u.length,dependencyGraphSnapshot:d,dependencyGraphUnchanged:f.dependencyGraphUnchanged,referenceFragmentsByFile:E,timings:{runtimeMs:i,graphMs:m,requestMs:R,serviceMs:C.reduce((T,p)=>T+p,0),assemblyMs:h,fragmentStoreMs:S,writeMs:g}};return e.onStatus(`${f.replaceProject?"Bounded TypeScript project refresh":"Incremental TypeScript index"} emitted ${P.affectedFiles.length-P.deletedFiles.length} document(s), removed ${P.deletedFiles.length}, and produced ${O.length} bounded batch(es) across ${f.projects.length} project(s) in ${(P.durationMs/1e3).toFixed(3)}s (${P.cold?"cold":"warm"} service; whole SCIP deferred; runtime ${i.toFixed(0)}ms, graph ${m.toFixed(0)}ms, request ${R.toFixed(0)}ms, assembly ${h.toFixed(0)}ms, fragments ${S.toFixed(0)}ms, write ${g.toFixed(0)}ms).`),P}catch(n){let r=n instanceof Error?n.message:String(n);if(e.onUnavailable?.(r),n instanceof Ce)throw e.onStatus(`Incremental TypeScript index stopped after memory pressure survived one cold Worker retry: ${r}. Preserving the accepted index instead of starting a memory-heavier whole-project rebuild.`),n;return e.onStatus(`Incremental TypeScript index unavailable: ${r}.`),null}}function ju(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Nu(e,t,n){if(!t)return null;let r=new Map(n.files.map(a=>[a.path,a])),i=!1,o=t.files.map(a=>{let s=r.get(a.path);if(a.semanticHash!==void 0||s?.semanticHash===void 0)return a;let c=Be(e,a.path,a.hash);return c===void 0?a:(i=!0,{...a,semanticHash:c})});return i?{...t,files:o}:t}function $u(e){let t=bn("sha256");t.update("typescript-overlay-batch-v1\0"),t.update(e.previousGenerationIdentity),t.update("\0"),t.update(e.targetGenerationIdentity);for(let n of[...e.fragments].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)))t.update("\0path\0"),t.update(n.relativePath),n.bytes===null?t.update("\0deleted"):(t.update("\0bytes\0"),t.update(bn("sha256").update(n.bytes).digest()));return t.digest("hex")}function Rn(e){let t=fn();if(!t.available)throw new Error(t.reason);let n=zr({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:fe(e.baseShardPath,{inputKind:"TypeScript base SCIP shard",maxBytes:Ne}),packageVersion:t.packageVersion});ko(e.candidateShardPath,n)}function dt(e,t,n){let r=e.files.filter(i=>{let o=Le(i.path,e.languages);return o==="ambient"||o==="config"&&(!ye(i.path)||n.has(i.path))}).map(i=>{let a=Le(i.path,e.languages)==="config"?i.semanticHash:void 0;return{path:i.path,size:a===void 0?i.size:0,hash:a??i.hash}}).sort((i,o)=>i.path.localeCompare(o.path));return`typescript-project-v3:${Ao(JSON.stringify({version:3,producerIdentity:t,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),nonSourceInputs:r}))}`}function wo(e,t){return Ao(JSON.stringify({version:1,producerIdentity:t,snapshot:Un(e)}))}function Ao(e){return bn("sha256").update(e).digest("hex")}import{closeSync as Vu,existsSync as pt,fstatSync as Bu,lstatSync as Uu,openSync as Gu,renameSync as vn,rmSync as Oe,statSync as Wu,writeSync as qu}from"fs";import{cpus as Hu}from"os";import{join as In}from"path";var xn=Symbol("no-error");async function Mo(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=Number.isFinite(t)?Math.max(1,Math.floor(t)):1,o=Math.min(e.length,i),a=0,s=xn,c=!0,u=Array.from({length:o},async()=>{for(;c&&a<e.length;){let l=a++;try{r[l]=await n(e[l])}catch(d){s===xn&&(s=d),c=!1}}});if(await Promise.all(u),s!==xn)throw s;return r}var Lo=8*1024;function jo(e,t,n){let r=Buffer.from(t,"utf8"),i=()=>Gu(e,"wx",384),o;try{o=i()}catch(a){if(a.code!=="EEXIST")throw a;if(n==="skip")return null;Oe(e,{force:!0}),o=i()}try{qu(o,r);let a=Bu(o);return{path:e,content:r,device:a.dev,inode:a.ino}}finally{Vu(o)}}function zu(e,t){let n=[];try{if(e.temporaryRootConfigContent!==void 0){let r=jo(In(t,"tsconfig.json"),e.temporaryRootConfigContent,"skip");r&&n.push(r)}for(let r of e.temporaryProjectConfigs??[]){let i=jo(r.path,r.content,"replace");i&&n.push(i)}return n}catch(r){for(let i of n.reverse())Vo(i);throw r}}function Vo(e){if(e)try{let t=Uu(e.path);if(!t.isFile()||t.dev!==e.device||t.ino!==e.inode||t.size!==e.content.byteLength)return;let n;try{n=fe(e.path,{maxBytes:e.content.byteLength,inputKind:"temporary TypeScript index configuration"})}catch{return}if(!n.equals(e.content))return;Oe(e.path)}catch(t){if(t.code!=="ENOENT")throw t}}function Ju(e,t,n){if(!e.defaultOutputPath)return;let r=In(t,e.defaultOutputPath);n!==r&&pt(r)&&vn(r,n)}function Yu(e,t,n){if(!e.defaultOutputPath)return null;let r=In(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Oe(i,{force:!0}),pt(r)?(vn(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Xu(e){e&&(Oe(e.defaultOutputPath,{force:!0}),e.backupPath&&pt(e.backupPath)&&vn(e.backupPath,e.defaultOutputPath))}function Ku(e,t){if(e<=1)return 1;let n=Number(process.env.SCIP_QUERY_INDEXER_CONCURRENCY??0),r=Number.isFinite(t)&&t&&t>0?t:Number.isFinite(n)&&n>0?n:Math.min(8,Math.max(1,Hu().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Bo(e,t,n,r,i){$(i,"Reindex cancelled by its owner.");let o=e.filter(u=>u.config.defaultOutputPath),a=e.filter(u=>!u.config.defaultOutputPath&&u.boundedConcurrency!==void 0),s=e.filter(u=>!u.config.defaultOutputPath&&u.boundedConcurrency===void 0),c=[];if(c.push(...await No(s,Ku(s.length,r),t,n,i)),a.length>0){let u=Math.max(1,Math.min(...a.map(l=>l.boundedConcurrency)));c.push(...await No(a,u,t,n,i))}for(let u of o)$(i,"Reindex cancelled by its owner."),c.push((await Pn(u,t,n,i)).result);return c.sort((u,l)=>e.findIndex(d=>d.id===u.id)-e.findIndex(d=>d.id===l.id))}async function No(e,t,n,r,i){let o=await Mo(e,Math.max(1,t),s=>Pn(s,n,r,i));if(t<=1)return o.map(({result:s})=>s);let a=new Map;for(let s of o.filter(c=>c.result.skipped&&c.retryable)){let c=e.find(u=>u.id===s.result.id);c&&(r(`Retrying ${c.label} indexer serially after parallel failure...`),$(i,"Reindex cancelled by its owner."),a.set(c.id,(await Pn(c,n,r,i)).result))}return o.map(({result:s})=>a.get(s.id)??s)}async function Pn(e,t,n,r){$(r,"Reindex cancelled by its owner."),n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Oe(e.scipPath,{force:!0});let i=Yu(e.config,t,e.scipPath),o=[],a=[e.binary,...e.args].join(" "),s=F();try{o=zu(e,t),e.trustedProjectTool&&br(t,e.trustedProjectTool);let u=yr(e.binary,e.args),l=await qe({command:u.binary,args:u.args,label:`${e.label} indexer`,cwd:t,env:e.env,timeoutMs:Qu(),maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,signal:r});if(l.status!==0){let d=l.stderr.trim();throw new Error(`${e.resolvedBinary} exited with status ${l.status}${d?`:
292
+ ${d}`:""}`)}Ju(e.config,t,e.scipPath)}catch(u){if(r?.aborted)throw zn(r,"Reindex cancelled by its owner.");let l=u instanceof Error?u.message:String(u),d=l.length<=Lo?l:`${l.slice(0,Lo)}
293
+ [indexer failure detail truncated]`,m=`${e.resolvedBinary} indexer failed: ${d}`,f=e.label===e.language?m:`${e.label}: ${m}`;return n(`Skipping ${e.label}: ${m}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:F()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:f}},retryable:Zu(u)}}finally{Xu(i);for(let u of o.reverse())Vo(u)}if(!pt(e.scipPath)){let u=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,l=e.label===e.language?u:`${e.label}: ${u}`;return n(`Skipping ${e.label}: ${u}`),{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:F()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},skipped:{language:e.language,reason:l}},retryable:!1}}let c;try{c=Wu(e.scipPath).size}catch{c=void 0}return{result:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:F()-s,command:a,...e.outputComposition?{outputComposition:e.outputComposition}:{},outputBytes:c},retryable:!1}}function Qu(){let e=Number(process.env.SCIP_QUERY_INDEXER_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):Tr.indexer}function Zu(e){return e instanceof wr?e.kind==="spawn"&&$o(e.cause):$o(e)}function $o(e){let t=e?.code;return t==="EAGAIN"||t==="ENOMEM"||t==="EMFILE"||t==="ENFILE"||t==="ETXTBSY"}import{execFileSync as Go}from"child_process";import{homedir as Uo,platform as el}from"os";import{delimiter as tl,join as mt}from"path";function Tn(e,t){let n=e.installMethods,r=ke(e);if(!n?.length)return t(`No auto-install method available for ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1;for(let i of n){if(!i.identity||!i.destination){t(`Refusing ${i.label} installation for ${r}: the installer descriptor lacks an immutable identity or destination.`);continue}if(!Dt(i.prerequisite))continue;let o=nl(i);t(`Installing immutable ${i.identity} via ${i.label} into ${o}; expected executable: ${r}.`);try{Go(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:el()==="win32"});let a=be(e);if(a){let s=a===e.indexerBinary?"":` (using ${a})`;return t(`Successfully installed ${i.identity} via ${i.label}${s}; resolved executable: ${a}.`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(a){let s=a instanceof Error?a.message:String(a);t(`${i.label} install failed: ${s}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}function nl(e){if(e.binary==="npm")return En("npm",["root","-g"])??e.destination;if(e.binary==="go"){let t=En("go",["env","GOBIN"]);if(t)return t;let n=En("go",["env","GOPATH"]);if(n)return mt(n.split(tl)[0],"bin")}return e.binary==="dotnet"?mt(process.env.DOTNET_CLI_HOME??Uo(),".dotnet","tools"):e.binary==="dart"?mt(process.env.PUB_CACHE??mt(Uo(),".pub-cache"),"bin"):e.destination}function En(e,t){try{return Go(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL",env:process.env}).trim()||null}catch{return null}}import pa from"better-sqlite3";import{existsSync as ma}from"fs";import{dirname as fa,join as ga,resolve as ha}from"path";import{randomUUID as il}from"crypto";import{mkdtempSync as ol,rmSync as al,statSync as qo}from"fs";import{tmpdir as sl}from"os";import{join as Ho}from"path";import{Worker as cl}from"worker_threads";function rl(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function Te(){return{skippedReferences:0,skippedReferenceReasons:rl(),skippedReferenceSamples:[]}}function ft(e,t){e.skippedReferences+=t.skippedReferences;for(let n of Object.keys(e.skippedReferenceReasons)){e.skippedReferenceReasons[n]+=t.skippedReferenceReasons[n];for(let r of t.skippedReferenceSamples.filter(i=>i.reason===n))e.skippedReferenceSamples.filter(o=>o.reason===n&&o.sourceFile===r.sourceFile).length<2&&e.skippedReferenceSamples.push(r)}}var ul=3e5,zo=64*1024*1024,ll={createResultDirectory:()=>ol(Ho(sl(),"scip-query-vue-workers-")),spawn:(e,t)=>new cl(e,{workerData:t}),resultSize:e=>qo(e).size,readResult:e=>N(e,{maxBytes:zo,inputKind:"Vue worker result"}),removeResultDirectory:e=>al(e,{recursive:!0,force:!0})};function Jo(e){return e.length>=8&&Xo(e.length)>1}async function Yo(e,t=ll){let n=Xo(e.vueFiles.length),r=vl(e.vueFiles),i=El(r,n),o=new URL("./augment-vue-worker.js",import.meta.url),a=e.timeoutMs??xl(),s=e.maxResultBytes??Pl();Wo("timeoutMs",a),Wo("maxResultBytes",s);let c=il(),u=t.createResultDirectory(),l=[],d,m,f;try{for(let b=0;b<i.length;b++){let k=b,O=i[b]??[],E=O.map(h=>h.taskId),C=Ho(u,`${k}.json`),w=t.spawn(o,{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:O,resultPath:C,runId:c,workerId:k,taskIds:E});l.push({workerId:k,taskIds:E,resultPath:C,handle:w,completion:dl(w,k)})}await pl(l,a);let y=l.sort((b,k)=>b.workerId-k.workerId).map(b=>fl(b,c,s,t));f={occurrences:y.flatMap(b=>b.occurrences),...Te()};for(let b of y)ft(f,b)}catch(y){d=y}finally{let y=await ml(l);if(y.length===0)try{t.removeResultDirectory(u)}catch(b){y.push(b)}if(y.length>0){let b=d===void 0?y:[d,...y];m=new AggregateError(b,`Vue worker cleanup failed: ${Rl(b[0])}`)}}if(m)throw m;if(d!==void 0)throw d;if(!f)throw new Error("Vue workers completed without producing a merged result.");return f}function dl(e,t){return new Promise((n,r)=>{let i=!1,o=c=>{i||(i=!0,e.off("error",a),e.off("exit",s),c?r(c):n())},a=c=>{o(new Error(`Vue reference worker ${t} failed: ${c.message}`,{cause:c}))},s=c=>{o(c===0?void 0:new Error(`Vue reference worker ${t} exited with code ${c}`))};e.once("error",a),e.once("exit",s)})}async function pl(e,t){let n;try{await Promise.race([Promise.all(e.map(r=>r.completion)),new Promise((r,i)=>{n=setTimeout(()=>i(new Error(`Vue reference workers timed out after ${(t/1e3).toFixed(3)}s`)),t),n.unref()})])}finally{n&&clearTimeout(n)}}async function ml(e){return(await Promise.allSettled(e.map(async n=>n.handle.terminate()))).flatMap(n=>n.status==="rejected"?[n.reason]:[])}function fl(e,t,n,r){let i=r.resultSize(e.resultPath);if(!Number.isSafeInteger(i)||i<0||i>n)throw new Error(`Vue reference worker ${e.workerId} result is ${i} bytes; limit is ${n} bytes`);let o;try{o=JSON.parse(r.readResult(e.resultPath))}catch(a){throw new Error(`Vue reference worker ${e.workerId} produced invalid JSON`,{cause:a})}if(!De(o)||o.version!==1||o.runId!==t||o.workerId!==e.workerId)throw new Error(`Vue reference worker ${e.workerId} result identity does not match its assignment`);if(!bl(o.taskIds,e.taskIds))throw new Error(`Vue reference worker ${e.workerId} result task identities do not match its assignment`);if(o.ok===!1)throw typeof o.error!="string"?new Error(`Vue reference worker ${e.workerId} failure payload is malformed`):new Error(`Vue reference worker ${e.workerId} failed: ${o.error}`);if(o.ok!==!0||!gl(o.result))throw new Error(`Vue reference worker ${e.workerId} success payload is malformed`);return o.result}function gl(e){if(!De(e)||!Array.isArray(e.occurrences)||!e.occurrences.every(hl)||!W(e.skippedReferences)||!De(e.skippedReferenceReasons))return!1;for(let t of["missing-source-file","missing-service-script","no-definition","same-file-definition","unindexed-definition"])if(!W(e.skippedReferenceReasons[t]))return!1;return Array.isArray(e.skippedReferenceSamples)&&e.skippedReferenceSamples.every(yl)}function hl(e){return De(e)&&typeof e.sourceFile=="string"&&W(e.sourceLine)&&W(e.sourceStartChar)&&W(e.sourceEndChar)&&typeof e.sourceToken=="string"&&typeof e.definitionFile=="string"&&W(e.symbolId)}function yl(e){return De(e)&&typeof e.sourceFile=="string"&&W(e.sourceLine)&&W(e.sourceStartChar)&&W(e.sourceEndChar)&&typeof e.token=="string"&&Sl(e.reason)}function Sl(e){return e==="missing-source-file"||e==="missing-service-script"||e==="no-definition"||e==="same-file-definition"||e==="unindexed-definition"}function W(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function De(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bl(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((n,r)=>typeof n=="string"&&n===t[r])}function Wo(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e} must be a positive safe integer.`)}function Rl(e){return e instanceof Error?e.message:String(e)}function Xo(e){let t=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKERS??0),n=Number.isFinite(t)&&t>0?t:1;return Math.max(1,Math.min(e,n))}function xl(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:ul}function Pl(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_RESULT_MAX_BYTES??0);return Number.isSafeInteger(e)&&e>0?e:zo}function vl(e){let t=Il(),n=[];for(let r of e){let i=Ko(r),o=Math.max(1,Math.ceil(i/t));for(let a=0;a<o;a++)n.push({taskId:`${n.length}:${r}:${a}`,fileName:r,startOffset:Math.floor(i*a/o),endOffset:a===o-1?Number.POSITIVE_INFINITY:Math.floor(i*(a+1)/o),countFileSkip:a===0})}return n}function Il(){return Number.POSITIVE_INFINITY}function El(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Tl(i)})).sort((i,o)=>o.weight-i.weight);for(let i of r){let o=n.reduce((a,s)=>s.weight<a.weight?s:a);o.tasks.push(i.task),o.weight+=i.weight}return n.map(i=>i.tasks).filter(i=>i.length>0)}function Tl(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Ko(e.fileName)-e.startOffset)}function Ko(e){try{return qo(e).size}catch{return 1}}import{createRequire as wl}from"module";import{existsSync as kl}from"fs";import{dirname as Qo,extname as _l,join as Zo,relative as Fl,resolve as Cl}from"path";import{pathToFileURL as Ol}from"url";function Dl(e){e.transaction(()=>{e.prepare(`
294
294
  DELETE FROM mentions
295
295
  WHERE chunk_id IN (
296
296
  SELECT c.id
@@ -305,12 +305,12 @@ ${l}`:""}`)}Rm(e.config,t,e.scipPath)}catch(d){if(r?.aborted)throw Fi(r,"Reindex
305
305
  FROM documents
306
306
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
307
307
  )
308
- `).run()})()}function fi(e,t){return e.prepare(`
308
+ `).run()})()}function kn(e,t){return e.prepare(`
309
309
  SELECT relative_path AS relativePath
310
310
  FROM documents
311
311
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
312
312
  ORDER BY relative_path
313
- `).all().map(r=>rg(t,r.relativePath))}function Gc(e,t){let{vueCore:n,ts:r,volarTs:i}=ag(e),{parsed:o,vueOptions:a}=sg(n,r,t),s=jc(t),c=n.createVueLanguagePlugin(r,o.options,a,m=>m),d=cg(n,r,c),u=dg(s,o),{languageServiceHost:l}=i.createLanguageServiceHost(r,r.sys,d,m=>m,u),p=r.createLanguageService(l);return{ts:r,language:d,languageService:p,fileNames:o.fileNames,configDir:s}}function ag(e){let t=Zm(ig(Nc(e,"package.json")).href);return{vueCore:pi(t,"@vue/language-core",e),ts:pi(t,"typescript",e),volarTs:pi(t,"@volar/typescript",e)}}function sg(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,jc(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function cg(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!eg(o))return;let a=L(o,{maxBytes:pe,inputKind:"Vue language-service source file"});r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??gg(o))});return r.current=i,i}function dg(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function pi(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 $c(e,t,n){let r=ug(e);return i=>{if(!i.name)return null;let o=ue(t,i.fileName),a=n.get(i.fileName);if(!a)return null;let s=n.positionAt(a,i.textSpan.start),c=r.get(o);if(!c)return null;let d=c.starts.find(l=>l.line===s.line&&l.displayName===i.name);if(d)return d.symbolId;let u=c.containingByLine.get(s.line);return u&&u.displayName===i.name?u.symbolId:lg(c.starts,s.line,2,i.name)}}function ug(e){let t=e.prepare(`
313
+ `).all().map(r=>Cl(t,r.relativePath))}function ea(e,t){let{vueCore:n,ts:r,volarTs:i}=Al(e),{parsed:o,vueOptions:a}=Ml(n,r,t),s=Qo(t),c=n.createVueLanguagePlugin(r,o.options,a,f=>f),u=Ll(n,r,c),l=jl(s,o),{languageServiceHost:d}=i.createLanguageServiceHost(r,r.sys,u,f=>f,l),m=r.createLanguageService(d);return{ts:r,language:u,languageService:m,fileNames:o.fileNames,configDir:s}}function Al(e){let t=wl(Ol(Zo(e,"package.json")).href);return{vueCore:wn(t,"@vue/language-core",e),ts:wn(t,"typescript",e),volarTs:wn(t,"@volar/typescript",e)}}function Ml(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,Qo(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Ll(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!kl(o))return;let a=N(o,{maxBytes:wt,inputKind:"Vue language-service source file"});r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??Gl(o))});return r.current=i,i}function jl(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function wn(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 ta(e,t,n){let r=Nl(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:$l(c.starts,s.line,2,i.name)}}function Nl(e){let t=e.prepare(`
314
314
  SELECT
315
315
  d.relative_path AS relativePath,
316
316
  der.start_line AS startLine,
@@ -321,22 +321,22 @@ ${l}`:""}`)}Rm(e.config,t,e.scipPath)}catch(d){if(r?.aborted)throw Fi(r,"Reindex
321
321
  JOIN documents d ON d.id = der.document_id
322
322
  JOIN global_symbols gs ON gs.id = der.symbol_id
323
323
  ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
324
- `).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function lg(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let s=Math.floor((i+o)/2);e[s].line<t?i=s+1:o=s-1}let a=null;for(let s of[o,i]){let c=e[s];if(!c||c.displayName!==r)continue;let d=Math.abs(c.line-t);d>n||(!a||d<a.distance)&&(a={distance:d,symbolId:c.symbolId})}return a?.symbolId??null}function mi(e,t,n){let r=Sg(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
324
+ `).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function $l(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let s=Math.floor((i+o)/2);e[s].line<t?i=s+1:o=s-1}let a=null;for(let s of[o,i]){let c=e[s];if(!c||c.displayName!==r)continue;let u=Math.abs(c.line-t);u>n||(!a||u<a.distance)&&(a={distance:u,symbolId:c.symbolId})}return a?.symbolId??null}function _n(e,t,n){let r=Hl(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
325
325
  INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
326
326
  VALUES (?, ?, ?, ?)
327
- `),a=0,s=new Map;return e.transaction(()=>{for(let d of n){let u=ue(t,d),l=Jc(r.name,r.version,u);o.run(l,"default",7,`Vue component|${u}`);let p=bg(i,r,t,d);p&&(a++,s.set(d,p))}})(),{get(d){return s.get(d)??null},syntheticSymbols:a}}function Bc(e,t,n,r,i){return e.transaction(()=>(og(e),pg(e,t,n,r),fg(e,i)))()}function pg(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
327
+ `),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let l=q(t,u),d=la(r.name,r.version,l);o.run(d,"default",7,`Vue component|${l}`);let m=zl(i,r,t,u);m&&(a++,s.set(u,m))}})(),{get(u){return s.get(u)??null},syntheticSymbols:a}}function na(e,t,n,r,i){return e.transaction(()=>(Dl(e),Vl(e,t,n,r),Bl(e,i)))()}function Vl(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
328
328
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
329
329
  VALUES (?, ?, ?, ?, X'00')
330
330
  `),a=e.prepare(`
331
331
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
332
332
  VALUES (?, ?, 1)
333
- `);for(let s of n){let c=r.get(s);if(!c)continue;let d=ue(t,s),u=i.get(d);if(!u)continue;let l=o.run(u.id,-1,0,0);a.run(Number(l.lastInsertRowid),c)}}function Vc(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(gi(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Uc(e){let t=new Set,n=[];for(let r of e){let i=qc(r);t.has(i)||(t.add(i),n.push(r))}return n}function qc(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function fg(e,t){let n=yg(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
333
+ `);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 ra(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(Fn(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function ia(e){let t=new Set,n=[];for(let r of e){let i=oa(r);t.has(i)||(t.add(i),n.push(r))}return n}function oa(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function Bl(e,t){let n=ql(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
334
334
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
335
335
  VALUES (?, ?, ?, ?, X'00')
336
336
  `),i=e.prepare(`
337
337
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
338
338
  VALUES (?, ?, 0)
339
- `),o=new Set,a=0,s=0;for(let c of t){let d=qc(c);if(o.has(d))continue;o.add(d);let u=n.get(c.sourceFile);if(!u)continue;let l=r.run(u,s++,c.sourceLine,c.sourceLine),p=i.run(Number(l.lastInsertRowid),c.symbolId);a+=Number(p.changes)}return a}function*Wc(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 Hc(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function gi(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function mg(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 zc(e,t){return ue(e,t).startsWith("node_modules/")}function ue(e,t){return ng(e,t).replaceAll("\\","/")}function gg(e){switch(tg(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 Yc(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=L(t,{maxBytes:pe,inputKind:"Vue source file"}),r={text:n,lineStarts:hg(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:mg}}function hg(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function yg(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 Sg(e){try{let t=JSON.parse(L(Nc(e,"package.json"),{maxBytes:q,inputKind:"project package manifest"}));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function bg(e,t,n,r){let i=ue(n,r),o=Jc(t.name,t.version,i);return e.get(o)?.id??null}function Jc(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function nd(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>vg({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function xg(e){return se(he(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),se(nd({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}async function Ig(e){return se(he(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),Pg(e)}function vg(e){let t=td(e.projectRoot,e.tsconfig);if(!Qc(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Kc(e.dbPath);try{let r=fi(n,e.projectRoot),i=ed(Zc(e.dbPath),"augment-vue-meta.json");return xa({cachePath:i,readFingerprint:()=>od(n,e.projectRoot,e.tsconfig),compute:()=>wg({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 Pg(e){let t=td(e.projectRoot,e.tsconfig);if(!Qc(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Kc(e.dbPath);try{let r=fi(n,e.projectRoot),i=ed(Zc(e.dbPath),"augment-vue-meta.json");return await Ia({cachePath:i,readFingerprint:()=>od(n,e.projectRoot,e.tsconfig),compute:()=>Eg({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function wg(e){let t=mi(e.db,e.projectRoot,e.vueFiles),n=id(e,t);return rd(e,t,n)}async function Eg(e){let t=mi(e.db,e.projectRoot,e.vueFiles),n=Ac(e.vueFiles)?await Oc({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles}):id(e,t);return rd(e,t,n)}function rd(e,t,n){let r=Uc(n.occurrences),i=Bc(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:Lg(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:Og(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function id(e,t){let n=Tg({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return kg({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function od(e,t,n){let r=e.prepare(`
339
+ `),o=new Set,a=0,s=0;for(let c of t){let u=oa(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),m=i.run(Number(d.lastInsertRowid),c.symbolId);a+=Number(m.changes)}return a}function*aa(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 sa(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function Fn(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Ul(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 ca(e,t){return q(e,t).startsWith("node_modules/")}function q(e,t){return Fl(e,t).replaceAll("\\","/")}function Gl(e){switch(_l(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 ua(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=N(t,{maxBytes:wt,inputKind:"Vue source file"}),r={text:n,lineStarts:Wl(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:Ul}}function Wl(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function ql(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 Hl(e){try{let t=JSON.parse(N(Zo(e,"package.json"),{maxBytes:me,inputKind:"project package manifest"}));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function zl(e,t,n,r){let i=q(n,r),o=la(t.name,t.version,i);return e.get(o)?.id??null}function la(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function ya(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>Kl({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Yl(e){return G(X(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),G(ya({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}async function Xl(e){return G(X(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),Ql(e)}function Kl(e){let t=ha(e.projectRoot,e.tsconfig);if(!ma(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new pa(e.dbPath);try{let r=kn(n,e.projectRoot),i=ga(fa(e.dbPath),"augment-vue-meta.json");return Ci({cachePath:i,readFingerprint:()=>Ra(n,e.projectRoot,e.tsconfig),compute:()=>Zl({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 Ql(e){let t=ha(e.projectRoot,e.tsconfig);if(!ma(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new pa(e.dbPath);try{let r=kn(n,e.projectRoot),i=ga(fa(e.dbPath),"augment-vue-meta.json");return await Oi({cachePath:i,readFingerprint:()=>Ra(n,e.projectRoot,e.tsconfig),compute:()=>ed({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function Zl(e){let t=_n(e.db,e.projectRoot,e.vueFiles),n=ba(e,t);return Sa(e,t,n)}async function ed(e){let t=_n(e.db,e.projectRoot,e.vueFiles),n=Jo(e.vueFiles)?await Yo({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles}):ba(e,t);return Sa(e,t,n)}function Sa(e,t,n){let r=ia(n.occurrences),i=na(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:ud(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:cd(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function ba(e,t){let n=td({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return nd({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function Ra(e,t,n){let r=e.prepare(`
340
340
  SELECT
341
341
  (SELECT COUNT(*) FROM documents) AS documents,
342
342
  (SELECT COUNT(*) FROM global_symbols) AS symbols,
@@ -345,13 +345,13 @@ ${l}`:""}`)}Rm(e.config,t,e.scipPath)}catch(d){if(r?.aborted)throw Fi(r,"Reindex
345
345
  (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
346
346
  (SELECT MAX(id) FROM chunks) AS maxChunkId,
347
347
  (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
348
- `).get();return{version:3,tsconfig:n,files:Xi(t),db:r}}function Tg(e){let t=Yc();return{projectRoot:e.projectRoot,context:Gc(e.projectRoot,e.configPath),symbolLookup:$c(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function kg(e){let t=[],n=Qe(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=Cg(e,i);t.push(...o.occurrences),fn(n,o)}return{occurrences:t,...n}}function Cg(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return Xc(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 Xc(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=ue(e.projectRoot,t.fileName),s=[...Wc(n.text)],c={tokens:s.filter(d=>d.start>=t.startOffset&&d.start<t.endOffset),tokenByStart:new Map(s.map(d=>[d.start,d])),tokenTextCounts:jg(s),processedStarts:new Set};return Dg({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function Dg(e){let t=[],n=Qe();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||_g(e.sourceInfo.text,r.start))continue;let i=Hc(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(u=>!zc(e.projectRoot,u.fileName));if(!a){hi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=ue(e.projectRoot,a.fileName),c=Fg(e.sourceFile,r.text,s);if(c){hi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let d=Vc(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(d===null){hi(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}ad(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,d),e.tokenContext.processedStarts.add(r.start),Mg(t,e,r,i,s,d)}return{occurrences:t,...n}}function _g(e,t){let n=e.lastIndexOf(`
349
- `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function Fg(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Xc(e,t,n){let r=Qe();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:ue(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function hi(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 yi(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 Ag(e,t){let n=yi(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=yi(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function Og(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(...yi(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function Lg(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return Ag(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function Mg(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of Ng(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&&(ad(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function ad(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 jg(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function Ng(e,t,n,r,i,o){let a=e.getDocumentHighlights?.(t,n,[t])??[],s=[];for(let c of a)if(c.fileName===t)for(let d of c.highlightSpans){let u=Gg(r,d.textSpan.start,o,i.text);u!==null&&s.push(u)}return s}function Gg(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=gi(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function gI(e){let{projectRoot:t,onStatus:n=console.log}=e,r=e.maxHeapMb??Hg(process.env.NODE_OPTIONS)??8192,i=e.skipAutoInstall===!0||e.installMissing!==!0,o=Yg(e),a=Date.now(),s=_();hn(E(o.outputScip),{recursive:!0}),hn(E(o.outputDb),{recursive:!0});let c=e.languages??Qn(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 d=Sn(o.metaPath),u=w("reindex.fingerprint",()=>Qi(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath},d,e.changeJournal,Cn(o.outputDb)),{languages:c.length}),l=u.fingerprint,p=u.mode==="delta"?e.changeJournal?.entries.filter(b=>b.kind!=="add").length??0:0,m=Math.max(0,(d?.files.length??0)-p);n(u.mode==="delta"?`Project fingerprint revalidated ${u.changedPaths.length} changed path(s), reused ${m} accepted file fingerprint(s), and accepted ${l.files.length} input(s)`:`Project fingerprint used full scan: ${u.reason}`);let g=await qg({opts:e,paths:o,languages:c,fingerprint:l,onStatus:n}),y=g.snapshot,v=g.releaseBuildLock,A=_d(e.trigger),T=Pe(N(E(o.outputDb),"cache-lifecycle.lock"),{waitMs:A?1e3:3e4});if(!T)throw v?.(),new jt(A?`Could not acquire scip-query cache lifecycle lock for ${E(o.outputDb)}; another refresh is publishing, so the watcher will retry.`:`Could not acquire scip-query cache lifecycle lock for ${E(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 M;try{M=await te("reindex.lock",()=>wh(N(E(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:n}),{languages:c.length})}catch(b){throw T.release(),v?.(),b}let C=null,S=Co();try{u.mode==="delta"&&Cn(o.outputDb)!==e.changeJournal?.baseGeneration&&(l=An(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),u={mode:"full",fingerprint:l,reason:"accepted-generation-changed-before-lock"},y=void 0,v?.(),v=void 0,n("Project fingerprint used full scan: accepted-generation-changed-before-lock")),Lr(o.outputDb,o.outputScip,o.metaPath);let b=Qg(E(o.outputDb));b.removed>0&&n(`Removed ${b.removed} abandoned reindex workspace(s)`);for(let I of b.errors)n(`Could not remove abandoned reindex workspace: ${I}`);let h=null,F=await te("reindex.reuse-check",async()=>(h=await Jg({opts:e,paths:o,languages:c,fingerprint:l,start:a,monotonicStart:s,onStatus:n}),h),()=>({languages:c.length,reused:h!==null}));if(F){dd({snapshot:y,paths:o,projectRoot:t,fingerprint:l,onStatus:n});let I=Hn(o.outputDb,F);return I.state==="failed"&&n(`Warning: reindex succeeded, but activity telemetry was not recorded: ${I.reason}`),_n(t,E(o.outputDb)),F}await te("reindex.scip-cli-ready",()=>gh(i,n));let x=Kg(o);C=x.runDir;let P,k=await te("reindex.fresh",async()=>(P=await Zg({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:x,fingerprint:l,start:a,monotonicStart:s,maxHeapMb:r,skipAutoInstall:i,onStatus:n,writeTelemetry:S}),P),()=>({languages:c.length,reused:P?.reused,skipped:P?.skipped.length}));dd({snapshot:y,paths:o,projectRoot:t,fingerprint:l,onStatus:n});let f=Hn(o.outputDb,k);return f.state==="failed"&&n(`Warning: reindex succeeded, but activity telemetry was not recorded: ${f.reason}`),_n(t,E(o.outputDb)),k}catch(b){let h=xn({trigger:e.trigger,result:"failed",start:a,monotonicStart:s,error:b instanceof Error?b.message:String(b)});Ld(o.metaPath,h);let F=To(o.outputDb,h);throw F.state==="failed"&&n(`Warning: failed reindex activity telemetry was not recorded: ${F.reason}`),b}finally{C&&_e(C,{recursive:!0,force:!0}),M(),T.release(),v?.()}}async function qg(e){let{opts:t,paths:n,languages:r,fingerprint:i,onStatus:o}=e,a=t.projectRoot;if(!(t.skipIfUnchanged!==!1&&!Ts(a,n.outputDb)&&sd(n.outputScip)===sd(N(E(n.outputDb),"index.scip"))))return{snapshot:void 0,releaseBuildLock:void 0};let c=Ft(a),d=c?.clean?nn(c,i):void 0;if(c&&!c.clean&&!ud(n))return cd({context:c,languages:r,opts:t,paths:n,fingerprint:i,projectRoot:a,onStatus:o,successMessage:"dirty worktree reindex",failurePrefix:"Shared baseline fork failed"}),{snapshot:d,releaseBuildLock:void 0};if(!d)return{snapshot:void 0,releaseBuildLock:void 0};let u=ce(d);if(u){if(!Wg(n,i))try{rn({snapshot:d,manifest:u,targetCacheDir:E(n.outputDb),targetProjectRoot:a}),o(`Attached shared generation ${d.generationId.slice(0,12)}`)}catch(p){o(`Shared generation attach failed; continuing locally: ${Fe(p)}`)}return{snapshot:d,releaseBuildLock:void 0}}c&&!ud(n)&&cd({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 l=await Ds(d);if(l.kind==="owner")return{snapshot:d,releaseBuildLock:l.release};if(l.kind==="generation-ready"){let p=ce(d);if(p)try{rn({snapshot:d,manifest:p,targetCacheDir:E(n.outputDb),targetProjectRoot:a,action:"waited"}),o(`Attached shared generation ${d.generationId.slice(0,12)} after waiting`)}catch(m){o(`Shared generation attach failed after waiting; continuing locally: ${Fe(m)}`)}}else o("Shared generation build lock timed out; continuing with an isolated local reindex");return{snapshot:d,releaseBuildLock:void 0}}function cd(e){let t=ks(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{rn({snapshot:t.snapshot,manifest:t.manifest,targetCacheDir:E(e.paths.outputDb),targetProjectRoot:e.projectRoot,persistLease:!1}),_s(t.snapshot,E(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: ${Fe(n)}`)}}function dd(e){if(e.snapshot)try{let t=Ft(e.projectRoot),n=t?nn(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=Cs({snapshot:e.snapshot,sourceCacheDir:E(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let i=Ft(e.projectRoot);return(i?nn(i,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}});qr(e.snapshot,E(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: ${Fe(t)}`)}}function Wg(e,t){if(!H(e.outputScip)||!H(e.outputDb)||Od(e.metaPath,t)===null)return!1;let n=K(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function ud(e){if(!H(e.outputScip)||!H(e.outputDb)||!Le(e.metaPath))return!1;let t=K(e.outputDb,e.metaPath);return t.state!=="invalid"&&t.state!=="drifted"}function Fe(e){return e instanceof Error?e.message:String(e)}function Hg(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 zg(e,t){return[(e??"").replace(/(?:^|\s)--max[-_]old[-_]space[-_]size(?:=|\s+)\d+/gu," ").trim(),`--max-old-space-size=${t}`].filter(Boolean).join(" ")}async function Ri(e,t,n,r,i,o,a,s=!1){try{await Ra(_o({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 Yg(e){let t=e.outputScip??N(e.projectRoot,"index.scip"),n=e.outputDb??N(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:N(E(n),"meta.json")}}async function Jg(e){let t=K(e.paths.outputDb,e.paths.metaPath),n=Od(e.paths.metaPath,e.fingerprint);if(e.opts.skipIfUnchanged===!1||!H(e.paths.outputScip)||!H(e.paths.outputDb)||n===null||t.state==="invalid"||t.state==="drifted")return null;let r=qt(e.paths.outputDb,e.fingerprint,e.languages);if(r.state!=="complete")return e.onStatus(xi("Accepted SQLite index",r)),null;se(he(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await Ri(e.opts.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0),K(e.paths.outputDb,e.paths.metaPath).state==="drifted"&&(Zt(e.paths.outputDb,e.paths.metaPath),e.onStatus("Published refreshed SQLite generation after post-index augmentation")),n==="operational-config-compatible"&&(Ah(e.paths.metaPath,e.fingerprint,e.languages,e.opts),Zt(e.paths.outputDb,e.paths.metaPath),e.onStatus("Migrated operational .scipquery.json metadata without rerunning language indexers."));let i=_()-e.monotonicStart,o=xn({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return Ld(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:Xg(e.paths,e.languages,e.opts,e.fingerprint)}}function Xg(e,t,n,r){let i=Ii(r,t,n);return t.map(o=>({id:o,language:o,reused:!0,strategy:"reused",fingerprint:Rt(i[o]),outputBytes:Ae(vi(e.outputDb,o)),durationMs:0}))}function Kg(e){let t=Bg(N(E(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:N(t,mn(e.outputScip)),tempOutputDb:N(t,mn(e.outputDb)),tempMetaPath:N(t,mn(e.metaPath))}}function Qg(e){let t=[],n;try{n=Sd(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[Fe(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{_e(N(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${Fe(o)}`)}return{removed:r,errors:t}}async function Zg(e){let t={...process.env,NODE_OPTIONS:zg(process.env.NODE_OPTIONS,e.maxHeapMb)},n,r=await te("reindex.language-indexers",async()=>(n=await th(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:a,languageFingerprints:s,shards:c,typescriptProjectShardContext:d,incrementalTypeScript:u}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),eh({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let m=await te("reindex.publish",()=>lh(e,i,o,a,s,d),{mode:"metadata-only",languages:i.length,reused:a.length}),g=m.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(y=>y.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:m,shards:c,writeTelemetry:e.writeTelemetry}}let l=await te("reindex.publish",()=>dh(e,t,i,o,a,s,d,u),{mode:u?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),p=l.durationMs;return e.onStatus(`Done in ${(p/1e3).toFixed(1)}s`),{languages:i.map(m=>m.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:p,reused:!1,skipped:o,lastRefresh:l,shards:c,writeTelemetry:e.writeTelemetry}}function eh(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!H(e.run.paths.outputScip)||!H(e.run.paths.outputDb))return!1;let t=K(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 th(e,t){let n=e.opts.skipIfUnchanged===!1,r=ah({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[f,I]of r)I.reused&&r.set(f,{...I,reused:!1,reason:"forced reindex requested"});let i=[],o=new Set;for(let[f,I]of r)I.reused&&(i.push({language:f,scipPath:I.scipPath}),o.add(f));for(let f of o)e.onStatus(`Reusing cached ${f} SCIP shard (language inputs unchanged).`);let a=r.get("typescript"),s=K(e.paths.outputDb,e.paths.metaPath),c=Le(e.paths.metaPath),d=s.state==="legacy"||s.state==="current",u=c?.scipCompanion!=="deferred"&&(s.state!=="current"||s.generation.publication?.scipCompanion!=="deferred"),l;n&&a&&!a.reused&&(l="forced reindex rebuilds from the compilers");let p=!n&&a&&!a.reused&&d?Sc({projectRoot:e.projectRoot,cacheDir:E(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:a.scipPath,candidateShardPath:Oe(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:Oe(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:u,previousSnapshot:Sn(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus,onUnavailable:f=>{l=f}}):null,m=new Set(p?["typescript"]:[]);if(e.opts.allowExpensiveRebuild===!1){let f=e.languages.filter(I=>!o.has(I)&&!m.has(I));if(f.length>0){let I=f.length===1&&f[0]==="typescript"&&l?`: ${l}`:"";throw new Error(`Incremental indexing is unavailable for ${f.join(", ")}${I}. 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 g=p||o.has("typescript")?void 0:nh(e,r),y=g&&n?{...g,classification:new Map([...g.classification].map(([f,I])=>[f,I.reused?{...I,reused:!1,reason:"forced reindex requested"}:I])),reusedProjects:[],missedProjectIds:new Set(g.allProjects.map(f=>`typescript:${f}`))}:g,{preparedRuns:v,skippedLanguages:A,languageOutputScipPaths:T}=hh({languages:e.languages.filter(f=>!o.has(f)&&!m.has(f)),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:y?.allProjects,typescriptShardCostDir:E(e.paths.outputDb),clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),M=y?v.filter(f=>f.language!=="typescript"||y.missedProjectIds.has(f.id)):v,C=await Ec(M,e.projectRoot,e.onStatus,e.opts.indexerConcurrency,e.opts.signal);if(to())for(let f of C)no({type:"span",name:`reindex.language-indexer.${f.id}`,durationMs:Math.round(f.durationMs),ok:!f.skipped,language:f.language,indexerCommand:f.command,outputBytes:f.outputBytes,measurement:"indexer-run-result"});Sh(E(e.paths.outputDb),e.projectRoot,M,C);let S=[];if(y){ih(e.paths.outputDb,C,e.writeTelemetry);let f=T.typescript??e.tempPaths.tempOutputScip;S=oh({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:f,reusedProjects:y.reusedProjects,writeTelemetry:e.writeTelemetry})}let b=[...C,...S],{indexedOutputs:h}=Rh(b,A),F=p?[{language:"typescript",scipPath:p.scipPath}]:[],x=[...i,...F,...h];xh(x,A,e.languages,e.opts.allowPartial,e.onStatus);let P=p?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:p.scipPath,outputScipPath:p.scipPath,durationMs:p.durationMs,command:"watch-service:typescript-index",outputBytes:Ae(p.scipPath)??void 0,producedOutputBytes:Ae(p.affectedScipPath)??void 0}]:[],k=sh(r,[...C,...P],y?{outputDb:e.paths.outputDb,classification:y.classification}:void 0,l);return{indexedOutputs:x,skippedLanguages:A,reusedLanguages:[...o],languageFingerprints:ch(r,e.languages),shards:k,typescriptProjectShardContext:y?{projects:y.allProjects,fingerprints:y.fingerprints}:void 0,incrementalTypeScript:p??void 0}}function nh(e,t){let n=t.get("typescript");if(!n||n.reused||n.cacheIntegrityFailed||e.opts.typescriptProjectMode!=="workspace")return;let r=Ee(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Ca(e.projectRoot,r),o=Ea(n.fingerprint.files,r),a=Ta(r,i),s=ka(r,o,a),c=Le(e.paths.metaPath),u=rh(c,s,g=>H(bn(e.paths.outputDb,g))),l=[...u.entries()].filter(([,g])=>g.reused).map(([g])=>g),p=new Set(l),m=new Set(r.filter(g=>!p.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:s,classification:u,reusedProjects:l,missedProjectIds:m}}function rh(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===Ne&&En(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(W(a)!==W(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 ih(e,t,n){for(let r of t){if(r.skipped||!r.id.startsWith("typescript:"))continue;let i=r.id.slice(11),o=bn(e,i);hn(E(o),{recursive:!0}),ke(n,Te(r.scipPath,o))}}function oh(e){return e.reusedProjects.map((t,n)=>{let r=bn(e.outputDb,t),i=Oe(e.tempOutputScip,"typescript-project-cached",n);return ke(e.writeTelemetry,Te(r,i)),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Ae(i)??void 0}})}function ah(e){let t=Le(e.paths.metaPath),n=Ii(e.projectFingerprint,e.languages,e),r=t&&H(e.paths.outputDb)?qt(e.paths.outputDb,e.projectFingerprint,e.languages):null,i=new Map;for(let o of e.languages){let a=vi(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!==Ne){i.set(o,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:s,scipPath:a});continue}if(!En(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(!H(a)){i.set(o,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:a});continue}let d=o==="typescript"?Dh(e.projectRoot,c):c;if(W(d)!==W(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:xi("accepted SQLite index",r),cacheIntegrityFailed:!0,fingerprint:s,scipPath:a});continue}i.set(o,{reused:!0,fingerprint:s,scipPath:a})}return i}function sh(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:Rt(a.fingerprint),outputBytes:Ae(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?Rt(c.fingerprint):a?Rt(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:Rt(a.fingerprint),outputBytes:Ae(bn(n.outputDb,o)),durationMs:0});return i}function Rt(e){return $g("sha256").update(W(e)).digest("hex").slice(0,16)}function Ae(e){try{return bi(e).size}catch{return null}}function ch(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}async function dh(e,t,n,r,i,o,a,s){z(e.opts.signal,"Reindex cancelled by its owner.");let c=!s||s.completeScipUpdated,d=!1;c&&(d=w("reindex.publish.scip-output",()=>{let S=mh({run:e,indexedOutputs:n,incrementalTypeScript:s,typescriptReused:i.includes("typescript")});return ld(e.paths.outputDb,S,e.writeTelemetry),pd(S,e.tempPaths.tempOutputScip,e.onStatus)}));let u=await te("reindex.publish.sqlite-output",()=>Ih({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:d,materializeFullFallback:async()=>{if(z(e.opts.signal,"Reindex cancelled by its owner."),!s||s.completeScipUpdated)return d;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),oi({cacheDir:E(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let S=n.map(b=>b.language==="typescript"?{language:b.language,scipPath:s.candidateScipPath}:b);return ld(e.paths.outputDb,S,e.writeTelemetry),d=pd(S,e.tempPaths.tempOutputScip,e.onStatus),d}}));z(e.opts.signal,"Reindex cancelled by its owner."),w("reindex.publish.auxiliary-documents",()=>{se(he(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus})}),await te("reindex.publish.runtime-boundaries",async()=>{let S=s?.plan.mode==="full-project",b=s?.dependencyGraphUnchanged===!0;S?e.onStatus("Rebuilding compiler-derived runtime-boundary relationships while retaining unchanged per-file extraction facts."):b&&e.onStatus("Reusing runtime-boundary relationships because TypeScript semantics are unchanged."),await Ri(e.projectRoot,e.tempPaths.tempOutputDb,e.tempPaths.tempOutputScip,e.onStatus,b,b?void 0:S?s?.changedFiles:s?.affectedFiles,N(E(e.paths.outputDb),Zi),S)});let l=w("reindex.publish.sqlite-layout",()=>lr(e.tempPaths.tempOutputDb,{analyze:uh(s,u.mode)}));l.added.length>0&&e.onStatus(`Added SQLite query indexes: ${l.added.join(", ")}`),l.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${l.removed.join(", ")}`),w("reindex.publish.coverage",()=>vd(e,e.tempPaths.tempOutputDb,n.map(S=>S.language)));let p,m=null;u.mode==="incremental"&&s&&w("reindex.publish.reference-fragments",()=>{if(s.dependencyGraphUnchanged){let h=new Z({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});try{m=Ln(h),e.onStatus("Preserved exact TypeScript reference fragments and dependency relationships because only trivia changed.")}finally{h.close()}return}let S=null,b=null;try{S=w("reindex.publish.reference-fragments.open-candidate",()=>new Z({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip})),b=w("reindex.publish.reference-fragments.open-evidence",()=>new Z({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip})),p=s.dependencyGraphSnapshot?w("reindex.publish.reference-fragments.dependency-graph",()=>co(S,s.dependencyGraphSnapshot,s.affectedFiles,s.deletedFiles))??void 0:void 0;let h=new Set(s.deletedFiles),F=h.size===0?s.referenceFragmentsByFile:new Map([...s.referenceFragmentsByFile].filter(([P])=>!h.has(P))),x=w("reindex.publish.reference-fragments.seed",()=>yo(S,e.fingerprint,F,b,p,new Set(s.affectedFiles)));e.onStatus(`Cached exact TypeScript reference fragments for ${x.affectedFiles} affected document(s) and carried ${x.carriedFiles} unaffected document(s) forward.`),x.skippedAffectedFiles>0&&e.onStatus(`Skipped exact TypeScript reference fragment prefill for ${x.skippedAffectedFiles} affected document(s) whose semantic identity was unavailable.`)}catch(h){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${h instanceof Error?h.message:String(h)}.`)}finally{S?.close(),b?.close()}});let g=Sn(e.paths.metaPath),y=w("reindex.publish.affected-shadow",()=>u.mode==="incremental"&&s?Ph(s,u.changedDocumentPaths):Xn({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:g,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"})),v=xn({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(S=>S.language),skipped:[...r]}),A=u.mode==="incremental"&&u.scipCompanion==="deferred",{metadata:T,pruneProjects:M}=xd({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:o,typescriptProjectShardContext:a,lastRefresh:v});T.scipCompanion=A?"deferred":"current",w("reindex.publish.metadata",()=>{Id(e),Pd(e.paths.outputDb,M),Rn(e.tempPaths.tempMetaPath,T)});let C=w("reindex.publish.generation-handoff",()=>Qt({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:u.mode==="incremental"&&u.scipCompanion==="deferred",publication:u.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:u.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:u.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:u.patchDurationMs,scipCompanion:u.scipCompanion,...u.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:u.converterDurationMs,scipCompanion:"current",...u.fallbackReason?{fallbackReason:u.fallbackReason}:{}}}));return C.achievedDurability==="file-flushed"&&e.onStatus(`Published local generation ${C.currentGeneration.slice(0,12)} (file-flushed; directory sync unsupported)`),u.mode==="incremental"&&s&&w("reindex.publish.dependency-graph",()=>{let S=null;try{S=new Z({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let b=s.plan.mode==="full-project"&&s.plan.reasons.length===0?s.changedFiles:s.affectedFiles,h=!1;if(s.dependencyGraphUnchanged){let F=Ln(S),x=m&&F?eo(S,"file-dependency-graph",m,F):0;h=x>0,e.onStatus(h?`Carried ${x} 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?h=so(S,s.dependencyGraphSnapshot,b,p):Lt(S);s.dependencyGraphUnchanged||e.onStatus(h?`Carried the dependency graph forward by replacing ${b.length} changed dependency owner(s).`:"Materialized a fresh dependency graph for the accepted generation because no compatible prior graph was available.")}catch(b){e.onStatus(`Dependency graph carry-forward unavailable: ${b instanceof Error?b.message:String(b)}. The next graph consumer will rebuild it.`)}finally{S?.close()}}),w("reindex.publish.cleanup",()=>{ss(E(e.paths.outputDb),u.mode==="incremental"&&u.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),ts(E(e.paths.outputDb),s?.completeScipUpdated?[s.nextFragmentGeneration]:[])}),w("reindex.publish.shadow-telemetry",()=>Rd(e.paths.outputDb,y,e.onStatus)),v}function uh(e,t){return t!=="incremental"||!e||e.plan.mode==="full-project"?!0:e.affectedFiles.length*20>=e.projectFileCount}async function lh(e,t,n,r,i,o){let a=Sn(e.paths.metaPath),s=null;try{ke(e.writeTelemetry,Te(e.paths.outputDb,e.tempPaths.tempOutputDb))}catch(p){s=Lo("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}se(he(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await Ri(e.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0);let c=lr(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(", ")}`),vd(e,e.paths.outputDb,t.map(p=>p.language)),s??=Xn({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,refreshResult:"reused"});let d=xn({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:u,pruneProjects:l}=xd({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:d});return Id(e),Pd(e.paths.outputDb,l),Rn(e.paths.metaPath,u),Zt(e.paths.outputDb,e.paths.metaPath),Rd(e.paths.outputDb,s,e.onStatus),d}function Sn(e){return Ze(Le(e)?.fingerprint)}function Rd(e,t,n){try{Mo(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 xd(e){let t=ph({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:Ne,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 Id(e){z(e.opts.signal,"Reindex cancelled by its owner.");let t=Ki(e.projectRoot,e.fingerprint);if(W(t)===W(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=>W(n.get(o))!==W(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 vd(e,t,n){let r=qt(t,e.fingerprint,n);if(r.state!=="complete")throw new Error(`${xi("Candidate SQLite index",r)} Refusing to publish it.`)}function xi(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 ph(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=Le(e.metaPath),n=t?.version===Ne?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 Pd(e,t){let n=Ad(e);if(t===null){_e(n,{recursive:!0,force:!0});return}let r;try{r=Sd(n)}catch{return}for(let i of fh(r,t))_e(N(n,i),{force:!0})}function fh(e,t){let n=new Set(t.map(r=>`${gr(r)}.scip`));return e.filter(r=>!n.has(r))}function mh(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=K(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":Le(e.run.paths.metaPath)?.scipCompanion==="deferred")||!r)return[...e.indexedOutputs];let o=Oe(e.run.tempPaths.tempOutputScip,"typescript-deferred",0);return e.run.onStatus("Materializing the deferred whole TypeScript SCIP companion for complete publication..."),oi({cacheDir:E(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 ld(e,t,n){for(let r of t){let i=vi(e,r.language);hn(E(i),{recursive:!0}),r.scipPath!==i&&ke(n,Te(r.scipPath,i))}}async function gh(e,t){if(!qn()){if(Ug()==="win32")throw new Error("The scip CLI was not found. On Windows it ships via the npm sidecar package scip-query-scip-windows (installed automatically with scip-query). Reinstall scip-query with optional dependencies enabled, or follow 'scip-query setup' guidance for the exact sidecar package version, or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(e)throw new Error(`The scip CLI is required but not found on PATH.
348
+ `).get();return{version:3,tsconfig:n,files:rr(t),db:r}}function td(e){let t=ua();return{projectRoot:e.projectRoot,context:ea(e.projectRoot,e.configPath),symbolLookup:ta(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function nd(e){let t=[],n=Te(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=rd(e,i);t.push(...o.occurrences),ft(n,o)}return{occurrences:t,...n}}function rd(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return da(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 da(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=q(e.projectRoot,t.fileName),s=[...aa(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:dd(s),processedStarts:new Set};return id({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function id(e){let t=[],n=Te();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||od(e.sourceInfo.text,r.start))continue;let i=sa(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(l=>!ca(e.projectRoot,l.fileName));if(!a){Cn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=q(e.projectRoot,a.fileName),c=ad(e.sourceFile,r.text,s);if(c){Cn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=ra(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){Cn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}xa(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),ld(t,e,r,i,s,u)}return{occurrences:t,...n}}function od(e,t){let n=e.lastIndexOf(`
349
+ `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function ad(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function da(e,t,n){let r=Te();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:q(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function Cn(e,t,n,r,i,o){if(e.skippedReferences++,e.skippedReferenceReasons[o]++,e.skippedReferenceSamples.filter(s=>s.reason===o&&s.sourceFile===r).length>=2)return;let a=t.positionAt(n,i.start);e.skippedReferenceSamples.push({sourceFile:r,sourceLine:a.line,sourceStartChar:a.character,sourceEndChar:a.character+i.text.length,token:i.text,reason:o})}function On(e,t){let n=new Map;for(let o of e){let a=n.get(o.sourceFile)??[];a.push(o),n.set(o.sourceFile,a)}let r=[...n.keys()].sort(),i=[];for(let o=0;i.length<t;o++){let a=!1;for(let s of r){let c=n.get(s)?.[o];if(c&&(i.push(c),a=!0,i.length===t))break}if(!a)break}return i}function sd(e,t){let n=On(e.filter(o=>o.sourceFile!==o.definitionFile),Math.ceil(t/2)),r=new Set(n.map(o=>`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),i=On(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function cd(e,t){let n=[...new Set(e.map(i=>i.reason))].sort(),r=[];for(let[i,o]of n.entries()){let a=n.length-i,s=Math.ceil((t-r.length)/a);r.push(...On(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function ud(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return sd(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function ld(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of pd(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(a))continue;let s=t.tokenContext.tokenByStart.get(a);s&&(xa(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function xa(e,t,n,r,i,o,a){let s=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,sourceToken:i.text,definitionFile:o,symbolId:a})}function dd(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function pd(e,t,n,r,i,o){let a=e.getDocumentHighlights?.(t,n,[t])??[],s=[];for(let c of a)if(c.fileName===t)for(let u of c.highlightSpans){let l=md(r,u.textSpan.start,o,i.text);l!==null&&s.push(l)}return s}function md(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=Fn(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function ph(e){let{projectRoot:t,onStatus:n=console.log}=e,r=e.maxHeapMb??ri(process.env.NODE_OPTIONS)??8192,i=e.skipAutoInstall===!0||e.installMissing!==!0,o=bd(e),a=Date.now(),s=F();yt(v(o.outputScip),{recursive:!0}),yt(v(o.outputDb),{recursive:!0});let c=e.languages??Ut(t);if(c.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");n(`Detected languages: ${c.join(", ")}`);let u=bt(o.metaPath),l=I("reindex.fingerprint",()=>ar(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath},u,e.changeJournal,_t(o.outputDb)),{languages:c.length}),d=l.fingerprint,m=l.mode==="delta"?e.changeJournal?.entries.filter(S=>S.kind!=="add").length??0:0,f=Math.max(0,(u?.files.length??0)-m);n(l.mode==="delta"?`Project fingerprint revalidated ${l.changedPaths.length} changed path(s), reused ${f} accepted file fingerprint(s), and accepted ${d.files.length} input(s)`:`Project fingerprint used full scan: ${l.reason}`);let y=await yd({opts:e,paths:o,languages:c,fingerprint:d,onStatus:n}),b=y.snapshot,k=y.releaseBuildLock,O=Ja(e.trigger),E=Xn(D(v(o.outputDb),"cache-lifecycle.lock"),{waitMs:O?1e3:3e4});if(!E)throw k?.(),new ze(O?`Could not acquire scip-query cache lifecycle lock for ${v(o.outputDb)}; another refresh is publishing, so the watcher will retry.`:`Could not acquire scip-query cache lifecycle lock for ${v(o.outputDb)}. A watch daemon or another reindex may hold it. Run "scip-query watch --stop", retry the reindex, then restart with "scip-query watch --daemon".`);let C;try{C=await B("reindex.lock",()=>Xd(D(v(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:n}),{languages:c.length})}catch(S){throw E.release(),k?.(),S}let w=null,h=ai();try{l.mode==="delta"&&_t(o.outputDb)!==e.changeJournal?.baseGeneration&&(d=ir(t,c,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),l={mode:"full",fingerprint:d,reason:"accepted-generation-changed-before-lock"},b=void 0,k?.(),k=void 0,n("Project fingerprint used full scan: accepted-generation-changed-before-lock")),Xr(o.outputDb,o.outputScip,o.metaPath);let S=vd(v(o.outputDb));S.removed>0&&n(`Removed ${S.removed} abandoned reindex workspace(s)`);for(let x of S.errors)n(`Could not remove abandoned reindex workspace: ${x}`);let g=null,_=await B("reindex.reuse-check",async()=>(g=await Rd({opts:e,paths:o,languages:c,fingerprint:d,start:a,monotonicStart:s,onStatus:n}),g),()=>({languages:c.length,reused:g!==null}));if(_){Ea({snapshot:b,paths:o,projectRoot:t,fingerprint:d,onStatus:n});let x=Wt(o.outputDb,_);return x.state==="failed"&&n(`Warning: reindex succeeded, but activity telemetry was not recorded: ${x.reason}`),Ct(t,v(o.outputDb)),_}kr()&&await B("reindex.scip-cli-ready",()=>Vd(i,n));let R=Pd(o);w=R.runDir;let P,T=await B("reindex.fresh",async()=>(P=await Id({opts:e,languages:c,projectRoot:t,paths:o,tempPaths:R,fingerprint:d,start:a,monotonicStart:s,maxHeapMb:r,skipAutoInstall:i,onStatus:n,writeTelemetry:h}),P),()=>({languages:c.length,reused:P?.reused,skipped:P?.skipped.length}));Ea({snapshot:b,paths:o,projectRoot:t,fingerprint:d,onStatus:n});let p=Wt(o.outputDb,T);return p.state==="failed"&&n(`Warning: reindex succeeded, but activity telemetry was not recorded: ${p.reason}`),Ct(t,v(o.outputDb)),T}catch(S){let g=Pt({trigger:e.trigger,result:"failed",start:a,monotonicStart:s,error:S instanceof Error?S.message:String(S)});Qa(o.metaPath,g);let _=Gr(o.outputDb,g);throw _.state==="failed"&&n(`Warning: failed reindex activity telemetry was not recorded: ${_.reason}`),S}finally{w&&se(w,{recursive:!0,force:!0}),C(),E.release(),k?.()}}async function yd(e){let{opts:t,paths:n,languages:r,fingerprint:i,onStatus:o}=e,a=t.projectRoot;if(!(t.skipIfUnchanged!==!1&&!Kr(a,n.outputDb)&&Pa(n.outputScip)===Pa(D(v(n.outputDb),"index.scip"))))return{snapshot:void 0,releaseBuildLock:void 0};let c=Ve(a),u=c?.clean?Ke(c,i):void 0;if(c&&!c.clean&&!Ta(n))return Ia({context:c,languages:r,opts:t,paths:n,fingerprint:i,projectRoot:a,onStatus:o,successMessage:"dirty worktree reindex",failurePrefix:"Shared baseline fork failed"}),{snapshot:u,releaseBuildLock:void 0};if(!u)return{snapshot:void 0,releaseBuildLock:void 0};let l=qt(u);if(l){if(!Sd(n,i))try{Qe({snapshot:u,manifest:l,targetCacheDir:v(n.outputDb),targetProjectRoot:a}),o(`Attached shared generation ${u.generationId.slice(0,12)}`)}catch(m){o(`Shared generation attach failed; continuing locally: ${ce(m)}`)}return{snapshot:u,releaseBuildLock:void 0}}c&&!Ta(n)&&Ia({context:c,languages:r,opts:t,paths:n,fingerprint:i,projectRoot:a,onStatus:o,successMessage:"cold worktree reindex",failurePrefix:"Compatible shared baseline fork failed",compatible:!0});let d=await ei(u);if(d.kind==="owner")return{snapshot:u,releaseBuildLock:d.release};if(d.kind==="generation-ready"){let m=qt(u);if(m)try{Qe({snapshot:u,manifest:m,targetCacheDir:v(n.outputDb),targetProjectRoot:a,action:"waited"}),o(`Attached shared generation ${u.generationId.slice(0,12)} after waiting`)}catch(f){o(`Shared generation attach failed after waiting; continuing locally: ${ce(f)}`)}}else o("Shared generation build lock timed out; continuing with an isolated local reindex");return{snapshot:u,releaseBuildLock:void 0}}function Ia(e){let t=Qr(e.context,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath},e.fingerprint);if(t)try{Qe({snapshot:t.snapshot,manifest:t.manifest,targetCacheDir:v(e.paths.outputDb),targetProjectRoot:e.projectRoot,persistLease:!1}),ni(t.snapshot,v(e.paths.outputDb)),e.onStatus(`Forked ${e.compatible?"compatible ":""}shared baseline ${t.snapshot.generationId.slice(0,12)} for ${e.successMessage}`)}catch(n){e.onStatus(`${e.failurePrefix}; continuing locally: ${ce(n)}`)}}function Ea(e){if(e.snapshot)try{let t=Ve(e.projectRoot),n=t?Ke(t,e.fingerprint):void 0;if(!n||n.generationId!==e.snapshot.generationId){e.onStatus("Skipped shared generation publication because the worktree changed during indexing");return}let r=Zr({snapshot:e.snapshot,sourceCacheDir:v(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let i=Ve(e.projectRoot);return(i?Ke(i,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}});ti(e.snapshot,v(e.paths.outputDb),"built"),e.onStatus(r.kind==="published"?`Published shared generation ${e.snapshot.generationId.slice(0,12)} (${r.achievedDurability})`:`Shared generation ${e.snapshot.generationId.slice(0,12)} was already available (${r.achievedDurability})`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${ce(t)}`)}}function Sd(e,t){if(!j(e.outputScip)||!j(e.outputDb)||Ka(e.metaPath,t)===null)return!1;let n=Y(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function Ta(e){if(!j(e.outputScip)||!j(e.outputDb)||!de(e.metaPath))return!1;let t=Y(e.outputDb,e.metaPath);return t.state!=="invalid"&&t.state!=="drifted"}function ce(e){return e instanceof Error?e.message:String(e)}async function Mn(e,t,n,r,i,o,a,s=!1){try{await Fi(ci({indexPath:n,evidenceDbPath:a,reuseExisting:i,affectedFiles:o,forceDerivedRebuild:s}),{projectRoot:e,dbPath:t,onStatus:r})}catch(c){r(`Runtime-boundary extraction unavailable: ${c instanceof Error?c.message:String(c)}.`)}}function bd(e){let t=e.outputScip??D(e.projectRoot,"index.scip"),n=e.outputDb??D(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:D(v(n),"meta.json")}}async function Rd(e){let t=Y(e.paths.outputDb,e.paths.metaPath),n=Ka(e.paths.metaPath,e.fingerprint);if(e.opts.skipIfUnchanged===!1||!j(e.paths.outputScip)||!j(e.paths.outputDb)||n===null||t.state==="invalid"||t.state==="drifted")return null;let r=Ye(e.paths.outputDb,e.fingerprint,e.languages);if(r.state!=="complete")return e.onStatus(Ln("Accepted SQLite index",r)),null;G(X(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await Mn(e.opts.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0),Y(e.paths.outputDb,e.paths.metaPath).state==="drifted"&&(Xe(e.paths.outputDb,e.paths.metaPath),e.onStatus("Published refreshed SQLite generation after post-index augmentation")),n==="operational-config-compatible"&&(ip(e.paths.metaPath,e.fingerprint,e.languages,e.opts),Xe(e.paths.outputDb,e.paths.metaPath),e.onStatus("Migrated operational .scipquery.json metadata without rerunning language indexers."));let i=F()-e.monotonicStart,o=Pt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:e.languages,skipped:[]});return Qa(e.paths.metaPath,o),e.onStatus(`Index unchanged; reused existing SQLite index in ${(i/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:i,reused:!0,skipped:[],lastRefresh:o,shards:xd(e.paths,e.languages,e.opts,e.fingerprint)}}function xd(e,t,n,r){let i=jn(r,t,n);return t.map(o=>({id:o,language:o,reused:!0,strategy:"reused",fingerprint:Ae(i[o]),outputBytes:ue(Nn(e.outputDb,o)),durationMs:0}))}function Pd(e){let t=gd(D(v(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:D(t,gt(e.outputScip)),tempOutputDb:D(t,gt(e.outputDb)),tempMetaPath:D(t,gt(e.metaPath))}}function vd(e){let t=[],n;try{n=Aa(e,{withFileTypes:!0})}catch(i){return{removed:0,errors:[ce(i)]}}let r=0;for(let i of n)if(!(!i.name.startsWith("reindex-")||!i.isDirectory()))try{se(D(e,i.name),{recursive:!0,force:!0}),r+=1}catch(o){t.push(`${i.name}: ${ce(o)}`)}return{removed:r,errors:t}}async function Id(e){let t={...process.env,NODE_OPTIONS:ii(process.env.NODE_OPTIONS,e.maxHeapMb)},n,r=await B("reindex.language-indexers",async()=>(n=await Td(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:a,languageFingerprints:s,shards:c,typescriptProjectShardContext:u,incrementalTypeScript:l}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),Ed({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let f=await B("reindex.publish",()=>Ld(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),y=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(y/1e3).toFixed(1)}s`),{languages:i.map(b=>b.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:y,reused:!0,skipped:o,lastRefresh:f,shards:c,writeTelemetry:e.writeTelemetry}}let d=await B("reindex.publish",()=>Ad(e,t,i,o,a,s,u,l),{mode:l?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),m=d.durationMs;return e.onStatus(`Done in ${(m/1e3).toFixed(1)}s`),{languages:i.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:m,reused:!1,skipped:o,lastRefresh:d,shards:c,writeTelemetry:e.writeTelemetry}}function Ed(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!j(e.run.paths.outputScip)||!j(e.run.paths.outputDb))return!1;let t=Y(e.run.paths.outputDb,e.run.paths.metaPath);if(t.state==="invalid"||t.state==="drifted")return!1;let n=new Set(e.reusedLanguages),r=new Set(e.indexedOutputs.map(i=>i.language));return e.run.languages.length>0&&r.size===e.run.languages.length&&e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(i=>n.has(i)&&r.has(i))}async function Td(e,t){let n=e.opts.skipIfUnchanged===!1,r=Cd({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath,projectFingerprint:e.fingerprint});if(n)for(let[p,x]of r)x.reused&&r.set(p,{...x,reused:!1,reason:"forced reindex requested"});let i=[],o=new Set;for(let[p,x]of r)x.reused&&(i.push({language:p,scipPath:x.scipPath}),o.add(p));for(let p of o)e.onStatus(`Reusing cached ${p} SCIP shard (language inputs unchanged).`);let a=r.get("typescript"),s=Y(e.paths.outputDb,e.paths.metaPath),c=de(e.paths.metaPath),u=s.state==="legacy"||s.state==="current",l=c?.scipCompanion!=="deferred"&&(s.state!=="current"||s.generation.publication?.scipCompanion!=="deferred"),d;n&&a&&!a.reused&&(d="forced reindex rebuilds from the compilers");let m=!n&&a&&!a.reused&&u?Do({projectRoot:e.projectRoot,cacheDir:v(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:a.scipPath,candidateShardPath:le(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:le(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:l,previousSnapshot:bt(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus,onUnavailable:p=>{d=p}}):null,f=new Set(m?["typescript"]:[]);if(e.opts.allowExpensiveRebuild===!1){let p=e.languages.filter(x=>!o.has(x)&&!f.has(x));if(p.length>0){let x=p.length===1&&p[0]==="typescript"&&d?`: ${d}`:"";throw new Error(`Incremental indexing is unavailable for ${p.join(", ")}${x}. The accepted index was preserved because whole-project rebuilds are disabled; run scip-query reindex --allow-expensive-rebuild only when you explicitly want that fallback.`)}}let y=m||o.has("typescript")?void 0:wd(e,r),b=y&&n?{...y,classification:new Map([...y.classification].map(([p,x])=>[p,x.reused?{...x,reused:!1,reason:"forced reindex requested"}:x])),reusedProjects:[],missedProjectIds:new Set(y.allProjects.map(p=>`typescript:${p}`))}:y,{preparedRuns:k,skippedLanguages:O,languageOutputScipPaths:E}=Bd({languages:e.languages.filter(p=>!o.has(p)&&!f.has(p)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,trustProjectTools:e.opts.trustProjectTools===!0,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:b?.allProjects,typescriptShardCostDir:v(e.paths.outputDb),clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),C=b?k.filter(p=>p.language!=="typescript"||b.missedProjectIds.has(p.id)):k,w=await Bo(C,e.projectRoot,e.onStatus,e.opts.indexerConcurrency,e.opts.signal);if(ur())for(let p of w)lr({type:"span",name:`reindex.language-indexer.${p.id}`,durationMs:Math.round(p.durationMs),ok:!p.skipped,language:p.language,indexerCommand:p.command,outputBytes:p.outputBytes,measurement:"indexer-run-result"});Gd(v(e.paths.outputDb),e.projectRoot,C,w);let h=[];if(b){_d(e.paths.outputDb,w,e.writeTelemetry);let p=E.typescript??e.tempPaths.tempOutputScip;h=Fd({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:p,reusedProjects:b.reusedProjects,writeTelemetry:e.writeTelemetry})}let S=[...w,...h],{indexedOutputs:g}=qd(S,O),_=m?[{language:"typescript",scipPath:m.scipPath}]:[],R=[...i,..._,...g];Hd(R,O,e.languages,e.opts.allowPartial,e.onStatus);let P=m?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:m.scipPath,outputScipPath:m.scipPath,durationMs:m.durationMs,command:"watch-service:typescript-index",outputBytes:ue(m.scipPath)??void 0,producedOutputBytes:ue(m.affectedScipPath)??void 0}]:[],T=Od(r,[...w,...P],b?{outputDb:e.paths.outputDb,classification:b.classification}:void 0,d);return{indexedOutputs:R,skippedLanguages:O,reusedLanguages:[...o],languageFingerprints:Dd(r,e.languages),shards:T,typescriptProjectShardContext:b?{projects:b.allProjects,fingerprints:b.fingerprints}:void 0,incrementalTypeScript:m??void 0}}function wd(e,t){let n=t.get("typescript");if(!n||n.reused||n.cacheIntegrityFailed||e.opts.typescriptProjectMode!=="workspace")return;let r=ne(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=$i(e.projectRoot,r),o=Li(n.fingerprint.files,r),a=ji(r,i),s=Ni(r,o,a),c=de(e.paths.metaPath),l=kd(c,s,y=>j(Rt(e.paths.outputDb,y))),d=[...l.entries()].filter(([,y])=>y.reused).map(([y])=>y),m=new Set(d),f=new Set(r.filter(y=>!m.has(y)).map(y=>`typescript:${y}`));return{allProjects:r,fingerprints:s,classification:l,reusedProjects:d,missedProjectIds:f}}function kd(e,t,n){let r=new Map;for(let i of Object.keys(t)){let o=t[i];if(!e){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:o});continue}let a=e.version===pe&&Tt(e).typescriptProjectShardReuse?e.typescriptProjectShards?.[i]:void 0;if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this project",fingerprint:o});continue}if(!n(i)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:o});continue}if(L(a)!==L(o)){r.set(i,{reused:!1,reason:"project inputs changed since last index",fingerprint:o});continue}r.set(i,{reused:!0,fingerprint:o})}return r}function _d(e,t,n){for(let r of t){if(r.skipped||!r.id.startsWith("typescript:"))continue;let i=r.id.slice(11),o=Rt(e,i);yt(v(o),{recursive:!0}),ae(n,oe(r.scipPath,o,void 0,{shareImmutable:!0}))}}function Fd(e){return e.reusedProjects.map((t,n)=>{let r=Rt(e.outputDb,t),i=le(e.tempOutputScip,"typescript-project-cached",n);return ae(e.writeTelemetry,oe(r,i,void 0,{shareImmutable:!0})),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:ue(i)??void 0}})}function Cd(e){let t=de(e.paths.metaPath),n=jn(e.projectFingerprint,e.languages,e),r=t&&j(e.paths.outputDb)?Ye(e.paths.outputDb,e.projectFingerprint,e.languages):null,i=new Map;for(let o of e.languages){let a=Nn(e.paths.outputDb,o),s=n[o];if(!t){i.set(o,{reused:!1,reason:"no reindex metadata found",fingerprint:s,scipPath:a});continue}if(t.version!==pe){i.set(o,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:s,scipPath:a});continue}if(!Tt(t).languageShardReuse||!t.languageFingerprints){i.set(o,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:s,scipPath:a});continue}let c=t.languageFingerprints[o];if(!c){i.set(o,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:s,scipPath:a});continue}if(!j(a)){i.set(o,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:a});continue}let u=o==="typescript"?tp(e.projectRoot,c):c;if(L(u)!==L(s)){i.set(o,{reused:!1,reason:"language inputs changed since last index",fingerprint:s,scipPath:a});continue}if(r?.state==="unavailable"||r?.state==="incomplete"&&r.affectedLanguages.includes(o)){i.set(o,{reused:!1,reason:Ln("accepted SQLite index",r),cacheIntegrityFailed:!0,fingerprint:s,scipPath:a});continue}i.set(o,{reused:!0,fingerprint:s,scipPath:a})}return i}function Od(e,t,n,r){let i=[];for(let[o,a]of e)a.reused&&i.push({id:o,language:o,reused:!0,strategy:"reused",fingerprint:Ae(a.fingerprint),outputBytes:ue(a.scipPath),durationMs:0});for(let o of t){let a=e.get(o.language),s=n&&o.id.startsWith("typescript:")?o.id.slice(11):null,c=s?n.classification.get(s):void 0;i.push({id:o.id,language:o.language,reused:!1,strategy:o.command==="watch-service:typescript-index"?"incremental":"full",missReason:c?.reason??a?.reason??o.skipped?.reason,fallbackReason:o.language==="typescript"?r:void 0,fingerprint:c?Ae(c.fingerprint):a?Ae(a.fingerprint):"unknown",outputBytes:o.outputBytes??null,producedOutputBytes:o.producedOutputBytes,durationMs:o.durationMs,command:o.command})}if(n)for(let[o,a]of n.classification)a.reused&&i.push({id:`typescript:${o}`,language:"typescript",reused:!0,strategy:"reused",fingerprint:Ae(a.fingerprint),outputBytes:ue(Rt(n.outputDb,o)),durationMs:0});return i}function Ae(e){return fd("sha256").update(L(e)).digest("hex").slice(0,16)}function ue(e){try{return An(e).size}catch{return null}}function Dd(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}async function Ad(e,t,n,r,i,o,a,s){$(e.opts.signal,"Reindex cancelled by its owner.");let c=!s||s.completeScipUpdated,u=!1;c&&(u=I("reindex.publish.scip-output",()=>{let h=$d({run:e,indexedOutputs:n,incrementalTypeScript:s,typescriptReused:i.includes("typescript")});return wa(e.paths.outputDb,h,e.writeTelemetry),ka(h,e.tempPaths.tempOutputScip,e.onStatus)}));let l=await B("reindex.publish.sqlite-output",()=>zd({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:u,materializeFullFallback:async()=>{if($(e.opts.signal,"Reindex cancelled by its owner."),!s||s.completeScipUpdated)return u;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),Rn({cacheDir:v(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let h=n.map(S=>S.language==="typescript"?{language:S.language,scipPath:s.candidateScipPath}:S);return wa(e.paths.outputDb,h,e.writeTelemetry),u=ka(h,e.tempPaths.tempOutputScip,e.onStatus),u}}));$(e.opts.signal,"Reindex cancelled by its owner."),I("reindex.publish.auxiliary-documents",()=>{G(X(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus})}),await B("reindex.publish.runtime-boundaries",async()=>{let h=s?.plan.mode==="full-project",S=s?.dependencyGraphUnchanged===!0;h?e.onStatus("Rebuilding compiler-derived runtime-boundary relationships while retaining unchanged per-file extraction facts."):S&&e.onStatus("Reusing runtime-boundary relationships because TypeScript semantics are unchanged."),await Mn(e.projectRoot,e.tempPaths.tempOutputDb,e.tempPaths.tempOutputScip,e.onStatus,S,S?void 0:h?s?.changedFiles:s?.affectedFiles,D(v(e.paths.outputDb),sr),h)});let d=I("reindex.publish.sqlite-layout",()=>Zt(e.tempPaths.tempOutputDb,{analyze:Md(s,l.mode)}));d.added.length>0&&e.onStatus(`Added SQLite query indexes: ${d.added.join(", ")}`),d.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${d.removed.join(", ")}`),I("reindex.publish.coverage",()=>Va(e,e.tempPaths.tempOutputDb,n.map(h=>h.language)));let m,f=null;l.mode==="incremental"&&s&&I("reindex.publish.reference-fragments",()=>{if(s.dependencyGraphUnchanged){let g=new V({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});try{f=Ot(g),e.onStatus("Preserved exact TypeScript reference fragments and dependency relationships because only trivia changed.")}finally{g.close()}return}let h=null,S=null;try{h=I("reindex.publish.reference-fragments.open-candidate",()=>new V({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip})),S=I("reindex.publish.reference-fragments.open-evidence",()=>new V({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip})),m=s.dependencyGraphSnapshot?I("reindex.publish.reference-fragments.dependency-graph",()=>gr(h,s.dependencyGraphSnapshot,s.affectedFiles,s.deletedFiles))??void 0:void 0;let g=new Set(s.deletedFiles),_=g.size===0?s.referenceFragmentsByFile:new Map([...s.referenceFragmentsByFile].filter(([P])=>!g.has(P))),R=I("reindex.publish.reference-fragments.seed",()=>Ir(h,e.fingerprint,_,S,m,new Set(s.affectedFiles)));e.onStatus(`Cached exact TypeScript reference fragments for ${R.affectedFiles} affected document(s) and carried ${R.carriedFiles} unaffected document(s) forward.`),R.skippedAffectedFiles>0&&e.onStatus(`Skipped exact TypeScript reference fragment prefill for ${R.skippedAffectedFiles} affected document(s) whose semantic identity was unavailable.`)}catch(g){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${g instanceof Error?g.message:String(g)}.`)}finally{h?.close(),S?.close()}});let y=bt(e.paths.metaPath);l.mode==="incremental"&&s||await La({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousSnapshot:y,currentSnapshot:e.fingerprint,onStatus:e.onStatus});let b=I("reindex.publish.affected-shadow",()=>l.mode==="incremental"&&s?Yd(s,l.changedDocumentPaths):Jt({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:y,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"})),k=Pt({trigger:e.opts.trigger,result:"rebuilt",start:e.start,monotonicStart:e.monotonicStart,languages:n.map(h=>h.language),skipped:[...r]}),O=l.mode==="incremental"&&l.scipCompanion==="deferred",{metadata:E,pruneProjects:C}=Na({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:o,typescriptProjectShardContext:a,lastRefresh:k});E.scipCompanion=O?"deferred":"current",I("reindex.publish.metadata",()=>{$a(e),Ba(e.paths.outputDb,C),xt(e.tempPaths.tempMetaPath,E)});let w=I("reindex.publish.generation-handoff",()=>Yr({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:l.mode==="incremental"&&l.scipCompanion==="deferred",publication:l.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:l.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:l.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:l.patchDurationMs,scipCompanion:l.scipCompanion,...l.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:l.converterDurationMs,scipCompanion:"current",...l.fallbackReason?{fallbackReason:l.fallbackReason}:{}}}));return w.achievedDurability==="file-flushed"&&e.onStatus(`Published local generation ${w.currentGeneration.slice(0,12)} (file-flushed; directory sync unsupported)`),l.mode==="incremental"&&s&&I("reindex.publish.dependency-graph",()=>{let h=null;try{h=new V({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let S=s.plan.mode==="full-project"&&s.plan.reasons.length===0?s.changedFiles:s.affectedFiles,g=!1;if(s.dependencyGraphUnchanged){let _=Ot(h),R=f&&_?cr(h,"file-dependency-graph",f,_):0;g=R>0,e.onStatus(g?`Carried ${R} unchanged dependency graph product(s) forward without rebuilding them.`:"No persisted dependency graph product required rekeying; the next graph consumer can materialize it.")}else s.dependencyGraphSnapshot?g=fr(h,s.dependencyGraphSnapshot,S,m):Ge(h);s.dependencyGraphUnchanged||e.onStatus(g?`Carried the dependency graph forward by replacing ${S.length} changed dependency owner(s).`:"Materialized a fresh dependency graph for the accepted generation because no compatible prior graph was available.")}catch(S){e.onStatus(`Dependency graph carry-forward unavailable: ${S instanceof Error?S.message:String(S)}. The next graph consumer will rebuild it.`)}finally{h?.close()}}),I("reindex.publish.cleanup",()=>{Jr(v(e.paths.outputDb),l.mode==="incremental"&&l.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),qr(v(e.paths.outputDb),s?.completeScipUpdated?[s.nextFragmentGeneration]:[])}),I("reindex.publish.shadow-telemetry",()=>ja(e.paths.outputDb,b,e.onStatus)),k}function Md(e,t){return t!=="incremental"||!e||e.plan.mode==="full-project"?!0:e.affectedFiles.length*20>=e.projectFileCount}async function Ld(e,t,n,r,i,o){let a=bt(e.paths.metaPath),s=null;try{ae(e.writeTelemetry,oe(e.paths.outputDb,e.tempPaths.tempOutputDb))}catch(m){s=pi("reused","oracle-error",`Could not snapshot the prior database: ${m instanceof Error?m.message:String(m)}`)}G(X(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),await Mn(e.projectRoot,e.paths.outputDb,e.paths.outputScip,e.onStatus,!0);let c=Zt(e.paths.outputDb);c.added.length>0&&e.onStatus(`Added SQLite query indexes: ${c.added.join(", ")}`),c.removed.length>0&&e.onStatus(`Removed redundant SQLite indexes: ${c.removed.join(", ")}`),Va(e,e.paths.outputDb,t.map(m=>m.language)),s==null&&await La({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,onStatus:e.onStatus}),s??=Jt({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,refreshResult:"reused"});let u=Pt({trigger:e.opts.trigger,result:"reused",start:e.start,monotonicStart:e.monotonicStart,languages:t.map(m=>m.language),skipped:[...n]}),{metadata:l,pruneProjects:d}=Na({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:u});return $a(e),Ba(e.paths.outputDb,d),xt(e.paths.metaPath,l),Xe(e.paths.outputDb,e.paths.metaPath),ja(e.paths.outputDb,s,e.onStatus),u}async function La(e){if(!j(e.previousDbPath))return;let t=z(e.previousSnapshot,e.currentSnapshot);if(t.changes.length===0||_e(t).fullProject)return;let n=null;try{if(n=new V({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),We(n))return;let r=await B("reindex.publish.affected-shadow.warm-sources",()=>hr(n,{yieldToEventLoop:()=>new Promise(i=>setImmediate(i))}));e.onStatus(`Persisted import products for ${r.files} document(s) before the affected-set shadow.`)}catch(r){e.onStatus(`Affected-set shadow import warm-up unavailable: ${r instanceof Error?r.message:String(r)}.`)}finally{n?.close()}}function bt(e){return Et(de(e)?.fingerprint)}function ja(e,t,n){try{mi(e,t),t.status==="evaluated"?n(`Affected-set shadow: ${(t.evaluation.recall*100).toFixed(1)}% recall; ${t.plan.affectedFiles.length} predicted, ${t.comparison.changedFiles.length} changed.`):n(`Affected-set shadow unavailable: ${t.reason}.`)}catch(r){n(`Affected-set shadow telemetry unavailable: ${r instanceof Error?r.message:String(r)}`)}}function Na(e){let t=jd({mode:e.run.opts.typescriptProjectMode,skippedLanguages:e.skippedLanguages,reusedLanguages:e.reusedLanguages,context:e.typescriptProjectShardContext,metaPath:e.run.paths.metaPath});return{metadata:{version:pe,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,sqliteLayoutVersion:1,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function $a(e){$(e.opts.signal,"Reindex cancelled by its owner.");let t=or(e.projectRoot,e.fingerprint);if(L(t)===L(e.fingerprint))return;let n=new Map(e.fingerprint.files.map(o=>[o.path,o])),r=new Map(t.files.map(o=>[o.path,o])),i=[...new Set([...n.keys(),...r.keys()])].filter(o=>L(n.get(o))!==L(r.get(o))).slice(0,5);throw new Error(`Project inputs changed during reindex (${i.join(", ")||"unknown path"}); refusing to publish artifacts built from a different filesystem snapshot.`)}function Va(e,t,n){let r=Ye(t,e.fingerprint,n);if(r.state!=="complete")throw new Error(`${Ln("Candidate SQLite index",r)} Refusing to publish it.`)}function Ln(e,t){if(t.state==="unavailable")return`${e} document coverage could not be verified (${t.reason}); rebuilding cached language shards.`;let n=t.missingPaths.length>0?` First missing path: ${t.missingPaths[0]}.`:"";return`${e} is missing ${t.missingDocumentCount} fingerprinted source document${t.missingDocumentCount===1?"":"s"}; rebuilding affected language shards.${n}`}function jd(e){if(e.mode!=="workspace")return{field:void 0,pruneProjects:null};if(e.skippedLanguages.some(t=>t.language==="typescript"))return{field:void 0,pruneProjects:null};if(e.reusedLanguages.includes("typescript")){let t=de(e.metaPath),n=t?.version===pe?t.typescriptProjectShards:void 0;return{field:n,pruneProjects:n?Object.keys(n):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function Ba(e,t){let n=Xa(e);if(t===null){se(n,{recursive:!0,force:!0});return}let r;try{r=Aa(n)}catch{return}for(let i of Nd(r,t))se(D(n,i),{force:!0})}function Nd(e,t){let n=new Set(t.map(r=>`${rn(r)}.scip`));return e.filter(r=>!n.has(r))}function $d(e){if(e.incrementalTypeScript?.completeScipUpdated)return[...e.indexedOutputs];let t=e.indexedOutputs.find(a=>a.language==="typescript");if(!t)return[...e.indexedOutputs];if(!e.typescriptReused)return[...e.indexedOutputs];let n=Y(e.run.paths.outputDb,e.run.paths.metaPath),r=n.state==="current"?n.generation.publication?.typescriptOverlayGeneration:void 0;if(!(n.state==="current"?n.generation.publication?.scipCompanion==="deferred":de(e.run.paths.metaPath)?.scipCompanion==="deferred")||!r)return[...e.indexedOutputs];let o=le(e.run.tempPaths.tempOutputScip,"typescript-deferred",0);return e.run.onStatus("Materializing the deferred whole TypeScript SCIP companion for complete publication..."),Rn({cacheDir:v(e.run.paths.outputDb),generationIdentity:r,baseShardPath:t.scipPath,candidateShardPath:o}),e.indexedOutputs.map(a=>a.language==="typescript"?{language:a.language,scipPath:o}:a)}function wa(e,t,n){for(let r of t){let i=Nn(e,r.language);yt(v(i),{recursive:!0}),r.scipPath!==i&&ae(n,oe(r.scipPath,i,void 0,{shareImmutable:!0}))}}async function Vd(e,t){let n=Fr();if(n){if(n.source==="path"&&va()!=="win32"){let r=Or();Cr(r)||(e?t(`scip on PATH reports ${r??"an unknown version"}; the reviewed version is ${He} and compatibility is unverified. Run scip-query setup --install-missing to install the reviewed release.`):(t(`scip on PATH reports ${r??"an unknown version"}; installing the reviewed ${He}.`),await Dr(t)))}return}if(va()==="win32")throw new Error("The scip CLI was not found. On Windows it ships via the npm sidecar package scip-query-scip-windows (installed automatically with scip-query). Reinstall scip-query with optional dependencies enabled, or follow 'scip-query setup' guidance for the exact sidecar package version, or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(e)throw new Error(`The scip CLI is required but not found on PATH.
350
350
  To install the reviewed version, run: scip-query reindex --install-missing
351
- Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!Wn(t))throw new Error(`The scip CLI is required but could not be installed.
352
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function hh(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?Oe(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=yh({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?wd(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function yh(e){if(e.language!=="typescript")return[gn({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.typescriptProjectMode==="workspace",n=t?e.preDiscoveredTypeScriptProjects??Ee(e.projectRoot,e.typescriptProjects):["."];return n.length===0?[gn({...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?Oe(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 d=bh(e,c);if(d)return d}return[gn({...c,...t?{projectPath:r}:{}})]}))}function Sh(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=zs(a,c=>{try{return bi(N(t,c)).size}catch{return 1}});s&&Ws(e,s)}catch{}}function bh(e,t){let n=zr(),r=Dn(e.projectRoot,"single");if(!r||!$s(r.size,n))return null;Js(e.projectRoot);let i=Ys(),o=Bs(r.size,n,i),a=e.typescriptShardCostDir?qs(e.typescriptShardCostDir):null,s=Hs(a),c=Vs({projectRoot:e.projectRoot,rootConfigPath:"tsconfig.json",inputPaths:[...r],targetFiles:n,shardCount:o,weightOf:u=>{let l=1;try{l=bi(N(e.projectRoot,u)).size}catch{}return s(u,l)}}),d=Math.min(i,c.length);return e.onStatus(`Indexing ${r.size} TypeScript inputs as ${c.length} ${a?"cost-balanced":"byte-balanced"} compiler shard(s), ${d} at a time.`),c.map((u,l)=>gn({...t,id:`typescript-compiler-shard:${l}`,label:`typescript compiler shard ${l+1}/${c.length}`,scipPath:Oe(e.tempOutputScip,"typescript-compiler-shard",l),projectPath:u.configPath,temporaryProjectConfigs:[{path:u.configPath,content:u.content}],boundedConcurrency:d,outputComposition:"protobuf-concatenate",shardInputPaths:u.inputPaths}))}function gn(e){let t=Bt(e.language),n=it(t),r=Nn(t,e.projectRoot),i=e.trustProjectTools&&r?lo(t,e.projectRoot):null,o=Ue(t);if(!i&&!o&&r){let u=`${n} is available only as repository-local code at ${r}. Review that exact tool and rerun with --trust-project-tools.`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}if(!i&&!o&&!jn(t)){if(e.skipAutoInstall){let u=`${n} not found on PATH. To install the reviewed version, run: scip-query reindex --install-missing${t.installUrl?` (manual source: ${t.installUrl})`:""}`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!li(t,e.onStatus)){let u=`${n} could not be auto-installed. ${t.installUrl?`Install manually from ${t.installUrl}`:`Install ${n} and put it on PATH.`}`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}}let a=i?.canonicalPath??Ue(t);if(!a){let u=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}let{binary:s,args:c}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:a,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0}),d=Yo({language:e.language,projectPath:e.projectPath,pnpmWorkspaces:e.pnpmWorkspaces});if(i&&!i.executable){let u=`${i.relativePath} is not executable; refusing project-local indexer.`;return e.onStatus(`Skipping ${e.language}: ${u}`),{skipped:{language:e.language,reason:u}}}return i&&e.onStatus(`Trusted project-local ${e.language} indexer ${i.relativePath} (${i.sha256.slice(0,12)}\u2026, ${i.canonicalPath}).`),{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:a,binary:s,args:c,env:Gn(t,e.env,a),...d===void 0?{}:{temporaryRootConfigContent:d},...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 Rh(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)wd(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?ca(o.scipPaths,o.outputScipPath):ar(o.scipPaths,o.outputScipPath),i.push({language:o.language,scipPath:o.outputScipPath});else{let a=o.scipPaths[0];a!==o.outputScipPath&&bd(a,o.outputScipPath),i.push({language:o.language,scipPath:o.outputScipPath})}return{indexedOutputs:i}}function wd(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 xh(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
351
+ Or install manually from: https://github.com/sourcegraph/scip/releases`);if(t("scip CLI not found on PATH. Attempting auto-install..."),!await Bt(t))throw new Error(`The scip CLI is required but could not be installed.
352
+ Install manually from: https://github.com/sourcegraph/scip/releases/tag/${He}`)}function Bd(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?le(e.tempOutputScip,o,a):e.tempOutputScip})),i=Object.fromEntries(r.map(({language:o,scipPath:a})=>[o,a]));for(let{language:o,scipPath:a}of r){let s=Ud({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?Ua(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function Ud(e){if(e.language!=="typescript")return[ht({...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?[ht({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(t&&e.onStatus(`Indexing TypeScript workspace as ${n.length} project shard(s).`),n.flatMap((r,i)=>{let o=t?`typescript:${r}`:"typescript",a=t?`typescript (${r})`:"typescript",s=t?le(e.tempOutputScip,"typescript-project",i):e.scipPath,c={...e,id:o,label:a,scipPath:s,outputScipPath:e.scipPath,pnpmWorkspaces:!1};if(!t&&r==="."&&!e.pnpmWorkspaces){let u=Wd(e,c);if(u)return u}return[ht({...c,...t?{projectPath:r}:{}})]}))}function Gd(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=so(a,c=>{try{return An(D(t,c)).size}catch{return 1}});s&&oo(e,s)}catch{}}function Wd(e,t){let n=cn(),r=Ft(e.projectRoot,"single");if(!r||!eo(r.size,n))return null;uo(e.projectRoot);let i=co(),o=to(r.size,n,i),a=e.typescriptShardCostDir?io(e.typescriptShardCostDir):null,s=ao(a),c=no({projectRoot:e.projectRoot,rootConfigPath:"tsconfig.json",inputPaths:[...r],targetFiles:n,shardCount:o,weightOf:l=>{let d=1;try{d=An(D(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)=>ht({...t,id:`typescript-compiler-shard:${d}`,label:`typescript compiler shard ${d+1}/${c.length}`,scipPath:le(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 ht(e){let t=nt(e.language),n=ke(t),r=Mt(t,e.projectRoot),i=e.trustProjectTools&&r?Sr(t,e.projectRoot):null,o=be(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&&!At(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...`),!Tn(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??be(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=xi({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:Lt(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 qd(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)Ua(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?Br(o.scipPaths,o.outputScipPath):Gt(o.scipPaths,o.outputScipPath),i.push({language:o.language,scipPath:o.outputScipPath});else{let a=o.scipPaths[0];a!==o.outputScipPath&&Ma(a,o.outputScipPath),i.push({language:o.language,scipPath:o.outputScipPath})}return{indexedOutputs:i}}function Ua(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 Hd(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
353
353
  `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
354
354
  `+o)}if(t.length!==0&&(i(`Indexed ${e.length} language output(s); skipped or incomplete: ${t.map(o=>o.language).join(", ")}.`),!r))throw new Error(`Failed to index all required languages; preserving the previous index. Pass --allow-partial to intentionally write an incomplete index.
355
355
  `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
356
- `))}function pd(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=da(e.map(o=>o.scipPath),t);return Td(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&bd(e[0].scipPath,t);return!1}async function Ih(e){let t;if(vh(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,d]of i.entries()){let u=N(e.run.tempPaths.runDir,`typescript-affected-${c}.db`);Ed(d.scipPath,e.run.onStatus),e.run.onStatus(`Converting bounded TypeScript batch ${c+1}/${i.length} (${d.affectedFiles.length-d.deletedFiles.length} emitted, ${d.deletedFiles.length} removed) to SQLite...`);let l=performance.now();await fd(d.scipPath,u,e.env,e.run.onStatus,!0,e.run.opts.signal),a+=performance.now()-l,Nt(e.run.writeTelemetry,Ae(u)??0);let p=ha({previousDbPath:e.run.paths.outputDb,miniDbPath:u,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:d.affectedFiles,deletedFiles:d.deletedFiles,reuseCandidate:c>0,deferIntegrity:c<i.length-1,trustedPriorGeneration:!0,writeTelemetry:e.run.writeTelemetry});s+=p.durationMs;for(let m of p.changedDocumentPaths)o.add(m);_e(u,{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(z(e.run.opts.signal,"Reindex cancelled by its owner."),t=i instanceof Error?i.message:String(i),_e(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 fd(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 vh(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!H(e.run.paths.outputDb)||!H(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 Ph(e,t){let n=_(),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:_()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:Jn(e.plan,o,e.projectFileCount)}}async function fd(e,t,n,r,i=!1,o){if(z(o,"Reindex cancelled by its owner."),r("Converting to SQLite..."),!H(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{if(i||Ed(e,r),n.SCIP_QUERY_SQLITE_CONVERTER==="scip-cli"){let a=qn();if(!a)throw new Error("scip CLI is not available");let s=await Mt({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 _e(t,{force:!0}),await Va(j(e,{maxBytes:G,inputKind:"SCIP index"}),t,{signal:o})}catch(a){z(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 Ed(e,t){let n=Zo(e);Td(n,t)}function Td(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function Oe(e,t,n){let r=Vg(e)||".scip",i=mn(e,r);return N(E(e),`${i}.${n+1}.${t}${r}`)}async function wh(e,t){for(let n=0;n<2;n++){let r=Eh(e,t);if(r)return r;let i=Th(e);if(i&&Dd(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await kh(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: ${Fe(s)}`,{cause:s})}if(!o)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${E(e)}; refusing to steal an active lock.`);let a=Tn(e,{parseLegacy:yn});if(!Ai(e,a,{parseLegacy:yn}))throw new Error(`Reindex lock ownership changed before preemption completed for ${E(e)}.`);continue}throw new jt(`Another scip-query reindex is already running for ${E(e)}.`)}throw new jt(`Could not acquire scip-query reindex lock for ${E(e)}.`)}function Eh(e,t){let n=ee(process.pid),r=Et(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:yn});if(r.kind==="acquired"&&r.reclaimed){let i=kd(r.reclaimed,e);i&&Dd(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 ${E(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function Th(e){return kd(Tn(e,{parseLegacy:yn}),e)}var yn=e=>{let t=Cd(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function kd(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:E(t),startedAt:e.record.startedAt,trigger:n.trigger}}return Cd(e.parsed,t)}function Cd(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=Ci(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:E(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function Dd(e,t){return e?.kind==="manual-cli"&&_d(t?.trigger)}function _d(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function kh(e){return!fe(e.pid)||(Si(e),md(e,"SIGTERM"),await gd(e,2e3))?!0:(Si(e),md(e,"SIGKILL"),gd(e,1e3))}function md(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!fe(e.pid))return;Si(e)}try{process.kill(e.pid,t)}catch{}}async function gd(e,t){let n=_()+t;for(;_()<n;){if(hd(e))return!0;await Ch(50)}return hd(e)}function Si(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=ee(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!et(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function hd(e){if(!fe(e.pid))return!0;if(!e.processIdentity)return!1;let t=ee(e.pid);return t!==null&&!et(e.processIdentity,t)}function Ch(e){return new Promise(t=>setTimeout(t,e))}function Ii(e,t,n){return Object.fromEntries(t.map(r=>{let i=r==="typescript"?Yi(n.typescriptProjects):[],o=r==="clojure"?_h(n.clojureConfigPath):void 0,a=[...Bt(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"&&Fh(n),...s,clojureConfigPath:o,files:e.files.filter(c=>Ei(c.path,r,a)).map(c=>Fd(c,r))}]}))}function Fd(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 Dh(e,t){let n=Ze(t);if(!n)return t;let r=n.typescriptProjectMode==="workspace"?Ee(e,n.typescriptProjects):["."],i=$e(r);return{...n,files:n.files.filter(o=>!Be(o.path)||i.has(o.path)).map(o=>{let a=o.semanticHash??At(e,o.path,o.hash);return Fd(a===void 0?o:{...o,semanticHash:a},"typescript")})}}function _h(e){return e?.trim()||void 0}function Fh(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function vi(e,t){return N(E(e),"language-indexes",`${t}.scip`)}function Ad(e){return N(E(e),"language-indexes","typescript-projects")}function bn(e,t){return N(Ad(e),`${gr(t)}.scip`)}function Le(e){try{return Pt(oe(U(e,"reindex metadata")))}catch{return null}}function Od(e,t){try{let n=oe(U(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return null;let r=n.metadata;return!n.capabilities.publishableGeneration||!ki(r)||W([...r.indexedLanguages??[]].sort())!==W(t.languages)?null:W(r.fingerprint)===W(t)?"exact":W(yd(r.fingerprint))===W(yd(t))?"operational-config-compatible":null}catch{return null}}function yd(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 Ah(e,t,n,r){let i=Pt(oe(U(e,"reindex metadata")));i&&Rn(e,{...i,fingerprint:t,...i.version===Ne?{languageFingerprints:Ii(t,n,r)}:{}})}function Rn(e,t){Y(e,t,{spacing:2,trailingNewline:!0})}function Ld(e,t){try{let n=Pt(oe(U(e,"reindex metadata")));if(!n)return;Rn(e,{...n,lastRefresh:t})}catch{}}function xn(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:_()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function W(e){return JSON.stringify(e)}export{zo as INDEXER_CONFIGS,Do as augmentAuxiliaryDocuments,xg as augmentVueResolvedReferences,Ig as augmentVueResolvedReferencesAsync,he as auxiliaryDocumentsAugmentationStage,it as describeIndexerBinary,Qn as detectLanguages,Bt as getIndexerConfig,Gn as getIndexerExecutionEnv,Mn as isBinaryAvailable,jn as isIndexerInstalled,ar as mergeScipFiles,or as mergeScipIndexes,gI as reindex,Ue as resolveIndexerBinary,Nn as resolveProjectLocalIndexerBinary,se as runPostIndexAugmentation,li as tryInstallIndexer,Wn as tryInstallScipCli,nd as vueResolvedReferencesAugmentationStage};
356
+ `))}function ka(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=Ur(e.map(o=>o.scipPath),t);return Wa(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Ma(e[0].scipPath,t);return!1}async function zd(e){let t;if(Jd(e))try{let i=e.incrementalTypeScript.affectedBatches.length>0?e.incrementalTypeScript.affectedBatches:[{scipPath:e.incrementalTypeScript.affectedScipPath,affectedFiles:e.incrementalTypeScript.affectedFiles,deletedFiles:e.incrementalTypeScript.deletedFiles}],o=new Set,a=0,s=0;for(let[c,u]of i.entries()){let l=D(e.run.tempPaths.runDir,`typescript-affected-${c}.db`);Ga(u.scipPath,e.run.onStatus),e.run.onStatus(`Converting bounded TypeScript batch ${c+1}/${i.length} (${u.affectedFiles.length-u.deletedFiles.length} emitted, ${u.deletedFiles.length} removed) to SQLite...`);let d=performance.now();await _a(u.scipPath,l,e.env,e.run.onStatus,!0,e.run.opts.signal),a+=performance.now()-d,Ze(e.run.writeTelemetry,ue(l)??0);let m=Ti({previousDbPath:e.run.paths.outputDb,miniDbPath:l,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:u.affectedFiles,deletedFiles:u.deletedFiles,reuseCandidate:c>0,deferIntegrity:c<i.length-1,trustedPriorGeneration:!0,writeTelemetry:e.run.writeTelemetry});s+=m.durationMs;for(let f of m.changedDocumentPaths)o.add(f);se(l,{force:!0})}return e.run.onStatus(`Patched ${e.incrementalTypeScript.affectedFiles.length} SQLite document path(s) across ${i.length} bounded batch(es) in ${(s/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:[...o].sort(),patchDurationMs:s,converterDurationMs:a,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(i){if($(e.run.opts.signal,"Reindex cancelled by its owner."),t=i instanceof Error?i.message:String(i),se(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.opts.allowExpensiveRebuild===!1)throw new Error(`Bounded incremental SQLite publication failed and the whole-project fallback is disabled: ${t}`,{cause:i});e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}let n=e.completeScipSanitized;e.completeScipAvailable||(n=await e.materializeFullFallback());let r=performance.now();return await _a(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n,e.run.opts.signal),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function Jd(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!j(e.run.paths.outputDb)||!j(e.run.paths.outputScip))return!1;let t=new Set(e.reusedLanguages);return e.indexedOutputs.length===e.run.languages.length&&e.run.languages.every(n=>n==="typescript"||t.has(n))}function Yd(e,t){let n=F(),r=[...t].sort(),i=new Set(r),o={addedFiles:[],modifiedFiles:r,deletedFiles:[],changedFiles:r,unchangedFiles:e.affectedFiles.filter(a=>!i.has(a)).sort()};return{version:1,status:"evaluated",refreshResult:"rebuilt",recordedAt:new Date().toISOString(),durationMs:F()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:zt(e.plan,o,e.projectFileCount)}}async function _a(e,t,n,r,i=!1,o){if($(o,"Reindex cancelled by its owner."),r("Converting to SQLite..."),!j(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{if(i||Ga(e,r),n.SCIP_QUERY_SQLITE_CONVERTER==="scip-cli"){let a=_r();if(!a)throw new Error("scip CLI is not available");let s=await qe({command:a,args:["expt-convert","--output",t,e],label:"SCIP SQLite conversion",env:n,maxStdoutBytes:50*1024*1024,maxStderrBytes:50*1024*1024,timeoutMs:3e5,signal:o});if(s.status!==0)throw new Error(`scip expt-convert exited with ${s.status}${s.stderr.trim()?`: ${s.stderr.trim()}`:""}`)}else se(t,{force:!0}),await Qi(fe(e,{maxBytes:Ne,inputKind:"SCIP index"}),t,{signal:o})}catch(a){$(o,"Reindex cancelled by its owner.");let s=a instanceof Error?a.message:String(a);throw new Error(`Failed to convert SCIP index to SQLite: ${s}`,{cause:a})}}function Ga(e,t){let n=Vr(e);Wa(n,t)}function Wa(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function le(e,t,n){let r=hd(e)||".scip",i=gt(e,r);return D(v(e),`${i}.${n+1}.${t}${r}`)}async function Xd(e,t){for(let n=0;n<2;n++){let r=Kd(e,t);if(r)return r;let i=Qd(e);if(i&&za(t.trigger,i)){t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`);let o;try{o=await Zd(i)}catch(s){throw new Error(`Could not verify the watcher's in-progress reindex owner (pid ${i.pid}); refusing to steal an active lock: ${ce(s)}`,{cause:s})}if(!o)throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${v(e)}; refusing to steal an active lock.`);let a=kt(e,{parseLegacy:St});if(!Yn(e,a,{parseLegacy:St}))throw new Error(`Reindex lock ownership changed before preemption completed for ${v(e)}.`);continue}throw new ze(`Another scip-query reindex is already running for ${v(e)}.`)}throw new ze(`Could not acquire scip-query reindex lock for ${v(e)}.`)}function Kd(e,t){let n=J(process.pid),r=Jn(e,{kind:"reindex",processIdentity:n,detail:{projectRoot:t.projectRoot,...process.env.SCIP_REINDEX_PROCESS_GROUP_LEADER==="1"?{processGroupLeader:!0}:{},...t.trigger?{trigger:t.trigger}:{}},parseLegacy:St});if(r.kind==="acquired"&&r.reclaimed){let i=qa(r.reclaimed,e);i&&za(t.trigger,i)?t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}; its prior owner was already stale.`):t.onStatus(`Recovered an abandoned or incomplete reindex lock for ${v(e)}.`)}return r.kind==="acquired"?()=>{r.lock.release()}:null}function Qd(e){return qa(kt(e,{parseLegacy:St}),e)}var St=e=>{let t=Ha(e,"");return t?{pid:t.pid,...t.processIdentity?{processIdentity:t.processIdentity}:{}}:null};function qa(e,t){if(e.state==="valid"&&e.record?.kind==="reindex"){let n=e.record.detail??{};return{version:2,pid:e.record.pid,...e.record.processIdentity?{processIdentity:e.record.processIdentity}:{},...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:v(t),startedAt:e.record.startedAt,trigger:n.trigger}}return Ha(e.parsed,t)}function Ha(e,t){try{let n=e;return typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=0?null:{version:n.version===2?2:1,pid:n.pid,...n.processIdentity===void 0?{}:(()=>{let r=qn(n.processIdentity);return r?.pid===n.pid?{processIdentity:r}:{}})(),...n.processGroupLeader===!0?{processGroupLeader:!0}:{},projectRoot:typeof n.projectRoot=="string"?n.projectRoot:v(t),startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",trigger:n.trigger}}catch{return null}}function za(e,t){return e?.kind==="manual-cli"&&Ja(t?.trigger)}function Ja(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function Zd(e){return!ge(e.pid)||(Dn(e),Fa(e,"SIGTERM"),await Ca(e,2e3))?!0:(Dn(e),Fa(e,"SIGKILL"),Ca(e,1e3))}function Fa(e,t){if(e.processGroupLeader)try{process.kill(-e.pid,t);return}catch{if(!ge(e.pid))return;Dn(e)}try{process.kill(e.pid,t)}catch{}}async function Ca(e,t){let n=F()+t;for(;F()<n;){if(Oa(e))return!0;await ep(50)}return Oa(e)}function Dn(e){if(!e.processIdentity)throw new Error(`Refusing to signal reindex pid ${e.pid}: its ownership record has no process identity.`);let t=J(e.pid);if(!t)throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity is unavailable.`);if(!we(e.processIdentity,t))throw new Error(`Refusing to signal reindex pid ${e.pid}: its process identity does not match the ownership record.`)}function Oa(e){if(!ge(e.pid))return!0;if(!e.processIdentity)return!1;let t=J(e.pid);return t!==null&&!we(e.processIdentity,t)}function ep(e){return new Promise(t=>setTimeout(t,e))}function jn(e,t,n){return Object.fromEntries(t.map(r=>{let i=r==="typescript"?tr(n.typescriptProjects):[],o=r==="clojure"?np(n.clojureConfigPath):void 0,a=[...nt(r).markerFiles,...i,...o?[o]:[]],s=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:i}:{typescriptProjectMode:"single",typescriptProjects:[]};return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&rp(n),...s,clojureConfigPath:o,files:e.files.filter(c=>Bn(c.path,r,a)).map(c=>Ya(c,r))}]}))}function Ya(e,t){let n=t==="typescript"&&/(?:^|\/)package\.json$/iu.test(e.path)?e.semanticHash:void 0;return{path:e.path,size:n===void 0?e.size:0,hash:n??e.hash}}function tp(e,t){let n=Et(t);if(!n)return t;let r=n.typescriptProjectMode==="workspace"?ne(e,n.typescriptProjects):["."],i=he(r);return{...n,files:n.files.filter(o=>!ye(o.path)||i.has(o.path)).map(o=>{let a=o.semanticHash??Be(e,o.path,o.hash);return Ya(a===void 0?o:{...o,semanticHash:a},"typescript")})}}function np(e){return e?.trim()||void 0}function rp(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Nn(e,t){return D(v(e),"language-indexes",`${t}.scip`)}function Xa(e){return D(v(e),"language-indexes","typescript-projects")}function Rt(e,t){return D(Xa(e),`${rn(t)}.scip`)}function de(e){try{return je(te(U(e,"reindex metadata")))}catch{return null}}function Ka(e,t){try{let n=te(U(e,"reindex metadata"));if(n.kind!=="legacy"&&n.kind!=="supported")return null;let r=n.metadata;return!n.capabilities.publishableGeneration||!Wn(r)||L([...r.indexedLanguages??[]].sort())!==L(t.languages)?null:L(r.fingerprint)===L(t)?"exact":L(Da(r.fingerprint))===L(Da(t))?"operational-config-compatible":null}catch{return null}}function Da(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return Array.isArray(t.files)?{...t,files:t.files.filter(n=>typeof n!="object"||n===null||Array.isArray(n)||n.path!==".scipquery.json")}:e}function ip(e,t,n,r){let i=je(te(U(e,"reindex metadata")));i&&xt(e,{...i,fingerprint:t,...i.version===pe?{languageFingerprints:jn(t,n,r)}:{}})}function xt(e,t){Kn(e,t,{spacing:2,trailingNewline:!0})}function Qa(e,t){try{let n=je(te(U(e,"reindex metadata")));if(!n)return;xt(e,{...n,lastRefresh:t})}catch{}}function Pt(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:F()-e.monotonicStart,indexedLanguages:e.languages?[...e.languages]:void 0,skipped:e.skipped?[...e.skipped]:void 0,error:e.error}}function L(e){return JSON.stringify(e)}export{Ri as INDEXER_CONFIGS,si as augmentAuxiliaryDocuments,Yl as augmentVueResolvedReferences,Xl as augmentVueResolvedReferencesAsync,X as auxiliaryDocumentsAugmentationStage,ke as describeIndexerBinary,Ut as detectLanguages,nt as getIndexerConfig,Lt as getIndexerExecutionEnv,Dt as isBinaryAvailable,At as isIndexerInstalled,Gt as mergeScipFiles,ns as mergeScipIndexes,ph as reindex,be as resolveIndexerBinary,Mt as resolveProjectLocalIndexerBinary,G as runPostIndexAugmentation,Tn as tryInstallIndexer,Bt as tryInstallScipCli,ya as vueResolvedReferencesAugmentationStage};
357
357
  //# sourceMappingURL=reindex.js.map