@zipbul/gildash 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  // @bun
2
- var Li=Object.defineProperty;var Yi=(n,u)=>{for(var i in u)Li(n,i,{get:u[i],enumerable:!0,configurable:!0,set:(t)=>u[i]=()=>t})};var Au=import.meta.require;import{isErr as ht}from"@zipbul/result";import{err as Xn,isErr as Wn}from"@zipbul/result";import Dn from"path";import{existsSync as Yt}from"fs";import{err as _u,isErr as bi}from"@zipbul/result";import{Database as Ri}from"bun:sqlite";import{mkdirSync as yi,unlinkSync as Ju,existsSync as Nu}from"fs";import{dirname as Fi,join as Mu}from"path";import{drizzle as pi}from"drizzle-orm/bun-sqlite";import{migrate as Ei}from"drizzle-orm/bun-sqlite/migrator";function J(n,u,i){return i!==void 0?{type:n,message:u,cause:i}:{type:n,message:u}}var nn=".gildash",In="gildash.db";var Fn={};Yi(Fn,{watcherOwner:()=>Ci,symbols:()=>U,relations:()=>W,files:()=>R});import{sql as Zi}from"drizzle-orm";import{sqliteTable as Hn,text as C,integer as d,real as Gi,index as gn,primaryKey as Xi,foreignKey as yn,check as Ti}from"drizzle-orm/sqlite-core";var R=Hn("files",{project:C("project").notNull(),filePath:C("file_path").notNull(),mtimeMs:Gi("mtime_ms").notNull(),size:d("size").notNull(),contentHash:C("content_hash").notNull(),updatedAt:C("updated_at").notNull(),lineCount:d("line_count")},(n)=>[Xi({columns:[n.project,n.filePath]})]),U=Hn("symbols",{id:d("id").primaryKey({autoIncrement:!0}),project:C("project").notNull(),filePath:C("file_path").notNull(),kind:C("kind").notNull(),name:C("name").notNull(),startLine:d("start_line").notNull(),startColumn:d("start_column").notNull(),endLine:d("end_line").notNull(),endColumn:d("end_column").notNull(),isExported:d("is_exported").notNull().default(0),signature:C("signature"),fingerprint:C("fingerprint"),detailJson:C("detail_json"),contentHash:C("content_hash").notNull(),indexedAt:C("indexed_at").notNull(),resolvedType:C("resolved_type")},(n)=>[gn("idx_symbols_project_file").on(n.project,n.filePath),gn("idx_symbols_project_kind").on(n.project,n.kind),gn("idx_symbols_project_name").on(n.project,n.name),gn("idx_symbols_fingerprint").on(n.project,n.fingerprint),yn({columns:[n.project,n.filePath],foreignColumns:[R.project,R.filePath]}).onDelete("cascade")]),W=Hn("relations",{id:d("id").primaryKey({autoIncrement:!0}),project:C("project").notNull(),type:C("type").notNull(),srcFilePath:C("src_file_path").notNull(),srcSymbolName:C("src_symbol_name"),dstProject:C("dst_project").notNull(),dstFilePath:C("dst_file_path").notNull(),dstSymbolName:C("dst_symbol_name"),metaJson:C("meta_json")},(n)=>[gn("idx_relations_src").on(n.project,n.srcFilePath),gn("idx_relations_dst").on(n.dstProject,n.dstFilePath),gn("idx_relations_type").on(n.project,n.type),yn({columns:[n.project,n.srcFilePath],foreignColumns:[R.project,R.filePath]}).onDelete("cascade"),yn({columns:[n.dstProject,n.dstFilePath],foreignColumns:[R.project,R.filePath]}).onDelete("cascade")]),Ci=Hn("watcher_owner",{id:d("id").primaryKey(),pid:d("pid").notNull(),startedAt:C("started_at").notNull(),heartbeatAt:C("heartbeat_at").notNull()},(n)=>[Ti("watcher_owner_singleton",Zi`${n.id} = 1`)]);class pn{client=null;drizzle=null;dbPath;txDepth=0;constructor(n){this.dbPath=Mu(n.projectRoot,nn,In)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{yi(Fi(this.dbPath),{recursive:!0}),this.client=new Ri(this.dbPath),this.client.run("PRAGMA journal_mode = WAL"),this.client.run("PRAGMA foreign_keys = OFF"),this.client.run("PRAGMA busy_timeout = 5000"),this.drizzle=pi(this.client,{schema:Fn}),Ei(this.drizzle,{migrationsFolder:Mu(import.meta.dirname,"migrations")});let n=this.client.prepare("PRAGMA foreign_key_check").all();if(n.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(n.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON");let u=this.client;if(typeof u.function==="function")u.function.call(this.client,"regexp",(i,t)=>{try{return new RegExp(i).test(t)?1:0}catch{return 0}})}catch(n){if(this.isCorruptionError(n)&&Nu(this.dbPath)){this.closeClient(),Ju(this.dbPath);for(let i of["-wal","-shm"]){let t=this.dbPath+i;if(Nu(t))Ju(t)}let u=this.open();if(bi(u))return _u(J("store",`Failed to recover database at ${this.dbPath}`,u.data));return u}return _u(J("store",`Failed to open database at ${this.dbPath}`,n))}}close(){this.closeClient(),this.drizzle=null}transaction(n){let u=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return u.transaction(()=>n(this))()}finally{this.txDepth--}}let i=`sp_${this.txDepth++}`;u.run(`SAVEPOINT "${i}"`);try{let t=n(this);return u.run(`RELEASE SAVEPOINT "${i}"`),t}catch(t){throw u.run(`ROLLBACK TO SAVEPOINT "${i}"`),u.run(`RELEASE SAVEPOINT "${i}"`),t}finally{this.txDepth--}}immediateTransaction(n){let u=this.requireClient();this.txDepth++,u.run("BEGIN IMMEDIATE");try{let i=n();return u.run("COMMIT"),i}catch(i){throw u.run("ROLLBACK"),i}finally{this.txDepth--}}query(n){let u=this.requireClient().prepare(n).get();if(!u)return null;return Object.values(u)[0]}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((u)=>u.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(n){let u=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at) VALUES (1, ?, ?, ?)").run(n,u,u)}replaceOwner(n){let u=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at) VALUES (1, ?, ?, ?)").run(n,u,u)}touchOwner(n){let u=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(u,n)}deleteOwner(n){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(n)}requireClient(){if(!this.client)throw Error("Database is not open. Call open() first.");return this.client}closeClient(){if(this.client)this.client.close(),this.client=null}isCorruptionError(n){if(!(n instanceof Error))return!1;let u=n.message.toLowerCase();return u.includes("malformed")||u.includes("corrupt")||u.includes("not a database")||u.includes("disk i/o error")||u.includes("sqlite_corrupt")}}import{eq as _n,and as $u}from"drizzle-orm";class En{db;constructor(n){this.db=n}getFile(n,u){return this.db.drizzleDb.select().from(R).where($u(_n(R.project,n),_n(R.filePath,u))).get()??null}upsertFile(n){this.db.drizzleDb.insert(R).values({project:n.project,filePath:n.filePath,mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}).onConflictDoUpdate({target:[R.project,R.filePath],set:{mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}}).run()}getAllFiles(n){return this.db.drizzleDb.select().from(R).where(_n(R.project,n)).all()}getFilesMap(n){let u=this.getAllFiles(n),i=new Map;for(let t of u)i.set(t.filePath,t);return i}deleteFile(n,u){this.db.drizzleDb.delete(R).where($u(_n(R.project,n),_n(R.filePath,u))).run()}}import{eq as y,and as rn,sql as Vn,count as vi}from"drizzle-orm";function Kn(n){return n.trim().split(/\s+/).map((u)=>u.trim()).filter((u)=>u.length>0).map((u)=>`"${u.replaceAll('"','""')}"*`).join(" ")}class vn{db;constructor(n){this.db=n}replaceFileSymbols(n,u,i,t){if(this.db.drizzleDb.delete(U).where(rn(y(U.project,n),y(U.filePath,u))).run(),!t.length)return;let m=new Date().toISOString();for(let g of t)this.db.drizzleDb.insert(U).values({project:n,filePath:u,kind:g.kind??"unknown",name:g.name??"",startLine:g.startLine??0,startColumn:g.startColumn??0,endLine:g.endLine??0,endColumn:g.endColumn??0,isExported:g.isExported??0,signature:g.signature??null,fingerprint:g.fingerprint??null,detailJson:g.detailJson??null,contentHash:i,indexedAt:g.indexedAt??m,resolvedType:g.resolvedType??null}).run()}getFileSymbols(n,u){return this.db.drizzleDb.select().from(U).where(rn(y(U.project,n),y(U.filePath,u))).all()}searchByName(n,u,i={}){let t=i.limit??50,m=Kn(u);if(!m)return[];return this.db.drizzleDb.select().from(U).where(rn(Vn`${U.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${m})`,y(U.project,n),i.kind?y(U.kind,i.kind):void 0)).orderBy(U.name).limit(t).all()}searchByKind(n,u){return this.db.drizzleDb.select().from(U).where(rn(y(U.project,n),y(U.kind,u))).orderBy(U.name).all()}getStats(n){let u=this.db.drizzleDb.select({symbolCount:vi(),fileCount:Vn`COUNT(DISTINCT ${U.filePath})`}).from(U).where(y(U.project,n)).get();return{symbolCount:u?.symbolCount??0,fileCount:u?.fileCount??0}}getByFingerprint(n,u){return this.db.drizzleDb.select().from(U).where(rn(y(U.project,n),y(U.fingerprint,u))).all()}deleteFileSymbols(n,u){this.db.drizzleDb.delete(U).where(rn(y(U.project,n),y(U.filePath,u))).run()}searchByQuery(n){let u=this.db.drizzleDb.select().from(U).where(rn(n.ftsQuery?Vn`${U.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${n.ftsQuery})`:void 0,n.exactName?y(U.name,n.exactName):void 0,n.project!==void 0?y(U.project,n.project):void 0,n.kind?y(U.kind,n.kind):void 0,n.filePath!==void 0?y(U.filePath,n.filePath):void 0,n.isExported!==void 0?y(U.isExported,n.isExported?1:0):void 0,n.decorator?Vn`${U.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${n.decorator})`:void 0,n.resolvedType!==void 0?y(U.resolvedType,n.resolvedType):void 0)).orderBy(U.name).limit(n.regex?Math.max(n.limit*50,5000):n.limit).all();if(!n.regex)return u;try{let i=new RegExp(n.regex);return u.filter((t)=>i.test(t.name)).slice(0,n.limit)}catch{return[]}}}import{eq as T,and as x,isNull as Wu,or as qi}from"drizzle-orm";class qn{db;constructor(n){this.db=n}replaceFileRelations(n,u,i){this.db.transaction((t)=>{if(t.drizzleDb.delete(W).where(x(T(W.project,n),T(W.srcFilePath,u))).run(),!i.length)return;for(let m of i)t.drizzleDb.insert(W).values({project:n,type:m.type??"unknown",srcFilePath:m.srcFilePath??u,srcSymbolName:m.srcSymbolName??null,dstProject:m.dstProject??n,dstFilePath:m.dstFilePath??"",dstSymbolName:m.dstSymbolName??null,metaJson:m.metaJson??null}).run()})}getOutgoing(n,u,i){if(i!==void 0)return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(T(W.project,n),T(W.srcFilePath,u),qi(T(W.srcSymbolName,i),Wu(W.srcSymbolName)))).all();return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(T(W.project,n),T(W.srcFilePath,u))).all()}getIncoming(n){let{dstProject:u,dstFilePath:i}=n;return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(T(W.dstProject,u),T(W.dstFilePath,i))).all()}getByType(n,u){return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(T(W.project,n),T(W.type,u))).all()}deleteFileRelations(n,u){this.db.drizzleDb.delete(W).where(x(T(W.project,n),T(W.srcFilePath,u))).run()}searchRelations(n){return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(n.project!==void 0?T(W.project,n.project):void 0,n.srcFilePath!==void 0?T(W.srcFilePath,n.srcFilePath):void 0,n.srcSymbolName!==void 0?T(W.srcSymbolName,n.srcSymbolName):void 0,n.dstProject!==void 0?T(W.dstProject,n.dstProject):void 0,n.dstFilePath!==void 0?T(W.dstFilePath,n.dstFilePath):void 0,n.dstSymbolName!==void 0?T(W.dstSymbolName,n.dstSymbolName):void 0,n.type!==void 0?T(W.type,n.type):void 0)).limit(n.limit).all()}retargetRelations(n){let{dstProject:u,oldFile:i,oldSymbol:t,newFile:m,newSymbol:g,newDstProject:O}=n,r=t===null?x(T(W.dstProject,u),T(W.dstFilePath,i),Wu(W.dstSymbolName)):x(T(W.dstProject,u),T(W.dstFilePath,i),T(W.dstSymbolName,t)),w={dstFilePath:m,dstSymbolName:g};if(O!==void 0)w.dstProject=O;this.db.drizzleDb.update(W).set(w).where(r).run()}}import{err as Du}from"@zipbul/result";import{subscribe as ji}from"@parcel/watcher";import jn from"path";var Pi=["**/.git/**",`**/${nn}/**`,"**/dist/**","**/node_modules/**"],di=new Set(["package.json","tsconfig.json"]);function hi(n){return n.replaceAll("\\","/")}function oi(n){if(n==="update")return"change";if(n==="create")return"create";return"delete"}class Pn{#n;#u;#i;#m;#t;#g;constructor(n,u=ji,i=console){this.#u=n.projectRoot,this.#i=[...Pi,...n.ignorePatterns??[]],this.#m=new Set((n.extensions??[".ts",".mts",".cts"]).map((t)=>t.toLowerCase())),this.#t=u,this.#g=i}async start(n){try{this.#n=await this.#t(this.#u,(u,i)=>{if(u){this.#g.error(J("watcher","Callback error",u));return}try{for(let t of i){let m=hi(jn.relative(this.#u,t.path));if(m.startsWith(".."))continue;let g=jn.basename(m),O=jn.extname(m).toLowerCase();if(!di.has(g)&&!this.#m.has(O))continue;if(m.endsWith(".d.ts"))continue;n({eventType:oi(t.type),filePath:m})}}catch(t){this.#g.error(J("watcher","Callback error",t))}},{ignore:this.#i})}catch(u){return Du(J("watcher","Failed to subscribe watcher",u))}}async close(){if(!this.#n)return;try{await this.#n.unsubscribe(),this.#n=void 0}catch(n){return Du(J("watcher","Failed to close watcher",n))}}}import dn from"path";import{promises as xi}from"fs";var li=["**/node_modules/**","**/.git/**",`**/${nn}/**`,"**/dist/**"];async function zn(n){let u=[];for await(let i of xi.glob("**/package.json",{cwd:n,exclude:li})){let t=dn.dirname(i).replaceAll("\\","/"),m=dn.join(n,i),g=await Bun.file(m).json(),O=typeof g?.name==="string"&&g.name.length>0?g.name:dn.basename(t==="."?n:t);u.push({dir:t,project:O})}return u.sort((i,t)=>t.dir.length-i.dir.length),u}function j(n,u,i="default"){let t=n.replaceAll("\\","/");for(let m of u){if(m.dir===".")return m.project;if(t===m.dir||t.startsWith(`${m.dir}/`))return m.project}return i}import ku from"path";var un=new Map;async function ci(n){let u=Bun.file(n);if(!await u.exists())return null;try{let i=await u.text(),t=Bun.JSONC.parse(i);return typeof t==="object"&&t!==null?t:null}catch{return null}}async function Jn(n){if(un.has(n))return un.get(n)??null;let u=ku.join(n,"tsconfig.json"),i=await ci(u);if(!i)return un.set(n,null),null;let t=typeof i.compilerOptions==="object"&&i.compilerOptions!==null?i.compilerOptions:null;if(!t)return un.set(n,null),null;let m=typeof t.baseUrl==="string"?t.baseUrl:null,g=typeof t.paths==="object"&&t.paths!==null?t.paths:null;if(!m&&!g)return un.set(n,null),null;let O=m?ku.resolve(n,m):n,r=new Map;if(g)for(let[a,s]of Object.entries(g)){if(!Array.isArray(s))continue;let f=s.filter((M)=>typeof M==="string");r.set(a,f)}let w={baseUrl:O,paths:r};return un.set(n,w),w}function Bn(n){if(n){un.delete(n);return}un.clear()}import Iu from"path";function Un(n,u){return Iu.relative(n,u).replaceAll("\\","/")}function an(n,u){return Iu.resolve(n,u)}function tn(n){let u=Bun.hash.xxHash64(n);return BigInt.asUintN(64,BigInt(u)).toString(16).padStart(16,"0")}import{isErr as Zu}from"@zipbul/result";import{err as ei}from"@zipbul/result";import{parseSync as nt}from"oxc-parser";function Nn(n,u,i,t=nt){try{let{program:m,errors:g,comments:O}=t(n,u,i);return{filePath:n,program:m,errors:g,comments:O,sourceText:u}}catch(m){return ei(J("parse",`Failed to parse file: ${n}`,m))}}import{promises as ut}from"fs";import{join as it}from"path";async function Hu(n){let{projectRoot:u,extensions:i,ignorePatterns:t,fileRepo:m}=n,g=m.getFilesMap(),O=new Set,r=[],w=[],a=t.map((f)=>new Bun.Glob(f));for await(let f of ut.glob("**/*",{cwd:u})){if(!i.some((S)=>f.endsWith(S)))continue;if(f.startsWith("node_modules/")||f.includes("/node_modules/"))continue;if(a.some((S)=>S.match(f)))continue;O.add(f);let M=it(u,f),k=Bun.file(M),{size:H,lastModified:K}=k,B=g.get(f);if(!B){let S=await k.text(),_=tn(S);r.push({filePath:f,contentHash:_,mtimeMs:K,size:H});continue}if(B.mtimeMs===K&&B.size===H){w.push({filePath:f,contentHash:B.contentHash,mtimeMs:K,size:H});continue}let A=await k.text(),N=tn(A);if(N===B.contentHash)w.push({filePath:f,contentHash:N,mtimeMs:K,size:H});else r.push({filePath:f,contentHash:N,mtimeMs:K,size:H})}let s=[];for(let f of g.keys())if(!O.has(f))s.push(f);return{changed:r,unchanged:w,deleted:s}}function Ku(n){let u=[0];for(let i=0;i<n.length;i++)if(n[i]===`
3
- `)u.push(i+1);return u}function hn(n,u){let i=0,t=n.length-1;while(i<t){let m=i+t+1>>1;if(n[m]<=u)i=m;else t=m-1}return{line:i+1,column:u-n[i]}}import{err as tt}from"@zipbul/result";import{parse as mt}from"comment-parser";function Vu(n){try{let u=n.trim();if(u.startsWith("/**"))u=u.slice(3);if(u.endsWith("*/"))u=u.slice(0,-2);let t=mt(`/** ${u} */`)[0]??{description:"",tags:[]};return{description:(t.description??"").trim(),tags:(t.tags??[]).map((m)=>({tag:m.tag??"",name:m.name??"",type:m.type??"",description:m.description??"",optional:m.optional??!1,...m.default!==void 0?{default:m.default}:{}}))}}catch(u){return tt(J("parse","Failed to parse JSDoc comment",u))}}import{isErr as gt}from"@zipbul/result";function Qn(n){let{program:u,sourceText:i,comments:t}=n,m=Ku(i);function g(A,N){return{start:hn(m,A),end:hn(m,N)}}function O(A){let N=null;for(let S of t){if(S.type!=="Block")continue;if(S.end>A)continue;if(!S.value.startsWith("*"))continue;if(!N||S.end>N.end)N={value:`/*${S.value}*/`,end:S.end}}if(!N)return;for(let S of u.body){let _=S.start??0;if(_===A)continue;if(_>N.end&&_<A)return}return N.value}function r(A){if(!A)return;let N=A.typeAnnotation??A;return i.slice(N.start,N.end)}function w(A){if(!A||A.length===0)return[];return A.map((N)=>{let S=N.expression;if(!S)return{name:"unknown"};if(S.type==="CallExpression"){let _=S.callee?.name??S.callee?.property?.name??"unknown",$=(S.arguments??[]).map((I)=>i.slice(I.start,I.end));return{name:_,arguments:$.length>0?$:void 0}}if(S.type==="Identifier")return{name:S.name??"unknown"};return{name:i.slice(S.start,S.end)}})}function a(A){let N=A.type==="TSParameterProperty"?A.parameter:A;if(N?.type==="RestElement"){let X=`...${N.argument?.name??"unknown"}`,D=N.typeAnnotation,Y=D?r(D):void 0,Q={name:X,isOptional:!1};if(Y)Q.type=Y;return Q}if(N?.type==="AssignmentPattern"){let{left:V,right:X}=N,D=V?.name??"unknown",Y=V?.typeAnnotation,Q=Y?r(Y):void 0,E=i.slice(X.start,X.end),h=w(V?.decorators??[]),o={name:D,isOptional:!0,defaultValue:E};if(Q)o.type=Q;if(h.length>0)o.decorators=h;return o}let S=N?.name??N?.pattern?.name??"unknown",_=!!N?.optional,$=N?.typeAnnotation,I=$?r($):void 0,z=w(N?.decorators??[]),L={name:S,isOptional:_};if(I)L.type=I;if(z.length>0)L.decorators=z;return L}function s(A,N){let S=[];if(N?.async)S.push("async");if(A.static)S.push("static");if(A.abstract)S.push("abstract");if(A.readonly)S.push("readonly");if(A.override)S.push("override");if(A.declare)S.push("declare");if(A.const)S.push("const");let _=A.accessibility;if(_==="private")S.push("private");else if(_==="protected")S.push("protected");else if(_==="public")S.push("public");return S}function f(A){let N=[];if(A.superClass){let _=i.slice(A.superClass.start,A.superClass.end);N.push({kind:"extends",name:_})}let S=A.implements??[];for(let _ of S){let $=_.expression??_,I=i.slice($.start,$.end);N.push({kind:"implements",name:I})}return N}function M(A){let N=[];for(let S of A.extends??[]){let _=S.expression??S,$=i.slice(_.start,_.end);N.push({kind:"extends",name:$})}return N}function k(A){let N=[];for(let S of A)if(S.type==="MethodDefinition"){let _=S.key?.name??"unknown",$=S.value,I=S.kind??"method",z=I==="constructor"?"constructor":I==="get"?"getter":I==="set"?"setter":"method",L=s(S,$),V=($?.params??[]).map(a),X=r($?.returnType),D={kind:"method",name:_,span:g(S.start,S.end),isExported:!1,methodKind:z,modifiers:L,parameters:V.length>0?V:void 0,returnType:X};N.push(D)}else if(S.type==="PropertyDefinition"){let _=S.key?.name??"unknown",$=s(S),I={kind:"property",name:_,span:g(S.start,S.end),isExported:!1,modifiers:$};N.push(I)}return N}function H(A){let N=[];for(let S of A)if(S.type==="TSMethodSignature"){let _=S.key?.name??"unknown",$=(S.params??[]).map(a),I=r(S.returnType);N.push({kind:"method",name:_,span:g(S.start,S.end),isExported:!1,modifiers:[],methodKind:"method",parameters:$.length>0?$:void 0,returnType:I})}else if(S.type==="TSPropertySignature"){let _=S.key?.name??"unknown",$=r(S.typeAnnotation),I={kind:"property",name:_,span:g(S.start,S.end),isExported:!1,modifiers:S.readonly?["readonly"]:[],returnType:$};N.push(I)}return N}function K(A,N){let S=A.type??"";if(S==="FunctionDeclaration"){let _=A.id?.name??"default",$=(A.params??[]).map(a),I=r(A.returnType),z=s(A,A),L=w(A.decorators??[]),V=A.typeParameters?.params?.map((D)=>D.name?.name).filter(Boolean)||void 0,X={kind:"function",name:_,span:g(A.start,A.end),isExported:N,modifiers:z,parameters:$.length>0?$:void 0,returnType:I,decorators:L.length>0?L:void 0};if(V&&V.length>0)X.typeParameters=V;return X}if(S==="ClassDeclaration"||S==="ClassExpression"){let _=A.id?.name??"default",$=f(A),I=k(A.body?.body??[]),z=w(A.decorators??[]),L=s(A,A),V=A.typeParameters?.params?.map((D)=>D.name?.name).filter(Boolean)||void 0,X={kind:"class",name:_,span:g(A.start,A.end),isExported:N,modifiers:L,heritage:$.length>0?$:void 0,members:I.length>0?I:void 0,decorators:z.length>0?z:void 0};if(V&&V.length>0)X.typeParameters=V;return X}if(S==="VariableDeclaration"){let _=[];for(let $ of A.declarations??[]){let{id:I,init:z}=$;if(I?.type==="ObjectPattern"){for(let Q of I.properties??[]){let E=Q.value?.name??Q.key?.name??"unknown";_.push({kind:"variable",name:E,span:g(Q.start??$.start,Q.end??$.end),isExported:N,modifiers:[]})}continue}if(I?.type==="ArrayPattern"){for(let Q of I.elements??[]){if(!Q||Q.type!=="Identifier")continue;let E=Q.name??"unknown";_.push({kind:"variable",name:E,span:g(Q.start??$.start,Q.end??$.end),isExported:N,modifiers:[]})}continue}let L=I?.name??"unknown",V="variable",X,D;if(z?.type==="FunctionExpression"||z?.type==="ArrowFunctionExpression")V="function",X=(z.params??[]).map(a),D=r(z.returnType);let Y=[];_.push({kind:V,name:L,span:g($.start,$.end),isExported:N,modifiers:Y,parameters:X,returnType:D})}if(_.length===0)return null;if(_.length===1)return _[0];return _}if(S==="TSTypeAliasDeclaration")return{kind:"type",name:A.id?.name??"unknown",span:g(A.start,A.end),isExported:N,modifiers:[]};if(S==="TSInterfaceDeclaration"){let _=A.id?.name??"unknown",$=M(A),I=H(A.body?.body??[]),z=A.typeParameters?.params?.map((V)=>V.name?.name).filter(Boolean)||void 0,L={kind:"interface",name:_,span:g(A.start,A.end),isExported:N,modifiers:[],heritage:$.length>0?$:void 0,members:I.length>0?I:void 0};if(z&&z.length>0)L.typeParameters=z;return L}if(S==="TSEnumDeclaration"){let _=A.id?.name??"unknown",$=s(A),z=(A.body?.members??[]).map((L)=>({kind:"property",name:L.id?.name??L.id?.value??"unknown",span:g(L.start,L.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:_,span:g(A.start,A.end),isExported:N,modifiers:$,members:z.length>0?z:void 0}}return null}let B=[];for(let A of u.body){let N=null,S=A,_=typeof S.type==="string"?S.type:"";if(_==="ExportNamedDeclaration"){let I=A;if(I.declaration){if(N=K(I.declaration,!0),N&&!Array.isArray(N))N.span=g(I.start,I.end);else if(Array.isArray(N))for(let z of N)z.span=g(I.start,I.end)}}else if(_==="ExportDefaultDeclaration"){let I=A,z=I.declaration;if(z){if(N=K(z,!0),N&&!Array.isArray(N))N.name=z.id?.name??"default",N.isExported=!0,N.span=g(I.start,I.end)}}else N=K(A,!1);let $=Array.isArray(N)?N:N?[N]:[];for(let I of $){let z=A.start??0,L=O(z);if(L){let V=Vu(L);if(!gt(V))I.jsDoc=V}B.push(I)}}return B}function rt(n){if(n.kind==="function"||n.kind==="method"){let u=n.parameters?.length??0,i=n.modifiers.includes("async")?1:0;return`params:${u}|async:${i}`}return null}function wt(n){let u={};if(n.jsDoc)u.jsDoc=n.jsDoc;if(n.kind==="function"||n.kind==="method"){if(n.parameters!==void 0)u.parameters=n.parameters;if(n.returnType!==void 0)u.returnType=n.returnType}if(n.heritage?.length)u.heritage=n.heritage;if(n.decorators?.length)u.decorators=n.decorators;if(n.typeParameters?.length)u.typeParameters=n.typeParameters;if(n.modifiers?.length)u.modifiers=n.modifiers;if(n.members?.length)u.members=n.members.map((i)=>{let t=i.modifiers.find((m)=>m==="private"||m==="protected"||m==="public");return{name:i.name,kind:i.methodKind??i.kind,type:i.returnType,visibility:t,isStatic:i.modifiers.includes("static")||void 0,isReadonly:i.modifiers.includes("readonly")||void 0}});return Object.keys(u).length>0?JSON.stringify(u):null}function zu(n,u,i,t,m){let g=rt(n),O=tn(`${u}|${n.kind}|${g??""}`);return{project:i,filePath:t,kind:n.kind,name:u,startLine:n.span.start.line,startColumn:n.span.start.column,endLine:n.span.end.line,endColumn:n.span.end.column,isExported:n.isExported?1:0,signature:g,fingerprint:O,detailJson:wt(n),contentHash:m,indexedAt:new Date().toISOString()}}function on(n){let{parsed:u,project:i,filePath:t,contentHash:m,symbolRepo:g}=n,O=Qn(u),r=[];for(let w of O){r.push(zu(w,w.name,i,t,m));for(let a of w.members??[])r.push(zu(a,`${w.name}.${a.name}`,i,t,m))}g.replaceFileSymbols(i,t,m,r)}import{resolve as xn,dirname as Ot,extname as St}from"path";function wn(n,u,i){let t=(m)=>{let g=St(m);if(g==="")return[m+".ts",m+".d.ts",m+"/index.ts",m+"/index.d.ts",m+".mts",m+"/index.mts",m+".cts",m+"/index.cts"];if(g===".js")return[m.slice(0,-3)+".ts"];if(g===".mjs")return[m.slice(0,-4)+".mts"];if(g===".cjs")return[m.slice(0,-4)+".cts"];return[m]};if(u.startsWith(".")){let m=xn(Ot(n),u);return t(m)}if(i)for(let[m,g]of i.paths){if(g.length===0)continue;let O=m.indexOf("*");if(O===-1){if(u===m){let r=[];for(let w of g)r.push(...t(xn(i.baseUrl,w)));return r}}else{let r=m.slice(0,O),w=m.slice(O+1);if(u.startsWith(r)&&(w===""||u.endsWith(w))){let a=u.slice(r.length,w===""?void 0:u.length-w.length),s=[];for(let f of g)s.push(...t(xn(i.baseUrl,f.replace("*",a))));return s}}}return[]}function Bu(n,u,i,t=wn){let m=new Map,g=n.body??[];for(let O of g){if(O.type!=="ImportDeclaration")continue;let r=O.source?.value??"",w=t(u,r,i);if(w.length===0)continue;let a=w[0],s=O.specifiers??[];for(let f of s)switch(f.type){case"ImportSpecifier":m.set(f.local.name,{path:a,importedName:f.imported.name});break;case"ImportDefaultSpecifier":m.set(f.local.name,{path:a,importedName:"default"});break;case"ImportNamespaceSpecifier":m.set(f.local.name,{path:a,importedName:"*"});break}}return m}var at=new Set(["loc","start","end","scope"]);function sn(n,u){if(!n||typeof n!=="object")return;if(Array.isArray(n)){for(let t of n)sn(t,u);return}let i=n;u(i);for(let t of Object.keys(i)){if(at.has(t))continue;let m=i[t];if(m&&typeof m==="object")sn(m,u)}}function Uu(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if((u.type==="StringLiteral"||u.type==="Literal")&&typeof u.value==="string")return u.value;return null}function On(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if(u.type==="Identifier"){let i=u.name;return{root:i,parts:[],full:i}}if(u.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(u.type==="Super")return{root:"super",parts:[],full:"super"};if(u.type==="MemberExpression"){let i=[],t=u;while(t.type==="MemberExpression"){let O=t.property;if(!O||typeof O.name!=="string")return null;i.unshift(O.name),t=t.object}let m;if(t.type==="Identifier")m=t.name;else if(t.type==="ThisExpression")m="this";else if(t.type==="Super")m="super";else return null;let g=[m,...i].join(".");return{root:m,parts:i,full:g}}return null}function Qu(n,u,i,t=wn){let m=[],g=n.body??[];for(let O of g){if(O.type==="ImportDeclaration"){let r=O.source?.value??"",w=t(u,r,i);if(w.length===0)continue;let a=w[0],s=O.importKind==="type",f=O.specifiers??[];if(f.length===0){let M={};if(s)M.isType=!0;m.push({type:s?"type-references":"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:a,dstSymbolName:null,...Object.keys(M).length>0?{metaJson:JSON.stringify(M)}:{}})}else for(let M of f){let k=M.type,H=s||M.importKind==="type",K={};if(H)K.isType=!0;let B,A;if(k==="ImportDefaultSpecifier")B="default",A=M.local.name;else if(k==="ImportNamespaceSpecifier")B="*",A=M.local.name,K.importKind="namespace";else B=M.imported.name,A=M.local.name;m.push({type:H?"type-references":"imports",srcFilePath:u,srcSymbolName:A,dstFilePath:a,dstSymbolName:B,...Object.keys(K).length>0?{metaJson:JSON.stringify(K)}:{}})}continue}if(O.type==="ExportAllDeclaration"&&O.source){let r=O.source?.value??"",w=t(u,r,i);if(w.length===0)continue;let a=w[0],s=O.exportKind==="type",f={isReExport:!0};if(s)f.isType=!0;m.push({type:s?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:a,dstSymbolName:null,metaJson:JSON.stringify(f)});continue}if(O.type==="ExportNamedDeclaration"&&O.source){let r=O.source?.value??"",w=t(u,r,i);if(w.length===0)continue;let a=w[0],s=O.exportKind==="type",k={isReExport:!0,specifiers:(O.specifiers??[]).map((H)=>({local:H.local.name,exported:H.exported.name}))};if(s)k.isType=!0;m.push({type:s?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:a,dstSymbolName:null,metaJson:JSON.stringify(k)})}}return sn(n,(O)=>{if(O.type!=="ImportExpression")return;let r=Uu(O.source);if(!r)return;let w=t(u,r,i);if(w.length===0)return;let a=w[0];m.push({type:"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:a,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),m}function Lu(n,u,i){let t=[],m=[],g=[];function O(){if(m.length>0)return m[m.length-1]??null;return null}function r(a){if(!a)return null;let s=i.get(a.root);if(a.parts.length===0){if(s)return{dstFilePath:s.path,dstSymbolName:s.importedName,resolution:"import"};return{dstFilePath:u,dstSymbolName:a.root,resolution:"local"}}else{if(s&&s.importedName==="*"){let f=a.parts[a.parts.length-1];return{dstFilePath:s.path,dstSymbolName:f,resolution:"namespace"}}return{dstFilePath:u,dstSymbolName:a.full,resolution:"local-member"}}}function w(a){if(!a||typeof a!=="object")return;if(Array.isArray(a)){for(let M of a)w(M);return}let s=a,f=typeof s.type==="string"?s.type:"";if(f==="ClassDeclaration"||f==="ClassExpression"){let M=s,k=M.id?.name??"AnonymousClass";g.push(k),w(M.body),g.pop();return}if(f==="FunctionDeclaration"){let M=s,k=M.id?.name??"anonymous";m.push(k),w(M.body),m.pop();return}if(f==="VariableDeclarator"&&s.init&&(s.init?.type==="FunctionExpression"||s.init?.type==="ArrowFunctionExpression")){let M=s,k=M.id?.name??"anonymous";m.push(k),w(M.init?.body??M.init),m.pop();return}if(f==="MethodDefinition"&&s.value){let M=s,k=g[g.length-1]??"",H=M.key?.name??"anonymous",K=k?`${k}.${H}`:H;m.push(K),w(M.value?.body),m.pop();return}if(f==="FunctionExpression"||f==="ArrowFunctionExpression"){let M=O(),k=M?`${M}.<anonymous>`:"<anonymous>";m.push(k),w(s.body),m.pop();return}if(f==="CallExpression"){let M=s,k=On(M.callee),H=r(k);if(H){let K=O(),B={};if(K===null)B.scope="module";t.push({type:"calls",srcFilePath:u,srcSymbolName:K,dstFilePath:H.dstFilePath,dstSymbolName:H.dstSymbolName,...Object.keys(B).length>0?{metaJson:JSON.stringify(B)}:{}})}w(M.callee);for(let K of M.arguments??[])w(K);return}if(f==="NewExpression"){let M=s,k=On(M.callee),H=r(k);if(H){let K=O(),B={isNew:!0};if(K===null)B.scope="module";t.push({type:"calls",srcFilePath:u,srcSymbolName:K,dstFilePath:H.dstFilePath,dstSymbolName:H.dstSymbolName,metaJson:JSON.stringify(B)})}for(let K of M.arguments??[])w(K);return}for(let M of Object.keys(s)){if(M==="loc"||M==="start"||M==="end"||M==="scope")continue;let k=s[M];if(k&&typeof k==="object")w(k)}}return w(n),t}function Yu(n,u,i){let t=[];return sn(n,(m)=>{if(m.type==="TSInterfaceDeclaration"){let r=m.id?.name??"AnonymousInterface",w=m.extends??[];for(let a of w){let s=a.expression??a,f=On(s);if(!f)continue;let M=ln(f,u,i);t.push({type:"extends",srcFilePath:u,srcSymbolName:r,...M})}return}if(m.type!=="ClassDeclaration"&&m.type!=="ClassExpression")return;let g=m.id?.name??"AnonymousClass";if(m.superClass){let r=On(m.superClass);if(r){let w=ln(r,u,i);t.push({type:"extends",srcFilePath:u,srcSymbolName:g,...w})}}let O=m.implements??[];for(let r of O){let w=r.expression??r,a=On(w);if(!a)continue;let s=ln(a,u,i);t.push({type:"implements",srcFilePath:u,srcSymbolName:g,...s})}}),t}function ln(n,u,i){let t=i.get(n.root);if(t){if(t.importedName==="*"){let m=n.parts[n.parts.length-1]??n.root;return{dstFilePath:t.path,dstSymbolName:m,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:t.path,dstSymbolName:n.parts.length>0?n.full:t.importedName}}return{dstFilePath:u,dstSymbolName:n.full,metaJson:JSON.stringify({isLocal:!0})}}function Ln(n,u,i,t=wn){let m=Bu(n,u,i,t),g=Qu(n,u,i,t),O=Lu(n,u,m),r=Yu(n,u,m);return[...g,...O,...r]}function cn(n){let{ast:u,project:i,filePath:t,relationRepo:m,projectRoot:g,tsconfigPaths:O,knownFiles:r,boundaries:w}=n,a=an(g,t),f=Ln(u,a,O,r?(k,H,K)=>{let B=wn(k,H,K);for(let A of B){let N=Un(g,A);if(w){let S=j(N,w);if(r.has(`${S}::${N}`))return[A]}else if(r.has(`${i}::${N}`))return[A]}return[]}:void 0),M=[];for(let k of f){let H=Un(g,k.dstFilePath);if(H.startsWith(".."))continue;let K=Un(g,k.srcFilePath),B=w?j(H,w):i;M.push({project:i,type:k.type,srcFilePath:K,srcSymbolName:k.srcSymbolName??null,dstProject:B,dstFilePath:H,dstSymbolName:k.dstSymbolName??null,metaJson:k.metaJson??null})}return m.replaceFileRelations(i,t,M),M.length}var st=100;class en{opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;constructor(n){this.opts=n,this.logger=n.logger??console,this.tsconfigPathsRaw=Jn(n.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(n){return this.startIndex(n,!1)}onIndexed(n){return this.callbacks.add(n),()=>this.callbacks.delete(n)}handleWatcherEvent(n){if(n.filePath.endsWith("tsconfig.json")){Bn(this.opts.projectRoot),this.tsconfigPathsRaw=Jn(this.opts.projectRoot),this.fullIndex().catch((u)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",u)});return}if(n.filePath.endsWith("package.json")){let u=this.opts.discoverProjectsFn??zn;this.boundariesRefresh=u(this.opts.projectRoot).then((i)=>{this.opts.boundaries=i})}if(this.pendingEvents.push(n),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},st)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(n,u){if(this.indexingLock){if(u)return this.pendingFullIndex=!0,new Promise((t,m)=>{this.pendingFullIndexWaiters.push({resolve:t,reject:m})});return this.currentIndexing}this.indexingLock=!0;let i=this.doIndex(n,u).then((t)=>{return this.fireCallbacks(t),t}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let t=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((m)=>{for(let g of t)g.resolve(m)}).catch((m)=>{for(let g of t)g.reject(m)})}else if(this.pendingEvents.length>0){let t=this.pendingEvents.splice(0);this.startIndex(t,!1).catch((m)=>this.logger.error("[IndexCoordinator] incremental drain error",m))}});return this.currentIndexing=i,i}async doIndex(n,u){let i=Date.now(),{fileRepo:t,symbolRepo:m,relationRepo:g,dbConnection:O}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let r,w;if(n!==void 0)r=n.filter((S)=>S.eventType==="create"||S.eventType==="change").map((S)=>({filePath:S.filePath,contentHash:"",mtimeMs:0,size:0})),w=n.filter((S)=>S.eventType==="delete").map((S)=>S.filePath);else{let S=new Map;for(let $ of this.opts.boundaries)for(let[I,z]of t.getFilesMap($.project))S.set(I,z);let _=await Hu({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>S}});r=_.changed,w=_.deleted}let a=await this.tsconfigPathsRaw??void 0,s=new Map;for(let S of w){let _=j(S,this.opts.boundaries),$=m.getFileSymbols(_,S);s.set(S,$)}let f=new Map,M=new Map;if(u)for(let S of this.opts.boundaries)for(let _ of t.getAllFiles(S.project))for(let $ of m.getFileSymbols(S.project,_.filePath))f.set(`${$.filePath}::${$.name}`,{name:$.name,filePath:$.filePath,kind:$.kind,fingerprint:$.fingerprint});else{for(let S of r){let _=j(S.filePath,this.opts.boundaries);for(let $ of m.getFileSymbols(_,S.filePath))f.set(`${$.filePath}::${$.name}`,{name:$.name,filePath:$.filePath,kind:$.kind,fingerprint:$.fingerprint})}for(let[,S]of s)for(let _ of S)f.set(`${_.filePath}::${_.name}`,{name:_.name,filePath:_.filePath,kind:_.kind,fingerprint:_.fingerprint})}let k=()=>{for(let S of w){let _=j(S,this.opts.boundaries);m.deleteFileSymbols(_,S),g.deleteFileRelations(_,S),t.deleteFile(_,S)}},H=async()=>{let{projectRoot:S,boundaries:_}=this.opts,{parseCache:$}=this.opts,I=0,z=0,L=[],V=[];for(let D of r)try{let Y=an(S,D.filePath),Q=Bun.file(Y),E=await Q.text(),h=D.contentHash||tn(E),o=j(D.filePath,_);t.upsertFile({project:o,filePath:D.filePath,mtimeMs:Q.lastModified,size:Q.size,contentHash:h,updatedAt:new Date().toISOString(),lineCount:E.split(`
4
- `).length});let Z=(this.opts.parseSourceFn??Nn)(Y,E);if(Zu(Z))throw Z.data;let P=Z;V.push({filePath:D.filePath,text:E,contentHash:h,parsed:P,project:o})}catch(Y){this.logger.error(`[IndexCoordinator] Failed to prepare ${D.filePath}:`,Y),L.push(D.filePath)}let X=new Set;for(let D of _)for(let[Y]of t.getFilesMap(D.project))X.add(`${D.project}::${Y}`);return O.transaction(()=>{for(let D of V)on({parsed:D.parsed,project:D.project,filePath:D.filePath,contentHash:D.contentHash,symbolRepo:m}),z+=cn({ast:D.parsed.program,project:D.project,filePath:D.filePath,relationRepo:g,projectRoot:S,tsconfigPaths:a,knownFiles:X,boundaries:_}),$.set(D.filePath,D.parsed),I+=m.getFileSymbols(D.project,D.filePath).length}),{symbols:I,relations:z,failedFiles:L}},K=0,B=0,A=[];if(u){let{projectRoot:S,boundaries:_}=this.opts,{parseCache:$}=this.opts,I=await Promise.allSettled(r.map(async(V)=>{let X=an(S,V.filePath),D=Bun.file(X),Y=await D.text(),Q=V.contentHash||tn(Y);return{filePath:V.filePath,text:Y,contentHash:Q,mtimeMs:D.lastModified,size:D.size}})),z=I.filter((V)=>V.status==="fulfilled").map((V)=>V.value);for(let V of I)if(V.status==="rejected")this.logger.error("[IndexCoordinator] Failed to pre-read file:",V.reason);let L=[];O.transaction(()=>{for(let D of z){let Y=j(D.filePath,_);t.deleteFile(Y,D.filePath)}for(let D of w){let Y=j(D,_);m.deleteFileSymbols(Y,D),g.deleteFileRelations(Y,D),t.deleteFile(Y,D)}for(let D of z){let Y=j(D.filePath,_);t.upsertFile({project:Y,filePath:D.filePath,mtimeMs:D.mtimeMs,size:D.size,contentHash:D.contentHash,updatedAt:new Date().toISOString(),lineCount:D.text.split(`
5
- `).length})}let V=new Set;for(let D of _)for(let[Y]of t.getFilesMap(D.project))V.add(`${D.project}::${Y}`);let X=this.opts.parseSourceFn??Nn;for(let D of z){let Y=j(D.filePath,_),Q=X(an(S,D.filePath),D.text);if(Zu(Q))throw Q.data;let E=Q;L.push({filePath:D.filePath,parsed:E}),on({parsed:E,project:Y,filePath:D.filePath,contentHash:D.contentHash,symbolRepo:m}),B+=cn({ast:E.program,project:Y,filePath:D.filePath,relationRepo:g,projectRoot:S,tsconfigPaths:a,knownFiles:V,boundaries:_}),K+=m.getFileSymbols(Y,D.filePath).length}});for(let V of L)$.set(V.filePath,V.parsed)}else{k();let S=await H();K=S.symbols,B=S.relations,A=S.failedFiles}for(let S of r){let _=j(S.filePath,this.opts.boundaries);for(let $ of m.getFileSymbols(_,S.filePath))M.set(`${$.filePath}::${$.name}`,{name:$.name,filePath:$.filePath,kind:$.kind,fingerprint:$.fingerprint})}let N={added:[],modified:[],removed:[]};for(let[S,_]of M){let $=f.get(S);if(!$)N.added.push({name:_.name,filePath:_.filePath,kind:_.kind});else if($.fingerprint!==_.fingerprint)N.modified.push({name:_.name,filePath:_.filePath,kind:_.kind})}for(let[S,_]of f)if(!M.has(S))N.removed.push({name:_.name,filePath:_.filePath,kind:_.kind});if(!u)for(let[S,_]of s)for(let $ of _){if(!$.fingerprint)continue;let I=j(S,this.opts.boundaries),z=m.getByFingerprint(I,$.fingerprint);if(z.length===1){let L=z[0];g.retargetRelations({dstProject:I,oldFile:S,oldSymbol:$.name,newFile:L.filePath,newSymbol:L.name})}}return{indexedFiles:r.length,removedFiles:w.length,totalSymbols:K,totalRelations:B,durationMs:Date.now()-i,changedFiles:r.map((S)=>S.filePath),deletedFiles:[...w],failedFiles:A,changedSymbols:N}}fireCallbacks(n){for(let u of this.callbacks)try{u(n)}catch(i){this.logger.error("[IndexCoordinator] onIndexed callback threw:",i)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let n=this.pendingEvents.splice(0);this.startIndex(n,!1).catch((u)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",u))}}}function ft(n){try{return process.kill(n,0),!0}catch(u){if(typeof u==="object"&&u&&"code"in u)return u.code!=="ESRCH";return!0}}function At(n){let u=new Date(n).getTime();return Number.isNaN(u)?0:u}function Gu(n,u,i={}){let t=i.now??Date.now,m=i.isAlive??ft,g=i.staleAfterSeconds??90;return n.immediateTransaction(()=>{let O=n.selectOwner();if(!O)return n.insertOwner(u),"owner";let r=Math.floor((t()-At(O.heartbeat_at))/1000);if(m(O.pid)&&r<g)return"reader";return n.replaceOwner(u),"owner"})}function Xu(n,u){n.deleteOwner(u)}function Tu(n,u){n.touchOwner(u)}class Mn{#n;#u=new Map;constructor(n){this.#n=Math.max(1,n)}get size(){return this.#u.size}has(n){return this.#u.has(n)}get(n){if(!this.#u.has(n))return;let u=this.#u.get(n);return this.#u.delete(n),this.#u.set(n,u),u}set(n,u){if(this.#u.has(n))this.#u.delete(n);if(this.#u.set(n,u),this.#u.size>this.#n){let i=this.#u.keys().next().value;if(i!==void 0)this.#u.delete(i)}}delete(n){return this.#u.delete(n)}clear(){this.#u.clear()}}class nu{lru;constructor(n=500){this.lru=new Mn(n)}get(n){return this.lru.get(n)}set(n,u){this.lru.set(n,u)}invalidate(n){this.lru.delete(n)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function uu(n){let{symbolRepo:u,project:i,query:t}=n,m=t.project??i,g=t.limit??100,O={kind:t.kind,filePath:t.filePath,isExported:t.isExported,project:m,limit:g,resolvedType:t.resolvedType};if(t.text)if(t.exact)O.exactName=t.text;else{let w=Kn(t.text);if(w)O.ftsQuery=w}if(t.decorator)O.decorator=t.decorator;if(t.regex)O.regex=t.regex;return u.searchByQuery(O).map((w)=>({id:w.id,filePath:w.filePath,kind:w.kind,name:w.name,span:{start:{line:w.startLine,column:w.startColumn},end:{line:w.endLine,column:w.endColumn}},isExported:w.isExported===1,signature:w.signature,fingerprint:w.fingerprint,detail:w.detailJson?(()=>{try{return JSON.parse(w.detailJson)}catch{return{}}})():{}}))}function iu(n){let{relationRepo:u,project:i,query:t}=n,m=t.project??i,g=t.limit??500;return u.searchRelations({srcFilePath:t.srcFilePath,srcSymbolName:t.srcSymbolName,dstFilePath:t.dstFilePath,dstSymbolName:t.dstSymbolName,dstProject:t.dstProject,type:t.type,project:m,limit:g}).map((r)=>{let w;if(r.metaJson)try{w=JSON.parse(r.metaJson)}catch{console.error("[relationSearch] malformed metaJson:",r.metaJson)}return{type:r.type,srcFilePath:r.srcFilePath,srcSymbolName:r.srcSymbolName,dstFilePath:r.dstFilePath,dstSymbolName:r.dstSymbolName,dstProject:r.dstProject,metaJson:r.metaJson??void 0,meta:w}})}import{findInFiles as _t,Lang as Jt}from"@ast-grep/napi";async function tu(n){if(n.filePaths.length===0)return[];let u=[];return await _t(Jt.TypeScript,{paths:n.filePaths,matcher:{rule:{pattern:n.pattern}}},(i,t)=>{if(i)return;for(let m of t){let g=m.range();u.push({filePath:m.getRoot().filename(),startLine:g.start.line+1,endLine:g.end.line+1,matchedText:m.text()})}}),u}import F from"typescript";import{isErr as Qt}from"@zipbul/result";import l from"typescript";import Nt from"path";import{err as mu}from"@zipbul/result";function Mt(n){try{return Au("fs").readFileSync(n,"utf-8")}catch{return}}function $t(n){try{return Au("fs").readFileSync(n,"utf-8")}catch{return}}class Yn{#n;#u;#i=!1;__testing__;constructor(n,u){this.#n=n,this.#u=u,this.__testing__={host:u}}static create(n,u={}){let i=u.readConfigFile??Mt,t=u.resolveNonTrackedFile??$t,m=Nt.dirname(n),g=i(n);if(g===void 0)return mu(J("semantic",`tsconfig not found: ${n}`));let O=l.parseJsonText(n,g),r=O.parseDiagnostics;if(r&&r.length>0){let f=r.map((M)=>l.flattenDiagnosticMessageText(M.messageText,`
6
- `)).join("; ");return mu(J("semantic",`tsconfig parse error: ${f}`))}let w=l.parseJsonSourceFileConfigFileContent(O,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(f)=>i(f)!==void 0||t(f)!==void 0,readFile:(f)=>i(f)??t(f)},m);if(w.errors.length>0){let f=w.errors.filter((M)=>M.category===l.DiagnosticCategory.Error&&M.code!==18003);if(f.length>0){let M=f.map((k)=>l.flattenDiagnosticMessageText(k.messageText,`
7
- `)).join("; ");return mu(J("semantic",`tsconfig compile error: ${M}`))}}let a=new Cu(w.fileNames,w.options,m,t),s=l.createLanguageService(a);return new Yn(s,a)}get isDisposed(){return this.#i}getProgram(){this.#m();let n=this.#n.getProgram();if(!n)throw Error("TscProgram: LanguageService returned null Program");return n}getChecker(){return this.#m(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#m(),this.#n}notifyFileChanged(n,u){if(this.#i)return;this.#u.updateFile(n,u)}removeFile(n){if(this.#i)return;this.#u.removeFile(n)}dispose(){if(this.#i)return;this.#i=!0,this.#n.dispose()}#m(){if(this.#i)throw Error("TscProgram is disposed")}}class Cu{#n;#u;#i;#m;#t=new Map;constructor(n,u,i,t){this.#n=[...n],this.#u=u,this.#i=i,this.#m=t}updateFile(n,u){let i=this.#t.get(n);if(i)i.version+=1,i.content=u;else this.#t.set(n,{version:1,content:u})}removeFile(n){this.#t.delete(n),this.#n=this.#n.filter((u)=>u!==n)}getScriptFileNames(){let n=[...this.#t.keys()];return[...this.#n.filter((i)=>!this.#t.has(i)),...n]}getScriptVersion(n){let u=this.#t.get(n);return u?String(u.version):"0"}getScriptSnapshot(n){let u=this.#t.get(n);if(u)return l.ScriptSnapshot.fromString(u.content);let i=this.#m(n);if(i!==void 0)return l.ScriptSnapshot.fromString(i);return}getCurrentDirectory(){return this.#i}getCompilationSettings(){return this.#u}getDefaultLibFileName(n){return l.getDefaultLibFilePath(n)}fileExists(n){if(this.#t.has(n))return!0;return this.#m(n)!==void 0}readFile(n){let u=this.#t.get(n);if(u)return u.content;return this.#m(n)}}import p from"typescript";import Wt from"typescript";function c(n,u){if(u<0||u>=n.getEnd())return;function i(t){let m=t.getStart(n,!1),g=t.getEnd();if(u<m||u>=g)return;let O;return Wt.forEachChild(t,(r)=>{if(!O)O=i(r)}),O??t}return i(n)}function Dt(n){return!!(n.flags&p.TypeFlags.Object)&&!!(n.objectFlags&p.ObjectFlags.Reference)}function $n(n,u,i=0){let t=n.typeToString(u),m=u.flags,g=!!(m&p.TypeFlags.Union),O=!!(m&p.TypeFlags.Intersection),r;if(i<8&&Dt(u)){let f=n.getTypeArguments(u);if(f.length>0)r=f}let w=!!(m&p.TypeFlags.TypeParameter)||r!==void 0&&r.length>0,a;if(g&&i<8)a=u.types.map((f)=>$n(n,f,i+1));else if(O&&i<8)a=u.types.map((f)=>$n(n,f,i+1));let s;if(r&&r.length>0)s=r.map((f)=>$n(n,f,i+1));return{text:t,flags:m,isUnion:g,isIntersection:O,isGeneric:w,members:a,typeArguments:s}}function kt(n){return p.isFunctionDeclaration(n)||p.isVariableDeclaration(n)||p.isClassDeclaration(n)||p.isInterfaceDeclaration(n)||p.isTypeAliasDeclaration(n)||p.isEnumDeclaration(n)||p.isMethodDeclaration(n)||p.isPropertyDeclaration(n)||p.isPropertySignature(n)||p.isMethodSignature(n)}class gu{program;constructor(n){this.program=n}collectAt(n,u){let i=this.program.getProgram(),t=this.program.getChecker();if(u<0)return null;let m=i.getSourceFile(n);if(!m)return null;if(u>=m.getEnd())return null;let g=c(m,u);if(!g)return null;if(!p.isIdentifier(g))return null;try{let O=t.getTypeAtLocation(g);return $n(t,O)}catch{return null}}collectFile(n){let u=new Map,i=this.program.getProgram(),t=this.program.getChecker(),m=i.getSourceFile(n);if(!m)return u;function g(O){if(kt(O)&&O.name&&p.isIdentifier(O.name)){let r=O.name;try{let w=t.getTypeAtLocation(r),a=r.getStart(m);u.set(a,$n(t,w))}catch{}}p.forEachChild(O,g)}return g(m),u}}import mn from"typescript";var It=1000,Ht=1;function Kt(n){let u=n.declarations?.[0],i=u?.getSourceFile(),t=u?mn.getNameOfDeclaration(u):void 0;return{name:n.getName(),filePath:i?.fileName??"",position:t?.getStart(i,!1)??u?.getStart(i,!1)??0}}function Zn(n,u=0){let i=n.declarations?.[0],t=i?.getSourceFile(),m=i?mn.getNameOfDeclaration(i):void 0,g=t?.fileName??"",O=m?.getStart(t,!1)??i?.getStart(t,!1)??0,r={name:n.getName(),filePath:g,position:O},w=n;if(w.parent)r.parent=Kt(w.parent);if(u<Ht){let a=n.flags,s=!!(a&mn.SymbolFlags.Enum),f=!!(a&(mn.SymbolFlags.NamespaceModule|mn.SymbolFlags.ValueModule)),M=!!(a&(mn.SymbolFlags.Class|mn.SymbolFlags.Interface));if(s&&n.exports&&n.exports.size>0){let k=[];n.exports.forEach((H)=>{k.push(Zn(H,u+1))}),r.members=k}else if(M&&n.members&&n.members.size>0){let k=[];n.members.forEach((H)=>{k.push(Zn(H,u+1))}),r.members=k}if(f&&n.exports&&n.exports.size>0){let k=[];n.exports.forEach((H)=>{k.push(Zn(H,u+1))}),r.exports=k}}return r}class ru{#n;#u;#i=new Map;constructor(n,u=It){this.#n=n,this.#u=new Mn(u)}get(n,u){if(this.#n.isDisposed)return null;let i=`${n}:${u}`,t=this.#u.get(i);if(t!==void 0)return t;let g=this.#n.getProgram().getSourceFile(n);if(!g)return null;let O=c(g,u);if(!O||!mn.isIdentifier(O))return null;let w=this.#n.getChecker().getSymbolAtLocation(O);if(!w)return null;let a=Zn(w);this.#u.set(i,a);let s=this.#i.get(n);if(!s)s=new Set,this.#i.set(n,s);return s.add(i),a}invalidate(n){let u=this.#i.get(n);if(u){for(let i of u)this.#u.delete(i);this.#i.delete(n)}}clear(){this.#u.clear(),this.#i.clear()}}import Vt from"typescript";class wu{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let i=this.#n.getProgram(),t=i.getSourceFile(n);if(!t)return[];let m=c(t,u);if(!m||!Vt.isIdentifier(m))return[];let O=this.#n.getLanguageService().findReferences(n,u);if(!O||O.length===0)return[];let r=[];for(let w of O)for(let a of w.references){let s=i.getSourceFile(a.fileName);if(!s)continue;let{line:f,character:M}=s.getLineAndCharacterOfPosition(a.textSpan.start);r.push({filePath:a.fileName,position:a.textSpan.start,line:f+1,column:M,isDefinition:a.isDefinition??!1,isWrite:a.isWriteAccess??!1})}return r}}import G from"typescript";function zt(n,u){let i=c(n,u);if(!i)return;if(bu(i))return i;let t=i.parent;for(let m=0;m<5&&t;m++){if(bu(t))return t;t=t.parent}return i}function bu(n){return G.isClassDeclaration(n)||G.isClassExpression(n)||G.isFunctionDeclaration(n)||G.isFunctionExpression(n)||G.isArrowFunction(n)||G.isVariableDeclaration(n)||G.isObjectLiteralExpression(n)}function Ru(n){if(G.isClassDeclaration(n)||G.isClassExpression(n))return"class";if(G.isFunctionDeclaration(n)||G.isFunctionExpression(n)||G.isArrowFunction(n))return"function";if(G.isObjectLiteralExpression(n))return"object";if(G.isVariableDeclaration(n)&&n.initializer)return Ru(n.initializer);return"class"}function Bt(n,u){if(G.isClassDeclaration(n)||G.isFunctionDeclaration(n))return n.name?.getText(u)??"";if(G.isClassExpression(n))return n.name?.getText(u)??"";if(G.isVariableDeclaration(n)&&G.isIdentifier(n.name))return n.name.getText(u);if(G.isFunctionExpression(n))return n.name?.getText(u)??"";if(G.isArrowFunction(n)&&n.parent&&G.isVariableDeclaration(n.parent)){if(G.isIdentifier(n.parent.name))return n.parent.name.getText(u)}if(G.isObjectLiteralExpression(n)&&n.parent&&G.isVariableDeclaration(n.parent)){if(G.isIdentifier(n.parent.name))return n.parent.name.getText(u)}return""}function Ut(n){if(!G.isClassDeclaration(n)&&!G.isClassExpression(n))return!1;let u=n.heritageClauses;if(!u)return!1;return u.some((i)=>i.token===G.SyntaxKind.ImplementsKeyword)}class Ou{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let i=this.#n.getProgram(),t=i.getSourceFile(n);if(!t)return[];let m=c(t,u);if(!m||!G.isIdentifier(m))return[];let O=this.#n.getLanguageService().getImplementationAtPosition(n,u);if(!O||O.length===0)return[];let r=[];for(let w of O){if(w.kind===G.ScriptElementKind.interfaceElement||w.kind===G.ScriptElementKind.typeElement)continue;let a=i.getSourceFile(w.fileName);if(!a)continue;let s=zt(a,w.textSpan.start);if(!s)continue;let f=Ru(s),M=Bt(s,a),k=Ut(s);r.push({filePath:w.fileName,symbolName:M,position:w.textSpan.start,kind:f,isExplicit:k})}return r}}function yu(n){return F.canHaveModifiers(n)&&F.getModifiers(n)?.some((u)=>u.kind===F.SyntaxKind.ExportKeyword)===!0}function Lt(n){if(F.isFunctionDeclaration(n))return"function";if(F.isClassDeclaration(n))return"class";if(F.isInterfaceDeclaration(n))return"interface";if(F.isTypeAliasDeclaration(n))return"type";if(F.isEnumDeclaration(n))return"enum";if(F.isVariableDeclaration(n))return"const";if(F.isVariableStatement(n))return"const";return"unknown"}function Fu(n){if(n>=97&&n<=122)return!0;if(n>=65&&n<=90)return!0;if(n>=48&&n<=57)return!0;if(n===95||n===36)return!0;return!1}class Gn{#n;#u;#i;#m;#t;#g=!1;constructor(n,u,i,t,m){this.#n=n,this.#u=u,this.#i=i,this.#m=t,this.#t=m}static create(n,u={}){let i=Yn.create(n,{readConfigFile:u.readConfigFile,resolveNonTrackedFile:u.resolveNonTrackedFile});if(Qt(i))return i;let t=i,m=u.typeCollector??new gu(t),g=u.symbolGraph??new ru(t),O=u.referenceResolver??new wu(t),r=u.implementationFinder??new Ou(t);return new Gn(t,m,g,O,r)}get isDisposed(){return this.#g}collectTypeAt(n,u){return this.#r(),this.#u.collectAt(n,u)}collectFileTypes(n){return this.#r(),this.#u.collectFile(n)}findReferences(n,u){return this.#r(),this.#m.findAt(n,u)}findImplementations(n,u){return this.#r(),this.#t.findAt(n,u)}getSymbolNode(n,u){return this.#r(),this.#i.get(n,u)}getModuleInterface(n){this.#r();let u=this.#u.collectFile(n),i=[],m=this.#n.getProgram().getSourceFile(n);if(!m)return{filePath:n,exports:i};function g(O){if(F.isVariableStatement(O)&&yu(O)){for(let r of O.declarationList.declarations)if(F.isIdentifier(r.name)){let w=r.name.getStart(m),a=u.get(w)??null;i.push({name:r.name.text,kind:"const",resolvedType:a})}return}if((F.isFunctionDeclaration(O)||F.isClassDeclaration(O)||F.isInterfaceDeclaration(O)||F.isTypeAliasDeclaration(O)||F.isEnumDeclaration(O))&&yu(O)&&O.name){let r=O.name,w=r.getStart(m),a=u.get(w)??null;i.push({name:r.text,kind:Lt(O),resolvedType:a});return}F.forEachChild(O,g)}return g(m),{filePath:n,exports:i}}notifyFileChanged(n,u){if(this.#g)return;this.#n.notifyFileChanged(n,u),this.#i.invalidate(n)}notifyFileDeleted(n){if(this.#g)return;this.#n.removeFile(n),this.#i.invalidate(n)}lineColumnToPosition(n,u,i){this.#r();let t=this.#n.getProgram().getSourceFile(n);if(!t)return null;try{return F.getPositionOfLineAndCharacter(t,u-1,i)}catch{return null}}findNamePosition(n,u,i){this.#r();let t=this.#n.getProgram().getSourceFile(n);if(!t)return null;let m=t.getFullText(),g=u;while(g<m.length){let O=m.indexOf(i,g);if(O<0)return null;let r=O>0?m.charCodeAt(O-1):32,w=O+i.length<m.length?m.charCodeAt(O+i.length):32;if(!Fu(r)&&!Fu(w))return O;g=O+1}return null}dispose(){if(this.#g)return;this.#g=!0,this.#n.dispose(),this.#i.clear()}#r(){if(this.#g)throw Error("SemanticLayer is disposed")}}var Zt=30000,pu=60000,Gt=10;function Xt(n,u){return(i)=>{if(u.handleWatcherEvent?.(i),n.semanticLayer)if(i.eventType==="delete")n.semanticLayer.notifyFileDeleted(i.filePath);else n.readFileFn(i.filePath).then((t)=>{n.semanticLayer?.notifyFileChanged(i.filePath,t)}).catch(()=>{})}}async function Tt(n){if(!n.semanticLayer)return;let u=n.fileRepo.getAllFiles(n.defaultProject);await Promise.all(u.map(async(i)=>{try{let t=Dn.resolve(n.projectRoot,i.filePath),m=await n.readFileFn(t);n.semanticLayer?.notifyFileChanged(t,m)}catch{}}))}async function Eu(n,u){let i=n.coordinatorFactory?n.coordinatorFactory():new en({projectRoot:n.projectRoot,boundaries:n.boundaries,extensions:n.extensions,ignorePatterns:n.ignorePatterns,dbConnection:n.db,parseCache:n.parseCache,fileRepo:n.fileRepo,symbolRepo:n.symbolRepo,relationRepo:n.relationRepo,logger:n.logger});n.coordinator=i;for(let t of n.onIndexedCallbacks)i.onIndexed(t);if(i.onIndexed(()=>{n.graphCache=null,n.graphCacheKey=null}),u.isWatchMode){let t=n.watcherFactory?n.watcherFactory():new Pn({projectRoot:n.projectRoot,ignorePatterns:n.ignorePatterns,extensions:n.extensions},void 0,n.logger);await t.start(Xt(n,i)).then((m)=>{if(Wn(m))throw m.data}),n.watcher=t,n.timer=setInterval(()=>{n.updateHeartbeatFn(n.db,process.pid)},Zt)}await i.fullIndex(),await Tt(n)}function Ct(n,u){let i=["SIGTERM","SIGINT","beforeExit"];for(let t of i){let m=()=>{u().catch((g)=>n.logger.error("[Gildash] close error during signal",t,g))};if(t==="beforeExit")process.on("beforeExit",m);else process.on(t,m);n.signalHandlers.push([t,m])}}async function vu(n){let{projectRoot:u,extensions:i=[".ts",".mts",".cts"],ignorePatterns:t=["**/node_modules/**"],parseCacheCapacity:m=500,logger:g=console,existsSyncFn:O=Yt,dbConnectionFactory:r,watcherFactory:w,coordinatorFactory:a,repositoryFactory:s,acquireWatcherRoleFn:f=Gu,releaseWatcherRoleFn:M=Xu,updateHeartbeatFn:k=Tu,discoverProjectsFn:H=zn,parseSourceFn:K=Nn,extractSymbolsFn:B=Qn,extractRelationsFn:A=Ln,symbolSearchFn:N=uu,relationSearchFn:S=iu,patternSearchFn:_=tu,loadTsconfigPathsFn:$=Jn,readFileFn:I=async(Q)=>Bun.file(Q).text(),unlinkFn:z=async(Q)=>{await Bun.file(Q).unlink()},watchMode:L,semantic:V,semanticLayerFactory:X}=n;if(!Dn.isAbsolute(u))return Xn(J("validation",`Gildash: projectRoot must be an absolute path, got: "${u}"`));if(!O(u))return Xn(J("validation",`Gildash: projectRoot does not exist: "${u}"`));let D=r?r():new pn({projectRoot:u}),Y=D.open();if(Wn(Y))return Y;try{let Q=await H(u),E=Q[0]?.project??Dn.basename(u),h=s?s():(()=>{let P=D;return{fileRepo:new En(P),symbolRepo:new vn(P),relationRepo:new qn(P),parseCache:new nu(m)}})(),o=L??!0,An;if(o)An=await Promise.resolve(f(D,process.pid,{}));else An="owner";let Z={projectRoot:u,extensions:i,ignorePatterns:t,logger:g,defaultProject:E,role:An,db:D,symbolRepo:h.symbolRepo,relationRepo:h.relationRepo,fileRepo:h.fileRepo,parseCache:h.parseCache,releaseWatcherRoleFn:M,parseSourceFn:K,extractSymbolsFn:B,extractRelationsFn:A,symbolSearchFn:N,relationSearchFn:S,patternSearchFn:_,readFileFn:I,unlinkFn:z,existsSyncFn:O,acquireWatcherRoleFn:f,updateHeartbeatFn:k,watcherFactory:w,coordinatorFactory:a,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:Q,onIndexedCallbacks:new Set,graphCache:null,graphCacheKey:null,semanticLayer:null};if(Bn(u),Z.tsconfigPaths=await $(u),V){let P=Dn.join(u,"tsconfig.json"),Sn=X?X(P):Gn.create(P);if(Wn(Sn))return D.close(),Sn;Z.semanticLayer=Sn}if(An==="owner")await Eu(Z,{isWatchMode:o});else{let P=0,Sn=async()=>{try{let bn=await Promise.resolve(Z.acquireWatcherRoleFn(Z.db,process.pid,{}));if(P=0,bn==="owner"){clearInterval(Z.timer),Z.timer=null;try{await Eu(Z,{isWatchMode:!0})}catch(Rn){if(Z.logger.error("[Gildash] owner promotion failed, reverting to reader",Rn),Z.watcher){let kn=await Z.watcher.close();if(Wn(kn))Z.logger.error("[Gildash] watcher close error during promotion rollback",kn.data);Z.watcher=null}if(Z.coordinator)await Z.coordinator.shutdown().catch((kn)=>Z.logger.error("[Gildash] coordinator shutdown error during promotion rollback",kn)),Z.coordinator=null;if(Z.timer===null)Z.timer=setInterval(Sn,pu)}}}catch(bn){if(P++,Z.logger.error("[Gildash] healthcheck error",bn),P>=Gt)Z.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(Z.timer),Z.timer=null,Tn(Z).catch((Rn)=>Z.logger.error("[Gildash] close error during healthcheck shutdown",Rn))}};Z.timer=setInterval(Sn,pu)}if(o)Ct(Z,()=>Tn(Z));return Z}catch(Q){return D.close(),Xn(J("store","Gildash: initialization failed",Q))}}async function Tn(n,u){if(n.closed)return;n.closed=!0;let i=[];for(let[t,m]of n.signalHandlers)if(t==="beforeExit")process.off("beforeExit",m);else process.off(t,m);if(n.signalHandlers=[],n.semanticLayer){try{n.semanticLayer.dispose()}catch(t){i.push(t instanceof Error?t:Error(String(t)))}n.semanticLayer=null}if(n.coordinator)try{await n.coordinator.shutdown()}catch(t){i.push(t instanceof Error?t:Error(String(t)))}if(n.watcher){let t=await n.watcher.close();if(Wn(t))i.push(t.data)}if(n.timer!==null)clearInterval(n.timer),n.timer=null;try{n.releaseWatcherRoleFn(n.db,process.pid)}catch(t){i.push(t instanceof Error?t:Error(String(t)))}try{n.db.close()}catch(t){i.push(t instanceof Error?t:Error(String(t)))}if(u?.cleanup)for(let t of["","-wal","-shm"])try{await n.unlinkFn(Dn.join(n.projectRoot,nn,In+t))}catch{}if(i.length>0)return Xn(J("close","Gildash: one or more errors occurred during close()",i))}import{err as qu,isErr as ju}from"@zipbul/result";function Pu(n,u,i,t){if(n.closed)return qu(J("closed","Gildash: instance is closed"));let m=n.parseSourceFn(u,i,t);if(ju(m))return m;return n.parseCache.set(u,m),m}async function du(n,u,i){if(n.closed)return qu(J("closed","Gildash: instance is closed"));let t=new Map;return await Promise.all(u.map(async(m)=>{try{let g=await n.readFileFn(m),O=n.parseSourceFn(m,g,i);if(!ju(O))t.set(m,O)}catch{}})),t}function hu(n,u){if(n.closed)return;return n.parseCache.get(u)}import{err as ou}from"@zipbul/result";function xu(n,u){if(n.closed)return ou(J("closed","Gildash: instance is closed"));return n.extractSymbolsFn(u)}function lu(n,u){if(n.closed)return ou(J("closed","Gildash: instance is closed"));return n.extractRelationsFn(u.program,u.filePath,n.tsconfigPaths??void 0)}import{err as b}from"@zipbul/result";import cu from"path";function eu(n,u){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{return n.symbolRepo.getStats(u??n.defaultProject)}catch(i){return b(J("store","Gildash: getStats failed",i))}}function Su(n,u){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:n.defaultProject,query:u})}catch(i){return b(J("search","Gildash: searchSymbols failed",i))}}function ni(n,u){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{return n.relationSearchFn({relationRepo:n.relationRepo,project:n.defaultProject,query:u})}catch(i){return b(J("search","Gildash: searchRelations failed",i))}}function ui(n,u){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:void 0,query:u})}catch(i){return b(J("search","Gildash: searchAllSymbols failed",i))}}function ii(n,u){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{return n.relationSearchFn({relationRepo:n.relationRepo,project:void 0,query:u})}catch(i){return b(J("search","Gildash: searchAllRelations failed",i))}}function ti(n,u){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{return n.fileRepo.getAllFiles(u??n.defaultProject)}catch(i){return b(J("store","Gildash: listIndexedFiles failed",i))}}function mi(n,u,i){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{return n.relationSearchFn({relationRepo:n.relationRepo,project:i??n.defaultProject,query:{srcFilePath:u,dstFilePath:u,limit:1e4}})}catch(t){return b(J("search","Gildash: getInternalRelations failed",t))}}function gi(n,u,i,t){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{let m=t??n.defaultProject,g=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:m,query:{text:u,exact:!0,filePath:i,limit:1}});if(g.length===0)return b(J("search",`Gildash: symbol '${u}' not found in '${i}'`));let O=g[0],r=O.detail,w={...O,members:Array.isArray(r.members)?r.members:void 0,jsDoc:typeof r.jsDoc==="string"?r.jsDoc:void 0,parameters:typeof r.parameters==="string"?r.parameters:void 0,returnType:typeof r.returnType==="string"?r.returnType:void 0,heritage:Array.isArray(r.heritage)?r.heritage:void 0,decorators:Array.isArray(r.decorators)?r.decorators:void 0,typeParameters:typeof r.typeParameters==="string"?r.typeParameters:void 0};if(n.semanticLayer)try{let a=cu.isAbsolute(i)?i:cu.resolve(n.projectRoot,i),s=n.semanticLayer.lineColumnToPosition(a,O.span.start.line,O.span.start.column);if(s!==null){let f=n.semanticLayer.findNamePosition(a,s,O.name)??s,M=n.semanticLayer.collectTypeAt(a,f);if(M)w.resolvedType=M}}catch{}return w}catch(m){return b(J("search","Gildash: getFullSymbol failed",m))}}function ri(n,u,i){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{let t=i??n.defaultProject,m=n.fileRepo.getFile(t,u);if(!m)return b(J("search",`Gildash: file '${u}' is not in the index`));let g=n.symbolRepo.getFileSymbols(t,u),O=n.relationRepo.getOutgoing(t,u);return{filePath:m.filePath,lineCount:m.lineCount??0,size:m.size,symbolCount:g.length,exportedSymbolCount:g.filter((r)=>r.isExported).length,relationCount:O.length}}catch(t){return b(J("store","Gildash: getFileStats failed",t))}}function wi(n,u,i){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{return n.fileRepo.getFile(i??n.defaultProject,u)}catch(t){return b(J("store","Gildash: getFileInfo failed",t))}}function Oi(n,u,i){return Su(n,{filePath:u,project:i??void 0,limit:1e4})}function Si(n,u,i){if(n.closed)return b(J("closed","Gildash: instance is closed"));try{let m=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:i??n.defaultProject,query:{filePath:u,isExported:!0}}).map((g)=>({name:g.name,kind:g.kind,parameters:g.detail.parameters??void 0,returnType:g.detail.returnType??void 0,jsDoc:g.detail.jsDoc??void 0}));return{filePath:u,exports:m}}catch(t){return b(J("search","Gildash: getModuleInterface failed",t))}}import{err as v}from"@zipbul/result";class Cn{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(n){this.options=n}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let u=[this.options.project,...this.options.additionalProjects??[]].flatMap((i)=>[...this.options.relationRepo.getByType(i,"imports"),...this.options.relationRepo.getByType(i,"type-references"),...this.options.relationRepo.getByType(i,"re-exports")]);for(let i of u){let{srcFilePath:t,dstFilePath:m}=i;if(!this.adjacencyList.has(t))this.adjacencyList.set(t,new Set);if(this.adjacencyList.get(t).add(m),!this.adjacencyList.has(m))this.adjacencyList.set(m,new Set);if(!this.reverseAdjacencyList.has(m))this.reverseAdjacencyList.set(m,new Set);this.reverseAdjacencyList.get(m).add(t)}}getDependencies(n){return Array.from(this.adjacencyList.get(n)??[])}getDependents(n){return Array.from(this.reverseAdjacencyList.get(n)??[])}getTransitiveDependents(n){let u=new Set,i=[n];while(i.length>0){let t=i.shift();for(let m of this.reverseAdjacencyList.get(t)??[])if(!u.has(m))u.add(m),i.push(m)}return Array.from(u)}hasCycle(){let n=new Set,u=new Set;for(let i of this.adjacencyList.keys()){if(n.has(i))continue;let t=[{node:i,entered:!1}];while(t.length>0){let m=t.pop();if(m.entered){u.delete(m.node);continue}if(u.has(m.node))return!0;if(n.has(m.node))continue;n.add(m.node),u.add(m.node),t.push({node:m.node,entered:!0});for(let g of this.adjacencyList.get(m.node)??[]){if(u.has(g))return!0;if(!n.has(g))t.push({node:g,entered:!1})}}}return!1}getAffectedByChange(n){let u=new Set;for(let i of n)for(let t of this.getTransitiveDependents(i))u.add(t);return Array.from(u)}getAdjacencyList(){let n=new Map;for(let[u,i]of this.adjacencyList)n.set(u,Array.from(i));return n}getTransitiveDependencies(n){let u=new Set,i=[n];while(i.length>0){let t=i.shift();for(let m of this.adjacencyList.get(t)??[])if(!u.has(m))u.add(m),i.push(m)}return Array.from(u)}getCyclePaths(n){let u=n?.maxCycles??1/0;if(u<=0)return[];let i=new Map;for(let[t,m]of this.adjacencyList)i.set(t,Array.from(m));return qt(i,u)}}var Ft=(n,u)=>n.localeCompare(u);function pt(n){let u=n.length>1&&n[0]===n[n.length-1]?n.slice(0,-1):[...n];if(u.length===0)return[];let i=u;for(let t=1;t<u.length;t++){let m=u.slice(t).concat(u.slice(0,t));if(m.join("::")<i.join("::"))i=m}return[...i]}function au(n,u,i){let t=pt(i);if(t.length===0)return!1;let m=t.join("->");if(n.has(m))return!1;return n.add(m),u.push(t),!0}function Et(n){let u=0,i=[],t=new Set,m=new Map,g=new Map,O=[],r=(w)=>{m.set(w,u),g.set(w,u),u+=1,i.push(w),t.add(w);for(let a of n.get(w)??[])if(!m.has(a))r(a),g.set(w,Math.min(g.get(w)??0,g.get(a)??0));else if(t.has(a))g.set(w,Math.min(g.get(w)??0,m.get(a)??0));if(g.get(w)===m.get(w)){let a=[],s="";do s=i.pop()??"",t.delete(s),a.push(s);while(s!==w&&i.length>0);O.push(a)}};for(let w of n.keys())if(!m.has(w))r(w);return{components:O}}function vt(n,u,i){let t=[],m=new Set,g=[...n].sort(Ft),O=(r,w,a)=>{w.delete(r);let s=a.get(r);if(!s)return;for(let f of s)if(w.has(f))O(f,w,a);s.clear()};for(let r=0;r<g.length&&t.length<i;r++){let w=g[r]??"",a=new Set(g.slice(r)),s=new Set,f=new Map,M=[],k=(K)=>(u.get(K)??[]).filter((B)=>a.has(B)),H=(K)=>{if(t.length>=i)return!0;let B=!1;M.push(K),s.add(K);for(let A of k(K)){if(t.length>=i)break;if(A===w)au(m,t,M.concat(w)),B=!0;else if(!s.has(A)){if(H(A))B=!0}}if(B)O(K,s,f);else for(let A of k(K)){let N=f.get(A)??new Set;N.add(K),f.set(A,N)}return M.pop(),B};H(w)}return t}function qt(n,u){let{components:i}=Et(n),t=[],m=new Set;for(let g of i){if(t.length>=u)break;if(g.length===0)continue;if(g.length===1){let w=g[0]??"";if((n.get(w)??[]).includes(w))au(m,t,[w,w]);continue}let O=u-t.length,r=vt(g,n,O);for(let w of r){if(t.length>=u)break;au(m,t,w)}}return t}function ai(n){n.graphCache=null,n.graphCacheKey=null}function fn(n,u){let i=u??"__cross__";if(n.graphCache&&n.graphCacheKey===i)return n.graphCache;let t=new Cn({relationRepo:n.relationRepo,project:u??n.defaultProject,additionalProjects:u?void 0:n.boundaries?.map((m)=>m.project)});return t.build(),n.graphCache=t,n.graphCacheKey=i,t}function si(n,u,i,t=1e4){if(n.closed)return v(J("closed","Gildash: instance is closed"));try{return n.relationSearchFn({relationRepo:n.relationRepo,project:i??n.defaultProject,query:{srcFilePath:u,type:"imports",project:i??n.defaultProject,limit:t}}).map((m)=>m.dstFilePath)}catch(m){return v(J("search","Gildash: getDependencies failed",m))}}function fi(n,u,i,t=1e4){if(n.closed)return v(J("closed","Gildash: instance is closed"));try{return n.relationSearchFn({relationRepo:n.relationRepo,project:i??n.defaultProject,query:{dstFilePath:u,type:"imports",project:i??n.defaultProject,limit:t}}).map((m)=>m.srcFilePath)}catch(m){return v(J("search","Gildash: getDependents failed",m))}}async function Ai(n,u,i){if(n.closed)return v(J("closed","Gildash: instance is closed"));try{return fn(n,i).getAffectedByChange(u)}catch(t){return v(J("search","Gildash: getAffected failed",t))}}async function _i(n,u){if(n.closed)return v(J("closed","Gildash: instance is closed"));try{return fn(n,u).hasCycle()}catch(i){return v(J("search","Gildash: hasCycle failed",i))}}async function Ji(n,u){if(n.closed)return v(J("closed","Gildash: instance is closed"));try{return fn(n,u).getAdjacencyList()}catch(i){return v(J("search","Gildash: getImportGraph failed",i))}}async function Ni(n,u,i){if(n.closed)return v(J("closed","Gildash: instance is closed"));try{return fn(n,i).getTransitiveDependencies(u)}catch(t){return v(J("search","Gildash: getTransitiveDependencies failed",t))}}async function Mi(n,u,i){if(n.closed)return v(J("closed","Gildash: instance is closed"));try{return fn(n,u).getCyclePaths(i)}catch(t){return v(J("search","Gildash: getCyclePaths failed",t))}}async function $i(n,u,i){if(n.closed)return v(J("closed","Gildash: instance is closed"));try{let t=fn(n,i);return{filePath:u,fanIn:t.getDependents(u).length,fanOut:t.getDependencies(u).length}}catch(t){return v(J("search","Gildash: getFanMetrics failed",t))}}import{err as q}from"@zipbul/result";import Wi from"path";function su(n,u,i,t){let m=t??n.defaultProject,g=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:m,query:{text:u,exact:!0,filePath:i,limit:1}});if(g.length===0)return null;let O=g[0],r=Wi.isAbsolute(i)?i:Wi.resolve(n.projectRoot,i),w=n.semanticLayer.lineColumnToPosition(r,O.span.start.line,O.span.start.column);if(w===null)return null;let a=n.semanticLayer.findNamePosition(r,w,O.name)??w;return{sym:O,position:a,absPath:r}}function Di(n,u,i,t){if(n.closed)return q(J("closed","Gildash: instance is closed"));if(!n.semanticLayer)return q(J("semantic","Gildash: semantic layer is not enabled"));try{let m=su(n,u,i,t);if(!m)return q(J("search",`Gildash: symbol '${u}' not found in '${i}'`));return n.semanticLayer.collectTypeAt(m.absPath,m.position)}catch(m){return q(J("search","Gildash: getResolvedType failed",m))}}function ki(n,u,i,t){if(n.closed)return q(J("closed","Gildash: instance is closed"));if(!n.semanticLayer)return q(J("semantic","Gildash: semantic layer is not enabled"));try{let m=su(n,u,i,t);if(!m)return q(J("search",`Gildash: symbol '${u}' not found in '${i}'`));return n.semanticLayer.findReferences(m.absPath,m.position)}catch(m){return q(J("search","Gildash: getSemanticReferences failed",m))}}function Ii(n,u,i,t){if(n.closed)return q(J("closed","Gildash: instance is closed"));if(!n.semanticLayer)return q(J("semantic","Gildash: semantic layer is not enabled"));try{let m=su(n,u,i,t);if(!m)return q(J("search",`Gildash: symbol '${u}' not found in '${i}'`));return n.semanticLayer.findImplementations(m.absPath,m.position)}catch(m){return q(J("search","Gildash: getImplementations failed",m))}}function Hi(n,u){if(n.closed)return q(J("closed","Gildash: instance is closed"));if(!n.semanticLayer)return q(J("semantic","Gildash: semantic layer is not enabled"));try{return n.semanticLayer.getModuleInterface(u)}catch(i){return q(J("search","Gildash: getSemanticModuleInterface failed",i))}}import{err as e}from"@zipbul/result";function Ki(n,u){let i=new Map(n.map((r)=>[`${r.name}::${r.filePath}`,r])),t=new Map(u.map((r)=>[`${r.name}::${r.filePath}`,r])),m=[],g=[],O=[];for(let[r,w]of t){let a=i.get(r);if(!a)m.push(w);else if(a.fingerprint!==w.fingerprint)O.push({before:a,after:w})}for(let[r,w]of i)if(!t.has(r))g.push(w);return{added:m,removed:g,modified:O}}function Vi(n,u){if(n.onIndexedCallbacks.add(u),!n.coordinator)return()=>{n.onIndexedCallbacks.delete(u)};let i=n.coordinator.onIndexed(u);return()=>{n.onIndexedCallbacks.delete(u),i()}}async function zi(n){if(n.closed)return e(J("closed","Gildash: instance is closed"));if(!n.coordinator)return e(J("closed","Gildash: reindex() is not available for readers"));try{let u=await n.coordinator.fullIndex();return ai(n),u}catch(u){return e(J("index","Gildash: reindex failed",u))}}function Bi(n,u,i,t){if(n.closed)return e(J("closed","Gildash: instance is closed"));let m=t??n.defaultProject,g=new Set,O=[],r=u,w=i;for(;;){let a=`${w}::${r}`;if(g.has(a))return e(J("search","Gildash: resolveSymbol detected circular re-export chain"));g.add(a);let s=n.relationSearchFn({relationRepo:n.relationRepo,project:m,query:{type:"re-exports",srcFilePath:w,limit:500}}),f,M;for(let k of s){let H;if(k.metaJson)try{let B=JSON.parse(k.metaJson);if(Array.isArray(B.specifiers))H=B.specifiers}catch{}if(!H)continue;let K=H.find((B)=>B.exported===r);if(!K)continue;f=k.dstFilePath,M=K.local;break}if(!f||!M)return{originalName:r,originalFilePath:w,reExportChain:O};O.push({filePath:w,exportedAs:r}),w=f,r=M}}async function Ui(n,u,i){if(n.closed)return e(J("closed","Gildash: instance is closed"));try{let t=i?.project??n.defaultProject,m=i?.filePaths?i.filePaths:n.fileRepo.getAllFiles(t).map((g)=>g.filePath);return await n.patternSearchFn({pattern:u,filePaths:m})}catch(t){return e(J("search","Gildash: findPattern failed",t))}}async function Qi(n,u,i,t){if(n.closed)return e(J("closed","Gildash: instance is closed"));try{let m=t??n.defaultProject,g=new Set,O=(r,w,a)=>{let s=`${r}::${w}`;if(g.has(s))return{symbolName:r,filePath:w,kind:a,children:[]};g.add(s);let k=n.relationSearchFn({relationRepo:n.relationRepo,project:m,query:{srcFilePath:w,srcSymbolName:r,limit:1000}}).filter((H)=>H.type==="extends"||H.type==="implements").filter((H)=>H.dstSymbolName!=null).map((H)=>O(H.dstSymbolName,H.dstFilePath,H.type));return{symbolName:r,filePath:w,kind:a,children:k}};return O(u,i)}catch(m){return e(J("search","Gildash: getHeritageChain failed",m))}}class fu{_ctx;get projectRoot(){return this._ctx.projectRoot}get role(){return this._ctx.role}get projects(){return[...this._ctx.boundaries]}constructor(n){this._ctx=n}static async open(n){let u=await vu(n);if(ht(u))return u;return new fu(u)}async close(n){return Tn(this._ctx,n)}parseSource(n,u,i){return Pu(this._ctx,n,u,i)}async batchParse(n,u){return du(this._ctx,n,u)}getParsedAst(n){return hu(this._ctx,n)}extractSymbols(n){return xu(this._ctx,n)}extractRelations(n){return lu(this._ctx,n)}getStats(n){return eu(this._ctx,n)}searchSymbols(n){return Su(this._ctx,n)}searchRelations(n){return ni(this._ctx,n)}searchAllSymbols(n){return ui(this._ctx,n)}searchAllRelations(n){return ii(this._ctx,n)}listIndexedFiles(n){return ti(this._ctx,n)}getInternalRelations(n,u){return mi(this._ctx,n,u)}getFullSymbol(n,u,i){return gi(this._ctx,n,u,i)}getFileStats(n,u){return ri(this._ctx,n,u)}getFileInfo(n,u){return wi(this._ctx,n,u)}getSymbolsByFile(n,u){return Oi(this._ctx,n,u)}getModuleInterface(n,u){return Si(this._ctx,n,u)}getDependencies(n,u,i=1e4){return si(this._ctx,n,u,i)}getDependents(n,u,i=1e4){return fi(this._ctx,n,u,i)}async getAffected(n,u){return Ai(this._ctx,n,u)}async hasCycle(n){return _i(this._ctx,n)}async getImportGraph(n){return Ji(this._ctx,n)}async getTransitiveDependencies(n,u){return Ni(this._ctx,n,u)}async getCyclePaths(n,u){return Mi(this._ctx,n,u)}async getFanMetrics(n,u){return $i(this._ctx,n,u)}getResolvedType(n,u,i){return Di(this._ctx,n,u,i)}getSemanticReferences(n,u,i){return ki(this._ctx,n,u,i)}getImplementations(n,u,i){return Ii(this._ctx,n,u,i)}getSemanticModuleInterface(n){return Hi(this._ctx,n)}diffSymbols(n,u){return Ki(n,u)}onIndexed(n){return Vi(this._ctx,n)}async reindex(){return zi(this._ctx)}resolveSymbol(n,u,i){return Bi(this._ctx,n,u,i)}async findPattern(n,u){return Ui(this._ctx,n,u)}async getHeritageChain(n,u,i){return Qi(this._ctx,n,u,i)}}export{uu as symbolSearch,iu as relationSearch,tu as patternSearch,J as gildashError,fu as Gildash,Cn as DependencyGraph};
2
+ var Ig=Object.defineProperty;var kg=(n)=>n;function Cg(n,u){this[n]=kg.bind(null,u)}var Tg=(n,u)=>{for(var g in u)Ig(n,g,{get:u[g],enumerable:!0,configurable:!0,set:Cg.bind(u,g)})};var Ju=import.meta.require;import{isErr as Kn}from"@zipbul/result";import Vn from"path";import{existsSync as qm}from"fs";import{err as Au,isErr as bg}from"@zipbul/result";import{Database as qg}from"bun:sqlite";import{mkdirSync as pg,unlinkSync as fu,existsSync as Nu}from"fs";import{dirname as vg,join as Mu}from"path";import{drizzle as Gg}from"drizzle-orm/bun-sqlite";import{migrate as Eg}from"drizzle-orm/bun-sqlite/migrator";class J extends Error{type;constructor(n,u,g){super(u,g);this.type=n;this.name="GildashError"}}function p(n,u,g){return new J(n,u,g!==void 0?{cause:g}:void 0)}var nn=".gildash",Wn="gildash.db";var an={};Tg(an,{watcherOwner:()=>ag,symbols:()=>k,relations:()=>K,files:()=>F});import{sql as yg}from"drizzle-orm";import{sqliteTable as Hn,text as y,integer as j,real as sg,index as un,primaryKey as Rg,foreignKey as Fn,check as Fg}from"drizzle-orm/sqlite-core";var F=Hn("files",{project:y("project").notNull(),filePath:y("file_path").notNull(),mtimeMs:sg("mtime_ms").notNull(),size:j("size").notNull(),contentHash:y("content_hash").notNull(),updatedAt:y("updated_at").notNull(),lineCount:j("line_count")},(n)=>[Rg({columns:[n.project,n.filePath]})]),k=Hn("symbols",{id:j("id").primaryKey({autoIncrement:!0}),project:y("project").notNull(),filePath:y("file_path").notNull(),kind:y("kind").notNull(),name:y("name").notNull(),startLine:j("start_line").notNull(),startColumn:j("start_column").notNull(),endLine:j("end_line").notNull(),endColumn:j("end_column").notNull(),isExported:j("is_exported").notNull().default(0),signature:y("signature"),fingerprint:y("fingerprint"),detailJson:y("detail_json"),contentHash:y("content_hash").notNull(),indexedAt:y("indexed_at").notNull(),resolvedType:y("resolved_type")},(n)=>[un("idx_symbols_project_file").on(n.project,n.filePath),un("idx_symbols_project_kind").on(n.project,n.kind),un("idx_symbols_project_name").on(n.project,n.name),un("idx_symbols_fingerprint").on(n.project,n.fingerprint),Fn({columns:[n.project,n.filePath],foreignColumns:[F.project,F.filePath]}).onDelete("cascade")]),K=Hn("relations",{id:j("id").primaryKey({autoIncrement:!0}),project:y("project").notNull(),type:y("type").notNull(),srcFilePath:y("src_file_path").notNull(),srcSymbolName:y("src_symbol_name"),dstProject:y("dst_project").notNull(),dstFilePath:y("dst_file_path").notNull(),dstSymbolName:y("dst_symbol_name"),metaJson:y("meta_json")},(n)=>[un("idx_relations_src").on(n.project,n.srcFilePath),un("idx_relations_dst").on(n.dstProject,n.dstFilePath),un("idx_relations_type").on(n.project,n.type),un("idx_relations_project_type_src").on(n.project,n.type,n.srcFilePath),Fn({columns:[n.project,n.srcFilePath],foreignColumns:[F.project,F.filePath]}).onDelete("cascade"),Fn({columns:[n.dstProject,n.dstFilePath],foreignColumns:[F.project,F.filePath]}).onDelete("cascade")]),ag=Hn("watcher_owner",{id:j("id").primaryKey(),pid:j("pid").notNull(),startedAt:y("started_at").notNull(),heartbeatAt:y("heartbeat_at").notNull(),instanceId:y("instance_id")},(n)=>[Fg("watcher_owner_singleton",yg`${n.id} = 1`)]);class bn{client=null;drizzle=null;dbPath;txDepth=0;constructor(n){this.dbPath=Mu(n.projectRoot,nn,Wn)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{pg(vg(this.dbPath),{recursive:!0}),this.client=new qg(this.dbPath),this.client.run("PRAGMA journal_mode = WAL"),this.client.run("PRAGMA foreign_keys = OFF"),this.client.run("PRAGMA busy_timeout = 5000"),this.drizzle=Gg(this.client,{schema:an}),Eg(this.drizzle,{migrationsFolder:Mu(import.meta.dirname,"migrations")});let n=this.client.prepare("PRAGMA foreign_key_check").all();if(n.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(n.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON");let u=this.client;if(typeof u.function==="function")u.function.call(this.client,"regexp",(g,m)=>{try{return new RegExp(g).test(m)?1:0}catch{return 0}})}catch(n){if(this.isCorruptionError(n)&&Nu(this.dbPath)){this.closeClient(),fu(this.dbPath);for(let g of["-wal","-shm"]){let m=this.dbPath+g;if(Nu(m))fu(m)}let u=this.open();if(bg(u))return Au(p("store",`Failed to recover database at ${this.dbPath}`,u.data));return u}return Au(p("store",`Failed to open database at ${this.dbPath}`,n))}}close(){this.closeClient(),this.drizzle=null}transaction(n){let u=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return u.transaction(()=>n(this))()}finally{this.txDepth--}}let g=`sp_${this.txDepth++}`;u.run(`SAVEPOINT "${g}"`);try{let m=n(this);return u.run(`RELEASE SAVEPOINT "${g}"`),m}catch(m){throw u.run(`ROLLBACK TO SAVEPOINT "${g}"`),u.run(`RELEASE SAVEPOINT "${g}"`),m}finally{this.txDepth--}}immediateTransaction(n){let u=this.requireClient();this.txDepth++,u.run("BEGIN IMMEDIATE");try{let g=n();return u.run("COMMIT"),g}catch(g){throw u.run("ROLLBACK"),g}finally{this.txDepth--}}query(n){let u=this.requireClient().prepare(n).get();if(!u)return null;return Object.values(u)[0]}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((u)=>u.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(n,u){let g=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(n,g,g,u??null)}replaceOwner(n,u){let g=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(n,g,g,u??null)}touchOwner(n){let u=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(u,n)}deleteOwner(n){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(n)}requireClient(){if(!this.client)throw Error("Database is not open. Call open() first.");return this.client}closeClient(){if(this.client)this.client.close(),this.client=null}isCorruptionError(n){if(!(n instanceof Error))return!1;let u=n.message.toLowerCase();return u.includes("malformed")||u.includes("corrupt")||u.includes("not a database")||u.includes("disk i/o error")||u.includes("sqlite_corrupt")}}import{eq as Nn,and as $u}from"drizzle-orm";class qn{db;constructor(n){this.db=n}getFile(n,u){return this.db.drizzleDb.select().from(F).where($u(Nn(F.project,n),Nn(F.filePath,u))).get()??null}upsertFile(n){this.db.drizzleDb.insert(F).values({project:n.project,filePath:n.filePath,mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}).onConflictDoUpdate({target:[F.project,F.filePath],set:{mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}}).run()}getAllFiles(n){return this.db.drizzleDb.select().from(F).where(Nn(F.project,n)).all()}getFilesMap(n){let u=this.getAllFiles(n),g=new Map;for(let m of u)g.set(m.filePath,m);return g}deleteFile(n,u){this.db.drizzleDb.delete(F).where($u(Nn(F.project,n),Nn(F.filePath,u))).run()}}import{eq as a,and as wn,sql as Un,count as jg}from"drizzle-orm";function Qn(n){return n.trim().split(/\s+/).map((u)=>u.trim()).filter((u)=>u.length>0).map((u)=>`"${u.replaceAll('"','""')}"*`).join(" ")}class pn{db;constructor(n){this.db=n}replaceFileSymbols(n,u,g,m){if(this.db.drizzleDb.delete(k).where(wn(a(k.project,n),a(k.filePath,u))).run(),!m.length)return;let i=new Date().toISOString();for(let t of m)this.db.drizzleDb.insert(k).values({project:n,filePath:u,kind:t.kind??"unknown",name:t.name??"",startLine:t.startLine??0,startColumn:t.startColumn??0,endLine:t.endLine??0,endColumn:t.endColumn??0,isExported:t.isExported??0,signature:t.signature??null,fingerprint:t.fingerprint??null,detailJson:t.detailJson??null,contentHash:g,indexedAt:t.indexedAt??i,resolvedType:t.resolvedType??null}).run()}getFileSymbols(n,u){return this.db.drizzleDb.select().from(k).where(wn(a(k.project,n),a(k.filePath,u))).all()}searchByName(n,u,g={}){let m=g.limit??50,i=Qn(u);if(!i)return[];return this.db.drizzleDb.select().from(k).where(wn(Un`${k.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${i})`,a(k.project,n),g.kind?a(k.kind,g.kind):void 0)).orderBy(k.name).limit(m).all()}searchByKind(n,u){return this.db.drizzleDb.select().from(k).where(wn(a(k.project,n),a(k.kind,u))).orderBy(k.name).all()}getStats(n){let u=this.db.drizzleDb.select({symbolCount:jg(),fileCount:Un`COUNT(DISTINCT ${k.filePath})`}).from(k).where(a(k.project,n)).get();return{symbolCount:u?.symbolCount??0,fileCount:u?.fileCount??0}}getByFingerprint(n,u){return this.db.drizzleDb.select().from(k).where(wn(a(k.project,n),a(k.fingerprint,u))).all()}deleteFileSymbols(n,u){this.db.drizzleDb.delete(k).where(wn(a(k.project,n),a(k.filePath,u))).run()}searchByQuery(n){let u=this.db.drizzleDb.select().from(k).where(wn(n.ftsQuery?Un`${k.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${n.ftsQuery})`:void 0,n.exactName?a(k.name,n.exactName):void 0,n.project!==void 0?a(k.project,n.project):void 0,n.kind?a(k.kind,n.kind):void 0,n.filePath!==void 0?a(k.filePath,n.filePath):void 0,n.isExported!==void 0?a(k.isExported,n.isExported?1:0):void 0,n.decorator?Un`${k.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${n.decorator})`:void 0,n.resolvedType!==void 0?a(k.resolvedType,n.resolvedType):void 0)).orderBy(k.name).limit(n.regex?Math.max(n.limit*50,5000):n.limit).all();if(!n.regex)return u;try{let g=new RegExp(n.regex);return u.filter((m)=>g.test(m.name)).slice(0,n.limit)}catch{return[]}}}import{eq as s,and as o,isNull as zu,or as Pg}from"drizzle-orm";class vn{db;constructor(n){this.db=n}replaceFileRelations(n,u,g){this.db.transaction((m)=>{if(m.drizzleDb.delete(K).where(o(s(K.project,n),s(K.srcFilePath,u))).run(),!g.length)return;for(let i of g)m.drizzleDb.insert(K).values({project:n,type:i.type??"unknown",srcFilePath:i.srcFilePath??u,srcSymbolName:i.srcSymbolName??null,dstProject:i.dstProject??n,dstFilePath:i.dstFilePath??"",dstSymbolName:i.dstSymbolName??null,metaJson:i.metaJson??null}).run()})}getOutgoing(n,u,g){if(g!==void 0)return this.db.drizzleDb.select({project:K.project,type:K.type,srcFilePath:K.srcFilePath,srcSymbolName:K.srcSymbolName,dstProject:K.dstProject,dstFilePath:K.dstFilePath,dstSymbolName:K.dstSymbolName,metaJson:K.metaJson}).from(K).where(o(s(K.project,n),s(K.srcFilePath,u),Pg(s(K.srcSymbolName,g),zu(K.srcSymbolName)))).all();return this.db.drizzleDb.select({project:K.project,type:K.type,srcFilePath:K.srcFilePath,srcSymbolName:K.srcSymbolName,dstProject:K.dstProject,dstFilePath:K.dstFilePath,dstSymbolName:K.dstSymbolName,metaJson:K.metaJson}).from(K).where(o(s(K.project,n),s(K.srcFilePath,u))).all()}getIncoming(n){let{dstProject:u,dstFilePath:g}=n;return this.db.drizzleDb.select({project:K.project,type:K.type,srcFilePath:K.srcFilePath,srcSymbolName:K.srcSymbolName,dstProject:K.dstProject,dstFilePath:K.dstFilePath,dstSymbolName:K.dstSymbolName,metaJson:K.metaJson}).from(K).where(o(s(K.dstProject,u),s(K.dstFilePath,g))).all()}getByType(n,u){return this.db.drizzleDb.select({project:K.project,type:K.type,srcFilePath:K.srcFilePath,srcSymbolName:K.srcSymbolName,dstProject:K.dstProject,dstFilePath:K.dstFilePath,dstSymbolName:K.dstSymbolName,metaJson:K.metaJson}).from(K).where(o(s(K.project,n),s(K.type,u))).all()}deleteFileRelations(n,u){this.db.drizzleDb.delete(K).where(o(s(K.project,n),s(K.srcFilePath,u))).run()}searchRelations(n){return this.db.drizzleDb.select({project:K.project,type:K.type,srcFilePath:K.srcFilePath,srcSymbolName:K.srcSymbolName,dstProject:K.dstProject,dstFilePath:K.dstFilePath,dstSymbolName:K.dstSymbolName,metaJson:K.metaJson}).from(K).where(o(n.project!==void 0?s(K.project,n.project):void 0,n.srcFilePath!==void 0?s(K.srcFilePath,n.srcFilePath):void 0,n.srcSymbolName!==void 0?s(K.srcSymbolName,n.srcSymbolName):void 0,n.dstProject!==void 0?s(K.dstProject,n.dstProject):void 0,n.dstFilePath!==void 0?s(K.dstFilePath,n.dstFilePath):void 0,n.dstSymbolName!==void 0?s(K.dstSymbolName,n.dstSymbolName):void 0,n.type!==void 0?s(K.type,n.type):void 0)).limit(n.limit).all()}retargetRelations(n){let{dstProject:u,oldFile:g,oldSymbol:m,newFile:i,newSymbol:t,newDstProject:S}=n,w=m===null?o(s(K.dstProject,u),s(K.dstFilePath,g),zu(K.dstSymbolName)):o(s(K.dstProject,u),s(K.dstFilePath,g),s(K.dstSymbolName,m)),O={dstFilePath:i,dstSymbolName:t};if(S!==void 0)O.dstProject=S;this.db.drizzleDb.update(K).set(O).where(w).run()}}import{err as Du}from"@zipbul/result";import{subscribe as hg}from"@parcel/watcher";import Gn from"path";var dg=["**/.git/**",`**/${nn}/**`,"**/dist/**","**/node_modules/**"],xg=new Set(["package.json","tsconfig.json"]);function og(n){return n.replaceAll("\\","/")}function lg(n){if(n==="update")return"change";if(n==="create")return"create";return"delete"}class En{#n;#u;#g;#i;#m;#t;constructor(n,u=hg,g=console){this.#u=n.projectRoot,this.#g=[...dg,...n.ignorePatterns??[]],this.#i=new Set((n.extensions??[".ts",".mts",".cts"]).map((m)=>m.toLowerCase())),this.#m=u,this.#t=g}async start(n){try{this.#n=await this.#m(this.#u,(u,g)=>{if(u){this.#t.error(p("watcher","Callback error",u));return}try{for(let m of g){let i=og(Gn.relative(this.#u,m.path));if(i.startsWith(".."))continue;let t=Gn.basename(i),S=Gn.extname(i).toLowerCase();if(!xg.has(t)&&!this.#i.has(S))continue;if(i.endsWith(".d.ts"))continue;n({eventType:lg(m.type),filePath:i})}}catch(m){this.#t.error(p("watcher","Callback error",m))}},{ignore:this.#g})}catch(u){return Du(p("watcher","Failed to subscribe watcher",u))}}async close(){if(!this.#n)return;try{await this.#n.unsubscribe(),this.#n=void 0}catch(n){return Du(p("watcher","Failed to close watcher",n))}}}import jn from"path";import{promises as cg}from"fs";var eg=["**/node_modules/**","**/.git/**",`**/${nn}/**`,"**/dist/**"];async function Bn(n){let u=[];for await(let g of cg.glob("**/package.json",{cwd:n,exclude:eg})){let m=jn.dirname(g).replaceAll("\\","/"),i=jn.join(n,g),t=await Bun.file(i).json(),S=typeof t?.name==="string"&&t.name.length>0?t.name:jn.basename(m==="."?n:m);u.push({dir:m,project:S})}return u.sort((g,m)=>m.dir.length-g.dir.length),u}function G(n,u,g="default"){let m=n.replaceAll("\\","/");for(let i of u){if(i.dir===".")return i.project;if(m===i.dir||m.startsWith(`${i.dir}/`))return i.project}return g}import Ku from"path";var gn=new Map;async function nm(n){let u=Bun.file(n);if(!await u.exists())return null;try{let g=await u.text(),m=Bun.JSONC.parse(g);return typeof m==="object"&&m!==null?m:null}catch{return null}}async function Mn(n){if(gn.has(n))return gn.get(n)??null;let u=Ku.join(n,"tsconfig.json"),g=await nm(u);if(!g)return gn.set(n,null),null;let m=typeof g.compilerOptions==="object"&&g.compilerOptions!==null?g.compilerOptions:null;if(!m)return gn.set(n,null),null;let i=typeof m.baseUrl==="string"?m.baseUrl:null,t=typeof m.paths==="object"&&m.paths!==null?m.paths:null;if(!i&&!t)return gn.set(n,null),null;let S=i?Ku.resolve(n,i):n,w=new Map;if(t)for(let[_,A]of Object.entries(t)){if(!Array.isArray(A))continue;let f=A.filter((z)=>typeof z==="string");w.set(_,f)}let O={baseUrl:S,paths:w};return gn.set(n,O),O}function Yn(n){if(n){gn.delete(n);return}gn.clear()}import Vu from"path";function Zn(n,u){return Vu.relative(n,u).replaceAll("\\","/")}function _n(n,u){return Vu.resolve(n,u)}function mn(n){let u=Bun.hash.xxHash64(n);return BigInt.asUintN(64,BigInt(u)).toString(16).padStart(16,"0")}import{isErr as Iu}from"@zipbul/result";import{err as um}from"@zipbul/result";import{parseSync as gm}from"oxc-parser";function $n(n,u,g,m=gm){try{let{program:i,errors:t,comments:S}=m(n,u,g);return{filePath:n,program:i,errors:t,comments:S,sourceText:u}}catch(i){return um(p("parse",`Failed to parse file: ${n}`,i))}}import{promises as mm}from"fs";import{join as im}from"path";async function Wu(n){let{projectRoot:u,extensions:g,ignorePatterns:m,fileRepo:i}=n,t=i.getFilesMap(),S=new Set,w=[],O=[],_=m.map((f)=>new Bun.Glob(f));for await(let f of mm.glob("**/*",{cwd:u})){if(!g.some((r)=>f.endsWith(r)))continue;if(f.startsWith("node_modules/")||f.includes("/node_modules/"))continue;if(_.some((r)=>r.match(f)))continue;S.add(f);let z=im(u,f),V=Bun.file(z),{size:Q,lastModified:B}=V,Y=t.get(f);if(!Y){let r=await V.text(),M=mn(r);w.push({filePath:f,contentHash:M,mtimeMs:B,size:Q});continue}if(Y.mtimeMs===B&&Y.size===Q){O.push({filePath:f,contentHash:Y.contentHash,mtimeMs:B,size:Q});continue}let N=await V.text(),$=mn(N);if($===Y.contentHash)O.push({filePath:f,contentHash:$,mtimeMs:B,size:Q});else w.push({filePath:f,contentHash:$,mtimeMs:B,size:Q})}let A=[];for(let f of t.keys())if(!S.has(f))A.push(f);return{changed:w,unchanged:O,deleted:A}}function Hu(n){let u=[0];for(let g=0;g<n.length;g++)if(n[g]===`
3
+ `)u.push(g+1);return u}function Pn(n,u){let g=0,m=n.length-1;while(g<m){let i=g+m+1>>1;if(n[i]<=u)g=i;else m=i-1}return{line:g+1,column:u-n[g]}}import{err as tm}from"@zipbul/result";import{parse as wm}from"comment-parser";function Qu(n){try{let u=n.trim();if(u.startsWith("/**"))u=u.slice(3);if(u.endsWith("*/"))u=u.slice(0,-2);let m=wm(`/** ${u} */`)[0]??{description:"",tags:[]};return{description:(m.description??"").trim(),tags:(m.tags??[]).map((i)=>({tag:i.tag??"",name:i.name??"",type:i.type??"",description:i.description??"",optional:i.optional??!1,...i.default!==void 0?{default:i.default}:{}}))}}catch(u){return tm(p("parse","Failed to parse JSDoc comment",u))}}import{isErr as Om}from"@zipbul/result";function Ln(n){let{program:u,sourceText:g,comments:m}=n,i=Hu(g);function t(N,$){return{start:Pn(i,N),end:Pn(i,$)}}function S(N){let $=null;for(let r of m){if(r.type!=="Block")continue;if(r.end>N)continue;if(!r.value.startsWith("*"))continue;if(!$||r.end>$.end)$={value:`/*${r.value}*/`,end:r.end}}if(!$)return;for(let r of u.body){let M=r.start??0;if(M===N)continue;if(M>$.end&&M<N)return}return $.value}function w(N){if(!N)return;let $=N.typeAnnotation??N;return g.slice($.start,$.end)}function O(N){if(!N||N.length===0)return[];return N.map(($)=>{let r=$.expression;if(!r)return{name:"unknown"};if(r.type==="CallExpression"){let M=r.callee?.name??r.callee?.property?.name??"unknown",D=(r.arguments??[]).map((H)=>g.slice(H.start,H.end));return{name:M,arguments:D.length>0?D:void 0}}if(r.type==="Identifier")return{name:r.name??"unknown"};return{name:g.slice(r.start,r.end)}})}function _(N){let $=N.type==="TSParameterProperty"?N.parameter:N;if($?.type==="RestElement"){let U=`...${$.argument?.name??"unknown"}`,W=$.typeAnnotation,R=W?w(W):void 0,X={name:U,isOptional:!1};if(R)X.type=R;return X}if($?.type==="AssignmentPattern"){let{left:C,right:U}=$,W=C?.name??"unknown",R=C?.typeAnnotation,X=R?w(R):void 0,v=g.slice(U.start,U.end),E=O(C?.decorators??[]),P={name:W,isOptional:!0,defaultValue:v};if(X)P.type=X;if(E.length>0)P.decorators=E;return P}let r=$?.name??$?.pattern?.name??"unknown",M=!!$?.optional,D=$?.typeAnnotation,H=D?w(D):void 0,Z=O($?.decorators??[]),L={name:r,isOptional:M};if(H)L.type=H;if(Z.length>0)L.decorators=Z;return L}function A(N,$){let r=[];if($?.async)r.push("async");if(N.static)r.push("static");if(N.abstract)r.push("abstract");if(N.readonly)r.push("readonly");if(N.override)r.push("override");if(N.declare)r.push("declare");if(N.const)r.push("const");let M=N.accessibility;if(M==="private")r.push("private");else if(M==="protected")r.push("protected");else if(M==="public")r.push("public");return r}function f(N){let $=[];if(N.superClass){let M=g.slice(N.superClass.start,N.superClass.end);$.push({kind:"extends",name:M})}let r=N.implements??[];for(let M of r){let D=M.expression??M,H=g.slice(D.start,D.end);$.push({kind:"implements",name:H})}return $}function z(N){let $=[];for(let r of N.extends??[]){let M=r.expression??r,D=g.slice(M.start,M.end);$.push({kind:"extends",name:D})}return $}function V(N){let $=[];for(let r of N)if(r.type==="MethodDefinition"){let M=r.key?.name??"unknown",D=r.value,H=r.kind??"method",Z=H==="constructor"?"constructor":H==="get"?"getter":H==="set"?"setter":"method",L=A(r,D),C=(D?.params??[]).map(_),U=w(D?.returnType),W={kind:"method",name:M,span:t(r.start,r.end),isExported:!1,methodKind:Z,modifiers:L,parameters:C.length>0?C:void 0,returnType:U};$.push(W)}else if(r.type==="PropertyDefinition"){let M=r.key?.name??"unknown",D=A(r),H={kind:"property",name:M,span:t(r.start,r.end),isExported:!1,modifiers:D};$.push(H)}return $}function Q(N){let $=[];for(let r of N)if(r.type==="TSMethodSignature"){let M=r.key?.name??"unknown",D=(r.params??[]).map(_),H=w(r.returnType);$.push({kind:"method",name:M,span:t(r.start,r.end),isExported:!1,modifiers:[],methodKind:"method",parameters:D.length>0?D:void 0,returnType:H})}else if(r.type==="TSPropertySignature"){let M=r.key?.name??"unknown",D=w(r.typeAnnotation),H={kind:"property",name:M,span:t(r.start,r.end),isExported:!1,modifiers:r.readonly?["readonly"]:[],returnType:D};$.push(H)}return $}function B(N,$){let r=N.type??"";if(r==="FunctionDeclaration"){let M=N.id?.name??"default",D=(N.params??[]).map(_),H=w(N.returnType),Z=A(N,N),L=O(N.decorators??[]),C=N.typeParameters?.params?.map((W)=>W.name?.name).filter(Boolean)||void 0,U={kind:"function",name:M,span:t(N.start,N.end),isExported:$,modifiers:Z,parameters:D.length>0?D:void 0,returnType:H,decorators:L.length>0?L:void 0};if(C&&C.length>0)U.typeParameters=C;return U}if(r==="ClassDeclaration"||r==="ClassExpression"){let M=N.id?.name??"default",D=f(N),H=V(N.body?.body??[]),Z=O(N.decorators??[]),L=A(N,N),C=N.typeParameters?.params?.map((W)=>W.name?.name).filter(Boolean)||void 0,U={kind:"class",name:M,span:t(N.start,N.end),isExported:$,modifiers:L,heritage:D.length>0?D:void 0,members:H.length>0?H:void 0,decorators:Z.length>0?Z:void 0};if(C&&C.length>0)U.typeParameters=C;return U}if(r==="VariableDeclaration"){let M=[];for(let D of N.declarations??[]){let{id:H,init:Z}=D;if(H?.type==="ObjectPattern"){for(let X of H.properties??[]){let v=X.value?.name??X.key?.name??"unknown";M.push({kind:"variable",name:v,span:t(X.start??D.start,X.end??D.end),isExported:$,modifiers:[]})}continue}if(H?.type==="ArrayPattern"){for(let X of H.elements??[]){if(!X||X.type!=="Identifier")continue;let v=X.name??"unknown";M.push({kind:"variable",name:v,span:t(X.start??D.start,X.end??D.end),isExported:$,modifiers:[]})}continue}let L=H?.name??"unknown",C="variable",U,W;if(Z?.type==="FunctionExpression"||Z?.type==="ArrowFunctionExpression")C="function",U=(Z.params??[]).map(_),W=w(Z.returnType);let R=[];M.push({kind:C,name:L,span:t(D.start,D.end),isExported:$,modifiers:R,parameters:U,returnType:W})}if(M.length===0)return null;if(M.length===1)return M[0];return M}if(r==="TSTypeAliasDeclaration")return{kind:"type",name:N.id?.name??"unknown",span:t(N.start,N.end),isExported:$,modifiers:[]};if(r==="TSInterfaceDeclaration"){let M=N.id?.name??"unknown",D=z(N),H=Q(N.body?.body??[]),Z=N.typeParameters?.params?.map((C)=>C.name?.name).filter(Boolean)||void 0,L={kind:"interface",name:M,span:t(N.start,N.end),isExported:$,modifiers:[],heritage:D.length>0?D:void 0,members:H.length>0?H:void 0};if(Z&&Z.length>0)L.typeParameters=Z;return L}if(r==="TSEnumDeclaration"){let M=N.id?.name??"unknown",D=A(N),Z=(N.body?.members??[]).map((L)=>({kind:"property",name:L.id?.name??L.id?.value??"unknown",span:t(L.start,L.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:M,span:t(N.start,N.end),isExported:$,modifiers:D,members:Z.length>0?Z:void 0}}return null}let Y=[];for(let N of u.body){let $=null,r=N,M=typeof r.type==="string"?r.type:"";if(M==="ExportNamedDeclaration"){let H=N;if(H.declaration){if($=B(H.declaration,!0),$&&!Array.isArray($))$.span=t(H.start,H.end);else if(Array.isArray($))for(let Z of $)Z.span=t(H.start,H.end)}}else if(M==="ExportDefaultDeclaration"){let H=N,Z=H.declaration;if(Z){if($=B(Z,!0),$&&!Array.isArray($))$.name=Z.id?.name??"default",$.isExported=!0,$.span=t(H.start,H.end)}}else $=B(N,!1);let D=Array.isArray($)?$:$?[$]:[];for(let H of D){let Z=N.start??0,L=S(Z);if(L){let C=Qu(L);if(!Om(C))H.jsDoc=C}Y.push(H)}}return Y}function Sm(n){if(n.kind==="function"||n.kind==="method"){let u=n.parameters?.length??0,g=n.modifiers.includes("async")?1:0;return`params:${u}|async:${g}`}return null}function rm(n){let u={};if(n.jsDoc)u.jsDoc=n.jsDoc;if(n.kind==="function"||n.kind==="method"){if(n.parameters!==void 0)u.parameters=n.parameters;if(n.returnType!==void 0)u.returnType=n.returnType}if(n.heritage?.length)u.heritage=n.heritage;if(n.decorators?.length)u.decorators=n.decorators;if(n.typeParameters?.length)u.typeParameters=n.typeParameters;if(n.modifiers?.length)u.modifiers=n.modifiers;if(n.members?.length)u.members=n.members.map((g)=>{let m=g.modifiers.find((i)=>i==="private"||i==="protected"||i==="public");return{name:g.name,kind:g.methodKind??g.kind,type:g.returnType,visibility:m,isStatic:g.modifiers.includes("static")||void 0,isReadonly:g.modifiers.includes("readonly")||void 0}});return Object.keys(u).length>0?JSON.stringify(u):null}function Uu(n,u,g,m,i){let t=Sm(n),S=mn(`${u}|${n.kind}|${t??""}`);return{project:g,filePath:m,kind:n.kind,name:u,startLine:n.span.start.line,startColumn:n.span.start.column,endLine:n.span.end.line,endColumn:n.span.end.column,isExported:n.isExported?1:0,signature:t,fingerprint:S,detailJson:rm(n),contentHash:i,indexedAt:new Date().toISOString()}}function hn(n){let{parsed:u,project:g,filePath:m,contentHash:i,symbolRepo:t}=n,S=Ln(u),w=[];for(let O of S){w.push(Uu(O,O.name,g,m,i));for(let _ of O.members??[])w.push(Uu(_,`${O.name}.${_.name}`,g,m,i))}t.replaceFileSymbols(g,m,i,w)}import{resolve as dn,dirname as _m,extname as Jm}from"path";function On(n,u,g){let m=(i)=>{let t=Jm(i);if(t==="")return[i+".ts",i+".d.ts",i+"/index.ts",i+"/index.d.ts",i+".mts",i+"/index.mts",i+".cts",i+"/index.cts"];if(t===".js")return[i.slice(0,-3)+".ts"];if(t===".mjs")return[i.slice(0,-4)+".mts"];if(t===".cjs")return[i.slice(0,-4)+".cts"];return[i]};if(u.startsWith(".")){let i=dn(_m(n),u);return m(i)}if(g)for(let[i,t]of g.paths){if(t.length===0)continue;let S=i.indexOf("*");if(S===-1){if(u===i){let w=[];for(let O of t)w.push(...m(dn(g.baseUrl,O)));return w}}else{let w=i.slice(0,S),O=i.slice(S+1);if(u.startsWith(w)&&(O===""||u.endsWith(O))){let _=u.slice(w.length,O===""?void 0:u.length-O.length),A=[];for(let f of t)A.push(...m(dn(g.baseUrl,f.replace("*",_))));return A}}}return[]}function Bu(n,u,g,m=On){let i=new Map,t=n.body??[];for(let S of t){if(S.type!=="ImportDeclaration")continue;let w=S.source?.value??"",O=m(u,w,g);if(O.length===0)continue;let _=O[0],A=S.specifiers??[];for(let f of A)switch(f.type){case"ImportSpecifier":i.set(f.local.name,{path:_,importedName:f.imported.name});break;case"ImportDefaultSpecifier":i.set(f.local.name,{path:_,importedName:"default"});break;case"ImportNamespaceSpecifier":i.set(f.local.name,{path:_,importedName:"*"});break}}return i}var Am=new Set(["loc","start","end","scope"]);function Jn(n,u){if(!n||typeof n!=="object")return;if(Array.isArray(n)){for(let m of n)Jn(m,u);return}let g=n;u(g);for(let m of Object.keys(g)){if(Am.has(m))continue;let i=g[m];if(i&&typeof i==="object")Jn(i,u)}}function Yu(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if((u.type==="StringLiteral"||u.type==="Literal")&&typeof u.value==="string")return u.value;return null}function Sn(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if(u.type==="Identifier"){let g=u.name;return{root:g,parts:[],full:g}}if(u.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(u.type==="Super")return{root:"super",parts:[],full:"super"};if(u.type==="MemberExpression"){let g=[],m=u;while(m.type==="MemberExpression"){let S=m.property;if(!S||typeof S.name!=="string")return null;g.unshift(S.name),m=m.object}let i;if(m.type==="Identifier")i=m.name;else if(m.type==="ThisExpression")i="this";else if(m.type==="Super")i="super";else return null;let t=[i,...g].join(".");return{root:i,parts:g,full:t}}return null}function Zu(n,u,g,m=On){let i=[],t=n.body??[];for(let S of t){if(S.type==="ImportDeclaration"){let w=S.source?.value??"",O=m(u,w,g);if(O.length===0)continue;let _=O[0],A=S.importKind==="type",f=S.specifiers??[];if(f.length===0){let z={};if(A)z.isType=!0;i.push({type:A?"type-references":"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:_,dstSymbolName:null,...Object.keys(z).length>0?{metaJson:JSON.stringify(z)}:{}})}else for(let z of f){let V=z.type,Q=A||z.importKind==="type",B={};if(Q)B.isType=!0;let Y,N;if(V==="ImportDefaultSpecifier")Y="default",N=z.local.name;else if(V==="ImportNamespaceSpecifier")Y="*",N=z.local.name,B.importKind="namespace";else Y=z.imported.name,N=z.local.name;i.push({type:Q?"type-references":"imports",srcFilePath:u,srcSymbolName:N,dstFilePath:_,dstSymbolName:Y,...Object.keys(B).length>0?{metaJson:JSON.stringify(B)}:{}})}continue}if(S.type==="ExportAllDeclaration"&&S.source){let w=S.source?.value??"",O=m(u,w,g);if(O.length===0)continue;let _=O[0],A=S.exportKind==="type",f={isReExport:!0};if(A)f.isType=!0;i.push({type:A?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:_,dstSymbolName:null,metaJson:JSON.stringify(f)});continue}if(S.type==="ExportNamedDeclaration"&&S.source){let w=S.source?.value??"",O=m(u,w,g);if(O.length===0)continue;let _=O[0],A=S.exportKind==="type",V={isReExport:!0,specifiers:(S.specifiers??[]).map((Q)=>({local:Q.local.name,exported:Q.exported.name}))};if(A)V.isType=!0;i.push({type:A?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:_,dstSymbolName:null,metaJson:JSON.stringify(V)})}}return Jn(n,(S)=>{if(S.type!=="ImportExpression")return;let w=Yu(S.source);if(!w)return;let O=m(u,w,g);if(O.length===0)return;let _=O[0];i.push({type:"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:_,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),i}function Lu(n,u,g){let m=[],i=[],t=[];function S(){if(i.length>0)return i[i.length-1]??null;return null}function w(_){if(!_)return null;let A=g.get(_.root);if(_.parts.length===0){if(A)return{dstFilePath:A.path,dstSymbolName:A.importedName,resolution:"import"};return{dstFilePath:u,dstSymbolName:_.root,resolution:"local"}}else{if(A&&A.importedName==="*"){let f=_.parts[_.parts.length-1];return{dstFilePath:A.path,dstSymbolName:f,resolution:"namespace"}}return{dstFilePath:u,dstSymbolName:_.full,resolution:"local-member"}}}function O(_){if(!_||typeof _!=="object")return;if(Array.isArray(_)){for(let z of _)O(z);return}let A=_,f=typeof A.type==="string"?A.type:"";if(f==="ClassDeclaration"||f==="ClassExpression"){let z=A,V=z.id?.name??"AnonymousClass";t.push(V),O(z.body),t.pop();return}if(f==="FunctionDeclaration"){let z=A,V=z.id?.name??"anonymous";i.push(V),O(z.body),i.pop();return}if(f==="VariableDeclarator"&&A.init&&(A.init?.type==="FunctionExpression"||A.init?.type==="ArrowFunctionExpression")){let z=A,V=z.id?.name??"anonymous";i.push(V),O(z.init?.body??z.init),i.pop();return}if(f==="MethodDefinition"&&A.value){let z=A,V=t[t.length-1]??"",Q=z.key?.name??"anonymous",B=V?`${V}.${Q}`:Q;i.push(B),O(z.value?.body),i.pop();return}if(f==="FunctionExpression"||f==="ArrowFunctionExpression"){let z=S(),V=z?`${z}.<anonymous>`:"<anonymous>";i.push(V),O(A.body),i.pop();return}if(f==="CallExpression"){let z=A,V=Sn(z.callee),Q=w(V);if(Q){let B=S(),Y={};if(B===null)Y.scope="module";m.push({type:"calls",srcFilePath:u,srcSymbolName:B,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,...Object.keys(Y).length>0?{metaJson:JSON.stringify(Y)}:{}})}O(z.callee);for(let B of z.arguments??[])O(B);return}if(f==="NewExpression"){let z=A,V=Sn(z.callee),Q=w(V);if(Q){let B=S(),Y={isNew:!0};if(B===null)Y.scope="module";m.push({type:"calls",srcFilePath:u,srcSymbolName:B,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,metaJson:JSON.stringify(Y)})}for(let B of z.arguments??[])O(B);return}for(let z of Object.keys(A)){if(z==="loc"||z==="start"||z==="end"||z==="scope")continue;let V=A[z];if(V&&typeof V==="object")O(V)}}return O(n),m}function Xu(n,u,g){let m=[];return Jn(n,(i)=>{if(i.type==="TSInterfaceDeclaration"){let w=i.id?.name??"AnonymousInterface",O=i.extends??[];for(let _ of O){let A=_.expression??_,f=Sn(A);if(!f)continue;let z=xn(f,u,g);m.push({type:"extends",srcFilePath:u,srcSymbolName:w,...z})}return}if(i.type!=="ClassDeclaration"&&i.type!=="ClassExpression")return;let t=i.id?.name??"AnonymousClass";if(i.superClass){let w=Sn(i.superClass);if(w){let O=xn(w,u,g);m.push({type:"extends",srcFilePath:u,srcSymbolName:t,...O})}}let S=i.implements??[];for(let w of S){let O=w.expression??w,_=Sn(O);if(!_)continue;let A=xn(_,u,g);m.push({type:"implements",srcFilePath:u,srcSymbolName:t,...A})}}),m}function xn(n,u,g){let m=g.get(n.root);if(m){if(m.importedName==="*"){let i=n.parts[n.parts.length-1]??n.root;return{dstFilePath:m.path,dstSymbolName:i,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:m.path,dstSymbolName:n.parts.length>0?n.full:m.importedName}}return{dstFilePath:u,dstSymbolName:n.full,metaJson:JSON.stringify({isLocal:!0})}}function Xn(n,u,g,m=On){let i=Bu(n,u,g,m),t=Zu(n,u,g,m),S=Lu(n,u,i),w=Xu(n,u,i);return[...t,...S,...w]}function on(n){let{ast:u,project:g,filePath:m,relationRepo:i,projectRoot:t,tsconfigPaths:S,knownFiles:w,boundaries:O}=n,_=_n(t,m),f=Xn(u,_,S,w?(V,Q,B)=>{let Y=On(V,Q,B);for(let N of Y){let $=Zn(t,N);if(O){let r=G($,O);if(w.has(`${r}::${$}`))return[N]}else if(w.has(`${g}::${$}`))return[N]}return[]}:void 0),z=[];for(let V of f){let Q=Zn(t,V.dstFilePath);if(Q.startsWith(".."))continue;let B=Zn(t,V.srcFilePath),Y=O?G(Q,O):g;z.push({project:g,type:V.type,srcFilePath:B,srcSymbolName:V.srcSymbolName??null,dstProject:Y,dstFilePath:Q,dstSymbolName:V.dstSymbolName??null,metaJson:V.metaJson??null})}return i.replaceFileRelations(g,m,z),z.length}var fm=100,ku=50;class ln{opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;constructor(n){this.opts=n,this.logger=n.logger??console,this.tsconfigPathsRaw=Mn(n.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(n){return this.startIndex(n,!1)}onIndexed(n){return this.callbacks.add(n),()=>this.callbacks.delete(n)}handleWatcherEvent(n){if(n.filePath.endsWith("tsconfig.json")){Yn(this.opts.projectRoot),this.tsconfigPathsRaw=Mn(this.opts.projectRoot),this.fullIndex().catch((u)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",u)});return}if(n.filePath.endsWith("package.json")){let u=this.opts.discoverProjectsFn??Bn;this.boundariesRefresh=u(this.opts.projectRoot).then((g)=>{this.opts.boundaries=g})}if(this.pendingEvents.push(n),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},fm)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(n,u){if(this.indexingLock){if(u)return this.pendingFullIndex=!0,new Promise((m,i)=>{this.pendingFullIndexWaiters.push({resolve:m,reject:i})});return this.currentIndexing}this.indexingLock=!0;let g=this.doIndex(n,u).then((m)=>{return this.fireCallbacks(m),m}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let m=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((i)=>{for(let t of m)t.resolve(i)}).catch((i)=>{for(let t of m)t.reject(i)})}else if(this.pendingEvents.length>0){let m=this.pendingEvents.splice(0);this.startIndex(m,!1).catch((i)=>this.logger.error("[IndexCoordinator] incremental drain error",i))}});return this.currentIndexing=g,g}async doIndex(n,u){let g=Date.now(),{fileRepo:m,symbolRepo:i,relationRepo:t,dbConnection:S}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let w,O;if(n!==void 0)w=n.filter((r)=>r.eventType==="create"||r.eventType==="change").map((r)=>({filePath:r.filePath,contentHash:"",mtimeMs:0,size:0})),O=n.filter((r)=>r.eventType==="delete").map((r)=>r.filePath);else{let r=new Map;for(let D of this.opts.boundaries)for(let[H,Z]of m.getFilesMap(D.project))r.set(H,Z);let M=await Wu({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>r}});w=M.changed,O=M.deleted}let _=await this.tsconfigPathsRaw??void 0,A=new Map;for(let r of O){let M=G(r,this.opts.boundaries),D=i.getFileSymbols(M,r);A.set(r,D)}let f=new Map,z=new Map;if(u)for(let r of this.opts.boundaries)for(let M of m.getAllFiles(r.project))for(let D of i.getFileSymbols(r.project,M.filePath))f.set(`${D.filePath}::${D.name}`,{name:D.name,filePath:D.filePath,kind:D.kind,fingerprint:D.fingerprint});else{for(let r of w){let M=G(r.filePath,this.opts.boundaries);for(let D of i.getFileSymbols(M,r.filePath))f.set(`${D.filePath}::${D.name}`,{name:D.name,filePath:D.filePath,kind:D.kind,fingerprint:D.fingerprint})}for(let[,r]of A)for(let M of r)f.set(`${M.filePath}::${M.name}`,{name:M.name,filePath:M.filePath,kind:M.kind,fingerprint:M.fingerprint})}let V=()=>{for(let r of O){let M=G(r,this.opts.boundaries);i.deleteFileSymbols(M,r),t.deleteFileRelations(M,r),m.deleteFile(M,r)}},Q=async()=>{let{projectRoot:r,boundaries:M}=this.opts,{parseCache:D}=this.opts,H=0,Z=0,L=[],C=[];for(let W of w)try{let R=_n(r,W.filePath),X=Bun.file(R),v=await X.text(),E=W.contentHash||mn(v),P=G(W.filePath,M);m.upsertFile({project:P,filePath:W.filePath,mtimeMs:X.lastModified,size:X.size,contentHash:E,updatedAt:new Date().toISOString(),lineCount:v.split(`
4
+ `).length});let e=(this.opts.parseSourceFn??$n)(R,v);if(Iu(e))throw e.data;let I=e;C.push({filePath:W.filePath,text:v,contentHash:E,parsed:I,project:P})}catch(R){this.logger.error(`[IndexCoordinator] Failed to prepare ${W.filePath}:`,R),L.push(W.filePath)}let U=new Set;for(let W of M)for(let[R]of m.getFilesMap(W.project))U.add(`${W.project}::${R}`);return S.transaction(()=>{for(let W of C)hn({parsed:W.parsed,project:W.project,filePath:W.filePath,contentHash:W.contentHash,symbolRepo:i}),Z+=on({ast:W.parsed.program,project:W.project,filePath:W.filePath,relationRepo:t,projectRoot:r,tsconfigPaths:_,knownFiles:U,boundaries:M}),D.set(W.filePath,W.parsed),H+=i.getFileSymbols(W.project,W.filePath).length}),{symbols:H,relations:Z,failedFiles:L}},B=0,Y=0,N=[];if(u){let{projectRoot:r,boundaries:M}=this.opts,{parseCache:D}=this.opts,H=[];for(let L=0;L<w.length;L+=ku){let C=w.slice(L,L+ku),U=await Promise.allSettled(C.map(async(W)=>{let R=_n(r,W.filePath),X=Bun.file(R),v=await X.text(),E=W.contentHash||mn(v);return{filePath:W.filePath,text:v,contentHash:E,mtimeMs:X.lastModified,size:X.size}}));for(let W of U)if(W.status==="fulfilled")H.push(W.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",W.reason)}let Z=[];S.transaction(()=>{for(let U of H){let W=G(U.filePath,M);m.deleteFile(W,U.filePath)}for(let U of O){let W=G(U,M);i.deleteFileSymbols(W,U),t.deleteFileRelations(W,U),m.deleteFile(W,U)}for(let U of H){let W=G(U.filePath,M);m.upsertFile({project:W,filePath:U.filePath,mtimeMs:U.mtimeMs,size:U.size,contentHash:U.contentHash,updatedAt:new Date().toISOString(),lineCount:U.text.split(`
5
+ `).length})}let L=new Set;for(let U of M)for(let[W]of m.getFilesMap(U.project))L.add(`${U.project}::${W}`);let C=this.opts.parseSourceFn??$n;for(let U of H){let W=G(U.filePath,M),R=C(_n(r,U.filePath),U.text);if(Iu(R))throw R.data;let X=R;Z.push({filePath:U.filePath,parsed:X}),hn({parsed:X,project:W,filePath:U.filePath,contentHash:U.contentHash,symbolRepo:i}),Y+=on({ast:X.program,project:W,filePath:U.filePath,relationRepo:t,projectRoot:r,tsconfigPaths:_,knownFiles:L,boundaries:M}),B+=i.getFileSymbols(W,U.filePath).length}});for(let L of Z)D.set(L.filePath,L.parsed)}else{V();let r=await Q();B=r.symbols,Y=r.relations,N=r.failedFiles}for(let r of w){let M=G(r.filePath,this.opts.boundaries);for(let D of i.getFileSymbols(M,r.filePath))z.set(`${D.filePath}::${D.name}`,{name:D.name,filePath:D.filePath,kind:D.kind,fingerprint:D.fingerprint})}let $={added:[],modified:[],removed:[]};for(let[r,M]of z){let D=f.get(r);if(!D)$.added.push({name:M.name,filePath:M.filePath,kind:M.kind});else if(D.fingerprint!==M.fingerprint)$.modified.push({name:M.name,filePath:M.filePath,kind:M.kind})}for(let[r,M]of f)if(!z.has(r))$.removed.push({name:M.name,filePath:M.filePath,kind:M.kind});if(!u)for(let[r,M]of A)for(let D of M){if(!D.fingerprint)continue;let H=G(r,this.opts.boundaries),Z=i.getByFingerprint(H,D.fingerprint);if(Z.length===1){let L=Z[0];t.retargetRelations({dstProject:H,oldFile:r,oldSymbol:D.name,newFile:L.filePath,newSymbol:L.name})}}return{indexedFiles:w.length,removedFiles:O.length,totalSymbols:B,totalRelations:Y,durationMs:Date.now()-g,changedFiles:w.map((r)=>r.filePath),deletedFiles:[...O],failedFiles:N,changedSymbols:$}}fireCallbacks(n){for(let u of this.callbacks)try{u(n)}catch(g){this.logger.error("[IndexCoordinator] onIndexed callback threw:",g)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let n=this.pendingEvents.splice(0);this.startIndex(n,!1).catch((u)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",u))}}}function Nm(n){try{return process.kill(n,0),!0}catch(u){if(typeof u==="object"&&u&&"code"in u)return u.code!=="ESRCH";return!0}}function Mm(n){let u=new Date(n).getTime();return Number.isNaN(u)?0:u}function Cu(n,u,g={}){let m=g.now??Date.now,i=g.isAlive??Nm,t=g.staleAfterSeconds??60,S=g.instanceId;return n.immediateTransaction(()=>{let w=n.selectOwner();if(!w)return n.insertOwner(u,S),"owner";let O=Math.floor((m()-Mm(w.heartbeat_at))/1000),_=i(w.pid);if(_&&S&&w.instance_id&&w.instance_id!==S&&w.pid!==u)return n.replaceOwner(u,S),"owner";if(_&&O<t)return"reader";return n.replaceOwner(u,S),"owner"})}function Tu(n,u){n.deleteOwner(u)}function yu(n,u){n.touchOwner(u)}class zn{#n;#u=new Map;constructor(n){this.#n=Math.max(1,n)}get size(){return this.#u.size}has(n){return this.#u.has(n)}get(n){if(!this.#u.has(n))return;let u=this.#u.get(n);return this.#u.delete(n),this.#u.set(n,u),u}set(n,u){if(this.#u.has(n))this.#u.delete(n);if(this.#u.set(n,u),this.#u.size>this.#n){let g=this.#u.keys().next().value;if(g!==void 0)this.#u.delete(g)}}delete(n){return this.#u.delete(n)}clear(){this.#u.clear()}}class cn{lru;constructor(n=500){this.lru=new zn(n)}get(n){return this.lru.get(n)}set(n,u){this.lru.set(n,u)}invalidate(n){this.lru.delete(n)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function en(n){let{symbolRepo:u,project:g,query:m}=n,i=m.project??g,t=m.limit??100,S={kind:m.kind,filePath:m.filePath,isExported:m.isExported,project:i,limit:t,resolvedType:m.resolvedType};if(m.text)if(m.exact)S.exactName=m.text;else{let O=Qn(m.text);if(O)S.ftsQuery=O}if(m.decorator)S.decorator=m.decorator;if(m.regex)S.regex=m.regex;return u.searchByQuery(S).map((O)=>({id:O.id,filePath:O.filePath,kind:O.kind,name:O.name,span:{start:{line:O.startLine,column:O.startColumn},end:{line:O.endLine,column:O.endColumn}},isExported:O.isExported===1,signature:O.signature,fingerprint:O.fingerprint,detail:O.detailJson?(()=>{try{return JSON.parse(O.detailJson)}catch{return{}}})():{}}))}function nu(n){let{relationRepo:u,project:g,query:m}=n,i=m.project??g,t=m.limit??500;return u.searchRelations({srcFilePath:m.srcFilePath,srcSymbolName:m.srcSymbolName,dstFilePath:m.dstFilePath,dstSymbolName:m.dstSymbolName,dstProject:m.dstProject,type:m.type,project:i,limit:t}).map((w)=>{let O;if(w.metaJson)try{O=JSON.parse(w.metaJson)}catch{}return{type:w.type,srcFilePath:w.srcFilePath,srcSymbolName:w.srcSymbolName,dstFilePath:w.dstFilePath,dstSymbolName:w.dstSymbolName,dstProject:w.dstProject,metaJson:w.metaJson??void 0,meta:O}})}import{findInFiles as $m,Lang as zm}from"@ast-grep/napi";async function uu(n){if(n.filePaths.length===0)return[];let u=[];return await $m(zm.TypeScript,{paths:n.filePaths,matcher:{rule:{pattern:n.pattern}}},(g,m)=>{if(g)return;for(let i of m){let t=i.range();u.push({filePath:i.getRoot().filename(),startLine:t.start.line+1,endLine:t.end.line+1,matchedText:i.text()})}}),u}import b from"typescript";import{isErr as km}from"@zipbul/result";import l from"typescript";import Dm from"path";import{err as gu}from"@zipbul/result";function Km(n){try{return Ju("fs").readFileSync(n,"utf-8")}catch{return}}function Vm(n){try{return Ju("fs").readFileSync(n,"utf-8")}catch{return}}class In{#n;#u;#g=!1;__testing__;constructor(n,u){this.#n=n,this.#u=u,this.__testing__={host:u}}static create(n,u={}){let g=u.readConfigFile??Km,m=u.resolveNonTrackedFile??Vm,i=Dm.dirname(n),t=g(n);if(t===void 0)return gu(p("semantic",`tsconfig not found: ${n}`));let S=l.parseJsonText(n,t),w=S.parseDiagnostics;if(w&&w.length>0){let f=w.map((z)=>l.flattenDiagnosticMessageText(z.messageText,`
6
+ `)).join("; ");return gu(p("semantic",`tsconfig parse error: ${f}`))}let O=l.parseJsonSourceFileConfigFileContent(S,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(f)=>g(f)!==void 0||m(f)!==void 0,readFile:(f)=>g(f)??m(f)},i);if(O.errors.length>0){let f=O.errors.filter((z)=>z.category===l.DiagnosticCategory.Error&&z.code!==18003);if(f.length>0){let z=f.map((V)=>l.flattenDiagnosticMessageText(V.messageText,`
7
+ `)).join("; ");return gu(p("semantic",`tsconfig compile error: ${z}`))}}let _=new su(O.fileNames,O.options,i,m),A=l.createLanguageService(_);return new In(A,_)}get isDisposed(){return this.#g}getProgram(){this.#i();let n=this.#n.getProgram();if(!n)throw Error("TscProgram: LanguageService returned null Program");return n}getChecker(){return this.#i(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#i(),this.#n}notifyFileChanged(n,u){if(this.#g)return;this.#u.updateFile(n,u)}removeFile(n){if(this.#g)return;this.#u.removeFile(n)}dispose(){if(this.#g)return;this.#g=!0,this.#n.dispose()}#i(){if(this.#g)throw Error("TscProgram is disposed")}}class su{#n;#u;#g;#i;#m=new Map;constructor(n,u,g,m){this.#n=[...n],this.#u=u,this.#g=g,this.#i=m}updateFile(n,u){let g=this.#m.get(n);if(g)g.version+=1,g.content=u;else this.#m.set(n,{version:1,content:u})}removeFile(n){this.#m.delete(n),this.#n=this.#n.filter((u)=>u!==n)}getScriptFileNames(){let n=[...this.#m.keys()];return[...this.#n.filter((g)=>!this.#m.has(g)),...n]}getScriptVersion(n){let u=this.#m.get(n);return u?String(u.version):"0"}getScriptSnapshot(n){let u=this.#m.get(n);if(u)return l.ScriptSnapshot.fromString(u.content);let g=this.#i(n);if(g!==void 0)return l.ScriptSnapshot.fromString(g);return}getCurrentDirectory(){return this.#g}getCompilationSettings(){return this.#u}getDefaultLibFileName(n){return l.getDefaultLibFilePath(n)}fileExists(n){if(this.#m.has(n))return!0;return this.#i(n)!==void 0}readFile(n){let u=this.#m.get(n);if(u)return u.content;return this.#i(n)}}import q from"typescript";import Wm from"typescript";function c(n,u){if(u<0||u>=n.getEnd())return;function g(m){let i=m.getStart(n,!1),t=m.getEnd();if(u<i||u>=t)return;let S;return Wm.forEachChild(m,(w)=>{if(!S)S=g(w)}),S??m}return g(n)}function Hm(n){return!!(n.flags&q.TypeFlags.Object)&&!!(n.objectFlags&q.ObjectFlags.Reference)}function Dn(n,u,g=0){let m=n.typeToString(u),i=u.flags,t=!!(i&q.TypeFlags.Union),S=!!(i&q.TypeFlags.Intersection),w;if(g<8&&Hm(u)){let f=n.getTypeArguments(u);if(f.length>0)w=f}let O=!!(i&q.TypeFlags.TypeParameter)||w!==void 0&&w.length>0,_;if(t&&g<8)_=u.types.map((f)=>Dn(n,f,g+1));else if(S&&g<8)_=u.types.map((f)=>Dn(n,f,g+1));let A;if(w&&w.length>0)A=w.map((f)=>Dn(n,f,g+1));return{text:m,flags:i,isUnion:t,isIntersection:S,isGeneric:O,members:_,typeArguments:A}}function Qm(n){return q.isFunctionDeclaration(n)||q.isVariableDeclaration(n)||q.isClassDeclaration(n)||q.isInterfaceDeclaration(n)||q.isTypeAliasDeclaration(n)||q.isEnumDeclaration(n)||q.isMethodDeclaration(n)||q.isPropertyDeclaration(n)||q.isPropertySignature(n)||q.isMethodSignature(n)}class mu{program;constructor(n){this.program=n}collectAt(n,u){let g=this.program.getProgram(),m=this.program.getChecker();if(u<0)return null;let i=g.getSourceFile(n);if(!i)return null;if(u>=i.getEnd())return null;let t=c(i,u);if(!t)return null;if(!q.isIdentifier(t))return null;try{let S=m.getTypeAtLocation(t);return Dn(m,S)}catch{return null}}collectFile(n){let u=new Map,g=this.program.getProgram(),m=this.program.getChecker(),i=g.getSourceFile(n);if(!i)return u;function t(S){if(Qm(S)&&S.name&&q.isIdentifier(S.name)){let w=S.name;try{let O=m.getTypeAtLocation(w),_=w.getStart(i);u.set(_,Dn(m,O))}catch{}}q.forEachChild(S,t)}return t(i),u}}import tn from"typescript";var Um=1000,Bm=1;function Ym(n){let u=n.declarations?.[0],g=u?.getSourceFile(),m=u?tn.getNameOfDeclaration(u):void 0;return{name:n.getName(),filePath:g?.fileName??"",position:m?.getStart(g,!1)??u?.getStart(g,!1)??0}}function kn(n,u=0){let g=n.declarations?.[0],m=g?.getSourceFile(),i=g?tn.getNameOfDeclaration(g):void 0,t=m?.fileName??"",S=i?.getStart(m,!1)??g?.getStart(m,!1)??0,w={name:n.getName(),filePath:t,position:S},O=n;if(O.parent)w.parent=Ym(O.parent);if(u<Bm){let _=n.flags,A=!!(_&tn.SymbolFlags.Enum),f=!!(_&(tn.SymbolFlags.NamespaceModule|tn.SymbolFlags.ValueModule)),z=!!(_&(tn.SymbolFlags.Class|tn.SymbolFlags.Interface));if(A&&n.exports&&n.exports.size>0){let V=[];n.exports.forEach((Q)=>{V.push(kn(Q,u+1))}),w.members=V}else if(z&&n.members&&n.members.size>0){let V=[];n.members.forEach((Q)=>{V.push(kn(Q,u+1))}),w.members=V}if(f&&n.exports&&n.exports.size>0){let V=[];n.exports.forEach((Q)=>{V.push(kn(Q,u+1))}),w.exports=V}}return w}class iu{#n;#u;#g=new Map;constructor(n,u=Um){this.#n=n,this.#u=new zn(u)}get(n,u){if(this.#n.isDisposed)return null;let g=`${n}:${u}`,m=this.#u.get(g);if(m!==void 0)return m;let t=this.#n.getProgram().getSourceFile(n);if(!t)return null;let S=c(t,u);if(!S||!tn.isIdentifier(S))return null;let O=this.#n.getChecker().getSymbolAtLocation(S);if(!O)return null;let _=kn(O);this.#u.set(g,_);let A=this.#g.get(n);if(!A)A=new Set,this.#g.set(n,A);return A.add(g),_}invalidate(n){let u=this.#g.get(n);if(u){for(let g of u)this.#u.delete(g);this.#g.delete(n)}}clear(){this.#u.clear(),this.#g.clear()}}import Zm from"typescript";class tu{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let g=this.#n.getProgram(),m=g.getSourceFile(n);if(!m)return[];let i=c(m,u);if(!i||!Zm.isIdentifier(i))return[];let S=this.#n.getLanguageService().findReferences(n,u);if(!S||S.length===0)return[];let w=[];for(let O of S)for(let _ of O.references){let A=g.getSourceFile(_.fileName);if(!A)continue;let{line:f,character:z}=A.getLineAndCharacterOfPosition(_.textSpan.start);w.push({filePath:_.fileName,position:_.textSpan.start,line:f+1,column:z,isDefinition:_.isDefinition??!1,isWrite:_.isWriteAccess??!1})}return w}}import T from"typescript";function Lm(n,u){let g=c(n,u);if(!g)return;if(Ru(g))return g;let m=g.parent;for(let i=0;i<5&&m;i++){if(Ru(m))return m;m=m.parent}return g}function Ru(n){return T.isClassDeclaration(n)||T.isClassExpression(n)||T.isFunctionDeclaration(n)||T.isFunctionExpression(n)||T.isArrowFunction(n)||T.isVariableDeclaration(n)||T.isObjectLiteralExpression(n)}function Fu(n){if(T.isClassDeclaration(n)||T.isClassExpression(n))return"class";if(T.isFunctionDeclaration(n)||T.isFunctionExpression(n)||T.isArrowFunction(n))return"function";if(T.isObjectLiteralExpression(n))return"object";if(T.isVariableDeclaration(n)&&n.initializer)return Fu(n.initializer);return"class"}function Xm(n,u){if(T.isClassDeclaration(n)||T.isFunctionDeclaration(n))return n.name?.getText(u)??"";if(T.isClassExpression(n))return n.name?.getText(u)??"";if(T.isVariableDeclaration(n)&&T.isIdentifier(n.name))return n.name.getText(u);if(T.isFunctionExpression(n))return n.name?.getText(u)??"";if(T.isArrowFunction(n)&&n.parent&&T.isVariableDeclaration(n.parent)){if(T.isIdentifier(n.parent.name))return n.parent.name.getText(u)}if(T.isObjectLiteralExpression(n)&&n.parent&&T.isVariableDeclaration(n.parent)){if(T.isIdentifier(n.parent.name))return n.parent.name.getText(u)}return""}function Im(n){if(!T.isClassDeclaration(n)&&!T.isClassExpression(n))return!1;let u=n.heritageClauses;if(!u)return!1;return u.some((g)=>g.token===T.SyntaxKind.ImplementsKeyword)}class wu{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let g=this.#n.getProgram(),m=g.getSourceFile(n);if(!m)return[];let i=c(m,u);if(!i||!T.isIdentifier(i))return[];let S=this.#n.getLanguageService().getImplementationAtPosition(n,u);if(!S||S.length===0)return[];let w=[];for(let O of S){if(O.kind===T.ScriptElementKind.interfaceElement||O.kind===T.ScriptElementKind.typeElement)continue;let _=g.getSourceFile(O.fileName);if(!_)continue;let A=Lm(_,O.textSpan.start);if(!A)continue;let f=Fu(A),z=Xm(A,_),V=Im(A);w.push({filePath:O.fileName,symbolName:z,position:O.textSpan.start,kind:f,isExplicit:V})}return w}}function au(n){return b.canHaveModifiers(n)&&b.getModifiers(n)?.some((u)=>u.kind===b.SyntaxKind.ExportKeyword)===!0}function Cm(n){if(b.isFunctionDeclaration(n))return"function";if(b.isClassDeclaration(n))return"class";if(b.isInterfaceDeclaration(n))return"interface";if(b.isTypeAliasDeclaration(n))return"type";if(b.isEnumDeclaration(n))return"enum";if(b.isVariableDeclaration(n))return"const";if(b.isVariableStatement(n))return"const";return"unknown"}function bu(n){if(n>=97&&n<=122)return!0;if(n>=65&&n<=90)return!0;if(n>=48&&n<=57)return!0;if(n===95||n===36)return!0;return!1}class Cn{#n;#u;#g;#i;#m;#t=!1;constructor(n,u,g,m,i){this.#n=n,this.#u=u,this.#g=g,this.#i=m,this.#m=i}static create(n,u={}){let g=In.create(n,{readConfigFile:u.readConfigFile,resolveNonTrackedFile:u.resolveNonTrackedFile});if(km(g))return g;let m=g,i=u.typeCollector??new mu(m),t=u.symbolGraph??new iu(m),S=u.referenceResolver??new tu(m),w=u.implementationFinder??new wu(m);return new Cn(m,i,t,S,w)}get isDisposed(){return this.#t}collectTypeAt(n,u){return this.#w(),this.#u.collectAt(n,u)}collectFileTypes(n){return this.#w(),this.#u.collectFile(n)}findReferences(n,u){return this.#w(),this.#i.findAt(n,u)}findImplementations(n,u){return this.#w(),this.#m.findAt(n,u)}getSymbolNode(n,u){return this.#w(),this.#g.get(n,u)}getModuleInterface(n){this.#w();let u=this.#u.collectFile(n),g=[],i=this.#n.getProgram().getSourceFile(n);if(!i)return{filePath:n,exports:g};function t(S){if(b.isVariableStatement(S)&&au(S)){for(let w of S.declarationList.declarations)if(b.isIdentifier(w.name)){let O=w.name.getStart(i),_=u.get(O)??null;g.push({name:w.name.text,kind:"const",resolvedType:_})}return}if((b.isFunctionDeclaration(S)||b.isClassDeclaration(S)||b.isInterfaceDeclaration(S)||b.isTypeAliasDeclaration(S)||b.isEnumDeclaration(S))&&au(S)&&S.name){let w=S.name,O=w.getStart(i),_=u.get(O)??null;g.push({name:w.text,kind:Cm(S),resolvedType:_});return}b.forEachChild(S,t)}return t(i),{filePath:n,exports:g}}notifyFileChanged(n,u){if(this.#t)return;this.#n.notifyFileChanged(n,u),this.#g.invalidate(n)}notifyFileDeleted(n){if(this.#t)return;this.#n.removeFile(n),this.#g.invalidate(n)}lineColumnToPosition(n,u,g){this.#w();let m=this.#n.getProgram().getSourceFile(n);if(!m)return null;try{return b.getPositionOfLineAndCharacter(m,u-1,g)}catch{return null}}findNamePosition(n,u,g){this.#w();let m=this.#n.getProgram().getSourceFile(n);if(!m)return null;let i=m.getFullText(),t=u;while(t<i.length){let S=i.indexOf(g,t);if(S<0)return null;let w=S>0?i.charCodeAt(S-1):32,O=S+g.length<i.length?i.charCodeAt(S+g.length):32;if(!bu(w)&&!bu(O))return S;t=S+1}return null}dispose(){if(this.#t)return;this.#t=!0,this.#n.dispose(),this.#g.clear()}#w(){if(this.#t)throw Error("SemanticLayer is disposed")}}class Tn{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(n){this.options=n}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let u=[this.options.project,...this.options.additionalProjects??[]].flatMap((g)=>[...this.options.relationRepo.getByType(g,"imports"),...this.options.relationRepo.getByType(g,"type-references"),...this.options.relationRepo.getByType(g,"re-exports")]);for(let g of u){let{srcFilePath:m,dstFilePath:i}=g;if(!this.adjacencyList.has(m))this.adjacencyList.set(m,new Set);if(this.adjacencyList.get(m).add(i),!this.adjacencyList.has(i))this.adjacencyList.set(i,new Set);if(!this.reverseAdjacencyList.has(i))this.reverseAdjacencyList.set(i,new Set);this.reverseAdjacencyList.get(i).add(m)}}patchFiles(n,u,g){let m=new Set([...n,...u]);for(let i of m){let t=this.adjacencyList.get(i);if(t){for(let w of t)this.reverseAdjacencyList.get(w)?.delete(i);t.clear()}let S=this.reverseAdjacencyList.get(i);if(S){for(let w of S)this.adjacencyList.get(w)?.delete(i);S.clear()}}for(let i of u)this.adjacencyList.delete(i),this.reverseAdjacencyList.delete(i);for(let i of n){let t=g(i);for(let S of t){if(!this.adjacencyList.has(S.srcFilePath))this.adjacencyList.set(S.srcFilePath,new Set);if(this.adjacencyList.get(S.srcFilePath).add(S.dstFilePath),!this.adjacencyList.has(S.dstFilePath))this.adjacencyList.set(S.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(S.dstFilePath))this.reverseAdjacencyList.set(S.dstFilePath,new Set);this.reverseAdjacencyList.get(S.dstFilePath).add(S.srcFilePath)}}}getDependencies(n){return Array.from(this.adjacencyList.get(n)??[])}getDependents(n){return Array.from(this.reverseAdjacencyList.get(n)??[])}getTransitiveDependents(n){let u=new Set,g=[n];while(g.length>0){let m=g.shift();for(let i of this.reverseAdjacencyList.get(m)??[])if(!u.has(i))u.add(i),g.push(i)}return Array.from(u)}hasCycle(){let n=new Set,u=new Set;for(let g of this.adjacencyList.keys()){if(n.has(g))continue;let m=[{node:g,entered:!1}];while(m.length>0){let i=m.pop();if(i.entered){u.delete(i.node);continue}if(u.has(i.node))return!0;if(n.has(i.node))continue;n.add(i.node),u.add(i.node),m.push({node:i.node,entered:!0});for(let t of this.adjacencyList.get(i.node)??[]){if(u.has(t))return!0;if(!n.has(t))m.push({node:t,entered:!1})}}}return!1}getAffectedByChange(n){let u=new Set;for(let g of n)for(let m of this.getTransitiveDependents(g))u.add(m);return Array.from(u)}getAdjacencyList(){let n=new Map;for(let[u,g]of this.adjacencyList)n.set(u,Array.from(g));return n}getTransitiveDependencies(n){let u=new Set,g=[n];while(g.length>0){let m=g.shift();for(let i of this.adjacencyList.get(m)??[])if(!u.has(i))u.add(i),g.push(i)}return Array.from(u)}getCyclePaths(n){let u=n?.maxCycles??1/0;if(u<=0)return[];let g=new Map;for(let[m,i]of this.adjacencyList)g.set(m,Array.from(i));return Fm(g,u)}}var Tm=(n,u)=>n.localeCompare(u);function ym(n){let u=n.length>1&&n[0]===n[n.length-1]?n.slice(0,-1):[...n];if(u.length===0)return[];let g=u;for(let m=1;m<u.length;m++){let i=u.slice(m).concat(u.slice(0,m));if(i.join("::")<g.join("::"))g=i}return[...g]}function Ou(n,u,g){let m=ym(g);if(m.length===0)return!1;let i=m.join("->");if(n.has(i))return!1;return n.add(i),u.push(m),!0}function sm(n){let u=0,g=[],m=new Set,i=new Map,t=new Map,S=[],w=(O)=>{i.set(O,u),t.set(O,u),u+=1,g.push(O),m.add(O);for(let _ of n.get(O)??[])if(!i.has(_))w(_),t.set(O,Math.min(t.get(O)??0,t.get(_)??0));else if(m.has(_))t.set(O,Math.min(t.get(O)??0,i.get(_)??0));if(t.get(O)===i.get(O)){let _=[],A="";do A=g.pop()??"",m.delete(A),_.push(A);while(A!==O&&g.length>0);S.push(_)}};for(let O of n.keys())if(!i.has(O))w(O);return{components:S}}function Rm(n,u,g){let m=[],i=new Set,t=[...n].sort(Tm),S=(w,O,_)=>{O.delete(w);let A=_.get(w);if(!A)return;for(let f of A)if(O.has(f))S(f,O,_);A.clear()};for(let w=0;w<t.length&&m.length<g;w++){let O=t[w]??"",_=new Set(t.slice(w)),A=new Set,f=new Map,z=[],V=(B)=>(u.get(B)??[]).filter((Y)=>_.has(Y)),Q=(B)=>{if(m.length>=g)return!0;let Y=!1;z.push(B),A.add(B);for(let N of V(B)){if(m.length>=g)break;if(N===O)Ou(i,m,z.concat(O)),Y=!0;else if(!A.has(N)){if(Q(N))Y=!0}}if(Y)S(B,A,f);else for(let N of V(B)){let $=f.get(N)??new Set;$.add(B),f.set(N,$)}return z.pop(),Y};Q(O)}return m}function Fm(n,u){let{components:g}=sm(n),m=[],i=new Set;for(let t of g){if(m.length>=u)break;if(t.length===0)continue;if(t.length===1){let O=t[0]??"";if((n.get(O)??[]).includes(O))Ou(i,m,[O,O]);continue}let S=u-m.length,w=Rm(t,n,S);for(let O of w){if(m.length>=u)break;Ou(i,m,O)}}return m}var am=15000;function yn(n){n.graphCache=null,n.graphCacheKey=null,n.graphCacheBuiltAt=null}function An(n,u){let g=u??"__cross__";if(n.graphCache&&n.graphCacheBuiltAt!==null){if(Date.now()-n.graphCacheBuiltAt>am)n.graphCache=null,n.graphCacheKey=null,n.graphCacheBuiltAt=null}if(n.graphCache&&n.graphCacheKey===g)return n.graphCache;let m=new Tn({relationRepo:n.relationRepo,project:u??n.defaultProject,additionalProjects:u?void 0:n.boundaries?.map((i)=>i.project)});return m.build(),n.graphCache=m,n.graphCacheKey=g,n.graphCacheBuiltAt=Date.now(),m}function qu(n,u,g,m=1e4){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:g??n.defaultProject,query:{srcFilePath:u,type:"imports",project:g??n.defaultProject,limit:m}}).map((i)=>i.dstFilePath)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getDependencies failed",{cause:i})}}function pu(n,u,g,m=1e4){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:g??n.defaultProject,query:{dstFilePath:u,type:"imports",project:g??n.defaultProject,limit:m}}).map((i)=>i.srcFilePath)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getDependents failed",{cause:i})}}async function vu(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return An(n,g).getAffectedByChange(u)}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getAffected failed",{cause:m})}}async function Gu(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return An(n,u).hasCycle()}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: hasCycle failed",{cause:g})}}async function Eu(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return An(n,u).getAdjacencyList()}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: getImportGraph failed",{cause:g})}}async function ju(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return An(n,g).getTransitiveDependencies(u)}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getTransitiveDependencies failed",{cause:m})}}async function Pu(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return An(n,u).getCyclePaths(g)}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getCyclePaths failed",{cause:m})}}async function hu(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let m=An(n,g);return{filePath:u,fanIn:m.getDependents(u).length,fanOut:m.getDependencies(u).length}}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getFanMetrics failed",{cause:m})}}var pm=30000,du=15000,vm=10;function Gm(n,u){return(g)=>{for(let m of n.onFileChangedCallbacks)try{m(g)}catch(i){n.logger.error("[Gildash] onFileChanged callback threw:",i)}if(u.handleWatcherEvent?.(g),n.semanticLayer)if(g.eventType==="delete")try{n.semanticLayer.notifyFileDeleted(g.filePath)}catch(m){n.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",m);for(let i of n.onErrorCallbacks)try{i(m instanceof J?m:new J("semantic","semantic notifyFileDeleted failed",{cause:m}))}catch{}}else n.readFileFn(g.filePath).then((m)=>{try{n.semanticLayer?.notifyFileChanged(g.filePath,m)}catch(i){n.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",i);for(let t of n.onErrorCallbacks)try{t(i instanceof J?i:new J("semantic","semantic notifyFileChanged failed",{cause:i}))}catch{}}}).catch((m)=>{n.logger.error("[Gildash] failed to read file for semantic layer",g.filePath,m);try{n.semanticLayer?.notifyFileDeleted(g.filePath)}catch(i){n.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",i)}})}}async function Em(n){if(!n.semanticLayer)return;let u=n.fileRepo.getAllFiles(n.defaultProject);await Promise.all(u.map(async(g)=>{try{let m=Vn.resolve(n.projectRoot,g.filePath),i=await n.readFileFn(m);n.semanticLayer?.notifyFileChanged(m,i)}catch{}}))}async function xu(n,u){let g=n.coordinatorFactory?n.coordinatorFactory():new ln({projectRoot:n.projectRoot,boundaries:n.boundaries,extensions:n.extensions,ignorePatterns:n.ignorePatterns,dbConnection:n.db,parseCache:n.parseCache,fileRepo:n.fileRepo,symbolRepo:n.symbolRepo,relationRepo:n.relationRepo,logger:n.logger});n.coordinator=g;for(let m of n.onIndexedCallbacks)g.onIndexed(m);if(g.onIndexed((m)=>{let i=m.changedFiles.length+m.deletedFiles.length;if(n.graphCache&&i>0&&i<100){let t=n.relationRepo;n.graphCache.patchFiles(m.changedFiles,m.deletedFiles,(S)=>{return[n.defaultProject,...n.boundaries.map((O)=>O.project)].flatMap((O)=>t.getByType(O,"imports").concat(t.getByType(O,"type-references")).concat(t.getByType(O,"re-exports"))).filter((O)=>O.srcFilePath===S||O.dstFilePath===S).map((O)=>({srcFilePath:O.srcFilePath,dstFilePath:O.dstFilePath}))}),n.graphCacheBuiltAt=Date.now()}else yn(n)}),u.isWatchMode){let m=n.watcherFactory?n.watcherFactory():new En({projectRoot:n.projectRoot,ignorePatterns:n.ignorePatterns,extensions:n.extensions},void 0,n.logger);await m.start(Gm(n,g)).then((i)=>{if(Kn(i))throw i.data}),n.watcher=m,n.timer=setInterval(()=>{n.updateHeartbeatFn(n.db,process.pid)},pm)}await g.fullIndex(),await Em(n)}function jm(n,u){let g=["SIGTERM","SIGINT","beforeExit"];for(let m of g){let i=()=>{u().catch((t)=>n.logger.error("[Gildash] close error during signal",m,t))};if(m==="beforeExit")process.on("beforeExit",i);else process.on(m,i);n.signalHandlers.push([m,i])}}async function ou(n){let{projectRoot:u,extensions:g=[".ts",".mts",".cts"],ignorePatterns:m=["**/node_modules/**"],parseCacheCapacity:i=500,logger:t=console,existsSyncFn:S=qm,dbConnectionFactory:w,watcherFactory:O,coordinatorFactory:_,repositoryFactory:A,acquireWatcherRoleFn:f=Cu,releaseWatcherRoleFn:z=Tu,updateHeartbeatFn:V=yu,discoverProjectsFn:Q=Bn,parseSourceFn:B=$n,extractSymbolsFn:Y=Ln,extractRelationsFn:N=Xn,symbolSearchFn:$=en,relationSearchFn:r=nu,patternSearchFn:M=uu,loadTsconfigPathsFn:D=Mn,readFileFn:H=async(X)=>Bun.file(X).text(),unlinkFn:Z=async(X)=>{await Bun.file(X).unlink()},watchMode:L,semantic:C,semanticLayerFactory:U}=n;if(!Vn.isAbsolute(u))throw new J("validation",`Gildash: projectRoot must be an absolute path, got: "${u}"`);if(!S(u))throw new J("validation",`Gildash: projectRoot does not exist: "${u}"`);let W=w?w():new bn({projectRoot:u}),R=W.open();if(Kn(R))throw R.data;try{let X=await Q(u),v=X[0]?.project??Vn.basename(u),E=A?A():(()=>{let h=W;return{fileRepo:new qn(h),symbolRepo:new pn(h),relationRepo:new vn(h),parseCache:new cn(i)}})(),P=L??!0,Rn=crypto.randomUUID(),e;if(P)e=await Promise.resolve(f(W,process.pid,{instanceId:Rn}));else e="owner";let I={projectRoot:u,extensions:g,ignorePatterns:m,logger:t,defaultProject:v,role:e,db:W,symbolRepo:E.symbolRepo,relationRepo:E.relationRepo,fileRepo:E.fileRepo,parseCache:E.parseCache,releaseWatcherRoleFn:z,parseSourceFn:B,extractSymbolsFn:Y,extractRelationsFn:N,symbolSearchFn:$,relationSearchFn:r,patternSearchFn:M,readFileFn:H,unlinkFn:Z,existsSyncFn:S,acquireWatcherRoleFn:f,updateHeartbeatFn:V,watcherFactory:O,coordinatorFactory:_,instanceId:Rn,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:X,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(Yn(u),I.tsconfigPaths=await D(u),C){let h=Vn.join(u,"tsconfig.json");try{if(U)I.semanticLayer=U(h);else{let d=Cn.create(h);if(Kn(d))throw d.data;I.semanticLayer=d}}catch(d){if(d instanceof J)throw d;throw new J("semantic","Gildash: semantic layer creation failed",{cause:d})}}if(e==="owner")await xu(I,{isWatchMode:P});else{let h=0,d=async()=>{try{let rn=await Promise.resolve(I.acquireWatcherRoleFn(I.db,process.pid,{instanceId:I.instanceId}));if(h=0,rn==="owner"){for(let fn of I.onRoleChangedCallbacks)try{fn("owner")}catch(x){I.logger.error("[Gildash] onRoleChanged callback threw:",x)}clearInterval(I.timer),I.timer=null;try{await xu(I,{isWatchMode:!0})}catch(fn){if(I.logger.error("[Gildash] owner promotion failed, reverting to reader",fn),I.watcher){let x=await I.watcher.close();if(Kn(x))I.logger.error("[Gildash] watcher close error during promotion rollback",x.data);I.watcher=null}if(I.coordinator)await I.coordinator.shutdown().catch((x)=>I.logger.error("[Gildash] coordinator shutdown error during promotion rollback",x)),I.coordinator=null;if(I.timer===null)I.timer=setInterval(d,du)}}}catch(rn){h++;let fn=rn instanceof J?rn:new J("watcher","Gildash: healthcheck error",{cause:rn});for(let x of I.onErrorCallbacks)try{x(fn)}catch(Xg){I.logger.error("[Gildash] onError callback threw:",Xg)}if(I.logger.error("[Gildash] healthcheck error",rn),h>=vm)I.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(I.timer),I.timer=null,sn(I).catch((x)=>I.logger.error("[Gildash] close error during healthcheck shutdown",x))}};I.timer=setInterval(d,du)}if(P)jm(I,()=>sn(I));return I}catch(X){if(W.close(),X instanceof J)throw X;throw new J("store","Gildash: initialization failed",{cause:X})}}async function sn(n,u){if(n.closed)return;n.closed=!0;let g=[];for(let[m,i]of n.signalHandlers)if(m==="beforeExit")process.off("beforeExit",i);else process.off(m,i);if(n.signalHandlers=[],n.semanticLayer){try{n.semanticLayer.dispose()}catch(m){g.push(m instanceof Error?m:Error(String(m)))}n.semanticLayer=null}if(n.coordinator)try{await n.coordinator.shutdown()}catch(m){g.push(m instanceof Error?m:Error(String(m)))}if(n.watcher){let m=await n.watcher.close();if(Kn(m))g.push(m.data)}if(n.timer!==null)clearInterval(n.timer),n.timer=null;try{n.releaseWatcherRoleFn(n.db,process.pid)}catch(m){g.push(m instanceof Error?m:Error(String(m)))}try{n.db.close()}catch(m){g.push(m instanceof Error?m:Error(String(m)))}if(u?.cleanup)for(let m of["","-wal","-shm"])try{await n.unlinkFn(Vn.join(n.projectRoot,nn,Wn+m))}catch{}if(g.length>0)throw new J("close","Gildash: one or more errors occurred during close()",{cause:g})}import{isErr as lu}from"@zipbul/result";function cu(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");let i=n.parseSourceFn(u,g,m);if(lu(i))throw i.data;return n.parseCache.set(u,i),i}async function eu(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");let m=new Map,i=[];return await Promise.all(u.map(async(t)=>{try{let S=await n.readFileFn(t),w=n.parseSourceFn(t,S,g);if(!lu(w))m.set(t,w);else i.push({filePath:t,error:w.data})}catch(S){i.push({filePath:t,error:S instanceof Error?S:Error(String(S))})}})),{parsed:m,failures:i}}function ng(n,u){if(n.closed)return;return n.parseCache.get(u)}function ug(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");return n.extractSymbolsFn(u)}function gg(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");return n.extractRelationsFn(u.program,u.filePath,n.tsconfigPaths??void 0)}import mg from"path";function ig(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.symbolRepo.getStats(u??n.defaultProject)}catch(g){if(g instanceof J)throw g;throw new J("store","Gildash: getStats failed",{cause:g})}}function Su(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:n.defaultProject,query:u})}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: searchSymbols failed",{cause:g})}}function tg(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:n.defaultProject,query:u})}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: searchRelations failed",{cause:g})}}function wg(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:void 0,query:u})}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: searchAllSymbols failed",{cause:g})}}function Og(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:void 0,query:u})}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: searchAllRelations failed",{cause:g})}}function Sg(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.fileRepo.getAllFiles(u??n.defaultProject)}catch(g){if(g instanceof J)throw g;throw new J("store","Gildash: listIndexedFiles failed",{cause:g})}}function rg(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:g??n.defaultProject,query:{srcFilePath:u,dstFilePath:u,limit:1e4}})}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getInternalRelations failed",{cause:m})}}function _g(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let i=m??n.defaultProject,t=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:i,query:{text:u,exact:!0,filePath:g,limit:1}});if(t.length===0)return null;let S=t[0],w=S.detail,O={...S,members:Array.isArray(w.members)?w.members:void 0,jsDoc:typeof w.jsDoc==="string"?w.jsDoc:void 0,parameters:typeof w.parameters==="string"?w.parameters:void 0,returnType:typeof w.returnType==="string"?w.returnType:void 0,heritage:Array.isArray(w.heritage)?w.heritage:void 0,decorators:Array.isArray(w.decorators)?w.decorators:void 0,typeParameters:typeof w.typeParameters==="string"?w.typeParameters:void 0};if(n.semanticLayer)try{let _=mg.isAbsolute(g)?g:mg.resolve(n.projectRoot,g),A=n.semanticLayer.lineColumnToPosition(_,S.span.start.line,S.span.start.column);if(A!==null){let f=n.semanticLayer.findNamePosition(_,A,S.name)??A,z=n.semanticLayer.collectTypeAt(_,f);if(z)O.resolvedType=z}}catch{}return O}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getFullSymbol failed",{cause:i})}}function Jg(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let m=g??n.defaultProject,i=n.fileRepo.getFile(m,u);if(!i)throw new J("search",`Gildash: file '${u}' is not in the index`);let t=n.symbolRepo.getFileSymbols(m,u),S=n.relationRepo.getOutgoing(m,u);return{filePath:i.filePath,lineCount:i.lineCount??0,size:i.size,symbolCount:t.length,exportedSymbolCount:t.filter((w)=>w.isExported).length,relationCount:S.length}}catch(m){if(m instanceof J)throw m;throw new J("store","Gildash: getFileStats failed",{cause:m})}}function Ag(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.fileRepo.getFile(g??n.defaultProject,u)}catch(m){if(m instanceof J)throw m;throw new J("store","Gildash: getFileInfo failed",{cause:m})}}function fg(n,u,g){return Su(n,{filePath:u,project:g??void 0,limit:1e4})}function Ng(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let i=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:g??n.defaultProject,query:{filePath:u,isExported:!0}}).map((t)=>({name:t.name,kind:t.kind,parameters:t.detail.parameters??void 0,returnType:t.detail.returnType??void 0,jsDoc:t.detail.jsDoc??void 0}));return{filePath:u,exports:i}}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getModuleInterface failed",{cause:m})}}import Mg from"path";function ru(n,u,g,m){let i=m??n.defaultProject,t=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:i,query:{text:u,exact:!0,filePath:g,limit:1}});if(t.length===0)return null;let S=t[0],w=Mg.isAbsolute(g)?g:Mg.resolve(n.projectRoot,g),O=n.semanticLayer.lineColumnToPosition(w,S.span.start.line,S.span.start.column);if(O===null)return null;let _=n.semanticLayer.findNamePosition(w,O,S.name)??O;return{sym:S,position:_,absPath:w}}function $g(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new J("semantic","Gildash: semantic layer is not enabled");try{let i=ru(n,u,g,m);if(!i)return null;return n.semanticLayer.collectTypeAt(i.absPath,i.position)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getResolvedType failed",{cause:i})}}function zg(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new J("semantic","Gildash: semantic layer is not enabled");try{let i=ru(n,u,g,m);if(!i)throw new J("search",`Gildash: symbol '${u}' not found in '${g}'`);return n.semanticLayer.findReferences(i.absPath,i.position)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getSemanticReferences failed",{cause:i})}}function Dg(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new J("semantic","Gildash: semantic layer is not enabled");try{let i=ru(n,u,g,m);if(!i)throw new J("search",`Gildash: symbol '${u}' not found in '${g}'`);return n.semanticLayer.findImplementations(i.absPath,i.position)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getImplementations failed",{cause:i})}}function Kg(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new J("semantic","Gildash: semantic layer is not enabled");try{return n.semanticLayer.getModuleInterface(u)}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: getSemanticModuleInterface failed",{cause:g})}}function Vg(n,u){let g=new Map(n.map((w)=>[`${w.name}::${w.filePath}`,w])),m=new Map(u.map((w)=>[`${w.name}::${w.filePath}`,w])),i=[],t=[],S=[];for(let[w,O]of m){let _=g.get(w);if(!_)i.push(O);else if(_.fingerprint!==O.fingerprint)S.push({before:_,after:O})}for(let[w,O]of g)if(!m.has(w))t.push(O);return{added:i,removed:t,modified:S}}function Wg(n,u){if(n.onIndexedCallbacks.add(u),!n.coordinator)return()=>{n.onIndexedCallbacks.delete(u)};let g=n.coordinator.onIndexed(u);return()=>{n.onIndexedCallbacks.delete(u),g()}}async function Hg(n){if(n.closed)throw new J("closed","Gildash: instance is closed");if(!n.coordinator)throw new J("closed","Gildash: reindex() is not available for readers");try{let u=await n.coordinator.fullIndex();return yn(n),u}catch(u){if(u instanceof J)throw u;throw new J("index","Gildash: reindex failed",{cause:u})}}function Qg(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");let i=m??n.defaultProject,t=new Set,S=[],w=u,O=g;for(;;){let _=`${O}::${w}`;if(t.has(_))return{originalName:w,originalFilePath:O,reExportChain:S,circular:!0};t.add(_);let A=n.relationSearchFn({relationRepo:n.relationRepo,project:i,query:{type:"re-exports",srcFilePath:O,limit:500}}),f,z;for(let V of A){let Q;if(V.metaJson)try{let Y=JSON.parse(V.metaJson);if(Array.isArray(Y.specifiers))Q=Y.specifiers}catch{}if(!Q)continue;let B=Q.find((Y)=>Y.exported===w);if(!B)continue;f=V.dstFilePath,z=B.local;break}if(!f||!z)return{originalName:w,originalFilePath:O,reExportChain:S,circular:!1};S.push({filePath:O,exportedAs:w}),O=f,w=z}}function Ug(n,u){return n.onFileChangedCallbacks.add(u),()=>{n.onFileChangedCallbacks.delete(u)}}function Bg(n,u){return n.onErrorCallbacks.add(u),()=>{n.onErrorCallbacks.delete(u)}}function Yg(n,u){return n.onRoleChangedCallbacks.add(u),()=>{n.onRoleChangedCallbacks.delete(u)}}async function Zg(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let m=g?.project??n.defaultProject,i=g?.filePaths?g.filePaths:n.fileRepo.getAllFiles(m).map((t)=>t.filePath);return await n.patternSearchFn({pattern:u,filePaths:i})}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: findPattern failed",{cause:m})}}async function Lg(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let i=m??n.defaultProject,t=new Set,S=(w,O,_)=>{let A=`${w}::${O}`;if(t.has(A))return{symbolName:w,filePath:O,kind:_,children:[]};t.add(A);let V=n.relationSearchFn({relationRepo:n.relationRepo,project:i,query:{srcFilePath:O,srcSymbolName:w,limit:1000}}).filter((Q)=>Q.type==="extends"||Q.type==="implements").filter((Q)=>Q.dstSymbolName!=null).map((Q)=>S(Q.dstSymbolName,Q.dstFilePath,Q.type));return{symbolName:w,filePath:O,kind:_,children:V}};return S(u,g)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getHeritageChain failed",{cause:i})}}class _u{_ctx;get projectRoot(){return this._ctx.projectRoot}get role(){return this._ctx.role}get projects(){return[...this._ctx.boundaries]}constructor(n){this._ctx=n}static async open(n){let u=await ou(n);return new _u(u)}async close(n){return sn(this._ctx,n)}parseSource(n,u,g){return cu(this._ctx,n,u,g)}async batchParse(n,u){return eu(this._ctx,n,u)}getParsedAst(n){return ng(this._ctx,n)}extractSymbols(n){return ug(this._ctx,n)}extractRelations(n){return gg(this._ctx,n)}getStats(n){return ig(this._ctx,n)}searchSymbols(n){return Su(this._ctx,n)}searchRelations(n){return tg(this._ctx,n)}searchAllSymbols(n){return wg(this._ctx,n)}searchAllRelations(n){return Og(this._ctx,n)}listIndexedFiles(n){return Sg(this._ctx,n)}getInternalRelations(n,u){return rg(this._ctx,n,u)}getFullSymbol(n,u,g){return _g(this._ctx,n,u,g)}getFileStats(n,u){return Jg(this._ctx,n,u)}getFileInfo(n,u){return Ag(this._ctx,n,u)}getSymbolsByFile(n,u){return fg(this._ctx,n,u)}getModuleInterface(n,u){return Ng(this._ctx,n,u)}getDependencies(n,u,g=1e4){return qu(this._ctx,n,u,g)}getDependents(n,u,g=1e4){return pu(this._ctx,n,u,g)}async getAffected(n,u){return vu(this._ctx,n,u)}async hasCycle(n){return Gu(this._ctx,n)}async getImportGraph(n){return Eu(this._ctx,n)}async getTransitiveDependencies(n,u){return ju(this._ctx,n,u)}async getCyclePaths(n,u){return Pu(this._ctx,n,u)}async getFanMetrics(n,u){return hu(this._ctx,n,u)}getResolvedType(n,u,g){return $g(this._ctx,n,u,g)}getSemanticReferences(n,u,g){return zg(this._ctx,n,u,g)}getImplementations(n,u,g){return Dg(this._ctx,n,u,g)}getSemanticModuleInterface(n){return Kg(this._ctx,n)}diffSymbols(n,u){return Vg(n,u)}onIndexed(n){return Wg(this._ctx,n)}async reindex(){return Hg(this._ctx)}resolveSymbol(n,u,g){return Qg(this._ctx,n,u,g)}async findPattern(n,u){return Zg(this._ctx,n,u)}async getHeritageChain(n,u,g){return Lg(this._ctx,n,u,g)}onFileChanged(n){return Ug(this._ctx,n)}onError(n){return Bg(this._ctx,n)}onRoleChanged(n){return Yg(this._ctx,n)}}export{en as symbolSearch,nu as relationSearch,uu as patternSearch,p as gildashError,J as GildashError,_u as Gildash,Tn as DependencyGraph};
8
8
 
9
- //# debugId=019D7FA17E588F3E64756E2164756E21
9
+ //# debugId=540D489DF398012964756E2164756E21
10
10
  //# sourceMappingURL=index.js.map