@zipbul/gildash 0.9.3 → 0.10.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,9 +1,9 @@
1
1
  // @bun
2
- var g$=Object.defineProperty;var _$=(u)=>u;function $$(u,g){this[u]=_$.bind(null,g)}var N$=(u,g)=>{for(var _ in g)g$(u,_,{get:g[_],enumerable:!0,configurable:!0,set:$$.bind(g,_)})};var Sg=import.meta.require;import{isErr as Gu}from"@zipbul/result";import ju from"path";import{existsSync as M0}from"fs";import{err as Rg,isErr as W$}from"@zipbul/result";import{Database as Y$}from"bun:sqlite";import{mkdirSync as V$,unlinkSync as Tg,existsSync as kg}from"fs";import{dirname as U$,join as Fg}from"path";import{drizzle as X$}from"drizzle-orm/bun-sqlite";import{migrate as Z$}from"drizzle-orm/bun-sqlite/migrator";class U extends Error{type;constructor(u,g,_){super(g,_);this.type=u;this.name="GildashError"}}function e(u,g,_){return new U(u,g,_!==void 0?{cause:_}:void 0)}var Yu=".gildash",Eu="gildash.db";var cu={};N$(cu,{watcherOwner:()=>O$,symbols:()=>f,symbolChangelog:()=>uu,relations:()=>L,files:()=>p,annotations:()=>$u});import{sql as J$}from"drizzle-orm";import{sqliteTable as nu,text as F,integer as t,real as Q$,index as gu,primaryKey as w$,foreignKey as vu,check as z$}from"drizzle-orm/sqlite-core";var p=nu("files",{project:F("project").notNull(),filePath:F("file_path").notNull(),mtimeMs:Q$("mtime_ms").notNull(),size:t("size").notNull(),contentHash:F("content_hash").notNull(),updatedAt:F("updated_at").notNull(),lineCount:t("line_count")},(u)=>[w$({columns:[u.project,u.filePath]})]),f=nu("symbols",{id:t("id").primaryKey({autoIncrement:!0}),project:F("project").notNull(),filePath:F("file_path").notNull(),kind:F("kind").notNull(),name:F("name").notNull(),startLine:t("start_line").notNull(),startColumn:t("start_column").notNull(),endLine:t("end_line").notNull(),endColumn:t("end_column").notNull(),isExported:t("is_exported").notNull().default(0),signature:F("signature"),fingerprint:F("fingerprint"),detailJson:F("detail_json"),contentHash:F("content_hash").notNull(),indexedAt:F("indexed_at").notNull(),resolvedType:F("resolved_type"),structuralFingerprint:F("structural_fingerprint")},(u)=>[gu("idx_symbols_project_file").on(u.project,u.filePath),gu("idx_symbols_project_kind").on(u.project,u.kind),gu("idx_symbols_project_name").on(u.project,u.name),gu("idx_symbols_fingerprint").on(u.project,u.fingerprint),vu({columns:[u.project,u.filePath],foreignColumns:[p.project,p.filePath]}).onDelete("cascade")]),L=nu("relations",{id:t("id").primaryKey({autoIncrement:!0}),project:F("project").notNull(),type:F("type").notNull(),srcFilePath:F("src_file_path").notNull(),srcSymbolName:F("src_symbol_name"),dstProject:F("dst_project").notNull(),dstFilePath:F("dst_file_path").notNull(),dstSymbolName:F("dst_symbol_name"),metaJson:F("meta_json")},(u)=>[gu("idx_relations_src").on(u.project,u.srcFilePath),gu("idx_relations_dst").on(u.dstProject,u.dstFilePath),gu("idx_relations_type").on(u.project,u.type),gu("idx_relations_project_type_src").on(u.project,u.type,u.srcFilePath),vu({columns:[u.project,u.srcFilePath],foreignColumns:[p.project,p.filePath]}).onDelete("cascade"),vu({columns:[u.dstProject,u.dstFilePath],foreignColumns:[p.project,p.filePath]}).onDelete("cascade")]),$u=nu("annotations",{id:t("id").primaryKey({autoIncrement:!0}),project:F("project").notNull(),filePath:F("file_path").notNull(),tag:F("tag").notNull(),value:F("value").notNull().default(""),source:F("source").notNull(),symbolName:F("symbol_name"),startLine:t("start_line").notNull(),startColumn:t("start_column").notNull(),endLine:t("end_line").notNull(),endColumn:t("end_column").notNull(),indexedAt:F("indexed_at").notNull()},(u)=>[gu("idx_annotations_project_file").on(u.project,u.filePath),gu("idx_annotations_project_tag").on(u.project,u.tag),gu("idx_annotations_project_symbol").on(u.project,u.symbolName),vu({columns:[u.project,u.filePath],foreignColumns:[p.project,p.filePath]}).onDelete("cascade")]),uu=nu("symbol_changelog",{id:t("id").primaryKey({autoIncrement:!0}),project:F("project").notNull(),changeType:F("change_type").notNull(),symbolName:F("symbol_name").notNull(),symbolKind:F("symbol_kind").notNull(),filePath:F("file_path").notNull(),oldName:F("old_name"),oldFilePath:F("old_file_path"),fingerprint:F("fingerprint"),changedAt:F("changed_at").notNull(),isFullIndex:t("is_full_index").notNull().default(0),indexRunId:F("index_run_id").notNull()},(u)=>[gu("idx_changelog_project_changed_at").on(u.project,u.changedAt),gu("idx_changelog_project_name").on(u.project,u.symbolName),gu("idx_changelog_project_run").on(u.project,u.indexRunId)]),O$=nu("watcher_owner",{id:t("id").primaryKey(),pid:t("pid").notNull(),startedAt:F("started_at").notNull(),heartbeatAt:F("heartbeat_at").notNull(),instanceId:F("instance_id")},(u)=>[z$("watcher_owner_singleton",J$`${u.id} = 1`)]);class su{client=null;drizzle=null;dbPath;txDepth=0;constructor(u){this.dbPath=Fg(u.projectRoot,Yu,Eu)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{V$(U$(this.dbPath),{recursive:!0}),this.client=new Y$(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=X$(this.client,{schema:cu}),Z$(this.drizzle,{migrationsFolder:Fg(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)&&kg(this.dbPath)){this.closeClient(),Tg(this.dbPath);for(let _ of["-wal","-shm"]){let $=this.dbPath+_;if(kg($))Tg($)}let g=this.open();if(W$(g))return Rg(e("store",`Failed to recover database at ${this.dbPath}`,g.data));return g}return Rg(e("store",`Failed to open database at ${this.dbPath}`,u))}}close(){this.closeClient(),this.drizzle=null}transaction(u){let g=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return g.transaction(()=>u(this))()}finally{this.txDepth--}}let _=`sp_${this.txDepth++}`;g.run(`SAVEPOINT "${_}"`);try{let $=u(this);return g.run(`RELEASE SAVEPOINT "${_}"`),$}catch($){throw g.run(`ROLLBACK TO SAVEPOINT "${_}"`),g.run(`RELEASE SAVEPOINT "${_}"`),$}finally{this.txDepth--}}immediateTransaction(u){let g=this.requireClient();this.txDepth++,g.run("BEGIN IMMEDIATE");try{let _=u();return g.run("COMMIT"),_}catch(_){throw g.run("ROLLBACK"),_}finally{this.txDepth--}}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((g)=>g.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(u,g){let _=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(u,_,_,g??null)}replaceOwner(u,g){let _=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??null)}touchOwner(u){let g=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(g,u)}deleteOwner(u){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(u)}registerRegexpUdf(u){let g=u;if(typeof g.function!=="function")return;g.function.call(u,"regexp",(_,$)=>{try{return new RegExp(_).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 g=u.message.toLowerCase();return g.includes("malformed")||g.includes("corrupt")||g.includes("not a database")||g.includes("disk i/o error")||g.includes("sqlite_corrupt")}}import{eq as Su,and as qg}from"drizzle-orm";class ou{db;constructor(u){this.db=u}getFile(u,g){return this.db.drizzleDb.select().from(p).where(qg(Su(p.project,u),Su(p.filePath,g))).get()??null}upsertFile(u){this.db.drizzleDb.insert(p).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:[p.project,p.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(p).where(Su(p.project,u)).all()}getFilesMap(u){let g=this.getAllFiles(u),_=new Map;for(let $ of g)_.set($.filePath,$);return _}deleteFile(u,g){this.db.drizzleDb.delete(p).where(qg(Su(p.project,u),Su(p.filePath,g))).run()}}import{eq as r,and as Xu,sql as Pu,count as K$}from"drizzle-orm";function Hu(u){return u.replaceAll("\x00","").trim().split(/\s+/).map((g)=>g.trim()).filter((g)=>g.length>0).map((g)=>`"${g.replaceAll('"','""')}"*`).join(" ")}var Gg=50;class eu{db;constructor(u){this.db=u}replaceFileSymbols(u,g,_,$){if(this.db.drizzleDb.delete(f).where(Xu(r(f.project,u),r(f.filePath,g))).run(),!$.length)return;let N=new Date().toISOString(),z=$.map((w)=>({project:u,filePath:g,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:_,indexedAt:w.indexedAt??N,resolvedType:w.resolvedType??null,structuralFingerprint:w.structuralFingerprint??null}));for(let w=0;w<z.length;w+=Gg)this.db.drizzleDb.insert(f).values(z.slice(w,w+Gg)).run()}getFileSymbols(u,g){return this.db.drizzleDb.select().from(f).where(Xu(r(f.project,u),r(f.filePath,g))).all()}searchByName(u,g,_={}){let $=_.limit??50,N=Hu(g);if(!N)return[];return this.db.drizzleDb.select().from(f).where(Xu(Pu`${f.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${N})`,r(f.project,u),_.kind?r(f.kind,_.kind):void 0)).orderBy(f.name).limit($).all()}searchByKind(u,g){return this.db.drizzleDb.select().from(f).where(Xu(r(f.project,u),r(f.kind,g))).orderBy(f.name).all()}getStats(u){let g=this.db.drizzleDb.select({symbolCount:K$(),fileCount:Pu`COUNT(DISTINCT ${f.filePath})`}).from(f).where(r(f.project,u)).get();return{symbolCount:g?.symbolCount??0,fileCount:g?.fileCount??0}}getByFingerprint(u,g){return this.db.drizzleDb.select().from(f).where(Xu(r(f.project,u),r(f.fingerprint,g))).all()}deleteFileSymbols(u,g){this.db.drizzleDb.delete(f).where(Xu(r(f.project,u),r(f.filePath,g))).run()}searchByQuery(u){let g=this.db.drizzleDb.select().from(f).where(Xu(u.ftsQuery?Pu`${f.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${u.ftsQuery})`:void 0,u.exactName?r(f.name,u.exactName):void 0,u.project!==void 0?r(f.project,u.project):void 0,u.kind?r(f.kind,u.kind):void 0,u.filePath!==void 0?r(f.filePath,u.filePath):void 0,u.isExported!==void 0?r(f.isExported,u.isExported?1:0):void 0,u.decorator?Pu`${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?r(f.resolvedType,u.resolvedType):void 0)).orderBy(f.name);if(!u.regex)return g.limit(u.limit).all();let _;try{_=new RegExp(u.regex)}catch{throw new U("validation",`Invalid regex pattern: ${u.regex}`)}let $=[];for(let N of[5,20,100]){let z=u.limit*N,w=g.limit(z).all();if($=w.filter((Q)=>_.test(Q.name)),$.length>=u.limit||w.length<z)return $.slice(0,u.limit)}return $.slice(0,u.limit)}}import{eq as x,and as wu,isNull as jg,or as M$}from"drizzle-orm";class ug{db;constructor(u){this.db=u}replaceFileRelations(u,g,_){this.db.transaction(($)=>{if($.drizzleDb.delete(L).where(wu(x(L.project,u),x(L.srcFilePath,g))).run(),!_.length)return;for(let N of _)$.drizzleDb.insert(L).values({project:u,type:N.type??"unknown",srcFilePath:N.srcFilePath??g,srcSymbolName:N.srcSymbolName??null,dstProject:N.dstProject??u,dstFilePath:N.dstFilePath??"",dstSymbolName:N.dstSymbolName??null,metaJson:N.metaJson??null}).run()})}getOutgoing(u,g,_){if(_!==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(x(L.project,u),x(L.srcFilePath,g),M$(x(L.srcSymbolName,_),jg(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(x(L.project,u),x(L.srcFilePath,g))).all()}getIncoming(u){let{dstProject:g,dstFilePath:_}=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(x(L.dstProject,g),x(L.dstFilePath,_))).all()}getByType(u,g){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(x(L.project,u),x(L.type,g))).all()}deleteFileRelations(u,g){this.db.drizzleDb.delete(L).where(wu(x(L.project,u),x(L.srcFilePath,g))).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?x(L.project,u.project):void 0,u.srcFilePath!==void 0?x(L.srcFilePath,u.srcFilePath):void 0,u.srcSymbolName!==void 0?x(L.srcSymbolName,u.srcSymbolName):void 0,u.dstProject!==void 0?x(L.dstProject,u.dstProject):void 0,u.dstFilePath!==void 0?x(L.dstFilePath,u.dstFilePath):void 0,u.dstSymbolName!==void 0?x(L.dstSymbolName,u.dstSymbolName):void 0,u.type!==void 0?x(L.type,u.type):void 0)).limit(u.limit).all()}retargetRelations(u){let{dstProject:g,oldFile:_,oldSymbol:$,newFile:N,newSymbol:z,newDstProject:w}=u,Q=$===null?wu(x(L.dstProject,g),x(L.dstFilePath,_),jg(L.dstSymbolName)):wu(x(L.dstProject,g),x(L.dstFilePath,_),x(L.dstSymbolName,$)),J={dstFilePath:N,dstSymbolName:z};if(w!==void 0)J.dstProject=w;this.db.drizzleDb.update(L).set(J).where(Q).run()}}import{err as Eg}from"@zipbul/result";import{subscribe as n$}from"@parcel/watcher";import gg from"path";var H$=["**/.git/**",`**/${Yu}/**`,"**/dist/**","**/node_modules/**"],B$=new Set(["package.json","tsconfig.json"]);function L$(u){return u.replaceAll("\\","/")}function D$(u){if(u==="update")return"change";if(u==="create")return"create";return"delete"}class _g{#u;#g;#_;#N;#$;#J;constructor(u,g=n$,_=console){this.#g=u.projectRoot,this.#_=[...H$,...u.ignorePatterns??[]],this.#N=new Set((u.extensions??[".ts",".mts",".cts"]).map(($)=>$.toLowerCase())),this.#$=g,this.#J=_}async start(u){try{this.#u=await this.#$(this.#g,(g,_)=>{if(g){this.#J.error(e("watcher","Callback error",g));return}try{for(let $ of _){let N=L$(gg.relative(this.#g,$.path));if(N.startsWith(".."))continue;let z=gg.basename(N),w=gg.extname(N).toLowerCase();if(!B$.has(z)&&!this.#N.has(w))continue;if(N.endsWith(".d.ts"))continue;u({eventType:D$($.type),filePath:N})}}catch($){this.#J.error(e("watcher","Callback error",$))}},{ignore:this.#_})}catch(g){return Eg(e("watcher","Failed to subscribe watcher",g))}}async close(){if(!this.#u)return;try{await this.#u.unsubscribe(),this.#u=void 0}catch(u){return Eg(e("watcher","Failed to close watcher",u))}}}import $g from"path";import{promises as A$}from"fs";var I$=["**/node_modules/**","**/.git/**",`**/${Yu}/**`,"**/dist/**"];async function bu(u){let g=[];for await(let _ of A$.glob("**/package.json",{cwd:u,exclude:I$})){let $=$g.dirname(_).replaceAll("\\","/"),N=$g.join(u,_),z=await Bun.file(N).json(),w=typeof z?.name==="string"&&z.name.length>0?z.name:$g.basename($==="."?u:$);g.push({dir:$,project:w})}return g.sort((_,$)=>$.dir.length-_.dir.length),g}function l(u,g,_="default"){let $=u.replaceAll("\\","/");for(let N of g){if(N.dir===".")return N.project;if($===N.dir||$.startsWith(`${N.dir}/`))return N.project}return _}import vg from"path";var Vu=new Map;async function C$(u){let g=Bun.file(u);if(!await g.exists())return null;try{let _=await g.text(),$=Bun.JSONC.parse(_);return typeof $==="object"&&$!==null?$:null}catch{return null}}async function Ru(u){if(Vu.has(u))return Vu.get(u)??null;let g=vg.join(u,"tsconfig.json"),_=await C$(g);if(!_)return Vu.set(u,null),null;let $=typeof _.compilerOptions==="object"&&_.compilerOptions!==null?_.compilerOptions:null;if(!$)return Vu.set(u,null),null;let N=typeof $.baseUrl==="string"?$.baseUrl:null,z=typeof $.paths==="object"&&$.paths!==null?$.paths:null;if(!N&&!z)return Vu.set(u,null),null;let w=N?vg.resolve(u,N):u,Q=new Map;if(z)for(let[Y,O]of Object.entries(z)){if(!Array.isArray(O))continue;let W=O.filter((Z)=>typeof Z==="string");Q.set(Y,W)}let J={baseUrl:w,paths:Q};return Vu.set(u,J),J}function fu(u){if(u){Vu.delete(u);return}Vu.clear()}import Pg from"path";function yu(u,g){return Pg.relative(u,g).replaceAll("\\","/")}function Bu(u,g){return Pg.resolve(u,g)}function Ju(u){let g=Bun.hash.xxHash64(u);return BigInt.asUintN(64,BigInt(g)).toString(16).padStart(16,"0")}import{isErr as dg}from"@zipbul/result";import{err as S$}from"@zipbul/result";import{parseSync as R$}from"oxc-parser";function Tu(u,g,_,$=R$){try{let{program:N,errors:z,comments:w}=$(u,g,_);return{filePath:u,program:N,errors:z,comments:w,sourceText:g}}catch(N){return S$(e("parse",`Failed to parse file: ${u}`,N))}}import{promises as T$}from"fs";import{join as k$}from"path";async function bg(u){let{projectRoot:g,extensions:_,ignorePatterns:$,fileRepo:N}=u,z=N.getFilesMap(),w=new Set,Q=[],J=[],Y=$.map((W)=>new Bun.Glob(W));for await(let W of T$.glob("**/*",{cwd:g})){if(!_.some((V)=>W.endsWith(V)))continue;if(W.startsWith("node_modules/")||W.includes("/node_modules/"))continue;if(Y.some((V)=>V.match(W)))continue;w.add(W);let Z=k$(g,W),n=Bun.file(Z),{size:A,lastModified:D}=n,k=z.get(W);if(!k){let V=await n.text(),K=Ju(V);Q.push({filePath:W,contentHash:K,mtimeMs:D,size:A});continue}if(k.mtimeMs===D&&k.size===A){J.push({filePath:W,contentHash:k.contentHash,mtimeMs:D,size:A});continue}let G=await n.text(),i=Ju(G);if(i===k.contentHash)J.push({filePath:W,contentHash:i,mtimeMs:D,size:A});else Q.push({filePath:W,contentHash:i,mtimeMs:D,size:A})}let O=[];for(let W of z.keys())if(!w.has(W))O.push(W);return{changed:Q,unchanged:J,deleted:O}}function iu(u){let g=[0];for(let _=0;_<u.length;_++)if(u[_]===`
3
- `)g.push(_+1);return g}function Nu(u,g){let _=0,$=u.length-1;while(_<$){let N=_+$+1>>1;if(u[N]<=g)_=N;else $=N-1}return{line:_+1,column:g-u[_]}}import{err as F$}from"@zipbul/result";import{parse as q$}from"comment-parser";function mu(u){try{let g=u.trim();if(g.startsWith("/**"))g=g.slice(3);if(g.endsWith("*/"))g=g.slice(0,-2);let $=q$(`/** ${g} */`)[0]??{description:"",tags:[]};return{description:($.description??"").trim(),tags:($.tags??[]).map((N)=>({tag:N.tag??"",name:N.name??"",type:N.type??"",description:N.description??"",optional:N.optional??!1,...N.default!==void 0?{default:N.default}:{}}))}}catch(g){return F$(e("parse","Failed to parse JSDoc comment",g))}}import{isErr as G$}from"@zipbul/result";function Lu(u){let{program:g,sourceText:_,comments:$}=u,N=iu(_),z=$.filter((V)=>V.type==="Block"&&V.value.startsWith("*")).sort((V,K)=>V.end-K.end),w=g.body.map((V)=>V.start??0).sort((V,K)=>V-K);function Q(V,K){return{start:Nu(N,V),end:Nu(N,K)}}function J(V){let K=0,M=z.length-1,R=-1;while(K<=M){let C=K+M>>>1;if(z[C].end<=V)R=C,K=C+1;else M=C-1}if(R<0)return;let I=z[R];K=0,M=w.length-1;while(K<=M){let C=K+M>>>1,v=w[C];if(v<=I.end)K=C+1;else if(v>=V)M=C-1;else return}return`/*${I.value}*/`}function Y(V){if(!V)return;let K=V.typeAnnotation??V;return _.slice(K.start,K.end)}function O(V){if(!V||V.length===0)return[];return V.map((K)=>{let M=K.expression;if(!M)return{name:"unknown"};if(M.type==="CallExpression"){let R=M.callee?.name??M.callee?.property?.name??"unknown",I=(M.arguments??[]).map((C)=>_.slice(C.start,C.end));return{name:R,arguments:I.length>0?I:void 0}}if(M.type==="Identifier")return{name:M.name??"unknown"};return{name:_.slice(M.start,M.end)}})}function W(V){let K=V.type==="TSParameterProperty"?V.parameter:V;if(K?.type==="RestElement"){let X=`...${K.argument?.name??"unknown"}`,B=K.typeAnnotation,S=B?Y(B):void 0,H={name:X,isOptional:!1};if(S)H.type=S;return H}if(K?.type==="AssignmentPattern"){let{left:j,right:X}=K,B=j?.name??"unknown",S=j?.typeAnnotation,H=S?Y(S):void 0,P=_.slice(X.start,X.end),q=O(j?.decorators??[]),c={name:B,isOptional:!0,defaultValue:P};if(H)c.type=H;if(q.length>0)c.decorators=q;return c}let M=K?.name??K?.pattern?.name??"unknown",R=!!K?.optional,I=K?.typeAnnotation,C=I?Y(I):void 0,v=O(K?.decorators??[]),y={name:M,isOptional:R};if(C)y.type=C;if(v.length>0)y.decorators=v;return y}function Z(V,K){let M=[];if(K?.async)M.push("async");if(V.static)M.push("static");if(V.abstract)M.push("abstract");if(V.readonly)M.push("readonly");if(V.override)M.push("override");if(V.declare)M.push("declare");if(V.const)M.push("const");let R=V.accessibility;if(R==="private")M.push("private");else if(R==="protected")M.push("protected");else if(R==="public")M.push("public");return M}function n(V){let K=[];if(V.superClass){let R=_.slice(V.superClass.start,V.superClass.end);K.push({kind:"extends",name:R})}let M=V.implements??[];for(let R of M){let I=R.expression??R,C=_.slice(I.start,I.end);K.push({kind:"implements",name:C})}return K}function A(V){let K=[];for(let M of V.extends??[]){let R=M.expression??M,I=_.slice(R.start,R.end);K.push({kind:"extends",name:I})}return K}function D(V){let K=[];for(let M of V)if(M.type==="MethodDefinition"){let R=M.key?.name??"unknown",I=M.value,C=M.kind??"method",v=C==="constructor"?"constructor":C==="get"?"getter":C==="set"?"setter":"method",y=Z(M,I),j=(I?.params??[]).map(W),X=Y(I?.returnType),B={kind:"method",name:R,span:Q(M.start,M.end),isExported:!1,methodKind:v,modifiers:y,parameters:j.length>0?j:void 0,returnType:X};K.push(B)}else if(M.type==="PropertyDefinition"){let R=M.key?.name??"unknown",I=Z(M),C={kind:"property",name:R,span:Q(M.start,M.end),isExported:!1,modifiers:I};K.push(C)}return K}function k(V){let K=[];for(let M of V)if(M.type==="TSMethodSignature"){let R=M.key?.name??"unknown",I=(M.params??[]).map(W),C=Y(M.returnType);K.push({kind:"method",name:R,span:Q(M.start,M.end),isExported:!1,modifiers:[],methodKind:"method",parameters:I.length>0?I:void 0,returnType:C})}else if(M.type==="TSPropertySignature"){let R=M.key?.name??"unknown",I=Y(M.typeAnnotation),C={kind:"property",name:R,span:Q(M.start,M.end),isExported:!1,modifiers:M.readonly?["readonly"]:[],returnType:I};K.push(C)}return K}function G(V,K){let M=V.type??"";if(M==="FunctionDeclaration"){let R=V.id?.name??"default",I=(V.params??[]).map(W),C=Y(V.returnType),v=Z(V,V),y=O(V.decorators??[]),j=V.typeParameters?.params?.flatMap((B)=>{let S=B.name?.name;return S?[S]:[]})||void 0,X={kind:"function",name:R,span:Q(V.start,V.end),isExported:K,modifiers:v,parameters:I.length>0?I:void 0,returnType:C,decorators:y.length>0?y:void 0};if(j&&j.length>0)X.typeParameters=j;return X}if(M==="ClassDeclaration"||M==="ClassExpression"){let R=V.id?.name??"default",I=n(V),C=D(V.body?.body??[]),v=O(V.decorators??[]),y=Z(V,V),j=V.typeParameters?.params?.flatMap((B)=>{let S=B.name?.name;return S?[S]:[]})||void 0,X={kind:"class",name:R,span:Q(V.start,V.end),isExported:K,modifiers:y,heritage:I.length>0?I:void 0,members:C.length>0?C:void 0,decorators:v.length>0?v:void 0};if(j&&j.length>0)X.typeParameters=j;return X}if(M==="VariableDeclaration"){let R=[];for(let I of V.declarations??[]){let{id:C,init:v}=I;if(C?.type==="ObjectPattern"){for(let H of C.properties??[]){let P=H.value?.name??H.key?.name??"unknown";R.push({kind:"variable",name:P,span:Q(H.start??I.start,H.end??I.end),isExported:K,modifiers:[]})}continue}if(C?.type==="ArrayPattern"){for(let H of C.elements??[]){if(!H||H.type!=="Identifier")continue;let P=H.name??"unknown";R.push({kind:"variable",name:P,span:Q(H.start??I.start,H.end??I.end),isExported:K,modifiers:[]})}continue}let y=C?.name??"unknown",j="variable",X,B;if(v?.type==="FunctionExpression"||v?.type==="ArrowFunctionExpression")j="function",X=(v.params??[]).map(W),B=Y(v.returnType);let S=[];R.push({kind:j,name:y,span:Q(I.start,I.end),isExported:K,modifiers:S,parameters:X,returnType:B})}if(R.length===0)return null;if(R.length===1)return R[0];return R}if(M==="TSTypeAliasDeclaration")return{kind:"type",name:V.id?.name??"unknown",span:Q(V.start,V.end),isExported:K,modifiers:[]};if(M==="TSInterfaceDeclaration"){let R=V.id?.name??"unknown",I=A(V),C=k(V.body?.body??[]),v=V.typeParameters?.params?.flatMap((j)=>{let X=j.name?.name;return X?[X]:[]})||void 0,y={kind:"interface",name:R,span:Q(V.start,V.end),isExported:K,modifiers:[],heritage:I.length>0?I:void 0,members:C.length>0?C:void 0};if(v&&v.length>0)y.typeParameters=v;return y}if(M==="TSEnumDeclaration"){let R=V.id?.name??"unknown",I=Z(V),v=(V.body?.members??[]).map((y)=>({kind:"property",name:y.id?.name??y.id?.value??"unknown",span:Q(y.start,y.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:R,span:Q(V.start,V.end),isExported:K,modifiers:I,members:v.length>0?v:void 0}}return null}let i=[];for(let V of g.body){let K=null,M=V,R=typeof M.type==="string"?M.type:"";if(R==="ExportNamedDeclaration"){let C=V;if(C.declaration){if(K=G(C.declaration,!0),K&&!Array.isArray(K))K.span=Q(C.start,C.end);else if(Array.isArray(K))for(let v of K)v.span=Q(C.start,C.end)}}else if(R==="ExportDefaultDeclaration"){let C=V,v=C.declaration;if(v){if(K=G(v,!0),K&&!Array.isArray(K))K.name=v.id?.name??"default",K.isExported=!0,K.span=Q(C.start,C.end)}}else K=G(V,!1);let I=Array.isArray(K)?K:K?[K]:[];for(let C of I){let v=V.start??0,y=J(v);if(y){let j=mu(y);if(!G$(j))C.jsDoc=j}i.push(C)}}return i}function j$(u){if(u.kind==="function"||u.kind==="method"){let g=u.parameters?.length??0,_=u.modifiers.includes("async")?1:0;return`params:${g}|async:${_}`}return null}function E$(u){let g={};if(u.jsDoc)g.jsDoc=u.jsDoc;if(u.kind==="function"||u.kind==="method"){if(u.parameters!==void 0)g.parameters=u.parameters;if(u.returnType!==void 0)g.returnType=u.returnType}if(u.heritage?.length)g.heritage=u.heritage;if(u.decorators?.length)g.decorators=u.decorators;if(u.typeParameters?.length)g.typeParameters=u.typeParameters;if(u.modifiers?.length)g.modifiers=u.modifiers;if(u.members?.length)g.members=u.members.map((_)=>{let $=_.modifiers.find((N)=>N==="private"||N==="protected"||N==="public");return{name:_.name,kind:_.methodKind??_.kind,type:_.returnType,visibility:$,isStatic:_.modifiers.includes("static")||void 0,isReadonly:_.modifiers.includes("readonly")||void 0}});return Object.keys(g).length>0?JSON.stringify(g):null}function v$(u){let g=[u.kind];if(u.modifiers.length)g.push(`mod:${[...u.modifiers].sort().join(",")}`);if(u.typeParameters?.length)g.push(`tp:${u.typeParameters.length}`);if(u.heritage?.length){let _=[...u.heritage].sort(($,N)=>$.name.localeCompare(N.name)).map(($)=>`${$.kind}:${$.name}`).join(",");g.push(`her:${_}`)}if(u.decorators?.length)g.push(`dec:${[...u.decorators].map((_)=>_.name).sort().join(",")}`);if(u.methodKind)g.push(`mk:${u.methodKind}`);if(u.parameters)g.push(`p:${u.parameters.length}`);if(u.returnType)g.push(`rt:${u.returnType}`);if(u.members?.length){let _=u.members.map(($)=>`${$.kind}:${$.modifiers.join(",")}:${$.parameters?.length??""}:${$.returnType??""}`).sort().join(";");g.push(`mem:${u.members.length}:${Ju(_)}`)}return Ju(g.join("|"))}function fg(u,g,_,$,N){let z=j$(u),w=Ju(`${g}|${u.kind}|${z??""}`),Q=v$(u);return{project:_,filePath:$,kind:u.kind,name:g,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:E$(u),contentHash:N,indexedAt:new Date().toISOString(),structuralFingerprint:Q}}function Ng(u){let{parsed:g,project:_,filePath:$,contentHash:N,symbolRepo:z}=u,w=Lu(g),Q=[];for(let J of w){Q.push(fg(J,J.name,_,$,N));for(let Y of J.members??[])Q.push(fg(Y,`${J.name}.${Y.name}`,_,$,N))}z.replaceFileSymbols(_,$,N,Q)}import{resolve as Jg,dirname as P$,extname as b$}from"path";function Zu(u,g,_){let $=(N)=>{let z=b$(N);if(z==="")return[N+".ts",N+".d.ts",N+"/index.ts",N+"/index.d.ts",N+".mts",N+"/index.mts",N+".cts",N+"/index.cts"];if(z===".js")return[N.slice(0,-3)+".ts"];if(z===".mjs")return[N.slice(0,-4)+".mts"];if(z===".cjs")return[N.slice(0,-4)+".cts"];return[N]};if(g.startsWith(".")){let N=Jg(P$(u),g);return $(N)}if(_)for(let[N,z]of _.paths){if(z.length===0)continue;let w=N.indexOf("*");if(w===-1){if(g===N){let Q=[];for(let J of z)Q.push(...$(Jg(_.baseUrl,J)));return Q}}else{let Q=N.slice(0,w),J=N.slice(w+1);if(g.startsWith(Q)&&(J===""||g.endsWith(J))){let Y=g.slice(Q.length,J===""?void 0:g.length-J.length),O=[];for(let W of z)O.push(...$(Jg(_.baseUrl,W.replace("*",Y))));return O}}}return[]}function yg(u,g,_,$=Zu){let N=new Map,z=u.body??[];for(let w of z){if(w.type!=="ImportDeclaration")continue;let Q=w.source?.value??"",J=$(g,Q,_);if(J.length===0)continue;let Y=J[0],O=w.specifiers??[];for(let W of O)switch(W.type){case"ImportSpecifier":N.set(W.local.name,{path:Y,importedName:W.imported.name});break;case"ImportDefaultSpecifier":N.set(W.local.name,{path:Y,importedName:"default"});break;case"ImportNamespaceSpecifier":N.set(W.local.name,{path:Y,importedName:"*"});break}}return N}var f$=new Set(["loc","start","end","scope"]);function Du(u,g){if(!u||typeof u!=="object")return;if(Array.isArray(u)){for(let $ of u)Du($,g);return}let _=u;g(_);for(let $ of Object.keys(_)){if(f$.has($))continue;let N=_[$];if(N&&typeof N==="object")Du(N,g)}}function ig(u){if(!u||typeof u!=="object"||Array.isArray(u))return null;let g=u;if((g.type==="StringLiteral"||g.type==="Literal")&&typeof g.value==="string")return g.value;return null}function Ku(u){if(!u||typeof u!=="object"||Array.isArray(u))return null;let g=u;if(g.type==="Identifier"){let _=g.name;return{root:_,parts:[],full:_}}if(g.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(g.type==="Super")return{root:"super",parts:[],full:"super"};if(g.type==="MemberExpression"){let _=[],$=g;while($.type==="MemberExpression"){let w=$.property;if(!w||typeof w.name!=="string")return null;_.push(w.name),$=$.object}let N;if($.type==="Identifier")N=$.name;else if($.type==="ThisExpression")N="this";else if($.type==="Super")N="super";else return null;_.reverse();let z=[N,..._].join(".");return{root:N,parts:_,full:z}}return null}function mg(u,g,_,$=Zu){let N=[],z=u.body??[];for(let w of z){if(w.type==="ImportDeclaration"){let Q=w.source?.value??"",J=$(g,Q,_);if(J.length===0)continue;let Y=J[0],O=w.importKind==="type",W=w.specifiers??[];if(W.length===0){let Z={};if(O)Z.isType=!0;N.push({type:O?"type-references":"imports",srcFilePath:g,srcSymbolName:null,dstFilePath:Y,dstSymbolName:null,...Object.keys(Z).length>0?{metaJson:JSON.stringify(Z)}:{}})}else for(let Z of W){let n=Z.type,A=O||Z.importKind==="type",D={};if(A)D.isType=!0;let k,G;if(n==="ImportDefaultSpecifier")k="default",G=Z.local.name;else if(n==="ImportNamespaceSpecifier")k="*",G=Z.local.name,D.importKind="namespace";else k=Z.imported.name,G=Z.local.name;N.push({type:A?"type-references":"imports",srcFilePath:g,srcSymbolName:G,dstFilePath:Y,dstSymbolName:k,...Object.keys(D).length>0?{metaJson:JSON.stringify(D)}:{}})}continue}if(w.type==="ExportAllDeclaration"&&w.source){let Q=w.source?.value??"",J=$(g,Q,_);if(J.length===0)continue;let Y=J[0],O=w.exportKind==="type",W={isReExport:!0};if(O)W.isType=!0;N.push({type:O?"type-references":"re-exports",srcFilePath:g,srcSymbolName:null,dstFilePath:Y,dstSymbolName:null,metaJson:JSON.stringify(W)});continue}if(w.type==="ExportNamedDeclaration"&&w.source){let Q=w.source?.value??"",J=$(g,Q,_);if(J.length===0)continue;let Y=J[0],O=w.exportKind==="type",n={isReExport:!0,specifiers:(w.specifiers??[]).map((A)=>({local:A.local.name,exported:A.exported.name}))};if(O)n.isType=!0;N.push({type:O?"type-references":"re-exports",srcFilePath:g,srcSymbolName:null,dstFilePath:Y,dstSymbolName:null,metaJson:JSON.stringify(n)})}}return Du(u,(w)=>{if(w.type!=="ImportExpression")return;let Q=ig(w.source);if(!Q)return;let J=$(g,Q,_);if(J.length===0)return;let Y=J[0];N.push({type:"imports",srcFilePath:g,srcSymbolName:null,dstFilePath:Y,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),N}function hg(u,g,_){let $=[],N=[],z=[];function w(){if(N.length>0)return N[N.length-1]??null;return null}function Q(Y){if(!Y)return null;let O=_.get(Y.root);if(Y.parts.length===0){if(O)return{dstFilePath:O.path,dstSymbolName:O.importedName,resolution:"import"};return{dstFilePath:g,dstSymbolName:Y.root,resolution:"local"}}else{if(O&&O.importedName==="*"){let W=Y.parts[Y.parts.length-1];return{dstFilePath:O.path,dstSymbolName:W,resolution:"namespace"}}return{dstFilePath:g,dstSymbolName:Y.full,resolution:"local-member"}}}function J(Y){if(!Y||typeof Y!=="object")return;if(Array.isArray(Y)){for(let Z of Y)J(Z);return}let O=Y,W=typeof O.type==="string"?O.type:"";if(W==="ClassDeclaration"||W==="ClassExpression"){let Z=O,n=Z.id?.name??"AnonymousClass";z.push(n),J(Z.body),z.pop();return}if(W==="FunctionDeclaration"){let Z=O,n=Z.id?.name??"anonymous";N.push(n),J(Z.body),N.pop();return}if(W==="VariableDeclarator"&&O.init&&(O.init?.type==="FunctionExpression"||O.init?.type==="ArrowFunctionExpression")){let Z=O,n=Z.id?.name??"anonymous";N.push(n),J(Z.init?.body??Z.init),N.pop();return}if(W==="MethodDefinition"&&O.value){let Z=O,n=z[z.length-1]??"",A=Z.key?.name??"anonymous",D=n?`${n}.${A}`:A;N.push(D),J(Z.value?.body),N.pop();return}if(W==="FunctionExpression"||W==="ArrowFunctionExpression"){let Z=w(),n=Z?`${Z}.<anonymous>`:"<anonymous>";N.push(n),J(O.body),N.pop();return}if(W==="CallExpression"){let Z=O,n=Ku(Z.callee),A=Q(n);if(A){let D=w(),k={};if(D===null)k.scope="module";$.push({type:"calls",srcFilePath:g,srcSymbolName:D,dstFilePath:A.dstFilePath,dstSymbolName:A.dstSymbolName,...Object.keys(k).length>0?{metaJson:JSON.stringify(k)}:{}})}J(Z.callee);for(let D of Z.arguments??[])J(D);return}if(W==="NewExpression"){let Z=O,n=Ku(Z.callee),A=Q(n);if(A){let D=w(),k={isNew:!0};if(D===null)k.scope="module";$.push({type:"calls",srcFilePath:g,srcSymbolName:D,dstFilePath:A.dstFilePath,dstSymbolName:A.dstSymbolName,metaJson:JSON.stringify(k)})}for(let D of Z.arguments??[])J(D);return}for(let Z of Object.keys(O)){if(Z==="loc"||Z==="start"||Z==="end"||Z==="scope")continue;let n=O[Z];if(n&&typeof n==="object")J(n)}}return J(u),$}function xg(u,g,_){let $=[];return Du(u,(N)=>{if(N.type==="TSInterfaceDeclaration"){let Q=N.id?.name??"AnonymousInterface",J=N.extends??[];for(let Y of J){let O=Y.expression??Y,W=Ku(O);if(!W)continue;let Z=Qg(W,g,_);$.push({type:"extends",srcFilePath:g,srcSymbolName:Q,...Z})}return}if(N.type!=="ClassDeclaration"&&N.type!=="ClassExpression")return;let z=N.id?.name??"AnonymousClass";if(N.superClass){let Q=Ku(N.superClass);if(Q){let J=Qg(Q,g,_);$.push({type:"extends",srcFilePath:g,srcSymbolName:z,...J})}}let w=N.implements??[];for(let Q of w){let J=Q.expression??Q,Y=Ku(J);if(!Y)continue;let O=Qg(Y,g,_);$.push({type:"implements",srcFilePath:g,srcSymbolName:z,...O})}}),$}function Qg(u,g,_){let $=_.get(u.root);if($){if($.importedName==="*"){let N=u.parts[u.parts.length-1]??u.root;return{dstFilePath:$.path,dstSymbolName:N,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:$.path,dstSymbolName:u.parts.length>0?u.full:$.importedName}}return{dstFilePath:g,dstSymbolName:u.full,metaJson:JSON.stringify({isLocal:!0})}}function hu(u,g,_,$=Zu){let N=yg(u,g,_,$),z=mg(u,g,_,$),w=hg(u,g,N),Q=xg(u,g,N);return[...z,...w,...Q]}function wg(u){let{ast:g,project:_,filePath:$,relationRepo:N,projectRoot:z,tsconfigPaths:w,knownFiles:Q,boundaries:J}=u,Y=Bu(z,$),W=hu(g,Y,w,Q?(n,A,D)=>{let k=Zu(n,A,D);for(let G of k){let i=yu(z,G);if(J){let V=l(i,J);if(Q.has(`${V}::${i}`))return[G]}else if(Q.has(`${_}::${i}`))return[G]}return[]}:void 0),Z=[];for(let n of W){let A=yu(z,n.dstFilePath);if(A.startsWith(".."))continue;let D=yu(z,n.srcFilePath),k=J?l(A,J):_;Z.push({project:_,type:n.type,srcFilePath:D,srcSymbolName:n.srcSymbolName??null,dstProject:k,dstFilePath:A,dstSymbolName:n.dstSymbolName??null,metaJson:n.metaJson??null})}return N.replaceFileRelations(_,$,Z),Z.length}import{isErr as y$}from"@zipbul/result";var pg=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function i$(u){let g=Lu(u),_=[];for(let $ of g){_.push({name:$.name,startLine:$.span.start.line});for(let N of $.members??[])_.push({name:`${$.name}.${N.name}`,startLine:N.span.start.line})}return _.sort(($,N)=>$.startLine-N.startLine),_}function zg(u,g,_){let $=0,N=u.length-1;while($<=N){let z=$+N>>1;if(u[z].startLine<=g)$=z+1;else N=z-1}if($<u.length){let z=u[$];if(z.startLine-g<=_)return z.name}return null}function xu(u,g,_){let $=Nu(u,g),N=Nu(u,_);return{start:$,end:N}}function lg(u){let{comments:g,sourceText:_}=u;if(!g.length)return[];let $=iu(_),N=i$(u),z=[],w=[...g].sort((J,Y)=>J.start-Y.start),Q=null;for(let J of w)if(J.type==="Block"&&J.value.startsWith("*")){Q=null;let Y=`/*${J.value}*/`,O=mu(Y);if(y$(O))continue;let W=O;if(!W.tags?.length)continue;let Z=Nu($,J.end),n=zg(N,Z.line,3),A=_.slice(J.start,J.end);for(let D of W.tags){let k=[D.name,D.description].filter(Boolean).join(" "),G=`@${D.tag}`,i=A.indexOf(G),V;if(i>=0){let K=J.start+i,M=_.indexOf(`
4
- `,K),R=M>=0?Math.min(M,J.end):J.end;V=xu($,K,R)}else V=xu($,J.start,J.end);z.push({tag:D.tag,value:k,source:"jsdoc",span:V,symbolName:n})}}else if(J.type==="Block"){Q=null;let Y=J.value.split(`
5
- `),O=0;for(let W of Y){let Z=W.replace(/^\s*\*?\s?/,""),n=pg.exec(Z);if(n){let A=n[1],D=n[2]?.trim()??"",k=`@${A}`,G=W.indexOf(k),i=J.start+2+O+(G>=0?G:0),V=J.start+2+O+W.length,K=xu($,i,V),M=Nu($,J.end),R=zg(N,M.line,3);z.push({tag:A,value:D,source:"block",span:K,symbolName:R})}O+=W.length+1}}else{let Y=J.value,O=pg.exec(Y),W=Nu($,J.start),Z=Nu($,J.end);if(O){let n=O[1],A=O[2]?.trim()??"",D=`@${n}`,k=Y.indexOf(D),G=J.start+2+(k>=0?k:0),i=xu($,G,J.end),V=zg(N,Z.line,3),K={tag:n,value:A,source:"line",span:i,symbolName:V};z.push(K),Q={annotation:K,endLine:Z.line}}else if(Q&&W.line===Q.endLine+1){let n=Y.trim();if(n)Q.annotation.value+=" "+n,Q.annotation.span.end=Nu($,J.end),Q.endLine=Z.line}else Q=null}return z}function Og(u){let{parsed:g,project:_,filePath:$,annotationRepo:N}=u,z=lg(g);if(N.deleteFileAnnotations(_,$),!z.length)return 0;let w=new Date().toISOString(),Q=z.map((J)=>({project:_,filePath:$,tag:J.tag,value:J.value,source:J.source,symbolName:J.symbolName,startLine:J.span.start.line,startColumn:J.span.start.column,endLine:J.span.end.line,endColumn:J.span.end.column,indexedAt:w}));return N.insertBatch(_,$,Q),z.length}function rg(u,g){let _=[],$=[],N=[];for(let[O,W]of g)if(!u.has(O))_.push({name:W.name,filePath:W.filePath,kind:W.kind,fingerprint:W.fingerprint});for(let[O,W]of u)if(!g.has(O))$.push({name:W.name,filePath:W.filePath,kind:W.kind,fingerprint:W.fingerprint});if(!_.length||!$.length)return{renamed:N,added:_,removed:$};let z=new Map,w=new Map;for(let O of _){let W=z.get(O.filePath)??[];W.push(O),z.set(O.filePath,W)}for(let O of $){let W=w.get(O.filePath)??[];W.push(O),w.set(O.filePath,W)}let Q=new Set,J=new Set;for(let[O,W]of z){let Z=w.get(O);if(!Z)continue;for(let n of new Set(W.map((A)=>A.kind))){let A=W.filter((V)=>V.kind===n&&!Q.has(V)),D=Z.filter((V)=>V.kind===n&&!J.has(V));if(!A.length||!D.length)continue;let k=(V,K)=>{return K.get(`${V.filePath}::${V.name}`)?.structuralFingerprint??null},G=(V,K)=>{return K.get(`${V.filePath}::${V.name}`)?.startLine??0},i=new Map;for(let V of D){let K=k(V,u);if(!K)continue;let M=i.get(K)??[];M.push(V),i.set(K,M)}for(let V of A){if(Q.has(V))continue;let K=k(V,g);if(!K)continue;let M=i.get(K);if(!M)continue;let R=M.filter((C)=>!J.has(C));if(!R.length)continue;let I=R[0];if(R.length>1){let C=G(V,g),v=Math.abs(G(I,u)-C);for(let y=1;y<R.length;y++){let j=Math.abs(G(R[y],u)-C);if(j<v)v=j,I=R[y]}}N.push({oldName:I.name,newName:V.name,filePath:O,kind:n}),Q.add(V),J.add(I)}}}let Y=N.filter((O)=>!O.oldName.includes("."));for(let O of Y){let W=`${O.oldName}.`,Z=`${O.newName}.`,n=$.filter((D)=>D.filePath===O.filePath&&D.name.startsWith(W)&&!J.has(D)),A=_.filter((D)=>D.filePath===O.filePath&&D.name.startsWith(Z)&&!Q.has(D));for(let D of n){let k=D.name.slice(W.length),G=A.find((i)=>i.name.slice(Z.length)===k);if(G)N.push({oldName:D.name,newName:G.name,filePath:O.filePath,kind:D.kind}),Q.add(G),J.add(D)}}return{renamed:N,added:_.filter((O)=>!Q.has(O)),removed:$.filter((O)=>!J.has(O))}}var m$=100,tg=50;class Wg{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=Ru(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")){fu(this.opts.projectRoot),this.tsconfigPathsRaw=Ru(this.opts.projectRoot),this.fullIndex().catch((g)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",g)});return}if(u.filePath.endsWith("package.json")){let g=this.opts.discoverProjectsFn??bu;this.boundariesRefresh=g(this.opts.projectRoot).then((_)=>{this.opts.boundaries=_})}if(this.pendingEvents.push(u),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},m$)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(u,g){if(this.indexingLock){if(g)return this.pendingFullIndex=!0,new Promise(($,N)=>{this.pendingFullIndexWaiters.push({resolve:$,reject:N})});return this.currentIndexing}this.indexingLock=!0;let _=this.doIndex(u,g).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((N)=>{for(let z of $)z.resolve(N)}).catch((N)=>{for(let z of $)z.reject(N)})}else if(this.pendingEvents.length>0){let $=this.pendingEvents.splice(0);this.startIndex($,!1).catch((N)=>this.logger.error("[IndexCoordinator] incremental drain error",N))}});return this.currentIndexing=_,_}async doIndex(u,g){let _=Date.now(),{fileRepo:$,symbolRepo:N,relationRepo:z,dbConnection:w}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let Q,J;if(u!==void 0)Q=u.filter((X)=>X.eventType==="create"||X.eventType==="change").map((X)=>({filePath:X.filePath,contentHash:"",mtimeMs:0,size:0})),J=u.filter((X)=>X.eventType==="delete").map((X)=>X.filePath);else{let X=new Map;for(let S of this.opts.boundaries)for(let[H,P]of $.getFilesMap(S.project))X.set(H,P);let B=await bg({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>X}});Q=B.changed,J=B.deleted}let Y=await this.tsconfigPathsRaw??void 0,O=new Map;for(let X of J){let B=l(X,this.opts.boundaries),S=N.getFileSymbols(B,X);O.set(X,S)}let W=crypto.randomUUID(),Z=new Map,n=new Map,A=(X)=>({name:X.name,filePath:X.filePath,kind:X.kind,fingerprint:X.fingerprint,structuralFingerprint:X.structuralFingerprint??null,startLine:X.startLine});if(g)for(let X of this.opts.boundaries)for(let B of $.getAllFiles(X.project))for(let S of N.getFileSymbols(X.project,B.filePath))Z.set(`${S.filePath}::${S.name}`,A(S));else{for(let X of Q){let B=l(X.filePath,this.opts.boundaries);for(let S of N.getFileSymbols(B,X.filePath))Z.set(`${S.filePath}::${S.name}`,A(S))}for(let[,X]of O)for(let B of X)Z.set(`${B.filePath}::${B.name}`,A(B))}let{annotationRepo:D,changelogRepo:k}=this.opts,G=()=>{for(let X of J){let B=l(X,this.opts.boundaries);if(N.deleteFileSymbols(B,X),z.deleteFileRelations(B,X),D)D.deleteFileAnnotations(B,X);$.deleteFile(B,X)}},i=0,V=async()=>{let{projectRoot:X,boundaries:B}=this.opts,{parseCache:S}=this.opts,H=0,P=0,q=0,c=[],b=[];for(let E of Q)try{let T=Bu(X,E.filePath),s=Bun.file(T),o=await s.text(),Qu=E.contentHash||Ju(o),Wu=l(E.filePath,B);$.upsertFile({project:Wu,filePath:E.filePath,mtimeMs:s.lastModified,size:s.size,contentHash:Qu,updatedAt:new Date().toISOString(),lineCount:o.split(`
6
- `).length});let Cu=(this.opts.parseSourceFn??Tu)(T,o);if(dg(Cu))throw Cu.data;let u$=Cu;b.push({filePath:E.filePath,text:o,contentHash:Qu,parsed:u$,project:Wu})}catch(T){this.logger.error(`[IndexCoordinator] Failed to prepare ${E.filePath}:`,T),c.push(E.filePath)}let h=new Set;for(let E of B)for(let[T]of $.getFilesMap(E.project))h.add(`${E.project}::${T}`);return w.transaction(()=>{for(let E of b){if(Ng({parsed:E.parsed,project:E.project,filePath:E.filePath,contentHash:E.contentHash,symbolRepo:N}),P+=wg({ast:E.parsed.program,project:E.project,filePath:E.filePath,relationRepo:z,projectRoot:X,tsconfigPaths:Y,knownFiles:h,boundaries:B}),D)q+=Og({parsed:E.parsed,project:E.project,filePath:E.filePath,annotationRepo:D});S.set(E.filePath,E.parsed),H+=N.getFileSymbols(E.project,E.filePath).length}}),{symbols:H,relations:P,annotations:q,failedFiles:c}},K=0,M=0,R=[];if(g){let{projectRoot:X,boundaries:B}=this.opts,{parseCache:S}=this.opts,H=[];for(let q=0;q<Q.length;q+=tg){let c=Q.slice(q,q+tg),b=await Promise.allSettled(c.map(async(h)=>{let E=Bu(X,h.filePath),T=Bun.file(E),s=await T.text(),o=h.contentHash||Ju(s);return{filePath:h.filePath,text:s,contentHash:o,mtimeMs:T.lastModified,size:T.size}}));for(let h=0;h<b.length;h++){let E=b[h];if(E.status==="fulfilled")H.push(E.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",E.reason),R.push(c[h].filePath)}}let P=[];w.transaction(()=>{for(let b of H){let h=l(b.filePath,B);$.deleteFile(h,b.filePath)}for(let b of J){let h=l(b,B);if(N.deleteFileSymbols(h,b),z.deleteFileRelations(h,b),D)D.deleteFileAnnotations(h,b);$.deleteFile(h,b)}for(let b of H){let h=l(b.filePath,B);$.upsertFile({project:h,filePath:b.filePath,mtimeMs:b.mtimeMs,size:b.size,contentHash:b.contentHash,updatedAt:new Date().toISOString(),lineCount:b.text.split(`
7
- `).length})}let q=new Set;for(let b of B)for(let[h]of $.getFilesMap(b.project))q.add(`${b.project}::${h}`);let c=this.opts.parseSourceFn??Tu;for(let b of H){let h=l(b.filePath,B),E=c(Bu(X,b.filePath),b.text);if(dg(E))throw E.data;let T=E;if(P.push({filePath:b.filePath,parsed:T}),Ng({parsed:T,project:h,filePath:b.filePath,contentHash:b.contentHash,symbolRepo:N}),D)i+=Og({parsed:T,project:h,filePath:b.filePath,annotationRepo:D});M+=wg({ast:T.program,project:h,filePath:b.filePath,relationRepo:z,projectRoot:X,tsconfigPaths:Y,knownFiles:q,boundaries:B}),K+=N.getFileSymbols(h,b.filePath).length}});for(let q of P)S.set(q.filePath,q.parsed)}else{G();let X=await V();K=X.symbols,M=X.relations,i=X.annotations,R=X.failedFiles}for(let X of Q){let B=l(X.filePath,this.opts.boundaries);for(let S of N.getFileSymbols(B,X.filePath))n.set(`${S.filePath}::${S.name}`,A(S))}let I={added:[],modified:[],removed:[]};for(let[X,B]of n){let S=Z.get(X);if(!S)I.added.push({name:B.name,filePath:B.filePath,kind:B.kind});else if(S.fingerprint!==B.fingerprint)I.modified.push({name:B.name,filePath:B.filePath,kind:B.kind})}for(let[X,B]of Z)if(!n.has(X))I.removed.push({name:B.name,filePath:B.filePath,kind:B.kind});let C=rg(Z,n),v=new Set(C.renamed.map((X)=>`${X.filePath}::${X.oldName}`)),y=new Set(C.renamed.map((X)=>`${X.filePath}::${X.newName}`));I.added=I.added.filter((X)=>!y.has(`${X.filePath}::${X.name}`)),I.removed=I.removed.filter((X)=>!v.has(`${X.filePath}::${X.name}`));let j=[];if(!g){for(let[X,B]of O)for(let S of B){if(!S.fingerprint)continue;let H=l(X,this.opts.boundaries),P=N.getByFingerprint(H,S.fingerprint);if(P.length===1){let q=P[0];z.retargetRelations({dstProject:H,oldFile:X,oldSymbol:S.name,newFile:q.filePath,newSymbol:q.name}),j.push({name:q.name,filePath:q.filePath,kind:q.kind,oldFilePath:X})}}for(let X of C.removed){let S=Z.get(`${X.filePath}::${X.name}`)?.fingerprint;if(!S)continue;let H=l(X.filePath,this.opts.boundaries),P=N.getByFingerprint(H,S);if(P.length===1){let q=P[0];if(q.filePath!==X.filePath||q.name!==X.name)z.retargetRelations({dstProject:H,oldFile:X.filePath,oldSymbol:X.name,newFile:q.filePath,newSymbol:q.name}),j.push({name:q.name,filePath:q.filePath,kind:q.kind,oldFilePath:X.filePath})}}}if(j.length){let X=new Set(j.map((S)=>`${S.filePath}::${S.name}`)),B=new Set(j.map((S)=>`${S.oldFilePath}::${S.name}`));I.added=I.added.filter((S)=>!X.has(`${S.filePath}::${S.name}`)),I.removed=I.removed.filter((S)=>!B.has(`${S.filePath}::${S.name}`))}if(k){let X=new Date().toISOString(),B=g?1:0,S=[];for(let H of I.added){let P=`${H.filePath}::${H.name}`,q=n.get(P),c=l(H.filePath,this.opts.boundaries);S.push({project:c,changeType:"added",symbolName:H.name,symbolKind:H.kind,filePath:H.filePath,oldName:null,oldFilePath:null,fingerprint:q?.fingerprint??null,changedAt:X,isFullIndex:B,indexRunId:W})}for(let H of I.modified){let P=n.get(`${H.filePath}::${H.name}`),q=l(H.filePath,this.opts.boundaries);S.push({project:q,changeType:"modified",symbolName:H.name,symbolKind:H.kind,filePath:H.filePath,oldName:null,oldFilePath:null,fingerprint:P?.fingerprint??null,changedAt:X,isFullIndex:B,indexRunId:W})}for(let H of I.removed){let P=`${H.filePath}::${H.name}`,q=Z.get(P),c=l(H.filePath,this.opts.boundaries);S.push({project:c,changeType:"removed",symbolName:H.name,symbolKind:H.kind,filePath:H.filePath,oldName:null,oldFilePath:null,fingerprint:q?.fingerprint??null,changedAt:X,isFullIndex:B,indexRunId:W})}for(let H of C.renamed){let P=n.get(`${H.filePath}::${H.newName}`),q=l(H.filePath,this.opts.boundaries);S.push({project:q,changeType:"renamed",symbolName:H.newName,symbolKind:H.kind,filePath:H.filePath,oldName:H.oldName,oldFilePath:null,fingerprint:P?.fingerprint??null,changedAt:X,isFullIndex:B,indexRunId:W})}for(let H of j){let P=n.get(`${H.filePath}::${H.name}`),q=l(H.filePath,this.opts.boundaries);S.push({project:q,changeType:"moved",symbolName:H.name,symbolKind:H.kind,filePath:H.filePath,oldName:null,oldFilePath:H.oldFilePath,fingerprint:P?.fingerprint??null,changedAt:X,isFullIndex:B,indexRunId:W})}if(S.length)try{w.transaction(()=>{k.insertBatch(S)})}catch(H){this.logger.error("[IndexCoordinator] changelog insert failed:",H)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let H=new Date(Date.now()-2592000000).toISOString();try{for(let P of this.opts.boundaries)k.pruneOlderThan(P.project,H)}catch(P){this.logger.error("[IndexCoordinator] changelog pruning failed:",P)}}}return{indexedFiles:Q.length,removedFiles:J.length,totalSymbols:K,totalRelations:M,totalAnnotations:i,durationMs:Date.now()-_,changedFiles:Q.map((X)=>X.filePath),deletedFiles:[...J],failedFiles:R,changedSymbols:I}}fireCallbacks(u){for(let g of this.callbacks)try{g(u)}catch(_){this.logger.error("[IndexCoordinator] onIndexed callback threw:",_)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let u=this.pendingEvents.splice(0);this.startIndex(u,!1).catch((g)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",g))}}}function h$(u){try{return process.kill(u,0),!0}catch(g){if(typeof g==="object"&&g&&"code"in g)return g.code!=="ESRCH";return!0}}function x$(u){let g=new Date(u).getTime();return Number.isNaN(g)?0:g}function ag(u,g,_={}){let $=_.now??Date.now,N=_.isAlive??h$,z=_.staleAfterSeconds??60,w=_.instanceId;return u.immediateTransaction(()=>{let Q=u.selectOwner();if(!Q)return u.insertOwner(g,w),"owner";let J=Math.floor(($()-x$(Q.heartbeat_at))/1000),Y=N(Q.pid);if(Y&&w&&Q.instance_id&&Q.instance_id!==w&&Q.pid!==g)return u.replaceOwner(g,w),"owner";if(Y&&J<z)return"reader";return u.replaceOwner(g,w),"owner"})}function cg(u,g){u.deleteOwner(g)}function sg(u,g){u.touchOwner(g)}class ku{#u;#g=new Map;constructor(u){this.#u=Math.max(1,u)}get size(){return this.#g.size}has(u){return this.#g.has(u)}get(u){if(!this.#g.has(u))return;let g=this.#g.get(u);return this.#g.delete(u),this.#g.set(u,g),g}set(u,g){if(this.#g.has(u))this.#g.delete(u);if(this.#g.set(u,g),this.#g.size>this.#u){let _=this.#g.keys().next().value;if(_!==void 0)this.#g.delete(_)}}delete(u){return this.#g.delete(u)}clear(){this.#g.clear()}}class Yg{lru;constructor(u=500){this.lru=new ku(u)}get(u){return this.lru.get(u)}set(u,g){this.lru.set(u,g)}invalidate(u){this.lru.delete(u)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function Vg(u){let{symbolRepo:g,project:_,query:$}=u,N=$.project??_,z=$.limit??100,w={kind:$.kind,filePath:$.filePath,isExported:$.isExported,project:N,limit:z,resolvedType:$.resolvedType};if($.text)if($.exact)w.exactName=$.text;else{let J=Hu($.text);if(J)w.ftsQuery=J}if($.decorator)w.decorator=$.decorator;if($.regex)w.regex=$.regex;return g.searchByQuery(w).map((J)=>({id:J.id,filePath:J.filePath,kind:J.kind,name:J.name,span:{start:{line:J.startLine,column:J.startColumn},end:{line:J.endLine,column:J.endColumn}},isExported:J.isExported===1,signature:J.signature,fingerprint:J.fingerprint,detail:J.detailJson?(()=>{try{return JSON.parse(J.detailJson)}catch{return{}}})():{}}))}function Ug(u){let{relationRepo:g,project:_,query:$}=u,N=$.project??_,z=$.limit??500;return g.searchRelations({srcFilePath:$.srcFilePath,srcSymbolName:$.srcSymbolName,dstFilePath:$.dstFilePath,dstSymbolName:$.dstSymbolName,dstProject:$.dstProject,type:$.type,project:N,limit:z}).map((Q)=>{let J;if(Q.metaJson)try{J=JSON.parse(Q.metaJson)}catch{}return{type:Q.type,srcFilePath:Q.srcFilePath,srcSymbolName:Q.srcSymbolName,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,dstProject:Q.dstProject,metaJson:Q.metaJson??void 0,meta:J}})}import{findInFiles as p$,Lang as l$}from"@ast-grep/napi";async function Xg(u){if(u.filePaths.length===0)return[];let g=[];return await p$(l$.TypeScript,{paths:u.filePaths,matcher:{rule:{pattern:u.pattern}}},(_,$)=>{if(_){console.warn("[patternSearch] findInFiles callback error:",_);return}for(let N of $){let z=N.range();g.push({filePath:N.getRoot().filename(),startLine:z.start.line+1,endLine:z.end.line+1,matchedText:N.text()})}}),g}import d from"typescript";import{isErr as J0}from"@zipbul/result";import zu from"typescript";import r$ from"path";import{err as Zg}from"@zipbul/result";function d$(u){try{return Sg("fs").readFileSync(u,"utf-8")}catch{return}}function t$(u){try{return Sg("fs").readFileSync(u,"utf-8")}catch{return}}class pu{#u;#g;#_=!1;__testing__;constructor(u,g){this.#u=u,this.#g=g,this.__testing__={host:g}}static create(u,g={}){let _=g.readConfigFile??d$,$=g.resolveNonTrackedFile??t$,N=r$.dirname(u),z=_(u);if(z===void 0)return Zg(e("semantic",`tsconfig not found: ${u}`));let w=zu.parseJsonText(u,z),Q=w.parseDiagnostics;if(Q&&Q.length>0){let W=Q.map((Z)=>zu.flattenDiagnosticMessageText(Z.messageText,`
8
- `)).join("; ");return Zg(e("semantic",`tsconfig parse error: ${W}`))}let J=zu.parseJsonSourceFileConfigFileContent(w,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(W)=>_(W)!==void 0||$(W)!==void 0,readFile:(W)=>_(W)??$(W)},N);if(J.errors.length>0){let W=J.errors.filter((Z)=>Z.category===zu.DiagnosticCategory.Error&&Z.code!==18003);if(W.length>0){let Z=W.map((n)=>zu.flattenDiagnosticMessageText(n.messageText,`
9
- `)).join("; ");return Zg(e("semantic",`tsconfig compile error: ${Z}`))}}let Y=new og(J.fileNames,J.options,N,$),O=zu.createLanguageService(Y);return new pu(O,Y)}get isDisposed(){return this.#_}getProgram(){this.#N();let u=this.#u.getProgram();if(!u)throw Error("TscProgram: LanguageService returned null Program");return u}getChecker(){return this.#N(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#N(),this.#u}notifyFileChanged(u,g){if(this.#_)return;this.#g.updateFile(u,g)}removeFile(u){if(this.#_)return;this.#g.removeFile(u)}dispose(){if(this.#_)return;this.#_=!0,this.#u.dispose()}#N(){if(this.#_)throw Error("TscProgram is disposed")}}class og{#u;#g;#_;#N;#$=new Map;constructor(u,g,_,$){this.#u=new Set(u),this.#g=g,this.#_=_,this.#N=$}updateFile(u,g){let _=this.#$.get(u);if(_)_.version+=1,_.content=g;else this.#$.set(u,{version:1,content:g})}removeFile(u){this.#$.delete(u),this.#u.delete(u)}getScriptFileNames(){let u=[...this.#$.keys()];return[...[...this.#u].filter((_)=>!this.#$.has(_)),...u]}getScriptVersion(u){let g=this.#$.get(u);return g?String(g.version):"0"}getScriptSnapshot(u){let g=this.#$.get(u);if(g)return zu.ScriptSnapshot.fromString(g.content);let _=this.#N(u);if(_!==void 0)return zu.ScriptSnapshot.fromString(_);return}getCurrentDirectory(){return this.#_}getCompilationSettings(){return this.#g}getDefaultLibFileName(u){return zu.getDefaultLibFilePath(u)}fileExists(u){if(this.#$.has(u))return!0;return this.#N(u)!==void 0}readFile(u){let g=this.#$.get(u);if(g)return g.content;return this.#N(u)}}import a from"typescript";import a$ from"typescript";function Ou(u,g){if(g<0||g>=u.getEnd())return;function _($){let N=$.getStart(u,!1),z=$.getEnd();if(g<N||g>=z)return;let w;return a$.forEachChild($,(Q)=>{if(!w)w=_(Q)}),w??$}return _(u)}function c$(u){return!!(u.flags&a.TypeFlags.Object)&&!!(u.objectFlags&a.ObjectFlags.Reference)}function Fu(u,g,_=0){let $=u.typeToString(g),N=g.flags,z=!!(N&a.TypeFlags.Union),w=!!(N&a.TypeFlags.Intersection),Q;if(_<8&&c$(g)){let W=u.getTypeArguments(g);if(W.length>0)Q=W}let J=!!(N&a.TypeFlags.TypeParameter)||Q!==void 0&&Q.length>0,Y;if(z&&_<8)Y=g.types.map((W)=>Fu(u,W,_+1));else if(w&&_<8)Y=g.types.map((W)=>Fu(u,W,_+1));let O;if(Q&&Q.length>0)O=Q.map((W)=>Fu(u,W,_+1));return{text:$,flags:N,isUnion:z,isIntersection:w,isGeneric:J,members:Y,typeArguments:O}}function s$(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 Kg{program;constructor(u){this.program=u}collectAt(u,g){let _=this.program.getProgram(),$=this.program.getChecker();if(g<0)return null;let N=_.getSourceFile(u);if(!N)return null;if(g>=N.getEnd())return null;let z=Ou(N,g);if(!z)return null;if(!a.isIdentifier(z))return null;try{let w=$.getTypeAtLocation(z);return Fu($,w)}catch{return null}}collectFile(u){let g=new Map,_=this.program.getProgram(),$=this.program.getChecker(),N=_.getSourceFile(u);if(!N)return g;function z(w){if(s$(w)&&w.name&&a.isIdentifier(w.name)){let Q=w.name;try{let J=$.getTypeAtLocation(Q),Y=Q.getStart(N);g.set(Y,Fu($,J))}catch{}}a.forEachChild(w,z)}return z(N),g}}import Uu from"typescript";var o$=1000,e$=1;function u0(u){let g=u.declarations?.[0],_=g?.getSourceFile(),$=g?Uu.getNameOfDeclaration(g):void 0;return{name:u.getName(),filePath:_?.fileName??"",position:$?.getStart(_,!1)??g?.getStart(_,!1)??0}}function lu(u,g=0){let _=u.declarations?.[0],$=_?.getSourceFile(),N=_?Uu.getNameOfDeclaration(_):void 0,z=$?.fileName??"",w=N?.getStart($,!1)??_?.getStart($,!1)??0,Q={name:u.getName(),filePath:z,position:w},J=u;if(J.parent)Q.parent=u0(J.parent);if(g<e$){let Y=u.flags,O=!!(Y&Uu.SymbolFlags.Enum),W=!!(Y&(Uu.SymbolFlags.NamespaceModule|Uu.SymbolFlags.ValueModule)),Z=!!(Y&(Uu.SymbolFlags.Class|Uu.SymbolFlags.Interface));if(O&&u.exports&&u.exports.size>0){let n=[];u.exports.forEach((A)=>{n.push(lu(A,g+1))}),Q.members=n}else if(Z&&u.members&&u.members.size>0){let n=[];u.members.forEach((A)=>{n.push(lu(A,g+1))}),Q.members=n}if(W&&u.exports&&u.exports.size>0){let n=[];u.exports.forEach((A)=>{n.push(lu(A,g+1))}),Q.exports=n}}return Q}class Mg{#u;#g;#_=new Map;constructor(u,g=o$){this.#u=u,this.#g=new ku(g)}get(u,g){if(this.#u.isDisposed)return null;let _=`${u}:${g}`,$=this.#g.get(_);if($!==void 0)return $;let z=this.#u.getProgram().getSourceFile(u);if(!z)return null;let w=Ou(z,g);if(!w||!Uu.isIdentifier(w))return null;let J=this.#u.getChecker().getSymbolAtLocation(w);if(!J)return null;let Y=lu(J);this.#g.set(_,Y);let O=this.#_.get(u);if(!O)O=new Set,this.#_.set(u,O);return O.add(_),Y}invalidate(u){let g=this.#_.get(u);if(g){for(let _ of g)this.#g.delete(_);this.#_.delete(u)}}clear(){this.#g.clear(),this.#_.clear()}}import g0 from"typescript";class ng{#u;constructor(u){this.#u=u}findAt(u,g){if(this.#u.isDisposed)return[];let _=this.#u.getProgram(),$=_.getSourceFile(u);if(!$)return[];let N=Ou($,g);if(!N||!g0.isIdentifier(N))return[];let w=this.#u.getLanguageService().findReferences(u,g);if(!w||w.length===0)return[];let Q=[];for(let J of w)for(let Y of J.references){let O=_.getSourceFile(Y.fileName);if(!O)continue;let{line:W,character:Z}=O.getLineAndCharacterOfPosition(Y.textSpan.start);Q.push({filePath:Y.fileName,position:Y.textSpan.start,line:W+1,column:Z,isDefinition:Y.isDefinition??!1,isWrite:Y.isWriteAccess??!1})}return Q}}import m from"typescript";function _0(u,g){let _=Ou(u,g);if(!_)return;if(eg(_))return _;let $=_.parent;for(let N=0;N<5&&$;N++){if(eg($))return $;$=$.parent}return _}function eg(u){return m.isClassDeclaration(u)||m.isClassExpression(u)||m.isFunctionDeclaration(u)||m.isFunctionExpression(u)||m.isArrowFunction(u)||m.isVariableDeclaration(u)||m.isObjectLiteralExpression(u)}function u_(u){if(m.isClassDeclaration(u)||m.isClassExpression(u))return"class";if(m.isFunctionDeclaration(u)||m.isFunctionExpression(u)||m.isArrowFunction(u))return"function";if(m.isObjectLiteralExpression(u))return"object";if(m.isVariableDeclaration(u)&&u.initializer)return u_(u.initializer);return"class"}function $0(u,g){if(m.isClassDeclaration(u)||m.isFunctionDeclaration(u))return u.name?.getText(g)??"";if(m.isClassExpression(u))return u.name?.getText(g)??"";if(m.isVariableDeclaration(u)&&m.isIdentifier(u.name))return u.name.getText(g);if(m.isFunctionExpression(u))return u.name?.getText(g)??"";if(m.isArrowFunction(u)&&u.parent&&m.isVariableDeclaration(u.parent)){if(m.isIdentifier(u.parent.name))return u.parent.name.getText(g)}if(m.isObjectLiteralExpression(u)&&u.parent&&m.isVariableDeclaration(u.parent)){if(m.isIdentifier(u.parent.name))return u.parent.name.getText(g)}return""}function N0(u){if(!m.isClassDeclaration(u)&&!m.isClassExpression(u))return!1;let g=u.heritageClauses;if(!g)return!1;return g.some((_)=>_.token===m.SyntaxKind.ImplementsKeyword)}class Hg{#u;constructor(u){this.#u=u}findAt(u,g){if(this.#u.isDisposed)return[];let _=this.#u.getProgram(),$=_.getSourceFile(u);if(!$)return[];let N=Ou($,g);if(!N||!m.isIdentifier(N))return[];let w=this.#u.getLanguageService().getImplementationAtPosition(u,g);if(!w||w.length===0)return[];let Q=[];for(let J of w){if(J.kind===m.ScriptElementKind.interfaceElement||J.kind===m.ScriptElementKind.typeElement)continue;let Y=_.getSourceFile(J.fileName);if(!Y)continue;let O=_0(Y,J.textSpan.start);if(!O)continue;let W=u_(O),Z=$0(O,Y),n=N0(O);Q.push({filePath:J.fileName,symbolName:Z,position:J.textSpan.start,kind:W,isExplicit:n})}return Q}}function g_(u){return d.canHaveModifiers(u)&&d.getModifiers(u)?.some((g)=>g.kind===d.SyntaxKind.ExportKeyword)===!0}function Q0(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 __(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;#_;#N;#$;#J=!1;constructor(u,g,_,$,N){this.#u=u,this.#g=g,this.#_=_,this.#N=$,this.#$=N}static create(u,g={}){let _=pu.create(u,{readConfigFile:g.readConfigFile,resolveNonTrackedFile:g.resolveNonTrackedFile});if(J0(_))return _;let $=_,N=g.typeCollector??new Kg($),z=g.symbolGraph??new Mg($),w=g.referenceResolver??new ng($),Q=g.implementationFinder??new Hg($);return new ru($,N,z,w,Q)}get isDisposed(){return this.#J}collectTypeAt(u,g){return this.#Q(),this.#g.collectAt(u,g)}collectFileTypes(u){return this.#Q(),this.#g.collectFile(u)}findReferences(u,g){return this.#Q(),this.#N.findAt(u,g)}findImplementations(u,g){return this.#Q(),this.#$.findAt(u,g)}getSymbolNode(u,g){return this.#Q(),this.#_.get(u,g)}getModuleInterface(u){this.#Q();let g=this.#g.collectFile(u),_=[],N=this.#u.getProgram().getSourceFile(u);if(!N)return{filePath:u,exports:_};function z(w){if(d.isVariableStatement(w)&&g_(w)){for(let Q of w.declarationList.declarations)if(d.isIdentifier(Q.name)){let J=Q.name.getStart(N),Y=g.get(J)??null;_.push({name:Q.name.text,kind:"const",resolvedType:Y})}return}if((d.isFunctionDeclaration(w)||d.isClassDeclaration(w)||d.isInterfaceDeclaration(w)||d.isTypeAliasDeclaration(w)||d.isEnumDeclaration(w))&&g_(w)&&w.name){let Q=w.name,J=Q.getStart(N),Y=g.get(J)??null;_.push({name:Q.text,kind:Q0(w),resolvedType:Y});return}d.forEachChild(w,z)}return z(N),{filePath:u,exports:_}}notifyFileChanged(u,g){if(this.#J)return;this.#u.notifyFileChanged(u,g),this.#_.invalidate(u)}notifyFileDeleted(u){if(this.#J)return;this.#u.removeFile(u),this.#_.invalidate(u)}lineColumnToPosition(u,g,_){this.#Q();let $=this.#u.getProgram().getSourceFile(u);if(!$)return null;try{return d.getPositionOfLineAndCharacter($,g-1,_)}catch{return null}}findNamePosition(u,g,_){this.#Q();let $=this.#u.getProgram().getSourceFile(u);if(!$)return null;let N=$.getFullText(),z=g;while(z<N.length){let w=N.indexOf(_,z);if(w<0)return null;let Q=w>0?N.charCodeAt(w-1):32,J=w+_.length<N.length?N.charCodeAt(w+_.length):32;if(!__(Q)&&!__(J))return w;z=w+1}return null}dispose(){if(this.#J)return;this.#J=!0,this.#u.dispose(),this.#_.clear()}#Q(){if(this.#J)throw Error("SemanticLayer is disposed")}}import{eq as Mu,and as $_,sql as w0}from"drizzle-orm";var N_=80;class Bg{db;constructor(u){this.db=u}insertBatch(u,g,_){if(!_.length)return;let $=_.map((N)=>({project:u,filePath:g,tag:N.tag,value:N.value,source:N.source,symbolName:N.symbolName,startLine:N.startLine,startColumn:N.startColumn,endLine:N.endLine,endColumn:N.endColumn,indexedAt:N.indexedAt}));for(let N=0;N<$.length;N+=N_)this.db.drizzleDb.insert($u).values($.slice(N,N+N_)).run()}deleteFileAnnotations(u,g){this.db.drizzleDb.delete($u).where($_(Mu($u.project,u),Mu($u.filePath,g))).run()}search(u){return this.db.drizzleDb.select().from($u).where($_(u.project?Mu($u.project,u.project):void 0,u.tag?Mu($u.tag,u.tag):void 0,u.filePath?Mu($u.filePath,u.filePath):void 0,u.symbolName?Mu($u.symbolName,u.symbolName):void 0,u.source?Mu($u.source,u.source):void 0,u.ftsQuery?w0`${$u.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${u.ftsQuery})`:void 0)).limit(u.limit).all()}}import{eq as Au,and as J_,sql as qu,gt as z0,gte as O0}from"drizzle-orm";var Q_=80;class Lg{db;constructor(u){this.db=u}insertBatch(u){if(!u.length)return;let g=u.map((_)=>({project:_.project,changeType:_.changeType,symbolName:_.symbolName,symbolKind:_.symbolKind,filePath:_.filePath,oldName:_.oldName,oldFilePath:_.oldFilePath,fingerprint:_.fingerprint,changedAt:_.changedAt,isFullIndex:_.isFullIndex,indexRunId:_.indexRunId}));for(let _=0;_<g.length;_+=Q_)this.db.drizzleDb.insert(uu).values(g.slice(_,_+Q_)).run()}getSince(u){return this.db.drizzleDb.select().from(uu).where(J_(Au(uu.project,u.project),O0(uu.changedAt,u.since),u.symbolName?Au(uu.symbolName,u.symbolName):void 0,u.changeTypes?.length?qu`${uu.changeType} IN (${qu.join(u.changeTypes.map((g)=>qu`${g}`),qu`, `)})`:void 0,u.filePath?Au(uu.filePath,u.filePath):void 0,u.includeFullIndex?void 0:Au(uu.isFullIndex,0),u.indexRunId?Au(uu.indexRunId,u.indexRunId):void 0,u.afterId?z0(uu.id,u.afterId):void 0)).orderBy(uu.id).limit(u.limit).all()}pruneOlderThan(u,g){return this.db.drizzleDb.delete(uu).where(J_(Au(uu.project,u),qu`${uu.changedAt} < ${g}`)).run().changes}}function w_(u){let{annotationRepo:g,project:_,query:$}=u,N=$.project??_,z=$.limit??100,w;if($.text){let J=Hu($.text);if(J)w=J}return g.search({project:N,tag:$.tag,filePath:$.filePath,symbolName:$.symbolName,source:$.source,ftsQuery:w,limit:z}).map((J)=>({tag:J.tag,value:J.value,source:J.source,filePath:J.filePath,symbolName:J.symbolName,span:{start:{line:J.startLine,column:J.startColumn},end:{line:J.endLine,column:J.endColumn}}}))}class du{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(u){this.options=u}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let g=[this.options.project,...this.options.additionalProjects??[]].flatMap((_)=>[...this.options.relationRepo.getByType(_,"imports"),...this.options.relationRepo.getByType(_,"type-references"),...this.options.relationRepo.getByType(_,"re-exports")]);for(let _ of g){let{srcFilePath:$,dstFilePath:N}=_;if(!this.adjacencyList.has($))this.adjacencyList.set($,new Set);if(this.adjacencyList.get($).add(N),!this.adjacencyList.has(N))this.adjacencyList.set(N,new Set);if(!this.reverseAdjacencyList.has(N))this.reverseAdjacencyList.set(N,new Set);this.reverseAdjacencyList.get(N).add($)}}patchFiles(u,g,_){let $=new Set([...u,...g]);for(let N of $){let z=this.adjacencyList.get(N);if(z){for(let Q of z)this.reverseAdjacencyList.get(Q)?.delete(N);z.clear()}let w=this.reverseAdjacencyList.get(N);if(w){for(let Q of w)this.adjacencyList.get(Q)?.delete(N);w.clear()}}for(let N of g)this.adjacencyList.delete(N),this.reverseAdjacencyList.delete(N);for(let N of u){let z=_(N);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 g=new Set,_=[u];while(_.length>0){let $=_.shift();for(let N of this.reverseAdjacencyList.get($)??[])if(!g.has(N))g.add(N),_.push(N)}return Array.from(g)}hasCycle(){let u=new Set,g=new Set;for(let _ of this.adjacencyList.keys()){if(u.has(_))continue;let $=[{node:_,entered:!1}];while($.length>0){let N=$.pop();if(N.entered){g.delete(N.node);continue}if(g.has(N.node))return!0;if(u.has(N.node))continue;u.add(N.node),g.add(N.node),$.push({node:N.node,entered:!0});for(let z of this.adjacencyList.get(N.node)??[]){if(g.has(z))return!0;if(!u.has(z))$.push({node:z,entered:!1})}}}return!1}getAffectedByChange(u){let g=new Set;for(let _ of u)for(let $ of this.getTransitiveDependents(_))g.add($);return Array.from(g)}getAdjacencyList(){let u=new Map;for(let[g,_]of this.adjacencyList)u.set(g,Array.from(_));return u}getTransitiveDependencies(u){let g=new Set,_=[u];while(_.length>0){let $=_.shift();for(let N of this.adjacencyList.get($)??[])if(!g.has(N))g.add(N),_.push(N)}return Array.from(g)}getCyclePaths(u){let g=u?.maxCycles??1/0;if(g<=0)return[];let _=new Map;for(let[$,N]of this.adjacencyList)_.set($,Array.from(N));return X0(_,g)}}var W0=(u,g)=>u.localeCompare(g);function Y0(u){let g=u.length>1&&u[0]===u[u.length-1]?u.slice(0,-1):[...u];if(g.length===0)return[];let _=g;for(let $=1;$<g.length;$++){let N=g.slice($).concat(g.slice(0,$));if(N.join("::")<_.join("::"))_=N}return[..._]}function Dg(u,g,_){let $=Y0(_);if($.length===0)return!1;let N=$.join("->");if(u.has(N))return!1;return u.add(N),g.push($),!0}function V0(u){let g=0,_=[],$=new Set,N=new Map,z=new Map,w=[],Q=(J)=>{N.set(J,g),z.set(J,g),g+=1,_.push(J),$.add(J);for(let Y of u.get(J)??[])if(!N.has(Y))Q(Y),z.set(J,Math.min(z.get(J)??0,z.get(Y)??0));else if($.has(Y))z.set(J,Math.min(z.get(J)??0,N.get(Y)??0));if(z.get(J)===N.get(J)){let Y=[],O="";do O=_.pop()??"",$.delete(O),Y.push(O);while(O!==J&&_.length>0);w.push(Y)}};for(let J of u.keys())if(!N.has(J))Q(J);return{components:w}}function U0(u,g,_){let $=[],N=new Set,z=[...u].sort(W0),w=(Q,J,Y)=>{J.delete(Q);let O=Y.get(Q);if(!O)return;for(let W of O)if(J.has(W))w(W,J,Y);O.clear()};for(let Q=0;Q<z.length&&$.length<_;Q++){let J=z[Q]??"",Y=new Set(z.slice(Q)),O=new Set,W=new Map,Z=[],n=(D)=>(g.get(D)??[]).filter((k)=>Y.has(k)),A=(D)=>{if($.length>=_)return!0;let k=!1;Z.push(D),O.add(D);for(let G of n(D)){if($.length>=_)break;if(G===J)Dg(N,$,Z.concat(J)),k=!0;else if(!O.has(G)){if(A(G))k=!0}}if(k)w(D,O,W);else for(let G of n(D)){let i=W.get(G)??new Set;i.add(D),W.set(G,i)}return Z.pop(),k};A(J)}return $}function X0(u,g){let{components:_}=V0(u),$=[],N=new Set;for(let z of _){if($.length>=g)break;if(z.length===0)continue;if(z.length===1){let J=z[0]??"";if((u.get(J)??[]).includes(J))Dg(N,$,[J,J]);continue}let w=g-$.length,Q=U0(z,u,w);for(let J of Q){if($.length>=g)break;Dg(N,$,J)}}return $}var Z0=15000;function tu(u){u.graphCache=null,u.graphCacheKey=null,u.graphCacheBuiltAt=null}function Iu(u,g){let _=g??"__cross__";if(u.graphCache&&u.graphCacheBuiltAt!==null){if(Date.now()-u.graphCacheBuiltAt>Z0)u.graphCache=null,u.graphCacheKey=null,u.graphCacheBuiltAt=null}if(u.graphCache&&u.graphCacheKey===_)return u.graphCache;let $=new du({relationRepo:u.relationRepo,project:g??u.defaultProject,additionalProjects:g?void 0:u.boundaries?.map((N)=>N.project)});return $.build(),u.graphCache=$,u.graphCacheKey=_,u.graphCacheBuiltAt=Date.now(),$}function z_(u,g,_,$=1e4){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:_??u.defaultProject,query:{srcFilePath:g,type:"imports",project:_??u.defaultProject,limit:$}}).map((N)=>N.dstFilePath)}catch(N){if(N instanceof U)throw N;throw new U("search","Gildash: getDependencies failed",{cause:N})}}function O_(u,g,_,$=1e4){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:_??u.defaultProject,query:{dstFilePath:g,type:"imports",project:_??u.defaultProject,limit:$}}).map((N)=>N.srcFilePath)}catch(N){if(N instanceof U)throw N;throw new U("search","Gildash: getDependents failed",{cause:N})}}async function W_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return Iu(u,_).getAffectedByChange(g)}catch($){if($ instanceof U)throw $;throw new U("search","Gildash: getAffected failed",{cause:$})}}async function Y_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return Iu(u,g).hasCycle()}catch(_){if(_ instanceof U)throw _;throw new U("search","Gildash: hasCycle failed",{cause:_})}}async function V_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return Iu(u,g).getAdjacencyList()}catch(_){if(_ instanceof U)throw _;throw new U("search","Gildash: getImportGraph failed",{cause:_})}}async function U_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return Iu(u,_).getTransitiveDependencies(g)}catch($){if($ instanceof U)throw $;throw new U("search","Gildash: getTransitiveDependencies failed",{cause:$})}}async function X_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return Iu(u,g).getCyclePaths(_)}catch($){if($ instanceof U)throw $;throw new U("search","Gildash: getCyclePaths failed",{cause:$})}}async function Z_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{let $=Iu(u,_);return{filePath:g,fanIn:$.getDependents(g).length,fanOut:$.getDependencies(g).length}}catch($){if($ instanceof U)throw $;throw new U("search","Gildash: getFanMetrics failed",{cause:$})}}var n0=30000,K_=15000,H0=10;function B0(u,g){return(_)=>{for(let $ of u.onFileChangedCallbacks)try{$(_)}catch(N){u.logger.error("[Gildash] onFileChanged callback threw:",N)}if(g.handleWatcherEvent?.(_),u.semanticLayer)if(_.eventType==="delete")try{u.semanticLayer.notifyFileDeleted(_.filePath)}catch($){u.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",$);for(let N of u.onErrorCallbacks)try{N($ instanceof U?$:new U("semantic","semantic notifyFileDeleted failed",{cause:$}))}catch{}}else u.readFileFn(_.filePath).then(($)=>{try{u.semanticLayer?.notifyFileChanged(_.filePath,$)}catch(N){u.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",N);for(let z of u.onErrorCallbacks)try{z(N instanceof U?N:new U("semantic","semantic notifyFileChanged failed",{cause:N}))}catch{}}}).catch(($)=>{u.logger.error("[Gildash] failed to read file for semantic layer",_.filePath,$);try{u.semanticLayer?.notifyFileDeleted(_.filePath)}catch(N){u.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",N)}})}}async function L0(u){if(!u.semanticLayer)return;let g=u.fileRepo.getAllFiles(u.defaultProject);await Promise.all(g.map(async(_)=>{try{let $=ju.resolve(u.projectRoot,_.filePath),N=await u.readFileFn($);u.semanticLayer?.notifyFileChanged($,N)}catch{}}))}async function M_(u,g){let _=u.coordinatorFactory?u.coordinatorFactory():new Wg({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=_;for(let $ of u.onIndexedCallbacks)_.onIndexed($);if(_.onIndexed(($)=>{let N=$.changedFiles.length+$.deletedFiles.length;if(u.graphCache&&N>0&&N<100){let z=u.relationRepo;u.graphCache.patchFiles($.changedFiles,$.deletedFiles,(w)=>{return[u.defaultProject,...u.boundaries.map((J)=>J.project)].flatMap((J)=>z.getByType(J,"imports").concat(z.getByType(J,"type-references")).concat(z.getByType(J,"re-exports"))).filter((J)=>J.srcFilePath===w||J.dstFilePath===w).map((J)=>({srcFilePath:J.srcFilePath,dstFilePath:J.dstFilePath}))}),u.graphCacheBuiltAt=Date.now()}else tu(u)}),g.isWatchMode){let $=u.watcherFactory?u.watcherFactory():new _g({projectRoot:u.projectRoot,ignorePatterns:u.ignorePatterns,extensions:u.extensions},void 0,u.logger);await $.start(B0(u,_)).then((N)=>{if(Gu(N))throw N.data}),u.watcher=$,u.timer=setInterval(()=>{u.updateHeartbeatFn(u.db,process.pid)},n0)}await _.fullIndex(),await L0(u)}function D0(u,g){let _=["SIGTERM","SIGINT","beforeExit"];for(let $ of _){let N=()=>{g().catch((z)=>u.logger.error("[Gildash] close error during signal",$,z))};if($==="beforeExit")process.on("beforeExit",N);else process.on($,N);u.signalHandlers.push([$,N])}}async function n_(u){let{projectRoot:g,extensions:_=[".ts",".mts",".cts"],ignorePatterns:$=["**/node_modules/**"],parseCacheCapacity:N=500,logger:z=console,existsSyncFn:w=M0,dbConnectionFactory:Q,watcherFactory:J,coordinatorFactory:Y,repositoryFactory:O,acquireWatcherRoleFn:W=ag,releaseWatcherRoleFn:Z=cg,updateHeartbeatFn:n=sg,discoverProjectsFn:A=bu,parseSourceFn:D=Tu,extractSymbolsFn:k=Lu,extractRelationsFn:G=hu,symbolSearchFn:i=Vg,relationSearchFn:V=Ug,patternSearchFn:K=Xg,loadTsconfigPathsFn:M=Ru,readFileFn:R=async(B)=>Bun.file(B).text(),unlinkFn:I=async(B)=>{await Bun.file(B).unlink()},watchMode:C,semantic:v,semanticLayerFactory:y}=u;if(!ju.isAbsolute(g))throw new U("validation",`Gildash: projectRoot must be an absolute path, got: "${g}"`);if(!w(g))throw new U("validation",`Gildash: projectRoot does not exist: "${g}"`);let j=Q?Q():new su({projectRoot:g}),X=j.open();if(Gu(X))throw X.data;try{let B=await A(g),S=B[0]?.project??ju.basename(g),H=O?O():(()=>{let s=j;return{fileRepo:new ou(s),symbolRepo:new eu(s),relationRepo:new ug(s),parseCache:new Yg(N)}})(),P=O?null:j,q=P?new Bg(P):null,c=P?new Lg(P):null,b=C??!0,h=crypto.randomUUID(),E;if(b)E=await Promise.resolve(W(j,process.pid,{instanceId:h}));else E="owner";let T={projectRoot:g,extensions:_,ignorePatterns:$,logger:z,defaultProject:S,role:E,db:j,symbolRepo:H.symbolRepo,relationRepo:H.relationRepo,fileRepo:H.fileRepo,parseCache:H.parseCache,annotationRepo:q,changelogRepo:c,annotationSearchFn:w_,releaseWatcherRoleFn:Z,parseSourceFn:D,extractSymbolsFn:k,extractRelationsFn:G,symbolSearchFn:i,relationSearchFn:V,patternSearchFn:K,readFileFn:R,unlinkFn:I,existsSyncFn:w,acquireWatcherRoleFn:W,updateHeartbeatFn:n,watcherFactory:J,coordinatorFactory:Y,instanceId:h,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:B,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(fu(g),T.tsconfigPaths=await M(g),v){let s=ju.join(g,"tsconfig.json");try{if(y)T.semanticLayer=y(s);else{let o=ru.create(s);if(Gu(o))throw o.data;T.semanticLayer=o}}catch(o){if(o instanceof U)throw o;throw new U("semantic","Gildash: semantic layer creation failed",{cause:o})}}if(E==="owner")await M_(T,{isWatchMode:b});else{let s=0,o=async()=>{try{let Qu=await Promise.resolve(T.acquireWatcherRoleFn(T.db,process.pid,{instanceId:T.instanceId}));if(s=0,Qu==="owner"){T.role="owner";for(let Wu of T.onRoleChangedCallbacks)try{Wu("owner")}catch(_u){T.logger.error("[Gildash] onRoleChanged callback threw:",_u)}clearInterval(T.timer),T.timer=null;try{await M_(T,{isWatchMode:!0})}catch(Wu){if(T.logger.error("[Gildash] owner promotion failed, reverting to reader",Wu),T.role="reader",T.timer!==null)clearInterval(T.timer),T.timer=null;if(T.watcher){let _u=await T.watcher.close();if(Gu(_u))T.logger.error("[Gildash] watcher close error during promotion rollback",_u.data);T.watcher=null}if(T.coordinator)await T.coordinator.shutdown().catch((_u)=>T.logger.error("[Gildash] coordinator shutdown error during promotion rollback",_u)),T.coordinator=null;try{T.releaseWatcherRoleFn(T.db,process.pid)}catch(_u){T.logger.error("[Gildash] failed to release watcher role during promotion rollback",_u)}T.timer=setInterval(o,K_)}}}catch(Qu){s++;let Wu=Qu instanceof U?Qu:new U("watcher","Gildash: healthcheck error",{cause:Qu});for(let _u of T.onErrorCallbacks)try{_u(Wu)}catch(Cu){T.logger.error("[Gildash] onError callback threw:",Cu)}if(T.logger.error("[Gildash] healthcheck error",Qu),s>=H0)T.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(T.timer),T.timer=null,au(T).catch((_u)=>T.logger.error("[Gildash] close error during healthcheck shutdown",_u))}};T.timer=setInterval(o,K_)}if(b)D0(T,()=>au(T));return T}catch(B){if(j.close(),B instanceof U)throw B;throw new U("store","Gildash: initialization failed",{cause:B})}}async function au(u,g){if(u.closed)return;u.closed=!0;let _=[];for(let[$,N]of u.signalHandlers)if($==="beforeExit")process.off("beforeExit",N);else process.off($,N);if(u.signalHandlers=[],u.semanticLayer){try{u.semanticLayer.dispose()}catch($){_.push($ instanceof Error?$:Error(String($)))}u.semanticLayer=null}if(u.coordinator)try{await u.coordinator.shutdown()}catch($){_.push($ instanceof Error?$:Error(String($)))}if(u.watcher){let $=await u.watcher.close();if(Gu($))_.push($.data)}if(u.timer!==null)clearInterval(u.timer),u.timer=null;try{u.releaseWatcherRoleFn(u.db,process.pid)}catch($){_.push($ instanceof Error?$:Error(String($)))}try{u.db.close()}catch($){_.push($ instanceof Error?$:Error(String($)))}if(g?.cleanup)for(let $ of["","-wal","-shm"])try{await u.unlinkFn(ju.join(u.projectRoot,Yu,Eu+$))}catch{}if(_.length>0)throw new U("close","Gildash: one or more errors occurred during close()",{cause:_})}import{isErr as H_}from"@zipbul/result";function B_(u,g,_,$){if(u.closed)throw new U("closed","Gildash: instance is closed");let N=u.parseSourceFn(g,_,$);if(H_(N))throw N.data;return u.parseCache.set(g,N),N}async function L_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");let $=new Map,N=[];return await Promise.all(g.map(async(z)=>{try{let w=await u.readFileFn(z),Q=u.parseSourceFn(z,w,_);if(!H_(Q))$.set(z,Q);else N.push({filePath:z,error:Q.data})}catch(w){N.push({filePath:z,error:w instanceof Error?w:Error(String(w))})}})),{parsed:$,failures:N}}function D_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");return u.parseCache.get(g)}function A_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");return u.extractSymbolsFn(g)}function I_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");return u.extractRelationsFn(g.program,g.filePath,u.tsconfigPaths??void 0)}import C_ from"path";function S_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.symbolRepo.getStats(g??u.defaultProject)}catch(_){if(_ instanceof U)throw _;throw new U("store","Gildash: getStats failed",{cause:_})}}function Ag(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.symbolSearchFn({symbolRepo:u.symbolRepo,project:u.defaultProject,query:g})}catch(_){if(_ instanceof U)throw _;throw new U("search","Gildash: searchSymbols failed",{cause:_})}}function R_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:u.defaultProject,query:g})}catch(_){if(_ instanceof U)throw _;throw new U("search","Gildash: searchRelations failed",{cause:_})}}function T_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.symbolSearchFn({symbolRepo:u.symbolRepo,project:void 0,query:g})}catch(_){if(_ instanceof U)throw _;throw new U("search","Gildash: searchAllSymbols failed",{cause:_})}}function k_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:void 0,query:g})}catch(_){if(_ instanceof U)throw _;throw new U("search","Gildash: searchAllRelations failed",{cause:_})}}function F_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.fileRepo.getAllFiles(g??u.defaultProject)}catch(_){if(_ instanceof U)throw _;throw new U("store","Gildash: listIndexedFiles failed",{cause:_})}}function q_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:_??u.defaultProject,query:{srcFilePath:g,dstFilePath:g,limit:1e4}})}catch($){if($ instanceof U)throw $;throw new U("search","Gildash: getInternalRelations failed",{cause:$})}}function G_(u,g,_,$){if(u.closed)throw new U("closed","Gildash: instance is closed");try{let N=$??u.defaultProject,z=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:N,query:{text:g,exact:!0,filePath:_,limit:1}});if(z.length===0)return null;let w=z[0],Q=w.detail,J={...w,members:Array.isArray(Q.members)?Q.members:void 0,jsDoc:typeof Q.jsDoc==="string"?Q.jsDoc:void 0,parameters:typeof Q.parameters==="string"?Q.parameters:void 0,returnType:typeof Q.returnType==="string"?Q.returnType:void 0,heritage:Array.isArray(Q.heritage)?Q.heritage:void 0,decorators:Array.isArray(Q.decorators)?Q.decorators:void 0,typeParameters:typeof Q.typeParameters==="string"?Q.typeParameters:void 0};if(u.semanticLayer)try{let Y=C_.isAbsolute(_)?_:C_.resolve(u.projectRoot,_),O=u.semanticLayer.lineColumnToPosition(Y,w.span.start.line,w.span.start.column);if(O!==null){let W=u.semanticLayer.findNamePosition(Y,O,w.name)??O,Z=u.semanticLayer.collectTypeAt(Y,W);if(Z)J.resolvedType=Z}}catch{}return J}catch(N){if(N instanceof U)throw N;throw new U("search","Gildash: getFullSymbol failed",{cause:N})}}function j_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{let $=_??u.defaultProject,N=u.fileRepo.getFile($,g);if(!N)throw new U("search",`Gildash: file '${g}' is not in the index`);let z=u.symbolRepo.getFileSymbols($,g),w=u.relationRepo.getOutgoing($,g);return{filePath:N.filePath,lineCount:N.lineCount??0,size:N.size,symbolCount:z.length,exportedSymbolCount:z.filter((Q)=>Q.isExported).length,relationCount:w.length}}catch($){if($ instanceof U)throw $;throw new U("store","Gildash: getFileStats failed",{cause:$})}}function E_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.fileRepo.getFile(_??u.defaultProject,g)}catch($){if($ instanceof U)throw $;throw new U("store","Gildash: getFileInfo failed",{cause:$})}}function v_(u,g,_){return Ag(u,{filePath:g,project:_??void 0,limit:1e4})}function P_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{let N=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:_??u.defaultProject,query:{filePath:g,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:g,exports:N}}catch($){if($ instanceof U)throw $;throw new U("search","Gildash: getModuleInterface failed",{cause:$})}}import b_ from"path";function Ig(u,g,_,$){let N=$??u.defaultProject,z=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:N,query:{text:g,exact:!0,filePath:_,limit:1}});if(z.length===0)return null;let w=z[0],Q=b_.isAbsolute(_)?_:b_.resolve(u.projectRoot,_),J=u.semanticLayer.lineColumnToPosition(Q,w.span.start.line,w.span.start.column);if(J===null)return null;let Y=u.semanticLayer.findNamePosition(Q,J,w.name)??J;return{sym:w,position:Y,absPath:Q}}function f_(u,g,_,$){if(u.closed)throw new U("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new U("semantic","Gildash: semantic layer is not enabled");try{let N=Ig(u,g,_,$);if(!N)return null;return u.semanticLayer.collectTypeAt(N.absPath,N.position)}catch(N){if(N instanceof U)throw N;throw new U("search","Gildash: getResolvedType failed",{cause:N})}}function y_(u,g,_,$){if(u.closed)throw new U("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new U("semantic","Gildash: semantic layer is not enabled");try{let N=Ig(u,g,_,$);if(!N)throw new U("search",`Gildash: symbol '${g}' not found in '${_}'`);return u.semanticLayer.findReferences(N.absPath,N.position)}catch(N){if(N instanceof U)throw N;throw new U("search","Gildash: getSemanticReferences failed",{cause:N})}}function i_(u,g,_,$){if(u.closed)throw new U("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new U("semantic","Gildash: semantic layer is not enabled");try{let N=Ig(u,g,_,$);if(!N)throw new U("search",`Gildash: symbol '${g}' not found in '${_}'`);return u.semanticLayer.findImplementations(N.absPath,N.position)}catch(N){if(N instanceof U)throw N;throw new U("search","Gildash: getImplementations failed",{cause:N})}}function m_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new U("semantic","Gildash: semantic layer is not enabled");try{return u.semanticLayer.getModuleInterface(g)}catch(_){if(_ instanceof U)throw _;throw new U("search","Gildash: getSemanticModuleInterface failed",{cause:_})}}function h_(u,g){let _=new Map(u.map((Q)=>[`${Q.name}::${Q.filePath}`,Q])),$=new Map(g.map((Q)=>[`${Q.name}::${Q.filePath}`,Q])),N=[],z=[],w=[];for(let[Q,J]of $){let Y=_.get(Q);if(!Y)N.push(J);else if(Y.fingerprint!==J.fingerprint)w.push({before:Y,after:J})}for(let[Q,J]of _)if(!$.has(Q))z.push(J);return{added:N,removed:z,modified:w}}function x_(u,g){if(u.onIndexedCallbacks.add(g),!u.coordinator)return()=>{u.onIndexedCallbacks.delete(g)};let _=u.coordinator.onIndexed(g);return()=>{u.onIndexedCallbacks.delete(g),_()}}async function p_(u){if(u.closed)throw new U("closed","Gildash: instance is closed");if(!u.coordinator)throw new U("closed","Gildash: reindex() is not available for readers");try{let g=await u.coordinator.fullIndex();return tu(u),g}catch(g){if(g instanceof U)throw g;throw new U("index","Gildash: reindex failed",{cause:g})}}function l_(u,g,_,$){if(u.closed)throw new U("closed","Gildash: instance is closed");let N=$??u.defaultProject,z=new Set,w=[],Q=g,J=_;for(;;){let Y=`${J}::${Q}`;if(z.has(Y))return{originalName:Q,originalFilePath:J,reExportChain:w,circular:!0};z.add(Y);let O=u.relationSearchFn({relationRepo:u.relationRepo,project:N,query:{type:"re-exports",srcFilePath:J,limit:500}}),W,Z;for(let n of O){let A;if(n.metaJson)try{let k=JSON.parse(n.metaJson);if(Array.isArray(k.specifiers))A=k.specifiers}catch{}if(!A)continue;let D=A.find((k)=>k.exported===Q);if(!D)continue;W=n.dstFilePath,Z=D.local;break}if(!W||!Z)return{originalName:Q,originalFilePath:J,reExportChain:w,circular:!1};w.push({filePath:J,exportedAs:Q}),J=W,Q=Z}}function r_(u,g){return u.onFileChangedCallbacks.add(g),()=>{u.onFileChangedCallbacks.delete(g)}}function d_(u,g){return u.onErrorCallbacks.add(g),()=>{u.onErrorCallbacks.delete(g)}}function t_(u,g){return u.onRoleChangedCallbacks.add(g),()=>{u.onRoleChangedCallbacks.delete(g)}}async function a_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{let $=_?.project??u.defaultProject,N=_?.filePaths?_.filePaths:u.fileRepo.getAllFiles($).map((z)=>z.filePath);return await u.patternSearchFn({pattern:g,filePaths:N})}catch($){if($ instanceof U)throw $;throw new U("search","Gildash: findPattern failed",{cause:$})}}async function c_(u,g,_,$){if(u.closed)throw new U("closed","Gildash: instance is closed");try{let N=$??u.defaultProject,z=new Set,w=(Q,J,Y)=>{let O=`${Q}::${J}`;if(z.has(O))return{symbolName:Q,filePath:J,kind:Y,children:[]};z.add(O);let n=u.relationSearchFn({relationRepo:u.relationRepo,project:N,query:{srcFilePath:J,srcSymbolName:Q,limit:1000}}).filter((A)=>A.type==="extends"||A.type==="implements").filter((A)=>A.dstSymbolName!=null).map((A)=>w(A.dstSymbolName,A.dstFilePath,A.type));return{symbolName:Q,filePath:J,kind:Y,children:n}};return w(g,_)}catch(N){if(N instanceof U)throw N;throw new U("search","Gildash: getHeritageChain failed",{cause:N})}}function s_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");if(!u.annotationRepo||!u.annotationSearchFn)return[];return u.annotationSearchFn({annotationRepo:u.annotationRepo,project:g.project??u.defaultProject,query:g})}function o_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");if(!u.changelogRepo)return[];let $=g instanceof Date?g.toISOString():g,N=_?.project??u.defaultProject,z=_?.limit??1000;return u.changelogRepo.getSince({project:N,since:$,symbolName:_?.symbolName,changeTypes:_?.changeTypes,filePath:_?.filePath,includeFullIndex:_?.includeFullIndex,indexRunId:_?.indexRunId,afterId:_?.afterId,limit:z}).map((Q)=>({changeType:Q.changeType,symbolName:Q.symbolName,symbolKind:Q.symbolKind,filePath:Q.filePath,oldName:Q.oldName,oldFilePath:Q.oldFilePath,fingerprint:Q.fingerprint,changedAt:Q.changedAt,isFullIndex:Q.isFullIndex===1,indexRunId:Q.indexRunId}))}function e_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");if(!u.changelogRepo)return 0;let _=g instanceof Date?g.toISOString():g,$=0,N=[u.defaultProject,...u.boundaries.map((w)=>w.project)],z=[...new Set(N)];for(let w of z)$+=u.changelogRepo.pruneOlderThan(w,_);return $}class Cg{_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 g=await n_(u);return new Cg(g)}async close(u){return au(this._ctx,u)}parseSource(u,g,_){return B_(this._ctx,u,g,_)}async batchParse(u,g){return L_(this._ctx,u,g)}getParsedAst(u){return D_(this._ctx,u)}extractSymbols(u){return A_(this._ctx,u)}extractRelations(u){return I_(this._ctx,u)}getStats(u){return S_(this._ctx,u)}searchSymbols(u){return Ag(this._ctx,u)}searchRelations(u){return R_(this._ctx,u)}searchAllSymbols(u){return T_(this._ctx,u)}searchAllRelations(u){return k_(this._ctx,u)}listIndexedFiles(u){return F_(this._ctx,u)}getInternalRelations(u,g){return q_(this._ctx,u,g)}getFullSymbol(u,g,_){return G_(this._ctx,u,g,_)}getFileStats(u,g){return j_(this._ctx,u,g)}getFileInfo(u,g){return E_(this._ctx,u,g)}getSymbolsByFile(u,g){return v_(this._ctx,u,g)}getModuleInterface(u,g){return P_(this._ctx,u,g)}getDependencies(u,g,_=1e4){return z_(this._ctx,u,g,_)}getDependents(u,g,_=1e4){return O_(this._ctx,u,g,_)}async getAffected(u,g){return W_(this._ctx,u,g)}async hasCycle(u){return Y_(this._ctx,u)}async getImportGraph(u){return V_(this._ctx,u)}async getTransitiveDependencies(u,g){return U_(this._ctx,u,g)}async getCyclePaths(u,g){return X_(this._ctx,u,g)}async getFanMetrics(u,g){return Z_(this._ctx,u,g)}getResolvedType(u,g,_){return f_(this._ctx,u,g,_)}getSemanticReferences(u,g,_){return y_(this._ctx,u,g,_)}getImplementations(u,g,_){return i_(this._ctx,u,g,_)}getSemanticModuleInterface(u){return m_(this._ctx,u)}diffSymbols(u,g){return h_(u,g)}onIndexed(u){return x_(this._ctx,u)}async reindex(){return p_(this._ctx)}resolveSymbol(u,g,_){return l_(this._ctx,u,g,_)}async findPattern(u,g){return a_(this._ctx,u,g)}async getHeritageChain(u,g,_){return c_(this._ctx,u,g,_)}onFileChanged(u){return r_(this._ctx,u)}onError(u){return d_(this._ctx,u)}onRoleChanged(u){return t_(this._ctx,u)}searchAnnotations(u){return s_(this._ctx,u)}getSymbolChanges(u,g){return o_(this._ctx,u,g)}pruneChangelog(u){return e_(this._ctx,u)}}export{Vg as symbolSearch,Ug as relationSearch,Xg as patternSearch,e as gildashError,U as GildashError,Cg as Gildash,du as DependencyGraph};
2
+ var W$=Object.defineProperty;var V$=(u)=>u;function U$(u,g){this[u]=V$.bind(null,g)}var Y$=(u,g)=>{for(var _ in g)W$(u,_,{get:g[_],enumerable:!0,configurable:!0,set:U$.bind(g,_)})};var Gg=import.meta.require;import{isErr as Eu}from"@zipbul/result";import vu from"path";import{existsSync as R0}from"fs";import{err as jg,isErr as H$}from"@zipbul/result";import{Database as L$}from"bun:sqlite";import{mkdirSync as I$,unlinkSync as Eg,existsSync as vg}from"fs";import{dirname as D$,join as bg}from"path";import{drizzle as A$}from"drizzle-orm/bun-sqlite";import{migrate as C$}from"drizzle-orm/bun-sqlite/migrator";class Y extends Error{type;constructor(u,g,_){super(g,_);this.type=u;this.name="GildashError"}}function _u(u,g,_){return new Y(u,g,_!==void 0?{cause:_}:void 0)}var Yu=".gildash",fu="gildash.db";var ug={};Y$(ug,{watcherOwner:()=>B$,symbols:()=>b,symbolChangelog:()=>$u,relations:()=>L,files:()=>a,annotations:()=>Nu});import{sql as Z$}from"drizzle-orm";import{sqliteTable as Iu,text as G,integer as uu,real as X$,index as Ju,primaryKey as K$,foreignKey as Pu,check as M$}from"drizzle-orm/sqlite-core";var a=Iu("files",{project:G("project").notNull(),filePath:G("file_path").notNull(),mtimeMs:X$("mtime_ms").notNull(),size:uu("size").notNull(),contentHash:G("content_hash").notNull(),updatedAt:G("updated_at").notNull(),lineCount:uu("line_count")},(u)=>[K$({columns:[u.project,u.filePath]})]),b=Iu("symbols",{id:uu("id").primaryKey({autoIncrement:!0}),project:G("project").notNull(),filePath:G("file_path").notNull(),kind:G("kind").notNull(),name:G("name").notNull(),startLine:uu("start_line").notNull(),startColumn:uu("start_column").notNull(),endLine:uu("end_line").notNull(),endColumn:uu("end_column").notNull(),isExported:uu("is_exported").notNull().default(0),signature:G("signature"),fingerprint:G("fingerprint"),detailJson:G("detail_json"),contentHash:G("content_hash").notNull(),indexedAt:G("indexed_at").notNull(),resolvedType:G("resolved_type"),structuralFingerprint:G("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),Pu({columns:[u.project,u.filePath],foreignColumns:[a.project,a.filePath]}).onDelete("cascade")]),L=Iu("relations",{id:uu("id").primaryKey({autoIncrement:!0}),project:G("project").notNull(),type:G("type").notNull(),srcFilePath:G("src_file_path").notNull(),srcSymbolName:G("src_symbol_name"),dstProject:G("dst_project").notNull(),dstFilePath:G("dst_file_path").notNull(),dstSymbolName:G("dst_symbol_name"),metaJson:G("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),Pu({columns:[u.project,u.srcFilePath],foreignColumns:[a.project,a.filePath]}).onDelete("cascade"),Pu({columns:[u.dstProject,u.dstFilePath],foreignColumns:[a.project,a.filePath]}).onDelete("cascade")]),Nu=Iu("annotations",{id:uu("id").primaryKey({autoIncrement:!0}),project:G("project").notNull(),filePath:G("file_path").notNull(),tag:G("tag").notNull(),value:G("value").notNull().default(""),source:G("source").notNull(),symbolName:G("symbol_name"),startLine:uu("start_line").notNull(),startColumn:uu("start_column").notNull(),endLine:uu("end_line").notNull(),endColumn:uu("end_column").notNull(),indexedAt:G("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),Pu({columns:[u.project,u.filePath],foreignColumns:[a.project,a.filePath]}).onDelete("cascade")]),$u=Iu("symbol_changelog",{id:uu("id").primaryKey({autoIncrement:!0}),project:G("project").notNull(),changeType:G("change_type").notNull(),symbolName:G("symbol_name").notNull(),symbolKind:G("symbol_kind").notNull(),filePath:G("file_path").notNull(),oldName:G("old_name"),oldFilePath:G("old_file_path"),fingerprint:G("fingerprint"),changedAt:G("changed_at").notNull(),isFullIndex:uu("is_full_index").notNull().default(0),indexRunId:G("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)]),B$=Iu("watcher_owner",{id:uu("id").primaryKey(),pid:uu("pid").notNull(),startedAt:G("started_at").notNull(),heartbeatAt:G("heartbeat_at").notNull(),instanceId:G("instance_id")},(u)=>[M$("watcher_owner_singleton",Z$`${u.id} = 1`)]);class gg{client=null;drizzle=null;dbPath;txDepth=0;constructor(u){this.dbPath=bg(u.projectRoot,Yu,fu)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{I$(D$(this.dbPath),{recursive:!0}),this.client=new L$(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=A$(this.client,{schema:ug}),C$(this.drizzle,{migrationsFolder:bg(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)&&vg(this.dbPath)){this.closeClient(),Eg(this.dbPath);for(let _ of["-wal","-shm"]){let $=this.dbPath+_;if(vg($))Eg($)}let g=this.open();if(H$(g))return jg(_u("store",`Failed to recover database at ${this.dbPath}`,g.data));return g}return jg(_u("store",`Failed to open database at ${this.dbPath}`,u))}}close(){this.closeClient(),this.drizzle=null}transaction(u){let g=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return g.transaction(()=>u(this))()}finally{this.txDepth--}}let _=`sp_${this.txDepth++}`;g.run(`SAVEPOINT "${_}"`);try{let $=u(this);return g.run(`RELEASE SAVEPOINT "${_}"`),$}catch($){throw g.run(`ROLLBACK TO SAVEPOINT "${_}"`),g.run(`RELEASE SAVEPOINT "${_}"`),$}finally{this.txDepth--}}immediateTransaction(u){let g=this.requireClient();this.txDepth++,g.run("BEGIN IMMEDIATE");try{let _=u();return g.run("COMMIT"),_}catch(_){throw g.run("ROLLBACK"),_}finally{this.txDepth--}}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((g)=>g.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(u,g){let _=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(u,_,_,g??null)}replaceOwner(u,g){let _=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??null)}touchOwner(u){let g=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(g,u)}deleteOwner(u){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(u)}registerRegexpUdf(u){let g=u;if(typeof g.function!=="function")return;g.function.call(u,"regexp",(_,$)=>{try{return new RegExp(_).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 g=u.message.toLowerCase();return g.includes("malformed")||g.includes("corrupt")||g.includes("not a database")||g.includes("disk i/o error")||g.includes("sqlite_corrupt")}}import{eq as ku,and as fg}from"drizzle-orm";class _g{db;constructor(u){this.db=u}getFile(u,g){return this.db.drizzleDb.select().from(a).where(fg(ku(a.project,u),ku(a.filePath,g))).get()??null}upsertFile(u){this.db.drizzleDb.insert(a).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:[a.project,a.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(a).where(ku(a.project,u)).all()}getFilesMap(u){let g=this.getAllFiles(u),_=new Map;for(let $ of g)_.set($.filePath,$);return _}deleteFile(u,g){this.db.drizzleDb.delete(a).where(fg(ku(a.project,u),ku(a.filePath,g))).run()}}import{eq as t,and as Ku,sql as yu,count as S$}from"drizzle-orm";function Du(u){return u.replaceAll("\x00","").trim().split(/\s+/).map((g)=>g.trim()).filter((g)=>g.length>0).map((g)=>`"${g.replaceAll('"','""')}"*`).join(" ")}var Pg=50;class $g{db;constructor(u){this.db=u}replaceFileSymbols(u,g,_,$){if(this.db.drizzleDb.delete(b).where(Ku(t(b.project,u),t(b.filePath,g))).run(),!$.length)return;let J=new Date().toISOString(),O=$.map((Q)=>({project:u,filePath:g,kind:Q.kind??"unknown",name:Q.name??"",startLine:Q.startLine??0,startColumn:Q.startColumn??0,endLine:Q.endLine??0,endColumn:Q.endColumn??0,isExported:Q.isExported??0,signature:Q.signature??null,fingerprint:Q.fingerprint??null,detailJson:Q.detailJson??null,contentHash:_,indexedAt:Q.indexedAt??J,resolvedType:Q.resolvedType??null,structuralFingerprint:Q.structuralFingerprint??null}));for(let Q=0;Q<O.length;Q+=Pg)this.db.drizzleDb.insert(b).values(O.slice(Q,Q+Pg)).run()}getFileSymbols(u,g){return this.db.drizzleDb.select().from(b).where(Ku(t(b.project,u),t(b.filePath,g))).all()}searchByName(u,g,_={}){let $=_.limit??50,J=Du(g);if(!J)return[];return this.db.drizzleDb.select().from(b).where(Ku(yu`${b.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${J})`,t(b.project,u),_.kind?t(b.kind,_.kind):void 0)).orderBy(b.name).limit($).all()}searchByKind(u,g){return this.db.drizzleDb.select().from(b).where(Ku(t(b.project,u),t(b.kind,g))).orderBy(b.name).all()}getStats(u){let g=this.db.drizzleDb.select({symbolCount:S$(),fileCount:yu`COUNT(DISTINCT ${b.filePath})`}).from(b).where(t(b.project,u)).get();return{symbolCount:g?.symbolCount??0,fileCount:g?.fileCount??0}}getByFingerprint(u,g){return this.db.drizzleDb.select().from(b).where(Ku(t(b.project,u),t(b.fingerprint,g))).all()}deleteFileSymbols(u,g){this.db.drizzleDb.delete(b).where(Ku(t(b.project,u),t(b.filePath,g))).run()}searchByQuery(u){let g=this.db.drizzleDb.select().from(b).where(Ku(u.ftsQuery?yu`${b.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${u.ftsQuery})`:void 0,u.exactName?t(b.name,u.exactName):void 0,u.project!==void 0?t(b.project,u.project):void 0,u.kind?t(b.kind,u.kind):void 0,u.filePath!==void 0?t(b.filePath,u.filePath):void 0,u.isExported!==void 0?t(b.isExported,u.isExported?1:0):void 0,u.decorator?yu`${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?t(b.resolvedType,u.resolvedType):void 0)).orderBy(b.name);if(!u.regex)return g.limit(u.limit).all();let _;try{_=new RegExp(u.regex)}catch{throw new Y("validation",`Invalid regex pattern: ${u.regex}`)}let $=[];for(let J of[5,20,100]){let O=u.limit*J,Q=g.limit(O).all();if($=Q.filter((z)=>_.test(z.name)),$.length>=u.limit||Q.length<O)return $.slice(0,u.limit)}return $.slice(0,u.limit)}}import{eq as l,and as Wu,isNull as yg,or as R$}from"drizzle-orm";class Jg{db;constructor(u){this.db=u}replaceFileRelations(u,g,_){this.db.transaction(($)=>{if($.drizzleDb.delete(L).where(Wu(l(L.project,u),l(L.srcFilePath,g))).run(),!_.length)return;for(let J of _)$.drizzleDb.insert(L).values({project:u,type:J.type??"unknown",srcFilePath:J.srcFilePath??g,srcSymbolName:J.srcSymbolName??null,dstProject:J.dstProject??u,dstFilePath:J.dstFilePath??"",dstSymbolName:J.dstSymbolName??null,metaJson:J.metaJson??null}).run()})}getOutgoing(u,g,_){if(_!==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(l(L.project,u),l(L.srcFilePath,g),R$(l(L.srcSymbolName,_),yg(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(l(L.project,u),l(L.srcFilePath,g))).all()}getIncoming(u){let{dstProject:g,dstFilePath:_}=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(l(L.dstProject,g),l(L.dstFilePath,_))).all()}getByType(u,g){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(l(L.project,u),l(L.type,g))).all()}deleteFileRelations(u,g){this.db.drizzleDb.delete(L).where(Wu(l(L.project,u),l(L.srcFilePath,g))).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?l(L.project,u.project):void 0,u.srcFilePath!==void 0?l(L.srcFilePath,u.srcFilePath):void 0,u.srcSymbolName!==void 0?l(L.srcSymbolName,u.srcSymbolName):void 0,u.dstProject!==void 0?l(L.dstProject,u.dstProject):void 0,u.dstFilePath!==void 0?l(L.dstFilePath,u.dstFilePath):void 0,u.dstSymbolName!==void 0?l(L.dstSymbolName,u.dstSymbolName):void 0,u.type!==void 0?l(L.type,u.type):void 0)).limit(u.limit).all()}retargetRelations(u){let{dstProject:g,oldFile:_,oldSymbol:$,newFile:J,newSymbol:O,newDstProject:Q}=u,z=$===null?Wu(l(L.dstProject,g),l(L.dstFilePath,_),yg(L.dstSymbolName)):Wu(l(L.dstProject,g),l(L.dstFilePath,_),l(L.dstSymbolName,$)),N={dstFilePath:J,dstSymbolName:O};if(Q!==void 0)N.dstProject=Q;this.db.drizzleDb.update(L).set(N).where(z).run()}}import{err as mg}from"@zipbul/result";import{subscribe as n$}from"@parcel/watcher";import Ng from"path";var k$=["**/.git/**",`**/${Yu}/**`,"**/dist/**","**/node_modules/**"],T$=new Set(["package.json","tsconfig.json"]);function q$(u){return u.replaceAll("\\","/")}function F$(u){if(u==="update")return"change";if(u==="create")return"create";return"delete"}class Qg{#u;#g;#_;#J;#$;#N;constructor(u,g=n$,_=console){this.#g=u.projectRoot,this.#_=[...k$,...u.ignorePatterns??[]],this.#J=new Set((u.extensions??[".ts",".mts",".cts"]).map(($)=>$.toLowerCase())),this.#$=g,this.#N=_}async start(u){try{this.#u=await this.#$(this.#g,(g,_)=>{if(g){this.#N.error(_u("watcher","Callback error",g));return}try{for(let $ of _){let J=q$(Ng.relative(this.#g,$.path));if(J.startsWith(".."))continue;let O=Ng.basename(J),Q=Ng.extname(J).toLowerCase();if(!T$.has(O)&&!this.#J.has(Q))continue;if(J.endsWith(".d.ts"))continue;u({eventType:F$($.type),filePath:J})}}catch($){this.#N.error(_u("watcher","Callback error",$))}},{ignore:this.#_})}catch(g){return mg(_u("watcher","Failed to subscribe watcher",g))}}async close(){if(!this.#u)return;try{await this.#u.unsubscribe(),this.#u=void 0}catch(u){return mg(_u("watcher","Failed to close watcher",u))}}}import zg from"path";import{promises as G$}from"fs";var j$=["**/node_modules/**","**/.git/**",`**/${Yu}/**`,"**/dist/**"];async function mu(u){let g=[];for await(let _ of G$.glob("**/package.json",{cwd:u,exclude:j$})){let $=zg.dirname(_).replaceAll("\\","/"),J=zg.join(u,_),O=await Bun.file(J).json(),Q=typeof O?.name==="string"&&O.name.length>0?O.name:zg.basename($==="."?u:$);g.push({dir:$,project:Q})}return g.sort((_,$)=>$.dir.length-_.dir.length),g}function r(u,g,_="default"){let $=u.replaceAll("\\","/");for(let J of g){if(J.dir===".")return J.project;if($===J.dir||$.startsWith(`${J.dir}/`))return J.project}return _}import hg from"path";var Zu=new Map;async function E$(u){let g=Bun.file(u);if(!await g.exists())return null;try{let _=await g.text(),$=Bun.JSONC.parse(_);return typeof $==="object"&&$!==null?$:null}catch{return null}}async function Tu(u){if(Zu.has(u))return Zu.get(u)??null;let g=hg.join(u,"tsconfig.json"),_=await E$(g);if(!_)return Zu.set(u,null),null;let $=typeof _.compilerOptions==="object"&&_.compilerOptions!==null?_.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 Q=J?hg.resolve(u,J):u,z=new Map;if(O)for(let[W,w]of Object.entries(O)){if(!Array.isArray(w))continue;let V=w.filter((X)=>typeof X==="string");z.set(W,V)}let N={baseUrl:Q,paths:z};return Zu.set(u,N),N}function hu(u){if(u){Zu.delete(u);return}Zu.clear()}import ig from"path";function iu(u,g){return ig.relative(u,g).replaceAll("\\","/")}function Au(u,g){return ig.resolve(u,g)}function Qu(u){let g=Bun.hash.xxHash64(u);return BigInt.asUintN(64,BigInt(g)).toString(16).padStart(16,"0")}import{isErr as eg}from"@zipbul/result";import{err as v$}from"@zipbul/result";import{parseSync as b$}from"oxc-parser";function qu(u,g,_,$=b$){try{let{program:J,errors:O,comments:Q}=$(u,g,_);return{filePath:u,program:J,errors:O,comments:Q,sourceText:g}}catch(J){return v$(_u("parse",`Failed to parse file: ${u}`,J))}}import{promises as f$}from"fs";import{join as P$}from"path";async function xg(u){let{projectRoot:g,extensions:_,ignorePatterns:$,fileRepo:J}=u,O=J.getFilesMap(),Q=new Set,z=[],N=[],W=$.map((V)=>new Bun.Glob(V));for await(let V of f$.glob("**/*",{cwd:g})){if(!_.some((Z)=>V.endsWith(Z)))continue;if(V.startsWith("node_modules/")||V.includes("/node_modules/"))continue;if(W.some((Z)=>Z.match(V)))continue;Q.add(V);let X=P$(g,V),M=Bun.file(X),{size:I,lastModified:A}=M,T=O.get(V);if(!T){let Z=await M.text(),K=Qu(Z);z.push({filePath:V,contentHash:K,mtimeMs:A,size:I});continue}if(T.mtimeMs===A&&T.size===I){N.push({filePath:V,contentHash:T.contentHash,mtimeMs:A,size:I});continue}let q=await M.text(),h=Qu(q);if(h===T.contentHash)N.push({filePath:V,contentHash:h,mtimeMs:A,size:I});else z.push({filePath:V,contentHash:h,mtimeMs:A,size:I})}let w=[];for(let V of O.keys())if(!Q.has(V))w.push(V);return{changed:z,unchanged:N,deleted:w}}function xu(u){let g=[0];for(let _=0;_<u.length;_++)if(u[_]===`
3
+ `)g.push(_+1);return g}function zu(u,g){let _=0,$=u.length-1;while(_<$){let J=_+$+1>>1;if(u[J]<=g)_=J;else $=J-1}return{line:_+1,column:g-u[_]}}import{err as y$}from"@zipbul/result";import{parse as m$}from"comment-parser";function pu(u){try{let g=u.trim();if(g.startsWith("/**"))g=g.slice(3);if(g.endsWith("*/"))g=g.slice(0,-2);let $=m$(`/** ${g} */`)[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(g){return y$(_u("parse","Failed to parse JSDoc comment",g))}}import{isErr as h$}from"@zipbul/result";function Cu(u){let{program:g,sourceText:_,comments:$}=u,J=xu(_),O=$.filter((Z)=>Z.type==="Block"&&Z.value.startsWith("*")).sort((Z,K)=>Z.end-K.end),Q=g.body.map((Z)=>Z.start??0).sort((Z,K)=>Z-K);function z(Z,K){return{start:zu(J,Z),end:zu(J,K)}}function N(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 k=O[R];K=0,B=Q.length-1;while(K<=B){let S=K+B>>>1,j=Q[S];if(j<=k.end)K=S+1;else if(j>=Z)B=S-1;else return}return`/*${k.value}*/`}function W(Z){if(!Z)return;let K=Z.typeAnnotation??Z;return _.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",k=(B.arguments??[]).map((S)=>_.slice(S.start,S.end));return{name:R,arguments:k.length>0?k:void 0}}if(B.type==="Identifier")return{name:B.name??"unknown"};return{name:_.slice(B.start,B.end)}})}function V(Z){let K=Z.type==="TSParameterProperty"?Z.parameter:Z;if(K?.type==="RestElement"){let v=`...${K.argument?.name??"unknown"}`,x=K.typeAnnotation,gu=x?W(x):void 0,d={name:v,isOptional:!1};if(gu)d.type=gu;return d}if(K?.type==="AssignmentPattern"){let{left:f,right:v}=K,x=f?.name??"unknown",gu=f?.typeAnnotation,d=gu?W(gu):void 0,e=_.slice(v.start,v.end),U=w(f?.decorators??[]),D={name:x,isOptional:!0,defaultValue:e};if(d)D.type=d;if(U.length>0)D.decorators=U;return D}let B=K?.name??K?.pattern?.name??"unknown",R=!!K?.optional,k=K?.typeAnnotation,S=k?W(k):void 0,j=w(K?.decorators??[]),P={name:B,isOptional:R};if(S)P.type=S;if(j.length>0)P.decorators=j;return P}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=_.slice(Z.superClass.start,Z.superClass.end);K.push({kind:"extends",name:R})}let B=Z.implements??[];for(let R of B){let k=R.expression??R,S=_.slice(k.start,k.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,k=_.slice(R.start,R.end);K.push({kind:"extends",name:k})}return K}function A(Z){let K=[];for(let B of Z)if(B.type==="MethodDefinition"){let R=B.key?.name??"unknown",k=B.value,S=B.kind??"method",j=S==="constructor"?"constructor":S==="get"?"getter":S==="set"?"setter":"method",P=X(B,k),f=(k?.params??[]).map(V),v=W(k?.returnType),x={kind:"method",name:R,span:z(B.start,B.end),isExported:!1,methodKind:j,modifiers:P,parameters:f.length>0?f:void 0,returnType:v};K.push(x)}else if(B.type==="PropertyDefinition"){let R=B.key?.name??"unknown",k=X(B),S={kind:"property",name:R,span:z(B.start,B.end),isExported:!1,modifiers:k};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",k=(B.params??[]).map(V),S=W(B.returnType);K.push({kind:"method",name:R,span:z(B.start,B.end),isExported:!1,modifiers:[],methodKind:"method",parameters:k.length>0?k:void 0,returnType:S})}else if(B.type==="TSPropertySignature"){let R=B.key?.name??"unknown",k=W(B.typeAnnotation),S={kind:"property",name:R,span:z(B.start,B.end),isExported:!1,modifiers:B.readonly?["readonly"]:[],returnType:k};K.push(S)}return K}function q(Z,K){let B=Z.type??"";if(B==="FunctionDeclaration"){let R=Z.id?.name??"default",k=(Z.params??[]).map(V),S=W(Z.returnType),j=X(Z,Z),P=w(Z.decorators??[]),f=Z.typeParameters?.params?.flatMap((x)=>{let gu=x.name?.name;return gu?[gu]:[]})||void 0,v={kind:"function",name:R,span:z(Z.start,Z.end),isExported:K,modifiers:j,parameters:k.length>0?k:void 0,returnType:S,decorators:P.length>0?P:void 0};if(f&&f.length>0)v.typeParameters=f;return v}if(B==="ClassDeclaration"||B==="ClassExpression"){let R=Z.id?.name??"default",k=M(Z),S=A(Z.body?.body??[]),j=w(Z.decorators??[]),P=X(Z,Z),f=Z.typeParameters?.params?.flatMap((x)=>{let gu=x.name?.name;return gu?[gu]:[]})||void 0,v={kind:"class",name:R,span:z(Z.start,Z.end),isExported:K,modifiers:P,heritage:k.length>0?k:void 0,members:S.length>0?S:void 0,decorators:j.length>0?j:void 0};if(f&&f.length>0)v.typeParameters=f;return v}if(B==="VariableDeclaration"){let R=[];for(let k of Z.declarations??[]){let{id:S,init:j}=k;if(S?.type==="ObjectPattern"){for(let d of S.properties??[]){let e=d.value?.name??d.key?.name??"unknown";R.push({kind:"variable",name:e,span:z(d.start??k.start,d.end??k.end),isExported:K,modifiers:[]})}continue}if(S?.type==="ArrayPattern"){for(let d of S.elements??[]){if(!d||d.type!=="Identifier")continue;let e=d.name??"unknown";R.push({kind:"variable",name:e,span:z(d.start??k.start,d.end??k.end),isExported:K,modifiers:[]})}continue}let P=S?.name??"unknown",f="variable",v,x;if(j?.type==="FunctionExpression"||j?.type==="ArrowFunctionExpression")f="function",v=(j.params??[]).map(V),x=W(j.returnType);let gu=[];R.push({kind:f,name:P,span:z(k.start,k.end),isExported:K,modifiers:gu,parameters:v,returnType:x})}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",k=I(Z),S=T(Z.body?.body??[]),j=Z.typeParameters?.params?.flatMap((f)=>{let v=f.name?.name;return v?[v]:[]})||void 0,P={kind:"interface",name:R,span:z(Z.start,Z.end),isExported:K,modifiers:[],heritage:k.length>0?k:void 0,members:S.length>0?S:void 0};if(j&&j.length>0)P.typeParameters=j;return P}if(B==="TSEnumDeclaration"){let R=Z.id?.name??"unknown",k=X(Z),j=(Z.body?.members??[]).map((P)=>({kind:"property",name:P.id?.name??P.id?.value??"unknown",span:z(P.start,P.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:R,span:z(Z.start,Z.end),isExported:K,modifiers:k,members:j.length>0?j:void 0}}return null}let h=[];for(let Z of g.body){let K=null,B=Z,R=typeof B.type==="string"?B.type:"";if(R==="ExportNamedDeclaration"){let S=Z;if(S.declaration){if(K=q(S.declaration,!0),K&&!Array.isArray(K))K.span=z(S.start,S.end);else if(Array.isArray(K))for(let j of K)j.span=z(S.start,S.end)}}else if(R==="ExportDefaultDeclaration"){let S=Z,j=S.declaration;if(j){if(K=q(j,!0),K&&!Array.isArray(K))K.name=j.id?.name??"default",K.isExported=!0,K.span=z(S.start,S.end)}}else K=q(Z,!1);let k=Array.isArray(K)?K:K?[K]:[];for(let S of k){let j=Z.start??0,P=N(j);if(P){let f=pu(P);if(!h$(f))S.jsDoc=f}h.push(S)}}return h}function i$(u){if(u.kind==="function"||u.kind==="method"){let g=u.parameters?.length??0,_=u.modifiers.includes("async")?1:0;return`params:${g}|async:${_}`}return null}function x$(u){let g={};if(u.jsDoc)g.jsDoc=u.jsDoc;if(u.kind==="function"||u.kind==="method"){if(u.parameters!==void 0)g.parameters=u.parameters;if(u.returnType!==void 0)g.returnType=u.returnType}if(u.heritage?.length)g.heritage=u.heritage;if(u.decorators?.length)g.decorators=u.decorators;if(u.typeParameters?.length)g.typeParameters=u.typeParameters;if(u.modifiers?.length)g.modifiers=u.modifiers;if(u.members?.length)g.members=u.members.map((_)=>{let $=_.modifiers.find((J)=>J==="private"||J==="protected"||J==="public");return{name:_.name,kind:_.methodKind??_.kind,type:_.returnType,visibility:$,isStatic:_.modifiers.includes("static")||void 0,isReadonly:_.modifiers.includes("readonly")||void 0}});return Object.keys(g).length>0?JSON.stringify(g):null}function p$(u){let g=[u.kind];if(u.modifiers.length)g.push(`mod:${[...u.modifiers].sort().join(",")}`);if(u.typeParameters?.length)g.push(`tp:${u.typeParameters.length}`);if(u.heritage?.length){let _=[...u.heritage].sort(($,J)=>$.name.localeCompare(J.name)).map(($)=>`${$.kind}:${$.name}`).join(",");g.push(`her:${_}`)}if(u.decorators?.length)g.push(`dec:${[...u.decorators].map((_)=>_.name).sort().join(",")}`);if(u.methodKind)g.push(`mk:${u.methodKind}`);if(u.parameters)g.push(`p:${u.parameters.length}`);if(u.returnType)g.push(`rt:${u.returnType}`);if(u.members?.length){let _=u.members.map(($)=>`${$.kind}:${$.modifiers.join(",")}:${$.parameters?.length??""}:${$.returnType??""}`).sort().join(";");g.push(`mem:${u.members.length}:${Qu(_)}`)}return Qu(g.join("|"))}function pg(u,g,_,$,J){let O=i$(u),Q=Qu(`${g}|${u.kind}|${O??""}`),z=p$(u);return{project:_,filePath:$,kind:u.kind,name:g,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:Q,detailJson:x$(u),contentHash:J,indexedAt:new Date().toISOString(),structuralFingerprint:z}}function Og(u){let{parsed:g,project:_,filePath:$,contentHash:J,symbolRepo:O}=u,Q=Cu(g),z=[];for(let N of Q){z.push(pg(N,N.name,_,$,J));for(let W of N.members??[])z.push(pg(W,`${N.name}.${W.name}`,_,$,J))}O.replaceFileSymbols(_,$,J,z)}import{resolve as wg,dirname as l$,extname as d$}from"path";function Mu(u,g,_){let $=(J)=>{let O=d$(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(g.startsWith(".")){let J=wg(l$(u),g);return $(J)}if(_)for(let[J,O]of _.paths){if(O.length===0)continue;let Q=J.indexOf("*");if(Q===-1){if(g===J){let z=[];for(let N of O)z.push(...$(wg(_.baseUrl,N)));return z}}else{let z=J.slice(0,Q),N=J.slice(Q+1);if(g.startsWith(z)&&(N===""||g.endsWith(N))){let W=g.slice(z.length,N===""?void 0:g.length-N.length),w=[];for(let V of O)w.push(...$(wg(_.baseUrl,V.replace("*",W))));return w}}}return[]}function lg(u,g,_,$=Mu){let J=new Map,O=u.body??[];for(let Q of O){if(Q.type!=="ImportDeclaration")continue;let z=Q.source?.value??"",N=$(g,z,_);if(N.length===0)continue;let W=N[0],w=Q.specifiers??[];for(let V of w)switch(V.type){case"ImportSpecifier":J.set(V.local.name,{path:W,importedName:V.imported.name});break;case"ImportDefaultSpecifier":J.set(V.local.name,{path:W,importedName:"default"});break;case"ImportNamespaceSpecifier":J.set(V.local.name,{path:W,importedName:"*"});break}}return J}var r$=new Set(["loc","start","end","scope"]);function Su(u,g){if(!u||typeof u!=="object")return;if(Array.isArray(u)){for(let $ of u)Su($,g);return}let _=u;g(_);for(let $ of Object.keys(_)){if(r$.has($))continue;let J=_[$];if(J&&typeof J==="object")Su(J,g)}}function dg(u){if(!u||typeof u!=="object"||Array.isArray(u))return null;let g=u;if((g.type==="StringLiteral"||g.type==="Literal")&&typeof g.value==="string")return g.value;return null}function Bu(u){if(!u||typeof u!=="object"||Array.isArray(u))return null;let g=u;if(g.type==="Identifier"){let _=g.name;return{root:_,parts:[],full:_}}if(g.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(g.type==="Super")return{root:"super",parts:[],full:"super"};if(g.type==="MemberExpression"){let _=[],$=g;while($.type==="MemberExpression"){let Q=$.property;if(!Q||typeof Q.name!=="string")return null;_.push(Q.name),$=$.object}let J;if($.type==="Identifier")J=$.name;else if($.type==="ThisExpression")J="this";else if($.type==="Super")J="super";else return null;_.reverse();let O=[J,..._].join(".");return{root:J,parts:_,full:O}}return null}function rg(u,g,_,$=Mu){let J=[],O=u.body??[];for(let Q of O){if(Q.type==="ImportDeclaration"){let z=Q.source?.value??"",N=$(g,z,_);if(N.length===0)continue;let W=N[0],w=Q.importKind==="type",V=Q.specifiers??[];if(V.length===0){let X={};if(w)X.isType=!0;J.push({type:w?"type-references":"imports",srcFilePath:g,srcSymbolName:null,dstFilePath:W,dstSymbolName:null,...Object.keys(X).length>0?{metaJson:JSON.stringify(X)}:{}})}else for(let X of V){let M=X.type,I=w||X.importKind==="type",A={};if(I)A.isType=!0;let T,q;if(M==="ImportDefaultSpecifier")T="default",q=X.local.name;else if(M==="ImportNamespaceSpecifier")T="*",q=X.local.name,A.importKind="namespace";else T=X.imported.name,q=X.local.name;J.push({type:I?"type-references":"imports",srcFilePath:g,srcSymbolName:q,dstFilePath:W,dstSymbolName:T,...Object.keys(A).length>0?{metaJson:JSON.stringify(A)}:{}})}continue}if(Q.type==="ExportAllDeclaration"&&Q.source){let z=Q.source?.value??"",N=$(g,z,_);if(N.length===0)continue;let W=N[0],w=Q.exportKind==="type",V={isReExport:!0};if(w)V.isType=!0;J.push({type:w?"type-references":"re-exports",srcFilePath:g,srcSymbolName:null,dstFilePath:W,dstSymbolName:null,metaJson:JSON.stringify(V)});continue}if(Q.type==="ExportNamedDeclaration"&&Q.source){let z=Q.source?.value??"",N=$(g,z,_);if(N.length===0)continue;let W=N[0],w=Q.exportKind==="type",M={isReExport:!0,specifiers:(Q.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:g,srcSymbolName:null,dstFilePath:W,dstSymbolName:null,metaJson:JSON.stringify(M)})}}return Su(u,(Q)=>{if(Q.type!=="ImportExpression")return;let z=dg(Q.source);if(!z)return;let N=$(g,z,_);if(N.length===0)return;let W=N[0];J.push({type:"imports",srcFilePath:g,srcSymbolName:null,dstFilePath:W,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),J}function cg(u,g,_){let $=[],J=[],O=[];function Q(){if(J.length>0)return J[J.length-1]??null;return null}function z(W){if(!W)return null;let w=_.get(W.root);if(W.parts.length===0){if(w)return{dstFilePath:w.path,dstSymbolName:w.importedName,resolution:"import"};return{dstFilePath:g,dstSymbolName:W.root,resolution:"local"}}else{if(w&&w.importedName==="*"){let V=W.parts[W.parts.length-1];return{dstFilePath:w.path,dstSymbolName:V,resolution:"namespace"}}return{dstFilePath:g,dstSymbolName:W.full,resolution:"local-member"}}}function N(W){if(!W||typeof W!=="object")return;if(Array.isArray(W)){for(let X of W)N(X);return}let w=W,V=typeof w.type==="string"?w.type:"";if(V==="ClassDeclaration"||V==="ClassExpression"){let X=w,M=X.id?.name??"AnonymousClass";O.push(M),N(X.body),O.pop();return}if(V==="FunctionDeclaration"){let X=w,M=X.id?.name??"anonymous";J.push(M),N(X.body),J.pop();return}if(V==="VariableDeclarator"&&w.init&&(w.init?.type==="FunctionExpression"||w.init?.type==="ArrowFunctionExpression")){let X=w,M=X.id?.name??"anonymous";J.push(M),N(X.init?.body??X.init),J.pop();return}if(V==="MethodDefinition"&&w.value){let X=w,M=O[O.length-1]??"",I=X.key?.name??"anonymous",A=M?`${M}.${I}`:I;J.push(A),N(X.value?.body),J.pop();return}if(V==="FunctionExpression"||V==="ArrowFunctionExpression"){let X=Q(),M=X?`${X}.<anonymous>`:"<anonymous>";J.push(M),N(w.body),J.pop();return}if(V==="CallExpression"){let X=w,M=Bu(X.callee),I=z(M);if(I){let A=Q(),T={};if(A===null)T.scope="module";$.push({type:"calls",srcFilePath:g,srcSymbolName:A,dstFilePath:I.dstFilePath,dstSymbolName:I.dstSymbolName,...Object.keys(T).length>0?{metaJson:JSON.stringify(T)}:{}})}N(X.callee);for(let A of X.arguments??[])N(A);return}if(V==="NewExpression"){let X=w,M=Bu(X.callee),I=z(M);if(I){let A=Q(),T={isNew:!0};if(A===null)T.scope="module";$.push({type:"calls",srcFilePath:g,srcSymbolName:A,dstFilePath:I.dstFilePath,dstSymbolName:I.dstSymbolName,metaJson:JSON.stringify(T)})}for(let A of X.arguments??[])N(A);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")N(M)}}return N(u),$}function ag(u,g,_){let $=[];return Su(u,(J)=>{if(J.type==="TSInterfaceDeclaration"){let z=J.id?.name??"AnonymousInterface",N=J.extends??[];for(let W of N){let w=W.expression??W,V=Bu(w);if(!V)continue;let X=Wg(V,g,_);$.push({type:"extends",srcFilePath:g,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 N=Wg(z,g,_);$.push({type:"extends",srcFilePath:g,srcSymbolName:O,...N})}}let Q=J.implements??[];for(let z of Q){let N=z.expression??z,W=Bu(N);if(!W)continue;let w=Wg(W,g,_);$.push({type:"implements",srcFilePath:g,srcSymbolName:O,...w})}}),$}function Wg(u,g,_){let $=_.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:g,dstSymbolName:u.full,metaJson:JSON.stringify({isLocal:!0})}}function lu(u,g,_,$=Mu){let J=lg(u,g,_,$),O=rg(u,g,_,$),Q=cg(u,g,J),z=ag(u,g,J);return[...O,...Q,...z]}function Vg(u){let{ast:g,project:_,filePath:$,relationRepo:J,projectRoot:O,tsconfigPaths:Q,knownFiles:z,boundaries:N}=u,W=Au(O,$),V=lu(g,W,Q,z?(M,I,A)=>{let T=Mu(M,I,A);for(let q of T){let h=iu(O,q);if(N){let Z=r(h,N);if(z.has(`${Z}::${h}`))return[q]}else if(z.has(`${_}::${h}`))return[q]}return[]}:void 0),X=[];for(let M of V){let I=iu(O,M.dstFilePath);if(I.startsWith(".."))continue;let A=iu(O,M.srcFilePath),T=N?r(I,N):_;X.push({project:_,type:M.type,srcFilePath:A,srcSymbolName:M.srcSymbolName??null,dstProject:T,dstFilePath:I,dstSymbolName:M.dstSymbolName??null,metaJson:M.metaJson??null})}return J.replaceFileRelations(_,$,X),X.length}import{isErr as c$}from"@zipbul/result";var sg=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function a$(u){let g=Cu(u),_=[];for(let $ of g){_.push({name:$.name,startLine:$.span.start.line});for(let J of $.members??[])_.push({name:`${$.name}.${J.name}`,startLine:J.span.start.line})}return _.sort(($,J)=>$.startLine-J.startLine),_}function Ug(u,g,_){let $=0,J=u.length-1;while($<=J){let O=$+J>>1;if(u[O].startLine<=g)$=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 $=zu(u,g),J=zu(u,_);return{start:$,end:J}}function tg(u){let{comments:g,sourceText:_}=u;if(!g.length)return[];let $=xu(_),J=a$(u),O=[],Q=[...g].sort((N,W)=>N.start-W.start),z=null;for(let N of Q)if(N.type==="Block"&&N.value.startsWith("*")){z=null;let W=`/*${N.value}*/`,w=pu(W);if(c$(w))continue;let V=w;if(!V.tags?.length)continue;let X=zu($,N.end),M=Ug(J,X.line,3),I=_.slice(N.start,N.end);for(let A of V.tags){let T=[A.name,A.description].filter(Boolean).join(" "),q=`@${A.tag}`,h=I.indexOf(q),Z;if(h>=0){let K=N.start+h,B=_.indexOf(`
4
+ `,K),R=B>=0?Math.min(B,N.end):N.end;Z=du($,K,R)}else Z=du($,N.start,N.end);O.push({tag:A.tag,value:T,source:"jsdoc",span:Z,symbolName:M})}}else if(N.type==="Block"){z=null;let W=N.value.split(`
5
+ `),w=0;for(let V of W){let X=V.replace(/^\s*\*?\s?/,""),M=sg.exec(X);if(M){let I=M[1],A=M[2]?.trim()??"",T=`@${I}`,q=V.indexOf(T),h=N.start+2+w+(q>=0?q:0),Z=N.start+2+w+V.length,K=du($,h,Z),B=zu($,N.end),R=Ug(J,B.line,3);O.push({tag:I,value:A,source:"block",span:K,symbolName:R})}w+=V.length+1}}else{let W=N.value,w=sg.exec(W),V=zu($,N.start),X=zu($,N.end);if(w){let M=w[1],I=w[2]?.trim()??"",A=`@${M}`,T=W.indexOf(A),q=N.start+2+(T>=0?T:0),h=du($,q,N.end),Z=Ug(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&&V.line===z.endLine+1){let M=W.trim();if(M)z.annotation.value+=" "+M,z.annotation.span.end=zu($,N.end),z.endLine=X.line}else z=null}return O}function Yg(u){let{parsed:g,project:_,filePath:$,annotationRepo:J}=u,O=tg(g);if(J.deleteFileAnnotations(_,$),!O.length)return 0;let Q=new Date().toISOString(),z=O.map((N)=>({project:_,filePath:$,tag:N.tag,value:N.value,source:N.source,symbolName:N.symbolName,startLine:N.span.start.line,startColumn:N.span.start.column,endLine:N.span.end.line,endColumn:N.span.end.column,indexedAt:Q}));return J.insertBatch(_,$,z),O.length}function og(u,g){let _=[],$=[],J=[];for(let[w,V]of g)if(!u.has(w))_.push({name:V.name,filePath:V.filePath,kind:V.kind,fingerprint:V.fingerprint});for(let[w,V]of u)if(!g.has(w))$.push({name:V.name,filePath:V.filePath,kind:V.kind,fingerprint:V.fingerprint});if(!_.length||!$.length)return{renamed:J,added:_,removed:$};let O=new Map,Q=new Map;for(let w of _){let V=O.get(w.filePath)??[];V.push(w),O.set(w.filePath,V)}for(let w of $){let V=Q.get(w.filePath)??[];V.push(w),Q.set(w.filePath,V)}let z=new Set,N=new Set;for(let[w,V]of O){let X=Q.get(w);if(!X)continue;for(let M of new Set(V.map((I)=>I.kind))){let I=V.filter((Z)=>Z.kind===M&&!z.has(Z)),A=X.filter((Z)=>Z.kind===M&&!N.has(Z));if(!I.length||!A.length)continue;let T=(Z,K)=>{return K.get(`${Z.filePath}::${Z.name}`)?.structuralFingerprint??null},q=(Z,K)=>{return K.get(`${Z.filePath}::${Z.name}`)?.startLine??0},h=new Map;for(let Z of A){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,g);if(!K)continue;let B=h.get(K);if(!B)continue;let R=B.filter((S)=>!N.has(S));if(!R.length)continue;let k=R[0];if(R.length>1){let S=q(Z,g),j=Math.abs(q(k,u)-S);for(let P=1;P<R.length;P++){let f=Math.abs(q(R[P],u)-S);if(f<j)j=f,k=R[P]}}J.push({oldName:k.name,newName:Z.name,filePath:w,kind:M}),z.add(Z),N.add(k)}}}let W=J.filter((w)=>!w.oldName.includes("."));for(let w of W){let V=`${w.oldName}.`,X=`${w.newName}.`,M=$.filter((A)=>A.filePath===w.filePath&&A.name.startsWith(V)&&!N.has(A)),I=_.filter((A)=>A.filePath===w.filePath&&A.name.startsWith(X)&&!z.has(A));for(let A of M){let T=A.name.slice(V.length),q=I.find((h)=>h.name.slice(X.length)===T);if(q)J.push({oldName:A.name,newName:q.name,filePath:w.filePath,kind:A.kind}),z.add(q),N.add(A)}}return{renamed:J,added:_.filter((w)=>!z.has(w)),removed:$.filter((w)=>!N.has(w))}}var s$=100,u_=50;class Zg{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")){hu(this.opts.projectRoot),this.tsconfigPathsRaw=Tu(this.opts.projectRoot),this.fullIndex().catch((g)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",g)});return}if(u.filePath.endsWith("package.json")){let g=this.opts.discoverProjectsFn??mu;this.boundariesRefresh=g(this.opts.projectRoot).then((_)=>{this.opts.boundaries=_})}if(this.pendingEvents.push(u),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},s$)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(u,g){if(this.indexingLock){if(g)return this.pendingFullIndex=!0,new Promise(($,J)=>{this.pendingFullIndexWaiters.push({resolve:$,reject:J})});return this.currentIndexing}this.indexingLock=!0;let _=this.doIndex(u,g).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=_,_}async doIndex(u,g){let _=Date.now(),{fileRepo:$,symbolRepo:J,relationRepo:O,dbConnection:Q}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let z,N;if(u!==void 0)z=u.filter((U)=>U.eventType==="create"||U.eventType==="change").map((U)=>({filePath:U.filePath,contentHash:"",mtimeMs:0,size:0})),N=u.filter((U)=>U.eventType==="delete").map((U)=>U.filePath);else{let U=new Map;for(let C of this.opts.boundaries)for(let[n,y]of $.getFilesMap(C.project))U.set(n,y);let D=await xg({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>U}});z=D.changed,N=D.deleted}let W=await this.tsconfigPathsRaw??void 0,w=new Map;for(let U of N){let D=r(U,this.opts.boundaries),C=J.getFileSymbols(D,U);w.set(U,C)}let V=crypto.randomUUID(),X=new Map,M=new Map,I=(U)=>({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint,structuralFingerprint:U.structuralFingerprint??null,startLine:U.startLine,isExported:U.isExported??0});if(g)for(let U of this.opts.boundaries)for(let D of $.getAllFiles(U.project))for(let C of J.getFileSymbols(U.project,D.filePath))X.set(`${C.filePath}::${C.name}`,I(C));else{for(let U of z){let D=r(U.filePath,this.opts.boundaries);for(let C of J.getFileSymbols(D,U.filePath))X.set(`${C.filePath}::${C.name}`,I(C))}for(let[,U]of w)for(let D of U)X.set(`${D.filePath}::${D.name}`,I(D))}let A=(U)=>`${U.type}|${U.srcFilePath}|${U.dstFilePath}|${U.srcSymbolName??""}|${U.dstSymbolName??""}|${Qu(U.metaJson??"")}`,T=new Map;if(g)for(let U of this.opts.boundaries)for(let D of $.getAllFiles(U.project))for(let C of O.getOutgoing(U.project,D.filePath))T.set(A(C),C);else{for(let U of z){let D=r(U.filePath,this.opts.boundaries);for(let C of O.getOutgoing(D,U.filePath))T.set(A(C),C)}for(let U of N){let D=r(U,this.opts.boundaries);for(let C of O.getOutgoing(D,U))T.set(A(C),C)}}let{annotationRepo:q,changelogRepo:h}=this.opts,Z=()=>{for(let U of N){let D=r(U,this.opts.boundaries);if(J.deleteFileSymbols(D,U),O.deleteFileRelations(D,U),q)q.deleteFileAnnotations(D,U);$.deleteFile(D,U)}},K=0,B=async()=>{let{projectRoot:U,boundaries:D}=this.opts,{parseCache:C}=this.opts,n=0,y=0,H=0,c=[],F=[];for(let E of z)try{let p=Au(U,E.filePath),Uu=Bun.file(p),Lu=await Uu.text(),qg=E.contentHash||Qu(Lu),Fg=r(E.filePath,D);$.upsertFile({project:Fg,filePath:E.filePath,mtimeMs:Uu.lastModified,size:Uu.size,contentHash:qg,updatedAt:new Date().toISOString(),lineCount:Lu.split(`
6
+ `).length});let eu=(this.opts.parseSourceFn??qu)(p,Lu);if(eg(eu))throw eu.data;let w$=eu;F.push({filePath:E.filePath,text:Lu,contentHash:qg,parsed:w$,project:Fg})}catch(p){this.logger.error(`[IndexCoordinator] Failed to prepare ${E.filePath}:`,p),c.push(E.filePath)}let m=new Set;for(let E of D)for(let[p]of $.getFilesMap(E.project))m.add(`${E.project}::${p}`);return Q.transaction(()=>{for(let E of F){if(Og({parsed:E.parsed,project:E.project,filePath:E.filePath,contentHash:E.contentHash,symbolRepo:J}),y+=Vg({ast:E.parsed.program,project:E.project,filePath:E.filePath,relationRepo:O,projectRoot:U,tsconfigPaths:W,knownFiles:m,boundaries:D}),q)H+=Yg({parsed:E.parsed,project:E.project,filePath:E.filePath,annotationRepo:q});C.set(E.filePath,E.parsed),n+=J.getFileSymbols(E.project,E.filePath).length}}),{symbols:n,relations:y,annotations:H,failedFiles:c}},R=0,k=0,S=[];if(g){let{projectRoot:U,boundaries:D}=this.opts,{parseCache:C}=this.opts,n=[];for(let H=0;H<z.length;H+=u_){let c=z.slice(H,H+u_),F=await Promise.allSettled(c.map(async(m)=>{let E=Au(U,m.filePath),p=Bun.file(E),Uu=await p.text(),Lu=m.contentHash||Qu(Uu);return{filePath:m.filePath,text:Uu,contentHash:Lu,mtimeMs:p.lastModified,size:p.size}}));for(let m=0;m<F.length;m++){let E=F[m];if(E.status==="fulfilled")n.push(E.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",E.reason),S.push(c[m].filePath)}}let y=[];Q.transaction(()=>{for(let F of n){let m=r(F.filePath,D);$.deleteFile(m,F.filePath)}for(let F of N){let m=r(F,D);if(J.deleteFileSymbols(m,F),O.deleteFileRelations(m,F),q)q.deleteFileAnnotations(m,F);$.deleteFile(m,F)}for(let F of n){let m=r(F.filePath,D);$.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 D)for(let[m]of $.getFilesMap(F.project))H.add(`${F.project}::${m}`);let c=this.opts.parseSourceFn??qu;for(let F of n){let m=r(F.filePath,D),E=c(Au(U,F.filePath),F.text);if(eg(E))throw E.data;let p=E;if(y.push({filePath:F.filePath,parsed:p}),Og({parsed:p,project:m,filePath:F.filePath,contentHash:F.contentHash,symbolRepo:J}),q)K+=Yg({parsed:p,project:m,filePath:F.filePath,annotationRepo:q});k+=Vg({ast:p.program,project:m,filePath:F.filePath,relationRepo:O,projectRoot:U,tsconfigPaths:W,knownFiles:H,boundaries:D}),R+=J.getFileSymbols(m,F.filePath).length}});for(let H of y)C.set(H.filePath,H.parsed)}else{Z();let U=await B();R=U.symbols,k=U.relations,K=U.annotations,S=U.failedFiles}for(let U of z){let D=r(U.filePath,this.opts.boundaries);for(let C of J.getFileSymbols(D,U.filePath))M.set(`${C.filePath}::${C.name}`,I(C))}let j=new Map;for(let U of z){let D=r(U.filePath,this.opts.boundaries);for(let C of O.getOutgoing(D,U.filePath))j.set(A(C),C)}let P=(U)=>({type:U.type,srcFilePath:U.srcFilePath,dstFilePath:U.dstFilePath,srcSymbolName:U.srcSymbolName,dstSymbolName:U.dstSymbolName,dstProject:U.dstProject,metaJson:U.metaJson}),f={added:[...j.entries()].filter(([U])=>!T.has(U)).map(([,U])=>P(U)),removed:[...T.entries()].filter(([U])=>!j.has(U)).map(([,U])=>P(U))},v={added:[],modified:[],removed:[]};for(let[U,D]of M){let C=X.get(U);if(!C)v.added.push({name:D.name,filePath:D.filePath,kind:D.kind,isExported:Boolean(D.isExported)});else{let n=C.fingerprint!==D.fingerprint,y=C.isExported!==D.isExported,H=C.structuralFingerprint!==null&&D.structuralFingerprint!==null&&C.structuralFingerprint!==D.structuralFingerprint;if(n||y||H)v.modified.push({name:D.name,filePath:D.filePath,kind:D.kind,isExported:Boolean(D.isExported)})}}for(let[U,D]of X)if(!M.has(U))v.removed.push({name:D.name,filePath:D.filePath,kind:D.kind,isExported:Boolean(D.isExported)});let x=og(X,M),gu=new Set(x.renamed.map((U)=>`${U.filePath}::${U.oldName}`)),d=new Set(x.renamed.map((U)=>`${U.filePath}::${U.newName}`));v.added=v.added.filter((U)=>!d.has(`${U.filePath}::${U.name}`)),v.removed=v.removed.filter((U)=>!gu.has(`${U.filePath}::${U.name}`));let e=[];if(!g){for(let[U,D]of w)for(let C of D){if(!C.fingerprint)continue;let n=r(U,this.opts.boundaries),y=J.getByFingerprint(n,C.fingerprint);if(y.length===1){let H=y[0];O.retargetRelations({dstProject:n,oldFile:U,oldSymbol:C.name,newFile:H.filePath,newSymbol:H.name}),e.push({name:H.name,filePath:H.filePath,kind:H.kind,oldFilePath:U,isExported:H.isExported??0})}}for(let U of x.removed){let C=X.get(`${U.filePath}::${U.name}`)?.fingerprint;if(!C)continue;let n=r(U.filePath,this.opts.boundaries),y=J.getByFingerprint(n,C);if(y.length===1){let H=y[0];if(H.filePath!==U.filePath||H.name!==U.name)O.retargetRelations({dstProject:n,oldFile:U.filePath,oldSymbol:U.name,newFile:H.filePath,newSymbol:H.name}),e.push({name:H.name,filePath:H.filePath,kind:H.kind,oldFilePath:U.filePath,isExported:H.isExported??0})}}}if(e.length){let U=new Set(e.map((C)=>`${C.filePath}::${C.name}`)),D=new Set(e.map((C)=>`${C.oldFilePath}::${C.name}`));v.added=v.added.filter((C)=>!U.has(`${C.filePath}::${C.name}`)),v.removed=v.removed.filter((C)=>!D.has(`${C.filePath}::${C.name}`))}if(h){let U=new Date().toISOString(),D=g?1:0,C=[];for(let n of v.added){let y=`${n.filePath}::${n.name}`,H=M.get(y),c=r(n.filePath,this.opts.boundaries);C.push({project:c,changeType:"added",symbolName:n.name,symbolKind:n.kind,filePath:n.filePath,oldName:null,oldFilePath:null,fingerprint:H?.fingerprint??null,changedAt:U,isFullIndex:D,indexRunId:V})}for(let n of v.modified){let y=M.get(`${n.filePath}::${n.name}`),H=r(n.filePath,this.opts.boundaries);C.push({project:H,changeType:"modified",symbolName:n.name,symbolKind:n.kind,filePath:n.filePath,oldName:null,oldFilePath:null,fingerprint:y?.fingerprint??null,changedAt:U,isFullIndex:D,indexRunId:V})}for(let n of v.removed){let y=`${n.filePath}::${n.name}`,H=X.get(y),c=r(n.filePath,this.opts.boundaries);C.push({project:c,changeType:"removed",symbolName:n.name,symbolKind:n.kind,filePath:n.filePath,oldName:null,oldFilePath:null,fingerprint:H?.fingerprint??null,changedAt:U,isFullIndex:D,indexRunId:V})}for(let n of x.renamed){let y=M.get(`${n.filePath}::${n.newName}`),H=r(n.filePath,this.opts.boundaries);C.push({project:H,changeType:"renamed",symbolName:n.newName,symbolKind:n.kind,filePath:n.filePath,oldName:n.oldName,oldFilePath:null,fingerprint:y?.fingerprint??null,changedAt:U,isFullIndex:D,indexRunId:V})}for(let n of e){let y=M.get(`${n.filePath}::${n.name}`),H=r(n.filePath,this.opts.boundaries);C.push({project:H,changeType:"moved",symbolName:n.name,symbolKind:n.kind,filePath:n.filePath,oldName:null,oldFilePath:n.oldFilePath,fingerprint:y?.fingerprint??null,changedAt:U,isFullIndex:D,indexRunId:V})}if(C.length)try{Q.transaction(()=>{h.insertBatch(C)})}catch(n){this.logger.error("[IndexCoordinator] changelog insert failed:",n)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let n=new Date(Date.now()-2592000000).toISOString();try{for(let y of this.opts.boundaries)h.pruneOlderThan(y.project,n)}catch(y){this.logger.error("[IndexCoordinator] changelog pruning failed:",y)}}}return{indexedFiles:z.length,removedFiles:N.length,totalSymbols:R,totalRelations:k,totalAnnotations:K,durationMs:Date.now()-_,changedFiles:z.map((U)=>U.filePath),deletedFiles:[...N],failedFiles:S,changedSymbols:v,renamedSymbols:x.renamed.map((U)=>({oldName:U.oldName,newName:U.newName,filePath:U.filePath,kind:U.kind,isExported:Boolean(M.get(`${U.filePath}::${U.newName}`)?.isExported)})),movedSymbols:e.map((U)=>({name:U.name,oldFilePath:U.oldFilePath,newFilePath:U.filePath,kind:U.kind,isExported:Boolean(U.isExported)})),changedRelations:f}}fireCallbacks(u){for(let g of this.callbacks)try{g(u)}catch(_){this.logger.error("[IndexCoordinator] onIndexed callback threw:",_)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let u=this.pendingEvents.splice(0);this.startIndex(u,!1).catch((g)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",g))}}}function t$(u){try{return process.kill(u,0),!0}catch(g){if(typeof g==="object"&&g&&"code"in g)return g.code!=="ESRCH";return!0}}function o$(u){let g=new Date(u).getTime();return Number.isNaN(g)?0:g}function g_(u,g,_={}){let $=_.now??Date.now,J=_.isAlive??t$,O=_.staleAfterSeconds??60,Q=_.instanceId;return u.immediateTransaction(()=>{let z=u.selectOwner();if(!z)return u.insertOwner(g,Q),"owner";let N=Math.floor(($()-o$(z.heartbeat_at))/1000),W=J(z.pid);if(W&&Q&&z.instance_id&&z.instance_id!==Q&&z.pid!==g)return u.replaceOwner(g,Q),"owner";if(W&&N<O)return"reader";return u.replaceOwner(g,Q),"owner"})}function __(u,g){u.deleteOwner(g)}function $_(u,g){u.touchOwner(g)}class Fu{#u;#g=new Map;constructor(u){this.#u=Math.max(1,u)}get size(){return this.#g.size}has(u){return this.#g.has(u)}get(u){if(!this.#g.has(u))return;let g=this.#g.get(u);return this.#g.delete(u),this.#g.set(u,g),g}set(u,g){if(this.#g.has(u))this.#g.delete(u);if(this.#g.set(u,g),this.#g.size>this.#u){let _=this.#g.keys().next().value;if(_!==void 0)this.#g.delete(_)}}delete(u){return this.#g.delete(u)}clear(){this.#g.clear()}}class Xg{lru;constructor(u=500){this.lru=new Fu(u)}get(u){return this.lru.get(u)}set(u,g){this.lru.set(u,g)}invalidate(u){this.lru.delete(u)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function Kg(u){let{symbolRepo:g,project:_,query:$}=u,J=$.project??_,O=$.limit??100,Q={kind:$.kind,filePath:$.filePath,isExported:$.isExported,project:J,limit:O,resolvedType:$.resolvedType};if($.text)if($.exact)Q.exactName=$.text;else{let N=Du($.text);if(N)Q.ftsQuery=N}if($.decorator)Q.decorator=$.decorator;if($.regex)Q.regex=$.regex;return g.searchByQuery(Q).map((N)=>({id:N.id,filePath:N.filePath,kind:N.kind,name:N.name,span:{start:{line:N.startLine,column:N.startColumn},end:{line:N.endLine,column:N.endColumn}},isExported:N.isExported===1,signature:N.signature,fingerprint:N.fingerprint,detail:N.detailJson?(()=>{try{return JSON.parse(N.detailJson)}catch{return{}}})():{}}))}function Mg(u){let{relationRepo:g,project:_,query:$}=u;if($.srcFilePath&&$.srcFilePathPattern)throw new Y("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if($.dstFilePath&&$.dstFilePathPattern)throw new Y("validation","dstFilePath and dstFilePathPattern are mutually exclusive");let J=$.project??_,O=$.limit??500,Q=!!($.srcFilePathPattern||$.dstFilePathPattern),z=Q?Number.MAX_SAFE_INTEGER:O,W=g.searchRelations({srcFilePath:$.srcFilePath,srcSymbolName:$.srcSymbolName,dstFilePath:$.dstFilePath,dstSymbolName:$.dstSymbolName,dstProject:$.dstProject,type:$.type,project:J,limit:z}).map((w)=>{let V;if(w.metaJson)try{V=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:V}});if($.srcFilePathPattern||$.dstFilePathPattern){let w=$.srcFilePathPattern?new Bun.Glob($.srcFilePathPattern):null,V=$.dstFilePathPattern?new Bun.Glob($.dstFilePathPattern):null;W=W.filter((X)=>(!w||w.match(X.srcFilePath))&&(!V||V.match(X.dstFilePath)))}if(Q&&W.length>O)W=W.slice(0,O);return W}import{findInFiles as e$,Lang as u0}from"@ast-grep/napi";async function Bg(u){if(u.filePaths.length===0)return[];let g=[];return await e$(u0.TypeScript,{paths:u.filePaths,matcher:{rule:{pattern:u.pattern}}},(_,$)=>{if(_){console.warn("[patternSearch] findInFiles callback error:",_);return}for(let J of $){let O=J.range();g.push({filePath:J.getRoot().filename(),startLine:O.start.line+1,endLine:O.end.line+1,matchedText:J.text()})}}),g}import o from"typescript";import{isErr as Z0}from"@zipbul/result";import Vu from"typescript";import g0 from"path";import{err as Hg}from"@zipbul/result";function _0(u){try{return Gg("fs").readFileSync(u,"utf-8")}catch{return}}function $0(u){try{return Gg("fs").readFileSync(u,"utf-8")}catch{return}}class ru{#u;#g;#_=!1;__testing__;constructor(u,g){this.#u=u,this.#g=g,this.__testing__={host:g}}static create(u,g={}){let _=g.readConfigFile??_0,$=g.resolveNonTrackedFile??$0,J=g0.dirname(u),O=_(u);if(O===void 0)return Hg(_u("semantic",`tsconfig not found: ${u}`));let Q=Vu.parseJsonText(u,O),z=Q.parseDiagnostics;if(z&&z.length>0){let V=z.map((X)=>Vu.flattenDiagnosticMessageText(X.messageText,`
8
+ `)).join("; ");return Hg(_u("semantic",`tsconfig parse error: ${V}`))}let N=Vu.parseJsonSourceFileConfigFileContent(Q,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(V)=>_(V)!==void 0||$(V)!==void 0,readFile:(V)=>_(V)??$(V)},J);if(N.errors.length>0){let V=N.errors.filter((X)=>X.category===Vu.DiagnosticCategory.Error&&X.code!==18003);if(V.length>0){let X=V.map((M)=>Vu.flattenDiagnosticMessageText(M.messageText,`
9
+ `)).join("; ");return Hg(_u("semantic",`tsconfig compile error: ${X}`))}}let W=new J_(N.fileNames,N.options,J,$),w=Vu.createLanguageService(W);return new ru(w,W)}get isDisposed(){return this.#_}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,g){if(this.#_)return;this.#g.updateFile(u,g)}removeFile(u){if(this.#_)return;this.#g.removeFile(u)}dispose(){if(this.#_)return;this.#_=!0,this.#u.dispose()}#J(){if(this.#_)throw Error("TscProgram is disposed")}}class J_{#u;#g;#_;#J;#$=new Map;constructor(u,g,_,$){this.#u=new Set(u),this.#g=g,this.#_=_,this.#J=$}updateFile(u,g){let _=this.#$.get(u);if(_)_.version+=1,_.content=g;else this.#$.set(u,{version:1,content:g})}removeFile(u){this.#$.delete(u),this.#u.delete(u)}getScriptFileNames(){let u=[...this.#$.keys()];return[...[...this.#u].filter((_)=>!this.#$.has(_)),...u]}getScriptVersion(u){let g=this.#$.get(u);return g?String(g.version):"0"}getScriptSnapshot(u){let g=this.#$.get(u);if(g)return Vu.ScriptSnapshot.fromString(g.content);let _=this.#J(u);if(_!==void 0)return Vu.ScriptSnapshot.fromString(_);return}getCurrentDirectory(){return this.#_}getCompilationSettings(){return this.#g}getDefaultLibFileName(u){return Vu.getDefaultLibFilePath(u)}fileExists(u){if(this.#$.has(u))return!0;return this.#J(u)!==void 0}readFile(u){let g=this.#$.get(u);if(g)return g.content;return this.#J(u)}}import s from"typescript";import J0 from"typescript";function Ou(u,g){if(g<0||g>=u.getEnd())return;function _($){let J=$.getStart(u,!1),O=$.getEnd();if(g<J||g>=O)return;let Q;return J0.forEachChild($,(z)=>{if(!Q)Q=_(z)}),Q??$}return _(u)}var Lg=8;function N0(u){return!!(u.flags&s.TypeFlags.Object)&&!!(u.objectFlags&s.ObjectFlags.Reference)}function Gu(u,g,_=0){let $=u.typeToString(g),J=g.flags,O=!!(J&s.TypeFlags.Union),Q=!!(J&s.TypeFlags.Intersection),z;if(_<Lg&&N0(g)){let V=u.getTypeArguments(g);if(V.length>0)z=V}let N=!!(J&s.TypeFlags.TypeParameter)||z!==void 0&&z.length>0,W;if(O&&_<Lg)W=g.types.map((V)=>Gu(u,V,_+1));else if(Q&&_<Lg)W=g.types.map((V)=>Gu(u,V,_+1));let w;if(z&&z.length>0)w=z.map((V)=>Gu(u,V,_+1));return{text:$,flags:J,isUnion:O,isIntersection:Q,isGeneric:N,members:W,typeArguments:w}}function Q0(u){return s.isFunctionDeclaration(u)||s.isVariableDeclaration(u)||s.isClassDeclaration(u)||s.isInterfaceDeclaration(u)||s.isTypeAliasDeclaration(u)||s.isEnumDeclaration(u)||s.isMethodDeclaration(u)||s.isPropertyDeclaration(u)||s.isPropertySignature(u)||s.isMethodSignature(u)}class Ig{program;constructor(u){this.program=u}collectAt(u,g){let _=this.program.getProgram(),$=this.program.getChecker();if(g<0)return null;let J=_.getSourceFile(u);if(!J)return null;if(g>=J.getEnd())return null;let O=Ou(J,g);if(!O)return null;if(!s.isIdentifier(O))return null;try{let Q=$.getTypeAtLocation(O);return Gu($,Q)}catch{return null}}isAssignableTo(u,g,_,$){let J=this.program.getChecker(),O=this.program.getProgram(),Q=O.getSourceFile(u);if(!Q)return null;let z=Ou(Q,g);if(!z||!s.isIdentifier(z))return null;let N=O.getSourceFile(_);if(!N)return null;let W=Ou(N,$);if(!W||!s.isIdentifier(W))return null;try{let w=J.getTypeAtLocation(z),V=J.getTypeAtLocation(W);return J.isTypeAssignableTo(w,V)}catch{return null}}collectFile(u){let g=new Map,_=this.program.getProgram(),$=this.program.getChecker(),J=_.getSourceFile(u);if(!J)return g;function O(Q){if(Q0(Q)&&Q.name&&s.isIdentifier(Q.name)){let z=Q.name;try{let N=$.getTypeAtLocation(z),W=z.getStart(J);g.set(W,Gu($,N))}catch{}}s.forEachChild(Q,O)}return O(J),g}}import Xu from"typescript";var z0=1000,O0=1;function w0(u){let g=u.declarations?.[0],_=g?.getSourceFile(),$=g?Xu.getNameOfDeclaration(g):void 0;return{name:u.getName(),filePath:_?.fileName??"",position:$?.getStart(_,!1)??g?.getStart(_,!1)??0}}function cu(u,g=0){let _=u.declarations?.[0],$=_?.getSourceFile(),J=_?Xu.getNameOfDeclaration(_):void 0,O=$?.fileName??"",Q=J?.getStart($,!1)??_?.getStart($,!1)??0,z={name:u.getName(),filePath:O,position:Q},N=u;if(N.parent)z.parent=w0(N.parent);if(g<O0){let W=u.flags,w=!!(W&Xu.SymbolFlags.Enum),V=!!(W&(Xu.SymbolFlags.NamespaceModule|Xu.SymbolFlags.ValueModule)),X=!!(W&(Xu.SymbolFlags.Class|Xu.SymbolFlags.Interface));if(w&&u.exports&&u.exports.size>0){let M=[];u.exports.forEach((I)=>{M.push(cu(I,g+1))}),z.members=M}else if(X&&u.members&&u.members.size>0){let M=[];u.members.forEach((I)=>{M.push(cu(I,g+1))}),z.members=M}if(V&&u.exports&&u.exports.size>0){let M=[];u.exports.forEach((I)=>{M.push(cu(I,g+1))}),z.exports=M}}return z}class Dg{#u;#g;#_=new Map;constructor(u,g=z0){this.#u=u,this.#g=new Fu(g)}get(u,g){if(this.#u.isDisposed)return null;let _=`${u}:${g}`,$=this.#g.get(_);if($!==void 0)return $;let O=this.#u.getProgram().getSourceFile(u);if(!O)return null;let Q=Ou(O,g);if(!Q||!Xu.isIdentifier(Q))return null;let N=this.#u.getChecker().getSymbolAtLocation(Q);if(!N)return null;let W=cu(N);this.#g.set(_,W);let w=this.#_.get(u);if(!w)w=new Set,this.#_.set(u,w);return w.add(_),W}invalidate(u){let g=this.#_.get(u);if(g){for(let _ of g)this.#g.delete(_);this.#_.delete(u)}}clear(){this.#g.clear(),this.#_.clear()}}import W0 from"typescript";class Ag{#u;constructor(u){this.#u=u}findAt(u,g){if(this.#u.isDisposed)return[];let _=this.#u.getProgram(),$=_.getSourceFile(u);if(!$)return[];let J=Ou($,g);if(!J||!W0.isIdentifier(J))return[];let Q=this.#u.getLanguageService().findReferences(u,g);if(!Q||Q.length===0)return[];let z=[];for(let N of Q)for(let W of N.references){let w=_.getSourceFile(W.fileName);if(!w)continue;let{line:V,character:X}=w.getLineAndCharacterOfPosition(W.textSpan.start);z.push({filePath:W.fileName,position:W.textSpan.start,line:V+1,column:X,isDefinition:W.isDefinition??!1,isWrite:W.isWriteAccess??!1})}return z}}import i from"typescript";function V0(u,g){let _=Ou(u,g);if(!_)return;if(N_(_))return _;let $=_.parent;for(let J=0;J<5&&$;J++){if(N_($))return $;$=$.parent}return _}function N_(u){return i.isClassDeclaration(u)||i.isClassExpression(u)||i.isFunctionDeclaration(u)||i.isFunctionExpression(u)||i.isArrowFunction(u)||i.isVariableDeclaration(u)||i.isObjectLiteralExpression(u)}function Q_(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 Q_(u.initializer);return"class"}function U0(u,g){if(i.isClassDeclaration(u)||i.isFunctionDeclaration(u))return u.name?.getText(g)??"";if(i.isClassExpression(u))return u.name?.getText(g)??"";if(i.isVariableDeclaration(u)&&i.isIdentifier(u.name))return u.name.getText(g);if(i.isFunctionExpression(u))return u.name?.getText(g)??"";if(i.isArrowFunction(u)&&u.parent&&i.isVariableDeclaration(u.parent)){if(i.isIdentifier(u.parent.name))return u.parent.name.getText(g)}if(i.isObjectLiteralExpression(u)&&u.parent&&i.isVariableDeclaration(u.parent)){if(i.isIdentifier(u.parent.name))return u.parent.name.getText(g)}return""}function Y0(u){if(!i.isClassDeclaration(u)&&!i.isClassExpression(u))return!1;let g=u.heritageClauses;if(!g)return!1;return g.some((_)=>_.token===i.SyntaxKind.ImplementsKeyword)}class Cg{#u;constructor(u){this.#u=u}findAt(u,g){if(this.#u.isDisposed)return[];let _=this.#u.getProgram(),$=_.getSourceFile(u);if(!$)return[];let J=Ou($,g);if(!J||!i.isIdentifier(J))return[];let Q=this.#u.getLanguageService().getImplementationAtPosition(u,g);if(!Q||Q.length===0)return[];let z=[];for(let N of Q){if(N.kind===i.ScriptElementKind.interfaceElement||N.kind===i.ScriptElementKind.typeElement)continue;let W=_.getSourceFile(N.fileName);if(!W)continue;let w=V0(W,N.textSpan.start);if(!w)continue;let V=Q_(w),X=U0(w,W),M=Y0(w);z.push({filePath:N.fileName,symbolName:X,position:N.textSpan.start,kind:V,isExplicit:M})}return z}}function z_(u){return o.canHaveModifiers(u)&&o.getModifiers(u)?.some((g)=>g.kind===o.SyntaxKind.ExportKeyword)===!0}function X0(u){if(o.isFunctionDeclaration(u))return"function";if(o.isClassDeclaration(u))return"class";if(o.isInterfaceDeclaration(u))return"interface";if(o.isTypeAliasDeclaration(u))return"type";if(o.isEnumDeclaration(u))return"enum";if(o.isVariableDeclaration(u))return"const";if(o.isVariableStatement(u))return"const";return"unknown"}function O_(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.#g=g,this.#_=_,this.#J=$,this.#$=J}static create(u,g={}){let _=ru.create(u,{readConfigFile:g.readConfigFile,resolveNonTrackedFile:g.resolveNonTrackedFile});if(Z0(_))return _;let $=_,J=g.typeCollector??new Ig($),O=g.symbolGraph??new Dg($),Q=g.referenceResolver??new Ag($),z=g.implementationFinder??new Cg($);return new au($,J,O,Q,z)}get isDisposed(){return this.#N}collectTypeAt(u,g){return this.#Q(),this.#g.collectAt(u,g)}collectFileTypes(u){return this.#Q(),this.#g.collectFile(u)}findReferences(u,g){return this.#Q(),this.#J.findAt(u,g)}findImplementations(u,g){return this.#Q(),this.#$.findAt(u,g)}isTypeAssignableTo(u,g,_,$){return this.#Q(),this.#g.isAssignableTo(u,g,_,$)}getSymbolNode(u,g){return this.#Q(),this.#_.get(u,g)}getModuleInterface(u){this.#Q();let g=this.#g.collectFile(u),_=[],J=this.#u.getProgram().getSourceFile(u);if(!J)return{filePath:u,exports:_};function O(Q){if(o.isVariableStatement(Q)&&z_(Q)){for(let z of Q.declarationList.declarations)if(o.isIdentifier(z.name)){let N=z.name.getStart(J),W=g.get(N)??null;_.push({name:z.name.text,kind:"const",resolvedType:W})}return}if((o.isFunctionDeclaration(Q)||o.isClassDeclaration(Q)||o.isInterfaceDeclaration(Q)||o.isTypeAliasDeclaration(Q)||o.isEnumDeclaration(Q))&&z_(Q)&&Q.name){let z=Q.name,N=z.getStart(J),W=g.get(N)??null;_.push({name:z.text,kind:X0(Q),resolvedType:W});return}o.forEachChild(Q,O)}return O(J),{filePath:u,exports:_}}notifyFileChanged(u,g){if(this.#N)return;this.#u.notifyFileChanged(u,g),this.#_.invalidate(u)}notifyFileDeleted(u){if(this.#N)return;this.#u.removeFile(u),this.#_.invalidate(u)}lineColumnToPosition(u,g,_){this.#Q();let $=this.#u.getProgram().getSourceFile(u);if(!$)return null;try{return o.getPositionOfLineAndCharacter($,g-1,_)}catch{return null}}findNamePosition(u,g,_){this.#Q();let $=this.#u.getProgram().getSourceFile(u);if(!$)return null;let J=$.getFullText(),O=g;while(O<J.length){let Q=J.indexOf(_,O);if(Q<0)return null;let z=Q>0?J.charCodeAt(Q-1):32,N=Q+_.length<J.length?J.charCodeAt(Q+_.length):32;if(!O_(z)&&!O_(N))return Q;O=Q+1}return null}dispose(){if(this.#N)return;this.#N=!0,this.#u.dispose(),this.#_.clear()}#Q(){if(this.#N)throw Error("SemanticLayer is disposed")}}import{eq as Hu,and as w_,sql as K0}from"drizzle-orm";var W_=80;class Sg{db;constructor(u){this.db=u}insertBatch(u,g,_){if(!_.length)return;let $=_.map((J)=>({project:u,filePath:g,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+=W_)this.db.drizzleDb.insert(Nu).values($.slice(J,J+W_)).run()}deleteFileAnnotations(u,g){this.db.drizzleDb.delete(Nu).where(w_(Hu(Nu.project,u),Hu(Nu.filePath,g))).run()}search(u){return this.db.drizzleDb.select().from(Nu).where(w_(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?K0`${Nu.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 V_,sql as ju,gt as M0,gte as B0}from"drizzle-orm";var U_=80;class Rg{db;constructor(u){this.db=u}insertBatch(u){if(!u.length)return;let g=u.map((_)=>({project:_.project,changeType:_.changeType,symbolName:_.symbolName,symbolKind:_.symbolKind,filePath:_.filePath,oldName:_.oldName,oldFilePath:_.oldFilePath,fingerprint:_.fingerprint,changedAt:_.changedAt,isFullIndex:_.isFullIndex,indexRunId:_.indexRunId}));for(let _=0;_<g.length;_+=U_)this.db.drizzleDb.insert($u).values(g.slice(_,_+U_)).run()}getSince(u){return this.db.drizzleDb.select().from($u).where(V_(Ru($u.project,u.project),B0($u.changedAt,u.since),u.symbolName?Ru($u.symbolName,u.symbolName):void 0,u.changeTypes?.length?ju`${$u.changeType} IN (${ju.join(u.changeTypes.map((g)=>ju`${g}`),ju`, `)})`: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?M0($u.id,u.afterId):void 0)).orderBy($u.id).limit(u.limit).all()}pruneOlderThan(u,g){return this.db.drizzleDb.delete($u).where(V_(Ru($u.project,u),ju`${$u.changedAt} < ${g}`)).run().changes}}function Y_(u){let{annotationRepo:g,project:_,query:$}=u,J=$.project??_,O=$.limit??100,Q;if($.text){let N=Du($.text);if(N)Q=N}return g.search({project:J,tag:$.tag,filePath:$.filePath,symbolName:$.symbolName,source:$.source,ftsQuery:Q,limit:O}).map((N)=>({tag:N.tag,value:N.value,source:N.source,filePath:N.filePath,symbolName:N.symbolName,span:{start:{line:N.startLine,column:N.startColumn},end:{line:N.endLine,column:N.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 g=[this.options.project,...this.options.additionalProjects??[]].flatMap((_)=>[...this.options.relationRepo.getByType(_,"imports"),...this.options.relationRepo.getByType(_,"type-references"),...this.options.relationRepo.getByType(_,"re-exports")]);for(let _ of g){let{srcFilePath:$,dstFilePath:J}=_;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,...g]);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 Q=this.reverseAdjacencyList.get(J);if(Q){for(let z of Q)this.adjacencyList.get(z)?.delete(J);Q.clear()}}for(let J of g)this.adjacencyList.delete(J),this.reverseAdjacencyList.delete(J);for(let J of u){let O=_(J);for(let Q of O){if(!this.adjacencyList.has(Q.srcFilePath))this.adjacencyList.set(Q.srcFilePath,new Set);if(this.adjacencyList.get(Q.srcFilePath).add(Q.dstFilePath),!this.adjacencyList.has(Q.dstFilePath))this.adjacencyList.set(Q.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(Q.dstFilePath))this.reverseAdjacencyList.set(Q.dstFilePath,new Set);this.reverseAdjacencyList.get(Q.dstFilePath).add(Q.srcFilePath)}}}getDependencies(u){return Array.from(this.adjacencyList.get(u)??[])}getDependents(u){return Array.from(this.reverseAdjacencyList.get(u)??[])}getTransitiveDependents(u){let g=new Set,_=[u];while(_.length>0){let $=_.shift();for(let J of this.reverseAdjacencyList.get($)??[])if(!g.has(J))g.add(J),_.push(J)}return Array.from(g)}hasCycle(){let u=new Set,g=new Set;for(let _ of this.adjacencyList.keys()){if(u.has(_))continue;let $=[{node:_,entered:!1}];while($.length>0){let J=$.pop();if(J.entered){g.delete(J.node);continue}if(g.has(J.node))return!0;if(u.has(J.node))continue;u.add(J.node),g.add(J.node),$.push({node:J.node,entered:!0});for(let O of this.adjacencyList.get(J.node)??[]){if(g.has(O))return!0;if(!u.has(O))$.push({node:O,entered:!1})}}}return!1}getAffectedByChange(u){let g=new Set;for(let _ of u)for(let $ of this.getTransitiveDependents(_))g.add($);return Array.from(g)}getAdjacencyList(){let u=new Map;for(let[g,_]of this.adjacencyList)u.set(g,Array.from(_));return u}getTransitiveDependencies(u){let g=new Set,_=[u];while(_.length>0){let $=_.shift();for(let J of this.adjacencyList.get($)??[])if(!g.has(J))g.add(J),_.push(J)}return Array.from(g)}getCyclePaths(u){let g=u?.maxCycles??1/0;if(g<=0)return[];let _=new Map;for(let[$,J]of this.adjacencyList)_.set($,Array.from(J));return A0(_,g)}}var H0=(u,g)=>u.localeCompare(g);function L0(u){let g=u.length>1&&u[0]===u[u.length-1]?u.slice(0,-1):[...u];if(g.length===0)return[];let _=g;for(let $=1;$<g.length;$++){let J=g.slice($).concat(g.slice(0,$));if(J.join("::")<_.join("::"))_=J}return[..._]}function ng(u,g,_){let $=L0(_);if($.length===0)return!1;let J=$.join("->");if(u.has(J))return!1;return u.add(J),g.push($),!0}function I0(u){let g=0,_=[],$=new Set,J=new Map,O=new Map,Q=[],z=(N)=>{J.set(N,g),O.set(N,g),g+=1,_.push(N),$.add(N);for(let W of u.get(N)??[])if(!J.has(W))z(W),O.set(N,Math.min(O.get(N)??0,O.get(W)??0));else if($.has(W))O.set(N,Math.min(O.get(N)??0,J.get(W)??0));if(O.get(N)===J.get(N)){let W=[],w="";do w=_.pop()??"",$.delete(w),W.push(w);while(w!==N&&_.length>0);Q.push(W)}};for(let N of u.keys())if(!J.has(N))z(N);return{components:Q}}function D0(u,g,_){let $=[],J=new Set,O=[...u].sort(H0),Q=(z,N,W)=>{N.delete(z);let w=W.get(z);if(!w)return;for(let V of w)if(N.has(V))Q(V,N,W);w.clear()};for(let z=0;z<O.length&&$.length<_;z++){let N=O[z]??"",W=new Set(O.slice(z)),w=new Set,V=new Map,X=[],M=(A)=>(g.get(A)??[]).filter((T)=>W.has(T)),I=(A)=>{if($.length>=_)return!0;let T=!1;X.push(A),w.add(A);for(let q of M(A)){if($.length>=_)break;if(q===N)ng(J,$,X.concat(N)),T=!0;else if(!w.has(q)){if(I(q))T=!0}}if(T)Q(A,w,V);else for(let q of M(A)){let h=V.get(q)??new Set;h.add(A),V.set(q,h)}return X.pop(),T};I(N)}return $}function A0(u,g){let{components:_}=I0(u),$=[],J=new Set;for(let O of _){if($.length>=g)break;if(O.length===0)continue;if(O.length===1){let N=O[0]??"";if((u.get(N)??[]).includes(N))ng(J,$,[N,N]);continue}let Q=g-$.length,z=D0(O,u,Q);for(let N of z){if($.length>=g)break;ng(J,$,N)}}return $}var C0=15000;function tu(u){u.graphCache=null,u.graphCacheKey=null,u.graphCacheBuiltAt=null}function nu(u,g){let _=g??"__cross__";if(u.graphCache&&u.graphCacheBuiltAt!==null){if(Date.now()-u.graphCacheBuiltAt>C0)u.graphCache=null,u.graphCacheKey=null,u.graphCacheBuiltAt=null}if(u.graphCache&&u.graphCacheKey===_)return u.graphCache;let $=new su({relationRepo:u.relationRepo,project:g??u.defaultProject,additionalProjects:g?void 0:u.boundaries?.map((J)=>J.project)});return $.build(),u.graphCache=$,u.graphCacheKey=_,u.graphCacheBuiltAt=Date.now(),$}function Z_(u,g,_,$=1e4){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:_??u.defaultProject,query:{srcFilePath:g,type:"imports",project:_??u.defaultProject,limit:$}}).map((J)=>J.dstFilePath)}catch(J){if(J instanceof Y)throw J;throw new Y("search","Gildash: getDependencies failed",{cause:J})}}function X_(u,g,_,$=1e4){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:_??u.defaultProject,query:{dstFilePath:g,type:"imports",project:_??u.defaultProject,limit:$}}).map((J)=>J.srcFilePath)}catch(J){if(J instanceof Y)throw J;throw new Y("search","Gildash: getDependents failed",{cause:J})}}async function K_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return nu(u,_).getAffectedByChange(g)}catch($){if($ instanceof Y)throw $;throw new Y("search","Gildash: getAffected failed",{cause:$})}}async function M_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return nu(u,g).hasCycle()}catch(_){if(_ instanceof Y)throw _;throw new Y("search","Gildash: hasCycle failed",{cause:_})}}async function B_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return nu(u,g).getAdjacencyList()}catch(_){if(_ instanceof Y)throw _;throw new Y("search","Gildash: getImportGraph failed",{cause:_})}}async function H_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return nu(u,_).getTransitiveDependencies(g)}catch($){if($ instanceof Y)throw $;throw new Y("search","Gildash: getTransitiveDependencies failed",{cause:$})}}async function L_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return nu(u,g).getCyclePaths(_)}catch($){if($ instanceof Y)throw $;throw new Y("search","Gildash: getCyclePaths failed",{cause:$})}}async function I_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{let $=nu(u,_);return{filePath:g,fanIn:$.getDependents(g).length,fanOut:$.getDependencies(g).length}}catch($){if($ instanceof Y)throw $;throw new Y("search","Gildash: getFanMetrics failed",{cause:$})}}var n0=30000,D_=15000,k0=10;function T0(u,g){return(_)=>{for(let $ of u.onFileChangedCallbacks)try{$(_)}catch(J){u.logger.error("[Gildash] onFileChanged callback threw:",J)}if(g.handleWatcherEvent?.(_),u.semanticLayer)if(_.eventType==="delete")try{u.semanticLayer.notifyFileDeleted(_.filePath)}catch($){u.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",$);for(let J of u.onErrorCallbacks)try{J($ instanceof Y?$:new Y("semantic","semantic notifyFileDeleted failed",{cause:$}))}catch{}}else u.readFileFn(_.filePath).then(($)=>{try{u.semanticLayer?.notifyFileChanged(_.filePath,$)}catch(J){u.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",J);for(let O of u.onErrorCallbacks)try{O(J instanceof Y?J:new Y("semantic","semantic notifyFileChanged failed",{cause:J}))}catch{}}}).catch(($)=>{u.logger.error("[Gildash] failed to read file for semantic layer",_.filePath,$);try{u.semanticLayer?.notifyFileDeleted(_.filePath)}catch(J){u.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",J)}})}}async function q0(u){if(!u.semanticLayer)return;let g=u.fileRepo.getAllFiles(u.defaultProject);await Promise.all(g.map(async(_)=>{try{let $=vu.resolve(u.projectRoot,_.filePath),J=await u.readFileFn($);u.semanticLayer?.notifyFileChanged($,J)}catch{}}))}async function A_(u,g){let _=u.coordinatorFactory?u.coordinatorFactory():new Zg({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=_;for(let $ of u.onIndexedCallbacks)_.onIndexed($);if(_.onIndexed(($)=>{let J=$.changedFiles.length+$.deletedFiles.length;if(u.graphCache&&J>0&&J<100){let O=u.relationRepo;u.graphCache.patchFiles($.changedFiles,$.deletedFiles,(Q)=>{return[u.defaultProject,...u.boundaries.map((N)=>N.project)].flatMap((N)=>O.getByType(N,"imports").concat(O.getByType(N,"type-references")).concat(O.getByType(N,"re-exports"))).filter((N)=>N.srcFilePath===Q||N.dstFilePath===Q).map((N)=>({srcFilePath:N.srcFilePath,dstFilePath:N.dstFilePath}))}),u.graphCacheBuiltAt=Date.now()}else tu(u)}),g.isWatchMode){let $=u.watcherFactory?u.watcherFactory():new Qg({projectRoot:u.projectRoot,ignorePatterns:u.ignorePatterns,extensions:u.extensions},void 0,u.logger);await $.start(T0(u,_)).then((J)=>{if(Eu(J))throw J.data}),u.watcher=$,u.timer=setInterval(()=>{u.updateHeartbeatFn(u.db,process.pid)},n0)}await _.fullIndex(),await q0(u)}function F0(u,g){let _=["SIGTERM","SIGINT","beforeExit"];for(let $ of _){let J=()=>{g().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 C_(u){let{projectRoot:g,extensions:_=[".ts",".mts",".cts"],ignorePatterns:$=["**/node_modules/**"],parseCacheCapacity:J=500,logger:O=console,existsSyncFn:Q=R0,dbConnectionFactory:z,watcherFactory:N,coordinatorFactory:W,repositoryFactory:w,acquireWatcherRoleFn:V=g_,releaseWatcherRoleFn:X=__,updateHeartbeatFn:M=$_,discoverProjectsFn:I=mu,parseSourceFn:A=qu,extractSymbolsFn:T=Cu,extractRelationsFn:q=lu,symbolSearchFn:h=Kg,relationSearchFn:Z=Mg,patternSearchFn:K=Bg,loadTsconfigPathsFn:B=Tu,readFileFn:R=async(x)=>Bun.file(x).text(),unlinkFn:k=async(x)=>{await Bun.file(x).unlink()},watchMode:S,semantic:j,semanticLayerFactory:P}=u;if(!vu.isAbsolute(g))throw new Y("validation",`Gildash: projectRoot must be an absolute path, got: "${g}"`);if(!Q(g))throw new Y("validation",`Gildash: projectRoot does not exist: "${g}"`);let f=z?z():new gg({projectRoot:g}),v=f.open();if(Eu(v))throw v.data;try{let x=await I(g),gu=x[0]?.project??vu.basename(g),d=w?w():(()=>{let c=f;return{fileRepo:new _g(c),symbolRepo:new $g(c),relationRepo:new Jg(c),parseCache:new Xg(J)}})(),e=w?null:f,U=e?new Sg(e):null,D=e?new Rg(e):null,C=S??!0,n=crypto.randomUUID(),y;if(C)y=await Promise.resolve(V(f,process.pid,{instanceId:n}));else y="owner";let H={projectRoot:g,extensions:_,ignorePatterns:$,logger:O,defaultProject:gu,role:y,db:f,symbolRepo:d.symbolRepo,relationRepo:d.relationRepo,fileRepo:d.fileRepo,parseCache:d.parseCache,annotationRepo:U,changelogRepo:D,annotationSearchFn:Y_,releaseWatcherRoleFn:X,parseSourceFn:A,extractSymbolsFn:T,extractRelationsFn:q,symbolSearchFn:h,relationSearchFn:Z,patternSearchFn:K,readFileFn:R,unlinkFn:k,existsSyncFn:Q,acquireWatcherRoleFn:V,updateHeartbeatFn:M,watcherFactory:N,coordinatorFactory:W,instanceId:n,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:x,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(hu(g),H.tsconfigPaths=await B(g),j){let c=vu.join(g,"tsconfig.json");try{if(P)H.semanticLayer=P(c);else{let F=au.create(c);if(Eu(F))throw F.data;H.semanticLayer=F}}catch(F){if(F instanceof Y)throw F;throw new Y("semantic","Gildash: semantic layer creation failed",{cause:F})}}if(y==="owner")await A_(H,{isWatchMode:C});else{let c=0,F=async()=>{try{let m=await Promise.resolve(H.acquireWatcherRoleFn(H.db,process.pid,{instanceId:H.instanceId}));if(c=0,m==="owner"){H.role="owner";for(let E of H.onRoleChangedCallbacks)try{E("owner")}catch(p){H.logger.error("[Gildash] onRoleChanged callback threw:",p)}clearInterval(H.timer),H.timer=null;try{await A_(H,{isWatchMode:!0})}catch(E){if(H.logger.error("[Gildash] owner promotion failed, reverting to reader",E),H.role="reader",H.timer!==null)clearInterval(H.timer),H.timer=null;if(H.watcher){let p=await H.watcher.close();if(Eu(p))H.logger.error("[Gildash] watcher close error during promotion rollback",p.data);H.watcher=null}if(H.coordinator)await H.coordinator.shutdown().catch((p)=>H.logger.error("[Gildash] coordinator shutdown error during promotion rollback",p)),H.coordinator=null;try{H.releaseWatcherRoleFn(H.db,process.pid)}catch(p){H.logger.error("[Gildash] failed to release watcher role during promotion rollback",p)}H.timer=setInterval(F,D_)}}}catch(m){c++;let E=m instanceof Y?m:new Y("watcher","Gildash: healthcheck error",{cause:m});for(let p of H.onErrorCallbacks)try{p(E)}catch(Uu){H.logger.error("[Gildash] onError callback threw:",Uu)}if(H.logger.error("[Gildash] healthcheck error",m),c>=k0)H.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(H.timer),H.timer=null,ou(H).catch((p)=>H.logger.error("[Gildash] close error during healthcheck shutdown",p))}};H.timer=setInterval(F,D_)}if(C)F0(H,()=>ou(H));return H}catch(x){if(f.close(),x instanceof Y)throw x;throw new Y("store","Gildash: initialization failed",{cause:x})}}async function ou(u,g){if(u.closed)return;u.closed=!0;let _=[];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($){_.push($ instanceof Error?$:Error(String($)))}u.semanticLayer=null}if(u.coordinator)try{await u.coordinator.shutdown()}catch($){_.push($ instanceof Error?$:Error(String($)))}if(u.watcher){let $=await u.watcher.close();if(Eu($))_.push($.data)}if(u.timer!==null)clearInterval(u.timer),u.timer=null;try{u.releaseWatcherRoleFn(u.db,process.pid)}catch($){_.push($ instanceof Error?$:Error(String($)))}try{u.db.close()}catch($){_.push($ instanceof Error?$:Error(String($)))}if(g?.cleanup)for(let $ of["","-wal","-shm"])try{await u.unlinkFn(vu.join(u.projectRoot,Yu,fu+$))}catch{}if(_.length>0)throw new Y("close","Gildash: one or more errors occurred during close()",{cause:_})}import{isErr as S_}from"@zipbul/result";function R_(u,g,_,$){if(u.closed)throw new Y("closed","Gildash: instance is closed");let J=u.parseSourceFn(g,_,$);if(S_(J))throw J.data;return u.parseCache.set(g,J),J}async function n_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");let $=new Map,J=[];return await Promise.all(g.map(async(O)=>{try{let Q=await u.readFileFn(O),z=u.parseSourceFn(O,Q,_);if(!S_(z))$.set(O,z);else J.push({filePath:O,error:z.data})}catch(Q){J.push({filePath:O,error:Q instanceof Error?Q:Error(String(Q))})}})),{parsed:$,failures:J}}function k_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");return u.parseCache.get(g)}function T_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");return u.extractSymbolsFn(g)}function q_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");return u.extractRelationsFn(g.program,g.filePath,u.tsconfigPaths??void 0)}import F_ from"path";function G_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.symbolRepo.getStats(g??u.defaultProject)}catch(_){if(_ instanceof Y)throw _;throw new Y("store","Gildash: getStats failed",{cause:_})}}function kg(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.symbolSearchFn({symbolRepo:u.symbolRepo,project:u.defaultProject,query:g})}catch(_){if(_ instanceof Y)throw _;throw new Y("search","Gildash: searchSymbols failed",{cause:_})}}function j_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:u.defaultProject,query:g})}catch(_){if(_ instanceof Y)throw _;throw new Y("search","Gildash: searchRelations failed",{cause:_})}}function E_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.symbolSearchFn({symbolRepo:u.symbolRepo,project:void 0,query:g})}catch(_){if(_ instanceof Y)throw _;throw new Y("search","Gildash: searchAllSymbols failed",{cause:_})}}function v_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:void 0,query:g})}catch(_){if(_ instanceof Y)throw _;throw new Y("search","Gildash: searchAllRelations failed",{cause:_})}}function b_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.fileRepo.getAllFiles(g??u.defaultProject)}catch(_){if(_ instanceof Y)throw _;throw new Y("store","Gildash: listIndexedFiles failed",{cause:_})}}function f_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:_??u.defaultProject,query:{srcFilePath:g,dstFilePath:g,limit:1e4}})}catch($){if($ instanceof Y)throw $;throw new Y("search","Gildash: getInternalRelations failed",{cause:$})}}function P_(u,g,_,$){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{let J=$??u.defaultProject,O=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:J,query:{text:g,exact:!0,filePath:_,limit:1}});if(O.length===0)return null;let Q=O[0],z=Q.detail,N={...Q,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 W=F_.isAbsolute(_)?_:F_.resolve(u.projectRoot,_),w=u.semanticLayer.lineColumnToPosition(W,Q.span.start.line,Q.span.start.column);if(w!==null){let V=u.semanticLayer.findNamePosition(W,w,Q.name)??w,X=u.semanticLayer.collectTypeAt(W,V);if(X)N.resolvedType=X}}catch{}return N}catch(J){if(J instanceof Y)throw J;throw new Y("search","Gildash: getFullSymbol failed",{cause:J})}}function y_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{let $=_??u.defaultProject,J=u.fileRepo.getFile($,g);if(!J)throw new Y("search",`Gildash: file '${g}' is not in the index`);let O=u.symbolRepo.getFileSymbols($,g),Q=u.relationRepo.getOutgoing($,g);return{filePath:J.filePath,lineCount:J.lineCount??0,size:J.size,symbolCount:O.length,exportedSymbolCount:O.filter((z)=>z.isExported).length,relationCount:Q.length}}catch($){if($ instanceof Y)throw $;throw new Y("store","Gildash: getFileStats failed",{cause:$})}}function m_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{return u.fileRepo.getFile(_??u.defaultProject,g)}catch($){if($ instanceof Y)throw $;throw new Y("store","Gildash: getFileInfo failed",{cause:$})}}function h_(u,g,_){return kg(u,{filePath:g,project:_??void 0,limit:1e4})}function i_(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{let J=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:_??u.defaultProject,query:{filePath:g,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:g,exports:J}}catch($){if($ instanceof Y)throw $;throw new Y("search","Gildash: getModuleInterface failed",{cause:$})}}import wu from"path";function bu(u,g,_,$){let J=$??u.defaultProject,O=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:J,query:{text:g,exact:!0,filePath:_,limit:1}});if(O.length===0)return null;let Q=O[0],z=wu.isAbsolute(_)?_:wu.resolve(u.projectRoot,_),N=u.semanticLayer.lineColumnToPosition(z,Q.span.start.line,Q.span.start.column);if(N===null)return null;let W=u.semanticLayer.findNamePosition(z,N,Q.name)??N;return{sym:Q,position:W,absPath:z}}function x_(u,g,_,$){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new Y("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 Y)throw J;throw new Y("search","Gildash: getResolvedType failed",{cause:J})}}function p_(u,g,_,$){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new Y("semantic","Gildash: semantic layer is not enabled");try{let J=bu(u,g,_,$);if(!J)throw new Y("search",`Gildash: symbol '${g}' not found in '${_}'`);return u.semanticLayer.findReferences(J.absPath,J.position)}catch(J){if(J instanceof Y)throw J;throw new Y("search","Gildash: getSemanticReferences failed",{cause:J})}}function l_(u,g,_,$){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new Y("semantic","Gildash: semantic layer is not enabled");try{let J=bu(u,g,_,$);if(!J)throw new Y("search",`Gildash: symbol '${g}' not found in '${_}'`);return u.semanticLayer.findImplementations(J.absPath,J.position)}catch(J){if(J instanceof Y)throw J;throw new Y("search","Gildash: getImplementations failed",{cause:J})}}function d_(u,g,_,$,J,O){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new Y("semantic","Gildash: semantic layer is not enabled");try{let Q=bu(u,g,_,O);if(!Q)throw new Y("search",`Gildash: source symbol '${g}' not found in '${_}'`);let z=bu(u,$,J,O);if(!z)throw new Y("search",`Gildash: target symbol '${$}' not found in '${J}'`);return u.semanticLayer.isTypeAssignableTo(Q.absPath,Q.position,z.absPath,z.position)}catch(Q){if(Q instanceof Y)throw Q;throw new Y("semantic","Gildash: isTypeAssignableTo failed",{cause:Q})}}function r_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new Y("semantic","Gildash: semantic layer is not enabled");try{let _=wu.isAbsolute(g)?g:wu.resolve(u.projectRoot,g);return u.semanticLayer.collectFileTypes(_)}catch(_){if(_ instanceof Y)throw _;throw new Y("semantic","Gildash: getFileTypes failed",{cause:_})}}function c_(u,g,_,$){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new Y("semantic","Gildash: semantic layer is not enabled");try{let J=wu.isAbsolute(g)?g:wu.resolve(u.projectRoot,g),O=u.semanticLayer.lineColumnToPosition(J,_,$);if(O===null)return null;return u.semanticLayer.collectTypeAt(J,O)}catch(J){if(J instanceof Y)throw J;throw new Y("semantic","Gildash: getResolvedTypeAt failed",{cause:J})}}function a_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new Y("semantic","Gildash: semantic layer is not enabled");try{let _=wu.isAbsolute(g.source.filePath)?g.source.filePath:wu.resolve(u.projectRoot,g.source.filePath),$=wu.isAbsolute(g.target.filePath)?g.target.filePath:wu.resolve(u.projectRoot,g.target.filePath),J=u.semanticLayer.lineColumnToPosition(_,g.source.line,g.source.column);if(J===null)return null;let O=u.semanticLayer.lineColumnToPosition($,g.target.line,g.target.column);if(O===null)return null;return u.semanticLayer.isTypeAssignableTo(_,J,$,O)}catch(_){if(_ instanceof Y)throw _;throw new Y("semantic","Gildash: isTypeAssignableToAt failed",{cause:_})}}function s_(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new Y("semantic","Gildash: semantic layer is not enabled");try{return u.semanticLayer.getModuleInterface(g)}catch(_){if(_ instanceof Y)throw _;throw new Y("search","Gildash: getSemanticModuleInterface failed",{cause:_})}}function t_(u,g){let _=new Map(u.map((z)=>[`${z.name}::${z.filePath}`,z])),$=new Map(g.map((z)=>[`${z.name}::${z.filePath}`,z])),J=[],O=[],Q=[];for(let[z,N]of $){let W=_.get(z);if(!W)J.push(N);else if(W.fingerprint!==N.fingerprint)Q.push({before:W,after:N})}for(let[z,N]of _)if(!$.has(z))O.push(N);return{added:J,removed:O,modified:Q}}function o_(u,g){if(u.onIndexedCallbacks.add(g),!u.coordinator)return()=>{u.onIndexedCallbacks.delete(g)};let _=u.coordinator.onIndexed(g);return()=>{u.onIndexedCallbacks.delete(g),_()}}async function e_(u){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.coordinator)throw new Y("closed","Gildash: reindex() is not available for readers");try{let g=await u.coordinator.fullIndex();return tu(u),g}catch(g){if(g instanceof Y)throw g;throw new Y("index","Gildash: reindex failed",{cause:g})}}function u$(u,g,_,$){if(u.closed)throw new Y("closed","Gildash: instance is closed");let J=$??u.defaultProject,O=new Set,Q=[],z=g,N=_;for(;;){let W=`${N}::${z}`;if(O.has(W))return{originalName:z,originalFilePath:N,reExportChain:Q,circular:!0};O.add(W);let w=u.relationSearchFn({relationRepo:u.relationRepo,project:J,query:{type:"re-exports",srcFilePath:N,limit:500}}),V,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 A=I.find((T)=>T.exported===z);if(!A)continue;V=M.dstFilePath,X=A.local;break}if(!V||!X)return{originalName:z,originalFilePath:N,reExportChain:Q,circular:!1};Q.push({filePath:N,exportedAs:z}),N=V,z=X}}function g$(u,g){return u.onFileChangedCallbacks.add(g),()=>{u.onFileChangedCallbacks.delete(g)}}function _$(u,g){return u.onErrorCallbacks.add(g),()=>{u.onErrorCallbacks.delete(g)}}function $$(u,g){return u.onRoleChangedCallbacks.add(g),()=>{u.onRoleChangedCallbacks.delete(g)}}async function J$(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{let $=_?.project??u.defaultProject,J=_?.filePaths?_.filePaths:u.fileRepo.getAllFiles($).map((O)=>O.filePath);return await u.patternSearchFn({pattern:g,filePaths:J})}catch($){if($ instanceof Y)throw $;throw new Y("search","Gildash: findPattern failed",{cause:$})}}async function N$(u,g,_,$){if(u.closed)throw new Y("closed","Gildash: instance is closed");try{let J=$??u.defaultProject,O=new Set,Q=(z,N,W)=>{let w=`${z}::${N}`;if(O.has(w))return{symbolName:z,filePath:N,kind:W,children:[]};O.add(w);let M=u.relationSearchFn({relationRepo:u.relationRepo,project:J,query:{srcFilePath:N,srcSymbolName:z,limit:1000}}).filter((I)=>I.type==="extends"||I.type==="implements").filter((I)=>I.dstSymbolName!=null).map((I)=>Q(I.dstSymbolName,I.dstFilePath,I.type));return{symbolName:z,filePath:N,kind:W,children:M}};return Q(g,_)}catch(J){if(J instanceof Y)throw J;throw new Y("search","Gildash: getHeritageChain failed",{cause:J})}}function Q$(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.annotationRepo||!u.annotationSearchFn)return[];return u.annotationSearchFn({annotationRepo:u.annotationRepo,project:g.project??u.defaultProject,query:g})}function z$(u,g,_){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.changelogRepo)return[];let $=g instanceof Date?g.toISOString():g,J=_?.project??u.defaultProject,O=_?.limit??1000;return u.changelogRepo.getSince({project:J,since:$,symbolName:_?.symbolName,changeTypes:_?.changeTypes,filePath:_?.filePath,includeFullIndex:_?.includeFullIndex,indexRunId:_?.indexRunId,afterId:_?.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 O$(u,g){if(u.closed)throw new Y("closed","Gildash: instance is closed");if(!u.changelogRepo)return 0;let _=g instanceof Date?g.toISOString():g,$=0,J=[u.defaultProject,...u.boundaries.map((Q)=>Q.project)],O=[...new Set(J)];for(let Q of O)$+=u.changelogRepo.pruneOlderThan(Q,_);return $}class Tg{_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 g=await C_(u);return new Tg(g)}async close(u){return ou(this._ctx,u)}parseSource(u,g,_){return R_(this._ctx,u,g,_)}async batchParse(u,g){return n_(this._ctx,u,g)}getParsedAst(u){return k_(this._ctx,u)}extractSymbols(u){return T_(this._ctx,u)}extractRelations(u){return q_(this._ctx,u)}getStats(u){return G_(this._ctx,u)}searchSymbols(u){return kg(this._ctx,u)}searchRelations(u){return j_(this._ctx,u)}searchAllSymbols(u){return E_(this._ctx,u)}searchAllRelations(u){return v_(this._ctx,u)}listIndexedFiles(u){return b_(this._ctx,u)}getInternalRelations(u,g){return f_(this._ctx,u,g)}getFullSymbol(u,g,_){return P_(this._ctx,u,g,_)}getFileStats(u,g){return y_(this._ctx,u,g)}getFileInfo(u,g){return m_(this._ctx,u,g)}getSymbolsByFile(u,g){return h_(this._ctx,u,g)}getModuleInterface(u,g){return i_(this._ctx,u,g)}getDependencies(u,g,_=1e4){return Z_(this._ctx,u,g,_)}getDependents(u,g,_=1e4){return X_(this._ctx,u,g,_)}async getAffected(u,g){return K_(this._ctx,u,g)}async hasCycle(u){return M_(this._ctx,u)}async getImportGraph(u){return B_(this._ctx,u)}async getTransitiveDependencies(u,g){return H_(this._ctx,u,g)}async getCyclePaths(u,g){return L_(this._ctx,u,g)}async getFanMetrics(u,g){return I_(this._ctx,u,g)}getResolvedType(u,g,_){return x_(this._ctx,u,g,_)}getSemanticReferences(u,g,_){return p_(this._ctx,u,g,_)}getImplementations(u,g,_){return l_(this._ctx,u,g,_)}isTypeAssignableTo(u,g,_,$,J){return d_(this._ctx,u,g,_,$,J)}getSemanticModuleInterface(u){return s_(this._ctx,u)}getFileTypes(u){return r_(this._ctx,u)}getResolvedTypeAt(u,g,_){return c_(this._ctx,u,g,_)}isTypeAssignableToAt(u){return a_(this._ctx,u)}diffSymbols(u,g){return t_(u,g)}onIndexed(u){return o_(this._ctx,u)}async reindex(){return e_(this._ctx)}resolveSymbol(u,g,_){return u$(this._ctx,u,g,_)}async findPattern(u,g){return J$(this._ctx,u,g)}async getHeritageChain(u,g,_){return N$(this._ctx,u,g,_)}onFileChanged(u){return g$(this._ctx,u)}onError(u){return _$(this._ctx,u)}onRoleChanged(u){return $$(this._ctx,u)}searchAnnotations(u){return Q$(this._ctx,u)}getSymbolChanges(u,g){return z$(this._ctx,u,g)}pruneChangelog(u){return O$(this._ctx,u)}}export{Kg as symbolSearch,Mg as relationSearch,Bg as patternSearch,_u as gildashError,Y as GildashError,Tg as Gildash,su as DependencyGraph};
@@ -56,7 +56,7 @@ export type CoordinatorLike = Pick<IndexCoordinator, 'fullIndex' | 'shutdown' |
56
56
  handleWatcherEvent?(event: FileChangeEvent): void;
57
57
  };
58
58
  export type WatcherLike = Pick<ProjectWatcher, 'start' | 'close'>;
59
- export type SemanticLayerLike = Pick<SemanticLayer, 'collectTypeAt' | 'collectFileTypes' | 'findReferences' | 'findImplementations' | 'getModuleInterface' | 'getSymbolNode' | 'notifyFileChanged' | 'notifyFileDeleted' | 'dispose' | 'isDisposed' | 'lineColumnToPosition' | 'findNamePosition'>;
59
+ export type SemanticLayerLike = Pick<SemanticLayer, 'collectTypeAt' | 'collectFileTypes' | 'findReferences' | 'findImplementations' | 'isTypeAssignableTo' | 'getModuleInterface' | 'getSymbolNode' | 'notifyFileChanged' | 'notifyFileDeleted' | 'dispose' | 'isDisposed' | 'lineColumnToPosition' | 'findNamePosition'>;
60
60
  /** Internal shared state for all Gildash API modules. */
61
61
  export interface GildashContext {
62
62
  readonly projectRoot: string;
@@ -79,10 +79,32 @@ export declare class Gildash {
79
79
  maxCycles?: number;
80
80
  }): Promise<string[][]>;
81
81
  getFanMetrics(filePath: string, project?: string): Promise<FanMetrics>;
82
+ /**
83
+ * Returns the resolved type tree for the given symbol.
84
+ *
85
+ * The returned tree is always a bounded, finite, acyclic structure.
86
+ * At the truncation boundary `members` and `typeArguments` will be
87
+ * `undefined`, but `text` always contains the full type string.
88
+ */
82
89
  getResolvedType(symbolName: string, filePath: string, project?: string): ResolvedType | null;
83
90
  getSemanticReferences(symbolName: string, filePath: string, project?: string): SemanticReference[];
84
91
  getImplementations(symbolName: string, filePath: string, project?: string): Implementation[];
92
+ isTypeAssignableTo(sourceSymbol: string, sourceFilePath: string, targetSymbol: string, targetFilePath: string, project?: string): boolean | null;
85
93
  getSemanticModuleInterface(filePath: string): SemanticModuleInterface;
94
+ getFileTypes(filePath: string): Map<number, ResolvedType>;
95
+ getResolvedTypeAt(filePath: string, line: number, column: number): ResolvedType | null;
96
+ isTypeAssignableToAt(opts: {
97
+ source: {
98
+ filePath: string;
99
+ line: number;
100
+ column: number;
101
+ };
102
+ target: {
103
+ filePath: string;
104
+ line: number;
105
+ column: number;
106
+ };
107
+ }): boolean | null;
86
108
  diffSymbols(before: SymbolSearchResult[], after: SymbolSearchResult[]): SymbolDiff;
87
109
  onIndexed(callback: (result: IndexResult) => void): () => void;
88
110
  reindex(): Promise<IndexResult>;
@@ -16,5 +16,24 @@ export declare function getResolvedType(ctx: GildashContext, symbolName: string,
16
16
  export declare function getSemanticReferences(ctx: GildashContext, symbolName: string, filePath: string, project?: string): SemanticReference[];
17
17
  /** Find implementations of an interface/abstract class. */
18
18
  export declare function getImplementations(ctx: GildashContext, symbolName: string, filePath: string, project?: string): Implementation[];
19
+ /** Check whether a source symbol's type is assignable to a target symbol's type. */
20
+ export declare function isTypeAssignableTo(ctx: GildashContext, sourceSymbol: string, sourceFilePath: string, targetSymbol: string, targetFilePath: string, project?: string): boolean | null;
21
+ /** Retrieve resolved types for all declarations in a file. */
22
+ export declare function getFileTypes(ctx: GildashContext, filePath: string): Map<number, ResolvedType>;
23
+ /** Retrieve the resolved type at a specific position (line:column) without DB lookup. */
24
+ export declare function getResolvedTypeAt(ctx: GildashContext, filePath: string, line: number, column: number): ResolvedType | null;
25
+ /** Check type assignability at specific positions without DB lookup. */
26
+ export declare function isTypeAssignableToAt(ctx: GildashContext, opts: {
27
+ source: {
28
+ filePath: string;
29
+ line: number;
30
+ column: number;
31
+ };
32
+ target: {
33
+ filePath: string;
34
+ line: number;
35
+ column: number;
36
+ };
37
+ }): boolean | null;
19
38
  /** Retrieve the semantic module interface — exported symbols with resolved types. */
20
39
  export declare function getSemanticModuleInterface(ctx: GildashContext, filePath: string): SemanticModuleInterface;
@@ -43,16 +43,56 @@ export interface IndexResult {
43
43
  name: string;
44
44
  filePath: string;
45
45
  kind: string;
46
+ isExported: boolean;
46
47
  }>;
47
48
  modified: Array<{
48
49
  name: string;
49
50
  filePath: string;
50
51
  kind: string;
52
+ isExported: boolean;
51
53
  }>;
52
54
  removed: Array<{
53
55
  name: string;
54
56
  filePath: string;
55
57
  kind: string;
58
+ isExported: boolean;
59
+ }>;
60
+ };
61
+ /** Symbols that were renamed (detected via structural fingerprint matching). */
62
+ renamedSymbols: Array<{
63
+ oldName: string;
64
+ newName: string;
65
+ filePath: string;
66
+ kind: string;
67
+ isExported: boolean;
68
+ }>;
69
+ /** Symbols that moved to a different file (detected via fingerprint matching). Incremental only. */
70
+ movedSymbols: Array<{
71
+ name: string;
72
+ oldFilePath: string;
73
+ newFilePath: string;
74
+ kind: string;
75
+ isExported: boolean;
76
+ }>;
77
+ /** Relation-level diff compared to the previous index state. */
78
+ changedRelations: {
79
+ added: Array<{
80
+ type: string;
81
+ srcFilePath: string;
82
+ dstFilePath: string;
83
+ srcSymbolName: string | null;
84
+ dstSymbolName: string | null;
85
+ dstProject: string;
86
+ metaJson: string | null;
87
+ }>;
88
+ removed: Array<{
89
+ type: string;
90
+ srcFilePath: string;
91
+ dstFilePath: string;
92
+ srcSymbolName: string | null;
93
+ dstSymbolName: string | null;
94
+ dstProject: string;
95
+ metaJson: string | null;
56
96
  }>;
57
97
  };
58
98
  }
@@ -92,6 +132,7 @@ export interface IndexCoordinatorOptions {
92
132
  newDstProject?: string;
93
133
  }): void;
94
134
  deleteFileRelations(project: string, filePath: string): void;
135
+ getOutgoing(project: string, srcFilePath: string): RelationRecord[];
95
136
  };
