@zipbul/gildash 0.7.0 → 0.8.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
@@ -292,7 +292,7 @@ try {
292
292
  | `findPattern(pattern, opts?)` | `Promise<PatternMatch[]>` | AST 구조적 검색 (ast-grep) |
293
293
  | `resolveSymbol(name, filePath)` | `ResolvedSymbol` | re-export 체인을 따라 원본 추적 |
294
294
  | `getHeritageChain(name, filePath)` | `Promise<HeritageNode>` | extends/implements 트리 |
295
- | `batchParse(filePaths, opts?)` | `Promise<Map>` | 다중 파일 동시 파싱. `opts`: oxc-parser `ParserOptions`. |
295
+ | `batchParse(filePaths, opts?)` | `Promise<BatchParseResult>` | 다중 파일 동시 파싱. `{ parsed, failures }` 반환. `opts`: oxc-parser `ParserOptions`. |
296
296
 
297
297
  ### 라이프사이클 & 저수준
298
298
 
@@ -300,6 +300,9 @@ try {
300
300
  |--------|-----------|------|
301
301
  | `reindex()` | `Promise<IndexResult>` | 강제 전체 재인덱싱 (owner만 가능) |
302
302
  | `onIndexed(callback)` | `() => void` | 인덱싱 완료 이벤트 구독 |
303
+ | `onFileChanged(callback)` | `() => void` | 파일 변경 이벤트 구독 |
304
+ | `onError(callback)` | `() => void` | 에러 이벤트 구독 |
305
+ | `onRoleChanged(callback)` | `() => void` | owner/reader 역할 변경 이벤트 구독 |
303
306
  | `parseSource(filePath, src, opts?)` | `ParsedFile` | 단일 파일 파싱 & 캐시. `opts`: oxc-parser `ParserOptions`. |
304
307
  | `extractSymbols(parsed)` | `ExtractedSymbol[]` | 파싱된 AST에서 심볼 추출 |
305
308
  | `extractRelations(parsed)` | `CodeRelation[]` | 파싱된 AST에서 관계 추출 |
@@ -407,13 +410,27 @@ Gildash (파사드)
407
410
  동일 SQLite DB를 여러 프로세스가 공유할 때, 단일 writer를 보장합니다:
408
411
 
409
412
  - **Owner** — 파일 워처 실행, 인덱싱 수행, 30초 간격으로 heartbeat 전송
410
- - **Reader** — 읽기 전용 접근; 60초 간격으로 owner 상태 확인, owner가 stale 상태가 되면 reader 중 하나가 owner로 승격
413
+ - **Reader** — 읽기 전용 접근; 15초 간격으로 owner 상태 확인, owner가 60초 이상 stale 상태이면 reader 중 하나가 owner로 승격
411
414
 
412
415
  <br>
413
416
 
414
417
  ## ⬆️ 업그레이드
415
418
 
416
- ### 0.5.x → 0.6.0
419
+ ### 0.7.x → 0.8.0
420
+
421
+ **Breaking:** `batchParse()`가 `Map<string, ParsedFile>` 대신 `BatchParseResult` (`parsed` + `failures` 필드)를 반환합니다.
422
+
423
+ ```diff
424
+ - const parsed = await ledger.batchParse(filePaths);
425
+ - const ast = parsed.get('src/app.ts');
426
+ + const { parsed, failures } = await ledger.batchParse(filePaths);
427
+ + const ast = parsed.get('src/app.ts');
428
+ + if (failures.length > 0) console.warn('실패:', failures);
429
+ ```
430
+
431
+ **새 이벤트 메서드:** `onFileChanged()`, `onError()`, `onRoleChanged()`가 `onIndexed()`와 함께 추가되었습니다.
432
+
433
+ ### 0.6.x → 0.7.0
417
434
 
418
435
  **Breaking:** `@zipbul/result`가 더 이상 public API의 일부가 아닙니다. 모든 메서드가 값을 직접 반환하고, 실패 시 `GildashError`를 throw합니다.
419
436
 
package/README.md CHANGED
@@ -293,7 +293,7 @@ Requires `semantic: true` at open time.
293
293
  | `findPattern(pattern, opts?)` | `Promise<PatternMatch[]>` | AST structural search (ast-grep) |
294
294
  | `resolveSymbol(name, filePath)` | `ResolvedSymbol` | Follow re-export chain to original |
295
295
  | `getHeritageChain(name, filePath)` | `Promise<HeritageNode>` | extends / implements tree |
296
- | `batchParse(filePaths, opts?)` | `Promise<Map>` | Concurrent multi-file parsing. `opts`: oxc-parser `ParserOptions`. |
296
+ | `batchParse(filePaths, opts?)` | `Promise<BatchParseResult>` | Concurrent multi-file parsing. Returns `{ parsed, failures }`. `opts`: oxc-parser `ParserOptions`. |
297
297
 
298
298
  ### Lifecycle & Low-level
299
299
 
@@ -301,6 +301,9 @@ Requires `semantic: true` at open time.
301
301
  |--------|---------|-------------|
302
302
  | `reindex()` | `Promise<IndexResult>` | Force full re-index (owner only) |
303
303
  | `onIndexed(callback)` | `() => void` | Subscribe to index-complete events |
304
+ | `onFileChanged(callback)` | `() => void` | Subscribe to file-change events |
305
+ | `onError(callback)` | `() => void` | Subscribe to error events |
306
+ | `onRoleChanged(callback)` | `() => void` | Subscribe to owner/reader role-change events |
304
307
  | `parseSource(filePath, src, opts?)` | `ParsedFile` | Parse & cache a single file. `opts`: oxc-parser `ParserOptions`. |
305
308
  | `extractSymbols(parsed)` | `ExtractedSymbol[]` | Extract symbols from parsed AST |
306
309
  | `extractRelations(parsed)` | `CodeRelation[]` | Extract relations from parsed AST |
@@ -518,13 +521,27 @@ Gildash (Facade)
518
521
  When multiple processes share the same SQLite database, gildash enforces a single-writer guarantee:
519
522
 
520
523
  - **Owner** — Runs the file watcher, performs indexing, sends a heartbeat every 30 s
521
- - **Reader** — Read-only access; polls owner health every 60 s and self-promotes if the owner goes stale
524
+ - **Reader** — Read-only access; polls owner health every 15 s and self-promotes if the owner goes stale (60 s threshold)
522
525
 
523
526
  <br>
524
527
 
525
528
  ## ⬆️ Upgrading
526
529
 
527
- ### From 0.5.x to 0.6.0
530
+ ### From 0.7.x to 0.8.0
531
+
532
+ **Breaking:** `batchParse()` now returns `BatchParseResult` (with `parsed` and `failures` fields) instead of `Map<string, ParsedFile>`.
533
+
534
+ ```diff
535
+ - const parsed = await ledger.batchParse(filePaths);
536
+ - const ast = parsed.get('src/app.ts');
537
+ + const { parsed, failures } = await ledger.batchParse(filePaths);
538
+ + const ast = parsed.get('src/app.ts');
539
+ + if (failures.length > 0) console.warn('Failed:', failures);
540
+ ```
541
+
542
+ **New event methods:** `onFileChanged()`, `onError()`, `onRoleChanged()` added alongside `onIndexed()`.
543
+
544
+ ### From 0.6.x to 0.7.0
528
545
 
529
546
  **Breaking:** `@zipbul/result` is no longer part of the public API. All methods now return values directly and throw `GildashError` on failure.
530
547
 
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  // @bun
2
- var Ht=Object.defineProperty;var Kt=(n)=>n;function Vt(n,u){this[n]=Kt.bind(null,u)}var Bt=(n,u)=>{for(var t in u)Ht(n,t,{get:u[t],enumerable:!0,configurable:!0,set:Vt.bind(u,t)})};var Su=import.meta.require;import{isErr as Nn}from"@zipbul/result";import Mn from"path";import{existsSync as Bi}from"fs";import{err as fu,isErr as Xt}from"@zipbul/result";import{Database as Tt}from"bun:sqlite";import{mkdirSync as Ct,unlinkSync as au,existsSync as su}from"fs";import{dirname as bt,join as Au}from"path";import{drizzle as Rt}from"drizzle-orm/bun-sqlite";import{migrate as yt}from"drizzle-orm/bun-sqlite/migrator";class a extends Error{type;constructor(n,u,t){super(u,t);this.type=n;this.name="GildashError"}}function v(n,u,t){return new a(n,u,t!==void 0?{cause:t}:void 0)}var e=".gildash",Wn="gildash.db";var bn={};Bt(bn,{watcherOwner:()=>Zt,symbols:()=>U,relations:()=>W,files:()=>R});import{sql as Qt}from"drizzle-orm";import{sqliteTable as Dn,text as b,integer as j,real as Ut,index as tn,primaryKey as Lt,foreignKey as Cn,check as Yt}from"drizzle-orm/sqlite-core";var R=Dn("files",{project:b("project").notNull(),filePath:b("file_path").notNull(),mtimeMs:Ut("mtime_ms").notNull(),size:j("size").notNull(),contentHash:b("content_hash").notNull(),updatedAt:b("updated_at").notNull(),lineCount:j("line_count")},(n)=>[Lt({columns:[n.project,n.filePath]})]),U=Dn("symbols",{id:j("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),filePath:b("file_path").notNull(),kind:b("kind").notNull(),name:b("name").notNull(),startLine:j("start_line").notNull(),startColumn:j("start_column").notNull(),endLine:j("end_line").notNull(),endColumn:j("end_column").notNull(),isExported:j("is_exported").notNull().default(0),signature:b("signature"),fingerprint:b("fingerprint"),detailJson:b("detail_json"),contentHash:b("content_hash").notNull(),indexedAt:b("indexed_at").notNull(),resolvedType:b("resolved_type")},(n)=>[tn("idx_symbols_project_file").on(n.project,n.filePath),tn("idx_symbols_project_kind").on(n.project,n.kind),tn("idx_symbols_project_name").on(n.project,n.name),tn("idx_symbols_fingerprint").on(n.project,n.fingerprint),Cn({columns:[n.project,n.filePath],foreignColumns:[R.project,R.filePath]}).onDelete("cascade")]),W=Dn("relations",{id:j("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),type:b("type").notNull(),srcFilePath:b("src_file_path").notNull(),srcSymbolName:b("src_symbol_name"),dstProject:b("dst_project").notNull(),dstFilePath:b("dst_file_path").notNull(),dstSymbolName:b("dst_symbol_name"),metaJson:b("meta_json")},(n)=>[tn("idx_relations_src").on(n.project,n.srcFilePath),tn("idx_relations_dst").on(n.dstProject,n.dstFilePath),tn("idx_relations_type").on(n.project,n.type),Cn({columns:[n.project,n.srcFilePath],foreignColumns:[R.project,R.filePath]}).onDelete("cascade"),Cn({columns:[n.dstProject,n.dstFilePath],foreignColumns:[R.project,R.filePath]}).onDelete("cascade")]),Zt=Dn("watcher_owner",{id:j("id").primaryKey(),pid:j("pid").notNull(),startedAt:b("started_at").notNull(),heartbeatAt:b("heartbeat_at").notNull()},(n)=>[Yt("watcher_owner_singleton",Qt`${n.id} = 1`)]);class Rn{client=null;drizzle=null;dbPath;txDepth=0;constructor(n){this.dbPath=Au(n.projectRoot,e,Wn)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{Ct(bt(this.dbPath),{recursive:!0}),this.client=new Tt(this.dbPath),this.client.run("PRAGMA journal_mode = WAL"),this.client.run("PRAGMA foreign_keys = OFF"),this.client.run("PRAGMA busy_timeout = 5000"),this.drizzle=Rt(this.client,{schema:bn}),yt(this.drizzle,{migrationsFolder:Au(import.meta.dirname,"migrations")});let n=this.client.prepare("PRAGMA foreign_key_check").all();if(n.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(n.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON");let u=this.client;if(typeof u.function==="function")u.function.call(this.client,"regexp",(t,i)=>{try{return new RegExp(t).test(i)?1:0}catch{return 0}})}catch(n){if(this.isCorruptionError(n)&&su(this.dbPath)){this.closeClient(),au(this.dbPath);for(let t of["-wal","-shm"]){let i=this.dbPath+t;if(su(i))au(i)}let u=this.open();if(Xt(u))return fu(v("store",`Failed to recover database at ${this.dbPath}`,u.data));return u}return fu(v("store",`Failed to open database at ${this.dbPath}`,n))}}close(){this.closeClient(),this.drizzle=null}transaction(n){let u=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return u.transaction(()=>n(this))()}finally{this.txDepth--}}let t=`sp_${this.txDepth++}`;u.run(`SAVEPOINT "${t}"`);try{let i=n(this);return u.run(`RELEASE SAVEPOINT "${t}"`),i}catch(i){throw u.run(`ROLLBACK TO SAVEPOINT "${t}"`),u.run(`RELEASE SAVEPOINT "${t}"`),i}finally{this.txDepth--}}immediateTransaction(n){let u=this.requireClient();this.txDepth++,u.run("BEGIN IMMEDIATE");try{let t=n();return u.run("COMMIT"),t}catch(t){throw u.run("ROLLBACK"),t}finally{this.txDepth--}}query(n){let u=this.requireClient().prepare(n).get();if(!u)return null;return Object.values(u)[0]}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((u)=>u.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(n){let u=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at) VALUES (1, ?, ?, ?)").run(n,u,u)}replaceOwner(n){let u=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at) VALUES (1, ?, ?, ?)").run(n,u,u)}touchOwner(n){let u=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run(u,n)}deleteOwner(n){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(n)}requireClient(){if(!this.client)throw Error("Database is not open. Call open() first.");return this.client}closeClient(){if(this.client)this.client.close(),this.client=null}isCorruptionError(n){if(!(n instanceof Error))return!1;let u=n.message.toLowerCase();return u.includes("malformed")||u.includes("corrupt")||u.includes("not a database")||u.includes("disk i/o error")||u.includes("sqlite_corrupt")}}import{eq as an,and as _u}from"drizzle-orm";class yn{db;constructor(n){this.db=n}getFile(n,u){return this.db.drizzleDb.select().from(R).where(_u(an(R.project,n),an(R.filePath,u))).get()??null}upsertFile(n){this.db.drizzleDb.insert(R).values({project:n.project,filePath:n.filePath,mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}).onConflictDoUpdate({target:[R.project,R.filePath],set:{mtimeMs:n.mtimeMs,size:n.size,contentHash:n.contentHash,updatedAt:n.updatedAt,lineCount:n.lineCount??null}}).run()}getAllFiles(n){return this.db.drizzleDb.select().from(R).where(an(R.project,n)).all()}getFilesMap(n){let u=this.getAllFiles(n),t=new Map;for(let i of u)t.set(i.filePath,i);return t}deleteFile(n,u){this.db.drizzleDb.delete(R).where(_u(an(R.project,n),an(R.filePath,u))).run()}}import{eq as y,and as gn,sql as zn,count as pt}from"drizzle-orm";function kn(n){return n.trim().split(/\s+/).map((u)=>u.trim()).filter((u)=>u.length>0).map((u)=>`"${u.replaceAll('"','""')}"*`).join(" ")}class pn{db;constructor(n){this.db=n}replaceFileSymbols(n,u,t,i){if(this.db.drizzleDb.delete(U).where(gn(y(U.project,n),y(U.filePath,u))).run(),!i.length)return;let g=new Date().toISOString();for(let m of i)this.db.drizzleDb.insert(U).values({project:n,filePath:u,kind:m.kind??"unknown",name:m.name??"",startLine:m.startLine??0,startColumn:m.startColumn??0,endLine:m.endLine??0,endColumn:m.endColumn??0,isExported:m.isExported??0,signature:m.signature??null,fingerprint:m.fingerprint??null,detailJson:m.detailJson??null,contentHash:t,indexedAt:m.indexedAt??g,resolvedType:m.resolvedType??null}).run()}getFileSymbols(n,u){return this.db.drizzleDb.select().from(U).where(gn(y(U.project,n),y(U.filePath,u))).all()}searchByName(n,u,t={}){let i=t.limit??50,g=kn(u);if(!g)return[];return this.db.drizzleDb.select().from(U).where(gn(zn`${U.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${g})`,y(U.project,n),t.kind?y(U.kind,t.kind):void 0)).orderBy(U.name).limit(i).all()}searchByKind(n,u){return this.db.drizzleDb.select().from(U).where(gn(y(U.project,n),y(U.kind,u))).orderBy(U.name).all()}getStats(n){let u=this.db.drizzleDb.select({symbolCount:pt(),fileCount:zn`COUNT(DISTINCT ${U.filePath})`}).from(U).where(y(U.project,n)).get();return{symbolCount:u?.symbolCount??0,fileCount:u?.fileCount??0}}getByFingerprint(n,u){return this.db.drizzleDb.select().from(U).where(gn(y(U.project,n),y(U.fingerprint,u))).all()}deleteFileSymbols(n,u){this.db.drizzleDb.delete(U).where(gn(y(U.project,n),y(U.filePath,u))).run()}searchByQuery(n){let u=this.db.drizzleDb.select().from(U).where(gn(n.ftsQuery?zn`${U.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${n.ftsQuery})`:void 0,n.exactName?y(U.name,n.exactName):void 0,n.project!==void 0?y(U.project,n.project):void 0,n.kind?y(U.kind,n.kind):void 0,n.filePath!==void 0?y(U.filePath,n.filePath):void 0,n.isExported!==void 0?y(U.isExported,n.isExported?1:0):void 0,n.decorator?zn`${U.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${n.decorator})`:void 0,n.resolvedType!==void 0?y(U.resolvedType,n.resolvedType):void 0)).orderBy(U.name).limit(n.regex?Math.max(n.limit*50,5000):n.limit).all();if(!n.regex)return u;try{let t=new RegExp(n.regex);return u.filter((i)=>t.test(i.name)).slice(0,n.limit)}catch{return[]}}}import{eq as C,and as x,isNull as Ju,or as Ft}from"drizzle-orm";class Fn{db;constructor(n){this.db=n}replaceFileRelations(n,u,t){this.db.transaction((i)=>{if(i.drizzleDb.delete(W).where(x(C(W.project,n),C(W.srcFilePath,u))).run(),!t.length)return;for(let g of t)i.drizzleDb.insert(W).values({project:n,type:g.type??"unknown",srcFilePath:g.srcFilePath??u,srcSymbolName:g.srcSymbolName??null,dstProject:g.dstProject??n,dstFilePath:g.dstFilePath??"",dstSymbolName:g.dstSymbolName??null,metaJson:g.metaJson??null}).run()})}getOutgoing(n,u,t){if(t!==void 0)return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(C(W.project,n),C(W.srcFilePath,u),Ft(C(W.srcSymbolName,t),Ju(W.srcSymbolName)))).all();return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(C(W.project,n),C(W.srcFilePath,u))).all()}getIncoming(n){let{dstProject:u,dstFilePath:t}=n;return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(C(W.dstProject,u),C(W.dstFilePath,t))).all()}getByType(n,u){return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(C(W.project,n),C(W.type,u))).all()}deleteFileRelations(n,u){this.db.drizzleDb.delete(W).where(x(C(W.project,n),C(W.srcFilePath,u))).run()}searchRelations(n){return this.db.drizzleDb.select({project:W.project,type:W.type,srcFilePath:W.srcFilePath,srcSymbolName:W.srcSymbolName,dstProject:W.dstProject,dstFilePath:W.dstFilePath,dstSymbolName:W.dstSymbolName,metaJson:W.metaJson}).from(W).where(x(n.project!==void 0?C(W.project,n.project):void 0,n.srcFilePath!==void 0?C(W.srcFilePath,n.srcFilePath):void 0,n.srcSymbolName!==void 0?C(W.srcSymbolName,n.srcSymbolName):void 0,n.dstProject!==void 0?C(W.dstProject,n.dstProject):void 0,n.dstFilePath!==void 0?C(W.dstFilePath,n.dstFilePath):void 0,n.dstSymbolName!==void 0?C(W.dstSymbolName,n.dstSymbolName):void 0,n.type!==void 0?C(W.type,n.type):void 0)).limit(n.limit).all()}retargetRelations(n){let{dstProject:u,oldFile:t,oldSymbol:i,newFile:g,newSymbol:m,newDstProject:O}=n,r=i===null?x(C(W.dstProject,u),C(W.dstFilePath,t),Ju(W.dstSymbolName)):x(C(W.dstProject,u),C(W.dstFilePath,t),C(W.dstSymbolName,i)),w={dstFilePath:g,dstSymbolName:m};if(O!==void 0)w.dstProject=O;this.db.drizzleDb.update(W).set(w).where(r).run()}}import{err as Nu}from"@zipbul/result";import{subscribe as vt}from"@parcel/watcher";import vn from"path";var Et=["**/.git/**",`**/${e}/**`,"**/dist/**","**/node_modules/**"],qt=new Set(["package.json","tsconfig.json"]);function Gt(n){return n.replaceAll("\\","/")}function jt(n){if(n==="update")return"change";if(n==="create")return"create";return"delete"}class En{#n;#u;#t;#g;#i;#m;constructor(n,u=vt,t=console){this.#u=n.projectRoot,this.#t=[...Et,...n.ignorePatterns??[]],this.#g=new Set((n.extensions??[".ts",".mts",".cts"]).map((i)=>i.toLowerCase())),this.#i=u,this.#m=t}async start(n){try{this.#n=await this.#i(this.#u,(u,t)=>{if(u){this.#m.error(v("watcher","Callback error",u));return}try{for(let i of t){let g=Gt(vn.relative(this.#u,i.path));if(g.startsWith(".."))continue;let m=vn.basename(g),O=vn.extname(g).toLowerCase();if(!qt.has(m)&&!this.#g.has(O))continue;if(g.endsWith(".d.ts"))continue;n({eventType:jt(i.type),filePath:g})}}catch(i){this.#m.error(v("watcher","Callback error",i))}},{ignore:this.#t})}catch(u){return Nu(v("watcher","Failed to subscribe watcher",u))}}async close(){if(!this.#n)return;try{await this.#n.unsubscribe(),this.#n=void 0}catch(n){return Nu(v("watcher","Failed to close watcher",n))}}}import qn from"path";import{promises as Pt}from"fs";var dt=["**/node_modules/**","**/.git/**",`**/${e}/**`,"**/dist/**"];async function In(n){let u=[];for await(let t of Pt.glob("**/package.json",{cwd:n,exclude:dt})){let i=qn.dirname(t).replaceAll("\\","/"),g=qn.join(n,t),m=await Bun.file(g).json(),O=typeof m?.name==="string"&&m.name.length>0?m.name:qn.basename(i==="."?n:i);u.push({dir:i,project:O})}return u.sort((t,i)=>i.dir.length-t.dir.length),u}function q(n,u,t="default"){let i=n.replaceAll("\\","/");for(let g of u){if(g.dir===".")return g.project;if(i===g.dir||i.startsWith(`${g.dir}/`))return g.project}return t}import Mu from"path";var c=new Map;async function ht(n){let u=Bun.file(n);if(!await u.exists())return null;try{let t=await u.text(),i=Bun.JSONC.parse(t);return typeof i==="object"&&i!==null?i:null}catch{return null}}async function sn(n){if(c.has(n))return c.get(n)??null;let u=Mu.join(n,"tsconfig.json"),t=await ht(u);if(!t)return c.set(n,null),null;let i=typeof t.compilerOptions==="object"&&t.compilerOptions!==null?t.compilerOptions:null;if(!i)return c.set(n,null),null;let g=typeof i.baseUrl==="string"?i.baseUrl:null,m=typeof i.paths==="object"&&i.paths!==null?i.paths:null;if(!g&&!m)return c.set(n,null),null;let O=g?Mu.resolve(n,g):n,r=new Map;if(m)for(let[f,s]of Object.entries(m)){if(!Array.isArray(s))continue;let A=s.filter((M)=>typeof M==="string");r.set(f,A)}let w={baseUrl:O,paths:r};return c.set(n,w),w}function Hn(n){if(n){c.delete(n);return}c.clear()}import $u from"path";function Kn(n,u){return $u.relative(n,u).replaceAll("\\","/")}function wn(n,u){return $u.resolve(n,u)}function nn(n){let u=Bun.hash.xxHash64(n);return BigInt.asUintN(64,BigInt(u)).toString(16).padStart(16,"0")}import{isErr as Qu}from"@zipbul/result";import{err as xt}from"@zipbul/result";import{parseSync as lt}from"oxc-parser";function An(n,u,t,i=lt){try{let{program:g,errors:m,comments:O}=i(n,u,t);return{filePath:n,program:g,errors:m,comments:O,sourceText:u}}catch(g){return xt(v("parse",`Failed to parse file: ${n}`,g))}}import{promises as ot}from"fs";import{join as et}from"path";async function Wu(n){let{projectRoot:u,extensions:t,ignorePatterns:i,fileRepo:g}=n,m=g.getFilesMap(),O=new Set,r=[],w=[],f=i.map((A)=>new Bun.Glob(A));for await(let A of ot.glob("**/*",{cwd:u})){if(!t.some((S)=>A.endsWith(S)))continue;if(A.startsWith("node_modules/")||A.includes("/node_modules/"))continue;if(f.some((S)=>S.match(A)))continue;O.add(A);let M=et(u,A),k=Bun.file(M),{size:I,lastModified:H}=k,B=m.get(A);if(!B){let S=await k.text(),J=nn(S);r.push({filePath:A,contentHash:J,mtimeMs:H,size:I});continue}if(B.mtimeMs===H&&B.size===I){w.push({filePath:A,contentHash:B.contentHash,mtimeMs:H,size:I});continue}let _=await k.text(),N=nn(_);if(N===B.contentHash)w.push({filePath:A,contentHash:N,mtimeMs:H,size:I});else r.push({filePath:A,contentHash:N,mtimeMs:H,size:I})}let s=[];for(let A of m.keys())if(!O.has(A))s.push(A);return{changed:r,unchanged:w,deleted:s}}function Du(n){let u=[0];for(let t=0;t<n.length;t++)if(n[t]===`
3
- `)u.push(t+1);return u}function Gn(n,u){let t=0,i=n.length-1;while(t<i){let g=t+i+1>>1;if(n[g]<=u)t=g;else i=g-1}return{line:t+1,column:u-n[t]}}import{err as ct}from"@zipbul/result";import{parse as ni}from"comment-parser";function ku(n){try{let u=n.trim();if(u.startsWith("/**"))u=u.slice(3);if(u.endsWith("*/"))u=u.slice(0,-2);let i=ni(`/** ${u} */`)[0]??{description:"",tags:[]};return{description:(i.description??"").trim(),tags:(i.tags??[]).map((g)=>({tag:g.tag??"",name:g.name??"",type:g.type??"",description:g.description??"",optional:g.optional??!1,...g.default!==void 0?{default:g.default}:{}}))}}catch(u){return ct(v("parse","Failed to parse JSDoc comment",u))}}import{isErr as ui}from"@zipbul/result";function Vn(n){let{program:u,sourceText:t,comments:i}=n,g=Du(t);function m(_,N){return{start:Gn(g,_),end:Gn(g,N)}}function O(_){let N=null;for(let S of i){if(S.type!=="Block")continue;if(S.end>_)continue;if(!S.value.startsWith("*"))continue;if(!N||S.end>N.end)N={value:`/*${S.value}*/`,end:S.end}}if(!N)return;for(let S of u.body){let J=S.start??0;if(J===_)continue;if(J>N.end&&J<_)return}return N.value}function r(_){if(!_)return;let N=_.typeAnnotation??_;return t.slice(N.start,N.end)}function w(_){if(!_||_.length===0)return[];return _.map((N)=>{let S=N.expression;if(!S)return{name:"unknown"};if(S.type==="CallExpression"){let J=S.callee?.name??S.callee?.property?.name??"unknown",$=(S.arguments??[]).map((z)=>t.slice(z.start,z.end));return{name:J,arguments:$.length>0?$:void 0}}if(S.type==="Identifier")return{name:S.name??"unknown"};return{name:t.slice(S.start,S.end)}})}function f(_){let N=_.type==="TSParameterProperty"?_.parameter:_;if(N?.type==="RestElement"){let T=`...${N.argument?.name??"unknown"}`,D=N.typeAnnotation,Y=D?r(D):void 0,Q={name:T,isOptional:!1};if(Y)Q.type=Y;return Q}if(N?.type==="AssignmentPattern"){let{left:K,right:T}=N,D=K?.name??"unknown",Y=K?.typeAnnotation,Q=Y?r(Y):void 0,E=t.slice(T.start,T.end),P=w(K?.decorators??[]),d={name:D,isOptional:!0,defaultValue:E};if(Q)d.type=Q;if(P.length>0)d.decorators=P;return d}let S=N?.name??N?.pattern?.name??"unknown",J=!!N?.optional,$=N?.typeAnnotation,z=$?r($):void 0,V=w(N?.decorators??[]),L={name:S,isOptional:J};if(z)L.type=z;if(V.length>0)L.decorators=V;return L}function s(_,N){let S=[];if(N?.async)S.push("async");if(_.static)S.push("static");if(_.abstract)S.push("abstract");if(_.readonly)S.push("readonly");if(_.override)S.push("override");if(_.declare)S.push("declare");if(_.const)S.push("const");let J=_.accessibility;if(J==="private")S.push("private");else if(J==="protected")S.push("protected");else if(J==="public")S.push("public");return S}function A(_){let N=[];if(_.superClass){let J=t.slice(_.superClass.start,_.superClass.end);N.push({kind:"extends",name:J})}let S=_.implements??[];for(let J of S){let $=J.expression??J,z=t.slice($.start,$.end);N.push({kind:"implements",name:z})}return N}function M(_){let N=[];for(let S of _.extends??[]){let J=S.expression??S,$=t.slice(J.start,J.end);N.push({kind:"extends",name:$})}return N}function k(_){let N=[];for(let S of _)if(S.type==="MethodDefinition"){let J=S.key?.name??"unknown",$=S.value,z=S.kind??"method",V=z==="constructor"?"constructor":z==="get"?"getter":z==="set"?"setter":"method",L=s(S,$),K=($?.params??[]).map(f),T=r($?.returnType),D={kind:"method",name:J,span:m(S.start,S.end),isExported:!1,methodKind:V,modifiers:L,parameters:K.length>0?K:void 0,returnType:T};N.push(D)}else if(S.type==="PropertyDefinition"){let J=S.key?.name??"unknown",$=s(S),z={kind:"property",name:J,span:m(S.start,S.end),isExported:!1,modifiers:$};N.push(z)}return N}function I(_){let N=[];for(let S of _)if(S.type==="TSMethodSignature"){let J=S.key?.name??"unknown",$=(S.params??[]).map(f),z=r(S.returnType);N.push({kind:"method",name:J,span:m(S.start,S.end),isExported:!1,modifiers:[],methodKind:"method",parameters:$.length>0?$:void 0,returnType:z})}else if(S.type==="TSPropertySignature"){let J=S.key?.name??"unknown",$=r(S.typeAnnotation),z={kind:"property",name:J,span:m(S.start,S.end),isExported:!1,modifiers:S.readonly?["readonly"]:[],returnType:$};N.push(z)}return N}function H(_,N){let S=_.type??"";if(S==="FunctionDeclaration"){let J=_.id?.name??"default",$=(_.params??[]).map(f),z=r(_.returnType),V=s(_,_),L=w(_.decorators??[]),K=_.typeParameters?.params?.map((D)=>D.name?.name).filter(Boolean)||void 0,T={kind:"function",name:J,span:m(_.start,_.end),isExported:N,modifiers:V,parameters:$.length>0?$:void 0,returnType:z,decorators:L.length>0?L:void 0};if(K&&K.length>0)T.typeParameters=K;return T}if(S==="ClassDeclaration"||S==="ClassExpression"){let J=_.id?.name??"default",$=A(_),z=k(_.body?.body??[]),V=w(_.decorators??[]),L=s(_,_),K=_.typeParameters?.params?.map((D)=>D.name?.name).filter(Boolean)||void 0,T={kind:"class",name:J,span:m(_.start,_.end),isExported:N,modifiers:L,heritage:$.length>0?$:void 0,members:z.length>0?z:void 0,decorators:V.length>0?V:void 0};if(K&&K.length>0)T.typeParameters=K;return T}if(S==="VariableDeclaration"){let J=[];for(let $ of _.declarations??[]){let{id:z,init:V}=$;if(z?.type==="ObjectPattern"){for(let Q of z.properties??[]){let E=Q.value?.name??Q.key?.name??"unknown";J.push({kind:"variable",name:E,span:m(Q.start??$.start,Q.end??$.end),isExported:N,modifiers:[]})}continue}if(z?.type==="ArrayPattern"){for(let Q of z.elements??[]){if(!Q||Q.type!=="Identifier")continue;let E=Q.name??"unknown";J.push({kind:"variable",name:E,span:m(Q.start??$.start,Q.end??$.end),isExported:N,modifiers:[]})}continue}let L=z?.name??"unknown",K="variable",T,D;if(V?.type==="FunctionExpression"||V?.type==="ArrowFunctionExpression")K="function",T=(V.params??[]).map(f),D=r(V.returnType);let Y=[];J.push({kind:K,name:L,span:m($.start,$.end),isExported:N,modifiers:Y,parameters:T,returnType:D})}if(J.length===0)return null;if(J.length===1)return J[0];return J}if(S==="TSTypeAliasDeclaration")return{kind:"type",name:_.id?.name??"unknown",span:m(_.start,_.end),isExported:N,modifiers:[]};if(S==="TSInterfaceDeclaration"){let J=_.id?.name??"unknown",$=M(_),z=I(_.body?.body??[]),V=_.typeParameters?.params?.map((K)=>K.name?.name).filter(Boolean)||void 0,L={kind:"interface",name:J,span:m(_.start,_.end),isExported:N,modifiers:[],heritage:$.length>0?$:void 0,members:z.length>0?z:void 0};if(V&&V.length>0)L.typeParameters=V;return L}if(S==="TSEnumDeclaration"){let J=_.id?.name??"unknown",$=s(_),V=(_.body?.members??[]).map((L)=>({kind:"property",name:L.id?.name??L.id?.value??"unknown",span:m(L.start,L.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:J,span:m(_.start,_.end),isExported:N,modifiers:$,members:V.length>0?V:void 0}}return null}let B=[];for(let _ of u.body){let N=null,S=_,J=typeof S.type==="string"?S.type:"";if(J==="ExportNamedDeclaration"){let z=_;if(z.declaration){if(N=H(z.declaration,!0),N&&!Array.isArray(N))N.span=m(z.start,z.end);else if(Array.isArray(N))for(let V of N)V.span=m(z.start,z.end)}}else if(J==="ExportDefaultDeclaration"){let z=_,V=z.declaration;if(V){if(N=H(V,!0),N&&!Array.isArray(N))N.name=V.id?.name??"default",N.isExported=!0,N.span=m(z.start,z.end)}}else N=H(_,!1);let $=Array.isArray(N)?N:N?[N]:[];for(let z of $){let V=_.start??0,L=O(V);if(L){let K=ku(L);if(!ui(K))z.jsDoc=K}B.push(z)}}return B}function ti(n){if(n.kind==="function"||n.kind==="method"){let u=n.parameters?.length??0,t=n.modifiers.includes("async")?1:0;return`params:${u}|async:${t}`}return null}function ii(n){let u={};if(n.jsDoc)u.jsDoc=n.jsDoc;if(n.kind==="function"||n.kind==="method"){if(n.parameters!==void 0)u.parameters=n.parameters;if(n.returnType!==void 0)u.returnType=n.returnType}if(n.heritage?.length)u.heritage=n.heritage;if(n.decorators?.length)u.decorators=n.decorators;if(n.typeParameters?.length)u.typeParameters=n.typeParameters;if(n.modifiers?.length)u.modifiers=n.modifiers;if(n.members?.length)u.members=n.members.map((t)=>{let i=t.modifiers.find((g)=>g==="private"||g==="protected"||g==="public");return{name:t.name,kind:t.methodKind??t.kind,type:t.returnType,visibility:i,isStatic:t.modifiers.includes("static")||void 0,isReadonly:t.modifiers.includes("readonly")||void 0}});return Object.keys(u).length>0?JSON.stringify(u):null}function zu(n,u,t,i,g){let m=ti(n),O=nn(`${u}|${n.kind}|${m??""}`);return{project:t,filePath:i,kind:n.kind,name:u,startLine:n.span.start.line,startColumn:n.span.start.column,endLine:n.span.end.line,endColumn:n.span.end.column,isExported:n.isExported?1:0,signature:m,fingerprint:O,detailJson:ii(n),contentHash:g,indexedAt:new Date().toISOString()}}function jn(n){let{parsed:u,project:t,filePath:i,contentHash:g,symbolRepo:m}=n,O=Vn(u),r=[];for(let w of O){r.push(zu(w,w.name,t,i,g));for(let f of w.members??[])r.push(zu(f,`${w.name}.${f.name}`,t,i,g))}m.replaceFileSymbols(t,i,g,r)}import{resolve as Pn,dirname as gi,extname as mi}from"path";function mn(n,u,t){let i=(g)=>{let m=mi(g);if(m==="")return[g+".ts",g+".d.ts",g+"/index.ts",g+"/index.d.ts",g+".mts",g+"/index.mts",g+".cts",g+"/index.cts"];if(m===".js")return[g.slice(0,-3)+".ts"];if(m===".mjs")return[g.slice(0,-4)+".mts"];if(m===".cjs")return[g.slice(0,-4)+".cts"];return[g]};if(u.startsWith(".")){let g=Pn(gi(n),u);return i(g)}if(t)for(let[g,m]of t.paths){if(m.length===0)continue;let O=g.indexOf("*");if(O===-1){if(u===g){let r=[];for(let w of m)r.push(...i(Pn(t.baseUrl,w)));return r}}else{let r=g.slice(0,O),w=g.slice(O+1);if(u.startsWith(r)&&(w===""||u.endsWith(w))){let f=u.slice(r.length,w===""?void 0:u.length-w.length),s=[];for(let A of m)s.push(...i(Pn(t.baseUrl,A.replace("*",f))));return s}}}return[]}function Iu(n,u,t,i=mn){let g=new Map,m=n.body??[];for(let O of m){if(O.type!=="ImportDeclaration")continue;let r=O.source?.value??"",w=i(u,r,t);if(w.length===0)continue;let f=w[0],s=O.specifiers??[];for(let A of s)switch(A.type){case"ImportSpecifier":g.set(A.local.name,{path:f,importedName:A.imported.name});break;case"ImportDefaultSpecifier":g.set(A.local.name,{path:f,importedName:"default"});break;case"ImportNamespaceSpecifier":g.set(A.local.name,{path:f,importedName:"*"});break}}return g}var ri=new Set(["loc","start","end","scope"]);function On(n,u){if(!n||typeof n!=="object")return;if(Array.isArray(n)){for(let i of n)On(i,u);return}let t=n;u(t);for(let i of Object.keys(t)){if(ri.has(i))continue;let g=t[i];if(g&&typeof g==="object")On(g,u)}}function Hu(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if((u.type==="StringLiteral"||u.type==="Literal")&&typeof u.value==="string")return u.value;return null}function rn(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if(u.type==="Identifier"){let t=u.name;return{root:t,parts:[],full:t}}if(u.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if(u.type==="Super")return{root:"super",parts:[],full:"super"};if(u.type==="MemberExpression"){let t=[],i=u;while(i.type==="MemberExpression"){let O=i.property;if(!O||typeof O.name!=="string")return null;t.unshift(O.name),i=i.object}let g;if(i.type==="Identifier")g=i.name;else if(i.type==="ThisExpression")g="this";else if(i.type==="Super")g="super";else return null;let m=[g,...t].join(".");return{root:g,parts:t,full:m}}return null}function Ku(n,u,t,i=mn){let g=[],m=n.body??[];for(let O of m){if(O.type==="ImportDeclaration"){let r=O.source?.value??"",w=i(u,r,t);if(w.length===0)continue;let f=w[0],s=O.importKind==="type",A=O.specifiers??[];if(A.length===0){let M={};if(s)M.isType=!0;g.push({type:s?"type-references":"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:f,dstSymbolName:null,...Object.keys(M).length>0?{metaJson:JSON.stringify(M)}:{}})}else for(let M of A){let k=M.type,I=s||M.importKind==="type",H={};if(I)H.isType=!0;let B,_;if(k==="ImportDefaultSpecifier")B="default",_=M.local.name;else if(k==="ImportNamespaceSpecifier")B="*",_=M.local.name,H.importKind="namespace";else B=M.imported.name,_=M.local.name;g.push({type:I?"type-references":"imports",srcFilePath:u,srcSymbolName:_,dstFilePath:f,dstSymbolName:B,...Object.keys(H).length>0?{metaJson:JSON.stringify(H)}:{}})}continue}if(O.type==="ExportAllDeclaration"&&O.source){let r=O.source?.value??"",w=i(u,r,t);if(w.length===0)continue;let f=w[0],s=O.exportKind==="type",A={isReExport:!0};if(s)A.isType=!0;g.push({type:s?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:f,dstSymbolName:null,metaJson:JSON.stringify(A)});continue}if(O.type==="ExportNamedDeclaration"&&O.source){let r=O.source?.value??"",w=i(u,r,t);if(w.length===0)continue;let f=w[0],s=O.exportKind==="type",k={isReExport:!0,specifiers:(O.specifiers??[]).map((I)=>({local:I.local.name,exported:I.exported.name}))};if(s)k.isType=!0;g.push({type:s?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:f,dstSymbolName:null,metaJson:JSON.stringify(k)})}}return On(n,(O)=>{if(O.type!=="ImportExpression")return;let r=Hu(O.source);if(!r)return;let w=i(u,r,t);if(w.length===0)return;let f=w[0];g.push({type:"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:f,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),g}function Vu(n,u,t){let i=[],g=[],m=[];function O(){if(g.length>0)return g[g.length-1]??null;return null}function r(f){if(!f)return null;let s=t.get(f.root);if(f.parts.length===0){if(s)return{dstFilePath:s.path,dstSymbolName:s.importedName,resolution:"import"};return{dstFilePath:u,dstSymbolName:f.root,resolution:"local"}}else{if(s&&s.importedName==="*"){let A=f.parts[f.parts.length-1];return{dstFilePath:s.path,dstSymbolName:A,resolution:"namespace"}}return{dstFilePath:u,dstSymbolName:f.full,resolution:"local-member"}}}function w(f){if(!f||typeof f!=="object")return;if(Array.isArray(f)){for(let M of f)w(M);return}let s=f,A=typeof s.type==="string"?s.type:"";if(A==="ClassDeclaration"||A==="ClassExpression"){let M=s,k=M.id?.name??"AnonymousClass";m.push(k),w(M.body),m.pop();return}if(A==="FunctionDeclaration"){let M=s,k=M.id?.name??"anonymous";g.push(k),w(M.body),g.pop();return}if(A==="VariableDeclarator"&&s.init&&(s.init?.type==="FunctionExpression"||s.init?.type==="ArrowFunctionExpression")){let M=s,k=M.id?.name??"anonymous";g.push(k),w(M.init?.body??M.init),g.pop();return}if(A==="MethodDefinition"&&s.value){let M=s,k=m[m.length-1]??"",I=M.key?.name??"anonymous",H=k?`${k}.${I}`:I;g.push(H),w(M.value?.body),g.pop();return}if(A==="FunctionExpression"||A==="ArrowFunctionExpression"){let M=O(),k=M?`${M}.<anonymous>`:"<anonymous>";g.push(k),w(s.body),g.pop();return}if(A==="CallExpression"){let M=s,k=rn(M.callee),I=r(k);if(I){let H=O(),B={};if(H===null)B.scope="module";i.push({type:"calls",srcFilePath:u,srcSymbolName:H,dstFilePath:I.dstFilePath,dstSymbolName:I.dstSymbolName,...Object.keys(B).length>0?{metaJson:JSON.stringify(B)}:{}})}w(M.callee);for(let H of M.arguments??[])w(H);return}if(A==="NewExpression"){let M=s,k=rn(M.callee),I=r(k);if(I){let H=O(),B={isNew:!0};if(H===null)B.scope="module";i.push({type:"calls",srcFilePath:u,srcSymbolName:H,dstFilePath:I.dstFilePath,dstSymbolName:I.dstSymbolName,metaJson:JSON.stringify(B)})}for(let H of M.arguments??[])w(H);return}for(let M of Object.keys(s)){if(M==="loc"||M==="start"||M==="end"||M==="scope")continue;let k=s[M];if(k&&typeof k==="object")w(k)}}return w(n),i}function Bu(n,u,t){let i=[];return On(n,(g)=>{if(g.type==="TSInterfaceDeclaration"){let r=g.id?.name??"AnonymousInterface",w=g.extends??[];for(let f of w){let s=f.expression??f,A=rn(s);if(!A)continue;let M=dn(A,u,t);i.push({type:"extends",srcFilePath:u,srcSymbolName:r,...M})}return}if(g.type!=="ClassDeclaration"&&g.type!=="ClassExpression")return;let m=g.id?.name??"AnonymousClass";if(g.superClass){let r=rn(g.superClass);if(r){let w=dn(r,u,t);i.push({type:"extends",srcFilePath:u,srcSymbolName:m,...w})}}let O=g.implements??[];for(let r of O){let w=r.expression??r,f=rn(w);if(!f)continue;let s=dn(f,u,t);i.push({type:"implements",srcFilePath:u,srcSymbolName:m,...s})}}),i}function dn(n,u,t){let i=t.get(n.root);if(i){if(i.importedName==="*"){let g=n.parts[n.parts.length-1]??n.root;return{dstFilePath:i.path,dstSymbolName:g,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:i.path,dstSymbolName:n.parts.length>0?n.full:i.importedName}}return{dstFilePath:u,dstSymbolName:n.full,metaJson:JSON.stringify({isLocal:!0})}}function Bn(n,u,t,i=mn){let g=Iu(n,u,t,i),m=Ku(n,u,t,i),O=Vu(n,u,g),r=Bu(n,u,g);return[...m,...O,...r]}function hn(n){let{ast:u,project:t,filePath:i,relationRepo:g,projectRoot:m,tsconfigPaths:O,knownFiles:r,boundaries:w}=n,f=wn(m,i),A=Bn(u,f,O,r?(k,I,H)=>{let B=mn(k,I,H);for(let _ of B){let N=Kn(m,_);if(w){let S=q(N,w);if(r.has(`${S}::${N}`))return[_]}else if(r.has(`${t}::${N}`))return[_]}return[]}:void 0),M=[];for(let k of A){let I=Kn(m,k.dstFilePath);if(I.startsWith(".."))continue;let H=Kn(m,k.srcFilePath),B=w?q(I,w):t;M.push({project:t,type:k.type,srcFilePath:H,srcSymbolName:k.srcSymbolName??null,dstProject:B,dstFilePath:I,dstSymbolName:k.dstSymbolName??null,metaJson:k.metaJson??null})}return g.replaceFileRelations(t,i,M),M.length}var wi=100;class xn{opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;constructor(n){this.opts=n,this.logger=n.logger??console,this.tsconfigPathsRaw=sn(n.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(n){return this.startIndex(n,!1)}onIndexed(n){return this.callbacks.add(n),()=>this.callbacks.delete(n)}handleWatcherEvent(n){if(n.filePath.endsWith("tsconfig.json")){Hn(this.opts.projectRoot),this.tsconfigPathsRaw=sn(this.opts.projectRoot),this.fullIndex().catch((u)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",u)});return}if(n.filePath.endsWith("package.json")){let u=this.opts.discoverProjectsFn??In;this.boundariesRefresh=u(this.opts.projectRoot).then((t)=>{this.opts.boundaries=t})}if(this.pendingEvents.push(n),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},wi)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(n,u){if(this.indexingLock){if(u)return this.pendingFullIndex=!0,new Promise((i,g)=>{this.pendingFullIndexWaiters.push({resolve:i,reject:g})});return this.currentIndexing}this.indexingLock=!0;let t=this.doIndex(n,u).then((i)=>{return this.fireCallbacks(i),i}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let i=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((g)=>{for(let m of i)m.resolve(g)}).catch((g)=>{for(let m of i)m.reject(g)})}else if(this.pendingEvents.length>0){let i=this.pendingEvents.splice(0);this.startIndex(i,!1).catch((g)=>this.logger.error("[IndexCoordinator] incremental drain error",g))}});return this.currentIndexing=t,t}async doIndex(n,u){let t=Date.now(),{fileRepo:i,symbolRepo:g,relationRepo:m,dbConnection:O}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let r,w;if(n!==void 0)r=n.filter((S)=>S.eventType==="create"||S.eventType==="change").map((S)=>({filePath:S.filePath,contentHash:"",mtimeMs:0,size:0})),w=n.filter((S)=>S.eventType==="delete").map((S)=>S.filePath);else{let S=new Map;for(let $ of this.opts.boundaries)for(let[z,V]of i.getFilesMap($.project))S.set(z,V);let J=await Wu({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>S}});r=J.changed,w=J.deleted}let f=await this.tsconfigPathsRaw??void 0,s=new Map;for(let S of w){let J=q(S,this.opts.boundaries),$=g.getFileSymbols(J,S);s.set(S,$)}let A=new Map,M=new Map;if(u)for(let S of this.opts.boundaries)for(let J of i.getAllFiles(S.project))for(let $ of g.getFileSymbols(S.project,J.filePath))A.set(`${$.filePath}::${$.name}`,{name:$.name,filePath:$.filePath,kind:$.kind,fingerprint:$.fingerprint});else{for(let S of r){let J=q(S.filePath,this.opts.boundaries);for(let $ of g.getFileSymbols(J,S.filePath))A.set(`${$.filePath}::${$.name}`,{name:$.name,filePath:$.filePath,kind:$.kind,fingerprint:$.fingerprint})}for(let[,S]of s)for(let J of S)A.set(`${J.filePath}::${J.name}`,{name:J.name,filePath:J.filePath,kind:J.kind,fingerprint:J.fingerprint})}let k=()=>{for(let S of w){let J=q(S,this.opts.boundaries);g.deleteFileSymbols(J,S),m.deleteFileRelations(J,S),i.deleteFile(J,S)}},I=async()=>{let{projectRoot:S,boundaries:J}=this.opts,{parseCache:$}=this.opts,z=0,V=0,L=[],K=[];for(let D of r)try{let Y=wn(S,D.filePath),Q=Bun.file(Y),E=await Q.text(),P=D.contentHash||nn(E),d=q(D.filePath,J);i.upsertFile({project:d,filePath:D.filePath,mtimeMs:Q.lastModified,size:Q.size,contentHash:P,updatedAt:new Date().toISOString(),lineCount:E.split(`
4
- `).length});let Z=(this.opts.parseSourceFn??An)(Y,E);if(Qu(Z))throw Z.data;let G=Z;K.push({filePath:D.filePath,text:E,contentHash:P,parsed:G,project:d})}catch(Y){this.logger.error(`[IndexCoordinator] Failed to prepare ${D.filePath}:`,Y),L.push(D.filePath)}let T=new Set;for(let D of J)for(let[Y]of i.getFilesMap(D.project))T.add(`${D.project}::${Y}`);return O.transaction(()=>{for(let D of K)jn({parsed:D.parsed,project:D.project,filePath:D.filePath,contentHash:D.contentHash,symbolRepo:g}),V+=hn({ast:D.parsed.program,project:D.project,filePath:D.filePath,relationRepo:m,projectRoot:S,tsconfigPaths:f,knownFiles:T,boundaries:J}),$.set(D.filePath,D.parsed),z+=g.getFileSymbols(D.project,D.filePath).length}),{symbols:z,relations:V,failedFiles:L}},H=0,B=0,_=[];if(u){let{projectRoot:S,boundaries:J}=this.opts,{parseCache:$}=this.opts,z=await Promise.allSettled(r.map(async(K)=>{let T=wn(S,K.filePath),D=Bun.file(T),Y=await D.text(),Q=K.contentHash||nn(Y);return{filePath:K.filePath,text:Y,contentHash:Q,mtimeMs:D.lastModified,size:D.size}})),V=z.filter((K)=>K.status==="fulfilled").map((K)=>K.value);for(let K of z)if(K.status==="rejected")this.logger.error("[IndexCoordinator] Failed to pre-read file:",K.reason);let L=[];O.transaction(()=>{for(let D of V){let Y=q(D.filePath,J);i.deleteFile(Y,D.filePath)}for(let D of w){let Y=q(D,J);g.deleteFileSymbols(Y,D),m.deleteFileRelations(Y,D),i.deleteFile(Y,D)}for(let D of V){let Y=q(D.filePath,J);i.upsertFile({project:Y,filePath:D.filePath,mtimeMs:D.mtimeMs,size:D.size,contentHash:D.contentHash,updatedAt:new Date().toISOString(),lineCount:D.text.split(`
5
- `).length})}let K=new Set;for(let D of J)for(let[Y]of i.getFilesMap(D.project))K.add(`${D.project}::${Y}`);let T=this.opts.parseSourceFn??An;for(let D of V){let Y=q(D.filePath,J),Q=T(wn(S,D.filePath),D.text);if(Qu(Q))throw Q.data;let E=Q;L.push({filePath:D.filePath,parsed:E}),jn({parsed:E,project:Y,filePath:D.filePath,contentHash:D.contentHash,symbolRepo:g}),B+=hn({ast:E.program,project:Y,filePath:D.filePath,relationRepo:m,projectRoot:S,tsconfigPaths:f,knownFiles:K,boundaries:J}),H+=g.getFileSymbols(Y,D.filePath).length}});for(let K of L)$.set(K.filePath,K.parsed)}else{k();let S=await I();H=S.symbols,B=S.relations,_=S.failedFiles}for(let S of r){let J=q(S.filePath,this.opts.boundaries);for(let $ of g.getFileSymbols(J,S.filePath))M.set(`${$.filePath}::${$.name}`,{name:$.name,filePath:$.filePath,kind:$.kind,fingerprint:$.fingerprint})}let N={added:[],modified:[],removed:[]};for(let[S,J]of M){let $=A.get(S);if(!$)N.added.push({name:J.name,filePath:J.filePath,kind:J.kind});else if($.fingerprint!==J.fingerprint)N.modified.push({name:J.name,filePath:J.filePath,kind:J.kind})}for(let[S,J]of A)if(!M.has(S))N.removed.push({name:J.name,filePath:J.filePath,kind:J.kind});if(!u)for(let[S,J]of s)for(let $ of J){if(!$.fingerprint)continue;let z=q(S,this.opts.boundaries),V=g.getByFingerprint(z,$.fingerprint);if(V.length===1){let L=V[0];m.retargetRelations({dstProject:z,oldFile:S,oldSymbol:$.name,newFile:L.filePath,newSymbol:L.name})}}return{indexedFiles:r.length,removedFiles:w.length,totalSymbols:H,totalRelations:B,durationMs:Date.now()-t,changedFiles:r.map((S)=>S.filePath),deletedFiles:[...w],failedFiles:_,changedSymbols:N}}fireCallbacks(n){for(let u of this.callbacks)try{u(n)}catch(t){this.logger.error("[IndexCoordinator] onIndexed callback threw:",t)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let n=this.pendingEvents.splice(0);this.startIndex(n,!1).catch((u)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",u))}}}function Oi(n){try{return process.kill(n,0),!0}catch(u){if(typeof u==="object"&&u&&"code"in u)return u.code!=="ESRCH";return!0}}function Si(n){let u=new Date(n).getTime();return Number.isNaN(u)?0:u}function Uu(n,u,t={}){let i=t.now??Date.now,g=t.isAlive??Oi,m=t.staleAfterSeconds??90;return n.immediateTransaction(()=>{let O=n.selectOwner();if(!O)return n.insertOwner(u),"owner";let r=Math.floor((i()-Si(O.heartbeat_at))/1000);if(g(O.pid)&&r<m)return"reader";return n.replaceOwner(u),"owner"})}function Lu(n,u){n.deleteOwner(u)}function Yu(n,u){n.touchOwner(u)}class _n{#n;#u=new Map;constructor(n){this.#n=Math.max(1,n)}get size(){return this.#u.size}has(n){return this.#u.has(n)}get(n){if(!this.#u.has(n))return;let u=this.#u.get(n);return this.#u.delete(n),this.#u.set(n,u),u}set(n,u){if(this.#u.has(n))this.#u.delete(n);if(this.#u.set(n,u),this.#u.size>this.#n){let t=this.#u.keys().next().value;if(t!==void 0)this.#u.delete(t)}}delete(n){return this.#u.delete(n)}clear(){this.#u.clear()}}class ln{lru;constructor(n=500){this.lru=new _n(n)}get(n){return this.lru.get(n)}set(n,u){this.lru.set(n,u)}invalidate(n){this.lru.delete(n)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function on(n){let{symbolRepo:u,project:t,query:i}=n,g=i.project??t,m=i.limit??100,O={kind:i.kind,filePath:i.filePath,isExported:i.isExported,project:g,limit:m,resolvedType:i.resolvedType};if(i.text)if(i.exact)O.exactName=i.text;else{let w=kn(i.text);if(w)O.ftsQuery=w}if(i.decorator)O.decorator=i.decorator;if(i.regex)O.regex=i.regex;return u.searchByQuery(O).map((w)=>({id:w.id,filePath:w.filePath,kind:w.kind,name:w.name,span:{start:{line:w.startLine,column:w.startColumn},end:{line:w.endLine,column:w.endColumn}},isExported:w.isExported===1,signature:w.signature,fingerprint:w.fingerprint,detail:w.detailJson?(()=>{try{return JSON.parse(w.detailJson)}catch{return{}}})():{}}))}function en(n){let{relationRepo:u,project:t,query:i}=n,g=i.project??t,m=i.limit??500;return u.searchRelations({srcFilePath:i.srcFilePath,srcSymbolName:i.srcSymbolName,dstFilePath:i.dstFilePath,dstSymbolName:i.dstSymbolName,dstProject:i.dstProject,type:i.type,project:g,limit:m}).map((r)=>{let w;if(r.metaJson)try{w=JSON.parse(r.metaJson)}catch{console.error("[relationSearch] malformed metaJson:",r.metaJson)}return{type:r.type,srcFilePath:r.srcFilePath,srcSymbolName:r.srcSymbolName,dstFilePath:r.dstFilePath,dstSymbolName:r.dstSymbolName,dstProject:r.dstProject,metaJson:r.metaJson??void 0,meta:w}})}import{findInFiles as fi,Lang as ai}from"@ast-grep/napi";async function cn(n){if(n.filePaths.length===0)return[];let u=[];return await fi(ai.TypeScript,{paths:n.filePaths,matcher:{rule:{pattern:n.pattern}}},(t,i)=>{if(t)return;for(let g of i){let m=g.range();u.push({filePath:g.getRoot().filename(),startLine:m.start.line+1,endLine:m.end.line+1,matchedText:g.text()})}}),u}import p from"typescript";import{isErr as Ki}from"@zipbul/result";import l from"typescript";import si from"path";import{err as nu}from"@zipbul/result";function Ai(n){try{return Su("fs").readFileSync(n,"utf-8")}catch{return}}function _i(n){try{return Su("fs").readFileSync(n,"utf-8")}catch{return}}class Qn{#n;#u;#t=!1;__testing__;constructor(n,u){this.#n=n,this.#u=u,this.__testing__={host:u}}static create(n,u={}){let t=u.readConfigFile??Ai,i=u.resolveNonTrackedFile??_i,g=si.dirname(n),m=t(n);if(m===void 0)return nu(v("semantic",`tsconfig not found: ${n}`));let O=l.parseJsonText(n,m),r=O.parseDiagnostics;if(r&&r.length>0){let A=r.map((M)=>l.flattenDiagnosticMessageText(M.messageText,`
6
- `)).join("; ");return nu(v("semantic",`tsconfig parse error: ${A}`))}let w=l.parseJsonSourceFileConfigFileContent(O,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(A)=>t(A)!==void 0||i(A)!==void 0,readFile:(A)=>t(A)??i(A)},g);if(w.errors.length>0){let A=w.errors.filter((M)=>M.category===l.DiagnosticCategory.Error&&M.code!==18003);if(A.length>0){let M=A.map((k)=>l.flattenDiagnosticMessageText(k.messageText,`
7
- `)).join("; ");return nu(v("semantic",`tsconfig compile error: ${M}`))}}let f=new Zu(w.fileNames,w.options,g,i),s=l.createLanguageService(f);return new Qn(s,f)}get isDisposed(){return this.#t}getProgram(){this.#g();let n=this.#n.getProgram();if(!n)throw Error("TscProgram: LanguageService returned null Program");return n}getChecker(){return this.#g(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#g(),this.#n}notifyFileChanged(n,u){if(this.#t)return;this.#u.updateFile(n,u)}removeFile(n){if(this.#t)return;this.#u.removeFile(n)}dispose(){if(this.#t)return;this.#t=!0,this.#n.dispose()}#g(){if(this.#t)throw Error("TscProgram is disposed")}}class Zu{#n;#u;#t;#g;#i=new Map;constructor(n,u,t,i){this.#n=[...n],this.#u=u,this.#t=t,this.#g=i}updateFile(n,u){let t=this.#i.get(n);if(t)t.version+=1,t.content=u;else this.#i.set(n,{version:1,content:u})}removeFile(n){this.#i.delete(n),this.#n=this.#n.filter((u)=>u!==n)}getScriptFileNames(){let n=[...this.#i.keys()];return[...this.#n.filter((t)=>!this.#i.has(t)),...n]}getScriptVersion(n){let u=this.#i.get(n);return u?String(u.version):"0"}getScriptSnapshot(n){let u=this.#i.get(n);if(u)return l.ScriptSnapshot.fromString(u.content);let t=this.#g(n);if(t!==void 0)return l.ScriptSnapshot.fromString(t);return}getCurrentDirectory(){return this.#t}getCompilationSettings(){return this.#u}getDefaultLibFileName(n){return l.getDefaultLibFilePath(n)}fileExists(n){if(this.#i.has(n))return!0;return this.#g(n)!==void 0}readFile(n){let u=this.#i.get(n);if(u)return u.content;return this.#g(n)}}import F from"typescript";import Ji from"typescript";function o(n,u){if(u<0||u>=n.getEnd())return;function t(i){let g=i.getStart(n,!1),m=i.getEnd();if(u<g||u>=m)return;let O;return Ji.forEachChild(i,(r)=>{if(!O)O=t(r)}),O??i}return t(n)}function Ni(n){return!!(n.flags&F.TypeFlags.Object)&&!!(n.objectFlags&F.ObjectFlags.Reference)}function Jn(n,u,t=0){let i=n.typeToString(u),g=u.flags,m=!!(g&F.TypeFlags.Union),O=!!(g&F.TypeFlags.Intersection),r;if(t<8&&Ni(u)){let A=n.getTypeArguments(u);if(A.length>0)r=A}let w=!!(g&F.TypeFlags.TypeParameter)||r!==void 0&&r.length>0,f;if(m&&t<8)f=u.types.map((A)=>Jn(n,A,t+1));else if(O&&t<8)f=u.types.map((A)=>Jn(n,A,t+1));let s;if(r&&r.length>0)s=r.map((A)=>Jn(n,A,t+1));return{text:i,flags:g,isUnion:m,isIntersection:O,isGeneric:w,members:f,typeArguments:s}}function Mi(n){return F.isFunctionDeclaration(n)||F.isVariableDeclaration(n)||F.isClassDeclaration(n)||F.isInterfaceDeclaration(n)||F.isTypeAliasDeclaration(n)||F.isEnumDeclaration(n)||F.isMethodDeclaration(n)||F.isPropertyDeclaration(n)||F.isPropertySignature(n)||F.isMethodSignature(n)}class uu{program;constructor(n){this.program=n}collectAt(n,u){let t=this.program.getProgram(),i=this.program.getChecker();if(u<0)return null;let g=t.getSourceFile(n);if(!g)return null;if(u>=g.getEnd())return null;let m=o(g,u);if(!m)return null;if(!F.isIdentifier(m))return null;try{let O=i.getTypeAtLocation(m);return Jn(i,O)}catch{return null}}collectFile(n){let u=new Map,t=this.program.getProgram(),i=this.program.getChecker(),g=t.getSourceFile(n);if(!g)return u;function m(O){if(Mi(O)&&O.name&&F.isIdentifier(O.name)){let r=O.name;try{let w=i.getTypeAtLocation(r),f=r.getStart(g);u.set(f,Jn(i,w))}catch{}}F.forEachChild(O,m)}return m(g),u}}import un from"typescript";var $i=1000,Wi=1;function Di(n){let u=n.declarations?.[0],t=u?.getSourceFile(),i=u?un.getNameOfDeclaration(u):void 0;return{name:n.getName(),filePath:t?.fileName??"",position:i?.getStart(t,!1)??u?.getStart(t,!1)??0}}function Un(n,u=0){let t=n.declarations?.[0],i=t?.getSourceFile(),g=t?un.getNameOfDeclaration(t):void 0,m=i?.fileName??"",O=g?.getStart(i,!1)??t?.getStart(i,!1)??0,r={name:n.getName(),filePath:m,position:O},w=n;if(w.parent)r.parent=Di(w.parent);if(u<Wi){let f=n.flags,s=!!(f&un.SymbolFlags.Enum),A=!!(f&(un.SymbolFlags.NamespaceModule|un.SymbolFlags.ValueModule)),M=!!(f&(un.SymbolFlags.Class|un.SymbolFlags.Interface));if(s&&n.exports&&n.exports.size>0){let k=[];n.exports.forEach((I)=>{k.push(Un(I,u+1))}),r.members=k}else if(M&&n.members&&n.members.size>0){let k=[];n.members.forEach((I)=>{k.push(Un(I,u+1))}),r.members=k}if(A&&n.exports&&n.exports.size>0){let k=[];n.exports.forEach((I)=>{k.push(Un(I,u+1))}),r.exports=k}}return r}class tu{#n;#u;#t=new Map;constructor(n,u=$i){this.#n=n,this.#u=new _n(u)}get(n,u){if(this.#n.isDisposed)return null;let t=`${n}:${u}`,i=this.#u.get(t);if(i!==void 0)return i;let m=this.#n.getProgram().getSourceFile(n);if(!m)return null;let O=o(m,u);if(!O||!un.isIdentifier(O))return null;let w=this.#n.getChecker().getSymbolAtLocation(O);if(!w)return null;let f=Un(w);this.#u.set(t,f);let s=this.#t.get(n);if(!s)s=new Set,this.#t.set(n,s);return s.add(t),f}invalidate(n){let u=this.#t.get(n);if(u){for(let t of u)this.#u.delete(t);this.#t.delete(n)}}clear(){this.#u.clear(),this.#t.clear()}}import ki from"typescript";class iu{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let t=this.#n.getProgram(),i=t.getSourceFile(n);if(!i)return[];let g=o(i,u);if(!g||!ki.isIdentifier(g))return[];let O=this.#n.getLanguageService().findReferences(n,u);if(!O||O.length===0)return[];let r=[];for(let w of O)for(let f of w.references){let s=t.getSourceFile(f.fileName);if(!s)continue;let{line:A,character:M}=s.getLineAndCharacterOfPosition(f.textSpan.start);r.push({filePath:f.fileName,position:f.textSpan.start,line:A+1,column:M,isDefinition:f.isDefinition??!1,isWrite:f.isWriteAccess??!1})}return r}}import X from"typescript";function zi(n,u){let t=o(n,u);if(!t)return;if(Xu(t))return t;let i=t.parent;for(let g=0;g<5&&i;g++){if(Xu(i))return i;i=i.parent}return t}function Xu(n){return X.isClassDeclaration(n)||X.isClassExpression(n)||X.isFunctionDeclaration(n)||X.isFunctionExpression(n)||X.isArrowFunction(n)||X.isVariableDeclaration(n)||X.isObjectLiteralExpression(n)}function Tu(n){if(X.isClassDeclaration(n)||X.isClassExpression(n))return"class";if(X.isFunctionDeclaration(n)||X.isFunctionExpression(n)||X.isArrowFunction(n))return"function";if(X.isObjectLiteralExpression(n))return"object";if(X.isVariableDeclaration(n)&&n.initializer)return Tu(n.initializer);return"class"}function Ii(n,u){if(X.isClassDeclaration(n)||X.isFunctionDeclaration(n))return n.name?.getText(u)??"";if(X.isClassExpression(n))return n.name?.getText(u)??"";if(X.isVariableDeclaration(n)&&X.isIdentifier(n.name))return n.name.getText(u);if(X.isFunctionExpression(n))return n.name?.getText(u)??"";if(X.isArrowFunction(n)&&n.parent&&X.isVariableDeclaration(n.parent)){if(X.isIdentifier(n.parent.name))return n.parent.name.getText(u)}if(X.isObjectLiteralExpression(n)&&n.parent&&X.isVariableDeclaration(n.parent)){if(X.isIdentifier(n.parent.name))return n.parent.name.getText(u)}return""}function Hi(n){if(!X.isClassDeclaration(n)&&!X.isClassExpression(n))return!1;let u=n.heritageClauses;if(!u)return!1;return u.some((t)=>t.token===X.SyntaxKind.ImplementsKeyword)}class gu{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let t=this.#n.getProgram(),i=t.getSourceFile(n);if(!i)return[];let g=o(i,u);if(!g||!X.isIdentifier(g))return[];let O=this.#n.getLanguageService().getImplementationAtPosition(n,u);if(!O||O.length===0)return[];let r=[];for(let w of O){if(w.kind===X.ScriptElementKind.interfaceElement||w.kind===X.ScriptElementKind.typeElement)continue;let f=t.getSourceFile(w.fileName);if(!f)continue;let s=zi(f,w.textSpan.start);if(!s)continue;let A=Tu(s),M=Ii(s,f),k=Hi(s);r.push({filePath:w.fileName,symbolName:M,position:w.textSpan.start,kind:A,isExplicit:k})}return r}}function Cu(n){return p.canHaveModifiers(n)&&p.getModifiers(n)?.some((u)=>u.kind===p.SyntaxKind.ExportKeyword)===!0}function Vi(n){if(p.isFunctionDeclaration(n))return"function";if(p.isClassDeclaration(n))return"class";if(p.isInterfaceDeclaration(n))return"interface";if(p.isTypeAliasDeclaration(n))return"type";if(p.isEnumDeclaration(n))return"enum";if(p.isVariableDeclaration(n))return"const";if(p.isVariableStatement(n))return"const";return"unknown"}function bu(n){if(n>=97&&n<=122)return!0;if(n>=65&&n<=90)return!0;if(n>=48&&n<=57)return!0;if(n===95||n===36)return!0;return!1}class Ln{#n;#u;#t;#g;#i;#m=!1;constructor(n,u,t,i,g){this.#n=n,this.#u=u,this.#t=t,this.#g=i,this.#i=g}static create(n,u={}){let t=Qn.create(n,{readConfigFile:u.readConfigFile,resolveNonTrackedFile:u.resolveNonTrackedFile});if(Ki(t))return t;let i=t,g=u.typeCollector??new uu(i),m=u.symbolGraph??new tu(i),O=u.referenceResolver??new iu(i),r=u.implementationFinder??new gu(i);return new Ln(i,g,m,O,r)}get isDisposed(){return this.#m}collectTypeAt(n,u){return this.#r(),this.#u.collectAt(n,u)}collectFileTypes(n){return this.#r(),this.#u.collectFile(n)}findReferences(n,u){return this.#r(),this.#g.findAt(n,u)}findImplementations(n,u){return this.#r(),this.#i.findAt(n,u)}getSymbolNode(n,u){return this.#r(),this.#t.get(n,u)}getModuleInterface(n){this.#r();let u=this.#u.collectFile(n),t=[],g=this.#n.getProgram().getSourceFile(n);if(!g)return{filePath:n,exports:t};function m(O){if(p.isVariableStatement(O)&&Cu(O)){for(let r of O.declarationList.declarations)if(p.isIdentifier(r.name)){let w=r.name.getStart(g),f=u.get(w)??null;t.push({name:r.name.text,kind:"const",resolvedType:f})}return}if((p.isFunctionDeclaration(O)||p.isClassDeclaration(O)||p.isInterfaceDeclaration(O)||p.isTypeAliasDeclaration(O)||p.isEnumDeclaration(O))&&Cu(O)&&O.name){let r=O.name,w=r.getStart(g),f=u.get(w)??null;t.push({name:r.text,kind:Vi(O),resolvedType:f});return}p.forEachChild(O,m)}return m(g),{filePath:n,exports:t}}notifyFileChanged(n,u){if(this.#m)return;this.#n.notifyFileChanged(n,u),this.#t.invalidate(n)}notifyFileDeleted(n){if(this.#m)return;this.#n.removeFile(n),this.#t.invalidate(n)}lineColumnToPosition(n,u,t){this.#r();let i=this.#n.getProgram().getSourceFile(n);if(!i)return null;try{return p.getPositionOfLineAndCharacter(i,u-1,t)}catch{return null}}findNamePosition(n,u,t){this.#r();let i=this.#n.getProgram().getSourceFile(n);if(!i)return null;let g=i.getFullText(),m=u;while(m<g.length){let O=g.indexOf(t,m);if(O<0)return null;let r=O>0?g.charCodeAt(O-1):32,w=O+t.length<g.length?g.charCodeAt(O+t.length):32;if(!bu(r)&&!bu(w))return O;m=O+1}return null}dispose(){if(this.#m)return;this.#m=!0,this.#n.dispose(),this.#t.clear()}#r(){if(this.#m)throw Error("SemanticLayer is disposed")}}var Qi=30000,Ru=60000,Ui=10;function Li(n,u){return(t)=>{if(u.handleWatcherEvent?.(t),n.semanticLayer)if(t.eventType==="delete")n.semanticLayer.notifyFileDeleted(t.filePath);else n.readFileFn(t.filePath).then((i)=>{n.semanticLayer?.notifyFileChanged(t.filePath,i)}).catch(()=>{})}}async function Yi(n){if(!n.semanticLayer)return;let u=n.fileRepo.getAllFiles(n.defaultProject);await Promise.all(u.map(async(t)=>{try{let i=Mn.resolve(n.projectRoot,t.filePath),g=await n.readFileFn(i);n.semanticLayer?.notifyFileChanged(i,g)}catch{}}))}async function yu(n,u){let t=n.coordinatorFactory?n.coordinatorFactory():new xn({projectRoot:n.projectRoot,boundaries:n.boundaries,extensions:n.extensions,ignorePatterns:n.ignorePatterns,dbConnection:n.db,parseCache:n.parseCache,fileRepo:n.fileRepo,symbolRepo:n.symbolRepo,relationRepo:n.relationRepo,logger:n.logger});n.coordinator=t;for(let i of n.onIndexedCallbacks)t.onIndexed(i);if(t.onIndexed(()=>{n.graphCache=null,n.graphCacheKey=null}),u.isWatchMode){let i=n.watcherFactory?n.watcherFactory():new En({projectRoot:n.projectRoot,ignorePatterns:n.ignorePatterns,extensions:n.extensions},void 0,n.logger);await i.start(Li(n,t)).then((g)=>{if(Nn(g))throw g.data}),n.watcher=i,n.timer=setInterval(()=>{n.updateHeartbeatFn(n.db,process.pid)},Qi)}await t.fullIndex(),await Yi(n)}function Zi(n,u){let t=["SIGTERM","SIGINT","beforeExit"];for(let i of t){let g=()=>{u().catch((m)=>n.logger.error("[Gildash] close error during signal",i,m))};if(i==="beforeExit")process.on("beforeExit",g);else process.on(i,g);n.signalHandlers.push([i,g])}}async function pu(n){let{projectRoot:u,extensions:t=[".ts",".mts",".cts"],ignorePatterns:i=["**/node_modules/**"],parseCacheCapacity:g=500,logger:m=console,existsSyncFn:O=Bi,dbConnectionFactory:r,watcherFactory:w,coordinatorFactory:f,repositoryFactory:s,acquireWatcherRoleFn:A=Uu,releaseWatcherRoleFn:M=Lu,updateHeartbeatFn:k=Yu,discoverProjectsFn:I=In,parseSourceFn:H=An,extractSymbolsFn:B=Vn,extractRelationsFn:_=Bn,symbolSearchFn:N=on,relationSearchFn:S=en,patternSearchFn:J=cn,loadTsconfigPathsFn:$=sn,readFileFn:z=async(Q)=>Bun.file(Q).text(),unlinkFn:V=async(Q)=>{await Bun.file(Q).unlink()},watchMode:L,semantic:K,semanticLayerFactory:T}=n;if(!Mn.isAbsolute(u))throw new a("validation",`Gildash: projectRoot must be an absolute path, got: "${u}"`);if(!O(u))throw new a("validation",`Gildash: projectRoot does not exist: "${u}"`);let D=r?r():new Rn({projectRoot:u}),Y=D.open();if(Nn(Y))throw Y.data;try{let Q=await I(u),E=Q[0]?.project??Mn.basename(u),P=s?s():(()=>{let G=D;return{fileRepo:new yn(G),symbolRepo:new pn(G),relationRepo:new Fn(G),parseCache:new ln(g)}})(),d=L??!0,fn;if(d)fn=await Promise.resolve(A(D,process.pid,{}));else fn="owner";let Z={projectRoot:u,extensions:t,ignorePatterns:i,logger:m,defaultProject:E,role:fn,db:D,symbolRepo:P.symbolRepo,relationRepo:P.relationRepo,fileRepo:P.fileRepo,parseCache:P.parseCache,releaseWatcherRoleFn:M,parseSourceFn:H,extractSymbolsFn:B,extractRelationsFn:_,symbolSearchFn:N,relationSearchFn:S,patternSearchFn:J,readFileFn:z,unlinkFn:V,existsSyncFn:O,acquireWatcherRoleFn:A,updateHeartbeatFn:k,watcherFactory:w,coordinatorFactory:f,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:Q,onIndexedCallbacks:new Set,graphCache:null,graphCacheKey:null,semanticLayer:null};if(Hn(u),Z.tsconfigPaths=await $(u),K){let G=Mn.join(u,"tsconfig.json");try{if(T)Z.semanticLayer=T(G);else{let h=Ln.create(G);if(Nn(h))throw h.data;Z.semanticLayer=h}}catch(h){if(h instanceof a)throw h;throw new a("semantic","Gildash: semantic layer creation failed",{cause:h})}}if(fn==="owner")await yu(Z,{isWatchMode:d});else{let G=0,h=async()=>{try{let Xn=await Promise.resolve(Z.acquireWatcherRoleFn(Z.db,process.pid,{}));if(G=0,Xn==="owner"){clearInterval(Z.timer),Z.timer=null;try{await yu(Z,{isWatchMode:!0})}catch(Tn){if(Z.logger.error("[Gildash] owner promotion failed, reverting to reader",Tn),Z.watcher){let $n=await Z.watcher.close();if(Nn($n))Z.logger.error("[Gildash] watcher close error during promotion rollback",$n.data);Z.watcher=null}if(Z.coordinator)await Z.coordinator.shutdown().catch(($n)=>Z.logger.error("[Gildash] coordinator shutdown error during promotion rollback",$n)),Z.coordinator=null;if(Z.timer===null)Z.timer=setInterval(h,Ru)}}}catch(Xn){if(G++,Z.logger.error("[Gildash] healthcheck error",Xn),G>=Ui)Z.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(Z.timer),Z.timer=null,Yn(Z).catch((Tn)=>Z.logger.error("[Gildash] close error during healthcheck shutdown",Tn))}};Z.timer=setInterval(h,Ru)}if(d)Zi(Z,()=>Yn(Z));return Z}catch(Q){if(D.close(),Q instanceof a)throw Q;throw new a("store","Gildash: initialization failed",{cause:Q})}}async function Yn(n,u){if(n.closed)return;n.closed=!0;let t=[];for(let[i,g]of n.signalHandlers)if(i==="beforeExit")process.off("beforeExit",g);else process.off(i,g);if(n.signalHandlers=[],n.semanticLayer){try{n.semanticLayer.dispose()}catch(i){t.push(i instanceof Error?i:Error(String(i)))}n.semanticLayer=null}if(n.coordinator)try{await n.coordinator.shutdown()}catch(i){t.push(i instanceof Error?i:Error(String(i)))}if(n.watcher){let i=await n.watcher.close();if(Nn(i))t.push(i.data)}if(n.timer!==null)clearInterval(n.timer),n.timer=null;try{n.releaseWatcherRoleFn(n.db,process.pid)}catch(i){t.push(i instanceof Error?i:Error(String(i)))}try{n.db.close()}catch(i){t.push(i instanceof Error?i:Error(String(i)))}if(u?.cleanup)for(let i of["","-wal","-shm"])try{await n.unlinkFn(Mn.join(n.projectRoot,e,Wn+i))}catch{}if(t.length>0)throw new a("close","Gildash: one or more errors occurred during close()",{cause:t})}import{isErr as Fu}from"@zipbul/result";function vu(n,u,t,i){if(n.closed)throw new a("closed","Gildash: instance is closed");let g=n.parseSourceFn(u,t,i);if(Fu(g))throw g.data;return n.parseCache.set(u,g),g}async function Eu(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");let i=new Map;return await Promise.all(u.map(async(g)=>{try{let m=await n.readFileFn(g),O=n.parseSourceFn(g,m,t);if(!Fu(O))i.set(g,O)}catch{}})),i}function qu(n,u){if(n.closed)return;return n.parseCache.get(u)}function Gu(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");return n.extractSymbolsFn(u)}function ju(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");return n.extractRelationsFn(u.program,u.filePath,n.tsconfigPaths??void 0)}import Pu from"path";function du(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.symbolRepo.getStats(u??n.defaultProject)}catch(t){if(t instanceof a)throw t;throw new a("store","Gildash: getStats failed",{cause:t})}}function mu(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:n.defaultProject,query:u})}catch(t){if(t instanceof a)throw t;throw new a("search","Gildash: searchSymbols failed",{cause:t})}}function hu(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:n.defaultProject,query:u})}catch(t){if(t instanceof a)throw t;throw new a("search","Gildash: searchRelations failed",{cause:t})}}function xu(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:void 0,query:u})}catch(t){if(t instanceof a)throw t;throw new a("search","Gildash: searchAllSymbols failed",{cause:t})}}function lu(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:void 0,query:u})}catch(t){if(t instanceof a)throw t;throw new a("search","Gildash: searchAllRelations failed",{cause:t})}}function ou(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.fileRepo.getAllFiles(u??n.defaultProject)}catch(t){if(t instanceof a)throw t;throw new a("store","Gildash: listIndexedFiles failed",{cause:t})}}function eu(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:t??n.defaultProject,query:{srcFilePath:u,dstFilePath:u,limit:1e4}})}catch(i){if(i instanceof a)throw i;throw new a("search","Gildash: getInternalRelations failed",{cause:i})}}function cu(n,u,t,i){if(n.closed)throw new a("closed","Gildash: instance is closed");try{let g=i??n.defaultProject,m=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:g,query:{text:u,exact:!0,filePath:t,limit:1}});if(m.length===0)return null;let O=m[0],r=O.detail,w={...O,members:Array.isArray(r.members)?r.members:void 0,jsDoc:typeof r.jsDoc==="string"?r.jsDoc:void 0,parameters:typeof r.parameters==="string"?r.parameters:void 0,returnType:typeof r.returnType==="string"?r.returnType:void 0,heritage:Array.isArray(r.heritage)?r.heritage:void 0,decorators:Array.isArray(r.decorators)?r.decorators:void 0,typeParameters:typeof r.typeParameters==="string"?r.typeParameters:void 0};if(n.semanticLayer)try{let f=Pu.isAbsolute(t)?t:Pu.resolve(n.projectRoot,t),s=n.semanticLayer.lineColumnToPosition(f,O.span.start.line,O.span.start.column);if(s!==null){let A=n.semanticLayer.findNamePosition(f,s,O.name)??s,M=n.semanticLayer.collectTypeAt(f,A);if(M)w.resolvedType=M}}catch{}return w}catch(g){if(g instanceof a)throw g;throw new a("search","Gildash: getFullSymbol failed",{cause:g})}}function nt(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{let i=t??n.defaultProject,g=n.fileRepo.getFile(i,u);if(!g)throw new a("search",`Gildash: file '${u}' is not in the index`);let m=n.symbolRepo.getFileSymbols(i,u),O=n.relationRepo.getOutgoing(i,u);return{filePath:g.filePath,lineCount:g.lineCount??0,size:g.size,symbolCount:m.length,exportedSymbolCount:m.filter((r)=>r.isExported).length,relationCount:O.length}}catch(i){if(i instanceof a)throw i;throw new a("store","Gildash: getFileStats failed",{cause:i})}}function ut(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.fileRepo.getFile(t??n.defaultProject,u)}catch(i){if(i instanceof a)throw i;throw new a("store","Gildash: getFileInfo failed",{cause:i})}}function tt(n,u,t){return mu(n,{filePath:u,project:t??void 0,limit:1e4})}function it(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{let g=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:t??n.defaultProject,query:{filePath:u,isExported:!0}}).map((m)=>({name:m.name,kind:m.kind,parameters:m.detail.parameters??void 0,returnType:m.detail.returnType??void 0,jsDoc:m.detail.jsDoc??void 0}));return{filePath:u,exports:g}}catch(i){if(i instanceof a)throw i;throw new a("search","Gildash: getModuleInterface failed",{cause:i})}}class Zn{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(n){this.options=n}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let u=[this.options.project,...this.options.additionalProjects??[]].flatMap((t)=>[...this.options.relationRepo.getByType(t,"imports"),...this.options.relationRepo.getByType(t,"type-references"),...this.options.relationRepo.getByType(t,"re-exports")]);for(let t of u){let{srcFilePath:i,dstFilePath:g}=t;if(!this.adjacencyList.has(i))this.adjacencyList.set(i,new Set);if(this.adjacencyList.get(i).add(g),!this.adjacencyList.has(g))this.adjacencyList.set(g,new Set);if(!this.reverseAdjacencyList.has(g))this.reverseAdjacencyList.set(g,new Set);this.reverseAdjacencyList.get(g).add(i)}}getDependencies(n){return Array.from(this.adjacencyList.get(n)??[])}getDependents(n){return Array.from(this.reverseAdjacencyList.get(n)??[])}getTransitiveDependents(n){let u=new Set,t=[n];while(t.length>0){let i=t.shift();for(let g of this.reverseAdjacencyList.get(i)??[])if(!u.has(g))u.add(g),t.push(g)}return Array.from(u)}hasCycle(){let n=new Set,u=new Set;for(let t of this.adjacencyList.keys()){if(n.has(t))continue;let i=[{node:t,entered:!1}];while(i.length>0){let g=i.pop();if(g.entered){u.delete(g.node);continue}if(u.has(g.node))return!0;if(n.has(g.node))continue;n.add(g.node),u.add(g.node),i.push({node:g.node,entered:!0});for(let m of this.adjacencyList.get(g.node)??[]){if(u.has(m))return!0;if(!n.has(m))i.push({node:m,entered:!1})}}}return!1}getAffectedByChange(n){let u=new Set;for(let t of n)for(let i of this.getTransitiveDependents(t))u.add(i);return Array.from(u)}getAdjacencyList(){let n=new Map;for(let[u,t]of this.adjacencyList)n.set(u,Array.from(t));return n}getTransitiveDependencies(n){let u=new Set,t=[n];while(t.length>0){let i=t.shift();for(let g of this.adjacencyList.get(i)??[])if(!u.has(g))u.add(g),t.push(g)}return Array.from(u)}getCyclePaths(n){let u=n?.maxCycles??1/0;if(u<=0)return[];let t=new Map;for(let[i,g]of this.adjacencyList)t.set(i,Array.from(g));return Fi(t,u)}}var bi=(n,u)=>n.localeCompare(u);function Ri(n){let u=n.length>1&&n[0]===n[n.length-1]?n.slice(0,-1):[...n];if(u.length===0)return[];let t=u;for(let i=1;i<u.length;i++){let g=u.slice(i).concat(u.slice(0,i));if(g.join("::")<t.join("::"))t=g}return[...t]}function ru(n,u,t){let i=Ri(t);if(i.length===0)return!1;let g=i.join("->");if(n.has(g))return!1;return n.add(g),u.push(i),!0}function yi(n){let u=0,t=[],i=new Set,g=new Map,m=new Map,O=[],r=(w)=>{g.set(w,u),m.set(w,u),u+=1,t.push(w),i.add(w);for(let f of n.get(w)??[])if(!g.has(f))r(f),m.set(w,Math.min(m.get(w)??0,m.get(f)??0));else if(i.has(f))m.set(w,Math.min(m.get(w)??0,g.get(f)??0));if(m.get(w)===g.get(w)){let f=[],s="";do s=t.pop()??"",i.delete(s),f.push(s);while(s!==w&&t.length>0);O.push(f)}};for(let w of n.keys())if(!g.has(w))r(w);return{components:O}}function pi(n,u,t){let i=[],g=new Set,m=[...n].sort(bi),O=(r,w,f)=>{w.delete(r);let s=f.get(r);if(!s)return;for(let A of s)if(w.has(A))O(A,w,f);s.clear()};for(let r=0;r<m.length&&i.length<t;r++){let w=m[r]??"",f=new Set(m.slice(r)),s=new Set,A=new Map,M=[],k=(H)=>(u.get(H)??[]).filter((B)=>f.has(B)),I=(H)=>{if(i.length>=t)return!0;let B=!1;M.push(H),s.add(H);for(let _ of k(H)){if(i.length>=t)break;if(_===w)ru(g,i,M.concat(w)),B=!0;else if(!s.has(_)){if(I(_))B=!0}}if(B)O(H,s,A);else for(let _ of k(H)){let N=A.get(_)??new Set;N.add(H),A.set(_,N)}return M.pop(),B};I(w)}return i}function Fi(n,u){let{components:t}=yi(n),i=[],g=new Set;for(let m of t){if(i.length>=u)break;if(m.length===0)continue;if(m.length===1){let w=m[0]??"";if((n.get(w)??[]).includes(w))ru(g,i,[w,w]);continue}let O=u-i.length,r=pi(m,n,O);for(let w of r){if(i.length>=u)break;ru(g,i,w)}}return i}function gt(n){n.graphCache=null,n.graphCacheKey=null}function Sn(n,u){let t=u??"__cross__";if(n.graphCache&&n.graphCacheKey===t)return n.graphCache;let i=new Zn({relationRepo:n.relationRepo,project:u??n.defaultProject,additionalProjects:u?void 0:n.boundaries?.map((g)=>g.project)});return i.build(),n.graphCache=i,n.graphCacheKey=t,i}function mt(n,u,t,i=1e4){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:t??n.defaultProject,query:{srcFilePath:u,type:"imports",project:t??n.defaultProject,limit:i}}).map((g)=>g.dstFilePath)}catch(g){if(g instanceof a)throw g;throw new a("search","Gildash: getDependencies failed",{cause:g})}}function rt(n,u,t,i=1e4){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:t??n.defaultProject,query:{dstFilePath:u,type:"imports",project:t??n.defaultProject,limit:i}}).map((g)=>g.srcFilePath)}catch(g){if(g instanceof a)throw g;throw new a("search","Gildash: getDependents failed",{cause:g})}}async function wt(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return Sn(n,t).getAffectedByChange(u)}catch(i){if(i instanceof a)throw i;throw new a("search","Gildash: getAffected failed",{cause:i})}}async function Ot(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return Sn(n,u).hasCycle()}catch(t){if(t instanceof a)throw t;throw new a("search","Gildash: hasCycle failed",{cause:t})}}async function St(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return Sn(n,u).getAdjacencyList()}catch(t){if(t instanceof a)throw t;throw new a("search","Gildash: getImportGraph failed",{cause:t})}}async function ft(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return Sn(n,t).getTransitiveDependencies(u)}catch(i){if(i instanceof a)throw i;throw new a("search","Gildash: getTransitiveDependencies failed",{cause:i})}}async function at(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{return Sn(n,u).getCyclePaths(t)}catch(i){if(i instanceof a)throw i;throw new a("search","Gildash: getCyclePaths failed",{cause:i})}}async function st(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{let i=Sn(n,t);return{filePath:u,fanIn:i.getDependents(u).length,fanOut:i.getDependencies(u).length}}catch(i){if(i instanceof a)throw i;throw new a("search","Gildash: getFanMetrics failed",{cause:i})}}import At from"path";function wu(n,u,t,i){let g=i??n.defaultProject,m=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:g,query:{text:u,exact:!0,filePath:t,limit:1}});if(m.length===0)return null;let O=m[0],r=At.isAbsolute(t)?t:At.resolve(n.projectRoot,t),w=n.semanticLayer.lineColumnToPosition(r,O.span.start.line,O.span.start.column);if(w===null)return null;let f=n.semanticLayer.findNamePosition(r,w,O.name)??w;return{sym:O,position:f,absPath:r}}function _t(n,u,t,i){if(n.closed)throw new a("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new a("semantic","Gildash: semantic layer is not enabled");try{let g=wu(n,u,t,i);if(!g)return null;return n.semanticLayer.collectTypeAt(g.absPath,g.position)}catch(g){if(g instanceof a)throw g;throw new a("search","Gildash: getResolvedType failed",{cause:g})}}function Jt(n,u,t,i){if(n.closed)throw new a("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new a("semantic","Gildash: semantic layer is not enabled");try{let g=wu(n,u,t,i);if(!g)throw new a("search",`Gildash: symbol '${u}' not found in '${t}'`);return n.semanticLayer.findReferences(g.absPath,g.position)}catch(g){if(g instanceof a)throw g;throw new a("search","Gildash: getSemanticReferences failed",{cause:g})}}function Nt(n,u,t,i){if(n.closed)throw new a("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new a("semantic","Gildash: semantic layer is not enabled");try{let g=wu(n,u,t,i);if(!g)throw new a("search",`Gildash: symbol '${u}' not found in '${t}'`);return n.semanticLayer.findImplementations(g.absPath,g.position)}catch(g){if(g instanceof a)throw g;throw new a("search","Gildash: getImplementations failed",{cause:g})}}function Mt(n,u){if(n.closed)throw new a("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new a("semantic","Gildash: semantic layer is not enabled");try{return n.semanticLayer.getModuleInterface(u)}catch(t){if(t instanceof a)throw t;throw new a("search","Gildash: getSemanticModuleInterface failed",{cause:t})}}function $t(n,u){let t=new Map(n.map((r)=>[`${r.name}::${r.filePath}`,r])),i=new Map(u.map((r)=>[`${r.name}::${r.filePath}`,r])),g=[],m=[],O=[];for(let[r,w]of i){let f=t.get(r);if(!f)g.push(w);else if(f.fingerprint!==w.fingerprint)O.push({before:f,after:w})}for(let[r,w]of t)if(!i.has(r))m.push(w);return{added:g,removed:m,modified:O}}function Wt(n,u){if(n.onIndexedCallbacks.add(u),!n.coordinator)return()=>{n.onIndexedCallbacks.delete(u)};let t=n.coordinator.onIndexed(u);return()=>{n.onIndexedCallbacks.delete(u),t()}}async function Dt(n){if(n.closed)throw new a("closed","Gildash: instance is closed");if(!n.coordinator)throw new a("closed","Gildash: reindex() is not available for readers");try{let u=await n.coordinator.fullIndex();return gt(n),u}catch(u){if(u instanceof a)throw u;throw new a("index","Gildash: reindex failed",{cause:u})}}function kt(n,u,t,i){if(n.closed)throw new a("closed","Gildash: instance is closed");let g=i??n.defaultProject,m=new Set,O=[],r=u,w=t;for(;;){let f=`${w}::${r}`;if(m.has(f))return{originalName:r,originalFilePath:w,reExportChain:O,circular:!0};m.add(f);let s=n.relationSearchFn({relationRepo:n.relationRepo,project:g,query:{type:"re-exports",srcFilePath:w,limit:500}}),A,M;for(let k of s){let I;if(k.metaJson)try{let B=JSON.parse(k.metaJson);if(Array.isArray(B.specifiers))I=B.specifiers}catch{}if(!I)continue;let H=I.find((B)=>B.exported===r);if(!H)continue;A=k.dstFilePath,M=H.local;break}if(!A||!M)return{originalName:r,originalFilePath:w,reExportChain:O,circular:!1};O.push({filePath:w,exportedAs:r}),w=A,r=M}}async function zt(n,u,t){if(n.closed)throw new a("closed","Gildash: instance is closed");try{let i=t?.project??n.defaultProject,g=t?.filePaths?t.filePaths:n.fileRepo.getAllFiles(i).map((m)=>m.filePath);return await n.patternSearchFn({pattern:u,filePaths:g})}catch(i){if(i instanceof a)throw i;throw new a("search","Gildash: findPattern failed",{cause:i})}}async function It(n,u,t,i){if(n.closed)throw new a("closed","Gildash: instance is closed");try{let g=i??n.defaultProject,m=new Set,O=(r,w,f)=>{let s=`${r}::${w}`;if(m.has(s))return{symbolName:r,filePath:w,kind:f,children:[]};m.add(s);let k=n.relationSearchFn({relationRepo:n.relationRepo,project:g,query:{srcFilePath:w,srcSymbolName:r,limit:1000}}).filter((I)=>I.type==="extends"||I.type==="implements").filter((I)=>I.dstSymbolName!=null).map((I)=>O(I.dstSymbolName,I.dstFilePath,I.type));return{symbolName:r,filePath:w,kind:f,children:k}};return O(u,t)}catch(g){if(g instanceof a)throw g;throw new a("search","Gildash: getHeritageChain failed",{cause:g})}}class Ou{_ctx;get projectRoot(){return this._ctx.projectRoot}get role(){return this._ctx.role}get projects(){return[...this._ctx.boundaries]}constructor(n){this._ctx=n}static async open(n){let u=await pu(n);return new Ou(u)}async close(n){return Yn(this._ctx,n)}parseSource(n,u,t){return vu(this._ctx,n,u,t)}async batchParse(n,u){return Eu(this._ctx,n,u)}getParsedAst(n){return qu(this._ctx,n)}extractSymbols(n){return Gu(this._ctx,n)}extractRelations(n){return ju(this._ctx,n)}getStats(n){return du(this._ctx,n)}searchSymbols(n){return mu(this._ctx,n)}searchRelations(n){return hu(this._ctx,n)}searchAllSymbols(n){return xu(this._ctx,n)}searchAllRelations(n){return lu(this._ctx,n)}listIndexedFiles(n){return ou(this._ctx,n)}getInternalRelations(n,u){return eu(this._ctx,n,u)}getFullSymbol(n,u,t){return cu(this._ctx,n,u,t)}getFileStats(n,u){return nt(this._ctx,n,u)}getFileInfo(n,u){return ut(this._ctx,n,u)}getSymbolsByFile(n,u){return tt(this._ctx,n,u)}getModuleInterface(n,u){return it(this._ctx,n,u)}getDependencies(n,u,t=1e4){return mt(this._ctx,n,u,t)}getDependents(n,u,t=1e4){return rt(this._ctx,n,u,t)}async getAffected(n,u){return wt(this._ctx,n,u)}async hasCycle(n){return Ot(this._ctx,n)}async getImportGraph(n){return St(this._ctx,n)}async getTransitiveDependencies(n,u){return ft(this._ctx,n,u)}async getCyclePaths(n,u){return at(this._ctx,n,u)}async getFanMetrics(n,u){return st(this._ctx,n,u)}getResolvedType(n,u,t){return _t(this._ctx,n,u,t)}getSemanticReferences(n,u,t){return Jt(this._ctx,n,u,t)}getImplementations(n,u,t){return Nt(this._ctx,n,u,t)}getSemanticModuleInterface(n){return Mt(this._ctx,n)}diffSymbols(n,u){return $t(n,u)}onIndexed(n){return Wt(this._ctx,n)}async reindex(){return Dt(this._ctx)}resolveSymbol(n,u,t){return kt(this._ctx,n,u,t)}async findPattern(n,u){return zt(this._ctx,n,u)}async getHeritageChain(n,u,t){return It(this._ctx,n,u,t)}}export{on as symbolSearch,en as relationSearch,cn as patternSearch,v as gildashError,a as GildashError,Ou as Gildash,Zn as DependencyGraph};
2
+ var Ig=Object.defineProperty;var kg=(n)=>n;function Cg(n,u){this[n]=kg.bind(null,u)}var Tg=(n,u)=>{for(var g in u)Ig(n,g,{get:u[g],enumerable:!0,configurable:!0,set:Cg.bind(u,g)})};var Ju=import.meta.require;import{isErr as Kn}from"@zipbul/result";import Vn from"path";import{existsSync as qm}from"fs";import{err as Au,isErr as bg}from"@zipbul/result";import{Database as qg}from"bun:sqlite";import{mkdirSync as pg,unlinkSync as fu,existsSync as Nu}from"fs";import{dirname as vg,join as Mu}from"path";import{drizzle as Gg}from"drizzle-orm/bun-sqlite";import{migrate as Eg}from"drizzle-orm/bun-sqlite/migrator";class J extends Error{type;constructor(n,u,g){super(u,g);this.type=n;this.name="GildashError"}}function p(n,u,g){return new J(n,u,g!==void 0?{cause:g}:void 0)}var nn=".gildash",Wn="gildash.db";var an={};Tg(an,{watcherOwner:()=>ag,symbols:()=>k,relations:()=>K,files:()=>F});import{sql as yg}from"drizzle-orm";import{sqliteTable as Hn,text as y,integer as j,real as sg,index as un,primaryKey as Rg,foreignKey as Fn,check as Fg}from"drizzle-orm/sqlite-core";var F=Hn("files",{project:y("project").notNull(),filePath:y("file_path").notNull(),mtimeMs:sg("mtime_ms").notNull(),size:j("size").notNull(),contentHash:y("content_hash").notNull(),updatedAt:y("updated_at").notNull(),lineCount:j("line_count")},(n)=>[Rg({columns:[n.project,n.filePath]})]),k=Hn("symbols",{id:j("id").primaryKey({autoIncrement:!0}),project:y("project").notNull(),filePath:y("file_path").notNull(),kind:y("kind").notNull(),name:y("name").notNull(),startLine:j("start_line").notNull(),startColumn:j("start_column").notNull(),endLine:j("end_line").notNull(),endColumn:j("end_column").notNull(),isExported:j("is_exported").notNull().default(0),signature:y("signature"),fingerprint:y("fingerprint"),detailJson:y("detail_json"),contentHash:y("content_hash").notNull(),indexedAt:y("indexed_at").notNull(),resolvedType:y("resolved_type")},(n)=>[un("idx_symbols_project_file").on(n.project,n.filePath),un("idx_symbols_project_kind").on(n.project,n.kind),un("idx_symbols_project_name").on(n.project,n.name),un("idx_symbols_fingerprint").on(n.project,n.fingerprint),Fn({columns:[n.project,n.filePath],foreignColumns:[F.project,F.filePath]}).onDelete("cascade")]),K=Hn("relations",{id:j("id").primaryKey({autoIncrement:!0}),project:y("project").notNull(),type:y("type").notNull(),srcFilePath:y("src_file_path").notNull(),srcSymbolName:y("src_symbol_name"),dstProject:y("dst_project").notNull(),dstFilePath:y("dst_file_path").notNull(),dstSymbolName:y("dst_symbol_name"),metaJson:y("meta_json")},(n)=>[un("idx_relations_src").on(n.project,n.srcFilePath),un("idx_relations_dst").on(n.dstProject,n.dstFilePath),un("idx_relations_type").on(n.project,n.type),un("idx_relations_project_type_src").on(n.project,n.type,n.srcFilePath),Fn({columns:[n.project,n.srcFilePath],foreignColumns:[F.project,F.filePath]}).onDelete("cascade"),Fn({columns:[n.dstProject,n.dstFilePath],foreignColumns:[F.project,F.filePath]}).onDelete("cascade")]),ag=Hn("watcher_owner",{id:j("id").primaryKey(),pid:j("pid").notNull(),startedAt:y("started_at").notNull(),heartbeatAt:y("heartbeat_at").notNull(),instanceId:y("instance_id")},(n)=>[Fg("watcher_owner_singleton",yg`${n.id} = 1`)]);class bn{client=null;drizzle=null;dbPath;txDepth=0;constructor(n){this.dbPath=Mu(n.projectRoot,nn,Wn)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{pg(vg(this.dbPath),{recursive:!0}),this.client=new qg(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=Gg(this.client,{schema:an}),Eg(this.drizzle,{migrationsFolder:Mu(import.meta.dirname,"migrations")});let n=this.client.prepare("PRAGMA foreign_key_check").all();if(n.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(n.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON");let u=this.client;if(typeof u.function==="function")u.function.call(this.client,"regexp",(g,m)=>{try{return new RegExp(g).test(m)?1:0}catch{return 0}})}catch(n){if(this.isCorruptionError(n)&&Nu(this.dbPath)){this.closeClient(),fu(this.dbPath);for(let g of["-wal","-shm"]){let m=this.dbPath+g;if(Nu(m))fu(m)}let u=this.open();if(bg(u))return Au(p("store",`Failed to recover database at ${this.dbPath}`,u.data));return u}return Au(p("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 g=`sp_${this.txDepth++}`;u.run(`SAVEPOINT "${g}"`);try{let m=n(this);return u.run(`RELEASE SAVEPOINT "${g}"`),m}catch(m){throw u.run(`ROLLBACK TO SAVEPOINT "${g}"`),u.run(`RELEASE SAVEPOINT "${g}"`),m}finally{this.txDepth--}}immediateTransaction(n){let u=this.requireClient();this.txDepth++,u.run("BEGIN IMMEDIATE");try{let g=n();return u.run("COMMIT"),g}catch(g){throw u.run("ROLLBACK"),g}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 g=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(n,g,g,u??null)}replaceOwner(n,u){let g=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(n,g,g,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 Nn,and as $u}from"drizzle-orm";class qn{db;constructor(n){this.db=n}getFile(n,u){return this.db.drizzleDb.select().from(F).where($u(Nn(F.project,n),Nn(F.filePath,u))).get()??null}upsertFile(n){this.db.drizzleDb.insert(F).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:[F.project,F.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(F).where(Nn(F.project,n)).all()}getFilesMap(n){let u=this.getAllFiles(n),g=new Map;for(let m of u)g.set(m.filePath,m);return g}deleteFile(n,u){this.db.drizzleDb.delete(F).where($u(Nn(F.project,n),Nn(F.filePath,u))).run()}}import{eq as a,and as wn,sql as Un,count as jg}from"drizzle-orm";function Qn(n){return n.trim().split(/\s+/).map((u)=>u.trim()).filter((u)=>u.length>0).map((u)=>`"${u.replaceAll('"','""')}"*`).join(" ")}class pn{db;constructor(n){this.db=n}replaceFileSymbols(n,u,g,m){if(this.db.drizzleDb.delete(k).where(wn(a(k.project,n),a(k.filePath,u))).run(),!m.length)return;let i=new Date().toISOString();for(let t of m)this.db.drizzleDb.insert(k).values({project:n,filePath:u,kind:t.kind??"unknown",name:t.name??"",startLine:t.startLine??0,startColumn:t.startColumn??0,endLine:t.endLine??0,endColumn:t.endColumn??0,isExported:t.isExported??0,signature:t.signature??null,fingerprint:t.fingerprint??null,detailJson:t.detailJson??null,contentHash:g,indexedAt:t.indexedAt??i,resolvedType:t.resolvedType??null}).run()}getFileSymbols(n,u){return this.db.drizzleDb.select().from(k).where(wn(a(k.project,n),a(k.filePath,u))).all()}searchByName(n,u,g={}){let m=g.limit??50,i=Qn(u);if(!i)return[];return this.db.drizzleDb.select().from(k).where(wn(Un`${k.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${i})`,a(k.project,n),g.kind?a(k.kind,g.kind):void 0)).orderBy(k.name).limit(m).all()}searchByKind(n,u){return this.db.drizzleDb.select().from(k).where(wn(a(k.project,n),a(k.kind,u))).orderBy(k.name).all()}getStats(n){let u=this.db.drizzleDb.select({symbolCount:jg(),fileCount:Un`COUNT(DISTINCT ${k.filePath})`}).from(k).where(a(k.project,n)).get();return{symbolCount:u?.symbolCount??0,fileCount:u?.fileCount??0}}getByFingerprint(n,u){return this.db.drizzleDb.select().from(k).where(wn(a(k.project,n),a(k.fingerprint,u))).all()}deleteFileSymbols(n,u){this.db.drizzleDb.delete(k).where(wn(a(k.project,n),a(k.filePath,u))).run()}searchByQuery(n){let u=this.db.drizzleDb.select().from(k).where(wn(n.ftsQuery?Un`${k.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${n.ftsQuery})`:void 0,n.exactName?a(k.name,n.exactName):void 0,n.project!==void 0?a(k.project,n.project):void 0,n.kind?a(k.kind,n.kind):void 0,n.filePath!==void 0?a(k.filePath,n.filePath):void 0,n.isExported!==void 0?a(k.isExported,n.isExported?1:0):void 0,n.decorator?Un`${k.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(k.resolvedType,n.resolvedType):void 0)).orderBy(k.name).limit(n.regex?Math.max(n.limit*50,5000):n.limit).all();if(!n.regex)return u;try{let g=new RegExp(n.regex);return u.filter((m)=>g.test(m.name)).slice(0,n.limit)}catch{return[]}}}import{eq as s,and as o,isNull as zu,or as Pg}from"drizzle-orm";class vn{db;constructor(n){this.db=n}replaceFileRelations(n,u,g){this.db.transaction((m)=>{if(m.drizzleDb.delete(K).where(o(s(K.project,n),s(K.srcFilePath,u))).run(),!g.length)return;for(let i of g)m.drizzleDb.insert(K).values({project:n,type:i.type??"unknown",srcFilePath:i.srcFilePath??u,srcSymbolName:i.srcSymbolName??null,dstProject:i.dstProject??n,dstFilePath:i.dstFilePath??"",dstSymbolName:i.dstSymbolName??null,metaJson:i.metaJson??null}).run()})}getOutgoing(n,u,g){if(g!==void 0)return this.db.drizzleDb.select({project:K.project,type:K.type,srcFilePath:K.srcFilePath,srcSymbolName:K.srcSymbolName,dstProject:K.dstProject,dstFilePath:K.dstFilePath,dstSymbolName:K.dstSymbolName,metaJson:K.metaJson}).from(K).where(o(s(K.project,n),s(K.srcFilePath,u),Pg(s(K.srcSymbolName,g),zu(K.srcSymbolName)))).all();return this.db.drizzleDb.select({project:K.project,type:K.type,srcFilePath:K.srcFilePath,srcSymbolName:K.srcSymbolName,dstProject:K.dstProject,dstFilePath:K.dstFilePath,dstSymbolName:K.dstSymbolName,metaJson:K.metaJson}).from(K).where(o(s(K.project,n),s(K.srcFilePath,u))).all()}getIncoming(n){let{dstProject:u,dstFilePath:g}=n;return this.db.drizzleDb.select({project:K.project,type:K.type,srcFilePath:K.srcFilePath,srcSymbolName:K.srcSymbolName,dstProject:K.dstProject,dstFilePath:K.dstFilePath,dstSymbolName:K.dstSymbolName,metaJson:K.metaJson}).from(K).where(o(s(K.dstProject,u),s(K.dstFilePath,g))).all()}getByType(n,u){return this.db.drizzleDb.select({project:K.project,type:K.type,srcFilePath:K.srcFilePath,srcSymbolName:K.srcSymbolName,dstProject:K.dstProject,dstFilePath:K.dstFilePath,dstSymbolName:K.dstSymbolName,metaJson:K.metaJson}).from(K).where(o(s(K.project,n),s(K.type,u))).all()}deleteFileRelations(n,u){this.db.drizzleDb.delete(K).where(o(s(K.project,n),s(K.srcFilePath,u))).run()}searchRelations(n){return this.db.drizzleDb.select({project:K.project,type:K.type,srcFilePath:K.srcFilePath,srcSymbolName:K.srcSymbolName,dstProject:K.dstProject,dstFilePath:K.dstFilePath,dstSymbolName:K.dstSymbolName,metaJson:K.metaJson}).from(K).where(o(n.project!==void 0?s(K.project,n.project):void 0,n.srcFilePath!==void 0?s(K.srcFilePath,n.srcFilePath):void 0,n.srcSymbolName!==void 0?s(K.srcSymbolName,n.srcSymbolName):void 0,n.dstProject!==void 0?s(K.dstProject,n.dstProject):void 0,n.dstFilePath!==void 0?s(K.dstFilePath,n.dstFilePath):void 0,n.dstSymbolName!==void 0?s(K.dstSymbolName,n.dstSymbolName):void 0,n.type!==void 0?s(K.type,n.type):void 0)).limit(n.limit).all()}retargetRelations(n){let{dstProject:u,oldFile:g,oldSymbol:m,newFile:i,newSymbol:t,newDstProject:S}=n,w=m===null?o(s(K.dstProject,u),s(K.dstFilePath,g),zu(K.dstSymbolName)):o(s(K.dstProject,u),s(K.dstFilePath,g),s(K.dstSymbolName,m)),O={dstFilePath:i,dstSymbolName:t};if(S!==void 0)O.dstProject=S;this.db.drizzleDb.update(K).set(O).where(w).run()}}import{err as Du}from"@zipbul/result";import{subscribe as hg}from"@parcel/watcher";import Gn from"path";var dg=["**/.git/**",`**/${nn}/**`,"**/dist/**","**/node_modules/**"],xg=new Set(["package.json","tsconfig.json"]);function og(n){return n.replaceAll("\\","/")}function lg(n){if(n==="update")return"change";if(n==="create")return"create";return"delete"}class En{#n;#u;#g;#i;#m;#t;constructor(n,u=hg,g=console){this.#u=n.projectRoot,this.#g=[...dg,...n.ignorePatterns??[]],this.#i=new Set((n.extensions??[".ts",".mts",".cts"]).map((m)=>m.toLowerCase())),this.#m=u,this.#t=g}async start(n){try{this.#n=await this.#m(this.#u,(u,g)=>{if(u){this.#t.error(p("watcher","Callback error",u));return}try{for(let m of g){let i=og(Gn.relative(this.#u,m.path));if(i.startsWith(".."))continue;let t=Gn.basename(i),S=Gn.extname(i).toLowerCase();if(!xg.has(t)&&!this.#i.has(S))continue;if(i.endsWith(".d.ts"))continue;n({eventType:lg(m.type),filePath:i})}}catch(m){this.#t.error(p("watcher","Callback error",m))}},{ignore:this.#g})}catch(u){return Du(p("watcher","Failed to subscribe watcher",u))}}async close(){if(!this.#n)return;try{await this.#n.unsubscribe(),this.#n=void 0}catch(n){return Du(p("watcher","Failed to close watcher",n))}}}import jn from"path";import{promises as cg}from"fs";var eg=["**/node_modules/**","**/.git/**",`**/${nn}/**`,"**/dist/**"];async function Bn(n){let u=[];for await(let g of cg.glob("**/package.json",{cwd:n,exclude:eg})){let m=jn.dirname(g).replaceAll("\\","/"),i=jn.join(n,g),t=await Bun.file(i).json(),S=typeof t?.name==="string"&&t.name.length>0?t.name:jn.basename(m==="."?n:m);u.push({dir:m,project:S})}return u.sort((g,m)=>m.dir.length-g.dir.length),u}function G(n,u,g="default"){let m=n.replaceAll("\\","/");for(let i of u){if(i.dir===".")return i.project;if(m===i.dir||m.startsWith(`${i.dir}/`))return i.project}return g}import Ku from"path";var gn=new Map;async function nm(n){let u=Bun.file(n);if(!await u.exists())return null;try{let g=await u.text(),m=Bun.JSONC.parse(g);return typeof m==="object"&&m!==null?m:null}catch{return null}}async function Mn(n){if(gn.has(n))return gn.get(n)??null;let u=Ku.join(n,"tsconfig.json"),g=await nm(u);if(!g)return gn.set(n,null),null;let m=typeof g.compilerOptions==="object"&&g.compilerOptions!==null?g.compilerOptions:null;if(!m)return gn.set(n,null),null;let i=typeof m.baseUrl==="string"?m.baseUrl:null,t=typeof m.paths==="object"&&m.paths!==null?m.paths:null;if(!i&&!t)return gn.set(n,null),null;let S=i?Ku.resolve(n,i):n,w=new Map;if(t)for(let[_,A]of Object.entries(t)){if(!Array.isArray(A))continue;let f=A.filter((z)=>typeof z==="string");w.set(_,f)}let O={baseUrl:S,paths:w};return gn.set(n,O),O}function Yn(n){if(n){gn.delete(n);return}gn.clear()}import Vu from"path";function Zn(n,u){return Vu.relative(n,u).replaceAll("\\","/")}function _n(n,u){return Vu.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 Iu}from"@zipbul/result";import{err as um}from"@zipbul/result";import{parseSync as gm}from"oxc-parser";function $n(n,u,g,m=gm){try{let{program:i,errors:t,comments:S}=m(n,u,g);return{filePath:n,program:i,errors:t,comments:S,sourceText:u}}catch(i){return um(p("parse",`Failed to parse file: ${n}`,i))}}import{promises as mm}from"fs";import{join as im}from"path";async function Wu(n){let{projectRoot:u,extensions:g,ignorePatterns:m,fileRepo:i}=n,t=i.getFilesMap(),S=new Set,w=[],O=[],_=m.map((f)=>new Bun.Glob(f));for await(let f of mm.glob("**/*",{cwd:u})){if(!g.some((r)=>f.endsWith(r)))continue;if(f.startsWith("node_modules/")||f.includes("/node_modules/"))continue;if(_.some((r)=>r.match(f)))continue;S.add(f);let z=im(u,f),V=Bun.file(z),{size:Q,lastModified:B}=V,Y=t.get(f);if(!Y){let r=await V.text(),M=mn(r);w.push({filePath:f,contentHash:M,mtimeMs:B,size:Q});continue}if(Y.mtimeMs===B&&Y.size===Q){O.push({filePath:f,contentHash:Y.contentHash,mtimeMs:B,size:Q});continue}let N=await V.text(),$=mn(N);if($===Y.contentHash)O.push({filePath:f,contentHash:$,mtimeMs:B,size:Q});else w.push({filePath:f,contentHash:$,mtimeMs:B,size:Q})}let A=[];for(let f of t.keys())if(!S.has(f))A.push(f);return{changed:w,unchanged:O,deleted:A}}function Hu(n){let u=[0];for(let g=0;g<n.length;g++)if(n[g]===`
3
+ `)u.push(g+1);return u}function Pn(n,u){let g=0,m=n.length-1;while(g<m){let i=g+m+1>>1;if(n[i]<=u)g=i;else m=i-1}return{line:g+1,column:u-n[g]}}import{err as tm}from"@zipbul/result";import{parse as wm}from"comment-parser";function Qu(n){try{let u=n.trim();if(u.startsWith("/**"))u=u.slice(3);if(u.endsWith("*/"))u=u.slice(0,-2);let m=wm(`/** ${u} */`)[0]??{description:"",tags:[]};return{description:(m.description??"").trim(),tags:(m.tags??[]).map((i)=>({tag:i.tag??"",name:i.name??"",type:i.type??"",description:i.description??"",optional:i.optional??!1,...i.default!==void 0?{default:i.default}:{}}))}}catch(u){return tm(p("parse","Failed to parse JSDoc comment",u))}}import{isErr as Om}from"@zipbul/result";function Ln(n){let{program:u,sourceText:g,comments:m}=n,i=Hu(g);function t(N,$){return{start:Pn(i,N),end:Pn(i,$)}}function S(N){let $=null;for(let r of m){if(r.type!=="Block")continue;if(r.end>N)continue;if(!r.value.startsWith("*"))continue;if(!$||r.end>$.end)$={value:`/*${r.value}*/`,end:r.end}}if(!$)return;for(let r of u.body){let M=r.start??0;if(M===N)continue;if(M>$.end&&M<N)return}return $.value}function w(N){if(!N)return;let $=N.typeAnnotation??N;return g.slice($.start,$.end)}function O(N){if(!N||N.length===0)return[];return N.map(($)=>{let r=$.expression;if(!r)return{name:"unknown"};if(r.type==="CallExpression"){let M=r.callee?.name??r.callee?.property?.name??"unknown",D=(r.arguments??[]).map((H)=>g.slice(H.start,H.end));return{name:M,arguments:D.length>0?D:void 0}}if(r.type==="Identifier")return{name:r.name??"unknown"};return{name:g.slice(r.start,r.end)}})}function _(N){let $=N.type==="TSParameterProperty"?N.parameter:N;if($?.type==="RestElement"){let U=`...${$.argument?.name??"unknown"}`,W=$.typeAnnotation,R=W?w(W):void 0,X={name:U,isOptional:!1};if(R)X.type=R;return X}if($?.type==="AssignmentPattern"){let{left:C,right:U}=$,W=C?.name??"unknown",R=C?.typeAnnotation,X=R?w(R):void 0,v=g.slice(U.start,U.end),E=O(C?.decorators??[]),P={name:W,isOptional:!0,defaultValue:v};if(X)P.type=X;if(E.length>0)P.decorators=E;return P}let r=$?.name??$?.pattern?.name??"unknown",M=!!$?.optional,D=$?.typeAnnotation,H=D?w(D):void 0,Z=O($?.decorators??[]),L={name:r,isOptional:M};if(H)L.type=H;if(Z.length>0)L.decorators=Z;return L}function A(N,$){let r=[];if($?.async)r.push("async");if(N.static)r.push("static");if(N.abstract)r.push("abstract");if(N.readonly)r.push("readonly");if(N.override)r.push("override");if(N.declare)r.push("declare");if(N.const)r.push("const");let M=N.accessibility;if(M==="private")r.push("private");else if(M==="protected")r.push("protected");else if(M==="public")r.push("public");return r}function f(N){let $=[];if(N.superClass){let M=g.slice(N.superClass.start,N.superClass.end);$.push({kind:"extends",name:M})}let r=N.implements??[];for(let M of r){let D=M.expression??M,H=g.slice(D.start,D.end);$.push({kind:"implements",name:H})}return $}function z(N){let $=[];for(let r of N.extends??[]){let M=r.expression??r,D=g.slice(M.start,M.end);$.push({kind:"extends",name:D})}return $}function V(N){let $=[];for(let r of N)if(r.type==="MethodDefinition"){let M=r.key?.name??"unknown",D=r.value,H=r.kind??"method",Z=H==="constructor"?"constructor":H==="get"?"getter":H==="set"?"setter":"method",L=A(r,D),C=(D?.params??[]).map(_),U=w(D?.returnType),W={kind:"method",name:M,span:t(r.start,r.end),isExported:!1,methodKind:Z,modifiers:L,parameters:C.length>0?C:void 0,returnType:U};$.push(W)}else if(r.type==="PropertyDefinition"){let M=r.key?.name??"unknown",D=A(r),H={kind:"property",name:M,span:t(r.start,r.end),isExported:!1,modifiers:D};$.push(H)}return $}function Q(N){let $=[];for(let r of N)if(r.type==="TSMethodSignature"){let M=r.key?.name??"unknown",D=(r.params??[]).map(_),H=w(r.returnType);$.push({kind:"method",name:M,span:t(r.start,r.end),isExported:!1,modifiers:[],methodKind:"method",parameters:D.length>0?D:void 0,returnType:H})}else if(r.type==="TSPropertySignature"){let M=r.key?.name??"unknown",D=w(r.typeAnnotation),H={kind:"property",name:M,span:t(r.start,r.end),isExported:!1,modifiers:r.readonly?["readonly"]:[],returnType:D};$.push(H)}return $}function B(N,$){let r=N.type??"";if(r==="FunctionDeclaration"){let M=N.id?.name??"default",D=(N.params??[]).map(_),H=w(N.returnType),Z=A(N,N),L=O(N.decorators??[]),C=N.typeParameters?.params?.map((W)=>W.name?.name).filter(Boolean)||void 0,U={kind:"function",name:M,span:t(N.start,N.end),isExported:$,modifiers:Z,parameters:D.length>0?D:void 0,returnType:H,decorators:L.length>0?L:void 0};if(C&&C.length>0)U.typeParameters=C;return U}if(r==="ClassDeclaration"||r==="ClassExpression"){let M=N.id?.name??"default",D=f(N),H=V(N.body?.body??[]),Z=O(N.decorators??[]),L=A(N,N),C=N.typeParameters?.params?.map((W)=>W.name?.name).filter(Boolean)||void 0,U={kind:"class",name:M,span:t(N.start,N.end),isExported:$,modifiers:L,heritage:D.length>0?D:void 0,members:H.length>0?H:void 0,decorators:Z.length>0?Z:void 0};if(C&&C.length>0)U.typeParameters=C;return U}if(r==="VariableDeclaration"){let M=[];for(let D of N.declarations??[]){let{id:H,init:Z}=D;if(H?.type==="ObjectPattern"){for(let X of H.properties??[]){let v=X.value?.name??X.key?.name??"unknown";M.push({kind:"variable",name:v,span:t(X.start??D.start,X.end??D.end),isExported:$,modifiers:[]})}continue}if(H?.type==="ArrayPattern"){for(let X of H.elements??[]){if(!X||X.type!=="Identifier")continue;let v=X.name??"unknown";M.push({kind:"variable",name:v,span:t(X.start??D.start,X.end??D.end),isExported:$,modifiers:[]})}continue}let L=H?.name??"unknown",C="variable",U,W;if(Z?.type==="FunctionExpression"||Z?.type==="ArrowFunctionExpression")C="function",U=(Z.params??[]).map(_),W=w(Z.returnType);let R=[];M.push({kind:C,name:L,span:t(D.start,D.end),isExported:$,modifiers:R,parameters:U,returnType:W})}if(M.length===0)return null;if(M.length===1)return M[0];return M}if(r==="TSTypeAliasDeclaration")return{kind:"type",name:N.id?.name??"unknown",span:t(N.start,N.end),isExported:$,modifiers:[]};if(r==="TSInterfaceDeclaration"){let M=N.id?.name??"unknown",D=z(N),H=Q(N.body?.body??[]),Z=N.typeParameters?.params?.map((C)=>C.name?.name).filter(Boolean)||void 0,L={kind:"interface",name:M,span:t(N.start,N.end),isExported:$,modifiers:[],heritage:D.length>0?D:void 0,members:H.length>0?H:void 0};if(Z&&Z.length>0)L.typeParameters=Z;return L}if(r==="TSEnumDeclaration"){let M=N.id?.name??"unknown",D=A(N),Z=(N.body?.members??[]).map((L)=>({kind:"property",name:L.id?.name??L.id?.value??"unknown",span:t(L.start,L.end),isExported:!1,modifiers:[]}));return{kind:"enum",name:M,span:t(N.start,N.end),isExported:$,modifiers:D,members:Z.length>0?Z:void 0}}return null}let Y=[];for(let N of u.body){let $=null,r=N,M=typeof r.type==="string"?r.type:"";if(M==="ExportNamedDeclaration"){let H=N;if(H.declaration){if($=B(H.declaration,!0),$&&!Array.isArray($))$.span=t(H.start,H.end);else if(Array.isArray($))for(let Z of $)Z.span=t(H.start,H.end)}}else if(M==="ExportDefaultDeclaration"){let H=N,Z=H.declaration;if(Z){if($=B(Z,!0),$&&!Array.isArray($))$.name=Z.id?.name??"default",$.isExported=!0,$.span=t(H.start,H.end)}}else $=B(N,!1);let D=Array.isArray($)?$:$?[$]:[];for(let H of D){let Z=N.start??0,L=S(Z);if(L){let C=Qu(L);if(!Om(C))H.jsDoc=C}Y.push(H)}}return Y}function Sm(n){if(n.kind==="function"||n.kind==="method"){let u=n.parameters?.length??0,g=n.modifiers.includes("async")?1:0;return`params:${u}|async:${g}`}return null}function rm(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((g)=>{let m=g.modifiers.find((i)=>i==="private"||i==="protected"||i==="public");return{name:g.name,kind:g.methodKind??g.kind,type:g.returnType,visibility:m,isStatic:g.modifiers.includes("static")||void 0,isReadonly:g.modifiers.includes("readonly")||void 0}});return Object.keys(u).length>0?JSON.stringify(u):null}function Uu(n,u,g,m,i){let t=Sm(n),S=mn(`${u}|${n.kind}|${t??""}`);return{project:g,filePath:m,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:t,fingerprint:S,detailJson:rm(n),contentHash:i,indexedAt:new Date().toISOString()}}function hn(n){let{parsed:u,project:g,filePath:m,contentHash:i,symbolRepo:t}=n,S=Ln(u),w=[];for(let O of S){w.push(Uu(O,O.name,g,m,i));for(let _ of O.members??[])w.push(Uu(_,`${O.name}.${_.name}`,g,m,i))}t.replaceFileSymbols(g,m,i,w)}import{resolve as dn,dirname as _m,extname as Jm}from"path";function On(n,u,g){let m=(i)=>{let t=Jm(i);if(t==="")return[i+".ts",i+".d.ts",i+"/index.ts",i+"/index.d.ts",i+".mts",i+"/index.mts",i+".cts",i+"/index.cts"];if(t===".js")return[i.slice(0,-3)+".ts"];if(t===".mjs")return[i.slice(0,-4)+".mts"];if(t===".cjs")return[i.slice(0,-4)+".cts"];return[i]};if(u.startsWith(".")){let i=dn(_m(n),u);return m(i)}if(g)for(let[i,t]of g.paths){if(t.length===0)continue;let S=i.indexOf("*");if(S===-1){if(u===i){let w=[];for(let O of t)w.push(...m(dn(g.baseUrl,O)));return w}}else{let w=i.slice(0,S),O=i.slice(S+1);if(u.startsWith(w)&&(O===""||u.endsWith(O))){let _=u.slice(w.length,O===""?void 0:u.length-O.length),A=[];for(let f of t)A.push(...m(dn(g.baseUrl,f.replace("*",_))));return A}}}return[]}function Bu(n,u,g,m=On){let i=new Map,t=n.body??[];for(let S of t){if(S.type!=="ImportDeclaration")continue;let w=S.source?.value??"",O=m(u,w,g);if(O.length===0)continue;let _=O[0],A=S.specifiers??[];for(let f of A)switch(f.type){case"ImportSpecifier":i.set(f.local.name,{path:_,importedName:f.imported.name});break;case"ImportDefaultSpecifier":i.set(f.local.name,{path:_,importedName:"default"});break;case"ImportNamespaceSpecifier":i.set(f.local.name,{path:_,importedName:"*"});break}}return i}var Am=new Set(["loc","start","end","scope"]);function Jn(n,u){if(!n||typeof n!=="object")return;if(Array.isArray(n)){for(let m of n)Jn(m,u);return}let g=n;u(g);for(let m of Object.keys(g)){if(Am.has(m))continue;let i=g[m];if(i&&typeof i==="object")Jn(i,u)}}function Yu(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 Sn(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let u=n;if(u.type==="Identifier"){let g=u.name;return{root:g,parts:[],full:g}}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 g=[],m=u;while(m.type==="MemberExpression"){let S=m.property;if(!S||typeof S.name!=="string")return null;g.unshift(S.name),m=m.object}let i;if(m.type==="Identifier")i=m.name;else if(m.type==="ThisExpression")i="this";else if(m.type==="Super")i="super";else return null;let t=[i,...g].join(".");return{root:i,parts:g,full:t}}return null}function Zu(n,u,g,m=On){let i=[],t=n.body??[];for(let S of t){if(S.type==="ImportDeclaration"){let w=S.source?.value??"",O=m(u,w,g);if(O.length===0)continue;let _=O[0],A=S.importKind==="type",f=S.specifiers??[];if(f.length===0){let z={};if(A)z.isType=!0;i.push({type:A?"type-references":"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:_,dstSymbolName:null,...Object.keys(z).length>0?{metaJson:JSON.stringify(z)}:{}})}else for(let z of f){let V=z.type,Q=A||z.importKind==="type",B={};if(Q)B.isType=!0;let Y,N;if(V==="ImportDefaultSpecifier")Y="default",N=z.local.name;else if(V==="ImportNamespaceSpecifier")Y="*",N=z.local.name,B.importKind="namespace";else Y=z.imported.name,N=z.local.name;i.push({type:Q?"type-references":"imports",srcFilePath:u,srcSymbolName:N,dstFilePath:_,dstSymbolName:Y,...Object.keys(B).length>0?{metaJson:JSON.stringify(B)}:{}})}continue}if(S.type==="ExportAllDeclaration"&&S.source){let w=S.source?.value??"",O=m(u,w,g);if(O.length===0)continue;let _=O[0],A=S.exportKind==="type",f={isReExport:!0};if(A)f.isType=!0;i.push({type:A?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:_,dstSymbolName:null,metaJson:JSON.stringify(f)});continue}if(S.type==="ExportNamedDeclaration"&&S.source){let w=S.source?.value??"",O=m(u,w,g);if(O.length===0)continue;let _=O[0],A=S.exportKind==="type",V={isReExport:!0,specifiers:(S.specifiers??[]).map((Q)=>({local:Q.local.name,exported:Q.exported.name}))};if(A)V.isType=!0;i.push({type:A?"type-references":"re-exports",srcFilePath:u,srcSymbolName:null,dstFilePath:_,dstSymbolName:null,metaJson:JSON.stringify(V)})}}return Jn(n,(S)=>{if(S.type!=="ImportExpression")return;let w=Yu(S.source);if(!w)return;let O=m(u,w,g);if(O.length===0)return;let _=O[0];i.push({type:"imports",srcFilePath:u,srcSymbolName:null,dstFilePath:_,dstSymbolName:null,metaJson:JSON.stringify({isDynamic:!0})})}),i}function Lu(n,u,g){let m=[],i=[],t=[];function S(){if(i.length>0)return i[i.length-1]??null;return null}function w(_){if(!_)return null;let A=g.get(_.root);if(_.parts.length===0){if(A)return{dstFilePath:A.path,dstSymbolName:A.importedName,resolution:"import"};return{dstFilePath:u,dstSymbolName:_.root,resolution:"local"}}else{if(A&&A.importedName==="*"){let f=_.parts[_.parts.length-1];return{dstFilePath:A.path,dstSymbolName:f,resolution:"namespace"}}return{dstFilePath:u,dstSymbolName:_.full,resolution:"local-member"}}}function O(_){if(!_||typeof _!=="object")return;if(Array.isArray(_)){for(let z of _)O(z);return}let A=_,f=typeof A.type==="string"?A.type:"";if(f==="ClassDeclaration"||f==="ClassExpression"){let z=A,V=z.id?.name??"AnonymousClass";t.push(V),O(z.body),t.pop();return}if(f==="FunctionDeclaration"){let z=A,V=z.id?.name??"anonymous";i.push(V),O(z.body),i.pop();return}if(f==="VariableDeclarator"&&A.init&&(A.init?.type==="FunctionExpression"||A.init?.type==="ArrowFunctionExpression")){let z=A,V=z.id?.name??"anonymous";i.push(V),O(z.init?.body??z.init),i.pop();return}if(f==="MethodDefinition"&&A.value){let z=A,V=t[t.length-1]??"",Q=z.key?.name??"anonymous",B=V?`${V}.${Q}`:Q;i.push(B),O(z.value?.body),i.pop();return}if(f==="FunctionExpression"||f==="ArrowFunctionExpression"){let z=S(),V=z?`${z}.<anonymous>`:"<anonymous>";i.push(V),O(A.body),i.pop();return}if(f==="CallExpression"){let z=A,V=Sn(z.callee),Q=w(V);if(Q){let B=S(),Y={};if(B===null)Y.scope="module";m.push({type:"calls",srcFilePath:u,srcSymbolName:B,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,...Object.keys(Y).length>0?{metaJson:JSON.stringify(Y)}:{}})}O(z.callee);for(let B of z.arguments??[])O(B);return}if(f==="NewExpression"){let z=A,V=Sn(z.callee),Q=w(V);if(Q){let B=S(),Y={isNew:!0};if(B===null)Y.scope="module";m.push({type:"calls",srcFilePath:u,srcSymbolName:B,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,metaJson:JSON.stringify(Y)})}for(let B of z.arguments??[])O(B);return}for(let z of Object.keys(A)){if(z==="loc"||z==="start"||z==="end"||z==="scope")continue;let V=A[z];if(V&&typeof V==="object")O(V)}}return O(n),m}function Xu(n,u,g){let m=[];return Jn(n,(i)=>{if(i.type==="TSInterfaceDeclaration"){let w=i.id?.name??"AnonymousInterface",O=i.extends??[];for(let _ of O){let A=_.expression??_,f=Sn(A);if(!f)continue;let z=xn(f,u,g);m.push({type:"extends",srcFilePath:u,srcSymbolName:w,...z})}return}if(i.type!=="ClassDeclaration"&&i.type!=="ClassExpression")return;let t=i.id?.name??"AnonymousClass";if(i.superClass){let w=Sn(i.superClass);if(w){let O=xn(w,u,g);m.push({type:"extends",srcFilePath:u,srcSymbolName:t,...O})}}let S=i.implements??[];for(let w of S){let O=w.expression??w,_=Sn(O);if(!_)continue;let A=xn(_,u,g);m.push({type:"implements",srcFilePath:u,srcSymbolName:t,...A})}}),m}function xn(n,u,g){let m=g.get(n.root);if(m){if(m.importedName==="*"){let i=n.parts[n.parts.length-1]??n.root;return{dstFilePath:m.path,dstSymbolName:i,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:m.path,dstSymbolName:n.parts.length>0?n.full:m.importedName}}return{dstFilePath:u,dstSymbolName:n.full,metaJson:JSON.stringify({isLocal:!0})}}function Xn(n,u,g,m=On){let i=Bu(n,u,g,m),t=Zu(n,u,g,m),S=Lu(n,u,i),w=Xu(n,u,i);return[...t,...S,...w]}function on(n){let{ast:u,project:g,filePath:m,relationRepo:i,projectRoot:t,tsconfigPaths:S,knownFiles:w,boundaries:O}=n,_=_n(t,m),f=Xn(u,_,S,w?(V,Q,B)=>{let Y=On(V,Q,B);for(let N of Y){let $=Zn(t,N);if(O){let r=G($,O);if(w.has(`${r}::${$}`))return[N]}else if(w.has(`${g}::${$}`))return[N]}return[]}:void 0),z=[];for(let V of f){let Q=Zn(t,V.dstFilePath);if(Q.startsWith(".."))continue;let B=Zn(t,V.srcFilePath),Y=O?G(Q,O):g;z.push({project:g,type:V.type,srcFilePath:B,srcSymbolName:V.srcSymbolName??null,dstProject:Y,dstFilePath:Q,dstSymbolName:V.dstSymbolName??null,metaJson:V.metaJson??null})}return i.replaceFileRelations(g,m,z),z.length}var fm=100,ku=50;class ln{opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;constructor(n){this.opts=n,this.logger=n.logger??console,this.tsconfigPathsRaw=Mn(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")){Yn(this.opts.projectRoot),this.tsconfigPathsRaw=Mn(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??Bn;this.boundariesRefresh=u(this.opts.projectRoot).then((g)=>{this.opts.boundaries=g})}if(this.pendingEvents.push(n),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},fm)}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((m,i)=>{this.pendingFullIndexWaiters.push({resolve:m,reject:i})});return this.currentIndexing}this.indexingLock=!0;let g=this.doIndex(n,u).then((m)=>{return this.fireCallbacks(m),m}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let m=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((i)=>{for(let t of m)t.resolve(i)}).catch((i)=>{for(let t of m)t.reject(i)})}else if(this.pendingEvents.length>0){let m=this.pendingEvents.splice(0);this.startIndex(m,!1).catch((i)=>this.logger.error("[IndexCoordinator] incremental drain error",i))}});return this.currentIndexing=g,g}async doIndex(n,u){let g=Date.now(),{fileRepo:m,symbolRepo:i,relationRepo:t,dbConnection:S}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let w,O;if(n!==void 0)w=n.filter((r)=>r.eventType==="create"||r.eventType==="change").map((r)=>({filePath:r.filePath,contentHash:"",mtimeMs:0,size:0})),O=n.filter((r)=>r.eventType==="delete").map((r)=>r.filePath);else{let r=new Map;for(let D of this.opts.boundaries)for(let[H,Z]of m.getFilesMap(D.project))r.set(H,Z);let M=await Wu({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>r}});w=M.changed,O=M.deleted}let _=await this.tsconfigPathsRaw??void 0,A=new Map;for(let r of O){let M=G(r,this.opts.boundaries),D=i.getFileSymbols(M,r);A.set(r,D)}let f=new Map,z=new Map;if(u)for(let r of this.opts.boundaries)for(let M of m.getAllFiles(r.project))for(let D of i.getFileSymbols(r.project,M.filePath))f.set(`${D.filePath}::${D.name}`,{name:D.name,filePath:D.filePath,kind:D.kind,fingerprint:D.fingerprint});else{for(let r of w){let M=G(r.filePath,this.opts.boundaries);for(let D of i.getFileSymbols(M,r.filePath))f.set(`${D.filePath}::${D.name}`,{name:D.name,filePath:D.filePath,kind:D.kind,fingerprint:D.fingerprint})}for(let[,r]of A)for(let M of r)f.set(`${M.filePath}::${M.name}`,{name:M.name,filePath:M.filePath,kind:M.kind,fingerprint:M.fingerprint})}let V=()=>{for(let r of O){let M=G(r,this.opts.boundaries);i.deleteFileSymbols(M,r),t.deleteFileRelations(M,r),m.deleteFile(M,r)}},Q=async()=>{let{projectRoot:r,boundaries:M}=this.opts,{parseCache:D}=this.opts,H=0,Z=0,L=[],C=[];for(let W of w)try{let R=_n(r,W.filePath),X=Bun.file(R),v=await X.text(),E=W.contentHash||mn(v),P=G(W.filePath,M);m.upsertFile({project:P,filePath:W.filePath,mtimeMs:X.lastModified,size:X.size,contentHash:E,updatedAt:new Date().toISOString(),lineCount:v.split(`
4
+ `).length});let e=(this.opts.parseSourceFn??$n)(R,v);if(Iu(e))throw e.data;let I=e;C.push({filePath:W.filePath,text:v,contentHash:E,parsed:I,project:P})}catch(R){this.logger.error(`[IndexCoordinator] Failed to prepare ${W.filePath}:`,R),L.push(W.filePath)}let U=new Set;for(let W of M)for(let[R]of m.getFilesMap(W.project))U.add(`${W.project}::${R}`);return S.transaction(()=>{for(let W of C)hn({parsed:W.parsed,project:W.project,filePath:W.filePath,contentHash:W.contentHash,symbolRepo:i}),Z+=on({ast:W.parsed.program,project:W.project,filePath:W.filePath,relationRepo:t,projectRoot:r,tsconfigPaths:_,knownFiles:U,boundaries:M}),D.set(W.filePath,W.parsed),H+=i.getFileSymbols(W.project,W.filePath).length}),{symbols:H,relations:Z,failedFiles:L}},B=0,Y=0,N=[];if(u){let{projectRoot:r,boundaries:M}=this.opts,{parseCache:D}=this.opts,H=[];for(let L=0;L<w.length;L+=ku){let C=w.slice(L,L+ku),U=await Promise.allSettled(C.map(async(W)=>{let R=_n(r,W.filePath),X=Bun.file(R),v=await X.text(),E=W.contentHash||mn(v);return{filePath:W.filePath,text:v,contentHash:E,mtimeMs:X.lastModified,size:X.size}}));for(let W of U)if(W.status==="fulfilled")H.push(W.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",W.reason)}let Z=[];S.transaction(()=>{for(let U of H){let W=G(U.filePath,M);m.deleteFile(W,U.filePath)}for(let U of O){let W=G(U,M);i.deleteFileSymbols(W,U),t.deleteFileRelations(W,U),m.deleteFile(W,U)}for(let U of H){let W=G(U.filePath,M);m.upsertFile({project:W,filePath:U.filePath,mtimeMs:U.mtimeMs,size:U.size,contentHash:U.contentHash,updatedAt:new Date().toISOString(),lineCount:U.text.split(`
5
+ `).length})}let L=new Set;for(let U of M)for(let[W]of m.getFilesMap(U.project))L.add(`${U.project}::${W}`);let C=this.opts.parseSourceFn??$n;for(let U of H){let W=G(U.filePath,M),R=C(_n(r,U.filePath),U.text);if(Iu(R))throw R.data;let X=R;Z.push({filePath:U.filePath,parsed:X}),hn({parsed:X,project:W,filePath:U.filePath,contentHash:U.contentHash,symbolRepo:i}),Y+=on({ast:X.program,project:W,filePath:U.filePath,relationRepo:t,projectRoot:r,tsconfigPaths:_,knownFiles:L,boundaries:M}),B+=i.getFileSymbols(W,U.filePath).length}});for(let L of Z)D.set(L.filePath,L.parsed)}else{V();let r=await Q();B=r.symbols,Y=r.relations,N=r.failedFiles}for(let r of w){let M=G(r.filePath,this.opts.boundaries);for(let D of i.getFileSymbols(M,r.filePath))z.set(`${D.filePath}::${D.name}`,{name:D.name,filePath:D.filePath,kind:D.kind,fingerprint:D.fingerprint})}let $={added:[],modified:[],removed:[]};for(let[r,M]of z){let D=f.get(r);if(!D)$.added.push({name:M.name,filePath:M.filePath,kind:M.kind});else if(D.fingerprint!==M.fingerprint)$.modified.push({name:M.name,filePath:M.filePath,kind:M.kind})}for(let[r,M]of f)if(!z.has(r))$.removed.push({name:M.name,filePath:M.filePath,kind:M.kind});if(!u)for(let[r,M]of A)for(let D of M){if(!D.fingerprint)continue;let H=G(r,this.opts.boundaries),Z=i.getByFingerprint(H,D.fingerprint);if(Z.length===1){let L=Z[0];t.retargetRelations({dstProject:H,oldFile:r,oldSymbol:D.name,newFile:L.filePath,newSymbol:L.name})}}return{indexedFiles:w.length,removedFiles:O.length,totalSymbols:B,totalRelations:Y,durationMs:Date.now()-g,changedFiles:w.map((r)=>r.filePath),deletedFiles:[...O],failedFiles:N,changedSymbols:$}}fireCallbacks(n){for(let u of this.callbacks)try{u(n)}catch(g){this.logger.error("[IndexCoordinator] onIndexed callback threw:",g)}}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 Nm(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 Mm(n){let u=new Date(n).getTime();return Number.isNaN(u)?0:u}function Cu(n,u,g={}){let m=g.now??Date.now,i=g.isAlive??Nm,t=g.staleAfterSeconds??60,S=g.instanceId;return n.immediateTransaction(()=>{let w=n.selectOwner();if(!w)return n.insertOwner(u,S),"owner";let O=Math.floor((m()-Mm(w.heartbeat_at))/1000),_=i(w.pid);if(_&&S&&w.instance_id&&w.instance_id!==S&&w.pid!==u)return n.replaceOwner(u,S),"owner";if(_&&O<t)return"reader";return n.replaceOwner(u,S),"owner"})}function Tu(n,u){n.deleteOwner(u)}function yu(n,u){n.touchOwner(u)}class zn{#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 g=this.#u.keys().next().value;if(g!==void 0)this.#u.delete(g)}}delete(n){return this.#u.delete(n)}clear(){this.#u.clear()}}class cn{lru;constructor(n=500){this.lru=new zn(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 en(n){let{symbolRepo:u,project:g,query:m}=n,i=m.project??g,t=m.limit??100,S={kind:m.kind,filePath:m.filePath,isExported:m.isExported,project:i,limit:t,resolvedType:m.resolvedType};if(m.text)if(m.exact)S.exactName=m.text;else{let O=Qn(m.text);if(O)S.ftsQuery=O}if(m.decorator)S.decorator=m.decorator;if(m.regex)S.regex=m.regex;return u.searchByQuery(S).map((O)=>({id:O.id,filePath:O.filePath,kind:O.kind,name:O.name,span:{start:{line:O.startLine,column:O.startColumn},end:{line:O.endLine,column:O.endColumn}},isExported:O.isExported===1,signature:O.signature,fingerprint:O.fingerprint,detail:O.detailJson?(()=>{try{return JSON.parse(O.detailJson)}catch{return{}}})():{}}))}function nu(n){let{relationRepo:u,project:g,query:m}=n,i=m.project??g,t=m.limit??500;return u.searchRelations({srcFilePath:m.srcFilePath,srcSymbolName:m.srcSymbolName,dstFilePath:m.dstFilePath,dstSymbolName:m.dstSymbolName,dstProject:m.dstProject,type:m.type,project:i,limit:t}).map((w)=>{let O;if(w.metaJson)try{O=JSON.parse(w.metaJson)}catch{}return{type:w.type,srcFilePath:w.srcFilePath,srcSymbolName:w.srcSymbolName,dstFilePath:w.dstFilePath,dstSymbolName:w.dstSymbolName,dstProject:w.dstProject,metaJson:w.metaJson??void 0,meta:O}})}import{findInFiles as $m,Lang as zm}from"@ast-grep/napi";async function uu(n){if(n.filePaths.length===0)return[];let u=[];return await $m(zm.TypeScript,{paths:n.filePaths,matcher:{rule:{pattern:n.pattern}}},(g,m)=>{if(g)return;for(let i of m){let t=i.range();u.push({filePath:i.getRoot().filename(),startLine:t.start.line+1,endLine:t.end.line+1,matchedText:i.text()})}}),u}import b from"typescript";import{isErr as km}from"@zipbul/result";import l from"typescript";import Dm from"path";import{err as gu}from"@zipbul/result";function Km(n){try{return Ju("fs").readFileSync(n,"utf-8")}catch{return}}function Vm(n){try{return Ju("fs").readFileSync(n,"utf-8")}catch{return}}class In{#n;#u;#g=!1;__testing__;constructor(n,u){this.#n=n,this.#u=u,this.__testing__={host:u}}static create(n,u={}){let g=u.readConfigFile??Km,m=u.resolveNonTrackedFile??Vm,i=Dm.dirname(n),t=g(n);if(t===void 0)return gu(p("semantic",`tsconfig not found: ${n}`));let S=l.parseJsonText(n,t),w=S.parseDiagnostics;if(w&&w.length>0){let f=w.map((z)=>l.flattenDiagnosticMessageText(z.messageText,`
6
+ `)).join("; ");return gu(p("semantic",`tsconfig parse error: ${f}`))}let O=l.parseJsonSourceFileConfigFileContent(S,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(f)=>g(f)!==void 0||m(f)!==void 0,readFile:(f)=>g(f)??m(f)},i);if(O.errors.length>0){let f=O.errors.filter((z)=>z.category===l.DiagnosticCategory.Error&&z.code!==18003);if(f.length>0){let z=f.map((V)=>l.flattenDiagnosticMessageText(V.messageText,`
7
+ `)).join("; ");return gu(p("semantic",`tsconfig compile error: ${z}`))}}let _=new su(O.fileNames,O.options,i,m),A=l.createLanguageService(_);return new In(A,_)}get isDisposed(){return this.#g}getProgram(){this.#i();let n=this.#n.getProgram();if(!n)throw Error("TscProgram: LanguageService returned null Program");return n}getChecker(){return this.#i(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#i(),this.#n}notifyFileChanged(n,u){if(this.#g)return;this.#u.updateFile(n,u)}removeFile(n){if(this.#g)return;this.#u.removeFile(n)}dispose(){if(this.#g)return;this.#g=!0,this.#n.dispose()}#i(){if(this.#g)throw Error("TscProgram is disposed")}}class su{#n;#u;#g;#i;#m=new Map;constructor(n,u,g,m){this.#n=[...n],this.#u=u,this.#g=g,this.#i=m}updateFile(n,u){let g=this.#m.get(n);if(g)g.version+=1,g.content=u;else this.#m.set(n,{version:1,content:u})}removeFile(n){this.#m.delete(n),this.#n=this.#n.filter((u)=>u!==n)}getScriptFileNames(){let n=[...this.#m.keys()];return[...this.#n.filter((g)=>!this.#m.has(g)),...n]}getScriptVersion(n){let u=this.#m.get(n);return u?String(u.version):"0"}getScriptSnapshot(n){let u=this.#m.get(n);if(u)return l.ScriptSnapshot.fromString(u.content);let g=this.#i(n);if(g!==void 0)return l.ScriptSnapshot.fromString(g);return}getCurrentDirectory(){return this.#g}getCompilationSettings(){return this.#u}getDefaultLibFileName(n){return l.getDefaultLibFilePath(n)}fileExists(n){if(this.#m.has(n))return!0;return this.#i(n)!==void 0}readFile(n){let u=this.#m.get(n);if(u)return u.content;return this.#i(n)}}import q from"typescript";import Wm from"typescript";function c(n,u){if(u<0||u>=n.getEnd())return;function g(m){let i=m.getStart(n,!1),t=m.getEnd();if(u<i||u>=t)return;let S;return Wm.forEachChild(m,(w)=>{if(!S)S=g(w)}),S??m}return g(n)}function Hm(n){return!!(n.flags&q.TypeFlags.Object)&&!!(n.objectFlags&q.ObjectFlags.Reference)}function Dn(n,u,g=0){let m=n.typeToString(u),i=u.flags,t=!!(i&q.TypeFlags.Union),S=!!(i&q.TypeFlags.Intersection),w;if(g<8&&Hm(u)){let f=n.getTypeArguments(u);if(f.length>0)w=f}let O=!!(i&q.TypeFlags.TypeParameter)||w!==void 0&&w.length>0,_;if(t&&g<8)_=u.types.map((f)=>Dn(n,f,g+1));else if(S&&g<8)_=u.types.map((f)=>Dn(n,f,g+1));let A;if(w&&w.length>0)A=w.map((f)=>Dn(n,f,g+1));return{text:m,flags:i,isUnion:t,isIntersection:S,isGeneric:O,members:_,typeArguments:A}}function Qm(n){return q.isFunctionDeclaration(n)||q.isVariableDeclaration(n)||q.isClassDeclaration(n)||q.isInterfaceDeclaration(n)||q.isTypeAliasDeclaration(n)||q.isEnumDeclaration(n)||q.isMethodDeclaration(n)||q.isPropertyDeclaration(n)||q.isPropertySignature(n)||q.isMethodSignature(n)}class mu{program;constructor(n){this.program=n}collectAt(n,u){let g=this.program.getProgram(),m=this.program.getChecker();if(u<0)return null;let i=g.getSourceFile(n);if(!i)return null;if(u>=i.getEnd())return null;let t=c(i,u);if(!t)return null;if(!q.isIdentifier(t))return null;try{let S=m.getTypeAtLocation(t);return Dn(m,S)}catch{return null}}collectFile(n){let u=new Map,g=this.program.getProgram(),m=this.program.getChecker(),i=g.getSourceFile(n);if(!i)return u;function t(S){if(Qm(S)&&S.name&&q.isIdentifier(S.name)){let w=S.name;try{let O=m.getTypeAtLocation(w),_=w.getStart(i);u.set(_,Dn(m,O))}catch{}}q.forEachChild(S,t)}return t(i),u}}import tn from"typescript";var Um=1000,Bm=1;function Ym(n){let u=n.declarations?.[0],g=u?.getSourceFile(),m=u?tn.getNameOfDeclaration(u):void 0;return{name:n.getName(),filePath:g?.fileName??"",position:m?.getStart(g,!1)??u?.getStart(g,!1)??0}}function kn(n,u=0){let g=n.declarations?.[0],m=g?.getSourceFile(),i=g?tn.getNameOfDeclaration(g):void 0,t=m?.fileName??"",S=i?.getStart(m,!1)??g?.getStart(m,!1)??0,w={name:n.getName(),filePath:t,position:S},O=n;if(O.parent)w.parent=Ym(O.parent);if(u<Bm){let _=n.flags,A=!!(_&tn.SymbolFlags.Enum),f=!!(_&(tn.SymbolFlags.NamespaceModule|tn.SymbolFlags.ValueModule)),z=!!(_&(tn.SymbolFlags.Class|tn.SymbolFlags.Interface));if(A&&n.exports&&n.exports.size>0){let V=[];n.exports.forEach((Q)=>{V.push(kn(Q,u+1))}),w.members=V}else if(z&&n.members&&n.members.size>0){let V=[];n.members.forEach((Q)=>{V.push(kn(Q,u+1))}),w.members=V}if(f&&n.exports&&n.exports.size>0){let V=[];n.exports.forEach((Q)=>{V.push(kn(Q,u+1))}),w.exports=V}}return w}class iu{#n;#u;#g=new Map;constructor(n,u=Um){this.#n=n,this.#u=new zn(u)}get(n,u){if(this.#n.isDisposed)return null;let g=`${n}:${u}`,m=this.#u.get(g);if(m!==void 0)return m;let t=this.#n.getProgram().getSourceFile(n);if(!t)return null;let S=c(t,u);if(!S||!tn.isIdentifier(S))return null;let O=this.#n.getChecker().getSymbolAtLocation(S);if(!O)return null;let _=kn(O);this.#u.set(g,_);let A=this.#g.get(n);if(!A)A=new Set,this.#g.set(n,A);return A.add(g),_}invalidate(n){let u=this.#g.get(n);if(u){for(let g of u)this.#u.delete(g);this.#g.delete(n)}}clear(){this.#u.clear(),this.#g.clear()}}import Zm from"typescript";class tu{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let g=this.#n.getProgram(),m=g.getSourceFile(n);if(!m)return[];let i=c(m,u);if(!i||!Zm.isIdentifier(i))return[];let S=this.#n.getLanguageService().findReferences(n,u);if(!S||S.length===0)return[];let w=[];for(let O of S)for(let _ of O.references){let A=g.getSourceFile(_.fileName);if(!A)continue;let{line:f,character:z}=A.getLineAndCharacterOfPosition(_.textSpan.start);w.push({filePath:_.fileName,position:_.textSpan.start,line:f+1,column:z,isDefinition:_.isDefinition??!1,isWrite:_.isWriteAccess??!1})}return w}}import T from"typescript";function Lm(n,u){let g=c(n,u);if(!g)return;if(Ru(g))return g;let m=g.parent;for(let i=0;i<5&&m;i++){if(Ru(m))return m;m=m.parent}return g}function Ru(n){return T.isClassDeclaration(n)||T.isClassExpression(n)||T.isFunctionDeclaration(n)||T.isFunctionExpression(n)||T.isArrowFunction(n)||T.isVariableDeclaration(n)||T.isObjectLiteralExpression(n)}function Fu(n){if(T.isClassDeclaration(n)||T.isClassExpression(n))return"class";if(T.isFunctionDeclaration(n)||T.isFunctionExpression(n)||T.isArrowFunction(n))return"function";if(T.isObjectLiteralExpression(n))return"object";if(T.isVariableDeclaration(n)&&n.initializer)return Fu(n.initializer);return"class"}function Xm(n,u){if(T.isClassDeclaration(n)||T.isFunctionDeclaration(n))return n.name?.getText(u)??"";if(T.isClassExpression(n))return n.name?.getText(u)??"";if(T.isVariableDeclaration(n)&&T.isIdentifier(n.name))return n.name.getText(u);if(T.isFunctionExpression(n))return n.name?.getText(u)??"";if(T.isArrowFunction(n)&&n.parent&&T.isVariableDeclaration(n.parent)){if(T.isIdentifier(n.parent.name))return n.parent.name.getText(u)}if(T.isObjectLiteralExpression(n)&&n.parent&&T.isVariableDeclaration(n.parent)){if(T.isIdentifier(n.parent.name))return n.parent.name.getText(u)}return""}function Im(n){if(!T.isClassDeclaration(n)&&!T.isClassExpression(n))return!1;let u=n.heritageClauses;if(!u)return!1;return u.some((g)=>g.token===T.SyntaxKind.ImplementsKeyword)}class wu{#n;constructor(n){this.#n=n}findAt(n,u){if(this.#n.isDisposed)return[];let g=this.#n.getProgram(),m=g.getSourceFile(n);if(!m)return[];let i=c(m,u);if(!i||!T.isIdentifier(i))return[];let S=this.#n.getLanguageService().getImplementationAtPosition(n,u);if(!S||S.length===0)return[];let w=[];for(let O of S){if(O.kind===T.ScriptElementKind.interfaceElement||O.kind===T.ScriptElementKind.typeElement)continue;let _=g.getSourceFile(O.fileName);if(!_)continue;let A=Lm(_,O.textSpan.start);if(!A)continue;let f=Fu(A),z=Xm(A,_),V=Im(A);w.push({filePath:O.fileName,symbolName:z,position:O.textSpan.start,kind:f,isExplicit:V})}return w}}function au(n){return b.canHaveModifiers(n)&&b.getModifiers(n)?.some((u)=>u.kind===b.SyntaxKind.ExportKeyword)===!0}function Cm(n){if(b.isFunctionDeclaration(n))return"function";if(b.isClassDeclaration(n))return"class";if(b.isInterfaceDeclaration(n))return"interface";if(b.isTypeAliasDeclaration(n))return"type";if(b.isEnumDeclaration(n))return"enum";if(b.isVariableDeclaration(n))return"const";if(b.isVariableStatement(n))return"const";return"unknown"}function bu(n){if(n>=97&&n<=122)return!0;if(n>=65&&n<=90)return!0;if(n>=48&&n<=57)return!0;if(n===95||n===36)return!0;return!1}class Cn{#n;#u;#g;#i;#m;#t=!1;constructor(n,u,g,m,i){this.#n=n,this.#u=u,this.#g=g,this.#i=m,this.#m=i}static create(n,u={}){let g=In.create(n,{readConfigFile:u.readConfigFile,resolveNonTrackedFile:u.resolveNonTrackedFile});if(km(g))return g;let m=g,i=u.typeCollector??new mu(m),t=u.symbolGraph??new iu(m),S=u.referenceResolver??new tu(m),w=u.implementationFinder??new wu(m);return new Cn(m,i,t,S,w)}get isDisposed(){return this.#t}collectTypeAt(n,u){return this.#w(),this.#u.collectAt(n,u)}collectFileTypes(n){return this.#w(),this.#u.collectFile(n)}findReferences(n,u){return this.#w(),this.#i.findAt(n,u)}findImplementations(n,u){return this.#w(),this.#m.findAt(n,u)}getSymbolNode(n,u){return this.#w(),this.#g.get(n,u)}getModuleInterface(n){this.#w();let u=this.#u.collectFile(n),g=[],i=this.#n.getProgram().getSourceFile(n);if(!i)return{filePath:n,exports:g};function t(S){if(b.isVariableStatement(S)&&au(S)){for(let w of S.declarationList.declarations)if(b.isIdentifier(w.name)){let O=w.name.getStart(i),_=u.get(O)??null;g.push({name:w.name.text,kind:"const",resolvedType:_})}return}if((b.isFunctionDeclaration(S)||b.isClassDeclaration(S)||b.isInterfaceDeclaration(S)||b.isTypeAliasDeclaration(S)||b.isEnumDeclaration(S))&&au(S)&&S.name){let w=S.name,O=w.getStart(i),_=u.get(O)??null;g.push({name:w.text,kind:Cm(S),resolvedType:_});return}b.forEachChild(S,t)}return t(i),{filePath:n,exports:g}}notifyFileChanged(n,u){if(this.#t)return;this.#n.notifyFileChanged(n,u),this.#g.invalidate(n)}notifyFileDeleted(n){if(this.#t)return;this.#n.removeFile(n),this.#g.invalidate(n)}lineColumnToPosition(n,u,g){this.#w();let m=this.#n.getProgram().getSourceFile(n);if(!m)return null;try{return b.getPositionOfLineAndCharacter(m,u-1,g)}catch{return null}}findNamePosition(n,u,g){this.#w();let m=this.#n.getProgram().getSourceFile(n);if(!m)return null;let i=m.getFullText(),t=u;while(t<i.length){let S=i.indexOf(g,t);if(S<0)return null;let w=S>0?i.charCodeAt(S-1):32,O=S+g.length<i.length?i.charCodeAt(S+g.length):32;if(!bu(w)&&!bu(O))return S;t=S+1}return null}dispose(){if(this.#t)return;this.#t=!0,this.#n.dispose(),this.#g.clear()}#w(){if(this.#t)throw Error("SemanticLayer is disposed")}}class Tn{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((g)=>[...this.options.relationRepo.getByType(g,"imports"),...this.options.relationRepo.getByType(g,"type-references"),...this.options.relationRepo.getByType(g,"re-exports")]);for(let g of u){let{srcFilePath:m,dstFilePath:i}=g;if(!this.adjacencyList.has(m))this.adjacencyList.set(m,new Set);if(this.adjacencyList.get(m).add(i),!this.adjacencyList.has(i))this.adjacencyList.set(i,new Set);if(!this.reverseAdjacencyList.has(i))this.reverseAdjacencyList.set(i,new Set);this.reverseAdjacencyList.get(i).add(m)}}patchFiles(n,u,g){let m=new Set([...n,...u]);for(let i of m){let t=this.adjacencyList.get(i);if(t){for(let w of t)this.reverseAdjacencyList.get(w)?.delete(i);t.clear()}let S=this.reverseAdjacencyList.get(i);if(S){for(let w of S)this.adjacencyList.get(w)?.delete(i);S.clear()}}for(let i of u)this.adjacencyList.delete(i),this.reverseAdjacencyList.delete(i);for(let i of n){let t=g(i);for(let S of t){if(!this.adjacencyList.has(S.srcFilePath))this.adjacencyList.set(S.srcFilePath,new Set);if(this.adjacencyList.get(S.srcFilePath).add(S.dstFilePath),!this.adjacencyList.has(S.dstFilePath))this.adjacencyList.set(S.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(S.dstFilePath))this.reverseAdjacencyList.set(S.dstFilePath,new Set);this.reverseAdjacencyList.get(S.dstFilePath).add(S.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,g=[n];while(g.length>0){let m=g.shift();for(let i of this.reverseAdjacencyList.get(m)??[])if(!u.has(i))u.add(i),g.push(i)}return Array.from(u)}hasCycle(){let n=new Set,u=new Set;for(let g of this.adjacencyList.keys()){if(n.has(g))continue;let m=[{node:g,entered:!1}];while(m.length>0){let i=m.pop();if(i.entered){u.delete(i.node);continue}if(u.has(i.node))return!0;if(n.has(i.node))continue;n.add(i.node),u.add(i.node),m.push({node:i.node,entered:!0});for(let t of this.adjacencyList.get(i.node)??[]){if(u.has(t))return!0;if(!n.has(t))m.push({node:t,entered:!1})}}}return!1}getAffectedByChange(n){let u=new Set;for(let g of n)for(let m of this.getTransitiveDependents(g))u.add(m);return Array.from(u)}getAdjacencyList(){let n=new Map;for(let[u,g]of this.adjacencyList)n.set(u,Array.from(g));return n}getTransitiveDependencies(n){let u=new Set,g=[n];while(g.length>0){let m=g.shift();for(let i of this.adjacencyList.get(m)??[])if(!u.has(i))u.add(i),g.push(i)}return Array.from(u)}getCyclePaths(n){let u=n?.maxCycles??1/0;if(u<=0)return[];let g=new Map;for(let[m,i]of this.adjacencyList)g.set(m,Array.from(i));return Fm(g,u)}}var Tm=(n,u)=>n.localeCompare(u);function ym(n){let u=n.length>1&&n[0]===n[n.length-1]?n.slice(0,-1):[...n];if(u.length===0)return[];let g=u;for(let m=1;m<u.length;m++){let i=u.slice(m).concat(u.slice(0,m));if(i.join("::")<g.join("::"))g=i}return[...g]}function Ou(n,u,g){let m=ym(g);if(m.length===0)return!1;let i=m.join("->");if(n.has(i))return!1;return n.add(i),u.push(m),!0}function sm(n){let u=0,g=[],m=new Set,i=new Map,t=new Map,S=[],w=(O)=>{i.set(O,u),t.set(O,u),u+=1,g.push(O),m.add(O);for(let _ of n.get(O)??[])if(!i.has(_))w(_),t.set(O,Math.min(t.get(O)??0,t.get(_)??0));else if(m.has(_))t.set(O,Math.min(t.get(O)??0,i.get(_)??0));if(t.get(O)===i.get(O)){let _=[],A="";do A=g.pop()??"",m.delete(A),_.push(A);while(A!==O&&g.length>0);S.push(_)}};for(let O of n.keys())if(!i.has(O))w(O);return{components:S}}function Rm(n,u,g){let m=[],i=new Set,t=[...n].sort(Tm),S=(w,O,_)=>{O.delete(w);let A=_.get(w);if(!A)return;for(let f of A)if(O.has(f))S(f,O,_);A.clear()};for(let w=0;w<t.length&&m.length<g;w++){let O=t[w]??"",_=new Set(t.slice(w)),A=new Set,f=new Map,z=[],V=(B)=>(u.get(B)??[]).filter((Y)=>_.has(Y)),Q=(B)=>{if(m.length>=g)return!0;let Y=!1;z.push(B),A.add(B);for(let N of V(B)){if(m.length>=g)break;if(N===O)Ou(i,m,z.concat(O)),Y=!0;else if(!A.has(N)){if(Q(N))Y=!0}}if(Y)S(B,A,f);else for(let N of V(B)){let $=f.get(N)??new Set;$.add(B),f.set(N,$)}return z.pop(),Y};Q(O)}return m}function Fm(n,u){let{components:g}=sm(n),m=[],i=new Set;for(let t of g){if(m.length>=u)break;if(t.length===0)continue;if(t.length===1){let O=t[0]??"";if((n.get(O)??[]).includes(O))Ou(i,m,[O,O]);continue}let S=u-m.length,w=Rm(t,n,S);for(let O of w){if(m.length>=u)break;Ou(i,m,O)}}return m}var am=15000;function yn(n){n.graphCache=null,n.graphCacheKey=null,n.graphCacheBuiltAt=null}function An(n,u){let g=u??"__cross__";if(n.graphCache&&n.graphCacheBuiltAt!==null){if(Date.now()-n.graphCacheBuiltAt>am)n.graphCache=null,n.graphCacheKey=null,n.graphCacheBuiltAt=null}if(n.graphCache&&n.graphCacheKey===g)return n.graphCache;let m=new Tn({relationRepo:n.relationRepo,project:u??n.defaultProject,additionalProjects:u?void 0:n.boundaries?.map((i)=>i.project)});return m.build(),n.graphCache=m,n.graphCacheKey=g,n.graphCacheBuiltAt=Date.now(),m}function qu(n,u,g,m=1e4){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:g??n.defaultProject,query:{srcFilePath:u,type:"imports",project:g??n.defaultProject,limit:m}}).map((i)=>i.dstFilePath)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getDependencies failed",{cause:i})}}function pu(n,u,g,m=1e4){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:g??n.defaultProject,query:{dstFilePath:u,type:"imports",project:g??n.defaultProject,limit:m}}).map((i)=>i.srcFilePath)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getDependents failed",{cause:i})}}async function vu(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return An(n,g).getAffectedByChange(u)}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getAffected failed",{cause:m})}}async function Gu(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return An(n,u).hasCycle()}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: hasCycle failed",{cause:g})}}async function Eu(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return An(n,u).getAdjacencyList()}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: getImportGraph failed",{cause:g})}}async function ju(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return An(n,g).getTransitiveDependencies(u)}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getTransitiveDependencies failed",{cause:m})}}async function Pu(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return An(n,u).getCyclePaths(g)}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getCyclePaths failed",{cause:m})}}async function hu(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let m=An(n,g);return{filePath:u,fanIn:m.getDependents(u).length,fanOut:m.getDependencies(u).length}}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getFanMetrics failed",{cause:m})}}var pm=30000,du=15000,vm=10;function Gm(n,u){return(g)=>{for(let m of n.onFileChangedCallbacks)try{m(g)}catch(i){n.logger.error("[Gildash] onFileChanged callback threw:",i)}if(u.handleWatcherEvent?.(g),n.semanticLayer)if(g.eventType==="delete")try{n.semanticLayer.notifyFileDeleted(g.filePath)}catch(m){n.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",m);for(let i of n.onErrorCallbacks)try{i(m instanceof J?m:new J("semantic","semantic notifyFileDeleted failed",{cause:m}))}catch{}}else n.readFileFn(g.filePath).then((m)=>{try{n.semanticLayer?.notifyFileChanged(g.filePath,m)}catch(i){n.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",i);for(let t of n.onErrorCallbacks)try{t(i instanceof J?i:new J("semantic","semantic notifyFileChanged failed",{cause:i}))}catch{}}}).catch((m)=>{n.logger.error("[Gildash] failed to read file for semantic layer",g.filePath,m);try{n.semanticLayer?.notifyFileDeleted(g.filePath)}catch(i){n.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",i)}})}}async function Em(n){if(!n.semanticLayer)return;let u=n.fileRepo.getAllFiles(n.defaultProject);await Promise.all(u.map(async(g)=>{try{let m=Vn.resolve(n.projectRoot,g.filePath),i=await n.readFileFn(m);n.semanticLayer?.notifyFileChanged(m,i)}catch{}}))}async function xu(n,u){let g=n.coordinatorFactory?n.coordinatorFactory():new ln({projectRoot:n.projectRoot,boundaries:n.boundaries,extensions:n.extensions,ignorePatterns:n.ignorePatterns,dbConnection:n.db,parseCache:n.parseCache,fileRepo:n.fileRepo,symbolRepo:n.symbolRepo,relationRepo:n.relationRepo,logger:n.logger});n.coordinator=g;for(let m of n.onIndexedCallbacks)g.onIndexed(m);if(g.onIndexed((m)=>{let i=m.changedFiles.length+m.deletedFiles.length;if(n.graphCache&&i>0&&i<100){let t=n.relationRepo;n.graphCache.patchFiles(m.changedFiles,m.deletedFiles,(S)=>{return[n.defaultProject,...n.boundaries.map((O)=>O.project)].flatMap((O)=>t.getByType(O,"imports").concat(t.getByType(O,"type-references")).concat(t.getByType(O,"re-exports"))).filter((O)=>O.srcFilePath===S||O.dstFilePath===S).map((O)=>({srcFilePath:O.srcFilePath,dstFilePath:O.dstFilePath}))}),n.graphCacheBuiltAt=Date.now()}else yn(n)}),u.isWatchMode){let m=n.watcherFactory?n.watcherFactory():new En({projectRoot:n.projectRoot,ignorePatterns:n.ignorePatterns,extensions:n.extensions},void 0,n.logger);await m.start(Gm(n,g)).then((i)=>{if(Kn(i))throw i.data}),n.watcher=m,n.timer=setInterval(()=>{n.updateHeartbeatFn(n.db,process.pid)},pm)}await g.fullIndex(),await Em(n)}function jm(n,u){let g=["SIGTERM","SIGINT","beforeExit"];for(let m of g){let i=()=>{u().catch((t)=>n.logger.error("[Gildash] close error during signal",m,t))};if(m==="beforeExit")process.on("beforeExit",i);else process.on(m,i);n.signalHandlers.push([m,i])}}async function ou(n){let{projectRoot:u,extensions:g=[".ts",".mts",".cts"],ignorePatterns:m=["**/node_modules/**"],parseCacheCapacity:i=500,logger:t=console,existsSyncFn:S=qm,dbConnectionFactory:w,watcherFactory:O,coordinatorFactory:_,repositoryFactory:A,acquireWatcherRoleFn:f=Cu,releaseWatcherRoleFn:z=Tu,updateHeartbeatFn:V=yu,discoverProjectsFn:Q=Bn,parseSourceFn:B=$n,extractSymbolsFn:Y=Ln,extractRelationsFn:N=Xn,symbolSearchFn:$=en,relationSearchFn:r=nu,patternSearchFn:M=uu,loadTsconfigPathsFn:D=Mn,readFileFn:H=async(X)=>Bun.file(X).text(),unlinkFn:Z=async(X)=>{await Bun.file(X).unlink()},watchMode:L,semantic:C,semanticLayerFactory:U}=n;if(!Vn.isAbsolute(u))throw new J("validation",`Gildash: projectRoot must be an absolute path, got: "${u}"`);if(!S(u))throw new J("validation",`Gildash: projectRoot does not exist: "${u}"`);let W=w?w():new bn({projectRoot:u}),R=W.open();if(Kn(R))throw R.data;try{let X=await Q(u),v=X[0]?.project??Vn.basename(u),E=A?A():(()=>{let h=W;return{fileRepo:new qn(h),symbolRepo:new pn(h),relationRepo:new vn(h),parseCache:new cn(i)}})(),P=L??!0,Rn=crypto.randomUUID(),e;if(P)e=await Promise.resolve(f(W,process.pid,{instanceId:Rn}));else e="owner";let I={projectRoot:u,extensions:g,ignorePatterns:m,logger:t,defaultProject:v,role:e,db:W,symbolRepo:E.symbolRepo,relationRepo:E.relationRepo,fileRepo:E.fileRepo,parseCache:E.parseCache,releaseWatcherRoleFn:z,parseSourceFn:B,extractSymbolsFn:Y,extractRelationsFn:N,symbolSearchFn:$,relationSearchFn:r,patternSearchFn:M,readFileFn:H,unlinkFn:Z,existsSyncFn:S,acquireWatcherRoleFn:f,updateHeartbeatFn:V,watcherFactory:O,coordinatorFactory:_,instanceId:Rn,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:X,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(Yn(u),I.tsconfigPaths=await D(u),C){let h=Vn.join(u,"tsconfig.json");try{if(U)I.semanticLayer=U(h);else{let d=Cn.create(h);if(Kn(d))throw d.data;I.semanticLayer=d}}catch(d){if(d instanceof J)throw d;throw new J("semantic","Gildash: semantic layer creation failed",{cause:d})}}if(e==="owner")await xu(I,{isWatchMode:P});else{let h=0,d=async()=>{try{let rn=await Promise.resolve(I.acquireWatcherRoleFn(I.db,process.pid,{instanceId:I.instanceId}));if(h=0,rn==="owner"){for(let fn of I.onRoleChangedCallbacks)try{fn("owner")}catch(x){I.logger.error("[Gildash] onRoleChanged callback threw:",x)}clearInterval(I.timer),I.timer=null;try{await xu(I,{isWatchMode:!0})}catch(fn){if(I.logger.error("[Gildash] owner promotion failed, reverting to reader",fn),I.watcher){let x=await I.watcher.close();if(Kn(x))I.logger.error("[Gildash] watcher close error during promotion rollback",x.data);I.watcher=null}if(I.coordinator)await I.coordinator.shutdown().catch((x)=>I.logger.error("[Gildash] coordinator shutdown error during promotion rollback",x)),I.coordinator=null;if(I.timer===null)I.timer=setInterval(d,du)}}}catch(rn){h++;let fn=rn instanceof J?rn:new J("watcher","Gildash: healthcheck error",{cause:rn});for(let x of I.onErrorCallbacks)try{x(fn)}catch(Xg){I.logger.error("[Gildash] onError callback threw:",Xg)}if(I.logger.error("[Gildash] healthcheck error",rn),h>=vm)I.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(I.timer),I.timer=null,sn(I).catch((x)=>I.logger.error("[Gildash] close error during healthcheck shutdown",x))}};I.timer=setInterval(d,du)}if(P)jm(I,()=>sn(I));return I}catch(X){if(W.close(),X instanceof J)throw X;throw new J("store","Gildash: initialization failed",{cause:X})}}async function sn(n,u){if(n.closed)return;n.closed=!0;let g=[];for(let[m,i]of n.signalHandlers)if(m==="beforeExit")process.off("beforeExit",i);else process.off(m,i);if(n.signalHandlers=[],n.semanticLayer){try{n.semanticLayer.dispose()}catch(m){g.push(m instanceof Error?m:Error(String(m)))}n.semanticLayer=null}if(n.coordinator)try{await n.coordinator.shutdown()}catch(m){g.push(m instanceof Error?m:Error(String(m)))}if(n.watcher){let m=await n.watcher.close();if(Kn(m))g.push(m.data)}if(n.timer!==null)clearInterval(n.timer),n.timer=null;try{n.releaseWatcherRoleFn(n.db,process.pid)}catch(m){g.push(m instanceof Error?m:Error(String(m)))}try{n.db.close()}catch(m){g.push(m instanceof Error?m:Error(String(m)))}if(u?.cleanup)for(let m of["","-wal","-shm"])try{await n.unlinkFn(Vn.join(n.projectRoot,nn,Wn+m))}catch{}if(g.length>0)throw new J("close","Gildash: one or more errors occurred during close()",{cause:g})}import{isErr as lu}from"@zipbul/result";function cu(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");let i=n.parseSourceFn(u,g,m);if(lu(i))throw i.data;return n.parseCache.set(u,i),i}async function eu(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");let m=new Map,i=[];return await Promise.all(u.map(async(t)=>{try{let S=await n.readFileFn(t),w=n.parseSourceFn(t,S,g);if(!lu(w))m.set(t,w);else i.push({filePath:t,error:w.data})}catch(S){i.push({filePath:t,error:S instanceof Error?S:Error(String(S))})}})),{parsed:m,failures:i}}function ng(n,u){if(n.closed)return;return n.parseCache.get(u)}function ug(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");return n.extractSymbolsFn(u)}function gg(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");return n.extractRelationsFn(u.program,u.filePath,n.tsconfigPaths??void 0)}import mg from"path";function ig(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.symbolRepo.getStats(u??n.defaultProject)}catch(g){if(g instanceof J)throw g;throw new J("store","Gildash: getStats failed",{cause:g})}}function Su(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:n.defaultProject,query:u})}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: searchSymbols failed",{cause:g})}}function tg(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:n.defaultProject,query:u})}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: searchRelations failed",{cause:g})}}function wg(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.symbolSearchFn({symbolRepo:n.symbolRepo,project:void 0,query:u})}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: searchAllSymbols failed",{cause:g})}}function Og(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:void 0,query:u})}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: searchAllRelations failed",{cause:g})}}function Sg(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.fileRepo.getAllFiles(u??n.defaultProject)}catch(g){if(g instanceof J)throw g;throw new J("store","Gildash: listIndexedFiles failed",{cause:g})}}function rg(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.relationSearchFn({relationRepo:n.relationRepo,project:g??n.defaultProject,query:{srcFilePath:u,dstFilePath:u,limit:1e4}})}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getInternalRelations failed",{cause:m})}}function _g(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let i=m??n.defaultProject,t=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:i,query:{text:u,exact:!0,filePath:g,limit:1}});if(t.length===0)return null;let S=t[0],w=S.detail,O={...S,members:Array.isArray(w.members)?w.members:void 0,jsDoc:typeof w.jsDoc==="string"?w.jsDoc:void 0,parameters:typeof w.parameters==="string"?w.parameters:void 0,returnType:typeof w.returnType==="string"?w.returnType:void 0,heritage:Array.isArray(w.heritage)?w.heritage:void 0,decorators:Array.isArray(w.decorators)?w.decorators:void 0,typeParameters:typeof w.typeParameters==="string"?w.typeParameters:void 0};if(n.semanticLayer)try{let _=mg.isAbsolute(g)?g:mg.resolve(n.projectRoot,g),A=n.semanticLayer.lineColumnToPosition(_,S.span.start.line,S.span.start.column);if(A!==null){let f=n.semanticLayer.findNamePosition(_,A,S.name)??A,z=n.semanticLayer.collectTypeAt(_,f);if(z)O.resolvedType=z}}catch{}return O}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getFullSymbol failed",{cause:i})}}function Jg(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let m=g??n.defaultProject,i=n.fileRepo.getFile(m,u);if(!i)throw new J("search",`Gildash: file '${u}' is not in the index`);let t=n.symbolRepo.getFileSymbols(m,u),S=n.relationRepo.getOutgoing(m,u);return{filePath:i.filePath,lineCount:i.lineCount??0,size:i.size,symbolCount:t.length,exportedSymbolCount:t.filter((w)=>w.isExported).length,relationCount:S.length}}catch(m){if(m instanceof J)throw m;throw new J("store","Gildash: getFileStats failed",{cause:m})}}function Ag(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{return n.fileRepo.getFile(g??n.defaultProject,u)}catch(m){if(m instanceof J)throw m;throw new J("store","Gildash: getFileInfo failed",{cause:m})}}function fg(n,u,g){return Su(n,{filePath:u,project:g??void 0,limit:1e4})}function Ng(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let i=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:g??n.defaultProject,query:{filePath:u,isExported:!0}}).map((t)=>({name:t.name,kind:t.kind,parameters:t.detail.parameters??void 0,returnType:t.detail.returnType??void 0,jsDoc:t.detail.jsDoc??void 0}));return{filePath:u,exports:i}}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: getModuleInterface failed",{cause:m})}}import Mg from"path";function ru(n,u,g,m){let i=m??n.defaultProject,t=n.symbolSearchFn({symbolRepo:n.symbolRepo,project:i,query:{text:u,exact:!0,filePath:g,limit:1}});if(t.length===0)return null;let S=t[0],w=Mg.isAbsolute(g)?g:Mg.resolve(n.projectRoot,g),O=n.semanticLayer.lineColumnToPosition(w,S.span.start.line,S.span.start.column);if(O===null)return null;let _=n.semanticLayer.findNamePosition(w,O,S.name)??O;return{sym:S,position:_,absPath:w}}function $g(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new J("semantic","Gildash: semantic layer is not enabled");try{let i=ru(n,u,g,m);if(!i)return null;return n.semanticLayer.collectTypeAt(i.absPath,i.position)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getResolvedType failed",{cause:i})}}function zg(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new J("semantic","Gildash: semantic layer is not enabled");try{let i=ru(n,u,g,m);if(!i)throw new J("search",`Gildash: symbol '${u}' not found in '${g}'`);return n.semanticLayer.findReferences(i.absPath,i.position)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getSemanticReferences failed",{cause:i})}}function Dg(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new J("semantic","Gildash: semantic layer is not enabled");try{let i=ru(n,u,g,m);if(!i)throw new J("search",`Gildash: symbol '${u}' not found in '${g}'`);return n.semanticLayer.findImplementations(i.absPath,i.position)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getImplementations failed",{cause:i})}}function Kg(n,u){if(n.closed)throw new J("closed","Gildash: instance is closed");if(!n.semanticLayer)throw new J("semantic","Gildash: semantic layer is not enabled");try{return n.semanticLayer.getModuleInterface(u)}catch(g){if(g instanceof J)throw g;throw new J("search","Gildash: getSemanticModuleInterface failed",{cause:g})}}function Vg(n,u){let g=new Map(n.map((w)=>[`${w.name}::${w.filePath}`,w])),m=new Map(u.map((w)=>[`${w.name}::${w.filePath}`,w])),i=[],t=[],S=[];for(let[w,O]of m){let _=g.get(w);if(!_)i.push(O);else if(_.fingerprint!==O.fingerprint)S.push({before:_,after:O})}for(let[w,O]of g)if(!m.has(w))t.push(O);return{added:i,removed:t,modified:S}}function Wg(n,u){if(n.onIndexedCallbacks.add(u),!n.coordinator)return()=>{n.onIndexedCallbacks.delete(u)};let g=n.coordinator.onIndexed(u);return()=>{n.onIndexedCallbacks.delete(u),g()}}async function Hg(n){if(n.closed)throw new J("closed","Gildash: instance is closed");if(!n.coordinator)throw new J("closed","Gildash: reindex() is not available for readers");try{let u=await n.coordinator.fullIndex();return yn(n),u}catch(u){if(u instanceof J)throw u;throw new J("index","Gildash: reindex failed",{cause:u})}}function Qg(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");let i=m??n.defaultProject,t=new Set,S=[],w=u,O=g;for(;;){let _=`${O}::${w}`;if(t.has(_))return{originalName:w,originalFilePath:O,reExportChain:S,circular:!0};t.add(_);let A=n.relationSearchFn({relationRepo:n.relationRepo,project:i,query:{type:"re-exports",srcFilePath:O,limit:500}}),f,z;for(let V of A){let Q;if(V.metaJson)try{let Y=JSON.parse(V.metaJson);if(Array.isArray(Y.specifiers))Q=Y.specifiers}catch{}if(!Q)continue;let B=Q.find((Y)=>Y.exported===w);if(!B)continue;f=V.dstFilePath,z=B.local;break}if(!f||!z)return{originalName:w,originalFilePath:O,reExportChain:S,circular:!1};S.push({filePath:O,exportedAs:w}),O=f,w=z}}function Ug(n,u){return n.onFileChangedCallbacks.add(u),()=>{n.onFileChangedCallbacks.delete(u)}}function Bg(n,u){return n.onErrorCallbacks.add(u),()=>{n.onErrorCallbacks.delete(u)}}function Yg(n,u){return n.onRoleChangedCallbacks.add(u),()=>{n.onRoleChangedCallbacks.delete(u)}}async function Zg(n,u,g){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let m=g?.project??n.defaultProject,i=g?.filePaths?g.filePaths:n.fileRepo.getAllFiles(m).map((t)=>t.filePath);return await n.patternSearchFn({pattern:u,filePaths:i})}catch(m){if(m instanceof J)throw m;throw new J("search","Gildash: findPattern failed",{cause:m})}}async function Lg(n,u,g,m){if(n.closed)throw new J("closed","Gildash: instance is closed");try{let i=m??n.defaultProject,t=new Set,S=(w,O,_)=>{let A=`${w}::${O}`;if(t.has(A))return{symbolName:w,filePath:O,kind:_,children:[]};t.add(A);let V=n.relationSearchFn({relationRepo:n.relationRepo,project:i,query:{srcFilePath:O,srcSymbolName:w,limit:1000}}).filter((Q)=>Q.type==="extends"||Q.type==="implements").filter((Q)=>Q.dstSymbolName!=null).map((Q)=>S(Q.dstSymbolName,Q.dstFilePath,Q.type));return{symbolName:w,filePath:O,kind:_,children:V}};return S(u,g)}catch(i){if(i instanceof J)throw i;throw new J("search","Gildash: getHeritageChain failed",{cause:i})}}class _u{_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 ou(n);return new _u(u)}async close(n){return sn(this._ctx,n)}parseSource(n,u,g){return cu(this._ctx,n,u,g)}async batchParse(n,u){return eu(this._ctx,n,u)}getParsedAst(n){return ng(this._ctx,n)}extractSymbols(n){return ug(this._ctx,n)}extractRelations(n){return gg(this._ctx,n)}getStats(n){return ig(this._ctx,n)}searchSymbols(n){return Su(this._ctx,n)}searchRelations(n){return tg(this._ctx,n)}searchAllSymbols(n){return wg(this._ctx,n)}searchAllRelations(n){return Og(this._ctx,n)}listIndexedFiles(n){return Sg(this._ctx,n)}getInternalRelations(n,u){return rg(this._ctx,n,u)}getFullSymbol(n,u,g){return _g(this._ctx,n,u,g)}getFileStats(n,u){return Jg(this._ctx,n,u)}getFileInfo(n,u){return Ag(this._ctx,n,u)}getSymbolsByFile(n,u){return fg(this._ctx,n,u)}getModuleInterface(n,u){return Ng(this._ctx,n,u)}getDependencies(n,u,g=1e4){return qu(this._ctx,n,u,g)}getDependents(n,u,g=1e4){return pu(this._ctx,n,u,g)}async getAffected(n,u){return vu(this._ctx,n,u)}async hasCycle(n){return Gu(this._ctx,n)}async getImportGraph(n){return Eu(this._ctx,n)}async getTransitiveDependencies(n,u){return ju(this._ctx,n,u)}async getCyclePaths(n,u){return Pu(this._ctx,n,u)}async getFanMetrics(n,u){return hu(this._ctx,n,u)}getResolvedType(n,u,g){return $g(this._ctx,n,u,g)}getSemanticReferences(n,u,g){return zg(this._ctx,n,u,g)}getImplementations(n,u,g){return Dg(this._ctx,n,u,g)}getSemanticModuleInterface(n){return Kg(this._ctx,n)}diffSymbols(n,u){return Vg(n,u)}onIndexed(n){return Wg(this._ctx,n)}async reindex(){return Hg(this._ctx)}resolveSymbol(n,u,g){return Qg(this._ctx,n,u,g)}async findPattern(n,u){return Zg(this._ctx,n,u)}async getHeritageChain(n,u,g){return Lg(this._ctx,n,u,g)}onFileChanged(n){return Ug(this._ctx,n)}onError(n){return Bg(this._ctx,n)}onRoleChanged(n){return Yg(this._ctx,n)}}export{en as symbolSearch,nu as relationSearch,uu as patternSearch,p as gildashError,J as GildashError,_u as Gildash,Tn as DependencyGraph};
8
8
 
9
- //# debugId=2B12BAE74427975264756E2164756E21
9
+ //# debugId=540D489DF398012964756E2164756E21
10
10
  //# sourceMappingURL=index.js.map