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