@zipbul/gildash 0.9.0 → 0.9.1

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/README.ko.md CHANGED
@@ -418,6 +418,32 @@ Gildash (파사드)
418
418
 
419
419
  ## ⬆️ 업그레이드
420
420
 
421
+ ### 0.9.0 → 0.9.1
422
+
423
+ **버그 수정 및 성능 개선.** API 호환성 변경 없음.
424
+
425
+ - **수정:** `getParsedAst()`가 인스턴스 닫힌 상태에서 `GildashError('closed')` throw (기존: `undefined` 반환)
426
+ - **수정:** `searchSymbols({ regex })`에 잘못된 regex 전달 시 `GildashError('validation')` throw (기존: `[]` 반환)
427
+ - **수정:** reader→owner 승격 시 `ctx.role`이 `'owner'`로 정상 갱신
428
+ - **수정:** Full-index 경로에서 파일 읽기 실패 시 `IndexResult.failedFiles`에 정상 추적
429
+ - **수정:** reader→owner 승격 실패 rollback에서 heartbeat 타이머 정리 및 watcher role 해제
430
+ - **성능:** 심볼/어노테이션/체인지로그 repository 배치 INSERT (N+1 개별 insert 제거)
431
+ - **성능:** JSDoc 코멘트 탐색에 binary search 도입 (대형 파일에서 ~40x 개선)
432
+ - **성능:** regex 검색 시 progressive fetch 전략 (고정 5000행 over-fetch 제거)
433
+ - **성능:** `getQualifiedName()` O(n²) unshift → push+reverse O(n)
434
+
435
+ ### 0.8.x → 0.9.0
436
+
437
+ **신규:** 어노테이션 추출 및 심볼 체인지로그 추적.
438
+
439
+ - `searchAnnotations(query)` — JSDoc, 라인, 블록 코멘트에서 `@tag value` 검색
440
+ - `getSymbolChanges(since, opts?)` — 심볼 레벨 변경 이력 (rename/move 감지 포함)
441
+ - `pruneChangelog(before)` — 오래된 체인지로그 항목 정리
442
+ - `IndexResult`에 `totalAnnotations` 필드 추가
443
+ - 마이그레이션 `0006_annotations`, `0007_symbol_changelog` 자동 적용
444
+
445
+ **호환성 변경 없음.** 기존 데이터베이스는 자동 마이그레이션됩니다.
446
+
421
447
  ### 0.7.x → 0.8.0
422
448
 
423
449
  **Breaking:** `batchParse()`가 `Map<string, ParsedFile>` 대신 `BatchParseResult` (`parsed` + `failures` 필드)를 반환합니다.
package/README.md CHANGED
@@ -631,6 +631,20 @@ When multiple processes share the same SQLite database, gildash enforces a singl
631
631
 
632
632
  ## ⬆️ Upgrading
633
633
 
634
+ ### From 0.9.0 to 0.9.1
635
+
636
+ **Bug fixes and performance improvements.** No breaking API changes.
637
+
638
+ - **Fix:** `getParsedAst()` now throws `GildashError('closed')` when the instance is closed, consistent with all other public APIs (previously returned `undefined`)
639
+ - **Fix:** `searchSymbols({ regex })` with an invalid regex now throws `GildashError('validation')` instead of silently returning `[]`
640
+ - **Fix:** `ctx.role` is now correctly updated to `'owner'` when a reader is promoted
641
+ - **Fix:** Full-index path now properly tracks failed file reads in `IndexResult.failedFiles`
642
+ - **Fix:** Reader→Owner promotion rollback now cleans up heartbeat timer and releases watcher role
643
+ - **Perf:** Batch INSERT for symbol, annotation, and changelog repositories (replaces N+1 individual inserts)
644
+ - **Perf:** Binary search for JSDoc comment association (~40x faster on large files)
645
+ - **Perf:** Progressive regex fetch strategy (replaces fixed 5000-row over-fetch)
646
+ - **Perf:** `getQualifiedName()` uses push+reverse instead of O(n²) unshift
647
+
634
648
  ### From 0.8.x to 0.9.0
635
649
 
