@zipbul/gildash 0.13.0 → 0.14.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 L$=Object.defineProperty;var I$=(u)=>u;function D$(u,_){this[u]=I$.bind(null,_)}var A$=(u,_)=>{for(var g in _)L$(u,g,{get:_[g],enumerable:!0,configurable:!0,set:D$.bind(_,g)})};var n_=import.meta.require;import{isErr as vu}from"@zipbul/result";import Eu from"path";import{existsSync as b0}from"fs";import{err as G_,isErr as q$}from"@zipbul/result";import{Database as j$}from"bun:sqlite";import{mkdirSync as F$,unlinkSync as v_,existsSync as E_}from"fs";import{dirname as n$,join as b_}from"path";import{drizzle as G$}from"drizzle-orm/bun-sqlite";import{migrate as v$}from"drizzle-orm/bun-sqlite/migrator";class w extends Error{type;constructor(u,_,g){super(_,g);this.type=u;this.name="GildashError"}}function $u(u,_,g){return new w(u,_,g!==void 0?{cause:g}:void 0)}var Yu=".gildash",yu="gildash.db";var u_={};A$(u_,{watcherOwner:()=>T$,symbols:()=>b,symbolChangelog:()=>Ju,relations:()=>L,files:()=>o,annotations:()=>Nu});import{sql as C$}from"drizzle-orm";import{sqliteTable as Du,text as n,integer as _u,real as S$,index as Qu,primaryKey as R$,foreignKey as fu,check as k$}from"drizzle-orm/sqlite-core";var o=Du("files",{project:n("project").notNull(),filePath:n("file_path").notNull(),mtimeMs:S$("mtime_ms").notNull(),size:_u("size").notNull(),contentHash:n("content_hash").notNull(),updatedAt:n("updated_at").notNull(),lineCount:_u("line_count")},(u)=>[R$({columns:[u.project,u.filePath]})]),b=Du("symbols",{id:_u("id").primaryKey({autoIncrement:!0}),project:n("project").notNull(),filePath:n("file_path").notNull(),kind:n("kind").notNull(),name:n("name").notNull(),startLine:_u("start_line").notNull(),startColumn:_u("start_column").notNull(),endLine:_u("end_line").notNull(),endColumn:_u("end_column").notNull(),isExported:_u("is_exported").notNull().default(0),signature:n("signature"),fingerprint:n("fingerprint"),detailJson:n("detail_json"),contentHash:n("content_hash").notNull(),indexedAt:n("indexed_at").notNull(),resolvedType:n("resolved_type"),structuralFingerprint:n("structural_fingerprint")},(u)=>[Qu("idx_symbols_project_file").on(u.project,u.filePath),Qu("idx_symbols_project_kind").on(u.project,u.kind),Qu("idx_symbols_project_name").on(u.project,u.name),Qu("idx_symbols_fingerprint").on(u.project,u.fingerprint),fu({columns:[u.project,u.filePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),L=Du("relations",{id:_u("id").primaryKey({autoIncrement:!0}),project:n("project").notNull(),type:n("type").notNull(),srcFilePath:n("src_file_path").notNull(),srcSymbolName:n("src_symbol_name"),dstProject:n("dst_project").notNull(),dstFilePath:n("dst_file_path").notNull(),dstSymbolName:n("dst_symbol_name"),metaJson:n("meta_json")},(u)=>[Qu("idx_relations_src").on(u.project,u.srcFilePath),Qu("idx_relations_dst").on(u.dstProject,u.dstFilePath),Qu("idx_relations_type").on(u.project,u.type),Qu("idx_relations_project_type_src").on(u.project,u.type,u.srcFilePath),fu({columns:[u.project,u.srcFilePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade"),fu({columns:[u.dstProject,u.dstFilePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),Nu=Du("annotations",{id:_u("id").primaryKey({autoIncrement:!0}),project:n("project").notNull(),filePath:n("file_path").notNull(),tag:n("tag").notNull(),value:n("value").notNull().default(""),source:n("source").notNull(),symbolName:n("symbol_name"),startLine:_u("start_line").notNull(),startColumn:_u("start_column").notNull(),endLine:_u("end_line").notNull(),endColumn:_u("end_column").notNull(),indexedAt:n("indexed_at").notNull()},(u)=>[Qu("idx_annotations_project_file").on(u.project,u.filePath),Qu("idx_annotations_project_tag").on(u.project,u.tag),Qu("idx_annotations_project_symbol").on(u.project,u.symbolName),fu({columns:[u.project,u.filePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),Ju=Du("symbol_changelog",{id:_u("id").primaryKey({autoIncrement:!0}),project:n("project").notNull(),changeType:n("change_type").notNull(),symbolName:n("symbol_name").notNull(),symbolKind:n("symbol_kind").notNull(),filePath:n("file_path").notNull(),oldName:n("old_name"),oldFilePath:n("old_file_path"),fingerprint:n("fingerprint"),changedAt:n("changed_at").notNull(),isFullIndex:_u("is_full_index").notNull().default(0),indexRunId:n("index_run_id").notNull()},(u)=>[Qu("idx_changelog_project_changed_at").on(u.project,u.changedAt),Qu("idx_changelog_project_name").on(u.project,u.symbolName),Qu("idx_changelog_project_run").on(u.project,u.indexRunId)]),T$=Du("watcher_owner",{id:_u("id").primaryKey(),pid:_u("pid").notNull(),startedAt:n("started_at").notNull(),heartbeatAt:n("heartbeat_at").notNull(),instanceId:n("instance_id")},(u)=>[k$("watcher_owner_singleton",C$`${u.id} = 1`)]);class __{client=null;drizzle=null;dbPath;txDepth=0;constructor(u){this.dbPath=b_(u.projectRoot,Yu,yu)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{F$(n$(this.dbPath),{recursive:!0}),this.client=new j$(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=G$(this.client,{schema:u_}),v$(this.drizzle,{migrationsFolder:b_(import.meta.dirname,"migrations")});let u=this.client.prepare("PRAGMA foreign_key_check").all();if(u.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(u.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON"),this.registerRegexpUdf(this.client)}catch(u){if(this.isCorruptionError(u)&&E_(this.dbPath)){this.closeClient(),v_(this.dbPath);for(let g of["-wal","-shm"]){let $=this.dbPath+g;if(E_($))v_($)}let _=this.open();if(q$(_))return G_($u("store",`Failed to recover database at ${this.dbPath}`,_.data));return _}return G_($u("store",`Failed to open database at ${this.dbPath}`,u))}}close(){this.closeClient(),this.drizzle=null}transaction(u){let _=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return _.transaction(()=>u(this))()}finally{this.txDepth--}}let g=`sp_${this.txDepth++}`;_.run(`SAVEPOINT "${g}"`);try{let $=u(this);return _.run(`RELEASE SAVEPOINT "${g}"`),$}catch($){throw _.run(`ROLLBACK TO SAVEPOINT "${g}"`),_.run(`RELEASE SAVEPOINT "${g}"`),$}finally{this.txDepth--}}immediateTransaction(u){let _=this.requireClient();this.txDepth++,_.run("BEGIN IMMEDIATE");try{let g=u();return _.run("COMMIT"),g}catch(g){throw _.run("ROLLBACK"),g}finally{this.txDepth--}}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((_)=>_.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(u,_){let g=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(u,g,g,_??null)}replaceOwner(u,_){let g=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(u,g,g,_??null)}touchOwner(u){let _=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(_,u)}deleteOwner(u){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(u)}registerRegexpUdf(u){let _=u;if(typeof _.function!=="function")return;_.function.call(u,"regexp",(g,$)=>{try{return new RegExp(g).test($)?1:0}catch{return 0}})}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(u){if(!(u instanceof Error))return!1;let _=u.message.toLowerCase();return _.includes("malformed")||_.includes("corrupt")||_.includes("not a database")||_.includes("disk i/o error")||_.includes("sqlite_corrupt")}}import{eq as Tu,and as y_}from"drizzle-orm";class g_{db;constructor(u){this.db=u}getFile(u,_){return this.db.drizzleDb.select().from(o).where(y_(Tu(o.project,u),Tu(o.filePath,_))).get()??null}upsertFile(u){this.db.drizzleDb.insert(o).values({project:u.project,filePath:u.filePath,mtimeMs:u.mtimeMs,size:u.size,contentHash:u.contentHash,updatedAt:u.updatedAt,lineCount:u.lineCount??null}).onConflictDoUpdate({target:[o.project,o.filePath],set:{mtimeMs:u.mtimeMs,size:u.size,contentHash:u.contentHash,updatedAt:u.updatedAt,lineCount:u.lineCount??null}}).run()}getAllFiles(u){return this.db.drizzleDb.select().from(o).where(Tu(o.project,u)).all()}getFilesMap(u){let _=this.getAllFiles(u),g=new Map;for(let $ of _)g.set($.filePath,$);return g}deleteFile(u,_){this.db.drizzleDb.delete(o).where(y_(Tu(o.project,u),Tu(o.filePath,_))).run()}}import{eq as e,and as Ku,sql as Pu,count as E$}from"drizzle-orm";function Au(u){return u.replaceAll("\x00","").trim().split(/\s+/).map((_)=>_.trim()).filter((_)=>_.length>0).map((_)=>`"${_.replaceAll('"','""')}"*`).join(" ")}var f_=50;class $_{db;constructor(u){this.db=u}replaceFileSymbols(u,_,g,$){if(this.db.drizzleDb.delete(b).where(Ku(e(b.project,u),e(b.filePath,_))).run(),!$.length)return;let J=new Date().toISOString(),O=$.map((N)=>({project:u,filePath:_,kind:N.kind??"unknown",name:N.name??"",startLine:N.startLine??0,startColumn:N.startColumn??0,endLine:N.endLine??0,endColumn:N.endColumn??0,isExported:N.isExported??0,signature:N.signature??null,fingerprint:N.fingerprint??null,detailJson:N.detailJson??null,contentHash:g,indexedAt:N.indexedAt??J,resolvedType:N.resolvedType??null,structuralFingerprint:N.structuralFingerprint??null}));for(let N=0;N<O.length;N+=f_)this.db.drizzleDb.insert(b).values(O.slice(N,N+f_)).run()}getFileSymbols(u,_){return this.db.drizzleDb.select().from(b).where(Ku(e(b.project,u),e(b.filePath,_))).all()}searchByName(u,_,g={}){let $=g.limit??50,J=Au(_);if(!J)return[];return this.db.drizzleDb.select().from(b).where(Ku(Pu`${b.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${J})`,e(b.project,u),g.kind?e(b.kind,g.kind):void 0)).orderBy(b.name).limit($).all()}searchByKind(u,_){return this.db.drizzleDb.select().from(b).where(Ku(e(b.project,u),e(b.kind,_))).orderBy(b.name).all()}getStats(u){let _=this.db.drizzleDb.select({symbolCount:E$(),fileCount:Pu`COUNT(DISTINCT ${b.filePath})`}).from(b).where(e(b.project,u)).get();return{symbolCount:_?.symbolCount??0,fileCount:_?.fileCount??0}}getByFingerprint(u,_){return this.db.drizzleDb.select().from(b).where(Ku(e(b.project,u),e(b.fingerprint,_))).all()}deleteFileSymbols(u,_){this.db.drizzleDb.delete(b).where(Ku(e(b.project,u),e(b.filePath,_))).run()}searchByQuery(u){let _=this.db.drizzleDb.select().from(b).where(Ku(u.ftsQuery?Pu`${b.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${u.ftsQuery})`:void 0,u.exactName?e(b.name,u.exactName):void 0,u.project!==void 0?e(b.project,u.project):void 0,u.kind?e(b.kind,u.kind):void 0,u.filePath!==void 0?e(b.filePath,u.filePath):void 0,u.isExported!==void 0?e(b.isExported,u.isExported?1:0):void 0,u.decorator?Pu`${b.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${u.decorator})`:void 0,u.resolvedType!==void 0?e(b.resolvedType,u.resolvedType):void 0)).orderBy(b.name);if(!u.regex)return _.limit(u.limit).all();let g;try{g=new RegExp(u.regex)}catch{throw new w("validation",`Invalid regex pattern: ${u.regex}`)}let $=[];for(let J of[5,20,100]){let O=u.limit*J,N=_.limit(O).all();if($=N.filter((z)=>g.test(z.name)),$.length>=u.limit||N.length<O)return $.slice(0,u.limit)}return $.slice(0,u.limit)}}import{eq as c,and as Wu,isNull as P_,or as b$}from"drizzle-orm";class J_{db;constructor(u){this.db=u}replaceFileRelations(u,_,g){this.db.transaction(($)=>{if($.drizzleDb.delete(L).where(Wu(c(L.project,u),c(L.srcFilePath,_))).run(),!g.length)return;for(let J of g)$.drizzleDb.insert(L).values({project:u,type:J.type??"unknown",srcFilePath:J.srcFilePath??_,srcSymbolName:J.srcSymbolName??null,dstProject:J.dstProject??u,dstFilePath:J.dstFilePath??"",dstSymbolName:J.dstSymbolName??null,metaJson:J.metaJson??null}).run()})}getOutgoing(u,_,g){if(g!==void 0)return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(Wu(c(L.project,u),c(L.srcFilePath,_),b$(c(L.srcSymbolName,g),P_(L.srcSymbolName)))).all();return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(Wu(c(L.project,u),c(L.srcFilePath,_))).all()}getIncoming(u){let{dstProject:_,dstFilePath:g}=u;return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(Wu(c(L.dstProject,_),c(L.dstFilePath,g))).all()}getByType(u,_){return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(Wu(c(L.project,u),c(L.type,_))).all()}deleteFileRelations(u,_){this.db.drizzleDb.delete(L).where(Wu(c(L.project,u),c(L.srcFilePath,_))).run()}searchRelations(u){return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(Wu(u.project!==void 0?c(L.project,u.project):void 0,u.srcFilePath!==void 0?c(L.srcFilePath,u.srcFilePath):void 0,u.srcSymbolName!==void 0?c(L.srcSymbolName,u.srcSymbolName):void 0,u.dstProject!==void 0?c(L.dstProject,u.dstProject):void 0,u.dstFilePath!==void 0?c(L.dstFilePath,u.dstFilePath):void 0,u.dstSymbolName!==void 0?c(L.dstSymbolName,u.dstSymbolName):void 0,u.type!==void 0?c(L.type,u.type):void 0)).limit(u.limit).all()}retargetRelations(u){let{dstProject:_,oldFile:g,oldSymbol:$,newFile:J,newSymbol:O,newDstProject:N}=u,z=$===null?Wu(c(L.dstProject,_),c(L.dstFilePath,g),P_(L.dstSymbolName)):Wu(c(L.dstProject,_),c(L.dstFilePath,g),c(L.dstSymbolName,$)),Q={dstFilePath:J,dstSymbolName:O};if(N!==void 0)Q.dstProject=N;this.db.drizzleDb.update(L).set(Q).where(z).run()}}import{err as m_}from"@zipbul/result";import{subscribe as y$}from"@parcel/watcher";import Q_ from"path";var f$=["**/.git/**",`**/${Yu}/**`,"**/dist/**","**/node_modules/**"],P$=new Set(["package.json","tsconfig.json"]);function m$(u){return u.replaceAll("\\","/")}function h$(u){if(u==="update")return"change";if(u==="create")return"create";return"delete"}class N_{#u;#_;#g;#J;#$;#N;constructor(u,_=y$,g=console){this.#_=u.projectRoot,this.#g=[...f$,...u.ignorePatterns??[]],this.#J=new Set((u.extensions??[".ts",".mts",".cts"]).map(($)=>$.toLowerCase())),this.#$=_,this.#N=g}async start(u){try{this.#u=await this.#$(this.#_,(_,g)=>{if(_){this.#N.error($u("watcher","Callback error",_));return}try{for(let $ of g){let J=m$(Q_.relative(this.#_,$.path));if(J.startsWith(".."))continue;let O=Q_.basename(J),N=Q_.extname(J).toLowerCase();if(!P$.has(O)&&!this.#J.has(N))continue;if(J.endsWith(".d.ts"))continue;u({eventType:h$($.type),filePath:J})}}catch($){this.#N.error($u("watcher","Callback error",$))}},{ignore:this.#g})}catch(_){return m_($u("watcher","Failed to subscribe watcher",_))}}async close(){if(!this.#u)return;try{await this.#u.unsubscribe(),this.#u=void 0}catch(u){return m_($u("watcher","Failed to close watcher",u))}}}import z_ from"path";import{promises as x$}from"fs";var i$=["**/node_modules/**","**/.git/**",`**/${Yu}/**`,"**/dist/**"];async function mu(u){let _=[];for await(let g of x$.glob("**/package.json",{cwd:u,exclude:i$})){let $=z_.dirname(g).replaceAll("\\","/"),J=z_.join(u,g),O=await Bun.file(J).json(),N=typeof O?.name==="string"&&O.name.length>0?O.name:z_.basename($==="."?u:$);_.push({dir:$,project:N})}return _.sort((g,$)=>$.dir.length-g.dir.length),_}function s(u,_,g="default"){let $=u.replaceAll("\\","/");for(let J of _){if(J.dir===".")return J.project;if($===J.dir||$.startsWith(`${J.dir}/`))return J.project}return g}import h_ from"path";var Zu=new Map;async function p$(u){let _=Bun.file(u);if(!await _.exists())return null;try{let g=await _.text(),$=Bun.JSONC.parse(g);return typeof $==="object"&&$!==null?$:null}catch{return null}}async function qu(u){if(Zu.has(u))return Zu.get(u)??null;let _=h_.join(u,"tsconfig.json"),g=await p$(_);if(!g)return Zu.set(u,null),null;let $=typeof g.compilerOptions==="object"&&g.compilerOptions!==null?g.compilerOptions:null;if(!$)return Zu.set(u,null),null;let J=typeof $.baseUrl==="string"?$.baseUrl:null,O=typeof $.paths==="object"&&$.paths!==null?$.paths:null;if(!J&&!O)return Zu.set(u,null),null;let N=J?h_.resolve(u,J):u,z=new Map;if(O)for(let[V,W]of Object.entries(O)){if(!Array.isArray(W))continue;let U=W.filter((X)=>typeof X==="string");z.set(V,U)}let Q={baseUrl:N,paths:z};return Zu.set(u,Q),Q}function hu(u){if(u){Zu.delete(u);return}Zu.clear()}import x_ from"path";function xu(u,_){return x_.relative(u,_).replaceAll("\\","/")}function Cu(u,_){return x_.resolve(u,_)}function Ou(u){let _=Bun.hash.xxHash64(u);return BigInt.asUintN(64,BigInt(_)).toString(16).padStart(16,"0")}import{isErr as e_}from"@zipbul/result";import{err as l$}from"@zipbul/result";import{parseSync as d$}from"oxc-parser";function ju(u,_,g,$=d$){try{let{program:J,errors:O,comments:N}=$(u,_,g);return{filePath:u,program:J,errors:O,comments:N,sourceText:_}}catch(J){return l$($u("parse",`Failed to parse file: ${u}`,J))}}import{promises as c$}from"fs";import{join as r$}from"path";async function i_(u){let{projectRoot:_,extensions:g,ignorePatterns:$,fileRepo:J}=u,O=J.getFilesMap(),N=new Set,z=[],Q=[],V=$.map((U)=>new Bun.Glob(U));for await(let U of c$.glob("**/*",{cwd:_})){if(!g.some((Z)=>U.endsWith(Z)))continue;if(U.startsWith("node_modules/")||U.includes("/node_modules/"))continue;if(V.some((Z)=>Z.match(U)))continue;N.add(U);let X=r$(_,U),M=Bun.file(X),{size:I,lastModified:D}=M,T=O.get(U);if(!T){let Z=await M.text(),K=Ou(Z);z.push({filePath:U,contentHash:K,mtimeMs:D,size:I});continue}if(T.mtimeMs===D&&T.size===I){Q.push({filePath:U,contentHash:T.contentHash,mtimeMs:D,size:I});continue}let j=await M.text(),h=Ou(j);if(h===T.contentHash)Q.push({filePath:U,contentHash:h,mtimeMs:D,size:I});else z.push({filePath:U,contentHash:h,mtimeMs:D,size:I})}let W=[];for(let U of O.keys())if(!N.has(U))W.push(U);return{changed:z,unchanged:Q,deleted:W}}function iu(u){let _=[0];for(let g=0;g<u.length;g++)if(u[g]===`
3
- `)_.push(g+1);return _}function wu(u,_){let g=0,$=u.length-1;while(g<$){let J=g+$+1>>1;if(u[J]<=_)g=J;else $=J-1}return{line:g+1,column:_-u[g]}}import{err as a$}from"@zipbul/result";import{parse as s$}from"comment-parser";function pu(u){try{let _=u.trim();if(_.startsWith("/**"))_=_.slice(3);if(_.endsWith("*/"))_=_.slice(0,-2);let $=s$(`/** ${_} */`)[0]??{description:"",tags:[]};return{description:($.description??"").trim(),tags:($.tags??[]).map((J)=>({tag:J.tag??"",name:J.name??"",type:J.type??"",description:J.description??"",optional:J.optional??!1,...J.default!==void 0?{default:J.default}:{}}))}}catch(_){return a$($u("parse","Failed to parse JSDoc comment",_))}}import{isErr as t$}from"@zipbul/result";function Su(u){let{program:_,sourceText:g,comments:$}=u,J=iu(g),O=$.filter((Z)=>Z.type==="Block"&&Z.value.startsWith("*")).sort((Z,K)=>Z.end-K.end),N=_.body.map((Z)=>Z.start??0).sort((Z,K)=>Z-K);function z(Z,K){return{start:wu(J,Z),end:wu(J,K)}}function Q(Z){let K=0,B=O.length-1,R=-1;while(K<=B){let S=K+B>>>1;if(O[S].end<=Z)R=S,K=S+1;else B=S-1}if(R<0)return;let q=O[R];K=0,B=N.length-1;while(K<=B){let S=K+B>>>1,G=N[S];if(G<=q.end)K=S+1;else if(G>=Z)B=S-1;else return}return`/*${q.value}*/`}function V(Z){if(!Z)return;let K=Z.typeAnnotation??Z;return g.slice(K.start,K.end)}function W(Z){if(!Z||Z.length===0)return[];return Z.map((K)=>{let B=K.expression;if(!B)return{name:"unknown"};if(B.type==="CallExpression"){let R=B.callee?.name??B.callee?.property?.name??"unknown",q=(B.arguments??[]).map((S)=>g.slice(S.start,S.end));return{name:R,arguments:q.length>0?q:void 0}}if(B.type==="Identifier")return{name:B.name??"unknown"};return{name:g.slice(B.start,B.end)}})}function U(Z){let K=Z.type==="TSParameterProperty"?Z.parameter:Z;if(K?.type==="RestElement"){let E=`...${K.argument?.name??"unknown"}`,p=K.typeAnnotation,gu=p?V(p):void 0,r={name:E,isOptional:!1};if(gu)r.type=gu;return r}if(K?.type==="AssignmentPattern"){let{left:y,right:E}=K,p=y?.name??"unknown",gu=y?.typeAnnotation,r=gu?V(gu):void 0,uu=g.slice(E.start,E.end),Y=W(y?.decorators??[]),A={name:p,isOptional:!0,defaultValue:uu};if(r)A.type=r;if(Y.length>0)A.decorators=Y;return A}let B=K?.name??K?.pattern?.name??"unknown",R=!!K?.optional,q=K?.typeAnnotation,S=q?V(q):void 0,G=W(K?.decorators??[]),f={name:B,isOptional:R};if(S)f.type=S;if(G.length>0)f.decorators=G;return f}function X(Z,K){let B=[];if(K?.async)B.push("async");if(Z.static)B.push("static");if(Z.abstract)B.push("abstract");if(Z.readonly)B.push("readonly");if(Z.override)B.push("override");if(Z.declare)B.push("declare");if(Z.const)B.push("const");let R=Z.accessibility;if(R==="private")B.push("private");else if(R==="protected")B.push("protected");else if(R==="public")B.push("public");return B}function M(Z){let K=[];if(Z.superClass){let R=g.slice(Z.superClass.start,Z.superClass.end);K.push({kind:"extends",name:R})}let B=Z.implements??[];for(let R of B){let q=R.expression??R,S=g.slice(q.start,q.end);K.push({kind:"implements",name:S})}return K}function I(Z){let K=[];for(let B of Z.extends??[]){let R=B.expression??B,q=g.slice(R.start,R.end);K.push({kind:"extends",name:q})}return K}function D(Z){let K=[];for(let B of Z)if(B.type==="MethodDefinition"){let R=B.key?.name??"unknown",q=B.value,S=B.kind??"method",G=S==="constructor"?"constructor":S==="get"?"getter":S==="set"?"setter":"method",f=X(B,q),y=(q?.params??[]).map(U),E=V(q?.returnType),p={kind:"method",name:R,span:z(B.start,B.end),isExported:!1,methodKind:G,modifiers:f,parameters:y.length>0?y:void 0,returnType:E};K.push(p)}else if(B.type==="PropertyDefinition"){let R=B.key?.name??"unknown",q=X(B),S={kind:"property",name:R,span:z(B.start,B.end),isExported:!1,modifiers:q};K.push(S)}return K}function T(Z){let K=[];for(let B of Z)if(B.type==="TSMethodSignature"){let R=B.key?.name??"unknown",q=(B.params??[]).map(U),S=V(B.returnType);K.push({kind:"method",name:R,span:z(B.start,B.end),isExported:!1,modifiers:[],methodKind:"method",parameters:q.length>0?q:void 0,returnType:S})}else if(B.type==="TSPropertySignature"){let R=B.key?.name??"unknown",q=V(B.typeAnnotation),S={kind:"property",name:R,span:z(B.start,B.end),isExported:!1,modifiers:B.readonly?["readonly"]:[],returnType:q};K.push(S)}return K}function j(Z,K){let B=Z.type??"";if(B==="FunctionDeclaration"||B==="TSDeclareFunction"){let R=Z.id?.name??"default",q=(Z.params??[]).map(U),S=V(Z.returnType),G=X(Z,Z),f=W(Z.decorators??[]),y=Z.typeParameters?.params?.flatMap((p)=>{let gu=p.name?.name;return gu?[gu]:[]})||void 0,E={kind:"function",name:R,span:z(Z.start,Z.end),isExported:K,modifiers:G,parameters:q.length>0?q:void 0,returnType:S,decorators:f.length>0?f:void 0};if(y&&y.length>0)E.typeParameters=y;return E}if(B==="ClassDeclaration"||B==="ClassExpression"){let R=Z.id?.name??"default",q=M(Z),S=D(Z.body?.body??[]),G=W(Z.decorators??[]),f=X(Z,Z),y=Z.typeParameters?.params?.flatMap((p)=>{let gu=p.name?.name;return gu?[gu]:[]})||void 0,E={kind:"class",name:R,span:z(Z.start,Z.end),isExported:K,modifiers:f,heritage:q.length>0?q:void 0,members:S.length>0?S:void 0,decorators:G.length>0?G:void 0};if(y&&y.length>0)E.typeParameters=y;return E}if(B==="VariableDeclaration"){let R=[];for(let q of Z.declarations??[]){let{id:S,init:G}=q;if(S?.type==="ObjectPattern"){for(let r of S.properties??[]){let uu=r.value?.name??r.key?.name??"unknown";R.push({kind:"variable",name:uu,span:z(r.start??q.start,r.end??q.end),isExported:K,modifiers:[]})}continue}if(S?.type==="ArrayPattern"){for(let r of S.elements??[]){if(!r||r.type!=="Identifier")continue;let uu=r.name??"unknown";R.push({kind:"variable",name:uu,span:z(r.start??q.start,r.end??q.end),isExported:K,modifiers:[]})}continue}let f=S?.name??"unknown",y="variable",E,p;if(G?.type==="FunctionExpression"||G?.type==="ArrowFunctionExpression")y="function",E=(G.params??[]).map(U),p=V(G.returnType);let gu=[];R.push({kind:y,name:f,span:z(q.start,q.end),isExported:K,modifiers:gu,parameters:E,returnType:p})}if(R.length===0)return null;if(R.length===1)return R[0];return R}if(B==="TSTypeAliasDeclaration")return{kind:"type",name:Z.id?.name??"unknown",span:z(Z.start,Z.end),isExported:K,modifiers:[]};if(B==="TSInterfaceDeclaration"){let R=Z.id?.name??"unknown",q=I(Z),S=T(Z.body?.body??[]),G=Z.typeParameters?.params?.flatMap((y)=>{let E=y.name?.name;return E?[E]:[]})||void 0,f={kind:"interface",name:R,span:z(Z.start,Z.end),isExported:K,modifiers:[],heritage:q.length>0?q:void 0,members:S.length>0?S:void 0};if(G&&G.length>0)f.typeParameters=G;return f}if(B==="TSEnumDeclaration"){let R=Z.id?.name??"unknown",q=X(Z),G=(Z.body?.members??[]).map((f)=>({kind:"property",name:f.id?.name??f.id?.value??"unknown",span:z(f.start,f.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:R,span:z(Z.start,Z.end),isExported:K,modifiers:q,members:G.length>0?G:void 0}}return null}let h=[];for(let Z of _.body){let K=null,B=Z,R=typeof B.type==="string"?B.type:"";if(R==="ExportNamedDeclaration"){let S=Z;if(S.declaration){if(K=j(S.declaration,!0),K&&!Array.isArray(K))K.span=z(S.start,S.end);else if(Array.isArray(K))for(let G of K)G.span=z(S.start,S.end)}}else if(R==="ExportDefaultDeclaration"){let S=Z,G=S.declaration;if(G){if(K=j(G,!0),K&&!Array.isArray(K))K.name=G.id?.name??"default",K.isExported=!0,K.span=z(S.start,S.end)}}else K=j(Z,!1);let q=Array.isArray(K)?K:K?[K]:[];for(let S of q){let G=Z.start??0,f=Q(G);if(f){let y=pu(f);if(!t$(y))S.jsDoc=y}h.push(S)}}return h}function o$(u){if(u.kind==="function"||u.kind==="method"){let _=u.parameters?.length??0,g=u.modifiers.includes("async")?1:0;return`params:${_}|async:${g}`}return null}function e$(u){let _={};if(u.jsDoc)_.jsDoc=u.jsDoc;if(u.kind==="function"||u.kind==="method"){if(u.parameters!==void 0)_.parameters=u.parameters;if(u.returnType!==void 0)_.returnType=u.returnType}if(u.heritage?.length)_.heritage=u.heritage;if(u.decorators?.length)_.decorators=u.decorators;if(u.typeParameters?.length)_.typeParameters=u.typeParameters;if(u.modifiers?.length)_.modifiers=u.modifiers;if(u.members?.length)_.members=u.members.map((g)=>{let $=g.modifiers.find((J)=>J==="private"||J==="protected"||J==="public");return{name:g.name,kind:g.methodKind??g.kind,type:g.returnType,visibility:$,isStatic:g.modifiers.includes("static")||void 0,isReadonly:g.modifiers.includes("readonly")||void 0}});return Object.keys(_).length>0?JSON.stringify(_):null}function u0(u){let _=[u.kind];if(u.modifiers.length)_.push(`mod:${[...u.modifiers].sort().join(",")}`);if(u.typeParameters?.length)_.push(`tp:${u.typeParameters.length}`);if(u.heritage?.length){let g=[...u.heritage].sort(($,J)=>$.name.localeCompare(J.name)).map(($)=>`${$.kind}:${$.name}`).join(",");_.push(`her:${g}`)}if(u.decorators?.length)_.push(`dec:${[...u.decorators].map((g)=>g.name).sort().join(",")}`);if(u.methodKind)_.push(`mk:${u.methodKind}`);if(u.parameters)_.push(`p:${u.parameters.length}`);if(u.returnType)_.push(`rt:${u.returnType}`);if(u.members?.length){let g=u.members.map(($)=>`${$.kind}:${$.modifiers.join(",")}:${$.parameters?.length??""}:${$.returnType??""}`).sort().join(";");_.push(`mem:${u.members.length}:${Ou(g)}`)}return Ou(_.join("|"))}function p_(u,_,g,$,J){let O=o$(u),N=Ou(`${_}|${u.kind}|${O??""}`),z=u0(u);return{project:g,filePath:$,kind:u.kind,name:_,startLine:u.span.start.line,startColumn:u.span.start.column,endLine:u.span.end.line,endColumn:u.span.end.column,isExported:u.isExported?1:0,signature:O,fingerprint:N,detailJson:e$(u),contentHash:J,indexedAt:new Date().toISOString(),structuralFingerprint:z}}function O_(u){let{parsed:_,project:g,filePath:$,contentHash:J,symbolRepo:O}=u,N=Su(_),z=[];for(let Q of N){z.push(p_(Q,Q.name,g,$,J));for(let V of Q.members??[])z.push(p_(V,`${Q.name}.${V.name}`,g,$,J))}O.replaceFileSymbols(g,$,J,z)}import{resolve as w_,dirname as _0,extname as g0}from"path";function Mu(u,_,g){let $=(J)=>{let O=g0(J);if(O==="")return[J+".ts",J+".d.ts",J+"/index.ts",J+"/index.d.ts",J+".mts",J+"/index.mts",J+".cts",J+"/index.cts"];if(O===".js")return[J.slice(0,-3)+".ts"];if(O===".mjs")return[J.slice(0,-4)+".mts"];if(O===".cjs")return[J.slice(0,-4)+".cts"];return[J]};if(_.startsWith(".")){let J=w_(_0(u),_);return $(J)}if(g)for(let[J,O]of g.paths){if(O.length===0)continue;let N=J.indexOf("*");if(N===-1){if(_===J){let z=[];for(let Q of O)z.push(...$(w_(g.baseUrl,Q)));return z}}else{let z=J.slice(0,N),Q=J.slice(N+1);if(_.startsWith(z)&&(Q===""||_.endsWith(Q))){let V=_.slice(z.length,Q===""?void 0:_.length-Q.length),W=[];for(let U of O)W.push(...$(w_(g.baseUrl,U.replace("*",V))));return W}}}return[]}function l_(u,_,g,$=Mu){let J=new Map,O=u.body??[];for(let N of O){if(N.type!=="ImportDeclaration")continue;let z=N.source?.value??"",Q=$(_,z,g);if(Q.length===0)continue;let V=Q[0],W=N.specifiers??[];for(let U of W)switch(U.type){case"ImportSpecifier":J.set(U.local.name,{path:V,importedName:U.imported.name});break;case"ImportDefaultSpecifier":J.set(U.local.name,{path:V,importedName:"default"});break;case"ImportNamespaceSpecifier":J.set(U.local.name,{path:V,importedName:"*"});break}}return J}var $0=new Set(["loc","start","end","scope"]);function Ru(u,_){if(!u||typeof u!=="object")return;if(Array.isArray(u)){for(let $ of u)Ru($,_);return}let g=u;_(g);for(let $ of Object.keys(g)){if($0.has($))continue;let J=g[$];if(J&&typeof J==="object")Ru(J,_)}}function d_(u){if(!u||typeof u!=="object"||Array.isArray(u))return null;let _=u;if((_.type==="StringLiteral"||_.type==="Literal")&&typeof _.value==="string")return _.value;return null}function Bu(u){if(!u||typeof u!=="object"||Array.isArray(u))return null;let _=u;if(_.type==="Identifier"){let g=_.name;return{root:g,parts:[],full:g}}if(_.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(_.type==="Super")return{root:"super",parts:[],full:"super"};if(_.type==="MemberExpression"){let g=[],$=_;while($.type==="MemberExpression"){let N=$.property;if(!N||typeof N.name!=="string")return null;g.push(N.name),$=$.object}let J;if($.type==="Identifier")J=$.name;else if($.type==="ThisExpression")J="this";else if($.type==="Super")J="super";else return null;g.reverse();let O=[J,...g].join(".");return{root:J,parts:g,full:O}}return null}function c_(u,_,g,$=Mu){let J=[],O=u.body??[];for(let N of O){if(N.type==="ImportDeclaration"){let z=N.source?.value??"",Q=$(_,z,g);if(Q.length===0)continue;let V=Q[0],W=N.importKind==="type",U=N.specifiers??[];if(U.length===0){let X={};if(W)X.isType=!0;J.push({type:W?"type-references":"imports",srcFilePath:_,srcSymbolName:null,dstFilePath:V,dstSymbolName:null,...Object.keys(X).length>0?{metaJson:JSON.stringify(X)}:{}})}else for(let X of U){let M=X.type,I=W||X.importKind==="type",D={};if(I)D.isType=!0;let T,j;if(M==="ImportDefaultSpecifier")T="default",j=X.local.name;else if(M==="ImportNamespaceSpecifier")T="*",j=X.local.name,D.importKind="namespace";else T=X.imported.name,j=X.local.name;J.push({type:I?"type-references":"imports",srcFilePath:_,srcSymbolName:j,dstFilePath:V,dstSymbolName:T,...Object.keys(D).length>0?{metaJson:JSON.stringify(D)}:{}})}continue}if(N.type==="ExportAllDeclaration"&&N.source){let z=N.source?.value??"",Q=$(_,z,g);if(Q.length===0)continue;let V=Q[0],W=N.exportKind==="type",U={isReExport:!0};if(W)U.isType=!0;J.push({type:W?"type-references":"re-exports",srcFilePath:_,srcSymbolName:null,dstFilePath:V,dstSymbolName:null,metaJson:JSON.stringify(U)});continue}if(N.type==="ExportNamedDeclaration"&&N.source){let z=N.source?.value??"",Q=$(_,z,g);if(Q.length===0)continue;let V=Q[0],W=N.exportKind==="type",M={isReExport:!0,specifiers:(N.specifiers??[]).map((I)=>({local:I.local.name,exported:I.exported.name}))};if(W)M.isType=!0;J.push({type:W?"type-references":"re-exports",srcFilePath:_,srcSymbolName:null,dstFilePath:V,dstSymbolName:null,metaJson:JSON.stringify(M)})}}return Ru(u,(N)=>{if(N.type!=="ImportExpression")return;let z=d_(N.source);if(!z)return;let Q=$(_,z,g);if(Q.length===0)return;let V=Q[0];J.push({type:"imports",srcFilePath:_,srcSymbolName:null,dstFilePath:V,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),J}function r_(u,_,g){let $=[],J=[],O=[];function N(){if(J.length>0)return J[J.length-1]??null;return null}function z(V){if(!V)return null;let W=g.get(V.root);if(V.parts.length===0){if(W)return{dstFilePath:W.path,dstSymbolName:W.importedName,resolution:"import"};return{dstFilePath:_,dstSymbolName:V.root,resolution:"local"}}else{if(W&&W.importedName==="*"){let U=V.parts[V.parts.length-1];return{dstFilePath:W.path,dstSymbolName:U,resolution:"namespace"}}return{dstFilePath:_,dstSymbolName:V.full,resolution:"local-member"}}}function Q(V){if(!V||typeof V!=="object")return;if(Array.isArray(V)){for(let X of V)Q(X);return}let W=V,U=typeof W.type==="string"?W.type:"";if(U==="ClassDeclaration"||U==="ClassExpression"){let X=W,M=X.id?.name??"AnonymousClass";O.push(M),Q(X.body),O.pop();return}if(U==="FunctionDeclaration"){let X=W,M=X.id?.name??"anonymous";J.push(M),Q(X.body),J.pop();return}if(U==="VariableDeclarator"&&W.init&&(W.init?.type==="FunctionExpression"||W.init?.type==="ArrowFunctionExpression")){let X=W,M=X.id?.name??"anonymous";J.push(M),Q(X.init?.body??X.init),J.pop();return}if(U==="MethodDefinition"&&W.value){let X=W,M=O[O.length-1]??"",I=X.key?.name??"anonymous",D=M?`${M}.${I}`:I;J.push(D),Q(X.value?.body),J.pop();return}if(U==="FunctionExpression"||U==="ArrowFunctionExpression"){let X=N(),M=X?`${X}.<anonymous>`:"<anonymous>";J.push(M),Q(W.body),J.pop();return}if(U==="CallExpression"){let X=W,M=Bu(X.callee),I=z(M);if(I){let D=N(),T={};if(D===null)T.scope="module";$.push({type:"calls",srcFilePath:_,srcSymbolName:D,dstFilePath:I.dstFilePath,dstSymbolName:I.dstSymbolName,...Object.keys(T).length>0?{metaJson:JSON.stringify(T)}:{}})}Q(X.callee);for(let D of X.arguments??[])Q(D);return}if(U==="NewExpression"){let X=W,M=Bu(X.callee),I=z(M);if(I){let D=N(),T={isNew:!0};if(D===null)T.scope="module";$.push({type:"calls",srcFilePath:_,srcSymbolName:D,dstFilePath:I.dstFilePath,dstSymbolName:I.dstSymbolName,metaJson:JSON.stringify(T)})}for(let D of X.arguments??[])Q(D);return}for(let X of Object.keys(W)){if(X==="loc"||X==="start"||X==="end"||X==="scope")continue;let M=W[X];if(M&&typeof M==="object")Q(M)}}return Q(u),$}function a_(u,_,g){let $=[];return Ru(u,(J)=>{if(J.type==="TSInterfaceDeclaration"){let z=J.id?.name??"AnonymousInterface",Q=J.extends??[];for(let V of Q){let W=V.expression??V,U=Bu(W);if(!U)continue;let X=W_(U,_,g);$.push({type:"extends",srcFilePath:_,srcSymbolName:z,...X})}return}if(J.type!=="ClassDeclaration"&&J.type!=="ClassExpression")return;let O=J.id?.name??"AnonymousClass";if(J.superClass){let z=Bu(J.superClass);if(z){let Q=W_(z,_,g);$.push({type:"extends",srcFilePath:_,srcSymbolName:O,...Q})}}let N=J.implements??[];for(let z of N){let Q=z.expression??z,V=Bu(Q);if(!V)continue;let W=W_(V,_,g);$.push({type:"implements",srcFilePath:_,srcSymbolName:O,...W})}}),$}function W_(u,_,g){let $=g.get(u.root);if($){if($.importedName==="*"){let J=u.parts[u.parts.length-1]??u.root;return{dstFilePath:$.path,dstSymbolName:J,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:$.path,dstSymbolName:u.parts.length>0?u.full:$.importedName}}return{dstFilePath:_,dstSymbolName:u.full,metaJson:JSON.stringify({isLocal:!0})}}function lu(u,_,g,$=Mu){let J=l_(u,_,g,$),O=c_(u,_,g,$),N=r_(u,_,J),z=a_(u,_,J);return[...O,...N,...z]}function V_(u){let{ast:_,project:g,filePath:$,relationRepo:J,projectRoot:O,tsconfigPaths:N,knownFiles:z,boundaries:Q}=u,V=Cu(O,$),U=lu(_,V,N,z?(M,I,D)=>{let T=Mu(M,I,D);for(let j of T){let h=xu(O,j);if(Q){let Z=s(h,Q);if(z.has(`${Z}::${h}`))return[j]}else if(z.has(`${g}::${h}`))return[j]}return[]}:void 0),X=[];for(let M of U){let I=xu(O,M.dstFilePath);if(I.startsWith(".."))continue;let D=xu(O,M.srcFilePath),T=Q?s(I,Q):g;X.push({project:g,type:M.type,srcFilePath:D,srcSymbolName:M.srcSymbolName??null,dstProject:T,dstFilePath:I,dstSymbolName:M.dstSymbolName??null,metaJson:M.metaJson??null})}return J.replaceFileRelations(g,$,X),X.length}import{isErr as J0}from"@zipbul/result";var s_=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function Q0(u){let _=Su(u),g=[];for(let $ of _){g.push({name:$.name,startLine:$.span.start.line});for(let J of $.members??[])g.push({name:`${$.name}.${J.name}`,startLine:J.span.start.line})}return g.sort(($,J)=>$.startLine-J.startLine),g}function U_(u,_,g){let $=0,J=u.length-1;while($<=J){let O=$+J>>1;if(u[O].startLine<=_)$=O+1;else J=O-1}if($<u.length){let O=u[$];if(O.startLine-_<=g)return O.name}return null}function du(u,_,g){let $=wu(u,_),J=wu(u,g);return{start:$,end:J}}function t_(u){let{comments:_,sourceText:g}=u;if(!_.length)return[];let $=iu(g),J=Q0(u),O=[],N=[..._].sort((Q,V)=>Q.start-V.start),z=null;for(let Q of N)if(Q.type==="Block"&&Q.value.startsWith("*")){z=null;let V=`/*${Q.value}*/`,W=pu(V);if(J0(W))continue;let U=W;if(!U.tags?.length)continue;let X=wu($,Q.end),M=U_(J,X.line,3),I=g.slice(Q.start,Q.end);for(let D of U.tags){let T=[D.name,D.description].filter(Boolean).join(" "),j=`@${D.tag}`,h=I.indexOf(j),Z;if(h>=0){let K=Q.start+h,B=g.indexOf(`
4
- `,K),R=B>=0?Math.min(B,Q.end):Q.end;Z=du($,K,R)}else Z=du($,Q.start,Q.end);O.push({tag:D.tag,value:T,source:"jsdoc",span:Z,symbolName:M})}}else if(Q.type==="Block"){z=null;let V=Q.value.split(`
5
- `),W=0;for(let U of V){let X=U.replace(/^\s*\*?\s?/,""),M=s_.exec(X);if(M){let I=M[1],D=M[2]?.trim()??"",T=`@${I}`,j=U.indexOf(T),h=Q.start+2+W+(j>=0?j:0),Z=Q.start+2+W+U.length,K=du($,h,Z),B=wu($,Q.end),R=U_(J,B.line,3);O.push({tag:I,value:D,source:"block",span:K,symbolName:R})}W+=U.length+1}}else{let V=Q.value,W=s_.exec(V),U=wu($,Q.start),X=wu($,Q.end);if(W){let M=W[1],I=W[2]?.trim()??"",D=`@${M}`,T=V.indexOf(D),j=Q.start+2+(T>=0?T:0),h=du($,j,Q.end),Z=U_(J,X.line,3),K={tag:M,value:I,source:"line",span:h,symbolName:Z};O.push(K),z={annotation:K,endLine:X.line}}else if(z&&U.line===z.endLine+1){let M=V.trim();if(M)z.annotation.value+=" "+M,z.annotation.span.end=wu($,Q.end),z.endLine=X.line}else z=null}return O}function Y_(u){let{parsed:_,project:g,filePath:$,annotationRepo:J}=u,O=t_(_);if(J.deleteFileAnnotations(g,$),!O.length)return 0;let N=new Date().toISOString(),z=O.map((Q)=>({project:g,filePath:$,tag:Q.tag,value:Q.value,source:Q.source,symbolName:Q.symbolName,startLine:Q.span.start.line,startColumn:Q.span.start.column,endLine:Q.span.end.line,endColumn:Q.span.end.column,indexedAt:N}));return J.insertBatch(g,$,z),O.length}function o_(u,_){let g=[],$=[],J=[];for(let[W,U]of _)if(!u.has(W))g.push({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint});for(let[W,U]of u)if(!_.has(W))$.push({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint});if(!g.length||!$.length)return{renamed:J,added:g,removed:$};let O=new Map,N=new Map;for(let W of g){let U=O.get(W.filePath)??[];U.push(W),O.set(W.filePath,U)}for(let W of $){let U=N.get(W.filePath)??[];U.push(W),N.set(W.filePath,U)}let z=new Set,Q=new Set;for(let[W,U]of O){let X=N.get(W);if(!X)continue;for(let M of new Set(U.map((I)=>I.kind))){let I=U.filter((Z)=>Z.kind===M&&!z.has(Z)),D=X.filter((Z)=>Z.kind===M&&!Q.has(Z));if(!I.length||!D.length)continue;let T=(Z,K)=>{return K.get(`${Z.filePath}::${Z.name}`)?.structuralFingerprint??null},j=(Z,K)=>{return K.get(`${Z.filePath}::${Z.name}`)?.startLine??0},h=new Map;for(let Z of D){let K=T(Z,u);if(!K)continue;let B=h.get(K)??[];B.push(Z),h.set(K,B)}for(let Z of I){if(z.has(Z))continue;let K=T(Z,_);if(!K)continue;let B=h.get(K);if(!B)continue;let R=B.filter((S)=>!Q.has(S));if(!R.length)continue;let q=R[0];if(R.length>1){let S=j(Z,_),G=Math.abs(j(q,u)-S);for(let f=1;f<R.length;f++){let y=Math.abs(j(R[f],u)-S);if(y<G)G=y,q=R[f]}}J.push({oldName:q.name,newName:Z.name,filePath:W,kind:M}),z.add(Z),Q.add(q)}}}let V=J.filter((W)=>!W.oldName.includes("."));for(let W of V){let U=`${W.oldName}.`,X=`${W.newName}.`,M=$.filter((D)=>D.filePath===W.filePath&&D.name.startsWith(U)&&!Q.has(D)),I=g.filter((D)=>D.filePath===W.filePath&&D.name.startsWith(X)&&!z.has(D));for(let D of M){let T=D.name.slice(U.length),j=I.find((h)=>h.name.slice(X.length)===T);if(j)J.push({oldName:D.name,newName:j.name,filePath:W.filePath,kind:D.kind}),z.add(j),Q.add(D)}}return{renamed:J,added:g.filter((W)=>!z.has(W)),removed:$.filter((W)=>!Q.has(W))}}var N0=100,ug=50;class Z_{opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;lastPruneAt=0;constructor(u){this.opts=u,this.logger=u.logger??console,this.tsconfigPathsRaw=qu(u.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(u){return this.startIndex(u,!1)}onIndexed(u){return this.callbacks.add(u),()=>this.callbacks.delete(u)}handleWatcherEvent(u){if(u.filePath.endsWith("tsconfig.json")){hu(this.opts.projectRoot),this.tsconfigPathsRaw=qu(this.opts.projectRoot),this.fullIndex().catch((_)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",_)});return}if(u.filePath.endsWith("package.json")){let _=this.opts.discoverProjectsFn??mu;this.boundariesRefresh=_(this.opts.projectRoot).then((g)=>{this.opts.boundaries=g})}if(this.pendingEvents.push(u),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},N0)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(u,_){if(this.indexingLock){if(_)return this.pendingFullIndex=!0,new Promise(($,J)=>{this.pendingFullIndexWaiters.push({resolve:$,reject:J})});return this.currentIndexing}this.indexingLock=!0;let g=this.doIndex(u,_).then(($)=>{return this.fireCallbacks($),$}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let $=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((J)=>{for(let O of $)O.resolve(J)}).catch((J)=>{for(let O of $)O.reject(J)})}else if(this.pendingEvents.length>0){let $=this.pendingEvents.splice(0);this.startIndex($,!1).catch((J)=>this.logger.error("[IndexCoordinator] incremental drain error",J))}});return this.currentIndexing=g,g}async doIndex(u,_){let g=Date.now(),{fileRepo:$,symbolRepo:J,relationRepo:O,dbConnection:N}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let z,Q;if(u!==void 0)z=u.filter((Y)=>Y.eventType==="create"||Y.eventType==="change").map((Y)=>({filePath:Y.filePath,contentHash:"",mtimeMs:0,size:0})),Q=u.filter((Y)=>Y.eventType==="delete").map((Y)=>Y.filePath);else{let Y=new Map;for(let C of this.opts.boundaries)for(let[k,P]of $.getFilesMap(C.project))Y.set(k,P);let A=await i_({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>Y}});z=A.changed,Q=A.deleted}let V=await this.tsconfigPathsRaw??void 0,W=new Map;for(let Y of Q){let A=s(Y,this.opts.boundaries),C=J.getFileSymbols(A,Y);W.set(Y,C)}let U=crypto.randomUUID(),X=new Map,M=new Map,I=(Y)=>({name:Y.name,filePath:Y.filePath,kind:Y.kind,fingerprint:Y.fingerprint,structuralFingerprint:Y.structuralFingerprint??null,startLine:Y.startLine,isExported:Y.isExported??0});if(_)for(let Y of this.opts.boundaries)for(let A of $.getAllFiles(Y.project))for(let C of J.getFileSymbols(Y.project,A.filePath))X.set(`${C.filePath}::${C.name}`,I(C));else{for(let Y of z){let A=s(Y.filePath,this.opts.boundaries);for(let C of J.getFileSymbols(A,Y.filePath))X.set(`${C.filePath}::${C.name}`,I(C))}for(let[,Y]of W)for(let A of Y)X.set(`${A.filePath}::${A.name}`,I(A))}let D=(Y)=>`${Y.type}|${Y.srcFilePath}|${Y.dstFilePath}|${Y.srcSymbolName??""}|${Y.dstSymbolName??""}|${Ou(Y.metaJson??"")}`,T=new Map;if(_)for(let Y of this.opts.boundaries)for(let A of $.getAllFiles(Y.project))for(let C of O.getOutgoing(Y.project,A.filePath))T.set(D(C),C);else{for(let Y of z){let A=s(Y.filePath,this.opts.boundaries);for(let C of O.getOutgoing(A,Y.filePath))T.set(D(C),C)}for(let Y of Q){let A=s(Y,this.opts.boundaries);for(let C of O.getOutgoing(A,Y))T.set(D(C),C)}}let{annotationRepo:j,changelogRepo:h}=this.opts,Z=()=>{for(let Y of Q){let A=s(Y,this.opts.boundaries);if(J.deleteFileSymbols(A,Y),O.deleteFileRelations(A,Y),j)j.deleteFileAnnotations(A,Y);$.deleteFile(A,Y)}},K=0,B=async()=>{let{projectRoot:Y,boundaries:A}=this.opts,{parseCache:C}=this.opts,k=0,P=0,H=0,t=[],F=[];for(let v of z)try{let l=Cu(Y,v.filePath),Uu=Bun.file(l),Iu=await Uu.text(),j_=v.contentHash||Ou(Iu),F_=s(v.filePath,A);$.upsertFile({project:F_,filePath:v.filePath,mtimeMs:Uu.lastModified,size:Uu.size,contentHash:j_,updatedAt:new Date().toISOString(),lineCount:Iu.split(`
6
- `).length});let eu=(this.opts.parseSourceFn??ju)(l,Iu);if(e_(eu))throw eu.data;let H$=eu;F.push({filePath:v.filePath,text:Iu,contentHash:j_,parsed:H$,project:F_})}catch(l){this.logger.error(`[IndexCoordinator] Failed to prepare ${v.filePath}:`,l),t.push(v.filePath)}let m=new Set;for(let v of A)for(let[l]of $.getFilesMap(v.project))m.add(`${v.project}::${l}`);return N.transaction(()=>{for(let v of F){if(O_({parsed:v.parsed,project:v.project,filePath:v.filePath,contentHash:v.contentHash,symbolRepo:J}),P+=V_({ast:v.parsed.program,project:v.project,filePath:v.filePath,relationRepo:O,projectRoot:Y,tsconfigPaths:V,knownFiles:m,boundaries:A}),j)H+=Y_({parsed:v.parsed,project:v.project,filePath:v.filePath,annotationRepo:j});C.set(v.filePath,v.parsed),k+=J.getFileSymbols(v.project,v.filePath).length}}),{symbols:k,relations:P,annotations:H,failedFiles:t}},R=0,q=0,S=[];if(_){let{projectRoot:Y,boundaries:A}=this.opts,{parseCache:C}=this.opts,k=[];for(let H=0;H<z.length;H+=ug){let t=z.slice(H,H+ug),F=await Promise.allSettled(t.map(async(m)=>{let v=Cu(Y,m.filePath),l=Bun.file(v),Uu=await l.text(),Iu=m.contentHash||Ou(Uu);return{filePath:m.filePath,text:Uu,contentHash:Iu,mtimeMs:l.lastModified,size:l.size}}));for(let m=0;m<F.length;m++){let v=F[m];if(v.status==="fulfilled")k.push(v.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",v.reason),S.push(t[m].filePath)}}let P=[];N.transaction(()=>{for(let F of k){let m=s(F.filePath,A);$.deleteFile(m,F.filePath)}for(let F of Q){let m=s(F,A);if(J.deleteFileSymbols(m,F),O.deleteFileRelations(m,F),j)j.deleteFileAnnotations(m,F);$.deleteFile(m,F)}for(let F of k){let m=s(F.filePath,A);$.upsertFile({project:m,filePath:F.filePath,mtimeMs:F.mtimeMs,size:F.size,contentHash:F.contentHash,updatedAt:new Date().toISOString(),lineCount:F.text.split(`
7
- `).length})}let H=new Set;for(let F of A)for(let[m]of $.getFilesMap(F.project))H.add(`${F.project}::${m}`);let t=this.opts.parseSourceFn??ju;for(let F of k){let m=s(F.filePath,A),v=t(Cu(Y,F.filePath),F.text);if(e_(v))throw v.data;let l=v;if(P.push({filePath:F.filePath,parsed:l}),O_({parsed:l,project:m,filePath:F.filePath,contentHash:F.contentHash,symbolRepo:J}),j)K+=Y_({parsed:l,project:m,filePath:F.filePath,annotationRepo:j});q+=V_({ast:l.program,project:m,filePath:F.filePath,relationRepo:O,projectRoot:Y,tsconfigPaths:V,knownFiles:H,boundaries:A}),R+=J.getFileSymbols(m,F.filePath).length}});for(let H of P)C.set(H.filePath,H.parsed)}else{Z();let Y=await B();R=Y.symbols,q=Y.relations,K=Y.annotations,S=Y.failedFiles}for(let Y of z){let A=s(Y.filePath,this.opts.boundaries);for(let C of J.getFileSymbols(A,Y.filePath))M.set(`${C.filePath}::${C.name}`,I(C))}let G=new Map;for(let Y of z){let A=s(Y.filePath,this.opts.boundaries);for(let C of O.getOutgoing(A,Y.filePath))G.set(D(C),C)}let f=(Y)=>({type:Y.type,srcFilePath:Y.srcFilePath,dstFilePath:Y.dstFilePath,srcSymbolName:Y.srcSymbolName,dstSymbolName:Y.dstSymbolName,dstProject:Y.dstProject,metaJson:Y.metaJson}),y={added:[...G.entries()].filter(([Y])=>!T.has(Y)).map(([,Y])=>f(Y)),removed:[...T.entries()].filter(([Y])=>!G.has(Y)).map(([,Y])=>f(Y))},E={added:[],modified:[],removed:[]};for(let[Y,A]of M){let C=X.get(Y);if(!C)E.added.push({name:A.name,filePath:A.filePath,kind:A.kind,isExported:Boolean(A.isExported)});else{let k=C.fingerprint!==A.fingerprint,P=C.isExported!==A.isExported,H=C.structuralFingerprint!==null&&A.structuralFingerprint!==null&&C.structuralFingerprint!==A.structuralFingerprint;if(k||P||H)E.modified.push({name:A.name,filePath:A.filePath,kind:A.kind,isExported:Boolean(A.isExported)})}}for(let[Y,A]of X)if(!M.has(Y))E.removed.push({name:A.name,filePath:A.filePath,kind:A.kind,isExported:Boolean(A.isExported)});let p=o_(X,M),gu=new Set(p.renamed.map((Y)=>`${Y.filePath}::${Y.oldName}`)),r=new Set(p.renamed.map((Y)=>`${Y.filePath}::${Y.newName}`));E.added=E.added.filter((Y)=>!r.has(`${Y.filePath}::${Y.name}`)),E.removed=E.removed.filter((Y)=>!gu.has(`${Y.filePath}::${Y.name}`));let uu=[];if(!_){for(let[Y,A]of W)for(let C of A){if(!C.fingerprint)continue;let k=s(Y,this.opts.boundaries),P=J.getByFingerprint(k,C.fingerprint);if(P.length===1){let H=P[0];O.retargetRelations({dstProject:k,oldFile:Y,oldSymbol:C.name,newFile:H.filePath,newSymbol:H.name}),uu.push({name:H.name,filePath:H.filePath,kind:H.kind,oldFilePath:Y,isExported:H.isExported??0})}}for(let Y of p.removed){let C=X.get(`${Y.filePath}::${Y.name}`)?.fingerprint;if(!C)continue;let k=s(Y.filePath,this.opts.boundaries),P=J.getByFingerprint(k,C);if(P.length===1){let H=P[0];if(H.filePath!==Y.filePath||H.name!==Y.name)O.retargetRelations({dstProject:k,oldFile:Y.filePath,oldSymbol:Y.name,newFile:H.filePath,newSymbol:H.name}),uu.push({name:H.name,filePath:H.filePath,kind:H.kind,oldFilePath:Y.filePath,isExported:H.isExported??0})}}}if(uu.length){let Y=new Set(uu.map((C)=>`${C.filePath}::${C.name}`)),A=new Set(uu.map((C)=>`${C.oldFilePath}::${C.name}`));E.added=E.added.filter((C)=>!Y.has(`${C.filePath}::${C.name}`)),E.removed=E.removed.filter((C)=>!A.has(`${C.filePath}::${C.name}`))}if(h){let Y=new Date().toISOString(),A=_?1:0,C=[];for(let k of E.added){let P=`${k.filePath}::${k.name}`,H=M.get(P),t=s(k.filePath,this.opts.boundaries);C.push({project:t,changeType:"added",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:H?.fingerprint??null,changedAt:Y,isFullIndex:A,indexRunId:U})}for(let k of E.modified){let P=M.get(`${k.filePath}::${k.name}`),H=s(k.filePath,this.opts.boundaries);C.push({project:H,changeType:"modified",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:P?.fingerprint??null,changedAt:Y,isFullIndex:A,indexRunId:U})}for(let k of E.removed){let P=`${k.filePath}::${k.name}`,H=X.get(P),t=s(k.filePath,this.opts.boundaries);C.push({project:t,changeType:"removed",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:H?.fingerprint??null,changedAt:Y,isFullIndex:A,indexRunId:U})}for(let k of p.renamed){let P=M.get(`${k.filePath}::${k.newName}`),H=s(k.filePath,this.opts.boundaries);C.push({project:H,changeType:"renamed",symbolName:k.newName,symbolKind:k.kind,filePath:k.filePath,oldName:k.oldName,oldFilePath:null,fingerprint:P?.fingerprint??null,changedAt:Y,isFullIndex:A,indexRunId:U})}for(let k of uu){let P=M.get(`${k.filePath}::${k.name}`),H=s(k.filePath,this.opts.boundaries);C.push({project:H,changeType:"moved",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:k.oldFilePath,fingerprint:P?.fingerprint??null,changedAt:Y,isFullIndex:A,indexRunId:U})}if(C.length)try{N.transaction(()=>{h.insertBatch(C)})}catch(k){this.logger.error("[IndexCoordinator] changelog insert failed:",k)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let k=new Date(Date.now()-2592000000).toISOString();try{for(let P of this.opts.boundaries)h.pruneOlderThan(P.project,k)}catch(P){this.logger.error("[IndexCoordinator] changelog pruning failed:",P)}}}return{indexedFiles:z.length,removedFiles:Q.length,totalSymbols:R,totalRelations:q,totalAnnotations:K,durationMs:Date.now()-g,changedFiles:z.map((Y)=>Y.filePath),deletedFiles:[...Q],failedFiles:S,changedSymbols:E,renamedSymbols:p.renamed.map((Y)=>({oldName:Y.oldName,newName:Y.newName,filePath:Y.filePath,kind:Y.kind,isExported:Boolean(M.get(`${Y.filePath}::${Y.newName}`)?.isExported)})),movedSymbols:uu.map((Y)=>({name:Y.name,oldFilePath:Y.oldFilePath,newFilePath:Y.filePath,kind:Y.kind,isExported:Boolean(Y.isExported)})),changedRelations:y}}fireCallbacks(u){for(let _ of this.callbacks)try{_(u)}catch(g){this.logger.error("[IndexCoordinator] onIndexed callback threw:",g)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let u=this.pendingEvents.splice(0);this.startIndex(u,!1).catch((_)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",_))}}}function z0(u){try{return process.kill(u,0),!0}catch(_){if(typeof _==="object"&&_&&"code"in _)return _.code!=="ESRCH";return!0}}function O0(u){let _=new Date(u).getTime();return Number.isNaN(_)?0:_}function _g(u,_,g={}){let $=g.now??Date.now,J=g.isAlive??z0,O=g.staleAfterSeconds??60,N=g.instanceId;return u.immediateTransaction(()=>{let z=u.selectOwner();if(!z)return u.insertOwner(_,N),"owner";let Q=Math.floor(($()-O0(z.heartbeat_at))/1000),V=J(z.pid);if(V&&N&&z.instance_id&&z.instance_id!==N&&z.pid!==_)return u.replaceOwner(_,N),"owner";if(V&&Q<O)return"reader";return u.replaceOwner(_,N),"owner"})}function gg(u,_){u.deleteOwner(_)}function $g(u,_){u.touchOwner(_)}class Fu{#u;#_=new Map;constructor(u){this.#u=Math.max(1,u)}get size(){return this.#_.size}has(u){return this.#_.has(u)}get(u){if(!this.#_.has(u))return;let _=this.#_.get(u);return this.#_.delete(u),this.#_.set(u,_),_}set(u,_){if(this.#_.has(u))this.#_.delete(u);if(this.#_.set(u,_),this.#_.size>this.#u){let g=this.#_.keys().next().value;if(g!==void 0)this.#_.delete(g)}}delete(u){return this.#_.delete(u)}clear(){this.#_.clear()}}class X_{lru;constructor(u=500){this.lru=new Fu(u)}get(u){return this.lru.get(u)}set(u,_){this.lru.set(u,_)}invalidate(u){this.lru.delete(u)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function K_(u){let{symbolRepo:_,project:g,query:$}=u,J=$.project??g,O=$.limit??100,N={kind:$.kind,filePath:$.filePath,isExported:$.isExported,project:J,limit:O,resolvedType:$.resolvedType};if($.text)if($.exact)N.exactName=$.text;else{let Q=Au($.text);if(Q)N.ftsQuery=Q}if($.decorator)N.decorator=$.decorator;if($.regex)N.regex=$.regex;return _.searchByQuery(N).map((Q)=>({id:Q.id,filePath:Q.filePath,kind:Q.kind,name:Q.name,span:{start:{line:Q.startLine,column:Q.startColumn},end:{line:Q.endLine,column:Q.endColumn}},isExported:Q.isExported===1,signature:Q.signature,fingerprint:Q.fingerprint,detail:Q.detailJson?(()=>{try{return JSON.parse(Q.detailJson)}catch{return{}}})():{}}))}function M_(u){let{relationRepo:_,project:g,query:$}=u;if($.srcFilePath&&$.srcFilePathPattern)throw new w("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if($.dstFilePath&&$.dstFilePathPattern)throw new w("validation","dstFilePath and dstFilePathPattern are mutually exclusive");let J=$.project??g,O=$.limit??500,N=!!($.srcFilePathPattern||$.dstFilePathPattern),z=N?Number.MAX_SAFE_INTEGER:O,V=_.searchRelations({srcFilePath:$.srcFilePath,srcSymbolName:$.srcSymbolName,dstFilePath:$.dstFilePath,dstSymbolName:$.dstSymbolName,dstProject:$.dstProject,type:$.type,project:J,limit:z}).map((W)=>{let U;if(W.metaJson)try{U=JSON.parse(W.metaJson)}catch{}return{type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,dstProject:W.dstProject,metaJson:W.metaJson??void 0,meta:U}});if($.srcFilePathPattern||$.dstFilePathPattern){let W=$.srcFilePathPattern?new Bun.Glob($.srcFilePathPattern):null,U=$.dstFilePathPattern?new Bun.Glob($.dstFilePathPattern):null;V=V.filter((X)=>(!W||W.match(X.srcFilePath))&&(!U||U.match(X.dstFilePath)))}if(N&&V.length>O)V=V.slice(0,O);return V}import{findInFiles as w0,Lang as W0}from"@ast-grep/napi";async function B_(u){if(u.filePaths.length===0)return[];let _=[];return await w0(W0.TypeScript,{paths:u.filePaths,matcher:{rule:{pattern:u.pattern}}},(g,$)=>{if(g){console.warn("[patternSearch] findInFiles callback error:",g);return}for(let J of $){let O=J.range();_.push({filePath:J.getRoot().filename(),startLine:O.start.line+1,endLine:O.end.line+1,matchedText:J.text()})}}),_}import d from"typescript";import{isErr as C0}from"@zipbul/result";import Vu from"typescript";import V0 from"path";import{err as H_}from"@zipbul/result";function U0(u){try{return n_("fs").readFileSync(u,"utf-8")}catch{return}}function Y0(u){try{return n_("fs").readFileSync(u,"utf-8")}catch{return}}class cu{#u;#_;#g=!1;__testing__;constructor(u,_){this.#u=u,this.#_=_,this.__testing__={host:_}}static create(u,_={}){let g=_.readConfigFile??U0,$=_.resolveNonTrackedFile??Y0,J=V0.dirname(u),O=g(u);if(O===void 0)return H_($u("semantic",`tsconfig not found: ${u}`));let N=Vu.parseJsonText(u,O),z=N.parseDiagnostics;if(z&&z.length>0){let U=z.map((X)=>Vu.flattenDiagnosticMessageText(X.messageText,`
8
- `)).join("; ");return H_($u("semantic",`tsconfig parse error: ${U}`))}let Q=Vu.parseJsonSourceFileConfigFileContent(N,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(U)=>g(U)!==void 0||$(U)!==void 0,readFile:(U)=>g(U)??$(U)},J);if(Q.errors.length>0){let U=Q.errors.filter((X)=>X.category===Vu.DiagnosticCategory.Error&&X.code!==18003);if(U.length>0){let X=U.map((M)=>Vu.flattenDiagnosticMessageText(M.messageText,`
9
- `)).join("; ");return H_($u("semantic",`tsconfig compile error: ${X}`))}}let V=new Jg(Q.fileNames,Q.options,J,$),W=Vu.createLanguageService(V);return new cu(W,V)}get isDisposed(){return this.#g}getProgram(){this.#J();let u=this.#u.getProgram();if(!u)throw Error("TscProgram: LanguageService returned null Program");return u}getChecker(){return this.#J(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#J(),this.#u}notifyFileChanged(u,_){if(this.#g)return;this.#_.updateFile(u,_)}removeFile(u){if(this.#g)return;this.#_.removeFile(u)}dispose(){if(this.#g)return;this.#g=!0,this.#u.dispose()}#J(){if(this.#g)throw Error("TscProgram is disposed")}}class Jg{#u;#_;#g;#J;#$=new Map;constructor(u,_,g,$){this.#u=new Set(u),this.#_=_,this.#g=g,this.#J=$}updateFile(u,_){let g=this.#$.get(u);if(g)g.version+=1,g.content=_;else this.#$.set(u,{version:1,content:_})}removeFile(u){this.#$.delete(u),this.#u.delete(u)}getScriptFileNames(){let u=[...this.#$.keys()];return[...[...this.#u].filter((g)=>!this.#$.has(g)),...u]}getScriptVersion(u){let _=this.#$.get(u);return _?String(_.version):"0"}getScriptSnapshot(u){let _=this.#$.get(u);if(_)return Vu.ScriptSnapshot.fromString(_.content);let g=this.#J(u);if(g!==void 0)return Vu.ScriptSnapshot.fromString(g);return}getCurrentDirectory(){return this.#g}getCompilationSettings(){return this.#_}getDefaultLibFileName(u){return Vu.getDefaultLibFilePath(u)}fileExists(u){if(this.#$.has(u))return!0;return this.#J(u)!==void 0}readFile(u){let _=this.#$.get(u);if(_)return _.content;return this.#J(u)}}import a from"typescript";import Z0 from"typescript";function zu(u,_){if(_<0||_>=u.getEnd())return;function g($){let J=$.getStart(u,!1),O=$.getEnd();if(_<J||_>=O)return;let N;return Z0.forEachChild($,(z)=>{if(!N)N=g(z)}),N??$}return g(u)}var L_=8;function X0(u){return!!(u.flags&a.TypeFlags.Object)&&!!(u.objectFlags&a.ObjectFlags.Reference)}function nu(u,_,g=0){let $=u.typeToString(_),J=_.flags,O=!!(J&a.TypeFlags.Union),N=!!(J&a.TypeFlags.Intersection),z;if(g<L_&&X0(_)){let U=u.getTypeArguments(_);if(U.length>0)z=U}let Q=!!(J&a.TypeFlags.TypeParameter)||z!==void 0&&z.length>0,V;if(O&&g<L_)V=_.types.map((U)=>nu(u,U,g+1));else if(N&&g<L_)V=_.types.map((U)=>nu(u,U,g+1));let W;if(z&&z.length>0)W=z.map((U)=>nu(u,U,g+1));return{text:$,flags:J,isUnion:O,isIntersection:N,isGeneric:Q,members:V,typeArguments:W}}function K0(u){return a.isFunctionDeclaration(u)||a.isVariableDeclaration(u)||a.isClassDeclaration(u)||a.isInterfaceDeclaration(u)||a.isTypeAliasDeclaration(u)||a.isEnumDeclaration(u)||a.isMethodDeclaration(u)||a.isPropertyDeclaration(u)||a.isPropertySignature(u)||a.isMethodSignature(u)}class I_{program;constructor(u){this.program=u}collectAt(u,_){let g=this.program.getProgram(),$=this.program.getChecker();if(_<0)return null;let J=g.getSourceFile(u);if(!J)return null;if(_>=J.getEnd())return null;let O=zu(J,_);if(!O)return null;if(!a.isIdentifier(O)&&!a.isTypeNode(O))return null;try{let N=$.getTypeAtLocation(O);return nu($,N)}catch{return null}}isAssignableTo(u,_,g,$){let J=this.program.getChecker(),O=this.program.getProgram(),N=O.getSourceFile(u);if(!N)return null;let z=zu(N,_);if(!z||!a.isIdentifier(z))return null;let Q=O.getSourceFile(g);if(!Q)return null;let V=zu(Q,$);if(!V||!a.isIdentifier(V))return null;try{let W=J.getTypeAtLocation(z),U=J.getTypeAtLocation(V);return J.isTypeAssignableTo(W,U)}catch{return null}}isAssignableToType(u,_,g,$){let J=this.program.getChecker(),N=this.program.getProgram().getSourceFile(u);if(!N)return null;let z=zu(N,_);if(!z||!a.isIdentifier(z)&&!a.isTypeNode(z))return null;let Q=`${u}.__gildash_probe__.ts`,V=`declare const __gildash_probe__: ${g};`;this.program.notifyFileChanged(Q,V);try{let W=J.getTypeAtLocation(z),X=this.program.getProgram().getSourceFile(Q);if(!X)return null;let M=this.program.getChecker(),I=X.statements[0];if(!I||!a.isVariableStatement(I))return null;let D=I.declarationList.declarations[0];if(!D)return null;let T=M.getTypeAtLocation(D.name);if($?.anyConstituent&&W.isUnion())return W.types.some((j)=>M.isTypeAssignableTo(j,T));return M.isTypeAssignableTo(W,T)}catch{return null}finally{this.program.removeFile(Q)}}collectFile(u){let _=new Map,g=this.program.getProgram(),$=this.program.getChecker(),J=g.getSourceFile(u);if(!J)return _;function O(N){if(K0(N)&&N.name&&a.isIdentifier(N.name)){let z=N.name;try{let Q=$.getTypeAtLocation(z),V=z.getStart(J);_.set(V,nu($,Q))}catch{}}a.forEachChild(N,O)}return O(J),_}}import Xu from"typescript";var M0=1000,B0=1;function H0(u){let _=u.declarations?.[0],g=_?.getSourceFile(),$=_?Xu.getNameOfDeclaration(_):void 0;return{name:u.getName(),filePath:g?.fileName??"",position:$?.getStart(g,!1)??_?.getStart(g,!1)??0}}function ru(u,_=0){let g=u.declarations?.[0],$=g?.getSourceFile(),J=g?Xu.getNameOfDeclaration(g):void 0,O=$?.fileName??"",N=J?.getStart($,!1)??g?.getStart($,!1)??0,z={name:u.getName(),filePath:O,position:N},Q=u;if(Q.parent)z.parent=H0(Q.parent);if(_<B0){let V=u.flags,W=!!(V&Xu.SymbolFlags.Enum),U=!!(V&(Xu.SymbolFlags.NamespaceModule|Xu.SymbolFlags.ValueModule)),X=!!(V&(Xu.SymbolFlags.Class|Xu.SymbolFlags.Interface));if(W&&u.exports&&u.exports.size>0){let M=[];u.exports.forEach((I)=>{M.push(ru(I,_+1))}),z.members=M}else if(X&&u.members&&u.members.size>0){let M=[];u.members.forEach((I)=>{M.push(ru(I,_+1))}),z.members=M}if(U&&u.exports&&u.exports.size>0){let M=[];u.exports.forEach((I)=>{M.push(ru(I,_+1))}),z.exports=M}}return z}class D_{#u;#_;#g=new Map;constructor(u,_=M0){this.#u=u,this.#_=new Fu(_)}get(u,_){if(this.#u.isDisposed)return null;let g=`${u}:${_}`,$=this.#_.get(g);if($!==void 0)return $;let O=this.#u.getProgram().getSourceFile(u);if(!O)return null;let N=zu(O,_);if(!N||!Xu.isIdentifier(N))return null;let Q=this.#u.getChecker().getSymbolAtLocation(N);if(!Q)return null;let V=ru(Q);this.#_.set(g,V);let W=this.#g.get(u);if(!W)W=new Set,this.#g.set(u,W);return W.add(g),V}invalidate(u){let _=this.#g.get(u);if(_){for(let g of _)this.#_.delete(g);this.#g.delete(u)}}clear(){this.#_.clear(),this.#g.clear()}}import L0 from"typescript";class A_{#u;constructor(u){this.#u=u}findAt(u,_){if(this.#u.isDisposed)return[];let g=this.#u.getProgram(),$=g.getSourceFile(u);if(!$)return[];let J=zu($,_);if(!J||!L0.isIdentifier(J))return[];let N=this.#u.getLanguageService().findReferences(u,_);if(!N||N.length===0)return[];let z=[];for(let Q of N)for(let V of Q.references){let W=g.getSourceFile(V.fileName);if(!W)continue;let{line:U,character:X}=W.getLineAndCharacterOfPosition(V.textSpan.start);z.push({filePath:V.fileName,position:V.textSpan.start,line:U+1,column:X,isDefinition:V.isDefinition??!1,isWrite:V.isWriteAccess??!1})}return z}}import x from"typescript";function I0(u,_){let g=zu(u,_);if(!g)return;if(Qg(g))return g;let $=g.parent;for(let J=0;J<5&&$;J++){if(Qg($))return $;$=$.parent}return g}function Qg(u){return x.isClassDeclaration(u)||x.isClassExpression(u)||x.isFunctionDeclaration(u)||x.isFunctionExpression(u)||x.isArrowFunction(u)||x.isVariableDeclaration(u)||x.isObjectLiteralExpression(u)}function Ng(u){if(x.isClassDeclaration(u)||x.isClassExpression(u))return"class";if(x.isFunctionDeclaration(u)||x.isFunctionExpression(u)||x.isArrowFunction(u))return"function";if(x.isObjectLiteralExpression(u))return"object";if(x.isVariableDeclaration(u)&&u.initializer)return Ng(u.initializer);return"class"}function D0(u,_){if(x.isClassDeclaration(u)||x.isFunctionDeclaration(u))return u.name?.getText(_)??"";if(x.isClassExpression(u))return u.name?.getText(_)??"";if(x.isVariableDeclaration(u)&&x.isIdentifier(u.name))return u.name.getText(_);if(x.isFunctionExpression(u))return u.name?.getText(_)??"";if(x.isArrowFunction(u)&&u.parent&&x.isVariableDeclaration(u.parent)){if(x.isIdentifier(u.parent.name))return u.parent.name.getText(_)}if(x.isObjectLiteralExpression(u)&&u.parent&&x.isVariableDeclaration(u.parent)){if(x.isIdentifier(u.parent.name))return u.parent.name.getText(_)}return""}function A0(u){if(!x.isClassDeclaration(u)&&!x.isClassExpression(u))return!1;let _=u.heritageClauses;if(!_)return!1;return _.some((g)=>g.token===x.SyntaxKind.ImplementsKeyword)}class C_{#u;constructor(u){this.#u=u}findAt(u,_){if(this.#u.isDisposed)return[];let g=this.#u.getProgram(),$=g.getSourceFile(u);if(!$)return[];let J=zu($,_);if(!J||!x.isIdentifier(J))return[];let N=this.#u.getLanguageService().getImplementationAtPosition(u,_);if(!N||N.length===0)return[];let z=[];for(let Q of N){if(Q.kind===x.ScriptElementKind.interfaceElement||Q.kind===x.ScriptElementKind.typeElement)continue;let V=g.getSourceFile(Q.fileName);if(!V)continue;let W=I0(V,Q.textSpan.start);if(!W)continue;let U=Ng(W),X=D0(W,V),M=A0(W);z.push({filePath:Q.fileName,symbolName:X,position:Q.textSpan.start,kind:U,isExplicit:M})}return z}}function zg(u){return d.canHaveModifiers(u)&&d.getModifiers(u)?.some((_)=>_.kind===d.SyntaxKind.ExportKeyword)===!0}function S0(u){if(d.isFunctionDeclaration(u))return"function";if(d.isClassDeclaration(u))return"class";if(d.isInterfaceDeclaration(u))return"interface";if(d.isTypeAliasDeclaration(u))return"type";if(d.isEnumDeclaration(u))return"enum";if(d.isVariableDeclaration(u))return"const";if(d.isVariableStatement(u))return"const";return"unknown"}function Og(u){if(u>=97&&u<=122)return!0;if(u>=65&&u<=90)return!0;if(u>=48&&u<=57)return!0;if(u===95||u===36)return!0;return!1}class au{#u;#_;#g;#J;#$;#N=!1;constructor(u,_,g,$,J){this.#u=u,this.#_=_,this.#g=g,this.#J=$,this.#$=J}static create(u,_={}){let g=cu.create(u,{readConfigFile:_.readConfigFile,resolveNonTrackedFile:_.resolveNonTrackedFile});if(C0(g))return g;let $=g,J=_.typeCollector??new I_($),O=_.symbolGraph??new D_($),N=_.referenceResolver??new A_($),z=_.implementationFinder??new C_($);return new au($,J,O,N,z)}get isDisposed(){return this.#N}collectTypeAt(u,_){return this.#Q(),this.#_.collectAt(u,_)}collectFileTypes(u){return this.#Q(),this.#_.collectFile(u)}findReferences(u,_){return this.#Q(),this.#J.findAt(u,_)}findImplementations(u,_){return this.#Q(),this.#$.findAt(u,_)}isTypeAssignableTo(u,_,g,$){return this.#Q(),this.#_.isAssignableTo(u,_,g,$)}isTypeAssignableToType(u,_,g,$){return this.#Q(),this.#_.isAssignableToType(u,_,g,$)}getSymbolNode(u,_){return this.#Q(),this.#g.get(u,_)}getModuleInterface(u){this.#Q();let _=this.#_.collectFile(u),g=[],J=this.#u.getProgram().getSourceFile(u);if(!J)return{filePath:u,exports:g};function O(N){if(d.isVariableStatement(N)&&zg(N)){for(let z of N.declarationList.declarations)if(d.isIdentifier(z.name)){let Q=z.name.getStart(J),V=_.get(Q)??null;g.push({name:z.name.text,kind:"const",resolvedType:V})}return}if((d.isFunctionDeclaration(N)||d.isClassDeclaration(N)||d.isInterfaceDeclaration(N)||d.isTypeAliasDeclaration(N)||d.isEnumDeclaration(N))&&zg(N)&&N.name){let z=N.name,Q=z.getStart(J),V=_.get(Q)??null;g.push({name:z.text,kind:S0(N),resolvedType:V});return}d.forEachChild(N,O)}return O(J),{filePath:u,exports:g}}notifyFileChanged(u,_){if(this.#N)return;this.#u.notifyFileChanged(u,_),this.#g.invalidate(u)}notifyFileDeleted(u){if(this.#N)return;this.#u.removeFile(u),this.#g.invalidate(u)}lineColumnToPosition(u,_,g){this.#Q();let $=this.#u.getProgram().getSourceFile(u);if(!$)return null;try{return d.getPositionOfLineAndCharacter($,_-1,g)}catch{return null}}findNamePosition(u,_,g){this.#Q();let $=this.#u.getProgram().getSourceFile(u);if(!$)return null;let J=$.getFullText(),O=_;while(O<J.length){let N=J.indexOf(g,O);if(N<0)return null;let z=N>0?J.charCodeAt(N-1):32,Q=N+g.length<J.length?J.charCodeAt(N+g.length):32;if(!Og(z)&&!Og(Q))return N;O=N+1}return null}getDiagnostics(u,_){this.#Q();let g=this.#u.getProgram(),$=g.getSourceFile(u);if(!$)return[];let J={[d.DiagnosticCategory.Error]:"error",[d.DiagnosticCategory.Warning]:"warning",[d.DiagnosticCategory.Suggestion]:"suggestion",[d.DiagnosticCategory.Message]:"suggestion"};return((_?.preEmit)?d.getPreEmitDiagnostics(g,$):g.getSemanticDiagnostics($)).map((N)=>{let z=1,Q=0;if(N.file&&N.start!==void 0){let V=d.getLineAndCharacterOfPosition(N.file,N.start);z=V.line+1,Q=V.character}return{filePath:N.file?.fileName??u,line:z,column:Q,message:d.flattenDiagnosticMessageText(N.messageText,`
10
- `),code:N.code,category:J[N.category]??"error"}})}dispose(){if(this.#N)return;this.#N=!0,this.#u.dispose(),this.#g.clear()}#Q(){if(this.#N)throw Error("SemanticLayer is disposed")}}import{eq as Hu,and as wg,sql as R0}from"drizzle-orm";var Wg=80;class S_{db;constructor(u){this.db=u}insertBatch(u,_,g){if(!g.length)return;let $=g.map((J)=>({project:u,filePath:_,tag:J.tag,value:J.value,source:J.source,symbolName:J.symbolName,startLine:J.startLine,startColumn:J.startColumn,endLine:J.endLine,endColumn:J.endColumn,indexedAt:J.indexedAt}));for(let J=0;J<$.length;J+=Wg)this.db.drizzleDb.insert(Nu).values($.slice(J,J+Wg)).run()}deleteFileAnnotations(u,_){this.db.drizzleDb.delete(Nu).where(wg(Hu(Nu.project,u),Hu(Nu.filePath,_))).run()}search(u){return this.db.drizzleDb.select().from(Nu).where(wg(u.project?Hu(Nu.project,u.project):void 0,u.tag?Hu(Nu.tag,u.tag):void 0,u.filePath?Hu(Nu.filePath,u.filePath):void 0,u.symbolName?Hu(Nu.symbolName,u.symbolName):void 0,u.source?Hu(Nu.source,u.source):void 0,u.ftsQuery?R0`${Nu.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${u.ftsQuery})`:void 0)).limit(u.limit).all()}}import{eq as ku,and as Vg,sql as Gu,gt as k0,gte as T0}from"drizzle-orm";var Ug=80;class R_{db;constructor(u){this.db=u}insertBatch(u){if(!u.length)return;let _=u.map((g)=>({project:g.project,changeType:g.changeType,symbolName:g.symbolName,symbolKind:g.symbolKind,filePath:g.filePath,oldName:g.oldName,oldFilePath:g.oldFilePath,fingerprint:g.fingerprint,changedAt:g.changedAt,isFullIndex:g.isFullIndex,indexRunId:g.indexRunId}));for(let g=0;g<_.length;g+=Ug)this.db.drizzleDb.insert(Ju).values(_.slice(g,g+Ug)).run()}getSince(u){return this.db.drizzleDb.select().from(Ju).where(Vg(ku(Ju.project,u.project),T0(Ju.changedAt,u.since),u.symbolName?ku(Ju.symbolName,u.symbolName):void 0,u.changeTypes?.length?Gu`${Ju.changeType} IN (${Gu.join(u.changeTypes.map((_)=>Gu`${_}`),Gu`, `)})`:void 0,u.filePath?ku(Ju.filePath,u.filePath):void 0,u.includeFullIndex?void 0:ku(Ju.isFullIndex,0),u.indexRunId?ku(Ju.indexRunId,u.indexRunId):void 0,u.afterId?k0(Ju.id,u.afterId):void 0)).orderBy(Ju.id).limit(u.limit).all()}pruneOlderThan(u,_){return this.db.drizzleDb.delete(Ju).where(Vg(ku(Ju.project,u),Gu`${Ju.changedAt} < ${_}`)).run().changes}}function Yg(u){let{annotationRepo:_,project:g,query:$}=u,J=$.project??g,O=$.limit??100,N;if($.text){let Q=Au($.text);if(Q)N=Q}return _.search({project:J,tag:$.tag,filePath:$.filePath,symbolName:$.symbolName,source:$.source,ftsQuery:N,limit:O}).map((Q)=>({tag:Q.tag,value:Q.value,source:Q.source,filePath:Q.filePath,symbolName:Q.symbolName,span:{start:{line:Q.startLine,column:Q.startColumn},end:{line:Q.endLine,column:Q.endColumn}}}))}class su{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(u){this.options=u}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let _=[this.options.project,...this.options.additionalProjects??[]].flatMap((g)=>[...this.options.relationRepo.getByType(g,"imports"),...this.options.relationRepo.getByType(g,"type-references"),...this.options.relationRepo.getByType(g,"re-exports")]);for(let g of _){let{srcFilePath:$,dstFilePath:J}=g;if(!this.adjacencyList.has($))this.adjacencyList.set($,new Set);if(this.adjacencyList.get($).add(J),!this.adjacencyList.has(J))this.adjacencyList.set(J,new Set);if(!this.reverseAdjacencyList.has(J))this.reverseAdjacencyList.set(J,new Set);this.reverseAdjacencyList.get(J).add($)}}patchFiles(u,_,g){let $=new Set([...u,..._]);for(let J of $){let O=this.adjacencyList.get(J);if(O){for(let z of O)this.reverseAdjacencyList.get(z)?.delete(J);O.clear()}let N=this.reverseAdjacencyList.get(J);if(N){for(let z of N)this.adjacencyList.get(z)?.delete(J);N.clear()}}for(let J of _)this.adjacencyList.delete(J),this.reverseAdjacencyList.delete(J);for(let J of u){let O=g(J);for(let N of O){if(!this.adjacencyList.has(N.srcFilePath))this.adjacencyList.set(N.srcFilePath,new Set);if(this.adjacencyList.get(N.srcFilePath).add(N.dstFilePath),!this.adjacencyList.has(N.dstFilePath))this.adjacencyList.set(N.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(N.dstFilePath))this.reverseAdjacencyList.set(N.dstFilePath,new Set);this.reverseAdjacencyList.get(N.dstFilePath).add(N.srcFilePath)}}}getDependencies(u){return Array.from(this.adjacencyList.get(u)??[])}getDependents(u){return Array.from(this.reverseAdjacencyList.get(u)??[])}getTransitiveDependents(u){let _=new Set,g=[u];while(g.length>0){let $=g.shift();for(let J of this.reverseAdjacencyList.get($)??[])if(!_.has(J))_.add(J),g.push(J)}return Array.from(_)}hasCycle(){let u=new Set,_=new Set;for(let g of this.adjacencyList.keys()){if(u.has(g))continue;let $=[{node:g,entered:!1}];while($.length>0){let J=$.pop();if(J.entered){_.delete(J.node);continue}if(_.has(J.node))return!0;if(u.has(J.node))continue;u.add(J.node),_.add(J.node),$.push({node:J.node,entered:!0});for(let O of this.adjacencyList.get(J.node)??[]){if(_.has(O))return!0;if(!u.has(O))$.push({node:O,entered:!1})}}}return!1}getAffectedByChange(u){let _=new Set;for(let g of u)for(let $ of this.getTransitiveDependents(g))_.add($);return Array.from(_)}getAdjacencyList(){let u=new Map;for(let[_,g]of this.adjacencyList)u.set(_,Array.from(g));return u}getTransitiveDependencies(u){let _=new Set,g=[u];while(g.length>0){let $=g.shift();for(let J of this.adjacencyList.get($)??[])if(!_.has(J))_.add(J),g.push(J)}return Array.from(_)}getCyclePaths(u){let _=u?.maxCycles??1/0;if(_<=0)return[];let g=new Map;for(let[$,J]of this.adjacencyList)g.set($,Array.from(J));return G0(g,_)}}var q0=(u,_)=>u.localeCompare(_);function j0(u){let _=u.length>1&&u[0]===u[u.length-1]?u.slice(0,-1):[...u];if(_.length===0)return[];let g=_;for(let $=1;$<_.length;$++){let J=_.slice($).concat(_.slice(0,$));if(J.join("::")<g.join("::"))g=J}return[...g]}function k_(u,_,g){let $=j0(g);if($.length===0)return!1;let J=$.join("->");if(u.has(J))return!1;return u.add(J),_.push($),!0}function F0(u){let _=0,g=[],$=new Set,J=new Map,O=new Map,N=[],z=(Q)=>{J.set(Q,_),O.set(Q,_),_+=1,g.push(Q),$.add(Q);for(let V of u.get(Q)??[])if(!J.has(V))z(V),O.set(Q,Math.min(O.get(Q)??0,O.get(V)??0));else if($.has(V))O.set(Q,Math.min(O.get(Q)??0,J.get(V)??0));if(O.get(Q)===J.get(Q)){let V=[],W="";do W=g.pop()??"",$.delete(W),V.push(W);while(W!==Q&&g.length>0);N.push(V)}};for(let Q of u.keys())if(!J.has(Q))z(Q);return{components:N}}function n0(u,_,g){let $=[],J=new Set,O=[...u].sort(q0),N=(z,Q,V)=>{Q.delete(z);let W=V.get(z);if(!W)return;for(let U of W)if(Q.has(U))N(U,Q,V);W.clear()};for(let z=0;z<O.length&&$.length<g;z++){let Q=O[z]??"",V=new Set(O.slice(z)),W=new Set,U=new Map,X=[],M=(D)=>(_.get(D)??[]).filter((T)=>V.has(T)),I=(D)=>{if($.length>=g)return!0;let T=!1;X.push(D),W.add(D);for(let j of M(D)){if($.length>=g)break;if(j===Q)k_(J,$,X.concat(Q)),T=!0;else if(!W.has(j)){if(I(j))T=!0}}if(T)N(D,W,U);else for(let j of M(D)){let h=U.get(j)??new Set;h.add(D),U.set(j,h)}return X.pop(),T};I(Q)}return $}function G0(u,_){let{components:g}=F0(u),$=[],J=new Set;for(let O of g){if($.length>=_)break;if(O.length===0)continue;if(O.length===1){let Q=O[0]??"";if((u.get(Q)??[]).includes(Q))k_(J,$,[Q,Q]);continue}let N=_-$.length,z=n0(O,u,N);for(let Q of z){if($.length>=_)break;k_(J,$,Q)}}return $}var v0=15000;function tu(u){u.graphCache=null,u.graphCacheKey=null,u.graphCacheBuiltAt=null}function Lu(u,_){let g=_??"__cross__";if(u.graphCache&&u.graphCacheBuiltAt!==null){if(Date.now()-u.graphCacheBuiltAt>v0)u.graphCache=null,u.graphCacheKey=null,u.graphCacheBuiltAt=null}if(u.graphCache&&u.graphCacheKey===g)return u.graphCache;let $=new su({relationRepo:u.relationRepo,project:_??u.defaultProject,additionalProjects:_?void 0:u.boundaries?.map((J)=>J.project)});return $.build(),u.graphCache=$,u.graphCacheKey=g,u.graphCacheBuiltAt=Date.now(),$}function Zg(u,_,g,$=1e4){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:g??u.defaultProject,query:{srcFilePath:_,type:"imports",project:g??u.defaultProject,limit:$}}).map((J)=>J.dstFilePath)}catch(J){if(J instanceof w)throw J;throw new w("search","Gildash: getDependencies failed",{cause:J})}}function Xg(u,_,g,$=1e4){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:g??u.defaultProject,query:{dstFilePath:_,type:"imports",project:g??u.defaultProject,limit:$}}).map((J)=>J.srcFilePath)}catch(J){if(J instanceof w)throw J;throw new w("search","Gildash: getDependents failed",{cause:J})}}async function Kg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,g).getAffectedByChange(_)}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getAffected failed",{cause:$})}}async function Mg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,_).hasCycle()}catch(g){if(g instanceof w)throw g;throw new w("search","Gildash: hasCycle failed",{cause:g})}}async function Bg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,_).getAdjacencyList()}catch(g){if(g instanceof w)throw g;throw new w("search","Gildash: getImportGraph failed",{cause:g})}}async function Hg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,g).getTransitiveDependencies(_)}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getTransitiveDependencies failed",{cause:$})}}async function Lg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,g).getTransitiveDependents(_)}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getTransitiveDependents failed",{cause:$})}}async function Ig(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return Lu(u,_).getCyclePaths(g)}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getCyclePaths failed",{cause:$})}}async function Dg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let $=Lu(u,g);return{filePath:_,fanIn:$.getDependents(_).length,fanOut:$.getDependencies(_).length}}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getFanMetrics failed",{cause:$})}}var y0=30000,Ag=15000,f0=10;function P0(u,_){return(g)=>{for(let $ of u.onFileChangedCallbacks)try{$(g)}catch(J){u.logger.error("[Gildash] onFileChanged callback threw:",J)}if(_.handleWatcherEvent?.(g),u.semanticLayer)if(g.eventType==="delete")try{u.semanticLayer.notifyFileDeleted(g.filePath)}catch($){u.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",$);for(let J of u.onErrorCallbacks)try{J($ instanceof w?$:new w("semantic","semantic notifyFileDeleted failed",{cause:$}))}catch{}}else u.readFileFn(g.filePath).then(($)=>{try{u.semanticLayer?.notifyFileChanged(g.filePath,$)}catch(J){u.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",J);for(let O of u.onErrorCallbacks)try{O(J instanceof w?J:new w("semantic","semantic notifyFileChanged failed",{cause:J}))}catch{}}}).catch(($)=>{u.logger.error("[Gildash] failed to read file for semantic layer",g.filePath,$);try{u.semanticLayer?.notifyFileDeleted(g.filePath)}catch(J){u.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",J)}})}}async function m0(u){if(!u.semanticLayer)return;let _=u.fileRepo.getAllFiles(u.defaultProject);await Promise.all(_.map(async(g)=>{try{let $=Eu.resolve(u.projectRoot,g.filePath),J=await u.readFileFn($);u.semanticLayer?.notifyFileChanged($,J)}catch{}}))}async function Cg(u,_){let g=u.coordinatorFactory?u.coordinatorFactory():new Z_({projectRoot:u.projectRoot,boundaries:u.boundaries,extensions:u.extensions,ignorePatterns:u.ignorePatterns,dbConnection:u.db,parseCache:u.parseCache,fileRepo:u.fileRepo,symbolRepo:u.symbolRepo,relationRepo:u.relationRepo,annotationRepo:u.annotationRepo??void 0,changelogRepo:u.changelogRepo??void 0,logger:u.logger});u.coordinator=g;for(let $ of u.onIndexedCallbacks)g.onIndexed($);if(g.onIndexed(($)=>{let J=$.changedFiles.length+$.deletedFiles.length;if(u.graphCache&&J>0&&J<100){let O=u.relationRepo;u.graphCache.patchFiles($.changedFiles,$.deletedFiles,(N)=>{return[u.defaultProject,...u.boundaries.map((Q)=>Q.project)].flatMap((Q)=>O.getByType(Q,"imports").concat(O.getByType(Q,"type-references")).concat(O.getByType(Q,"re-exports"))).filter((Q)=>Q.srcFilePath===N||Q.dstFilePath===N).map((Q)=>({srcFilePath:Q.srcFilePath,dstFilePath:Q.dstFilePath}))}),u.graphCacheBuiltAt=Date.now()}else tu(u)}),_.isWatchMode){let $=u.watcherFactory?u.watcherFactory():new N_({projectRoot:u.projectRoot,ignorePatterns:u.ignorePatterns,extensions:u.extensions},void 0,u.logger);await $.start(P0(u,g)).then((J)=>{if(vu(J))throw J.data}),u.watcher=$,u.timer=setInterval(()=>{u.updateHeartbeatFn(u.db,process.pid)},y0)}await g.fullIndex(),await m0(u)}function h0(u,_){let g=["SIGTERM","SIGINT","beforeExit"];for(let $ of g){let J=()=>{_().catch((O)=>u.logger.error("[Gildash] close error during signal",$,O))};if($==="beforeExit")process.on("beforeExit",J);else process.on($,J);u.signalHandlers.push([$,J])}}async function Sg(u){let{projectRoot:_,extensions:g=[".ts",".mts",".cts"],ignorePatterns:$=["**/node_modules/**"],parseCacheCapacity:J=500,logger:O=console,existsSyncFn:N=b0,dbConnectionFactory:z,watcherFactory:Q,coordinatorFactory:V,repositoryFactory:W,acquireWatcherRoleFn:U=_g,releaseWatcherRoleFn:X=gg,updateHeartbeatFn:M=$g,discoverProjectsFn:I=mu,parseSourceFn:D=ju,extractSymbolsFn:T=Su,extractRelationsFn:j=lu,symbolSearchFn:h=K_,relationSearchFn:Z=M_,patternSearchFn:K=B_,loadTsconfigPathsFn:B=qu,readFileFn:R=async(p)=>Bun.file(p).text(),unlinkFn:q=async(p)=>{await Bun.file(p).unlink()},watchMode:S,semantic:G,semanticLayerFactory:f}=u;if(!Eu.isAbsolute(_))throw new w("validation",`Gildash: projectRoot must be an absolute path, got: "${_}"`);if(!N(_))throw new w("validation",`Gildash: projectRoot does not exist: "${_}"`);let y=z?z():new __({projectRoot:_}),E=y.open();if(vu(E))throw E.data;try{let p=await I(_),gu=p[0]?.project??Eu.basename(_),r=W?W():(()=>{let t=y;return{fileRepo:new g_(t),symbolRepo:new $_(t),relationRepo:new J_(t),parseCache:new X_(J)}})(),uu=W?null:y,Y=uu?new S_(uu):null,A=uu?new R_(uu):null,C=S??!0,k=crypto.randomUUID(),P;if(C)P=await Promise.resolve(U(y,process.pid,{instanceId:k}));else P="owner";let H={projectRoot:_,extensions:g,ignorePatterns:$,logger:O,defaultProject:gu,role:P,db:y,symbolRepo:r.symbolRepo,relationRepo:r.relationRepo,fileRepo:r.fileRepo,parseCache:r.parseCache,annotationRepo:Y,changelogRepo:A,annotationSearchFn:Yg,releaseWatcherRoleFn:X,parseSourceFn:D,extractSymbolsFn:T,extractRelationsFn:j,symbolSearchFn:h,relationSearchFn:Z,patternSearchFn:K,readFileFn:R,unlinkFn:q,existsSyncFn:N,acquireWatcherRoleFn:U,updateHeartbeatFn:M,watcherFactory:Q,coordinatorFactory:V,instanceId:k,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:p,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(hu(_),H.tsconfigPaths=await B(_),G){let t=Eu.join(_,"tsconfig.json");try{if(f)H.semanticLayer=f(t);else{let F=au.create(t);if(vu(F))throw F.data;H.semanticLayer=F}}catch(F){if(F instanceof w)throw F;throw new w("semantic","Gildash: semantic layer creation failed",{cause:F})}}if(P==="owner")await Cg(H,{isWatchMode:C});else{let t=0,F=async()=>{try{let m=await Promise.resolve(H.acquireWatcherRoleFn(H.db,process.pid,{instanceId:H.instanceId}));if(t=0,m==="owner"){H.role="owner";for(let v of H.onRoleChangedCallbacks)try{v("owner")}catch(l){H.logger.error("[Gildash] onRoleChanged callback threw:",l)}clearInterval(H.timer),H.timer=null;try{await Cg(H,{isWatchMode:!0})}catch(v){if(H.logger.error("[Gildash] owner promotion failed, reverting to reader",v),H.role="reader",H.timer!==null)clearInterval(H.timer),H.timer=null;if(H.watcher){let l=await H.watcher.close();if(vu(l))H.logger.error("[Gildash] watcher close error during promotion rollback",l.data);H.watcher=null}if(H.coordinator)await H.coordinator.shutdown().catch((l)=>H.logger.error("[Gildash] coordinator shutdown error during promotion rollback",l)),H.coordinator=null;try{H.releaseWatcherRoleFn(H.db,process.pid)}catch(l){H.logger.error("[Gildash] failed to release watcher role during promotion rollback",l)}H.timer=setInterval(F,Ag)}}}catch(m){t++;let v=m instanceof w?m:new w("watcher","Gildash: healthcheck error",{cause:m});for(let l of H.onErrorCallbacks)try{l(v)}catch(Uu){H.logger.error("[Gildash] onError callback threw:",Uu)}if(H.logger.error("[Gildash] healthcheck error",m),t>=f0)H.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(H.timer),H.timer=null,ou(H).catch((l)=>H.logger.error("[Gildash] close error during healthcheck shutdown",l))}};H.timer=setInterval(F,Ag)}if(C)h0(H,()=>ou(H));return H}catch(p){if(y.close(),p instanceof w)throw p;throw new w("store","Gildash: initialization failed",{cause:p})}}async function ou(u,_){if(u.closed)return;u.closed=!0;let g=[];for(let[$,J]of u.signalHandlers)if($==="beforeExit")process.off("beforeExit",J);else process.off($,J);if(u.signalHandlers=[],u.semanticLayer){try{u.semanticLayer.dispose()}catch($){g.push($ instanceof Error?$:Error(String($)))}u.semanticLayer=null}if(u.coordinator)try{await u.coordinator.shutdown()}catch($){g.push($ instanceof Error?$:Error(String($)))}if(u.watcher){let $=await u.watcher.close();if(vu($))g.push($.data)}if(u.timer!==null)clearInterval(u.timer),u.timer=null;try{u.releaseWatcherRoleFn(u.db,process.pid)}catch($){g.push($ instanceof Error?$:Error(String($)))}try{u.db.close()}catch($){g.push($ instanceof Error?$:Error(String($)))}if(_?.cleanup)for(let $ of["","-wal","-shm"])try{await u.unlinkFn(Eu.join(u.projectRoot,Yu,yu+$))}catch{}if(g.length>0)throw new w("close","Gildash: one or more errors occurred during close()",{cause:g})}import{isErr as Rg}from"@zipbul/result";function kg(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");let J=u.parseSourceFn(_,g,$);if(Rg(J))throw J.data;return u.parseCache.set(_,J),J}async function Tg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");let $=new Map,J=[];return await Promise.all(_.map(async(O)=>{try{let N=await u.readFileFn(O),z=u.parseSourceFn(O,N,g);if(!Rg(z))$.set(O,z);else J.push({filePath:O,error:z.data})}catch(N){J.push({filePath:O,error:N instanceof Error?N:Error(String(N))})}})),{parsed:$,failures:J}}function qg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");return u.parseCache.get(_)}function jg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");return u.extractSymbolsFn(_)}function Fg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");return u.extractRelationsFn(_.program,_.filePath,u.tsconfigPaths??void 0)}import ng from"path";function Gg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.symbolRepo.getStats(_??u.defaultProject)}catch(g){if(g instanceof w)throw g;throw new w("store","Gildash: getStats failed",{cause:g})}}function T_(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.symbolSearchFn({symbolRepo:u.symbolRepo,project:u.defaultProject,query:_})}catch(g){if(g instanceof w)throw g;throw new w("search","Gildash: searchSymbols failed",{cause:g})}}function vg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:u.defaultProject,query:_})}catch(g){if(g instanceof w)throw g;throw new w("search","Gildash: searchRelations failed",{cause:g})}}function Eg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.symbolSearchFn({symbolRepo:u.symbolRepo,project:void 0,query:_})}catch(g){if(g instanceof w)throw g;throw new w("search","Gildash: searchAllSymbols failed",{cause:g})}}function bg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:void 0,query:_})}catch(g){if(g instanceof w)throw g;throw new w("search","Gildash: searchAllRelations failed",{cause:g})}}function yg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.fileRepo.getAllFiles(_??u.defaultProject)}catch(g){if(g instanceof w)throw g;throw new w("store","Gildash: listIndexedFiles failed",{cause:g})}}function fg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:g??u.defaultProject,query:{srcFilePath:_,dstFilePath:_,limit:1e4}})}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getInternalRelations failed",{cause:$})}}function Pg(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let J=$??u.defaultProject,O=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:J,query:{text:_,exact:!0,filePath:g,limit:1}});if(O.length===0)return null;let N=O[0],z=N.detail,Q={...N,members:Array.isArray(z.members)?z.members:void 0,jsDoc:typeof z.jsDoc==="string"?z.jsDoc:void 0,parameters:typeof z.parameters==="string"?z.parameters:void 0,returnType:typeof z.returnType==="string"?z.returnType:void 0,heritage:Array.isArray(z.heritage)?z.heritage:void 0,decorators:Array.isArray(z.decorators)?z.decorators:void 0,typeParameters:typeof z.typeParameters==="string"?z.typeParameters:void 0};if(u.semanticLayer)try{let V=ng.isAbsolute(g)?g:ng.resolve(u.projectRoot,g),W=u.semanticLayer.lineColumnToPosition(V,N.span.start.line,N.span.start.column);if(W!==null){let U=u.semanticLayer.findNamePosition(V,W,N.name)??W,X=u.semanticLayer.collectTypeAt(V,U);if(X)Q.resolvedType=X}}catch{}return Q}catch(J){if(J instanceof w)throw J;throw new w("search","Gildash: getFullSymbol failed",{cause:J})}}function mg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let $=g??u.defaultProject,J=u.fileRepo.getFile($,_);if(!J)throw new w("search",`Gildash: file '${_}' is not in the index`);let O=u.symbolRepo.getFileSymbols($,_),N=u.relationRepo.getOutgoing($,_);return{filePath:J.filePath,lineCount:J.lineCount??0,size:J.size,symbolCount:O.length,exportedSymbolCount:O.filter((z)=>z.isExported).length,relationCount:N.length}}catch($){if($ instanceof w)throw $;throw new w("store","Gildash: getFileStats failed",{cause:$})}}function hg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{return u.fileRepo.getFile(g??u.defaultProject,_)}catch($){if($ instanceof w)throw $;throw new w("store","Gildash: getFileInfo failed",{cause:$})}}function xg(u,_,g){return T_(u,{filePath:_,project:g??void 0,limit:1e4})}function ig(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let J=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:g??u.defaultProject,query:{filePath:_,isExported:!0}}).map((O)=>({name:O.name,kind:O.kind,parameters:O.detail.parameters??void 0,returnType:O.detail.returnType??void 0,jsDoc:O.detail.jsDoc??void 0}));return{filePath:_,exports:J}}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: getModuleInterface failed",{cause:$})}}import i from"path";function bu(u,_,g,$){let J=$??u.defaultProject,O=i.isAbsolute(g)?i.relative(u.projectRoot,g):g,N=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:J,query:{text:_,exact:!0,filePath:O,limit:1}});if(N.length===0)return null;let z=N[0],Q=i.isAbsolute(g)?g:i.resolve(u.projectRoot,g),V=u.semanticLayer.lineColumnToPosition(Q,z.span.start.line,z.span.start.column);if(V===null)return null;let W=u.semanticLayer.findNamePosition(Q,V,z.name)??V;return{sym:z,position:W,absPath:Q}}function pg(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let J=bu(u,_,g,$);if(!J)return null;return u.semanticLayer.collectTypeAt(J.absPath,J.position)}catch(J){if(J instanceof w)throw J;throw new w("search","Gildash: getResolvedType failed",{cause:J})}}function lg(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let J=bu(u,_,g,$);if(!J)throw new w("search",`Gildash: symbol '${_}' not found in '${g}'`);return u.semanticLayer.findReferences(J.absPath,J.position)}catch(J){if(J instanceof w)throw J;throw new w("search","Gildash: getSemanticReferences failed",{cause:J})}}function dg(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let J=bu(u,_,g,$);if(!J)throw new w("search",`Gildash: symbol '${_}' not found in '${g}'`);return u.semanticLayer.findImplementations(J.absPath,J.position)}catch(J){if(J instanceof w)throw J;throw new w("search","Gildash: getImplementations failed",{cause:J})}}function cg(u,_,g,$,J,O){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let N=bu(u,_,g,O);if(!N)throw new w("search",`Gildash: source symbol '${_}' not found in '${g}'`);let z=bu(u,$,J,O);if(!z)throw new w("search",`Gildash: target symbol '${$}' not found in '${J}'`);return u.semanticLayer.isTypeAssignableTo(N.absPath,N.position,z.absPath,z.position)}catch(N){if(N instanceof w)throw N;throw new w("semantic","Gildash: isTypeAssignableTo failed",{cause:N})}}function rg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let g=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.collectFileTypes(g)}catch(g){if(g instanceof w)throw g;throw new w("semantic","Gildash: getFileTypes failed",{cause:g})}}function ag(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let J=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_),O=u.semanticLayer.lineColumnToPosition(J,g,$);if(O===null)return null;return u.semanticLayer.collectTypeAt(J,O)}catch(J){if(J instanceof w)throw J;throw new w("semantic","Gildash: getResolvedTypeAt failed",{cause:J})}}function sg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let g=i.isAbsolute(_.source.filePath)?_.source.filePath:i.resolve(u.projectRoot,_.source.filePath),$=i.isAbsolute(_.target.filePath)?_.target.filePath:i.resolve(u.projectRoot,_.target.filePath),J=u.semanticLayer.lineColumnToPosition(g,_.source.line,_.source.column);if(J===null)return null;let O=u.semanticLayer.lineColumnToPosition($,_.target.line,_.target.column);if(O===null)return null;return u.semanticLayer.isTypeAssignableTo(g,J,$,O)}catch(g){if(g instanceof w)throw g;throw new w("semantic","Gildash: isTypeAssignableToAt failed",{cause:g})}}function tg(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{return u.semanticLayer.getModuleInterface(_)}catch(g){if(g instanceof w)throw g;throw new w("search","Gildash: getSemanticModuleInterface failed",{cause:g})}}function og(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let $=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.collectTypeAt($,g)}catch($){if($ instanceof w)throw $;throw new w("semantic","Gildash: getResolvedTypeAtPosition failed",{cause:$})}}function eg(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let $=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.findReferences($,g)}catch($){if($ instanceof w)throw $;throw new w("semantic","Gildash: getSemanticReferencesAtPosition failed",{cause:$})}}function u$(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let $=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.findImplementations($,g)}catch($){if($ instanceof w)throw $;throw new w("semantic","Gildash: getImplementationsAtPosition failed",{cause:$})}}function _$(u,_,g,$,J){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let O=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_),N=i.isAbsolute($)?$:i.resolve(u.projectRoot,$);return u.semanticLayer.isTypeAssignableTo(O,g,N,J)}catch(O){if(O instanceof w)throw O;throw new w("semantic","Gildash: isTypeAssignableToAtPosition failed",{cause:O})}}function g$(u,_,g,$,J){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let O=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.isTypeAssignableToType(O,g,$,J)}catch(O){if(O instanceof w)throw O;throw new w("semantic","Gildash: isTypeAssignableToType failed",{cause:O})}}function $$(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let J=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.lineColumnToPosition(J,g,$)}catch(J){if(J instanceof w)throw J;throw new w("semantic","Gildash: lineColumnToPosition failed",{cause:J})}}function J$(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let J=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.findNamePosition(J,g,$)}catch(J){if(J instanceof w)throw J;throw new w("semantic","Gildash: findNamePosition failed",{cause:J})}}function Q$(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let $=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.getSymbolNode($,g)}catch($){if($ instanceof w)throw $;throw new w("semantic","Gildash: getSymbolNode failed",{cause:$})}}function N$(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new w("semantic","Gildash: semantic layer is not enabled");try{let $=i.isAbsolute(_)?_:i.resolve(u.projectRoot,_);return u.semanticLayer.getDiagnostics($,g)}catch($){if($ instanceof w)throw $;throw new w("semantic","Gildash: getSemanticDiagnostics failed",{cause:$})}}function z$(u,_){let g=new Map(u.map((z)=>[`${z.name}::${z.filePath}`,z])),$=new Map(_.map((z)=>[`${z.name}::${z.filePath}`,z])),J=[],O=[],N=[];for(let[z,Q]of $){let V=g.get(z);if(!V)J.push(Q);else if(V.fingerprint!==Q.fingerprint)N.push({before:V,after:Q})}for(let[z,Q]of g)if(!$.has(z))O.push(Q);return{added:J,removed:O,modified:N}}function O$(u,_){if(u.onIndexedCallbacks.add(_),!u.coordinator)return()=>{u.onIndexedCallbacks.delete(_)};let g=u.coordinator.onIndexed(_);return()=>{u.onIndexedCallbacks.delete(_),g()}}async function w$(u){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.coordinator)throw new w("closed","Gildash: reindex() is not available for readers");try{let _=await u.coordinator.fullIndex();return tu(u),_}catch(_){if(_ instanceof w)throw _;throw new w("index","Gildash: reindex failed",{cause:_})}}function W$(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");let J=$??u.defaultProject,O=new Set,N=[],z=_,Q=g;for(;;){let V=`${Q}::${z}`;if(O.has(V))return{originalName:z,originalFilePath:Q,reExportChain:N,circular:!0};O.add(V);let W=u.relationSearchFn({relationRepo:u.relationRepo,project:J,query:{type:"re-exports",srcFilePath:Q,limit:500}}),U,X;for(let M of W){let I;if(M.metaJson)try{let T=JSON.parse(M.metaJson);if(Array.isArray(T.specifiers))I=T.specifiers}catch{}if(!I)continue;let D=I.find((T)=>T.exported===z);if(!D)continue;U=M.dstFilePath,X=D.local;break}if(!U||!X)return{originalName:z,originalFilePath:Q,reExportChain:N,circular:!1};N.push({filePath:Q,exportedAs:z}),Q=U,z=X}}function V$(u,_){return u.onFileChangedCallbacks.add(_),()=>{u.onFileChangedCallbacks.delete(_)}}function U$(u,_){return u.onErrorCallbacks.add(_),()=>{u.onErrorCallbacks.delete(_)}}function Y$(u,_){return u.onRoleChangedCallbacks.add(_),()=>{u.onRoleChangedCallbacks.delete(_)}}async function Z$(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let $=g?.project??u.defaultProject,J=g?.filePaths?g.filePaths:u.fileRepo.getAllFiles($).map((O)=>O.filePath);return await u.patternSearchFn({pattern:_,filePaths:J})}catch($){if($ instanceof w)throw $;throw new w("search","Gildash: findPattern failed",{cause:$})}}async function X$(u,_,g,$){if(u.closed)throw new w("closed","Gildash: instance is closed");try{let J=$??u.defaultProject,O=new Set,N=(z,Q,V)=>{let W=`${z}::${Q}`;if(O.has(W))return{symbolName:z,filePath:Q,kind:V,children:[]};O.add(W);let M=u.relationSearchFn({relationRepo:u.relationRepo,project:J,query:{srcFilePath:Q,srcSymbolName:z,limit:1000}}).filter((I)=>I.type==="extends"||I.type==="implements").filter((I)=>I.dstSymbolName!=null).map((I)=>N(I.dstSymbolName,I.dstFilePath,I.type));return{symbolName:z,filePath:Q,kind:V,children:M}};return N(_,g)}catch(J){if(J instanceof w)throw J;throw new w("search","Gildash: getHeritageChain failed",{cause:J})}}function K$(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.annotationRepo||!u.annotationSearchFn)return[];return u.annotationSearchFn({annotationRepo:u.annotationRepo,project:_.project??u.defaultProject,query:_})}function M$(u,_,g){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.changelogRepo)return[];let $=_ instanceof Date?_.toISOString():_,J=g?.project??u.defaultProject,O=g?.limit??1000;return u.changelogRepo.getSince({project:J,since:$,symbolName:g?.symbolName,changeTypes:g?.changeTypes,filePath:g?.filePath,includeFullIndex:g?.includeFullIndex,indexRunId:g?.indexRunId,afterId:g?.afterId,limit:O}).map((z)=>({changeType:z.changeType,symbolName:z.symbolName,symbolKind:z.symbolKind,filePath:z.filePath,oldName:z.oldName,oldFilePath:z.oldFilePath,fingerprint:z.fingerprint,changedAt:z.changedAt,isFullIndex:z.isFullIndex===1,indexRunId:z.indexRunId}))}function B$(u,_){if(u.closed)throw new w("closed","Gildash: instance is closed");if(!u.changelogRepo)return 0;let g=_ instanceof Date?_.toISOString():_,$=0,J=[u.defaultProject,...u.boundaries.map((N)=>N.project)],O=[...new Set(J)];for(let N of O)$+=u.changelogRepo.pruneOlderThan(N,g);return $}class q_{_ctx;get projectRoot(){return this._ctx.projectRoot}get role(){return this._ctx.role}get projects(){return[...this._ctx.boundaries]}constructor(u){this._ctx=u}static async open(u){let _=await Sg(u);return new q_(_)}async close(u){return ou(this._ctx,u)}parseSource(u,_,g){return kg(this._ctx,u,_,g)}async batchParse(u,_){return Tg(this._ctx,u,_)}getParsedAst(u){return qg(this._ctx,u)}extractSymbols(u){return jg(this._ctx,u)}extractRelations(u){return Fg(this._ctx,u)}getStats(u){return Gg(this._ctx,u)}searchSymbols(u){return T_(this._ctx,u)}searchRelations(u){return vg(this._ctx,u)}searchAllSymbols(u){return Eg(this._ctx,u)}searchAllRelations(u){return bg(this._ctx,u)}listIndexedFiles(u){return yg(this._ctx,u)}getInternalRelations(u,_){return fg(this._ctx,u,_)}getFullSymbol(u,_,g){return Pg(this._ctx,u,_,g)}getFileStats(u,_){return mg(this._ctx,u,_)}getFileInfo(u,_){return hg(this._ctx,u,_)}getSymbolsByFile(u,_){return xg(this._ctx,u,_)}getModuleInterface(u,_){return ig(this._ctx,u,_)}getDependencies(u,_,g=1e4){return Zg(this._ctx,u,_,g)}getDependents(u,_,g=1e4){return Xg(this._ctx,u,_,g)}async getAffected(u,_){return Kg(this._ctx,u,_)}async hasCycle(u){return Mg(this._ctx,u)}async getImportGraph(u){return Bg(this._ctx,u)}async getTransitiveDependencies(u,_){return Hg(this._ctx,u,_)}async getTransitiveDependents(u,_){return Lg(this._ctx,u,_)}async getCyclePaths(u,_){return Ig(this._ctx,u,_)}async getFanMetrics(u,_){return Dg(this._ctx,u,_)}getResolvedType(u,_,g){return pg(this._ctx,u,_,g)}getSemanticReferences(u,_,g){return lg(this._ctx,u,_,g)}getImplementations(u,_,g){return dg(this._ctx,u,_,g)}isTypeAssignableTo(u,_,g,$,J){return cg(this._ctx,u,_,g,$,J)}getSemanticModuleInterface(u){return tg(this._ctx,u)}getFileTypes(u){return rg(this._ctx,u)}getResolvedTypeAt(u,_,g){return ag(this._ctx,u,_,g)}isTypeAssignableToAt(u){return sg(this._ctx,u)}getResolvedTypeAtPosition(u,_){return og(this._ctx,u,_)}getSemanticReferencesAtPosition(u,_){return eg(this._ctx,u,_)}getImplementationsAtPosition(u,_){return u$(this._ctx,u,_)}isTypeAssignableToAtPosition(u,_,g,$){return _$(this._ctx,u,_,g,$)}isTypeAssignableToType(u,_,g,$){return g$(this._ctx,u,_,g,$)}lineColumnToPosition(u,_,g){return $$(this._ctx,u,_,g)}findNamePosition(u,_,g){return J$(this._ctx,u,_,g)}getSymbolNode(u,_){return Q$(this._ctx,u,_)}getSemanticDiagnostics(u,_){return N$(this._ctx,u,_)}diffSymbols(u,_){return z$(u,_)}onIndexed(u){return O$(this._ctx,u)}async reindex(){return w$(this._ctx)}resolveSymbol(u,_,g){return W$(this._ctx,u,_,g)}async findPattern(u,_){return Z$(this._ctx,u,_)}async getHeritageChain(u,_,g){return X$(this._ctx,u,_,g)}onFileChanged(u){return V$(this._ctx,u)}onError(u){return U$(this._ctx,u)}onRoleChanged(u){return Y$(this._ctx,u)}searchAnnotations(u){return K$(this._ctx,u)}getSymbolChanges(u,_){return M$(this._ctx,u,_)}pruneChangelog(u){return B$(this._ctx,u)}}export{K_ as symbolSearch,M_ as relationSearch,B_ as patternSearch,$u as gildashError,w as GildashError,q_ as Gildash,su as DependencyGraph};
2
+ var B$=Object.defineProperty;var L$=(u)=>u;function I$(u,_){this[u]=L$.bind(null,_)}var D$=(u,_)=>{for(var g in _)B$(u,g,{get:_[g],enumerable:!0,configurable:!0,set:I$.bind(_,g)})};var F_=import.meta.require;import{isErr as Gu}from"@zipbul/result";import vu from"path";import{existsSync as E0}from"fs";import{err as n_,isErr as T$}from"@zipbul/result";import{Database as q$}from"bun:sqlite";import{mkdirSync as j$,unlinkSync as G_,existsSync as v_}from"fs";import{dirname as F$,join as E_}from"path";import{drizzle as n$}from"drizzle-orm/bun-sqlite";import{migrate as G$}from"drizzle-orm/bun-sqlite/migrator";class N extends Error{type;constructor(u,_,g){super(_,g);this.type=u;this.name="GildashError"}}var Vu=".gildash",bu="gildash.db";var eu={};D$(eu,{watcherOwner:()=>k$,symbols:()=>f,symbolChangelog:()=>$u,relations:()=>L,files:()=>o,annotations:()=>Qu});import{sql as A$}from"drizzle-orm";import{sqliteTable as Iu,text as v,integer as _u,real as C$,index as Ju,primaryKey as S$,foreignKey as yu,check as R$}from"drizzle-orm/sqlite-core";var o=Iu("files",{project:v("project").notNull(),filePath:v("file_path").notNull(),mtimeMs:C$("mtime_ms").notNull(),size:_u("size").notNull(),contentHash:v("content_hash").notNull(),updatedAt:v("updated_at").notNull(),lineCount:_u("line_count")},(u)=>[S$({columns:[u.project,u.filePath]})]),f=Iu("symbols",{id:_u("id").primaryKey({autoIncrement:!0}),project:v("project").notNull(),filePath:v("file_path").notNull(),kind:v("kind").notNull(),name:v("name").notNull(),startLine:_u("start_line").notNull(),startColumn:_u("start_column").notNull(),endLine:_u("end_line").notNull(),endColumn:_u("end_column").notNull(),isExported:_u("is_exported").notNull().default(0),signature:v("signature"),fingerprint:v("fingerprint"),detailJson:v("detail_json"),contentHash:v("content_hash").notNull(),indexedAt:v("indexed_at").notNull(),resolvedType:v("resolved_type"),structuralFingerprint:v("structural_fingerprint")},(u)=>[Ju("idx_symbols_project_file").on(u.project,u.filePath),Ju("idx_symbols_project_kind").on(u.project,u.kind),Ju("idx_symbols_project_name").on(u.project,u.name),Ju("idx_symbols_fingerprint").on(u.project,u.fingerprint),yu({columns:[u.project,u.filePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),L=Iu("relations",{id:_u("id").primaryKey({autoIncrement:!0}),project:v("project").notNull(),type:v("type").notNull(),srcFilePath:v("src_file_path").notNull(),srcSymbolName:v("src_symbol_name"),dstProject:v("dst_project").notNull(),dstFilePath:v("dst_file_path").notNull(),dstSymbolName:v("dst_symbol_name"),metaJson:v("meta_json")},(u)=>[Ju("idx_relations_src").on(u.project,u.srcFilePath),Ju("idx_relations_dst").on(u.dstProject,u.dstFilePath),Ju("idx_relations_type").on(u.project,u.type),Ju("idx_relations_project_type_src").on(u.project,u.type,u.srcFilePath),yu({columns:[u.project,u.srcFilePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade"),yu({columns:[u.dstProject,u.dstFilePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),Qu=Iu("annotations",{id:_u("id").primaryKey({autoIncrement:!0}),project:v("project").notNull(),filePath:v("file_path").notNull(),tag:v("tag").notNull(),value:v("value").notNull().default(""),source:v("source").notNull(),symbolName:v("symbol_name"),startLine:_u("start_line").notNull(),startColumn:_u("start_column").notNull(),endLine:_u("end_line").notNull(),endColumn:_u("end_column").notNull(),indexedAt:v("indexed_at").notNull()},(u)=>[Ju("idx_annotations_project_file").on(u.project,u.filePath),Ju("idx_annotations_project_tag").on(u.project,u.tag),Ju("idx_annotations_project_symbol").on(u.project,u.symbolName),yu({columns:[u.project,u.filePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),$u=Iu("symbol_changelog",{id:_u("id").primaryKey({autoIncrement:!0}),project:v("project").notNull(),changeType:v("change_type").notNull(),symbolName:v("symbol_name").notNull(),symbolKind:v("symbol_kind").notNull(),filePath:v("file_path").notNull(),oldName:v("old_name"),oldFilePath:v("old_file_path"),fingerprint:v("fingerprint"),changedAt:v("changed_at").notNull(),isFullIndex:_u("is_full_index").notNull().default(0),indexRunId:v("index_run_id").notNull()},(u)=>[Ju("idx_changelog_project_changed_at").on(u.project,u.changedAt),Ju("idx_changelog_project_name").on(u.project,u.symbolName),Ju("idx_changelog_project_run").on(u.project,u.indexRunId)]),k$=Iu("watcher_owner",{id:_u("id").primaryKey(),pid:_u("pid").notNull(),startedAt:v("started_at").notNull(),heartbeatAt:v("heartbeat_at").notNull(),instanceId:v("instance_id")},(u)=>[R$("watcher_owner_singleton",A$`${u.id} = 1`)]);class u_{client=null;drizzle=null;dbPath;txDepth=0;constructor(u){this.dbPath=E_(u.projectRoot,Vu,bu)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{j$(F$(this.dbPath),{recursive:!0}),this.client=new q$(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=n$(this.client,{schema:eu}),G$(this.drizzle,{migrationsFolder:E_(import.meta.dirname,"migrations")});let u=this.client.prepare("PRAGMA foreign_key_check").all();if(u.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(u.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON"),this.registerRegexpUdf(this.client)}catch(u){if(this.isCorruptionError(u)&&v_(this.dbPath)){this.closeClient(),G_(this.dbPath);for(let g of["-wal","-shm"]){let $=this.dbPath+g;if(v_($))G_($)}let _=this.open();if(T$(_))return n_(new N("store",`Failed to recover database at ${this.dbPath}`,{cause:_.data}));return _}return n_(new N("store",`Failed to open database at ${this.dbPath}`,{cause:u}))}}close(){this.closeClient(),this.drizzle=null}transaction(u){let _=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return _.transaction(()=>u(this))()}finally{this.txDepth--}}let g=`sp_${this.txDepth++}`;_.run(`SAVEPOINT "${g}"`);try{let $=u(this);return _.run(`RELEASE SAVEPOINT "${g}"`),$}catch($){throw _.run(`ROLLBACK TO SAVEPOINT "${g}"`),_.run(`RELEASE SAVEPOINT "${g}"`),$}finally{this.txDepth--}}immediateTransaction(u){let _=this.requireClient();this.txDepth++,_.run("BEGIN IMMEDIATE");try{let g=u();return _.run("COMMIT"),g}catch(g){throw _.run("ROLLBACK"),g}finally{this.txDepth--}}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((_)=>_.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(u,_){let g=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(u,g,g,_??null)}replaceOwner(u,_){let g=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(u,g,g,_??null)}touchOwner(u){let _=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(_,u)}deleteOwner(u){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(u)}registerRegexpUdf(u){let _=u;if(typeof _.function!=="function")return;_.function.call(u,"regexp",(g,$)=>{try{return new RegExp(g).test($)?1:0}catch{return 0}})}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(u){if(!(u instanceof Error))return!1;let _=u.message.toLowerCase();return _.includes("malformed")||_.includes("corrupt")||_.includes("not a database")||_.includes("disk i/o error")||_.includes("sqlite_corrupt")}}import{eq as ku,and as b_}from"drizzle-orm";class __{db;constructor(u){this.db=u}getFile(u,_){return this.db.drizzleDb.select().from(o).where(b_(ku(o.project,u),ku(o.filePath,_))).get()??null}upsertFile(u){this.db.drizzleDb.insert(o).values({project:u.project,filePath:u.filePath,mtimeMs:u.mtimeMs,size:u.size,contentHash:u.contentHash,updatedAt:u.updatedAt,lineCount:u.lineCount??null}).onConflictDoUpdate({target:[o.project,o.filePath],set:{mtimeMs:u.mtimeMs,size:u.size,contentHash:u.contentHash,updatedAt:u.updatedAt,lineCount:u.lineCount??null}}).run()}getAllFiles(u){return this.db.drizzleDb.select().from(o).where(ku(o.project,u)).all()}getFilesMap(u){let _=this.getAllFiles(u),g=new Map;for(let $ of _)g.set($.filePath,$);return g}deleteFile(u,_){this.db.drizzleDb.delete(o).where(b_(ku(o.project,u),ku(o.filePath,_))).run()}}import{eq as uu,and as Xu,sql as fu,count as v$}from"drizzle-orm";function Du(u){return u.replaceAll("\x00","").trim().split(/\s+/).map((_)=>_.trim()).filter((_)=>_.length>0).map((_)=>`"${_.replaceAll('"','""')}"*`).join(" ")}var y_=50;class g_{db;constructor(u){this.db=u}replaceFileSymbols(u,_,g,$){if(this.db.drizzleDb.delete(f).where(Xu(uu(f.project,u),uu(f.filePath,_))).run(),!$.length)return;let J=new Date().toISOString(),z=$.map((w)=>({project:u,filePath:_,kind:w.kind??"unknown",name:w.name??"",startLine:w.startLine??0,startColumn:w.startColumn??0,endLine:w.endLine??0,endColumn:w.endColumn??0,isExported:w.isExported??0,signature:w.signature??null,fingerprint:w.fingerprint??null,detailJson:w.detailJson??null,contentHash:g,indexedAt:w.indexedAt??J,resolvedType:w.resolvedType??null,structuralFingerprint:w.structuralFingerprint??null}));for(let w=0;w<z.length;w+=y_)this.db.drizzleDb.insert(f).values(z.slice(w,w+y_)).run()}getFileSymbols(u,_){return this.db.drizzleDb.select().from(f).where(Xu(uu(f.project,u),uu(f.filePath,_))).all()}searchByName(u,_,g={}){let $=g.limit??50,J=Du(_);if(!J)return[];return this.db.drizzleDb.select().from(f).where(Xu(fu`${f.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${J})`,uu(f.project,u),g.kind?uu(f.kind,g.kind):void 0)).orderBy(f.name).limit($).all()}searchByKind(u,_){return this.db.drizzleDb.select().from(f).where(Xu(uu(f.project,u),uu(f.kind,_))).orderBy(f.name).all()}getStats(u){let _=this.db.drizzleDb.select({symbolCount:v$(),fileCount:fu`COUNT(DISTINCT ${f.filePath})`}).from(f).where(uu(f.project,u)).get();return{symbolCount:_?.symbolCount??0,fileCount:_?.fileCount??0}}getByFingerprint(u,_){return this.db.drizzleDb.select().from(f).where(Xu(uu(f.project,u),uu(f.fingerprint,_))).all()}deleteFileSymbols(u,_){this.db.drizzleDb.delete(f).where(Xu(uu(f.project,u),uu(f.filePath,_))).run()}searchByQuery(u){let _=this.db.drizzleDb.select().from(f).where(Xu(u.ftsQuery?fu`${f.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${u.ftsQuery})`:void 0,u.exactName?uu(f.name,u.exactName):void 0,u.project!==void 0?uu(f.project,u.project):void 0,u.kind?uu(f.kind,u.kind):void 0,u.filePath!==void 0?uu(f.filePath,u.filePath):void 0,u.isExported!==void 0?uu(f.isExported,u.isExported?1:0):void 0,u.decorator?fu`${f.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${u.decorator})`:void 0,u.resolvedType!==void 0?uu(f.resolvedType,u.resolvedType):void 0)).orderBy(f.name);if(!u.regex)return _.limit(u.limit).all();let g;try{g=new RegExp(u.regex)}catch{throw new N("validation",`Invalid regex pattern: ${u.regex}`)}let $=[];for(let J of[5,20,100]){let z=u.limit*J,w=_.limit(z).all();if($=w.filter((O)=>g.test(O.name)),$.length>=u.limit||w.length<z)return $.slice(0,u.limit)}return $.slice(0,u.limit)}}import{eq as r,and as Nu,isNull as f_,or as E$}from"drizzle-orm";class $_{db;constructor(u){this.db=u}replaceFileRelations(u,_,g){this.db.transaction(($)=>{if($.drizzleDb.delete(L).where(Nu(r(L.project,u),r(L.srcFilePath,_))).run(),!g.length)return;for(let J of g)$.drizzleDb.insert(L).values({project:u,type:J.type??"unknown",srcFilePath:J.srcFilePath??_,srcSymbolName:J.srcSymbolName??null,dstProject:J.dstProject??u,dstFilePath:J.dstFilePath??"",dstSymbolName:J.dstSymbolName??null,metaJson:J.metaJson??null}).run()})}getOutgoing(u,_,g){if(g!==void 0)return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(Nu(r(L.project,u),r(L.srcFilePath,_),E$(r(L.srcSymbolName,g),f_(L.srcSymbolName)))).all();return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(Nu(r(L.project,u),r(L.srcFilePath,_))).all()}getIncoming(u){let{dstProject:_,dstFilePath:g}=u;return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(Nu(r(L.dstProject,_),r(L.dstFilePath,g))).all()}getByType(u,_){return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(Nu(r(L.project,u),r(L.type,_))).all()}deleteFileRelations(u,_){this.db.drizzleDb.delete(L).where(Nu(r(L.project,u),r(L.srcFilePath,_))).run()}searchRelations(u){return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(Nu(u.project!==void 0?r(L.project,u.project):void 0,u.srcFilePath!==void 0?r(L.srcFilePath,u.srcFilePath):void 0,u.srcSymbolName!==void 0?r(L.srcSymbolName,u.srcSymbolName):void 0,u.dstProject!==void 0?r(L.dstProject,u.dstProject):void 0,u.dstFilePath!==void 0?r(L.dstFilePath,u.dstFilePath):void 0,u.dstSymbolName!==void 0?r(L.dstSymbolName,u.dstSymbolName):void 0,u.type!==void 0?r(L.type,u.type):void 0)).limit(u.limit).all()}retargetRelations(u){let{dstProject:_,oldFile:g,oldSymbol:$,newFile:J,newSymbol:z,newDstProject:w}=u,O=$===null?Nu(r(L.dstProject,_),r(L.dstFilePath,g),f_(L.dstSymbolName)):Nu(r(L.dstProject,_),r(L.dstFilePath,g),r(L.dstSymbolName,$)),Q={dstFilePath:J,dstSymbolName:z};if(w!==void 0)Q.dstProject=w;this.db.drizzleDb.update(L).set(Q).where(O).run()}}import{err as P_}from"@zipbul/result";import{subscribe as b$}from"@parcel/watcher";import J_ from"path";var y$=["**/.git/**",`**/${Vu}/**`,"**/dist/**","**/node_modules/**"],f$=new Set(["package.json","tsconfig.json"]);function P$(u){return u.replaceAll("\\","/")}function m$(u){if(u==="update")return"change";if(u==="create")return"create";return"delete"}class Q_{#u;#_;#g;#J;#$;#w;constructor(u,_=b$,g=console){this.#_=u.projectRoot,this.#g=[...y$,...u.ignorePatterns??[]],this.#J=new Set((u.extensions??[".ts",".mts",".cts"]).map(($)=>$.toLowerCase())),this.#$=_,this.#w=g}async start(u){try{this.#u=await this.#$(this.#_,(_,g)=>{if(_){this.#w.error(new N("watcher","Callback error",{cause:_}));return}try{for(let $ of g){let J=P$(J_.relative(this.#_,$.path));if(J.startsWith(".."))continue;let z=J_.basename(J),w=J_.extname(J).toLowerCase();if(!f$.has(z)&&!this.#J.has(w))continue;if(J.endsWith(".d.ts"))continue;u({eventType:m$($.type),filePath:J})}}catch($){this.#w.error(new N("watcher","Callback error",{cause:$}))}},{ignore:this.#g})}catch(_){return P_(new N("watcher","Failed to subscribe watcher",{cause:_}))}}async close(){if(!this.#u)return;try{await this.#u.unsubscribe(),this.#u=void 0}catch(u){return P_(new N("watcher","Failed to close watcher",{cause:u}))}}}import w_ from"path";import{promises as h$}from"fs";var x$=["**/node_modules/**","**/.git/**",`**/${Vu}/**`,"**/dist/**"];async function Pu(u){let _=[];for await(let g of h$.glob("**/package.json",{cwd:u,exclude:x$})){let $=w_.dirname(g).replaceAll("\\","/"),J=w_.join(u,g),z=await Bun.file(J).json(),w=typeof z?.name==="string"&&z.name.length>0?z.name:w_.basename($==="."?u:$);_.push({dir:$,project:w})}return _.sort((g,$)=>$.dir.length-g.dir.length),_}function s(u,_,g="default"){let $=u.replaceAll("\\","/");for(let J of _){if(J.dir===".")return J.project;if($===J.dir||$.startsWith(`${J.dir}/`))return J.project}return g}import m_ from"path";var Yu=new Map;async function i$(u){let _=Bun.file(u);if(!await _.exists())return null;try{let g=await _.text(),$=Bun.JSONC.parse(g);return typeof $==="object"&&$!==null?$:null}catch{return null}}async function Tu(u){if(Yu.has(u))return Yu.get(u)??null;let _=m_.join(u,"tsconfig.json"),g=await i$(_);if(!g)return Yu.set(u,null),null;let $=typeof g.compilerOptions==="object"&&g.compilerOptions!==null?g.compilerOptions:null;if(!$)return Yu.set(u,null),null;let J=typeof $.baseUrl==="string"?$.baseUrl:null,z=typeof $.paths==="object"&&$.paths!==null?$.paths:null;if(!J&&!z)return Yu.set(u,null),null;let w=J?m_.resolve(u,J):u,O=new Map;if(z)for(let[U,W]of Object.entries(z)){if(!Array.isArray(W))continue;let Y=W.filter((X)=>typeof X==="string");O.set(U,Y)}let Q={baseUrl:w,paths:O};return Yu.set(u,Q),Q}function mu(u){if(u){Yu.delete(u);return}Yu.clear()}import h_ from"path";function hu(u,_){return h_.relative(u,_).replaceAll("\\","/")}function Au(u,_){return h_.resolve(u,_)}function Ou(u){let _=Bun.hash.xxHash64(u);return BigInt.asUintN(64,BigInt(_)).toString(16).padStart(16,"0")}import{isErr as o_}from"@zipbul/result";import{err as p$}from"@zipbul/result";import{parseSync as l$}from"oxc-parser";function qu(u,_,g,$=l$){try{let{program:J,errors:z,comments:w}=$(u,_,g);return{filePath:u,program:J,errors:z,comments:w,sourceText:_}}catch(J){return p$(new N("parse",`Failed to parse file: ${u}`,{cause:J}))}}import{promises as d$}from"fs";import{join as c$}from"path";async function x_(u){let{projectRoot:_,extensions:g,ignorePatterns:$,fileRepo:J}=u,z=J.getFilesMap(),w=new Set,O=[],Q=[],U=$.map((Y)=>new Bun.Glob(Y));for await(let Y of d$.glob("**/*",{cwd:_})){if(!g.some((G)=>Y.endsWith(G)))continue;if(Y.startsWith("node_modules/")||Y.includes("/node_modules/"))continue;if(U.some((G)=>G.match(Y)))continue;w.add(Y);let X=c$(_,Y),K=Bun.file(X),{size:I,lastModified:D}=K,k=z.get(Y);if(!k){let G=await K.text(),Z=Ou(G);O.push({filePath:Y,contentHash:Z,mtimeMs:D,size:I});continue}if(k.mtimeMs===D&&k.size===I){Q.push({filePath:Y,contentHash:k.contentHash,mtimeMs:D,size:I});continue}let j=await K.text(),x=Ou(j);if(x===k.contentHash)Q.push({filePath:Y,contentHash:x,mtimeMs:D,size:I});else O.push({filePath:Y,contentHash:x,mtimeMs:D,size:I})}let W=[];for(let Y of z.keys())if(!w.has(Y))W.push(Y);return{changed:O,unchanged:Q,deleted:W}}function xu(u){let _=[0];for(let g=0;g<u.length;g++)if(u[g]===`
3
+ `)_.push(g+1);return _}function zu(u,_){let g=0,$=u.length-1;while(g<$){let J=g+$+1>>1;if(u[J]<=_)g=J;else $=J-1}return{line:g+1,column:_-u[g]}}import{err as r$}from"@zipbul/result";import{parse as a$}from"comment-parser";function iu(u){try{let _=u.trim();if(_.startsWith("/**"))_=_.slice(3);if(_.endsWith("*/"))_=_.slice(0,-2);let $=a$(`/** ${_} */`)[0]??{description:"",tags:[]};return{description:($.description??"").trim(),tags:($.tags??[]).map((J)=>({tag:J.tag??"",name:J.name??"",type:J.type??"",description:J.description??"",optional:J.optional??!1,...J.default!==void 0?{default:J.default}:{}}))}}catch(_){return r$(new N("parse","Failed to parse JSDoc comment",{cause:_}))}}import{isErr as s$}from"@zipbul/result";function Cu(u){let{program:_,sourceText:g,comments:$}=u,J=xu(g),z=$.filter((Z)=>Z.type==="Block"&&Z.value.startsWith("*")).sort((Z,M)=>Z.end-M.end),w=_.body.map((Z)=>Z.start??0).sort((Z,M)=>Z-M);function O(Z,M){return{start:zu(J,Z),end:zu(J,M)}}function Q(Z){let M=0,H=z.length-1,T=-1;while(M<=H){let S=M+H>>>1;if(z[S].end<=Z)T=S,M=S+1;else H=S-1}if(T<0)return;let q=z[T];M=0,H=w.length-1;while(M<=H){let S=M+H>>>1,F=w[S];if(F<=q.end)M=S+1;else if(F>=Z)H=S-1;else return}return`/*${q.value}*/`}function U(Z){if(!Z)return;let M=Z.typeAnnotation??Z;return g.slice(M.start,M.end)}function W(Z){if(!Z||Z.length===0)return[];return Z.map((M)=>{let H=M.expression;if(!H)return{name:"unknown"};if(H.type==="CallExpression"){let T=H.callee?.name??H.callee?.property?.name??"unknown",q=(H.arguments??[]).map((S)=>g.slice(S.start,S.end));return{name:T,arguments:q.length>0?q:void 0}}if(H.type==="Identifier")return{name:H.name??"unknown"};return{name:g.slice(H.start,H.end)}})}function Y(Z){let M=Z.type==="TSParameterProperty"?Z.parameter:Z;if(M?.type==="RestElement"){let P=`...${M.argument?.name??"unknown"}`,gu=M.typeAnnotation,e=gu?U(gu):void 0,l={name:P,isOptional:!1};if(e)l.type=e;return l}if(M?.type==="AssignmentPattern"){let{left:E,right:P}=M,gu=E?.name??"unknown",e=E?.typeAnnotation,l=e?U(e):void 0,V=g.slice(P.start,P.end),A=W(E?.decorators??[]),C={name:gu,isOptional:!0,defaultValue:V};if(l)C.type=l;if(A.length>0)C.decorators=A;return C}let H=M?.name??M?.pattern?.name??"unknown",T=!!M?.optional,q=M?.typeAnnotation,S=q?U(q):void 0,F=W(M?.decorators??[]),y={name:H,isOptional:T};if(S)y.type=S;if(F.length>0)y.decorators=F;return y}function X(Z,M){let H=[];if(M?.async)H.push("async");if(Z.static)H.push("static");if(Z.abstract)H.push("abstract");if(Z.readonly)H.push("readonly");if(Z.override)H.push("override");if(Z.declare)H.push("declare");if(Z.const)H.push("const");let T=Z.accessibility;if(T==="private")H.push("private");else if(T==="protected")H.push("protected");else if(T==="public")H.push("public");return H}function K(Z){let M=[];if(Z.superClass){let T=g.slice(Z.superClass.start,Z.superClass.end);M.push({kind:"extends",name:T})}let H=Z.implements??[];for(let T of H){let q=T.expression??T,S=g.slice(q.start,q.end);M.push({kind:"implements",name:S})}return M}function I(Z){let M=[];for(let H of Z.extends??[]){let T=H.expression??H,q=g.slice(T.start,T.end);M.push({kind:"extends",name:q})}return M}function D(Z){let M=[];for(let H of Z)if(H.type==="MethodDefinition"){let T=H.key?.name??"unknown",q=H.value,S=H.kind??"method",F=S==="constructor"?"constructor":S==="get"?"getter":S==="set"?"setter":"method",y=X(H,q),E=(q?.params??[]).map(Y),P=U(q?.returnType),gu={kind:"method",name:T,span:O(H.start,H.end),isExported:!1,methodKind:F,modifiers:y,parameters:E.length>0?E:void 0,returnType:P};M.push(gu)}else if(H.type==="PropertyDefinition"){let T=H.key?.name??"unknown",q=X(H),S={kind:"property",name:T,span:O(H.start,H.end),isExported:!1,modifiers:q};M.push(S)}return M}function k(Z){let M=[];for(let H of Z)if(H.type==="TSMethodSignature"){let T=H.key?.name??"unknown",q=(H.params??[]).map(Y),S=U(H.returnType);M.push({kind:"method",name:T,span:O(H.start,H.end),isExported:!1,modifiers:[],methodKind:"method",parameters:q.length>0?q:void 0,returnType:S})}else if(H.type==="TSPropertySignature"){let T=H.key?.name??"unknown",q=U(H.typeAnnotation),S={kind:"property",name:T,span:O(H.start,H.end),isExported:!1,modifiers:H.readonly?["readonly"]:[],returnType:q};M.push(S)}return M}function j(Z,M){let H=Z.type??"";if(H==="FunctionDeclaration"||H==="TSDeclareFunction"){let T=Z.id?.name??"default",q=(Z.params??[]).map(Y),S=U(Z.returnType),F=X(Z,Z),y=W(Z.decorators??[]),E=Z.typeParameters?.params?.flatMap((gu)=>{let e=gu.name?.name;return e?[e]:[]})||void 0,P={kind:"function",name:T,span:O(Z.start,Z.end),isExported:M,modifiers:F,parameters:q.length>0?q:void 0,returnType:S,decorators:y.length>0?y:void 0};if(E&&E.length>0)P.typeParameters=E;return P}if(H==="ClassDeclaration"||H==="ClassExpression"){let T=Z.id?.name??"default",q=K(Z),S=D(Z.body?.body??[]),F=W(Z.decorators??[]),y=X(Z,Z),E=Z.typeParameters?.params?.flatMap((gu)=>{let e=gu.name?.name;return e?[e]:[]})||void 0,P={kind:"class",name:T,span:O(Z.start,Z.end),isExported:M,modifiers:y,heritage:q.length>0?q:void 0,members:S.length>0?S:void 0,decorators:F.length>0?F:void 0};if(E&&E.length>0)P.typeParameters=E;return P}if(H==="VariableDeclaration"){let T=[];for(let q of Z.declarations??[]){let{id:S,init:F}=q;if(S?.type==="ObjectPattern"){for(let l of S.properties??[]){let V=l.value?.name??l.key?.name??"unknown";T.push({kind:"variable",name:V,span:O(l.start??q.start,l.end??q.end),isExported:M,modifiers:[]})}continue}if(S?.type==="ArrayPattern"){for(let l of S.elements??[]){if(!l||l.type!=="Identifier")continue;let V=l.name??"unknown";T.push({kind:"variable",name:V,span:O(l.start??q.start,l.end??q.end),isExported:M,modifiers:[]})}continue}let y=S?.name??"unknown",E="variable",P,gu;if(F?.type==="FunctionExpression"||F?.type==="ArrowFunctionExpression")E="function",P=(F.params??[]).map(Y),gu=U(F.returnType);let e=[];T.push({kind:E,name:y,span:O(q.start,q.end),isExported:M,modifiers:e,parameters:P,returnType:gu})}if(T.length===0)return null;if(T.length===1)return T[0];return T}if(H==="TSTypeAliasDeclaration")return{kind:"type",name:Z.id?.name??"unknown",span:O(Z.start,Z.end),isExported:M,modifiers:[]};if(H==="TSInterfaceDeclaration"){let T=Z.id?.name??"unknown",q=I(Z),S=k(Z.body?.body??[]),F=Z.typeParameters?.params?.flatMap((E)=>{let P=E.name?.name;return P?[P]:[]})||void 0,y={kind:"interface",name:T,span:O(Z.start,Z.end),isExported:M,modifiers:[],heritage:q.length>0?q:void 0,members:S.length>0?S:void 0};if(F&&F.length>0)y.typeParameters=F;return y}if(H==="TSEnumDeclaration"){let T=Z.id?.name??"unknown",q=X(Z),F=(Z.body?.members??[]).map((y)=>({kind:"property",name:y.id?.name??y.id?.value??"unknown",span:O(y.start,y.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:T,span:O(Z.start,Z.end),isExported:M,modifiers:q,members:F.length>0?F:void 0}}return null}let x=[],G=new Set;for(let Z of _.body){let M=null,H=Z,T=typeof H.type==="string"?H.type:"";if(T==="ExportNamedDeclaration"){let S=Z;if(S.declaration){if(M=j(S.declaration,!0),M&&!Array.isArray(M))M.span=O(S.start,S.end);else if(Array.isArray(M))for(let F of M)F.span=O(S.start,S.end)}else if(!S.source&&S.specifiers)for(let F of S.specifiers){let y=F.local?.name;if(y)G.add(y)}}else if(T==="ExportDefaultDeclaration"){let S=Z,F=S.declaration;if(F){if(M=j(F,!0),M&&!Array.isArray(M))M.name=F.id?.name??"default",M.isExported=!0,M.span=O(S.start,S.end)}}else M=j(Z,!1);let q=Array.isArray(M)?M:M?[M]:[];for(let S of q){let F=Z.start??0,y=Q(F);if(y){let E=iu(y);if(!s$(E))S.jsDoc=E}x.push(S)}}if(G.size>0){for(let Z of x)if(!Z.isExported&&G.has(Z.name))Z.isExported=!0}return x}function t$(u){if(u.kind==="function"||u.kind==="method"){let _=u.parameters?.length??0,g=u.modifiers.includes("async")?1:0;return`params:${_}|async:${g}`}return null}function o$(u){let _={};if(u.jsDoc)_.jsDoc=u.jsDoc;if(u.kind==="function"||u.kind==="method"){if(u.parameters!==void 0)_.parameters=u.parameters;if(u.returnType!==void 0)_.returnType=u.returnType}if(u.heritage?.length)_.heritage=u.heritage;if(u.decorators?.length)_.decorators=u.decorators;if(u.typeParameters?.length)_.typeParameters=u.typeParameters;if(u.modifiers?.length)_.modifiers=u.modifiers;if(u.members?.length)_.members=u.members.map((g)=>{let $=g.modifiers.find((J)=>J==="private"||J==="protected"||J==="public");return{name:g.name,kind:g.methodKind??g.kind,type:g.returnType,visibility:$,isStatic:g.modifiers.includes("static")||void 0,isReadonly:g.modifiers.includes("readonly")||void 0}});return Object.keys(_).length>0?JSON.stringify(_):null}function e$(u){let _=[u.kind];if(u.modifiers.length)_.push(`mod:${[...u.modifiers].sort().join(",")}`);if(u.typeParameters?.length)_.push(`tp:${u.typeParameters.length}`);if(u.heritage?.length){let g=[...u.heritage].sort(($,J)=>$.name.localeCompare(J.name)).map(($)=>`${$.kind}:${$.name}`).join(",");_.push(`her:${g}`)}if(u.decorators?.length)_.push(`dec:${[...u.decorators].map((g)=>g.name).sort().join(",")}`);if(u.methodKind)_.push(`mk:${u.methodKind}`);if(u.parameters)_.push(`p:${u.parameters.length}`);if(u.returnType)_.push(`rt:${u.returnType}`);if(u.members?.length){let g=u.members.map(($)=>`${$.kind}:${$.modifiers.join(",")}:${$.parameters?.length??""}:${$.returnType??""}`).sort().join(";");_.push(`mem:${u.members.length}:${Ou(g)}`)}return Ou(_.join("|"))}function i_(u,_,g,$,J){let z=t$(u),w=Ou(`${_}|${u.kind}|${z??""}`),O=e$(u);return{project:g,filePath:$,kind:u.kind,name:_,startLine:u.span.start.line,startColumn:u.span.start.column,endLine:u.span.end.line,endColumn:u.span.end.column,isExported:u.isExported?1:0,signature:z,fingerprint:w,detailJson:o$(u),contentHash:J,indexedAt:new Date().toISOString(),structuralFingerprint:O}}function O_(u){let{parsed:_,project:g,filePath:$,contentHash:J,symbolRepo:z}=u,w=Cu(_),O=[];for(let Q of w){O.push(i_(Q,Q.name,g,$,J));for(let U of Q.members??[])O.push(i_(U,`${Q.name}.${U.name}`,g,$,J))}z.replaceFileSymbols(g,$,J,O)}import{resolve as z_,dirname as u0,extname as _0}from"path";function Ku(u,_,g){let $=(J)=>{let z=_0(J);if(z==="")return[J+".ts",J+".d.ts",J+"/index.ts",J+"/index.d.ts",J+".mts",J+"/index.mts",J+".cts",J+"/index.cts"];if(z===".js")return[J.slice(0,-3)+".ts"];if(z===".mjs")return[J.slice(0,-4)+".mts"];if(z===".cjs")return[J.slice(0,-4)+".cts"];return[J]};if(_.startsWith(".")){let J=z_(u0(u),_);return $(J)}if(g)for(let[J,z]of g.paths){if(z.length===0)continue;let w=J.indexOf("*");if(w===-1){if(_===J){let O=[];for(let Q of z)O.push(...$(z_(g.baseUrl,Q)));return O}}else{let O=J.slice(0,w),Q=J.slice(w+1);if(_.startsWith(O)&&(Q===""||_.endsWith(Q))){let U=_.slice(O.length,Q===""?void 0:_.length-Q.length),W=[];for(let Y of z)W.push(...$(z_(g.baseUrl,Y.replace("*",U))));return W}}}return[]}function p_(u,_,g,$=Ku){let J=new Map,z=u.body??[];for(let w of z){if(w.type!=="ImportDeclaration")continue;let O=w.source?.value??"",Q=$(_,O,g);if(Q.length===0)continue;let U=Q[0],W=w.specifiers??[];for(let Y of W)switch(Y.type){case"ImportSpecifier":J.set(Y.local.name,{path:U,importedName:Y.imported.name});break;case"ImportDefaultSpecifier":J.set(Y.local.name,{path:U,importedName:"default"});break;case"ImportNamespaceSpecifier":J.set(Y.local.name,{path:U,importedName:"*"});break}}return J}var g0=new Set(["loc","start","end","scope"]);function Su(u,_){if(!u||typeof u!=="object")return;if(Array.isArray(u)){for(let $ of u)Su($,_);return}let g=u;_(g);for(let $ of Object.keys(g)){if(g0.has($))continue;let J=g[$];if(J&&typeof J==="object")Su(J,_)}}function l_(u){if(!u||typeof u!=="object"||Array.isArray(u))return null;let _=u;if((_.type==="StringLiteral"||_.type==="Literal")&&typeof _.value==="string")return _.value;return null}function Mu(u){if(!u||typeof u!=="object"||Array.isArray(u))return null;let _=u;if(_.type==="Identifier"){let g=_.name;return{root:g,parts:[],full:g}}if(_.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(_.type==="Super")return{root:"super",parts:[],full:"super"};if(_.type==="MemberExpression"){let g=[],$=_;while($.type==="MemberExpression"){let w=$.property;if(!w||typeof w.name!=="string")return null;g.push(w.name),$=$.object}let J;if($.type==="Identifier")J=$.name;else if($.type==="ThisExpression")J="this";else if($.type==="Super")J="super";else return null;g.reverse();let z=[J,...g].join(".");return{root:J,parts:g,full:z}}return null}function d_(u,_,g,$=Ku){let J=[],z=u.body??[];for(let w of z){if(w.type==="ImportDeclaration"){let O=w.source?.value??"",Q=$(_,O,g);if(Q.length===0)continue;let U=Q[0],W=w.importKind==="type",Y=w.specifiers??[];if(Y.length===0){let X={};if(W)X.isType=!0;J.push({type:W?"type-references":"imports",srcFilePath:_,srcSymbolName:null,dstFilePath:U,dstSymbolName:null,...Object.keys(X).length>0?{metaJson:JSON.stringify(X)}:{}})}else for(let X of Y){let K=X.type,I=W||X.importKind==="type",D={};if(I)D.isType=!0;let k,j;if(K==="ImportDefaultSpecifier")k="default",j=X.local.name;else if(K==="ImportNamespaceSpecifier")k="*",j=X.local.name,D.importKind="namespace";else k=X.imported.name,j=X.local.name;J.push({type:I?"type-references":"imports",srcFilePath:_,srcSymbolName:j,dstFilePath:U,dstSymbolName:k,...Object.keys(D).length>0?{metaJson:JSON.stringify(D)}:{}})}continue}if(w.type==="ExportAllDeclaration"&&w.source){let O=w.source?.value??"",Q=$(_,O,g);if(Q.length===0)continue;let U=Q[0],W=w.exportKind==="type",Y={isReExport:!0};if(W)Y.isType=!0;J.push({type:W?"type-references":"re-exports",srcFilePath:_,srcSymbolName:null,dstFilePath:U,dstSymbolName:null,metaJson:JSON.stringify(Y)});continue}if(w.type==="ExportNamedDeclaration"&&w.source){let O=w.source?.value??"",Q=$(_,O,g);if(Q.length===0)continue;let U=Q[0],W=w.exportKind==="type",K={isReExport:!0,specifiers:(w.specifiers??[]).map((I)=>({local:I.local.name,exported:I.exported.name}))};if(W)K.isType=!0;J.push({type:W?"type-references":"re-exports",srcFilePath:_,srcSymbolName:null,dstFilePath:U,dstSymbolName:null,metaJson:JSON.stringify(K)})}}return Su(u,(w)=>{if(w.type!=="ImportExpression")return;let O=l_(w.source);if(!O)return;let Q=$(_,O,g);if(Q.length===0)return;let U=Q[0];J.push({type:"imports",srcFilePath:_,srcSymbolName:null,dstFilePath:U,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),J}function c_(u,_,g){let $=[],J=[],z=[];function w(){if(J.length>0)return J[J.length-1]??null;return null}function O(U){if(!U)return null;let W=g.get(U.root);if(U.parts.length===0){if(W)return{dstFilePath:W.path,dstSymbolName:W.importedName,resolution:"import"};return{dstFilePath:_,dstSymbolName:U.root,resolution:"local"}}else{if(W&&W.importedName==="*"){let Y=U.parts[U.parts.length-1];return{dstFilePath:W.path,dstSymbolName:Y,resolution:"namespace"}}return{dstFilePath:_,dstSymbolName:U.full,resolution:"local-member"}}}function Q(U){if(!U||typeof U!=="object")return;if(Array.isArray(U)){for(let X of U)Q(X);return}let W=U,Y=typeof W.type==="string"?W.type:"";if(Y==="ClassDeclaration"||Y==="ClassExpression"){let X=W,K=X.id?.name??"AnonymousClass";z.push(K),Q(X.body),z.pop();return}if(Y==="FunctionDeclaration"){let X=W,K=X.id?.name??"anonymous";J.push(K),Q(X.body),J.pop();return}if(Y==="VariableDeclarator"&&W.init&&(W.init?.type==="FunctionExpression"||W.init?.type==="ArrowFunctionExpression")){let X=W,K=X.id?.name??"anonymous";J.push(K),Q(X.init?.body??X.init),J.pop();return}if(Y==="MethodDefinition"&&W.value){let X=W,K=z[z.length-1]??"",I=X.key?.name??"anonymous",D=K?`${K}.${I}`:I;J.push(D),Q(X.value?.body),J.pop();return}if(Y==="FunctionExpression"||Y==="ArrowFunctionExpression"){let X=w(),K=X?`${X}.<anonymous>`:"<anonymous>";J.push(K),Q(W.body),J.pop();return}if(Y==="CallExpression"){let X=W,K=Mu(X.callee),I=O(K);if(I){let D=w(),k={};if(D===null)k.scope="module";$.push({type:"calls",srcFilePath:_,srcSymbolName:D,dstFilePath:I.dstFilePath,dstSymbolName:I.dstSymbolName,...Object.keys(k).length>0?{metaJson:JSON.stringify(k)}:{}})}Q(X.callee);for(let D of X.arguments??[])Q(D);return}if(Y==="NewExpression"){let X=W,K=Mu(X.callee),I=O(K);if(I){let D=w(),k={isNew:!0};if(D===null)k.scope="module";$.push({type:"calls",srcFilePath:_,srcSymbolName:D,dstFilePath:I.dstFilePath,dstSymbolName:I.dstSymbolName,metaJson:JSON.stringify(k)})}for(let D of X.arguments??[])Q(D);return}for(let X of Object.keys(W)){if(X==="loc"||X==="start"||X==="end"||X==="scope")continue;let K=W[X];if(K&&typeof K==="object")Q(K)}}return Q(u),$}function r_(u,_,g){let $=[];return Su(u,(J)=>{if(J.type==="TSInterfaceDeclaration"){let O=J.id?.name??"AnonymousInterface",Q=J.extends??[];for(let U of Q){let W=U.expression??U,Y=Mu(W);if(!Y)continue;let X=N_(Y,_,g);$.push({type:"extends",srcFilePath:_,srcSymbolName:O,...X})}return}if(J.type!=="ClassDeclaration"&&J.type!=="ClassExpression")return;let z=J.id?.name??"AnonymousClass";if(J.superClass){let O=Mu(J.superClass);if(O){let Q=N_(O,_,g);$.push({type:"extends",srcFilePath:_,srcSymbolName:z,...Q})}}let w=J.implements??[];for(let O of w){let Q=O.expression??O,U=Mu(Q);if(!U)continue;let W=N_(U,_,g);$.push({type:"implements",srcFilePath:_,srcSymbolName:z,...W})}}),$}function N_(u,_,g){let $=g.get(u.root);if($){if($.importedName==="*"){let J=u.parts[u.parts.length-1]??u.root;return{dstFilePath:$.path,dstSymbolName:J,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:$.path,dstSymbolName:u.parts.length>0?u.full:$.importedName}}return{dstFilePath:_,dstSymbolName:u.full,metaJson:JSON.stringify({isLocal:!0})}}function pu(u,_,g,$=Ku){let J=p_(u,_,g,$),z=d_(u,_,g,$),w=c_(u,_,J),O=r_(u,_,J);return[...z,...w,...O]}function W_(u){let{ast:_,project:g,filePath:$,relationRepo:J,projectRoot:z,tsconfigPaths:w,knownFiles:O,boundaries:Q}=u,U=Au(z,$),Y=pu(_,U,w,O?(K,I,D)=>{let k=Ku(K,I,D);for(let j of k){let x=hu(z,j);if(Q){let G=s(x,Q);if(O.has(`${G}::${x}`))return[j]}else if(O.has(`${g}::${x}`))return[j]}return[]}:void 0),X=[];for(let K of Y){let I=hu(z,K.dstFilePath);if(I.startsWith(".."))continue;let D=hu(z,K.srcFilePath),k=Q?s(I,Q):g;X.push({project:g,type:K.type,srcFilePath:D,srcSymbolName:K.srcSymbolName??null,dstProject:k,dstFilePath:I,dstSymbolName:K.dstSymbolName??null,metaJson:K.metaJson??null})}return J.replaceFileRelations(g,$,X),X.length}import{isErr as $0}from"@zipbul/result";var a_=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function J0(u){let _=Cu(u),g=[];for(let $ of _){g.push({name:$.name,startLine:$.span.start.line});for(let J of $.members??[])g.push({name:`${$.name}.${J.name}`,startLine:J.span.start.line})}return g.sort(($,J)=>$.startLine-J.startLine),g}function U_(u,_,g){let $=0,J=u.length-1;while($<=J){let z=$+J>>1;if(u[z].startLine<=_)$=z+1;else J=z-1}if($<u.length){let z=u[$];if(z.startLine-_<=g)return z.name}return null}function lu(u,_,g){let $=zu(u,_),J=zu(u,g);return{start:$,end:J}}function s_(u){let{comments:_,sourceText:g}=u;if(!_.length)return[];let $=xu(g),J=J0(u),z=[],w=[..._].sort((Q,U)=>Q.start-U.start),O=null;for(let Q of w)if(Q.type==="Block"&&Q.value.startsWith("*")){O=null;let U=`/*${Q.value}*/`,W=iu(U);if($0(W))continue;let Y=W;if(!Y.tags?.length)continue;let X=zu($,Q.end),K=U_(J,X.line,3),I=g.slice(Q.start,Q.end);for(let D of Y.tags){let k=[D.name,D.description].filter(Boolean).join(" "),j=`@${D.tag}`,x=I.indexOf(j),G;if(x>=0){let Z=Q.start+x,M=g.indexOf(`
4
+ `,Z),H=M>=0?Math.min(M,Q.end):Q.end;G=lu($,Z,H)}else G=lu($,Q.start,Q.end);z.push({tag:D.tag,value:k,source:"jsdoc",span:G,symbolName:K})}}else if(Q.type==="Block"){O=null;let U=Q.value.split(`
5
+ `),W=0;for(let Y of U){let X=Y.replace(/^\s*\*?\s?/,""),K=a_.exec(X);if(K){let I=K[1],D=K[2]?.trim()??"",k=`@${I}`,j=Y.indexOf(k),x=Q.start+2+W+(j>=0?j:0),G=Q.start+2+W+Y.length,Z=lu($,x,G),M=zu($,Q.end),H=U_(J,M.line,3);z.push({tag:I,value:D,source:"block",span:Z,symbolName:H})}W+=Y.length+1}}else{let U=Q.value,W=a_.exec(U),Y=zu($,Q.start),X=zu($,Q.end);if(W){let K=W[1],I=W[2]?.trim()??"",D=`@${K}`,k=U.indexOf(D),j=Q.start+2+(k>=0?k:0),x=lu($,j,Q.end),G=U_(J,X.line,3),Z={tag:K,value:I,source:"line",span:x,symbolName:G};z.push(Z),O={annotation:Z,endLine:X.line}}else if(O&&Y.line===O.endLine+1){let K=U.trim();if(K)O.annotation.value+=" "+K,O.annotation.span.end=zu($,Q.end),O.endLine=X.line}else O=null}return z}function V_(u){let{parsed:_,project:g,filePath:$,annotationRepo:J}=u,z=s_(_);if(J.deleteFileAnnotations(g,$),!z.length)return 0;let w=new Date().toISOString(),O=z.map((Q)=>({project:g,filePath:$,tag:Q.tag,value:Q.value,source:Q.source,symbolName:Q.symbolName,startLine:Q.span.start.line,startColumn:Q.span.start.column,endLine:Q.span.end.line,endColumn:Q.span.end.column,indexedAt:w}));return J.insertBatch(g,$,O),z.length}function t_(u,_){let g=[],$=[],J=[];for(let[W,Y]of _)if(!u.has(W))g.push({name:Y.name,filePath:Y.filePath,kind:Y.kind,fingerprint:Y.fingerprint});for(let[W,Y]of u)if(!_.has(W))$.push({name:Y.name,filePath:Y.filePath,kind:Y.kind,fingerprint:Y.fingerprint});if(!g.length||!$.length)return{renamed:J,added:g,removed:$};let z=new Map,w=new Map;for(let W of g){let Y=z.get(W.filePath)??[];Y.push(W),z.set(W.filePath,Y)}for(let W of $){let Y=w.get(W.filePath)??[];Y.push(W),w.set(W.filePath,Y)}let O=new Set,Q=new Set;for(let[W,Y]of z){let X=w.get(W);if(!X)continue;for(let K of new Set(Y.map((I)=>I.kind))){let I=Y.filter((G)=>G.kind===K&&!O.has(G)),D=X.filter((G)=>G.kind===K&&!Q.has(G));if(!I.length||!D.length)continue;let k=(G,Z)=>{return Z.get(`${G.filePath}::${G.name}`)?.structuralFingerprint??null},j=(G,Z)=>{return Z.get(`${G.filePath}::${G.name}`)?.startLine??0},x=new Map;for(let G of D){let Z=k(G,u);if(!Z)continue;let M=x.get(Z)??[];M.push(G),x.set(Z,M)}for(let G of I){if(O.has(G))continue;let Z=k(G,_);if(!Z)continue;let M=x.get(Z);if(!M)continue;let H=M.filter((q)=>!Q.has(q));if(!H.length)continue;let T=H[0];if(H.length>1){let q=j(G,_),S=Math.abs(j(T,u)-q);for(let F=1;F<H.length;F++){let y=Math.abs(j(H[F],u)-q);if(y<S)S=y,T=H[F]}}J.push({oldName:T.name,newName:G.name,filePath:W,kind:K}),O.add(G),Q.add(T)}}}let U=J.filter((W)=>!W.oldName.includes("."));for(let W of U){let Y=`${W.oldName}.`,X=`${W.newName}.`,K=$.filter((D)=>D.filePath===W.filePath&&D.name.startsWith(Y)&&!Q.has(D)),I=g.filter((D)=>D.filePath===W.filePath&&D.name.startsWith(X)&&!O.has(D));for(let D of K){let k=D.name.slice(Y.length),j=I.find((x)=>x.name.slice(X.length)===k);if(j)J.push({oldName:D.name,newName:j.name,filePath:W.filePath,kind:D.kind}),O.add(j),Q.add(D)}}return{renamed:J,added:g.filter((W)=>!O.has(W)),removed:$.filter((W)=>!Q.has(W))}}var Q0=100,e_=50;class Y_{opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;lastPruneAt=0;constructor(u){this.opts=u,this.logger=u.logger??console,this.tsconfigPathsRaw=Tu(u.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(u){return this.startIndex(u,!1)}onIndexed(u){return this.callbacks.add(u),()=>this.callbacks.delete(u)}handleWatcherEvent(u){if(u.filePath.endsWith("tsconfig.json")){mu(this.opts.projectRoot),this.tsconfigPathsRaw=Tu(this.opts.projectRoot),this.fullIndex().catch((_)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",_)});return}if(u.filePath.endsWith("package.json")){let _=this.opts.discoverProjectsFn??Pu;this.boundariesRefresh=_(this.opts.projectRoot).then((g)=>{this.opts.boundaries=g})}if(this.pendingEvents.push(u),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},Q0)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(u,_){if(this.indexingLock){if(_)return this.pendingFullIndex=!0,new Promise(($,J)=>{this.pendingFullIndexWaiters.push({resolve:$,reject:J})});return this.currentIndexing}this.indexingLock=!0;let g=this.doIndex(u,_).then(($)=>{return this.fireCallbacks($),$}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let $=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((J)=>{for(let z of $)z.resolve(J)}).catch((J)=>{for(let z of $)z.reject(J)})}else if(this.pendingEvents.length>0){let $=this.pendingEvents.splice(0);this.startIndex($,!1).catch((J)=>this.logger.error("[IndexCoordinator] incremental drain error",J))}});return this.currentIndexing=g,g}async doIndex(u,_){let g=Date.now(),{fileRepo:$,symbolRepo:J,relationRepo:z,dbConnection:w}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let O,Q;if(u!==void 0)O=u.filter((V)=>V.eventType==="create"||V.eventType==="change").map((V)=>({filePath:V.filePath,contentHash:"",mtimeMs:0,size:0})),Q=u.filter((V)=>V.eventType==="delete").map((V)=>V.filePath);else{let V=new Map;for(let C of this.opts.boundaries)for(let[R,m]of $.getFilesMap(C.project))V.set(R,m);let A=await x_({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>V}});O=A.changed,Q=A.deleted}let U=await this.tsconfigPathsRaw??void 0,W=new Map;for(let V of Q){let A=s(V,this.opts.boundaries),C=J.getFileSymbols(A,V);W.set(V,C)}let Y=crypto.randomUUID(),X=new Map,K=new Map,I=(V)=>({name:V.name,filePath:V.filePath,kind:V.kind,fingerprint:V.fingerprint,structuralFingerprint:V.structuralFingerprint??null,startLine:V.startLine,isExported:V.isExported??0});if(_)for(let V of this.opts.boundaries)for(let A of $.getAllFiles(V.project))for(let C of J.getFileSymbols(V.project,A.filePath))X.set(`${C.filePath}::${C.name}`,I(C));else{for(let V of O){let A=s(V.filePath,this.opts.boundaries);for(let C of J.getFileSymbols(A,V.filePath))X.set(`${C.filePath}::${C.name}`,I(C))}for(let[,V]of W)for(let A of V)X.set(`${A.filePath}::${A.name}`,I(A))}let D=(V)=>`${V.type}|${V.srcFilePath}|${V.dstFilePath}|${V.srcSymbolName??""}|${V.dstSymbolName??""}|${Ou(V.metaJson??"")}`,k=new Map;if(_)for(let V of this.opts.boundaries)for(let A of $.getAllFiles(V.project))for(let C of z.getOutgoing(V.project,A.filePath))k.set(D(C),C);else{for(let V of O){let A=s(V.filePath,this.opts.boundaries);for(let C of z.getOutgoing(A,V.filePath))k.set(D(C),C)}for(let V of Q){let A=s(V,this.opts.boundaries);for(let C of z.getOutgoing(A,V))k.set(D(C),C)}}let{annotationRepo:j,changelogRepo:x}=this.opts,G=()=>{for(let V of Q){let A=s(V,this.opts.boundaries);if(J.deleteFileSymbols(A,V),z.deleteFileRelations(A,V),j)j.deleteFileAnnotations(A,V);$.deleteFile(A,V)}},Z=0,M=async()=>{let{projectRoot:V,boundaries:A}=this.opts,{parseCache:C}=this.opts,R=0,m=0,B=0,t=[],n=[];for(let b of O)try{let d=Au(V,b.filePath),Uu=Bun.file(d),Lu=await Uu.text(),q_=b.contentHash||Ou(Lu),j_=s(b.filePath,A);$.upsertFile({project:j_,filePath:b.filePath,mtimeMs:Uu.lastModified,size:Uu.size,contentHash:q_,updatedAt:new Date().toISOString(),lineCount:Lu.split(`
6
+ `).length});let ou=(this.opts.parseSourceFn??qu)(d,Lu);if(o_(ou))throw ou.data;let H$=ou;n.push({filePath:b.filePath,text:Lu,contentHash:q_,parsed:H$,project:j_})}catch(d){this.logger.error(`[IndexCoordinator] Failed to prepare ${b.filePath}:`,d),t.push(b.filePath)}let h=new Set;for(let b of A)for(let[d]of $.getFilesMap(b.project))h.add(`${b.project}::${d}`);return w.transaction(()=>{for(let b of n){if(O_({parsed:b.parsed,project:b.project,filePath:b.filePath,contentHash:b.contentHash,symbolRepo:J}),m+=W_({ast:b.parsed.program,project:b.project,filePath:b.filePath,relationRepo:z,projectRoot:V,tsconfigPaths:U,knownFiles:h,boundaries:A}),j)B+=V_({parsed:b.parsed,project:b.project,filePath:b.filePath,annotationRepo:j});C.set(b.filePath,b.parsed),R+=J.getFileSymbols(b.project,b.filePath).length}}),{symbols:R,relations:m,annotations:B,failedFiles:t}},H=0,T=0,q=[];if(_){let{projectRoot:V,boundaries:A}=this.opts,{parseCache:C}=this.opts,R=[];for(let B=0;B<O.length;B+=e_){let t=O.slice(B,B+e_),n=await Promise.allSettled(t.map(async(h)=>{let b=Au(V,h.filePath),d=Bun.file(b),Uu=await d.text(),Lu=h.contentHash||Ou(Uu);return{filePath:h.filePath,text:Uu,contentHash:Lu,mtimeMs:d.lastModified,size:d.size}}));for(let h=0;h<n.length;h++){let b=n[h];if(b.status==="fulfilled")R.push(b.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",b.reason),q.push(t[h].filePath)}}let m=[];w.transaction(()=>{for(let n of R){let h=s(n.filePath,A);$.deleteFile(h,n.filePath)}for(let n of Q){let h=s(n,A);if(J.deleteFileSymbols(h,n),z.deleteFileRelations(h,n),j)j.deleteFileAnnotations(h,n);$.deleteFile(h,n)}for(let n of R){let h=s(n.filePath,A);$.upsertFile({project:h,filePath:n.filePath,mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:new Date().toISOString(),lineCount:n.text.split(`
7
+ `).length})}let B=new Set;for(let n of A)for(let[h]of $.getFilesMap(n.project))B.add(`${n.project}::${h}`);let t=this.opts.parseSourceFn??qu;for(let n of R){let h=s(n.filePath,A),b=t(Au(V,n.filePath),n.text);if(o_(b))throw b.data;let d=b;if(m.push({filePath:n.filePath,parsed:d}),O_({parsed:d,project:h,filePath:n.filePath,contentHash:n.contentHash,symbolRepo:J}),j)Z+=V_({parsed:d,project:h,filePath:n.filePath,annotationRepo:j});T+=W_({ast:d.program,project:h,filePath:n.filePath,relationRepo:z,projectRoot:V,tsconfigPaths:U,knownFiles:B,boundaries:A}),H+=J.getFileSymbols(h,n.filePath).length}});for(let B of m)C.set(B.filePath,B.parsed)}else{G();let V=await M();H=V.symbols,T=V.relations,Z=V.annotations,q=V.failedFiles}for(let V of O){let A=s(V.filePath,this.opts.boundaries);for(let C of J.getFileSymbols(A,V.filePath))K.set(`${C.filePath}::${C.name}`,I(C))}let S=new Map;for(let V of O){let A=s(V.filePath,this.opts.boundaries);for(let C of z.getOutgoing(A,V.filePath))S.set(D(C),C)}let F=(V)=>({type:V.type,srcFilePath:V.srcFilePath,dstFilePath:V.dstFilePath,srcSymbolName:V.srcSymbolName,dstSymbolName:V.dstSymbolName,dstProject:V.dstProject,metaJson:V.metaJson}),y={added:[...S.entries()].filter(([V])=>!k.has(V)).map(([,V])=>F(V)),removed:[...k.entries()].filter(([V])=>!S.has(V)).map(([,V])=>F(V))},E={added:[],modified:[],removed:[]};for(let[V,A]of K){let C=X.get(V);if(!C)E.added.push({name:A.name,filePath:A.filePath,kind:A.kind,isExported:Boolean(A.isExported)});else{let R=C.fingerprint!==A.fingerprint,m=C.isExported!==A.isExported,B=C.structuralFingerprint!==null&&A.structuralFingerprint!==null&&C.structuralFingerprint!==A.structuralFingerprint;if(R||m||B)E.modified.push({name:A.name,filePath:A.filePath,kind:A.kind,isExported:Boolean(A.isExported)})}}for(let[V,A]of X)if(!K.has(V))E.removed.push({name:A.name,filePath:A.filePath,kind:A.kind,isExported:Boolean(A.isExported)});let P=t_(X,K),gu=new Set(P.renamed.map((V)=>`${V.filePath}::${V.oldName}`)),e=new Set(P.renamed.map((V)=>`${V.filePath}::${V.newName}`));E.added=E.added.filter((V)=>!e.has(`${V.filePath}::${V.name}`)),E.removed=E.removed.filter((V)=>!gu.has(`${V.filePath}::${V.name}`));let l=[];if(!_){for(let[V,A]of W)for(let C of A){if(!C.fingerprint)continue;let R=s(V,this.opts.boundaries),m=J.getByFingerprint(R,C.fingerprint);if(m.length===1){let B=m[0];z.retargetRelations({dstProject:R,oldFile:V,oldSymbol:C.name,newFile:B.filePath,newSymbol:B.name}),l.push({name:B.name,filePath:B.filePath,kind:B.kind,oldFilePath:V,isExported:B.isExported??0})}}for(let V of P.removed){let C=X.get(`${V.filePath}::${V.name}`)?.fingerprint;if(!C)continue;let R=s(V.filePath,this.opts.boundaries),m=J.getByFingerprint(R,C);if(m.length===1){let B=m[0];if(B.filePath!==V.filePath||B.name!==V.name)z.retargetRelations({dstProject:R,oldFile:V.filePath,oldSymbol:V.name,newFile:B.filePath,newSymbol:B.name}),l.push({name:B.name,filePath:B.filePath,kind:B.kind,oldFilePath:V.filePath,isExported:B.isExported??0})}}}if(l.length){let V=new Set(l.map((C)=>`${C.filePath}::${C.name}`)),A=new Set(l.map((C)=>`${C.oldFilePath}::${C.name}`));E.added=E.added.filter((C)=>!V.has(`${C.filePath}::${C.name}`)),E.removed=E.removed.filter((C)=>!A.has(`${C.filePath}::${C.name}`))}if(x){let V=new Date().toISOString(),A=_?1:0,C=[];for(let R of E.added){let m=`${R.filePath}::${R.name}`,B=K.get(m),t=s(R.filePath,this.opts.boundaries);C.push({project:t,changeType:"added",symbolName:R.name,symbolKind:R.kind,filePath:R.filePath,oldName:null,oldFilePath:null,fingerprint:B?.fingerprint??null,changedAt:V,isFullIndex:A,indexRunId:Y})}for(let R of E.modified){let m=K.get(`${R.filePath}::${R.name}`),B=s(R.filePath,this.opts.boundaries);C.push({project:B,changeType:"modified",symbolName:R.name,symbolKind:R.kind,filePath:R.filePath,oldName:null,oldFilePath:null,fingerprint:m?.fingerprint??null,changedAt:V,isFullIndex:A,indexRunId:Y})}for(let R of E.removed){let m=`${R.filePath}::${R.name}`,B=X.get(m),t=s(R.filePath,this.opts.boundaries);C.push({project:t,changeType:"removed",symbolName:R.name,symbolKind:R.kind,filePath:R.filePath,oldName:null,oldFilePath:null,fingerprint:B?.fingerprint??null,changedAt:V,isFullIndex:A,indexRunId:Y})}for(let R of P.renamed){let m=K.get(`${R.filePath}::${R.newName}`),B=s(R.filePath,this.opts.boundaries);C.push({project:B,changeType:"renamed",symbolName:R.newName,symbolKind:R.kind,filePath:R.filePath,oldName:R.oldName,oldFilePath:null,fingerprint:m?.fingerprint??null,changedAt:V,isFullIndex:A,indexRunId:Y})}for(let R of l){let m=K.get(`${R.filePath}::${R.name}`),B=s(R.filePath,this.opts.boundaries);C.push({project:B,changeType:"moved",symbolName:R.name,symbolKind:R.kind,filePath:R.filePath,oldName:null,oldFilePath:R.oldFilePath,fingerprint:m?.fingerprint??null,changedAt:V,isFullIndex:A,indexRunId:Y})}if(C.length)try{w.transaction(()=>{x.insertBatch(C)})}catch(R){this.logger.error("[IndexCoordinator] changelog insert failed:",R)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let R=new Date(Date.now()-2592000000).toISOString();try{for(let m of this.opts.boundaries)x.pruneOlderThan(m.project,R)}catch(m){this.logger.error("[IndexCoordinator] changelog pruning failed:",m)}}}return{indexedFiles:O.length,removedFiles:Q.length,totalSymbols:H,totalRelations:T,totalAnnotations:Z,durationMs:Date.now()-g,changedFiles:O.map((V)=>V.filePath),deletedFiles:[...Q],failedFiles:q,changedSymbols:E,renamedSymbols:P.renamed.map((V)=>({oldName:V.oldName,newName:V.newName,filePath:V.filePath,kind:V.kind,isExported:Boolean(K.get(`${V.filePath}::${V.newName}`)?.isExported)})),movedSymbols:l.map((V)=>({name:V.name,oldFilePath:V.oldFilePath,newFilePath:V.filePath,kind:V.kind,isExported:Boolean(V.isExported)})),changedRelations:y}}fireCallbacks(u){for(let _ of this.callbacks)try{_(u)}catch(g){this.logger.error("[IndexCoordinator] onIndexed callback threw:",g)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let u=this.pendingEvents.splice(0);this.startIndex(u,!1).catch((_)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",_))}}}function w0(u){try{return process.kill(u,0),!0}catch(_){if(typeof _==="object"&&_&&"code"in _)return _.code!=="ESRCH";return!0}}function O0(u){let _=new Date(u).getTime();return Number.isNaN(_)?0:_}function ug(u,_,g={}){let $=g.now??Date.now,J=g.isAlive??w0,z=g.staleAfterSeconds??60,w=g.instanceId;return u.immediateTransaction(()=>{let O=u.selectOwner();if(!O)return u.insertOwner(_,w),"owner";let Q=Math.floor(($()-O0(O.heartbeat_at))/1000),U=J(O.pid);if(U&&w&&O.instance_id&&O.instance_id!==w&&O.pid!==_)return u.replaceOwner(_,w),"owner";if(U&&Q<z)return"reader";return u.replaceOwner(_,w),"owner"})}function _g(u,_){u.deleteOwner(_)}function gg(u,_){u.touchOwner(_)}class ju{#u;#_=new Map;constructor(u){this.#u=Math.max(1,u)}get size(){return this.#_.size}has(u){return this.#_.has(u)}get(u){if(!this.#_.has(u))return;let _=this.#_.get(u);return this.#_.delete(u),this.#_.set(u,_),_}set(u,_){if(this.#_.has(u))this.#_.delete(u);if(this.#_.set(u,_),this.#_.size>this.#u){let g=this.#_.keys().next().value;if(g!==void 0)this.#_.delete(g)}}delete(u){return this.#_.delete(u)}clear(){this.#_.clear()}}class Z_{lru;constructor(u=500){this.lru=new ju(u)}get(u){return this.lru.get(u)}set(u,_){this.lru.set(u,_)}invalidate(u){this.lru.delete(u)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function X_(u){let{symbolRepo:_,project:g,query:$}=u,J=$.project??g,z=$.limit??100,w={kind:$.kind,filePath:$.filePath,isExported:$.isExported,project:J,limit:z,resolvedType:$.resolvedType};if($.text)if($.exact)w.exactName=$.text;else{let Q=Du($.text);if(Q)w.ftsQuery=Q}if($.decorator)w.decorator=$.decorator;if($.regex)w.regex=$.regex;return _.searchByQuery(w).map((Q)=>{let U=Q.name.indexOf(".");return{id:Q.id,filePath:Q.filePath,kind:Q.kind,name:Q.name,memberName:U>=0?Q.name.slice(U+1):null,span:{start:{line:Q.startLine,column:Q.startColumn},end:{line:Q.endLine,column:Q.endColumn}},isExported:Q.isExported===1,signature:Q.signature,fingerprint:Q.fingerprint,detail:Q.detailJson?(()=>{try{return JSON.parse(Q.detailJson)}catch{return{}}})():{}}})}function K_(u){let{relationRepo:_,project:g,query:$}=u;if($.srcFilePath&&$.srcFilePathPattern)throw new N("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if($.dstFilePath&&$.dstFilePathPattern)throw new N("validation","dstFilePath and dstFilePathPattern are mutually exclusive");let J=$.project??g,z=$.limit??500,w=!!($.srcFilePathPattern||$.dstFilePathPattern),O=w?Number.MAX_SAFE_INTEGER:z,U=_.searchRelations({srcFilePath:$.srcFilePath,srcSymbolName:$.srcSymbolName,dstFilePath:$.dstFilePath,dstSymbolName:$.dstSymbolName,dstProject:$.dstProject,type:$.type,project:J,limit:O}).map((W)=>{let Y;if(W.metaJson)try{Y=JSON.parse(W.metaJson)}catch{}return{type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,dstProject:W.dstProject,metaJson:W.metaJson??void 0,meta:Y}});if($.srcFilePathPattern||$.dstFilePathPattern){let W=$.srcFilePathPattern?new Bun.Glob($.srcFilePathPattern):null,Y=$.dstFilePathPattern?new Bun.Glob($.dstFilePathPattern):null;U=U.filter((X)=>(!W||W.match(X.srcFilePath))&&(!Y||Y.match(X.dstFilePath)))}if(w&&U.length>z)U=U.slice(0,z);return U}import{findInFiles as z0,Lang as N0}from"@ast-grep/napi";async function M_(u){if(u.filePaths.length===0)return[];let _=[];return await z0(N0.TypeScript,{paths:u.filePaths,matcher:{rule:{pattern:u.pattern}}},(g,$)=>{if(g){console.warn("[patternSearch] findInFiles callback error:",g);return}for(let J of $){let z=J.range();_.push({filePath:J.getRoot().filename(),startLine:z.start.line+1,endLine:z.end.line+1,matchedText:J.text()})}}),_}import c from"typescript";import{isErr as A0}from"@zipbul/result";import Wu from"typescript";import W0 from"path";import{err as H_}from"@zipbul/result";function U0(u){try{return F_("fs").readFileSync(u,"utf-8")}catch{return}}function V0(u){try{return F_("fs").readFileSync(u,"utf-8")}catch{return}}class du{#u;#_;#g=!1;__testing__;constructor(u,_){this.#u=u,this.#_=_,this.__testing__={host:_}}static create(u,_={}){let g=_.readConfigFile??U0,$=_.resolveNonTrackedFile??V0,J=W0.dirname(u),z=g(u);if(z===void 0)return H_(new N("semantic",`tsconfig not found: ${u}`));let w=Wu.parseJsonText(u,z),O=w.parseDiagnostics;if(O&&O.length>0){let Y=O.map((X)=>Wu.flattenDiagnosticMessageText(X.messageText,`
8
+ `)).join("; ");return H_(new N("semantic",`tsconfig parse error: ${Y}`))}let Q=Wu.parseJsonSourceFileConfigFileContent(w,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(Y)=>g(Y)!==void 0||$(Y)!==void 0,readFile:(Y)=>g(Y)??$(Y)},J);if(Q.errors.length>0){let Y=Q.errors.filter((X)=>X.category===Wu.DiagnosticCategory.Error&&X.code!==18003);if(Y.length>0){let X=Y.map((K)=>Wu.flattenDiagnosticMessageText(K.messageText,`
9
+ `)).join("; ");return H_(new N("semantic",`tsconfig compile error: ${X}`))}}let U=new $g(Q.fileNames,Q.options,J,$),W=Wu.createLanguageService(U);return new du(W,U)}get isDisposed(){return this.#g}getProgram(){this.#J();let u=this.#u.getProgram();if(!u)throw Error("TscProgram: LanguageService returned null Program");return u}getChecker(){return this.#J(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#J(),this.#u}notifyFileChanged(u,_){if(this.#g)return;this.#_.updateFile(u,_)}removeFile(u){if(this.#g)return;this.#_.removeFile(u)}dispose(){if(this.#g)return;this.#g=!0,this.#u.dispose()}#J(){if(this.#g)throw Error("TscProgram is disposed")}}class $g{#u;#_;#g;#J;#$=new Map;constructor(u,_,g,$){this.#u=new Set(u),this.#_=_,this.#g=g,this.#J=$}updateFile(u,_){let g=this.#$.get(u);if(g)g.version+=1,g.content=_;else this.#$.set(u,{version:1,content:_})}removeFile(u){this.#$.delete(u),this.#u.delete(u)}getScriptFileNames(){let u=[...this.#$.keys()];return[...[...this.#u].filter((g)=>!this.#$.has(g)),...u]}getScriptVersion(u){let _=this.#$.get(u);return _?String(_.version):"0"}getScriptSnapshot(u){let _=this.#$.get(u);if(_)return Wu.ScriptSnapshot.fromString(_.content);let g=this.#J(u);if(g!==void 0)return Wu.ScriptSnapshot.fromString(g);return}getCurrentDirectory(){return this.#g}getCompilationSettings(){return this.#_}getDefaultLibFileName(u){return Wu.getDefaultLibFilePath(u)}fileExists(u){if(this.#$.has(u))return!0;return this.#J(u)!==void 0}readFile(u){let _=this.#$.get(u);if(_)return _.content;return this.#J(u)}}import a from"typescript";import Y0 from"typescript";function wu(u,_){if(_<0||_>=u.getEnd())return;function g($){let J=$.getStart(u,!1),z=$.getEnd();if(_<J||_>=z)return;let w;return Y0.forEachChild($,(O)=>{if(!w)w=g(O)}),w??$}return g(u)}var B_=8;function Z0(u){return!!(u.flags&a.TypeFlags.Object)&&!!(u.objectFlags&a.ObjectFlags.Reference)}function Fu(u,_,g=0){let $=u.typeToString(_),J=_.flags,z=!!(J&a.TypeFlags.Union),w=!!(J&a.TypeFlags.Intersection),O;if(g<B_&&Z0(_)){let Y=u.getTypeArguments(_);if(Y.length>0)O=Y}let Q=!!(J&a.TypeFlags.TypeParameter)||O!==void 0&&O.length>0,U;if(z&&g<B_)U=_.types.map((Y)=>Fu(u,Y,g+1));else if(w&&g<B_)U=_.types.map((Y)=>Fu(u,Y,g+1));let W;if(O&&O.length>0)W=O.map((Y)=>Fu(u,Y,g+1));return{text:$,flags:J,isUnion:z,isIntersection:w,isGeneric:Q,members:U,typeArguments:W}}function X0(u){return a.isFunctionDeclaration(u)||a.isVariableDeclaration(u)||a.isClassDeclaration(u)||a.isInterfaceDeclaration(u)||a.isTypeAliasDeclaration(u)||a.isEnumDeclaration(u)||a.isMethodDeclaration(u)||a.isPropertyDeclaration(u)||a.isPropertySignature(u)||a.isMethodSignature(u)}class L_{program;constructor(u){this.program=u}collectAt(u,_){let g=this.program.getProgram(),$=this.program.getChecker();if(_<0)return null;let J=g.getSourceFile(u);if(!J)return null;if(_>=J.getEnd())return null;let z=wu(J,_);if(!z)return null;if(!a.isIdentifier(z)&&!a.isTypeNode(z))return null;try{let w=$.getTypeAtLocation(z);return Fu($,w)}catch{return null}}isAssignableTo(u,_,g,$){let J=this.program.getChecker(),z=this.program.getProgram(),w=z.getSourceFile(u);if(!w)return null;let O=wu(w,_);if(!O||!a.isIdentifier(O))return null;let Q=z.getSourceFile(g);if(!Q)return null;let U=wu(Q,$);if(!U||!a.isIdentifier(U))return null;try{let W=J.getTypeAtLocation(O),Y=J.getTypeAtLocation(U);return J.isTypeAssignableTo(W,Y)}catch{return null}}isAssignableToType(u,_,g,$){let J=this.program.getChecker(),w=this.program.getProgram().getSourceFile(u);if(!w)return null;let O=wu(w,_);if(!O||!a.isIdentifier(O)&&!a.isTypeNode(O))return null;let Q=`${u}.__gildash_probe__.ts`,U=`declare const __gildash_probe__: ${g};`;this.program.notifyFileChanged(Q,U);try{let W=J.getTypeAtLocation(O),X=this.program.getProgram().getSourceFile(Q);if(!X)return null;let K=this.program.getChecker(),I=X.statements[0];if(!I||!a.isVariableStatement(I))return null;let D=I.declarationList.declarations[0];if(!D)return null;let k=K.getTypeAtLocation(D.name);if($?.anyConstituent&&W.isUnion())return W.types.some((j)=>K.isTypeAssignableTo(j,k));return K.isTypeAssignableTo(W,k)}catch{return null}finally{this.program.removeFile(Q)}}collectFile(u){let _=new Map,g=this.program.getProgram(),$=this.program.getChecker(),J=g.getSourceFile(u);if(!J)return _;function z(w){if(X0(w)&&w.name&&a.isIdentifier(w.name)){let O=w.name;try{let Q=$.getTypeAtLocation(O),U=O.getStart(J);_.set(U,Fu($,Q))}catch{}}a.forEachChild(w,z)}return z(J),_}}import Zu from"typescript";var K0=1000,M0=1;function H0(u){let _=u.declarations?.[0],g=_?.getSourceFile(),$=_?Zu.getNameOfDeclaration(_):void 0;return{name:u.getName(),filePath:g?.fileName??"",position:$?.getStart(g,!1)??_?.getStart(g,!1)??0}}function cu(u,_=0){let g=u.declarations?.[0],$=g?.getSourceFile(),J=g?Zu.getNameOfDeclaration(g):void 0,z=$?.fileName??"",w=J?.getStart($,!1)??g?.getStart($,!1)??0,O={name:u.getName(),filePath:z,position:w},Q=u;if(Q.parent)O.parent=H0(Q.parent);if(_<M0){let U=u.flags,W=!!(U&Zu.SymbolFlags.Enum),Y=!!(U&(Zu.SymbolFlags.NamespaceModule|Zu.SymbolFlags.ValueModule)),X=!!(U&(Zu.SymbolFlags.Class|Zu.SymbolFlags.Interface));if(W&&u.exports&&u.exports.size>0){let K=[];u.exports.forEach((I)=>{K.push(cu(I,_+1))}),O.members=K}else if(X&&u.members&&u.members.size>0){let K=[];u.members.forEach((I)=>{K.push(cu(I,_+1))}),O.members=K}if(Y&&u.exports&&u.exports.size>0){let K=[];u.exports.forEach((I)=>{K.push(cu(I,_+1))}),O.exports=K}}return O}class I_{#u;#_;#g=new Map;constructor(u,_=K0){this.#u=u,this.#_=new ju(_)}get(u,_){if(this.#u.isDisposed)return null;let g=`${u}:${_}`,$=this.#_.get(g);if($!==void 0)return $;let z=this.#u.getProgram().getSourceFile(u);if(!z)return null;let w=wu(z,_);if(!w||!Zu.isIdentifier(w))return null;let Q=this.#u.getChecker().getSymbolAtLocation(w);if(!Q)return null;let U=cu(Q);this.#_.set(g,U);let W=this.#g.get(u);if(!W)W=new Set,this.#g.set(u,W);return W.add(g),U}invalidate(u){let _=this.#g.get(u);if(_){for(let g of _)this.#_.delete(g);this.#g.delete(u)}}clear(){this.#_.clear(),this.#g.clear()}}import B0 from"typescript";class D_{#u;constructor(u){this.#u=u}findAt(u,_){if(this.#u.isDisposed)return[];let g=this.#u.getProgram(),$=g.getSourceFile(u);if(!$)return[];let J=wu($,_);if(!J||!B0.isIdentifier(J))return[];let w=this.#u.getLanguageService().findReferences(u,_);if(!w||w.length===0)return[];let O=[];for(let Q of w)for(let U of Q.references){let W=g.getSourceFile(U.fileName);if(!W)continue;let{line:Y,character:X}=W.getLineAndCharacterOfPosition(U.textSpan.start);O.push({filePath:U.fileName,position:U.textSpan.start,line:Y+1,column:X,isDefinition:U.isDefinition??!1,isWrite:U.isWriteAccess??!1})}return O}}import i from"typescript";function L0(u,_){let g=wu(u,_);if(!g)return;if(Jg(g))return g;let $=g.parent;for(let J=0;J<5&&$;J++){if(Jg($))return $;$=$.parent}return g}function Jg(u){return i.isClassDeclaration(u)||i.isClassExpression(u)||i.isFunctionDeclaration(u)||i.isFunctionExpression(u)||i.isArrowFunction(u)||i.isVariableDeclaration(u)||i.isObjectLiteralExpression(u)}function Qg(u){if(i.isClassDeclaration(u)||i.isClassExpression(u))return"class";if(i.isFunctionDeclaration(u)||i.isFunctionExpression(u)||i.isArrowFunction(u))return"function";if(i.isObjectLiteralExpression(u))return"object";if(i.isVariableDeclaration(u)&&u.initializer)return Qg(u.initializer);return"class"}function I0(u,_){if(i.isClassDeclaration(u)||i.isFunctionDeclaration(u))return u.name?.getText(_)??"";if(i.isClassExpression(u))return u.name?.getText(_)??"";if(i.isVariableDeclaration(u)&&i.isIdentifier(u.name))return u.name.getText(_);if(i.isFunctionExpression(u))return u.name?.getText(_)??"";if(i.isArrowFunction(u)&&u.parent&&i.isVariableDeclaration(u.parent)){if(i.isIdentifier(u.parent.name))return u.parent.name.getText(_)}if(i.isObjectLiteralExpression(u)&&u.parent&&i.isVariableDeclaration(u.parent)){if(i.isIdentifier(u.parent.name))return u.parent.name.getText(_)}return""}function D0(u){if(!i.isClassDeclaration(u)&&!i.isClassExpression(u))return!1;let _=u.heritageClauses;if(!_)return!1;return _.some((g)=>g.token===i.SyntaxKind.ImplementsKeyword)}class A_{#u;constructor(u){this.#u=u}findAt(u,_){if(this.#u.isDisposed)return[];let g=this.#u.getProgram(),$=g.getSourceFile(u);if(!$)return[];let J=wu($,_);if(!J||!i.isIdentifier(J))return[];let w=this.#u.getLanguageService().getImplementationAtPosition(u,_);if(!w||w.length===0)return[];let O=[];for(let Q of w){if(Q.kind===i.ScriptElementKind.interfaceElement||Q.kind===i.ScriptElementKind.typeElement)continue;let U=g.getSourceFile(Q.fileName);if(!U)continue;let W=L0(U,Q.textSpan.start);if(!W)continue;let Y=Qg(W),X=I0(W,U),K=D0(W);O.push({filePath:Q.fileName,symbolName:X,position:Q.textSpan.start,kind:Y,isExplicit:K})}return O}}function wg(u){return c.canHaveModifiers(u)&&c.getModifiers(u)?.some((_)=>_.kind===c.SyntaxKind.ExportKeyword)===!0}function C0(u){if(c.isFunctionDeclaration(u))return"function";if(c.isClassDeclaration(u))return"class";if(c.isInterfaceDeclaration(u))return"interface";if(c.isTypeAliasDeclaration(u))return"type";if(c.isEnumDeclaration(u))return"enum";if(c.isVariableDeclaration(u))return"const";if(c.isVariableStatement(u))return"const";return"unknown"}function Og(u){if(u>=97&&u<=122)return!0;if(u>=65&&u<=90)return!0;if(u>=48&&u<=57)return!0;if(u===95||u===36)return!0;return!1}class ru{#u;#_;#g;#J;#$;#w=!1;constructor(u,_,g,$,J){this.#u=u,this.#_=_,this.#g=g,this.#J=$,this.#$=J}static create(u,_={}){let g=du.create(u,{readConfigFile:_.readConfigFile,resolveNonTrackedFile:_.resolveNonTrackedFile});if(A0(g))return g;let $=g,J=_.typeCollector??new L_($),z=_.symbolGraph??new I_($),w=_.referenceResolver??new D_($),O=_.implementationFinder??new A_($);return new ru($,J,z,w,O)}get isDisposed(){return this.#w}collectTypeAt(u,_){return this.#Q(),this.#_.collectAt(u,_)}collectFileTypes(u){return this.#Q(),this.#_.collectFile(u)}findReferences(u,_){return this.#Q(),this.#J.findAt(u,_)}findImplementations(u,_){return this.#Q(),this.#$.findAt(u,_)}isTypeAssignableTo(u,_,g,$){return this.#Q(),this.#_.isAssignableTo(u,_,g,$)}isTypeAssignableToType(u,_,g,$){return this.#Q(),this.#_.isAssignableToType(u,_,g,$)}getSymbolNode(u,_){return this.#Q(),this.#g.get(u,_)}getModuleInterface(u){this.#Q();let _=this.#_.collectFile(u),g=[],J=this.#u.getProgram().getSourceFile(u);if(!J)return{filePath:u,exports:g};function z(w){if(c.isVariableStatement(w)&&wg(w)){for(let O of w.declarationList.declarations)if(c.isIdentifier(O.name)){let Q=O.name.getStart(J),U=_.get(Q)??null;g.push({name:O.name.text,kind:"const",resolvedType:U})}return}if((c.isFunctionDeclaration(w)||c.isClassDeclaration(w)||c.isInterfaceDeclaration(w)||c.isTypeAliasDeclaration(w)||c.isEnumDeclaration(w))&&wg(w)&&w.name){let O=w.name,Q=O.getStart(J),U=_.get(Q)??null;g.push({name:O.text,kind:C0(w),resolvedType:U});return}c.forEachChild(w,z)}return z(J),{filePath:u,exports:g}}notifyFileChanged(u,_){if(this.#w)return;this.#u.notifyFileChanged(u,_),this.#g.invalidate(u)}notifyFileDeleted(u){if(this.#w)return;this.#u.removeFile(u),this.#g.invalidate(u)}lineColumnToPosition(u,_,g){this.#Q();let $=this.#u.getProgram().getSourceFile(u);if(!$)return null;try{return c.getPositionOfLineAndCharacter($,_-1,g)}catch{return null}}findNamePosition(u,_,g){this.#Q();let $=this.#u.getProgram().getSourceFile(u);if(!$)return null;let J=$.getFullText(),z=_;while(z<J.length){let w=J.indexOf(g,z);if(w<0)return null;let O=w>0?J.charCodeAt(w-1):32,Q=w+g.length<J.length?J.charCodeAt(w+g.length):32;if(!Og(O)&&!Og(Q))return w;z=w+1}return null}getDiagnostics(u,_){this.#Q();let g=this.#u.getProgram(),$=g.getSourceFile(u);if(!$)return[];let J={[c.DiagnosticCategory.Error]:"error",[c.DiagnosticCategory.Warning]:"warning",[c.DiagnosticCategory.Suggestion]:"suggestion",[c.DiagnosticCategory.Message]:"suggestion"};return((_?.preEmit)?c.getPreEmitDiagnostics(g,$):g.getSemanticDiagnostics($)).map((w)=>{let O=1,Q=0;if(w.file&&w.start!==void 0){let U=c.getLineAndCharacterOfPosition(w.file,w.start);O=U.line+1,Q=U.character}return{filePath:w.file?.fileName??u,line:O,column:Q,message:c.flattenDiagnosticMessageText(w.messageText,`
10
+ `),code:w.code,category:J[w.category]??"error"}})}dispose(){if(this.#w)return;this.#w=!0,this.#u.dispose(),this.#g.clear()}#Q(){if(this.#w)throw Error("SemanticLayer is disposed")}}import{eq as Hu,and as zg,sql as S0}from"drizzle-orm";var Ng=80;class C_{db;constructor(u){this.db=u}insertBatch(u,_,g){if(!g.length)return;let $=g.map((J)=>({project:u,filePath:_,tag:J.tag,value:J.value,source:J.source,symbolName:J.symbolName,startLine:J.startLine,startColumn:J.startColumn,endLine:J.endLine,endColumn:J.endColumn,indexedAt:J.indexedAt}));for(let J=0;J<$.length;J+=Ng)this.db.drizzleDb.insert(Qu).values($.slice(J,J+Ng)).run()}deleteFileAnnotations(u,_){this.db.drizzleDb.delete(Qu).where(zg(Hu(Qu.project,u),Hu(Qu.filePath,_))).run()}search(u){return this.db.drizzleDb.select().from(Qu).where(zg(u.project?Hu(Qu.project,u.project):void 0,u.tag?Hu(Qu.tag,u.tag):void 0,u.filePath?Hu(Qu.filePath,u.filePath):void 0,u.symbolName?Hu(Qu.symbolName,u.symbolName):void 0,u.source?Hu(Qu.source,u.source):void 0,u.ftsQuery?S0`${Qu.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${u.ftsQuery})`:void 0)).limit(u.limit).all()}}import{eq as Ru,and as Wg,sql as nu,gt as R0,gte as k0}from"drizzle-orm";var Ug=80;class S_{db;constructor(u){this.db=u}insertBatch(u){if(!u.length)return;let _=u.map((g)=>({project:g.project,changeType:g.changeType,symbolName:g.symbolName,symbolKind:g.symbolKind,filePath:g.filePath,oldName:g.oldName,oldFilePath:g.oldFilePath,fingerprint:g.fingerprint,changedAt:g.changedAt,isFullIndex:g.isFullIndex,indexRunId:g.indexRunId}));for(let g=0;g<_.length;g+=Ug)this.db.drizzleDb.insert($u).values(_.slice(g,g+Ug)).run()}getSince(u){return this.db.drizzleDb.select().from($u).where(Wg(Ru($u.project,u.project),k0($u.changedAt,u.since),u.symbolName?Ru($u.symbolName,u.symbolName):void 0,u.changeTypes?.length?nu`${$u.changeType} IN (${nu.join(u.changeTypes.map((_)=>nu`${_}`),nu`, `)})`:void 0,u.filePath?Ru($u.filePath,u.filePath):void 0,u.includeFullIndex?void 0:Ru($u.isFullIndex,0),u.indexRunId?Ru($u.indexRunId,u.indexRunId):void 0,u.afterId?R0($u.id,u.afterId):void 0)).orderBy($u.id).limit(u.limit).all()}pruneOlderThan(u,_){return this.db.drizzleDb.delete($u).where(Wg(Ru($u.project,u),nu`${$u.changedAt} < ${_}`)).run().changes}}function Vg(u){let{annotationRepo:_,project:g,query:$}=u,J=$.project??g,z=$.limit??100,w;if($.text){let Q=Du($.text);if(Q)w=Q}return _.search({project:J,tag:$.tag,filePath:$.filePath,symbolName:$.symbolName,source:$.source,ftsQuery:w,limit:z}).map((Q)=>({tag:Q.tag,value:Q.value,source:Q.source,filePath:Q.filePath,symbolName:Q.symbolName,span:{start:{line:Q.startLine,column:Q.startColumn},end:{line:Q.endLine,column:Q.endColumn}}}))}class au{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(u){this.options=u}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let _=[this.options.project,...this.options.additionalProjects??[]].flatMap((g)=>[...this.options.relationRepo.getByType(g,"imports"),...this.options.relationRepo.getByType(g,"type-references"),...this.options.relationRepo.getByType(g,"re-exports")]);for(let g of _){let{srcFilePath:$,dstFilePath:J}=g;if(!this.adjacencyList.has($))this.adjacencyList.set($,new Set);if(this.adjacencyList.get($).add(J),!this.adjacencyList.has(J))this.adjacencyList.set(J,new Set);if(!this.reverseAdjacencyList.has(J))this.reverseAdjacencyList.set(J,new Set);this.reverseAdjacencyList.get(J).add($)}}patchFiles(u,_,g){let $=new Set([...u,..._]);for(let J of $){let z=this.adjacencyList.get(J);if(z){for(let O of z)this.reverseAdjacencyList.get(O)?.delete(J);z.clear()}let w=this.reverseAdjacencyList.get(J);if(w){for(let O of w)this.adjacencyList.get(O)?.delete(J);w.clear()}}for(let J of _)this.adjacencyList.delete(J),this.reverseAdjacencyList.delete(J);for(let J of u){let z=g(J);for(let w of z){if(!this.adjacencyList.has(w.srcFilePath))this.adjacencyList.set(w.srcFilePath,new Set);if(this.adjacencyList.get(w.srcFilePath).add(w.dstFilePath),!this.adjacencyList.has(w.dstFilePath))this.adjacencyList.set(w.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(w.dstFilePath))this.reverseAdjacencyList.set(w.dstFilePath,new Set);this.reverseAdjacencyList.get(w.dstFilePath).add(w.srcFilePath)}}}getDependencies(u){return Array.from(this.adjacencyList.get(u)??[])}getDependents(u){return Array.from(this.reverseAdjacencyList.get(u)??[])}getTransitiveDependents(u){let _=new Set,g=[u];while(g.length>0){let $=g.shift();for(let J of this.reverseAdjacencyList.get($)??[])if(!_.has(J))_.add(J),g.push(J)}return Array.from(_)}hasCycle(){let u=new Set,_=new Set;for(let g of this.adjacencyList.keys()){if(u.has(g))continue;let $=[{node:g,entered:!1}];while($.length>0){let J=$.pop();if(J.entered){_.delete(J.node);continue}if(_.has(J.node))return!0;if(u.has(J.node))continue;u.add(J.node),_.add(J.node),$.push({node:J.node,entered:!0});for(let z of this.adjacencyList.get(J.node)??[]){if(_.has(z))return!0;if(!u.has(z))$.push({node:z,entered:!1})}}}return!1}getAffectedByChange(u){let _=new Set;for(let g of u)for(let $ of this.getTransitiveDependents(g))_.add($);return Array.from(_)}getAdjacencyList(){let u=new Map;for(let[_,g]of this.adjacencyList)u.set(_,Array.from(g));return u}getTransitiveDependencies(u){let _=new Set,g=[u];while(g.length>0){let $=g.shift();for(let J of this.adjacencyList.get($)??[])if(!_.has(J))_.add(J),g.push(J)}return Array.from(_)}getCyclePaths(u){let _=u?.maxCycles??1/0;if(_<=0)return[];let g=new Map;for(let[$,J]of this.adjacencyList)g.set($,Array.from(J));return n0(g,_)}}var T0=(u,_)=>u.localeCompare(_);function q0(u){let _=u.length>1&&u[0]===u[u.length-1]?u.slice(0,-1):[...u];if(_.length===0)return[];let g=_;for(let $=1;$<_.length;$++){let J=_.slice($).concat(_.slice(0,$));if(J.join("::")<g.join("::"))g=J}return[...g]}function R_(u,_,g){let $=q0(g);if($.length===0)return!1;let J=$.join("->");if(u.has(J))return!1;return u.add(J),_.push($),!0}function j0(u){let _=0,g=[],$=new Set,J=new Map,z=new Map,w=[],O=(Q)=>{J.set(Q,_),z.set(Q,_),_+=1,g.push(Q),$.add(Q);for(let U of u.get(Q)??[])if(!J.has(U))O(U),z.set(Q,Math.min(z.get(Q)??0,z.get(U)??0));else if($.has(U))z.set(Q,Math.min(z.get(Q)??0,J.get(U)??0));if(z.get(Q)===J.get(Q)){let U=[],W="";do W=g.pop()??"",$.delete(W),U.push(W);while(W!==Q&&g.length>0);w.push(U)}};for(let Q of u.keys())if(!J.has(Q))O(Q);return{components:w}}function F0(u,_,g){let $=[],J=new Set,z=[...u].sort(T0),w=(O,Q,U)=>{Q.delete(O);let W=U.get(O);if(!W)return;for(let Y of W)if(Q.has(Y))w(Y,Q,U);W.clear()};for(let O=0;O<z.length&&$.length<g;O++){let Q=z[O]??"",U=new Set(z.slice(O)),W=new Set,Y=new Map,X=[],K=(D)=>(_.get(D)??[]).filter((k)=>U.has(k)),I=(D)=>{if($.length>=g)return!0;let k=!1;X.push(D),W.add(D);for(let j of K(D)){if($.length>=g)break;if(j===Q)R_(J,$,X.concat(Q)),k=!0;else if(!W.has(j)){if(I(j))k=!0}}if(k)w(D,W,Y);else for(let j of K(D)){let x=Y.get(j)??new Set;x.add(D),Y.set(j,x)}return X.pop(),k};I(Q)}return $}function n0(u,_){let{components:g}=j0(u),$=[],J=new Set;for(let z of g){if($.length>=_)break;if(z.length===0)continue;if(z.length===1){let Q=z[0]??"";if((u.get(Q)??[]).includes(Q))R_(J,$,[Q,Q]);continue}let w=_-$.length,O=F0(z,u,w);for(let Q of O){if($.length>=_)break;R_(J,$,Q)}}return $}var G0=15000;function su(u){u.graphCache=null,u.graphCacheKey=null,u.graphCacheBuiltAt=null}function Bu(u,_){let g=_??"__cross__";if(u.graphCache&&u.graphCacheBuiltAt!==null){if(Date.now()-u.graphCacheBuiltAt>G0)u.graphCache=null,u.graphCacheKey=null,u.graphCacheBuiltAt=null}if(u.graphCache&&u.graphCacheKey===g)return u.graphCache;let $=new au({relationRepo:u.relationRepo,project:_??u.defaultProject,additionalProjects:_?void 0:u.boundaries?.map((J)=>J.project)});return $.build(),u.graphCache=$,u.graphCacheKey=g,u.graphCacheBuiltAt=Date.now(),$}function Yg(u,_,g,$=1e4){if(u.closed)throw new N("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:g??u.defaultProject,query:{srcFilePath:_,type:"imports",project:g??u.defaultProject,limit:$}}).map((J)=>J.dstFilePath)}catch(J){if(J instanceof N)throw J;throw new N("search","Gildash: getDependencies failed",{cause:J})}}function Zg(u,_,g,$=1e4){if(u.closed)throw new N("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:g??u.defaultProject,query:{dstFilePath:_,type:"imports",project:g??u.defaultProject,limit:$}}).map((J)=>J.srcFilePath)}catch(J){if(J instanceof N)throw J;throw new N("search","Gildash: getDependents failed",{cause:J})}}async function Xg(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");try{return Bu(u,g).getAffectedByChange(_)}catch($){if($ instanceof N)throw $;throw new N("search","Gildash: getAffected failed",{cause:$})}}async function Kg(u,_){if(u.closed)throw new N("closed","Gildash: instance is closed");try{return Bu(u,_).hasCycle()}catch(g){if(g instanceof N)throw g;throw new N("search","Gildash: hasCycle failed",{cause:g})}}async function Mg(u,_){if(u.closed)throw new N("closed","Gildash: instance is closed");try{return Bu(u,_).getAdjacencyList()}catch(g){if(g instanceof N)throw g;throw new N("search","Gildash: getImportGraph failed",{cause:g})}}async function Hg(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");try{return Bu(u,g).getTransitiveDependencies(_)}catch($){if($ instanceof N)throw $;throw new N("search","Gildash: getTransitiveDependencies failed",{cause:$})}}async function Bg(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");try{return Bu(u,g).getTransitiveDependents(_)}catch($){if($ instanceof N)throw $;throw new N("search","Gildash: getTransitiveDependents failed",{cause:$})}}async function Lg(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");try{return Bu(u,_).getCyclePaths(g)}catch($){if($ instanceof N)throw $;throw new N("search","Gildash: getCyclePaths failed",{cause:$})}}async function Ig(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");try{let $=Bu(u,g);return{filePath:_,fanIn:$.getDependents(_).length,fanOut:$.getDependencies(_).length}}catch($){if($ instanceof N)throw $;throw new N("search","Gildash: getFanMetrics failed",{cause:$})}}var b0=30000,Dg=15000,y0=10;function f0(u,_){return(g)=>{for(let $ of u.onFileChangedCallbacks)try{$(g)}catch(J){u.logger.error("[Gildash] onFileChanged callback threw:",J)}if(_.handleWatcherEvent?.(g),u.semanticLayer)if(g.eventType==="delete")try{u.semanticLayer.notifyFileDeleted(g.filePath)}catch($){u.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",$);for(let J of u.onErrorCallbacks)try{J($ instanceof N?$:new N("semantic","semantic notifyFileDeleted failed",{cause:$}))}catch{}}else u.readFileFn(g.filePath).then(($)=>{try{u.semanticLayer?.notifyFileChanged(g.filePath,$)}catch(J){u.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",J);for(let z of u.onErrorCallbacks)try{z(J instanceof N?J:new N("semantic","semantic notifyFileChanged failed",{cause:J}))}catch{}}}).catch(($)=>{u.logger.error("[Gildash] failed to read file for semantic layer",g.filePath,$);try{u.semanticLayer?.notifyFileDeleted(g.filePath)}catch(J){u.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",J)}})}}async function P0(u){if(!u.semanticLayer)return;let _=u.fileRepo.getAllFiles(u.defaultProject);await Promise.all(_.map(async(g)=>{try{let $=vu.resolve(u.projectRoot,g.filePath),J=await u.readFileFn($);u.semanticLayer?.notifyFileChanged($,J)}catch{}}))}async function Ag(u,_){let g=u.coordinatorFactory?u.coordinatorFactory():new Y_({projectRoot:u.projectRoot,boundaries:u.boundaries,extensions:u.extensions,ignorePatterns:u.ignorePatterns,dbConnection:u.db,parseCache:u.parseCache,fileRepo:u.fileRepo,symbolRepo:u.symbolRepo,relationRepo:u.relationRepo,annotationRepo:u.annotationRepo??void 0,changelogRepo:u.changelogRepo??void 0,logger:u.logger});u.coordinator=g;for(let $ of u.onIndexedCallbacks)g.onIndexed($);if(g.onIndexed(($)=>{let J=$.changedFiles.length+$.deletedFiles.length;if(u.graphCache&&J>0&&J<100){let z=u.relationRepo;u.graphCache.patchFiles($.changedFiles,$.deletedFiles,(w)=>{return[u.defaultProject,...u.boundaries.map((Q)=>Q.project)].flatMap((Q)=>z.getByType(Q,"imports").concat(z.getByType(Q,"type-references")).concat(z.getByType(Q,"re-exports"))).filter((Q)=>Q.srcFilePath===w||Q.dstFilePath===w).map((Q)=>({srcFilePath:Q.srcFilePath,dstFilePath:Q.dstFilePath}))}),u.graphCacheBuiltAt=Date.now()}else su(u)}),_.isWatchMode){let $=u.watcherFactory?u.watcherFactory():new Q_({projectRoot:u.projectRoot,ignorePatterns:u.ignorePatterns,extensions:u.extensions},void 0,u.logger);await $.start(f0(u,g)).then((J)=>{if(Gu(J))throw J.data}),u.watcher=$,u.timer=setInterval(()=>{u.updateHeartbeatFn(u.db,process.pid)},b0)}await g.fullIndex(),await P0(u)}function m0(u,_){let g=["SIGTERM","SIGINT","beforeExit"];for(let $ of g){let J=()=>{_().catch((z)=>u.logger.error("[Gildash] close error during signal",$,z))};if($==="beforeExit")process.on("beforeExit",J);else process.on($,J);u.signalHandlers.push([$,J])}}async function Cg(u){let{projectRoot:_,extensions:g=[".ts",".mts",".cts"],ignorePatterns:$=["**/node_modules/**"],parseCacheCapacity:J=500,logger:z=console,existsSyncFn:w=E0,dbConnectionFactory:O,watcherFactory:Q,coordinatorFactory:U,repositoryFactory:W,acquireWatcherRoleFn:Y=ug,releaseWatcherRoleFn:X=_g,updateHeartbeatFn:K=gg,discoverProjectsFn:I=Pu,parseSourceFn:D=qu,extractSymbolsFn:k=Cu,extractRelationsFn:j=pu,symbolSearchFn:x=X_,relationSearchFn:G=K_,patternSearchFn:Z=M_,loadTsconfigPathsFn:M=Tu,readFileFn:H=async(P)=>Bun.file(P).text(),unlinkFn:T=async(P)=>{await Bun.file(P).unlink()},watchMode:q,semantic:S,semanticLayerFactory:F}=u;if(!vu.isAbsolute(_))throw new N("validation",`Gildash: projectRoot must be an absolute path, got: "${_}"`);if(!w(_))throw new N("validation",`Gildash: projectRoot does not exist: "${_}"`);let y=O?O():new u_({projectRoot:_}),E=y.open();if(Gu(E))throw E.data;try{let P=await I(_),gu=P[0]?.project??vu.basename(_),e=W?W():(()=>{let t=y;return{fileRepo:new __(t),symbolRepo:new g_(t),relationRepo:new $_(t),parseCache:new Z_(J)}})(),l=W?null:y,V=l?new C_(l):null,A=l?new S_(l):null,C=q??!0,R=crypto.randomUUID(),m;if(C)m=await Promise.resolve(Y(y,process.pid,{instanceId:R}));else m="owner";let B={projectRoot:_,extensions:g,ignorePatterns:$,logger:z,defaultProject:gu,role:m,db:y,symbolRepo:e.symbolRepo,relationRepo:e.relationRepo,fileRepo:e.fileRepo,parseCache:e.parseCache,annotationRepo:V,changelogRepo:A,annotationSearchFn:Vg,releaseWatcherRoleFn:X,parseSourceFn:D,extractSymbolsFn:k,extractRelationsFn:j,symbolSearchFn:x,relationSearchFn:G,patternSearchFn:Z,readFileFn:H,unlinkFn:T,existsSyncFn:w,acquireWatcherRoleFn:Y,updateHeartbeatFn:K,watcherFactory:Q,coordinatorFactory:U,instanceId:R,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:P,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(mu(_),B.tsconfigPaths=await M(_),S){let t=vu.join(_,"tsconfig.json");try{if(F)B.semanticLayer=F(t);else{let n=ru.create(t);if(Gu(n))throw n.data;B.semanticLayer=n}}catch(n){if(n instanceof N)throw n;throw new N("semantic","Gildash: semantic layer creation failed",{cause:n})}}if(m==="owner")await Ag(B,{isWatchMode:C});else{let t=0,n=async()=>{try{let h=await Promise.resolve(B.acquireWatcherRoleFn(B.db,process.pid,{instanceId:B.instanceId}));if(t=0,h==="owner"){B.role="owner";for(let b of B.onRoleChangedCallbacks)try{b("owner")}catch(d){B.logger.error("[Gildash] onRoleChanged callback threw:",d)}clearInterval(B.timer),B.timer=null;try{await Ag(B,{isWatchMode:!0})}catch(b){if(B.logger.error("[Gildash] owner promotion failed, reverting to reader",b),B.role="reader",B.timer!==null)clearInterval(B.timer),B.timer=null;if(B.watcher){let d=await B.watcher.close();if(Gu(d))B.logger.error("[Gildash] watcher close error during promotion rollback",d.data);B.watcher=null}if(B.coordinator)await B.coordinator.shutdown().catch((d)=>B.logger.error("[Gildash] coordinator shutdown error during promotion rollback",d)),B.coordinator=null;try{B.releaseWatcherRoleFn(B.db,process.pid)}catch(d){B.logger.error("[Gildash] failed to release watcher role during promotion rollback",d)}B.timer=setInterval(n,Dg)}}}catch(h){t++;let b=h instanceof N?h:new N("watcher","Gildash: healthcheck error",{cause:h});for(let d of B.onErrorCallbacks)try{d(b)}catch(Uu){B.logger.error("[Gildash] onError callback threw:",Uu)}if(B.logger.error("[Gildash] healthcheck error",h),t>=y0)B.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(B.timer),B.timer=null,tu(B).catch((d)=>B.logger.error("[Gildash] close error during healthcheck shutdown",d))}};B.timer=setInterval(n,Dg)}if(C)m0(B,()=>tu(B));return B}catch(P){if(y.close(),P instanceof N)throw P;throw new N("store","Gildash: initialization failed",{cause:P})}}async function tu(u,_){if(u.closed)return;u.closed=!0;let g=[];for(let[$,J]of u.signalHandlers)if($==="beforeExit")process.off("beforeExit",J);else process.off($,J);if(u.signalHandlers=[],u.semanticLayer){try{u.semanticLayer.dispose()}catch($){g.push($ instanceof Error?$:Error(String($)))}u.semanticLayer=null}if(u.coordinator)try{await u.coordinator.shutdown()}catch($){g.push($ instanceof Error?$:Error(String($)))}if(u.watcher){let $=await u.watcher.close();if(Gu($))g.push($.data)}if(u.timer!==null)clearInterval(u.timer),u.timer=null;try{u.releaseWatcherRoleFn(u.db,process.pid)}catch($){g.push($ instanceof Error?$:Error(String($)))}try{u.db.close()}catch($){g.push($ instanceof Error?$:Error(String($)))}if(_?.cleanup)for(let $ of["","-wal","-shm"])try{await u.unlinkFn(vu.join(u.projectRoot,Vu,bu+$))}catch{}if(g.length>0)throw new N("close","Gildash: one or more errors occurred during close()",{cause:g})}import{isErr as Sg}from"@zipbul/result";function Rg(u,_,g,$){if(u.closed)throw new N("closed","Gildash: instance is closed");let J=u.parseSourceFn(_,g,$);if(Sg(J))throw J.data;return u.parseCache.set(_,J),J}async function kg(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");let $=new Map,J=[];return await Promise.all(_.map(async(z)=>{try{let w=await u.readFileFn(z),O=u.parseSourceFn(z,w,g);if(!Sg(O))$.set(z,O);else J.push({filePath:z,error:O.data})}catch(w){J.push({filePath:z,error:w instanceof Error?w:Error(String(w))})}})),{parsed:$,failures:J}}function Tg(u,_){if(u.closed)throw new N("closed","Gildash: instance is closed");return u.parseCache.get(_)}function qg(u,_){if(u.closed)throw new N("closed","Gildash: instance is closed");return u.extractSymbolsFn(_)}function jg(u,_){if(u.closed)throw new N("closed","Gildash: instance is closed");return u.extractRelationsFn(_.program,_.filePath,u.tsconfigPaths??void 0)}import Fg from"path";function ng(u,_){if(u.closed)throw new N("closed","Gildash: instance is closed");try{return u.symbolRepo.getStats(_??u.defaultProject)}catch(g){if(g instanceof N)throw g;throw new N("store","Gildash: getStats failed",{cause:g})}}function k_(u,_){if(u.closed)throw new N("closed","Gildash: instance is closed");try{return u.symbolSearchFn({symbolRepo:u.symbolRepo,project:u.defaultProject,query:_})}catch(g){if(g instanceof N)throw g;throw new N("search","Gildash: searchSymbols failed",{cause:g})}}function Gg(u,_){if(u.closed)throw new N("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:u.defaultProject,query:_})}catch(g){if(g instanceof N)throw g;throw new N("search","Gildash: searchRelations failed",{cause:g})}}function vg(u,_){if(u.closed)throw new N("closed","Gildash: instance is closed");try{return u.symbolSearchFn({symbolRepo:u.symbolRepo,project:void 0,query:_})}catch(g){if(g instanceof N)throw g;throw new N("search","Gildash: searchAllSymbols failed",{cause:g})}}function Eg(u,_){if(u.closed)throw new N("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:void 0,query:_})}catch(g){if(g instanceof N)throw g;throw new N("search","Gildash: searchAllRelations failed",{cause:g})}}function bg(u,_){if(u.closed)throw new N("closed","Gildash: instance is closed");try{return u.fileRepo.getAllFiles(_??u.defaultProject)}catch(g){if(g instanceof N)throw g;throw new N("store","Gildash: listIndexedFiles failed",{cause:g})}}function yg(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:g??u.defaultProject,query:{srcFilePath:_,dstFilePath:_,limit:1e4}})}catch($){if($ instanceof N)throw $;throw new N("search","Gildash: getInternalRelations failed",{cause:$})}}function fg(u,_,g,$){if(u.closed)throw new N("closed","Gildash: instance is closed");try{let J=$??u.defaultProject,z=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:J,query:{text:_,exact:!0,filePath:g,limit:1}});if(z.length===0)return null;let w=z[0],O=w.detail,Q={...w,members:Array.isArray(O.members)?O.members:void 0,jsDoc:typeof O.jsDoc==="string"?O.jsDoc:void 0,parameters:typeof O.parameters==="string"?O.parameters:void 0,returnType:typeof O.returnType==="string"?O.returnType:void 0,heritage:Array.isArray(O.heritage)?O.heritage:void 0,decorators:Array.isArray(O.decorators)?O.decorators:void 0,typeParameters:typeof O.typeParameters==="string"?O.typeParameters:void 0};if(u.semanticLayer)try{let U=Fg.isAbsolute(g)?g:Fg.resolve(u.projectRoot,g),W=u.semanticLayer.lineColumnToPosition(U,w.span.start.line,w.span.start.column);if(W!==null){let Y=u.semanticLayer.findNamePosition(U,W,w.name)??W,X=u.semanticLayer.collectTypeAt(U,Y);if(X)Q.resolvedType=X}}catch{}return Q}catch(J){if(J instanceof N)throw J;throw new N("search","Gildash: getFullSymbol failed",{cause:J})}}function Pg(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");try{let $=g??u.defaultProject,J=u.fileRepo.getFile($,_);if(!J)throw new N("search",`Gildash: file '${_}' is not in the index`);let z=u.symbolRepo.getFileSymbols($,_),w=u.relationRepo.getOutgoing($,_);return{filePath:J.filePath,lineCount:J.lineCount??0,size:J.size,symbolCount:z.length,exportedSymbolCount:z.filter((O)=>O.isExported).length,relationCount:w.length}}catch($){if($ instanceof N)throw $;throw new N("store","Gildash: getFileStats failed",{cause:$})}}function mg(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");try{return u.fileRepo.getFile(g??u.defaultProject,_)}catch($){if($ instanceof N)throw $;throw new N("store","Gildash: getFileInfo failed",{cause:$})}}function hg(u,_,g){return k_(u,{filePath:_,project:g??void 0,limit:1e4})}function xg(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");try{let J=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:g??u.defaultProject,query:{filePath:_,isExported:!0}}).map((z)=>({name:z.name,kind:z.kind,parameters:z.detail.parameters??void 0,returnType:z.detail.returnType??void 0,jsDoc:z.detail.jsDoc??void 0}));return{filePath:_,exports:J}}catch($){if($ instanceof N)throw $;throw new N("search","Gildash: getModuleInterface failed",{cause:$})}}import p from"path";function Eu(u,_,g,$){let J=$??u.defaultProject,z=p.isAbsolute(g)?p.relative(u.projectRoot,g):g,w=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:J,query:{text:_,exact:!0,filePath:z,limit:1}});if(w.length===0)return null;let O=w[0],Q=p.isAbsolute(g)?g:p.resolve(u.projectRoot,g),U=u.semanticLayer.lineColumnToPosition(Q,O.span.start.line,O.span.start.column);if(U===null)return null;let W=u.semanticLayer.findNamePosition(Q,U,O.name)??U;return{sym:O,position:W,absPath:Q}}function ig(u,_,g,$){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{let J=Eu(u,_,g,$);if(!J)return null;return u.semanticLayer.collectTypeAt(J.absPath,J.position)}catch(J){if(J instanceof N)throw J;throw new N("search","Gildash: getResolvedType failed",{cause:J})}}function pg(u,_,g,$){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{let J=Eu(u,_,g,$);if(!J)throw new N("search",`Gildash: symbol '${_}' not found in '${g}'`);return u.semanticLayer.findReferences(J.absPath,J.position)}catch(J){if(J instanceof N)throw J;throw new N("search","Gildash: getSemanticReferences failed",{cause:J})}}function lg(u,_,g,$){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{let J=Eu(u,_,g,$);if(!J)throw new N("search",`Gildash: symbol '${_}' not found in '${g}'`);return u.semanticLayer.findImplementations(J.absPath,J.position)}catch(J){if(J instanceof N)throw J;throw new N("search","Gildash: getImplementations failed",{cause:J})}}function dg(u,_,g,$,J,z){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{let w=Eu(u,_,g,z);if(!w)throw new N("search",`Gildash: source symbol '${_}' not found in '${g}'`);let O=Eu(u,$,J,z);if(!O)throw new N("search",`Gildash: target symbol '${$}' not found in '${J}'`);return u.semanticLayer.isTypeAssignableTo(w.absPath,w.position,O.absPath,O.position)}catch(w){if(w instanceof N)throw w;throw new N("semantic","Gildash: isTypeAssignableTo failed",{cause:w})}}function cg(u,_){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{let g=p.isAbsolute(_)?_:p.resolve(u.projectRoot,_);return u.semanticLayer.collectFileTypes(g)}catch(g){if(g instanceof N)throw g;throw new N("semantic","Gildash: getFileTypes failed",{cause:g})}}function rg(u,_,g,$){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{let J=p.isAbsolute(_)?_:p.resolve(u.projectRoot,_),z=u.semanticLayer.lineColumnToPosition(J,g,$);if(z===null)return null;return u.semanticLayer.collectTypeAt(J,z)}catch(J){if(J instanceof N)throw J;throw new N("semantic","Gildash: getResolvedTypeAt failed",{cause:J})}}function ag(u,_){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{let g=p.isAbsolute(_.source.filePath)?_.source.filePath:p.resolve(u.projectRoot,_.source.filePath),$=p.isAbsolute(_.target.filePath)?_.target.filePath:p.resolve(u.projectRoot,_.target.filePath),J=u.semanticLayer.lineColumnToPosition(g,_.source.line,_.source.column);if(J===null)return null;let z=u.semanticLayer.lineColumnToPosition($,_.target.line,_.target.column);if(z===null)return null;return u.semanticLayer.isTypeAssignableTo(g,J,$,z)}catch(g){if(g instanceof N)throw g;throw new N("semantic","Gildash: isTypeAssignableToAt failed",{cause:g})}}function sg(u,_){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{return u.semanticLayer.getModuleInterface(_)}catch(g){if(g instanceof N)throw g;throw new N("search","Gildash: getSemanticModuleInterface failed",{cause:g})}}function tg(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{let $=p.isAbsolute(_)?_:p.resolve(u.projectRoot,_);return u.semanticLayer.collectTypeAt($,g)}catch($){if($ instanceof N)throw $;throw new N("semantic","Gildash: getResolvedTypeAtPosition failed",{cause:$})}}function og(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{let $=p.isAbsolute(_)?_:p.resolve(u.projectRoot,_);return u.semanticLayer.findReferences($,g)}catch($){if($ instanceof N)throw $;throw new N("semantic","Gildash: getSemanticReferencesAtPosition failed",{cause:$})}}function eg(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{let $=p.isAbsolute(_)?_:p.resolve(u.projectRoot,_);return u.semanticLayer.findImplementations($,g)}catch($){if($ instanceof N)throw $;throw new N("semantic","Gildash: getImplementationsAtPosition failed",{cause:$})}}function u$(u,_,g,$,J){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{let z=p.isAbsolute(_)?_:p.resolve(u.projectRoot,_),w=p.isAbsolute($)?$:p.resolve(u.projectRoot,$);return u.semanticLayer.isTypeAssignableTo(z,g,w,J)}catch(z){if(z instanceof N)throw z;throw new N("semantic","Gildash: isTypeAssignableToAtPosition failed",{cause:z})}}function _$(u,_,g,$,J){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{let z=p.isAbsolute(_)?_:p.resolve(u.projectRoot,_);return u.semanticLayer.isTypeAssignableToType(z,g,$,J)}catch(z){if(z instanceof N)throw z;throw new N("semantic","Gildash: isTypeAssignableToType failed",{cause:z})}}function g$(u,_,g,$){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{let J=p.isAbsolute(_)?_:p.resolve(u.projectRoot,_);return u.semanticLayer.lineColumnToPosition(J,g,$)}catch(J){if(J instanceof N)throw J;throw new N("semantic","Gildash: lineColumnToPosition failed",{cause:J})}}function $$(u,_,g,$){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{let J=p.isAbsolute(_)?_:p.resolve(u.projectRoot,_);return u.semanticLayer.findNamePosition(J,g,$)}catch(J){if(J instanceof N)throw J;throw new N("semantic","Gildash: findNamePosition failed",{cause:J})}}function J$(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{let $=p.isAbsolute(_)?_:p.resolve(u.projectRoot,_);return u.semanticLayer.getSymbolNode($,g)}catch($){if($ instanceof N)throw $;throw new N("semantic","Gildash: getSymbolNode failed",{cause:$})}}function Q$(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new N("semantic","Gildash: semantic layer is not enabled");try{let $=p.isAbsolute(_)?_:p.resolve(u.projectRoot,_);return u.semanticLayer.getDiagnostics($,g)}catch($){if($ instanceof N)throw $;throw new N("semantic","Gildash: getSemanticDiagnostics failed",{cause:$})}}function w$(u,_){let g=new Map(u.map((O)=>[`${O.name}::${O.filePath}`,O])),$=new Map(_.map((O)=>[`${O.name}::${O.filePath}`,O])),J=[],z=[],w=[];for(let[O,Q]of $){let U=g.get(O);if(!U)J.push(Q);else if(U.fingerprint!==Q.fingerprint)w.push({before:U,after:Q})}for(let[O,Q]of g)if(!$.has(O))z.push(Q);return{added:J,removed:z,modified:w}}function O$(u,_){if(u.onIndexedCallbacks.add(_),!u.coordinator)return()=>{u.onIndexedCallbacks.delete(_)};let g=u.coordinator.onIndexed(_);return()=>{u.onIndexedCallbacks.delete(_),g()}}async function z$(u){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.coordinator)throw new N("closed","Gildash: reindex() is not available for readers");try{let _=await u.coordinator.fullIndex();return su(u),_}catch(_){if(_ instanceof N)throw _;throw new N("index","Gildash: reindex failed",{cause:_})}}function N$(u,_,g,$){if(u.closed)throw new N("closed","Gildash: instance is closed");let J=$??u.defaultProject,z=new Set,w=[],O=_,Q=g;for(;;){let U=`${Q}::${O}`;if(z.has(U))return{originalName:O,originalFilePath:Q,reExportChain:w,circular:!0};z.add(U);let W=u.relationSearchFn({relationRepo:u.relationRepo,project:J,query:{type:"re-exports",srcFilePath:Q,limit:500}}),Y,X;for(let K of W){let I;if(K.metaJson)try{let k=JSON.parse(K.metaJson);if(Array.isArray(k.specifiers))I=k.specifiers}catch{}if(!I)continue;let D=I.find((k)=>k.exported===O);if(!D)continue;Y=K.dstFilePath,X=D.local;break}if(!Y||!X)return{originalName:O,originalFilePath:Q,reExportChain:w,circular:!1};w.push({filePath:Q,exportedAs:O}),Q=Y,O=X}}function W$(u,_){return u.onFileChangedCallbacks.add(_),()=>{u.onFileChangedCallbacks.delete(_)}}function U$(u,_){return u.onErrorCallbacks.add(_),()=>{u.onErrorCallbacks.delete(_)}}function V$(u,_){return u.onRoleChangedCallbacks.add(_),()=>{u.onRoleChangedCallbacks.delete(_)}}async function Y$(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");try{let $=g?.project??u.defaultProject,J=g?.filePaths?g.filePaths:u.fileRepo.getAllFiles($).map((z)=>z.filePath);return await u.patternSearchFn({pattern:_,filePaths:J})}catch($){if($ instanceof N)throw $;throw new N("search","Gildash: findPattern failed",{cause:$})}}async function Z$(u,_,g,$){if(u.closed)throw new N("closed","Gildash: instance is closed");try{let J=$??u.defaultProject,z=new Set,w=(O,Q,U)=>{let W=`${O}::${Q}`;if(z.has(W))return{symbolName:O,filePath:Q,kind:U,children:[]};z.add(W);let K=u.relationSearchFn({relationRepo:u.relationRepo,project:J,query:{srcFilePath:Q,srcSymbolName:O,limit:1000}}).filter((I)=>I.type==="extends"||I.type==="implements").filter((I)=>I.dstSymbolName!=null).map((I)=>w(I.dstSymbolName,I.dstFilePath,I.type));return{symbolName:O,filePath:Q,kind:U,children:K}};return w(_,g)}catch(J){if(J instanceof N)throw J;throw new N("search","Gildash: getHeritageChain failed",{cause:J})}}function X$(u,_){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.annotationRepo||!u.annotationSearchFn)return[];return u.annotationSearchFn({annotationRepo:u.annotationRepo,project:_.project??u.defaultProject,query:_})}function K$(u,_,g){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.changelogRepo)return[];let $=_ instanceof Date?_.toISOString():_,J=g?.project??u.defaultProject,z=g?.limit??1000;return u.changelogRepo.getSince({project:J,since:$,symbolName:g?.symbolName,changeTypes:g?.changeTypes,filePath:g?.filePath,includeFullIndex:g?.includeFullIndex,indexRunId:g?.indexRunId,afterId:g?.afterId,limit:z}).map((O)=>({changeType:O.changeType,symbolName:O.symbolName,symbolKind:O.symbolKind,filePath:O.filePath,oldName:O.oldName,oldFilePath:O.oldFilePath,fingerprint:O.fingerprint,changedAt:O.changedAt,isFullIndex:O.isFullIndex===1,indexRunId:O.indexRunId}))}function M$(u,_){if(u.closed)throw new N("closed","Gildash: instance is closed");if(!u.changelogRepo)return 0;let g=_ instanceof Date?_.toISOString():_,$=0,J=[u.defaultProject,...u.boundaries.map((w)=>w.project)],z=[...new Set(J)];for(let w of z)$+=u.changelogRepo.pruneOlderThan(w,g);return $}class T_{_ctx;get projectRoot(){return this._ctx.projectRoot}get role(){return this._ctx.role}get projects(){return[...this._ctx.boundaries]}constructor(u){this._ctx=u}static async open(u){let _=await Cg(u);return new T_(_)}async close(u){return tu(this._ctx,u)}parseSource(u,_,g){return Rg(this._ctx,u,_,g)}async batchParse(u,_){return kg(this._ctx,u,_)}getParsedAst(u){return Tg(this._ctx,u)}extractSymbols(u){return qg(this._ctx,u)}extractRelations(u){return jg(this._ctx,u)}getStats(u){return ng(this._ctx,u)}searchSymbols(u){return k_(this._ctx,u)}searchRelations(u){return Gg(this._ctx,u)}searchAllSymbols(u){return vg(this._ctx,u)}searchAllRelations(u){return Eg(this._ctx,u)}listIndexedFiles(u){return bg(this._ctx,u)}getInternalRelations(u,_){return yg(this._ctx,u,_)}getFullSymbol(u,_,g){return fg(this._ctx,u,_,g)}getFileStats(u,_){return Pg(this._ctx,u,_)}getFileInfo(u,_){return mg(this._ctx,u,_)}getSymbolsByFile(u,_){return hg(this._ctx,u,_)}getModuleInterface(u,_){return xg(this._ctx,u,_)}getDependencies(u,_,g=1e4){return Yg(this._ctx,u,_,g)}getDependents(u,_,g=1e4){return Zg(this._ctx,u,_,g)}async getAffected(u,_){return Xg(this._ctx,u,_)}async hasCycle(u){return Kg(this._ctx,u)}async getImportGraph(u){return Mg(this._ctx,u)}async getTransitiveDependencies(u,_){return Hg(this._ctx,u,_)}async getTransitiveDependents(u,_){return Bg(this._ctx,u,_)}async getCyclePaths(u,_){return Lg(this._ctx,u,_)}async getFanMetrics(u,_){return Ig(this._ctx,u,_)}getResolvedType(u,_,g){return ig(this._ctx,u,_,g)}getSemanticReferences(u,_,g){return pg(this._ctx,u,_,g)}getImplementations(u,_,g){return lg(this._ctx,u,_,g)}isTypeAssignableTo(u,_,g,$,J){return dg(this._ctx,u,_,g,$,J)}getSemanticModuleInterface(u){return sg(this._ctx,u)}getFileTypes(u){return cg(this._ctx,u)}getResolvedTypeAt(u,_,g){return rg(this._ctx,u,_,g)}isTypeAssignableToAt(u){return ag(this._ctx,u)}getResolvedTypeAtPosition(u,_){return tg(this._ctx,u,_)}getSemanticReferencesAtPosition(u,_){return og(this._ctx,u,_)}getImplementationsAtPosition(u,_){return eg(this._ctx,u,_)}isTypeAssignableToAtPosition(u,_,g,$){return u$(this._ctx,u,_,g,$)}isTypeAssignableToType(u,_,g,$){return _$(this._ctx,u,_,g,$)}lineColumnToPosition(u,_,g){return g$(this._ctx,u,_,g)}findNamePosition(u,_,g){return $$(this._ctx,u,_,g)}getSymbolNode(u,_){return J$(this._ctx,u,_)}getSemanticDiagnostics(u,_){return Q$(this._ctx,u,_)}diffSymbols(u,_){return w$(u,_)}onIndexed(u){return O$(this._ctx,u)}async reindex(){return z$(this._ctx)}resolveSymbol(u,_,g){return N$(this._ctx,u,_,g)}async findPattern(u,_){return Y$(this._ctx,u,_)}async getHeritageChain(u,_,g){return Z$(this._ctx,u,_,g)}onFileChanged(u){return W$(this._ctx,u)}onError(u){return U$(this._ctx,u)}onRoleChanged(u){return V$(this._ctx,u)}searchAnnotations(u){return X$(this._ctx,u)}getSymbolChanges(u,_){return K$(this._ctx,u,_)}pruneChangelog(u){return M$(this._ctx,u)}}export{X_ as symbolSearch,K_ as relationSearch,M_ as patternSearch,N as GildashError,T_ as Gildash,au as DependencyGraph};
@@ -12,13 +12,3 @@ export declare class GildashError extends Error {
12
12
  cause?: unknown;
13
13
  });
14
14
  }
15
- /**
16
- * Factory function that creates a {@link GildashError} value.
17
- *
18
- * @param type - One of the {@link GildashErrorType} variants.
19
- * @param message - Human-readable description of the error.
20
- * @param cause - Optional root cause (any value). When `undefined`, the `cause`
21
- * property is omitted from the returned object entirely.
22
- * @deprecated Use `new GildashError(type, message, { cause })` instead.
23
- */
24
- export declare function gildashError(type: GildashErrorType, message: string, cause?: unknown): GildashError;
@@ -1,6 +1,6 @@
1
1
  export { Gildash } from "./gildash";
2
2
  export type { GildashOptions, Logger, SymbolDiff, ModuleInterface, HeritageNode, FullSymbol, FileStats, FanMetrics, ResolvedSymbol } from "./gildash";
3
- export { GildashError, gildashError } from "./errors";
3
+ export { GildashError } from "./errors";
4
4
  export type { GildashErrorType } from "./errors";
5
5
  export { symbolSearch } from "./search/symbol-search";
6
6
  export type { SymbolSearchQuery, SymbolSearchResult } from "./search/symbol-search";
@@ -1,4 +1,4 @@
1
1
  import { type Result } from '@zipbul/result';
2
2
  import type { JsDocBlock } from '../extractor/types';
3
- import { type GildashError } from '../errors';
3
+ import { GildashError } from '../errors';
4
4
  export declare function parseJsDoc(commentText: string): Result<JsDocBlock, GildashError>;
@@ -2,5 +2,5 @@ import { type Result } from '@zipbul/result';
2
2
  import { parseSync as defaultParseSync } from 'oxc-parser';
3
3
  import type { ParserOptions } from 'oxc-parser';
4
4
  import type { ParsedFile } from './types';
5
- import { type GildashError } from '../errors';
5
+ import { GildashError } from '../errors';
6
6
  export declare function parseSource(filePath: string, sourceText: string, options?: ParserOptions, parseSyncFn?: typeof defaultParseSync): Result<ParsedFile, GildashError>;
@@ -46,8 +46,10 @@ export interface SymbolSearchResult {
46
46
  filePath: string;
47
47
  /** Kind of the symbol (function, class, variable, etc.). */
48
48
  kind: SymbolKind;
49
- /** Symbol name. */
49
+ /** Symbol name (qualified for members, e.g. `"ClassName.methodName"`). */
50
50
  name: string;
51
+ /** Unqualified member name (e.g. `"methodName"`), or `null` for top-level symbols. */
52
+ memberName: string | null;
51
53
  /** Source location span (start/end line and column). */
52
54
  span: {
53
55
  start: {
@@ -5,7 +5,7 @@
5
5
  * 하나의 facade로 통합한다.
6
6
  */
7
7
  import { type Result } from "@zipbul/result";
8
- import { type GildashError } from "../errors";
8
+ import { GildashError } from "../errors";
9
9
  import { type TscProgramOptions } from "./tsc-program";
10
10
  import { TypeCollector } from "./type-collector";
11
11
  import { SymbolGraph, type SymbolNode } from "./symbol-graph";
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import ts from "typescript";
11
11
  import { type Result } from "@zipbul/result";
12
- import { type GildashError } from "../errors";
12
+ import { GildashError } from "../errors";
13
13
  /**
14
14
  * Reads a file at `path` and returns its content, or `undefined` if missing.
15
15
  */
@@ -1,6 +1,6 @@
1
1
  import { type Result } from '@zipbul/result';
2
2
  import { type BunSQLiteDatabase } from 'drizzle-orm/bun-sqlite';
3
- import { type GildashError } from '../errors';
3
+ import { GildashError } from '../errors';
4
4
  import * as schema from './schema';
5
5
  export interface DbConnectionOptions {
6
6
  projectRoot: string;
@@ -2,7 +2,7 @@ import { type Result } from '@zipbul/result';
2
2
  import type { AsyncSubscription, SubscribeCallback } from "@parcel/watcher";
3
3
  import { subscribe as parcelSubscribe } from "@parcel/watcher";
4
4
  type SubscribeOptions = NonNullable<Parameters<typeof parcelSubscribe>[2]>;
5
- import { type GildashError } from "../errors";
5
+ import { GildashError } from "../errors";
6
6
  import type { FileChangeEvent, WatcherOptions } from "./types";
7
7
  import type { Logger } from "../gildash";
8
8
  type SubscribeFn = (directoryPath: string, callback: SubscribeCallback, options?: SubscribeOptions) => Promise<AsyncSubscription>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zipbul/gildash",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "TypeScript code indexing and dependency graph engine for Bun",
5
5
  "license": "MIT",
6
6
  "repository": {