scip-query 0.17.0 → 0.17.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 (103) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +19 -0
  3. package/dist/{chunk-A4KRWTXD.js → chunk-2DUWNJKE.js} +2 -2
  4. package/dist/{chunk-KTZACYL6.js → chunk-2TM23JYJ.js} +2 -2
  5. package/dist/{chunk-42YU6TEB.js → chunk-35DURZXI.js} +2 -2
  6. package/dist/{chunk-TCOWAGR2.js → chunk-3YEBIYXL.js} +2 -2
  7. package/dist/{chunk-H4SMB657.js → chunk-5QSMW5IO.js} +2 -2
  8. package/dist/{chunk-AQ34B63A.js → chunk-623AZLTE.js} +2 -2
  9. package/dist/{chunk-RZEVUYMG.js → chunk-6TJERPN3.js} +2 -2
  10. package/dist/{chunk-NJBARXRO.js → chunk-7H37Z4UO.js} +2 -2
  11. package/dist/{chunk-VT2KFEPG.js → chunk-BBTVIIOI.js} +2 -2
  12. package/dist/{chunk-CYDOV3AQ.js → chunk-BTYDBDX5.js} +2 -2
  13. package/dist/{chunk-3EBDPBBU.js → chunk-BW4VDICR.js} +2 -2
  14. package/dist/{chunk-JVTMRIKU.js → chunk-CKRVVBM6.js} +2 -2
  15. package/dist/{chunk-6G3GQWTK.js → chunk-CSMPXDYE.js} +2 -2
  16. package/dist/{chunk-KYUYAWKA.js → chunk-E5HPTSRD.js} +2 -2
  17. package/dist/chunk-E7BTIEAY.js +2 -0
  18. package/dist/{chunk-KLFCCRI7.js → chunk-EUMETOTD.js} +2 -2
  19. package/dist/{chunk-MVFNACWB.js → chunk-FY6RCFDH.js} +2 -2
  20. package/dist/{chunk-JYBF5CPE.js → chunk-FZXN37RN.js} +2 -2
  21. package/dist/{chunk-Y3DG4J6A.js → chunk-G4IUQW27.js} +2 -2
  22. package/dist/{chunk-WH65EY7U.js → chunk-HJYHSTCP.js} +2 -2
  23. package/dist/{chunk-PVXSHZLW.js → chunk-HYRSGWFX.js} +2 -2
  24. package/dist/{chunk-ZMD4O5UP.js → chunk-HZVG4KID.js} +2 -2
  25. package/dist/{chunk-HV4N3UBV.js → chunk-IHD2CHMX.js} +2 -2
  26. package/dist/{chunk-7CHIAMKS.js → chunk-IKAJI4SI.js} +2 -2
  27. package/dist/{chunk-TL2IXVGH.js → chunk-IZLWLO4X.js} +2 -2
  28. package/dist/{chunk-JJAH2VLD.js → chunk-JYBP5ZIR.js} +2 -2
  29. package/dist/{chunk-QNCVN5EH.js → chunk-KWMRY4RN.js} +2 -2
  30. package/dist/{chunk-KAOWSWEX.js → chunk-KWQKWY6M.js} +2 -2
  31. package/dist/{chunk-IK2NG76R.js → chunk-MBDBNQBW.js} +2 -2
  32. package/dist/chunk-MON5XXTG.js +7 -0
  33. package/dist/{chunk-BBBZB5WY.js → chunk-O27267B6.js} +2 -2
  34. package/dist/{chunk-34RCSYMZ.js → chunk-O56VBJKB.js} +2 -2
  35. package/dist/{chunk-J4HK7PQS.js → chunk-OBPR6E5Z.js} +2 -2
  36. package/dist/{chunk-YD7GGLGE.js → chunk-OC7XDK62.js} +2 -2
  37. package/dist/{chunk-ABRWGVC6.js → chunk-PPAT3XUL.js} +2 -2
  38. package/dist/{chunk-PYOZHG6A.js → chunk-QYBCGCY5.js} +2 -2
  39. package/dist/{chunk-EPDV3SQD.js → chunk-RPPV6Y4K.js} +2 -2
  40. package/dist/{chunk-OQRMCT2N.js → chunk-SQJ72PQW.js} +5 -5
  41. package/dist/{chunk-KO2TFDIP.js → chunk-SSH2NPYS.js} +2 -2
  42. package/dist/chunk-U267E6YN.js +120 -0
  43. package/dist/{chunk-JUADXGUH.js → chunk-UKUISUS6.js} +2 -2
  44. package/dist/{chunk-LC57FSPX.js → chunk-V7MX6YUF.js} +2 -2
  45. package/dist/{chunk-SREWDA7Q.js → chunk-W2I4QAW7.js} +2 -2
  46. package/dist/{chunk-5ODF4JGH.js → chunk-W3HSUCRG.js} +2 -2
  47. package/dist/{chunk-VCOAUTSI.js → chunk-WENI5ZDR.js} +2 -2
  48. package/dist/{chunk-VPVAQRHM.js → chunk-WGDIA2TU.js} +2 -2
  49. package/dist/{chunk-7MT6UM4D.js → chunk-WT34AUWL.js} +2 -2
  50. package/dist/{chunk-OP5RO2CF.js → chunk-Y4BBVPRK.js} +2 -2
  51. package/dist/cli.js +280 -280
  52. package/dist/index.js +1 -1
  53. package/dist/queries/affected.js +1 -1
  54. package/dist/queries/bottlenecks.js +1 -1
  55. package/dist/queries/call-graph.js +1 -1
  56. package/dist/queries/change-surface.js +1 -1
  57. package/dist/queries/cleanup-plan.js +1 -1
  58. package/dist/queries/complexity-hotspots.js +1 -1
  59. package/dist/queries/complexity.js +1 -1
  60. package/dist/queries/convergence.js +1 -1
  61. package/dist/queries/dataflow.js +1 -1
  62. package/dist/queries/dead.js +1 -1
  63. package/dist/queries/decorative-checkers.js +1 -1
  64. package/dist/queries/diff-gate.js +1 -1
  65. package/dist/queries/diff-impact.js +1 -1
  66. package/dist/queries/drift.js +1 -1
  67. package/dist/queries/extract-candidates.js +1 -1
  68. package/dist/queries/health.js +1 -1
  69. package/dist/queries/hotspots.js +1 -1
  70. package/dist/queries/imports.js +1 -1
  71. package/dist/queries/incomplete-migration.js +1 -1
  72. package/dist/queries/index.js +1 -1
  73. package/dist/queries/isolated.js +1 -1
  74. package/dist/queries/locality-candidates.js +1 -1
  75. package/dist/queries/members.js +1 -1
  76. package/dist/queries/methods.js +1 -1
  77. package/dist/queries/not-implemented.js +1 -1
  78. package/dist/queries/passthrough-candidates.js +1 -1
  79. package/dist/queries/plan-context.js +1 -1
  80. package/dist/queries/recent-duplicates.js +1 -1
  81. package/dist/queries/redundant-reexports.js +1 -1
  82. package/dist/queries/refs.js +1 -1
  83. package/dist/queries/self-audit.js +1 -1
  84. package/dist/queries/similar-signatures.js +1 -1
  85. package/dist/queries/similar.js +1 -1
  86. package/dist/queries/slice.js +1 -1
  87. package/dist/queries/stale-abstractions.js +1 -1
  88. package/dist/queries/surface.js +1 -1
  89. package/dist/queries/trace.js +1 -1
  90. package/dist/queries/twin-ab.js +1 -1
  91. package/dist/queries/unused-imports.js +1 -1
  92. package/dist/queries/unused-params.js +1 -1
  93. package/dist/queries/wrapper-candidates.js +1 -1
  94. package/dist/reindex-worker.js +22 -22
  95. package/dist/reindex.js +36 -36
  96. package/dist/runtime.d.ts +2 -0
  97. package/dist/runtime.js +1 -1
  98. package/dist/watch-server.js +4 -4
  99. package/package.json +2 -1
  100. package/skills/scip-tla-model-system/SKILL.md +10 -8
  101. package/dist/chunk-L7UITWFE.js +0 -120
  102. package/dist/chunk-QVZSWLLZ.js +0 -2
  103. package/dist/chunk-RSZ4KX4B.js +0 -7
