scip-query 0.19.0 → 0.19.1

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 (178) hide show
  1. package/dist/augment-vue-worker.js +1 -1
  2. package/dist/{chunk-YHYTDWFT.js → chunk-24ET4VLC.js} +2 -2
  3. package/dist/{chunk-IXORBCMR.js → chunk-2NA6TYP4.js} +2 -2
  4. package/dist/{chunk-XKWEMFHP.js → chunk-2WCXKANA.js} +2 -2
  5. package/dist/{chunk-GJ3FR5WG.js → chunk-34MLC6UI.js} +2 -2
  6. package/dist/{chunk-PAZFJMXB.js → chunk-3WLRW5TC.js} +2 -2
  7. package/dist/{chunk-EZHARAL4.js → chunk-4BU54UJG.js} +2 -2
  8. package/dist/{chunk-XTSVYYAL.js → chunk-4CZJ4YJB.js} +2 -2
  9. package/dist/{chunk-TCVRJ56J.js → chunk-4FMT4HPC.js} +2 -2
  10. package/dist/{chunk-7FG5M53V.js → chunk-53SUJOJA.js} +2 -2
  11. package/dist/{chunk-YBAC3RON.js → chunk-5GOBZI34.js} +2 -2
  12. package/dist/{chunk-X36LKKVG.js → chunk-5OZCNAVM.js} +2 -2
  13. package/dist/{chunk-FMC3BI4I.js → chunk-5TEUKVSM.js} +2 -2
  14. package/dist/{chunk-WT7TOU2C.js → chunk-5W2VAEVR.js} +2 -2
  15. package/dist/{chunk-AWSRND4W.js → chunk-63P42UR6.js} +2 -2
  16. package/dist/{chunk-GNJHHPZE.js → chunk-64QITTX7.js} +2 -2
  17. package/dist/{chunk-XPYXEEDO.js → chunk-6O5JOS7T.js} +2 -2
  18. package/dist/{chunk-X65VYV2S.js → chunk-6PKO2TNZ.js} +2 -2
  19. package/dist/{chunk-X3OOU7CF.js → chunk-7SGOWD2Y.js} +2 -2
  20. package/dist/{chunk-ZXWFN7CK.js → chunk-7TJJY2C3.js} +2 -2
  21. package/dist/{chunk-OGHGTD6Z.js → chunk-AEM24WSF.js} +2 -2
  22. package/dist/{chunk-IWK562KR.js → chunk-AGTATREV.js} +2 -2
  23. package/dist/{chunk-SATRCB5O.js → chunk-AOSFSYEA.js} +2 -2
  24. package/dist/{chunk-3OSRXJKK.js → chunk-APLNTJPJ.js} +2 -2
  25. package/dist/{chunk-TDGCALH6.js → chunk-AYRHVJXW.js} +2 -2
  26. package/dist/{chunk-AM2LGOEX.js → chunk-B2WQKQKP.js} +2 -2
  27. package/dist/{chunk-F5L7WEZF.js → chunk-BBBKPOIT.js} +2 -2
  28. package/dist/{chunk-2FAJTZSX.js → chunk-BCMOTIB6.js} +2 -2
  29. package/dist/{chunk-RJLU7IMR.js → chunk-BMTBVMA3.js} +2 -2
  30. package/dist/{chunk-JFGUBZWE.js → chunk-C3KCSAQ4.js} +2 -2
  31. package/dist/{chunk-FLIF3JWA.js → chunk-CAKPEQZB.js} +2 -2
  32. package/dist/{chunk-PKAPOFF5.js → chunk-CIYUFF24.js} +2 -2
  33. package/dist/{chunk-7EI4MU5A.js → chunk-CKFMZE77.js} +2 -2
  34. package/dist/{chunk-A45K6VUK.js → chunk-DCDOGW32.js} +2 -2
  35. package/dist/{chunk-4ZCNFENR.js → chunk-DFQNE73Y.js} +2 -2
  36. package/dist/{chunk-J3U47L4Q.js → chunk-DO775SYA.js} +2 -2
  37. package/dist/{chunk-NEG77KKH.js → chunk-DRH3AD7W.js} +2 -2
  38. package/dist/{chunk-UVMME4FI.js → chunk-DZXFZAZO.js} +2 -2
  39. package/dist/{chunk-GMZYT44R.js → chunk-E3KWOHH7.js} +2 -2
  40. package/dist/{chunk-F334Z5UA.js → chunk-EMIIOOTM.js} +2 -2
  41. package/dist/{chunk-GBB2RUDN.js → chunk-ESNRT7QN.js} +130 -130
  42. package/dist/{chunk-RIGY5DDE.js → chunk-FB6IKAKZ.js} +2 -2
  43. package/dist/{chunk-BGUYAA3Q.js → chunk-FBUNGRKI.js} +2 -2
  44. package/dist/{chunk-M2TRDR25.js → chunk-FC5K7T35.js} +1 -1
  45. package/dist/{chunk-4ZHJAHLE.js → chunk-FHLYJVXF.js} +2 -2
  46. package/dist/{chunk-KWBA6FDD.js → chunk-FRXB74RQ.js} +2 -2
  47. package/dist/{chunk-BYPVNKJT.js → chunk-FTRNGQGR.js} +2 -2
  48. package/dist/{chunk-54UYBTZW.js → chunk-FUFNRZFJ.js} +2 -2
  49. package/dist/{chunk-QNMOZ3CJ.js → chunk-GAE7WCBK.js} +2 -2
  50. package/dist/{chunk-547VY366.js → chunk-GIHVWNKQ.js} +2 -2
  51. package/dist/{chunk-AEDB4WXE.js → chunk-HCS5LB6U.js} +2 -2
  52. package/dist/{chunk-UXOVHGT6.js → chunk-HFBNIIZX.js} +2 -2
  53. package/dist/{chunk-JHK2DMUQ.js → chunk-HGFDYOVB.js} +1 -1
  54. package/dist/{chunk-6SHX42QQ.js → chunk-IOOCKVUA.js} +2 -2
  55. package/dist/{chunk-XDVT7QPG.js → chunk-J4MYRIYT.js} +2 -2
  56. package/dist/{chunk-TAB7AWKO.js → chunk-J5XJWCB3.js} +2 -2
  57. package/dist/{chunk-PXJIEMND.js → chunk-JBZXJXIS.js} +2 -2
  58. package/dist/{chunk-UJL3N6TC.js → chunk-JJZRS2OP.js} +2 -2
  59. package/dist/chunk-KC2IFAAU.js +3 -0
  60. package/dist/{chunk-4XTPZ5CR.js → chunk-KMOMNTB4.js} +2 -2
  61. package/dist/{chunk-YYR7ADNB.js → chunk-KMUFGAIK.js} +2 -2
  62. package/dist/{chunk-DWN7QDTV.js → chunk-LF5CIKWZ.js} +2 -2
  63. package/dist/{chunk-ZL5Y23AJ.js → chunk-LM72NQ7T.js} +1 -1
  64. package/dist/{chunk-3KQOIXLO.js → chunk-LQUDSHLB.js} +2 -2
  65. package/dist/{chunk-VV5WJLRO.js → chunk-MP43RX4O.js} +1 -1
  66. package/dist/{chunk-D5OXYOJP.js → chunk-MQ2B33LQ.js} +1 -1
  67. package/dist/{chunk-EZGT3NJX.js → chunk-NTOBQK5H.js} +2 -2
  68. package/dist/{chunk-TOYQTO44.js → chunk-OLG2YPLS.js} +2 -2
  69. package/dist/{chunk-J65FQLDL.js → chunk-OOUJBAKJ.js} +2 -2
  70. package/dist/{chunk-PBADFBRR.js → chunk-OQ6TCHBB.js} +2 -2
  71. package/dist/{chunk-BOXAKNN6.js → chunk-PNESKY2Z.js} +2 -2
  72. package/dist/{chunk-TDZXQAH7.js → chunk-PYMZU5EG.js} +2 -2
  73. package/dist/{chunk-HOXI4F5I.js → chunk-Q2WEWIKX.js} +2 -2
  74. package/dist/{chunk-DQIJMKNE.js → chunk-QHKXGMOI.js} +2 -2
  75. package/dist/{chunk-MTFHE7ZO.js → chunk-RPEA7P5Z.js} +2 -2
  76. package/dist/{chunk-DV6B262O.js → chunk-SJ6XSCG7.js} +2 -2
  77. package/dist/{chunk-LJD7V7UO.js → chunk-SSXEYWN3.js} +2 -2
  78. package/dist/{chunk-XESK6725.js → chunk-SYGAA54M.js} +2 -2
  79. package/dist/{chunk-TC3X33N6.js → chunk-TYEGFDOP.js} +2 -2
  80. package/dist/chunk-UJKZQLDB.js +2 -0
  81. package/dist/{chunk-QB5WSOTY.js → chunk-US44MEVU.js} +2 -2
  82. package/dist/{chunk-2ZNZSNVW.js → chunk-V5WBVF6K.js} +2 -2
  83. package/dist/{chunk-S65OEY2G.js → chunk-V7J4A3AH.js} +2 -2
  84. package/dist/{chunk-J6BR4MD6.js → chunk-VIKEPD4D.js} +2 -2
  85. package/dist/{chunk-XDSB47KO.js → chunk-WAU7HVDI.js} +2 -2
  86. package/dist/{chunk-T5CSWYAZ.js → chunk-WCZAABYF.js} +2 -2
  87. package/dist/{chunk-KD6TPIXM.js → chunk-WFRET75Z.js} +2 -2
  88. package/dist/chunk-WWCZCH7W.js +3 -0
  89. package/dist/{chunk-G6RQVDTI.js → chunk-XCPE3G75.js} +2 -2
  90. package/dist/{chunk-QN67MWDU.js → chunk-XYBNOILR.js} +2 -2
  91. package/dist/{chunk-MFBXBLHA.js → chunk-XZXUMGAA.js} +2 -2
  92. package/dist/{chunk-QHOUNTDZ.js → chunk-YCSTKIYU.js} +2 -2
  93. package/dist/{chunk-ZNSLF5AC.js → chunk-YGQBJUS6.js} +2 -2
  94. package/dist/{chunk-6DHPQS72.js → chunk-YILKXTIY.js} +2 -2
  95. package/dist/{chunk-G6QQCX45.js → chunk-ZJGZCBYT.js} +2 -2
  96. package/dist/{chunk-MDDF67O2.js → chunk-ZNK6K3LB.js} +2 -2
  97. package/dist/cli.js +1 -1
  98. package/dist/{command-descriptors-SWFWGIFK.js → command-descriptors-3EJHQLQZ.js} +55 -55
  99. package/dist/direct-navigation-C2A44KFT.js +3 -0
  100. package/dist/index.js +1 -1
  101. package/dist/queries/affected.js +1 -1
  102. package/dist/queries/architecture.js +1 -1
  103. package/dist/queries/bottlenecks.js +1 -1
  104. package/dist/queries/by-kind.js +1 -1
  105. package/dist/queries/call-graph.js +1 -1
  106. package/dist/queries/change-surface.js +1 -1
  107. package/dist/queries/cleanup-plan.js +1 -1
  108. package/dist/queries/co-change.js +1 -1
  109. package/dist/queries/code.js +1 -1
  110. package/dist/queries/complexity-hotspots.js +1 -1
  111. package/dist/queries/complexity.js +1 -1
  112. package/dist/queries/convergence.js +1 -1
  113. package/dist/queries/coupling.js +1 -1
  114. package/dist/queries/cycles.js +1 -1
  115. package/dist/queries/dataflow.js +1 -1
  116. package/dist/queries/dead.js +1 -1
  117. package/dist/queries/decorative-checkers.js +1 -1
  118. package/dist/queries/deep-chains.js +1 -1
  119. package/dist/queries/deps.js +1 -1
  120. package/dist/queries/diff-gate.js +1 -1
  121. package/dist/queries/diff-impact.js +1 -1
  122. package/dist/queries/doc-drift.js +1 -1
  123. package/dist/queries/drift.js +1 -1
  124. package/dist/queries/duplicate-bodies.js +1 -1
  125. package/dist/queries/extract-candidates.js +1 -1
  126. package/dist/queries/fan.js +1 -1
  127. package/dist/queries/health.js +1 -1
  128. package/dist/queries/hierarchy.js +1 -1
  129. package/dist/queries/hotspots.js +1 -1
  130. package/dist/queries/imports.js +1 -1
  131. package/dist/queries/incomplete-migration.js +1 -1
  132. package/dist/queries/index.js +1 -1
  133. package/dist/queries/isolated.js +1 -1
  134. package/dist/queries/locality-candidates.js +1 -1
  135. package/dist/queries/members.js +1 -1
  136. package/dist/queries/methods.js +1 -1
  137. package/dist/queries/not-implemented.js +1 -1
  138. package/dist/queries/outline.js +1 -1
  139. package/dist/queries/passthrough-candidates.js +1 -1
  140. package/dist/queries/plan-context.js +1 -1
  141. package/dist/queries/react-component-duplicates.js +1 -1
  142. package/dist/queries/react-hook-candidates.js +1 -1
  143. package/dist/queries/react-large-component-pressure.js +1 -1
  144. package/dist/queries/recent-duplicates.js +1 -1
  145. package/dist/queries/redundant-reexports.js +1 -1
  146. package/dist/queries/refs.js +1 -1
  147. package/dist/queries/self-audit.js +1 -1
  148. package/dist/queries/similar-chains.js +1 -1
  149. package/dist/queries/similar-files.js +1 -1
  150. package/dist/queries/similar-signatures.js +1 -1
  151. package/dist/queries/similar.js +1 -1
  152. package/dist/queries/slice.js +1 -1
  153. package/dist/queries/stale-abstractions.js +1 -1
  154. package/dist/queries/surface.js +1 -1
  155. package/dist/queries/symbols.js +1 -1
  156. package/dist/queries/system.js +1 -1
  157. package/dist/queries/test-quality.js +1 -1
  158. package/dist/queries/trace.js +1 -1
  159. package/dist/queries/twin-ab.js +1 -1
  160. package/dist/queries/twin-drift.js +1 -1
  161. package/dist/queries/unused-imports.js +1 -1
  162. package/dist/queries/unused-params.js +1 -1
  163. package/dist/queries/vue-component-duplicates.js +1 -1
  164. package/dist/queries/vue-composable-candidates.js +1 -1
  165. package/dist/queries/vue-large-view-pressure.js +1 -1
  166. package/dist/queries/wrapper-candidates.js +1 -1
  167. package/dist/reindex-worker.js +5 -5
  168. package/dist/reindex.js +15 -15
  169. package/dist/runtime.js +1 -1
  170. package/dist/rust-semantic-session-server.js +1 -1
  171. package/dist/rust-semantic-session-worker.js +1 -1
  172. package/dist/rust-semantic-worker.js +1 -1
  173. package/dist/watch-server.js +1 -1
  174. package/package.json +1 -1
  175. package/dist/chunk-42QYU6FD.js +0 -3
  176. package/dist/chunk-AERYQJ52.js +0 -3
  177. package/dist/chunk-OYYZLJVT.js +0 -2
  178. package/dist/direct-navigation-RKMPBXMI.js +0 -3