96
137
  annotationRepo?: {
97
138
  deleteFileAnnotations(project: string, filePath: string): void;
@@ -5,6 +5,7 @@ export interface SymbolSnap {
5
5
  fingerprint: string | null;
6
6
  structuralFingerprint: string | null;
7
7
  startLine: number;
8
+ isExported: number;
8
9
  }
9
10
  export interface RenamedEntry {
10
11
  oldName: string;
@@ -23,6 +23,10 @@ export interface RelationSearchQuery {
23
23
  dstSymbolName?: string;
24
24
  /** Destination project. */
25
25
  dstProject?: string;
26
+ /** Glob pattern for source file path filtering (app-level, via Bun.Glob). Mutually exclusive with srcFilePath. */
27
+ srcFilePathPattern?: string;
28
+ /** Glob pattern for destination file path filtering (app-level, via Bun.Glob). Mutually exclusive with dstFilePath. */
29
+ dstFilePathPattern?: string;
26
30
  /** Relationship type: `'imports'`, `'calls'`, `'extends'`, or `'implements'`. */
27
31
  type?: CodeRelation['type'];
28
32
  /** Limit results to this project. */
@@ -37,6 +37,7 @@ export declare class SemanticLayer {
37
37
  collectFileTypes(filePath: string): Map<number, ResolvedType>;
38
38
  findReferences(filePath: string, position: number): SemanticReference[];
39
39
  findImplementations(filePath: string, position: number): Implementation[];
40
+ isTypeAssignableTo(sourceFilePath: string, sourcePosition: number, targetFilePath: string, targetPosition: number): boolean | null;
40
41
  getSymbolNode(filePath: string, position: number): SymbolNode | null;
41
42
  getModuleInterface(filePath: string): SemanticModuleInterface;
42
43
  notifyFileChanged(filePath: string, content: string): void;
@@ -16,6 +16,16 @@ export declare class TypeCollector {
16
16
  * - `TscProgram이` disposed 상태이면 throw (getProgram이 throw)
17
17
  */
18
18
  collectAt(filePath: string, position: number): ResolvedType | null;
19
+ /**
20
+ * 두 위치의 타입 호환성을 검사한다.
21
+ *
22
+ * `sourceFilePath:sourcePosition`의 타입이 `targetFilePath:targetPosition`의 타입에
23
+ * 할당 가능한지 여부를 반환한다.
24
+ *
25
+ * - 파일이 없거나 위치에 식별자가 없으면 `null` 반환
26
+ * - `TscProgram`이 disposed 상태이면 throw (getProgram이 throw)
27
+ */
28
+ isAssignableTo(sourceFilePath: string, sourcePosition: number, targetFilePath: string, targetPosition: number): boolean | null;
19
29
  /**
20
30
  * `filePath`에서 모든 선언 이름 심볼의 타입을 수집한다.
21
31
  *
@@ -9,6 +9,11 @@
9
9
  *
10
10
  * Captures the full structural description of a type including union/intersection
11
11
  * decomposition and generic argument resolution.
12
+ *
13
+ * **Tree structure guarantee**: The returned value is always a bounded, finite,
14
+ * acyclic tree. Beyond the internal depth limit, `members` and `typeArguments`
15
+ * are `undefined` (leaf node), but `text` is always populated with the full
16
+ * type string at every level.
12
17
  */
13
18
  export interface ResolvedType {
14
19
  /** Human-readable type string, e.g. `"string | undefined"`, `"Promise<number>"`. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zipbul/gildash",
3
- "version": "0.9.3",
3
+ "version": "0.10.0",
4
4
  "description": "TypeScript code indexing and dependency graph engine for Bun",
5
5
  "license": "MIT",
6
6
  "repository": {