package/dist/reindex.js CHANGED
@@ -1,8 +1,8 @@
1
- import{a as B}from"./chunk-WA64GKWB.js";import{a as lt,e as pt,f as Ee,j as On,k as jn,l as _n}from"./chunk-RSZ4KX4B.js";import{a as Fn}from"./chunk-YZXV3CU3.js";import{A as En,B as ke,C as Tn,E as Dn,a as Co,b as ve,c as rt,d as it,e as ot,f as at,g as st,h as ct,i as T,j as b,o as xn,p as In,q as Pe,r as vn,s as Pn,t as wn,u as ut,v as dt,y as kn,z as we}from"./chunk-OQRMCT2N.js";import"./chunk-P5XHIJHI.js";import{a as Ie}from"./chunk-QEIGJJBC.js";import{a as Ao}from"./chunk-QVZSWLLZ.js";import"./chunk-7XP7ZRSI.js";import"./chunk-JLZUM476.js";import{J as bn,K as Rn,d as K}from"./chunk-TLTLJ4SW.js";import{a as xe}from"./chunk-64MNV6AB.js";import{s as Z,t as ee}from"./chunk-M2TRDR25.js";import{execFileSync as od}from"child_process";import{createHash as ad}from"crypto";import{closeSync as sd,copyFileSync as Ze,existsSync as O,mkdirSync as Ke,mkdtempSync as cd,openSync as ud,readdirSync as dd,readFileSync as et,renameSync as xo,rmSync as W,statSync as ld,writeFileSync as pd}from"fs";import{basename as Xe,dirname as h,extname as gd,join as I,resolve as fo}from"path";import{platform as fd}from"os";import{randomUUID as Cn}from"crypto";import{closeSync as An,mkdirSync as Lo,openSync as Ln,readFileSync as Mn,unlinkSync as Nn,writeFileSync as $n}from"fs";import{dirname as Mo,join as No}from"path";function Gn(e,t={}){return te(No(e,"gc.lock"),t)}function te(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??Date.now,o=Date.now()+n;Lo(Mo(e),{recursive:!0});do{let a=Cn();try{let s=Ln(e,"wx");try{let c={version:1,pid:process.pid,token:a,startedAt:new Date(i()).toISOString()};$n(s,`${JSON.stringify(c)}
2
- `)}finally{An(s)}return{release:()=>Un(e,a)}}catch(s){if(s.code!=="EEXIST")return null;let c=Vn(e);if(c&&(c.pid===void 0||!T(c.pid))){$o(e,c);continue}if(Date.now()>=o)return null;Go(Math.min(r,Math.max(1,o-Date.now())))}}while(Date.now()<=o);return null}function Vn(e){try{let t=Mn(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 $o(e,t){let n=`${e}.reclaim`,r=Cn(),i;try{i=Ln(n,"wx")}catch{return!1}try{$n(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
3
- `)}finally{An(i)}try{let o=Vn(e);return!o||o.raw!==t.raw||o.pid!==void 0&&T(o.pid)?!1:(Nn(e),!0)}catch{return!1}finally{Un(n,r)}}function Un(e,t){try{let n=JSON.parse(Mn(e,"utf8"));n.pid===process.pid&&n.token===t&&Nn(e)}catch{}}function Go(e){let t=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));Atomics.wait(t,0,0,e)}import Vo from"better-sqlite3";import{execFileSync as Uo}from"child_process";import{existsSync as Wo,readdirSync as Bo,readFileSync as Jo}from"fs";import{extname as Te,join as Wn}from"path";function J(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Bn({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Bn(e){let t=new Set((e.extensions??bn).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Wo(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Fn(e.projectRoot),r=Ho(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Vo(e.dbPath);try{let o=zo(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
4
- VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let p=0;for(let l of d){if(o.has(l))continue;let m=Jo(Wn(e.projectRoot,l),"utf-8"),g=a.run(Yo(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 Ho(e,t){let n=qo(e,t);if(n)return n;let r=[],i=o=>{let a=o?Wn(e,o):e,s;try{s=Bo(a,{withFileTypes:!0})}catch{return}for(let c of s){if(Rn.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(Te(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function qo(e,t){try{return Uo("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
5
- `).filter(r=>r&&t.has(Te(r).toLowerCase())).sort()}catch{return null}}function zo(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 Yo(e){return Te(e).toLowerCase()===".vue"?"vue":Te(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as Qo}from"crypto";import{appendFileSync as Xo,existsSync as Ko,mkdirSync as Zo,readFileSync as pl}from"fs";import{dirname as qn,join as Jn}from"path";var ea="<global-symbols>";function ta(e){let t=[];for(let n of e.all(`
1
+ import{a as B}from"./chunk-WA64GKWB.js";import{a as lt,e as pt,h as On,i as jn,j as _n}from"./chunk-MON5XXTG.js";import{a as Fn}from"./chunk-YZXV3CU3.js";import{A as En,B as Ee,C as Tn,E as Dn,a as Ao,b as ve,c as rt,d as it,e as ot,f as at,g as st,h as ct,i as T,j as b,o as Rn,p as xn,q as Pe,r as In,s as Pn,t as wn,u as ut,v as dt,y as kn,z as ke}from"./chunk-SQJ72PQW.js";import"./chunk-P5XHIJHI.js";import{a as Ie}from"./chunk-QEIGJJBC.js";import{a as Lo,b as we,e as vn}from"./chunk-E7BTIEAY.js";import"./chunk-7XP7ZRSI.js";import"./chunk-JLZUM476.js";import{J as Sn,K as bn,d as K}from"./chunk-TLTLJ4SW.js";import{a as xe}from"./chunk-64MNV6AB.js";import{s as Z,t as ee}from"./chunk-M2TRDR25.js";import{execFileSync as ad}from"child_process";import{createHash as sd}from"crypto";import{closeSync as cd,copyFileSync as Ze,existsSync as O,mkdirSync as Ke,mkdtempSync as ud,openSync as dd,readdirSync as ld,readFileSync as et,renameSync as Io,rmSync as W,statSync as pd,writeFileSync as gd}from"fs";import{basename as Xe,dirname as h,extname as fd,join as I,resolve as mo}from"path";import{platform as md}from"os";import{randomUUID as Cn}from"crypto";import{closeSync as An,mkdirSync as Mo,openSync as Ln,readFileSync as Mn,unlinkSync as Nn,writeFileSync as $n}from"fs";import{dirname as No,join as $o}from"path";function Gn(e,t={}){return te($o(e,"gc.lock"),t)}function te(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??Date.now,o=Date.now()+n;Mo(No(e),{recursive:!0});do{let a=Cn();try{let s=Ln(e,"wx");try{let c={version:1,pid:process.pid,token:a,startedAt:new Date(i()).toISOString()};$n(s,`${JSON.stringify(c)}
2
+ `)}finally{An(s)}return{release:()=>Un(e,a)}}catch(s){if(s.code!=="EEXIST")return null;let c=Vn(e);if(c&&(c.pid===void 0||!T(c.pid))){Go(e,c);continue}if(Date.now()>=o)return null;Vo(Math.min(r,Math.max(1,o-Date.now())))}}while(Date.now()<=o);return null}function Vn(e){try{let t=Mn(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 Go(e,t){let n=`${e}.reclaim`,r=Cn(),i;try{i=Ln(n,"wx")}catch{return!1}try{$n(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
3
+ `)}finally{An(i)}try{let o=Vn(e);return!o||o.raw!==t.raw||o.pid!==void 0&&T(o.pid)?!1:(Nn(e),!0)}catch{return!1}finally{Un(n,r)}}function Un(e,t){try{let n=JSON.parse(Mn(e,"utf8"));n.pid===process.pid&&n.token===t&&Nn(e)}catch{}}function Vo(e){let t=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));Atomics.wait(t,0,0,e)}import Uo from"better-sqlite3";import{execFileSync as Wo}from"child_process";import{existsSync as Bo,readdirSync as Jo,readFileSync as Ho}from"fs";import{extname as Te,join as Wn}from"path";function J(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Bn({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Bn(e){let t=new Set((e.extensions??Sn).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Bo(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Fn(e.projectRoot),r=qo(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Uo(e.dbPath);try{let o=Yo(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
4
+ VALUES (?, ?, NULL, ?)`),c=i.transaction(d=>{let p=0;for(let l of d){if(o.has(l))continue;let m=Ho(Wn(e.projectRoot,l),"utf-8"),g=a.run(Qo(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 qo(e,t){let n=zo(e,t);if(n)return n;let r=[],i=o=>{let a=o?Wn(e,o):e,s;try{s=Jo(a,{withFileTypes:!0})}catch{return}for(let c of s){if(bn.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(Te(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function zo(e,t){try{return Wo("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
5
+ `).filter(r=>r&&t.has(Te(r).toLowerCase())).sort()}catch{return null}}function Yo(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 Qo(e){return Te(e).toLowerCase()===".vue"?"vue":Te(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as Xo}from"crypto";import{appendFileSync as Ko,existsSync as Zo,mkdirSync as ea,readFileSync as gl}from"fs";import{dirname as qn,join as Jn}from"path";var ta="<global-symbols>";function na(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(`
@@ -58,10 +58,10 @@ import{a as B}from"./chunk-WA64GKWB.js";import{a as lt,e as pt,f as Ee,j as On,k
58
58
  ) AND NOT EXISTS (
59
59
  SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
60
60
  )
61
- `))t.push({relativePath:ea,kind:"global-symbol",values:gt(n)});return na(t)}function na(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=Qo("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 ra(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 ft(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 mt(e,t=oa){let n=t.now();if(!t.databaseExists(e.previousDbPath))return De(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return De(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=we(e.previousSnapshot,e.currentSnapshot),s=new Set(o),c=a.changes.length>0&&!En(a).fullProject&&a.changes.every(l=>s.has(l.path)),u=ke(a,c?t.dependencyGraph(r):new Map,o),d=ra(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:ft(u,d,o.length)}}catch(o){return De(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{Hn(r),Hn(i)}}function zn(e,t,n,r=Date.now()){return De(e,t,r,r,n)}function ia(e){let t=qn(e);return{latestPath:Jn(t,"affected-shadow-latest.json"),historyPath:Jn(t,"affected-shadow.jsonl")}}function Yn(e,t,n=aa){let r=ia(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}function gt(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 oa={now:()=>Date.now(),databaseExists:e=>Ko(e),openDatabase:(e,t,n)=>new B({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>xe(e),dependencyGraph:e=>Ie(e),factDigests:e=>ta(e)},aa={appendHistory:(e,t)=>{Zo(qn(e),{recursive:!0}),Xo(e,`${JSON.stringify(t)}
63
- `)},writeLatest:(e,t)=>b(e,t,{spacing:2,trailingNewline:!0})};function De(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 Hn(e){try{e?.close()}catch{}}import{execFileSync as sa}from"child_process";import{existsSync as ca,readdirSync as Xn}from"fs";import{extname as Kn,join as Zn}from"path";var er=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),ua=[{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 ht(e){let t=[],n=da(e),r=fa(e);for(let i of ua){if(la(e,i.files)){t.push(i.language);continue}if(pa(n,i.globs)){t.push(i.language);continue}ha(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&Qn(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&Qn(t,"c"),t}function da(e){try{return Xn(e)}catch{return[]}}function la(e,t){return t?.length?t.some(n=>ca(Zn(e,n))):!1}function pa(e,t){return t?.length?e.some(n=>t.some(r=>ga(n,r))):!1}function ga(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 fa(e){let t=ma(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=Xn(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=Zn(i,a.name);if(a.isDirectory()){er.has(a.name)||r.push(s);continue}let c=Kn(a.name).toLowerCase();c&&n.add(c)}}return n}function ma(e){try{let t=sa("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=>er.has(o)))continue;let i=Kn(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function ha(e,t){return t?.length?t.some(n=>e.has(n)):!1}function Qn(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{readFileSync as St,writeFileSync as bt}from"fs";import{create as ne}from"@bufbuild/protobuf";import{deserializeSCIP as Rt,serializeSCIP as xt,DocumentSchema as Pa,IndexSchema as rr,MetadataSchema as wa,SymbolInformationSchema as ka}from"@c4312/scip";import{readFileSync as ya,writeFileSync as Sa}from"fs";import{create as tr}from"@bufbuild/protobuf";import{deserializeSCIP as ba,DocumentSchema as Ra,IndexSchema as xa,serializeSCIP as Ia,SymbolRole as va}from"@c4312/scip";function nr(e){let t;try{t=ba(ya(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=yt(t);return n.removedDefinitionOccurrences>0&&Sa(e,Buffer.from(Ia(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function yt(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&va.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(tr(Ra,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:tr(xa,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function It(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=Ta(e),n=Da(e.flatMap(i=>i.documents??[])),r=ar(e.flatMap(i=>i.externalSymbols??[]));return ne(rr,{metadata:t,documents:n,externalSymbols:r})}function vt(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Rt(St(i))),r=It(n);return bt(t,Buffer.from(xt(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function ir(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Rt(St(i))),r=yt(It(n));return bt(t,Buffer.from(xt(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function Ea(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 ne(rr,{metadata:ne(wa,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function or(e,t,n){let r=Rt(St(e)),i=Ea(r,t,n);bt(e,Buffer.from(xt(i)))}function Ta(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 Da(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,ne(Pa,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:Fa([...r.occurrences,...n.occurrences]),symbols:ar([...r.symbols,...n.symbols]),text:ja(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Fa(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 ar(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,ne(ka,{symbol:r.symbol,documentation:_a([...r.documentation,...n.documentation]),relationships:Oa([...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 Oa(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 ja(e,t){return e?t?e.length>=t.length?e:t:e:t}function _a(e){return[...new Set(e)]}import{createHash as Ca}from"crypto";import{copyFileSync as Aa,existsSync as sr,rmSync as cr}from"fs";import{resolve as La}from"path";import lr from"better-sqlite3";var Ma={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}]},Na={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 pr(e){let t=Date.now(),n=$a(e.affectedFiles);if(Ga(e.previousDbPath,e.miniDbPath,e.candidateDbPath),cr(e.candidateDbPath,{force:!0}),!sr(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!sr(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");ur(e.previousDbPath,"previous SQLite generation",!1),ur(e.miniDbPath,"incremental SQLite mini database"),Aa(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new lr(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Pt(r,"main","candidate SQLite generation"),Pt(r,"incremental","incremental SQLite mini database"),Va(r,n),Ua(r,n.length);let i=wt(r,"main",!0),o=M(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{Wa(r),Ba(r),Ja(r),e.onStage?.("after-delete"),Ha(r),e.onStage?.("after-symbol-reconciliation"),qa(r),e.onStage?.("after-insert"),za(r),Ya(r,n.length,o),e.onStage?.("before-commit")}).immediate(),gr(r,"main","candidate SQLite generation");let c=[...Qa(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{cr(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function $a(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 Ga(e,t,n){let r=[e,t,n].map(i=>La(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function ur(e,t,n=!0){let r=new lr(e,{readonly:!0,fileMustExist:!0});try{Pt(r,"main",t),n&&gr(r,"main",t)}finally{r.close()}}function Pt(e,t,n){for(let[r,i]of Object.entries(Ma)){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(Na)){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}`)}dr(e,t,"documents",["relative_path"],n),dr(e,t,"global_symbols",["symbol"],n)}function dr(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 gr(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 Va(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 Ua(e,t){let n=M(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=M(e,`SELECT COUNT(*) AS value
61
+ `))t.push({relativePath:ta,kind:"global-symbol",values:gt(n)});return ra(t)}function ra(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=Xo("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 ia(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 ft(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 mt(e,t=aa){let n=t.now();if(!t.databaseExists(e.previousDbPath))return De(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return De(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&&!En(a).fullProject&&a.changes.every(l=>s.has(l.path)),u=Ee(a,c?t.dependencyGraph(r):new Map,o),d=ia(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:ft(u,d,o.length)}}catch(o){return De(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{Hn(r),Hn(i)}}function zn(e,t,n,r=Date.now()){return De(e,t,r,r,n)}function oa(e){let t=qn(e);return{latestPath:Jn(t,"affected-shadow-latest.json"),historyPath:Jn(t,"affected-shadow.jsonl")}}function Yn(e,t,n=sa){let r=oa(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}function gt(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 aa={now:()=>Date.now(),databaseExists:e=>Zo(e),openDatabase:(e,t,n)=>new B({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>xe(e),dependencyGraph:e=>Ie(e),factDigests:e=>na(e)},sa={appendHistory:(e,t)=>{ea(qn(e),{recursive:!0}),Ko(e,`${JSON.stringify(t)}
63
+ `)},writeLatest:(e,t)=>b(e,t,{spacing:2,trailingNewline:!0})};function De(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 Hn(e){try{e?.close()}catch{}}import{execFileSync as ca}from"child_process";import{existsSync as ua,readdirSync as Xn}from"fs";import{extname as Kn,join as Zn}from"path";var er=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),da=[{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 ht(e){let t=[],n=la(e),r=ma(e);for(let i of da){if(pa(e,i.files)){t.push(i.language);continue}if(ga(n,i.globs)){t.push(i.language);continue}ya(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&Qn(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&Qn(t,"c"),t}function la(e){try{return Xn(e)}catch{return[]}}function pa(e,t){return t?.length?t.some(n=>ua(Zn(e,n))):!1}function ga(e,t){return t?.length?e.some(n=>t.some(r=>fa(n,r))):!1}function fa(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 ma(e){let t=ha(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=Xn(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=Zn(i,a.name);if(a.isDirectory()){er.has(a.name)||r.push(s);continue}let c=Kn(a.name).toLowerCase();c&&n.add(c)}}return n}function ha(e){try{let t=ca("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=>er.has(o)))continue;let i=Kn(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function ya(e,t){return t?.length?t.some(n=>e.has(n)):!1}function Qn(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{readFileSync as St,writeFileSync as bt}from"fs";import{create as ne}from"@bufbuild/protobuf";import{deserializeSCIP as Rt,serializeSCIP as xt,DocumentSchema as wa,IndexSchema as rr,MetadataSchema as ka,SymbolInformationSchema as Ea}from"@c4312/scip";import{readFileSync as Sa,writeFileSync as ba}from"fs";import{create as tr}from"@bufbuild/protobuf";import{deserializeSCIP as Ra,DocumentSchema as xa,IndexSchema as Ia,serializeSCIP as va,SymbolRole as Pa}from"@c4312/scip";function nr(e){let t;try{t=Ra(Sa(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=yt(t);return n.removedDefinitionOccurrences>0&&ba(e,Buffer.from(va(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function yt(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&Pa.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(tr(xa,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:tr(Ia,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function It(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=Da(e),n=Fa(e.flatMap(i=>i.documents??[])),r=ar(e.flatMap(i=>i.externalSymbols??[]));return ne(rr,{metadata:t,documents:n,externalSymbols:r})}function vt(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Rt(St(i))),r=It(n);return bt(t,Buffer.from(xt(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function ir(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>Rt(St(i))),r=yt(It(n));return bt(t,Buffer.from(xt(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function Ta(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 ne(rr,{metadata:ne(ka,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function or(e,t,n){let r=Rt(St(e)),i=Ta(r,t,n);bt(e,Buffer.from(xt(i)))}function Da(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 Fa(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,ne(wa,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:Oa([...r.occurrences,...n.occurrences]),symbols:ar([...r.symbols,...n.symbols]),text:_a(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function Oa(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 ar(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,ne(Ea,{symbol:r.symbol,documentation:Ca([...r.documentation,...n.documentation]),relationships:ja([...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 ja(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 _a(e,t){return e?t?e.length>=t.length?e:t:e:t}function Ca(e){return[...new Set(e)]}import{createHash as Aa}from"crypto";import{copyFileSync as La,existsSync as sr,rmSync as cr}from"fs";import{resolve as Ma}from"path";import lr from"better-sqlite3";var Na={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}]},$a={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 pr(e){let t=Date.now(),n=Ga(e.affectedFiles);if(Va(e.previousDbPath,e.miniDbPath,e.candidateDbPath),cr(e.candidateDbPath,{force:!0}),!sr(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!sr(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");ur(e.previousDbPath,"previous SQLite generation",!1),ur(e.miniDbPath,"incremental SQLite mini database"),La(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new lr(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Pt(r,"main","candidate SQLite generation"),Pt(r,"incremental","incremental SQLite mini database"),Ua(r,n),Wa(r,n.length);let i=wt(r,"main",!0),o=M(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{Ba(r),Ja(r),Ha(r),e.onStage?.("after-delete"),qa(r),e.onStage?.("after-symbol-reconciliation"),za(r),e.onStage?.("after-insert"),Ya(r),Qa(r,n.length,o),e.onStage?.("before-commit")}).immediate(),gr(r,"main","candidate SQLite generation");let c=[...Xa(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{cr(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function Ga(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 Va(e,t,n){let r=[e,t,n].map(i=>Ma(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function ur(e,t,n=!0){let r=new lr(e,{readonly:!0,fileMustExist:!0});try{Pt(r,"main",t),n&&gr(r,"main",t)}finally{r.close()}}function Pt(e,t,n){for(let[r,i]of Object.entries(Na)){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($a)){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}`)}dr(e,t,"documents",["relative_path"],n),dr(e,t,"global_symbols",["symbol"],n)}function dr(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 gr(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 Ua(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 Wa(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
@@ -71,7 +71,7 @@ import{a as B}from"./chunk-WA64GKWB.js";import{a as lt,e as pt,f as Ee,j as On,k
71
71
  FROM incremental.documents d
72
72
  LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
73
73
  WHERE p.relative_path IS NULL
74
- LIMIT 1`).pluck().get();if(n!==t||r!==t||i!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function Wa(e){e.exec(`
74
+ LIMIT 1`).pluck().get();if(n!==t||r!==t||i!==void 0||o!==void 0)throw new Error("incremental SQLite mini database does not exactly match the affected document set")}function Ba(e){e.exec(`
75
75
  CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
76
76
  INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
77
77
  SELECT g.symbol
@@ -98,7 +98,7 @@ import{a as B}from"./chunk-WA64GKWB.js";import{a as lt,e as pt,f as Ee,j as On,k
98
98
  FROM incremental.mentions m
99
99
  JOIN incremental.global_symbols g ON g.id = m.symbol_id
100
100
  WHERE m.role = 1;
101
- `)}function Ba(e){let t=e.prepare(`WITH changed_symbols AS (
101
+ `)}function Ja(e){let t=e.prepare(`WITH changed_symbols AS (
102
102
  SELECT symbol FROM temp.incremental_old_defined_symbols
103
103
  UNION
104
104
  SELECT symbol FROM temp.incremental_new_defined_symbols
@@ -121,7 +121,7 @@ import{a as B}from"./chunk-WA64GKWB.js";import{a as lt,e as pt,f as Ee,j as On,k
121
121
  SELECT u.symbol
122
122
  FROM unaffected_definitions u
123
123
  JOIN changed_symbols c ON c.symbol = u.symbol
124
- LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function Ja(e){e.exec(`
124
+ LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function Ha(e){e.exec(`
125
125
  DELETE FROM main.mentions
126
126
  WHERE chunk_id IN (
127
127
  SELECT c.id
@@ -143,7 +143,7 @@ import{a as B}from"./chunk-WA64GKWB.js";import{a as lt,e as pt,f as Ee,j as On,k
143
143
  );
144
144
  DELETE FROM main.documents
145
145
  WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
146
- `)}function Ha(e){e.exec(`
146
+ `)}function qa(e){e.exec(`
147
147
  UPDATE main.global_symbols
148
148
  SET display_name = NULL,
149
149
  kind = NULL,
@@ -185,7 +185,7 @@ import{a as B}from"./chunk-WA64GKWB.js";import{a as lt,e as pt,f as Ee,j as On,k
185
185
  WHERE source.symbol = main.global_symbols.symbol
186
186
  )
187
187
  WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
188
- `)}function qa(e){let t=M(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=M(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=M(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
188
+ `)}function za(e){let t=M(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=M(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=M(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.defn_enclosing_ranges");e.prepare(`INSERT INTO main.documents(id, language, relative_path, position_encoding, text)
189
189
  SELECT id + ?, language, relative_path, position_encoding, text
190
190
  FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
191
191
  SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
@@ -200,15 +200,15 @@ import{a as B}from"./chunk-WA64GKWB.js";import{a as lt,e as pt,f as Ee,j as On,k
200
200
  r.start_line, r.start_char, r.end_line, r.end_char
201
201
  FROM incremental.defn_enclosing_ranges r
202
202
  JOIN incremental.global_symbols source ON source.id = r.symbol_id
203
- JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function za(e){e.exec(`
203
+ JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function Ya(e){e.exec(`
204
204
  DELETE FROM main.global_symbols
205
205
  WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
206
206
  AND NOT EXISTS (
207
207
  SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
208
208
  );
209
- `)}function Ya(e,t,n){let r=M(e,"SELECT COUNT(*) AS value FROM main.documents"),i=M(e,`SELECT COUNT(*) AS value
209
+ `)}function Qa(e,t,n){let r=M(e,"SELECT COUNT(*) AS value FROM main.documents"),i=M(e,`SELECT COUNT(*) AS value
210
210
  FROM main.documents d
211
- JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(r!==n||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly");let o=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),a=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(o!==void 0||a!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function Qa(e){let t=wt(e,"main",!0),n=wt(e,"incremental",!1);if(JSON.stringify([...t])!==JSON.stringify([...n]))throw new Error("candidate SQLite affected document facts differ from the mini database");return t}function wt(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
211
+ JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`);if(r!==n||i!==t)throw new Error("candidate SQLite document counts changed unexpectedly");let o=e.prepare("SELECT relative_path FROM main.documents GROUP BY relative_path HAVING COUNT(*) > 1 LIMIT 1").pluck().get(),a=e.prepare("SELECT symbol FROM main.global_symbols GROUP BY symbol HAVING COUNT(*) > 1 LIMIT 1").pluck().get();if(o!==void 0||a!==void 0)throw new Error("candidate SQLite generation contains duplicate document paths or symbols")}function Xa(e){let t=wt(e,"main",!0),n=wt(e,"incremental",!1);if(JSON.stringify([...t])!==JSON.stringify([...n]))throw new Error("candidate SQLite affected document facts differ from the mini database");return t}function wt(e,t,n){let r=n?"JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path":"",i=e.prepare(`SELECT d.relative_path, d.language, d.position_encoding, d.text
212
212
  FROM ${t}.documents d
213
213
  ${r}
214
214
  ORDER BY d.relative_path`).all(),o=e.prepare(`SELECT d.relative_path, c.chunk_index, c.start_line, c.end_line, hex(c.occurrences) AS occurrences
@@ -230,13 +230,13 @@ import{a as B}from"./chunk-WA64GKWB.js";import{a as lt,e as pt,f as Ee,j as On,k
230
230
  JOIN ${t}.documents d ON d.id = c.document_id
231
231
  JOIN ${t}.global_symbols g ON g.id = m.symbol_id
232
232
  ${r}
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=Ca("sha256");for(let m of p.sort())l.update(m).update(`
234
- `);u.set(d,l.digest("hex"))}return u}function M(e,t){return e.prepare(t).get().value}import{readFileSync as Xa,writeFileSync as Ka}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 mr(e){let t=e.readFingerprint(),n=Za(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return es(e.cachePath,e.readFingerprint(),r),r}function Za(e,t){try{let n=JSON.parse(Xa(e,"utf-8"));return fr(n.fingerprint)===fr(t)?{result:n.result}:null}catch{return null}}function es(e,t,n){Ka(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
235
- `)}function fr(e){return JSON.stringify(e)}import{createHash as ts}from"crypto";import{existsSync as kt,readFileSync as ns,readdirSync as rs}from"fs";import{dirname as Et,join as Fe,relative as is,resolve as Tt,sep as hr}from"path";function yr(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=xr(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Sr(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=xr(s,e);c&&c!==i&&a.add(c)}}return os(e,r)}function br(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 Dt(e){if(e===".")return"root";let t=ts("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Rr(e,t){let n=Tt(e),r={};for(let i of t)r[i]=as(n,i);return r}function xr(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 os(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 as(e,t){let n=t==="."?e:Fe(e,t),r=ss(n),i=cs(n),o=i?us(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=Fe(e,"package.json");if(!kt(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Ft(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 cs(e){let t=Fe(e,"tsconfig.json");if(kt(t))return t;let n;try{n=rs(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?Fe(e,n[0]):void 0}function us(e,t){let n=Ft(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=ds(n.value,e,t),i=Ir(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function ds(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=Et(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=vr(s,i,n);c&&o.add(c)}return[...o]}function Ir(e,t,n,r){let i=ls(t);if(i)return{pathsTargets:ps(i,Et(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=gs(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=Ft(o);return a.ok?Ir(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function ls(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 ps(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=vr(o,t,n);a&&r.add(a)}return[...r]}function gs(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=Tt(Et(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(hr).includes("node_modules")&&K(n,i)&&kt(i))return i}function vr(e,t,n){let r=e.replace(/\/?\*+$/,""),i=Tt(t,r===""?".":r);if(!K(n,i))return;let a=is(n,i).split(hr).join("/");return a===""?".":a}function fs(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 Ft(e){try{let t=ns(e,"utf-8"),n=JSON.parse(fs(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as li,randomUUID as Jt}from"crypto";import{closeSync as pi,constants as Hs,copyFileSync as si,existsSync as U,lstatSync as qs,mkdirSync as C,mkdtempSync as gi,openSync as fi,readdirSync as zs,readFileSync as F,realpathSync as Ys,renameSync as z,rmSync as V,statSync as Qs,unlinkSync as Wt,writeFileSync as mi}from"fs";import{dirname as hi,join as f,resolve as pe}from"path";import{setTimeout as Xs}from"timers/promises";import{pathToFileURL as ci}from"url";import{deserializeSCIP as yi}from"@c4312/scip";import Ks from"better-sqlite3";import{createRequire as ms}from"module";var hs=ms(import.meta.url),Pr=ys().version;function ys(){for(let e of["../package.json","../../package.json"])try{return hs(e)}catch{}return{version:"0.0.0"}}import{lstatSync as js,readdirSync as _s}from"fs";import{join as Cs,relative as As,resolve as $t,sep as Ls}from"path";import{createHash as Ss}from"crypto";import{existsSync as jt,mkdirSync as bs,readFileSync as Oe,readdirSync as Yl,renameSync as Rs,rmSync as Ql,writeFileSync as xs}from"fs";import{join as Y}from"path";import{create as kr,fromBinary as Er,toBinary as Is}from"@bufbuild/protobuf";import{deserializeSCIP as je,DocumentSchema as _t,IndexSchema as Tr,serializeSCIP as Dr}from"@c4312/scip";var _e=1,re="typescript-scip-fragments";function Fr(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=H(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=Er(_t,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=Dr(kr(Tr,{documents:n,externalSymbols:[]})),i=je(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function Ce(e){let t=Y(e,re);return{rootDir:t,blobDir:Y(t,"blobs"),generationDir:Y(t,"generations")}}function vs(e){let t=je(e.indexBytes);Ur(t.metadata,Wr(e)),Vr(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let a=H(o.relativePath);if(n.has(a))throw new Error(`duplicate TypeScript SCIP document path: ${a}`);n.add(a);let s=Is(_t,o),c=e.documentIdentities.get(a)??(e.allowUntrackedDocuments?q(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:a,contentHash:q(s)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${a}`);r.push(Mr(e.cacheDir,{relativePath:a,bytes:s,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=Nr(e,r);return $r(e.cacheDir,i),i}function Or(e){let t=Ce(e.cacheDir);if(!jt(Ct(t,e.generationIdentity)))return vs(e);let n=_r({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 jr(e){let t=_r({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=H(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,Mr(e.cacheDir,o,s))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=Nr(e,[...n.values()]);return $r(e.cacheDir,i),i}function _r(e){let t=Ce(e.cacheDir),n=Ct(t,e.generationIdentity),r;try{r=Gr(Oe(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=Y(t.blobDir,`${o.blobHash}.scipdoc`),s=Oe(a);if(s.byteLength!==o.byteLength||q(s)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,s)}return{manifest:r,fragments:i}}function Cr(e){let t=Lr(e);return Ot(t.baseIndex,t.completeDocuments,"assembled")}function Ar(e){let t=Lr(e);return Ps(t.deletedAffectedPaths),{completeIndexBytes:Ot(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:Ot(t.baseIndex,t.affectedDocuments,"affected")}}function Lr(e){let t=je(e.baseIndexBytes);Ur(t.metadata,Wr(e)),Vr(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=H(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=H(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=Er(_t,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 Ot(e,t,n){let r=Dr(kr(Tr,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=je(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function Ps(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function Mr(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=H(t.relativePath),i=Buffer.from(t.bytes),o=q(i),a=Ce(e);bs(a.blobDir,{recursive:!0});let s=Y(a.blobDir,`${o}.scipdoc`);if(jt(s)){let c=Oe(s);if(c.byteLength!==i.byteLength||q(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${s}.${process.pid}.${Date.now()}.tmp`;xs(c,i),Rs(c,s)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function Nr(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:_e,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function $r(e,t){let n=Ce(e),r=Ct(n,t.generationIdentity);if(jt(r)){let i=Gr(Oe(r,"utf8"));if(wr(i)!==wr(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}b(r,t,{spacing:2,trailingNewline:!0})}function wr(e){return q(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function Gr(e){let t=JSON.parse(e);if(t.version!==_e||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(H(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function Ct(e,t){return Y(e.generationDir,ws(t))}function ws(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${q(e)}.json`}function Vr(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function Ur(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 Wr(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function H(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 q(e){return Ss("sha256").update(e).digest("hex")}import{createHash as ks}from"crypto";import{existsSync as ie,mkdirSync as Es,readFileSync as ae,readdirSync as At,renameSync as Ts,rmSync as Br,writeFileSync as Ds}from"fs";import{join as D}from"path";var Ae=1,Hr=64*1024*1024,se="typescript-scip-overlays";function qr(e){let t=Qr(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=Nt(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript overlay: ${a}`);r.add(a),n.set(a,Fs(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:Ae,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 Os(e.cacheDir,i),i}function zr(e){let t=Qr(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=ae(D(ce(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||oe(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 Cr({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function Yr(e,t){let n=ce(e),r=D(n,"generations");if(!ie(r))return;let i=new Set(t.map(Mt)),o=new Set;for(let s of At(r).filter(c=>i.has(c))){let c=Lt(ae(D(r,s),"utf8"));for(let u of c.overlays)u.blobHash&&o.add(`${u.blobHash}.scipdoc`)}for(let s of At(r))i.has(s)||Br(D(r,s),{force:!0});let a=D(n,"blobs");if(ie(a))for(let s of At(a))o.has(s)||Br(D(a,s),{force:!0})}function Qr(e,t){let n=D(ce(e),"generations",Mt(t));if(!ie(n))return null;let r=Lt(ae(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function Fs(e,t){let n=Nt(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=oe(r),o=D(ce(e),"blobs");Es(o,{recursive:!0});let a=D(o,`${i}.scipdoc`);if(ie(a)){let s=ae(a);if(s.byteLength!==r.byteLength||oe(s)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let s=`${a}.${process.pid}.${Date.now()}.tmp`;Ds(s,r),Ts(s,a)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function Os(e,t){let n=D(ce(e),"generations",Mt(t.generationIdentity));if(ie(n)){let r=Lt(ae(n,"utf8"));if(Jr(r)!==Jr(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}b(n,t,{spacing:2,trailingNewline:!0})}function Lt(e){let t=JSON.parse(e);if(t.version!==Ae||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(Nt(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function ce(e){return D(e,se)}function Mt(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${oe(e)}.json`}function Jr(e){return oe(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function Nt(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 oe(e){return ks("sha256").update(e).digest("hex")}var ue=1,Gt="language-indexes",Xr=["index.db","index.scip","meta.json"],Kr=[Gt,re,se];function Le(e){let t=[];for(let n of Xr)Ms(e,n),t.push(n);for(let n of Kr)Zr(e,n,t);return{version:ue,files:t.sort()}}function Me(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(!Xr.includes(e)&&!Kr.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function j(e,t){let n=Me(t),r=$t(e),i=$t(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${Ls}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function Zr(e,t,n){let r=Cs(e,t),i;try{i=_s(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()?Zr(e,a,n):o.isFile()&&n.push(Me(a))}}function Ms(e,t){let n=j(e,t),r;try{r=js(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(As($t(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{createHash as Ns}from"crypto";import{copyFileSync as ei,existsSync as $,linkSync as $s,mkdirSync as ti,readFileSync as ii,readdirSync as ni,renameSync as Ut,rmSync as $e,statSync as Gs}from"fs";import{basename as Ne,dirname as de,join as P,relative as ri}from"path";var Q=1,Ge=".scipquery-generations";function Ve(e){let t=Ue(e.outputDb),n=Vs(e,t);e.onStage?.("after-recovery-retained"),e.preserveOutputScip||Vt(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),Vt(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),Vt(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let r=We(e.metaPath,e.outputDb),i={version:Q,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 oi(e){try{let t=JSON.parse(ii(P(Ue(e),"state.json"),"utf8"));return t.version!==Q||typeof t.currentGeneration!="string"||!t.currentGeneration||typeof t.publishedAt!="string"||!Number.isFinite(Date.parse(t.publishedAt))||!Bs(t.previousGeneration)||!Js(t.publication)?null:t}catch{return null}}function ai(e,t,n=()=>new Date){if(!$(e)||!$(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=oi(e),i={version:Q,currentGeneration:We(t,e),...r?.previousGeneration?{previousGeneration:r.previousGeneration}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return b(P(Ue(e),"state.json"),i,{spacing:2,trailingNewline:!0}),i}function G(e,t=P(de(e),"meta.json")){let n=P(Ue(e),"state.json");if(!$(n))return{state:"legacy",statePath:n};let r=oi(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=We(t,e),o=r.currentGeneration===i,a=r.previousGeneration?$(P(de(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 Ue(e){return P(de(e),Ge)}function Vs(e,t){if(!$(e.outputDb))return;let n=We(e.metaPath,e.outputDb),r=P(t,n),i=P(r,Ne(e.outputDb)),o=$(e.metaPath)?P(r,Ne(e.metaPath)):void 0;if(!$(i)){let a=`${r}.${process.pid}.${Date.now()}.tmp`;$e(a,{recursive:!0,force:!0}),ti(a,{recursive:!0});let s=P(a,Ne(e.outputDb));try{$s(e.outputDb,s)}catch{ei(e.outputDb,s)}o&&ei(e.metaPath,P(a,Ne(e.metaPath))),ti(t,{recursive:!0}),Ut(a,r)}return Us(t,n),{generationIdentity:n,databasePath:ri(de(e.outputDb),i),...o?{metadataPath:ri(de(e.outputDb),o)}:{}}}function Us(e,t){for(let n of ni(e,{withFileTypes:!0}))!n.isDirectory()||n.name===t||n.name.endsWith(".tmp")||$e(P(e,n.name),{recursive:!0,force:!0});for(let n of ni(e,{withFileTypes:!0}))n.isDirectory()&&n.name.endsWith(".tmp")&&$e(P(e,n.name),{recursive:!0,force:!0})}function We(e,t){let n=Ns("sha256").update(`sqlite-generation-v${Q}\0`);$(e)&&n.update(Ws(ii(e,"utf8")));let r=Gs(t);return n.update(`\0${r.size}`),n.digest("hex")}function Ws(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 Vt(e,t){$e(`${t}.tmp-replace`,{force:!0}),Ut(e,`${t}.tmp-replace`),Ut(`${t}.tmp-replace`,t)}function Bs(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 Js(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 Ht=1,ui="SCIP_QUERY_SHARED_CACHE",Bt=JSON.stringify({cliVersion:Pr,artifactCatalogVersion:ue,sqliteGenerationStoreVersion:Q,typescriptFragmentStoreVersion:_e,typescriptOverlayStoreVersion:Ae}),Si="manifest.json",Zs="shared-cache.json",qt=[Gt,re,se];function Be(e,t){if(!e.clean||!e.treeOid)return;let n=fe(JSON.stringify({version:Ht,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:Bt}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:Bt,generationId:n,repositoryCacheDir:jn(e.repositoryId)}}function bi(e,t,n){if(process.env[ui]==="0")return`${ui}=0`;if(!_n(n))return"explicit cache or database override";if(pe(t)!==pe(f(On(e),"index.db")))return"index database is outside the managed worktree cache"}function _(e,t=!0){let n=Yt(e),r;try{r=tc(F(f(n,Si),"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=Qs(o);if(!a.isFile()||a.size!==i.size||fe(F(o))!==i.sha256)return null}}catch{return null}return r}function Ri(e){let t=_(e.snapshot);if(t)return t;if(!Pi(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=di(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=Le(e.sourceCacheDir),i=f(e.snapshot.repositoryCacheDir,"generations");C(i,{recursive:!0});let o=gi(f(i,`.tmp-${process.pid}-`));try{let a=[];for(let p of r.files){let l=j(e.sourceCacheDir,p),m=j(o,p);ge(l,m);let g=F(m);a.push({path:p,size:g.byteLength,sha256:fe(g)})}let s=yi(F(f(o,"index.scip"))).metadata?.projectRoot;if(!s)throw new Error("shared SCIP generation has no project root metadata");let c=Qt(e.sourceProjectRoot);if(s!==c)throw new Error("shared SCIP generation root does not match its source worktree");if(di(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let u={version:Ht,artifactCatalogVersion:ue,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,Si),u,{spacing:2,trailingNewline:!0});let d=Yt(e.snapshot);try{if(U(d)&&!_(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=_(e.snapshot);if(l)return l;throw p}return u}finally{V(o,{recursive:!0,force:!0})}}function zt(e){let t=Yt(e.snapshot);C(e.targetCacheDir,{recursive:!0});let n=te(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=gi(f(e.targetCacheDir,".shared-hydrate-")),uc(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let u=j(t,c.path),d=j(r,c.path);ge(u,d);let p=F(d);if(p.byteLength!==c.size||fe(p)!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=Qt(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&or(j(r,c.path),e.manifest.scipProjectRoot,a);if(!Pi(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=ac(e.targetCacheDir,r),o=!0,sc(r,e.targetCacheDir,i),Ve({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}`);Je(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&cc(e.targetCacheDir,i),a}finally{r&&V(r,{recursive:!0,force:!0}),n.release()}}async function xi(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(C(a,{recursive:!0});i()<=o;){if(_(e))return{kind:"generation-ready"};let c=Jt();try{let u=fi(s,"wx");try{mi(u,`${JSON.stringify({version:1,pid:process.pid,token:c,generationId:e.generationId,startedAt:new Date(i()).toISOString()})}
237
- `)}finally{pi(u)}return{kind:"owner",release:()=>{try{let d=JSON.parse(F(s,"utf8"));d.pid===process.pid&&d.token===c&&Wt(s)}catch{}}}}catch(u){if(u.code!=="EEXIST")return{kind:"timeout"};let d=Ii(s);if(d&&(d.pid===void 0||!T(d.pid))){ic(s,d);continue}await Xs(r)}}return _(e)?{kind:"generation-ready"}:{kind:"timeout"}}function Je(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:ec(i)};return oc(e.repositoryCacheDir,o,!0),o}function ec(e){return fe(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:pe(e.projectRoot),localCacheDir:pe(e.localCacheDir)}))}function tc(e){let t=JSON.parse(e);if(t.version!==Ht||t.artifactCatalogVersion!==ue||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!==Bt||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(Me(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 ge(e,t){C(hi(t),{recursive:!0});try{si(e,t,Hs.COPYFILE_FICLONE)}catch{si(e,t)}}function nc(e,t,n){C(e,{recursive:!0}),b(f(e,Zs),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function di(e){try{let t=Le(e),n=li("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 rc(e){try{return JSON.parse(F(f(e,"meta.json"),"utf8"))}catch{return}}function Yt(e){return f(e.repositoryCacheDir,"generations",e.generationId)}function Ii(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 ic(e,t){let n=`${e}.reclaim`,r=Jt(),i;try{i=fi(n,"wx")}catch{return!1}try{mi(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
238
- `)}finally{pi(i)}try{let o=Ii(e);return!o||o.raw!==t.raw||o.pid!==void 0&&T(o.pid)?!1:(Wt(e),!0)}catch{return!1}finally{try{let o=JSON.parse(F(n,"utf8"));o.pid===process.pid&&o.token===r&&Wt(n)}catch{}}}function oc(e,t,n){let r=Gn(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!U(f(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=f(e,"worktrees");C(i,{recursive:!0}),b(f(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),nc(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function ac(e,t){let n=f(t,".rollback"),r=new Map,i=new Map;C(n,{recursive:!0});for(let s of["index.scip","index.db","meta.json"]){let c=f(e,s),u=U(c);r.set(s,u),u&&ge(c,f(n,"stable",s))}for(let s of qt){let c=f(e,s),u=U(c);if(u){let d=qs(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,Ge),a=U(o);return a&&vi(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);C(hi(a),{recursive:!0}),z(i,a)}let o=f(e,r);U(o)&&z(o,i)}}function cc(e,t){for(let i of qt){let o=f(e,i),a=f(t.root,"managed",i);t.managedDirectories.get(i)?U(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-${Jt()}`;ge(f(t.root,"stable",i),s),V(a,{force:!0}),z(s,a)}let n=f(e,Ge);V(n,{recursive:!0,force:!0});let r=f(t.root,"sqlite-generations");t.generationStoreExisted&&U(r)&&z(r,n)}function vi(e,t){C(t,{recursive:!0});for(let n of zs(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()?vi(r,i):n.isFile()&&ge(r,i)}}function uc(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 Pi(e,t,n,r=!0,i=!0){try{let o=rc(e);if(o?.status!=="complete"||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return le("source validation rejected metadata"),!1;let a=Le(e),s=G(f(e,"index.db"),f(e,"meta.json"));if(r?s.state!=="current":s.state==="invalid"||s.state==="drifted")return le(`source validation rejected SQLite generation state ${s.state}`),!1;let c=new Ks(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=Qt(t),p=(i?a.files.filter(l=>l.endsWith(".scip")):["index.scip"]).every(l=>{let m=yi(F(j(e,l))).metadata?.projectRoot;return m!==u&&le(`source validation rejected SCIP root for ${l}: ${String(m)}`),m===u});return p||le("source validation rejected SCIP project roots"),p}catch(o){return le(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function le(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function Qt(e){try{return ci(Ys(e)).href}catch{return ci(pe(e)).href}}function fe(e){return li("sha256").update(e).digest("hex")}import{existsSync as dc,readFileSync as lc,readdirSync as pc,statSync as gc}from"fs";import x from"path";var fc=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function me(e,t=[]){let n=x.resolve(e),r=t.flatMap(c=>hc(n,c));if(r.length>0)return wi(n,ki(r));let i=mc(n),o=ki(i),a=Sc(n,o)?[n,...o]:o,s=a.length>0?a:[n];return wi(n,s)}function wi(e,t){return[...new Set(t.map(n=>Rc(e,n)))].sort((n,r)=>n.localeCompare(r))}function mc(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=pc(r,{withFileTypes:!0})}catch{continue}for(let o of i){let a=x.join(r,o.name);if(o.isDirectory()){!fc.has(o.name)&&!o.name.startsWith(".")&&n.push(a);continue}o.isFile()&&yc(a)&&t.push(x.dirname(a))}}return t}function hc(e,t){let n=t.trim();if(!n)return[];let r=x.resolve(e,n);if(!K(e,r))return[];try{let i=gc(r);if(i.isDirectory())return[r];if(i.isFile()&&Ei(x.basename(r)))return[x.dirname(r)]}catch{return[]}return[]}function yc(e){if(!Ei(x.basename(e)))return!1;let t=Ti(e);return t?x.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function Ei(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function ki(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&&xc(n,r)))}function Sc(e,t){if(t.length===0||t.some(r=>x.resolve(r)===e))return!1;let n=x.join(e,"tsconfig.json");return dc(n)&&bc(n)}function bc(e){let n=Ti(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 Ti(e){try{let t=JSON.parse(lc(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Rc(e,t){let n=x.relative(e,t);return n?n.split(x.sep).join("/"):"."}function xc(e,t){let n=x.relative(e,t);return!!n&&!n.startsWith("..")&&!x.isAbsolute(n)}import{createHash as Uc}from"crypto";import{existsSync as Zt,readFileSync as Gi,statSync as Wc,writeFileSync as en}from"fs";import{join as Bc}from"path";import{readFileSync as Di}from"fs";import{createRequire as Ic}from"module";import{dirname as vc,isAbsolute as Wp,relative as Bp,resolve as Jp,sep as Hp}from"path";var Fi=Ic(import.meta.url),Pc=1,Oi="0.4.0";function Xt(){let e=wc();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function wc(){try{let e=Fi.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(Di(e,"utf8"));if(t.version!==Oi)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${Oi}`};let n=vc(e),r=Fi.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(Di(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:kc(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function kc(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${Pc}`}import{createHash as Ec}from"crypto";import{readFileSync as Tc}from"fs";import{dirname as Dc,join as He}from"path";var qe=2,Fc="typescript-index";function ji(e){let t=He(e,Fc);return{rootDir:t,requestDir:He(t,"requests"),responseDir:He(t,"responses")}}function _i(e){try{let t=JSON.parse(Tc(He(Dc(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:Ec("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 Oc}from"crypto";import{existsSync as jc,mkdirSync as Ci,readFileSync as _c,rmSync as Ai}from"fs";import{resolve as Kt}from"path";var Cc=12e4,Ac=5,ze=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=Kt(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Gc(),this.runtime=n.runtime??Vc}request(t){let n=wn(this.cacheDir),r=ji(this.cacheDir),i=ut(n.statePath);if(!Li(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),a=Kt(r.requestDir,`${o}.json`),s=Kt(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;Ci(r.requestDir,{recursive:!0}),Ci(r.responseDir,{recursive:!0}),b(a,{protocolVersion:qe,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(jc(s))return Lc(_c(s,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let u=ut(n.statePath);if(!Li(u,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(Ac)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{Ai(a,{force:!0}),Ai(s,{force:!0})}}};function Li(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=Pn,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 Lc(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=Mc(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 Mc(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(Nc)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:$c(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 Nc(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 $c(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Gc(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Cc}var Vc={now:Date.now,randomId:Oc,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:T};function Jc(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=we(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"||!dt(u.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=ke(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=Hc([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=Mi(e.currentSnapshot,e.projectFiles,e.producerIdentity),a=Mi(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==a)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let s=$i(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!s)return{eligible:!1,reason:"prior document identity unavailable"};let c=$i(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:Ni(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:Ni(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 Hc(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 Vi(e){let t=Date.now();try{if(!Zt(e.previousDbPath)||!Zt(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=Xt();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new B({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a,s;try{a=xe(o,{includeIgnored:!1}).filter(dt).sort(),s=Ie(o)}finally{o.close()}let c=performance.now()-n,u=Jc({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?me(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:a,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:Zt(Bc(e.projectRoot,"tsconfig.json"))});if(!u.eligible)throw new Error(u.reason);let d=_i(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let l=new ze({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=Wc(e.previousShardPath).size>=Hr;n=performance.now();let v=g?null:Gi(e.previousShardPath),S=g?{completeIndexBytes:null,affectedIndexBytes:Fr(l.fragments)}:Ar({packageVersion:r.packageVersion,baseIndexBytes:v,fragments:l.fragments}),R=performance.now()-n;n=performance.now(),g?qr({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,nextGenerationIdentity:u.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:l.fragments}):(Or({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:v,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.previousFragmentGeneration,documentIdentities:u.previousDocumentIdentities,allowUntrackedDocuments:!0}),jr({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&&en(e.candidateShardPath,S.completeIndexBytes),en(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(Re=>[Re.relativePath,Re.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 Ui(e){let t=Xt();if(!t.available)throw new Error(t.reason);let n=zr({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:Gi(e.baseShardPath),packageVersion:t.packageVersion});en(e.candidateShardPath,n)}function Mi(e,t,n){let r=e.files.filter(i=>xn(i.path,e.languages)!=="source").map(i=>({path:i.path,size:i.size,hash:i.hash})).sort((i,o)=>i.path.localeCompare(o.path));return tn(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function Ni(e,t){return tn(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function $i(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),a=Tn({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,tn(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function tn(e){return Uc("sha256").update(e).digest("hex")}import{execFile as qc}from"child_process";import{existsSync as Ye,renameSync as rn,rmSync as on,statSync as zc}from"fs";import{cpus as Yc}from"os";import{join as Wi}from"path";function Qc(e,t,n){if(!e.defaultOutputPath)return;let r=Wi(t,e.defaultOutputPath);n!==r&&Ye(r)&&rn(r,n)}function Xc(e,t,n){if(!e.defaultOutputPath)return null;let r=Wi(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return on(i,{force:!0}),Ye(r)?(rn(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Kc(e){e&&(on(e.defaultOutputPath,{force:!0}),e.backupPath&&Ye(e.backupPath)&&rn(e.backupPath,e.defaultOutputPath))}function Zc(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,Yc().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Bi(e,t,n,r){let i=e.filter(u=>u.config.defaultOutputPath),o=e.filter(u=>!u.config.defaultOutputPath),a=[],s=Zc(o.length,r),c=await tu(o,s,u=>nn(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 nn(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 nn(u,t,n));return a.sort((u,d)=>e.findIndex(p=>p.id===u.id)-e.findIndex(p=>p.id===d.id))}async function nn(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),on(e.scipPath,{force:!0});let r=Xc(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{await eu(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),Qc(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{Kc(r)}if(!Ye(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=zc(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 eu(e,t,n){return new Promise((r,i)=>{qc(e,[...t],n,o=>{o?i(o):r()})})}async function tu(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 Lu from"better-sqlite3";import{existsSync as Mu}from"fs";import{dirname as Nu,join as $u,resolve as Gu}from"path";import{readFileSync as ru,rmSync as iu,statSync as ou,mkdtempSync as au}from"fs";import{tmpdir as su}from"os";import{join as an}from"path";import{Worker as cu}from"worker_threads";function nu(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function X(){return{skippedReferences:0,skippedReferenceReasons:nu(),skippedReferenceSamples:[]}}function Qe(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 Ji(e){return e.length>=8&&qi(e.length)>1}function Hi(e){let t=qi(e.vueFiles.length),n=du(e.vueFiles),r=pu(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=au(an(su(),"scip-query-vue-workers-")),a=new SharedArrayBuffer(4),s=new Int32Array(a),c=uu(),u=Date.now();try{for(let l=0;l<r.length;l++)new cu(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[l],resultPath:an(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(ru(an(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),...X()};for(let l of d)Qe(p,l);return p}finally{iu(o,{recursive:!0,force:!0})}}function qi(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 uu(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function du(e){let t=lu(),n=[];for(let r of e){let i=zi(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 lu(){return Number.POSITIVE_INFINITY}function pu(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:gu(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 gu(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,zi(e.fileName)-e.startOffset)}function zi(e){try{return ou(e).size}catch{return 1}}import{createRequire as fu}from"module";import{existsSync as mu,readFileSync as cn}from"fs";import{dirname as Yi,extname as hu,join as Qi,relative as yu,resolve as Su}from"path";import{pathToFileURL as bu}from"url";function Ru(e){e.transaction(()=>{e.prepare(`
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=Aa("sha256");for(let m of p.sort())l.update(m).update(`
234
+ `);u.set(d,l.digest("hex"))}return u}function M(e,t){return e.prepare(t).get().value}import{readFileSync as Ka,writeFileSync as Za}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 mr(e){let t=e.readFingerprint(),n=es(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return ts(e.cachePath,e.readFingerprint(),r),r}function es(e,t){try{let n=JSON.parse(Ka(e,"utf-8"));return fr(n.fingerprint)===fr(t)?{result:n.result}:null}catch{return null}}function ts(e,t,n){Za(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
235
+ `)}function fr(e){return JSON.stringify(e)}import{createHash as ns}from"crypto";import{existsSync as kt,readFileSync as rs,readdirSync as is}from"fs";import{dirname as Et,join as Fe,relative as os,resolve as Tt,sep as hr}from"path";function yr(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=xr(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function Sr(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=xr(s,e);c&&c!==i&&a.add(c)}}return as(e,r)}function br(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 Dt(e){if(e===".")return"root";let t=ns("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Rr(e,t){let n=Tt(e),r={};for(let i of t)r[i]=ss(n,i);return r}function xr(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 as(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 ss(e,t){let n=t==="."?e:Fe(e,t),r=cs(n),i=us(n),o=i?ds(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 cs(e){let t=Fe(e,"package.json");if(!kt(t))return{name:void 0,dependencyNames:[],failed:!1};let n=Ft(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 us(e){let t=Fe(e,"tsconfig.json");if(kt(t))return t;let n;try{n=is(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?Fe(e,n[0]):void 0}function ds(e,t){let n=Ft(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=ls(n.value,e,t),i=Ir(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function ls(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=Et(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=vr(s,i,n);c&&o.add(c)}return[...o]}function Ir(e,t,n,r){let i=ps(t);if(i)return{pathsTargets:gs(i,Et(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=fs(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=Ft(o);return a.ok?Ir(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function ps(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 gs(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=vr(o,t,n);a&&r.add(a)}return[...r]}function fs(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=Tt(Et(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(hr).includes("node_modules")&&K(n,i)&&kt(i))return i}function vr(e,t,n){let r=e.replace(/\/?\*+$/,""),i=Tt(t,r===""?".":r);if(!K(n,i))return;let a=os(n,i).split(hr).join("/");return a===""?".":a}function ms(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 Ft(e){try{let t=rs(e,"utf-8"),n=JSON.parse(ms(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as li,randomUUID as Jt}from"crypto";import{closeSync as pi,constants as qs,copyFileSync as si,existsSync as U,lstatSync as zs,mkdirSync as C,mkdtempSync as gi,openSync as fi,readdirSync as Ys,readFileSync as F,realpathSync as Qs,renameSync as z,rmSync as V,statSync as Xs,unlinkSync as Wt,writeFileSync as mi}from"fs";import{dirname as hi,join as f,resolve as pe}from"path";import{setTimeout as Ks}from"timers/promises";import{pathToFileURL as ci}from"url";import{deserializeSCIP as yi}from"@c4312/scip";import Zs from"better-sqlite3";import{createRequire as hs}from"module";var ys=hs(import.meta.url),Pr=Ss().version;function Ss(){for(let e of["../package.json","../../package.json"])try{return ys(e)}catch{}return{version:"0.0.0"}}import{lstatSync as _s,readdirSync as Cs}from"fs";import{join as As,relative as Ls,resolve as $t,sep as Ms}from"path";import{createHash as bs}from"crypto";import{existsSync as jt,mkdirSync as Rs,readFileSync as Oe,readdirSync as Ql,renameSync as xs,rmSync as Xl,writeFileSync as Is}from"fs";import{join as Y}from"path";import{create as kr,fromBinary as Er,toBinary as vs}from"@bufbuild/protobuf";import{deserializeSCIP as je,DocumentSchema as _t,IndexSchema as Tr,serializeSCIP as Dr}from"@c4312/scip";var _e=1,re="typescript-scip-fragments";function Fr(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=H(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=Er(_t,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=Dr(kr(Tr,{documents:n,externalSymbols:[]})),i=je(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function Ce(e){let t=Y(e,re);return{rootDir:t,blobDir:Y(t,"blobs"),generationDir:Y(t,"generations")}}function Ps(e){let t=je(e.indexBytes);Ur(t.metadata,Wr(e)),Vr(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let a=H(o.relativePath);if(n.has(a))throw new Error(`duplicate TypeScript SCIP document path: ${a}`);n.add(a);let s=vs(_t,o),c=e.documentIdentities.get(a)??(e.allowUntrackedDocuments?q(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:a,contentHash:q(s)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${a}`);r.push(Mr(e.cacheDir,{relativePath:a,bytes:s,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=Nr(e,r);return $r(e.cacheDir,i),i}function Or(e){let t=Ce(e.cacheDir);if(!jt(Ct(t,e.generationIdentity)))return Ps(e);let n=_r({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 jr(e){let t=_r({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=H(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,Mr(e.cacheDir,o,s))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=Nr(e,[...n.values()]);return $r(e.cacheDir,i),i}function _r(e){let t=Ce(e.cacheDir),n=Ct(t,e.generationIdentity),r;try{r=Gr(Oe(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=Y(t.blobDir,`${o.blobHash}.scipdoc`),s=Oe(a);if(s.byteLength!==o.byteLength||q(s)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,s)}return{manifest:r,fragments:i}}function Cr(e){let t=Lr(e);return Ot(t.baseIndex,t.completeDocuments,"assembled")}function Ar(e){let t=Lr(e);return ws(t.deletedAffectedPaths),{completeIndexBytes:Ot(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:Ot(t.baseIndex,t.affectedDocuments,"affected")}}function Lr(e){let t=je(e.baseIndexBytes);Ur(t.metadata,Wr(e)),Vr(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=H(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=H(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=Er(_t,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 Ot(e,t,n){let r=Dr(kr(Tr,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=je(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function ws(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function Mr(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=H(t.relativePath),i=Buffer.from(t.bytes),o=q(i),a=Ce(e);Rs(a.blobDir,{recursive:!0});let s=Y(a.blobDir,`${o}.scipdoc`);if(jt(s)){let c=Oe(s);if(c.byteLength!==i.byteLength||q(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${s}.${process.pid}.${Date.now()}.tmp`;Is(c,i),xs(c,s)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function Nr(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:_e,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function $r(e,t){let n=Ce(e),r=Ct(n,t.generationIdentity);if(jt(r)){let i=Gr(Oe(r,"utf8"));if(wr(i)!==wr(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}b(r,t,{spacing:2,trailingNewline:!0})}function wr(e){return q(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function Gr(e){let t=JSON.parse(e);if(t.version!==_e||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(H(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function Ct(e,t){return Y(e.generationDir,ks(t))}function ks(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${q(e)}.json`}function Vr(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function Ur(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 Wr(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function H(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 q(e){return bs("sha256").update(e).digest("hex")}import{createHash as Es}from"crypto";import{existsSync as ie,mkdirSync as Ts,readFileSync as ae,readdirSync as At,renameSync as Ds,rmSync as Br,writeFileSync as Fs}from"fs";import{join as D}from"path";var Ae=1,Hr=64*1024*1024,se="typescript-scip-overlays";function qr(e){let t=Qr(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=Nt(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript overlay: ${a}`);r.add(a),n.set(a,Os(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:Ae,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 js(e.cacheDir,i),i}function zr(e){let t=Qr(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=ae(D(ce(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||oe(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 Cr({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function Yr(e,t){let n=ce(e),r=D(n,"generations");if(!ie(r))return;let i=new Set(t.map(Mt)),o=new Set;for(let s of At(r).filter(c=>i.has(c))){let c=Lt(ae(D(r,s),"utf8"));for(let u of c.overlays)u.blobHash&&o.add(`${u.blobHash}.scipdoc`)}for(let s of At(r))i.has(s)||Br(D(r,s),{force:!0});let a=D(n,"blobs");if(ie(a))for(let s of At(a))o.has(s)||Br(D(a,s),{force:!0})}function Qr(e,t){let n=D(ce(e),"generations",Mt(t));if(!ie(n))return null;let r=Lt(ae(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function Os(e,t){let n=Nt(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=oe(r),o=D(ce(e),"blobs");Ts(o,{recursive:!0});let a=D(o,`${i}.scipdoc`);if(ie(a)){let s=ae(a);if(s.byteLength!==r.byteLength||oe(s)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let s=`${a}.${process.pid}.${Date.now()}.tmp`;Fs(s,r),Ds(s,a)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function js(e,t){let n=D(ce(e),"generations",Mt(t.generationIdentity));if(ie(n)){let r=Lt(ae(n,"utf8"));if(Jr(r)!==Jr(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}b(n,t,{spacing:2,trailingNewline:!0})}function Lt(e){let t=JSON.parse(e);if(t.version!==Ae||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(Nt(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function ce(e){return D(e,se)}function Mt(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${oe(e)}.json`}function Jr(e){return oe(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function Nt(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 oe(e){return Es("sha256").update(e).digest("hex")}var ue=1,Gt="language-indexes",Xr=["index.db","index.scip","meta.json"],Kr=[Gt,re,se];function Le(e){let t=[];for(let n of Xr)Ns(e,n),t.push(n);for(let n of Kr)Zr(e,n,t);return{version:ue,files:t.sort()}}function Me(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(!Xr.includes(e)&&!Kr.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function j(e,t){let n=Me(t),r=$t(e),i=$t(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${Ms}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function Zr(e,t,n){let r=As(e,t),i;try{i=Cs(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()?Zr(e,a,n):o.isFile()&&n.push(Me(a))}}function Ns(e,t){let n=j(e,t),r;try{r=_s(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(Ls($t(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{createHash as $s}from"crypto";import{copyFileSync as ei,existsSync as $,linkSync as Gs,mkdirSync as ti,readFileSync as ii,readdirSync as ni,renameSync as Ut,rmSync as $e,statSync as Vs}from"fs";import{basename as Ne,dirname as de,join as P,relative as ri}from"path";var Q=1,Ge=".scipquery-generations";function Ve(e){let t=Ue(e.outputDb),n=Us(e,t);e.onStage?.("after-recovery-retained"),e.preserveOutputScip||Vt(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),Vt(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),Vt(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let r=We(e.metaPath,e.outputDb),i={version:Q,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 oi(e){try{let t=JSON.parse(ii(P(Ue(e),"state.json"),"utf8"));return t.version!==Q||typeof t.currentGeneration!="string"||!t.currentGeneration||typeof t.publishedAt!="string"||!Number.isFinite(Date.parse(t.publishedAt))||!Js(t.previousGeneration)||!Hs(t.publication)?null:t}catch{return null}}function ai(e,t,n=()=>new Date){if(!$(e)||!$(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=oi(e),i={version:Q,currentGeneration:We(t,e),...r?.previousGeneration?{previousGeneration:r.previousGeneration}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return b(P(Ue(e),"state.json"),i,{spacing:2,trailingNewline:!0}),i}function G(e,t=P(de(e),"meta.json")){let n=P(Ue(e),"state.json");if(!$(n))return{state:"legacy",statePath:n};let r=oi(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=We(t,e),o=r.currentGeneration===i,a=r.previousGeneration?$(P(de(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 Ue(e){return P(de(e),Ge)}function Us(e,t){if(!$(e.outputDb))return;let n=We(e.metaPath,e.outputDb),r=P(t,n),i=P(r,Ne(e.outputDb)),o=$(e.metaPath)?P(r,Ne(e.metaPath)):void 0;if(!$(i)){let a=`${r}.${process.pid}.${Date.now()}.tmp`;$e(a,{recursive:!0,force:!0}),ti(a,{recursive:!0});let s=P(a,Ne(e.outputDb));try{Gs(e.outputDb,s)}catch{ei(e.outputDb,s)}o&&ei(e.metaPath,P(a,Ne(e.metaPath))),ti(t,{recursive:!0}),Ut(a,r)}return Ws(t,n),{generationIdentity:n,databasePath:ri(de(e.outputDb),i),...o?{metadataPath:ri(de(e.outputDb),o)}:{}}}function Ws(e,t){for(let n of ni(e,{withFileTypes:!0}))!n.isDirectory()||n.name===t||n.name.endsWith(".tmp")||$e(P(e,n.name),{recursive:!0,force:!0});for(let n of ni(e,{withFileTypes:!0}))n.isDirectory()&&n.name.endsWith(".tmp")&&$e(P(e,n.name),{recursive:!0,force:!0})}function We(e,t){let n=$s("sha256").update(`sqlite-generation-v${Q}\0`);$(e)&&n.update(Bs(ii(e,"utf8")));let r=Vs(t);return n.update(`\0${r.size}`),n.digest("hex")}function Bs(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 Vt(e,t){$e(`${t}.tmp-replace`,{force:!0}),Ut(e,`${t}.tmp-replace`),Ut(`${t}.tmp-replace`,t)}function Js(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 Hs(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 Ht=1,ui="SCIP_QUERY_SHARED_CACHE",Bt=JSON.stringify({cliVersion:Pr,artifactCatalogVersion:ue,sqliteGenerationStoreVersion:Q,typescriptFragmentStoreVersion:_e,typescriptOverlayStoreVersion:Ae}),Si="manifest.json",ec="shared-cache.json",qt=[Gt,re,se];function Be(e,t){if(!e.clean||!e.treeOid)return;let n=fe(JSON.stringify({version:Ht,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:Bt}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:Bt,generationId:n,repositoryCacheDir:jn(e.repositoryId)}}function bi(e,t,n){if(process.env[ui]==="0")return`${ui}=0`;if(!_n(n))return"explicit cache or database override";if(pe(t)!==pe(f(On(e),"index.db")))return"index database is outside the managed worktree cache"}function _(e,t=!0){let n=Yt(e),r;try{r=nc(F(f(n,Si),"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=Xs(o);if(!a.isFile()||a.size!==i.size||fe(F(o))!==i.sha256)return null}}catch{return null}return r}function Ri(e){let t=_(e.snapshot);if(t)return t;if(!Pi(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=di(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=Le(e.sourceCacheDir),i=f(e.snapshot.repositoryCacheDir,"generations");C(i,{recursive:!0});let o=gi(f(i,`.tmp-${process.pid}-`));try{let a=[];for(let p of r.files){let l=j(e.sourceCacheDir,p),m=j(o,p);ge(l,m);let g=F(m);a.push({path:p,size:g.byteLength,sha256:fe(g)})}let s=yi(F(f(o,"index.scip"))).metadata?.projectRoot;if(!s)throw new Error("shared SCIP generation has no project root metadata");let c=Qt(e.sourceProjectRoot);if(s!==c)throw new Error("shared SCIP generation root does not match its source worktree");if(di(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let u={version:Ht,artifactCatalogVersion:ue,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,Si),u,{spacing:2,trailingNewline:!0});let d=Yt(e.snapshot);try{if(U(d)&&!_(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=_(e.snapshot);if(l)return l;throw p}return u}finally{V(o,{recursive:!0,force:!0})}}function zt(e){let t=Yt(e.snapshot);C(e.targetCacheDir,{recursive:!0});let n=te(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=gi(f(e.targetCacheDir,".shared-hydrate-")),dc(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let u=j(t,c.path),d=j(r,c.path);ge(u,d);let p=F(d);if(p.byteLength!==c.size||fe(p)!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let a=Qt(e.targetProjectRoot);if(a!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&or(j(r,c.path),e.manifest.scipProjectRoot,a);if(!Pi(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=sc(e.targetCacheDir,r),o=!0,cc(r,e.targetCacheDir,i),Ve({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}`);Je(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(a){throw o&&i&&uc(e.targetCacheDir,i),a}finally{r&&V(r,{recursive:!0,force:!0}),n.release()}}async function xi(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(C(a,{recursive:!0});i()<=o;){if(_(e))return{kind:"generation-ready"};let c=Jt();try{let u=fi(s,"wx");try{mi(u,`${JSON.stringify({version:1,pid:process.pid,token:c,generationId:e.generationId,startedAt:new Date(i()).toISOString()})}
237
+ `)}finally{pi(u)}return{kind:"owner",release:()=>{try{let d=JSON.parse(F(s,"utf8"));d.pid===process.pid&&d.token===c&&Wt(s)}catch{}}}}catch(u){if(u.code!=="EEXIST")return{kind:"timeout"};let d=Ii(s);if(d&&(d.pid===void 0||!T(d.pid))){oc(s,d);continue}await Ks(r)}}return _(e)?{kind:"generation-ready"}:{kind:"timeout"}}function Je(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:tc(i)};return ac(e.repositoryCacheDir,o,!0),o}function tc(e){return fe(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:pe(e.projectRoot),localCacheDir:pe(e.localCacheDir)}))}function nc(e){let t=JSON.parse(e);if(t.version!==Ht||t.artifactCatalogVersion!==ue||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!==Bt||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(Me(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 ge(e,t){C(hi(t),{recursive:!0});try{si(e,t,qs.COPYFILE_FICLONE)}catch{si(e,t)}}function rc(e,t,n){C(e,{recursive:!0}),b(f(e,ec),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function di(e){try{let t=Le(e),n=li("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 ic(e){try{return JSON.parse(F(f(e,"meta.json"),"utf8"))}catch{return}}function Yt(e){return f(e.repositoryCacheDir,"generations",e.generationId)}function Ii(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 oc(e,t){let n=`${e}.reclaim`,r=Jt(),i;try{i=fi(n,"wx")}catch{return!1}try{mi(i,`${JSON.stringify({version:1,pid:process.pid,token:r,startedAt:new Date().toISOString()})}
238
+ `)}finally{pi(i)}try{let o=Ii(e);return!o||o.raw!==t.raw||o.pid!==void 0&&T(o.pid)?!1:(Wt(e),!0)}catch{return!1}finally{try{let o=JSON.parse(F(n,"utf8"));o.pid===process.pid&&o.token===r&&Wt(n)}catch{}}}function ac(e,t,n){let r=Gn(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!U(f(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=f(e,"worktrees");C(i,{recursive:!0}),b(f(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),rc(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function sc(e,t){let n=f(t,".rollback"),r=new Map,i=new Map;C(n,{recursive:!0});for(let s of["index.scip","index.db","meta.json"]){let c=f(e,s),u=U(c);r.set(s,u),u&&ge(c,f(n,"stable",s))}for(let s of qt){let c=f(e,s),u=U(c);if(u){let d=zs(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,Ge),a=U(o);return a&&vi(o,f(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:a}}function cc(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);C(hi(a),{recursive:!0}),z(i,a)}let o=f(e,r);U(o)&&z(o,i)}}function uc(e,t){for(let i of qt){let o=f(e,i),a=f(t.root,"managed",i);t.managedDirectories.get(i)?U(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-${Jt()}`;ge(f(t.root,"stable",i),s),V(a,{force:!0}),z(s,a)}let n=f(e,Ge);V(n,{recursive:!0,force:!0});let r=f(t.root,"sqlite-generations");t.generationStoreExisted&&U(r)&&z(r,n)}function vi(e,t){C(t,{recursive:!0});for(let n of Ys(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()?vi(r,i):n.isFile()&&ge(r,i)}}function dc(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 Pi(e,t,n,r=!0,i=!0){try{let o=ic(e);if(o?.status!=="complete"||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return le("source validation rejected metadata"),!1;let a=Le(e),s=G(f(e,"index.db"),f(e,"meta.json"));if(r?s.state!=="current":s.state==="invalid"||s.state==="drifted")return le(`source validation rejected SQLite generation state ${s.state}`),!1;let c=new Zs(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=Qt(t),p=(i?a.files.filter(l=>l.endsWith(".scip")):["index.scip"]).every(l=>{let m=yi(F(j(e,l))).metadata?.projectRoot;return m!==u&&le(`source validation rejected SCIP root for ${l}: ${String(m)}`),m===u});return p||le("source validation rejected SCIP project roots"),p}catch(o){return le(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function le(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function Qt(e){try{return ci(Qs(e)).href}catch{return ci(pe(e)).href}}function fe(e){return li("sha256").update(e).digest("hex")}import{existsSync as lc,readFileSync as pc,readdirSync as gc,statSync as fc}from"fs";import x from"path";var mc=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function me(e,t=[]){let n=x.resolve(e),r=t.flatMap(c=>yc(n,c));if(r.length>0)return wi(n,ki(r));let i=hc(n),o=ki(i),a=bc(n,o)?[n,...o]:o,s=a.length>0?a:[n];return wi(n,s)}function wi(e,t){return[...new Set(t.map(n=>xc(e,n)))].sort((n,r)=>n.localeCompare(r))}function hc(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=gc(r,{withFileTypes:!0})}catch{continue}for(let o of i){let a=x.join(r,o.name);if(o.isDirectory()){!mc.has(o.name)&&!o.name.startsWith(".")&&n.push(a);continue}o.isFile()&&Sc(a)&&t.push(x.dirname(a))}}return t}function yc(e,t){let n=t.trim();if(!n)return[];let r=x.resolve(e,n);if(!K(e,r))return[];try{let i=fc(r);if(i.isDirectory())return[r];if(i.isFile()&&Ei(x.basename(r)))return[x.dirname(r)]}catch{return[]}return[]}function Sc(e){if(!Ei(x.basename(e)))return!1;let t=Ti(e);return t?x.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function Ei(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function ki(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&&Ic(n,r)))}function bc(e,t){if(t.length===0||t.some(r=>x.resolve(r)===e))return!1;let n=x.join(e,"tsconfig.json");return lc(n)&&Rc(n)}function Rc(e){let n=Ti(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 Ti(e){try{let t=JSON.parse(pc(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function xc(e,t){let n=x.relative(e,t);return n?n.split(x.sep).join("/"):"."}function Ic(e,t){let n=x.relative(e,t);return!!n&&!n.startsWith("..")&&!x.isAbsolute(n)}import{createHash as Wc}from"crypto";import{existsSync as Kt,readFileSync as Vi,statSync as Bc,writeFileSync as Zt}from"fs";import{join as Jc}from"path";import{readFileSync as Di}from"fs";import{createRequire as vc}from"module";import{dirname as Pc,isAbsolute as Bp,relative as Jp,resolve as Hp,sep as qp}from"path";var Fi=vc(import.meta.url),wc=1,Oi="0.4.0";function Xt(){let e=kc();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function kc(){try{let e=Fi.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(Di(e,"utf8"));if(t.version!==Oi)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${Oi}`};let n=Pc(e),r=Fi.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(Di(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:Ec(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function Ec(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${wc}`}import{createHash as Tc}from"crypto";import{readFileSync as Dc}from"fs";import{dirname as Fc,join as He}from"path";var qe=2,Oc="typescript-index";function ji(e){let t=He(e,Oc);return{rootDir:t,requestDir:He(t,"requests"),responseDir:He(t,"responses")}}function _i(e){try{let t=JSON.parse(Dc(He(Fc(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:Tc("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 jc}from"crypto";import{existsSync as _c,mkdirSync as Ci,readFileSync as Cc,rmSync as Ai}from"fs";import{resolve as Li}from"path";var Ac=12e4,Lc=5,ze=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=vn(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Vc(),this.runtime=n.runtime??Uc}request(t){let n=wn(this.cacheDir),r=ji(this.cacheDir),i=ut(n.statePath);if(!Mi(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),a=Li(r.requestDir,`${o}.json`),s=Li(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;Ci(r.requestDir,{recursive:!0}),Ci(r.responseDir,{recursive:!0}),b(a,{protocolVersion:qe,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(_c(s))return Mc(Cc(s,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let u=ut(n.statePath);if(!Mi(u,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(Lc)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{Ai(a,{force:!0}),Ai(s,{force:!0})}}};function Mi(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=Pn,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 Mc(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=Nc(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 Nc(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($c)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:Gc(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 $c(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 Gc(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Vc(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Ac}var Uc={now:Date.now,randomId:jc,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:T};function Hc(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"||!dt(u.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=Ee(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=qc([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=Ni(e.currentSnapshot,e.projectFiles,e.producerIdentity),a=Ni(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==a)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let s=Gi(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!s)return{eligible:!1,reason:"prior document identity unavailable"};let c=Gi(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:$i(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:$i(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 qc(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 Ui(e){let t=Date.now();try{if(!Kt(e.previousDbPath)||!Kt(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=Xt();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new B({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a,s;try{a=xe(o,{includeIgnored:!1}).filter(dt).sort(),s=Ie(o)}finally{o.close()}let c=performance.now()-n,u=Hc({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?me(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:a,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:Kt(Jc(e.projectRoot,"tsconfig.json"))});if(!u.eligible)throw new Error(u.reason);let d=_i(e.previousDbPath);if(!d)throw new Error("published TypeScript base generation unavailable");n=performance.now();let l=new ze({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=Bc(e.previousShardPath).size>=Hr;n=performance.now();let v=g?null:Vi(e.previousShardPath),S=g?{completeIndexBytes:null,affectedIndexBytes:Fr(l.fragments)}:Ar({packageVersion:r.packageVersion,baseIndexBytes:v,fragments:l.fragments}),R=performance.now()-n;n=performance.now(),g?qr({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,nextGenerationIdentity:u.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:l.fragments}):(Or({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:v,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.previousFragmentGeneration,documentIdentities:u.previousDocumentIdentities,allowUntrackedDocuments:!0}),jr({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&&Zt(e.candidateShardPath,S.completeIndexBytes),Zt(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(Re=>[Re.relativePath,Re.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 Wi(e){let t=Xt();if(!t.available)throw new Error(t.reason);let n=zr({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:Vi(e.baseShardPath),packageVersion:t.packageVersion});Zt(e.candidateShardPath,n)}function Ni(e,t,n){let r=e.files.filter(i=>Rn(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 en(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function $i(e,t){return en(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function Gi(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),a=Tn({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,en(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function en(e){return Wc("sha256").update(e).digest("hex")}import{execFile as zc}from"child_process";import{existsSync as Ye,renameSync as nn,rmSync as rn,statSync as Yc}from"fs";import{cpus as Qc}from"os";import{join as Bi}from"path";function Xc(e,t,n){if(!e.defaultOutputPath)return;let r=Bi(t,e.defaultOutputPath);n!==r&&Ye(r)&&nn(r,n)}function Kc(e,t,n){if(!e.defaultOutputPath)return null;let r=Bi(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return rn(i,{force:!0}),Ye(r)?(nn(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function Zc(e){e&&(rn(e.defaultOutputPath,{force:!0}),e.backupPath&&Ye(e.backupPath)&&nn(e.backupPath,e.defaultOutputPath))}function eu(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,Qc().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function Ji(e,t,n,r){let i=e.filter(u=>u.config.defaultOutputPath),o=e.filter(u=>!u.config.defaultOutputPath),a=[],s=eu(o.length,r),c=await nu(o,s,u=>tn(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 tn(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 tn(u,t,n));return a.sort((u,d)=>e.findIndex(p=>p.id===u.id)-e.findIndex(p=>p.id===d.id))}async function tn(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),rn(e.scipPath,{force:!0});let r=Kc(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{await tu(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),Xc(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{Zc(r)}if(!Ye(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=Yc(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 tu(e,t,n){return new Promise((r,i)=>{zc(e,[...t],n,o=>{o?i(o):r()})})}async function nu(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 Mu from"better-sqlite3";import{existsSync as Nu}from"fs";import{dirname as $u,join as Gu,resolve as Vu}from"path";import{readFileSync as iu,rmSync as ou,statSync as au,mkdtempSync as su}from"fs";import{tmpdir as cu}from"os";import{join as on}from"path";import{Worker as uu}from"worker_threads";function ru(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function X(){return{skippedReferences:0,skippedReferenceReasons:ru(),skippedReferenceSamples:[]}}function Qe(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 Hi(e){return e.length>=8&&zi(e.length)>1}function qi(e){let t=zi(e.vueFiles.length),n=lu(e.vueFiles),r=gu(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=su(on(cu(),"scip-query-vue-workers-")),a=new SharedArrayBuffer(4),s=new Int32Array(a),c=du(),u=Date.now();try{for(let l=0;l<r.length;l++)new uu(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[l],resultPath:on(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(iu(on(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),...X()};for(let l of d)Qe(p,l);return p}finally{ou(o,{recursive:!0,force:!0})}}function zi(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 du(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function lu(e){let t=pu(),n=[];for(let r of e){let i=Yi(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 gu(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:fu(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 fu(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Yi(e.fileName)-e.startOffset)}function Yi(e){try{return au(e).size}catch{return 1}}import{createRequire as mu}from"module";import{existsSync as hu,readFileSync as sn}from"fs";import{dirname as Qi,extname as yu,join as Xi,relative as Su,resolve as bu}from"path";import{pathToFileURL as Ru}from"url";function xu(e){e.transaction(()=>{e.prepare(`
240
240
  DELETE FROM mentions
241
241
  WHERE chunk_id IN (
242
242
  SELECT c.id
@@ -251,12 +251,12 @@ import{a as B}from"./chunk-WA64GKWB.js";import{a as lt,e as pt,f as Ee,j as On,k
251
251
  FROM documents
252
252
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
253
253
  )
254
- `).run()})()}function Xi(e,t){return e.prepare(`
254
+ `).run()})()}function Ki(e,t){return e.prepare(`
255
255
  SELECT relative_path AS relativePath
256
256
  FROM documents
257
257
  WHERE language = 'vue' OR relative_path LIKE '%.vue'
258
258
  ORDER BY relative_path
259
- `).all().map(r=>Su(t,r.relativePath))}function Ki(e,t){let{vueCore:n,ts:r,volarTs:i}=xu(e),{parsed:o,vueOptions:a}=Iu(n,r,t),s=Yi(t),c=n.createVueLanguagePlugin(r,o.options,a,m=>m),u=vu(n,r,c),d=Pu(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 xu(e){let t=fu(bu(Qi(e,"package.json")).href);return{vueCore:sn(t,"@vue/language-core",e),ts:sn(t,"typescript",e),volarTs:sn(t,"@volar/typescript",e)}}function Iu(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,Yi(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function vu(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!mu(o))return;let a=cn(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??Fu(o))});return r.current=i,i}function Pu(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function sn(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 Zi(e,t,n){let r=wu(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:ku(c.starts,s.line,2,i.name)}}function wu(e){let t=e.prepare(`
259
+ `).all().map(r=>bu(t,r.relativePath))}function Zi(e,t){let{vueCore:n,ts:r,volarTs:i}=Iu(e),{parsed:o,vueOptions:a}=vu(n,r,t),s=Qi(t),c=n.createVueLanguagePlugin(r,o.options,a,m=>m),u=Pu(n,r,c),d=wu(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 Iu(e){let t=mu(Ru(Xi(e,"package.json")).href);return{vueCore:an(t,"@vue/language-core",e),ts:an(t,"typescript",e),volarTs:an(t,"@volar/typescript",e)}}function vu(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,Qi(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Pu(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!hu(o))return;let a=sn(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??Ou(o))});return r.current=i,i}function wu(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function an(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 eo(e,t,n){let r=ku(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:Eu(c.starts,s.line,2,i.name)}}function ku(e){let t=e.prepare(`
260
260
  SELECT
261
261
  d.relative_path AS relativePath,
262
262
  der.start_line AS startLine,
@@ -267,22 +267,22 @@ import{a as B}from"./chunk-WA64GKWB.js";import{a as lt,e as pt,f as Ee,j as On,k
267
267
  JOIN documents d ON d.id = der.document_id
268
268
  JOIN global_symbols gs ON gs.id = der.symbol_id
269
269
  ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
270
- `).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function ku(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let s=Math.floor((i+o)/2);e[s].line<t?i=s+1:o=s-1}let a=null;for(let s of[o,i]){let c=e[s];if(!c||c.displayName!==r)continue;let u=Math.abs(c.line-t);u>n||(!a||u<a.distance)&&(a={distance:u,symbolId:c.symbolId})}return a?.symbolId??null}function eo(e,t,n){let r=_u(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
270
+ `).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function Eu(e,t,n,r){let i=0,o=e.length-1;for(;i<=o;){let s=Math.floor((i+o)/2);e[s].line<t?i=s+1:o=s-1}let a=null;for(let s of[o,i]){let c=e[s];if(!c||c.displayName!==r)continue;let u=Math.abs(c.line-t);u>n||(!a||u<a.distance)&&(a={distance:u,symbolId:c.symbolId})}return a?.symbolId??null}function to(e,t,n){let r=Cu(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
271
271
  INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
272
272
  VALUES (?, ?, ?, ?)
273
- `),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let d=A(t,u),p=uo(r.name,r.version,d);o.run(p,"default",7,`Vue component|${d}`);let l=Cu(i,r,t,u);l&&(a++,s.set(u,l))}})(),{get(u){return s.get(u)??null},syntheticSymbols:a}}function to(e,t,n,r,i){return e.transaction(()=>(Ru(e),Eu(e,t,n,r),Tu(e,i)))()}function Eu(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
273
+ `),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let d=A(t,u),p=lo(r.name,r.version,d);o.run(p,"default",7,`Vue component|${d}`);let l=Au(i,r,t,u);l&&(a++,s.set(u,l))}})(),{get(u){return s.get(u)??null},syntheticSymbols:a}}function no(e,t,n,r,i){return e.transaction(()=>(xu(e),Tu(e,t,n,r),Du(e,i)))()}function Tu(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
274
274
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
275
275
  VALUES (?, ?, ?, ?, X'00')
276
276
  `),a=e.prepare(`
277
277
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
278
278
  VALUES (?, ?, 1)
279
- `);for(let s of n){let c=r.get(s);if(!c)continue;let u=A(t,s),d=i.get(u);if(!d)continue;let p=o.run(d.id,-1,0,0);a.run(Number(p.lastInsertRowid),c)}}function no(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let o=r.language.scripts.get(e.fileName),a=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&a){let s=r.language.maps.get(a,o);if(un(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function ro(e){let t=new Set,n=[];for(let r of e){let i=io(r);t.has(i)||(t.add(i),n.push(r))}return n}function io(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function Tu(e,t){let n=ju(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
279
+ `);for(let s of n){let c=r.get(s);if(!c)continue;let u=A(t,s),d=i.get(u);if(!d)continue;let p=o.run(d.id,-1,0,0);a.run(Number(p.lastInsertRowid),c)}}function ro(e,t,n,r,i){if(e.fileName.endsWith(".vue")){let o=r.language.scripts.get(e.fileName),a=o?.generated?.languagePlugin.typescript?.getServiceScript(o.generated.root)?.code;if(o&&a){let s=r.language.maps.get(a,o);if(cn(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function io(e){let t=new Set,n=[];for(let r of e){let i=oo(r);t.has(i)||(t.add(i),n.push(r))}return n}function oo(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function Du(e,t){let n=_u(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
280
280
  INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
281
281
  VALUES (?, ?, ?, ?, X'00')
282
282
  `),i=e.prepare(`
283
283
  INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
284
284
  VALUES (?, ?, 0)
285
- `),o=new Set,a=0,s=0;for(let c of t){let u=io(c);if(o.has(u))continue;o.add(u);let d=n.get(c.sourceFile);if(!d)continue;let p=r.run(d,s++,c.sourceLine,c.sourceLine),l=i.run(Number(p.lastInsertRowid),c.symbolId);a+=Number(l.changes)}return a}function*oo(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function ao(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function un(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Du(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let o=Math.floor((n+r)/2);e.lineStarts[o]<=t?n=o+1:r=o-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function so(e,t){return A(e,t).startsWith("node_modules/")}function A(e,t){return yu(e,t).replaceAll("\\","/")}function Fu(e){switch(hu(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function co(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=cn(t,"utf-8"),r={text:n,lineStarts:Ou(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:Du}}function Ou(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function ju(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),a=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let s of a)n.set(s.relativePath,s.id)}return n}function _u(e){try{let t=JSON.parse(cn(Qi(e,"package.json"),"utf-8"));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function Cu(e,t,n,r){let i=A(n,r),o=uo(t.name,t.version,i);return e.get(o)?.id??null}function uo(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function po(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>Uu({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Vu(e){return N(J(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),N(po({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function Uu(e){let t=Gu(e.projectRoot,e.tsconfig);if(!Mu(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Lu(e.dbPath);try{let r=Xi(n,e.projectRoot),i=$u(Nu(e.dbPath),"augment-vue-meta.json");return mr({cachePath:i,readFingerprint:()=>Ju(n,e.projectRoot,e.tsconfig),compute:()=>Wu({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function Wu(e){let t=eo(e.db,e.projectRoot,e.vueFiles),n=Bu(e,t),r=ro(n.occurrences),i=to(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:ed(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:Zu(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function Bu(e,t){if(Ji(e.vueFiles))return Hi({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=Hu({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return qu({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function Ju(e,t,n){let r=e.prepare(`
285
+ `),o=new Set,a=0,s=0;for(let c of t){let u=oo(c);if(o.has(u))continue;o.add(u);let d=n.get(c.sourceFile);if(!d)continue;let p=r.run(d,s++,c.sourceLine,c.sourceLine),l=i.run(Number(p.lastInsertRowid),c.symbolId);a+=Number(l.changes)}return a}function*ao(e){let t=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,n=new Set(["script","setup","template","style","lang","scoped","true","false","null","undefined","const","let","var","import","from","export","return","if","else","for","while","function","class","type","interface","as","await","async"]),r;for(;r=t.exec(e);){let i=r[0];n.has(i)||(yield{text:i,start:r.index,end:r.index+i.length})}}function so(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function cn(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Fu(e,t){let n=0,r=e.lineStarts.length-1;for(;n<=r;){let o=Math.floor((n+r)/2);e.lineStarts[o]<=t?n=o+1:r=o-1}let i=Math.max(0,r);return{line:i,character:t-e.lineStarts[i]}}function co(e,t){return A(e,t).startsWith("node_modules/")}function A(e,t){return Su(e,t).replaceAll("\\","/")}function Ou(e){switch(yu(e)){case".vue":return"vue";case".tsx":return"typescriptreact";case".ts":case".mts":case".cts":return"typescript";case".jsx":return"javascriptreact";case".js":case".mjs":case".cjs":return"javascript";case".json":return"json";default:return"typescript"}}function uo(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=sn(t,"utf-8"),r={text:n,lineStarts:ju(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:Fu}}function ju(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function _u(e,t){let n=new Map,r=500;for(let i=0;i<t.length;i+=r){let o=t.slice(i,i+r),a=e.prepare(`SELECT id, relative_path AS relativePath FROM documents WHERE relative_path IN (${o.map(()=>"?").join(",")})`).all(...o);for(let s of a)n.set(s.relativePath,s.id)}return n}function Cu(e){try{let t=JSON.parse(sn(Xi(e,"package.json"),"utf-8"));return{name:t.name??"workspace",version:t.version??"0.0.0"}}catch{return{name:"workspace",version:"0.0.0"}}}function Au(e,t,n,r){let i=A(n,r),o=lo(t.name,t.version,i);return e.get(o)?.id??null}function lo(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function go(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>Wu({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function Uu(e){return N(J(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),N(go({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function Wu(e){let t=Vu(e.projectRoot,e.tsconfig);if(!Nu(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Mu(e.dbPath);try{let r=Ki(n,e.projectRoot),i=Gu($u(e.dbPath),"augment-vue-meta.json");return mr({cachePath:i,readFingerprint:()=>Hu(n,e.projectRoot,e.tsconfig),compute:()=>Bu({db:n,projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,configPath:t,vueFiles:r,onStatus:e.onStatus}),onCacheHit:o=>e.onStatus?.(`Vue references unchanged; reused ${o.resolvedReferences} cached resolved references.`)})}finally{n.close()}}function Bu(e){let t=to(e.db,e.projectRoot,e.vueFiles),n=Ju(e,t),r=io(n.occurrences),i=no(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:td(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:ed(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function Ju(e,t){if(Hi(e.vueFiles))return qi({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=qu({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return zu({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function Hu(e,t,n){let r=e.prepare(`
286
286
  SELECT
287
287
  (SELECT COUNT(*) FROM documents) AS documents,
288
288
  (SELECT COUNT(*) FROM global_symbols) AS symbols,
@@ -291,13 +291,13 @@ import{a as B}from"./chunk-WA64GKWB.js";import{a as lt,e as pt,f as Ee,j as On,k
291
291
  (SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
292
292
  (SELECT MAX(id) FROM chunks) AS maxChunkId,
293
293
  (SELECT MAX(id) FROM global_symbols) AS maxSymbolId
294
- `).get();return{version:3,tsconfig:n,files:Pe(t),db:r}}function Hu(e){let t=co();return{projectRoot:e.projectRoot,context:Ki(e.projectRoot,e.configPath),symbolLookup:Zi(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function qu(e){let t=[],n=X(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=zu(e,i);t.push(...o.occurrences),Qe(n,o)}return{occurrences:t,...n}}function zu(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return lo(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 lo(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=A(e.projectRoot,t.fileName),s=[...oo(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:nd(s),processedStarts:new Set};return Yu({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function Yu(e){let t=[],n=X();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||Qu(e.sourceInfo.text,r.start))continue;let i=ao(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!so(e.projectRoot,d.fileName));if(!a){dn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=A(e.projectRoot,a.fileName),c=Xu(e.sourceFile,r.text,s);if(c){dn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=no(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){dn(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}go(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),td(t,e,r,i,s,u)}return{occurrences:t,...n}}function Qu(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 Xu(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function lo(e,t,n){let r=X();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 dn(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 ln(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 Ku(e,t){let n=ln(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=ln(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function Zu(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(...ln(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function ed(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return Ku(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function td(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of rd(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&&(go(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function go(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 nd(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function rd(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=id(r,u.textSpan.start,o,i.text);d!==null&&s.push(d)}return s}function id(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=un(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function Df(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=hd(e),a=Date.now();Ke(h(o.outputScip),{recursive:!0}),Ke(h(o.outputDb),{recursive:!0});let s=e.languages??ht(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=Z("reindex.fingerprint",()=>Yd(t,s,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:s.length}),u,d;if(e.skipIfUnchanged!==!1&&!bi(t,o.outputDb)&&fo(o.outputScip)===fo(I(h(o.outputDb),"index.scip"))){let g=Ee(t);if(u=g?Be(g,c):void 0,u){let v=_(u);if(v){if(!md(o,c))try{zt({snapshot:u,manifest:v,targetCacheDir:h(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${u.generationId.slice(0,12)}`)}catch(S){r(`Shared generation attach failed; continuing locally: ${gn(S)}`)}}else{let S=await xi(u);if(S.kind==="owner")d=S.release;else if(S.kind==="generation-ready"){let R=_(u);if(R)try{zt({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: ${gn(y)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let p=te(I(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 ee("reindex.lock",()=>Ud(I(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,v=Z("reindex.reuse-check",()=>(g=yd({opts:e,paths:o,languages:s,fingerprint:c,start:a,onStatus:r}),g),()=>({languages:s.length,reused:g!==null}));if(v)return mo({snapshot:u,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),v;await ee("reindex.scip-cli-ready",()=>Cd(i,r));let S=bd(o);m=S.runDir;let R,y=await ee("reindex.fresh",async()=>(R=await Rd({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 mo({snapshot:u,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),y}catch(g){throw Oo(o.metaPath,nt({trigger:e.trigger,result:"failed",start:a,error:g instanceof Error?g.message:String(g)})),g}finally{m&&W(m,{recursive:!0,force:!0}),l(),p.release(),d?.()}}function mo(e){if(e.snapshot){if(_(e.snapshot)){Je(e.snapshot,h(e.paths.outputDb),"local-fresh");return}try{let t=Ee(e.projectRoot),n=t?Be(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}Ri({snapshot:e.snapshot,sourceCacheDir:h(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=Ee(e.projectRoot);return(r?Be(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),Je(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: ${gn(t)}`)}}}function md(e,t){if(!O(e.outputScip)||!O(e.outputDb)||!Fo(e.metaPath,t))return!1;let n=G(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function gn(e){return e instanceof Error?e.message:String(e)}function hd(e){let t=e.outputScip??I(e.projectRoot,"index.scip"),n=e.outputDb??I(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:I(h(n),"meta.json")}}function yd(e){let t=G(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!O(e.paths.outputScip)||!O(e.paths.outputDb)||!Fo(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=nt({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return Oo(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:Sd(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function Sd(e,t,n,r){let i=To(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:he(i[o]),outputBytes:ye(mn(e.outputDb,o)),durationMs:0}))}function bd(e){let t=cd(I(h(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:I(t,Xe(e.outputScip)),tempOutputDb:I(t,Xe(e.outputDb)),tempMetaPath:I(t,Xe(e.metaPath))}}async function Rd(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await ee("reindex.language-indexers",async()=>(n=await Id(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(", ")}`),xd({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let m=Z("reindex.publish",()=>Od(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(v=>v.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:m,shards:c}}let p=Z("reindex.publish",()=>Fd(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 xd(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 Id(e,t){let n=Ed({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,Sn]of n)Sn.reused&&(r.push({language:E,scipPath:Sn.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=be(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?Vi({projectRoot:e.projectRoot,cacheDir:h(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:Se(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:Se(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:u,previousSnapshot:fn(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,p=new Set(d?["typescript"]:[]),l=d?void 0:vd(e,n),{preparedRuns:m,skippedLanguages:g,languageOutputScipPaths:v}=Ad({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 Bi(S,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),y=[];if(l){wd(e.paths.outputDb,R);let E=v.typescript??e.tempPaths.tempOutputScip;y=kd({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:E,reusedProjects:l.reusedProjects})}let w=[...R,...y],{indexedOutputs:k}=Md(w,g),Re=d?[{language:"typescript",scipPath:d.scipPath}]:[],yn=[...r,...Re,...k];Nd(yn,g,e.languages,e.opts.allowPartial,e.onStatus);let jo=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:ye(d.scipPath)??void 0}]:[],_o=Td(n,[...R,...jo],l?{outputDb:e.paths.outputDb,classification:l.classification}:void 0);return{indexedOutputs:yn,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:Dd(n,e.languages),shards:_o,typescriptProjectShardContext:l?{projects:l.allProjects,fingerprints:l.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function vd(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=me(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Rr(e.projectRoot,r),o=yr(n.fingerprint.files,r),a=Sr(r,i),s=br(r,o,a),c=be(e.paths.metaPath),d=Pd(c,s,g=>O(tt(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 Pd(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 wd(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=tt(e,r);Ke(h(i),{recursive:!0}),Ze(n.scipPath,i)}}function kd(e){return e.reusedProjects.map((t,n)=>{let r=tt(e.outputDb,t),i=Se(e.tempOutputScip,"typescript-project-cached",n);return Ze(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:ye(i)??void 0}})}function Ed(e){let t=be(e.paths.metaPath),n=To(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=mn(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 Td(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:he(o.fingerprint),outputBytes:ye(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),a=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,s=a?n.classification.get(a):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:s?.reason??o?.reason??i.skipped?.reason,fingerprint:s?he(s.fingerprint):o?he(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:he(o.fingerprint),outputBytes:ye(tt(n.outputDb,i)),durationMs:0});return r}function he(e){return ad("sha256").update(L(e)).digest("hex").slice(0,16)}function ye(e){try{return ld(e).size}catch{return null}}function Dd(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function Fd(e,t,n,r,i,o,a,s){let c=!s||s.completeScipUpdated,u=!1;c&&(ho(e.paths.outputDb,n),u=yo(n,e.tempPaths.tempOutputScip,e.onStatus));let d=$d({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..."),Ui({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 ho(e.paths.outputDb,y),u=yo(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 B({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),w=new B({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let k=Dn(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=fn(e.paths.metaPath),l=d.mode==="incremental"&&s?Vd(s,d.changedDocumentPaths):mt({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=nt({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(y=>y.language),skipped:[...r]}),g=d.mode==="incremental"&&d.scipCompanion==="deferred",v={...o};g&&delete v.typescript;let{metadata:S,pruneProjects:R}=vo({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:v,typescriptProjectShardContext:a,lastRefresh:m});return S.scipCompanion=g?"deferred":"current",Po(e.paths.outputDb,R),hn(e.tempPaths.tempMetaPath,S),Ve({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}:{}}}),Yr(h(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),Io(e.paths.outputDb,l,e.onStatus),m}function Od(e,t,n,r,i,o){let a=fn(e.paths.metaPath),s=null;try{Ze(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??=mt({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=nt({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:u,pruneProjects:d}=vo({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return Po(e.paths.outputDb,d),hn(e.paths.metaPath,u),ai(e.paths.outputDb,e.paths.metaPath),Io(e.paths.outputDb,s,e.onStatus),c}function fn(e){return kn(be(e)?.fingerprint)}function Io(e,t,n){try{Yn(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 vo(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=be(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 Po(e,t){let n=Do(e);if(t===null){W(n,{recursive:!0,force:!0});return}let r;try{r=dd(n)}catch{return}for(let i of _d(r,t))W(I(n,i),{force:!0})}function _d(e,t){let n=new Set(t.map(r=>`${Dt(r)}.scip`));return e.filter(r=>!n.has(r))}function ho(e,t){for(let n of t){let r=mn(e,n.language);Ke(h(r),{recursive:!0}),n.scipPath!==r&&Ze(n.scipPath,r)}}async function Cd(e,t){if(!lt()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
296
- Install from: https://github.com/sourcegraph/scip/releases`);if(fd()==="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..."),!pt(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 Ad(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?Se(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=Ld({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?wo(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function Ld(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[pn({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??me(e.projectRoot,e.typescriptProjects);return t.length===0?[pn({...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)=>pn({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:Se(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function pn(e){let t=ve(e.language),n=rt(t),r=at(t,e.projectRoot);if(!r&&!ot(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...`),!ct(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??it(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:st(t,e.env,i)}}}function Md(e,t){let n=new Map;for(let i of e)if(i.skipped)wo(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)vt(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&xo(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function wo(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 Nd(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
294
+ `).get();return{version:3,tsconfig:n,files:Pe(t),db:r}}function qu(e){let t=uo();return{projectRoot:e.projectRoot,context:Zi(e.projectRoot,e.configPath),symbolLookup:eo(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function zu(e){let t=[],n=X(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=Yu(e,i);t.push(...o.occurrences),Qe(n,o)}return{occurrences:t,...n}}function Yu(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return po(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 po(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=A(e.projectRoot,t.fileName),s=[...ao(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:rd(s),processedStarts:new Set};return Qu({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function Qu(e){let t=[],n=X();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||Xu(e.sourceInfo.text,r.start))continue;let i=so(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(d=>!co(e.projectRoot,d.fileName));if(!a){un(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=A(e.projectRoot,a.fileName),c=Ku(e.sourceFile,r.text,s);if(c){un(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=ro(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){un(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}fo(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),nd(t,e,r,i,s,u)}return{occurrences:t,...n}}function Xu(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 Ku(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function po(e,t,n){let r=X();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 un(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 dn(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 Zu(e,t){let n=dn(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=dn(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function ed(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(...dn(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function td(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return Zu(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function nd(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of id(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&&(fo(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function fo(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 rd(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function id(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=od(r,u.textSpan.start,o,i.text);d!==null&&s.push(d)}return s}function od(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=cn(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function Of(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=yd(e),a=Date.now();Ke(h(o.outputScip),{recursive:!0}),Ke(h(o.outputDb),{recursive:!0});let s=e.languages??ht(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=Z("reindex.fingerprint",()=>Qd(t,s,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:s.length}),u,d;if(e.skipIfUnchanged!==!1&&!bi(t,o.outputDb)&&mo(o.outputScip)===mo(I(h(o.outputDb),"index.scip"))){let g=we(t);if(u=g?Be(g,c):void 0,u){let v=_(u);if(v){if(!hd(o,c))try{zt({snapshot:u,manifest:v,targetCacheDir:h(o.outputDb),targetProjectRoot:t}),r(`Attached shared generation ${u.generationId.slice(0,12)}`)}catch(S){r(`Shared generation attach failed; continuing locally: ${pn(S)}`)}}else{let S=await xi(u);if(S.kind==="owner")d=S.release;else if(S.kind==="generation-ready"){let R=_(u);if(R)try{zt({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: ${pn(y)}`)}}else r("Shared generation build lock timed out; continuing with an isolated local reindex")}}}let p=te(I(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 ee("reindex.lock",()=>Wd(I(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,v=Z("reindex.reuse-check",()=>(g=Sd({opts:e,paths:o,languages:s,fingerprint:c,start:a,onStatus:r}),g),()=>({languages:s.length,reused:g!==null}));if(v)return ho({snapshot:u,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),v;await ee("reindex.scip-cli-ready",()=>Ad(i,r));let S=Rd(o);m=S.runDir;let R,y=await ee("reindex.fresh",async()=>(R=await xd({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 ho({snapshot:u,paths:o,projectRoot:t,fingerprint:c,onStatus:r}),y}catch(g){throw jo(o.metaPath,nt({trigger:e.trigger,result:"failed",start:a,error:g instanceof Error?g.message:String(g)})),g}finally{m&&W(m,{recursive:!0,force:!0}),l(),p.release(),d?.()}}function ho(e){if(e.snapshot){if(_(e.snapshot)){Je(e.snapshot,h(e.paths.outputDb),"local-fresh");return}try{let t=we(e.projectRoot),n=t?Be(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}Ri({snapshot:e.snapshot,sourceCacheDir:h(e.paths.outputDb),sourceProjectRoot:e.projectRoot,sourceStillValid:()=>{let r=we(e.projectRoot);return(r?Be(r,e.fingerprint):void 0)?.generationId===e.snapshot?.generationId}}),Je(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: ${pn(t)}`)}}}function hd(e,t){if(!O(e.outputScip)||!O(e.outputDb)||!Oo(e.metaPath,t))return!1;let n=G(e.outputDb,e.metaPath);return n.state!=="invalid"&&n.state!=="drifted"}function pn(e){return e instanceof Error?e.message:String(e)}function yd(e){let t=e.outputScip??I(e.projectRoot,"index.scip"),n=e.outputDb??I(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:I(h(n),"meta.json")}}function Sd(e){let t=G(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!O(e.paths.outputScip)||!O(e.paths.outputDb)||!Oo(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=nt({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return jo(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:bd(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function bd(e,t,n,r){let i=Do(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:he(i[o]),outputBytes:ye(fn(e.outputDb,o)),durationMs:0}))}function Rd(e){let t=ud(I(h(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:I(t,Xe(e.outputScip)),tempOutputDb:I(t,Xe(e.outputDb)),tempMetaPath:I(t,Xe(e.metaPath))}}async function xd(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await ee("reindex.language-indexers",async()=>(n=await vd(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(", ")}`),Id({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let m=Z("reindex.publish",()=>jd(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(v=>v.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:m,shards:c}}let p=Z("reindex.publish",()=>Od(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 Id(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 vd(e,t){let n=Td({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,yn]of n)yn.reused&&(r.push({language:E,scipPath:yn.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=be(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?Ui({projectRoot:e.projectRoot,cacheDir:h(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:Se(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:Se(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:u,previousSnapshot:gn(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,p=new Set(d?["typescript"]:[]),l=d?void 0:Pd(e,n),{preparedRuns:m,skippedLanguages:g,languageOutputScipPaths:v}=Ld({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 Ji(S,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),y=[];if(l){kd(e.paths.outputDb,R);let E=v.typescript??e.tempPaths.tempOutputScip;y=Ed({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:E,reusedProjects:l.reusedProjects})}let w=[...R,...y],{indexedOutputs:k}=Nd(w,g),Re=d?[{language:"typescript",scipPath:d.scipPath}]:[],hn=[...r,...Re,...k];$d(hn,g,e.languages,e.opts.allowPartial,e.onStatus);let _o=d?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:d.scipPath,outputScipPath:d.scipPath,durationMs:d.durationMs,command:"watch-service:typescript-index",outputBytes:ye(d.scipPath)??void 0}]:[],Co=Dd(n,[...R,..._o],l?{outputDb:e.paths.outputDb,classification:l.classification}:void 0);return{indexedOutputs:hn,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:Fd(n,e.languages),shards:Co,typescriptProjectShardContext:l?{projects:l.allProjects,fingerprints:l.fingerprints}:void 0,incrementalTypeScript:d??void 0}}function Pd(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=me(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Rr(e.projectRoot,r),o=yr(n.fingerprint.files,r),a=Sr(r,i),s=br(r,o,a),c=be(e.paths.metaPath),d=wd(c,s,g=>O(tt(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 wd(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 kd(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=tt(e,r);Ke(h(i),{recursive:!0}),Ze(n.scipPath,i)}}function Ed(e){return e.reusedProjects.map((t,n)=>{let r=tt(e.outputDb,t),i=Se(e.tempOutputScip,"typescript-project-cached",n);return Ze(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:ye(i)??void 0}})}function Td(e){let t=be(e.paths.metaPath),n=Do(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=fn(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 Dd(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:he(o.fingerprint),outputBytes:ye(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),a=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,s=a?n.classification.get(a):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:s?.reason??o?.reason??i.skipped?.reason,fingerprint:s?he(s.fingerprint):o?he(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:he(o.fingerprint),outputBytes:ye(tt(n.outputDb,i)),durationMs:0});return r}function he(e){return sd("sha256").update(L(e)).digest("hex").slice(0,16)}function ye(e){try{return pd(e).size}catch{return null}}function Fd(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function Od(e,t,n,r,i,o,a,s){let c=!s||s.completeScipUpdated,u=!1;c&&(yo(e.paths.outputDb,n),u=So(n,e.tempPaths.tempOutputScip,e.onStatus));let d=Gd({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..."),Wi({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 yo(e.paths.outputDb,y),u=So(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 B({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),w=new B({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let k=Dn(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=gn(e.paths.metaPath),l=d.mode==="incremental"&&s?Ud(s,d.changedDocumentPaths):mt({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=nt({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(y=>y.language),skipped:[...r]}),g=d.mode==="incremental"&&d.scipCompanion==="deferred",v={...o};g&&delete v.typescript;let{metadata:S,pruneProjects:R}=Po({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:v,typescriptProjectShardContext:a,lastRefresh:m});return S.scipCompanion=g?"deferred":"current",wo(e.paths.outputDb,R),mn(e.tempPaths.tempMetaPath,S),Ve({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}:{}}}),Yr(h(e.paths.outputDb),d.mode==="incremental"&&d.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),vo(e.paths.outputDb,l,e.onStatus),m}function jd(e,t,n,r,i,o){let a=gn(e.paths.metaPath),s=null;try{Ze(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??=mt({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=nt({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:u,pruneProjects:d}=Po({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return wo(e.paths.outputDb,d),mn(e.paths.metaPath,u),ai(e.paths.outputDb,e.paths.metaPath),vo(e.paths.outputDb,s,e.onStatus),c}function gn(e){return kn(be(e)?.fingerprint)}function vo(e,t,n){try{Yn(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 Po(e){let t=_d({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 _d(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=be(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 wo(e,t){let n=Fo(e);if(t===null){W(n,{recursive:!0,force:!0});return}let r;try{r=ld(n)}catch{return}for(let i of Cd(r,t))W(I(n,i),{force:!0})}function Cd(e,t){let n=new Set(t.map(r=>`${Dt(r)}.scip`));return e.filter(r=>!n.has(r))}function yo(e,t){for(let n of t){let r=fn(e,n.language);Ke(h(r),{recursive:!0}),n.scipPath!==r&&Ze(n.scipPath,r)}}async function Ad(e,t){if(!lt()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
296
+ Install from: https://github.com/sourcegraph/scip/releases`);if(md()==="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..."),!pt(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 Ld(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?Se(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=Md({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?ko(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function Md(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[ln({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??me(e.projectRoot,e.typescriptProjects);return t.length===0?[ln({...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)=>ln({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:Se(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function ln(e){let t=ve(e.language),n=rt(t),r=at(t,e.projectRoot);if(!r&&!ot(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...`),!ct(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??it(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:st(t,e.env,i)}}}function Nd(e,t){let n=new Map;for(let i of e)if(i.skipped)ko(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)vt(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&Io(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function ko(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 $d(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 yo(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=ir(e.map(o=>o.scipPath),t);return Eo(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&xo(e[0].scipPath,t);return!1}function $d(e){let t;if(Gd(e)){let i=I(e.run.tempPaths.runDir,"typescript-affected.db");try{ko(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();So(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=pr({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),W(i,{force:!0}),W(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 So(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function Gd(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 Vd(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:ft(e.plan,o,e.projectFileCount)}}function So(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||ko(e,r);let o=lt();if(!o)throw new Error("scip CLI is not available");od(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 ko(e,t){let n=nr(e);Eo(n,t)}function Eo(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function Se(e,t,n){let r=gd(e)||".scip",i=Xe(e,r);return I(h(e),`${i}.${n+1}.${t}${r}`)}async function Ud(e,t){for(let n=0;n<2;n++){let r=Wd(e,t);if(r)return r;let i=Bd(e);if(i&&Jd(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await qd(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.`);W(e,{force:!0});continue}if(i&&!T(i.pid)){W(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 Wd(e,t){let n;try{n=ud(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 pd(n,JSON.stringify(r)+`
302
- `),()=>{try{sd(n)}finally{W(e,{force:!0})}}}function Bd(e){try{let t=JSON.parse(et(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 Jd(e,t){return e?.kind==="manual-cli"&&Hd(t?.trigger)}function Hd(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function qd(e){return bo(e,"SIGTERM"),await Ro(e,2e3)?!0:(bo(e,"SIGKILL"),Ro(e,1e3))}function bo(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function Ro(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!T(e))return!0;await zd(50)}return!T(e)}function zd(e){return new Promise(t=>setTimeout(t,e))}function Yd(e,t,n){return vn(e,t,n)}function To(e,t,n){return Object.fromEntries(t.map(r=>{let i=ve(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:In(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},a=r==="clojure"?Qd(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&Xd(n),...o,clojureConfigPath:a,files:Pe(e,{language:r,markerFiles:i})}]}))}function Qd(e){return e?.trim()||void 0}function Xd(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function mn(e,t){return I(h(e),"language-indexes",`${t}.scip`)}function Do(e){return I(h(e),"language-indexes","typescript-projects")}function tt(e,t){return I(Do(e),`${Dt(t)}.scip`)}function be(e){try{return JSON.parse(et(e,"utf-8"))}catch{return null}}function Fo(e,t){try{let n=JSON.parse(et(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 hn(e,t){b(e,t,{spacing:2,trailingNewline:!0})}function Oo(e,t){try{let n=JSON.parse(et(e,"utf-8"));if(n.version!==2&&n.version!==3)return;hn(e,{...n,lastRefresh:t})}catch{}}function nt(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs: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{Co as INDEXER_CONFIGS,Bn as augmentAuxiliaryDocuments,Vu as augmentVueResolvedReferences,J as auxiliaryDocumentsAugmentationStage,rt as describeIndexerBinary,ht as detectLanguages,ve as getIndexerConfig,st as getIndexerExecutionEnv,Ao as isBinaryAvailable,ot as isIndexerInstalled,vt as mergeScipFiles,It as mergeScipIndexes,Df as reindex,it as resolveIndexerBinary,at as resolveProjectLocalIndexerBinary,N as runPostIndexAugmentation,ct as tryInstallIndexer,pt as tryInstallScipCli,po as vueResolvedReferencesAugmentationStage};
301
+ `))}function So(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=ir(e.map(o=>o.scipPath),t);return To(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&Io(e[0].scipPath,t);return!1}function Gd(e){let t;if(Vd(e)){let i=I(e.run.tempPaths.runDir,"typescript-affected.db");try{Eo(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();bo(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=pr({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),W(i,{force:!0}),W(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 bo(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function Vd(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 Ud(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:ft(e.plan,o,e.projectFileCount)}}function bo(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||Eo(e,r);let o=lt();if(!o)throw new Error("scip CLI is not available");ad(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 Eo(e,t){let n=nr(e);To(n,t)}function To(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function Se(e,t,n){let r=fd(e)||".scip",i=Xe(e,r);return I(h(e),`${i}.${n+1}.${t}${r}`)}async function Wd(e,t){for(let n=0;n<2;n++){let r=Bd(e,t);if(r)return r;let i=Jd(e);if(i&&Hd(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await zd(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.`);W(e,{force:!0});continue}if(i&&!T(i.pid)){W(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 Bd(e,t){let n;try{n=dd(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 gd(n,JSON.stringify(r)+`
302
+ `),()=>{try{cd(n)}finally{W(e,{force:!0})}}}function Jd(e){try{let t=JSON.parse(et(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 Hd(e,t){return e?.kind==="manual-cli"&&qd(t?.trigger)}function qd(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function zd(e){return Ro(e,"SIGTERM"),await xo(e,2e3)?!0:(Ro(e,"SIGKILL"),xo(e,1e3))}function Ro(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function xo(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!T(e))return!0;await Yd(50)}return!T(e)}function Yd(e){return new Promise(t=>setTimeout(t,e))}function Qd(e,t,n){return In(e,t,n)}function Do(e,t,n){return Object.fromEntries(t.map(r=>{let i=ve(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:xn(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},a=r==="clojure"?Xd(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&Kd(n),...o,clojureConfigPath:a,files:Pe(e,{language:r,markerFiles:i})}]}))}function Xd(e){return e?.trim()||void 0}function Kd(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function fn(e,t){return I(h(e),"language-indexes",`${t}.scip`)}function Fo(e){return I(h(e),"language-indexes","typescript-projects")}function tt(e,t){return I(Fo(e),`${Dt(t)}.scip`)}function be(e){try{return JSON.parse(et(e,"utf-8"))}catch{return null}}function Oo(e,t){try{let n=JSON.parse(et(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 mn(e,t){b(e,t,{spacing:2,trailingNewline:!0})}function jo(e,t){try{let n=JSON.parse(et(e,"utf-8"));if(n.version!==2&&n.version!==3)return;mn(e,{...n,lastRefresh:t})}catch{}}function nt(e){return{trigger:e.trigger??{kind:"unknown"},result:e.result,startedAt:new Date(e.start).toISOString(),completedAt:new Date().toISOString(),durationMs: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{Ao as INDEXER_CONFIGS,Bn as augmentAuxiliaryDocuments,Uu as augmentVueResolvedReferences,J as auxiliaryDocumentsAugmentationStage,rt as describeIndexerBinary,ht as detectLanguages,ve as getIndexerConfig,st as getIndexerExecutionEnv,Lo as isBinaryAvailable,ot as isIndexerInstalled,vt as mergeScipFiles,It as mergeScipIndexes,Of as reindex,it as resolveIndexerBinary,at as resolveProjectLocalIndexerBinary,N as runPostIndexAugmentation,ct as tryInstallIndexer,pt as tryInstallScipCli,go as vueResolvedReferencesAugmentationStage};
303
303
  //# sourceMappingURL=reindex.js.map