636
650
  **New:** Annotation extraction and symbol changelog tracking.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- var ei=Object.defineProperty;var ng=(n)=>n;function ug(n,u){this[n]=ng.bind(null,u)}var ig=(n,u)=>{for(var i in u)ei(n,i,{get:u[i],enumerable:!0,configurable:!0,set:ug.bind(u,i)})};var Zu=import.meta.require;import{isErr as kn}from"@zipbul/result";import yn from"path";import{existsSync as Mt}from"fs";import{err as Xu,isErr as wg}from"@zipbul/result";import{Database as _g}from"bun:sqlite";import{mkdirSync as Ng,unlinkSync as Bu,existsSync as Cu}from"fs";import{dirname as Sg,join as Tu}from"path";import{drizzle as $g}from"drizzle-orm/bun-sqlite";import{migrate as Jg}from"drizzle-orm/bun-sqlite/migrator";class $ extends Error{type;constructor(n,u,i){super(u,i);this.type=n;this.name="GildashError"}}function c(n,u,i){return new $(n,u,i!==void 0?{cause:i}:void 0)}var $n=".gildash",Rn="gildash.db";var on={};ig(on,{watcherOwner:()=>Og,symbols:()=>y,symbolChangelog:()=>e,relations:()=>V,files:()=>v,annotations:()=>un});import{sql as gg}from"drizzle-orm";import{sqliteTable as Dn,text as T,integer as x,real as tg,index as nn,primaryKey as rg,foreignKey as Fn,check as mg}from"drizzle-orm/sqlite-core";var v=Dn("files",{project:T("project").notNull(),filePath:T("file_path").notNull(),mtimeMs:tg("mtime_ms").notNull(),size:x("size").notNull(),contentHash:T("content_hash").notNull(),updatedAt:T("updated_at").notNull(),lineCount:x("line_count")},(n)=>[rg({columns:[n.project,n.filePath]})]),y=Dn("symbols",{id:x("id").primaryKey({autoIncrement:!0}),project:T("project").notNull(),filePath:T("file_path").notNull(),kind:T("kind").notNull(),name:T("name").notNull(),startLine:x("start_line").notNull(),startColumn:x("start_column").notNull(),endLine:x("end_line").notNull(),endColumn:x("end_column").notNull(),isExported:x("is_exported").notNull().default(0),signature:T("signature"),fingerprint:T("fingerprint"),detailJson:T("detail_json"),contentHash:T("content_hash").notNull(),indexedAt:T("indexed_at").notNull(),resolvedType:T("resolved_type"),structuralFingerprint:T("structural_fingerprint")},(n)=>[nn("idx_symbols_project_file").on(n.project,n.filePath),nn("idx_symbols_project_kind").on(n.project,n.kind),nn("idx_symbols_project_name").on(n.project,n.name),nn("idx_symbols_fingerprint").on(n.project,n.fingerprint),Fn({columns:[n.project,n.filePath],foreignColumns:[v.project,v.filePath]}).onDelete("cascade")]),V=Dn("relations",{id:x("id").primaryKey({autoIncrement:!0}),project:T("project").notNull(),type:T("type").notNull(),srcFilePath:T("src_file_path").notNull(),srcSymbolName:T("src_symbol_name"),dstProject:T("dst_project").notNull(),dstFilePath:T("dst_file_path").notNull(),dstSymbolName:T("dst_symbol_name"),metaJson:T("meta_json")},(n)=>[nn("idx_relations_src").on(n.project,n.srcFilePath),nn("idx_relations_dst").on(n.dstProject,n.dstFilePath),nn("idx_relations_type").on(n.project,n.type),nn("idx_relations_project_type_src").on(n.project,n.type,n.srcFilePath),Fn({columns:[n.project,n.srcFilePath],foreignColumns:[v.project,v.filePath]}).onDelete("cascade"),Fn({columns:[n.dstProject,n.dstFilePath],foreignColumns:[v.project,v.filePath]}).onDelete("cascade")]),un=Dn("annotations",{id:x("id").primaryKey({autoIncrement:!0}),project:T("project").notNull(),filePath:T("file_path").notNull(),tag:T("tag").notNull(),value:T("value").notNull().default(""),source:T("source").notNull(),symbolName:T("symbol_name"),startLine:x("start_line").notNull(),startColumn:x("start_column").notNull(),endLine:x("end_line").notNull(),endColumn:x("end_column").notNull(),indexedAt:T("indexed_at").notNull()},(n)=>[nn("idx_annotations_project_file").on(n.project,n.filePath),nn("idx_annotations_project_tag").on(n.project,n.tag),nn("idx_annotations_project_symbol").on(n.project,n.symbolName),Fn({columns:[n.project,n.filePath],foreignColumns:[v.project,v.filePath]}).onDelete("cascade")]),e=Dn("symbol_changelog",{id:x("id").primaryKey({autoIncrement:!0}),project:T("project").notNull(),changeType:T("change_type").notNull(),symbolName:T("symbol_name").notNull(),symbolKind:T("symbol_kind").notNull(),filePath:T("file_path").notNull(),oldName:T("old_name"),oldFilePath:T("old_file_path"),fingerprint:T("fingerprint"),changedAt:T("changed_at").notNull(),isFullIndex:x("is_full_index").notNull().default(0),indexRunId:T("index_run_id").notNull()},(n)=>[nn("idx_changelog_project_changed_at").on(n.project,n.changedAt),nn("idx_changelog_project_name").on(n.project,n.symbolName),nn("idx_changelog_project_run").on(n.project,n.indexRunId)]),Og=Dn("watcher_owner",{id:x("id").primaryKey(),pid:x("pid").notNull(),startedAt:T("started_at").notNull(),heartbeatAt:T("heartbeat_at").notNull(),instanceId:T("instance_id")},(n)=>[mg("watcher_owner_singleton",gg`${n.id} = 1`)]);class cn{client=null;drizzle=null;dbPath;txDepth=0;constructor(n){this.dbPath=Tu(n.projectRoot,$n,Rn)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{Ng(Sg(this.dbPath),{recursive:!0}),this.client=new _g(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:on}),Jg(this.drizzle,{migrationsFolder:Tu(import.meta.dirname,"migrations")});let n=this.client.prepare("PRAGMA foreign_key_check").all();if(n.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(n.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON");let u=this.client;if(typeof u.function==="function")u.function.call(this.client,"regexp",(i,g)=>{try{return new RegExp(i).test(g)?1:0}catch{return 0}})}catch(n){if(this.isCorruptionError(n)&&Cu(this.dbPath)){this.closeClient(),Bu(this.dbPath);for(let i of["-wal","-shm"]){let g=this.dbPath+i;if(Cu(g))Bu(g)}let u=this.open();if(wg(u))return Xu(c("store",`Failed to recover database at ${this.dbPath}`,u.data));return u}return Xu(c("store",`Failed to open database at ${this.dbPath}`,n))}}close(){this.closeClient(),this.drizzle=null}transaction(n){let u=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return u.transaction(()=>n(this))()}finally{this.txDepth--}}let i=`sp_${this.txDepth++}`;u.run(`SAVEPOINT "${i}"`);try{let g=n(this);return u.run(`RELEASE SAVEPOINT "${i}"`),g}catch(g){throw u.run(`ROLLBACK TO SAVEPOINT "${i}"`),u.run(`RELEASE SAVEPOINT "${i}"`),g}finally{this.txDepth--}}immediateTransaction(n){let u=this.requireClient();this.txDepth++,u.run("BEGIN IMMEDIATE");try{let i=n();return u.run("COMMIT"),i}catch(i){throw u.run("ROLLBACK"),i}finally{this.txDepth--}}query(n){let u=this.requireClient().prepare(n).get();if(!u)return null;return Object.values(u)[0]}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((u)=>u.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(n,u){let i=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(n,i,i,u??null)}replaceOwner(n,u){let i=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(n,i,i,u??null)}touchOwner(n){let u=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(u,n)}deleteOwner(n){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(n)}requireClient(){if(!this.client)throw Error("Database is not open. Call open() first.");return this.client}closeClient(){if(this.client)this.client.close(),this.client=null}isCorruptionError(n){if(!(n instanceof Error))return!1;let u=n.message.toLowerCase();return u.includes("malformed")||u.includes("corrupt")||u.includes("not a database")||u.includes("disk i/o error")||u.includes("sqlite_corrupt")}}import{eq as Zn,and as Lu}from"drizzle-orm";class en{db;constructor(n){this.db=n}getFile(n,u){return this.db.drizzleDb.select().from(v).where(Lu(Zn(v.project,n),Zn(v.filePath,u))).get()??null}upsertFile(n){this.db.drizzleDb.insert(v).values({project:n.project,filePath:n.filePath,mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}).onConflictDoUpdate({target:[v.project,v.filePath],set:{mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}}).run()}getAllFiles(n){return this.db.drizzleDb.select().from(v).where(Zn(v.project,n)).all()}getFilesMap(n){let u=this.getAllFiles(n),i=new Map;for(let g of u)i.set(g.filePath,g);return i}deleteFile(n,u){this.db.drizzleDb.delete(v).where(Lu(Zn(v.project,n),Zn(v.filePath,u))).run()}}import{eq as a,and as Mn,sql as sn,count as Ag}from"drizzle-orm";function Kn(n){return n.trim().split(/\s+/).map((u)=>u.trim()).filter((u)=>u.length>0).map((u)=>`"${u.replaceAll('"','""')}"*`).join(" ")}class nu{db;constructor(n){this.db=n}replaceFileSymbols(n,u,i,g){if(this.db.drizzleDb.delete(y).where(Mn(a(y.project,n),a(y.filePath,u))).run(),!g.length)return;let t=new Date().toISOString();for(let m of g)this.db.drizzleDb.insert(y).values({project:n,filePath:u,kind:m.kind??"unknown",name:m.name??"",startLine:m.startLine??0,startColumn:m.startColumn??0,endLine:m.endLine??0,endColumn:m.endColumn??0,isExported:m.isExported??0,signature:m.signature??null,fingerprint:m.fingerprint??null,detailJson:m.detailJson??null,contentHash:i,indexedAt:m.indexedAt??t,resolvedType:m.resolvedType??null,structuralFingerprint:m.structuralFingerprint??null}).run()}getFileSymbols(n,u){return this.db.drizzleDb.select().from(y).where(Mn(a(y.project,n),a(y.filePath,u))).all()}searchByName(n,u,i={}){let g=i.limit??50,t=Kn(u);if(!t)return[];return this.db.drizzleDb.select().from(y).where(Mn(sn`${y.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${t})`,a(y.project,n),i.kind?a(y.kind,i.kind):void 0)).orderBy(y.name).limit(g).all()}searchByKind(n,u){return this.db.drizzleDb.select().from(y).where(Mn(a(y.project,n),a(y.kind,u))).orderBy(y.name).all()}getStats(n){let u=this.db.drizzleDb.select({symbolCount:Ag(),fileCount:sn`COUNT(DISTINCT ${y.filePath})`}).from(y).where(a(y.project,n)).get();return{symbolCount:u?.symbolCount??0,fileCount:u?.fileCount??0}}getByFingerprint(n,u){return this.db.drizzleDb.select().from(y).where(Mn(a(y.project,n),a(y.fingerprint,u))).all()}deleteFileSymbols(n,u){this.db.drizzleDb.delete(y).where(Mn(a(y.project,n),a(y.filePath,u))).run()}searchByQuery(n){let u=this.db.drizzleDb.select().from(y).where(Mn(n.ftsQuery?sn`${y.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${n.ftsQuery})`:void 0,n.exactName?a(y.name,n.exactName):void 0,n.project!==void 0?a(y.project,n.project):void 0,n.kind?a(y.kind,n.kind):void 0,n.filePath!==void 0?a(y.filePath,n.filePath):void 0,n.isExported!==void 0?a(y.isExported,n.isExported?1:0):void 0,n.decorator?sn`${y.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${n.decorator})`:void 0,n.resolvedType!==void 0?a(y.resolvedType,n.resolvedType):void 0)).orderBy(y.name).limit(n.regex?Math.max(n.limit*50,5000):n.limit).all();if(!n.regex)return u;try{let i=new RegExp(n.regex);return u.filter((g)=>i.test(g.name)).slice(0,n.limit)}catch{return[]}}}import{eq as p,and as wn,isNull as ku,or as Mg}from"drizzle-orm";class uu{db;constructor(n){this.db=n}replaceFileRelations(n,u,i){this.db.transaction((g)=>{if(g.drizzleDb.delete(V).where(wn(p(V.project,n),p(V.srcFilePath,u))).run(),!i.length)return;for(let t of i)g.drizzleDb.insert(V).values({project:n,type:t.type??"unknown",srcFilePath:t.srcFilePath??u,srcSymbolName:t.srcSymbolName??null,dstProject:t.dstProject??n,dstFilePath:t.dstFilePath??"",dstSymbolName:t.dstSymbolName??null,metaJson:t.metaJson??null}).run()})}getOutgoing(n,u,i){if(i!==void 0)return this.db.drizzleDb.select({project:V.project,type:V.type,srcFilePath:V.srcFilePath,srcSymbolName:V.srcSymbolName,dstProject:V.dstProject,dstFilePath:V.dstFilePath,dstSymbolName:V.dstSymbolName,metaJson:V.metaJson}).from(V).where(wn(p(V.project,n),p(V.srcFilePath,u),Mg(p(V.srcSymbolName,i),ku(V.srcSymbolName)))).all();return this.db.drizzleDb.select({project:V.project,type:V.type,srcFilePath:V.srcFilePath,srcSymbolName:V.srcSymbolName,dstProject:V.dstProject,dstFilePath:V.dstFilePath,dstSymbolName:V.dstSymbolName,metaJson:V.metaJson}).from(V).where(wn(p(V.project,n),p(V.srcFilePath,u))).all()}getIncoming(n){let{dstProject:u,dstFilePath:i}=n;return this.db.drizzleDb.select({project:V.project,type:V.type,srcFilePath:V.srcFilePath,srcSymbolName:V.srcSymbolName,dstProject:V.dstProject,dstFilePath:V.dstFilePath,dstSymbolName:V.dstSymbolName,metaJson:V.metaJson}).from(V).where(wn(p(V.dstProject,u),p(V.dstFilePath,i))).all()}getByType(n,u){return this.db.drizzleDb.select({project:V.project,type:V.type,srcFilePath:V.srcFilePath,srcSymbolName:V.srcSymbolName,dstProject:V.dstProject,dstFilePath:V.dstFilePath,dstSymbolName:V.dstSymbolName,metaJson:V.metaJson}).from(V).where(wn(p(V.project,n),p(V.type,u))).all()}deleteFileRelations(n,u){this.db.drizzleDb.delete(V).where(wn(p(V.project,n),p(V.srcFilePath,u))).run()}searchRelations(n){return this.db.drizzleDb.select({project:V.project,type:V.type,srcFilePath:V.srcFilePath,srcSymbolName:V.srcSymbolName,dstProject:V.dstProject,dstFilePath:V.dstFilePath,dstSymbolName:V.dstSymbolName,metaJson:V.metaJson}).from(V).where(wn(n.project!==void 0?p(V.project,n.project):void 0,n.srcFilePath!==void 0?p(V.srcFilePath,n.srcFilePath):void 0,n.srcSymbolName!==void 0?p(V.srcSymbolName,n.srcSymbolName):void 0,n.dstProject!==void 0?p(V.dstProject,n.dstProject):void 0,n.dstFilePath!==void 0?p(V.dstFilePath,n.dstFilePath):void 0,n.dstSymbolName!==void 0?p(V.dstSymbolName,n.dstSymbolName):void 0,n.type!==void 0?p(V.type,n.type):void 0)).limit(n.limit).all()}retargetRelations(n){let{dstProject:u,oldFile:i,oldSymbol:g,newFile:t,newSymbol:m,newDstProject:w}=n,O=g===null?wn(p(V.dstProject,u),p(V.dstFilePath,i),ku(V.dstSymbolName)):wn(p(V.dstProject,u),p(V.dstFilePath,i),p(V.dstSymbolName,g)),r={dstFilePath:t,dstSymbolName:m};if(w!==void 0)r.dstProject=w;this.db.drizzleDb.update(V).set(r).where(O).run()}}import{err as yu}from"@zipbul/result";import{subscribe as Qg}from"@parcel/watcher";import iu from"path";var zg=["**/.git/**",`**/${$n}/**`,"**/dist/**","**/node_modules/**"],fg=new Set(["package.json","tsconfig.json"]);function Dg(n){return n.replaceAll("\\","/")}function Kg(n){if(n==="update")return"change";if(n==="create")return"create";return"delete"}class gu{#n;#u;#i;#t;#g;#r;constructor(n,u=Qg,i=console){this.#u=n.projectRoot,this.#i=[...zg,...n.ignorePatterns??[]],this.#t=new Set((n.extensions??[".ts",".mts",".cts"]).map((g)=>g.toLowerCase())),this.#g=u,this.#r=i}async start(n){try{this.#n=await this.#g(this.#u,(u,i)=>{if(u){this.#r.error(c("watcher","Callback error",u));return}try{for(let g of i){let t=Dg(iu.relative(this.#u,g.path));if(t.startsWith(".."))continue;let m=iu.basename(t),w=iu.extname(t).toLowerCase();if(!fg.has(m)&&!this.#t.has(w))continue;if(t.endsWith(".d.ts"))continue;n({eventType:Kg(g.type),filePath:t})}}catch(g){this.#r.error(c("watcher","Callback error",g))}},{ignore:this.#i})}catch(u){return yu(c("watcher","Failed to subscribe watcher",u))}}async close(){if(!this.#n)return;try{await this.#n.unsubscribe(),this.#n=void 0}catch(n){return yu(c("watcher","Failed to close watcher",n))}}}import tu from"path";import{promises as Vg}from"fs";var Wg=["**/node_modules/**","**/.git/**",`**/${$n}/**`,"**/dist/**"];async function jn(n){let u=[];for await(let i of Vg.glob("**/package.json",{cwd:n,exclude:Wg})){let g=tu.dirname(i).replaceAll("\\","/"),t=tu.join(n,i),m=await Bun.file(t).json(),w=typeof m?.name==="string"&&m.name.length>0?m.name:tu.basename(g==="."?n:g);u.push({dir:g,project:w})}return u.sort((i,g)=>g.dir.length-i.dir.length),u}function P(n,u,i="default"){let g=n.replaceAll("\\","/");for(let t of u){if(t.dir===".")return t.project;if(g===t.dir||g.startsWith(`${t.dir}/`))return t.project}return i}import Ru from"path";var Jn=new Map;async function Hg(n){let u=Bun.file(n);if(!await u.exists())return null;try{let i=await u.text(),g=Bun.JSONC.parse(i);return typeof g==="object"&&g!==null?g:null}catch{return null}}async function Xn(n){if(Jn.has(n))return Jn.get(n)??null;let u=Ru.join(n,"tsconfig.json"),i=await Hg(u);if(!i)return Jn.set(n,null),null;let g=typeof i.compilerOptions==="object"&&i.compilerOptions!==null?i.compilerOptions:null;if(!g)return Jn.set(n,null),null;let t=typeof g.baseUrl==="string"?g.baseUrl:null,m=typeof g.paths==="object"&&g.paths!==null?g.paths:null;if(!t&&!m)return Jn.set(n,null),null;let w=t?Ru.resolve(n,t):n,O=new Map;if(m)for(let[S,_]of Object.entries(m)){if(!Array.isArray(_))continue;let N=_.filter((M)=>typeof M==="string");O.set(S,N)}let r={baseUrl:w,paths:O};return Jn.set(n,r),r}function bn(n){if(n){Jn.delete(n);return}Jn.clear()}import Fu from"path";function qn(n,u){return Fu.relative(n,u).replaceAll("\\","/")}function Vn(n,u){return Fu.resolve(n,u)}function mn(n){let u=Bun.hash.xxHash64(n);return BigInt.asUintN(64,BigInt(u)).toString(16).padStart(16,"0")}import{isErr as hu}from"@zipbul/result";import{err as Ug}from"@zipbul/result";import{parseSync as Yg}from"oxc-parser";function Bn(n,u,i,g=Yg){try{let{program:t,errors:m,comments:w}=g(n,u,i);return{filePath:n,program:t,errors:m,comments:w,sourceText:u}}catch(t){return Ug(c("parse",`Failed to parse file: ${n}`,t))}}import{promises as Ig}from"fs";import{join as Zg}from"path";async function su(n){let{projectRoot:u,extensions:i,ignorePatterns:g,fileRepo:t}=n,m=t.getFilesMap(),w=new Set,O=[],r=[],S=g.map((N)=>new Bun.Glob(N));for await(let N of Ig.glob("**/*",{cwd:u})){if(!i.some((J)=>N.endsWith(J)))continue;if(N.startsWith("node_modules/")||N.includes("/node_modules/"))continue;if(S.some((J)=>J.match(N)))continue;w.add(N);let M=Zg(u,N),f=Bun.file(M),{size:H,lastModified:K}=f,X=m.get(N);if(!X){let J=await f.text(),W=mn(J);O.push({filePath:N,contentHash:W,mtimeMs:K,size:H});continue}if(X.mtimeMs===K&&X.size===H){r.push({filePath:N,contentHash:X.contentHash,mtimeMs:K,size:H});continue}let A=await f.text(),z=mn(A);if(z===X.contentHash)r.push({filePath:N,contentHash:z,mtimeMs:K,size:H});else O.push({filePath:N,contentHash:z,mtimeMs:K,size:H})}let _=[];for(let N of m.keys())if(!w.has(N))_.push(N);return{changed:O,unchanged:r,deleted:_}}function Gn(n){let u=[0];for(let i=0;i<n.length;i++)if(n[i]===`
3
- `)u.push(i+1);return u}function rn(n,u){let i=0,g=n.length-1;while(i<g){let t=i+g+1>>1;if(n[t]<=u)i=t;else g=t-1}return{line:i+1,column:u-n[i]}}import{err as Xg}from"@zipbul/result";import{parse as Bg}from"comment-parser";function En(n){try{let u=n.trim();if(u.startsWith("/**"))u=u.slice(3);if(u.endsWith("*/"))u=u.slice(0,-2);let g=Bg(`/** ${u} */`)[0]??{description:"",tags:[]};return{description:(g.description??"").trim(),tags:(g.tags??[]).map((t)=>({tag:t.tag??"",name:t.name??"",type:t.type??"",description:t.description??"",optional:t.optional??!1,...t.default!==void 0?{default:t.default}:{}}))}}catch(u){return Xg(c("parse","Failed to parse JSDoc comment",u))}}import{isErr as Cg}from"@zipbul/result";function Wn(n){let{program:u,sourceText:i,comments:g}=n,t=Gn(i);function m(A,z){return{start:rn(t,A),end:rn(t,z)}}function w(A){let z=null;for(let J of g){if(J.type!=="Block")continue;if(J.end>A)continue;if(!J.value.startsWith("*"))continue;if(!z||J.end>z.end)z={value:`/*${J.value}*/`,end:J.end}}if(!z)return;for(let J of u.body){let W=J.start??0;if(W===A)continue;if(W>z.end&&W<A)return}return z.value}function O(A){if(!A)return;let z=A.typeAnnotation??A;return i.slice(z.start,z.end)}function r(A){if(!A||A.length===0)return[];return A.map((z)=>{let J=z.expression;if(!J)return{name:"unknown"};if(J.type==="CallExpression"){let W=J.callee?.name??J.callee?.property?.name??"unknown",Y=(J.arguments??[]).map((I)=>i.slice(I.start,I.end));return{name:W,arguments:Y.length>0?Y:void 0}}if(J.type==="Identifier")return{name:J.name??"unknown"};return{name:i.slice(J.start,J.end)}})}function S(A){let z=A.type==="TSParameterProperty"?A.parameter:A;if(z?.type==="RestElement"){let E=`...${z.argument?.name??"unknown"}`,q=z.typeAnnotation,Q=q?O(q):void 0,D={name:E,isOptional:!1};if(Q)D.type=Q;return D}if(z?.type==="AssignmentPattern"){let{left:b,right:E}=z,q=b?.name??"unknown",Q=b?.typeAnnotation,D=Q?O(Q):void 0,Z=i.slice(E.start,E.end),U=r(b?.decorators??[]),R={name:q,isOptional:!0,defaultValue:Z};if(D)R.type=D;if(U.length>0)R.decorators=U;return R}let J=z?.name??z?.pattern?.name??"unknown",W=!!z?.optional,Y=z?.typeAnnotation,I=Y?O(Y):void 0,B=r(z?.decorators??[]),s={name:J,isOptional:W};if(I)s.type=I;if(B.length>0)s.decorators=B;return s}function _(A,z){let J=[];if(z?.async)J.push("async");if(A.static)J.push("static");if(A.abstract)J.push("abstract");if(A.readonly)J.push("readonly");if(A.override)J.push("override");if(A.declare)J.push("declare");if(A.const)J.push("const");let W=A.accessibility;if(W==="private")J.push("private");else if(W==="protected")J.push("protected");else if(W==="public")J.push("public");return J}function N(A){let z=[];if(A.superClass){let W=i.slice(A.superClass.start,A.superClass.end);z.push({kind:"extends",name:W})}let J=A.implements??[];for(let W of J){let Y=W.expression??W,I=i.slice(Y.start,Y.end);z.push({kind:"implements",name:I})}return z}function M(A){let z=[];for(let J of A.extends??[]){let W=J.expression??J,Y=i.slice(W.start,W.end);z.push({kind:"extends",name:Y})}return z}function f(A){let z=[];for(let J of A)if(J.type==="MethodDefinition"){let W=J.key?.name??"unknown",Y=J.value,I=J.kind??"method",B=I==="constructor"?"constructor":I==="get"?"getter":I==="set"?"setter":"method",s=_(J,Y),b=(Y?.params??[]).map(S),E=O(Y?.returnType),q={kind:"method",name:W,span:m(J.start,J.end),isExported:!1,methodKind:B,modifiers:s,parameters:b.length>0?b:void 0,returnType:E};z.push(q)}else if(J.type==="PropertyDefinition"){let W=J.key?.name??"unknown",Y=_(J),I={kind:"property",name:W,span:m(J.start,J.end),isExported:!1,modifiers:Y};z.push(I)}return z}function H(A){let z=[];for(let J of A)if(J.type==="TSMethodSignature"){let W=J.key?.name??"unknown",Y=(J.params??[]).map(S),I=O(J.returnType);z.push({kind:"method",name:W,span:m(J.start,J.end),isExported:!1,modifiers:[],methodKind:"method",parameters:Y.length>0?Y:void 0,returnType:I})}else if(J.type==="TSPropertySignature"){let W=J.key?.name??"unknown",Y=O(J.typeAnnotation),I={kind:"property",name:W,span:m(J.start,J.end),isExported:!1,modifiers:J.readonly?["readonly"]:[],returnType:Y};z.push(I)}return z}function K(A,z){let J=A.type??"";if(J==="FunctionDeclaration"){let W=A.id?.name??"default",Y=(A.params??[]).map(S),I=O(A.returnType),B=_(A,A),s=r(A.decorators??[]),b=A.typeParameters?.params?.map((q)=>q.name?.name).filter(Boolean)||void 0,E={kind:"function",name:W,span:m(A.start,A.end),isExported:z,modifiers:B,parameters:Y.length>0?Y:void 0,returnType:I,decorators:s.length>0?s:void 0};if(b&&b.length>0)E.typeParameters=b;return E}if(J==="ClassDeclaration"||J==="ClassExpression"){let W=A.id?.name??"default",Y=N(A),I=f(A.body?.body??[]),B=r(A.decorators??[]),s=_(A,A),b=A.typeParameters?.params?.map((q)=>q.name?.name).filter(Boolean)||void 0,E={kind:"class",name:W,span:m(A.start,A.end),isExported:z,modifiers:s,heritage:Y.length>0?Y:void 0,members:I.length>0?I:void 0,decorators:B.length>0?B:void 0};if(b&&b.length>0)E.typeParameters=b;return E}if(J==="VariableDeclaration"){let W=[];for(let Y of A.declarations??[]){let{id:I,init:B}=Y;if(I?.type==="ObjectPattern"){for(let D of I.properties??[]){let Z=D.value?.name??D.key?.name??"unknown";W.push({kind:"variable",name:Z,span:m(D.start??Y.start,D.end??Y.end),isExported:z,modifiers:[]})}continue}if(I?.type==="ArrayPattern"){for(let D of I.elements??[]){if(!D||D.type!=="Identifier")continue;let Z=D.name??"unknown";W.push({kind:"variable",name:Z,span:m(D.start??Y.start,D.end??Y.end),isExported:z,modifiers:[]})}continue}let s=I?.name??"unknown",b="variable",E,q;if(B?.type==="FunctionExpression"||B?.type==="ArrowFunctionExpression")b="function",E=(B.params??[]).map(S),q=O(B.returnType);let Q=[];W.push({kind:b,name:s,span:m(Y.start,Y.end),isExported:z,modifiers:Q,parameters:E,returnType:q})}if(W.length===0)return null;if(W.length===1)return W[0];return W}if(J==="TSTypeAliasDeclaration")return{kind:"type",name:A.id?.name??"unknown",span:m(A.start,A.end),isExported:z,modifiers:[]};if(J==="TSInterfaceDeclaration"){let W=A.id?.name??"unknown",Y=M(A),I=H(A.body?.body??[]),B=A.typeParameters?.params?.map((b)=>b.name?.name).filter(Boolean)||void 0,s={kind:"interface",name:W,span:m(A.start,A.end),isExported:z,modifiers:[],heritage:Y.length>0?Y:void 0,members:I.length>0?I:void 0};if(B&&B.length>0)s.typeParameters=B;return s}if(J==="TSEnumDeclaration"){let W=A.id?.name??"unknown",Y=_(A),B=(A.body?.members??[]).map((s)=>({kind:"property",name:s.id?.name??s.id?.value??"unknown",span:m(s.start,s.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:W,span:m(A.start,A.end),isExported:z,modifiers:Y,members:B.length>0?B:void 0}}return null}let X=[];for(let A of u.body){let z=null,J=A,W=typeof J.type==="string"?J.type:"";if(W==="ExportNamedDeclaration"){let I=A;if(I.declaration){if(z=K(I.declaration,!0),z&&!Array.isArray(z))z.span=m(I.start,I.end);else if(Array.isArray(z))for(let B of z)B.span=m(I.start,I.end)}}else if(W==="ExportDefaultDeclaration"){let I=A,B=I.declaration;if(B){if(z=K(B,!0),z&&!Array.isArray(z))z.name=B.id?.name??"default",z.isExported=!0,z.span=m(I.start,I.end)}}else z=K(A,!1);let Y=Array.isArray(z)?z:z?[z]:[];for(let I of Y){let B=A.start??0,s=w(B);if(s){let b=En(s);if(!Cg(b))I.jsDoc=b}X.push(I)}}return X}function Tg(n){if(n.kind==="function"||n.kind==="method"){let u=n.parameters?.length??0,i=n.modifiers.includes("async")?1:0;return`params:${u}|async:${i}`}return null}function Lg(n){let u={};if(n.jsDoc)u.jsDoc=n.jsDoc;if(n.kind==="function"||n.kind==="method"){if(n.parameters!==void 0)u.parameters=n.parameters;if(n.returnType!==void 0)u.returnType=n.returnType}if(n.heritage?.length)u.heritage=n.heritage;if(n.decorators?.length)u.decorators=n.decorators;if(n.typeParameters?.length)u.typeParameters=n.typeParameters;if(n.modifiers?.length)u.modifiers=n.modifiers;if(n.members?.length)u.members=n.members.map((i)=>{let g=i.modifiers.find((t)=>t==="private"||t==="protected"||t==="public");return{name:i.name,kind:i.methodKind??i.kind,type:i.returnType,visibility:g,isStatic:i.modifiers.includes("static")||void 0,isReadonly:i.modifiers.includes("readonly")||void 0}});return Object.keys(u).length>0?JSON.stringify(u):null}function kg(n){let u=[n.kind];if(n.modifiers.length)u.push(`mod:${[...n.modifiers].sort().join(",")}`);if(n.typeParameters?.length)u.push(`tp:${n.typeParameters.length}`);if(n.heritage?.length){let i=[...n.heritage].sort((g,t)=>g.name.localeCompare(t.name)).map((g)=>`${g.kind}:${g.name}`).join(",");u.push(`her:${i}`)}if(n.decorators?.length)u.push(`dec:${[...n.decorators].map((i)=>i.name).sort().join(",")}`);if(n.methodKind)u.push(`mk:${n.methodKind}`);if(n.parameters)u.push(`p:${n.parameters.length}`);if(n.returnType)u.push(`rt:${n.returnType}`);if(n.members?.length){let i=n.members.map((g)=>`${g.kind}:${g.modifiers.join(",")}:${g.parameters?.length??""}:${g.returnType??""}`).sort().join(";");u.push(`mem:${n.members.length}:${mn(i)}`)}return mn(u.join("|"))}function ju(n,u,i,g,t){let m=Tg(n),w=mn(`${u}|${n.kind}|${m??""}`),O=kg(n);return{project:i,filePath:g,kind:n.kind,name:u,startLine:n.span.start.line,startColumn:n.span.start.column,endLine:n.span.end.line,endColumn:n.span.end.column,isExported:n.isExported?1:0,signature:m,fingerprint:w,detailJson:Lg(n),contentHash:t,indexedAt:new Date().toISOString(),structuralFingerprint:O}}function ru(n){let{parsed:u,project:i,filePath:g,contentHash:t,symbolRepo:m}=n,w=Wn(u),O=[];for(let r of w){O.push(ju(r,r.name,i,g,t));for(let S of r.members??[])O.push(ju(S,`${r.name}.${S.name}`,i,g,t))}m.replaceFileSymbols(i,g,t,O)}import{resolve as mu,dirname as yg,extname as Rg}from"path";function Qn(n,u,i){let g=(t)=>{let m=Rg(t);if(m==="")return[t+".ts",t+".d.ts",t+"/index.ts",t+"/index.d.ts",t+".mts",t+"/index.mts",t+".cts",t+"/index.cts"];if(m===".js")return[t.slice(0,-3)+".ts"];if(m===".mjs")return[t.slice(0,-4)+".mts"];if(m===".cjs")return[t.slice(0,-4)+".cts"];return[t]};if(u.startsWith(".")){let t=mu(yg(n),u);return g(t)}if(i)for(let[t,m]of i.paths){if(m.length===0)continue;let w=t.indexOf("*");if(w===-1){if(u===t){let O=[];for(let r of m)O.push(...g(mu(i.baseUrl,r)));return O}}else{let O=t.slice(0,w),r=t.slice(w+1);if(u.startsWith(O)&&(r===""||u.endsWith(r))){let S=u.slice(O.length,r===""?void 0:u.length-r.length),_=[];for(let N of m)_.push(...g(mu(i.baseUrl,N.replace("*",S))));return _}}}return[]}function bu(n,u,i,g=Qn){let t=new Map,m=n.body??[];for(let w of m){if(w.type!=="ImportDeclaration")continue;let O=w.source?.value??"",r=g(u,O,i);if(r.length===0)continue;let S=r[0],_=w.specifiers??[];for(let N of _)switch(N.type){case"ImportSpecifier":t.set(N.local.name,{path:S,importedName:N.imported.name});break;case"ImportDefaultSpecifier":t.set(N.local.name,{path:S,importedName:"default"});break;case"ImportNamespaceSpecifier":t.set(N.local.name,{path:S,importedName:"*"});break}}return t}var Fg=new Set(["loc","start","end","scope"]);function Hn(n,u){if(!n||typeof n!=="object")return;if(Array.isArray(n)){for(let g of n)Hn(g,u);return}let i=n;u(i);for(let g of Object.keys(i)){if(Fg.has(g))continue;let t=i[g];if(t&&typeof t==="object")Hn(t,u)}}function qu(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if((u.type==="StringLiteral"||u.type==="Literal")&&typeof u.value==="string")return u.value;return null}function zn(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if(u.type==="Identifier"){let i=u.name;return{root:i,parts:[],full:i}}if(u.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(u.type==="Super")return{root:"super",parts:[],full:"super"};if(u.type==="MemberExpression"){let i=[],g=u;while(g.type==="MemberExpression"){let w=g.property;if(!w||typeof w.name!=="string")return null;i.unshift(w.name),g=g.object}let t;if(g.type==="Identifier")t=g.name;else if(g.type==="ThisExpression")t="this";else if(g.type==="Super")t="super";else return null;let m=[t,...i].join(".");return{root:t,parts:i,full:m}}return null}function Gu(n,u,i,g=Qn){let t=[],m=n.body??[];for(let w of m){if(w.type==="ImportDeclaration"){let O=w.source?.value??"",r=g(u,O,i);if(r.length===0)continue;let S=r[0],_=w.importKind==="type",N=w.specifiers??[];if(N.length===0){let M={};if(_)M.isType=!0;t.push({type:_?"type-references":"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:S,dstSymbolName:null,...Object.keys(M).length>0?{metaJson:JSON.stringify(M)}:{}})}else for(let M of N){let f=M.type,H=_||M.importKind==="type",K={};if(H)K.isType=!0;let X,A;if(f==="ImportDefaultSpecifier")X="default",A=M.local.name;else if(f==="ImportNamespaceSpecifier")X="*",A=M.local.name,K.importKind="namespace";else X=M.imported.name,A=M.local.name;t.push({type:H?"type-references":"imports",srcFilePath:u,srcSymbolName:A,dstFilePath:S,dstSymbolName:X,...Object.keys(K).length>0?{metaJson:JSON.stringify(K)}:{}})}continue}if(w.type==="ExportAllDeclaration"&&w.source){let O=w.source?.value??"",r=g(u,O,i);if(r.length===0)continue;let S=r[0],_=w.exportKind==="type",N={isReExport:!0};if(_)N.isType=!0;t.push({type:_?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:S,dstSymbolName:null,metaJson:JSON.stringify(N)});continue}if(w.type==="ExportNamedDeclaration"&&w.source){let O=w.source?.value??"",r=g(u,O,i);if(r.length===0)continue;let S=r[0],_=w.exportKind==="type",f={isReExport:!0,specifiers:(w.specifiers??[]).map((H)=>({local:H.local.name,exported:H.exported.name}))};if(_)f.isType=!0;t.push({type:_?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:S,dstSymbolName:null,metaJson:JSON.stringify(f)})}}return Hn(n,(w)=>{if(w.type!=="ImportExpression")return;let O=qu(w.source);if(!O)return;let r=g(u,O,i);if(r.length===0)return;let S=r[0];t.push({type:"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:S,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),t}function Eu(n,u,i){let g=[],t=[],m=[];function w(){if(t.length>0)return t[t.length-1]??null;return null}function O(S){if(!S)return null;let _=i.get(S.root);if(S.parts.length===0){if(_)return{dstFilePath:_.path,dstSymbolName:_.importedName,resolution:"import"};return{dstFilePath:u,dstSymbolName:S.root,resolution:"local"}}else{if(_&&_.importedName==="*"){let N=S.parts[S.parts.length-1];return{dstFilePath:_.path,dstSymbolName:N,resolution:"namespace"}}return{dstFilePath:u,dstSymbolName:S.full,resolution:"local-member"}}}function r(S){if(!S||typeof S!=="object")return;if(Array.isArray(S)){for(let M of S)r(M);return}let _=S,N=typeof _.type==="string"?_.type:"";if(N==="ClassDeclaration"||N==="ClassExpression"){let M=_,f=M.id?.name??"AnonymousClass";m.push(f),r(M.body),m.pop();return}if(N==="FunctionDeclaration"){let M=_,f=M.id?.name??"anonymous";t.push(f),r(M.body),t.pop();return}if(N==="VariableDeclarator"&&_.init&&(_.init?.type==="FunctionExpression"||_.init?.type==="ArrowFunctionExpression")){let M=_,f=M.id?.name??"anonymous";t.push(f),r(M.init?.body??M.init),t.pop();return}if(N==="MethodDefinition"&&_.value){let M=_,f=m[m.length-1]??"",H=M.key?.name??"anonymous",K=f?`${f}.${H}`:H;t.push(K),r(M.value?.body),t.pop();return}if(N==="FunctionExpression"||N==="ArrowFunctionExpression"){let M=w(),f=M?`${M}.<anonymous>`:"<anonymous>";t.push(f),r(_.body),t.pop();return}if(N==="CallExpression"){let M=_,f=zn(M.callee),H=O(f);if(H){let K=w(),X={};if(K===null)X.scope="module";g.push({type:"calls",srcFilePath:u,srcSymbolName:K,dstFilePath:H.dstFilePath,dstSymbolName:H.dstSymbolName,...Object.keys(X).length>0?{metaJson:JSON.stringify(X)}:{}})}r(M.callee);for(let K of M.arguments??[])r(K);return}if(N==="NewExpression"){let M=_,f=zn(M.callee),H=O(f);if(H){let K=w(),X={isNew:!0};if(K===null)X.scope="module";g.push({type:"calls",srcFilePath:u,srcSymbolName:K,dstFilePath:H.dstFilePath,dstSymbolName:H.dstSymbolName,metaJson:JSON.stringify(X)})}for(let K of M.arguments??[])r(K);return}for(let M of Object.keys(_)){if(M==="loc"||M==="start"||M==="end"||M==="scope")continue;let f=_[M];if(f&&typeof f==="object")r(f)}}return r(n),g}function pu(n,u,i){let g=[];return Hn(n,(t)=>{if(t.type==="TSInterfaceDeclaration"){let O=t.id?.name??"AnonymousInterface",r=t.extends??[];for(let S of r){let _=S.expression??S,N=zn(_);if(!N)continue;let M=Ou(N,u,i);g.push({type:"extends",srcFilePath:u,srcSymbolName:O,...M})}return}if(t.type!=="ClassDeclaration"&&t.type!=="ClassExpression")return;let m=t.id?.name??"AnonymousClass";if(t.superClass){let O=zn(t.superClass);if(O){let r=Ou(O,u,i);g.push({type:"extends",srcFilePath:u,srcSymbolName:m,...r})}}let w=t.implements??[];for(let O of w){let r=O.expression??O,S=zn(r);if(!S)continue;let _=Ou(S,u,i);g.push({type:"implements",srcFilePath:u,srcSymbolName:m,..._})}}),g}function Ou(n,u,i){let g=i.get(n.root);if(g){if(g.importedName==="*"){let t=n.parts[n.parts.length-1]??n.root;return{dstFilePath:g.path,dstSymbolName:t,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:g.path,dstSymbolName:n.parts.length>0?n.full:g.importedName}}return{dstFilePath:u,dstSymbolName:n.full,metaJson:JSON.stringify({isLocal:!0})}}function pn(n,u,i,g=Qn){let t=bu(n,u,i,g),m=Gu(n,u,i,g),w=Eu(n,u,t),O=pu(n,u,t);return[...m,...w,...O]}function wu(n){let{ast:u,project:i,filePath:g,relationRepo:t,projectRoot:m,tsconfigPaths:w,knownFiles:O,boundaries:r}=n,S=Vn(m,g),N=pn(u,S,w,O?(f,H,K)=>{let X=Qn(f,H,K);for(let A of X){let z=qn(m,A);if(r){let J=P(z,r);if(O.has(`${J}::${z}`))return[A]}else if(O.has(`${i}::${z}`))return[A]}return[]}:void 0),M=[];for(let f of N){let H=qn(m,f.dstFilePath);if(H.startsWith(".."))continue;let K=qn(m,f.srcFilePath),X=r?P(H,r):i;M.push({project:i,type:f.type,srcFilePath:K,srcSymbolName:f.srcSymbolName??null,dstProject:X,dstFilePath:H,dstSymbolName:f.dstSymbolName??null,metaJson:f.metaJson??null})}return t.replaceFileRelations(i,g,M),M.length}import{isErr as sg}from"@zipbul/result";var vu=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function jg(n){let u=Wn(n),i=[];for(let g of u){i.push({name:g.name,startLine:g.span.start.line});for(let t of g.members??[])i.push({name:`${g.name}.${t.name}`,startLine:t.span.start.line})}return i.sort((g,t)=>g.startLine-t.startLine),i}function _u(n,u,i){let g=0,t=n.length-1;while(g<=t){let m=g+t>>1;if(n[m].startLine<=u)g=m+1;else t=m-1}if(g<n.length){let m=n[g];if(m.startLine-u<=i)return m.name}return null}function vn(n,u,i){let g=rn(n,u),t=rn(n,i);return{start:g,end:t}}function Pu(n){let{comments:u,sourceText:i}=n;if(!u.length)return[];let g=Gn(i),t=jg(n),m=[],w=[...u].sort((r,S)=>r.start-S.start),O=null;for(let r of w)if(r.type==="Block"&&r.value.startsWith("*")){O=null;let S=`/*${r.value}*/`,_=En(S);if(sg(_))continue;let N=_;if(!N.tags?.length)continue;let M=rn(g,r.end),f=_u(t,M.line,3),H=i.slice(r.start,r.end);for(let K of N.tags){let X=[K.name,K.description].filter(Boolean).join(" "),A=`@${K.tag}`,z=H.indexOf(A),J;if(z>=0){let W=r.start+z,Y=i.indexOf(`
4
- `,W),I=Y>=0?Math.min(Y,r.end):r.end;J=vn(g,W,I)}else J=vn(g,r.start,r.end);m.push({tag:K.tag,value:X,source:"jsdoc",span:J,symbolName:f})}}else if(r.type==="Block"){O=null;let S=r.value.split(`
5
- `),_=0;for(let N of S){let M=N.replace(/^\s*\*?\s?/,""),f=vu.exec(M);if(f){let H=f[1],K=f[2]?.trim()??"",X=`@${H}`,A=N.indexOf(X),z=r.start+2+_+(A>=0?A:0),J=r.start+2+_+N.length,W=vn(g,z,J),Y=rn(g,r.end),I=_u(t,Y.line,3);m.push({tag:H,value:K,source:"block",span:W,symbolName:I})}_+=N.length+1}}else{let S=r.value,_=vu.exec(S),N=rn(g,r.start),M=rn(g,r.end);if(_){let f=_[1],H=_[2]?.trim()??"",K=`@${f}`,X=S.indexOf(K),A=r.start+2+(X>=0?X:0),z=vn(g,A,r.end),J=_u(t,M.line,3),W={tag:f,value:H,source:"line",span:z,symbolName:J};m.push(W),O={annotation:W,endLine:M.line}}else if(O&&N.line===O.endLine+1){let f=S.trim();if(f)O.annotation.value+=" "+f,O.annotation.span.end=rn(g,r.end),O.endLine=M.line}else O=null}return m}function Nu(n){let{parsed:u,project:i,filePath:g,annotationRepo:t}=n,m=Pu(u);if(t.deleteFileAnnotations(i,g),!m.length)return 0;let w=new Date().toISOString(),O=m.map((r)=>({project:i,filePath:g,tag:r.tag,value:r.value,source:r.source,symbolName:r.symbolName,startLine:r.span.start.line,startColumn:r.span.start.column,endLine:r.span.end.line,endColumn:r.span.end.column,indexedAt:w}));return t.insertBatch(i,g,O),m.length}function au(n,u){let i=[],g=[],t=[];for(let[_,N]of u)if(!n.has(_))i.push({name:N.name,filePath:N.filePath,kind:N.kind,fingerprint:N.fingerprint});for(let[_,N]of n)if(!u.has(_))g.push({name:N.name,filePath:N.filePath,kind:N.kind,fingerprint:N.fingerprint});if(!i.length||!g.length)return{renamed:t,added:i,removed:g};let m=new Map,w=new Map;for(let _ of i){let N=m.get(_.filePath)??[];N.push(_),m.set(_.filePath,N)}for(let _ of g){let N=w.get(_.filePath)??[];N.push(_),w.set(_.filePath,N)}let O=new Set,r=new Set;for(let[_,N]of m){let M=w.get(_);if(!M)continue;for(let f of new Set(N.map((H)=>H.kind))){let H=N.filter((J)=>J.kind===f&&!O.has(J)),K=M.filter((J)=>J.kind===f&&!r.has(J));if(!H.length||!K.length)continue;let X=(J,W)=>{return W.get(`${J.filePath}::${J.name}`)?.structuralFingerprint??null},A=(J,W)=>{return W.get(`${J.filePath}::${J.name}`)?.startLine??0},z=new Map;for(let J of K){let W=X(J,n);if(!W)continue;let Y=z.get(W)??[];Y.push(J),z.set(W,Y)}for(let J of H){if(O.has(J))continue;let W=X(J,u);if(!W)continue;let Y=z.get(W);if(!Y)continue;let I=Y.filter((s)=>!r.has(s));if(!I.length)continue;let B=I[0];if(I.length>1){let s=A(J,u),b=Math.abs(A(B,n)-s);for(let E=1;E<I.length;E++){let q=Math.abs(A(I[E],n)-s);if(q<b)b=q,B=I[E]}}t.push({oldName:B.name,newName:J.name,filePath:_,kind:f}),O.add(J),r.add(B)}}}let S=t.filter((_)=>!_.oldName.includes("."));for(let _ of S){let N=`${_.oldName}.`,M=`${_.newName}.`,f=g.filter((K)=>K.filePath===_.filePath&&K.name.startsWith(N)&&!r.has(K)),H=i.filter((K)=>K.filePath===_.filePath&&K.name.startsWith(M)&&!O.has(K));for(let K of f){let X=K.name.slice(N.length),A=H.find((z)=>z.name.slice(M.length)===X);if(A)t.push({oldName:K.name,newName:A.name,filePath:_.filePath,kind:K.kind}),O.add(A),r.add(K)}}return{renamed:t,added:i.filter((_)=>!O.has(_)),removed:g.filter((_)=>!r.has(_))}}var bg=100,xu=50;class Su{opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;lastPruneAt=0;constructor(n){this.opts=n,this.logger=n.logger??console,this.tsconfigPathsRaw=Xn(n.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(n){return this.startIndex(n,!1)}onIndexed(n){return this.callbacks.add(n),()=>this.callbacks.delete(n)}handleWatcherEvent(n){if(n.filePath.endsWith("tsconfig.json")){bn(this.opts.projectRoot),this.tsconfigPathsRaw=Xn(this.opts.projectRoot),this.fullIndex().catch((u)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",u)});return}if(n.filePath.endsWith("package.json")){let u=this.opts.discoverProjectsFn??jn;this.boundariesRefresh=u(this.opts.projectRoot).then((i)=>{this.opts.boundaries=i})}if(this.pendingEvents.push(n),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},bg)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(n,u){if(this.indexingLock){if(u)return this.pendingFullIndex=!0,new Promise((g,t)=>{this.pendingFullIndexWaiters.push({resolve:g,reject:t})});return this.currentIndexing}this.indexingLock=!0;let i=this.doIndex(n,u).then((g)=>{return this.fireCallbacks(g),g}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let g=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((t)=>{for(let m of g)m.resolve(t)}).catch((t)=>{for(let m of g)m.reject(t)})}else if(this.pendingEvents.length>0){let g=this.pendingEvents.splice(0);this.startIndex(g,!1).catch((t)=>this.logger.error("[IndexCoordinator] incremental drain error",t))}});return this.currentIndexing=i,i}async doIndex(n,u){let i=Date.now(),{fileRepo:g,symbolRepo:t,relationRepo:m,dbConnection:w}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let O,r;if(n!==void 0)O=n.filter((Q)=>Q.eventType==="create"||Q.eventType==="change").map((Q)=>({filePath:Q.filePath,contentHash:"",mtimeMs:0,size:0})),r=n.filter((Q)=>Q.eventType==="delete").map((Q)=>Q.filePath);else{let Q=new Map;for(let Z of this.opts.boundaries)for(let[U,R]of g.getFilesMap(Z.project))Q.set(U,R);let D=await su({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>Q}});O=D.changed,r=D.deleted}let S=await this.tsconfigPathsRaw??void 0,_=new Map;for(let Q of r){let D=P(Q,this.opts.boundaries),Z=t.getFileSymbols(D,Q);_.set(Q,Z)}let N=crypto.randomUUID(),M=new Map,f=new Map,H=(Q)=>({name:Q.name,filePath:Q.filePath,kind:Q.kind,fingerprint:Q.fingerprint,structuralFingerprint:Q.structuralFingerprint??null,startLine:Q.startLine});if(u)for(let Q of this.opts.boundaries)for(let D of g.getAllFiles(Q.project))for(let Z of t.getFileSymbols(Q.project,D.filePath))M.set(`${Z.filePath}::${Z.name}`,H(Z));else{for(let Q of O){let D=P(Q.filePath,this.opts.boundaries);for(let Z of t.getFileSymbols(D,Q.filePath))M.set(`${Z.filePath}::${Z.name}`,H(Z))}for(let[,Q]of _)for(let D of Q)M.set(`${D.filePath}::${D.name}`,H(D))}let{annotationRepo:K,changelogRepo:X}=this.opts,A=()=>{for(let Q of r){let D=P(Q,this.opts.boundaries);if(t.deleteFileSymbols(D,Q),m.deleteFileRelations(D,Q),K)K.deleteFileAnnotations(D,Q);g.deleteFile(D,Q)}},z=0,J=async()=>{let{projectRoot:Q,boundaries:D}=this.opts,{parseCache:Z}=this.opts,U=0,R=0,L=0,gn=[],k=[];for(let F of O)try{let C=Vn(Q,F.filePath),l=Bun.file(C),o=await l.text(),On=F.contentHash||mn(o),Sn=P(F.filePath,D);g.upsertFile({project:Sn,filePath:F.filePath,mtimeMs:l.lastModified,size:l.size,contentHash:On,updatedAt:new Date().toISOString(),lineCount:o.split(`
6
- `).length});let In=(this.opts.parseSourceFn??Bn)(C,o);if(hu(In))throw In.data;let ci=In;k.push({filePath:F.filePath,text:o,contentHash:On,parsed:ci,project:Sn})}catch(C){this.logger.error(`[IndexCoordinator] Failed to prepare ${F.filePath}:`,C),gn.push(F.filePath)}let G=new Set;for(let F of D)for(let[C]of g.getFilesMap(F.project))G.add(`${F.project}::${C}`);return w.transaction(()=>{for(let F of k){if(ru({parsed:F.parsed,project:F.project,filePath:F.filePath,contentHash:F.contentHash,symbolRepo:t}),R+=wu({ast:F.parsed.program,project:F.project,filePath:F.filePath,relationRepo:m,projectRoot:Q,tsconfigPaths:S,knownFiles:G,boundaries:D}),K)L+=Nu({parsed:F.parsed,project:F.project,filePath:F.filePath,annotationRepo:K});Z.set(F.filePath,F.parsed),U+=t.getFileSymbols(F.project,F.filePath).length}}),{symbols:U,relations:R,annotations:L,failedFiles:gn}},W=0,Y=0,I=[];if(u){let{projectRoot:Q,boundaries:D}=this.opts,{parseCache:Z}=this.opts,U=[];for(let L=0;L<O.length;L+=xu){let gn=O.slice(L,L+xu),k=await Promise.allSettled(gn.map(async(G)=>{let F=Vn(Q,G.filePath),C=Bun.file(F),l=await C.text(),o=G.contentHash||mn(l);return{filePath:G.filePath,text:l,contentHash:o,mtimeMs:C.lastModified,size:C.size}}));for(let G of k)if(G.status==="fulfilled")U.push(G.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",G.reason)}let R=[];w.transaction(()=>{for(let k of U){let G=P(k.filePath,D);g.deleteFile(G,k.filePath)}for(let k of r){let G=P(k,D);if(t.deleteFileSymbols(G,k),m.deleteFileRelations(G,k),K)K.deleteFileAnnotations(G,k);g.deleteFile(G,k)}for(let k of U){let G=P(k.filePath,D);g.upsertFile({project:G,filePath:k.filePath,mtimeMs:k.mtimeMs,size:k.size,contentHash:k.contentHash,updatedAt:new Date().toISOString(),lineCount:k.text.split(`
7
- `).length})}let L=new Set;for(let k of D)for(let[G]of g.getFilesMap(k.project))L.add(`${k.project}::${G}`);let gn=this.opts.parseSourceFn??Bn;for(let k of U){let G=P(k.filePath,D),F=gn(Vn(Q,k.filePath),k.text);if(hu(F))throw F.data;let C=F;if(R.push({filePath:k.filePath,parsed:C}),ru({parsed:C,project:G,filePath:k.filePath,contentHash:k.contentHash,symbolRepo:t}),K)z+=Nu({parsed:C,project:G,filePath:k.filePath,annotationRepo:K});Y+=wu({ast:C.program,project:G,filePath:k.filePath,relationRepo:m,projectRoot:Q,tsconfigPaths:S,knownFiles:L,boundaries:D}),W+=t.getFileSymbols(G,k.filePath).length}});for(let L of R)Z.set(L.filePath,L.parsed)}else{A();let Q=await J();W=Q.symbols,Y=Q.relations,z=Q.annotations,I=Q.failedFiles}for(let Q of O){let D=P(Q.filePath,this.opts.boundaries);for(let Z of t.getFileSymbols(D,Q.filePath))f.set(`${Z.filePath}::${Z.name}`,H(Z))}let B={added:[],modified:[],removed:[]};for(let[Q,D]of f){let Z=M.get(Q);if(!Z)B.added.push({name:D.name,filePath:D.filePath,kind:D.kind});else if(Z.fingerprint!==D.fingerprint)B.modified.push({name:D.name,filePath:D.filePath,kind:D.kind})}for(let[Q,D]of M)if(!f.has(Q))B.removed.push({name:D.name,filePath:D.filePath,kind:D.kind});let s=au(M,f),b=new Set(s.renamed.map((Q)=>`${Q.filePath}::${Q.oldName}`)),E=new Set(s.renamed.map((Q)=>`${Q.filePath}::${Q.newName}`));B.added=B.added.filter((Q)=>!E.has(`${Q.filePath}::${Q.name}`)),B.removed=B.removed.filter((Q)=>!b.has(`${Q.filePath}::${Q.name}`));let q=[];if(!u){for(let[Q,D]of _)for(let Z of D){if(!Z.fingerprint)continue;let U=P(Q,this.opts.boundaries),R=t.getByFingerprint(U,Z.fingerprint);if(R.length===1){let L=R[0];m.retargetRelations({dstProject:U,oldFile:Q,oldSymbol:Z.name,newFile:L.filePath,newSymbol:L.name}),q.push({name:L.name,filePath:L.filePath,kind:L.kind,oldFilePath:Q})}}for(let Q of s.removed){let Z=M.get(`${Q.filePath}::${Q.name}`)?.fingerprint;if(!Z)continue;let U=P(Q.filePath,this.opts.boundaries),R=t.getByFingerprint(U,Z);if(R.length===1){let L=R[0];if(L.filePath!==Q.filePath||L.name!==Q.name)m.retargetRelations({dstProject:U,oldFile:Q.filePath,oldSymbol:Q.name,newFile:L.filePath,newSymbol:L.name}),q.push({name:L.name,filePath:L.filePath,kind:L.kind,oldFilePath:Q.filePath})}}}if(q.length){let Q=new Set(q.map((Z)=>`${Z.filePath}::${Z.name}`)),D=new Set(q.map((Z)=>`${Z.oldFilePath}::${Z.name}`));B.added=B.added.filter((Z)=>!Q.has(`${Z.filePath}::${Z.name}`)),B.removed=B.removed.filter((Z)=>!D.has(`${Z.filePath}::${Z.name}`))}if(X){let Q=new Date().toISOString(),D=u?1:0,Z=[];for(let U of B.added){let R=`${U.filePath}::${U.name}`,L=f.get(R),gn=P(U.filePath,this.opts.boundaries);Z.push({project:gn,changeType:"added",symbolName:U.name,symbolKind:U.kind,filePath:U.filePath,oldName:null,oldFilePath:null,fingerprint:L?.fingerprint??null,changedAt:Q,isFullIndex:D,indexRunId:N})}for(let U of B.modified){let R=f.get(`${U.filePath}::${U.name}`),L=P(U.filePath,this.opts.boundaries);Z.push({project:L,changeType:"modified",symbolName:U.name,symbolKind:U.kind,filePath:U.filePath,oldName:null,oldFilePath:null,fingerprint:R?.fingerprint??null,changedAt:Q,isFullIndex:D,indexRunId:N})}for(let U of B.removed){let R=`${U.filePath}::${U.name}`,L=M.get(R),gn=P(U.filePath,this.opts.boundaries);Z.push({project:gn,changeType:"removed",symbolName:U.name,symbolKind:U.kind,filePath:U.filePath,oldName:null,oldFilePath:null,fingerprint:L?.fingerprint??null,changedAt:Q,isFullIndex:D,indexRunId:N})}for(let U of s.renamed){let R=f.get(`${U.filePath}::${U.newName}`),L=P(U.filePath,this.opts.boundaries);Z.push({project:L,changeType:"renamed",symbolName:U.newName,symbolKind:U.kind,filePath:U.filePath,oldName:U.oldName,oldFilePath:null,fingerprint:R?.fingerprint??null,changedAt:Q,isFullIndex:D,indexRunId:N})}for(let U of q){let R=f.get(`${U.filePath}::${U.name}`),L=P(U.filePath,this.opts.boundaries);Z.push({project:L,changeType:"moved",symbolName:U.name,symbolKind:U.kind,filePath:U.filePath,oldName:null,oldFilePath:U.oldFilePath,fingerprint:R?.fingerprint??null,changedAt:Q,isFullIndex:D,indexRunId:N})}if(Z.length)try{w.transaction(()=>{X.insertBatch(Z)})}catch(U){this.logger.error("[IndexCoordinator] changelog insert failed:",U)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let U=new Date(Date.now()-2592000000).toISOString();try{for(let R of this.opts.boundaries)X.pruneOlderThan(R.project,U)}catch(R){this.logger.error("[IndexCoordinator] changelog pruning failed:",R)}}}return{indexedFiles:O.length,removedFiles:r.length,totalSymbols:W,totalRelations:Y,totalAnnotations:z,durationMs:Date.now()-i,changedFiles:O.map((Q)=>Q.filePath),deletedFiles:[...r],failedFiles:I,changedSymbols:B}}fireCallbacks(n){for(let u of this.callbacks)try{u(n)}catch(i){this.logger.error("[IndexCoordinator] onIndexed callback threw:",i)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let n=this.pendingEvents.splice(0);this.startIndex(n,!1).catch((u)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",u))}}}function qg(n){try{return process.kill(n,0),!0}catch(u){if(typeof u==="object"&&u&&"code"in u)return u.code!=="ESRCH";return!0}}function Gg(n){let u=new Date(n).getTime();return Number.isNaN(u)?0:u}function du(n,u,i={}){let g=i.now??Date.now,t=i.isAlive??qg,m=i.staleAfterSeconds??60,w=i.instanceId;return n.immediateTransaction(()=>{let O=n.selectOwner();if(!O)return n.insertOwner(u,w),"owner";let r=Math.floor((g()-Gg(O.heartbeat_at))/1000),S=t(O.pid);if(S&&w&&O.instance_id&&O.instance_id!==w&&O.pid!==u)return n.replaceOwner(u,w),"owner";if(S&&r<m)return"reader";return n.replaceOwner(u,w),"owner"})}function lu(n,u){n.deleteOwner(u)}function ou(n,u){n.touchOwner(u)}class Cn{#n;#u=new Map;constructor(n){this.#n=Math.max(1,n)}get size(){return this.#u.size}has(n){return this.#u.has(n)}get(n){if(!this.#u.has(n))return;let u=this.#u.get(n);return this.#u.delete(n),this.#u.set(n,u),u}set(n,u){if(this.#u.has(n))this.#u.delete(n);if(this.#u.set(n,u),this.#u.size>this.#n){let i=this.#u.keys().next().value;if(i!==void 0)this.#u.delete(i)}}delete(n){return this.#u.delete(n)}clear(){this.#u.clear()}}class $u{lru;constructor(n=500){this.lru=new Cn(n)}get(n){return this.lru.get(n)}set(n,u){this.lru.set(n,u)}invalidate(n){this.lru.delete(n)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function Ju(n){let{symbolRepo:u,project:i,query:g}=n,t=g.project??i,m=g.limit??100,w={kind:g.kind,filePath:g.filePath,isExported:g.isExported,project:t,limit:m,resolvedType:g.resolvedType};if(g.text)if(g.exact)w.exactName=g.text;else{let r=Kn(g.text);if(r)w.ftsQuery=r}if(g.decorator)w.decorator=g.decorator;if(g.regex)w.regex=g.regex;return u.searchByQuery(w).map((r)=>({id:r.id,filePath:r.filePath,kind:r.kind,name:r.name,span:{start:{line:r.startLine,column:r.startColumn},end:{line:r.endLine,column:r.endColumn}},isExported:r.isExported===1,signature:r.signature,fingerprint:r.fingerprint,detail:r.detailJson?(()=>{try{return JSON.parse(r.detailJson)}catch{return{}}})():{}}))}function Au(n){let{relationRepo:u,project:i,query:g}=n,t=g.project??i,m=g.limit??500;return u.searchRelations({srcFilePath:g.srcFilePath,srcSymbolName:g.srcSymbolName,dstFilePath:g.dstFilePath,dstSymbolName:g.dstSymbolName,dstProject:g.dstProject,type:g.type,project:t,limit:m}).map((O)=>{let r;if(O.metaJson)try{r=JSON.parse(O.metaJson)}catch{}return{type:O.type,srcFilePath:O.srcFilePath,srcSymbolName:O.srcSymbolName,dstFilePath:O.dstFilePath,dstSymbolName:O.dstSymbolName,dstProject:O.dstProject,metaJson:O.metaJson??void 0,meta:r}})}import{findInFiles as Eg,Lang as pg}from"@ast-grep/napi";async function Mu(n){if(n.filePaths.length===0)return[];let u=[];return await Eg(pg.TypeScript,{paths:n.filePaths,matcher:{rule:{pattern:n.pattern}}},(i,g)=>{if(i)return;for(let t of g){let m=t.range();u.push({filePath:t.getRoot().filename(),startLine:m.start.line+1,endLine:m.end.line+1,matchedText:t.text()})}}),u}import h from"typescript";import{isErr as gt}from"@zipbul/result";import _n from"typescript";import vg from"path";import{err as Qu}from"@zipbul/result";function Pg(n){try{return Zu("fs").readFileSync(n,"utf-8")}catch{return}}function ag(n){try{return Zu("fs").readFileSync(n,"utf-8")}catch{return}}class Pn{#n;#u;#i=!1;__testing__;constructor(n,u){this.#n=n,this.#u=u,this.__testing__={host:u}}static create(n,u={}){let i=u.readConfigFile??Pg,g=u.resolveNonTrackedFile??ag,t=vg.dirname(n),m=i(n);if(m===void 0)return Qu(c("semantic",`tsconfig not found: ${n}`));let w=_n.parseJsonText(n,m),O=w.parseDiagnostics;if(O&&O.length>0){let N=O.map((M)=>_n.flattenDiagnosticMessageText(M.messageText,`
8
- `)).join("; ");return Qu(c("semantic",`tsconfig parse error: ${N}`))}let r=_n.parseJsonSourceFileConfigFileContent(w,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(N)=>i(N)!==void 0||g(N)!==void 0,readFile:(N)=>i(N)??g(N)},t);if(r.errors.length>0){let N=r.errors.filter((M)=>M.category===_n.DiagnosticCategory.Error&&M.code!==18003);if(N.length>0){let M=N.map((f)=>_n.flattenDiagnosticMessageText(f.messageText,`
9
- `)).join("; ");return Qu(c("semantic",`tsconfig compile error: ${M}`))}}let S=new cu(r.fileNames,r.options,t,g),_=_n.createLanguageService(S);return new Pn(_,S)}get isDisposed(){return this.#i}getProgram(){this.#t();let n=this.#n.getProgram();if(!n)throw Error("TscProgram: LanguageService returned null Program");return n}getChecker(){return this.#t(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#t(),this.#n}notifyFileChanged(n,u){if(this.#i)return;this.#u.updateFile(n,u)}removeFile(n){if(this.#i)return;this.#u.removeFile(n)}dispose(){if(this.#i)return;this.#i=!0,this.#n.dispose()}#t(){if(this.#i)throw Error("TscProgram is disposed")}}class cu{#n;#u;#i;#t;#g=new Map;constructor(n,u,i,g){this.#n=[...n],this.#u=u,this.#i=i,this.#t=g}updateFile(n,u){let i=this.#g.get(n);if(i)i.version+=1,i.content=u;else this.#g.set(n,{version:1,content:u})}removeFile(n){this.#g.delete(n),this.#n=this.#n.filter((u)=>u!==n)}getScriptFileNames(){let n=[...this.#g.keys()];return[...this.#n.filter((i)=>!this.#g.has(i)),...n]}getScriptVersion(n){let u=this.#g.get(n);return u?String(u.version):"0"}getScriptSnapshot(n){let u=this.#g.get(n);if(u)return _n.ScriptSnapshot.fromString(u.content);let i=this.#t(n);if(i!==void 0)return _n.ScriptSnapshot.fromString(i);return}getCurrentDirectory(){return this.#i}getCompilationSettings(){return this.#u}getDefaultLibFileName(n){return _n.getDefaultLibFilePath(n)}fileExists(n){if(this.#g.has(n))return!0;return this.#t(n)!==void 0}readFile(n){let u=this.#g.get(n);if(u)return u.content;return this.#t(n)}}import d from"typescript";import hg from"typescript";function Nn(n,u){if(u<0||u>=n.getEnd())return;function i(g){let t=g.getStart(n,!1),m=g.getEnd();if(u<t||u>=m)return;let w;return hg.forEachChild(g,(O)=>{if(!w)w=i(O)}),w??g}return i(n)}function xg(n){return!!(n.flags&d.TypeFlags.Object)&&!!(n.objectFlags&d.ObjectFlags.Reference)}function Tn(n,u,i=0){let g=n.typeToString(u),t=u.flags,m=!!(t&d.TypeFlags.Union),w=!!(t&d.TypeFlags.Intersection),O;if(i<8&&xg(u)){let N=n.getTypeArguments(u);if(N.length>0)O=N}let r=!!(t&d.TypeFlags.TypeParameter)||O!==void 0&&O.length>0,S;if(m&&i<8)S=u.types.map((N)=>Tn(n,N,i+1));else if(w&&i<8)S=u.types.map((N)=>Tn(n,N,i+1));let _;if(O&&O.length>0)_=O.map((N)=>Tn(n,N,i+1));return{text:g,flags:t,isUnion:m,isIntersection:w,isGeneric:r,members:S,typeArguments:_}}function dg(n){return d.isFunctionDeclaration(n)||d.isVariableDeclaration(n)||d.isClassDeclaration(n)||d.isInterfaceDeclaration(n)||d.isTypeAliasDeclaration(n)||d.isEnumDeclaration(n)||d.isMethodDeclaration(n)||d.isPropertyDeclaration(n)||d.isPropertySignature(n)||d.isMethodSignature(n)}class zu{program;constructor(n){this.program=n}collectAt(n,u){let i=this.program.getProgram(),g=this.program.getChecker();if(u<0)return null;let t=i.getSourceFile(n);if(!t)return null;if(u>=t.getEnd())return null;let m=Nn(t,u);if(!m)return null;if(!d.isIdentifier(m))return null;try{let w=g.getTypeAtLocation(m);return Tn(g,w)}catch{return null}}collectFile(n){let u=new Map,i=this.program.getProgram(),g=this.program.getChecker(),t=i.getSourceFile(n);if(!t)return u;function m(w){if(dg(w)&&w.name&&d.isIdentifier(w.name)){let O=w.name;try{let r=g.getTypeAtLocation(O),S=O.getStart(t);u.set(S,Tn(g,r))}catch{}}d.forEachChild(w,m)}return m(t),u}}import An from"typescript";var lg=1000,og=1;function cg(n){let u=n.declarations?.[0],i=u?.getSourceFile(),g=u?An.getNameOfDeclaration(u):void 0;return{name:n.getName(),filePath:i?.fileName??"",position:g?.getStart(i,!1)??u?.getStart(i,!1)??0}}function an(n,u=0){let i=n.declarations?.[0],g=i?.getSourceFile(),t=i?An.getNameOfDeclaration(i):void 0,m=g?.fileName??"",w=t?.getStart(g,!1)??i?.getStart(g,!1)??0,O={name:n.getName(),filePath:m,position:w},r=n;if(r.parent)O.parent=cg(r.parent);if(u<og){let S=n.flags,_=!!(S&An.SymbolFlags.Enum),N=!!(S&(An.SymbolFlags.NamespaceModule|An.SymbolFlags.ValueModule)),M=!!(S&(An.SymbolFlags.Class|An.SymbolFlags.Interface));if(_&&n.exports&&n.exports.size>0){let f=[];n.exports.forEach((H)=>{f.push(an(H,u+1))}),O.members=f}else if(M&&n.members&&n.members.size>0){let f=[];n.members.forEach((H)=>{f.push(an(H,u+1))}),O.members=f}if(N&&n.exports&&n.exports.size>0){let f=[];n.exports.forEach((H)=>{f.push(an(H,u+1))}),O.exports=f}}return O}class fu{#n;#u;#i=new Map;constructor(n,u=lg){this.#n=n,this.#u=new Cn(u)}get(n,u){if(this.#n.isDisposed)return null;let i=`${n}:${u}`,g=this.#u.get(i);if(g!==void 0)return g;let m=this.#n.getProgram().getSourceFile(n);if(!m)return null;let w=Nn(m,u);if(!w||!An.isIdentifier(w))return null;let r=this.#n.getChecker().getSymbolAtLocation(w);if(!r)return null;let S=an(r);this.#u.set(i,S);let _=this.#i.get(n);if(!_)_=new Set,this.#i.set(n,_);return _.add(i),S}invalidate(n){let u=this.#i.get(n);if(u){for(let i of u)this.#u.delete(i);this.#i.delete(n)}}clear(){this.#u.clear(),this.#i.clear()}}import eg from"typescript";class Du{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let i=this.#n.getProgram(),g=i.getSourceFile(n);if(!g)return[];let t=Nn(g,u);if(!t||!eg.isIdentifier(t))return[];let w=this.#n.getLanguageService().findReferences(n,u);if(!w||w.length===0)return[];let O=[];for(let r of w)for(let S of r.references){let _=i.getSourceFile(S.fileName);if(!_)continue;let{line:N,character:M}=_.getLineAndCharacterOfPosition(S.textSpan.start);O.push({filePath:S.fileName,position:S.textSpan.start,line:N+1,column:M,isDefinition:S.isDefinition??!1,isWrite:S.isWriteAccess??!1})}return O}}import j from"typescript";function nt(n,u){let i=Nn(n,u);if(!i)return;if(eu(i))return i;let g=i.parent;for(let t=0;t<5&&g;t++){if(eu(g))return g;g=g.parent}return i}function eu(n){return j.isClassDeclaration(n)||j.isClassExpression(n)||j.isFunctionDeclaration(n)||j.isFunctionExpression(n)||j.isArrowFunction(n)||j.isVariableDeclaration(n)||j.isObjectLiteralExpression(n)}function ni(n){if(j.isClassDeclaration(n)||j.isClassExpression(n))return"class";if(j.isFunctionDeclaration(n)||j.isFunctionExpression(n)||j.isArrowFunction(n))return"function";if(j.isObjectLiteralExpression(n))return"object";if(j.isVariableDeclaration(n)&&n.initializer)return ni(n.initializer);return"class"}function ut(n,u){if(j.isClassDeclaration(n)||j.isFunctionDeclaration(n))return n.name?.getText(u)??"";if(j.isClassExpression(n))return n.name?.getText(u)??"";if(j.isVariableDeclaration(n)&&j.isIdentifier(n.name))return n.name.getText(u);if(j.isFunctionExpression(n))return n.name?.getText(u)??"";if(j.isArrowFunction(n)&&n.parent&&j.isVariableDeclaration(n.parent)){if(j.isIdentifier(n.parent.name))return n.parent.name.getText(u)}if(j.isObjectLiteralExpression(n)&&n.parent&&j.isVariableDeclaration(n.parent)){if(j.isIdentifier(n.parent.name))return n.parent.name.getText(u)}return""}function it(n){if(!j.isClassDeclaration(n)&&!j.isClassExpression(n))return!1;let u=n.heritageClauses;if(!u)return!1;return u.some((i)=>i.token===j.SyntaxKind.ImplementsKeyword)}class Ku{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let i=this.#n.getProgram(),g=i.getSourceFile(n);if(!g)return[];let t=Nn(g,u);if(!t||!j.isIdentifier(t))return[];let w=this.#n.getLanguageService().getImplementationAtPosition(n,u);if(!w||w.length===0)return[];let O=[];for(let r of w){if(r.kind===j.ScriptElementKind.interfaceElement||r.kind===j.ScriptElementKind.typeElement)continue;let S=i.getSourceFile(r.fileName);if(!S)continue;let _=nt(S,r.textSpan.start);if(!_)continue;let N=ni(_),M=ut(_,S),f=it(_);O.push({filePath:r.fileName,symbolName:M,position:r.textSpan.start,kind:N,isExplicit:f})}return O}}function ui(n){return h.canHaveModifiers(n)&&h.getModifiers(n)?.some((u)=>u.kind===h.SyntaxKind.ExportKeyword)===!0}function tt(n){if(h.isFunctionDeclaration(n))return"function";if(h.isClassDeclaration(n))return"class";if(h.isInterfaceDeclaration(n))return"interface";if(h.isTypeAliasDeclaration(n))return"type";if(h.isEnumDeclaration(n))return"enum";if(h.isVariableDeclaration(n))return"const";if(h.isVariableStatement(n))return"const";return"unknown"}function ii(n){if(n>=97&&n<=122)return!0;if(n>=65&&n<=90)return!0;if(n>=48&&n<=57)return!0;if(n===95||n===36)return!0;return!1}class hn{#n;#u;#i;#t;#g;#r=!1;constructor(n,u,i,g,t){this.#n=n,this.#u=u,this.#i=i,this.#t=g,this.#g=t}static create(n,u={}){let i=Pn.create(n,{readConfigFile:u.readConfigFile,resolveNonTrackedFile:u.resolveNonTrackedFile});if(gt(i))return i;let g=i,t=u.typeCollector??new zu(g),m=u.symbolGraph??new fu(g),w=u.referenceResolver??new Du(g),O=u.implementationFinder??new Ku(g);return new hn(g,t,m,w,O)}get isDisposed(){return this.#r}collectTypeAt(n,u){return this.#m(),this.#u.collectAt(n,u)}collectFileTypes(n){return this.#m(),this.#u.collectFile(n)}findReferences(n,u){return this.#m(),this.#t.findAt(n,u)}findImplementations(n,u){return this.#m(),this.#g.findAt(n,u)}getSymbolNode(n,u){return this.#m(),this.#i.get(n,u)}getModuleInterface(n){this.#m();let u=this.#u.collectFile(n),i=[],t=this.#n.getProgram().getSourceFile(n);if(!t)return{filePath:n,exports:i};function m(w){if(h.isVariableStatement(w)&&ui(w)){for(let O of w.declarationList.declarations)if(h.isIdentifier(O.name)){let r=O.name.getStart(t),S=u.get(r)??null;i.push({name:O.name.text,kind:"const",resolvedType:S})}return}if((h.isFunctionDeclaration(w)||h.isClassDeclaration(w)||h.isInterfaceDeclaration(w)||h.isTypeAliasDeclaration(w)||h.isEnumDeclaration(w))&&ui(w)&&w.name){let O=w.name,r=O.getStart(t),S=u.get(r)??null;i.push({name:O.text,kind:tt(w),resolvedType:S});return}h.forEachChild(w,m)}return m(t),{filePath:n,exports:i}}notifyFileChanged(n,u){if(this.#r)return;this.#n.notifyFileChanged(n,u),this.#i.invalidate(n)}notifyFileDeleted(n){if(this.#r)return;this.#n.removeFile(n),this.#i.invalidate(n)}lineColumnToPosition(n,u,i){this.#m();let g=this.#n.getProgram().getSourceFile(n);if(!g)return null;try{return h.getPositionOfLineAndCharacter(g,u-1,i)}catch{return null}}findNamePosition(n,u,i){this.#m();let g=this.#n.getProgram().getSourceFile(n);if(!g)return null;let t=g.getFullText(),m=u;while(m<t.length){let w=t.indexOf(i,m);if(w<0)return null;let O=w>0?t.charCodeAt(w-1):32,r=w+i.length<t.length?t.charCodeAt(w+i.length):32;if(!ii(O)&&!ii(r))return w;m=w+1}return null}dispose(){if(this.#r)return;this.#r=!0,this.#n.dispose(),this.#i.clear()}#m(){if(this.#r)throw Error("SemanticLayer is disposed")}}import{eq as fn,and as gi,sql as rt}from"drizzle-orm";class Vu{db;constructor(n){this.db=n}insertBatch(n,u,i){for(let g of i)this.db.drizzleDb.insert(un).values({project:n,filePath:u,tag:g.tag,value:g.value,source:g.source,symbolName:g.symbolName,startLine:g.startLine,startColumn:g.startColumn,endLine:g.endLine,endColumn:g.endColumn,indexedAt:g.indexedAt}).run()}deleteFileAnnotations(n,u){this.db.drizzleDb.delete(un).where(gi(fn(un.project,n),fn(un.filePath,u))).run()}search(n){return this.db.drizzleDb.select().from(un).where(gi(n.project?fn(un.project,n.project):void 0,n.tag?fn(un.tag,n.tag):void 0,n.filePath?fn(un.filePath,n.filePath):void 0,n.symbolName?fn(un.symbolName,n.symbolName):void 0,n.source?fn(un.source,n.source):void 0,n.ftsQuery?rt`${un.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${n.ftsQuery})`:void 0)).limit(n.limit).all()}}import{eq as Un,and as ti,sql as Ln,gt as mt,gte as Ot}from"drizzle-orm";class Wu{db;constructor(n){this.db=n}insertBatch(n){for(let u of n)this.db.drizzleDb.insert(e).values({project:u.project,changeType:u.changeType,symbolName:u.symbolName,symbolKind:u.symbolKind,filePath:u.filePath,oldName:u.oldName,oldFilePath:u.oldFilePath,fingerprint:u.fingerprint,changedAt:u.changedAt,isFullIndex:u.isFullIndex,indexRunId:u.indexRunId}).run()}getSince(n){return this.db.drizzleDb.select().from(e).where(ti(Un(e.project,n.project),Ot(e.changedAt,n.since),n.symbolName?Un(e.symbolName,n.symbolName):void 0,n.changeTypes?.length?Ln`${e.changeType} IN (${Ln.join(n.changeTypes.map((u)=>Ln`${u}`),Ln`, `)})`:void 0,n.filePath?Un(e.filePath,n.filePath):void 0,n.includeFullIndex?void 0:Un(e.isFullIndex,0),n.indexRunId?Un(e.indexRunId,n.indexRunId):void 0,n.afterId?mt(e.id,n.afterId):void 0)).orderBy(e.id).limit(n.limit).all()}pruneOlderThan(n,u){return this.db.drizzleDb.delete(e).where(ti(Un(e.project,n),Ln`${e.changedAt} < ${u}`)).run().changes}}function ri(n){let{annotationRepo:u,project:i,query:g}=n,t=g.project??i,m=g.limit??100,w;if(g.text)w=Kn(g.text)??void 0;return u.search({project:t,tag:g.tag,filePath:g.filePath,symbolName:g.symbolName,source:g.source,ftsQuery:w,limit:m}).map((r)=>({tag:r.tag,value:r.value,source:r.source,filePath:r.filePath,symbolName:r.symbolName,span:{start:{line:r.startLine,column:r.startColumn},end:{line:r.endLine,column:r.endColumn}}}))}class xn{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(n){this.options=n}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let u=[this.options.project,...this.options.additionalProjects??[]].flatMap((i)=>[...this.options.relationRepo.getByType(i,"imports"),...this.options.relationRepo.getByType(i,"type-references"),...this.options.relationRepo.getByType(i,"re-exports")]);for(let i of u){let{srcFilePath:g,dstFilePath:t}=i;if(!this.adjacencyList.has(g))this.adjacencyList.set(g,new Set);if(this.adjacencyList.get(g).add(t),!this.adjacencyList.has(t))this.adjacencyList.set(t,new Set);if(!this.reverseAdjacencyList.has(t))this.reverseAdjacencyList.set(t,new Set);this.reverseAdjacencyList.get(t).add(g)}}patchFiles(n,u,i){let g=new Set([...n,...u]);for(let t of g){let m=this.adjacencyList.get(t);if(m){for(let O of m)this.reverseAdjacencyList.get(O)?.delete(t);m.clear()}let w=this.reverseAdjacencyList.get(t);if(w){for(let O of w)this.adjacencyList.get(O)?.delete(t);w.clear()}}for(let t of u)this.adjacencyList.delete(t),this.reverseAdjacencyList.delete(t);for(let t of n){let m=i(t);for(let w of m){if(!this.adjacencyList.has(w.srcFilePath))this.adjacencyList.set(w.srcFilePath,new Set);if(this.adjacencyList.get(w.srcFilePath).add(w.dstFilePath),!this.adjacencyList.has(w.dstFilePath))this.adjacencyList.set(w.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(w.dstFilePath))this.reverseAdjacencyList.set(w.dstFilePath,new Set);this.reverseAdjacencyList.get(w.dstFilePath).add(w.srcFilePath)}}}getDependencies(n){return Array.from(this.adjacencyList.get(n)??[])}getDependents(n){return Array.from(this.reverseAdjacencyList.get(n)??[])}getTransitiveDependents(n){let u=new Set,i=[n];while(i.length>0){let g=i.shift();for(let t of this.reverseAdjacencyList.get(g)??[])if(!u.has(t))u.add(t),i.push(t)}return Array.from(u)}hasCycle(){let n=new Set,u=new Set;for(let i of this.adjacencyList.keys()){if(n.has(i))continue;let g=[{node:i,entered:!1}];while(g.length>0){let t=g.pop();if(t.entered){u.delete(t.node);continue}if(u.has(t.node))return!0;if(n.has(t.node))continue;n.add(t.node),u.add(t.node),g.push({node:t.node,entered:!0});for(let m of this.adjacencyList.get(t.node)??[]){if(u.has(m))return!0;if(!n.has(m))g.push({node:m,entered:!1})}}}return!1}getAffectedByChange(n){let u=new Set;for(let i of n)for(let g of this.getTransitiveDependents(i))u.add(g);return Array.from(u)}getAdjacencyList(){let n=new Map;for(let[u,i]of this.adjacencyList)n.set(u,Array.from(i));return n}getTransitiveDependencies(n){let u=new Set,i=[n];while(i.length>0){let g=i.shift();for(let t of this.adjacencyList.get(g)??[])if(!u.has(t))u.add(t),i.push(t)}return Array.from(u)}getCyclePaths(n){let u=n?.maxCycles??1/0;if(u<=0)return[];let i=new Map;for(let[g,t]of this.adjacencyList)i.set(g,Array.from(t));return $t(i,u)}}var wt=(n,u)=>n.localeCompare(u);function _t(n){let u=n.length>1&&n[0]===n[n.length-1]?n.slice(0,-1):[...n];if(u.length===0)return[];let i=u;for(let g=1;g<u.length;g++){let t=u.slice(g).concat(u.slice(0,g));if(t.join("::")<i.join("::"))i=t}return[...i]}function Hu(n,u,i){let g=_t(i);if(g.length===0)return!1;let t=g.join("->");if(n.has(t))return!1;return n.add(t),u.push(g),!0}function Nt(n){let u=0,i=[],g=new Set,t=new Map,m=new Map,w=[],O=(r)=>{t.set(r,u),m.set(r,u),u+=1,i.push(r),g.add(r);for(let S of n.get(r)??[])if(!t.has(S))O(S),m.set(r,Math.min(m.get(r)??0,m.get(S)??0));else if(g.has(S))m.set(r,Math.min(m.get(r)??0,t.get(S)??0));if(m.get(r)===t.get(r)){let S=[],_="";do _=i.pop()??"",g.delete(_),S.push(_);while(_!==r&&i.length>0);w.push(S)}};for(let r of n.keys())if(!t.has(r))O(r);return{components:w}}function St(n,u,i){let g=[],t=new Set,m=[...n].sort(wt),w=(O,r,S)=>{r.delete(O);let _=S.get(O);if(!_)return;for(let N of _)if(r.has(N))w(N,r,S);_.clear()};for(let O=0;O<m.length&&g.length<i;O++){let r=m[O]??"",S=new Set(m.slice(O)),_=new Set,N=new Map,M=[],f=(K)=>(u.get(K)??[]).filter((X)=>S.has(X)),H=(K)=>{if(g.length>=i)return!0;let X=!1;M.push(K),_.add(K);for(let A of f(K)){if(g.length>=i)break;if(A===r)Hu(t,g,M.concat(r)),X=!0;else if(!_.has(A)){if(H(A))X=!0}}if(X)w(K,_,N);else for(let A of f(K)){let z=N.get(A)??new Set;z.add(K),N.set(A,z)}return M.pop(),X};H(r)}return g}function $t(n,u){let{components:i}=Nt(n),g=[],t=new Set;for(let m of i){if(g.length>=u)break;if(m.length===0)continue;if(m.length===1){let r=m[0]??"";if((n.get(r)??[]).includes(r))Hu(t,g,[r,r]);continue}let w=u-g.length,O=St(m,n,w);for(let r of O){if(g.length>=u)break;Hu(t,g,r)}}return g}var Jt=15000;function dn(n){n.graphCache=null,n.graphCacheKey=null,n.graphCacheBuiltAt=null}function Yn(n,u){let i=u??"__cross__";if(n.graphCache&&n.graphCacheBuiltAt!==null){if(Date.now()-n.graphCacheBuiltAt>Jt)n.graphCache=null,n.graphCacheKey=null,n.graphCacheBuiltAt=null}if(n.graphCache&&n.graphCacheKey===i)return n.graphCache;let g=new xn({relationRepo:n.relationRepo,project:u??n.defaultProject,additionalProjects:u?void 0:n.boundaries?.map((t)=>t.project)});return g.build(),n.graphCache=g,n.graphCacheKey=i,n.graphCacheBuiltAt=Date.now(),g}function mi(n,u,i,g=1e4){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:i??n.defaultProject,query:{srcFilePath:u,type:"imports",project:i??n.defaultProject,limit:g}}).map((t)=>t.dstFilePath)}catch(t){if(t instanceof $)throw t;throw new $("search","Gildash: getDependencies failed",{cause:t})}}function Oi(n,u,i,g=1e4){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:i??n.defaultProject,query:{dstFilePath:u,type:"imports",project:i??n.defaultProject,limit:g}}).map((t)=>t.srcFilePath)}catch(t){if(t instanceof $)throw t;throw new $("search","Gildash: getDependents failed",{cause:t})}}async function wi(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return Yn(n,i).getAffectedByChange(u)}catch(g){if(g instanceof $)throw g;throw new $("search","Gildash: getAffected failed",{cause:g})}}async function _i(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return Yn(n,u).hasCycle()}catch(i){if(i instanceof $)throw i;throw new $("search","Gildash: hasCycle failed",{cause:i})}}async function Ni(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return Yn(n,u).getAdjacencyList()}catch(i){if(i instanceof $)throw i;throw new $("search","Gildash: getImportGraph failed",{cause:i})}}async function Si(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return Yn(n,i).getTransitiveDependencies(u)}catch(g){if(g instanceof $)throw g;throw new $("search","Gildash: getTransitiveDependencies failed",{cause:g})}}async function $i(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return Yn(n,u).getCyclePaths(i)}catch(g){if(g instanceof $)throw g;throw new $("search","Gildash: getCyclePaths failed",{cause:g})}}async function Ji(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{let g=Yn(n,i);return{filePath:u,fanIn:g.getDependents(u).length,fanOut:g.getDependencies(u).length}}catch(g){if(g instanceof $)throw g;throw new $("search","Gildash: getFanMetrics failed",{cause:g})}}var Qt=30000,Ai=15000,zt=10;function ft(n,u){return(i)=>{for(let g of n.onFileChangedCallbacks)try{g(i)}catch(t){n.logger.error("[Gildash] onFileChanged callback threw:",t)}if(u.handleWatcherEvent?.(i),n.semanticLayer)if(i.eventType==="delete")try{n.semanticLayer.notifyFileDeleted(i.filePath)}catch(g){n.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",g);for(let t of n.onErrorCallbacks)try{t(g instanceof $?g:new $("semantic","semantic notifyFileDeleted failed",{cause:g}))}catch{}}else n.readFileFn(i.filePath).then((g)=>{try{n.semanticLayer?.notifyFileChanged(i.filePath,g)}catch(t){n.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",t);for(let m of n.onErrorCallbacks)try{m(t instanceof $?t:new $("semantic","semantic notifyFileChanged failed",{cause:t}))}catch{}}}).catch((g)=>{n.logger.error("[Gildash] failed to read file for semantic layer",i.filePath,g);try{n.semanticLayer?.notifyFileDeleted(i.filePath)}catch(t){n.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",t)}})}}async function Dt(n){if(!n.semanticLayer)return;let u=n.fileRepo.getAllFiles(n.defaultProject);await Promise.all(u.map(async(i)=>{try{let g=yn.resolve(n.projectRoot,i.filePath),t=await n.readFileFn(g);n.semanticLayer?.notifyFileChanged(g,t)}catch{}}))}async function Mi(n,u){let i=n.coordinatorFactory?n.coordinatorFactory():new Su({projectRoot:n.projectRoot,boundaries:n.boundaries,extensions:n.extensions,ignorePatterns:n.ignorePatterns,dbConnection:n.db,parseCache:n.parseCache,fileRepo:n.fileRepo,symbolRepo:n.symbolRepo,relationRepo:n.relationRepo,annotationRepo:n.annotationRepo??void 0,changelogRepo:n.changelogRepo??void 0,logger:n.logger});n.coordinator=i;for(let g of n.onIndexedCallbacks)i.onIndexed(g);if(i.onIndexed((g)=>{let t=g.changedFiles.length+g.deletedFiles.length;if(n.graphCache&&t>0&&t<100){let m=n.relationRepo;n.graphCache.patchFiles(g.changedFiles,g.deletedFiles,(w)=>{return[n.defaultProject,...n.boundaries.map((r)=>r.project)].flatMap((r)=>m.getByType(r,"imports").concat(m.getByType(r,"type-references")).concat(m.getByType(r,"re-exports"))).filter((r)=>r.srcFilePath===w||r.dstFilePath===w).map((r)=>({srcFilePath:r.srcFilePath,dstFilePath:r.dstFilePath}))}),n.graphCacheBuiltAt=Date.now()}else dn(n)}),u.isWatchMode){let g=n.watcherFactory?n.watcherFactory():new gu({projectRoot:n.projectRoot,ignorePatterns:n.ignorePatterns,extensions:n.extensions},void 0,n.logger);await g.start(ft(n,i)).then((t)=>{if(kn(t))throw t.data}),n.watcher=g,n.timer=setInterval(()=>{n.updateHeartbeatFn(n.db,process.pid)},Qt)}await i.fullIndex(),await Dt(n)}function Kt(n,u){let i=["SIGTERM","SIGINT","beforeExit"];for(let g of i){let t=()=>{u().catch((m)=>n.logger.error("[Gildash] close error during signal",g,m))};if(g==="beforeExit")process.on("beforeExit",t);else process.on(g,t);n.signalHandlers.push([g,t])}}async function Qi(n){let{projectRoot:u,extensions:i=[".ts",".mts",".cts"],ignorePatterns:g=["**/node_modules/**"],parseCacheCapacity:t=500,logger:m=console,existsSyncFn:w=Mt,dbConnectionFactory:O,watcherFactory:r,coordinatorFactory:S,repositoryFactory:_,acquireWatcherRoleFn:N=du,releaseWatcherRoleFn:M=lu,updateHeartbeatFn:f=ou,discoverProjectsFn:H=jn,parseSourceFn:K=Bn,extractSymbolsFn:X=Wn,extractRelationsFn:A=pn,symbolSearchFn:z=Ju,relationSearchFn:J=Au,patternSearchFn:W=Mu,loadTsconfigPathsFn:Y=Xn,readFileFn:I=async(D)=>Bun.file(D).text(),unlinkFn:B=async(D)=>{await Bun.file(D).unlink()},watchMode:s,semantic:b,semanticLayerFactory:E}=n;if(!yn.isAbsolute(u))throw new $("validation",`Gildash: projectRoot must be an absolute path, got: "${u}"`);if(!w(u))throw new $("validation",`Gildash: projectRoot does not exist: "${u}"`);let q=O?O():new cn({projectRoot:u}),Q=q.open();if(kn(Q))throw Q.data;try{let D=await H(u),Z=D[0]?.project??yn.basename(u),U=_?_():(()=>{let l=q;return{fileRepo:new en(l),symbolRepo:new nu(l),relationRepo:new uu(l),parseCache:new $u(t)}})(),R=_?null:q,L=R?new Vu(R):null,gn=R?new Wu(R):null,k=s??!0,G=crypto.randomUUID(),F;if(k)F=await Promise.resolve(N(q,process.pid,{instanceId:G}));else F="owner";let C={projectRoot:u,extensions:i,ignorePatterns:g,logger:m,defaultProject:Z,role:F,db:q,symbolRepo:U.symbolRepo,relationRepo:U.relationRepo,fileRepo:U.fileRepo,parseCache:U.parseCache,annotationRepo:L,changelogRepo:gn,annotationSearchFn:ri,releaseWatcherRoleFn:M,parseSourceFn:K,extractSymbolsFn:X,extractRelationsFn:A,symbolSearchFn:z,relationSearchFn:J,patternSearchFn:W,readFileFn:I,unlinkFn:B,existsSyncFn:w,acquireWatcherRoleFn:N,updateHeartbeatFn:f,watcherFactory:r,coordinatorFactory:S,instanceId:G,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:D,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(bn(u),C.tsconfigPaths=await Y(u),b){let l=yn.join(u,"tsconfig.json");try{if(E)C.semanticLayer=E(l);else{let o=hn.create(l);if(kn(o))throw o.data;C.semanticLayer=o}}catch(o){if(o instanceof $)throw o;throw new $("semantic","Gildash: semantic layer creation failed",{cause:o})}}if(F==="owner")await Mi(C,{isWatchMode:k});else{let l=0,o=async()=>{try{let On=await Promise.resolve(C.acquireWatcherRoleFn(C.db,process.pid,{instanceId:C.instanceId}));if(l=0,On==="owner"){for(let Sn of C.onRoleChangedCallbacks)try{Sn("owner")}catch(tn){C.logger.error("[Gildash] onRoleChanged callback threw:",tn)}clearInterval(C.timer),C.timer=null;try{await Mi(C,{isWatchMode:!0})}catch(Sn){if(C.logger.error("[Gildash] owner promotion failed, reverting to reader",Sn),C.watcher){let tn=await C.watcher.close();if(kn(tn))C.logger.error("[Gildash] watcher close error during promotion rollback",tn.data);C.watcher=null}if(C.coordinator)await C.coordinator.shutdown().catch((tn)=>C.logger.error("[Gildash] coordinator shutdown error during promotion rollback",tn)),C.coordinator=null;if(C.timer===null)C.timer=setInterval(o,Ai)}}}catch(On){l++;let Sn=On instanceof $?On:new $("watcher","Gildash: healthcheck error",{cause:On});for(let tn of C.onErrorCallbacks)try{tn(Sn)}catch(In){C.logger.error("[Gildash] onError callback threw:",In)}if(C.logger.error("[Gildash] healthcheck error",On),l>=zt)C.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(C.timer),C.timer=null,ln(C).catch((tn)=>C.logger.error("[Gildash] close error during healthcheck shutdown",tn))}};C.timer=setInterval(o,Ai)}if(k)Kt(C,()=>ln(C));return C}catch(D){if(q.close(),D instanceof $)throw D;throw new $("store","Gildash: initialization failed",{cause:D})}}async function ln(n,u){if(n.closed)return;n.closed=!0;let i=[];for(let[g,t]of n.signalHandlers)if(g==="beforeExit")process.off("beforeExit",t);else process.off(g,t);if(n.signalHandlers=[],n.semanticLayer){try{n.semanticLayer.dispose()}catch(g){i.push(g instanceof Error?g:Error(String(g)))}n.semanticLayer=null}if(n.coordinator)try{await n.coordinator.shutdown()}catch(g){i.push(g instanceof Error?g:Error(String(g)))}if(n.watcher){let g=await n.watcher.close();if(kn(g))i.push(g.data)}if(n.timer!==null)clearInterval(n.timer),n.timer=null;try{n.releaseWatcherRoleFn(n.db,process.pid)}catch(g){i.push(g instanceof Error?g:Error(String(g)))}try{n.db.close()}catch(g){i.push(g instanceof Error?g:Error(String(g)))}if(u?.cleanup)for(let g of["","-wal","-shm"])try{await n.unlinkFn(yn.join(n.projectRoot,$n,Rn+g))}catch{}if(i.length>0)throw new $("close","Gildash: one or more errors occurred during close()",{cause:i})}import{isErr as zi}from"@zipbul/result";function fi(n,u,i,g){if(n.closed)throw new $("closed","Gildash: instance is closed");let t=n.parseSourceFn(u,i,g);if(zi(t))throw t.data;return n.parseCache.set(u,t),t}async function Di(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");let g=new Map,t=[];return await Promise.all(u.map(async(m)=>{try{let w=await n.readFileFn(m),O=n.parseSourceFn(m,w,i);if(!zi(O))g.set(m,O);else t.push({filePath:m,error:O.data})}catch(w){t.push({filePath:m,error:w instanceof Error?w:Error(String(w))})}})),{parsed:g,failures:t}}function Ki(n,u){if(n.closed)return;return n.parseCache.get(u)}function Vi(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");return n.extractSymbolsFn(u)}function Wi(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");return n.extractRelationsFn(u.program,u.filePath,n.tsconfigPaths??void 0)}import Hi from"path";function Ui(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.symbolRepo.getStats(u??n.defaultProject)}catch(i){if(i instanceof $)throw i;throw new $("store","Gildash: getStats failed",{cause:i})}}function Uu(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:n.defaultProject,query:u})}catch(i){if(i instanceof $)throw i;throw new $("search","Gildash: searchSymbols failed",{cause:i})}}function Yi(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:n.defaultProject,query:u})}catch(i){if(i instanceof $)throw i;throw new $("search","Gildash: searchRelations failed",{cause:i})}}function Ii(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:void 0,query:u})}catch(i){if(i instanceof $)throw i;throw new $("search","Gildash: searchAllSymbols failed",{cause:i})}}function Zi(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:void 0,query:u})}catch(i){if(i instanceof $)throw i;throw new $("search","Gildash: searchAllRelations failed",{cause:i})}}function Xi(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.fileRepo.getAllFiles(u??n.defaultProject)}catch(i){if(i instanceof $)throw i;throw new $("store","Gildash: listIndexedFiles failed",{cause:i})}}function Bi(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:i??n.defaultProject,query:{srcFilePath:u,dstFilePath:u,limit:1e4}})}catch(g){if(g instanceof $)throw g;throw new $("search","Gildash: getInternalRelations failed",{cause:g})}}function Ci(n,u,i,g){if(n.closed)throw new $("closed","Gildash: instance is closed");try{let t=g??n.defaultProject,m=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:t,query:{text:u,exact:!0,filePath:i,limit:1}});if(m.length===0)return null;let w=m[0],O=w.detail,r={...w,members:Array.isArray(O.members)?O.members:void 0,jsDoc:typeof O.jsDoc==="string"?O.jsDoc:void 0,parameters:typeof O.parameters==="string"?O.parameters:void 0,returnType:typeof O.returnType==="string"?O.returnType:void 0,heritage:Array.isArray(O.heritage)?O.heritage:void 0,decorators:Array.isArray(O.decorators)?O.decorators:void 0,typeParameters:typeof O.typeParameters==="string"?O.typeParameters:void 0};if(n.semanticLayer)try{let S=Hi.isAbsolute(i)?i:Hi.resolve(n.projectRoot,i),_=n.semanticLayer.lineColumnToPosition(S,w.span.start.line,w.span.start.column);if(_!==null){let N=n.semanticLayer.findNamePosition(S,_,w.name)??_,M=n.semanticLayer.collectTypeAt(S,N);if(M)r.resolvedType=M}}catch{}return r}catch(t){if(t instanceof $)throw t;throw new $("search","Gildash: getFullSymbol failed",{cause:t})}}function Ti(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{let g=i??n.defaultProject,t=n.fileRepo.getFile(g,u);if(!t)throw new $("search",`Gildash: file '${u}' is not in the index`);let m=n.symbolRepo.getFileSymbols(g,u),w=n.relationRepo.getOutgoing(g,u);return{filePath:t.filePath,lineCount:t.lineCount??0,size:t.size,symbolCount:m.length,exportedSymbolCount:m.filter((O)=>O.isExported).length,relationCount:w.length}}catch(g){if(g instanceof $)throw g;throw new $("store","Gildash: getFileStats failed",{cause:g})}}function Li(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{return n.fileRepo.getFile(i??n.defaultProject,u)}catch(g){if(g instanceof $)throw g;throw new $("store","Gildash: getFileInfo failed",{cause:g})}}function ki(n,u,i){return Uu(n,{filePath:u,project:i??void 0,limit:1e4})}function yi(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{let t=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:i??n.defaultProject,query:{filePath:u,isExported:!0}}).map((m)=>({name:m.name,kind:m.kind,parameters:m.detail.parameters??void 0,returnType:m.detail.returnType??void 0,jsDoc:m.detail.jsDoc??void 0}));return{filePath:u,exports:t}}catch(g){if(g instanceof $)throw g;throw new $("search","Gildash: getModuleInterface failed",{cause:g})}}import Ri from"path";function Yu(n,u,i,g){let t=g??n.defaultProject,m=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:t,query:{text:u,exact:!0,filePath:i,limit:1}});if(m.length===0)return null;let w=m[0],O=Ri.isAbsolute(i)?i:Ri.resolve(n.projectRoot,i),r=n.semanticLayer.lineColumnToPosition(O,w.span.start.line,w.span.start.column);if(r===null)return null;let S=n.semanticLayer.findNamePosition(O,r,w.name)??r;return{sym:w,position:S,absPath:O}}function Fi(n,u,i,g){if(n.closed)throw new $("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new $("semantic","Gildash: semantic layer is not enabled");try{let t=Yu(n,u,i,g);if(!t)return null;return n.semanticLayer.collectTypeAt(t.absPath,t.position)}catch(t){if(t instanceof $)throw t;throw new $("search","Gildash: getResolvedType failed",{cause:t})}}function si(n,u,i,g){if(n.closed)throw new $("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new $("semantic","Gildash: semantic layer is not enabled");try{let t=Yu(n,u,i,g);if(!t)throw new $("search",`Gildash: symbol '${u}' not found in '${i}'`);return n.semanticLayer.findReferences(t.absPath,t.position)}catch(t){if(t instanceof $)throw t;throw new $("search","Gildash: getSemanticReferences failed",{cause:t})}}function ji(n,u,i,g){if(n.closed)throw new $("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new $("semantic","Gildash: semantic layer is not enabled");try{let t=Yu(n,u,i,g);if(!t)throw new $("search",`Gildash: symbol '${u}' not found in '${i}'`);return n.semanticLayer.findImplementations(t.absPath,t.position)}catch(t){if(t instanceof $)throw t;throw new $("search","Gildash: getImplementations failed",{cause:t})}}function bi(n,u){if(n.closed)throw new $("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new $("semantic","Gildash: semantic layer is not enabled");try{return n.semanticLayer.getModuleInterface(u)}catch(i){if(i instanceof $)throw i;throw new $("search","Gildash: getSemanticModuleInterface failed",{cause:i})}}function qi(n,u){let i=new Map(n.map((O)=>[`${O.name}::${O.filePath}`,O])),g=new Map(u.map((O)=>[`${O.name}::${O.filePath}`,O])),t=[],m=[],w=[];for(let[O,r]of g){let S=i.get(O);if(!S)t.push(r);else if(S.fingerprint!==r.fingerprint)w.push({before:S,after:r})}for(let[O,r]of i)if(!g.has(O))m.push(r);return{added:t,removed:m,modified:w}}function Gi(n,u){if(n.onIndexedCallbacks.add(u),!n.coordinator)return()=>{n.onIndexedCallbacks.delete(u)};let i=n.coordinator.onIndexed(u);return()=>{n.onIndexedCallbacks.delete(u),i()}}async function Ei(n){if(n.closed)throw new $("closed","Gildash: instance is closed");if(!n.coordinator)throw new $("closed","Gildash: reindex() is not available for readers");try{let u=await n.coordinator.fullIndex();return dn(n),u}catch(u){if(u instanceof $)throw u;throw new $("index","Gildash: reindex failed",{cause:u})}}function pi(n,u,i,g){if(n.closed)throw new $("closed","Gildash: instance is closed");let t=g??n.defaultProject,m=new Set,w=[],O=u,r=i;for(;;){let S=`${r}::${O}`;if(m.has(S))return{originalName:O,originalFilePath:r,reExportChain:w,circular:!0};m.add(S);let _=n.relationSearchFn({relationRepo:n.relationRepo,project:t,query:{type:"re-exports",srcFilePath:r,limit:500}}),N,M;for(let f of _){let H;if(f.metaJson)try{let X=JSON.parse(f.metaJson);if(Array.isArray(X.specifiers))H=X.specifiers}catch{}if(!H)continue;let K=H.find((X)=>X.exported===O);if(!K)continue;N=f.dstFilePath,M=K.local;break}if(!N||!M)return{originalName:O,originalFilePath:r,reExportChain:w,circular:!1};w.push({filePath:r,exportedAs:O}),r=N,O=M}}function vi(n,u){return n.onFileChangedCallbacks.add(u),()=>{n.onFileChangedCallbacks.delete(u)}}function Pi(n,u){return n.onErrorCallbacks.add(u),()=>{n.onErrorCallbacks.delete(u)}}function ai(n,u){return n.onRoleChangedCallbacks.add(u),()=>{n.onRoleChangedCallbacks.delete(u)}}async function hi(n,u,i){if(n.closed)throw new $("closed","Gildash: instance is closed");try{let g=i?.project??n.defaultProject,t=i?.filePaths?i.filePaths:n.fileRepo.getAllFiles(g).map((m)=>m.filePath);return await n.patternSearchFn({pattern:u,filePaths:t})}catch(g){if(g instanceof $)throw g;throw new $("search","Gildash: findPattern failed",{cause:g})}}async function xi(n,u,i,g){if(n.closed)throw new $("closed","Gildash: instance is closed");try{let t=g??n.defaultProject,m=new Set,w=(O,r,S)=>{let _=`${O}::${r}`;if(m.has(_))return{symbolName:O,filePath:r,kind:S,children:[]};m.add(_);let f=n.relationSearchFn({relationRepo:n.relationRepo,project:t,query:{srcFilePath:r,srcSymbolName:O,limit:1000}}).filter((H)=>H.type==="extends"||H.type==="implements").filter((H)=>H.dstSymbolName!=null).map((H)=>w(H.dstSymbolName,H.dstFilePath,H.type));return{symbolName:O,filePath:r,kind:S,children:f}};return w(u,i)}catch(t){if(t instanceof $)throw t;throw new $("search","Gildash: getHeritageChain failed",{cause:t})}}function di(n,u){if(n.closed)throw new $("closed","Gildash instance is closed");if(!n.annotationRepo||!n.annotationSearchFn)return[];return n.annotationSearchFn({annotationRepo:n.annotationRepo,project:u.project??n.defaultProject,query:u})}function li(n,u,i){if(n.closed)throw new $("closed","Gildash instance is closed");if(!n.changelogRepo)return[];let g=u instanceof Date?u.toISOString():u,t=i?.project??n.defaultProject,m=i?.limit??1000;return n.changelogRepo.getSince({project:t,since:g,symbolName:i?.symbolName,changeTypes:i?.changeTypes,filePath:i?.filePath,includeFullIndex:i?.includeFullIndex,indexRunId:i?.indexRunId,afterId:i?.afterId,limit:m}).map((O)=>({changeType:O.changeType,symbolName:O.symbolName,symbolKind:O.symbolKind,filePath:O.filePath,oldName:O.oldName,oldFilePath:O.oldFilePath,fingerprint:O.fingerprint,changedAt:O.changedAt,isFullIndex:O.isFullIndex===1,indexRunId:O.indexRunId}))}function oi(n,u){if(n.closed)throw new $("closed","Gildash instance is closed");if(!n.changelogRepo)return 0;let i=u instanceof Date?u.toISOString():u,g=0,t=[n.defaultProject,...n.boundaries.map((w)=>w.project)],m=[...new Set(t)];for(let w of m)g+=n.changelogRepo.pruneOlderThan(w,i);return g}class Iu{_ctx;get projectRoot(){return this._ctx.projectRoot}get role(){return this._ctx.role}get projects(){return[...this._ctx.boundaries]}constructor(n){this._ctx=n}static async open(n){let u=await Qi(n);return new Iu(u)}async close(n){return ln(this._ctx,n)}parseSource(n,u,i){return fi(this._ctx,n,u,i)}async batchParse(n,u){return Di(this._ctx,n,u)}getParsedAst(n){return Ki(this._ctx,n)}extractSymbols(n){return Vi(this._ctx,n)}extractRelations(n){return Wi(this._ctx,n)}getStats(n){return Ui(this._ctx,n)}searchSymbols(n){return Uu(this._ctx,n)}searchRelations(n){return Yi(this._ctx,n)}searchAllSymbols(n){return Ii(this._ctx,n)}searchAllRelations(n){return Zi(this._ctx,n)}listIndexedFiles(n){return Xi(this._ctx,n)}getInternalRelations(n,u){return Bi(this._ctx,n,u)}getFullSymbol(n,u,i){return Ci(this._ctx,n,u,i)}getFileStats(n,u){return Ti(this._ctx,n,u)}getFileInfo(n,u){return Li(this._ctx,n,u)}getSymbolsByFile(n,u){return ki(this._ctx,n,u)}getModuleInterface(n,u){return yi(this._ctx,n,u)}getDependencies(n,u,i=1e4){return mi(this._ctx,n,u,i)}getDependents(n,u,i=1e4){return Oi(this._ctx,n,u,i)}async getAffected(n,u){return wi(this._ctx,n,u)}async hasCycle(n){return _i(this._ctx,n)}async getImportGraph(n){return Ni(this._ctx,n)}async getTransitiveDependencies(n,u){return Si(this._ctx,n,u)}async getCyclePaths(n,u){return $i(this._ctx,n,u)}async getFanMetrics(n,u){return Ji(this._ctx,n,u)}getResolvedType(n,u,i){return Fi(this._ctx,n,u,i)}getSemanticReferences(n,u,i){return si(this._ctx,n,u,i)}getImplementations(n,u,i){return ji(this._ctx,n,u,i)}getSemanticModuleInterface(n){return bi(this._ctx,n)}diffSymbols(n,u){return qi(n,u)}onIndexed(n){return Gi(this._ctx,n)}async reindex(){return Ei(this._ctx)}resolveSymbol(n,u,i){return pi(this._ctx,n,u,i)}async findPattern(n,u){return hi(this._ctx,n,u)}async getHeritageChain(n,u,i){return xi(this._ctx,n,u,i)}onFileChanged(n){return vi(this._ctx,n)}onError(n){return Pi(this._ctx,n)}onRoleChanged(n){return ai(this._ctx,n)}searchAnnotations(n){return di(this._ctx,n)}getSymbolChanges(n,u){return li(this._ctx,n,u)}pruneChangelog(n){return oi(this._ctx,n)}}export{Ju as symbolSearch,Au as relationSearch,Mu as patternSearch,c as gildashError,$ as GildashError,Iu as Gildash,xn as DependencyGraph};
2
+ var g$=Object.defineProperty;var _$=(u)=>u;function $$(u,g){this[u]=_$.bind(null,g)}var N$=(u,g)=>{for(var _ in g)g$(u,_,{get:g[_],enumerable:!0,configurable:!0,set:$$.bind(g,_)})};var Sg=import.meta.require;import{isErr as Gu}from"@zipbul/result";import ju from"path";import{existsSync as M0}from"fs";import{err as Rg,isErr as W$}from"@zipbul/result";import{Database as Y$}from"bun:sqlite";import{mkdirSync as V$,unlinkSync as Tg,existsSync as kg}from"fs";import{dirname as U$,join as Fg}from"path";import{drizzle as X$}from"drizzle-orm/bun-sqlite";import{migrate as Z$}from"drizzle-orm/bun-sqlite/migrator";class U extends Error{type;constructor(u,g,_){super(g,_);this.type=u;this.name="GildashError"}}function e(u,g,_){return new U(u,g,_!==void 0?{cause:_}:void 0)}var Yu=".gildash",Eu="gildash.db";var cu={};N$(cu,{watcherOwner:()=>O$,symbols:()=>f,symbolChangelog:()=>uu,relations:()=>L,files:()=>p,annotations:()=>$u});import{sql as J$}from"drizzle-orm";import{sqliteTable as nu,text as F,integer as t,real as Q$,index as gu,primaryKey as z$,foreignKey as vu,check as w$}from"drizzle-orm/sqlite-core";var p=nu("files",{project:F("project").notNull(),filePath:F("file_path").notNull(),mtimeMs:Q$("mtime_ms").notNull(),size:t("size").notNull(),contentHash:F("content_hash").notNull(),updatedAt:F("updated_at").notNull(),lineCount:t("line_count")},(u)=>[z$({columns:[u.project,u.filePath]})]),f=nu("symbols",{id:t("id").primaryKey({autoIncrement:!0}),project:F("project").notNull(),filePath:F("file_path").notNull(),kind:F("kind").notNull(),name:F("name").notNull(),startLine:t("start_line").notNull(),startColumn:t("start_column").notNull(),endLine:t("end_line").notNull(),endColumn:t("end_column").notNull(),isExported:t("is_exported").notNull().default(0),signature:F("signature"),fingerprint:F("fingerprint"),detailJson:F("detail_json"),contentHash:F("content_hash").notNull(),indexedAt:F("indexed_at").notNull(),resolvedType:F("resolved_type"),structuralFingerprint:F("structural_fingerprint")},(u)=>[gu("idx_symbols_project_file").on(u.project,u.filePath),gu("idx_symbols_project_kind").on(u.project,u.kind),gu("idx_symbols_project_name").on(u.project,u.name),gu("idx_symbols_fingerprint").on(u.project,u.fingerprint),vu({columns:[u.project,u.filePath],foreignColumns:[p.project,p.filePath]}).onDelete("cascade")]),L=nu("relations",{id:t("id").primaryKey({autoIncrement:!0}),project:F("project").notNull(),type:F("type").notNull(),srcFilePath:F("src_file_path").notNull(),srcSymbolName:F("src_symbol_name"),dstProject:F("dst_project").notNull(),dstFilePath:F("dst_file_path").notNull(),dstSymbolName:F("dst_symbol_name"),metaJson:F("meta_json")},(u)=>[gu("idx_relations_src").on(u.project,u.srcFilePath),gu("idx_relations_dst").on(u.dstProject,u.dstFilePath),gu("idx_relations_type").on(u.project,u.type),gu("idx_relations_project_type_src").on(u.project,u.type,u.srcFilePath),vu({columns:[u.project,u.srcFilePath],foreignColumns:[p.project,p.filePath]}).onDelete("cascade"),vu({columns:[u.dstProject,u.dstFilePath],foreignColumns:[p.project,p.filePath]}).onDelete("cascade")]),$u=nu("annotations",{id:t("id").primaryKey({autoIncrement:!0}),project:F("project").notNull(),filePath:F("file_path").notNull(),tag:F("tag").notNull(),value:F("value").notNull().default(""),source:F("source").notNull(),symbolName:F("symbol_name"),startLine:t("start_line").notNull(),startColumn:t("start_column").notNull(),endLine:t("end_line").notNull(),endColumn:t("end_column").notNull(),indexedAt:F("indexed_at").notNull()},(u)=>[gu("idx_annotations_project_file").on(u.project,u.filePath),gu("idx_annotations_project_tag").on(u.project,u.tag),gu("idx_annotations_project_symbol").on(u.project,u.symbolName),vu({columns:[u.project,u.filePath],foreignColumns:[p.project,p.filePath]}).onDelete("cascade")]),uu=nu("symbol_changelog",{id:t("id").primaryKey({autoIncrement:!0}),project:F("project").notNull(),changeType:F("change_type").notNull(),symbolName:F("symbol_name").notNull(),symbolKind:F("symbol_kind").notNull(),filePath:F("file_path").notNull(),oldName:F("old_name"),oldFilePath:F("old_file_path"),fingerprint:F("fingerprint"),changedAt:F("changed_at").notNull(),isFullIndex:t("is_full_index").notNull().default(0),indexRunId:F("index_run_id").notNull()},(u)=>[gu("idx_changelog_project_changed_at").on(u.project,u.changedAt),gu("idx_changelog_project_name").on(u.project,u.symbolName),gu("idx_changelog_project_run").on(u.project,u.indexRunId)]),O$=nu("watcher_owner",{id:t("id").primaryKey(),pid:t("pid").notNull(),startedAt:F("started_at").notNull(),heartbeatAt:F("heartbeat_at").notNull(),instanceId:F("instance_id")},(u)=>[w$("watcher_owner_singleton",J$`${u.id} = 1`)]);class su{client=null;drizzle=null;dbPath;txDepth=0;constructor(u){this.dbPath=Fg(u.projectRoot,Yu,Eu)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{V$(U$(this.dbPath),{recursive:!0}),this.client=new Y$(this.dbPath),this.client.run("PRAGMA journal_mode = WAL"),this.client.run("PRAGMA foreign_keys = OFF"),this.client.run("PRAGMA busy_timeout = 5000"),this.drizzle=X$(this.client,{schema:cu}),Z$(this.drizzle,{migrationsFolder:Fg(import.meta.dirname,"migrations")});let u=this.client.prepare("PRAGMA foreign_key_check").all();if(u.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(u.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON"),this.registerRegexpUdf(this.client)}catch(u){if(this.isCorruptionError(u)&&kg(this.dbPath)){this.closeClient(),Tg(this.dbPath);for(let _ of["-wal","-shm"]){let $=this.dbPath+_;if(kg($))Tg($)}let g=this.open();if(W$(g))return Rg(e("store",`Failed to recover database at ${this.dbPath}`,g.data));return g}return Rg(e("store",`Failed to open database at ${this.dbPath}`,u))}}close(){this.closeClient(),this.drizzle=null}transaction(u){let g=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return g.transaction(()=>u(this))()}finally{this.txDepth--}}let _=`sp_${this.txDepth++}`;g.run(`SAVEPOINT "${_}"`);try{let $=u(this);return g.run(`RELEASE SAVEPOINT "${_}"`),$}catch($){throw g.run(`ROLLBACK TO SAVEPOINT "${_}"`),g.run(`RELEASE SAVEPOINT "${_}"`),$}finally{this.txDepth--}}immediateTransaction(u){let g=this.requireClient();this.txDepth++,g.run("BEGIN IMMEDIATE");try{let _=u();return g.run("COMMIT"),_}catch(_){throw g.run("ROLLBACK"),_}finally{this.txDepth--}}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((g)=>g.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(u,g){let _=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(u,_,_,g??null)}replaceOwner(u,g){let _=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(u,_,_,g??null)}touchOwner(u){let g=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(g,u)}deleteOwner(u){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(u)}registerRegexpUdf(u){let g=u;if(typeof g.function!=="function")return;g.function.call(u,"regexp",(_,$)=>{try{return new RegExp(_).test($)?1:0}catch{return 0}})}requireClient(){if(!this.client)throw Error("Database is not open. Call open() first.");return this.client}closeClient(){if(this.client)this.client.close(),this.client=null}isCorruptionError(u){if(!(u instanceof Error))return!1;let g=u.message.toLowerCase();return g.includes("malformed")||g.includes("corrupt")||g.includes("not a database")||g.includes("disk i/o error")||g.includes("sqlite_corrupt")}}import{eq as Su,and as qg}from"drizzle-orm";class ou{db;constructor(u){this.db=u}getFile(u,g){return this.db.drizzleDb.select().from(p).where(qg(Su(p.project,u),Su(p.filePath,g))).get()??null}upsertFile(u){this.db.drizzleDb.insert(p).values({project:u.project,filePath:u.filePath,mtimeMs:u.mtimeMs,size:u.size,contentHash:u.contentHash,updatedAt:u.updatedAt,lineCount:u.lineCount??null}).onConflictDoUpdate({target:[p.project,p.filePath],set:{mtimeMs:u.mtimeMs,size:u.size,contentHash:u.contentHash,updatedAt:u.updatedAt,lineCount:u.lineCount??null}}).run()}getAllFiles(u){return this.db.drizzleDb.select().from(p).where(Su(p.project,u)).all()}getFilesMap(u){let g=this.getAllFiles(u),_=new Map;for(let $ of g)_.set($.filePath,$);return _}deleteFile(u,g){this.db.drizzleDb.delete(p).where(qg(Su(p.project,u),Su(p.filePath,g))).run()}}import{eq as r,and as Xu,sql as Pu,count as K$}from"drizzle-orm";function Hu(u){return u.trim().split(/\s+/).map((g)=>g.trim()).filter((g)=>g.length>0).map((g)=>`"${g.replaceAll('"','""')}"*`).join(" ")}var Gg=50;class eu{db;constructor(u){this.db=u}replaceFileSymbols(u,g,_,$){if(this.db.drizzleDb.delete(f).where(Xu(r(f.project,u),r(f.filePath,g))).run(),!$.length)return;let N=new Date().toISOString(),w=$.map((z)=>({project:u,filePath:g,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:_,indexedAt:z.indexedAt??N,resolvedType:z.resolvedType??null,structuralFingerprint:z.structuralFingerprint??null}));for(let z=0;z<w.length;z+=Gg)this.db.drizzleDb.insert(f).values(w.slice(z,z+Gg)).run()}getFileSymbols(u,g){return this.db.drizzleDb.select().from(f).where(Xu(r(f.project,u),r(f.filePath,g))).all()}searchByName(u,g,_={}){let $=_.limit??50,N=Hu(g);if(!N)return[];return this.db.drizzleDb.select().from(f).where(Xu(Pu`${f.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${N})`,r(f.project,u),_.kind?r(f.kind,_.kind):void 0)).orderBy(f.name).limit($).all()}searchByKind(u,g){return this.db.drizzleDb.select().from(f).where(Xu(r(f.project,u),r(f.kind,g))).orderBy(f.name).all()}getStats(u){let g=this.db.drizzleDb.select({symbolCount:K$(),fileCount:Pu`COUNT(DISTINCT ${f.filePath})`}).from(f).where(r(f.project,u)).get();return{symbolCount:g?.symbolCount??0,fileCount:g?.fileCount??0}}getByFingerprint(u,g){return this.db.drizzleDb.select().from(f).where(Xu(r(f.project,u),r(f.fingerprint,g))).all()}deleteFileSymbols(u,g){this.db.drizzleDb.delete(f).where(Xu(r(f.project,u),r(f.filePath,g))).run()}searchByQuery(u){let g=this.db.drizzleDb.select().from(f).where(Xu(u.ftsQuery?Pu`${f.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${u.ftsQuery})`:void 0,u.exactName?r(f.name,u.exactName):void 0,u.project!==void 0?r(f.project,u.project):void 0,u.kind?r(f.kind,u.kind):void 0,u.filePath!==void 0?r(f.filePath,u.filePath):void 0,u.isExported!==void 0?r(f.isExported,u.isExported?1:0):void 0,u.decorator?Pu`${f.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${u.decorator})`:void 0,u.resolvedType!==void 0?r(f.resolvedType,u.resolvedType):void 0)).orderBy(f.name);if(!u.regex)return g.limit(u.limit).all();let _;try{_=new RegExp(u.regex)}catch{throw new U("validation",`Invalid regex pattern: ${u.regex}`)}for(let $ of[5,20,100]){let N=u.limit*$,w=g.limit(N).all(),z=w.filter((Q)=>_.test(Q.name));if(z.length>=u.limit||w.length<N)return z.slice(0,u.limit)}return[]}}import{eq as x,and as zu,isNull as jg,or as M$}from"drizzle-orm";class ug{db;constructor(u){this.db=u}replaceFileRelations(u,g,_){this.db.transaction(($)=>{if($.drizzleDb.delete(L).where(zu(x(L.project,u),x(L.srcFilePath,g))).run(),!_.length)return;for(let N of _)$.drizzleDb.insert(L).values({project:u,type:N.type??"unknown",srcFilePath:N.srcFilePath??g,srcSymbolName:N.srcSymbolName??null,dstProject:N.dstProject??u,dstFilePath:N.dstFilePath??"",dstSymbolName:N.dstSymbolName??null,metaJson:N.metaJson??null}).run()})}getOutgoing(u,g,_){if(_!==void 0)return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(zu(x(L.project,u),x(L.srcFilePath,g),M$(x(L.srcSymbolName,_),jg(L.srcSymbolName)))).all();return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(zu(x(L.project,u),x(L.srcFilePath,g))).all()}getIncoming(u){let{dstProject:g,dstFilePath:_}=u;return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(zu(x(L.dstProject,g),x(L.dstFilePath,_))).all()}getByType(u,g){return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(zu(x(L.project,u),x(L.type,g))).all()}deleteFileRelations(u,g){this.db.drizzleDb.delete(L).where(zu(x(L.project,u),x(L.srcFilePath,g))).run()}searchRelations(u){return this.db.drizzleDb.select({project:L.project,type:L.type,srcFilePath:L.srcFilePath,srcSymbolName:L.srcSymbolName,dstProject:L.dstProject,dstFilePath:L.dstFilePath,dstSymbolName:L.dstSymbolName,metaJson:L.metaJson}).from(L).where(zu(u.project!==void 0?x(L.project,u.project):void 0,u.srcFilePath!==void 0?x(L.srcFilePath,u.srcFilePath):void 0,u.srcSymbolName!==void 0?x(L.srcSymbolName,u.srcSymbolName):void 0,u.dstProject!==void 0?x(L.dstProject,u.dstProject):void 0,u.dstFilePath!==void 0?x(L.dstFilePath,u.dstFilePath):void 0,u.dstSymbolName!==void 0?x(L.dstSymbolName,u.dstSymbolName):void 0,u.type!==void 0?x(L.type,u.type):void 0)).limit(u.limit).all()}retargetRelations(u){let{dstProject:g,oldFile:_,oldSymbol:$,newFile:N,newSymbol:w,newDstProject:z}=u,Q=$===null?zu(x(L.dstProject,g),x(L.dstFilePath,_),jg(L.dstSymbolName)):zu(x(L.dstProject,g),x(L.dstFilePath,_),x(L.dstSymbolName,$)),J={dstFilePath:N,dstSymbolName:w};if(z!==void 0)J.dstProject=z;this.db.drizzleDb.update(L).set(J).where(Q).run()}}import{err as Eg}from"@zipbul/result";import{subscribe as n$}from"@parcel/watcher";import gg from"path";var H$=["**/.git/**",`**/${Yu}/**`,"**/dist/**","**/node_modules/**"],B$=new Set(["package.json","tsconfig.json"]);function L$(u){return u.replaceAll("\\","/")}function D$(u){if(u==="update")return"change";if(u==="create")return"create";return"delete"}class _g{#u;#g;#_;#N;#$;#J;constructor(u,g=n$,_=console){this.#g=u.projectRoot,this.#_=[...H$,...u.ignorePatterns??[]],this.#N=new Set((u.extensions??[".ts",".mts",".cts"]).map(($)=>$.toLowerCase())),this.#$=g,this.#J=_}async start(u){try{this.#u=await this.#$(this.#g,(g,_)=>{if(g){this.#J.error(e("watcher","Callback error",g));return}try{for(let $ of _){let N=L$(gg.relative(this.#g,$.path));if(N.startsWith(".."))continue;let w=gg.basename(N),z=gg.extname(N).toLowerCase();if(!B$.has(w)&&!this.#N.has(z))continue;if(N.endsWith(".d.ts"))continue;u({eventType:D$($.type),filePath:N})}}catch($){this.#J.error(e("watcher","Callback error",$))}},{ignore:this.#_})}catch(g){return Eg(e("watcher","Failed to subscribe watcher",g))}}async close(){if(!this.#u)return;try{await this.#u.unsubscribe(),this.#u=void 0}catch(u){return Eg(e("watcher","Failed to close watcher",u))}}}import $g from"path";import{promises as A$}from"fs";var I$=["**/node_modules/**","**/.git/**",`**/${Yu}/**`,"**/dist/**"];async function bu(u){let g=[];for await(let _ of A$.glob("**/package.json",{cwd:u,exclude:I$})){let $=$g.dirname(_).replaceAll("\\","/"),N=$g.join(u,_),w=await Bun.file(N).json(),z=typeof w?.name==="string"&&w.name.length>0?w.name:$g.basename($==="."?u:$);g.push({dir:$,project:z})}return g.sort((_,$)=>$.dir.length-_.dir.length),g}function l(u,g,_="default"){let $=u.replaceAll("\\","/");for(let N of g){if(N.dir===".")return N.project;if($===N.dir||$.startsWith(`${N.dir}/`))return N.project}return _}import vg from"path";var Vu=new Map;async function C$(u){let g=Bun.file(u);if(!await g.exists())return null;try{let _=await g.text(),$=Bun.JSONC.parse(_);return typeof $==="object"&&$!==null?$:null}catch{return null}}async function Ru(u){if(Vu.has(u))return Vu.get(u)??null;let g=vg.join(u,"tsconfig.json"),_=await C$(g);if(!_)return Vu.set(u,null),null;let $=typeof _.compilerOptions==="object"&&_.compilerOptions!==null?_.compilerOptions:null;if(!$)return Vu.set(u,null),null;let N=typeof $.baseUrl==="string"?$.baseUrl:null,w=typeof $.paths==="object"&&$.paths!==null?$.paths:null;if(!N&&!w)return Vu.set(u,null),null;let z=N?vg.resolve(u,N):u,Q=new Map;if(w)for(let[Y,O]of Object.entries(w)){if(!Array.isArray(O))continue;let W=O.filter((Z)=>typeof Z==="string");Q.set(Y,W)}let J={baseUrl:z,paths:Q};return Vu.set(u,J),J}function fu(u){if(u){Vu.delete(u);return}Vu.clear()}import Pg from"path";function yu(u,g){return Pg.relative(u,g).replaceAll("\\","/")}function Bu(u,g){return Pg.resolve(u,g)}function Ju(u){let g=Bun.hash.xxHash64(u);return BigInt.asUintN(64,BigInt(g)).toString(16).padStart(16,"0")}import{isErr as dg}from"@zipbul/result";import{err as S$}from"@zipbul/result";import{parseSync as R$}from"oxc-parser";function Tu(u,g,_,$=R$){try{let{program:N,errors:w,comments:z}=$(u,g,_);return{filePath:u,program:N,errors:w,comments:z,sourceText:g}}catch(N){return S$(e("parse",`Failed to parse file: ${u}`,N))}}import{promises as T$}from"fs";import{join as k$}from"path";async function bg(u){let{projectRoot:g,extensions:_,ignorePatterns:$,fileRepo:N}=u,w=N.getFilesMap(),z=new Set,Q=[],J=[],Y=$.map((W)=>new Bun.Glob(W));for await(let W of T$.glob("**/*",{cwd:g})){if(!_.some((V)=>W.endsWith(V)))continue;if(W.startsWith("node_modules/")||W.includes("/node_modules/"))continue;if(Y.some((V)=>V.match(W)))continue;z.add(W);let Z=k$(g,W),n=Bun.file(Z),{size:A,lastModified:D}=n,k=w.get(W);if(!k){let V=await n.text(),K=Ju(V);Q.push({filePath:W,contentHash:K,mtimeMs:D,size:A});continue}if(k.mtimeMs===D&&k.size===A){J.push({filePath:W,contentHash:k.contentHash,mtimeMs:D,size:A});continue}let G=await n.text(),i=Ju(G);if(i===k.contentHash)J.push({filePath:W,contentHash:i,mtimeMs:D,size:A});else Q.push({filePath:W,contentHash:i,mtimeMs:D,size:A})}let O=[];for(let W of w.keys())if(!z.has(W))O.push(W);return{changed:Q,unchanged:J,deleted:O}}function iu(u){let g=[0];for(let _=0;_<u.length;_++)if(u[_]===`
3
+ `)g.push(_+1);return g}function Nu(u,g){let _=0,$=u.length-1;while(_<$){let N=_+$+1>>1;if(u[N]<=g)_=N;else $=N-1}return{line:_+1,column:g-u[_]}}import{err as F$}from"@zipbul/result";import{parse as q$}from"comment-parser";function mu(u){try{let g=u.trim();if(g.startsWith("/**"))g=g.slice(3);if(g.endsWith("*/"))g=g.slice(0,-2);let $=q$(`/** ${g} */`)[0]??{description:"",tags:[]};return{description:($.description??"").trim(),tags:($.tags??[]).map((N)=>({tag:N.tag??"",name:N.name??"",type:N.type??"",description:N.description??"",optional:N.optional??!1,...N.default!==void 0?{default:N.default}:{}}))}}catch(g){return F$(e("parse","Failed to parse JSDoc comment",g))}}import{isErr as G$}from"@zipbul/result";function Lu(u){let{program:g,sourceText:_,comments:$}=u,N=iu(_),w=$.filter((V)=>V.type==="Block"&&V.value.startsWith("*")).sort((V,K)=>V.end-K.end),z=g.body.map((V)=>V.start??0).sort((V,K)=>V-K);function Q(V,K){return{start:Nu(N,V),end:Nu(N,K)}}function J(V){let K=0,M=w.length-1,R=-1;while(K<=M){let C=K+M>>>1;if(w[C].end<=V)R=C,K=C+1;else M=C-1}if(R<0)return;let I=w[R];K=0,M=z.length-1;while(K<=M){let C=K+M>>>1,v=z[C];if(v<=I.end)K=C+1;else if(v>=V)M=C-1;else return}return`/*${I.value}*/`}function Y(V){if(!V)return;let K=V.typeAnnotation??V;return _.slice(K.start,K.end)}function O(V){if(!V||V.length===0)return[];return V.map((K)=>{let M=K.expression;if(!M)return{name:"unknown"};if(M.type==="CallExpression"){let R=M.callee?.name??M.callee?.property?.name??"unknown",I=(M.arguments??[]).map((C)=>_.slice(C.start,C.end));return{name:R,arguments:I.length>0?I:void 0}}if(M.type==="Identifier")return{name:M.name??"unknown"};return{name:_.slice(M.start,M.end)}})}function W(V){let K=V.type==="TSParameterProperty"?V.parameter:V;if(K?.type==="RestElement"){let X=`...${K.argument?.name??"unknown"}`,B=K.typeAnnotation,S=B?Y(B):void 0,H={name:X,isOptional:!1};if(S)H.type=S;return H}if(K?.type==="AssignmentPattern"){let{left:j,right:X}=K,B=j?.name??"unknown",S=j?.typeAnnotation,H=S?Y(S):void 0,P=_.slice(X.start,X.end),q=O(j?.decorators??[]),c={name:B,isOptional:!0,defaultValue:P};if(H)c.type=H;if(q.length>0)c.decorators=q;return c}let M=K?.name??K?.pattern?.name??"unknown",R=!!K?.optional,I=K?.typeAnnotation,C=I?Y(I):void 0,v=O(K?.decorators??[]),y={name:M,isOptional:R};if(C)y.type=C;if(v.length>0)y.decorators=v;return y}function Z(V,K){let M=[];if(K?.async)M.push("async");if(V.static)M.push("static");if(V.abstract)M.push("abstract");if(V.readonly)M.push("readonly");if(V.override)M.push("override");if(V.declare)M.push("declare");if(V.const)M.push("const");let R=V.accessibility;if(R==="private")M.push("private");else if(R==="protected")M.push("protected");else if(R==="public")M.push("public");return M}function n(V){let K=[];if(V.superClass){let R=_.slice(V.superClass.start,V.superClass.end);K.push({kind:"extends",name:R})}let M=V.implements??[];for(let R of M){let I=R.expression??R,C=_.slice(I.start,I.end);K.push({kind:"implements",name:C})}return K}function A(V){let K=[];for(let M of V.extends??[]){let R=M.expression??M,I=_.slice(R.start,R.end);K.push({kind:"extends",name:I})}return K}function D(V){let K=[];for(let M of V)if(M.type==="MethodDefinition"){let R=M.key?.name??"unknown",I=M.value,C=M.kind??"method",v=C==="constructor"?"constructor":C==="get"?"getter":C==="set"?"setter":"method",y=Z(M,I),j=(I?.params??[]).map(W),X=Y(I?.returnType),B={kind:"method",name:R,span:Q(M.start,M.end),isExported:!1,methodKind:v,modifiers:y,parameters:j.length>0?j:void 0,returnType:X};K.push(B)}else if(M.type==="PropertyDefinition"){let R=M.key?.name??"unknown",I=Z(M),C={kind:"property",name:R,span:Q(M.start,M.end),isExported:!1,modifiers:I};K.push(C)}return K}function k(V){let K=[];for(let M of V)if(M.type==="TSMethodSignature"){let R=M.key?.name??"unknown",I=(M.params??[]).map(W),C=Y(M.returnType);K.push({kind:"method",name:R,span:Q(M.start,M.end),isExported:!1,modifiers:[],methodKind:"method",parameters:I.length>0?I:void 0,returnType:C})}else if(M.type==="TSPropertySignature"){let R=M.key?.name??"unknown",I=Y(M.typeAnnotation),C={kind:"property",name:R,span:Q(M.start,M.end),isExported:!1,modifiers:M.readonly?["readonly"]:[],returnType:I};K.push(C)}return K}function G(V,K){let M=V.type??"";if(M==="FunctionDeclaration"){let R=V.id?.name??"default",I=(V.params??[]).map(W),C=Y(V.returnType),v=Z(V,V),y=O(V.decorators??[]),j=V.typeParameters?.params?.flatMap((B)=>{let S=B.name?.name;return S?[S]:[]})||void 0,X={kind:"function",name:R,span:Q(V.start,V.end),isExported:K,modifiers:v,parameters:I.length>0?I:void 0,returnType:C,decorators:y.length>0?y:void 0};if(j&&j.length>0)X.typeParameters=j;return X}if(M==="ClassDeclaration"||M==="ClassExpression"){let R=V.id?.name??"default",I=n(V),C=D(V.body?.body??[]),v=O(V.decorators??[]),y=Z(V,V),j=V.typeParameters?.params?.flatMap((B)=>{let S=B.name?.name;return S?[S]:[]})||void 0,X={kind:"class",name:R,span:Q(V.start,V.end),isExported:K,modifiers:y,heritage:I.length>0?I:void 0,members:C.length>0?C:void 0,decorators:v.length>0?v:void 0};if(j&&j.length>0)X.typeParameters=j;return X}if(M==="VariableDeclaration"){let R=[];for(let I of V.declarations??[]){let{id:C,init:v}=I;if(C?.type==="ObjectPattern"){for(let H of C.properties??[]){let P=H.value?.name??H.key?.name??"unknown";R.push({kind:"variable",name:P,span:Q(H.start??I.start,H.end??I.end),isExported:K,modifiers:[]})}continue}if(C?.type==="ArrayPattern"){for(let H of C.elements??[]){if(!H||H.type!=="Identifier")continue;let P=H.name??"unknown";R.push({kind:"variable",name:P,span:Q(H.start??I.start,H.end??I.end),isExported:K,modifiers:[]})}continue}let y=C?.name??"unknown",j="variable",X,B;if(v?.type==="FunctionExpression"||v?.type==="ArrowFunctionExpression")j="function",X=(v.params??[]).map(W),B=Y(v.returnType);let S=[];R.push({kind:j,name:y,span:Q(I.start,I.end),isExported:K,modifiers:S,parameters:X,returnType:B})}if(R.length===0)return null;if(R.length===1)return R[0];return R}if(M==="TSTypeAliasDeclaration")return{kind:"type",name:V.id?.name??"unknown",span:Q(V.start,V.end),isExported:K,modifiers:[]};if(M==="TSInterfaceDeclaration"){let R=V.id?.name??"unknown",I=A(V),C=k(V.body?.body??[]),v=V.typeParameters?.params?.flatMap((j)=>{let X=j.name?.name;return X?[X]:[]})||void 0,y={kind:"interface",name:R,span:Q(V.start,V.end),isExported:K,modifiers:[],heritage:I.length>0?I:void 0,members:C.length>0?C:void 0};if(v&&v.length>0)y.typeParameters=v;return y}if(M==="TSEnumDeclaration"){let R=V.id?.name??"unknown",I=Z(V),v=(V.body?.members??[]).map((y)=>({kind:"property",name:y.id?.name??y.id?.value??"unknown",span:Q(y.start,y.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:R,span:Q(V.start,V.end),isExported:K,modifiers:I,members:v.length>0?v:void 0}}return null}let i=[];for(let V of g.body){let K=null,M=V,R=typeof M.type==="string"?M.type:"";if(R==="ExportNamedDeclaration"){let C=V;if(C.declaration){if(K=G(C.declaration,!0),K&&!Array.isArray(K))K.span=Q(C.start,C.end);else if(Array.isArray(K))for(let v of K)v.span=Q(C.start,C.end)}}else if(R==="ExportDefaultDeclaration"){let C=V,v=C.declaration;if(v){if(K=G(v,!0),K&&!Array.isArray(K))K.name=v.id?.name??"default",K.isExported=!0,K.span=Q(C.start,C.end)}}else K=G(V,!1);let I=Array.isArray(K)?K:K?[K]:[];for(let C of I){let v=V.start??0,y=J(v);if(y){let j=mu(y);if(!G$(j))C.jsDoc=j}i.push(C)}}return i}function j$(u){if(u.kind==="function"||u.kind==="method"){let g=u.parameters?.length??0,_=u.modifiers.includes("async")?1:0;return`params:${g}|async:${_}`}return null}function E$(u){let g={};if(u.jsDoc)g.jsDoc=u.jsDoc;if(u.kind==="function"||u.kind==="method"){if(u.parameters!==void 0)g.parameters=u.parameters;if(u.returnType!==void 0)g.returnType=u.returnType}if(u.heritage?.length)g.heritage=u.heritage;if(u.decorators?.length)g.decorators=u.decorators;if(u.typeParameters?.length)g.typeParameters=u.typeParameters;if(u.modifiers?.length)g.modifiers=u.modifiers;if(u.members?.length)g.members=u.members.map((_)=>{let $=_.modifiers.find((N)=>N==="private"||N==="protected"||N==="public");return{name:_.name,kind:_.methodKind??_.kind,type:_.returnType,visibility:$,isStatic:_.modifiers.includes("static")||void 0,isReadonly:_.modifiers.includes("readonly")||void 0}});return Object.keys(g).length>0?JSON.stringify(g):null}function v$(u){let g=[u.kind];if(u.modifiers.length)g.push(`mod:${[...u.modifiers].sort().join(",")}`);if(u.typeParameters?.length)g.push(`tp:${u.typeParameters.length}`);if(u.heritage?.length){let _=[...u.heritage].sort(($,N)=>$.name.localeCompare(N.name)).map(($)=>`${$.kind}:${$.name}`).join(",");g.push(`her:${_}`)}if(u.decorators?.length)g.push(`dec:${[...u.decorators].map((_)=>_.name).sort().join(",")}`);if(u.methodKind)g.push(`mk:${u.methodKind}`);if(u.parameters)g.push(`p:${u.parameters.length}`);if(u.returnType)g.push(`rt:${u.returnType}`);if(u.members?.length){let _=u.members.map(($)=>`${$.kind}:${$.modifiers.join(",")}:${$.parameters?.length??""}:${$.returnType??""}`).sort().join(";");g.push(`mem:${u.members.length}:${Ju(_)}`)}return Ju(g.join("|"))}function fg(u,g,_,$,N){let w=j$(u),z=Ju(`${g}|${u.kind}|${w??""}`),Q=v$(u);return{project:_,filePath:$,kind:u.kind,name:g,startLine:u.span.start.line,startColumn:u.span.start.column,endLine:u.span.end.line,endColumn:u.span.end.column,isExported:u.isExported?1:0,signature:w,fingerprint:z,detailJson:E$(u),contentHash:N,indexedAt:new Date().toISOString(),structuralFingerprint:Q}}function Ng(u){let{parsed:g,project:_,filePath:$,contentHash:N,symbolRepo:w}=u,z=Lu(g),Q=[];for(let J of z){Q.push(fg(J,J.name,_,$,N));for(let Y of J.members??[])Q.push(fg(Y,`${J.name}.${Y.name}`,_,$,N))}w.replaceFileSymbols(_,$,N,Q)}import{resolve as Jg,dirname as P$,extname as b$}from"path";function Zu(u,g,_){let $=(N)=>{let w=b$(N);if(w==="")return[N+".ts",N+".d.ts",N+"/index.ts",N+"/index.d.ts",N+".mts",N+"/index.mts",N+".cts",N+"/index.cts"];if(w===".js")return[N.slice(0,-3)+".ts"];if(w===".mjs")return[N.slice(0,-4)+".mts"];if(w===".cjs")return[N.slice(0,-4)+".cts"];return[N]};if(g.startsWith(".")){let N=Jg(P$(u),g);return $(N)}if(_)for(let[N,w]of _.paths){if(w.length===0)continue;let z=N.indexOf("*");if(z===-1){if(g===N){let Q=[];for(let J of w)Q.push(...$(Jg(_.baseUrl,J)));return Q}}else{let Q=N.slice(0,z),J=N.slice(z+1);if(g.startsWith(Q)&&(J===""||g.endsWith(J))){let Y=g.slice(Q.length,J===""?void 0:g.length-J.length),O=[];for(let W of w)O.push(...$(Jg(_.baseUrl,W.replace("*",Y))));return O}}}return[]}function yg(u,g,_,$=Zu){let N=new Map,w=u.body??[];for(let z of w){if(z.type!=="ImportDeclaration")continue;let Q=z.source?.value??"",J=$(g,Q,_);if(J.length===0)continue;let Y=J[0],O=z.specifiers??[];for(let W of O)switch(W.type){case"ImportSpecifier":N.set(W.local.name,{path:Y,importedName:W.imported.name});break;case"ImportDefaultSpecifier":N.set(W.local.name,{path:Y,importedName:"default"});break;case"ImportNamespaceSpecifier":N.set(W.local.name,{path:Y,importedName:"*"});break}}return N}var f$=new Set(["loc","start","end","scope"]);function Du(u,g){if(!u||typeof u!=="object")return;if(Array.isArray(u)){for(let $ of u)Du($,g);return}let _=u;g(_);for(let $ of Object.keys(_)){if(f$.has($))continue;let N=_[$];if(N&&typeof N==="object")Du(N,g)}}function ig(u){if(!u||typeof u!=="object"||Array.isArray(u))return null;let g=u;if((g.type==="StringLiteral"||g.type==="Literal")&&typeof g.value==="string")return g.value;return null}function Ku(u){if(!u||typeof u!=="object"||Array.isArray(u))return null;let g=u;if(g.type==="Identifier"){let _=g.name;return{root:_,parts:[],full:_}}if(g.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(g.type==="Super")return{root:"super",parts:[],full:"super"};if(g.type==="MemberExpression"){let _=[],$=g;while($.type==="MemberExpression"){let z=$.property;if(!z||typeof z.name!=="string")return null;_.push(z.name),$=$.object}let N;if($.type==="Identifier")N=$.name;else if($.type==="ThisExpression")N="this";else if($.type==="Super")N="super";else return null;_.reverse();let w=[N,..._].join(".");return{root:N,parts:_,full:w}}return null}function mg(u,g,_,$=Zu){let N=[],w=u.body??[];for(let z of w){if(z.type==="ImportDeclaration"){let Q=z.source?.value??"",J=$(g,Q,_);if(J.length===0)continue;let Y=J[0],O=z.importKind==="type",W=z.specifiers??[];if(W.length===0){let Z={};if(O)Z.isType=!0;N.push({type:O?"type-references":"imports",srcFilePath:g,srcSymbolName:null,dstFilePath:Y,dstSymbolName:null,...Object.keys(Z).length>0?{metaJson:JSON.stringify(Z)}:{}})}else for(let Z of W){let n=Z.type,A=O||Z.importKind==="type",D={};if(A)D.isType=!0;let k,G;if(n==="ImportDefaultSpecifier")k="default",G=Z.local.name;else if(n==="ImportNamespaceSpecifier")k="*",G=Z.local.name,D.importKind="namespace";else k=Z.imported.name,G=Z.local.name;N.push({type:A?"type-references":"imports",srcFilePath:g,srcSymbolName:G,dstFilePath:Y,dstSymbolName:k,...Object.keys(D).length>0?{metaJson:JSON.stringify(D)}:{}})}continue}if(z.type==="ExportAllDeclaration"&&z.source){let Q=z.source?.value??"",J=$(g,Q,_);if(J.length===0)continue;let Y=J[0],O=z.exportKind==="type",W={isReExport:!0};if(O)W.isType=!0;N.push({type:O?"type-references":"re-exports",srcFilePath:g,srcSymbolName:null,dstFilePath:Y,dstSymbolName:null,metaJson:JSON.stringify(W)});continue}if(z.type==="ExportNamedDeclaration"&&z.source){let Q=z.source?.value??"",J=$(g,Q,_);if(J.length===0)continue;let Y=J[0],O=z.exportKind==="type",n={isReExport:!0,specifiers:(z.specifiers??[]).map((A)=>({local:A.local.name,exported:A.exported.name}))};if(O)n.isType=!0;N.push({type:O?"type-references":"re-exports",srcFilePath:g,srcSymbolName:null,dstFilePath:Y,dstSymbolName:null,metaJson:JSON.stringify(n)})}}return Du(u,(z)=>{if(z.type!=="ImportExpression")return;let Q=ig(z.source);if(!Q)return;let J=$(g,Q,_);if(J.length===0)return;let Y=J[0];N.push({type:"imports",srcFilePath:g,srcSymbolName:null,dstFilePath:Y,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),N}function hg(u,g,_){let $=[],N=[],w=[];function z(){if(N.length>0)return N[N.length-1]??null;return null}function Q(Y){if(!Y)return null;let O=_.get(Y.root);if(Y.parts.length===0){if(O)return{dstFilePath:O.path,dstSymbolName:O.importedName,resolution:"import"};return{dstFilePath:g,dstSymbolName:Y.root,resolution:"local"}}else{if(O&&O.importedName==="*"){let W=Y.parts[Y.parts.length-1];return{dstFilePath:O.path,dstSymbolName:W,resolution:"namespace"}}return{dstFilePath:g,dstSymbolName:Y.full,resolution:"local-member"}}}function J(Y){if(!Y||typeof Y!=="object")return;if(Array.isArray(Y)){for(let Z of Y)J(Z);return}let O=Y,W=typeof O.type==="string"?O.type:"";if(W==="ClassDeclaration"||W==="ClassExpression"){let Z=O,n=Z.id?.name??"AnonymousClass";w.push(n),J(Z.body),w.pop();return}if(W==="FunctionDeclaration"){let Z=O,n=Z.id?.name??"anonymous";N.push(n),J(Z.body),N.pop();return}if(W==="VariableDeclarator"&&O.init&&(O.init?.type==="FunctionExpression"||O.init?.type==="ArrowFunctionExpression")){let Z=O,n=Z.id?.name??"anonymous";N.push(n),J(Z.init?.body??Z.init),N.pop();return}if(W==="MethodDefinition"&&O.value){let Z=O,n=w[w.length-1]??"",A=Z.key?.name??"anonymous",D=n?`${n}.${A}`:A;N.push(D),J(Z.value?.body),N.pop();return}if(W==="FunctionExpression"||W==="ArrowFunctionExpression"){let Z=z(),n=Z?`${Z}.<anonymous>`:"<anonymous>";N.push(n),J(O.body),N.pop();return}if(W==="CallExpression"){let Z=O,n=Ku(Z.callee),A=Q(n);if(A){let D=z(),k={};if(D===null)k.scope="module";$.push({type:"calls",srcFilePath:g,srcSymbolName:D,dstFilePath:A.dstFilePath,dstSymbolName:A.dstSymbolName,...Object.keys(k).length>0?{metaJson:JSON.stringify(k)}:{}})}J(Z.callee);for(let D of Z.arguments??[])J(D);return}if(W==="NewExpression"){let Z=O,n=Ku(Z.callee),A=Q(n);if(A){let D=z(),k={isNew:!0};if(D===null)k.scope="module";$.push({type:"calls",srcFilePath:g,srcSymbolName:D,dstFilePath:A.dstFilePath,dstSymbolName:A.dstSymbolName,metaJson:JSON.stringify(k)})}for(let D of Z.arguments??[])J(D);return}for(let Z of Object.keys(O)){if(Z==="loc"||Z==="start"||Z==="end"||Z==="scope")continue;let n=O[Z];if(n&&typeof n==="object")J(n)}}return J(u),$}function xg(u,g,_){let $=[];return Du(u,(N)=>{if(N.type==="TSInterfaceDeclaration"){let Q=N.id?.name??"AnonymousInterface",J=N.extends??[];for(let Y of J){let O=Y.expression??Y,W=Ku(O);if(!W)continue;let Z=Qg(W,g,_);$.push({type:"extends",srcFilePath:g,srcSymbolName:Q,...Z})}return}if(N.type!=="ClassDeclaration"&&N.type!=="ClassExpression")return;let w=N.id?.name??"AnonymousClass";if(N.superClass){let Q=Ku(N.superClass);if(Q){let J=Qg(Q,g,_);$.push({type:"extends",srcFilePath:g,srcSymbolName:w,...J})}}let z=N.implements??[];for(let Q of z){let J=Q.expression??Q,Y=Ku(J);if(!Y)continue;let O=Qg(Y,g,_);$.push({type:"implements",srcFilePath:g,srcSymbolName:w,...O})}}),$}function Qg(u,g,_){let $=_.get(u.root);if($){if($.importedName==="*"){let N=u.parts[u.parts.length-1]??u.root;return{dstFilePath:$.path,dstSymbolName:N,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:$.path,dstSymbolName:u.parts.length>0?u.full:$.importedName}}return{dstFilePath:g,dstSymbolName:u.full,metaJson:JSON.stringify({isLocal:!0})}}function hu(u,g,_,$=Zu){let N=yg(u,g,_,$),w=mg(u,g,_,$),z=hg(u,g,N),Q=xg(u,g,N);return[...w,...z,...Q]}function zg(u){let{ast:g,project:_,filePath:$,relationRepo:N,projectRoot:w,tsconfigPaths:z,knownFiles:Q,boundaries:J}=u,Y=Bu(w,$),W=hu(g,Y,z,Q?(n,A,D)=>{let k=Zu(n,A,D);for(let G of k){let i=yu(w,G);if(J){let V=l(i,J);if(Q.has(`${V}::${i}`))return[G]}else if(Q.has(`${_}::${i}`))return[G]}return[]}:void 0),Z=[];for(let n of W){let A=yu(w,n.dstFilePath);if(A.startsWith(".."))continue;let D=yu(w,n.srcFilePath),k=J?l(A,J):_;Z.push({project:_,type:n.type,srcFilePath:D,srcSymbolName:n.srcSymbolName??null,dstProject:k,dstFilePath:A,dstSymbolName:n.dstSymbolName??null,metaJson:n.metaJson??null})}return N.replaceFileRelations(_,$,Z),Z.length}import{isErr as y$}from"@zipbul/result";var pg=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function i$(u){let g=Lu(u),_=[];for(let $ of g){_.push({name:$.name,startLine:$.span.start.line});for(let N of $.members??[])_.push({name:`${$.name}.${N.name}`,startLine:N.span.start.line})}return _.sort(($,N)=>$.startLine-N.startLine),_}function wg(u,g,_){let $=0,N=u.length-1;while($<=N){let w=$+N>>1;if(u[w].startLine<=g)$=w+1;else N=w-1}if($<u.length){let w=u[$];if(w.startLine-g<=_)return w.name}return null}function xu(u,g,_){let $=Nu(u,g),N=Nu(u,_);return{start:$,end:N}}function lg(u){let{comments:g,sourceText:_}=u;if(!g.length)return[];let $=iu(_),N=i$(u),w=[],z=[...g].sort((J,Y)=>J.start-Y.start),Q=null;for(let J of z)if(J.type==="Block"&&J.value.startsWith("*")){Q=null;let Y=`/*${J.value}*/`,O=mu(Y);if(y$(O))continue;let W=O;if(!W.tags?.length)continue;let Z=Nu($,J.end),n=wg(N,Z.line,3),A=_.slice(J.start,J.end);for(let D of W.tags){let k=[D.name,D.description].filter(Boolean).join(" "),G=`@${D.tag}`,i=A.indexOf(G),V;if(i>=0){let K=J.start+i,M=_.indexOf(`
4
+ `,K),R=M>=0?Math.min(M,J.end):J.end;V=xu($,K,R)}else V=xu($,J.start,J.end);w.push({tag:D.tag,value:k,source:"jsdoc",span:V,symbolName:n})}}else if(J.type==="Block"){Q=null;let Y=J.value.split(`
5
+ `),O=0;for(let W of Y){let Z=W.replace(/^\s*\*?\s?/,""),n=pg.exec(Z);if(n){let A=n[1],D=n[2]?.trim()??"",k=`@${A}`,G=W.indexOf(k),i=J.start+2+O+(G>=0?G:0),V=J.start+2+O+W.length,K=xu($,i,V),M=Nu($,J.end),R=wg(N,M.line,3);w.push({tag:A,value:D,source:"block",span:K,symbolName:R})}O+=W.length+1}}else{let Y=J.value,O=pg.exec(Y),W=Nu($,J.start),Z=Nu($,J.end);if(O){let n=O[1],A=O[2]?.trim()??"",D=`@${n}`,k=Y.indexOf(D),G=J.start+2+(k>=0?k:0),i=xu($,G,J.end),V=wg(N,Z.line,3),K={tag:n,value:A,source:"line",span:i,symbolName:V};w.push(K),Q={annotation:K,endLine:Z.line}}else if(Q&&W.line===Q.endLine+1){let n=Y.trim();if(n)Q.annotation.value+=" "+n,Q.annotation.span.end=Nu($,J.end),Q.endLine=Z.line}else Q=null}return w}function Og(u){let{parsed:g,project:_,filePath:$,annotationRepo:N}=u,w=lg(g);if(N.deleteFileAnnotations(_,$),!w.length)return 0;let z=new Date().toISOString(),Q=w.map((J)=>({project:_,filePath:$,tag:J.tag,value:J.value,source:J.source,symbolName:J.symbolName,startLine:J.span.start.line,startColumn:J.span.start.column,endLine:J.span.end.line,endColumn:J.span.end.column,indexedAt:z}));return N.insertBatch(_,$,Q),w.length}function rg(u,g){let _=[],$=[],N=[];for(let[O,W]of g)if(!u.has(O))_.push({name:W.name,filePath:W.filePath,kind:W.kind,fingerprint:W.fingerprint});for(let[O,W]of u)if(!g.has(O))$.push({name:W.name,filePath:W.filePath,kind:W.kind,fingerprint:W.fingerprint});if(!_.length||!$.length)return{renamed:N,added:_,removed:$};let w=new Map,z=new Map;for(let O of _){let W=w.get(O.filePath)??[];W.push(O),w.set(O.filePath,W)}for(let O of $){let W=z.get(O.filePath)??[];W.push(O),z.set(O.filePath,W)}let Q=new Set,J=new Set;for(let[O,W]of w){let Z=z.get(O);if(!Z)continue;for(let n of new Set(W.map((A)=>A.kind))){let A=W.filter((V)=>V.kind===n&&!Q.has(V)),D=Z.filter((V)=>V.kind===n&&!J.has(V));if(!A.length||!D.length)continue;let k=(V,K)=>{return K.get(`${V.filePath}::${V.name}`)?.structuralFingerprint??null},G=(V,K)=>{return K.get(`${V.filePath}::${V.name}`)?.startLine??0},i=new Map;for(let V of D){let K=k(V,u);if(!K)continue;let M=i.get(K)??[];M.push(V),i.set(K,M)}for(let V of A){if(Q.has(V))continue;let K=k(V,g);if(!K)continue;let M=i.get(K);if(!M)continue;let R=M.filter((C)=>!J.has(C));if(!R.length)continue;let I=R[0];if(R.length>1){let C=G(V,g),v=Math.abs(G(I,u)-C);for(let y=1;y<R.length;y++){let j=Math.abs(G(R[y],u)-C);if(j<v)v=j,I=R[y]}}N.push({oldName:I.name,newName:V.name,filePath:O,kind:n}),Q.add(V),J.add(I)}}}let Y=N.filter((O)=>!O.oldName.includes("."));for(let O of Y){let W=`${O.oldName}.`,Z=`${O.newName}.`,n=$.filter((D)=>D.filePath===O.filePath&&D.name.startsWith(W)&&!J.has(D)),A=_.filter((D)=>D.filePath===O.filePath&&D.name.startsWith(Z)&&!Q.has(D));for(let D of n){let k=D.name.slice(W.length),G=A.find((i)=>i.name.slice(Z.length)===k);if(G)N.push({oldName:D.name,newName:G.name,filePath:O.filePath,kind:D.kind}),Q.add(G),J.add(D)}}return{renamed:N,added:_.filter((O)=>!Q.has(O)),removed:$.filter((O)=>!J.has(O))}}var m$=100,tg=50;class Wg{opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;lastPruneAt=0;constructor(u){this.opts=u,this.logger=u.logger??console,this.tsconfigPathsRaw=Ru(u.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(u){return this.startIndex(u,!1)}onIndexed(u){return this.callbacks.add(u),()=>this.callbacks.delete(u)}handleWatcherEvent(u){if(u.filePath.endsWith("tsconfig.json")){fu(this.opts.projectRoot),this.tsconfigPathsRaw=Ru(this.opts.projectRoot),this.fullIndex().catch((g)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",g)});return}if(u.filePath.endsWith("package.json")){let g=this.opts.discoverProjectsFn??bu;this.boundariesRefresh=g(this.opts.projectRoot).then((_)=>{this.opts.boundaries=_})}if(this.pendingEvents.push(u),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},m$)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(u,g){if(this.indexingLock){if(g)return this.pendingFullIndex=!0,new Promise(($,N)=>{this.pendingFullIndexWaiters.push({resolve:$,reject:N})});return this.currentIndexing}this.indexingLock=!0;let _=this.doIndex(u,g).then(($)=>{return this.fireCallbacks($),$}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let $=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((N)=>{for(let w of $)w.resolve(N)}).catch((N)=>{for(let w of $)w.reject(N)})}else if(this.pendingEvents.length>0){let $=this.pendingEvents.splice(0);this.startIndex($,!1).catch((N)=>this.logger.error("[IndexCoordinator] incremental drain error",N))}});return this.currentIndexing=_,_}async doIndex(u,g){let _=Date.now(),{fileRepo:$,symbolRepo:N,relationRepo:w,dbConnection:z}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let Q,J;if(u!==void 0)Q=u.filter((X)=>X.eventType==="create"||X.eventType==="change").map((X)=>({filePath:X.filePath,contentHash:"",mtimeMs:0,size:0})),J=u.filter((X)=>X.eventType==="delete").map((X)=>X.filePath);else{let X=new Map;for(let S of this.opts.boundaries)for(let[H,P]of $.getFilesMap(S.project))X.set(H,P);let B=await bg({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>X}});Q=B.changed,J=B.deleted}let Y=await this.tsconfigPathsRaw??void 0,O=new Map;for(let X of J){let B=l(X,this.opts.boundaries),S=N.getFileSymbols(B,X);O.set(X,S)}let W=crypto.randomUUID(),Z=new Map,n=new Map,A=(X)=>({name:X.name,filePath:X.filePath,kind:X.kind,fingerprint:X.fingerprint,structuralFingerprint:X.structuralFingerprint??null,startLine:X.startLine});if(g)for(let X of this.opts.boundaries)for(let B of $.getAllFiles(X.project))for(let S of N.getFileSymbols(X.project,B.filePath))Z.set(`${S.filePath}::${S.name}`,A(S));else{for(let X of Q){let B=l(X.filePath,this.opts.boundaries);for(let S of N.getFileSymbols(B,X.filePath))Z.set(`${S.filePath}::${S.name}`,A(S))}for(let[,X]of O)for(let B of X)Z.set(`${B.filePath}::${B.name}`,A(B))}let{annotationRepo:D,changelogRepo:k}=this.opts,G=()=>{for(let X of J){let B=l(X,this.opts.boundaries);if(N.deleteFileSymbols(B,X),w.deleteFileRelations(B,X),D)D.deleteFileAnnotations(B,X);$.deleteFile(B,X)}},i=0,V=async()=>{let{projectRoot:X,boundaries:B}=this.opts,{parseCache:S}=this.opts,H=0,P=0,q=0,c=[],b=[];for(let E of Q)try{let T=Bu(X,E.filePath),s=Bun.file(T),o=await s.text(),Qu=E.contentHash||Ju(o),Wu=l(E.filePath,B);$.upsertFile({project:Wu,filePath:E.filePath,mtimeMs:s.lastModified,size:s.size,contentHash:Qu,updatedAt:new Date().toISOString(),lineCount:o.split(`
6
+ `).length});let Cu=(this.opts.parseSourceFn??Tu)(T,o);if(dg(Cu))throw Cu.data;let u$=Cu;b.push({filePath:E.filePath,text:o,contentHash:Qu,parsed:u$,project:Wu})}catch(T){this.logger.error(`[IndexCoordinator] Failed to prepare ${E.filePath}:`,T),c.push(E.filePath)}let h=new Set;for(let E of B)for(let[T]of $.getFilesMap(E.project))h.add(`${E.project}::${T}`);return z.transaction(()=>{for(let E of b){if(Ng({parsed:E.parsed,project:E.project,filePath:E.filePath,contentHash:E.contentHash,symbolRepo:N}),P+=zg({ast:E.parsed.program,project:E.project,filePath:E.filePath,relationRepo:w,projectRoot:X,tsconfigPaths:Y,knownFiles:h,boundaries:B}),D)q+=Og({parsed:E.parsed,project:E.project,filePath:E.filePath,annotationRepo:D});S.set(E.filePath,E.parsed),H+=N.getFileSymbols(E.project,E.filePath).length}}),{symbols:H,relations:P,annotations:q,failedFiles:c}},K=0,M=0,R=[];if(g){let{projectRoot:X,boundaries:B}=this.opts,{parseCache:S}=this.opts,H=[];for(let q=0;q<Q.length;q+=tg){let c=Q.slice(q,q+tg),b=await Promise.allSettled(c.map(async(h)=>{let E=Bu(X,h.filePath),T=Bun.file(E),s=await T.text(),o=h.contentHash||Ju(s);return{filePath:h.filePath,text:s,contentHash:o,mtimeMs:T.lastModified,size:T.size}}));for(let h=0;h<b.length;h++){let E=b[h];if(E.status==="fulfilled")H.push(E.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",E.reason),R.push(c[h].filePath)}}let P=[];z.transaction(()=>{for(let b of H){let h=l(b.filePath,B);$.deleteFile(h,b.filePath)}for(let b of J){let h=l(b,B);if(N.deleteFileSymbols(h,b),w.deleteFileRelations(h,b),D)D.deleteFileAnnotations(h,b);$.deleteFile(h,b)}for(let b of H){let h=l(b.filePath,B);$.upsertFile({project:h,filePath:b.filePath,mtimeMs:b.mtimeMs,size:b.size,contentHash:b.contentHash,updatedAt:new Date().toISOString(),lineCount:b.text.split(`
7
+ `).length})}let q=new Set;for(let b of B)for(let[h]of $.getFilesMap(b.project))q.add(`${b.project}::${h}`);let c=this.opts.parseSourceFn??Tu;for(let b of H){let h=l(b.filePath,B),E=c(Bu(X,b.filePath),b.text);if(dg(E))throw E.data;let T=E;if(P.push({filePath:b.filePath,parsed:T}),Ng({parsed:T,project:h,filePath:b.filePath,contentHash:b.contentHash,symbolRepo:N}),D)i+=Og({parsed:T,project:h,filePath:b.filePath,annotationRepo:D});M+=zg({ast:T.program,project:h,filePath:b.filePath,relationRepo:w,projectRoot:X,tsconfigPaths:Y,knownFiles:q,boundaries:B}),K+=N.getFileSymbols(h,b.filePath).length}});for(let q of P)S.set(q.filePath,q.parsed)}else{G();let X=await V();K=X.symbols,M=X.relations,i=X.annotations,R=X.failedFiles}for(let X of Q){let B=l(X.filePath,this.opts.boundaries);for(let S of N.getFileSymbols(B,X.filePath))n.set(`${S.filePath}::${S.name}`,A(S))}let I={added:[],modified:[],removed:[]};for(let[X,B]of n){let S=Z.get(X);if(!S)I.added.push({name:B.name,filePath:B.filePath,kind:B.kind});else if(S.fingerprint!==B.fingerprint)I.modified.push({name:B.name,filePath:B.filePath,kind:B.kind})}for(let[X,B]of Z)if(!n.has(X))I.removed.push({name:B.name,filePath:B.filePath,kind:B.kind});let C=rg(Z,n),v=new Set(C.renamed.map((X)=>`${X.filePath}::${X.oldName}`)),y=new Set(C.renamed.map((X)=>`${X.filePath}::${X.newName}`));I.added=I.added.filter((X)=>!y.has(`${X.filePath}::${X.name}`)),I.removed=I.removed.filter((X)=>!v.has(`${X.filePath}::${X.name}`));let j=[];if(!g){for(let[X,B]of O)for(let S of B){if(!S.fingerprint)continue;let H=l(X,this.opts.boundaries),P=N.getByFingerprint(H,S.fingerprint);if(P.length===1){let q=P[0];w.retargetRelations({dstProject:H,oldFile:X,oldSymbol:S.name,newFile:q.filePath,newSymbol:q.name}),j.push({name:q.name,filePath:q.filePath,kind:q.kind,oldFilePath:X})}}for(let X of C.removed){let S=Z.get(`${X.filePath}::${X.name}`)?.fingerprint;if(!S)continue;let H=l(X.filePath,this.opts.boundaries),P=N.getByFingerprint(H,S);if(P.length===1){let q=P[0];if(q.filePath!==X.filePath||q.name!==X.name)w.retargetRelations({dstProject:H,oldFile:X.filePath,oldSymbol:X.name,newFile:q.filePath,newSymbol:q.name}),j.push({name:q.name,filePath:q.filePath,kind:q.kind,oldFilePath:X.filePath})}}}if(j.length){let X=new Set(j.map((S)=>`${S.filePath}::${S.name}`)),B=new Set(j.map((S)=>`${S.oldFilePath}::${S.name}`));I.added=I.added.filter((S)=>!X.has(`${S.filePath}::${S.name}`)),I.removed=I.removed.filter((S)=>!B.has(`${S.filePath}::${S.name}`))}if(k){let X=new Date().toISOString(),B=g?1:0,S=[];for(let H of I.added){let P=`${H.filePath}::${H.name}`,q=n.get(P),c=l(H.filePath,this.opts.boundaries);S.push({project:c,changeType:"added",symbolName:H.name,symbolKind:H.kind,filePath:H.filePath,oldName:null,oldFilePath:null,fingerprint:q?.fingerprint??null,changedAt:X,isFullIndex:B,indexRunId:W})}for(let H of I.modified){let P=n.get(`${H.filePath}::${H.name}`),q=l(H.filePath,this.opts.boundaries);S.push({project:q,changeType:"modified",symbolName:H.name,symbolKind:H.kind,filePath:H.filePath,oldName:null,oldFilePath:null,fingerprint:P?.fingerprint??null,changedAt:X,isFullIndex:B,indexRunId:W})}for(let H of I.removed){let P=`${H.filePath}::${H.name}`,q=Z.get(P),c=l(H.filePath,this.opts.boundaries);S.push({project:c,changeType:"removed",symbolName:H.name,symbolKind:H.kind,filePath:H.filePath,oldName:null,oldFilePath:null,fingerprint:q?.fingerprint??null,changedAt:X,isFullIndex:B,indexRunId:W})}for(let H of C.renamed){let P=n.get(`${H.filePath}::${H.newName}`),q=l(H.filePath,this.opts.boundaries);S.push({project:q,changeType:"renamed",symbolName:H.newName,symbolKind:H.kind,filePath:H.filePath,oldName:H.oldName,oldFilePath:null,fingerprint:P?.fingerprint??null,changedAt:X,isFullIndex:B,indexRunId:W})}for(let H of j){let P=n.get(`${H.filePath}::${H.name}`),q=l(H.filePath,this.opts.boundaries);S.push({project:q,changeType:"moved",symbolName:H.name,symbolKind:H.kind,filePath:H.filePath,oldName:null,oldFilePath:H.oldFilePath,fingerprint:P?.fingerprint??null,changedAt:X,isFullIndex:B,indexRunId:W})}if(S.length)try{z.transaction(()=>{k.insertBatch(S)})}catch(H){this.logger.error("[IndexCoordinator] changelog insert failed:",H)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let H=new Date(Date.now()-2592000000).toISOString();try{for(let P of this.opts.boundaries)k.pruneOlderThan(P.project,H)}catch(P){this.logger.error("[IndexCoordinator] changelog pruning failed:",P)}}}return{indexedFiles:Q.length,removedFiles:J.length,totalSymbols:K,totalRelations:M,totalAnnotations:i,durationMs:Date.now()-_,changedFiles:Q.map((X)=>X.filePath),deletedFiles:[...J],failedFiles:R,changedSymbols:I}}fireCallbacks(u){for(let g of this.callbacks)try{g(u)}catch(_){this.logger.error("[IndexCoordinator] onIndexed callback threw:",_)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let u=this.pendingEvents.splice(0);this.startIndex(u,!1).catch((g)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",g))}}}function h$(u){try{return process.kill(u,0),!0}catch(g){if(typeof g==="object"&&g&&"code"in g)return g.code!=="ESRCH";return!0}}function x$(u){let g=new Date(u).getTime();return Number.isNaN(g)?0:g}function ag(u,g,_={}){let $=_.now??Date.now,N=_.isAlive??h$,w=_.staleAfterSeconds??60,z=_.instanceId;return u.immediateTransaction(()=>{let Q=u.selectOwner();if(!Q)return u.insertOwner(g,z),"owner";let J=Math.floor(($()-x$(Q.heartbeat_at))/1000),Y=N(Q.pid);if(Y&&z&&Q.instance_id&&Q.instance_id!==z&&Q.pid!==g)return u.replaceOwner(g,z),"owner";if(Y&&J<w)return"reader";return u.replaceOwner(g,z),"owner"})}function cg(u,g){u.deleteOwner(g)}function sg(u,g){u.touchOwner(g)}class ku{#u;#g=new Map;constructor(u){this.#u=Math.max(1,u)}get size(){return this.#g.size}has(u){return this.#g.has(u)}get(u){if(!this.#g.has(u))return;let g=this.#g.get(u);return this.#g.delete(u),this.#g.set(u,g),g}set(u,g){if(this.#g.has(u))this.#g.delete(u);if(this.#g.set(u,g),this.#g.size>this.#u){let _=this.#g.keys().next().value;if(_!==void 0)this.#g.delete(_)}}delete(u){return this.#g.delete(u)}clear(){this.#g.clear()}}class Yg{lru;constructor(u=500){this.lru=new ku(u)}get(u){return this.lru.get(u)}set(u,g){this.lru.set(u,g)}invalidate(u){this.lru.delete(u)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function Vg(u){let{symbolRepo:g,project:_,query:$}=u,N=$.project??_,w=$.limit??100,z={kind:$.kind,filePath:$.filePath,isExported:$.isExported,project:N,limit:w,resolvedType:$.resolvedType};if($.text)if($.exact)z.exactName=$.text;else{let J=Hu($.text);if(J)z.ftsQuery=J}if($.decorator)z.decorator=$.decorator;if($.regex)z.regex=$.regex;return g.searchByQuery(z).map((J)=>({id:J.id,filePath:J.filePath,kind:J.kind,name:J.name,span:{start:{line:J.startLine,column:J.startColumn},end:{line:J.endLine,column:J.endColumn}},isExported:J.isExported===1,signature:J.signature,fingerprint:J.fingerprint,detail:J.detailJson?(()=>{try{return JSON.parse(J.detailJson)}catch{return{}}})():{}}))}function Ug(u){let{relationRepo:g,project:_,query:$}=u,N=$.project??_,w=$.limit??500;return g.searchRelations({srcFilePath:$.srcFilePath,srcSymbolName:$.srcSymbolName,dstFilePath:$.dstFilePath,dstSymbolName:$.dstSymbolName,dstProject:$.dstProject,type:$.type,project:N,limit:w}).map((Q)=>{let J;if(Q.metaJson)try{J=JSON.parse(Q.metaJson)}catch{}return{type:Q.type,srcFilePath:Q.srcFilePath,srcSymbolName:Q.srcSymbolName,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,dstProject:Q.dstProject,metaJson:Q.metaJson??void 0,meta:J}})}import{findInFiles as p$,Lang as l$}from"@ast-grep/napi";async function Xg(u){if(u.filePaths.length===0)return[];let g=[];return await p$(l$.TypeScript,{paths:u.filePaths,matcher:{rule:{pattern:u.pattern}}},(_,$)=>{if(_){console.warn("[patternSearch] findInFiles callback error:",_);return}for(let N of $){let w=N.range();g.push({filePath:N.getRoot().filename(),startLine:w.start.line+1,endLine:w.end.line+1,matchedText:N.text()})}}),g}import d from"typescript";import{isErr as J0}from"@zipbul/result";import wu from"typescript";import r$ from"path";import{err as Zg}from"@zipbul/result";function d$(u){try{return Sg("fs").readFileSync(u,"utf-8")}catch{return}}function t$(u){try{return Sg("fs").readFileSync(u,"utf-8")}catch{return}}class pu{#u;#g;#_=!1;__testing__;constructor(u,g){this.#u=u,this.#g=g,this.__testing__={host:g}}static create(u,g={}){let _=g.readConfigFile??d$,$=g.resolveNonTrackedFile??t$,N=r$.dirname(u),w=_(u);if(w===void 0)return Zg(e("semantic",`tsconfig not found: ${u}`));let z=wu.parseJsonText(u,w),Q=z.parseDiagnostics;if(Q&&Q.length>0){let W=Q.map((Z)=>wu.flattenDiagnosticMessageText(Z.messageText,`
8
+ `)).join("; ");return Zg(e("semantic",`tsconfig parse error: ${W}`))}let J=wu.parseJsonSourceFileConfigFileContent(z,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(W)=>_(W)!==void 0||$(W)!==void 0,readFile:(W)=>_(W)??$(W)},N);if(J.errors.length>0){let W=J.errors.filter((Z)=>Z.category===wu.DiagnosticCategory.Error&&Z.code!==18003);if(W.length>0){let Z=W.map((n)=>wu.flattenDiagnosticMessageText(n.messageText,`
9
+ `)).join("; ");return Zg(e("semantic",`tsconfig compile error: ${Z}`))}}let Y=new og(J.fileNames,J.options,N,$),O=wu.createLanguageService(Y);return new pu(O,Y)}get isDisposed(){return this.#_}getProgram(){this.#N();let u=this.#u.getProgram();if(!u)throw Error("TscProgram: LanguageService returned null Program");return u}getChecker(){return this.#N(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#N(),this.#u}notifyFileChanged(u,g){if(this.#_)return;this.#g.updateFile(u,g)}removeFile(u){if(this.#_)return;this.#g.removeFile(u)}dispose(){if(this.#_)return;this.#_=!0,this.#u.dispose()}#N(){if(this.#_)throw Error("TscProgram is disposed")}}class og{#u;#g;#_;#N;#$=new Map;constructor(u,g,_,$){this.#u=new Set(u),this.#g=g,this.#_=_,this.#N=$}updateFile(u,g){let _=this.#$.get(u);if(_)_.version+=1,_.content=g;else this.#$.set(u,{version:1,content:g})}removeFile(u){this.#$.delete(u),this.#u.delete(u)}getScriptFileNames(){let u=[...this.#$.keys()];return[...[...this.#u].filter((_)=>!this.#$.has(_)),...u]}getScriptVersion(u){let g=this.#$.get(u);return g?String(g.version):"0"}getScriptSnapshot(u){let g=this.#$.get(u);if(g)return wu.ScriptSnapshot.fromString(g.content);let _=this.#N(u);if(_!==void 0)return wu.ScriptSnapshot.fromString(_);return}getCurrentDirectory(){return this.#_}getCompilationSettings(){return this.#g}getDefaultLibFileName(u){return wu.getDefaultLibFilePath(u)}fileExists(u){if(this.#$.has(u))return!0;return this.#N(u)!==void 0}readFile(u){let g=this.#$.get(u);if(g)return g.content;return this.#N(u)}}import a from"typescript";import a$ from"typescript";function Ou(u,g){if(g<0||g>=u.getEnd())return;function _($){let N=$.getStart(u,!1),w=$.getEnd();if(g<N||g>=w)return;let z;return a$.forEachChild($,(Q)=>{if(!z)z=_(Q)}),z??$}return _(u)}function c$(u){return!!(u.flags&a.TypeFlags.Object)&&!!(u.objectFlags&a.ObjectFlags.Reference)}function Fu(u,g,_=0){let $=u.typeToString(g),N=g.flags,w=!!(N&a.TypeFlags.Union),z=!!(N&a.TypeFlags.Intersection),Q;if(_<8&&c$(g)){let W=u.getTypeArguments(g);if(W.length>0)Q=W}let J=!!(N&a.TypeFlags.TypeParameter)||Q!==void 0&&Q.length>0,Y;if(w&&_<8)Y=g.types.map((W)=>Fu(u,W,_+1));else if(z&&_<8)Y=g.types.map((W)=>Fu(u,W,_+1));let O;if(Q&&Q.length>0)O=Q.map((W)=>Fu(u,W,_+1));return{text:$,flags:N,isUnion:w,isIntersection:z,isGeneric:J,members:Y,typeArguments:O}}function s$(u){return a.isFunctionDeclaration(u)||a.isVariableDeclaration(u)||a.isClassDeclaration(u)||a.isInterfaceDeclaration(u)||a.isTypeAliasDeclaration(u)||a.isEnumDeclaration(u)||a.isMethodDeclaration(u)||a.isPropertyDeclaration(u)||a.isPropertySignature(u)||a.isMethodSignature(u)}class Kg{program;constructor(u){this.program=u}collectAt(u,g){let _=this.program.getProgram(),$=this.program.getChecker();if(g<0)return null;let N=_.getSourceFile(u);if(!N)return null;if(g>=N.getEnd())return null;let w=Ou(N,g);if(!w)return null;if(!a.isIdentifier(w))return null;try{let z=$.getTypeAtLocation(w);return Fu($,z)}catch{return null}}collectFile(u){let g=new Map,_=this.program.getProgram(),$=this.program.getChecker(),N=_.getSourceFile(u);if(!N)return g;function w(z){if(s$(z)&&z.name&&a.isIdentifier(z.name)){let Q=z.name;try{let J=$.getTypeAtLocation(Q),Y=Q.getStart(N);g.set(Y,Fu($,J))}catch{}}a.forEachChild(z,w)}return w(N),g}}import Uu from"typescript";var o$=1000,e$=1;function u0(u){let g=u.declarations?.[0],_=g?.getSourceFile(),$=g?Uu.getNameOfDeclaration(g):void 0;return{name:u.getName(),filePath:_?.fileName??"",position:$?.getStart(_,!1)??g?.getStart(_,!1)??0}}function lu(u,g=0){let _=u.declarations?.[0],$=_?.getSourceFile(),N=_?Uu.getNameOfDeclaration(_):void 0,w=$?.fileName??"",z=N?.getStart($,!1)??_?.getStart($,!1)??0,Q={name:u.getName(),filePath:w,position:z},J=u;if(J.parent)Q.parent=u0(J.parent);if(g<e$){let Y=u.flags,O=!!(Y&Uu.SymbolFlags.Enum),W=!!(Y&(Uu.SymbolFlags.NamespaceModule|Uu.SymbolFlags.ValueModule)),Z=!!(Y&(Uu.SymbolFlags.Class|Uu.SymbolFlags.Interface));if(O&&u.exports&&u.exports.size>0){let n=[];u.exports.forEach((A)=>{n.push(lu(A,g+1))}),Q.members=n}else if(Z&&u.members&&u.members.size>0){let n=[];u.members.forEach((A)=>{n.push(lu(A,g+1))}),Q.members=n}if(W&&u.exports&&u.exports.size>0){let n=[];u.exports.forEach((A)=>{n.push(lu(A,g+1))}),Q.exports=n}}return Q}class Mg{#u;#g;#_=new Map;constructor(u,g=o$){this.#u=u,this.#g=new ku(g)}get(u,g){if(this.#u.isDisposed)return null;let _=`${u}:${g}`,$=this.#g.get(_);if($!==void 0)return $;let w=this.#u.getProgram().getSourceFile(u);if(!w)return null;let z=Ou(w,g);if(!z||!Uu.isIdentifier(z))return null;let J=this.#u.getChecker().getSymbolAtLocation(z);if(!J)return null;let Y=lu(J);this.#g.set(_,Y);let O=this.#_.get(u);if(!O)O=new Set,this.#_.set(u,O);return O.add(_),Y}invalidate(u){let g=this.#_.get(u);if(g){for(let _ of g)this.#g.delete(_);this.#_.delete(u)}}clear(){this.#g.clear(),this.#_.clear()}}import g0 from"typescript";class ng{#u;constructor(u){this.#u=u}findAt(u,g){if(this.#u.isDisposed)return[];let _=this.#u.getProgram(),$=_.getSourceFile(u);if(!$)return[];let N=Ou($,g);if(!N||!g0.isIdentifier(N))return[];let z=this.#u.getLanguageService().findReferences(u,g);if(!z||z.length===0)return[];let Q=[];for(let J of z)for(let Y of J.references){let O=_.getSourceFile(Y.fileName);if(!O)continue;let{line:W,character:Z}=O.getLineAndCharacterOfPosition(Y.textSpan.start);Q.push({filePath:Y.fileName,position:Y.textSpan.start,line:W+1,column:Z,isDefinition:Y.isDefinition??!1,isWrite:Y.isWriteAccess??!1})}return Q}}import m from"typescript";function _0(u,g){let _=Ou(u,g);if(!_)return;if(eg(_))return _;let $=_.parent;for(let N=0;N<5&&$;N++){if(eg($))return $;$=$.parent}return _}function eg(u){return m.isClassDeclaration(u)||m.isClassExpression(u)||m.isFunctionDeclaration(u)||m.isFunctionExpression(u)||m.isArrowFunction(u)||m.isVariableDeclaration(u)||m.isObjectLiteralExpression(u)}function u_(u){if(m.isClassDeclaration(u)||m.isClassExpression(u))return"class";if(m.isFunctionDeclaration(u)||m.isFunctionExpression(u)||m.isArrowFunction(u))return"function";if(m.isObjectLiteralExpression(u))return"object";if(m.isVariableDeclaration(u)&&u.initializer)return u_(u.initializer);return"class"}function $0(u,g){if(m.isClassDeclaration(u)||m.isFunctionDeclaration(u))return u.name?.getText(g)??"";if(m.isClassExpression(u))return u.name?.getText(g)??"";if(m.isVariableDeclaration(u)&&m.isIdentifier(u.name))return u.name.getText(g);if(m.isFunctionExpression(u))return u.name?.getText(g)??"";if(m.isArrowFunction(u)&&u.parent&&m.isVariableDeclaration(u.parent)){if(m.isIdentifier(u.parent.name))return u.parent.name.getText(g)}if(m.isObjectLiteralExpression(u)&&u.parent&&m.isVariableDeclaration(u.parent)){if(m.isIdentifier(u.parent.name))return u.parent.name.getText(g)}return""}function N0(u){if(!m.isClassDeclaration(u)&&!m.isClassExpression(u))return!1;let g=u.heritageClauses;if(!g)return!1;return g.some((_)=>_.token===m.SyntaxKind.ImplementsKeyword)}class Hg{#u;constructor(u){this.#u=u}findAt(u,g){if(this.#u.isDisposed)return[];let _=this.#u.getProgram(),$=_.getSourceFile(u);if(!$)return[];let N=Ou($,g);if(!N||!m.isIdentifier(N))return[];let z=this.#u.getLanguageService().getImplementationAtPosition(u,g);if(!z||z.length===0)return[];let Q=[];for(let J of z){if(J.kind===m.ScriptElementKind.interfaceElement||J.kind===m.ScriptElementKind.typeElement)continue;let Y=_.getSourceFile(J.fileName);if(!Y)continue;let O=_0(Y,J.textSpan.start);if(!O)continue;let W=u_(O),Z=$0(O,Y),n=N0(O);Q.push({filePath:J.fileName,symbolName:Z,position:J.textSpan.start,kind:W,isExplicit:n})}return Q}}function g_(u){return d.canHaveModifiers(u)&&d.getModifiers(u)?.some((g)=>g.kind===d.SyntaxKind.ExportKeyword)===!0}function Q0(u){if(d.isFunctionDeclaration(u))return"function";if(d.isClassDeclaration(u))return"class";if(d.isInterfaceDeclaration(u))return"interface";if(d.isTypeAliasDeclaration(u))return"type";if(d.isEnumDeclaration(u))return"enum";if(d.isVariableDeclaration(u))return"const";if(d.isVariableStatement(u))return"const";return"unknown"}function __(u){if(u>=97&&u<=122)return!0;if(u>=65&&u<=90)return!0;if(u>=48&&u<=57)return!0;if(u===95||u===36)return!0;return!1}class ru{#u;#g;#_;#N;#$;#J=!1;constructor(u,g,_,$,N){this.#u=u,this.#g=g,this.#_=_,this.#N=$,this.#$=N}static create(u,g={}){let _=pu.create(u,{readConfigFile:g.readConfigFile,resolveNonTrackedFile:g.resolveNonTrackedFile});if(J0(_))return _;let $=_,N=g.typeCollector??new Kg($),w=g.symbolGraph??new Mg($),z=g.referenceResolver??new ng($),Q=g.implementationFinder??new Hg($);return new ru($,N,w,z,Q)}get isDisposed(){return this.#J}collectTypeAt(u,g){return this.#Q(),this.#g.collectAt(u,g)}collectFileTypes(u){return this.#Q(),this.#g.collectFile(u)}findReferences(u,g){return this.#Q(),this.#N.findAt(u,g)}findImplementations(u,g){return this.#Q(),this.#$.findAt(u,g)}getSymbolNode(u,g){return this.#Q(),this.#_.get(u,g)}getModuleInterface(u){this.#Q();let g=this.#g.collectFile(u),_=[],N=this.#u.getProgram().getSourceFile(u);if(!N)return{filePath:u,exports:_};function w(z){if(d.isVariableStatement(z)&&g_(z)){for(let Q of z.declarationList.declarations)if(d.isIdentifier(Q.name)){let J=Q.name.getStart(N),Y=g.get(J)??null;_.push({name:Q.name.text,kind:"const",resolvedType:Y})}return}if((d.isFunctionDeclaration(z)||d.isClassDeclaration(z)||d.isInterfaceDeclaration(z)||d.isTypeAliasDeclaration(z)||d.isEnumDeclaration(z))&&g_(z)&&z.name){let Q=z.name,J=Q.getStart(N),Y=g.get(J)??null;_.push({name:Q.text,kind:Q0(z),resolvedType:Y});return}d.forEachChild(z,w)}return w(N),{filePath:u,exports:_}}notifyFileChanged(u,g){if(this.#J)return;this.#u.notifyFileChanged(u,g),this.#_.invalidate(u)}notifyFileDeleted(u){if(this.#J)return;this.#u.removeFile(u),this.#_.invalidate(u)}lineColumnToPosition(u,g,_){this.#Q();let $=this.#u.getProgram().getSourceFile(u);if(!$)return null;try{return d.getPositionOfLineAndCharacter($,g-1,_)}catch{return null}}findNamePosition(u,g,_){this.#Q();let $=this.#u.getProgram().getSourceFile(u);if(!$)return null;let N=$.getFullText(),w=g;while(w<N.length){let z=N.indexOf(_,w);if(z<0)return null;let Q=z>0?N.charCodeAt(z-1):32,J=z+_.length<N.length?N.charCodeAt(z+_.length):32;if(!__(Q)&&!__(J))return z;w=z+1}return null}dispose(){if(this.#J)return;this.#J=!0,this.#u.dispose(),this.#_.clear()}#Q(){if(this.#J)throw Error("SemanticLayer is disposed")}}import{eq as Mu,and as $_,sql as z0}from"drizzle-orm";var N_=80;class Bg{db;constructor(u){this.db=u}insertBatch(u,g,_){if(!_.length)return;let $=_.map((N)=>({project:u,filePath:g,tag:N.tag,value:N.value,source:N.source,symbolName:N.symbolName,startLine:N.startLine,startColumn:N.startColumn,endLine:N.endLine,endColumn:N.endColumn,indexedAt:N.indexedAt}));for(let N=0;N<$.length;N+=N_)this.db.drizzleDb.insert($u).values($.slice(N,N+N_)).run()}deleteFileAnnotations(u,g){this.db.drizzleDb.delete($u).where($_(Mu($u.project,u),Mu($u.filePath,g))).run()}search(u){return this.db.drizzleDb.select().from($u).where($_(u.project?Mu($u.project,u.project):void 0,u.tag?Mu($u.tag,u.tag):void 0,u.filePath?Mu($u.filePath,u.filePath):void 0,u.symbolName?Mu($u.symbolName,u.symbolName):void 0,u.source?Mu($u.source,u.source):void 0,u.ftsQuery?z0`${$u.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${u.ftsQuery})`:void 0)).limit(u.limit).all()}}import{eq as Au,and as J_,sql as qu,gt as w0,gte as O0}from"drizzle-orm";var Q_=80;class Lg{db;constructor(u){this.db=u}insertBatch(u){if(!u.length)return;let g=u.map((_)=>({project:_.project,changeType:_.changeType,symbolName:_.symbolName,symbolKind:_.symbolKind,filePath:_.filePath,oldName:_.oldName,oldFilePath:_.oldFilePath,fingerprint:_.fingerprint,changedAt:_.changedAt,isFullIndex:_.isFullIndex,indexRunId:_.indexRunId}));for(let _=0;_<g.length;_+=Q_)this.db.drizzleDb.insert(uu).values(g.slice(_,_+Q_)).run()}getSince(u){return this.db.drizzleDb.select().from(uu).where(J_(Au(uu.project,u.project),O0(uu.changedAt,u.since),u.symbolName?Au(uu.symbolName,u.symbolName):void 0,u.changeTypes?.length?qu`${uu.changeType} IN (${qu.join(u.changeTypes.map((g)=>qu`${g}`),qu`, `)})`:void 0,u.filePath?Au(uu.filePath,u.filePath):void 0,u.includeFullIndex?void 0:Au(uu.isFullIndex,0),u.indexRunId?Au(uu.indexRunId,u.indexRunId):void 0,u.afterId?w0(uu.id,u.afterId):void 0)).orderBy(uu.id).limit(u.limit).all()}pruneOlderThan(u,g){return this.db.drizzleDb.delete(uu).where(J_(Au(uu.project,u),qu`${uu.changedAt} < ${g}`)).run().changes}}function z_(u){let{annotationRepo:g,project:_,query:$}=u,N=$.project??_,w=$.limit??100,z;if($.text)z=Hu($.text)??void 0;return g.search({project:N,tag:$.tag,filePath:$.filePath,symbolName:$.symbolName,source:$.source,ftsQuery:z,limit:w}).map((J)=>({tag:J.tag,value:J.value,source:J.source,filePath:J.filePath,symbolName:J.symbolName,span:{start:{line:J.startLine,column:J.startColumn},end:{line:J.endLine,column:J.endColumn}}}))}class du{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(u){this.options=u}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let g=[this.options.project,...this.options.additionalProjects??[]].flatMap((_)=>[...this.options.relationRepo.getByType(_,"imports"),...this.options.relationRepo.getByType(_,"type-references"),...this.options.relationRepo.getByType(_,"re-exports")]);for(let _ of g){let{srcFilePath:$,dstFilePath:N}=_;if(!this.adjacencyList.has($))this.adjacencyList.set($,new Set);if(this.adjacencyList.get($).add(N),!this.adjacencyList.has(N))this.adjacencyList.set(N,new Set);if(!this.reverseAdjacencyList.has(N))this.reverseAdjacencyList.set(N,new Set);this.reverseAdjacencyList.get(N).add($)}}patchFiles(u,g,_){let $=new Set([...u,...g]);for(let N of $){let w=this.adjacencyList.get(N);if(w){for(let Q of w)this.reverseAdjacencyList.get(Q)?.delete(N);w.clear()}let z=this.reverseAdjacencyList.get(N);if(z){for(let Q of z)this.adjacencyList.get(Q)?.delete(N);z.clear()}}for(let N of g)this.adjacencyList.delete(N),this.reverseAdjacencyList.delete(N);for(let N of u){let w=_(N);for(let z of w){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 g=new Set,_=[u];while(_.length>0){let $=_.shift();for(let N of this.reverseAdjacencyList.get($)??[])if(!g.has(N))g.add(N),_.push(N)}return Array.from(g)}hasCycle(){let u=new Set,g=new Set;for(let _ of this.adjacencyList.keys()){if(u.has(_))continue;let $=[{node:_,entered:!1}];while($.length>0){let N=$.pop();if(N.entered){g.delete(N.node);continue}if(g.has(N.node))return!0;if(u.has(N.node))continue;u.add(N.node),g.add(N.node),$.push({node:N.node,entered:!0});for(let w of this.adjacencyList.get(N.node)??[]){if(g.has(w))return!0;if(!u.has(w))$.push({node:w,entered:!1})}}}return!1}getAffectedByChange(u){let g=new Set;for(let _ of u)for(let $ of this.getTransitiveDependents(_))g.add($);return Array.from(g)}getAdjacencyList(){let u=new Map;for(let[g,_]of this.adjacencyList)u.set(g,Array.from(_));return u}getTransitiveDependencies(u){let g=new Set,_=[u];while(_.length>0){let $=_.shift();for(let N of this.adjacencyList.get($)??[])if(!g.has(N))g.add(N),_.push(N)}return Array.from(g)}getCyclePaths(u){let g=u?.maxCycles??1/0;if(g<=0)return[];let _=new Map;for(let[$,N]of this.adjacencyList)_.set($,Array.from(N));return X0(_,g)}}var W0=(u,g)=>u.localeCompare(g);function Y0(u){let g=u.length>1&&u[0]===u[u.length-1]?u.slice(0,-1):[...u];if(g.length===0)return[];let _=g;for(let $=1;$<g.length;$++){let N=g.slice($).concat(g.slice(0,$));if(N.join("::")<_.join("::"))_=N}return[..._]}function Dg(u,g,_){let $=Y0(_);if($.length===0)return!1;let N=$.join("->");if(u.has(N))return!1;return u.add(N),g.push($),!0}function V0(u){let g=0,_=[],$=new Set,N=new Map,w=new Map,z=[],Q=(J)=>{N.set(J,g),w.set(J,g),g+=1,_.push(J),$.add(J);for(let Y of u.get(J)??[])if(!N.has(Y))Q(Y),w.set(J,Math.min(w.get(J)??0,w.get(Y)??0));else if($.has(Y))w.set(J,Math.min(w.get(J)??0,N.get(Y)??0));if(w.get(J)===N.get(J)){let Y=[],O="";do O=_.pop()??"",$.delete(O),Y.push(O);while(O!==J&&_.length>0);z.push(Y)}};for(let J of u.keys())if(!N.has(J))Q(J);return{components:z}}function U0(u,g,_){let $=[],N=new Set,w=[...u].sort(W0),z=(Q,J,Y)=>{J.delete(Q);let O=Y.get(Q);if(!O)return;for(let W of O)if(J.has(W))z(W,J,Y);O.clear()};for(let Q=0;Q<w.length&&$.length<_;Q++){let J=w[Q]??"",Y=new Set(w.slice(Q)),O=new Set,W=new Map,Z=[],n=(D)=>(g.get(D)??[]).filter((k)=>Y.has(k)),A=(D)=>{if($.length>=_)return!0;let k=!1;Z.push(D),O.add(D);for(let G of n(D)){if($.length>=_)break;if(G===J)Dg(N,$,Z.concat(J)),k=!0;else if(!O.has(G)){if(A(G))k=!0}}if(k)z(D,O,W);else for(let G of n(D)){let i=W.get(G)??new Set;i.add(D),W.set(G,i)}return Z.pop(),k};A(J)}return $}function X0(u,g){let{components:_}=V0(u),$=[],N=new Set;for(let w of _){if($.length>=g)break;if(w.length===0)continue;if(w.length===1){let J=w[0]??"";if((u.get(J)??[]).includes(J))Dg(N,$,[J,J]);continue}let z=g-$.length,Q=U0(w,u,z);for(let J of Q){if($.length>=g)break;Dg(N,$,J)}}return $}var Z0=15000;function tu(u){u.graphCache=null,u.graphCacheKey=null,u.graphCacheBuiltAt=null}function Iu(u,g){let _=g??"__cross__";if(u.graphCache&&u.graphCacheBuiltAt!==null){if(Date.now()-u.graphCacheBuiltAt>Z0)u.graphCache=null,u.graphCacheKey=null,u.graphCacheBuiltAt=null}if(u.graphCache&&u.graphCacheKey===_)return u.graphCache;let $=new du({relationRepo:u.relationRepo,project:g??u.defaultProject,additionalProjects:g?void 0:u.boundaries?.map((N)=>N.project)});return $.build(),u.graphCache=$,u.graphCacheKey=_,u.graphCacheBuiltAt=Date.now(),$}function w_(u,g,_,$=1e4){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:_??u.defaultProject,query:{srcFilePath:g,type:"imports",project:_??u.defaultProject,limit:$}}).map((N)=>N.dstFilePath)}catch(N){if(N instanceof U)throw N;throw new U("search","Gildash: getDependencies failed",{cause:N})}}function O_(u,g,_,$=1e4){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:_??u.defaultProject,query:{dstFilePath:g,type:"imports",project:_??u.defaultProject,limit:$}}).map((N)=>N.srcFilePath)}catch(N){if(N instanceof U)throw N;throw new U("search","Gildash: getDependents failed",{cause:N})}}async function W_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return Iu(u,_).getAffectedByChange(g)}catch($){if($ instanceof U)throw $;throw new U("search","Gildash: getAffected failed",{cause:$})}}async function Y_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return Iu(u,g).hasCycle()}catch(_){if(_ instanceof U)throw _;throw new U("search","Gildash: hasCycle failed",{cause:_})}}async function V_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return Iu(u,g).getAdjacencyList()}catch(_){if(_ instanceof U)throw _;throw new U("search","Gildash: getImportGraph failed",{cause:_})}}async function U_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return Iu(u,_).getTransitiveDependencies(g)}catch($){if($ instanceof U)throw $;throw new U("search","Gildash: getTransitiveDependencies failed",{cause:$})}}async function X_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return Iu(u,g).getCyclePaths(_)}catch($){if($ instanceof U)throw $;throw new U("search","Gildash: getCyclePaths failed",{cause:$})}}async function Z_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{let $=Iu(u,_);return{filePath:g,fanIn:$.getDependents(g).length,fanOut:$.getDependencies(g).length}}catch($){if($ instanceof U)throw $;throw new U("search","Gildash: getFanMetrics failed",{cause:$})}}var n0=30000,K_=15000,H0=10;function B0(u,g){return(_)=>{for(let $ of u.onFileChangedCallbacks)try{$(_)}catch(N){u.logger.error("[Gildash] onFileChanged callback threw:",N)}if(g.handleWatcherEvent?.(_),u.semanticLayer)if(_.eventType==="delete")try{u.semanticLayer.notifyFileDeleted(_.filePath)}catch($){u.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",$);for(let N of u.onErrorCallbacks)try{N($ instanceof U?$:new U("semantic","semantic notifyFileDeleted failed",{cause:$}))}catch{}}else u.readFileFn(_.filePath).then(($)=>{try{u.semanticLayer?.notifyFileChanged(_.filePath,$)}catch(N){u.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",N);for(let w of u.onErrorCallbacks)try{w(N instanceof U?N:new U("semantic","semantic notifyFileChanged failed",{cause:N}))}catch{}}}).catch(($)=>{u.logger.error("[Gildash] failed to read file for semantic layer",_.filePath,$);try{u.semanticLayer?.notifyFileDeleted(_.filePath)}catch(N){u.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",N)}})}}async function L0(u){if(!u.semanticLayer)return;let g=u.fileRepo.getAllFiles(u.defaultProject);await Promise.all(g.map(async(_)=>{try{let $=ju.resolve(u.projectRoot,_.filePath),N=await u.readFileFn($);u.semanticLayer?.notifyFileChanged($,N)}catch{}}))}async function M_(u,g){let _=u.coordinatorFactory?u.coordinatorFactory():new Wg({projectRoot:u.projectRoot,boundaries:u.boundaries,extensions:u.extensions,ignorePatterns:u.ignorePatterns,dbConnection:u.db,parseCache:u.parseCache,fileRepo:u.fileRepo,symbolRepo:u.symbolRepo,relationRepo:u.relationRepo,annotationRepo:u.annotationRepo??void 0,changelogRepo:u.changelogRepo??void 0,logger:u.logger});u.coordinator=_;for(let $ of u.onIndexedCallbacks)_.onIndexed($);if(_.onIndexed(($)=>{let N=$.changedFiles.length+$.deletedFiles.length;if(u.graphCache&&N>0&&N<100){let w=u.relationRepo;u.graphCache.patchFiles($.changedFiles,$.deletedFiles,(z)=>{return[u.defaultProject,...u.boundaries.map((J)=>J.project)].flatMap((J)=>w.getByType(J,"imports").concat(w.getByType(J,"type-references")).concat(w.getByType(J,"re-exports"))).filter((J)=>J.srcFilePath===z||J.dstFilePath===z).map((J)=>({srcFilePath:J.srcFilePath,dstFilePath:J.dstFilePath}))}),u.graphCacheBuiltAt=Date.now()}else tu(u)}),g.isWatchMode){let $=u.watcherFactory?u.watcherFactory():new _g({projectRoot:u.projectRoot,ignorePatterns:u.ignorePatterns,extensions:u.extensions},void 0,u.logger);await $.start(B0(u,_)).then((N)=>{if(Gu(N))throw N.data}),u.watcher=$,u.timer=setInterval(()=>{u.updateHeartbeatFn(u.db,process.pid)},n0)}await _.fullIndex(),await L0(u)}function D0(u,g){let _=["SIGTERM","SIGINT","beforeExit"];for(let $ of _){let N=()=>{g().catch((w)=>u.logger.error("[Gildash] close error during signal",$,w))};if($==="beforeExit")process.on("beforeExit",N);else process.on($,N);u.signalHandlers.push([$,N])}}async function n_(u){let{projectRoot:g,extensions:_=[".ts",".mts",".cts"],ignorePatterns:$=["**/node_modules/**"],parseCacheCapacity:N=500,logger:w=console,existsSyncFn:z=M0,dbConnectionFactory:Q,watcherFactory:J,coordinatorFactory:Y,repositoryFactory:O,acquireWatcherRoleFn:W=ag,releaseWatcherRoleFn:Z=cg,updateHeartbeatFn:n=sg,discoverProjectsFn:A=bu,parseSourceFn:D=Tu,extractSymbolsFn:k=Lu,extractRelationsFn:G=hu,symbolSearchFn:i=Vg,relationSearchFn:V=Ug,patternSearchFn:K=Xg,loadTsconfigPathsFn:M=Ru,readFileFn:R=async(B)=>Bun.file(B).text(),unlinkFn:I=async(B)=>{await Bun.file(B).unlink()},watchMode:C,semantic:v,semanticLayerFactory:y}=u;if(!ju.isAbsolute(g))throw new U("validation",`Gildash: projectRoot must be an absolute path, got: "${g}"`);if(!z(g))throw new U("validation",`Gildash: projectRoot does not exist: "${g}"`);let j=Q?Q():new su({projectRoot:g}),X=j.open();if(Gu(X))throw X.data;try{let B=await A(g),S=B[0]?.project??ju.basename(g),H=O?O():(()=>{let s=j;return{fileRepo:new ou(s),symbolRepo:new eu(s),relationRepo:new ug(s),parseCache:new Yg(N)}})(),P=O?null:j,q=P?new Bg(P):null,c=P?new Lg(P):null,b=C??!0,h=crypto.randomUUID(),E;if(b)E=await Promise.resolve(W(j,process.pid,{instanceId:h}));else E="owner";let T={projectRoot:g,extensions:_,ignorePatterns:$,logger:w,defaultProject:S,role:E,db:j,symbolRepo:H.symbolRepo,relationRepo:H.relationRepo,fileRepo:H.fileRepo,parseCache:H.parseCache,annotationRepo:q,changelogRepo:c,annotationSearchFn:z_,releaseWatcherRoleFn:Z,parseSourceFn:D,extractSymbolsFn:k,extractRelationsFn:G,symbolSearchFn:i,relationSearchFn:V,patternSearchFn:K,readFileFn:R,unlinkFn:I,existsSyncFn:z,acquireWatcherRoleFn:W,updateHeartbeatFn:n,watcherFactory:J,coordinatorFactory:Y,instanceId:h,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:B,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(fu(g),T.tsconfigPaths=await M(g),v){let s=ju.join(g,"tsconfig.json");try{if(y)T.semanticLayer=y(s);else{let o=ru.create(s);if(Gu(o))throw o.data;T.semanticLayer=o}}catch(o){if(o instanceof U)throw o;throw new U("semantic","Gildash: semantic layer creation failed",{cause:o})}}if(E==="owner")await M_(T,{isWatchMode:b});else{let s=0,o=async()=>{try{let Qu=await Promise.resolve(T.acquireWatcherRoleFn(T.db,process.pid,{instanceId:T.instanceId}));if(s=0,Qu==="owner"){T.role="owner";for(let Wu of T.onRoleChangedCallbacks)try{Wu("owner")}catch(_u){T.logger.error("[Gildash] onRoleChanged callback threw:",_u)}clearInterval(T.timer),T.timer=null;try{await M_(T,{isWatchMode:!0})}catch(Wu){if(T.logger.error("[Gildash] owner promotion failed, reverting to reader",Wu),T.role="reader",T.timer!==null)clearInterval(T.timer),T.timer=null;if(T.watcher){let _u=await T.watcher.close();if(Gu(_u))T.logger.error("[Gildash] watcher close error during promotion rollback",_u.data);T.watcher=null}if(T.coordinator)await T.coordinator.shutdown().catch((_u)=>T.logger.error("[Gildash] coordinator shutdown error during promotion rollback",_u)),T.coordinator=null;try{T.releaseWatcherRoleFn(T.db,process.pid)}catch(_u){T.logger.error("[Gildash] failed to release watcher role during promotion rollback",_u)}T.timer=setInterval(o,K_)}}}catch(Qu){s++;let Wu=Qu instanceof U?Qu:new U("watcher","Gildash: healthcheck error",{cause:Qu});for(let _u of T.onErrorCallbacks)try{_u(Wu)}catch(Cu){T.logger.error("[Gildash] onError callback threw:",Cu)}if(T.logger.error("[Gildash] healthcheck error",Qu),s>=H0)T.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(T.timer),T.timer=null,au(T).catch((_u)=>T.logger.error("[Gildash] close error during healthcheck shutdown",_u))}};T.timer=setInterval(o,K_)}if(b)D0(T,()=>au(T));return T}catch(B){if(j.close(),B instanceof U)throw B;throw new U("store","Gildash: initialization failed",{cause:B})}}async function au(u,g){if(u.closed)return;u.closed=!0;let _=[];for(let[$,N]of u.signalHandlers)if($==="beforeExit")process.off("beforeExit",N);else process.off($,N);if(u.signalHandlers=[],u.semanticLayer){try{u.semanticLayer.dispose()}catch($){_.push($ instanceof Error?$:Error(String($)))}u.semanticLayer=null}if(u.coordinator)try{await u.coordinator.shutdown()}catch($){_.push($ instanceof Error?$:Error(String($)))}if(u.watcher){let $=await u.watcher.close();if(Gu($))_.push($.data)}if(u.timer!==null)clearInterval(u.timer),u.timer=null;try{u.releaseWatcherRoleFn(u.db,process.pid)}catch($){_.push($ instanceof Error?$:Error(String($)))}try{u.db.close()}catch($){_.push($ instanceof Error?$:Error(String($)))}if(g?.cleanup)for(let $ of["","-wal","-shm"])try{await u.unlinkFn(ju.join(u.projectRoot,Yu,Eu+$))}catch{}if(_.length>0)throw new U("close","Gildash: one or more errors occurred during close()",{cause:_})}import{isErr as H_}from"@zipbul/result";function B_(u,g,_,$){if(u.closed)throw new U("closed","Gildash: instance is closed");let N=u.parseSourceFn(g,_,$);if(H_(N))throw N.data;return u.parseCache.set(g,N),N}async function L_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");let $=new Map,N=[];return await Promise.all(g.map(async(w)=>{try{let z=await u.readFileFn(w),Q=u.parseSourceFn(w,z,_);if(!H_(Q))$.set(w,Q);else N.push({filePath:w,error:Q.data})}catch(z){N.push({filePath:w,error:z instanceof Error?z:Error(String(z))})}})),{parsed:$,failures:N}}function D_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");return u.parseCache.get(g)}function A_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");return u.extractSymbolsFn(g)}function I_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");return u.extractRelationsFn(g.program,g.filePath,u.tsconfigPaths??void 0)}import C_ from"path";function S_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.symbolRepo.getStats(g??u.defaultProject)}catch(_){if(_ instanceof U)throw _;throw new U("store","Gildash: getStats failed",{cause:_})}}function Ag(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.symbolSearchFn({symbolRepo:u.symbolRepo,project:u.defaultProject,query:g})}catch(_){if(_ instanceof U)throw _;throw new U("search","Gildash: searchSymbols failed",{cause:_})}}function R_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:u.defaultProject,query:g})}catch(_){if(_ instanceof U)throw _;throw new U("search","Gildash: searchRelations failed",{cause:_})}}function T_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.symbolSearchFn({symbolRepo:u.symbolRepo,project:void 0,query:g})}catch(_){if(_ instanceof U)throw _;throw new U("search","Gildash: searchAllSymbols failed",{cause:_})}}function k_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:void 0,query:g})}catch(_){if(_ instanceof U)throw _;throw new U("search","Gildash: searchAllRelations failed",{cause:_})}}function F_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.fileRepo.getAllFiles(g??u.defaultProject)}catch(_){if(_ instanceof U)throw _;throw new U("store","Gildash: listIndexedFiles failed",{cause:_})}}function q_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.relationSearchFn({relationRepo:u.relationRepo,project:_??u.defaultProject,query:{srcFilePath:g,dstFilePath:g,limit:1e4}})}catch($){if($ instanceof U)throw $;throw new U("search","Gildash: getInternalRelations failed",{cause:$})}}function G_(u,g,_,$){if(u.closed)throw new U("closed","Gildash: instance is closed");try{let N=$??u.defaultProject,w=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:N,query:{text:g,exact:!0,filePath:_,limit:1}});if(w.length===0)return null;let z=w[0],Q=z.detail,J={...z,members:Array.isArray(Q.members)?Q.members:void 0,jsDoc:typeof Q.jsDoc==="string"?Q.jsDoc:void 0,parameters:typeof Q.parameters==="string"?Q.parameters:void 0,returnType:typeof Q.returnType==="string"?Q.returnType:void 0,heritage:Array.isArray(Q.heritage)?Q.heritage:void 0,decorators:Array.isArray(Q.decorators)?Q.decorators:void 0,typeParameters:typeof Q.typeParameters==="string"?Q.typeParameters:void 0};if(u.semanticLayer)try{let Y=C_.isAbsolute(_)?_:C_.resolve(u.projectRoot,_),O=u.semanticLayer.lineColumnToPosition(Y,z.span.start.line,z.span.start.column);if(O!==null){let W=u.semanticLayer.findNamePosition(Y,O,z.name)??O,Z=u.semanticLayer.collectTypeAt(Y,W);if(Z)J.resolvedType=Z}}catch{}return J}catch(N){if(N instanceof U)throw N;throw new U("search","Gildash: getFullSymbol failed",{cause:N})}}function j_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{let $=_??u.defaultProject,N=u.fileRepo.getFile($,g);if(!N)throw new U("search",`Gildash: file '${g}' is not in the index`);let w=u.symbolRepo.getFileSymbols($,g),z=u.relationRepo.getOutgoing($,g);return{filePath:N.filePath,lineCount:N.lineCount??0,size:N.size,symbolCount:w.length,exportedSymbolCount:w.filter((Q)=>Q.isExported).length,relationCount:z.length}}catch($){if($ instanceof U)throw $;throw new U("store","Gildash: getFileStats failed",{cause:$})}}function E_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{return u.fileRepo.getFile(_??u.defaultProject,g)}catch($){if($ instanceof U)throw $;throw new U("store","Gildash: getFileInfo failed",{cause:$})}}function v_(u,g,_){return Ag(u,{filePath:g,project:_??void 0,limit:1e4})}function P_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{let N=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:_??u.defaultProject,query:{filePath:g,isExported:!0}}).map((w)=>({name:w.name,kind:w.kind,parameters:w.detail.parameters??void 0,returnType:w.detail.returnType??void 0,jsDoc:w.detail.jsDoc??void 0}));return{filePath:g,exports:N}}catch($){if($ instanceof U)throw $;throw new U("search","Gildash: getModuleInterface failed",{cause:$})}}import b_ from"path";function Ig(u,g,_,$){let N=$??u.defaultProject,w=u.symbolSearchFn({symbolRepo:u.symbolRepo,project:N,query:{text:g,exact:!0,filePath:_,limit:1}});if(w.length===0)return null;let z=w[0],Q=b_.isAbsolute(_)?_:b_.resolve(u.projectRoot,_),J=u.semanticLayer.lineColumnToPosition(Q,z.span.start.line,z.span.start.column);if(J===null)return null;let Y=u.semanticLayer.findNamePosition(Q,J,z.name)??J;return{sym:z,position:Y,absPath:Q}}function f_(u,g,_,$){if(u.closed)throw new U("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new U("semantic","Gildash: semantic layer is not enabled");try{let N=Ig(u,g,_,$);if(!N)return null;return u.semanticLayer.collectTypeAt(N.absPath,N.position)}catch(N){if(N instanceof U)throw N;throw new U("search","Gildash: getResolvedType failed",{cause:N})}}function y_(u,g,_,$){if(u.closed)throw new U("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new U("semantic","Gildash: semantic layer is not enabled");try{let N=Ig(u,g,_,$);if(!N)throw new U("search",`Gildash: symbol '${g}' not found in '${_}'`);return u.semanticLayer.findReferences(N.absPath,N.position)}catch(N){if(N instanceof U)throw N;throw new U("search","Gildash: getSemanticReferences failed",{cause:N})}}function i_(u,g,_,$){if(u.closed)throw new U("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new U("semantic","Gildash: semantic layer is not enabled");try{let N=Ig(u,g,_,$);if(!N)throw new U("search",`Gildash: symbol '${g}' not found in '${_}'`);return u.semanticLayer.findImplementations(N.absPath,N.position)}catch(N){if(N instanceof U)throw N;throw new U("search","Gildash: getImplementations failed",{cause:N})}}function m_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");if(!u.semanticLayer)throw new U("semantic","Gildash: semantic layer is not enabled");try{return u.semanticLayer.getModuleInterface(g)}catch(_){if(_ instanceof U)throw _;throw new U("search","Gildash: getSemanticModuleInterface failed",{cause:_})}}function h_(u,g){let _=new Map(u.map((Q)=>[`${Q.name}::${Q.filePath}`,Q])),$=new Map(g.map((Q)=>[`${Q.name}::${Q.filePath}`,Q])),N=[],w=[],z=[];for(let[Q,J]of $){let Y=_.get(Q);if(!Y)N.push(J);else if(Y.fingerprint!==J.fingerprint)z.push({before:Y,after:J})}for(let[Q,J]of _)if(!$.has(Q))w.push(J);return{added:N,removed:w,modified:z}}function x_(u,g){if(u.onIndexedCallbacks.add(g),!u.coordinator)return()=>{u.onIndexedCallbacks.delete(g)};let _=u.coordinator.onIndexed(g);return()=>{u.onIndexedCallbacks.delete(g),_()}}async function p_(u){if(u.closed)throw new U("closed","Gildash: instance is closed");if(!u.coordinator)throw new U("closed","Gildash: reindex() is not available for readers");try{let g=await u.coordinator.fullIndex();return tu(u),g}catch(g){if(g instanceof U)throw g;throw new U("index","Gildash: reindex failed",{cause:g})}}function l_(u,g,_,$){if(u.closed)throw new U("closed","Gildash: instance is closed");let N=$??u.defaultProject,w=new Set,z=[],Q=g,J=_;for(;;){let Y=`${J}::${Q}`;if(w.has(Y))return{originalName:Q,originalFilePath:J,reExportChain:z,circular:!0};w.add(Y);let O=u.relationSearchFn({relationRepo:u.relationRepo,project:N,query:{type:"re-exports",srcFilePath:J,limit:500}}),W,Z;for(let n of O){let A;if(n.metaJson)try{let k=JSON.parse(n.metaJson);if(Array.isArray(k.specifiers))A=k.specifiers}catch{}if(!A)continue;let D=A.find((k)=>k.exported===Q);if(!D)continue;W=n.dstFilePath,Z=D.local;break}if(!W||!Z)return{originalName:Q,originalFilePath:J,reExportChain:z,circular:!1};z.push({filePath:J,exportedAs:Q}),J=W,Q=Z}}function r_(u,g){return u.onFileChangedCallbacks.add(g),()=>{u.onFileChangedCallbacks.delete(g)}}function d_(u,g){return u.onErrorCallbacks.add(g),()=>{u.onErrorCallbacks.delete(g)}}function t_(u,g){return u.onRoleChangedCallbacks.add(g),()=>{u.onRoleChangedCallbacks.delete(g)}}async function a_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");try{let $=_?.project??u.defaultProject,N=_?.filePaths?_.filePaths:u.fileRepo.getAllFiles($).map((w)=>w.filePath);return await u.patternSearchFn({pattern:g,filePaths:N})}catch($){if($ instanceof U)throw $;throw new U("search","Gildash: findPattern failed",{cause:$})}}async function c_(u,g,_,$){if(u.closed)throw new U("closed","Gildash: instance is closed");try{let N=$??u.defaultProject,w=new Set,z=(Q,J,Y)=>{let O=`${Q}::${J}`;if(w.has(O))return{symbolName:Q,filePath:J,kind:Y,children:[]};w.add(O);let n=u.relationSearchFn({relationRepo:u.relationRepo,project:N,query:{srcFilePath:J,srcSymbolName:Q,limit:1000}}).filter((A)=>A.type==="extends"||A.type==="implements").filter((A)=>A.dstSymbolName!=null).map((A)=>z(A.dstSymbolName,A.dstFilePath,A.type));return{symbolName:Q,filePath:J,kind:Y,children:n}};return z(g,_)}catch(N){if(N instanceof U)throw N;throw new U("search","Gildash: getHeritageChain failed",{cause:N})}}function s_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");if(!u.annotationRepo||!u.annotationSearchFn)return[];return u.annotationSearchFn({annotationRepo:u.annotationRepo,project:g.project??u.defaultProject,query:g})}function o_(u,g,_){if(u.closed)throw new U("closed","Gildash: instance is closed");if(!u.changelogRepo)return[];let $=g instanceof Date?g.toISOString():g,N=_?.project??u.defaultProject,w=_?.limit??1000;return u.changelogRepo.getSince({project:N,since:$,symbolName:_?.symbolName,changeTypes:_?.changeTypes,filePath:_?.filePath,includeFullIndex:_?.includeFullIndex,indexRunId:_?.indexRunId,afterId:_?.afterId,limit:w}).map((Q)=>({changeType:Q.changeType,symbolName:Q.symbolName,symbolKind:Q.symbolKind,filePath:Q.filePath,oldName:Q.oldName,oldFilePath:Q.oldFilePath,fingerprint:Q.fingerprint,changedAt:Q.changedAt,isFullIndex:Q.isFullIndex===1,indexRunId:Q.indexRunId}))}function e_(u,g){if(u.closed)throw new U("closed","Gildash: instance is closed");if(!u.changelogRepo)return 0;let _=g instanceof Date?g.toISOString():g,$=0,N=[u.defaultProject,...u.boundaries.map((z)=>z.project)],w=[...new Set(N)];for(let z of w)$+=u.changelogRepo.pruneOlderThan(z,_);return $}class Cg{_ctx;get projectRoot(){return this._ctx.projectRoot}get role(){return this._ctx.role}get projects(){return[...this._ctx.boundaries]}constructor(u){this._ctx=u}static async open(u){let g=await n_(u);return new Cg(g)}async close(u){return au(this._ctx,u)}parseSource(u,g,_){return B_(this._ctx,u,g,_)}async batchParse(u,g){return L_(this._ctx,u,g)}getParsedAst(u){return D_(this._ctx,u)}extractSymbols(u){return A_(this._ctx,u)}extractRelations(u){return I_(this._ctx,u)}getStats(u){return S_(this._ctx,u)}searchSymbols(u){return Ag(this._ctx,u)}searchRelations(u){return R_(this._ctx,u)}searchAllSymbols(u){return T_(this._ctx,u)}searchAllRelations(u){return k_(this._ctx,u)}listIndexedFiles(u){return F_(this._ctx,u)}getInternalRelations(u,g){return q_(this._ctx,u,g)}getFullSymbol(u,g,_){return G_(this._ctx,u,g,_)}getFileStats(u,g){return j_(this._ctx,u,g)}getFileInfo(u,g){return E_(this._ctx,u,g)}getSymbolsByFile(u,g){return v_(this._ctx,u,g)}getModuleInterface(u,g){return P_(this._ctx,u,g)}getDependencies(u,g,_=1e4){return w_(this._ctx,u,g,_)}getDependents(u,g,_=1e4){return O_(this._ctx,u,g,_)}async getAffected(u,g){return W_(this._ctx,u,g)}async hasCycle(u){return Y_(this._ctx,u)}async getImportGraph(u){return V_(this._ctx,u)}async getTransitiveDependencies(u,g){return U_(this._ctx,u,g)}async getCyclePaths(u,g){return X_(this._ctx,u,g)}async getFanMetrics(u,g){return Z_(this._ctx,u,g)}getResolvedType(u,g,_){return f_(this._ctx,u,g,_)}getSemanticReferences(u,g,_){return y_(this._ctx,u,g,_)}getImplementations(u,g,_){return i_(this._ctx,u,g,_)}getSemanticModuleInterface(u){return m_(this._ctx,u)}diffSymbols(u,g){return h_(u,g)}onIndexed(u){return x_(this._ctx,u)}async reindex(){return p_(this._ctx)}resolveSymbol(u,g,_){return l_(this._ctx,u,g,_)}async findPattern(u,g){return a_(this._ctx,u,g)}async getHeritageChain(u,g,_){return c_(this._ctx,u,g,_)}onFileChanged(u){return r_(this._ctx,u)}onError(u){return d_(this._ctx,u)}onRoleChanged(u){return t_(this._ctx,u)}searchAnnotations(u){return s_(this._ctx,u)}getSymbolChanges(u,g){return o_(this._ctx,u,g)}pruneChangelog(u){return e_(this._ctx,u)}}export{Vg as symbolSearch,Ug as relationSearch,Xg as patternSearch,e as gildashError,U as GildashError,Cg as Gildash,du as DependencyGraph};
@@ -64,7 +64,7 @@ export interface GildashContext {
64
64
  readonly ignorePatterns: string[];
65
65
  readonly logger: Logger;
66
66
  readonly defaultProject: string;
67
- readonly role: 'owner' | 'reader';
67
+ role: 'owner' | 'reader';
68
68
  readonly db: DbStore;
69
69
  readonly symbolRepo: SymbolRepository;
70
70
  readonly relationRepo: RelationRepository;
@@ -16,7 +16,6 @@ export declare class DbConnection {
16
16
  close(): void;
17
17
  transaction<T>(fn: (tx: DbConnection) => T): T;
18
18
  immediateTransaction<T>(fn: () => T): T;
19
- query(sql: string): unknown;
20
19
  getTableNames(): string[];
21
20
  selectOwner(): {
22
21
  pid: number;
@@ -27,6 +26,7 @@ export declare class DbConnection {
27
26
  replaceOwner(pid: number, instanceId?: string): void;
28
27
  touchOwner(pid: number): void;
29
28
  deleteOwner(pid: number): void;
29
+ private registerRegexpUdf;
30
30
  private requireClient;
31
31
  private closeClient;
32
32
  private isCorruptionError;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zipbul/gildash",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
4
4
  "description": "TypeScript code indexing and dependency graph engine for Bun",
5
5
  "license": "MIT",
6
6
  "repository": {