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