package/dist/reindex.js CHANGED
@@ -1,8 +1,8 @@
1
- import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h as Mn}from"./chunk-6SHX42QQ.js";import{a as _n}from"./chunk-YZXV3CU3.js";import{A as Cn,a as Y,b as ne,c as re,d as st,e as ct,f as ut,g as T,h as b,m as wn,n as kn,o as ke,p as En,q as Ee,r as Tn,s as Dn,t as Fn,u as dt,v as lt,y as On}from"./chunk-GMZYT44R.js";import"./chunk-P5XHIJHI.js";import{a as at,b as Pn,d as Te,g as jn}from"./chunk-ZL5Y23AJ.js";import{a as we}from"./chunk-SATRCB5O.js";import"./chunk-TDGCALH6.js";import"./chunk-QNMOZ3CJ.js";import{J as vn,K as In,d as Z}from"./chunk-XDSB47KO.js";import{s as ee,t as te}from"./chunk-M2TRDR25.js";import{a as Pe}from"./chunk-64MNV6AB.js";import{execFileSync as Sd}from"child_process";import{createHash as bd}from"crypto";import{closeSync as Rd,copyFileSync as nt,existsSync as j,mkdirSync as tt,mkdtempSync as xd,openSync as vd,readdirSync as Id,readFileSync as rt,renameSync as Fo,rmSync as U,statSync as Pd,writeFileSync as wd}from"fs";import{basename as et,dirname as h,extname as kd,join as v,resolve as Io}from"path";import{platform as Ed}from"os";import{randomUUID as Nn}from"crypto";import{closeSync as $n,mkdirSync as Uo,openSync as Gn,readFileSync as Vn,unlinkSync as Bn,writeFileSync as Un}from"fs";import{dirname as Wo,join as Jo}from"path";function Wn(e,t={}){return ie(Jo(e,"gc.lock"),t)}function ie(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??Date.now,o=Date.now()+n;Uo(Wo(e),{recursive:!0});do{let a=Nn();try{let s=Gn(e,"wx");try{let c={version:1,pid:process.pid,token:a,startedAt:new Date(i()).toISOString()};Un(s,`${JSON.stringify(c)}
1
+ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h as Mn}from"./chunk-IOOCKVUA.js";import{a as _n}from"./chunk-YZXV3CU3.js";import{A as Cn,a as Y,b as ne,c as re,d as st,e as ct,f as ut,g as T,h as b,m as wn,n as kn,o as ke,p as En,q as Ee,r as Tn,s as Dn,t as Fn,u as dt,v as lt,y as jn}from"./chunk-E3KWOHH7.js";import"./chunk-P5XHIJHI.js";import{a as at,b as Pn,d as Te,g as On}from"./chunk-LM72NQ7T.js";import{a as we}from"./chunk-AOSFSYEA.js";import"./chunk-AYRHVJXW.js";import"./chunk-GAE7WCBK.js";import{J as vn,K as In,d as Z}from"./chunk-WAU7HVDI.js";import{s as ee,t as te}from"./chunk-FC5K7T35.js";import{a as Pe}from"./chunk-64MNV6AB.js";import{execFileSync as Sd}from"child_process";import{createHash as bd}from"crypto";import{closeSync as Rd,copyFileSync as nt,existsSync as O,mkdirSync as tt,mkdtempSync as xd,openSync as vd,readdirSync as Id,readFileSync as rt,renameSync as Fo,rmSync as U,statSync as Pd,writeFileSync as wd}from"fs";import{basename as et,dirname as h,extname as kd,join as v,resolve as Io}from"path";import{platform as Ed}from"os";import{randomUUID as Nn}from"crypto";import{closeSync as $n,mkdirSync as Uo,openSync as Gn,readFileSync as Vn,unlinkSync as Bn,writeFileSync as Un}from"fs";import{dirname as Wo,join as Jo}from"path";function Wn(e,t={}){return ie(Jo(e,"gc.lock"),t)}function ie(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??Date.now,o=Date.now()+n;Uo(Wo(e),{recursive:!0});do{let a=Nn();try{let s=Gn(e,"wx");try{let c={version:1,pid:process.pid,token:a,startedAt:new Date(i()).toISOString()};Un(s,`${JSON.stringify(c)}
2
2
  `)}finally{$n(s)}return{release:()=>qn(e,a)}}catch(s){if(s.code!=="EEXIST")return null;let c=Jn(e);if(c&&(c.pid===void 0||!T(c.pid))){qo(e,c);continue}if(Date.now()>=o)return null;Ho(Math.min(r,Math.max(1,o-Date.now())))}}while(Date.now()<=o);return null}function Jn(e){try{let t=Vn(e,"utf8"),n=JSON.parse(t),r=typeof n.pid=="number"&&Number.isSafeInteger(n.pid)&&n.pid>0?n.pid:void 0;return{raw:t,...r===void 0?{}:{pid:r}}}catch{return null}}function qo(e,t){let n=`${e}.reclaim`,r=Nn(),i;try{i=Gn(n,"wx")}catch{return!1}try{Un(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
3
3
  `)}finally{$n(i)}try{let o=Jn(e);return!o||o.raw!==t.raw||o.pid!==void 0&&T(o.pid)?!1:(Bn(e),!0)}catch{return!1}finally{qn(n,r)}}function qn(e,t){try{let n=JSON.parse(Vn(e,"utf8"));n.pid===process.pid&&n.token===t&&Bn(e)}catch{}}function Ho(e){let t=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));Atomics.wait(t,0,0,e)}import zo from"better-sqlite3";import{execFileSync as Yo}from"child_process";import{existsSync as Qo,readdirSync as Xo,readFileSync as Ko}from"fs";import{extname as De,join as Hn}from"path";function J(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>zn({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function zn(e){let t=new Set((e.extensions??vn).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Qo(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=_n(e.projectRoot),r=Zo(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new zo(e.dbPath);try{let o=ta(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
4
4
  VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let p=0;for(let l of d){if(o.has(l))continue;let m=Ko(Hn(e.projectRoot,l),"utf-8"),g=a.run(na(l),l,m);p+=Number(g.changes)}return p})(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 Zo(e,t){let n=ea(e,t);if(n)return n;let r=[],i=o=>{let a=o?Hn(e,o):e,s;try{s=Xo(a,{withFileTypes:!0})}catch{return}for(let c of s){if(In.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(De(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function ea(e,t){try{return Yo("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
5
- `).filter(r=>r&&t.has(De(r).toLowerCase())).sort()}catch{return null}}function ta(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 na(e){return De(e).toLowerCase()===".vue"?"vue":De(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as ia}from"crypto";import{appendFileSync as oa,existsSync as aa,mkdirSync as sa,readFileSync as kl}from"fs";import{dirname as Kn,join as Qn}from"path";function ft(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=ft(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"),Yn(r,i,a)):a.size>0?Yn(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:ra(r,t,i),reasons:[]}}function Yn(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function ra(e,t,n){let r=new Map;for(let[a,s]of t)if(n.has(a))for(let c of s){if(!n.has(c))continue;let u=r.get(c)??new Set;u.add(a),r.set(c,u)}let i=new Set(e),o=[...e];for(let a=0;a<o.length;a+=1){let s=o[a];if(s!==void 0)for(let c of r.get(s)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}var ca="<global-symbols>";function ua(e){let t=[];for(let n of e.all(`
5
+ `).filter(r=>r&&t.has(De(r).toLowerCase())).sort()}catch{return null}}function ta(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 na(e){return De(e).toLowerCase()===".vue"?"vue":De(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as ia}from"crypto";import{appendFileSync as oa,existsSync as aa,mkdirSync as sa,readFileSync as wl}from"fs";import{dirname as Kn,join as Qn}from"path";function ft(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=ft(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"),Yn(r,i,a)):a.size>0?Yn(r,i,a):{mode:"closure",changedFiles:r,affectedFiles:ra(r,t,i),reasons:[]}}function Yn(e,t,n){return{mode:"full-project",changedFiles:e,affectedFiles:[...t].sort(),reasons:[...n].sort()}}function ra(e,t,n){let r=new Map;for(let[a,s]of t)if(n.has(a))for(let c of s){if(!n.has(c))continue;let u=r.get(c)??new Set;u.add(a),r.set(c,u)}let i=new Set(e),o=[...e];for(let a=0;a<o.length;a+=1){let s=o[a];if(s!==void 0)for(let c of r.get(s)??[])i.has(c)||(i.add(c),o.push(c))}return[...i].sort()}var ca="<global-symbols>";function ua(e){let t=[];for(let n of e.all(`
6
6
  SELECT relative_path, language, position_encoding, text
7
7
  FROM documents
8
8
  `))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
@@ -59,9 +59,9 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
59
59
  SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
60
60
  )
61
61
  `))t.push({relativePath:ca,kind:"global-symbol",values:mt(n)});return da(t)}function da(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=ia("sha256");for(let a of i.sort())o.update(String(Buffer.byteLength(a))),o.update(":"),o.update(a),o.update(`
62
- `);n.set(r,o.digest("hex"))}return n}function la(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 ht(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 yt(e,t=ga){let n=t.now();if(!t.databaseExists(e.previousDbPath))return je(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return je(e.refreshResult,"candidate-index-unavailable",n,t.now());let r=null,i=null;try{r=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),i=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let o=[...new Set([...t.indexedPaths(r),...t.indexedPaths(i)])].sort(),a=ke(e.previousSnapshot,e.currentSnapshot),s=new Set(o),c=a.changes.length>0&&!ft(a).fullProject&&a.changes.every(l=>s.has(l.path)),u=Fe(a,c?t.dependencyGraph(r):new Map,o),d=la(t.factDigests(r),t.factDigests(i)),p=t.now();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(p).toISOString(),durationMs:Math.max(0,p-n),manifest:a,plan:u,comparison:d,evaluation:ht(u,d,o.length)}}catch(o){return je(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{Xn(r),Xn(i)}}function Zn(e,t,n,r=Date.now()){return je(e,t,r,r,n)}function pa(e){let t=Kn(e);return{latestPath:Qn(t,"affected-shadow-latest.json"),historyPath:Qn(t,"affected-shadow.jsonl")}}function er(e,t,n=fa){let r=pa(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}function mt(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 ga={now:()=>Date.now(),databaseExists:e=>aa(e),openDatabase:(e,t,n)=>new W({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>Pe(e),dependencyGraph:e=>we(e),factDigests:e=>ua(e)},fa={appendHistory:(e,t)=>{sa(Kn(e),{recursive:!0}),oa(e,`${JSON.stringify(t)}
63
- `)},writeLatest:(e,t)=>b(e,t,{spacing:2,trailingNewline:!0})};function je(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(r).toISOString(),durationMs:Math.max(0,r-n),reason:t,...i?{error:i}:{}}}function Xn(e){try{e?.close()}catch{}}import{execFileSync as ma}from"child_process";import{existsSync as ha,readdirSync as nr}from"fs";import{extname as rr,join as ir}from"path";var or=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),ya=[{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 St(e){let t=[],n=Sa(e),r=va(e);for(let i of ya){if(ba(e,i.files)){t.push(i.language);continue}if(Ra(n,i.globs)){t.push(i.language);continue}Pa(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&tr(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&tr(t,"c"),t}function Sa(e){try{return nr(e)}catch{return[]}}function ba(e,t){return t?.length?t.some(n=>ha(ir(e,n))):!1}function Ra(e,t){return t?.length?e.some(n=>t.some(r=>xa(n,r))):!1}function xa(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 va(e){let t=Ia(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=nr(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=ir(i,a.name);if(a.isDirectory()){or.has(a.name)||r.push(s);continue}let c=rr(a.name).toLowerCase();c&&n.add(c)}}return n}function Ia(e){try{let t=ma("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}),n=new Set;for(let r of t.split(`
64
- `)){if(!r||r.split("/").some(o=>or.has(o)))continue;let i=rr(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Pa(e,t){return t?.length?t.some(n=>e.has(n)):!1}function tr(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as ar,readdirSync as wa}from"fs";import{isAbsolute as ka,join as bt,resolve as Ea}from"path";var cr={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>{let i=r?["index","--output",e,"--no-progress-bar",r]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!r&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:Y.language,indexerBinary:Y.indexerBinary,checkCommand:`${Y.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:Y.indexerBinary,args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:Y.installUrl},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",ka(r)?r:Ea(e,r)),{binary:n,args:i}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",sr(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",sr(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:["pubspec.yaml"],installMethods:[{label:"dart pub",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({projectRoot:e,indexerBinary:t})=>{let n=bt(e,"vendor","bin","scip-php"),r=bt(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",ar(r)?r:ar(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function Oe(e){return cr[e]}function sr(e,t){let n;try{n=wa(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return bt(e,i);return null}import{readFileSync as xt,writeFileSync as vt}from"fs";import{create as oe}from"@bufbuild/protobuf";import{deserializeSCIP as It,serializeSCIP as Pt,DocumentSchema as Aa,IndexSchema as lr,MetadataSchema as La,SymbolInformationSchema as Ma}from"@c4312/scip";import{readFileSync as Ta,writeFileSync as Da}from"fs";import{create as ur}from"@bufbuild/protobuf";import{deserializeSCIP as Fa,DocumentSchema as ja,IndexSchema as Oa,serializeSCIP as Ca,SymbolRole as _a}from"@c4312/scip";function dr(e){let t;try{t=Fa(Ta(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=Rt(t);return n.removedDefinitionOccurrences>0&&Da(e,Buffer.from(Ca(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function Rt(e){let t=new Set;for(let o of e.documents)for(let a of o.symbols)a.symbol&&t.add(a.symbol);for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,r=0,i=[];for(let o of e.documents){let a=o.occurrences.filter(s=>(s.symbolRoles&_a.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(ur(ja,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:ur(Oa,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function wt(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=$a(e),n=Ga(e.flatMap(i=>i.documents??[])),r=fr(e.flatMap(i=>i.externalSymbols??[]));return oe(lr,{metadata:t,documents:n,externalSymbols:r})}function kt(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>It(xt(i))),r=wt(n);return vt(t,Buffer.from(Pt(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function pr(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>It(xt(i))),r=Rt(wt(n));return vt(t,Buffer.from(Pt(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function Na(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(r.projectRoot!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return oe(lr,{metadata:oe(La,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function gr(e,t,n){let r=It(xt(e)),i=Na(r,t,n);vt(e,Buffer.from(Pt(i)))}function $a(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 Ga(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,oe(Aa,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:Va([...r.occurrences,...n.occurrences]),symbols:fr([...r.symbols,...n.symbols]),text:Ua(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Va(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 fr(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,oe(Ma,{symbol:r.symbol,documentation:Wa([...r.documentation,...n.documentation]),relationships:Ba([...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 Ba(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 Ua(e,t){return e?t?e.length>=t.length?e:t:e:t}function Wa(e){return[...new Set(e)]}import{createHash as Ja}from"crypto";import{copyFileSync as qa,existsSync as mr,rmSync as hr}from"fs";import{resolve as Ha}from"path";import br from"better-sqlite3";var za={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}]},Ya={idx_chunks_doc_id:{table:"chunks",columns:["document_id"]},idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_global_symbols_symbol:{table:"global_symbols",columns:["symbol"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Rr(e){let t=Date.now(),n=Qa(e.affectedFiles);if(Xa(e.previousDbPath,e.miniDbPath,e.candidateDbPath),hr(e.candidateDbPath,{force:!0}),!mr(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!mr(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");yr(e.previousDbPath,"previous SQLite generation",!1),yr(e.miniDbPath,"incremental SQLite mini database"),qa(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new br(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Et(r,"main","candidate SQLite generation"),Et(r,"incremental","incremental SQLite mini database"),Ka(r,n),Za(r,n.length);let i=Tt(r,"main",!0),o=M(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{es(r),ts(r),ns(r),e.onStage?.("after-delete"),rs(r),e.onStage?.("after-symbol-reconciliation"),is(r),e.onStage?.("after-insert"),os(r),as(r,n.length,o),e.onStage?.("before-commit")}).immediate(),xr(r,"main","candidate SQLite generation");let c=[...ss(r)].filter(([u,d])=>i.get(u)!==d).map(([u])=>u).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:Date.now()-t}}catch(i){try{r?.close()}finally{hr(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function Qa(e){if(e.length===0)throw new Error("incremental SQLite publication requires affected documents");let t=[...e].sort();for(let n of t)if(!n||n.startsWith("/")||n.includes("\\")||n.split("/").includes(".."))throw new Error(`invalid affected document path: ${n}`);if(new Set(t).size!==t.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return t}function Xa(e,t,n){let r=[e,t,n].map(i=>Ha(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function yr(e,t,n=!0){let r=new br(e,{readonly:!0,fileMustExist:!0});try{Et(r,"main",t),n&&xr(r,"main",t)}finally{r.close()}}function Et(e,t,n){for(let[r,i]of Object.entries(za)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:d})=>({name:s,type:c.toUpperCase(),notnull:u,pk:d}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(Ya)){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}`)}Sr(e,t,"documents",["relative_path"],n),Sr(e,t,"global_symbols",["symbol"],n)}function Sr(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 xr(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 Ka(e,t){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let n=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)");e.transaction(i=>{for(let o of i)n.run(o)})(t)}function Za(e,t){let n=M(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=M(e,`SELECT COUNT(*) AS value
62
+ `);n.set(r,o.digest("hex"))}return n}function la(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 ht(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 yt(e,t=ga){let n=t.now();if(!t.databaseExists(e.previousDbPath))return Oe(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return Oe(e.refreshResult,"candidate-index-unavailable",n,t.now());let r=null,i=null;try{r=t.openDatabase(e.projectRoot,e.previousDbPath,e.previousIndexPath),i=t.openDatabase(e.projectRoot,e.candidateDbPath,e.candidateIndexPath);let o=[...new Set([...t.indexedPaths(r),...t.indexedPaths(i)])].sort(),a=ke(e.previousSnapshot,e.currentSnapshot),s=new Set(o),c=a.changes.length>0&&!ft(a).fullProject&&a.changes.every(l=>s.has(l.path)),u=Fe(a,c?t.dependencyGraph(r):new Map,o),d=la(t.factDigests(r),t.factDigests(i)),p=t.now();return{version:1,status:"evaluated",refreshResult:e.refreshResult,recordedAt:new Date(p).toISOString(),durationMs:Math.max(0,p-n),manifest:a,plan:u,comparison:d,evaluation:ht(u,d,o.length)}}catch(o){return Oe(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{Xn(r),Xn(i)}}function Zn(e,t,n,r=Date.now()){return Oe(e,t,r,r,n)}function pa(e){let t=Kn(e);return{latestPath:Qn(t,"affected-shadow-latest.json"),historyPath:Qn(t,"affected-shadow.jsonl")}}function er(e,t,n=fa){let r=pa(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}function mt(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 ga={now:()=>Date.now(),databaseExists:e=>aa(e),openDatabase:(e,t,n)=>new W({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>Pe(e),dependencyGraph:e=>we(e),factDigests:e=>ua(e)},fa={appendHistory:(e,t)=>{sa(Kn(e),{recursive:!0}),oa(e,`${JSON.stringify(t)}
63
+ `)},writeLatest:(e,t)=>b(e,t,{spacing:2,trailingNewline:!0})};function Oe(e,t,n,r,i){return{version:1,status:"unavailable",refreshResult:e,recordedAt:new Date(r).toISOString(),durationMs:Math.max(0,r-n),reason:t,...i?{error:i}:{}}}function Xn(e){try{e?.close()}catch{}}import{execFileSync as ma}from"child_process";import{existsSync as ha,readdirSync as nr}from"fs";import{extname as rr,join as ir}from"path";var or=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),ya=[{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 St(e){let t=[],n=Sa(e),r=va(e);for(let i of ya){if(ba(e,i.files)){t.push(i.language);continue}if(Ra(n,i.globs)){t.push(i.language);continue}Pa(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&tr(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&tr(t,"c"),t}function Sa(e){try{return nr(e)}catch{return[]}}function ba(e,t){return t?.length?t.some(n=>ha(ir(e,n))):!1}function Ra(e,t){return t?.length?e.some(n=>t.some(r=>xa(n,r))):!1}function xa(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 va(e){let t=Ia(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=nr(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=ir(i,a.name);if(a.isDirectory()){or.has(a.name)||r.push(s);continue}let c=rr(a.name).toLowerCase();c&&n.add(c)}}return n}function Ia(e){try{let t=ma("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}),n=new Set;for(let r of t.split(`
64
+ `)){if(!r||r.split("/").some(o=>or.has(o)))continue;let i=rr(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Pa(e,t){return t?.length?t.some(n=>e.has(n)):!1}function tr(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{existsSync as ar,readdirSync as wa}from"fs";import{isAbsolute as ka,join as bt,resolve as Ea}from"path";var cr={typescript:{language:"typescript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,pnpmWorkspaces:t,indexerBinary:n,projectPath:r})=>{let i=r?["index","--output",e,"--no-progress-bar",r]:["index","--infer-tsconfig","--output",e,"--no-progress-bar"];return t&&!r&&i.splice(1,0,"--pnpm-workspaces"),{binary:n,args:i}},markerFiles:["tsconfig.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},javascript:{language:"javascript",indexerBinary:"scip-typescript",checkCommand:"npx scip-typescript --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--infer-tsconfig","--output",e,"--no-progress-bar"]}),markerFiles:["package.json"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","@sourcegraph/scip-typescript"]}],installUrl:"https://github.com/sourcegraph/scip-typescript",bundledNpmPackage:"@sourcegraph/scip-typescript"},java:{language:"java",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["pom.xml","build.gradle"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},scala:{language:"scala",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.sbt"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},kotlin:{language:"kotlin",indexerBinary:"scip-java",checkCommand:"scip-java --version",indexArgs:({outputPath:e})=>({binary:"scip-java",args:["index","--output",e]}),markerFiles:["build.gradle.kts"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-java/releases"},rust:{language:Y.language,indexerBinary:Y.indexerBinary,checkCommand:`${Y.indexerBinary} --version`,indexArgs:({outputPath:e})=>({binary:Y.indexerBinary,args:["scip",".","--output",e]}),markerFiles:["Cargo.toml"],installMethods:[{label:"rustup",prerequisite:"rustup",binary:"rustup",args:["component","add","rust-analyzer"]}],installUrl:Y.installUrl},python:{language:"python",indexerBinary:"scip-python-plus",binaryAliases:["scip-python"],checkCommand:"scip-python-plus --version",indexArgs:({outputPath:e,indexerBinary:t})=>({binary:t,args:["index","--output",e,"--project-name","project"]}),markerFiles:["pyproject.toml","setup.py"],installMethods:[{label:"npm",prerequisite:"npm",binary:"npm",args:["install","-g","scip-python-plus"]}],installUrl:"https://github.com/PlunderStruck/scip-python",bundledNpmPackage:"scip-python-plus"},clojure:{language:"clojure",indexerBinary:"scip-clojure",projectLocalBinaries:["node_modules/.bin/scip-clojure"],checkCommand:"scip-clojure -h",indexArgs:({projectRoot:e,outputPath:t,indexerBinary:n,configPath:r})=>{let i=["-root",e,"-output",t];return r&&i.push("-config",ka(r)?r:Ea(e,r)),{binary:n,args:i}},markerFiles:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],installMethods:[],installUrl:"https://github.com/PlunderStruck/scip-clojure"},ruby:{language:"ruby",indexerBinary:"scip-ruby",checkCommand:"scip-ruby --version",indexArgs:({indexerBinary:e})=>({binary:e,args:["--dir","."]}),defaultOutputPath:"index.scip",markerFiles:["Gemfile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-ruby/releases"},go:{language:"go",indexerBinary:"scip-go",checkCommand:"scip-go --version",indexArgs:({outputPath:e})=>({binary:"scip-go",args:["--output",e]}),markerFiles:["go.mod"],installMethods:[{label:"go install",prerequisite:"go",binary:"go",args:["install","github.com/sourcegraph/scip-go@latest"]}],installUrl:"https://github.com/sourcegraph/scip-go"},cpp:{language:"cpp",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},c:{language:"c",indexerBinary:"scip-clang",checkCommand:"scip-clang --version",indexArgs:({outputPath:e})=>({binary:"scip-clang",args:["--compdb-path","compile_commands.json","--index-output-path",e]}),markerFiles:["CMakeLists.txt","Makefile"],installMethods:[],installUrl:"https://github.com/sourcegraph/scip-clang/releases"},csharp:{language:"csharp",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",sr(e,[".sln",".csproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.csproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},vb:{language:"vb",indexerBinary:"scip-dotnet",checkCommand:"scip-dotnet --version",indexArgs:({projectRoot:e,outputPath:t})=>({binary:"scip-dotnet",args:["index",sr(e,[".sln",".vbproj"])??e,"--output",t,"--working-directory",e]}),markerFiles:["*.vbproj","*.sln"],installMethods:[{label:"dotnet",prerequisite:"dotnet",binary:"dotnet",args:["tool","install","--global","scip-dotnet"]}],installUrl:"https://github.com/sourcegraph/scip-dotnet/releases"},dart:{language:"dart",indexerBinary:"scip-dart",checkCommand:"scip-dart --version",indexArgs:({indexerBinary:e,outputPath:t})=>({binary:e,args:["--output",t]}),markerFiles:["pubspec.yaml"],installMethods:[{label:"dart pub",prerequisite:"dart",binary:"dart",args:["pub","global","activate","scip_dart"]}],installUrl:"https://github.com/Workiva/scip-dart/releases"},php:{language:"php",indexerBinary:"scip-php",projectLocalBinaries:["vendor/davidrjenni/scip-php/bin/scip-php","vendor/bin/scip-php"],checkCommand:"scip-php --version",indexArgs:({projectRoot:e,indexerBinary:t})=>{let n=bt(e,"vendor","bin","scip-php"),r=bt(e,"vendor","davidrjenni","scip-php","bin","scip-php");return{binary:"php",args:["-d","error_reporting=E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED",ar(r)?r:ar(n)?n:t]}},defaultOutputPath:"index.scip",markerFiles:["composer.json"],installMethods:[],installUrl:"https://github.com/davidrjenni/scip-php/releases"}};function je(e){return cr[e]}function sr(e,t){let n;try{n=wa(e)}catch{return null}for(let r of t)for(let i of n)if(i.endsWith(r))return bt(e,i);return null}import{readFileSync as xt,writeFileSync as vt}from"fs";import{create as oe}from"@bufbuild/protobuf";import{deserializeSCIP as It,serializeSCIP as Pt,DocumentSchema as Aa,IndexSchema as lr,MetadataSchema as La,SymbolInformationSchema as Ma}from"@c4312/scip";import{readFileSync as Ta,writeFileSync as Da}from"fs";import{create as ur}from"@bufbuild/protobuf";import{deserializeSCIP as Fa,DocumentSchema as Oa,IndexSchema as ja,serializeSCIP as Ca,SymbolRole as _a}from"@c4312/scip";function dr(e){let t;try{t=Fa(Ta(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=Rt(t);return n.removedDefinitionOccurrences>0&&Da(e,Buffer.from(Ca(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function Rt(e){let t=new Set;for(let o of e.documents)for(let a of o.symbols)a.symbol&&t.add(a.symbol);for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,r=0,i=[];for(let o of e.documents){let a=o.occurrences.filter(s=>(s.symbolRoles&_a.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(ur(Oa,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:ur(ja,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function wt(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=$a(e),n=Ga(e.flatMap(i=>i.documents??[])),r=fr(e.flatMap(i=>i.externalSymbols??[]));return oe(lr,{metadata:t,documents:n,externalSymbols:r})}function kt(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>It(xt(i))),r=wt(n);return vt(t,Buffer.from(Pt(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function pr(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>It(xt(i))),r=Rt(wt(n));return vt(t,Buffer.from(Pt(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function Na(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(r.projectRoot!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return oe(lr,{metadata:oe(La,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function gr(e,t,n){let r=It(xt(e)),i=Na(r,t,n);vt(e,Buffer.from(Pt(i)))}function $a(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 Ga(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,oe(Aa,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:Va([...r.occurrences,...n.occurrences]),symbols:fr([...r.symbols,...n.symbols]),text:Ua(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Va(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 fr(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,oe(Ma,{symbol:r.symbol,documentation:Wa([...r.documentation,...n.documentation]),relationships:Ba([...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 Ba(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 Ua(e,t){return e?t?e.length>=t.length?e:t:e:t}function Wa(e){return[...new Set(e)]}import{createHash as Ja}from"crypto";import{copyFileSync as qa,existsSync as mr,rmSync as hr}from"fs";import{resolve as Ha}from"path";import br from"better-sqlite3";var za={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}]},Ya={idx_chunks_doc_id:{table:"chunks",columns:["document_id"]},idx_chunks_line_range:{table:"chunks",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_document:{table:"defn_enclosing_ranges",columns:["document_id","start_line","end_line"]},idx_defn_enclosing_ranges_symbol_id:{table:"defn_enclosing_ranges",columns:["symbol_id"]},idx_global_symbols_symbol:{table:"global_symbols",columns:["symbol"]},idx_mentions_symbol_id_role:{table:"mentions",columns:["symbol_id","role"]}};function Rr(e){let t=Date.now(),n=Qa(e.affectedFiles);if(Xa(e.previousDbPath,e.miniDbPath,e.candidateDbPath),hr(e.candidateDbPath,{force:!0}),!mr(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!mr(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");yr(e.previousDbPath,"previous SQLite generation",!1),yr(e.miniDbPath,"incremental SQLite mini database"),qa(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new br(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Et(r,"main","candidate SQLite generation"),Et(r,"incremental","incremental SQLite mini database"),Ka(r,n),Za(r,n.length);let i=Tt(r,"main",!0),o=M(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{es(r),ts(r),ns(r),e.onStage?.("after-delete"),rs(r),e.onStage?.("after-symbol-reconciliation"),is(r),e.onStage?.("after-insert"),os(r),as(r,n.length,o),e.onStage?.("before-commit")}).immediate(),xr(r,"main","candidate SQLite generation");let c=[...ss(r)].filter(([u,d])=>i.get(u)!==d).map(([u])=>u).sort();return r.exec("DETACH DATABASE incremental"),r.close(),r=null,{candidateDbPath:e.candidateDbPath,affectedDocumentCount:n.length,changedDocumentPaths:c,durationMs:Date.now()-t}}catch(i){try{r?.close()}finally{hr(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function Qa(e){if(e.length===0)throw new Error("incremental SQLite publication requires affected documents");let t=[...e].sort();for(let n of t)if(!n||n.startsWith("/")||n.includes("\\")||n.split("/").includes(".."))throw new Error(`invalid affected document path: ${n}`);if(new Set(t).size!==t.length)throw new Error("incremental SQLite publication contains duplicate affected documents");return t}function Xa(e,t,n){let r=[e,t,n].map(i=>Ha(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function yr(e,t,n=!0){let r=new br(e,{readonly:!0,fileMustExist:!0});try{Et(r,"main",t),n&&xr(r,"main",t)}finally{r.close()}}function Et(e,t,n){for(let[r,i]of Object.entries(za)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:d})=>({name:s,type:c.toUpperCase(),notnull:u,pk:d}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(Ya)){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}`)}Sr(e,t,"documents",["relative_path"],n),Sr(e,t,"global_symbols",["symbol"],n)}function Sr(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 xr(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 Ka(e,t){e.exec("CREATE TEMP TABLE incremental_affected_paths (relative_path TEXT PRIMARY KEY) WITHOUT ROWID");let n=e.prepare("INSERT INTO temp.incremental_affected_paths(relative_path) VALUES (?)");e.transaction(i=>{for(let o of i)n.run(o)})(t)}function Za(e,t){let n=M(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=M(e,`SELECT COUNT(*) AS value
65
65
  FROM main.documents d
66
66
  JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
67
67
  FROM temp.incremental_affected_paths p
@@ -232,11 +232,11 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
232
232
  ${r}
233
233
  ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[d,p]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let l of p){let m=JSON.stringify([d,l]),g=c.get(l.relative_path)??[];g.push(m),c.set(l.relative_path,g)}let u=new Map;for(let[d,p]of[...c].sort(([l],[m])=>l.localeCompare(m))){let l=Ja("sha256");for(let m of p.sort())l.update(m).update(`
234
234
  `);u.set(d,l.digest("hex"))}return u}function M(e,t){return e.prepare(t).get().value}import{readFileSync as cs,writeFileSync as us}from"fs";function N(e,t){let n=Date.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:Date.now()-n,result:r}}function Ir(e){let t=e.readFingerprint(),n=ds(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return ls(e.cachePath,e.readFingerprint(),r),r}function ds(e,t){try{let n=JSON.parse(cs(e,"utf-8"));return vr(n.fingerprint)===vr(t)?{result:n.result}:null}catch{return null}}function ls(e,t,n){us(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
235
- `)}function vr(e){return JSON.stringify(e)}import{createHash as ps}from"crypto";import{existsSync as Dt,readFileSync as gs,readdirSync as fs}from"fs";import{dirname as Ft,join as Ce,relative as ms,resolve as jt,sep as Pr}from"path";function wr(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=Dr(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function kr(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=Dr(s,e);c&&c!==i&&a.add(c)}}return hs(e,r)}function Er(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 Ot(e){if(e===".")return"root";let t=ps("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Tr(e,t){let n=jt(e),r={};for(let i of t)r[i]=ys(n,i);return r}function Dr(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 hs(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 ys(e,t){let n=t==="."?e:Ce(e,t),r=Ss(n),i=bs(n),o=i?Rs(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 Ss(e){let t=Ce(e,"package.json");if(!Dt(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Ct(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 bs(e){let t=Ce(e,"tsconfig.json");if(Dt(t))return t;let n;try{n=fs(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?Ce(e,n[0]):void 0}function Rs(e,t){let n=Ct(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=xs(n.value,e,t),i=Fr(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function xs(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=Ft(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=jr(s,i,n);c&&o.add(c)}return[...o]}function Fr(e,t,n,r){let i=vs(t);if(i)return{pathsTargets:Is(i,Ft(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=Ps(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=Ct(o);return a.ok?Fr(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function vs(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 Is(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=jr(o,t,n);a&&r.add(a)}return[...r]}function Ps(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=jt(Ft(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Pr).includes("node_modules")&&Z(n,i)&&Dt(i))return i}function jr(e,t,n){let r=e.replace(/\/?\*+$/,""),i=jt(t,r===""?".":r);if(!Z(n,i))return;let a=ms(n,i).split(Pr).join("/");return a===""?".":a}function ws(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]!==`
236
- `;)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 Ct(e){try{let t=gs(e,"utf-8"),n=JSON.parse(ws(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as bi,randomUUID as zt}from"crypto";import{closeSync as Ri,constants as rc,copyFileSync as mi,existsSync as B,lstatSync as ic,mkdirSync as _,mkdtempSync as xi,openSync as vi,readdirSync as oc,readFileSync as F,realpathSync as ac,renameSync as z,rmSync as V,statSync as sc,unlinkSync as qt,writeFileSync as Ii}from"fs";import{dirname as Pi,join as f,resolve as me}from"path";import{setTimeout as cc}from"timers/promises";import{pathToFileURL as hi}from"url";import{deserializeSCIP as wi}from"@c4312/scip";import uc from"better-sqlite3";import{createRequire as ks}from"module";var Es=ks(import.meta.url),Or=Ts().version;function Ts(){for(let e of["../package.json","../../package.json"])try{return Es(e)}catch{}return{version:"0.0.0"}}import{lstatSync as Us,readdirSync as Ws}from"fs";import{join as Js,relative as qs,resolve as Bt,sep as Hs}from"path";import{createHash as Ds}from"crypto";import{existsSync as At,mkdirSync as Fs,readFileSync as _e,readdirSync as fp,renameSync as js,rmSync as mp,writeFileSync as Os}from"fs";import{join as Q}from"path";import{create as _r,fromBinary as Ar,toBinary as Cs}from"@bufbuild/protobuf";import{deserializeSCIP as Ae,DocumentSchema as Lt,IndexSchema as Lr,serializeSCIP as Mr}from"@c4312/scip";var Le=1,ae="typescript-scip-fragments";function Nr(e){if(e.length===0)throw new Error("affected TypeScript mini index requires documents");let t=new Set,n=[];for(let o of e){let a=q(o.relativePath);if(t.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(t.add(a),o.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${a}`);let s=Ar(Lt,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=Mr(_r(Lr,{documents:n,externalSymbols:[]})),i=Ae(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function Me(e){let t=Q(e,ae);return{rootDir:t,blobDir:Q(t,"blobs"),generationDir:Q(t,"generations")}}function _s(e){let t=Ae(e.indexBytes);Qr(t.metadata,Xr(e)),Yr(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let a=q(o.relativePath);if(n.has(a))throw new Error(`duplicate TypeScript SCIP document path: ${a}`);n.add(a);let s=Cs(Lt,o),c=e.documentIdentities.get(a)??(e.allowUntrackedDocuments?H(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:a,contentHash:H(s)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${a}`);r.push(Jr(e.cacheDir,{relativePath:a,bytes:s,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=qr(e,r);return Hr(e.cacheDir,i),i}function $r(e){let t=Me(e.cacheDir);if(!At(Mt(t,e.generationIdentity)))return _s(e);let n=Vr({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity});if(!e.allowUntrackedDocuments&&n.manifest.documents.length!==e.documentIdentities.size)throw new Error("TypeScript fragment generation document identities changed");for(let r of n.manifest.documents){let i=e.documentIdentities.get(r.relativePath);if(!(i===void 0&&e.allowUntrackedDocuments)&&i!==r.documentIdentity)throw new Error(`TypeScript fragment generation document identity changed: ${r.relativePath}`)}return n.manifest}function Gr(e){let t=Vr({cacheDir:e.cacheDir,generationIdentity:e.previousGenerationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity}).manifest,n=new Map(t.documents.map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let a=q(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(r.add(a),!n.has(a))throw new Error(`TypeScript fragment replacement has no prior document: ${a}`);let s=e.documentIdentities.get(a);if(!s)throw new Error(`missing TypeScript document identity: ${a}`);o.bytes===null?n.delete(a):n.set(a,Jr(e.cacheDir,o,s))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=qr(e,[...n.values()]);return Hr(e.cacheDir,i),i}function Vr(e){let t=Me(e.cacheDir),n=Mt(t,e.generationIdentity),r;try{r=zr(_e(n,"utf8"))}catch(o){throw new Error(`TypeScript fragment generation is unavailable: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(r.generationIdentity!==e.generationIdentity)throw new Error("TypeScript fragment generation identity does not match its manifest path");if(e.producerIdentity&&r.producerIdentity!==e.producerIdentity)throw new Error("TypeScript fragment producer identity changed");if(e.projectIdentity&&r.projectIdentity!==e.projectIdentity)throw new Error("TypeScript fragment project identity changed");let i=new Map;for(let o of r.documents){let a=Q(t.blobDir,`${o.blobHash}.scipdoc`),s=_e(a);if(s.byteLength!==o.byteLength||H(s)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,s)}return{manifest:r,fragments:i}}function Br(e){let t=Wr(e);return _t(t.baseIndex,t.completeDocuments,"assembled")}function Ur(e){let t=Wr(e);return As(t.deletedAffectedPaths),{completeIndexBytes:_t(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:_t(t.baseIndex,t.affectedDocuments,"affected")}}function Wr(e){let t=Ae(e.baseIndexBytes);Qr(t.metadata,Xr(e)),Yr(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=q(s.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);n.set(c,s)}if(n.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let r=new Set,i=[],o=[],a=[];for(let s of t.documents){let c=q(s.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let u=n.get(c);if(!u){i.push(s);continue}if(n.delete(c),u.bytes===null){a.push(c);continue}let d=Ar(Lt,u.bytes);if(d.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${d.relativePath}`);i.push(d),o.push(d)}if(n.size>0)throw new Error(`TypeScript fragment replacement has no prior document: ${[...n.keys()].sort()[0]}`);return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:a}}function _t(e,t,n){let r=Mr(_r(Lr,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=Ae(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function As(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function Jr(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=q(t.relativePath),i=Buffer.from(t.bytes),o=H(i),a=Me(e);Fs(a.blobDir,{recursive:!0});let s=Q(a.blobDir,`${o}.scipdoc`);if(At(s)){let c=_e(s);if(c.byteLength!==i.byteLength||H(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${s}.${process.pid}.${Date.now()}.tmp`;Os(c,i),js(c,s)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function qr(e,t){if(!e.producerIdentity||!e.projectIdentity||!e.generationIdentity)throw new Error("TypeScript fragment generation identities must be non-empty");let n=[...t].sort((r,i)=>r.relativePath.localeCompare(i.relativePath));if(new Set(n.map(r=>r.relativePath)).size!==n.length)throw new Error("TypeScript fragment generation contains duplicate document paths");return{version:Le,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function Hr(e,t){let n=Me(e),r=Mt(n,t.generationIdentity);if(At(r)){let i=zr(_e(r,"utf8"));if(Cr(i)!==Cr(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}b(r,t,{spacing:2,trailingNewline:!0})}function Cr(e){return H(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function zr(e){let t=JSON.parse(e);if(t.version!==Le||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let n=new Set;for(let r of t.documents){if(!r||typeof r.relativePath!="string"||typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash)||typeof r.byteLength!="number"||!Number.isInteger(r.byteLength)||r.byteLength<0||typeof r.documentIdentity!="string"||!r.documentIdentity)throw new Error("invalid TypeScript fragment record");if(q(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function Mt(e,t){return Q(e.generationDir,Ls(t))}function Ls(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${H(e)}.json`}function Yr(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function Qr(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 Xr(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function q(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.includes("\\"))throw new Error(`invalid TypeScript SCIP document path: ${e}`);let t=e.split("/");if(t.includes("")||t.includes(".")||t.includes(".."))throw new Error(`invalid TypeScript SCIP document path: ${e}`);return e}function H(e){return Ds("sha256").update(e).digest("hex")}import{createHash as Ms}from"crypto";import{existsSync as se,mkdirSync as Ns,readFileSync as ue,readdirSync as Nt,renameSync as $s,rmSync as Kr,writeFileSync as Gs}from"fs";import{join as D}from"path";var Ne=1,ei=64*1024*1024,de="typescript-scip-overlays";function ti(e){let t=ii(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t&&(t.producerIdentity!==e.producerIdentity||t.projectIdentity!==e.projectIdentity))throw new Error("TypeScript overlay producer or project identity changed");let n=new Map((t?.overlays??[]).map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let a=Vt(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript overlay: ${a}`);r.add(a),n.set(a,Vs(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:Ne,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...n.values()].sort((o,a)=>o.relativePath.localeCompare(a.relativePath))};return Bs(e.cacheDir,i),i}function ni(e){let t=ii(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=ue(D(le(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||ce(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 Br({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function ri(e,t){let n=le(e),r=D(n,"generations");if(!se(r))return;let i=new Set(t.map(Gt)),o=new Set;for(let s of Nt(r).filter(c=>i.has(c))){let c=$t(ue(D(r,s),"utf8"));for(let u of c.overlays)u.blobHash&&o.add(`${u.blobHash}.scipdoc`)}for(let s of Nt(r))i.has(s)||Kr(D(r,s),{force:!0});let a=D(n,"blobs");if(se(a))for(let s of Nt(a))o.has(s)||Kr(D(a,s),{force:!0})}function ii(e,t){let n=D(le(e),"generations",Gt(t));if(!se(n))return null;let r=$t(ue(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function Vs(e,t){let n=Vt(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=ce(r),o=D(le(e),"blobs");Ns(o,{recursive:!0});let a=D(o,`${i}.scipdoc`);if(se(a)){let s=ue(a);if(s.byteLength!==r.byteLength||ce(s)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let s=`${a}.${process.pid}.${Date.now()}.tmp`;Gs(s,r),$s(s,a)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function Bs(e,t){let n=D(le(e),"generations",Gt(t.generationIdentity));if(se(n)){let r=$t(ue(n,"utf8"));if(Zr(r)!==Zr(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}b(n,t,{spacing:2,trailingNewline:!0})}function $t(e){let t=JSON.parse(e);if(t.version!==Ne||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(Vt(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function le(e){return D(e,de)}function Gt(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${ce(e)}.json`}function Zr(e){return ce(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function Vt(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}function ce(e){return Ms("sha256").update(e).digest("hex")}var pe=1,Ut="language-indexes",oi=["index.db","index.scip","meta.json"],ai=[Ut,ae,de];function $e(e){let t=[];for(let n of oi)zs(e,n),t.push(n);for(let n of ai)si(e,n,t);return{version:pe,files:t.sort()}}function Ge(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(!oi.includes(e)&&!ai.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function O(e,t){let n=Ge(t),r=Bt(e),i=Bt(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${Hs}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function si(e,t,n){let r=Js(e,t),i;try{i=Ws(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()?si(e,a,n):o.isFile()&&n.push(Ge(a))}}function zs(e,t){let n=O(e,t),r;try{r=Us(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(qs(Bt(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{createHash as Ys}from"crypto";import{copyFileSync as ci,existsSync as $,linkSync as Qs,mkdirSync as ui,readFileSync as pi,readdirSync as di,renameSync as Jt,rmSync as Be,statSync as Xs}from"fs";import{basename as Ve,dirname as ge,join as P,relative as li}from"path";var X=1,Ue=".scipquery-generations";function We(e){let t=Je(e.outputDb),n=Ks(e,t);e.onStage?.("after-recovery-retained"),e.preserveOutputScip||Wt(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),Wt(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),Wt(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let r=qe(e.metaPath,e.outputDb),i={version:X,currentGeneration:r,...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:(e.now??(()=>new Date))().toISOString()};return b(P(t,"state.json"),i,{spacing:2,trailingNewline:!0}),{currentGeneration:r,...n?{previousGeneration:n}:{}}}function gi(e){try{let t=JSON.parse(pi(P(Je(e),"state.json"),"utf8"));return t.version!==X||typeof t.currentGeneration!="string"||!t.currentGeneration||typeof t.publishedAt!="string"||!Number.isFinite(Date.parse(t.publishedAt))||!tc(t.previousGeneration)||!nc(t.publication)?null:t}catch{return null}}function fi(e,t,n=()=>new Date){if(!$(e)||!$(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=gi(e),i={version:X,currentGeneration:qe(t,e),...r?.previousGeneration?{previousGeneration:r.previousGeneration}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return b(P(Je(e),"state.json"),i,{spacing:2,trailingNewline:!0}),i}function G(e,t=P(ge(e),"meta.json")){let n=P(Je(e),"state.json");if(!$(n))return{state:"legacy",statePath:n};let r=gi(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=qe(t,e),o=r.currentGeneration===i,a=r.previousGeneration?$(P(ge(e),r.previousGeneration.databasePath)):!0;return!o||!a?{state:"drifted",statePath:n,currentMatches:o,recoveryExists:a,generation:r,reason:o?"retained recovery database is missing":"stable database or metadata no longer matches the published generation"}:{state:"current",statePath:n,currentMatches:o,recoveryExists:a,generation:r}}catch(i){return{state:"drifted",statePath:n,currentMatches:!1,recoveryExists:!1,generation:r,reason:i instanceof Error?i.message:String(i)}}}function Je(e){return P(ge(e),Ue)}function Ks(e,t){if(!$(e.outputDb))return;let n=qe(e.metaPath,e.outputDb),r=P(t,n),i=P(r,Ve(e.outputDb)),o=$(e.metaPath)?P(r,Ve(e.metaPath)):void 0;if(!$(i)){let a=`${r}.${process.pid}.${Date.now()}.tmp`;Be(a,{recursive:!0,force:!0}),ui(a,{recursive:!0});let s=P(a,Ve(e.outputDb));try{Qs(e.outputDb,s)}catch{ci(e.outputDb,s)}o&&ci(e.metaPath,P(a,Ve(e.metaPath))),ui(t,{recursive:!0}),Jt(a,r)}return Zs(t,n),{generationIdentity:n,databasePath:li(ge(e.outputDb),i),...o?{metadataPath:li(ge(e.outputDb),o)}:{}}}function Zs(e,t){for(let n of di(e,{withFileTypes:!0}))!n.isDirectory()||n.name===t||n.name.endsWith(".tmp")||Be(P(e,n.name),{recursive:!0,force:!0});for(let n of di(e,{withFileTypes:!0}))n.isDirectory()&&n.name.endsWith(".tmp")&&Be(P(e,n.name),{recursive:!0,force:!0})}function qe(e,t){let n=Ys("sha256").update(`sqlite-generation-v${X}\0`);$(e)&&n.update(ec(pi(e,"utf8")));let r=Xs(t);return n.update(`\0${r.size}`),n.digest("hex")}function ec(e){try{let t=JSON.parse(e);if((t.version===2||t.version===3)&&t.status==="complete"&&typeof t.updatedAt=="string"&&t.fingerprint!==void 0)return JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages,scipCompanion:t.scipCompanion})}catch{}return e}function Wt(e,t){Be(`${t}.tmp-replace`,{force:!0}),Jt(e,`${t}.tmp-replace`),Jt(`${t}.tmp-replace`,t)}function tc(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e;return typeof t.generationIdentity=="string"&&!!t.generationIdentity&&typeof t.databasePath=="string"&&!!t.databasePath&&(t.metadataPath===void 0||typeof t.metadataPath=="string"&&!!t.metadataPath)}function nc(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e,n=[t.converterDurationMs,t.affectedDocumentCount,t.changedDocumentCount,t.producerDurationMs,t.materializationDurationMs,t.patchDurationMs].filter(r=>r!==void 0);return(t.mode==="incremental"||t.mode==="full")&&t.validation==="passed"&&t.converterDurationMs!==void 0&&n.every(r=>typeof r=="number"&&Number.isFinite(r)&&r>=0)&&(t.scipCompanion===void 0||t.scipCompanion==="current"||t.scipCompanion==="deferred")&&(t.typescriptOverlayGeneration===void 0||typeof t.typescriptOverlayGeneration=="string"&&!!t.typescriptOverlayGeneration)&&(t.scipCompanion!=="deferred"||!!t.typescriptOverlayGeneration)&&(t.fallbackReason===void 0||typeof t.fallbackReason=="string")}var Yt=1,yi="SCIP_QUERY_SHARED_CACHE",Ht=JSON.stringify({cliVersion:Or,artifactCatalogVersion:pe,sqliteGenerationStoreVersion:X,typescriptFragmentStoreVersion:Le,typescriptOverlayStoreVersion:Ne}),ki="manifest.json",dc="shared-cache.json",Qt=[Ut,ae,de];function He(e,t){if(!e.clean||!e.treeOid)return;let n=ye(JSON.stringify({version:Yt,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:Ht}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:Ht,generationId:n,repositoryCacheDir:Ln(e.repositoryId)}}function Ei(e,t,n){if(process.env[yi]==="0")return`${yi}=0`;if(!Mn(n))return"explicit cache or database override";if(me(t)!==me(f(An(e),"index.db")))return"index database is outside the managed worktree cache"}function C(e,t=!0){let n=Kt(e),r;try{r=pc(F(f(n,ki),"utf8"))}catch{return null}if(r.generationId!==e.generationId||r.repositoryId!==e.repositoryId||r.treeOid!==e.treeOid||r.producerIdentity!==e.producerIdentity||JSON.stringify(r.fingerprint)!==JSON.stringify(e.fingerprint))return null;if(!t)return r;try{for(let i of r.artifacts){let o=O(n,i.path),a=sc(o);if(!a.isFile()||a.size!==i.size||ye(F(o))!==i.sha256)return null}}catch{return null}return r}function Ti(e){let t=C(e.snapshot);if(t)return t;if(!Oi(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=Si(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=$e(e.sourceCacheDir),i=f(e.snapshot.repositoryCacheDir,"generations");_(i,{recursive:!0});let o=xi(f(i,`.tmp-${process.pid}-`));try{let a=[];for(let p of r.files){let l=O(e.sourceCacheDir,p),m=O(o,p);he(l,m);let g=F(m);a.push({path:p,size:g.byteLength,sha256:ye(g)})}let s=wi(F(f(o,"index.scip"))).metadata?.projectRoot;if(!s)throw new Error("shared SCIP generation has no project root metadata");let c=Zt(e.sourceProjectRoot);if(s!==c)throw new Error("shared SCIP generation root does not match its source worktree");if(Si(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let u={version:Yt,artifactCatalogVersion:pe,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:s,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:a.sort((p,l)=>p.path.localeCompare(l.path))};b(f(o,ki),u,{spacing:2,trailingNewline:!0});let d=Kt(e.snapshot);try{if(B(d)&&!C(e.snapshot)){let p=`${d}.corrupt-${process.pid}-${Date.now()}`;z(d,p),V(p,{recursive:!0,force:!0})}z(o,d)}catch(p){let l=C(e.snapshot);if(l)return l;throw p}return u}finally{V(o,{recursive:!0,force:!0})}}function Xt(e){let t=Kt(e.snapshot);_(e.targetCacheDir,{recursive:!0});let n=ie(f(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:3e4});if(!n)throw new Error("timed out waiting for another cache hydration");let r,i,o=!1;try{r=xi(f(e.targetCacheDir,".shared-hydrate-")),Rc(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let u=O(t,c.path),d=O(r,c.path);he(u,d);let p=F(d);if(p.byteLength!==c.size||ye(p)!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=Zt(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&gr(O(r,c.path),e.manifest.scipProjectRoot,a);if(!Oi(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=yc(e.targetCacheDir,r),o=!0,Sc(r,e.targetCacheDir,i),We({tempOutputScip:f(r,"index.scip"),tempOutputDb:f(r,"index.db"),tempMetaPath:f(r,"meta.json"),outputScip:f(e.targetCacheDir,"index.scip"),outputDb:f(e.targetCacheDir,"index.db"),metaPath:f(e.targetCacheDir,"meta.json"),now:e.now});let s=G(f(e.targetCacheDir,"index.db"),f(e.targetCacheDir,"meta.json"));if(s.state==="invalid"||s.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${s.reason}`);ze(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&bc(e.targetCacheDir,i),a}finally{r&&V(r,{recursive:!0,force:!0}),n.release()}}async function Di(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??Date.now,o=i()+n,a=f(e.repositoryCacheDir,"locks"),s=f(a,`${e.generationId}.lock`);for(_(a,{recursive:!0});i()<=o;){if(C(e))return{kind:"generation-ready"};let c=zt();try{let u=vi(s,"wx");try{Ii(u,`${JSON.stringify({version:1,pid:process.pid,token:c,generationId:e.generationId,startedAt:new Date(i()).toISOString()})}
237
- `)}finally{Ri(u)}return{kind:"owner",release:()=>{try{let d=JSON.parse(F(s,"utf8"));d.pid===process.pid&&d.token===c&&qt(s)}catch{}}}}catch(u){if(u.code!=="EEXIST")return{kind:"timeout"};let d=Fi(s);if(d&&(d.pid===void 0||!T(d.pid))){mc(s,d);continue}await cc(r)}}return C(e)?{kind:"generation-ready"}:{kind:"timeout"}}function ze(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:lc(i)};return hc(e.repositoryCacheDir,o,!0),o}function lc(e){return ye(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:me(e.projectRoot),localCacheDir:me(e.localCacheDir)}))}function pc(e){let t=JSON.parse(e);if(t.version!==Yt||t.artifactCatalogVersion!==pe||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!==Ht||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(Ge(r.path),n.has(r.path))throw new Error(`duplicate shared generation artifact: ${r.path}`);n.add(r.path)}for(let r of["index.db","index.scip","meta.json"])if(!n.has(r))throw new Error(`shared generation is missing ${r}`);return t}function he(e,t){_(Pi(t),{recursive:!0});try{mi(e,t,rc.COPYFILE_FICLONE)}catch{mi(e,t)}}function gc(e,t,n){_(e,{recursive:!0}),b(f(e,dc),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function Si(e){try{let t=$e(e),n=bi("sha256");for(let r of t.files){let i=F(O(e,r));n.update(r).update("\0").update(String(i.byteLength)).update("\0").update(i).update("\0")}return n.digest("hex")}catch{return null}}function fc(e){try{return JSON.parse(F(f(e,"meta.json"),"utf8"))}catch{return}}function Kt(e){return f(e.repositoryCacheDir,"generations",e.generationId)}function Fi(e){try{let t=F(e,"utf8"),n=JSON.parse(t),r=typeof n.pid=="number"&&Number.isSafeInteger(n.pid)&&n.pid>0?n.pid:void 0;return{raw:t,...r===void 0?{}:{pid:r}}}catch{return null}}function mc(e,t){let n=`${e}.reclaim`,r=zt(),i;try{i=vi(n,"wx")}catch{return!1}try{Ii(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
238
- `)}finally{Ri(i)}try{let o=Fi(e);return!o||o.raw!==t.raw||o.pid!==void 0&&T(o.pid)?!1:(qt(e),!0)}catch{return!1}finally{try{let o=JSON.parse(F(n,"utf8"));o.pid===process.pid&&o.token===r&&qt(n)}catch{}}}function hc(e,t,n){let r=Wn(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!B(f(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=f(e,"worktrees");_(i,{recursive:!0}),b(f(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),gc(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function yc(e,t){let n=f(t,".rollback"),r=new Map,i=new Map;_(n,{recursive:!0});for(let s of["index.scip","index.db","meta.json"]){let c=f(e,s),u=B(c);r.set(s,u),u&&he(c,f(n,"stable",s))}for(let s of Qt){let c=f(e,s),u=B(c);if(u){let d=ic(c);if(!d.isDirectory()||d.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${s}`)}i.set(s,u)}let o=f(e,Ue),a=B(o);return a&&ji(o,f(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:a}}function Sc(e,t,n){for(let r of Qt){let i=f(t,r);if(n.managedDirectories.get(r)){let a=f(n.root,"managed",r);_(Pi(a),{recursive:!0}),z(i,a)}let o=f(e,r);B(o)&&z(o,i)}}function bc(e,t){for(let i of Qt){let o=f(e,i),a=f(t.root,"managed",i);t.managedDirectories.get(i)?B(a)&&(V(o,{recursive:!0,force:!0}),z(a,o)):V(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let a=f(e,i);if(!o){V(a,{force:!0});continue}let s=`${a}.shared-restore-${zt()}`;he(f(t.root,"stable",i),s),V(a,{force:!0}),z(s,a)}let n=f(e,Ue);V(n,{recursive:!0,force:!0});let r=f(t.root,"sqlite-generations");t.generationStoreExisted&&B(r)&&z(r,n)}function ji(e,t){_(t,{recursive:!0});for(let n of oc(e,{withFileTypes:!0})){let r=f(e,n.name),i=f(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?ji(r,i):n.isFile()&&he(r,i)}}function Rc(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||JSON.stringify(e.fingerprint)!==JSON.stringify(t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function Oi(e,t,n,r=!0,i=!0){try{let o=fc(e);if(o?.status!=="complete"||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return fe("source validation rejected metadata"),!1;let a=$e(e),s=G(f(e,"index.db"),f(e,"meta.json"));if(r?s.state!=="current":s.state==="invalid"||s.state==="drifted")return fe(`source validation rejected SQLite generation state ${s.state}`),!1;let c=new uc(f(e,"index.db"),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let u=Zt(t),p=(i?a.files.filter(l=>l.endsWith(".scip")):["index.scip"]).every(l=>{let m=wi(F(O(e,l))).metadata?.projectRoot;return m!==u&&fe(`source validation rejected SCIP root for ${l}: ${String(m)}`),m===u});return p||fe("source validation rejected SCIP project roots"),p}catch(o){return fe(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function fe(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function Zt(e){try{return hi(ac(e)).href}catch{return hi(me(e)).href}}function ye(e){return bi("sha256").update(e).digest("hex")}import{existsSync as xc,readFileSync as vc,readdirSync as Ic,statSync as Pc}from"fs";import x from"path";var wc=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function Se(e,t=[]){let n=x.resolve(e),r=t.flatMap(c=>Ec(n,c));if(r.length>0)return Ci(n,_i(r));let i=kc(n),o=_i(i),a=Dc(n,o)?[n,...o]:o,s=a.length>0?a:[n];return Ci(n,s)}function Ci(e,t){return[...new Set(t.map(n=>jc(e,n)))].sort((n,r)=>n.localeCompare(r))}function kc(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=Ic(r,{withFileTypes:!0})}catch{continue}for(let o of i){let a=x.join(r,o.name);if(o.isDirectory()){!wc.has(o.name)&&!o.name.startsWith(".")&&n.push(a);continue}o.isFile()&&Tc(a)&&t.push(x.dirname(a))}}return t}function Ec(e,t){let n=t.trim();if(!n)return[];let r=x.resolve(e,n);if(!Z(e,r))return[];try{let i=Pc(r);if(i.isDirectory())return[r];if(i.isFile()&&Ai(x.basename(r)))return[x.dirname(r)]}catch{return[]}return[]}function Tc(e){if(!Ai(x.basename(e)))return!1;let t=Li(e);return t?x.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function Ai(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function _i(e){let t=[...new Set(e.map(n=>x.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&Oc(n,r)))}function Dc(e,t){if(t.length===0||t.some(r=>x.resolve(r)===e))return!1;let n=x.join(e,"tsconfig.json");return xc(n)&&Fc(n)}function Fc(e){let n=Li(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!x.extname(r))):!1}function Li(e){try{let t=JSON.parse(vc(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function jc(e,t){let n=x.relative(e,t);return n?n.split(x.sep).join("/"):"."}function Oc(e,t){let n=x.relative(e,t);return!!n&&!n.startsWith("..")&&!x.isAbsolute(n)}import{createHash as Zc}from"crypto";import{existsSync as tn,readFileSync as Yi,statSync as eu,writeFileSync as nn}from"fs";import{join as tu}from"path";import{readFileSync as Mi}from"fs";import{createRequire as Cc}from"module";import{dirname as _c,isAbsolute as cg,relative as ug,resolve as dg,sep as lg}from"path";var Ni=Cc(import.meta.url),Ac=1,$i="0.4.0";function en(){let e=Lc();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Lc(){try{let e=Ni.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(Mi(e,"utf8"));if(t.version!==$i)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${$i}`};let n=_c(e),r=Ni.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(Mi(r,"utf8"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:Mc(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Mc(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Ac}`}import{createHash as Nc}from"crypto";import{readFileSync as $c}from"fs";import{dirname as Gc,join as Ye}from"path";var Qe=2,Vc="typescript-index";function Gi(e){let t=Ye(e,Vc);return{rootDir:t,requestDir:Ye(t,"requests"),responseDir:Ye(t,"responses")}}function Vi(e){try{let t=JSON.parse($c(Ye(Gc(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:Nc("sha256").update(JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages})).digest("hex")}catch{return null}}import{randomUUID as Bc}from"crypto";import{existsSync as Uc,mkdirSync as Bi,readFileSync as Wc,rmSync as Ui}from"fs";import{resolve as Wi}from"path";var Jc=12e4,qc=5,Xe=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=jn(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Xc(),this.runtime=n.runtime??Kc}request(t){let n=Fn(this.cacheDir),r=Gi(this.cacheDir),i=dt(n.statePath);if(!Ji(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),a=Wi(r.requestDir,`${o}.json`),s=Wi(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;Bi(r.requestDir,{recursive:!0}),Bi(r.responseDir,{recursive:!0}),b(a,{protocolVersion:Qe,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(Uc(s))return Hc(Wc(s,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let u=dt(n.statePath);if(!Ji(u,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(qc)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{Ui(a,{force:!0}),Ui(s,{force:!0})}}};function Ji(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=Dn,i=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===Qe&&n.isProcessAlive(e.pid)&&(r||i)}function Hc(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==Qe||o.id!==t||o.ok===!0&&o.baseGeneration!==n)throw new Error("TypeScript index service wrote an incompatible response.");if(o.ok!==!0)throw new Error(typeof o.error=="string"?o.error:"TypeScript index service request failed.");let a=zc(o.response,r),s=[...new Set(i)].sort(),c=a.fragments.map(u=>u.relativePath).sort();if(JSON.stringify(c)!==JSON.stringify(s))throw new Error("TypeScript index service omitted or added an affected document.");return a}function zc(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(Yc)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:Qc(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 Yc(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 Qc(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Xc(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Jc}var Kc={now:Date.now,randomId:Bc,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:T};function nu(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."];if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let n=ke(e.previousSnapshot,e.currentSnapshot);if(n.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};if(n.changes.some(u=>u.kind!=="modified"||u.inputKind!=="source"||!lt(u.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=Fe(n,e.graph,e.projectFiles);if(r.mode!=="closure"||r.affectedFiles.length===0)return{eligible:!1,reason:r.reasons.length>0?`affected set widened: ${r.reasons.join(", ")}`:"empty affected set"};let i=ru([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=qi(e.currentSnapshot,e.projectFiles,e.producerIdentity),a=qi(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==a)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let s=zi(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!s)return{eligible:!1,reason:"prior document identity unavailable"};let c=zi(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:Hi(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:Hi(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:s,nextDocumentIdentities:c,tsconfigPath:i==="."?"tsconfig.json":`${i}/tsconfig.json`,projectArgument:i}:{eligible:!1,reason:"next document identity unavailable"}}function ru(e,t){let n=null;for(let r of e){let i=t.filter(o=>o==="."||r===o||r.startsWith(`${o}/`));if(i.length!==1||n!==null&&n!==i[0])return null;n=i[0]}return n}function Qi(e){let t=Date.now();try{if(!tn(e.previousDbPath)||!tn(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=en();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new W({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a,s;try{a=Pe(o,{includeIgnored:!1}).filter(lt).sort(),s=we(o)}finally{o.close()}let c=performance.now()-n,u=nu({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?Se(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:a,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:tn(tu(e.projectRoot,"tsconfig.json"))});if(!u.eligible)throw new Error(u.reason);let d=Vi(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let l=new Xe({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:d}).request({kind:"emit-documents",tsconfigPath:u.tsconfigPath,projectArgument:u.projectArgument,projectIdentity:u.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles}),m=performance.now()-n,g=eu(e.previousShardPath).size>=ei;n=performance.now();let I=g?null:Yi(e.previousShardPath),S=g?{completeIndexBytes:null,affectedIndexBytes:Nr(l.fragments)}:Ur({packageVersion:r.packageVersion,baseIndexBytes:I,fragments:l.fragments}),R=performance.now()-n;n=performance.now(),g?ti({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,nextGenerationIdentity:u.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:l.fragments}):($r({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:I,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.previousFragmentGeneration,documentIdentities:u.previousDocumentIdentities,allowUntrackedDocuments:!0}),Gr({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.nextFragmentGeneration,fragments:l.fragments,documentIdentities:u.nextDocumentIdentities}));let y=performance.now()-n;n=performance.now(),S.completeIndexBytes&&nn(e.candidateShardPath,S.completeIndexBytes),nn(e.candidateAffectedScipPath,S.affectedIndexBytes);let w=performance.now()-n,k={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:Date.now()-t,cold:l.cold,changedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:u.previousFragmentGeneration,nextFragmentGeneration:u.nextFragmentGeneration,manifest:u.manifest,plan:u.plan,projectFileCount:a.length,referenceFragmentsByFile:new Map(l.fragments.map(Ie=>[Ie.relativePath,Ie.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:m,serviceMs:l.durationMs,assemblyMs:R,fragmentStoreMs:y,writeMs:w}};return e.onStatus(`Incremental TypeScript index emitted ${k.affectedFiles.length} affected document(s) in ${(k.durationMs/1e3).toFixed(3)}s (${k.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${m.toFixed(0)}ms, assembly ${R.toFixed(0)}ms, fragments ${y.toFixed(0)}ms, write ${w.toFixed(0)}ms).`),k}catch(n){return e.onStatus(`Incremental TypeScript index unavailable: ${n instanceof Error?n.message:String(n)}. Falling back to the whole-project indexer.`),null}}function Xi(e){let t=en();if(!t.available)throw new Error(t.reason);let n=ni({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:Yi(e.baseShardPath),packageVersion:t.packageVersion});nn(e.candidateShardPath,n)}function qi(e,t,n){let r=e.files.filter(i=>wn(i.path,e.languages)!=="source").map(i=>({path:i.path,size:i.size,hash:i.hash})).sort((i,o)=>i.path.localeCompare(o.path));return rn(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function Hi(e,t){return rn(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function zi(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),a=On({projectFiles:t.filter(c=>o.has(c)),snapshot:e,graph:n,engineIdentity:r}),s=new Map;for(let c of i){let u=a.identityFor(c,"typescript-scip-document-v1");if(u.key){s.set(c,u.key);continue}if(o.has(c))return null;s.set(c,rn(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function rn(e){return Zc("sha256").update(e).digest("hex")}import{execFile as iu}from"child_process";import{existsSync as Ke,renameSync as an,rmSync as sn,statSync as ou}from"fs";import{cpus as au}from"os";import{join as Ki}from"path";function su(e,t,n){if(!e.defaultOutputPath)return;let r=Ki(t,e.defaultOutputPath);n!==r&&Ke(r)&&an(r,n)}function cu(e,t,n){if(!e.defaultOutputPath)return null;let r=Ki(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return sn(i,{force:!0}),Ke(r)?(an(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function uu(e){e&&(sn(e.defaultOutputPath,{force:!0}),e.backupPath&&Ke(e.backupPath)&&an(e.backupPath,e.defaultOutputPath))}function du(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,au().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Zi(e,t,n,r){let i=e.filter(u=>u.config.defaultOutputPath),o=e.filter(u=>!u.config.defaultOutputPath),a=[],s=du(o.length,r),c=await pu(o,s,u=>on(u,t,n));if(s>1){let u=new Map;for(let d of c.filter(p=>p.skipped)){let p=o.find(l=>l.id===d.id);p&&(n(`Retrying ${p.label} indexer serially after parallel failure...`),u.set(p.id,await on(p,t,n)))}a.push(...c.map(d=>u.get(d.id)??d))}else a.push(...c);for(let u of i)a.push(await on(u,t,n));return a.sort((u,d)=>e.findIndex(p=>p.id===u.id)-e.findIndex(p=>p.id===d.id))}async function on(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),sn(e.scipPath,{force:!0});let r=cu(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{let s=Pn(e.binary,e.args);await lu(s.binary,s.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),su(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.message:String(s),u=`${e.resolvedBinary} indexer failed: ${c.split(`
239
- `)[0]}`,d=e.label===e.language?u:`${e.label}: ${u}`;return n(`Skipping ${e.label}: ${u}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:d}}}finally{uu(r)}if(!Ke(e.scipPath)){let s=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,c=e.label===e.language?s:`${e.label}: ${s}`;return n(`Skipping ${e.label}: ${s}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:c}}}let a;try{a=ou(e.scipPath).size}catch{a=void 0}return{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,outputBytes:a}}function lu(e,t,n){return new Promise((r,i)=>{iu(e,[...t],n,o=>{o?i(o):r()})})}async function pu(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=0,o=Math.max(1,Math.min(e.length,t)),a=Array.from({length:o},async()=>{for(;i<e.length;){let s=i++;r[s]=await n(e[s])}});return await Promise.all(a),r}import{execFileSync as gu}from"child_process";import{platform as fu}from"os";function cn(e,t){let n=e.installMethods,r=ne(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(at(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{gu(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:fu()==="win32"});let o=re(e);if(o){let a=o===e.indexerBinary?"":` (using ${o})`;return t(`Successfully installed ${r} via ${i.label}${a}`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(o){let a=o instanceof Error?o.message:String(o);t(`${i.label} install failed: ${a}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}import Yu from"better-sqlite3";import{existsSync as Qu}from"fs";import{dirname as Xu,join as Ku,resolve as Zu}from"path";import{readFileSync as hu,rmSync as yu,statSync as Su,mkdtempSync as bu}from"fs";import{tmpdir as Ru}from"os";import{join as un}from"path";import{Worker as xu}from"worker_threads";function mu(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function K(){return{skippedReferences:0,skippedReferenceReasons:mu(),skippedReferenceSamples:[]}}function Ze(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)}}function eo(e){return e.length>=8&&no(e.length)>1}function to(e){let t=no(e.vueFiles.length),n=Iu(e.vueFiles),r=wu(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=bu(un(Ru(),"scip-query-vue-workers-")),a=new SharedArrayBuffer(4),s=new Int32Array(a),c=vu(),u=Date.now();try{for(let l=0;l<r.length;l++)new xu(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[l],resultPath:un(o,`${l}.json`),sharedBuffer:a}});for(;Atomics.load(s,0)<r.length;){if(Date.now()-u>c)throw new Error(`Vue reference workers timed out after ${(c/1e3).toFixed(0)}s`);Atomics.wait(s,0,Atomics.load(s,0),100)}let d=r.map((l,m)=>{let g=JSON.parse(hu(un(o,`${m}.json`),"utf-8"));if(!g.ok)throw new Error(`Vue reference worker failed: ${g.error}`);return g.result}),p={occurrences:d.flatMap(l=>l.occurrences),...K()};for(let l of d)Ze(p,l);return p}finally{yu(o,{recursive:!0,force:!0})}}function no(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 vu(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function Iu(e){let t=Pu(),n=[];for(let r of e){let i=ro(r),o=Math.max(1,Math.ceil(i/t));for(let a=0;a<o;a++)n.push({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 Pu(){return Number.POSITIVE_INFINITY}function wu(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:ku(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 ku(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,ro(e.fileName)-e.startOffset)}function ro(e){try{return Su(e).size}catch{return 1}}import{createRequire as Eu}from"module";import{existsSync as Tu,readFileSync as ln}from"fs";import{dirname as io,extname as Du,join as oo,relative as Fu,resolve as ju}from"path";import{pathToFileURL as Ou}from"url";function Cu(e){e.transaction(()=>{e.prepare(`
235
+ `)}function vr(e){return JSON.stringify(e)}import{createHash as ps}from"crypto";import{existsSync as Dt,readFileSync as gs,readdirSync as fs}from"fs";import{dirname as Ft,join as Ce,relative as ms,resolve as Ot,sep as Pr}from"path";function wr(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=Dr(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function kr(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=Dr(s,e);c&&c!==i&&a.add(c)}}return hs(e,r)}function Er(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 jt(e){if(e===".")return"root";let t=ps("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Tr(e,t){let n=Ot(e),r={};for(let i of t)r[i]=ys(n,i);return r}function Dr(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 hs(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 ys(e,t){let n=t==="."?e:Ce(e,t),r=Ss(n),i=bs(n),o=i?Rs(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 Ss(e){let t=Ce(e,"package.json");if(!Dt(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Ct(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 bs(e){let t=Ce(e,"tsconfig.json");if(Dt(t))return t;let n;try{n=fs(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?Ce(e,n[0]):void 0}function Rs(e,t){let n=Ct(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=xs(n.value,e,t),i=Fr(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function xs(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=Ft(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=Or(s,i,n);c&&o.add(c)}return[...o]}function Fr(e,t,n,r){let i=vs(t);if(i)return{pathsTargets:Is(i,Ft(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=Ps(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=Ct(o);return a.ok?Fr(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function vs(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 Is(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=Or(o,t,n);a&&r.add(a)}return[...r]}function Ps(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=Ot(Ft(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(Pr).includes("node_modules")&&Z(n,i)&&Dt(i))return i}function Or(e,t,n){let r=e.replace(/\/?\*+$/,""),i=Ot(t,r===""?".":r);if(!Z(n,i))return;let a=ms(n,i).split(Pr).join("/");return a===""?".":a}function ws(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]!==`
236
+ `;)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 Ct(e){try{let t=gs(e,"utf-8"),n=JSON.parse(ws(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as bi,randomUUID as zt}from"crypto";import{closeSync as Ri,constants as rc,copyFileSync as mi,existsSync as B,lstatSync as ic,mkdirSync as _,mkdtempSync as xi,openSync as vi,readdirSync as oc,readFileSync as F,realpathSync as ac,renameSync as z,rmSync as V,statSync as sc,unlinkSync as qt,writeFileSync as Ii}from"fs";import{dirname as Pi,join as f,resolve as me}from"path";import{setTimeout as cc}from"timers/promises";import{pathToFileURL as hi}from"url";import{deserializeSCIP as wi}from"@c4312/scip";import uc from"better-sqlite3";import{createRequire as ks}from"module";var Es=ks(import.meta.url),jr=Ts().version;function Ts(){for(let e of["../package.json","../../package.json"])try{return Es(e)}catch{}return{version:"0.0.0"}}import{lstatSync as Us,readdirSync as Ws}from"fs";import{join as Js,relative as qs,resolve as Bt,sep as Hs}from"path";import{createHash as Ds}from"crypto";import{existsSync as At,mkdirSync as Fs,readFileSync as _e,readdirSync as gp,renameSync as Os,rmSync as fp,writeFileSync as js}from"fs";import{join as Q}from"path";import{create as _r,fromBinary as Ar,toBinary as Cs}from"@bufbuild/protobuf";import{deserializeSCIP as Ae,DocumentSchema as Lt,IndexSchema as Lr,serializeSCIP as Mr}from"@c4312/scip";var Le=1,ae="typescript-scip-fragments";function Nr(e){if(e.length===0)throw new Error("affected TypeScript mini index requires documents");let t=new Set,n=[];for(let o of e){let a=q(o.relativePath);if(t.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(t.add(a),o.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${a}`);let s=Ar(Lt,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=Mr(_r(Lr,{documents:n,externalSymbols:[]})),i=Ae(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function Me(e){let t=Q(e,ae);return{rootDir:t,blobDir:Q(t,"blobs"),generationDir:Q(t,"generations")}}function _s(e){let t=Ae(e.indexBytes);Qr(t.metadata,Xr(e)),Yr(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let a=q(o.relativePath);if(n.has(a))throw new Error(`duplicate TypeScript SCIP document path: ${a}`);n.add(a);let s=Cs(Lt,o),c=e.documentIdentities.get(a)??(e.allowUntrackedDocuments?H(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:a,contentHash:H(s)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${a}`);r.push(Jr(e.cacheDir,{relativePath:a,bytes:s,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=qr(e,r);return Hr(e.cacheDir,i),i}function $r(e){let t=Me(e.cacheDir);if(!At(Mt(t,e.generationIdentity)))return _s(e);let n=Vr({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity});if(!e.allowUntrackedDocuments&&n.manifest.documents.length!==e.documentIdentities.size)throw new Error("TypeScript fragment generation document identities changed");for(let r of n.manifest.documents){let i=e.documentIdentities.get(r.relativePath);if(!(i===void 0&&e.allowUntrackedDocuments)&&i!==r.documentIdentity)throw new Error(`TypeScript fragment generation document identity changed: ${r.relativePath}`)}return n.manifest}function Gr(e){let t=Vr({cacheDir:e.cacheDir,generationIdentity:e.previousGenerationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity}).manifest,n=new Map(t.documents.map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let a=q(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript fragment replacement: ${a}`);if(r.add(a),!n.has(a))throw new Error(`TypeScript fragment replacement has no prior document: ${a}`);let s=e.documentIdentities.get(a);if(!s)throw new Error(`missing TypeScript document identity: ${a}`);o.bytes===null?n.delete(a):n.set(a,Jr(e.cacheDir,o,s))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=qr(e,[...n.values()]);return Hr(e.cacheDir,i),i}function Vr(e){let t=Me(e.cacheDir),n=Mt(t,e.generationIdentity),r;try{r=zr(_e(n,"utf8"))}catch(o){throw new Error(`TypeScript fragment generation is unavailable: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(r.generationIdentity!==e.generationIdentity)throw new Error("TypeScript fragment generation identity does not match its manifest path");if(e.producerIdentity&&r.producerIdentity!==e.producerIdentity)throw new Error("TypeScript fragment producer identity changed");if(e.projectIdentity&&r.projectIdentity!==e.projectIdentity)throw new Error("TypeScript fragment project identity changed");let i=new Map;for(let o of r.documents){let a=Q(t.blobDir,`${o.blobHash}.scipdoc`),s=_e(a);if(s.byteLength!==o.byteLength||H(s)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,s)}return{manifest:r,fragments:i}}function Br(e){let t=Wr(e);return _t(t.baseIndex,t.completeDocuments,"assembled")}function Ur(e){let t=Wr(e);return As(t.deletedAffectedPaths),{completeIndexBytes:_t(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:_t(t.baseIndex,t.affectedDocuments,"affected")}}function Wr(e){let t=Ae(e.baseIndexBytes);Qr(t.metadata,Xr(e)),Yr(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=q(s.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);n.set(c,s)}if(n.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let r=new Set,i=[],o=[],a=[];for(let s of t.documents){let c=q(s.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let u=n.get(c);if(!u){i.push(s);continue}if(n.delete(c),u.bytes===null){a.push(c);continue}let d=Ar(Lt,u.bytes);if(d.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${d.relativePath}`);i.push(d),o.push(d)}if(n.size>0)throw new Error(`TypeScript fragment replacement has no prior document: ${[...n.keys()].sort()[0]}`);return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:a}}function _t(e,t,n){let r=Mr(_r(Lr,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=Ae(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function As(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function Jr(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=q(t.relativePath),i=Buffer.from(t.bytes),o=H(i),a=Me(e);Fs(a.blobDir,{recursive:!0});let s=Q(a.blobDir,`${o}.scipdoc`);if(At(s)){let c=_e(s);if(c.byteLength!==i.byteLength||H(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${s}.${process.pid}.${Date.now()}.tmp`;js(c,i),Os(c,s)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function qr(e,t){if(!e.producerIdentity||!e.projectIdentity||!e.generationIdentity)throw new Error("TypeScript fragment generation identities must be non-empty");let n=[...t].sort((r,i)=>r.relativePath.localeCompare(i.relativePath));if(new Set(n.map(r=>r.relativePath)).size!==n.length)throw new Error("TypeScript fragment generation contains duplicate document paths");return{version:Le,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function Hr(e,t){let n=Me(e),r=Mt(n,t.generationIdentity);if(At(r)){let i=zr(_e(r,"utf8"));if(Cr(i)!==Cr(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}b(r,t,{spacing:2,trailingNewline:!0})}function Cr(e){return H(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function zr(e){let t=JSON.parse(e);if(t.version!==Le||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let n=new Set;for(let r of t.documents){if(!r||typeof r.relativePath!="string"||typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash)||typeof r.byteLength!="number"||!Number.isInteger(r.byteLength)||r.byteLength<0||typeof r.documentIdentity!="string"||!r.documentIdentity)throw new Error("invalid TypeScript fragment record");if(q(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function Mt(e,t){return Q(e.generationDir,Ls(t))}function Ls(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${H(e)}.json`}function Yr(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function Qr(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 Xr(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function q(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.includes("\\"))throw new Error(`invalid TypeScript SCIP document path: ${e}`);let t=e.split("/");if(t.includes("")||t.includes(".")||t.includes(".."))throw new Error(`invalid TypeScript SCIP document path: ${e}`);return e}function H(e){return Ds("sha256").update(e).digest("hex")}import{createHash as Ms}from"crypto";import{existsSync as se,mkdirSync as Ns,readFileSync as ue,readdirSync as Nt,renameSync as $s,rmSync as Kr,writeFileSync as Gs}from"fs";import{join as D}from"path";var Ne=1,ei=64*1024*1024,de="typescript-scip-overlays";function ti(e){let t=ii(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t&&(t.producerIdentity!==e.producerIdentity||t.projectIdentity!==e.projectIdentity))throw new Error("TypeScript overlay producer or project identity changed");let n=new Map((t?.overlays??[]).map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let a=Vt(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript overlay: ${a}`);r.add(a),n.set(a,Vs(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:Ne,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...n.values()].sort((o,a)=>o.relativePath.localeCompare(a.relativePath))};return Bs(e.cacheDir,i),i}function ni(e){let t=ii(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=ue(D(le(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||ce(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 Br({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function ri(e,t){let n=le(e),r=D(n,"generations");if(!se(r))return;let i=new Set(t.map(Gt)),o=new Set;for(let s of Nt(r).filter(c=>i.has(c))){let c=$t(ue(D(r,s),"utf8"));for(let u of c.overlays)u.blobHash&&o.add(`${u.blobHash}.scipdoc`)}for(let s of Nt(r))i.has(s)||Kr(D(r,s),{force:!0});let a=D(n,"blobs");if(se(a))for(let s of Nt(a))o.has(s)||Kr(D(a,s),{force:!0})}function ii(e,t){let n=D(le(e),"generations",Gt(t));if(!se(n))return null;let r=$t(ue(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function Vs(e,t){let n=Vt(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=ce(r),o=D(le(e),"blobs");Ns(o,{recursive:!0});let a=D(o,`${i}.scipdoc`);if(se(a)){let s=ue(a);if(s.byteLength!==r.byteLength||ce(s)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let s=`${a}.${process.pid}.${Date.now()}.tmp`;Gs(s,r),$s(s,a)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function Bs(e,t){let n=D(le(e),"generations",Gt(t.generationIdentity));if(se(n)){let r=$t(ue(n,"utf8"));if(Zr(r)!==Zr(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}b(n,t,{spacing:2,trailingNewline:!0})}function $t(e){let t=JSON.parse(e);if(t.version!==Ne||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(Vt(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function le(e){return D(e,de)}function Gt(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${ce(e)}.json`}function Zr(e){return ce(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function Vt(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}function ce(e){return Ms("sha256").update(e).digest("hex")}var pe=1,Ut="language-indexes",oi=["index.db","index.scip","meta.json"],ai=[Ut,ae,de];function $e(e){let t=[];for(let n of oi)zs(e,n),t.push(n);for(let n of ai)si(e,n,t);return{version:pe,files:t.sort()}}function Ge(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(!oi.includes(e)&&!ai.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function j(e,t){let n=Ge(t),r=Bt(e),i=Bt(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${Hs}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function si(e,t,n){let r=Js(e,t),i;try{i=Ws(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()?si(e,a,n):o.isFile()&&n.push(Ge(a))}}function zs(e,t){let n=j(e,t),r;try{r=Us(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(qs(Bt(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{createHash as Ys}from"crypto";import{copyFileSync as ci,existsSync as $,linkSync as Qs,mkdirSync as ui,readFileSync as pi,readdirSync as di,renameSync as Jt,rmSync as Be,statSync as Xs}from"fs";import{basename as Ve,dirname as ge,join as P,relative as li}from"path";var X=1,Ue=".scipquery-generations";function We(e){let t=Je(e.outputDb),n=Ks(e,t);e.onStage?.("after-recovery-retained"),e.preserveOutputScip||Wt(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),Wt(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),Wt(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let r=qe(e.metaPath,e.outputDb),i={version:X,currentGeneration:r,...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:(e.now??(()=>new Date))().toISOString()};return b(P(t,"state.json"),i,{spacing:2,trailingNewline:!0}),{currentGeneration:r,...n?{previousGeneration:n}:{}}}function gi(e){try{let t=JSON.parse(pi(P(Je(e),"state.json"),"utf8"));return t.version!==X||typeof t.currentGeneration!="string"||!t.currentGeneration||typeof t.publishedAt!="string"||!Number.isFinite(Date.parse(t.publishedAt))||!tc(t.previousGeneration)||!nc(t.publication)?null:t}catch{return null}}function fi(e,t,n=()=>new Date){if(!$(e)||!$(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=gi(e),i={version:X,currentGeneration:qe(t,e),...r?.previousGeneration?{previousGeneration:r.previousGeneration}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return b(P(Je(e),"state.json"),i,{spacing:2,trailingNewline:!0}),i}function G(e,t=P(ge(e),"meta.json")){let n=P(Je(e),"state.json");if(!$(n))return{state:"legacy",statePath:n};let r=gi(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=qe(t,e),o=r.currentGeneration===i,a=r.previousGeneration?$(P(ge(e),r.previousGeneration.databasePath)):!0;return!o||!a?{state:"drifted",statePath:n,currentMatches:o,recoveryExists:a,generation:r,reason:o?"retained recovery database is missing":"stable database or metadata no longer matches the published generation"}:{state:"current",statePath:n,currentMatches:o,recoveryExists:a,generation:r}}catch(i){return{state:"drifted",statePath:n,currentMatches:!1,recoveryExists:!1,generation:r,reason:i instanceof Error?i.message:String(i)}}}function Je(e){return P(ge(e),Ue)}function Ks(e,t){if(!$(e.outputDb))return;let n=qe(e.metaPath,e.outputDb),r=P(t,n),i=P(r,Ve(e.outputDb)),o=$(e.metaPath)?P(r,Ve(e.metaPath)):void 0;if(!$(i)){let a=`${r}.${process.pid}.${Date.now()}.tmp`;Be(a,{recursive:!0,force:!0}),ui(a,{recursive:!0});let s=P(a,Ve(e.outputDb));try{Qs(e.outputDb,s)}catch{ci(e.outputDb,s)}o&&ci(e.metaPath,P(a,Ve(e.metaPath))),ui(t,{recursive:!0}),Jt(a,r)}return Zs(t,n),{generationIdentity:n,databasePath:li(ge(e.outputDb),i),...o?{metadataPath:li(ge(e.outputDb),o)}:{}}}function Zs(e,t){for(let n of di(e,{withFileTypes:!0}))!n.isDirectory()||n.name===t||n.name.endsWith(".tmp")||Be(P(e,n.name),{recursive:!0,force:!0});for(let n of di(e,{withFileTypes:!0}))n.isDirectory()&&n.name.endsWith(".tmp")&&Be(P(e,n.name),{recursive:!0,force:!0})}function qe(e,t){let n=Ys("sha256").update(`sqlite-generation-v${X}\0`);$(e)&&n.update(ec(pi(e,"utf8")));let r=Xs(t);return n.update(`\0${r.size}`),n.digest("hex")}function ec(e){try{let t=JSON.parse(e);if((t.version===2||t.version===3)&&t.status==="complete"&&typeof t.updatedAt=="string"&&t.fingerprint!==void 0)return JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages,scipCompanion:t.scipCompanion})}catch{}return e}function Wt(e,t){Be(`${t}.tmp-replace`,{force:!0}),Jt(e,`${t}.tmp-replace`),Jt(`${t}.tmp-replace`,t)}function tc(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e;return typeof t.generationIdentity=="string"&&!!t.generationIdentity&&typeof t.databasePath=="string"&&!!t.databasePath&&(t.metadataPath===void 0||typeof t.metadataPath=="string"&&!!t.metadataPath)}function nc(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e,n=[t.converterDurationMs,t.affectedDocumentCount,t.changedDocumentCount,t.producerDurationMs,t.materializationDurationMs,t.patchDurationMs].filter(r=>r!==void 0);return(t.mode==="incremental"||t.mode==="full")&&t.validation==="passed"&&t.converterDurationMs!==void 0&&n.every(r=>typeof r=="number"&&Number.isFinite(r)&&r>=0)&&(t.scipCompanion===void 0||t.scipCompanion==="current"||t.scipCompanion==="deferred")&&(t.typescriptOverlayGeneration===void 0||typeof t.typescriptOverlayGeneration=="string"&&!!t.typescriptOverlayGeneration)&&(t.scipCompanion!=="deferred"||!!t.typescriptOverlayGeneration)&&(t.fallbackReason===void 0||typeof t.fallbackReason=="string")}var Yt=1,yi="SCIP_QUERY_SHARED_CACHE",Ht=JSON.stringify({cliVersion:jr,artifactCatalogVersion:pe,sqliteGenerationStoreVersion:X,typescriptFragmentStoreVersion:Le,typescriptOverlayStoreVersion:Ne}),ki="manifest.json",dc="shared-cache.json",Qt=[Ut,ae,de];function He(e,t){if(!e.clean||!e.treeOid)return;let n=ye(JSON.stringify({version:Yt,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:Ht}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:Ht,generationId:n,repositoryCacheDir:Ln(e.repositoryId)}}function Ei(e,t,n){if(process.env[yi]==="0")return`${yi}=0`;if(!Mn(n))return"explicit cache or database override";if(me(t)!==me(f(An(e),"index.db")))return"index database is outside the managed worktree cache"}function C(e,t=!0){let n=Kt(e),r;try{r=pc(F(f(n,ki),"utf8"))}catch{return null}if(r.generationId!==e.generationId||r.repositoryId!==e.repositoryId||r.treeOid!==e.treeOid||r.producerIdentity!==e.producerIdentity||JSON.stringify(r.fingerprint)!==JSON.stringify(e.fingerprint))return null;if(!t)return r;try{for(let i of r.artifacts){let o=j(n,i.path),a=sc(o);if(!a.isFile()||a.size!==i.size||ye(F(o))!==i.sha256)return null}}catch{return null}return r}function Ti(e){let t=C(e.snapshot);if(t)return t;if(!ji(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=Si(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=$e(e.sourceCacheDir),i=f(e.snapshot.repositoryCacheDir,"generations");_(i,{recursive:!0});let o=xi(f(i,`.tmp-${process.pid}-`));try{let a=[];for(let p of r.files){let l=j(e.sourceCacheDir,p),m=j(o,p);he(l,m);let g=F(m);a.push({path:p,size:g.byteLength,sha256:ye(g)})}let s=wi(F(f(o,"index.scip"))).metadata?.projectRoot;if(!s)throw new Error("shared SCIP generation has no project root metadata");let c=Zt(e.sourceProjectRoot);if(s!==c)throw new Error("shared SCIP generation root does not match its source worktree");if(Si(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let u={version:Yt,artifactCatalogVersion:pe,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:s,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:a.sort((p,l)=>p.path.localeCompare(l.path))};b(f(o,ki),u,{spacing:2,trailingNewline:!0});let d=Kt(e.snapshot);try{if(B(d)&&!C(e.snapshot)){let p=`${d}.corrupt-${process.pid}-${Date.now()}`;z(d,p),V(p,{recursive:!0,force:!0})}z(o,d)}catch(p){let l=C(e.snapshot);if(l)return l;throw p}return u}finally{V(o,{recursive:!0,force:!0})}}function Xt(e){let t=Kt(e.snapshot);_(e.targetCacheDir,{recursive:!0});let n=ie(f(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:3e4});if(!n)throw new Error("timed out waiting for another cache hydration");let r,i,o=!1;try{r=xi(f(e.targetCacheDir,".shared-hydrate-")),Rc(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let u=j(t,c.path),d=j(r,c.path);he(u,d);let p=F(d);if(p.byteLength!==c.size||ye(p)!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=Zt(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&gr(j(r,c.path),e.manifest.scipProjectRoot,a);if(!ji(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=yc(e.targetCacheDir,r),o=!0,Sc(r,e.targetCacheDir,i),We({tempOutputScip:f(r,"index.scip"),tempOutputDb:f(r,"index.db"),tempMetaPath:f(r,"meta.json"),outputScip:f(e.targetCacheDir,"index.scip"),outputDb:f(e.targetCacheDir,"index.db"),metaPath:f(e.targetCacheDir,"meta.json"),now:e.now});let s=G(f(e.targetCacheDir,"index.db"),f(e.targetCacheDir,"meta.json"));if(s.state==="invalid"||s.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${s.reason}`);ze(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&bc(e.targetCacheDir,i),a}finally{r&&V(r,{recursive:!0,force:!0}),n.release()}}async function Di(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??Date.now,o=i()+n,a=f(e.repositoryCacheDir,"locks"),s=f(a,`${e.generationId}.lock`);for(_(a,{recursive:!0});i()<=o;){if(C(e))return{kind:"generation-ready"};let c=zt();try{let u=vi(s,"wx");try{Ii(u,`${JSON.stringify({version:1,pid:process.pid,token:c,generationId:e.generationId,startedAt:new Date(i()).toISOString()})}
237
+ `)}finally{Ri(u)}return{kind:"owner",release:()=>{try{let d=JSON.parse(F(s,"utf8"));d.pid===process.pid&&d.token===c&&qt(s)}catch{}}}}catch(u){if(u.code!=="EEXIST")return{kind:"timeout"};let d=Fi(s);if(d&&(d.pid===void 0||!T(d.pid))){mc(s,d);continue}await cc(r)}}return C(e)?{kind:"generation-ready"}:{kind:"timeout"}}function ze(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:lc(i)};return hc(e.repositoryCacheDir,o,!0),o}function lc(e){return ye(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:me(e.projectRoot),localCacheDir:me(e.localCacheDir)}))}function pc(e){let t=JSON.parse(e);if(t.version!==Yt||t.artifactCatalogVersion!==pe||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!==Ht||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(Ge(r.path),n.has(r.path))throw new Error(`duplicate shared generation artifact: ${r.path}`);n.add(r.path)}for(let r of["index.db","index.scip","meta.json"])if(!n.has(r))throw new Error(`shared generation is missing ${r}`);return t}function he(e,t){_(Pi(t),{recursive:!0});try{mi(e,t,rc.COPYFILE_FICLONE)}catch{mi(e,t)}}function gc(e,t,n){_(e,{recursive:!0}),b(f(e,dc),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function Si(e){try{let t=$e(e),n=bi("sha256");for(let r of t.files){let i=F(j(e,r));n.update(r).update("\0").update(String(i.byteLength)).update("\0").update(i).update("\0")}return n.digest("hex")}catch{return null}}function fc(e){try{return JSON.parse(F(f(e,"meta.json"),"utf8"))}catch{return}}function Kt(e){return f(e.repositoryCacheDir,"generations",e.generationId)}function Fi(e){try{let t=F(e,"utf8"),n=JSON.parse(t),r=typeof n.pid=="number"&&Number.isSafeInteger(n.pid)&&n.pid>0?n.pid:void 0;return{raw:t,...r===void 0?{}:{pid:r}}}catch{return null}}function mc(e,t){let n=`${e}.reclaim`,r=zt(),i;try{i=vi(n,"wx")}catch{return!1}try{Ii(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
238
+ `)}finally{Ri(i)}try{let o=Fi(e);return!o||o.raw!==t.raw||o.pid!==void 0&&T(o.pid)?!1:(qt(e),!0)}catch{return!1}finally{try{let o=JSON.parse(F(n,"utf8"));o.pid===process.pid&&o.token===r&&qt(n)}catch{}}}function hc(e,t,n){let r=Wn(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!B(f(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=f(e,"worktrees");_(i,{recursive:!0}),b(f(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),gc(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function yc(e,t){let n=f(t,".rollback"),r=new Map,i=new Map;_(n,{recursive:!0});for(let s of["index.scip","index.db","meta.json"]){let c=f(e,s),u=B(c);r.set(s,u),u&&he(c,f(n,"stable",s))}for(let s of Qt){let c=f(e,s),u=B(c);if(u){let d=ic(c);if(!d.isDirectory()||d.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${s}`)}i.set(s,u)}let o=f(e,Ue),a=B(o);return a&&Oi(o,f(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:a}}function Sc(e,t,n){for(let r of Qt){let i=f(t,r);if(n.managedDirectories.get(r)){let a=f(n.root,"managed",r);_(Pi(a),{recursive:!0}),z(i,a)}let o=f(e,r);B(o)&&z(o,i)}}function bc(e,t){for(let i of Qt){let o=f(e,i),a=f(t.root,"managed",i);t.managedDirectories.get(i)?B(a)&&(V(o,{recursive:!0,force:!0}),z(a,o)):V(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let a=f(e,i);if(!o){V(a,{force:!0});continue}let s=`${a}.shared-restore-${zt()}`;he(f(t.root,"stable",i),s),V(a,{force:!0}),z(s,a)}let n=f(e,Ue);V(n,{recursive:!0,force:!0});let r=f(t.root,"sqlite-generations");t.generationStoreExisted&&B(r)&&z(r,n)}function Oi(e,t){_(t,{recursive:!0});for(let n of oc(e,{withFileTypes:!0})){let r=f(e,n.name),i=f(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?Oi(r,i):n.isFile()&&he(r,i)}}function Rc(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||JSON.stringify(e.fingerprint)!==JSON.stringify(t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function ji(e,t,n,r=!0,i=!0){try{let o=fc(e);if(o?.status!=="complete"||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return fe("source validation rejected metadata"),!1;let a=$e(e),s=G(f(e,"index.db"),f(e,"meta.json"));if(r?s.state!=="current":s.state==="invalid"||s.state==="drifted")return fe(`source validation rejected SQLite generation state ${s.state}`),!1;let c=new uc(f(e,"index.db"),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let u=Zt(t),p=(i?a.files.filter(l=>l.endsWith(".scip")):["index.scip"]).every(l=>{let m=wi(F(j(e,l))).metadata?.projectRoot;return m!==u&&fe(`source validation rejected SCIP root for ${l}: ${String(m)}`),m===u});return p||fe("source validation rejected SCIP project roots"),p}catch(o){return fe(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function fe(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function Zt(e){try{return hi(ac(e)).href}catch{return hi(me(e)).href}}function ye(e){return bi("sha256").update(e).digest("hex")}import{existsSync as xc,readFileSync as vc,readdirSync as Ic,statSync as Pc}from"fs";import x from"path";var wc=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function Se(e,t=[]){let n=x.resolve(e),r=t.flatMap(c=>Ec(n,c));if(r.length>0)return Ci(n,_i(r));let i=kc(n),o=_i(i),a=Dc(n,o)?[n,...o]:o,s=a.length>0?a:[n];return Ci(n,s)}function Ci(e,t){return[...new Set(t.map(n=>Oc(e,n)))].sort((n,r)=>n.localeCompare(r))}function kc(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=Ic(r,{withFileTypes:!0})}catch{continue}for(let o of i){let a=x.join(r,o.name);if(o.isDirectory()){!wc.has(o.name)&&!o.name.startsWith(".")&&n.push(a);continue}o.isFile()&&Tc(a)&&t.push(x.dirname(a))}}return t}function Ec(e,t){let n=t.trim();if(!n)return[];let r=x.resolve(e,n);if(!Z(e,r))return[];try{let i=Pc(r);if(i.isDirectory())return[r];if(i.isFile()&&Ai(x.basename(r)))return[x.dirname(r)]}catch{return[]}return[]}function Tc(e){if(!Ai(x.basename(e)))return!1;let t=Li(e);return t?x.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function Ai(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function _i(e){let t=[...new Set(e.map(n=>x.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&jc(n,r)))}function Dc(e,t){if(t.length===0||t.some(r=>x.resolve(r)===e))return!1;let n=x.join(e,"tsconfig.json");return xc(n)&&Fc(n)}function Fc(e){let n=Li(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!x.extname(r))):!1}function Li(e){try{let t=JSON.parse(vc(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Oc(e,t){let n=x.relative(e,t);return n?n.split(x.sep).join("/"):"."}function jc(e,t){let n=x.relative(e,t);return!!n&&!n.startsWith("..")&&!x.isAbsolute(n)}import{createHash as Zc}from"crypto";import{existsSync as tn,readFileSync as Yi,statSync as eu,writeFileSync as nn}from"fs";import{join as tu}from"path";import{readFileSync as Mi}from"fs";import{createRequire as Cc}from"module";import{dirname as _c,isAbsolute as sg,relative as cg,resolve as ug,sep as dg}from"path";var Ni=Cc(import.meta.url),Ac=1,$i="0.4.0";function en(){let e=Lc();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Lc(){try{let e=Ni.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(Mi(e,"utf8"));if(t.version!==$i)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${$i}`};let n=_c(e),r=Ni.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(Mi(r,"utf8"));return typeof i.version!="string"||!i.version?{available:!1,reason:"scip-typescript TypeScript compiler version is unavailable"}:{available:!0,packageRoot:n,packageVersion:t.version,typescriptVersion:i.version,producerIdentity:Mc(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Mc(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Ac}`}import{createHash as Nc}from"crypto";import{readFileSync as $c}from"fs";import{dirname as Gc,join as Ye}from"path";var Qe=2,Vc="typescript-index";function Gi(e){let t=Ye(e,Vc);return{rootDir:t,requestDir:Ye(t,"requests"),responseDir:Ye(t,"responses")}}function Vi(e){try{let t=JSON.parse($c(Ye(Gc(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:Nc("sha256").update(JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages})).digest("hex")}catch{return null}}import{randomUUID as Bc}from"crypto";import{existsSync as Uc,mkdirSync as Bi,readFileSync as Wc,rmSync as Ui}from"fs";import{resolve as Wi}from"path";var Jc=12e4,qc=5,Xe=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=On(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Xc(),this.runtime=n.runtime??Kc}request(t){let n=Fn(this.cacheDir),r=Gi(this.cacheDir),i=dt(n.statePath);if(!Ji(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),a=Wi(r.requestDir,`${o}.json`),s=Wi(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;Bi(r.requestDir,{recursive:!0}),Bi(r.responseDir,{recursive:!0}),b(a,{protocolVersion:Qe,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(Uc(s))return Hc(Wc(s,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let u=dt(n.statePath);if(!Ji(u,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(qc)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{Ui(a,{force:!0}),Ui(s,{force:!0})}}};function Ji(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=Dn,i=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===Qe&&n.isProcessAlive(e.pid)&&(r||i)}function Hc(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==Qe||o.id!==t||o.ok===!0&&o.baseGeneration!==n)throw new Error("TypeScript index service wrote an incompatible response.");if(o.ok!==!0)throw new Error(typeof o.error=="string"?o.error:"TypeScript index service request failed.");let a=zc(o.response,r),s=[...new Set(i)].sort(),c=a.fragments.map(u=>u.relativePath).sort();if(JSON.stringify(c)!==JSON.stringify(s))throw new Error("TypeScript index service omitted or added an affected document.");return a}function zc(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(Yc)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:Qc(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 Yc(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 Qc(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Xc(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Jc}var Kc={now:Date.now,randomId:Bc,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:T};function nu(e){let t=e.projectMode==="workspace"?e.workspaceProjects??[]:["."];if(t.length===0)return{eligible:!1,reason:"workspace project roots unavailable"};if(t.length===1&&t[0]==="."&&!e.rootTsconfigExists)return{eligible:!1,reason:"root tsconfig unavailable"};if(!e.previousSnapshot)return{eligible:!1,reason:"prior project snapshot unavailable"};if(e.graph===null)return{eligible:!1,reason:"dependency graph unavailable"};if(e.projectFiles.length===0)return{eligible:!1,reason:"prior TypeScript documents unavailable"};let n=ke(e.previousSnapshot,e.currentSnapshot);if(n.changes.length===0)return{eligible:!1,reason:"no changed project inputs"};if(n.changes.some(u=>u.kind!=="modified"||u.inputKind!=="source"||!lt(u.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=Fe(n,e.graph,e.projectFiles);if(r.mode!=="closure"||r.affectedFiles.length===0)return{eligible:!1,reason:r.reasons.length>0?`affected set widened: ${r.reasons.join(", ")}`:"empty affected set"};let i=ru([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=qi(e.currentSnapshot,e.projectFiles,e.producerIdentity),a=qi(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==a)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let s=zi(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!s)return{eligible:!1,reason:"prior document identity unavailable"};let c=zi(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:Hi(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:Hi(e.currentSnapshot,e.producerIdentity),previousDocumentIdentities:s,nextDocumentIdentities:c,tsconfigPath:i==="."?"tsconfig.json":`${i}/tsconfig.json`,projectArgument:i}:{eligible:!1,reason:"next document identity unavailable"}}function ru(e,t){let n=null;for(let r of e){let i=t.filter(o=>o==="."||r===o||r.startsWith(`${o}/`));if(i.length!==1||n!==null&&n!==i[0])return null;n=i[0]}return n}function Qi(e){let t=Date.now();try{if(!tn(e.previousDbPath)||!tn(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=en();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new W({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a,s;try{a=Pe(o,{includeIgnored:!1}).filter(lt).sort(),s=we(o)}finally{o.close()}let c=performance.now()-n,u=nu({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?Se(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:a,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:tn(tu(e.projectRoot,"tsconfig.json"))});if(!u.eligible)throw new Error(u.reason);let d=Vi(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let l=new Xe({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:d}).request({kind:"emit-documents",tsconfigPath:u.tsconfigPath,projectArgument:u.projectArgument,projectIdentity:u.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles}),m=performance.now()-n,g=eu(e.previousShardPath).size>=ei;n=performance.now();let I=g?null:Yi(e.previousShardPath),S=g?{completeIndexBytes:null,affectedIndexBytes:Nr(l.fragments)}:Ur({packageVersion:r.packageVersion,baseIndexBytes:I,fragments:l.fragments}),R=performance.now()-n;n=performance.now(),g?ti({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,nextGenerationIdentity:u.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:l.fragments}):($r({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:I,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.previousFragmentGeneration,documentIdentities:u.previousDocumentIdentities,allowUntrackedDocuments:!0}),Gr({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.nextFragmentGeneration,fragments:l.fragments,documentIdentities:u.nextDocumentIdentities}));let y=performance.now()-n;n=performance.now(),S.completeIndexBytes&&nn(e.candidateShardPath,S.completeIndexBytes),nn(e.candidateAffectedScipPath,S.affectedIndexBytes);let w=performance.now()-n,k={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:Date.now()-t,cold:l.cold,changedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles,producerIdentity:r.producerIdentity,previousFragmentGeneration:u.previousFragmentGeneration,nextFragmentGeneration:u.nextFragmentGeneration,manifest:u.manifest,plan:u.plan,projectFileCount:a.length,referenceFragmentsByFile:new Map(l.fragments.map(Ie=>[Ie.relativePath,Ie.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:m,serviceMs:l.durationMs,assemblyMs:R,fragmentStoreMs:y,writeMs:w}};return e.onStatus(`Incremental TypeScript index emitted ${k.affectedFiles.length} affected document(s) in ${(k.durationMs/1e3).toFixed(3)}s (${k.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${m.toFixed(0)}ms, assembly ${R.toFixed(0)}ms, fragments ${y.toFixed(0)}ms, write ${w.toFixed(0)}ms).`),k}catch(n){return e.onStatus(`Incremental TypeScript index unavailable: ${n instanceof Error?n.message:String(n)}. Falling back to the whole-project indexer.`),null}}function Xi(e){let t=en();if(!t.available)throw new Error(t.reason);let n=ni({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:Yi(e.baseShardPath),packageVersion:t.packageVersion});nn(e.candidateShardPath,n)}function qi(e,t,n){let r=e.files.filter(i=>wn(i.path,e.languages)!=="source").map(i=>({path:i.path,size:i.size,hash:i.hash})).sort((i,o)=>i.path.localeCompare(o.path));return rn(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function Hi(e,t){return rn(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function zi(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),a=jn({projectFiles:t.filter(c=>o.has(c)),snapshot:e,graph:n,engineIdentity:r}),s=new Map;for(let c of i){let u=a.identityFor(c,"typescript-scip-document-v1");if(u.key){s.set(c,u.key);continue}if(o.has(c))return null;s.set(c,rn(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function rn(e){return Zc("sha256").update(e).digest("hex")}import{execFile as iu}from"child_process";import{existsSync as Ke,renameSync as an,rmSync as sn,statSync as ou}from"fs";import{cpus as au}from"os";import{join as Ki}from"path";function su(e,t,n){if(!e.defaultOutputPath)return;let r=Ki(t,e.defaultOutputPath);n!==r&&Ke(r)&&an(r,n)}function cu(e,t,n){if(!e.defaultOutputPath)return null;let r=Ki(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return sn(i,{force:!0}),Ke(r)?(an(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function uu(e){e&&(sn(e.defaultOutputPath,{force:!0}),e.backupPath&&Ke(e.backupPath)&&an(e.backupPath,e.defaultOutputPath))}function du(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,au().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Zi(e,t,n,r){let i=e.filter(u=>u.config.defaultOutputPath),o=e.filter(u=>!u.config.defaultOutputPath),a=[],s=du(o.length,r),c=await pu(o,s,u=>on(u,t,n));if(s>1){let u=new Map;for(let d of c.filter(p=>p.skipped)){let p=o.find(l=>l.id===d.id);p&&(n(`Retrying ${p.label} indexer serially after parallel failure...`),u.set(p.id,await on(p,t,n)))}a.push(...c.map(d=>u.get(d.id)??d))}else a.push(...c);for(let u of i)a.push(await on(u,t,n));return a.sort((u,d)=>e.findIndex(p=>p.id===u.id)-e.findIndex(p=>p.id===d.id))}async function on(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),sn(e.scipPath,{force:!0});let r=cu(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{let s=Pn(e.binary,e.args);await lu(s.binary,s.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),su(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.message:String(s),u=`${e.resolvedBinary} indexer failed: ${c.split(`
239
+ `)[0]}`,d=e.label===e.language?u:`${e.label}: ${u}`;return n(`Skipping ${e.label}: ${u}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:d}}}finally{uu(r)}if(!Ke(e.scipPath)){let s=`${e.resolvedBinary} indexer completed but did not produce ${e.scipPath}`,c=e.label===e.language?s:`${e.label}: ${s}`;return n(`Skipping ${e.label}: ${s}`),{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,skipped:{language:e.language,reason:c}}}let a;try{a=ou(e.scipPath).size}catch{a=void 0}return{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,durationMs:Date.now()-o,command:i,outputBytes:a}}function lu(e,t,n){return new Promise((r,i)=>{iu(e,[...t],n,o=>{o?i(o):r()})})}async function pu(e,t,n){if(e.length===0)return[];let r=new Array(e.length),i=0,o=Math.max(1,Math.min(e.length,t)),a=Array.from({length:o},async()=>{for(;i<e.length;){let s=i++;r[s]=await n(e[s])}});return await Promise.all(a),r}import{execFileSync as gu}from"child_process";import{platform as fu}from"os";function cn(e,t){let n=e.installMethods,r=ne(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(at(i.prerequisite)){t(`Installing ${r} via ${i.label}...`);try{gu(i.binary,i.args,{stdio:"inherit",timeout:3e5,env:process.env,shell:fu()==="win32"});let o=re(e);if(o){let a=o===e.indexerBinary?"":` (using ${o})`;return t(`Successfully installed ${r} via ${i.label}${a}`),!0}t(`${i.label} command completed but ${r} was not found on PATH`)}catch(o){let a=o instanceof Error?o.message:String(o);t(`${i.label} install failed: ${a}`)}}return t(`Could not auto-install ${r}.`),e.installUrl&&t(`Install manually from: ${e.installUrl}`),!1}import Yu from"better-sqlite3";import{existsSync as Qu}from"fs";import{dirname as Xu,join as Ku,resolve as Zu}from"path";import{readFileSync as hu,rmSync as yu,statSync as Su,mkdtempSync as bu}from"fs";import{tmpdir as Ru}from"os";import{join as un}from"path";import{Worker as xu}from"worker_threads";function mu(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function K(){return{skippedReferences:0,skippedReferenceReasons:mu(),skippedReferenceSamples:[]}}function Ze(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)}}function eo(e){return e.length>=8&&no(e.length)>1}function to(e){let t=no(e.vueFiles.length),n=Iu(e.vueFiles),r=wu(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=bu(un(Ru(),"scip-query-vue-workers-")),a=new SharedArrayBuffer(4),s=new Int32Array(a),c=vu(),u=Date.now();try{for(let l=0;l<r.length;l++)new xu(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[l],resultPath:un(o,`${l}.json`),sharedBuffer:a}});for(;Atomics.load(s,0)<r.length;){if(Date.now()-u>c)throw new Error(`Vue reference workers timed out after ${(c/1e3).toFixed(0)}s`);Atomics.wait(s,0,Atomics.load(s,0),100)}let d=r.map((l,m)=>{let g=JSON.parse(hu(un(o,`${m}.json`),"utf-8"));if(!g.ok)throw new Error(`Vue reference worker failed: ${g.error}`);return g.result}),p={occurrences:d.flatMap(l=>l.occurrences),...K()};for(let l of d)Ze(p,l);return p}finally{yu(o,{recursive:!0,force:!0})}}function no(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 vu(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function Iu(e){let t=Pu(),n=[];for(let r of e){let i=ro(r),o=Math.max(1,Math.ceil(i/t));for(let a=0;a<o;a++)n.push({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 Pu(){return Number.POSITIVE_INFINITY}function wu(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:ku(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 ku(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,ro(e.fileName)-e.startOffset)}function ro(e){try{return Su(e).size}catch{return 1}}import{createRequire as Eu}from"module";import{existsSync as Tu,readFileSync as ln}from"fs";import{dirname as io,extname as Du,join as oo,relative as Fu,resolve as Ou}from"path";import{pathToFileURL as ju}from"url";function Cu(e){e.transaction(()=>{e.prepare(`
240
240
  DELETE FROM mentions
241
241
  WHERE chunk_id IN (
242
242
  SELECT c.id
@@ -256,7 +256,7 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
256
256
  FROM documents
257
257
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
258
258
  ORDER BY relative_path
259
- `).all().map(r=>ju(t,r.relativePath))}function so(e,t){let{vueCore:n,ts:r,volarTs:i}=_u(e),{parsed:o,vueOptions:a}=Au(n,r,t),s=io(t),c=n.createVueLanguagePlugin(r,o.options,a,m=>m),u=Lu(n,r,c),d=Mu(s,o),{languageServiceHost:p}=i.createLanguageServiceHost(r,r.sys,u,m=>m,d),l=r.createLanguageService(p);return{ts:r,language:u,languageService:l,fileNames:o.fileNames,configDir:s}}function _u(e){let t=Eu(Ou(oo(e,"package.json")).href);return{vueCore:dn(t,"@vue/language-core",e),ts:dn(t,"typescript",e),volarTs:dn(t,"@volar/typescript",e)}}function Au(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,io(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Lu(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!Tu(o))return;let a=ln(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??Uu(o))});return r.current=i,i}function Mu(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function dn(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 co(e,t,n){let r=Nu(e);return i=>{if(!i.name)return null;let o=A(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(p=>p.line===s.line&&p.displayName===i.name);if(u)return u.symbolId;let d=c.containingByLine.get(s.line);return d&&d.displayName===i.name?d.symbolId:$u(c.starts,s.line,2,i.name)}}function Nu(e){let t=e.prepare(`
259
+ `).all().map(r=>Ou(t,r.relativePath))}function so(e,t){let{vueCore:n,ts:r,volarTs:i}=_u(e),{parsed:o,vueOptions:a}=Au(n,r,t),s=io(t),c=n.createVueLanguagePlugin(r,o.options,a,m=>m),u=Lu(n,r,c),d=Mu(s,o),{languageServiceHost:p}=i.createLanguageServiceHost(r,r.sys,u,m=>m,d),l=r.createLanguageService(p);return{ts:r,language:u,languageService:l,fileNames:o.fileNames,configDir:s}}function _u(e){let t=Eu(ju(oo(e,"package.json")).href);return{vueCore:dn(t,"@vue/language-core",e),ts:dn(t,"typescript",e),volarTs:dn(t,"@volar/typescript",e)}}function Au(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,io(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Lu(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!Tu(o))return;let a=ln(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??Uu(o))});return r.current=i,i}function Mu(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function dn(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 co(e,t,n){let r=Nu(e);return i=>{if(!i.name)return null;let o=A(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(p=>p.line===s.line&&p.displayName===i.name);if(u)return u.symbolId;let d=c.containingByLine.get(s.line);return d&&d.displayName===i.name?d.symbolId:$u(c.starts,s.line,2,i.name)}}function Nu(e){let t=e.prepare(`
260
260
  SELECT
261
261
  d.relative_path AS relativePath,
262
262
  der.start_line AS startLine,
@@ -292,12 +292,12 @@ import{a as W}from"./chunk-NH7WNNQC.js";import{a as pt,e as gt,f as An,g as Ln,h
292
292
  (SELECT MAX(id) FROM chunks) AS maxChunkId,
293
293
  (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
294
294
  `).get();return{version:3,tsconfig:n,files:Ee(t),db:r}}function od(e){let t=So();return{projectRoot:e.projectRoot,context:so(e.projectRoot,e.configPath),symbolLookup:co(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function ad(e){let t=[],n=K(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=sd(e,i);t.push(...o.occurrences),Ze(n,o)}return{occurrences:t,...n}}function sd(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return Ro(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 Ro(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=A(e.projectRoot,t.fileName),s=[...mo(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:md(s),processedStarts:new Set};return cd({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function cd(e){let t=[],n=K();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||ud(e.sourceInfo.text,r.start))continue;let i=ho(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!yo(e.projectRoot,d.fileName));if(!a){gn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=A(e.projectRoot,a.fileName),c=dd(e.sourceFile,r.text,s);if(c){gn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=po(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){gn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}vo(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),fd(t,e,r,i,s,u)}return{occurrences:t,...n}}function ud(e,t){let n=e.lastIndexOf(`
295
- `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function dd(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Ro(e,t,n){let r=K();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:A(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function gn(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 fn(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 ld(e,t){let n=fn(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=fn(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function pd(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(...fn(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function gd(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return ld(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function fd(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of hd(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&&(vo(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function vo(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 md(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function hd(e,t,n,r,i,o){let a=e.getDocumentHighlights?.(t,n,[t])??[],s=[];for(let c of a)if(c.fileName===t)for(let u of c.highlightSpans){let d=yd(r,u.textSpan.start,o,i.text);d!==null&&s.push(d)}return s}function yd(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=pn(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function nm(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=Dd(e),a=Date.now();tt(h(o.outputScip),{recursive:!0}),tt(h(o.outputDb),{recursive:!0});let s=e.languages??St(t);if(s.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${s.join(", ")}`);let c=ee("reindex.fingerprint",()=>cl(t,s,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:s.length}),u,d;if(e.skipIfUnchanged!==!1&&!Ei(t,o.outputDb)&&Io(o.outputScip)===Io(v(h(o.outputDb),"index.scip"))){let g=Te(t);if(u=g?He(g,c):void 0,u){let I=C(u);if(I){if(!Td(o,c))try{Xt({snapshot:u,manifest:I,targetCacheDir:h(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${u.generationId.slice(0,12)}`)}catch(S){r(`Shared generation attach failed; continuing locally: ${hn(S)}`)}}else{let S=await Di(u);if(S.kind==="owner")d=S.release;else if(S.kind==="generation-ready"){let R=C(u);if(R)try{Xt({snapshot:u,manifest:R,targetCacheDir:h(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${u.generationId.slice(0,12)} after waiting`)}catch(y){r(`Shared generation attach failed after waiting; continuing locally: ${hn(y)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let p=ie(v(h(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!p)throw d?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${h(o.outputDb)}.`);let l;try{l=await te("reindex.lock",()=>tl(v(h(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:s.length})}catch(g){throw p.release(),d?.(),g}let m=null;try{let g=null,I=ee("reindex.reuse-check",()=>(g=Fd({opts:e,paths:o,languages:s,fingerprint:c,start:a,onStatus:r}),g),()=>({languages:s.length,reused:g!==null}));if(I)return Po({snapshot:u,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),I;await te("reindex.scip-cli-ready",()=>Hd(i,r));let S=Od(o);m=S.runDir;let R,y=await te("reindex.fresh",async()=>(R=await Cd({opts:e,languages:s,projectRoot:t,paths:o,tempPaths:S,fingerprint:c,start:a,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),R),()=>({languages:s.length,reused:R?.reused,skipped:R?.skipped.length}));return Po({snapshot:u,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),y}catch(g){throw Go(o.metaPath,ot({trigger:e.trigger,result:"failed",start:a,error:g instanceof Error?g.message:String(g)})),g}finally{m&&U(m,{recursive:!0,force:!0}),l(),p.release(),d?.()}}function Po(e){if(e.snapshot){if(C(e.snapshot)){ze(e.snapshot,h(e.paths.outputDb),"local-fresh");return}try{let t=Te(e.projectRoot),n=t?He(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}Ti({snapshot:e.snapshot,sourceCacheDir:h(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=Te(e.projectRoot);return(r?He(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),ze(e.snapshot,h(e.paths.outputDb),"built"),e.onStatus(`Published shared generation ${e.snapshot.generationId.slice(0,12)}`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${hn(t)}`)}}}function Td(e,t){if(!j(e.outputScip)||!j(e.outputDb)||!$o(e.metaPath,t))return!1;let n=G(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function hn(e){return e instanceof Error?e.message:String(e)}function Dd(e){let t=e.outputScip??v(e.projectRoot,"index.scip"),n=e.outputDb??v(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:v(h(n),"meta.json")}}function Fd(e){let t=G(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!j(e.paths.outputScip)||!j(e.paths.outputDb)||!$o(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;N(J(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=Date.now()-e.start,r=ot({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return Go(e.paths.metaPath,r),e.onStatus(`Index unchanged; reused existing SQLite index in ${(n/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:n,reused:!0,skipped:[],lastRefresh:r,shards:jd(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function jd(e,t,n,r){let i=Mo(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:be(i[o]),outputBytes:Re(Sn(e.outputDb,o)),durationMs:0}))}function Od(e){let t=xd(v(h(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:v(t,et(e.outputScip)),tempOutputDb:v(t,et(e.outputDb)),tempMetaPath:v(t,et(e.metaPath))}}async function Cd(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await te("reindex.language-indexers",async()=>(n=await Ad(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:a,languageFingerprints:s,shards:c,typescriptProjectShardContext:u,incrementalTypeScript:d}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),_d({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let m=ee("reindex.publish",()=>Wd(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),g=m.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(I=>I.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:m,shards:c}}let p=ee("reindex.publish",()=>Ud(e,t,i,o,a,s,u,d),{mode:d?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),l=p.durationMs;return e.onStatus(`Done in ${(l/1e3).toFixed(1)}s`),{languages:i.map(m=>m.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:l,reused:!1,skipped:o,lastRefresh:p,shards:c}}function _d(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=G(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 Ad(e,t){let n=Gd({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath}),r=[],i=new Set;for(let[E,xn]of n)xn.reused&&(r.push({language:E,scipPath:xn.scipPath}),i.add(E));for(let E of i)e.onStatus(`Reusing cached ${E} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),a=G(e.paths.outputDb,e.paths.metaPath),s=ve(e.paths.metaPath),c=a.state==="legacy"||a.state==="current",u=s?.scipCompanion!=="deferred"&&(a.state!=="current"||a.generation.publication?.scipCompanion!=="deferred"),d=o&&!o.reused&&c?Qi({projectRoot:e.projectRoot,cacheDir:h(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:xe(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:xe(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:u,previousSnapshot:yn(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,p=new Set(d?["typescript"]:[]),l=d?void 0:Ld(e,n),{preparedRuns:m,skippedLanguages:g,languageOutputScipPaths:I}=zd({languages:e.languages.filter(E=>!i.has(E)&&!p.has(E)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:l?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),S=l?m.filter(E=>E.language!=="typescript"||l.missedProjectIds.has(E.id)):m,R=await Zi(S,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),y=[];if(l){Nd(e.paths.outputDb,R);let E=I.typescript??e.tempPaths.tempOutputScip;y=$d({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:E,reusedProjects:l.reusedProjects})}let w=[...R,...y],{indexedOutputs:k}=Qd(w,g),Ie=d?[{language:"typescript",scipPath:d.scipPath}]:[],Rn=[...r,...Ie,...k];Xd(Rn,g,e.languages,e.opts.allowPartial,e.onStatus);let Vo=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:Re(d.scipPath)??void 0}]:[],Bo=Vd(n,[...R,...Vo],l?{outputDb:e.paths.outputDb,classification:l.classification}:void 0);return{indexedOutputs:Rn,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:Bd(n,e.languages),shards:Bo,typescriptProjectShardContext:l?{projects:l.allProjects,fingerprints:l.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function Ld(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=Se(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Tr(e.projectRoot,r),o=wr(n.fingerprint.files,r),a=kr(r,i),s=Er(r,o,a),c=ve(e.paths.metaPath),d=Md(c,s,g=>j(it(e.paths.outputDb,g))),p=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),l=new Set(p),m=new Set(r.filter(g=>!l.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:s,classification:d,reusedProjects:p,missedProjectIds:m}}function Md(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.typescriptProjectShards?.[i];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 Nd(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=it(e,r);tt(h(i),{recursive:!0}),nt(n.scipPath,i)}}function $d(e){return e.reusedProjects.map((t,n)=>{let r=it(e.outputDb,t),i=xe(e.tempOutputScip,"typescript-project-cached",n);return nt(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Re(i)??void 0}})}function Gd(e){let t=ve(e.paths.metaPath),n=Mo(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Sn(e.paths.outputDb,i),a=n[i];if(!t){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:a,scipPath:o});continue}if(t.version!==3){r.set(i,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:a,scipPath:o});continue}if(i==="typescript"&&t.scipCompanion==="deferred"){r.set(i,{reused:!1,reason:"whole TypeScript SCIP companion is deferred behind changed-document overlays",fingerprint:a,scipPath:o});continue}if(!t.languageFingerprints){r.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:a,scipPath:o});continue}let s=t.languageFingerprints[i];if(!s){r.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:a,scipPath:o});continue}if(!j(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:a,scipPath:o});continue}if(L(s)!==L(a)){r.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:a,scipPath:o});continue}r.set(i,{reused:!0,fingerprint:a,scipPath:o})}return r}function Vd(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:be(o.fingerprint),outputBytes:Re(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),a=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,s=a?n.classification.get(a):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:s?.reason??o?.reason??i.skipped?.reason,fingerprint:s?be(s.fingerprint):o?be(o.fingerprint):"unknown",outputBytes:i.outputBytes??null,durationMs:i.durationMs,command:i.command})}if(n)for(let[i,o]of n.classification)o.reused&&r.push({id:`typescript:${i}`,language:"typescript",reused:!0,fingerprint:be(o.fingerprint),outputBytes:Re(it(n.outputDb,i)),durationMs:0});return r}function be(e){return bd("sha256").update(L(e)).digest("hex").slice(0,16)}function Re(e){try{return Pd(e).size}catch{return null}}function Bd(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function Ud(e,t,n,r,i,o,a,s){let c=!s||s.completeScipUpdated,u=!1;c&&(wo(e.paths.outputDb,n),u=ko(n,e.tempPaths.tempOutputScip,e.onStatus));let d=Kd({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:u,materializeFullFallback:()=>{if(!s||s.completeScipUpdated)return u;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),Xi({cacheDir:h(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let y=n.map(w=>w.language==="typescript"?{language:w.language,scipPath:s.candidateScipPath}:w);return wo(e.paths.outputDb,y),u=ko(y,e.tempPaths.tempOutputScip,e.onStatus),u}});if(N(J(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&s){let y=null,w=null;try{y=new W({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),w=new W({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let k=Cn(y,e.fingerprint,s.referenceFragmentsByFile,w);e.onStatus(`Cached exact TypeScript reference fragments for ${k} affected document(s).`)}catch(k){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${k instanceof Error?k.message:String(k)}.`)}finally{y?.close(),w?.close()}}let p=yn(e.paths.metaPath),l=d.mode==="incremental"&&s?el(s,d.changedDocumentPaths):yt({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:p,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),m=ot({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(y=>y.language),skipped:[...r]}),g=d.mode==="incremental"&&d.scipCompanion==="deferred",I={...o};g&&delete I.typescript;let{metadata:S,pruneProjects:R}=Oo({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:I,typescriptProjectShardContext:a,lastRefresh:m});return S.scipCompanion=g?"deferred":"current",Co(e.paths.outputDb,R),bn(e.tempPaths.tempMetaPath,S),We({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:d.mode==="incremental"&&d.scipCompanion==="deferred",publication:d.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:d.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:d.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:d.patchDurationMs,scipCompanion:d.scipCompanion,...d.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:d.converterDurationMs,scipCompanion:"current",...d.fallbackReason?{fallbackReason:d.fallbackReason}:{}}}),ri(h(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),jo(e.paths.outputDb,l,e.onStatus),m}function Wd(e,t,n,r,i,o){let a=yn(e.paths.metaPath),s=null;try{nt(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(p){s=Zn("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}N(J(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),s??=yt({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,refreshResult:"reused"});let c=ot({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:u,pruneProjects:d}=Oo({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return Co(e.paths.outputDb,d),bn(e.paths.metaPath,u),fi(e.paths.outputDb,e.paths.metaPath),jo(e.paths.outputDb,s,e.onStatus),c}function yn(e){return kn(ve(e)?.fingerprint)}function jo(e,t,n){try{er(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 Oo(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:3,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function 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=ve(e.metaPath)?.typescriptProjectShards;return{field:t,pruneProjects:t?Object.keys(t):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function Co(e,t){let n=No(e);if(t===null){U(n,{recursive:!0,force:!0});return}let r;try{r=Id(n)}catch{return}for(let i of qd(r,t))U(v(n,i),{force:!0})}function qd(e,t){let n=new Set(t.map(r=>`${Ot(r)}.scip`));return e.filter(r=>!n.has(r))}function wo(e,t){for(let n of t){let r=Sn(e,n.language);tt(h(r),{recursive:!0}),n.scipPath!==r&&nt(n.scipPath,r)}}async function Hd(e,t){if(!pt()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
295
+ `,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function dd(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function Ro(e,t,n){let r=K();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:A(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function gn(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 fn(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 ld(e,t){let n=fn(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=fn(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function pd(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(...fn(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function gd(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return ld(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function fd(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of hd(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&&(vo(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function vo(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 md(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function hd(e,t,n,r,i,o){let a=e.getDocumentHighlights?.(t,n,[t])??[],s=[];for(let c of a)if(c.fileName===t)for(let u of c.highlightSpans){let d=yd(r,u.textSpan.start,o,i.text);d!==null&&s.push(d)}return s}function yd(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=pn(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function tm(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=Dd(e),a=Date.now();tt(h(o.outputScip),{recursive:!0}),tt(h(o.outputDb),{recursive:!0});let s=e.languages??St(t);if(s.length===0)throw new Error("No supported languages detected in this project. Looked for: tsconfig.json, Cargo.toml, go.mod, pyproject.toml, etc.");r(`Detected languages: ${s.join(", ")}`);let c=ee("reindex.fingerprint",()=>Tn(t,s,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:s.length}),u,d;if(e.skipIfUnchanged!==!1&&!Ei(t,o.outputDb)&&Io(o.outputScip)===Io(v(h(o.outputDb),"index.scip"))){let g=Te(t);if(u=g?He(g,c):void 0,u){let I=C(u);if(I){if(!Td(o,c))try{Xt({snapshot:u,manifest:I,targetCacheDir:h(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${u.generationId.slice(0,12)}`)}catch(S){r(`Shared generation attach failed; continuing locally: ${hn(S)}`)}}else{let S=await Di(u);if(S.kind==="owner")d=S.release;else if(S.kind==="generation-ready"){let R=C(u);if(R)try{Xt({snapshot:u,manifest:R,targetCacheDir:h(o.outputDb),targetProjectRoot:t,action:"waited"}),r(`Attached shared generation ${u.generationId.slice(0,12)} after waiting`)}catch(y){r(`Shared generation attach failed after waiting; continuing locally: ${hn(y)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let p=ie(v(h(o.outputDb),"cache-lifecycle.lock"),{waitMs:3e4});if(!p)throw d?.(),new Error(`Could not acquire scip-query cache lifecycle lock for ${h(o.outputDb)}.`);let l;try{l=await te("reindex.lock",()=>tl(v(h(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:s.length})}catch(g){throw p.release(),d?.(),g}let m=null;try{let g=null,I=ee("reindex.reuse-check",()=>(g=Fd({opts:e,paths:o,languages:s,fingerprint:c,start:a,onStatus:r}),g),()=>({languages:s.length,reused:g!==null}));if(I)return Po({snapshot:u,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),I;await te("reindex.scip-cli-ready",()=>Hd(i,r));let S=jd(o);m=S.runDir;let R,y=await te("reindex.fresh",async()=>(R=await Cd({opts:e,languages:s,projectRoot:t,paths:o,tempPaths:S,fingerprint:c,start:a,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),R),()=>({languages:s.length,reused:R?.reused,skipped:R?.skipped.length}));return Po({snapshot:u,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),y}catch(g){throw Go(o.metaPath,ot({trigger:e.trigger,result:"failed",start:a,error:g instanceof Error?g.message:String(g)})),g}finally{m&&U(m,{recursive:!0,force:!0}),l(),p.release(),d?.()}}function Po(e){if(e.snapshot){if(C(e.snapshot)){ze(e.snapshot,h(e.paths.outputDb),"local-fresh");return}try{let t=Te(e.projectRoot),n=t?He(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}Ti({snapshot:e.snapshot,sourceCacheDir:h(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=Te(e.projectRoot);return(r?He(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),ze(e.snapshot,h(e.paths.outputDb),"built"),e.onStatus(`Published shared generation ${e.snapshot.generationId.slice(0,12)}`)}catch(t){e.onStatus(`Shared generation publication failed; local index remains valid: ${hn(t)}`)}}}function Td(e,t){if(!O(e.outputScip)||!O(e.outputDb)||!$o(e.metaPath,t))return!1;let n=G(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function hn(e){return e instanceof Error?e.message:String(e)}function Dd(e){let t=e.outputScip??v(e.projectRoot,"index.scip"),n=e.outputDb??v(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:v(h(n),"meta.json")}}function Fd(e){let t=G(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!O(e.paths.outputScip)||!O(e.paths.outputDb)||!$o(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;N(J(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=Date.now()-e.start,r=ot({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return Go(e.paths.metaPath,r),e.onStatus(`Index unchanged; reused existing SQLite index in ${(n/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:n,reused:!0,skipped:[],lastRefresh:r,shards:Od(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function Od(e,t,n,r){let i=Mo(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:be(i[o]),outputBytes:Re(Sn(e.outputDb,o)),durationMs:0}))}function jd(e){let t=xd(v(h(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:v(t,et(e.outputScip)),tempOutputDb:v(t,et(e.outputDb)),tempMetaPath:v(t,et(e.metaPath))}}async function Cd(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await te("reindex.language-indexers",async()=>(n=await Ad(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:a,languageFingerprints:s,shards:c,typescriptProjectShardContext:u,incrementalTypeScript:d}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),_d({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let m=ee("reindex.publish",()=>Wd(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),g=m.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(I=>I.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:m,shards:c}}let p=ee("reindex.publish",()=>Ud(e,t,i,o,a,s,u,d),{mode:d?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),l=p.durationMs;return e.onStatus(`Done in ${(l/1e3).toFixed(1)}s`),{languages:i.map(m=>m.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:l,reused:!1,skipped:o,lastRefresh:p,shards:c}}function _d(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!O(e.run.paths.outputScip)||!O(e.run.paths.outputDb))return!1;let t=G(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 Ad(e,t){let n=Gd({paths:e.paths,projectRoot:e.projectRoot,languages:e.languages,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath}),r=[],i=new Set;for(let[E,xn]of n)xn.reused&&(r.push({language:E,scipPath:xn.scipPath}),i.add(E));for(let E of i)e.onStatus(`Reusing cached ${E} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),a=G(e.paths.outputDb,e.paths.metaPath),s=ve(e.paths.metaPath),c=a.state==="legacy"||a.state==="current",u=s?.scipCompanion!=="deferred"&&(a.state!=="current"||a.generation.publication?.scipCompanion!=="deferred"),d=o&&!o.reused&&c?Qi({projectRoot:e.projectRoot,cacheDir:h(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:xe(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:xe(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:u,previousSnapshot:yn(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,p=new Set(d?["typescript"]:[]),l=d?void 0:Ld(e,n),{preparedRuns:m,skippedLanguages:g,languageOutputScipPaths:I}=zd({languages:e.languages.filter(E=>!i.has(E)&&!p.has(E)),tempOutputScip:e.tempPaths.tempOutputScip,projectRoot:e.projectRoot,env:t,skipAutoInstall:e.skipAutoInstall,pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,preDiscoveredTypeScriptProjects:l?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),S=l?m.filter(E=>E.language!=="typescript"||l.missedProjectIds.has(E.id)):m,R=await Zi(S,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),y=[];if(l){Nd(e.paths.outputDb,R);let E=I.typescript??e.tempPaths.tempOutputScip;y=$d({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:E,reusedProjects:l.reusedProjects})}let w=[...R,...y],{indexedOutputs:k}=Qd(w,g),Ie=d?[{language:"typescript",scipPath:d.scipPath}]:[],Rn=[...r,...Ie,...k];Xd(Rn,g,e.languages,e.opts.allowPartial,e.onStatus);let Vo=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:Re(d.scipPath)??void 0}]:[],Bo=Vd(n,[...R,...Vo],l?{outputDb:e.paths.outputDb,classification:l.classification}:void 0);return{indexedOutputs:Rn,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:Bd(n,e.languages),shards:Bo,typescriptProjectShardContext:l?{projects:l.allProjects,fingerprints:l.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function Ld(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=Se(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Tr(e.projectRoot,r),o=wr(n.fingerprint.files,r),a=kr(r,i),s=Er(r,o,a),c=ve(e.paths.metaPath),d=Md(c,s,g=>O(it(e.paths.outputDb,g))),p=[...d.entries()].filter(([,g])=>g.reused).map(([g])=>g),l=new Set(p),m=new Set(r.filter(g=>!l.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:s,classification:d,reusedProjects:p,missedProjectIds:m}}function Md(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.typescriptProjectShards?.[i];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 Nd(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=it(e,r);tt(h(i),{recursive:!0}),nt(n.scipPath,i)}}function $d(e){return e.reusedProjects.map((t,n)=>{let r=it(e.outputDb,t),i=xe(e.tempOutputScip,"typescript-project-cached",n);return nt(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Re(i)??void 0}})}function Gd(e){let t=ve(e.paths.metaPath),n=Mo(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Sn(e.paths.outputDb,i),a=n[i];if(!t){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:a,scipPath:o});continue}if(t.version!==3){r.set(i,{reused:!1,reason:`metadata version ${String(t.version??"unknown")} predates per-language shard caching`,fingerprint:a,scipPath:o});continue}if(i==="typescript"&&t.scipCompanion==="deferred"){r.set(i,{reused:!1,reason:"whole TypeScript SCIP companion is deferred behind changed-document overlays",fingerprint:a,scipPath:o});continue}if(!t.languageFingerprints){r.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:a,scipPath:o});continue}let s=t.languageFingerprints[i];if(!s){r.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:a,scipPath:o});continue}if(!O(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:a,scipPath:o});continue}if(L(s)!==L(a)){r.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:a,scipPath:o});continue}r.set(i,{reused:!0,fingerprint:a,scipPath:o})}return r}function Vd(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:be(o.fingerprint),outputBytes:Re(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),a=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,s=a?n.classification.get(a):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:s?.reason??o?.reason??i.skipped?.reason,fingerprint:s?be(s.fingerprint):o?be(o.fingerprint):"unknown",outputBytes:i.outputBytes??null,durationMs:i.durationMs,command:i.command})}if(n)for(let[i,o]of n.classification)o.reused&&r.push({id:`typescript:${i}`,language:"typescript",reused:!0,fingerprint:be(o.fingerprint),outputBytes:Re(it(n.outputDb,i)),durationMs:0});return r}function be(e){return bd("sha256").update(L(e)).digest("hex").slice(0,16)}function Re(e){try{return Pd(e).size}catch{return null}}function Bd(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function Ud(e,t,n,r,i,o,a,s){let c=!s||s.completeScipUpdated,u=!1;c&&(wo(e.paths.outputDb,n),u=ko(n,e.tempPaths.tempOutputScip,e.onStatus));let d=Kd({run:e,env:t,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,incrementalTypeScript:s,completeScipAvailable:c,completeScipSanitized:u,materializeFullFallback:()=>{if(!s||s.completeScipUpdated)return u;e.onStatus("Materializing the deferred whole TypeScript SCIP companion for full conversion..."),Xi({cacheDir:h(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let y=n.map(w=>w.language==="typescript"?{language:w.language,scipPath:s.candidateScipPath}:w);return wo(e.paths.outputDb,y),u=ko(y,e.tempPaths.tempOutputScip,e.onStatus),u}});if(N(J(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),d.mode==="incremental"&&s){let y=null,w=null;try{y=new W({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),w=new W({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let k=Cn(y,e.fingerprint,s.referenceFragmentsByFile,w);e.onStatus(`Cached exact TypeScript reference fragments for ${k} affected document(s).`)}catch(k){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${k instanceof Error?k.message:String(k)}.`)}finally{y?.close(),w?.close()}}let p=yn(e.paths.metaPath),l=d.mode==="incremental"&&s?el(s,d.changedDocumentPaths):yt({projectRoot:e.projectRoot,previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.tempPaths.tempOutputDb,candidateIndexPath:e.tempPaths.tempOutputScip,previousSnapshot:p,currentSnapshot:e.fingerprint,refreshResult:"rebuilt"}),m=ot({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(y=>y.language),skipped:[...r]}),g=d.mode==="incremental"&&d.scipCompanion==="deferred",I={...o};g&&delete I.typescript;let{metadata:S,pruneProjects:R}=jo({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:I,typescriptProjectShardContext:a,lastRefresh:m});return S.scipCompanion=g?"deferred":"current",Co(e.paths.outputDb,R),bn(e.tempPaths.tempMetaPath,S),We({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:d.mode==="incremental"&&d.scipCompanion==="deferred",publication:d.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:d.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:d.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:d.patchDurationMs,scipCompanion:d.scipCompanion,...d.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:d.converterDurationMs,scipCompanion:"current",...d.fallbackReason?{fallbackReason:d.fallbackReason}:{}}}),ri(h(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),Oo(e.paths.outputDb,l,e.onStatus),m}function Wd(e,t,n,r,i,o){let a=yn(e.paths.metaPath),s=null;try{nt(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(p){s=Zn("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}N(J(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),s??=yt({projectRoot:e.projectRoot,previousDbPath:e.tempPaths.tempOutputDb,previousIndexPath:e.paths.outputScip,candidateDbPath:e.paths.outputDb,candidateIndexPath:e.paths.outputScip,previousSnapshot:a,currentSnapshot:e.fingerprint,refreshResult:"reused"});let c=ot({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:u,pruneProjects:d}=jo({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return Co(e.paths.outputDb,d),bn(e.paths.metaPath,u),fi(e.paths.outputDb,e.paths.metaPath),Oo(e.paths.outputDb,s,e.onStatus),c}function yn(e){return kn(ve(e)?.fingerprint)}function Oo(e,t,n){try{er(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 jo(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:3,status:e.skippedLanguages.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.run.fingerprint,languageFingerprints:e.languageFingerprints,typescriptProjectShards:t.field,requestedLanguages:e.run.languages,indexedLanguages:e.indexedOutputs.map(n=>n.language),skipped:[...e.skippedLanguages],lastRefresh:e.lastRefresh},pruneProjects:t.pruneProjects}}function 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=ve(e.metaPath)?.typescriptProjectShards;return{field:t,pruneProjects:t?Object.keys(t):[]}}return e.context?{field:e.context.fingerprints,pruneProjects:e.context.projects}:{field:void 0,pruneProjects:[]}}function Co(e,t){let n=No(e);if(t===null){U(n,{recursive:!0,force:!0});return}let r;try{r=Id(n)}catch{return}for(let i of qd(r,t))U(v(n,i),{force:!0})}function qd(e,t){let n=new Set(t.map(r=>`${jt(r)}.scip`));return e.filter(r=>!n.has(r))}function wo(e,t){for(let n of t){let r=Sn(e,n.language);tt(h(r),{recursive:!0}),n.scipPath!==r&&nt(n.scipPath,r)}}async function Hd(e,t){if(!pt()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
296
296
  Install from: https://github.com/sourcegraph/scip/releases`);if(Ed()==="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 with optional dependencies enabled, run 'npm install -g scip-query-scip-windows', or set SCIP_QUERY_SCIP_BIN to a local scip.exe path.");if(t("scip CLI not found on PATH. Attempting auto-install..."),!gt(t))throw new Error(`The scip CLI is required but could not be installed.
297
- Install manually from: https://github.com/sourcegraph/scip/releases`)}}function zd(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?xe(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=Yd({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?_o(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function Yd(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[mn({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??Se(e.projectRoot,e.typescriptProjects);return t.length===0?[mn({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(e.onStatus(`Indexing TypeScript workspace as ${t.length} project shard(s).`),t.map((n,r)=>mn({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:xe(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function mn(e){let t=Oe(e.language),n=ne(t),r=ct(t,e.projectRoot);if(!r&&!st(t)){if(e.skipAutoInstall){let s=`${n} not found on PATH (auto-install disabled). ${t.installUrl??""}`.trim();return e.onStatus(`Skipping ${e.language}: ${s}`),{skipped:{language:e.language,reason:s}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!cn(t,e.onStatus)){let s=`${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}: ${s}`),{skipped:{language:e.language,reason:s}}}}let i=r??re(t);if(!i){let s=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${s}`),{skipped:{language:e.language,reason:s}}}let{binary:o,args:a}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:i,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0});return{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:i,binary:o,args:a,env:ut(t,e.env,i)}}}function Qd(e,t){let n=new Map;for(let i of e)if(i.skipped)_o(t,i.skipped);else{let o=`${i.language}\0${i.outputScipPath}`,a=n.get(o)??{language:i.language,outputScipPath:i.outputScipPath,scipPaths:[]};a.scipPaths.push(i.scipPath),n.set(o,a)}let r=[];for(let i of n.values())if(i.scipPaths.length>1)kt(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&Fo(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function _o(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 Xd(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
297
+ Install manually from: https://github.com/sourcegraph/scip/releases`)}}function zd(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?xe(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=Yd({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?_o(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function Yd(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[mn({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??Se(e.projectRoot,e.typescriptProjects);return t.length===0?[mn({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})]:(e.onStatus(`Indexing TypeScript workspace as ${t.length} project shard(s).`),t.map((n,r)=>mn({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:xe(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function mn(e){let t=je(e.language),n=ne(t),r=ct(t,e.projectRoot);if(!r&&!st(t)){if(e.skipAutoInstall){let s=`${n} not found on PATH (auto-install disabled). ${t.installUrl??""}`.trim();return e.onStatus(`Skipping ${e.language}: ${s}`),{skipped:{language:e.language,reason:s}}}if(e.onStatus(`${n} not found. Attempting auto-install...`),!cn(t,e.onStatus)){let s=`${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}: ${s}`),{skipped:{language:e.language,reason:s}}}}let i=r??re(t);if(!i){let s=`${n} was not found after installation checks.`;return e.onStatus(`Skipping ${e.language}: ${s}`),{skipped:{language:e.language,reason:s}}}let{binary:o,args:a}=t.indexArgs({projectRoot:e.projectRoot,outputPath:e.scipPath,pnpmWorkspaces:e.pnpmWorkspaces,indexerBinary:i,projectPath:e.projectPath,configPath:e.language==="clojure"?e.clojureConfigPath:void 0});return{prepared:{id:e.id,language:e.language,label:e.label,scipPath:e.scipPath,outputScipPath:e.outputScipPath,config:t,resolvedBinary:i,binary:o,args:a,env:ut(t,e.env,i)}}}function Qd(e,t){let n=new Map;for(let i of e)if(i.skipped)_o(t,i.skipped);else{let o=`${i.language}\0${i.outputScipPath}`,a=n.get(o)??{language:i.language,outputScipPath:i.outputScipPath,scipPaths:[]};a.scipPaths.push(i.scipPath),n.set(o,a)}let r=[];for(let i of n.values())if(i.scipPaths.length>1)kt(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&Fo(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function _o(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 Xd(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
298
298
  `);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
299
299
  `+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.
300
300
  `+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
301
- `))}function ko(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=pr(e.map(o=>o.scipPath),t);return Lo(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Fo(e[0].scipPath,t);return!1}function Kd(e){let t;if(Zd(e)){let i=v(e.run.tempPaths.runDir,"typescript-affected.db");try{Ao(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();Eo(e.incrementalTypeScript.affectedScipPath,i,e.env,e.run.onStatus),e.run.onStatus(`Converted affected SCIP documents in ${(performance.now()-o).toFixed(0)}ms.`);let a=Rr({previousDbPath:e.run.paths.outputDb,miniDbPath:i,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:e.incrementalTypeScript.affectedFiles});return e.run.onStatus(`Patched ${a.affectedDocumentCount} SQLite document(s) in ${(a.durationMs/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:a.changedDocumentPaths,patchDurationMs:a.durationMs,converterDurationMs:performance.now()-o,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(o){t=o instanceof Error?o.message:String(o),U(i,{force:!0}),U(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}}let n=e.completeScipSanitized;e.completeScipAvailable||(n=e.materializeFullFallback());let r=performance.now();return Eo(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function Zd(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 el(e,t){let n=Date.now(),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:Date.now()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:ht(e.plan,o,e.projectFileCount)}}function Eo(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!j(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||Ao(e,r);let o=pt();if(!o)throw new Error("scip CLI is not available");Sd(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(o){let a=o instanceof Error?o.message:String(o);throw new Error(`Failed to convert SCIP index to SQLite: ${a}`,{cause:o})}}function Ao(e,t){let n=dr(e);Lo(n,t)}function Lo(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function xe(e,t,n){let r=kd(e)||".scip",i=et(e,r);return v(h(e),`${i}.${n+1}.${t}${r}`)}async function tl(e,t){for(let n=0;n<2;n++){let r=nl(e,t);if(r)return r;let i=rl(e);if(i&&il(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await al(i.pid))throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${h(e)}; refusing to steal an active lock.`);U(e,{force:!0});continue}if(i&&!T(i.pid)){U(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${h(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${h(e)}.`)}function nl(e,t){let n;try{n=vd(e,"wx")}catch(i){if((typeof i=="object"&&i&&"code"in i?i.code:void 0)==="EEXIST")return null;throw i}let r={version:1,pid:process.pid,projectRoot:t.projectRoot,startedAt:new Date().toISOString(),trigger:t.trigger};return wd(n,JSON.stringify(r)+`
302
- `),()=>{try{Rd(n)}finally{U(e,{force:!0})}}}function rl(e){try{let t=JSON.parse(rt(e,"utf-8"));return typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0?null:{version:1,pid:t.pid,projectRoot:typeof t.projectRoot=="string"?t.projectRoot:h(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function il(e,t){return e?.kind==="manual-cli"&&ol(t?.trigger)}function ol(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function al(e){return To(e,"SIGTERM"),await Do(e,2e3)?!0:(To(e,"SIGKILL"),Do(e,1e3))}function To(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function Do(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!T(e))return!0;await sl(50)}return!T(e)}function sl(e){return new Promise(t=>setTimeout(t,e))}function cl(e,t,n){return Tn(e,t,n)}function Mo(e,t,n){return Object.fromEntries(t.map(r=>{let i=Oe(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:En(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},a=r==="clojure"?ul(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&dl(n),...o,clojureConfigPath:a,files:Ee(e,{language:r,markerFiles:i})}]}))}function ul(e){return e?.trim()||void 0}function dl(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Sn(e,t){return v(h(e),"language-indexes",`${t}.scip`)}function No(e){return v(h(e),"language-indexes","typescript-projects")}function it(e,t){return v(No(e),`${Ot(t)}.scip`)}function ve(e){try{return JSON.parse(rt(e,"utf-8"))}catch{return null}}function $o(e,t){try{let n=JSON.parse(rt(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&L(n.fingerprint)===L(t)&&L([...n.indexedLanguages??[]].sort())===L(t.languages)}catch{return!1}}function bn(e,t){b(e,t,{spacing:2,trailingNewline:!0})}function Go(e,t){try{let n=JSON.parse(rt(e,"utf-8"));if(n.version!==2&&n.version!==3)return;bn(e,{...n,lastRefresh:t})}catch{}}function ot(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:Date.now()-e.start,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{cr as INDEXER_CONFIGS,zn as augmentAuxiliaryDocuments,ed as augmentVueResolvedReferences,J as auxiliaryDocumentsAugmentationStage,ne as describeIndexerBinary,St as detectLanguages,Oe as getIndexerConfig,ut as getIndexerExecutionEnv,at as isBinaryAvailable,st as isIndexerInstalled,kt as mergeScipFiles,wt as mergeScipIndexes,nm as reindex,re as resolveIndexerBinary,ct as resolveProjectLocalIndexerBinary,N as runPostIndexAugmentation,cn as tryInstallIndexer,gt as tryInstallScipCli,xo as vueResolvedReferencesAugmentationStage};
301
+ `))}function ko(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=pr(e.map(o=>o.scipPath),t);return Lo(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Fo(e[0].scipPath,t);return!1}function Kd(e){let t;if(Zd(e)){let i=v(e.run.tempPaths.runDir,"typescript-affected.db");try{Ao(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();Eo(e.incrementalTypeScript.affectedScipPath,i,e.env,e.run.onStatus),e.run.onStatus(`Converted affected SCIP documents in ${(performance.now()-o).toFixed(0)}ms.`);let a=Rr({previousDbPath:e.run.paths.outputDb,miniDbPath:i,candidateDbPath:e.run.tempPaths.tempOutputDb,affectedFiles:e.incrementalTypeScript.affectedFiles});return e.run.onStatus(`Patched ${a.affectedDocumentCount} SQLite document(s) in ${(a.durationMs/1e3).toFixed(3)}s.`),{mode:"incremental",changedDocumentPaths:a.changedDocumentPaths,patchDurationMs:a.durationMs,converterDurationMs:performance.now()-o,scipCompanion:e.incrementalTypeScript.completeScipUpdated?"current":"deferred"}}catch(o){t=o instanceof Error?o.message:String(o),U(i,{force:!0}),U(e.run.tempPaths.tempOutputDb,{force:!0}),e.run.onStatus(`Incremental SQLite publication unavailable: ${t}. Falling back to complete conversion.`)}}let n=e.completeScipSanitized;e.completeScipAvailable||(n=e.materializeFullFallback());let r=performance.now();return Eo(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function Zd(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!O(e.run.paths.outputDb)||!O(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 el(e,t){let n=Date.now(),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:Date.now()-n,manifest:e.manifest,plan:e.plan,comparison:o,evaluation:ht(e.plan,o,e.projectFileCount)}}function Eo(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!O(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||Ao(e,r);let o=pt();if(!o)throw new Error("scip CLI is not available");Sd(o,["expt-convert","--output",t,e],{env:n,stdio:"pipe",maxBuffer:50*1024*1024})}catch(o){let a=o instanceof Error?o.message:String(o);throw new Error(`Failed to convert SCIP index to SQLite: ${a}`,{cause:o})}}function Ao(e,t){let n=dr(e);Lo(n,t)}function Lo(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function xe(e,t,n){let r=kd(e)||".scip",i=et(e,r);return v(h(e),`${i}.${n+1}.${t}${r}`)}async function tl(e,t){for(let n=0;n<2;n++){let r=nl(e,t);if(r)return r;let i=rl(e);if(i&&il(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await al(i.pid))throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${h(e)}; refusing to steal an active lock.`);U(e,{force:!0});continue}if(i&&!T(i.pid)){U(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${h(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${h(e)}.`)}function nl(e,t){let n;try{n=vd(e,"wx")}catch(i){if((typeof i=="object"&&i&&"code"in i?i.code:void 0)==="EEXIST")return null;throw i}let r={version:1,pid:process.pid,projectRoot:t.projectRoot,startedAt:new Date().toISOString(),trigger:t.trigger};return wd(n,JSON.stringify(r)+`
302
+ `),()=>{try{Rd(n)}finally{U(e,{force:!0})}}}function rl(e){try{let t=JSON.parse(rt(e,"utf-8"));return typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0?null:{version:1,pid:t.pid,projectRoot:typeof t.projectRoot=="string"?t.projectRoot:h(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function il(e,t){return e?.kind==="manual-cli"&&ol(t?.trigger)}function ol(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function al(e){return To(e,"SIGTERM"),await Do(e,2e3)?!0:(To(e,"SIGKILL"),Do(e,1e3))}function To(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function Do(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!T(e))return!0;await sl(50)}return!T(e)}function sl(e){return new Promise(t=>setTimeout(t,e))}function Mo(e,t,n){return Object.fromEntries(t.map(r=>{let i=je(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:En(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},a=r==="clojure"?cl(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&ul(n),...o,clojureConfigPath:a,files:Ee(e,{language:r,markerFiles:i})}]}))}function cl(e){return e?.trim()||void 0}function ul(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Sn(e,t){return v(h(e),"language-indexes",`${t}.scip`)}function No(e){return v(h(e),"language-indexes","typescript-projects")}function it(e,t){return v(No(e),`${jt(t)}.scip`)}function ve(e){try{return JSON.parse(rt(e,"utf-8"))}catch{return null}}function $o(e,t){try{let n=JSON.parse(rt(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&L(n.fingerprint)===L(t)&&L([...n.indexedLanguages??[]].sort())===L(t.languages)}catch{return!1}}function bn(e,t){b(e,t,{spacing:2,trailingNewline:!0})}function Go(e,t){try{let n=JSON.parse(rt(e,"utf-8"));if(n.version!==2&&n.version!==3)return;bn(e,{...n,lastRefresh:t})}catch{}}function ot(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs:Date.now()-e.start,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{cr as INDEXER_CONFIGS,zn as augmentAuxiliaryDocuments,ed as augmentVueResolvedReferences,J as auxiliaryDocumentsAugmentationStage,ne as describeIndexerBinary,St as detectLanguages,je as getIndexerConfig,ut as getIndexerExecutionEnv,at as isBinaryAvailable,st as isIndexerInstalled,kt as mergeScipFiles,wt as mergeScipIndexes,tm as reindex,re as resolveIndexerBinary,ct as resolveProjectLocalIndexerBinary,N as runPostIndexAugmentation,cn as tryInstallIndexer,gt as tryInstallScipCli,xo as vueResolvedReferencesAugmentationStage};
303
303
  //# sourceMappingURL=reindex.js.map