scip-query 0.15.0 → 0.16.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.
- package/CHANGELOG.md +41 -1
- package/README.md +148 -66
- package/dist/augment-vue-worker.js +1 -1
- package/dist/chunk-2EU6WVR3.js +3 -0
- package/dist/chunk-2HFXPIBT.js +2 -0
- package/dist/chunk-2LGPMYS2.js +35 -0
- package/dist/chunk-2Y7YX54K.js +16 -0
- package/dist/chunk-363TZ64I.js +2 -0
- package/dist/chunk-3I34FZ6R.js +2 -0
- package/dist/chunk-3LAKH6BV.js +2 -0
- package/dist/chunk-3M2UCPFS.js +3 -0
- package/dist/chunk-3OPIMH42.js +2 -0
- package/dist/{chunk-QZOAOLLZ.js → chunk-3YAZH3JU.js} +2 -2
- package/dist/chunk-5P26M63Y.js +2 -0
- package/dist/{chunk-72FR7KEZ.js → chunk-5TVNLPUM.js} +14 -12
- package/dist/chunk-5UKDCXVC.js +5 -0
- package/dist/{chunk-R7U2I55B.js → chunk-5XDNFOAH.js} +2 -2
- package/dist/chunk-62Y3PC27.js +4 -0
- package/dist/chunk-6DNE65QS.js +40 -0
- package/dist/{chunk-N2OTJWC2.js → chunk-6EVORGCB.js} +2 -2
- package/dist/chunk-6GZ7LM7S.js +2 -0
- package/dist/chunk-753JWTUH.js +3 -0
- package/dist/chunk-7II7NFRV.js +4 -0
- package/dist/{chunk-M7EEHYSU.js → chunk-7RAS466A.js} +2 -2
- package/dist/chunk-A46JTKTM.js +5 -0
- package/dist/{chunk-2XRXEIRK.js → chunk-AAMZRDJT.js} +2 -2
- package/dist/chunk-AMPN2VMF.js +3 -0
- package/dist/{chunk-6XA4LDHY.js → chunk-B3X6KU75.js} +2 -2
- package/dist/chunk-BFWVHD2P.js +16 -0
- package/dist/chunk-BVHP2B4D.js +61 -0
- package/dist/{chunk-BUNDZ6K2.js → chunk-BVUA3GZC.js} +2 -2
- package/dist/{chunk-EDSD3VJK.js → chunk-CKIAEVGM.js} +2 -2
- package/dist/chunk-CM4EZLW4.js +2 -0
- package/dist/chunk-CS3FXTUC.js +2 -0
- package/dist/chunk-CVBS2FD4.js +2 -0
- package/dist/chunk-D5OXYOJP.js +7 -0
- package/dist/chunk-DA34GNNO.js +29 -0
- package/dist/chunk-DKK2H4D7.js +7 -0
- package/dist/chunk-EBSSCVR4.js +5 -0
- package/dist/{chunk-OXTM2RX3.js → chunk-EVCSXWER.js} +2 -2
- package/dist/chunk-FFIYGYQR.js +67 -0
- package/dist/chunk-G4KQ7S74.js +20 -0
- package/dist/{chunk-44P4SJFN.js → chunk-GWWYLYD3.js} +2 -2
- package/dist/chunk-HGUNWXJX.js +2 -0
- package/dist/chunk-HLRWOFXC.js +9 -0
- package/dist/{chunk-YQKECTPV.js → chunk-IRIM3SUR.js} +2 -2
- package/dist/chunk-JHK2DMUQ.js +4 -0
- package/dist/chunk-JQ2PCFZW.js +3 -0
- package/dist/chunk-JRFCWCOD.js +16 -0
- package/dist/chunk-JXAJDINF.js +2 -0
- package/dist/chunk-K32ZOW3P.js +2 -0
- package/dist/{chunk-3H5OSDF7.js → chunk-KI4WPR7Q.js} +2 -2
- package/dist/{chunk-43GKP6LI.js → chunk-KP2DJY7D.js} +2 -2
- package/dist/{chunk-YTVKPJXW.js → chunk-L27UIF3E.js} +2 -2
- package/dist/chunk-LT6AHYVY.js +18 -0
- package/dist/chunk-MCNWCJYL.js +11 -0
- package/dist/{chunk-K6UI6EBZ.js → chunk-MZB3DTHW.js} +2 -2
- package/dist/chunk-NLRWGGPY.js +8 -0
- package/dist/chunk-NLVKD45E.js +13 -0
- package/dist/chunk-OO6S4ECV.js +112 -0
- package/dist/{chunk-QYOPMTZ6.js → chunk-OYGKBDAD.js} +2 -2
- package/dist/chunk-P5QZILZ4.js +2 -0
- package/dist/chunk-P5XHIJHI.js +2 -0
- package/dist/chunk-PCCMMI2M.js +3 -0
- package/dist/{chunk-2TPCIPYA.js → chunk-Q65QYKU7.js} +2 -2
- package/dist/{chunk-K7SPOJHZ.js → chunk-QB7NRST4.js} +2 -2
- package/dist/{chunk-7JZRFDCU.js → chunk-QSNG3NHQ.js} +2 -2
- package/dist/chunk-QVZSWLLZ.js +2 -0
- package/dist/chunk-RLB7FZKR.js +10 -0
- package/dist/{chunk-KYB7FPXT.js → chunk-RPMT6MTX.js} +2 -2
- package/dist/chunk-RQWNF2RM.js +2 -0
- package/dist/chunk-RYFIRFYJ.js +4 -0
- package/dist/{chunk-QARYU7R3.js → chunk-S2FZILCF.js} +2 -2
- package/dist/{chunk-HV27H2V2.js → chunk-S3IXCXW2.js} +2 -2
- package/dist/{chunk-TYCZ7S4I.js → chunk-S5MTSES5.js} +2 -2
- package/dist/chunk-S5RZQA6V.js +2 -0
- package/dist/{chunk-PEHDARNC.js → chunk-SEEJPIWG.js} +2 -2
- package/dist/chunk-SOCS3467.js +2 -0
- package/dist/chunk-U6BJVXWQ.js +2 -0
- package/dist/chunk-UO4IADXJ.js +38 -0
- package/dist/{chunk-ZEO4CXQR.js → chunk-VLSI5MYU.js} +2 -2
- package/dist/chunk-VSQRU3AP.js +2 -0
- package/dist/chunk-VYQY75NA.js +2 -0
- package/dist/{chunk-NOKUZU56.js → chunk-VZCR3VQY.js} +2 -2
- package/dist/chunk-W3ZVRLCH.js +2 -0
- package/dist/chunk-WA64GKWB.js +20 -0
- package/dist/chunk-WFRZGMWJ.js +71 -0
- package/dist/chunk-WN6XEYVX.js +2 -0
- package/dist/chunk-XAEU4ROB.js +101 -0
- package/dist/chunk-XBPAJASV.js +2 -0
- package/dist/{chunk-GY3HAWUA.js → chunk-XC6PUFNN.js} +2 -2
- package/dist/chunk-Y42DMR6F.js +6 -0
- package/dist/chunk-YCVYOV4A.js +7 -0
- package/dist/{chunk-WPZPB42I.js → chunk-YD37KSEK.js} +2 -2
- package/dist/{chunk-V5W7H7V4.js → chunk-YFEJIYWH.js} +2 -2
- package/dist/chunk-YSUD2S7T.js +3 -0
- package/dist/{chunk-KJCDEDQW.js → chunk-ZEKBAMCN.js} +2 -2
- package/dist/chunk-ZHGUZKJL.js +2 -0
- package/dist/cli.js +586 -312
- package/dist/{config-types-aCgyLrvE.d.ts → config-types-SVkUIufk.d.ts} +8 -2
- package/dist/{db-DwCdT3rv.d.ts → db-CS0TuVH6.d.ts} +1 -1
- package/dist/{git-history-Dao3_Pu9.d.ts → git-history-ChNHbfZQ.d.ts} +2 -1
- package/dist/{health-nJUidasZ.d.ts → health-Btal3mQi.d.ts} +4 -4
- package/dist/index.d.ts +7 -5
- package/dist/index.js +1 -19
- package/dist/queries/affected.d.ts +2 -2
- package/dist/queries/affected.js +1 -1
- package/dist/queries/bottlenecks.d.ts +8 -2
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.d.ts +2 -2
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +2 -2
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +2 -2
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.d.ts +2 -2
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.d.ts +4 -3
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +2 -2
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +3 -3
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +5 -4
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.d.ts +2 -2
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +2 -2
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +2 -2
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +2 -2
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.d.ts +12 -3
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.d.ts +2 -2
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/deep-chains.d.ts +8 -3
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/deps.d.ts +2 -2
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-gate.d.ts +5 -4
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.d.ts +3 -3
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +4 -2
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +2 -2
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.d.ts +3 -3
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/extract-candidates.d.ts +2 -2
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +11 -5
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +2 -2
- package/dist/queries/health.d.ts +3 -3
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +2 -2
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +2 -2
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +2 -2
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +3 -3
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +5 -5
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.d.ts +2 -2
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.d.ts +2 -2
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.d.ts +2 -2
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.d.ts +2 -2
- package/dist/queries/methods.js +1 -1
- package/dist/queries/not-implemented.d.ts +2 -2
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.d.ts +2 -2
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.d.ts +3 -3
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.d.ts +4 -4
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/react-component-duplicates.d.ts +4 -2
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.d.ts +4 -2
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.d.ts +2 -2
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.d.ts +4 -2
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +2 -2
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.d.ts +2 -2
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.d.ts +2 -2
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-chains.d.ts +2 -2
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.d.ts +2 -2
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.d.ts +2 -2
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +2 -2
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.d.ts +2 -2
- package/dist/queries/slice.js +1 -1
- package/dist/queries/stale-abstractions.d.ts +2 -2
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/stats.d.ts +2 -2
- package/dist/queries/surface.d.ts +2 -2
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.d.ts +2 -2
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.d.ts +2 -2
- package/dist/queries/system.js +1 -1
- package/dist/queries/test-quality.d.ts +2 -2
- package/dist/queries/test-quality.js +1 -1
- package/dist/queries/trace.d.ts +2 -2
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.d.ts +2 -2
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/twin-drift.d.ts +2 -2
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.d.ts +2 -2
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.d.ts +2 -2
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/vue-component-duplicates.d.ts +4 -2
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.d.ts +4 -2
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.d.ts +2 -2
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/queries/wrapper-candidates.d.ts +2 -2
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/reindex-worker.js +256 -12
- package/dist/reindex.d.ts +29 -3
- package/dist/reindex.js +251 -22
- package/dist/runtime.d.ts +8 -4
- package/dist/runtime.js +2 -2
- package/dist/rust-semantic-session-server.js +2 -0
- package/dist/rust-semantic-session-worker.js +2 -0
- package/dist/rust-semantic-worker.js +2 -0
- package/dist/{scip-cli-DeAbuJ2b.d.ts → scip-cli-BKL-26TZ.d.ts} +2 -2
- package/dist/{symbol-types-DaoeXKUt.d.ts → symbol-types-BgWU6lhL.d.ts} +2 -0
- package/dist/watch-server.js +42 -0
- package/docs/AGENT_GUIDE.md +110 -34
- package/docs/AI_FAILURE_MODES.md +8 -3
- package/docs/COMMAND_REFERENCE.md +10 -6
- package/docs/REGEX_POLICY.md +3 -1
- package/docs/accuracy-audit-checklist.md +300 -0
- package/docs/accuracy-hardening-goal.md +493 -54
- package/docs/analyzer-inventory.md +31 -23
- package/docs/analyzer-validation-ledger.md +51 -21
- package/package.json +2 -1
- package/scripts/build-scip-windows.mjs +7 -7
- package/skills/_shared/SKILL.md +20 -19
- package/skills/scip-calibrate/SKILL.md +4 -2
- package/skills/scip-hyper-optimization/SKILL.md +5 -1
- package/skills/scip-query/SKILL.md +1 -1
- package/skills/scip-setup/SKILL.md +104 -4
- package/skills/scip-verify/SKILL.md +20 -14
- package/dist/chunk-27HMTUJE.js +0 -3
- package/dist/chunk-27XEGMCT.js +0 -7
- package/dist/chunk-3AMWF6V5.js +0 -3
- package/dist/chunk-4SCMYKD6.js +0 -2
- package/dist/chunk-5AAAEZ2Z.js +0 -2
- package/dist/chunk-5JRMZMLM.js +0 -2
- package/dist/chunk-5VY3RIEI.js +0 -38
- package/dist/chunk-6JUAGXR4.js +0 -4
- package/dist/chunk-6KDOYKCB.js +0 -40
- package/dist/chunk-6KMTPNZL.js +0 -3
- package/dist/chunk-7COVQPQQ.js +0 -9
- package/dist/chunk-7S5E7KWT.js +0 -2
- package/dist/chunk-7TVFPOD7.js +0 -102
- package/dist/chunk-A6KSEIRN.js +0 -61
- package/dist/chunk-AAMURYOK.js +0 -4
- package/dist/chunk-BP7S6V3M.js +0 -20
- package/dist/chunk-BRBF3E5X.js +0 -35
- package/dist/chunk-BZXE3HO4.js +0 -6
- package/dist/chunk-CXQQOXSI.js +0 -10
- package/dist/chunk-EVZSAR3S.js +0 -2
- package/dist/chunk-GMOEX7EV.js +0 -2
- package/dist/chunk-GNG622H3.js +0 -3
- package/dist/chunk-GUDKRIGW.js +0 -7
- package/dist/chunk-GULVO6NF.js +0 -43
- package/dist/chunk-HZZQKNVE.js +0 -2
- package/dist/chunk-I4R3SNMR.js +0 -2
- package/dist/chunk-IMQFJ53K.js +0 -2
- package/dist/chunk-ISLWJ4PY.js +0 -10
- package/dist/chunk-IUSSGHJO.js +0 -2
- package/dist/chunk-J5WVNZ6O.js +0 -2
- package/dist/chunk-JJUX2OAP.js +0 -2
- package/dist/chunk-JZBGTSAB.js +0 -13
- package/dist/chunk-K5N5RNGM.js +0 -2
- package/dist/chunk-KSJ544IV.js +0 -5
- package/dist/chunk-LY7NMOBW.js +0 -2
- package/dist/chunk-N23FT4EZ.js +0 -2
- package/dist/chunk-NCVFKOLB.js +0 -2
- package/dist/chunk-PESEPWZO.js +0 -2
- package/dist/chunk-PMY4UFGV.js +0 -2
- package/dist/chunk-Q7PWDXL5.js +0 -5
- package/dist/chunk-QVGFVRKD.js +0 -2
- package/dist/chunk-R5336VHZ.js +0 -2
- package/dist/chunk-RLB6SG25.js +0 -2
- package/dist/chunk-SFDVBARK.js +0 -2
- package/dist/chunk-TG7QSYCJ.js +0 -2
- package/dist/chunk-UHPWZCYQ.js +0 -3
- package/dist/chunk-URSSPS5H.js +0 -2
- package/dist/chunk-WIBFXSYB.js +0 -6
- package/dist/chunk-WMO2VZZK.js +0 -3
- package/dist/chunk-WS3Z6W3M.js +0 -65
- package/dist/chunk-X3DTIEMU.js +0 -18
- package/dist/chunk-X5C43YVI.js +0 -2
- package/dist/chunk-X7CHWTZ2.js +0 -72
- package/dist/chunk-XDESMVOL.js +0 -4
- package/dist/chunk-XZBLZHXL.js +0 -16
- package/dist/chunk-YBGC7HTY.js +0 -3
- package/dist/chunk-ZMGBWSFZ.js +0 -2
package/dist/reindex.js
CHANGED
|
@@ -1,11 +1,238 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
VALUES (?, ?, NULL, ?)`),
|
|
3
|
-
`).filter(r=>r&&t.has(
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
`)
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
import{a as L}from"./chunk-WA64GKWB.js";import{a as $e,e as Ge}from"./chunk-Y42DMR6F.js";import{a as Ut}from"./chunk-YZXV3CU3.js";import{A as se,B as $t,D as Gt,a as hi,b as oe,c as je,d as Oe,e as _e,f as Me,g as Le,h as Ce,i as V,j as R,o as Lt,p as Ae,q as H,r as Ct,s as At,t as Ne,u as Ve,x as Nt,y as ae,z as Vt}from"./chunk-EBSSCVR4.js";import"./chunk-P5XHIJHI.js";import{a as ie}from"./chunk-G4KQ7S74.js";import{a as yi}from"./chunk-QVZSWLLZ.js";import"./chunk-OO6S4ECV.js";import"./chunk-NLVKD45E.js";import{J as _t,K as Mt,d as U}from"./chunk-MCNWCJYL.js";import{a as re}from"./chunk-64MNV6AB.js";import{s as B,t as W}from"./chunk-WFRZGMWJ.js";import{execFileSync as pc}from"child_process";import{createHash as gc}from"crypto";import{closeSync as fc,copyFileSync as Ee,existsSync as k,mkdirSync as Te,mkdtempSync as mc,openSync as hc,readdirSync as yc,readFileSync as ke,renameSync as ni,rmSync as M,statSync as Sc,writeFileSync as bc}from"fs";import{basename as we,dirname as m,extname as Rc,join as b}from"path";import{platform as xc}from"os";import Si from"better-sqlite3";import{execFileSync as bi}from"child_process";import{existsSync as Ri,readdirSync as xi,readFileSync as vi}from"fs";import{extname as ce,join as Bt}from"path";function C(e={}){return{id:"auxiliary-documents",facts:["auxiliary-document"],run:t=>Wt({projectRoot:t.projectRoot,dbPath:t.dbPath,extensions:e.extensions,onStatus:t.onStatus})}}function Wt(e){let t=new Set((e.extensions??_t).map(o=>o.toLowerCase()));if(t.size===0)return{scanned:0,inserted:0,existing:0};if(!Ri(e.dbPath))throw new Error(`SCIP SQLite database not found at ${e.dbPath}`);let n=Ut(e.projectRoot),r=Pi(e.projectRoot,t).filter(o=>!n.isIgnored(o)),i=new Si(e.dbPath);try{let o=wi(i,r),a=i.prepare(`INSERT OR IGNORE INTO documents (language, relative_path, position_encoding, text)
|
|
2
|
+
VALUES (?, ?, NULL, ?)`),c=i.transaction(l=>{let p=0;for(let d of l){if(o.has(d))continue;let f=vi(Bt(e.projectRoot,d),"utf-8"),g=a.run(Ti(d),d,f);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 Pi(e,t){let n=Ii(e,t);if(n)return n;let r=[],i=o=>{let a=o?Bt(e,o):e,s;try{s=xi(a,{withFileTypes:!0})}catch{return}for(let c of s){if(Mt.has(c.name))continue;let u=o?`${o}/${c.name}`:c.name;if(c.isDirectory()){i(u);continue}t.has(ce(c.name).toLowerCase())&&r.push(u)}};return i(""),r.sort()}function Ii(e,t){try{return bi("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"]}).split(`
|
|
3
|
+
`).filter(r=>r&&t.has(ce(r).toLowerCase())).sort()}catch{return null}}function wi(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 Ti(e){return ce(e).toLowerCase()===".vue"?"vue":ce(e).replace(/^\./,"").toLowerCase()||"source"}import{createHash as Ei}from"crypto";import{appendFileSync as ki,existsSync as Di,mkdirSync as Fi,readFileSync as pu}from"fs";import{dirname as Jt,join as Ht}from"path";var ji="<global-symbols>";function Oi(e){let t=[];for(let n of e.all(`
|
|
4
|
+
SELECT relative_path, language, position_encoding, text
|
|
5
|
+
FROM documents
|
|
6
|
+
`))t.push({relativePath:n.relative_path,kind:"document",values:[n.language,n.position_encoding,n.text]});for(let n of e.all(`
|
|
7
|
+
SELECT d.relative_path,
|
|
8
|
+
c.chunk_index,
|
|
9
|
+
c.start_line,
|
|
10
|
+
c.end_line,
|
|
11
|
+
hex(c.occurrences) AS occurrences_hex
|
|
12
|
+
FROM chunks c
|
|
13
|
+
JOIN documents d ON d.id = c.document_id
|
|
14
|
+
`))t.push({relativePath:n.relative_path,kind:"chunk",values:[n.chunk_index,n.start_line,n.end_line,n.occurrences_hex]});for(let n of e.all(`
|
|
15
|
+
SELECT d.relative_path,
|
|
16
|
+
r.start_line,
|
|
17
|
+
r.start_char,
|
|
18
|
+
r.end_line,
|
|
19
|
+
r.end_char,
|
|
20
|
+
g.symbol,
|
|
21
|
+
g.display_name,
|
|
22
|
+
g.kind,
|
|
23
|
+
g.documentation,
|
|
24
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
25
|
+
g.enclosing_symbol,
|
|
26
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
27
|
+
FROM defn_enclosing_ranges r
|
|
28
|
+
JOIN documents d ON d.id = r.document_id
|
|
29
|
+
JOIN global_symbols g ON g.id = r.symbol_id
|
|
30
|
+
`))t.push({relativePath:n.relative_path,kind:"definition",values:Ue(n,[n.start_line,n.start_char,n.end_line,n.end_char])});for(let n of e.all(`
|
|
31
|
+
SELECT d.relative_path,
|
|
32
|
+
c.chunk_index,
|
|
33
|
+
m.role,
|
|
34
|
+
g.symbol,
|
|
35
|
+
g.display_name,
|
|
36
|
+
g.kind,
|
|
37
|
+
g.documentation,
|
|
38
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
39
|
+
g.enclosing_symbol,
|
|
40
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
41
|
+
FROM mentions m
|
|
42
|
+
JOIN chunks c ON c.id = m.chunk_id
|
|
43
|
+
JOIN documents d ON d.id = c.document_id
|
|
44
|
+
JOIN global_symbols g ON g.id = m.symbol_id
|
|
45
|
+
`))t.push({relativePath:n.relative_path,kind:"mention",values:Ue(n,[n.chunk_index,n.role])});for(let n of e.all(`
|
|
46
|
+
SELECT g.symbol,
|
|
47
|
+
g.display_name,
|
|
48
|
+
g.kind,
|
|
49
|
+
g.documentation,
|
|
50
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature_hex,
|
|
51
|
+
g.enclosing_symbol,
|
|
52
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships_hex
|
|
53
|
+
FROM global_symbols g
|
|
54
|
+
WHERE NOT EXISTS (
|
|
55
|
+
SELECT 1 FROM defn_enclosing_ranges r WHERE r.symbol_id = g.id
|
|
56
|
+
) AND NOT EXISTS (
|
|
57
|
+
SELECT 1 FROM mentions m WHERE m.symbol_id = g.id
|
|
58
|
+
)
|
|
59
|
+
`))t.push({relativePath:ji,kind:"global-symbol",values:Ue(n)});return _i(t)}function _i(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=Ei("sha256");for(let a of i.sort())o.update(String(Buffer.byteLength(a))),o.update(":"),o.update(a),o.update(`
|
|
60
|
+
`);n.set(r,o.digest("hex"))}return n}function Mi(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 Be(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 We(e,t=Ci){let n=t.now();if(!t.databaseExists(e.previousDbPath))return ue(e.refreshResult,"prior-index-unavailable",n,t.now());if(!t.databaseExists(e.candidateDbPath))return ue(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=ae(e.previousSnapshot,e.currentSnapshot),s=new Set(o),c=a.changes.length>0&&!Vt(a).fullProject&&a.changes.every(d=>s.has(d.path)),u=se(a,c?t.dependencyGraph(r):new Map,o),l=Mi(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:l,evaluation:Be(u,l,o.length)}}catch(o){return ue(e.refreshResult,"oracle-error",n,t.now(),o instanceof Error?o.message:String(o))}finally{qt(r),qt(i)}}function zt(e,t,n,r=Date.now()){return ue(e,t,r,r,n)}function Li(e){let t=Jt(e);return{latestPath:Ht(t,"affected-shadow-latest.json"),historyPath:Ht(t,"affected-shadow.jsonl")}}function Yt(e,t,n=Ai){let r=Li(e);return n.appendHistory(r.historyPath,t),n.writeLatest(r.latestPath,t),r}function Ue(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 Ci={now:()=>Date.now(),databaseExists:e=>Di(e),openDatabase:(e,t,n)=>new L({projectRoot:e,dbPath:t,indexPath:n}),indexedPaths:e=>re(e),dependencyGraph:e=>ie(e),factDigests:e=>Oi(e)},Ai={appendHistory:(e,t)=>{Fi(Jt(e),{recursive:!0}),ki(e,`${JSON.stringify(t)}
|
|
61
|
+
`)},writeLatest:(e,t)=>R(e,t,{spacing:2,trailingNewline:!0})};function ue(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 qt(e){try{e?.close()}catch{}}import{execFileSync as Ni}from"child_process";import{existsSync as Vi,readdirSync as Xt}from"fs";import{extname as Kt,join as Zt}from"path";var en=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),$i=[{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 He(e){let t=[],n=Gi(e),r=Hi(e);for(let i of $i){if(Ui(e,i.files)){t.push(i.language);continue}if(Bi(n,i.globs)){t.push(i.language);continue}Ji(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&Qt(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&Qt(t,"c"),t}function Gi(e){try{return Xt(e)}catch{return[]}}function Ui(e,t){return t?.length?t.some(n=>Vi(Zt(e,n))):!1}function Bi(e,t){return t?.length?e.some(n=>t.some(r=>Wi(n,r))):!1}function Wi(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 Hi(e){let t=qi(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=Xt(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=Zt(i,a.name);if(a.isDirectory()){en.has(a.name)||r.push(s);continue}let c=Kt(a.name).toLowerCase();c&&n.add(c)}}return n}function qi(e){try{let t=Ni("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(`
|
|
62
|
+
`)){if(!r||r.split("/").some(o=>en.has(o)))continue;let i=Kt(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function Ji(e,t){return t?.length?t.some(n=>e.has(n)):!1}function Qt(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{readFileSync as rn,writeFileSync as on}from"fs";import{create as Je}from"@bufbuild/protobuf";import{deserializeSCIP as an,serializeSCIP as sn,DocumentSchema as to,IndexSchema as no,SymbolInformationSchema as ro}from"@c4312/scip";import{readFileSync as zi,writeFileSync as Yi}from"fs";import{create as tn}from"@bufbuild/protobuf";import{deserializeSCIP as Qi,DocumentSchema as Xi,IndexSchema as Ki,serializeSCIP as Zi,SymbolRole as eo}from"@c4312/scip";function nn(e){let t;try{t=Qi(zi(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=qe(t);return n.removedDefinitionOccurrences>0&&Yi(e,Buffer.from(Zi(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function qe(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&eo.Definition)===0||t.has(s.symbol)?!0:(n+=1,!1));if(a.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(tn(Xi,{language:o.language,relativePath:o.relativePath,occurrences:a,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:tn(Ki,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function ze(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=io(e),n=oo(e.flatMap(i=>i.documents??[])),r=un(e.flatMap(i=>i.externalSymbols??[]));return Je(no,{metadata:t,documents:n,externalSymbols:r})}function Ye(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>an(rn(i))),r=ze(n);return on(t,Buffer.from(sn(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function cn(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>an(rn(i))),r=qe(ze(n));return on(t,Buffer.from(sn(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function io(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 oo(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,Je(to,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:ao([...r.occurrences,...n.occurrences]),symbols:un([...r.symbols,...n.symbols]),text:co(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function ao(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 un(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,Je(ro,{symbol:r.symbol,documentation:uo([...r.documentation,...n.documentation]),relationships:so([...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 so(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 co(e,t){return e?t?e.length>=t.length?e:t:e:t}function uo(e){return[...new Set(e)]}import{createHash as lo}from"crypto";import{copyFileSync as po,existsSync as ln,rmSync as dn}from"fs";import{resolve as go}from"path";import fn from"better-sqlite3";var fo={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}]},mo={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 mn(e){let t=Date.now(),n=ho(e.affectedFiles);if(yo(e.previousDbPath,e.miniDbPath,e.candidateDbPath),dn(e.candidateDbPath,{force:!0}),!ln(e.previousDbPath))throw new Error("previous SQLite generation is unavailable");if(!ln(e.miniDbPath))throw new Error("incremental SQLite mini database is unavailable");pn(e.previousDbPath,"previous SQLite generation",!1),pn(e.miniDbPath,"incremental SQLite mini database"),po(e.previousDbPath,e.candidateDbPath);let r=null;try{r=new fn(e.candidateDbPath,{fileMustExist:!0}),r.pragma("busy_timeout = 5000"),r.pragma("foreign_keys = ON"),r.prepare("ATTACH DATABASE ? AS incremental").run(e.miniDbPath),Qe(r,"main","candidate SQLite generation"),Qe(r,"incremental","incremental SQLite mini database"),So(r,n),bo(r,n.length);let i=Xe(r,"main",!0),o=j(r,"SELECT COUNT(*) AS value FROM main.documents");r.transaction(()=>{Ro(r),xo(r),vo(r),e.onStage?.("after-delete"),Po(r),e.onStage?.("after-symbol-reconciliation"),Io(r),e.onStage?.("after-insert"),wo(r),To(r,n.length,o),e.onStage?.("before-commit")}).immediate(),hn(r,"main","candidate SQLite generation");let c=[...Eo(r)].filter(([u,l])=>i.get(u)!==l).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{dn(e.candidateDbPath,{force:!0})}throw new Error(`Incremental SQLite publication rejected: ${i instanceof Error?i.message:String(i)}`,{cause:i})}}function ho(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 yo(e,t,n){let r=[e,t,n].map(i=>go(i));if(new Set(r).size!==r.length)throw new Error("previous, mini, and candidate SQLite paths must be distinct")}function pn(e,t,n=!0){let r=new fn(e,{readonly:!0,fileMustExist:!0});try{Qe(r,"main",t),n&&hn(r,"main",t)}finally{r.close()}}function Qe(e,t,n){for(let[r,i]of Object.entries(fo)){let a=e.prepare(`PRAGMA ${t}.table_info('${r}')`).all().map(({name:s,type:c,notnull:u,pk:l})=>({name:s,type:c.toUpperCase(),notnull:u,pk:l}));if(JSON.stringify(a)!==JSON.stringify(i))throw new Error(`${n} schema changed for table ${r}`)}for(let[r,i]of Object.entries(mo)){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}`)}gn(e,t,"documents",["relative_path"],n),gn(e,t,"global_symbols",["symbol"],n)}function gn(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 hn(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 So(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 bo(e,t){let n=j(e,"SELECT COUNT(*) AS value FROM incremental.documents"),r=j(e,`SELECT COUNT(*) AS value
|
|
63
|
+
FROM main.documents d
|
|
64
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path`),i=e.prepare(`SELECT p.relative_path
|
|
65
|
+
FROM temp.incremental_affected_paths p
|
|
66
|
+
LEFT JOIN incremental.documents d ON d.relative_path = p.relative_path
|
|
67
|
+
WHERE d.id IS NULL
|
|
68
|
+
LIMIT 1`).pluck().get(),o=e.prepare(`SELECT d.relative_path
|
|
69
|
+
FROM incremental.documents d
|
|
70
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
71
|
+
WHERE p.relative_path IS NULL
|
|
72
|
+
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 Ro(e){e.exec(`
|
|
73
|
+
CREATE TEMP TABLE incremental_old_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
74
|
+
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
75
|
+
SELECT g.symbol
|
|
76
|
+
FROM main.defn_enclosing_ranges r
|
|
77
|
+
JOIN main.documents d ON d.id = r.document_id
|
|
78
|
+
JOIN main.global_symbols g ON g.id = r.symbol_id
|
|
79
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path;
|
|
80
|
+
INSERT OR IGNORE INTO temp.incremental_old_defined_symbols(symbol)
|
|
81
|
+
SELECT g.symbol
|
|
82
|
+
FROM main.mentions m
|
|
83
|
+
JOIN main.chunks c ON c.id = m.chunk_id
|
|
84
|
+
JOIN main.documents d ON d.id = c.document_id
|
|
85
|
+
JOIN main.global_symbols g ON g.id = m.symbol_id
|
|
86
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
87
|
+
WHERE m.role = 1;
|
|
88
|
+
|
|
89
|
+
CREATE TEMP TABLE incremental_new_defined_symbols (symbol TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
90
|
+
INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
|
|
91
|
+
SELECT g.symbol
|
|
92
|
+
FROM incremental.defn_enclosing_ranges r
|
|
93
|
+
JOIN incremental.global_symbols g ON g.id = r.symbol_id;
|
|
94
|
+
INSERT OR IGNORE INTO temp.incremental_new_defined_symbols(symbol)
|
|
95
|
+
SELECT g.symbol
|
|
96
|
+
FROM incremental.mentions m
|
|
97
|
+
JOIN incremental.global_symbols g ON g.id = m.symbol_id
|
|
98
|
+
WHERE m.role = 1;
|
|
99
|
+
`)}function xo(e){let t=e.prepare(`WITH changed_symbols AS (
|
|
100
|
+
SELECT symbol FROM temp.incremental_old_defined_symbols
|
|
101
|
+
UNION
|
|
102
|
+
SELECT symbol FROM temp.incremental_new_defined_symbols
|
|
103
|
+
), unaffected_definitions AS (
|
|
104
|
+
SELECT g.symbol
|
|
105
|
+
FROM main.defn_enclosing_ranges r
|
|
106
|
+
JOIN main.documents d ON d.id = r.document_id
|
|
107
|
+
JOIN main.global_symbols g ON g.id = r.symbol_id
|
|
108
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
109
|
+
WHERE p.relative_path IS NULL
|
|
110
|
+
UNION
|
|
111
|
+
SELECT g.symbol
|
|
112
|
+
FROM main.mentions m
|
|
113
|
+
JOIN main.chunks c ON c.id = m.chunk_id
|
|
114
|
+
JOIN main.documents d ON d.id = c.document_id
|
|
115
|
+
JOIN main.global_symbols g ON g.id = m.symbol_id
|
|
116
|
+
LEFT JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
117
|
+
WHERE m.role = 1 AND p.relative_path IS NULL
|
|
118
|
+
)
|
|
119
|
+
SELECT u.symbol
|
|
120
|
+
FROM unaffected_definitions u
|
|
121
|
+
JOIN changed_symbols c ON c.symbol = u.symbol
|
|
122
|
+
LIMIT 1`).pluck().get();if(typeof t=="string")throw new Error(`symbol definition is shared by affected and unaffected documents: ${t}`)}function vo(e){e.exec(`
|
|
123
|
+
DELETE FROM main.mentions
|
|
124
|
+
WHERE chunk_id IN (
|
|
125
|
+
SELECT c.id
|
|
126
|
+
FROM main.chunks c
|
|
127
|
+
JOIN main.documents d ON d.id = c.document_id
|
|
128
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
129
|
+
);
|
|
130
|
+
DELETE FROM main.chunks
|
|
131
|
+
WHERE document_id IN (
|
|
132
|
+
SELECT d.id
|
|
133
|
+
FROM main.documents d
|
|
134
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
135
|
+
);
|
|
136
|
+
DELETE FROM main.defn_enclosing_ranges
|
|
137
|
+
WHERE document_id IN (
|
|
138
|
+
SELECT d.id
|
|
139
|
+
FROM main.documents d
|
|
140
|
+
JOIN temp.incremental_affected_paths p ON p.relative_path = d.relative_path
|
|
141
|
+
);
|
|
142
|
+
DELETE FROM main.documents
|
|
143
|
+
WHERE relative_path IN (SELECT relative_path FROM temp.incremental_affected_paths);
|
|
144
|
+
`)}function Po(e){e.exec(`
|
|
145
|
+
UPDATE main.global_symbols
|
|
146
|
+
SET display_name = NULL,
|
|
147
|
+
kind = NULL,
|
|
148
|
+
documentation = NULL,
|
|
149
|
+
signature = NULL,
|
|
150
|
+
enclosing_symbol = NULL,
|
|
151
|
+
relationships = NULL
|
|
152
|
+
WHERE symbol IN (SELECT symbol FROM temp.incremental_old_defined_symbols);
|
|
153
|
+
|
|
154
|
+
INSERT OR IGNORE INTO main.global_symbols(
|
|
155
|
+
symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
|
|
156
|
+
)
|
|
157
|
+
SELECT symbol, display_name, kind, documentation, signature, enclosing_symbol, relationships
|
|
158
|
+
FROM incremental.global_symbols;
|
|
159
|
+
|
|
160
|
+
UPDATE main.global_symbols
|
|
161
|
+
SET display_name = (
|
|
162
|
+
SELECT source.display_name FROM incremental.global_symbols source
|
|
163
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
164
|
+
),
|
|
165
|
+
kind = (
|
|
166
|
+
SELECT source.kind FROM incremental.global_symbols source
|
|
167
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
168
|
+
),
|
|
169
|
+
documentation = (
|
|
170
|
+
SELECT source.documentation FROM incremental.global_symbols source
|
|
171
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
172
|
+
),
|
|
173
|
+
signature = (
|
|
174
|
+
SELECT source.signature FROM incremental.global_symbols source
|
|
175
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
176
|
+
),
|
|
177
|
+
enclosing_symbol = (
|
|
178
|
+
SELECT source.enclosing_symbol FROM incremental.global_symbols source
|
|
179
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
180
|
+
),
|
|
181
|
+
relationships = (
|
|
182
|
+
SELECT source.relationships FROM incremental.global_symbols source
|
|
183
|
+
WHERE source.symbol = main.global_symbols.symbol
|
|
184
|
+
)
|
|
185
|
+
WHERE symbol IN (SELECT symbol FROM temp.incremental_new_defined_symbols);
|
|
186
|
+
`)}function Io(e){let t=j(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.documents"),n=j(e,"SELECT COALESCE(MAX(id), 0) AS value FROM main.chunks"),r=j(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)
|
|
187
|
+
SELECT id + ?, language, relative_path, position_encoding, text
|
|
188
|
+
FROM incremental.documents`).run(t),e.prepare(`INSERT INTO main.chunks(id, document_id, chunk_index, start_line, end_line, occurrences)
|
|
189
|
+
SELECT id + ?, document_id + ?, chunk_index, start_line, end_line, occurrences
|
|
190
|
+
FROM incremental.chunks`).run(n,t),e.prepare(`INSERT INTO main.mentions(chunk_id, symbol_id, role)
|
|
191
|
+
SELECT m.chunk_id + ?, target.id, m.role
|
|
192
|
+
FROM incremental.mentions m
|
|
193
|
+
JOIN incremental.global_symbols source ON source.id = m.symbol_id
|
|
194
|
+
JOIN main.global_symbols target ON target.symbol = source.symbol`).run(n),e.prepare(`INSERT INTO main.defn_enclosing_ranges(
|
|
195
|
+
id, document_id, symbol_id, start_line, start_char, end_line, end_char
|
|
196
|
+
)
|
|
197
|
+
SELECT r.id + ?, r.document_id + ?, target.id,
|
|
198
|
+
r.start_line, r.start_char, r.end_line, r.end_char
|
|
199
|
+
FROM incremental.defn_enclosing_ranges r
|
|
200
|
+
JOIN incremental.global_symbols source ON source.id = r.symbol_id
|
|
201
|
+
JOIN main.global_symbols target ON target.symbol = source.symbol`).run(r,t)}function wo(e){e.exec(`
|
|
202
|
+
DELETE FROM main.global_symbols
|
|
203
|
+
WHERE NOT EXISTS (SELECT 1 FROM main.mentions m WHERE m.symbol_id = main.global_symbols.id)
|
|
204
|
+
AND NOT EXISTS (
|
|
205
|
+
SELECT 1 FROM main.defn_enclosing_ranges r WHERE r.symbol_id = main.global_symbols.id
|
|
206
|
+
);
|
|
207
|
+
`)}function To(e,t,n){let r=j(e,"SELECT COUNT(*) AS value FROM main.documents"),i=j(e,`SELECT COUNT(*) AS value
|
|
208
|
+
FROM main.documents d
|
|
209
|
+
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 Eo(e){let t=Xe(e,"main",!0),n=Xe(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 Xe(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
|
|
210
|
+
FROM ${t}.documents d
|
|
211
|
+
${r}
|
|
212
|
+
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
|
|
213
|
+
FROM ${t}.chunks c
|
|
214
|
+
JOIN ${t}.documents d ON d.id = c.document_id
|
|
215
|
+
${r}
|
|
216
|
+
ORDER BY d.relative_path, c.chunk_index, c.start_line, c.end_line, c.id`).all(),a=e.prepare(`SELECT d.relative_path, r.start_line, r.start_char, r.end_line, r.end_char,
|
|
217
|
+
g.symbol, g.display_name, g.kind, g.documentation,
|
|
218
|
+
CASE WHEN g.signature IS NULL THEN NULL ELSE hex(g.signature) END AS signature,
|
|
219
|
+
g.enclosing_symbol,
|
|
220
|
+
CASE WHEN g.relationships IS NULL THEN NULL ELSE hex(g.relationships) END AS relationships
|
|
221
|
+
FROM ${t}.defn_enclosing_ranges r
|
|
222
|
+
JOIN ${t}.documents d ON d.id = r.document_id
|
|
223
|
+
JOIN ${t}.global_symbols g ON g.id = r.symbol_id
|
|
224
|
+
${r}
|
|
225
|
+
ORDER BY d.relative_path, r.start_line, r.start_char, r.end_line, r.end_char, g.symbol`).all(),s=e.prepare(`SELECT d.relative_path, c.chunk_index, m.role, g.symbol
|
|
226
|
+
FROM ${t}.mentions m
|
|
227
|
+
JOIN ${t}.chunks c ON c.id = m.chunk_id
|
|
228
|
+
JOIN ${t}.documents d ON d.id = c.document_id
|
|
229
|
+
JOIN ${t}.global_symbols g ON g.id = m.symbol_id
|
|
230
|
+
${r}
|
|
231
|
+
ORDER BY d.relative_path, c.chunk_index, m.role, g.symbol`).all(),c=new Map;for(let[l,p]of Object.entries({documents:i,chunks:o,definitions:a,mentions:s}))for(let d of p){let f=JSON.stringify([l,d]),g=c.get(d.relative_path)??[];g.push(f),c.set(d.relative_path,g)}let u=new Map;for(let[l,p]of[...c].sort(([d],[f])=>d.localeCompare(f))){let d=lo("sha256");for(let f of p.sort())d.update(f).update(`
|
|
232
|
+
`);u.set(l,d.digest("hex"))}return u}function j(e,t){return e.prepare(t).get().value}import{readFileSync as ko,writeFileSync as Do}from"fs";function O(e,t){let n=Date.now(),r=e.run(t);return{stageId:e.id,facts:e.facts,durationMs:Date.now()-n,result:r}}function Sn(e){let t=e.readFingerprint(),n=Fo(e.cachePath,t);if(n)return e.onCacheHit?.(n.result),n.result;let r=e.compute();return jo(e.cachePath,e.readFingerprint(),r),r}function Fo(e,t){try{let n=JSON.parse(ko(e,"utf-8"));return yn(n.fingerprint)===yn(t)?{result:n.result}:null}catch{return null}}function jo(e,t,n){Do(e,`${JSON.stringify({updatedAt:new Date().toISOString(),fingerprint:t,result:n},null,2)}
|
|
233
|
+
`)}function yn(e){return JSON.stringify(e)}import{createHash as Oo}from"crypto";import{existsSync as Ke,readFileSync as _o,readdirSync as Mo}from"fs";import{dirname as Ze,join as le,relative as Lo,resolve as et,sep as bn}from"path";function Rn(e,t){let n=t.includes("."),r={};for(let o of t)r[o]=[];let i=[];for(let o of e){let a=In(o.path,t);a?r[a].push(o):n?r["."].push(o):i.push(o)}return{files:r,shared:i}}function xn(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=In(s,e);c&&c!==i&&a.add(c)}}return Co(e,r)}function vn(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 tt(e){if(e===".")return"root";let t=Oo("sha256").update(e).digest("hex").slice(0,8);return`${e.split("/").join("__")}-${t}`}function Pn(e,t){let n=et(e),r={};for(let i of t)r[i]=Ao(n,i);return r}function In(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 Co(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 Ao(e,t){let n=t==="."?e:le(e,t),r=No(n),i=Vo(n),o=i?$o(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 No(e){let t=le(e,"package.json");if(!Ke(t))return{name:void 0,dependencyNames:[],failed:!1};let n=nt(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 Vo(e){let t=le(e,"tsconfig.json");if(Ke(t))return t;let n;try{n=Mo(e).filter(r=>/^tsconfig.*\.json$/.test(r))}catch{return}return n.sort((r,i)=>r.localeCompare(i)),n.length>0?le(e,n[0]):void 0}function $o(e,t){let n=nt(e);if(!n.ok)return{pathsTargets:[],referencesPaths:[],failed:!0};let r=Go(n.value,e,t),i=wn(e,n.value,t,0);return{pathsTargets:i.pathsTargets,referencesPaths:r,failed:i.failed}}function Go(e,t,n){let r=e.references;if(!Array.isArray(r))return[];let i=Ze(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=Tn(s,i,n);c&&o.add(c)}return[...o]}function wn(e,t,n,r){let i=Uo(t);if(i)return{pathsTargets:Bo(i,Ze(e),n),failed:!1};if(r>=5)return{pathsTargets:[],failed:!1};let o=Wo(t.extends,e,n);if(!o)return{pathsTargets:[],failed:!1};let a=nt(o);return a.ok?wn(o,a.value,n,r+1):{pathsTargets:[],failed:!0}}function Uo(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 Bo(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=Tn(o,t,n);a&&r.add(a)}return[...r]}function Wo(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=et(Ze(t),r);if(i.endsWith(".json")||(i=`${i}.json`),!i.split(bn).includes("node_modules")&&U(n,i)&&Ke(i))return i}function Tn(e,t,n){let r=e.replace(/\/?\*+$/,""),i=et(t,r===""?".":r);if(!U(n,i))return;let a=Lo(n,i).split(bn).join("/");return a===""?".":a}function Ho(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]!==`
|
|
234
|
+
`;)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 nt(e){try{let t=_o(e,"utf-8"),n=JSON.parse(Ho(t));return n&&typeof n=="object"&&!Array.isArray(n)?{ok:!0,value:n}:{ok:!1}}catch{return{ok:!1}}}import{createHash as qo}from"crypto";import{copyFileSync as En,existsSync as _,linkSync as Jo,mkdirSync as kn,readFileSync as jn,readdirSync as Dn,renameSync as it,rmSync as pe,statSync as zo}from"fs";import{basename as de,dirname as q,join as S,relative as Fn}from"path";var ge=1,Yo=".scipquery-generations";function On(e){let t=me(e.outputDb),n=Qo(e,t);e.onStage?.("after-recovery-retained"),e.preserveOutputScip||rt(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),rt(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),rt(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let r=he(e.metaPath,e.outputDb),i={version:ge,currentGeneration:r,...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:(e.now??(()=>new Date))().toISOString()};return R(S(t,"state.json"),i,{spacing:2,trailingNewline:!0}),{currentGeneration:r,...n?{previousGeneration:n}:{}}}function _n(e){try{let t=JSON.parse(jn(S(me(e),"state.json"),"utf8"));return t.version!==ge||typeof t.currentGeneration!="string"||!t.currentGeneration||typeof t.publishedAt!="string"||!Number.isFinite(Date.parse(t.publishedAt))||!Zo(t.previousGeneration)||!ea(t.publication)?null:t}catch{return null}}function Mn(e,t,n=()=>new Date){if(!_(e)||!_(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=_n(e),i={version:ge,currentGeneration:he(t,e),...r?.previousGeneration?{previousGeneration:r.previousGeneration}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return R(S(me(e),"state.json"),i,{spacing:2,trailingNewline:!0}),i}function fe(e,t=S(q(e),"meta.json")){let n=S(me(e),"state.json");if(!_(n))return{state:"legacy",statePath:n};let r=_n(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=he(t,e),o=r.currentGeneration===i,a=r.previousGeneration?_(S(q(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 me(e){return S(q(e),Yo)}function Qo(e,t){if(!_(e.outputDb))return;let n=he(e.metaPath,e.outputDb),r=S(t,n),i=S(r,de(e.outputDb)),o=_(e.metaPath)?S(r,de(e.metaPath)):void 0;if(!_(i)){let a=`${r}.${process.pid}.${Date.now()}.tmp`;pe(a,{recursive:!0,force:!0}),kn(a,{recursive:!0});let s=S(a,de(e.outputDb));try{Jo(e.outputDb,s)}catch{En(e.outputDb,s)}o&&En(e.metaPath,S(a,de(e.metaPath))),kn(t,{recursive:!0}),it(a,r)}return Xo(t,n),{generationIdentity:n,databasePath:Fn(q(e.outputDb),i),...o?{metadataPath:Fn(q(e.outputDb),o)}:{}}}function Xo(e,t){for(let n of Dn(e,{withFileTypes:!0}))!n.isDirectory()||n.name===t||n.name.endsWith(".tmp")||pe(S(e,n.name),{recursive:!0,force:!0});for(let n of Dn(e,{withFileTypes:!0}))n.isDirectory()&&n.name.endsWith(".tmp")&&pe(S(e,n.name),{recursive:!0,force:!0})}function he(e,t){let n=qo("sha256").update(`sqlite-generation-v${ge}\0`);_(e)&&n.update(Ko(jn(e,"utf8")));let r=zo(t);return n.update(`\0${r.size}`),n.digest("hex")}function Ko(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 rt(e,t){pe(`${t}.tmp-replace`,{force:!0}),it(e,`${t}.tmp-replace`),it(`${t}.tmp-replace`,t)}function Zo(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 ea(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")}import{createHash as la}from"crypto";import{existsSync as J,mkdirSync as da,readFileSync as Y,readdirSync as ut,renameSync as pa,rmSync as tr,writeFileSync as ga}from"fs";import{join as I}from"path";import{createHash as ta}from"crypto";import{existsSync as at,mkdirSync as na,readFileSync as ye,readdirSync as Ku,renameSync as ra,rmSync as Zu,writeFileSync as ia}from"fs";import{join as $}from"path";import{create as Cn,fromBinary as An,toBinary as oa}from"@bufbuild/protobuf";import{deserializeSCIP as Se,DocumentSchema as st,IndexSchema as Nn,serializeSCIP as Vn}from"@c4312/scip";var $n=1,aa="typescript-scip-fragments";function Gn(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=A(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=An(st,o.bytes);if(s.relativePath!==a)throw new Error(`TypeScript fragment path mismatch: expected ${a}, got ${s.relativePath}`);n.push(s)}let r=Vn(Cn(Nn,{documents:n,externalSymbols:[]})),i=Se(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function be(e){let t=$(e,aa);return{rootDir:t,blobDir:$(t,"blobs"),generationDir:$(t,"generations")}}function sa(e){let t=Se(e.indexBytes);Zn(t.metadata,er(e)),Kn(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let a=A(o.relativePath);if(n.has(a))throw new Error(`duplicate TypeScript SCIP document path: ${a}`);n.add(a);let s=oa(st,o),c=e.documentIdentities.get(a)??(e.allowUntrackedDocuments?N(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:a,contentHash:N(s)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${a}`);r.push(zn(e.cacheDir,{relativePath:a,bytes:s,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=Yn(e,r);return Qn(e.cacheDir,i),i}function Un(e){let t=be(e.cacheDir);if(!at(ct(t,e.generationIdentity)))return sa(e);let n=Wn({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 Bn(e){let t=Wn({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=A(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,zn(e.cacheDir,o,s))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=Yn(e,[...n.values()]);return Qn(e.cacheDir,i),i}function Wn(e){let t=be(e.cacheDir),n=ct(t,e.generationIdentity),r;try{r=Xn(ye(n,"utf8"))}catch(o){throw new Error(`TypeScript fragment generation is unavailable: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(r.generationIdentity!==e.generationIdentity)throw new Error("TypeScript fragment generation identity does not match its manifest path");if(e.producerIdentity&&r.producerIdentity!==e.producerIdentity)throw new Error("TypeScript fragment producer identity changed");if(e.projectIdentity&&r.projectIdentity!==e.projectIdentity)throw new Error("TypeScript fragment project identity changed");let i=new Map;for(let o of r.documents){let a=$(t.blobDir,`${o.blobHash}.scipdoc`),s=ye(a);if(s.byteLength!==o.byteLength||N(s)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,s)}return{manifest:r,fragments:i}}function Hn(e){let t=Jn(e);return ot(t.baseIndex,t.completeDocuments,"assembled")}function qn(e){let t=Jn(e);return ca(t.deletedAffectedPaths),{completeIndexBytes:ot(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:ot(t.baseIndex,t.affectedDocuments,"affected")}}function Jn(e){let t=Se(e.baseIndexBytes);Zn(t.metadata,er(e)),Kn(t.externalSymbols);let n=new Map;for(let s of e.fragments){let c=A(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=A(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 l=An(st,u.bytes);if(l.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${l.relativePath}`);i.push(l),o.push(l)}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=Vn(Cn(Nn,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=Se(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function ca(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function zn(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=A(t.relativePath),i=Buffer.from(t.bytes),o=N(i),a=be(e);na(a.blobDir,{recursive:!0});let s=$(a.blobDir,`${o}.scipdoc`);if(at(s)){let c=ye(s);if(c.byteLength!==i.byteLength||N(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${s}.${process.pid}.${Date.now()}.tmp`;ia(c,i),ra(c,s)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function Yn(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:$n,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function Qn(e,t){let n=be(e),r=ct(n,t.generationIdentity);if(at(r)){let i=Xn(ye(r,"utf8"));if(Ln(i)!==Ln(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}R(r,t,{spacing:2,trailingNewline:!0})}function Ln(e){return N(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function Xn(e){let t=JSON.parse(e);if(t.version!==$n||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(A(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function ct(e,t){return $(e.generationDir,ua(t))}function ua(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${N(e)}.json`}function Kn(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function Zn(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 er(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function A(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 N(e){return ta("sha256").update(e).digest("hex")}var rr=1,ir=64*1024*1024,fa="typescript-scip-overlays";function or(e){let t=cr(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=pt(o.relativePath);if(r.has(a))throw new Error(`duplicate TypeScript overlay: ${a}`);r.add(a),n.set(a,ma(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:rr,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 ha(e.cacheDir,i),i}function ar(e){let t=cr(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=Y(I(Q(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||z(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 Hn({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function sr(e,t){let n=Q(e),r=I(n,"generations");if(!J(r))return;let i=new Set(t.map(dt)),o=new Set;for(let s of ut(r).filter(c=>i.has(c))){let c=lt(Y(I(r,s),"utf8"));for(let u of c.overlays)u.blobHash&&o.add(`${u.blobHash}.scipdoc`)}for(let s of ut(r))i.has(s)||tr(I(r,s),{force:!0});let a=I(n,"blobs");if(J(a))for(let s of ut(a))o.has(s)||tr(I(a,s),{force:!0})}function cr(e,t){let n=I(Q(e),"generations",dt(t));if(!J(n))return null;let r=lt(Y(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function ma(e,t){let n=pt(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=z(r),o=I(Q(e),"blobs");da(o,{recursive:!0});let a=I(o,`${i}.scipdoc`);if(J(a)){let s=Y(a);if(s.byteLength!==r.byteLength||z(s)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let s=`${a}.${process.pid}.${Date.now()}.tmp`;ga(s,r),pa(s,a)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function ha(e,t){let n=I(Q(e),"generations",dt(t.generationIdentity));if(J(n)){let r=lt(Y(n,"utf8"));if(nr(r)!==nr(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}R(n,t,{spacing:2,trailingNewline:!0})}function lt(e){let t=JSON.parse(e);if(t.version!==rr||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(pt(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function Q(e){return I(e,fa)}function dt(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${z(e)}.json`}function nr(e){return z(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function pt(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 z(e){return la("sha256").update(e).digest("hex")}import{existsSync as ya,readFileSync as Sa,readdirSync as ba,statSync as Ra}from"fs";import h from"path";var xa=new Set([".cache",".git",".next",".nuxt",".turbo",".nx","build","coverage","dist","node_modules","tmp","vendor"]);function X(e,t=[]){let n=h.resolve(e),r=t.flatMap(c=>Pa(n,c));if(r.length>0)return ur(n,lr(r));let i=va(n),o=lr(i),a=wa(n,o)?[n,...o]:o,s=a.length>0?a:[n];return ur(n,s)}function ur(e,t){return[...new Set(t.map(n=>Ea(e,n)))].sort((n,r)=>n.localeCompare(r))}function va(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop(),i;try{i=ba(r,{withFileTypes:!0})}catch{continue}for(let o of i){let a=h.join(r,o.name);if(o.isDirectory()){!xa.has(o.name)&&!o.name.startsWith(".")&&n.push(a);continue}o.isFile()&&Ia(a)&&t.push(h.dirname(a))}}return t}function Pa(e,t){let n=t.trim();if(!n)return[];let r=h.resolve(e,n);if(!U(e,r))return[];try{let i=Ra(r);if(i.isDirectory())return[r];if(i.isFile()&&dr(h.basename(r)))return[h.dirname(r)]}catch{return[]}return[]}function Ia(e){if(!dr(h.basename(e)))return!1;let t=pr(e);return t?h.basename(e)==="tsconfig.json"||"include"in t||"files"in t||"references"in t:!1}function dr(e){return e.startsWith("tsconfig")&&e.endsWith(".json")}function lr(e){let t=[...new Set(e.map(n=>h.resolve(n)))].sort((n,r)=>n.localeCompare(r));return t.length<=1?t:t.filter(n=>!t.some(r=>r!==n&&ka(n,r)))}function wa(e,t){if(t.length===0||t.some(r=>h.resolve(r)===e))return!1;let n=h.join(e,"tsconfig.json");return ya(n)&&Ta(n)}function Ta(e){let n=pr(e)?.include;return Array.isArray(n)?n.some(r=>typeof r=="string"&&r.trim()!==""&&!r.startsWith("!")&&(r.includes("/")||r.includes("**")||!h.extname(r))):!1}function pr(e){try{let t=JSON.parse(Sa(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Ea(e,t){let n=h.relative(e,t);return n?n.split(h.sep).join("/"):"."}function ka(e,t){let n=h.relative(e,t);return!!n&&!n.startsWith("..")&&!h.isAbsolute(n)}import{createHash as Ya}from"crypto";import{existsSync as mt,readFileSync as Ir,statSync as Qa,writeFileSync as ht}from"fs";import{join as Xa}from"path";import{readFileSync as gr}from"fs";import{createRequire as Da}from"module";import{dirname as Fa,isAbsolute as Sl,relative as bl,resolve as Rl,sep as xl}from"path";var fr=Da(import.meta.url),ja=1,mr="0.4.0";function gt(){let e=Oa();return e.available?{available:!0,packageVersion:e.packageVersion,typescriptVersion:e.typescriptVersion,producerIdentity:e.producerIdentity}:e}function Oa(){try{let e=fr.resolve("@sourcegraph/scip-typescript/package.json"),t=JSON.parse(gr(e,"utf8"));if(t.version!==mr)return{available:!1,reason:`unsupported scip-typescript version ${String(t.version??"unknown")}; expected ${mr}`};let n=Fa(e),r=fr.resolve("typescript/package.json",{paths:[n]}),i=JSON.parse(gr(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:_a(t.version,i.version)}}catch(e){return{available:!1,reason:`scip-typescript document producer unavailable: ${e instanceof Error?e.message:String(e)}`}}}function _a(e,t){return`scip-typescript:${e}:typescript:${t}:document-adapter:${ja}`}import{createHash as Ma}from"crypto";import{readFileSync as La}from"fs";import{dirname as Ca,join as Re}from"path";var xe=2,Aa="typescript-index";function hr(e){let t=Re(e,Aa);return{rootDir:t,requestDir:Re(t,"requests"),responseDir:Re(t,"responses")}}function yr(e){try{let t=JSON.parse(La(Re(Ca(e),"meta.json"),"utf8"));return t.version!==2&&t.version!==3||t.status!=="complete"||typeof t.updatedAt!="string"||t.fingerprint===void 0?null:Ma("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 Na}from"crypto";import{existsSync as Va,mkdirSync as Sr,readFileSync as $a,rmSync as br}from"fs";import{resolve as ft}from"path";var Ga=12e4,Ua=5,ve=class{projectRoot;cacheDir;baseGeneration;timeoutMs;runtime;constructor(t,n={}){this.projectRoot=ft(t.projectRoot),this.cacheDir=t.cacheDir,this.baseGeneration=t.baseGeneration,this.timeoutMs=n.timeoutMs??Ja(),this.runtime=n.runtime??za}request(t){let n=At(this.cacheDir),r=hr(this.cacheDir),i=Ne(n.statePath);if(!Rr(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript index service is not running.");let o=this.runtime.randomId(),a=ft(r.requestDir,`${o}.json`),s=ft(r.responseDir,`${o}.json`),c=this.runtime.now()+this.timeoutMs;Sr(r.requestDir,{recursive:!0}),Sr(r.responseDir,{recursive:!0}),R(a,{protocolVersion:xe,id:o,baseGeneration:this.baseGeneration,deadlineAtMs:c,request:t});try{for(;this.runtime.now()<=c;){if(Va(s))return Ba($a(s,"utf8"),o,this.baseGeneration,t.producerIdentity,t.affectedFiles);let u=Ne(n.statePath);if(!Rr(u,this.projectRoot,this.runtime))throw new Error("TypeScript index service stopped while processing a request.");this.runtime.sleep(Ua)}throw new Error(`TypeScript index service timed out after ${this.timeoutMs}ms.`)}finally{br(a,{force:!0}),br(s,{force:!0})}}};function Rr(e,t,n){let r=e!==null&&n.now()-Date.parse(e.heartbeatAt)<=Ct,i=e?.typescriptIndex?.busyUntil!==void 0&&n.now()<=Date.parse(e.typescriptIndex.busyUntil);return e!==null&&e.projectRoot===t&&e.typescriptIndex?.protocolVersion===xe&&n.isProcessAlive(e.pid)&&(r||i)}function Ba(e,t,n,r,i){let o=JSON.parse(e);if(o.protocolVersion!==xe||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=Wa(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 Wa(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(Ha)||r.has(o.relativePath))throw new Error("TypeScript index service wrote an invalid fragment.");r.add(o.relativePath);let a=o.bytesBase64===null?null:qa(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 Ha(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 qa(e){let t=Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("TypeScript index service wrote invalid base64.");return t}function Ja(){let e=Number(process.env.SCIP_TYPESCRIPT_INDEX_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:Ga}var za={now:Date.now,randomId:Na,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:V};function Ka(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=ae(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"||!Ve(u.path)))return{eligible:!1,reason:"change is not a modified TypeScript source file"};let r=se(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=Za([...r.changedFiles,...r.affectedFiles],t);if(!i)return{eligible:!1,reason:"affected files cross or ambiguously match TypeScript projects"};let o=xr(e.currentSnapshot,e.projectFiles,e.producerIdentity),a=xr(e.previousSnapshot,e.projectFiles,e.producerIdentity);if(o!==a)return{eligible:!1,reason:"TypeScript fragment project identity changed"};let s=Pr(e.previousSnapshot,e.projectFiles,e.graph,e.producerIdentity,e.projectFiles);if(!s)return{eligible:!1,reason:"prior document identity unavailable"};let c=Pr(e.currentSnapshot,e.projectFiles,e.graph,e.producerIdentity,r.affectedFiles);return c?{eligible:!0,manifest:n,plan:r,projectIdentity:o,previousFragmentGeneration:vr(e.previousSnapshot,e.producerIdentity),nextFragmentGeneration:vr(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 Za(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 wr(e){let t=Date.now();try{if(!mt(e.previousDbPath)||!mt(e.previousShardPath))throw new Error("prior TypeScript graph or language shard unavailable");let n=performance.now(),r=gt();if(!r.available)throw new Error(r.reason);let i=performance.now()-n;n=performance.now();let o=new L({projectRoot:e.projectRoot,dbPath:e.previousDbPath,indexPath:e.previousIndexPath}),a,s;try{a=re(o,{includeIgnored:!1}).filter(Ve).sort(),s=ie(o)}finally{o.close()}let c=performance.now()-n,u=Ka({projectMode:e.projectMode,workspaceProjects:e.projectMode==="workspace"?X(e.projectRoot,e.currentSnapshot.typescriptProjects):void 0,previousSnapshot:e.previousSnapshot,currentSnapshot:e.currentSnapshot,projectFiles:a,graph:s,producerIdentity:r.producerIdentity,rootTsconfigExists:mt(Xa(e.projectRoot,"tsconfig.json"))});if(!u.eligible)throw new Error(u.reason);let l=yr(e.previousDbPath);if(!l)throw new Error("published TypeScript base generation unavailable");n=performance.now();let d=new ve({projectRoot:e.projectRoot,cacheDir:e.cacheDir,baseGeneration:l}).request({kind:"emit-documents",tsconfigPath:u.tsconfigPath,projectArgument:u.projectArgument,projectIdentity:u.projectIdentity,producerIdentity:r.producerIdentity,modifiedFiles:u.plan.changedFiles,affectedFiles:u.plan.affectedFiles}),f=performance.now()-n,g=Qa(e.previousShardPath).size>=ir;n=performance.now();let w=g?null:Ir(e.previousShardPath),D=g?{completeIndexBytes:null,affectedIndexBytes:Gn(d.fragments)}:qn({packageVersion:r.packageVersion,baseIndexBytes:w,fragments:d.fragments}),F=performance.now()-n;n=performance.now(),g?or({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,nextGenerationIdentity:u.nextFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,baseShardCurrent:e.baseShardCurrent,fragments:d.fragments}):(Un({cacheDir:e.cacheDir,packageVersion:r.packageVersion,indexBytes:w,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.previousFragmentGeneration,documentIdentities:u.previousDocumentIdentities,allowUntrackedDocuments:!0}),Bn({cacheDir:e.cacheDir,previousGenerationIdentity:u.previousFragmentGeneration,producerIdentity:r.producerIdentity,projectIdentity:u.projectIdentity,generationIdentity:u.nextFragmentGeneration,fragments:d.fragments,documentIdentities:u.nextDocumentIdentities}));let y=performance.now()-n;n=performance.now(),D.completeIndexBytes&&ht(e.candidateShardPath,D.completeIndexBytes),ht(e.candidateAffectedScipPath,D.affectedIndexBytes);let x=performance.now()-n,v={scipPath:g?e.previousShardPath:e.candidateShardPath,candidateScipPath:e.candidateShardPath,affectedScipPath:e.candidateAffectedScipPath,completeScipUpdated:!g,durationMs:Date.now()-t,cold:d.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(d.fragments.map(ne=>[ne.relativePath,ne.referenceFragments])),timings:{runtimeMs:i,graphMs:c,requestMs:f,serviceMs:d.durationMs,assemblyMs:F,fragmentStoreMs:y,writeMs:x}};return e.onStatus(`Incremental TypeScript index emitted ${v.affectedFiles.length} affected document(s) in ${(v.durationMs/1e3).toFixed(3)}s (${v.cold?"cold":"warm"} service; ${g?"whole SCIP deferred":"whole SCIP current"}; runtime ${i.toFixed(0)}ms, graph ${c.toFixed(0)}ms, request ${f.toFixed(0)}ms, assembly ${F.toFixed(0)}ms, fragments ${y.toFixed(0)}ms, write ${x.toFixed(0)}ms).`),v}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 Tr(e){let t=gt();if(!t.available)throw new Error(t.reason);let n=ar({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,baseIndexBytes:Ir(e.baseShardPath),packageVersion:t.packageVersion});ht(e.candidateShardPath,n)}function xr(e,t,n){let r=e.files.filter(i=>Lt(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 yt(JSON.stringify({version:1,producerIdentity:n,pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),projectFiles:[...t].sort(),nonSourceInputs:r}))}function vr(e,t){return yt(JSON.stringify({version:1,producerIdentity:t,snapshot:e}))}function Pr(e,t,n,r,i){let o=new Set(e.files.map(c=>c.path)),a=$t({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,yt(JSON.stringify({version:1,producerIdentity:r,generatedDocument:c})))}return s}function yt(e){return Ya("sha256").update(e).digest("hex")}import{execFile as es}from"child_process";import{existsSync as Pe,renameSync as bt,rmSync as Rt,statSync as ts}from"fs";import{cpus as ns}from"os";import{join as Er}from"path";function rs(e,t,n){if(!e.defaultOutputPath)return;let r=Er(t,e.defaultOutputPath);n!==r&&Pe(r)&&bt(r,n)}function is(e,t,n){if(!e.defaultOutputPath)return null;let r=Er(t,e.defaultOutputPath);if(r===n)return null;let i=`${n}.default-output-backup`;return Rt(i,{force:!0}),Pe(r)?(bt(r,i),{defaultOutputPath:r,backupPath:i}):{defaultOutputPath:r,backupPath:null}}function os(e){e&&(Rt(e.defaultOutputPath,{force:!0}),e.backupPath&&Pe(e.backupPath)&&bt(e.backupPath,e.defaultOutputPath))}function as(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,ns().length));return Math.max(1,Math.min(e,Math.floor(r)))}async function kr(e,t,n,r){let i=e.filter(u=>u.config.defaultOutputPath),o=e.filter(u=>!u.config.defaultOutputPath),a=[],s=as(o.length,r),c=await cs(o,s,u=>St(u,t,n));if(s>1){let u=new Map;for(let l of c.filter(p=>p.skipped)){let p=o.find(d=>d.id===l.id);p&&(n(`Retrying ${p.label} indexer serially after parallel failure...`),u.set(p.id,await St(p,t,n)))}a.push(...c.map(l=>u.get(l.id)??l))}else a.push(...c);for(let u of i)a.push(await St(u,t,n));return a.sort((u,l)=>e.findIndex(p=>p.id===u.id)-e.findIndex(p=>p.id===l.id))}async function St(e,t,n){n(`Indexing ${e.label} with ${e.resolvedBinary}...`),Rt(e.scipPath,{force:!0});let r=is(e.config,t,e.scipPath),i=[e.binary,...e.args].join(" "),o=Date.now();try{await ss(e.binary,e.args,{cwd:t,env:e.env,maxBuffer:50*1024*1024}),rs(e.config,t,e.scipPath)}catch(s){let c=s instanceof Error?s.message:String(s),u=`${e.resolvedBinary} indexer failed: ${c.split(`
|
|
235
|
+
`)[0]}`,l=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:l}}}finally{os(r)}if(!Pe(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=ts(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 ss(e,t,n){return new Promise((r,i)=>{es(e,[...t],n,o=>{o?i(o):r()})})}async function cs(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 Bs from"better-sqlite3";import{existsSync as Ws}from"fs";import{dirname as Hs,join as qs,resolve as Js}from"path";import{readFileSync as ls,rmSync as ds,statSync as ps,mkdtempSync as gs}from"fs";import{tmpdir as fs}from"os";import{join as xt}from"path";import{Worker as ms}from"worker_threads";function us(){return{"missing-source-file":0,"missing-service-script":0,"no-definition":0,"same-file-definition":0,"unindexed-definition":0}}function G(){return{skippedReferences:0,skippedReferenceReasons:us(),skippedReferenceSamples:[]}}function Ie(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 Dr(e){return e.length>=8&&jr(e.length)>1}function Fr(e){let t=jr(e.vueFiles.length),n=ys(e.vueFiles),r=bs(n,t),i=new URL("./augment-vue-worker.js",import.meta.url),o=gs(xt(fs(),"scip-query-vue-workers-")),a=new SharedArrayBuffer(4),s=new Int32Array(a),c=hs(),u=Date.now();try{for(let d=0;d<r.length;d++)new ms(i,{workerData:{projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,tasks:r[d],resultPath:xt(o,`${d}.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 l=r.map((d,f)=>{let g=JSON.parse(ls(xt(o,`${f}.json`),"utf-8"));if(!g.ok)throw new Error(`Vue reference worker failed: ${g.error}`);return g.result}),p={occurrences:l.flatMap(d=>d.occurrences),...G()};for(let d of l)Ie(p,d);return p}finally{ds(o,{recursive:!0,force:!0})}}function jr(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 hs(){let e=Number(process.env.SCIP_QUERY_AUGMENT_VUE_WORKER_TIMEOUT_MS??0);return Number.isFinite(e)&&e>0?e:3e5}function ys(e){let t=Ss(),n=[];for(let r of e){let i=Or(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 Ss(){return Number.POSITIVE_INFINITY}function bs(e,t){let n=Array.from({length:t},()=>({tasks:[],weight:0})),r=e.map(i=>({task:i,weight:Rs(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 Rs(e){return Number.isFinite(e.endOffset)?Math.max(1,e.endOffset-e.startOffset):Math.max(1,Or(e.fileName)-e.startOffset)}function Or(e){try{return ps(e).size}catch{return 1}}import{createRequire as xs}from"module";import{existsSync as vs,readFileSync as Pt}from"fs";import{dirname as _r,extname as Ps,join as Mr,relative as Is,resolve as ws}from"path";import{pathToFileURL as Ts}from"url";function Es(e){e.transaction(()=>{e.prepare(`
|
|
9
236
|
DELETE FROM mentions
|
|
10
237
|
WHERE chunk_id IN (
|
|
11
238
|
SELECT c.id
|
|
@@ -20,36 +247,38 @@ import{a as k,b as U,f as J}from"./chunk-WIBFXSYB.js";import{a as we}from"./chun
|
|
|
20
247
|
FROM documents
|
|
21
248
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
22
249
|
)
|
|
23
|
-
`).run()})()}function
|
|
250
|
+
`).run()})()}function Lr(e,t){return e.prepare(`
|
|
24
251
|
SELECT relative_path AS relativePath
|
|
25
252
|
FROM documents
|
|
26
253
|
WHERE language = 'vue' OR relative_path LIKE '%.vue'
|
|
27
254
|
ORDER BY relative_path
|
|
28
|
-
`).all().map(r=>
|
|
255
|
+
`).all().map(r=>ws(t,r.relativePath))}function Cr(e,t){let{vueCore:n,ts:r,volarTs:i}=ks(e),{parsed:o,vueOptions:a}=Ds(n,r,t),s=_r(t),c=n.createVueLanguagePlugin(r,o.options,a,f=>f),u=Fs(n,r,c),l=js(s,o),{languageServiceHost:p}=i.createLanguageServiceHost(r,r.sys,u,f=>f,l),d=r.createLanguageService(p);return{ts:r,language:u,languageService:d,fileNames:o.fileNames,configDir:s}}function ks(e){let t=xs(Ts(Mr(e,"package.json")).href);return{vueCore:vt(t,"@vue/language-core",e),ts:vt(t,"typescript",e),volarTs:vt(t,"@volar/typescript",e)}}function Ds(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,_r(n),void 0,n,void 0,e.getAllExtensions(o).map(a=>({extension:a.slice(1),isMixedContent:!0,scriptKind:t.ScriptKind.Deferred}))),vueOptions:o}}function Fs(e,t,n){let r={},i=e.createLanguage([n],new Map,o=>{if(!vs(o))return;let a=Pt(o,"utf-8");r.current?.scripts.set(o,t.ScriptSnapshot.fromString(a),n.getLanguageId(o)??As(o))});return r.current=i,i}function js(e,t){return{getCurrentDirectory:()=>e,getCompilationSettings:()=>t.options,getScriptFileNames:()=>t.fileNames,getProjectReferences:()=>t.projectReferences,getProjectVersion:()=>"0"}}function vt(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 Ar(e,t,n){let r=Os(e);return i=>{if(!i.name)return null;let o=T(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 l=c.containingByLine.get(s.line);return l&&l.displayName===i.name?l.symbolId:_s(c.starts,s.line,2,i.name)}}function Os(e){let t=e.prepare(`
|
|
29
256
|
SELECT
|
|
30
257
|
d.relative_path AS relativePath,
|
|
31
258
|
der.start_line AS startLine,
|
|
32
259
|
der.end_line AS endLine,
|
|
33
|
-
der.symbol_id AS symbolId
|
|
260
|
+
der.symbol_id AS symbolId,
|
|
261
|
+
gs.display_name AS displayName
|
|
34
262
|
FROM defn_enclosing_ranges der
|
|
35
263
|
JOIN documents d ON d.id = der.document_id
|
|
264
|
+
JOIN global_symbols gs ON gs.id = der.symbol_id
|
|
36
265
|
ORDER BY d.relative_path, (der.end_line - der.start_line) DESC
|
|
37
|
-
`).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});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,r.symbolId)}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function
|
|
266
|
+
`).all(),n=new Map;for(let r of t){let i=n.get(r.relativePath);i||(i={containingByLine:new Map,starts:[]},n.set(r.relativePath,i)),i.starts.push({line:r.startLine,symbolId:r.symbolId,displayName:r.displayName});for(let o=r.startLine;o<=r.endLine;o++)i.containingByLine.set(o,{symbolId:r.symbolId,displayName:r.displayName})}for(let r of n.values())r.starts.sort((i,o)=>i.line-o.line);return n}function _s(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 Nr(e,t,n){let r=$s(t),i=e.prepare("SELECT id FROM global_symbols WHERE symbol = ?"),o=e.prepare(`
|
|
38
267
|
INSERT OR IGNORE INTO global_symbols (symbol, display_name, kind, documentation)
|
|
39
268
|
VALUES (?, ?, ?, ?)
|
|
40
|
-
`),
|
|
269
|
+
`),a=0,s=new Map;return e.transaction(()=>{for(let u of n){let l=T(t,u),p=Jr(r.name,r.version,l);o.run(p,"default",7,`Vue component|${l}`);let d=Gs(i,r,t,u);d&&(a++,s.set(u,d))}})(),{get(u){return s.get(u)??null},syntheticSymbols:a}}function Vr(e,t,n,r,i){return e.transaction(()=>(Es(e),Ms(e,t,n,r),Ls(e,i)))()}function Ms(e,t,n,r){let i=e.prepare("SELECT id FROM documents WHERE relative_path = ?"),o=e.prepare(`
|
|
41
270
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
42
271
|
VALUES (?, ?, ?, ?, X'00')
|
|
43
|
-
`),
|
|
272
|
+
`),a=e.prepare(`
|
|
44
273
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
45
274
|
VALUES (?, ?, 1)
|
|
46
|
-
`);for(let
|
|
275
|
+
`);for(let s of n){let c=r.get(s);if(!c)continue;let u=T(t,s),l=i.get(u);if(!l)continue;let p=o.run(l.id,-1,0,0);a.run(Number(p.lastInsertRowid),c)}}function $r(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(It(s,e.textSpan.start)!==null)return n.get(e.fileName)}return e.fileName.startsWith(i)?n.get(e.fileName):null}return t(e)}function Gr(e){let t=new Set,n=[];for(let r of e){let i=Ur(r);t.has(i)||(t.add(i),n.push(r))}return n}function Ur(e){return[e.sourceFile,e.sourceLine,e.sourceStartChar,e.sourceEndChar,e.symbolId].join(":")}function Ls(e,t){let n=Vs(e,[...new Set(t.map(c=>c.sourceFile))]),r=e.prepare(`
|
|
47
276
|
INSERT INTO chunks (document_id, chunk_index, start_line, end_line, occurrences)
|
|
48
277
|
VALUES (?, ?, ?, ?, X'00')
|
|
49
278
|
`),i=e.prepare(`
|
|
50
279
|
INSERT OR IGNORE INTO mentions (chunk_id, symbol_id, role)
|
|
51
280
|
VALUES (?, ?, 0)
|
|
52
|
-
`),o=new Set,
|
|
281
|
+
`),o=new Set,a=0,s=0;for(let c of t){let u=Ur(c);if(o.has(u))continue;o.add(u);let l=n.get(c.sourceFile);if(!l)continue;let p=r.run(l,s++,c.sourceLine,c.sourceLine),d=i.run(Number(p.lastInsertRowid),c.symbolId);a+=Number(d.changes)}return a}function*Br(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 Wr(e,t){for(let[n]of e.toGeneratedLocation(t,r=>!!r.navigation))return n;return null}function It(e,t){let n=e;for(let[r]of n.toSourceLocation(t,i=>!!i.navigation))return r;return null}function Cs(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 Hr(e,t){return T(e,t).startsWith("node_modules/")}function T(e,t){return Is(e,t).replaceAll("\\","/")}function As(e){switch(Ps(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 qr(){let e=new Map;return{get(t){if(e.has(t))return e.get(t)??null;try{let n=Pt(t,"utf-8"),r={text:n,lineStarts:Ns(n)};return e.set(t,r),r}catch{return e.set(t,null),null}},positionAt:Cs}}function Ns(e){let t=[0];for(let n=0;n<e.length;n++)e.charCodeAt(n)===10&&t.push(n+1);return t}function Vs(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 $s(e){try{let t=JSON.parse(Pt(Mr(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 Gs(e,t,n,r){let i=T(n,r),o=Jr(t.name,t.version,i);return e.get(o)?.id??null}function Jr(e,t,n){let r=n.split("/").map(i=>`\`${i.replaceAll("`","")}\``).join("/");return`scip-vue npm ${e} ${t} ${r}/default.`}function Yr(e){return{id:"vue-resolved-references",facts:["synthetic-symbol","source-mapped-occurrence","definition-mention","replacement-chunk","fingerprint-cache"],run:t=>Ys({projectRoot:t.projectRoot,dbPath:t.dbPath,tsconfig:e.tsconfig,onStatus:t.onStatus})}}function zs(e){return O(C(),{projectRoot:e.projectRoot,dbPath:e.dbPath}),O(Yr({tsconfig:e.tsconfig}),{projectRoot:e.projectRoot,dbPath:e.dbPath,onStatus:e.onStatus}).result}function Ys(e){let t=Js(e.projectRoot,e.tsconfig);if(!Ws(t))throw new Error(`Vue tsconfig not found at ${t}`);let n=new Bs(e.dbPath);try{let r=Lr(n,e.projectRoot),i=qs(Hs(e.dbPath),"augment-vue-meta.json");return Sn({cachePath:i,readFingerprint:()=>Ks(n,e.projectRoot,e.tsconfig),compute:()=>Qs({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 Qs(e){let t=Nr(e.db,e.projectRoot,e.vueFiles),n=Xs(e,t),r=Gr(n.occurrences),i=Vr(e.db,e.projectRoot,e.vueFiles,t,r),o={vueFiles:e.vueFiles.length,resolvedReferences:r.length,resolvedReferenceSamples:sc(e.db,r,20),insertedMentions:i,skippedReferences:n.skippedReferences,skippedReferenceReasons:n.skippedReferenceReasons,skippedReferenceSamples:ac(n.skippedReferenceSamples,20),syntheticSymbols:t.syntheticSymbols};return e.onStatus?.(`Resolved ${o.resolvedReferences} Vue references with Volar; inserted ${o.insertedMentions} mentions.`),o}function Xs(e,t){if(Dr(e.vueFiles))return Fr({projectRoot:e.projectRoot,dbPath:e.dbPath,tsconfig:e.tsconfig,vueFiles:e.vueFiles});let n=Zs({db:e.db,projectRoot:e.projectRoot,configPath:e.configPath,vueSymbolLookup:t});return ec({...n,vueFiles:n.context.fileNames.filter(r=>r.endsWith(".vue"))})}function Ks(e,t,n){let r=e.prepare(`
|
|
53
282
|
SELECT
|
|
54
283
|
(SELECT COUNT(*) FROM documents) AS documents,
|
|
55
284
|
(SELECT COUNT(*) FROM global_symbols) AS symbols,
|
|
@@ -58,13 +287,13 @@ import{a as k,b as U,f as J}from"./chunk-WIBFXSYB.js";import{a as we}from"./chun
|
|
|
58
287
|
(SELECT COUNT(*) FROM defn_enclosing_ranges) AS ranges,
|
|
59
288
|
(SELECT MAX(id) FROM chunks) AS maxChunkId,
|
|
60
289
|
(SELECT MAX(id) FROM global_symbols) AS maxSymbolId
|
|
61
|
-
`).get();return{version:2,tsconfig:n,files:I(t),db:r}}function ji(e){let t=It();return{projectRoot:e.projectRoot,context:ht(e.projectRoot,e.configPath),symbolLookup:yt(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function vi(e){let t=[],n=0,r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=ki(e,i);t.push(...o.occurrences),n+=o.skippedReferences}return{occurrences:t,skippedReferences:n}}function ki(e,t){let n=e.context.language.scripts.get(t.fileName),r=n?.generated?.languagePlugin.typescript?.getServiceScript(n.generated.root)?.code;if(!n||!r)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let i=e.sourceReader.get(t.fileName);if(!i)return{occurrences:[],skippedReferences:t.countFileSkip?1:0};let o=e.context.language.maps.get(r,n),s=P(e.projectRoot,t.fileName),a=[...jt(i.text)],u={tokens:a.filter(c=>c.start>=t.startOffset&&c.start<t.endOffset),tokenByStart:new Map(a.map(c=>[c.start,c])),tokenTextCounts:Ci(a),processedStarts:new Set};return Ii({...e,fileName:t.fileName,sourceInfo:i,sourceFile:s,map:o,tokenContext:u})}function Ii(e){let t=[],n=0;for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start))continue;let i=vt(e.map,r.start);if(i===null)continue;let s=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(u=>!kt(e.projectRoot,u.fileName));if(!s){n++;continue}let a=xt(s,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(a===null){n++;continue}Lt(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,a),e.tokenContext.processedStarts.add(r.start),wi(t,e,r,i,a)}return{occurrences:t,skippedReferences:n}}function wi(e,t,n,r,i){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let o of Li(t.context.languageService,t.fileName,r+1,t.map,n,t.tokenContext.tokenByStart)){if(t.tokenContext.processedStarts.has(o))continue;let s=t.tokenContext.tokenByStart.get(o);s&&(Lt(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i),t.tokenContext.processedStarts.add(o))}}function Lt(e,t,n,r,i,o){let s=t.positionAt(n,i.start);e.push({sourceFile:r,sourceLine:s.line,sourceStartChar:s.character,sourceEndChar:s.character+i.text.length,symbolId:o})}function Ci(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function Li(e,t,n,r,i,o){let s=e.getDocumentHighlights?.(t,n,[t])??[],a=[];for(let u of s)if(u.fileName===t)for(let c of u.highlightSpans){let p=Fi(r,c.textSpan.start,o,i.text);p!==null&&a.push(p)}return a}function Fi(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=fe(e,t);if(o===null)return null;let s=n.get(o);return s?.text===r?s.start:null}async function ea(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=_i(e),s=Date.now();$(m(o.outputScip),{recursive:!0}),$(m(o.outputDb),{recursive:!0});let a=e.languages??G(t);if(a.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: ${a.join(", ")}`);let u=bo(t,a,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),c=await lo(y(m(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),p=null;try{let l=Bi({opts:e,paths:o,languages:a,fingerprint:u,start:s,onStatus:r});if(l)return l;await ro(i,r);let g=Ui(o);return p=g.runDir,await Ji({opts:e,languages:a,projectRoot:t,paths:o,tempPaths:g,fingerprint:u,start:s,maxHeapMb:n,skipAutoInstall:i,onStatus:r})}catch(l){throw Vt(o.metaPath,je({trigger:e.trigger,result:"failed",start:s,error:l instanceof Error?l.message:String(l)})),l}finally{p&&R(p,{recursive:!0,force:!0}),c()}}function _i(e){let t=e.outputScip??y(e.projectRoot,"index.scip"),n=e.outputDb??y(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:y(m(n),"meta.json")}}function Bi(e){if(e.opts.skipIfUnchanged===!1||!L(e.paths.outputScip)||!L(e.paths.outputDb)||!xo(e.paths.metaPath,e.fingerprint))return null;x(j(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let t=Date.now()-e.start,n=je({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return Vt(e.paths.metaPath,n),e.onStatus(`Index unchanged; reused existing SQLite index in ${(t/1e3).toFixed(1)}s`),{languages:e.languages,indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:t,reused:!0,skipped:[],lastRefresh:n,shards:Wi(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function Wi(e,t,n,r){let i=xe(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:C(i[o]),outputBytes:_(Pe(e.outputDb,o)),durationMs:0}))}function Ui(e){let t=Oi(y(m(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:y(t,V(e.outputScip)),tempOutputDb:y(t,V(e.outputDb)),tempMetaPath:y(t,V(e.metaPath))}}async function Ji(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},{indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,shards:o,typescriptProjectShardContext:s}=await Gi(e,t);i.length>0&&e.onStatus(`Reused ${i.length} cached language shard(s): ${i.join(", ")}`);let a=Qi(e,t,n,r,i,s),u=a.durationMs;return e.onStatus(`Done in ${(u/1e3).toFixed(1)}s`),{languages:n.map(c=>c.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:u,reused:!1,skipped:r,lastRefresh:a,shards:o}}async function Gi(e,t){let n=Xi({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[S,ve]of n)ve.reused&&(r.push({language:S,scipPath:ve.scipPath}),i.add(S));for(let S of i)e.onStatus(`Reusing cached ${S} SCIP shard (language inputs unchanged).`);let o=qi(e,n),{preparedRuns:s,skippedLanguages:a,languageOutputScipPaths:u}=io({languages:e.languages.filter(S=>!i.has(S)),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:o?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),c=o?s.filter(S=>S.language!=="typescript"||o.missedProjectIds.has(S.id)):s,p=await ot(c,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),l=[];if(o){Hi(e.paths.outputDb,p);let S=u.typescript??e.tempPaths.tempOutputScip;l=Ki({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:S,reusedProjects:o.reusedProjects})}let g=[...p,...l],{indexedOutputs:h}=so(g,a),f=[...r,...h];ao(f,a,e.languages,e.opts.allowPartial,e.onStatus);let $t=Yi(n,p,o?{outputDb:e.paths.outputDb,classification:o.classification}:void 0);return{indexedOutputs:f,skippedLanguages:a,reusedLanguages:[...i],shards:$t,typescriptProjectShardContext:o?{projects:o.allProjects,fingerprints:o.fingerprints}:void 0}}function qi(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=ee(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=He(e.projectRoot,r),o=Ge(n.fingerprint.files,r),s=qe(r,i),a=ze(r,o,s),u=Re(e.paths.metaPath),p=zi(u,a,f=>L(W(e.paths.outputDb,f))),l=[...p.entries()].filter(([,f])=>f.reused).map(([f])=>f),g=new Set(l),h=new Set(r.filter(f=>!g.has(f)).map(f=>`typescript:${f}`));return{allProjects:r,fingerprints:a,classification:p,reusedProjects:l,missedProjectIds:h}}function zi(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 s=e.typescriptProjectShards?.[i];if(!s){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(b(s)!==b(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 Hi(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=W(e,r);$(m(i),{recursive:!0}),Se(n.scipPath,i)}}function Ki(e){return e.reusedProjects.map((t,n)=>{let r=W(e.outputDb,t),i=be(e.tempOutputScip,"typescript-project-cached",n);return Se(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:_(i)??void 0}})}function Xi(e){let t=Re(e.paths.metaPath),n=xe(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Pe(e.paths.outputDb,i),s=n[i];if(!t){r.set(i,{reused:!1,reason:"no reindex metadata found",fingerprint:s,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:s,scipPath:o});continue}if(!t.languageFingerprints){r.set(i,{reused:!1,reason:"no per-language fingerprints recorded in metadata",fingerprint:s,scipPath:o});continue}let a=t.languageFingerprints[i];if(!a){r.set(i,{reused:!1,reason:"no cached fingerprint for this language",fingerprint:s,scipPath:o});continue}if(!L(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:s,scipPath:o});continue}if(b(a)!==b(s)){r.set(i,{reused:!1,reason:"language inputs changed since last index",fingerprint:s,scipPath:o});continue}r.set(i,{reused:!0,fingerprint:s,scipPath:o})}return r}function Yi(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:C(o.fingerprint),outputBytes:_(o.scipPath),durationMs:0});for(let i of t){let o=e.get(i.language),s=n&&i.id.startsWith("typescript:")?i.id.slice(11):null,a=s?n.classification.get(s):void 0;r.push({id:i.id,language:i.language,reused:!1,missReason:a?.reason??o?.reason??i.skipped?.reason,fingerprint:a?C(a.fingerprint):o?C(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:C(o.fingerprint),outputBytes:_(W(n.outputDb,i)),durationMs:0});return r}function C(e){return Mi("sha256").update(b(e)).digest("hex").slice(0,16)}function _(e){try{return Ni(e).size}catch{return null}}function Qi(e,t,n,r,i,o){no(e.paths.outputDb,n),uo(n,e.tempPaths.tempOutputScip,e.onStatus),co(e.tempPaths.tempOutputScip,e.tempPaths.tempOutputDb,t,e.onStatus),x(j(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus});let s=Zi({mode:e.opts.typescriptProjectMode,skippedLanguages:r,reusedLanguages:i,context:o,metaPath:e.paths.metaPath});eo(e.paths.outputDb,s.pruneProjects);let a=je({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(u=>u.language),skipped:[...r]});return Nt(e.tempPaths.tempMetaPath,{version:3,status:r.length===0?"complete":"partial",updatedAt:new Date().toISOString(),fingerprint:e.fingerprint,languageFingerprints:xe(e.projectRoot,e.languages,{pnpmWorkspaces:e.opts.pnpmWorkspaces,typescriptProjectMode:e.opts.typescriptProjectMode,typescriptProjects:e.opts.typescriptProjects,clojureConfigPath:e.opts.clojureConfigPath}),typescriptProjectShards:s.field,requestedLanguages:e.languages,indexedLanguages:n.map(u=>u.language),skipped:[...r],lastRefresh:a}),So({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath}),a}function Zi(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=Re(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 eo(e,t){let n=At(e);if(t===null){R(n,{recursive:!0,force:!0});return}let r;try{r=Ai(n)}catch{return}for(let i of to(r,t))R(y(n,i),{force:!0})}function to(e,t){let n=new Set(t.map(r=>`${Q(r)}.scip`));return e.filter(r=>!n.has(r))}function no(e,t){for(let n of t){let r=Pe(e,n.language);$(m(r),{recursive:!0}),n.scipPath!==r&&Se(n.scipPath,r)}}async function ro(e,t){if(!U()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
62
|
-
Install from: https://github.com/sourcegraph/scip/releases`);if($i()==="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..."),!J(t))throw new Error(`The scip CLI is required but could not be installed.
|
|
63
|
-
Install
|
|
290
|
+
`).get();return{version:3,tsconfig:n,files:H(t),db:r}}function Zs(e){let t=qr();return{projectRoot:e.projectRoot,context:Cr(e.projectRoot,e.configPath),symbolLookup:Ar(e.db,e.projectRoot,t),vueSymbolLookup:e.vueSymbolLookup,sourceReader:t}}function ec(e){let t=[],n=G(),r=e.tasks??e.vueFiles.map(i=>({fileName:i,startOffset:0,endOffset:Number.POSITIVE_INFINITY,countFileSkip:!0}));for(let i of r){let o=tc(e,i);t.push(...o.occurrences),Ie(n,o)}return{occurrences:t,...n}}function tc(e,t){let n=e.sourceReader.get(t.fileName);if(!n)return zr(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 zr(e.projectRoot,t,"missing-service-script");let o=e.context.language.maps.get(i,r),a=T(e.projectRoot,t.fileName),s=[...Br(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:uc(s),processedStarts:new Set};return nc({...e,fileName:t.fileName,sourceInfo:n,sourceFile:a,map:o,tokenContext:c})}function nc(e){let t=[],n=G();for(let r of e.tokenContext.tokens){if(e.tokenContext.processedStarts.has(r.start)||rc(e.sourceInfo.text,r.start))continue;let i=Wr(e.map,r.start);if(i===null)continue;let a=(e.context.languageService.getDefinitionAtPosition(e.fileName,i+1)??[]).find(l=>!Hr(e.projectRoot,l.fileName));if(!a){wt(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"no-definition");continue}let s=T(e.projectRoot,a.fileName),c=ic(e.sourceFile,r.text,s);if(c){wt(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,c);continue}let u=$r(a,e.symbolLookup,e.vueSymbolLookup,e.context,e.projectRoot);if(u===null){wt(n,e.sourceReader,e.sourceInfo,e.sourceFile,r,"unindexed-definition");continue}Qr(t,e.sourceReader,e.sourceInfo,e.sourceFile,r,s,u),e.tokenContext.processedStarts.add(r.start),cc(t,e,r,i,s,u)}return{occurrences:t,...n}}function rc(e,t){let n=e.lastIndexOf(`
|
|
291
|
+
`,t-1)+1,r=e.slice(n,t);return/\bfrom\s+['"][^'"]*$/.test(r)||/\bimport\s*\(\s*['"][^'"]*$/.test(r)}function ic(e,t,n){return n===e?"same-file-definition":n.endsWith(".vue")&&t!==n.split("/").at(-1)?.replace(/\.vue$/,"")?"unindexed-definition":null}function zr(e,t,n){let r=G();return t.countFileSkip&&(r.skippedReferences=1,r.skippedReferenceReasons[n]=1,r.skippedReferenceSamples.push({sourceFile:T(e,t.fileName),sourceLine:0,sourceStartChar:0,sourceEndChar:0,token:"",reason:n})),{occurrences:[],...r}}function wt(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 Tt(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 oc(e,t){let n=Tt(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=Tt(e.filter(o=>!r.has(`${o.sourceFile}:${o.sourceLine}:${o.sourceStartChar}:${o.sourceEndChar}:${o.symbolId}`)),t-n.length);return[...n,...i]}function ac(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(...Tt(e.filter(c=>c.reason===o),s))}return r.slice(0,t)}function sc(e,t,n){let r=e.prepare("SELECT symbol FROM global_symbols WHERE id = ?");return oc(t,n).map(({symbolId:i,...o})=>({...o,definitionSymbol:r.get(i)?.symbol??`symbol-id:${i}`}))}function cc(e,t,n,r,i,o){if(!((t.tokenContext.tokenTextCounts.get(n.text)??0)<=1))for(let a of lc(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&&(Qr(e,t.sourceReader,t.sourceInfo,t.sourceFile,s,i,o),t.tokenContext.processedStarts.add(a))}}function Qr(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 uc(e){let t=new Map;for(let n of e)t.set(n.text,(t.get(n.text)??0)+1);return t}function lc(e,t,n,r,i,o){let a=e.getDocumentHighlights?.(t,n,[t])??[],s=[];for(let c of a)if(c.fileName===t)for(let u of c.highlightSpans){let l=dc(r,u.textSpan.start,o,i.text);l!==null&&s.push(l)}return s}function dc(e,t,n,r){let i=n.get(t);if(i?.text===r)return i.start;let o=It(e,t);if(o===null)return null;let a=n.get(o);return a?.text===r?a.start:null}async function ep(e){let{projectRoot:t,maxHeapMb:n=8192,onStatus:r=console.log,skipAutoInstall:i=!1}=e,o=vc(e),a=Date.now();Te(m(o.outputScip),{recursive:!0}),Te(m(o.outputDb),{recursive:!0});let s=e.languages??He(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=B("reindex.fingerprint",()=>tu(t,s,{pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:e.typescriptProjects,clojureConfigPath:e.clojureConfigPath}),{languages:s.length}),u=await W("reindex.lock",()=>zc(b(m(o.outputDb),"index.lock"),{projectRoot:t,trigger:e.trigger,onStatus:r}),{languages:s.length}),l=null;try{let p=null,d=B("reindex.reuse-check",()=>(p=Pc({opts:e,paths:o,languages:s,fingerprint:c,start:a,onStatus:r}),p),()=>({languages:s.length,reused:p!==null}));if(d)return d;await W("reindex.scip-cli-ready",()=>$c(i,r));let f=wc(o);l=f.runDir;let g;return await W("reindex.fresh",async()=>(g=await Tc({opts:e,languages:s,projectRoot:t,paths:o,tempPaths:f,fingerprint:c,start:a,maxHeapMb:n,skipAutoInstall:i,onStatus:r}),g),()=>({languages:s.length,reused:g?.reused,skipped:g?.skipped.length}))}catch(p){throw gi(o.metaPath,Fe({trigger:e.trigger,result:"failed",start:a,error:p instanceof Error?p.message:String(p)})),p}finally{l&&M(l,{recursive:!0,force:!0}),u()}}function vc(e){let t=e.outputScip??b(e.projectRoot,"index.scip"),n=e.outputDb??b(e.projectRoot,"index.db");return{outputScip:t,outputDb:n,metaPath:b(m(n),"meta.json")}}function Pc(e){let t=fe(e.paths.outputDb,e.paths.metaPath);if(e.opts.skipIfUnchanged===!1||!k(e.paths.outputScip)||!k(e.paths.outputDb)||!nu(e.paths.metaPath,e.fingerprint)||t.state==="invalid"||t.state==="drifted")return null;O(C(),{projectRoot:e.opts.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus});let n=Date.now()-e.start,r=Fe({trigger:e.opts.trigger,result:"reused",start:e.start,languages:e.languages,skipped:[]});return gi(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:Ic(e.paths,e.opts.projectRoot,e.languages,e.opts)}}function Ic(e,t,n,r){let i=ui(t,n,r);return n.map(o=>({id:o,language:o,reused:!0,fingerprint:K(i[o]),outputBytes:Z(Dt(e.outputDb,o)),durationMs:0}))}function wc(e){let t=mc(b(m(e.outputDb),"reindex-"));return{runDir:t,tempOutputScip:b(t,we(e.outputScip)),tempOutputDb:b(t,we(e.outputDb)),tempMetaPath:b(t,we(e.metaPath))}}async function Tc(e){let t={...process.env,NODE_OPTIONS:`--max-old-space-size=${e.maxHeapMb}`},n,r=await W("reindex.language-indexers",async()=>(n=await kc(e,t),n),()=>({languages:e.languages.length,indexed:n?.indexedOutputs.length,reused:n?.reusedLanguages.length,skipped:n?.skippedLanguages.length})),{indexedOutputs:i,skippedLanguages:o,reusedLanguages:a,languageFingerprints:s,shards:c,typescriptProjectShardContext:u,incrementalTypeScript:l}=r;if(a.length>0&&e.onStatus(`Reused ${a.length} cached language shard(s): ${a.join(", ")}`),Ec({run:e,indexedOutputs:i,skippedLanguages:o,reusedLanguages:a})){let f=B("reindex.publish",()=>Ac(e,i,o,a,s,u),{mode:"metadata-only",languages:i.length,reused:a.length}),g=f.durationMs;return e.onStatus(`All language shards unchanged; reused existing SQLite index in ${(g/1e3).toFixed(1)}s`),{languages:i.map(w=>w.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:g,reused:!0,skipped:o,lastRefresh:f,shards:c}}let p=B("reindex.publish",()=>Cc(e,t,i,o,a,s,u,l),{mode:l?"incremental-or-fallback":"full",languages:i.length,reused:a.length,skipped:o.length}),d=p.durationMs;return e.onStatus(`Done in ${(d/1e3).toFixed(1)}s`),{languages:i.map(f=>f.language),indexPath:e.paths.outputScip,dbPath:e.paths.outputDb,durationMs:d,reused:!1,skipped:o,lastRefresh:p,shards:c}}function Ec(e){if(e.run.opts.skipIfUnchanged===!1||e.skippedLanguages.length>0||!k(e.run.paths.outputScip)||!k(e.run.paths.outputDb))return!1;let t=fe(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 kc(e,t){let n=_c({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[P,Ot]of n)Ot.reused&&(r.push({language:P,scipPath:Ot.scipPath}),i.add(P));for(let P of i)e.onStatus(`Reusing cached ${P} SCIP shard (language inputs unchanged).`);let o=n.get("typescript"),a=fe(e.paths.outputDb,e.paths.metaPath),s=te(e.paths.metaPath),c=a.state==="legacy"||a.state==="current",u=s?.scipCompanion!=="deferred"&&(a.state!=="current"||a.generation.publication?.scipCompanion!=="deferred"),l=o&&!o.reused&&c?wr({projectRoot:e.projectRoot,cacheDir:m(e.paths.outputDb),previousDbPath:e.paths.outputDb,previousIndexPath:e.paths.outputScip,previousShardPath:o.scipPath,candidateShardPath:ee(e.tempPaths.tempOutputScip,"typescript-incremental",0),candidateAffectedScipPath:ee(e.tempPaths.tempOutputScip,"typescript-affected",0),baseShardCurrent:u,previousSnapshot:kt(e.paths.metaPath),currentSnapshot:e.fingerprint,projectMode:e.opts.typescriptProjectMode,onStatus:e.onStatus}):null,p=new Set(l?["typescript"]:[]),d=l?void 0:Dc(e,n),{preparedRuns:f,skippedLanguages:g,languageOutputScipPaths:w}=Gc({languages:e.languages.filter(P=>!i.has(P)&&!p.has(P)),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:d?.allProjects,clojureConfigPath:e.opts.clojureConfigPath,onStatus:e.onStatus}),D=d?f.filter(P=>P.language!=="typescript"||d.missedProjectIds.has(P.id)):f,F=await kr(D,e.projectRoot,e.onStatus,e.opts.indexerConcurrency),y=[];if(d){jc(e.paths.outputDb,F);let P=w.typescript??e.tempPaths.tempOutputScip;y=Oc({outputDb:e.paths.outputDb,tempOutputScip:e.tempPaths.tempOutputScip,outputScipPath:P,reusedProjects:d.reusedProjects})}let x=[...F,...y],{indexedOutputs:v}=Bc(x,g),ne=l?[{language:"typescript",scipPath:l.scipPath}]:[],jt=[...r,...ne,...v];Wc(jt,g,e.languages,e.opts.allowPartial,e.onStatus);let fi=l?[{id:"typescript",language:"typescript",label:"typescript (incremental documents)",scipPath:l.scipPath,outputScipPath:l.scipPath,durationMs:l.durationMs,command:"watch-service:typescript-index",outputBytes:Z(l.scipPath)??void 0}]:[],mi=Mc(n,[...F,...fi],d?{outputDb:e.paths.outputDb,classification:d.classification}:void 0);return{indexedOutputs:jt,skippedLanguages:g,reusedLanguages:[...i],languageFingerprints:Lc(n,e.languages),shards:mi,typescriptProjectShardContext:d?{projects:d.allProjects,fingerprints:d.fingerprints}:void 0,incrementalTypeScript:l??void 0}}function Dc(e,t){let n=t.get("typescript");if(!n||n.reused||e.opts.typescriptProjectMode!=="workspace")return;let r=X(e.projectRoot,e.opts.typescriptProjects);if(r.length===0)return;let i=Pn(e.projectRoot,r),o=Rn(n.fingerprint.files,r),a=xn(r,i),s=vn(r,o,a),c=te(e.paths.metaPath),l=Fc(c,s,g=>k(De(e.paths.outputDb,g))),p=[...l.entries()].filter(([,g])=>g.reused).map(([g])=>g),d=new Set(p),f=new Set(r.filter(g=>!d.has(g)).map(g=>`typescript:${g}`));return{allProjects:r,fingerprints:s,classification:l,reusedProjects:p,missedProjectIds:f}}function Fc(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(E(a)!==E(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 jc(e,t){for(let n of t){if(n.skipped||!n.id.startsWith("typescript:"))continue;let r=n.id.slice(11),i=De(e,r);Te(m(i),{recursive:!0}),Ee(n.scipPath,i)}}function Oc(e){return e.reusedProjects.map((t,n)=>{let r=De(e.outputDb,t),i=ee(e.tempOutputScip,"typescript-project-cached",n);return Ee(r,i),{id:`typescript:${t}`,language:"typescript",label:`typescript (${t})`,scipPath:i,outputScipPath:e.outputScipPath,durationMs:0,command:"cached",outputBytes:Z(i)??void 0}})}function _c(e){let t=te(e.paths.metaPath),n=ui(e.projectRoot,e.languages,e),r=new Map;for(let i of e.languages){let o=Dt(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(!k(o)){r.set(i,{reused:!1,reason:"cached shard file missing on disk",fingerprint:a,scipPath:o});continue}if(E(s)!==E(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 Mc(e,t,n){let r=[];for(let[i,o]of e)o.reused&&r.push({id:i,language:i,reused:!0,fingerprint:K(o.fingerprint),outputBytes:Z(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?K(s.fingerprint):o?K(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:K(o.fingerprint),outputBytes:Z(De(n.outputDb,i)),durationMs:0});return r}function K(e){return gc("sha256").update(E(e)).digest("hex").slice(0,16)}function Z(e){try{return Sc(e).size}catch{return null}}function Lc(e,t){let n={};for(let r of t){let i=e.get(r);i&&(n[r]=i.fingerprint)}return n}function Cc(e,t,n,r,i,o,a,s){let c=!s||s.completeScipUpdated,u=!1;c&&(Xr(e.paths.outputDb,n),u=Kr(n,e.tempPaths.tempOutputScip,e.onStatus));let l=Hc({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..."),Tr({cacheDir:m(e.paths.outputDb),generationIdentity:s.nextFragmentGeneration,baseShardPath:s.scipPath,candidateShardPath:s.candidateScipPath});let y=n.map(x=>x.language==="typescript"?{language:x.language,scipPath:s.candidateScipPath}:x);return Xr(e.paths.outputDb,y),u=Kr(y,e.tempPaths.tempOutputScip,e.onStatus),u}});if(O(C(),{projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,onStatus:e.onStatus}),l.mode==="incremental"&&s){let y=null,x=null;try{y=new L({projectRoot:e.projectRoot,dbPath:e.tempPaths.tempOutputDb,indexPath:e.tempPaths.tempOutputScip}),x=new L({projectRoot:e.projectRoot,dbPath:e.paths.outputDb,indexPath:e.paths.outputScip});let v=Gt(y,e.fingerprint,s.referenceFragmentsByFile,x);e.onStatus(`Cached exact TypeScript reference fragments for ${v} affected document(s).`)}catch(v){e.onStatus(`Exact TypeScript reference fragment prefill unavailable: ${v instanceof Error?v.message:String(v)}.`)}finally{y?.close(),x?.close()}}let p=kt(e.paths.metaPath),d=l.mode==="incremental"&&s?Jc(s,l.changedDocumentPaths):We({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"}),f=Fe({trigger:e.opts.trigger,result:"rebuilt",start:e.start,languages:n.map(y=>y.language),skipped:[...r]}),g=l.mode==="incremental"&&l.scipCompanion==="deferred",w={...o};g&&delete w.typescript;let{metadata:D,pruneProjects:F}=ii({run:e,indexedOutputs:n,skippedLanguages:r,reusedLanguages:i,languageFingerprints:w,typescriptProjectShardContext:a,lastRefresh:f});return D.scipCompanion=g?"deferred":"current",oi(e.paths.outputDb,F),Ft(e.tempPaths.tempMetaPath,D),On({tempOutputScip:e.tempPaths.tempOutputScip,tempOutputDb:e.tempPaths.tempOutputDb,tempMetaPath:e.tempPaths.tempMetaPath,outputScip:e.paths.outputScip,outputDb:e.paths.outputDb,metaPath:e.paths.metaPath,preserveOutputScip:l.mode==="incremental"&&l.scipCompanion==="deferred",publication:l.mode==="incremental"?{mode:"incremental",validation:"passed",converterDurationMs:l.converterDurationMs,affectedDocumentCount:s?.affectedFiles.length,changedDocumentCount:l.changedDocumentPaths.length,producerDurationMs:s?.timings.serviceMs,materializationDurationMs:s?.durationMs,patchDurationMs:l.patchDurationMs,scipCompanion:l.scipCompanion,...l.scipCompanion==="deferred"&&s?{typescriptOverlayGeneration:s.nextFragmentGeneration}:{}}:{mode:"full",validation:"passed",converterDurationMs:l.converterDurationMs,scipCompanion:"current",...l.fallbackReason?{fallbackReason:l.fallbackReason}:{}}}),sr(m(e.paths.outputDb),l.mode==="incremental"&&l.scipCompanion==="deferred"?[s.nextFragmentGeneration]:[]),ri(e.paths.outputDb,d,e.onStatus),f}function Ac(e,t,n,r,i,o){let a=kt(e.paths.metaPath),s=null;try{Ee(e.paths.outputDb,e.tempPaths.tempOutputDb)}catch(p){s=zt("reused","oracle-error",`Could not snapshot the prior database: ${p instanceof Error?p.message:String(p)}`)}O(C(),{projectRoot:e.projectRoot,dbPath:e.paths.outputDb,onStatus:e.onStatus}),s??=We({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=Fe({trigger:e.opts.trigger,result:"reused",start:e.start,languages:t.map(p=>p.language),skipped:[...n]}),{metadata:u,pruneProjects:l}=ii({run:e,indexedOutputs:t,skippedLanguages:n,reusedLanguages:r,languageFingerprints:i,typescriptProjectShardContext:o,lastRefresh:c});return oi(e.paths.outputDb,l),Ft(e.paths.metaPath,u),Mn(e.paths.outputDb,e.paths.metaPath),ri(e.paths.outputDb,s,e.onStatus),c}function kt(e){return Nt(te(e)?.fingerprint)}function ri(e,t,n){try{Yt(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 ii(e){let t=Nc({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 Nc(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=te(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 oi(e,t){let n=pi(e);if(t===null){M(n,{recursive:!0,force:!0});return}let r;try{r=yc(n)}catch{return}for(let i of Vc(r,t))M(b(n,i),{force:!0})}function Vc(e,t){let n=new Set(t.map(r=>`${tt(r)}.scip`));return e.filter(r=>!n.has(r))}function Xr(e,t){for(let n of t){let r=Dt(e,n.language);Te(m(r),{recursive:!0}),n.scipPath!==r&&Ee(n.scipPath,r)}}async function $c(e,t){if(!$e()){if(e)throw new Error(`The scip CLI is required but not found on PATH.
|
|
292
|
+
Install from: https://github.com/sourcegraph/scip/releases`);if(xc()==="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..."),!Ge(t))throw new Error(`The scip CLI is required but could not be installed.
|
|
293
|
+
Install manually from: https://github.com/sourcegraph/scip/releases`)}}function Gc(e){let t=[],n=[],r=e.languages.map((o,a)=>({language:o,scipPath:e.languages.length>1?ee(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=Uc({...e,language:o,scipPath:a});for(let c of s)"skipped"in c?ai(n,c.skipped):t.push(c.prepared)}return{preparedRuns:t,skippedLanguages:n,languageOutputScipPaths:i}}function Uc(e){if(e.language!=="typescript"||e.typescriptProjectMode!=="workspace")return[Et({...e,id:e.language,label:e.language,outputScipPath:e.scipPath})];let t=e.preDiscoveredTypeScriptProjects??X(e.projectRoot,e.typescriptProjects);return t.length===0?[Et({...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)=>Et({...e,id:`typescript:${n}`,label:`typescript (${n})`,scipPath:ee(e.tempOutputScip,"typescript-project",r),outputScipPath:e.scipPath,pnpmWorkspaces:!1,projectPath:n})))}function Et(e){let t=oe(e.language),n=je(t),r=Me(t,e.projectRoot);if(!r&&!_e(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...`),!Ce(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??Oe(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:Le(t,e.env,i)}}}function Bc(e,t){let n=new Map;for(let i of e)if(i.skipped)ai(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)Ye(i.scipPaths,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath});else{let o=i.scipPaths[0];o!==i.outputScipPath&&ni(o,i.outputScipPath),r.push({language:i.language,scipPath:i.outputScipPath})}return{indexedOutputs:r}}function ai(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 Wc(e,t,n,r,i){if(e.length===0){let o=t.map(a=>` - ${a.language}: ${a.reason}`).join(`
|
|
64
294
|
`);throw new Error(`No language indexers ran successfully. Install at least one indexer for the languages in this project.
|
|
65
295
|
`+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.
|
|
66
296
|
`+t.map(o=>` - ${o.language}: ${o.reason}`).join(`
|
|
67
|
-
`))}function
|
|
68
|
-
`),()=>{try{
|
|
69
|
-
`),F(n,e)}function Vt(e,t){try{let n=JSON.parse(B(e,"utf-8"));if(n.version!==2&&n.version!==3)return;Nt(e,{...n,lastRefresh:t})}catch{}}function je(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 b(e){return JSON.stringify(e)}export{Ae as INDEXER_CONFIGS,Le as augmentAuxiliaryDocuments,Si as augmentVueResolvedReferences,j as auxiliaryDocumentsAugmentationStage,N as describeIndexerBinary,G as detectLanguages,M as getIndexerConfig,ce as getIndexerExecutionEnv,k as isBinaryAvailable,ae as isIndexerInstalled,D as mergeScipFiles,Ne as mergeScipIndexes,ea as reindex,w as resolveIndexerBinary,ue as resolveProjectLocalIndexerBinary,x as runPostIndexAugmentation,le as tryInstallIndexer,J as tryInstallScipCli,Ct as vueResolvedReferencesAugmentationStage};
|
|
297
|
+
`))}function Kr(e,t,n){if(e.length>1){n(`Merging ${e.length} language indexes...`);let r=performance.now(),i=cn(e.map(o=>o.scipPath),t);return ci(i,n),n(`Merged and sanitized SCIP indexes in ${(performance.now()-r).toFixed(0)}ms.`),!0}else e[0].scipPath!==t&&ni(e[0].scipPath,t);return!1}function Hc(e){let t;if(qc(e)){let i=b(e.run.tempPaths.runDir,"typescript-affected.db");try{si(e.incrementalTypeScript.affectedScipPath,e.run.onStatus),e.run.onStatus(`Converting ${e.incrementalTypeScript.affectedFiles.length} affected TypeScript document(s) to SQLite...`);let o=performance.now();Zr(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=mn({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),M(i,{force:!0}),M(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 Zr(e.run.tempPaths.tempOutputScip,e.run.tempPaths.tempOutputDb,e.env,e.run.onStatus,n),{mode:"full",converterDurationMs:performance.now()-r,...t?{fallbackReason:t}:{}}}function qc(e){if(!e.incrementalTypeScript||e.skippedLanguages.length>0||!k(e.run.paths.outputDb)||!k(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 Jc(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:Be(e.plan,o,e.projectFileCount)}}function Zr(e,t,n,r,i=!1){if(r("Converting to SQLite..."),!k(e))throw new Error(`SCIP index not found at ${e} after indexing`);try{i||si(e,r);let o=$e();if(!o)throw new Error("scip CLI is not available");pc(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 si(e,t){let n=nn(e);ci(n,t)}function ci(e,t){e.removedDefinitionOccurrences!==0&&t(`Sanitized ${e.removedDefinitionOccurrences} invalid definition occurrences across ${e.touchedDocuments} documents before SQLite conversion.`)}function ee(e,t,n){let r=Rc(e)||".scip",i=we(e,r);return b(m(e),`${i}.${n+1}.${t}${r}`)}async function zc(e,t){for(let n=0;n<2;n++){let r=Yc(e,t);if(r)return r;let i=Qc(e);if(i&&Xc(t.trigger,i)){if(t.onStatus(`Manual reindex preempting watcher refresh started at ${i.startedAt}.`),!await Zc(i.pid))throw new Error(`Could not confirm the watcher's in-progress reindex (pid ${i.pid}) terminated for ${m(e)}; refusing to steal an active lock.`);M(e,{force:!0});continue}if(i&&!V(i.pid)){M(e,{force:!0});continue}throw new Error(`Another scip-query reindex is already running for ${m(e)}.`)}throw new Error(`Could not acquire scip-query reindex lock for ${m(e)}.`)}function Yc(e,t){let n;try{n=hc(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 bc(n,JSON.stringify(r)+`
|
|
298
|
+
`),()=>{try{fc(n)}finally{M(e,{force:!0})}}}function Qc(e){try{let t=JSON.parse(ke(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:m(e),startedAt:typeof t.startedAt=="string"?t.startedAt:"unknown",trigger:t.trigger}}catch{return null}}function Xc(e,t){return e?.kind==="manual-cli"&&Kc(t?.trigger)}function Kc(e){return e?.kind==="watch-source"||e?.kind==="watch-git-head"||e?.kind==="watch-git-index"||e?.kind==="watch-git-state"}async function Zc(e){return ei(e,"SIGTERM"),await ti(e,2e3)?!0:(ei(e,"SIGKILL"),ti(e,1e3))}function ei(e,t){try{process.kill(-e,t)}catch{try{process.kill(e,t)}catch{}}}async function ti(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!V(e))return!0;await eu(50)}return!V(e)}function eu(e){return new Promise(t=>setTimeout(t,e))}function tu(e,t,n){return{version:2,languages:[...t].sort(),pnpmWorkspaces:di(n),typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Ae(n.typescriptProjects),clojureConfigPath:li(n.clojureConfigPath),files:H(e)}}function ui(e,t,n){return Object.fromEntries(t.map(r=>{let i=oe(r).markerFiles,o=r==="typescript"?{typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:Ae(n.typescriptProjects)}:{typescriptProjectMode:"single",typescriptProjects:[]},a=r==="clojure"?li(n.clojureConfigPath):void 0;return[r,{version:2,languages:[r],pnpmWorkspaces:r==="typescript"&&di(n),...o,clojureConfigPath:a,files:H(e,{language:r,markerFiles:i})}]}))}function li(e){return e?.trim()||void 0}function di(e){return e.typescriptProjectMode!=="workspace"&&e.pnpmWorkspaces===!0}function Dt(e,t){return b(m(e),"language-indexes",`${t}.scip`)}function pi(e){return b(m(e),"language-indexes","typescript-projects")}function De(e,t){return b(pi(e),`${tt(t)}.scip`)}function te(e){try{return JSON.parse(ke(e,"utf-8"))}catch{return null}}function nu(e,t){try{let n=JSON.parse(ke(e,"utf-8"));return(n.version===2||n.version===3)&&n.status==="complete"&&E(n.fingerprint)===E(t)&&E([...n.indexedLanguages??[]].sort())===E(t.languages)}catch{return!1}}function Ft(e,t){R(e,t,{spacing:2,trailingNewline:!0})}function gi(e,t){try{let n=JSON.parse(ke(e,"utf-8"));if(n.version!==2&&n.version!==3)return;Ft(e,{...n,lastRefresh:t})}catch{}}function Fe(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 E(e){return JSON.stringify(e)}export{hi as INDEXER_CONFIGS,Wt as augmentAuxiliaryDocuments,zs as augmentVueResolvedReferences,C as auxiliaryDocumentsAugmentationStage,je as describeIndexerBinary,He as detectLanguages,oe as getIndexerConfig,Le as getIndexerExecutionEnv,yi as isBinaryAvailable,_e as isIndexerInstalled,Ye as mergeScipFiles,ze as mergeScipIndexes,ep as reindex,Oe as resolveIndexerBinary,Me as resolveProjectLocalIndexerBinary,O as runPostIndexAugmentation,Ce as tryInstallIndexer,Ge as tryInstallScipCli,Yr as vueResolvedReferencesAugmentationStage};
|
|
70
299
|
//# sourceMappingURL=reindex.js.map
|