@zipbul/gildash 0.15.1 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var g1=Object.defineProperty;var q1=(_)=>_;function S1(_,$){this[_]=q1.bind(null,$)}var T1=(_,$)=>{for(var J in $)g1(_,J,{get:$[J],enumerable:!0,configurable:!0,set:S1.bind($,J)})};var P$=import.meta.require;import{isErr as n_}from"@zipbul/result";import m_ from"path";import{existsSync as cJ}from"fs";import{err as f$,isErr as E1}from"@zipbul/result";import{Database as v1}from"bun:sqlite";import{mkdirSync as b1,unlinkSync as n$,existsSync as m$}from"fs";import{dirname as y1,join as x$}from"path";import{drizzle as P1}from"drizzle-orm/bun-sqlite";import{migrate as f1}from"drizzle-orm/bun-sqlite/migrator";class V extends Error{type;constructor(_,$,J){super($,J);this.type=_;this.name="GildashError"}}var L_=".gildash",h_="gildash.db";var Y$={};T1(Y$,{watcherOwner:()=>j1,symbols:()=>n,symbolChangelog:()=>Q_,relations:()=>G,files:()=>__,annotations:()=>Y_});import{sql as R1}from"drizzle-orm";import{sqliteTable as A_,text as b,integer as e,real as k1,index as z_,primaryKey as F1,foreignKey as W$,check as G1}from"drizzle-orm/sqlite-core";var __=A_("files",{project:b("project").notNull(),filePath:b("file_path").notNull(),mtimeMs:k1("mtime_ms").notNull(),size:e("size").notNull(),contentHash:b("content_hash").notNull(),updatedAt:b("updated_at").notNull(),lineCount:e("line_count")},(_)=>[F1({columns:[_.project,_.filePath]})]),n=A_("symbols",{id:e("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),filePath:b("file_path").notNull(),kind:b("kind").notNull(),name:b("name").notNull(),startLine:e("start_line").notNull(),startColumn:e("start_column").notNull(),endLine:e("end_line").notNull(),endColumn:e("end_column").notNull(),isExported:e("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"),structuralFingerprint:b("structural_fingerprint")},(_)=>[z_("idx_symbols_project_file").on(_.project,_.filePath),z_("idx_symbols_project_kind").on(_.project,_.kind),z_("idx_symbols_project_name").on(_.project,_.name),z_("idx_symbols_fingerprint").on(_.project,_.fingerprint),W$({columns:[_.project,_.filePath],foreignColumns:[__.project,__.filePath]}).onDelete("cascade")]),G=A_("relations",{id:e("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"),dstFilePath:b("dst_file_path"),dstSymbolName:b("dst_symbol_name"),metaJson:b("meta_json"),specifier:b("specifier"),isExternal:e("is_external").notNull().default(0)},(_)=>[z_("idx_relations_src").on(_.project,_.srcFilePath),z_("idx_relations_dst").on(_.dstProject,_.dstFilePath),z_("idx_relations_type").on(_.project,_.type),z_("idx_relations_project_type_src").on(_.project,_.type,_.srcFilePath),z_("idx_relations_specifier").on(_.project,_.specifier),W$({columns:[_.project,_.srcFilePath],foreignColumns:[__.project,__.filePath]}).onDelete("cascade")]),Y_=A_("annotations",{id:e("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),filePath:b("file_path").notNull(),tag:b("tag").notNull(),value:b("value").notNull().default(""),source:b("source").notNull(),symbolName:b("symbol_name"),startLine:e("start_line").notNull(),startColumn:e("start_column").notNull(),endLine:e("end_line").notNull(),endColumn:e("end_column").notNull(),indexedAt:b("indexed_at").notNull()},(_)=>[z_("idx_annotations_project_file").on(_.project,_.filePath),z_("idx_annotations_project_tag").on(_.project,_.tag),z_("idx_annotations_project_symbol").on(_.project,_.symbolName),W$({columns:[_.project,_.filePath],foreignColumns:[__.project,__.filePath]}).onDelete("cascade")]),Q_=A_("symbol_changelog",{id:e("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),changeType:b("change_type").notNull(),symbolName:b("symbol_name").notNull(),symbolKind:b("symbol_kind").notNull(),filePath:b("file_path").notNull(),oldName:b("old_name"),oldFilePath:b("old_file_path"),fingerprint:b("fingerprint"),changedAt:b("changed_at").notNull(),isFullIndex:e("is_full_index").notNull().default(0),indexRunId:b("index_run_id").notNull()},(_)=>[z_("idx_changelog_project_changed_at").on(_.project,_.changedAt),z_("idx_changelog_project_name").on(_.project,_.symbolName),z_("idx_changelog_project_run").on(_.project,_.indexRunId)]),j1=A_("watcher_owner",{id:e("id").primaryKey(),pid:e("pid").notNull(),startedAt:b("started_at").notNull(),heartbeatAt:b("heartbeat_at").notNull(),instanceId:b("instance_id")},(_)=>[G1("watcher_owner_singleton",R1`${_.id} = 1`)]);class Z${client=null;drizzle=null;dbPath;txDepth=0;constructor(_){this.dbPath=x$(_.projectRoot,L_,h_)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{b1(y1(this.dbPath),{recursive:!0}),this.client=new v1(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=P1(this.client,{schema:Y$}),f1(this.drizzle,{migrationsFolder:x$(import.meta.dirname,"migrations")});let _=this.client.prepare("PRAGMA foreign_key_check").all();if(_.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(_.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON"),this.registerRegexpUdf(this.client)}catch(_){if(this.isCorruptionError(_)&&m$(this.dbPath)){this.closeClient(),n$(this.dbPath);for(let J of["-wal","-shm"]){let Q=this.dbPath+J;if(m$(Q))n$(Q)}let $=this.open();if(E1($))return f$(new V("store",`Failed to recover database at ${this.dbPath}`,{cause:$.data}));return $}return f$(new V("store",`Failed to open database at ${this.dbPath}`,{cause:_}))}}close(){this.closeClient(),this.drizzle=null}transaction(_){let $=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return $.transaction(()=>_(this))()}finally{this.txDepth--}}let J=`sp_${this.txDepth++}`;$.run(`SAVEPOINT "${J}"`);try{let Q=_(this);return $.run(`RELEASE SAVEPOINT "${J}"`),Q}catch(Q){throw $.run(`ROLLBACK TO SAVEPOINT "${J}"`),$.run(`RELEASE SAVEPOINT "${J}"`),Q}finally{this.txDepth--}}immediateTransaction(_){let $=this.requireClient();this.txDepth++,$.run("BEGIN IMMEDIATE");try{let J=_();return $.run("COMMIT"),J}catch(J){throw $.run("ROLLBACK"),J}finally{this.txDepth--}}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(($)=>$.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(_,$){let J=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(_,J,J,$??null)}replaceOwner(_,$){let J=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(_,J,J,$??null)}touchOwner(_){let $=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run($,_)}deleteOwner(_){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(_)}registerRegexpUdf(_){let $=_;if(typeof $.function!=="function")return;$.function.call(_,"regexp",(J,Q)=>{try{return new RegExp(J).test(Q)?1:0}catch{return 0}})}requireClient(){if(!this.client)throw Error("Database is not open. Call open() first.");return this.client}closeClient(){if(this.client)this.client.close(),this.client=null}isCorruptionError(_){if(!(_ instanceof Error))return!1;let $=_.message.toLowerCase();return $.includes("malformed")||$.includes("corrupt")||$.includes("not a database")||$.includes("disk i/o error")||$.includes("sqlite_corrupt")}}import{eq as F_,and as h$}from"drizzle-orm";class X${db;constructor(_){this.db=_}getFile(_,$){return this.db.drizzleDb.select().from(__).where(h$(F_(__.project,_),F_(__.filePath,$))).get()??null}upsertFile(_){this.db.drizzleDb.insert(__).values({project:_.project,filePath:_.filePath,mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}).onConflictDoUpdate({target:[__.project,__.filePath],set:{mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}}).run()}getAllFiles(_){return this.db.drizzleDb.select().from(__).where(F_(__.project,_)).all()}getFilesMap(_){let $=this.getAllFiles(_),J=new Map;for(let Q of $)J.set(Q.filePath,Q);return J}deleteFile(_,$){this.db.drizzleDb.delete(__).where(h$(F_(__.project,_),F_(__.filePath,$))).run()}}import{eq as $_,and as w_,sql as p_,count as n1}from"drizzle-orm";function g_(_){return _.replaceAll("\x00","").trim().split(/\s+/).map(($)=>$.trim()).filter(($)=>$.length>0).map(($)=>`"${$.replaceAll('"','""')}"*`).join(" ")}var p$=50;class O${db;constructor(_){this.db=_}replaceFileSymbols(_,$,J,Q){if(this.db.drizzleDb.delete(n).where(w_($_(n.project,_),$_(n.filePath,$))).run(),!Q.length)return;let z=new Date().toISOString(),Y=Q.map((Z)=>({project:_,filePath:$,kind:Z.kind??"unknown",name:Z.name??"",startLine:Z.startLine??0,startColumn:Z.startColumn??0,endLine:Z.endLine??0,endColumn:Z.endColumn??0,isExported:Z.isExported??0,signature:Z.signature??null,fingerprint:Z.fingerprint??null,detailJson:Z.detailJson??null,contentHash:J,indexedAt:Z.indexedAt??z,resolvedType:Z.resolvedType??null,structuralFingerprint:Z.structuralFingerprint??null}));for(let Z=0;Z<Y.length;Z+=p$)this.db.drizzleDb.insert(n).values(Y.slice(Z,Z+p$)).run()}getFileSymbols(_,$){return this.db.drizzleDb.select().from(n).where(w_($_(n.project,_),$_(n.filePath,$))).all()}searchByName(_,$,J={}){let Q=J.limit??50,z=g_($);if(!z)return[];return this.db.drizzleDb.select().from(n).where(w_(p_`${n.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${z})`,$_(n.project,_),J.kind?$_(n.kind,J.kind):void 0)).orderBy(n.name).limit(Q).all()}searchByKind(_,$){return this.db.drizzleDb.select().from(n).where(w_($_(n.project,_),$_(n.kind,$))).orderBy(n.name).all()}getStats(_){let $=this.db.drizzleDb.select({symbolCount:n1(),fileCount:p_`COUNT(DISTINCT ${n.filePath})`}).from(n).where($_(n.project,_)).get();return{symbolCount:$?.symbolCount??0,fileCount:$?.fileCount??0}}getByFingerprint(_,$){return this.db.drizzleDb.select().from(n).where(w_($_(n.project,_),$_(n.fingerprint,$))).all()}deleteFileSymbols(_,$){this.db.drizzleDb.delete(n).where(w_($_(n.project,_),$_(n.filePath,$))).run()}searchByQuery(_){let $=this.db.drizzleDb.select().from(n).where(w_(_.ftsQuery?p_`${n.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${_.ftsQuery})`:void 0,_.exactName?$_(n.name,_.exactName):void 0,_.project!==void 0?$_(n.project,_.project):void 0,_.kind?$_(n.kind,_.kind):void 0,_.filePath!==void 0?$_(n.filePath,_.filePath):void 0,_.isExported!==void 0?$_(n.isExported,_.isExported?1:0):void 0,_.decorator?p_`${n.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${_.decorator})`:void 0,_.resolvedType!==void 0?$_(n.resolvedType,_.resolvedType):void 0)).orderBy(n.name);if(!_.regex)return(_.limit!==void 0?$.limit(_.limit):$).all();let J;try{J=new RegExp(_.regex)}catch{throw new V("validation",`Invalid regex pattern: ${_.regex}`)}if(_.limit===void 0)return $.all().filter((Y)=>J.test(Y.name));let Q=[];for(let z of[5,20,100]){let Y=_.limit*z,Z=$.limit(Y).all();if(Q=Z.filter((W)=>J.test(W.name)),Q.length>=_.limit||Z.length<Y)return Q.slice(0,_.limit)}return Q.slice(0,_.limit)}}import{eq as c,and as V_,isNull as i$,or as m1}from"drizzle-orm";var G_={project:G.project,type:G.type,srcFilePath:G.srcFilePath,srcSymbolName:G.srcSymbolName,dstProject:G.dstProject,dstFilePath:G.dstFilePath,dstSymbolName:G.dstSymbolName,metaJson:G.metaJson,specifier:G.specifier,isExternal:G.isExternal};class V${db;constructor(_){this.db=_}replaceFileRelations(_,$,J){this.db.transaction((Q)=>{if(Q.drizzleDb.delete(G).where(V_(c(G.project,_),c(G.srcFilePath,$))).run(),!J.length)return;for(let z of J)Q.drizzleDb.insert(G).values({project:_,type:z.type??"unknown",srcFilePath:z.srcFilePath??$,srcSymbolName:z.srcSymbolName??null,dstProject:z.dstProject??(z.dstFilePath!=null?_:null),dstFilePath:z.dstFilePath??null,dstSymbolName:z.dstSymbolName??null,metaJson:z.metaJson??null,specifier:z.specifier??null,isExternal:z.isExternal??0}).run()})}getOutgoing(_,$,J){if(J!==void 0)return this.db.drizzleDb.select(G_).from(G).where(V_(c(G.project,_),c(G.srcFilePath,$),m1(c(G.srcSymbolName,J),i$(G.srcSymbolName)))).all();return this.db.drizzleDb.select(G_).from(G).where(V_(c(G.project,_),c(G.srcFilePath,$))).all()}getIncoming(_){let{dstProject:$,dstFilePath:J}=_;return this.db.drizzleDb.select(G_).from(G).where(V_(c(G.dstProject,$),c(G.dstFilePath,J))).all()}getByType(_,$){return this.db.drizzleDb.select(G_).from(G).where(V_(c(G.project,_),c(G.type,$))).all()}deleteFileRelations(_,$){this.db.drizzleDb.delete(G).where(V_(c(G.project,_),c(G.srcFilePath,$))).run()}deleteIncomingRelations(_,$){this.db.drizzleDb.delete(G).where(V_(c(G.dstProject,_),c(G.dstFilePath,$))).run()}searchRelations(_){let $=this.db.drizzleDb.select(G_).from(G).where(V_(_.project!==void 0?c(G.project,_.project):void 0,_.srcFilePath!==void 0?c(G.srcFilePath,_.srcFilePath):void 0,_.srcSymbolName!==void 0?c(G.srcSymbolName,_.srcSymbolName):void 0,_.dstProject!==void 0?c(G.dstProject,_.dstProject):void 0,_.dstFilePath!==void 0?c(G.dstFilePath,_.dstFilePath):void 0,_.dstSymbolName!==void 0?c(G.dstSymbolName,_.dstSymbolName):void 0,_.type!==void 0?c(G.type,_.type):void 0,_.specifier!==void 0?c(G.specifier,_.specifier):void 0,_.isExternal!==void 0?c(G.isExternal,_.isExternal?1:0):void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}retargetRelations(_){let{dstProject:$,oldFile:J,oldSymbol:Q,newFile:z,newSymbol:Y,newDstProject:Z}=_,W=Q===null?V_(c(G.dstProject,$),c(G.dstFilePath,J),i$(G.dstSymbolName)):V_(c(G.dstProject,$),c(G.dstFilePath,J),c(G.dstSymbolName,Q)),X={dstFilePath:z,dstSymbolName:Y};if(Z!==void 0)X.dstProject=Z;this.db.drizzleDb.update(G).set(X).where(W).run()}}import{err as l$}from"@zipbul/result";import{subscribe as x1}from"@parcel/watcher";import U$ from"path";import d$ from"path";function Z_(_){return _.replaceAll("\\","/")}function j_(_,$){return Z_(d$.relative(_,$))}function q_(_,$){return Z_(d$.resolve(_,$))}var h1=["**/.git/**",`**/${L_}/**`,"**/dist/**","**/node_modules/**"],p1=new Set(["package.json","tsconfig.json"]);function i1(_){if(_==="update")return"change";if(_==="create")return"create";return"delete"}class H${#_;#$;#J;#z;#Q;#Y;constructor(_,$=x1,J=console){this.#$=_.projectRoot,this.#J=[...h1,..._.ignorePatterns??[]],this.#z=new Set((_.extensions??[".ts",".mts",".cts"]).map((Q)=>Q.toLowerCase())),this.#Q=$,this.#Y=J}async start(_){try{this.#_=await this.#Q(this.#$,($,J)=>{if($){this.#Y.error(new V("watcher","Callback error",{cause:$}));return}try{for(let Q of J){let z=Z_(U$.relative(this.#$,Q.path));if(z.startsWith(".."))continue;let Y=U$.basename(z),Z=U$.extname(z).toLowerCase();if(!p1.has(Y)&&!this.#z.has(Z))continue;if(z.endsWith(".d.ts"))continue;_({eventType:i1(Q.type),filePath:z})}}catch(Q){this.#Y.error(new V("watcher","Callback error",{cause:Q}))}},{ignore:this.#J})}catch($){return l$(new V("watcher","Failed to subscribe watcher",{cause:$}))}}async close(){if(!this.#_)return;try{await this.#_.unsubscribe(),this.#_=void 0}catch(_){return l$(new V("watcher","Failed to close watcher",{cause:_}))}}}import M$ from"path";import{promises as d1}from"fs";var l1=["**/node_modules/**","**/.git/**",`**/${L_}/**`,"**/dist/**"];async function i_(_){let $=[];for await(let J of d1.glob("**/package.json",{cwd:_,exclude:l1})){let Q=Z_(M$.dirname(J)),z=M$.join(_,J),Y=await Bun.file(z).json(),Z=typeof Y?.name==="string"&&Y.name.length>0?Y.name:M$.basename(Q==="."?_:Q);$.push({dir:Q,project:Z})}return $.sort((J,Q)=>Q.dir.length-J.dir.length),$}function o(_,$,J="default"){let Q=Z_(_);for(let z of $){if(z.dir===".")return z.project;if(Q===z.dir||Q.startsWith(`${z.dir}/`))return z.project}return J}import E_ from"path";var B_=new Map;async function c1(_){let $=Bun.file(_);if(!await $.exists())return null;try{let J=await $.text(),Q=Bun.JSONC.parse(J);return typeof Q==="object"&&Q!==null?Q:null}catch{return null}}function a1(_,$){if($.startsWith(".")){let J=E_.resolve(_,$);return J.endsWith(".json")?J:J+".json"}return E_.resolve(_,"node_modules",$)}async function c$(_,$=5){if($<=0)return null;let J=await c1(_);if(!J)return null;let Q=J.extends;if(typeof Q!=="string"||!Q)return J;let z=a1(E_.dirname(_),Q),Y=await c$(z,$-1);if(!Y)return J;let Z=typeof Y.compilerOptions==="object"&&Y.compilerOptions!==null?Y.compilerOptions:{},W=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:{};return{...Y,...J,compilerOptions:{...Z,...W}}}async function v_(_){if(B_.has(_))return B_.get(_)??null;let $=E_.join(_,"tsconfig.json"),J=await c$($);if(!J)return B_.set(_,null),null;let Q=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:null;if(!Q)return B_.set(_,null),null;let z=typeof Q.baseUrl==="string"?Q.baseUrl:null,Y=typeof Q.paths==="object"&&Q.paths!==null?Q.paths:null;if(!z&&!Y)return B_.set(_,null),null;let Z=z?E_.resolve(_,z):_,W=new Map;if(Y)for(let[H,O]of Object.entries(Y)){if(!Array.isArray(O))continue;let U=O.filter((K)=>typeof K==="string");W.set(H,U)}let X={baseUrl:Z,paths:W};return B_.set(_,X),X}function d_(_){if(_){B_.delete(_);return}B_.clear()}function O_(_){let $=Bun.hash.xxHash64(_);return BigInt.asUintN(64,BigInt($)).toString(16).padStart(16,"0")}import{isErr as Q0}from"@zipbul/result";import{err as s1}from"@zipbul/result";import{parseSync as r1}from"oxc-parser";function b_(_,$,J,Q=r1){try{let z={preserveParens:!1,...J},Y=Q(_,$,z);return{filePath:_,program:Y.program,errors:Y.errors,comments:Y.comments,sourceText:$,module:Y.module}}catch(z){return s1(new V("parse",`Failed to parse file: ${_}`,{cause:z}))}}import{promises as o1}from"fs";import{join as t1}from"path";async function a$(_){let{projectRoot:$,extensions:J,ignorePatterns:Q,fileRepo:z}=_,Y=z.getFilesMap(),Z=new Set,W=[],X=[],H=Q.map((U)=>new Bun.Glob(U));for await(let U of o1.glob("**/*",{cwd:$})){let K=Z_(U);if(!J.some((P)=>K.endsWith(P)))continue;if(K.startsWith("node_modules/")||K.includes("/node_modules/"))continue;if(H.some((P)=>P.match(K)))continue;Z.add(K);let u=t1($,K),L=Bun.file(u),{size:w,lastModified:T}=L,F=Y.get(K);if(!F){let P=await L.text(),r=O_(P);W.push({filePath:K,contentHash:r,mtimeMs:T,size:w});continue}if(F.mtimeMs===T&&F.size===w){X.push({filePath:K,contentHash:F.contentHash,mtimeMs:T,size:w});continue}let m=await L.text(),j=O_(m);if(j===F.contentHash)X.push({filePath:K,contentHash:j,mtimeMs:T,size:w});else W.push({filePath:K,contentHash:j,mtimeMs:T,size:w})}let O=[];for(let U of Y.keys())if(!Z.has(U))O.push(U);return{changed:W,unchanged:X,deleted:O}}function y_(_){let $=[0];for(let J=0;J<_.length;J++)if(_[J]===`
|
|
3
|
-
`)$.push(J+1);return $}function X_(_,$){let J=0,Q=_.length-1;while(J<Q){let z=J+Q+1>>1;if(_[z]<=$)J=z;else Q=z-1}return{line:J+1,column:$-_[J]}}import{err as e1}from"@zipbul/result";import{parse as _J}from"comment-parser";function l_(_){try{let $=_.trim();if($.startsWith("/**"))$=$.slice(3);if($.endsWith("*/"))$=$.slice(0,-2);let Q=_J(`/** ${$} */`)[0]??{description:"",tags:[]};return{description:(Q.description??"").trim(),tags:(Q.tags??[]).map((z)=>({tag:z.tag??"",name:z.name??"",type:z.type??"",description:z.description??"",optional:z.optional??!1,...z.default!==void 0?{default:z.default}:{}}))}}catch($){return e1(new V("parse","Failed to parse JSDoc comment",{cause:$}))}}import{isErr as $J}from"@zipbul/result";function c_(_){if("name"in _&&typeof _.name==="string")return _.name;if("value"in _&&typeof _.value==="string")return _.value;return"unknown"}function S_(_){if(_.type==="Identifier")return[_.name];if(_.type==="ObjectPattern"){let $=[];for(let J of _.properties)if(J.type==="RestElement")$.push(...S_(J.argument));else $.push(...S_(J.value));return $}if(_.type==="ArrayPattern"){let $=[];for(let J of _.elements){if(!J)continue;if(J.type==="RestElement")$.push(...S_(J.argument));else $.push(...S_(J))}return $}if(_.type==="AssignmentPattern")return S_(_.left);return[]}function T_(_){let{program:$,sourceText:J,comments:Q}=_,z=y_(J),Y=Q.filter((B)=>B.type==="Block"&&B.value.startsWith("*")).sort((B,A)=>B.end-A.end),Z=$.body.map((B)=>B.start).sort((B,A)=>B-A);function W(B,A){return{start:X_(z,B),end:X_(z,A)}}function X(B){let A=0,D=Y.length-1,C=-1;while(A<=D){let g=A+D>>>1;if(Y[g].end<=B)C=g,A=g+1;else D=g-1}if(C<0)return;let N=Y[C];A=0,D=Z.length-1;while(A<=D){let g=A+D>>>1,R=Z[g];if(R<=N.end)A=g+1;else if(R>=B)D=g-1;else return}return`/*${N.value}*/`}function H(B){if(!B)return;let A="typeAnnotation"in B&&B.typeAnnotation?B.typeAnnotation:B;return J.slice(A.start,A.end)}function O(B){if(!B||B.length===0)return[];return B.map((A)=>{let D=A.expression;if(D.type==="CallExpression"){let C=D,N=C.callee,g="name"in N&&typeof N.name==="string"?N.name:("property"in N)&&N.property&&typeof N.property.name==="string"?N.property.name:"unknown",R=C.arguments.map((E)=>J.slice(E.start,E.end));return{name:g,arguments:R.length>0?R:void 0}}if(D.type==="Identifier")return{name:D.name??"unknown"};return{name:J.slice(D.start,D.end)}})}function U(B){if(B.type==="TSParameterProperty"){let D=B;return K(D.parameter,D.parameter.decorators)}if(B.type==="RestElement"){let D=B,C=D.argument,g=`...${"name"in C&&typeof C.name==="string"?C.name:"unknown"}`,R=D.typeAnnotation,E=R?H(R):void 0,p={name:g,isOptional:!1};if(E)p.type=E;return p}let A=B;return K(A,A.decorators)}function K(B,A){if(B.type==="AssignmentPattern"){let{left:p,right:d}=B,a="name"in p&&typeof p.name==="string"?p.name:"unknown",M="typeAnnotation"in p?p.typeAnnotation:null,q=M?H(M):void 0,S=J.slice(d.start,d.end),k="decorators"in p&&Array.isArray(p.decorators)?p.decorators:[],f=O(k),I={name:a,isOptional:!0,defaultValue:S};if(q)I.type=q;if(f.length>0)I.decorators=f;return I}let D="name"in B&&typeof B.name==="string"?B.name:("pattern"in B)&&B.pattern&&typeof B.pattern.name==="string"?B.pattern.name:"unknown",C=!!(("optional"in B)&&B.optional),N="typeAnnotation"in B?B.typeAnnotation:null,g=N?H(N):void 0,R=O(A??[]),E={name:D,isOptional:C};if(g)E.type=g;if(R.length>0)E.decorators=R;return E}function u(B,A){let D=[];if(A?.async)D.push("async");if(B.static)D.push("static");if(B.abstract)D.push("abstract");if(B.readonly)D.push("readonly");if(B.override)D.push("override");if(B.declare)D.push("declare");if(B.const)D.push("const");let C=B.accessibility;if(C==="private")D.push("private");else if(C==="protected")D.push("protected");else if(C==="public")D.push("public");return D}function L(B){if(!B)return;let A=B.params.flatMap((D)=>{let C=D.name.name;return C?[C]:[]});return A.length>0?A:void 0}function w(B){let A=[];if(B.superClass){let C=J.slice(B.superClass.start,B.superClass.end);A.push({kind:"extends",name:C})}let D=B.implements??[];for(let C of D){let N=C.expression,g=J.slice(N.start,N.end);A.push({kind:"implements",name:g})}return A}function T(B){let A=[],D=B.extends;for(let C of D){let N=C.expression,g=J.slice(N.start,N.end);A.push({kind:"extends",name:g})}return A}function F(B){let A=[];for(let D of B)if(D.type==="MethodDefinition"||D.type==="TSAbstractMethodDefinition"){let C=D,N=c_(C.key),g=C.value,R=C.kind,E=R==="constructor"?"constructor":R==="get"?"getter":R==="set"?"setter":"method",p=u(C,g);if(D.type==="TSAbstractMethodDefinition"&&!p.includes("abstract"))p.push("abstract");let d=g.params.map(U),a=H(g.returnType),M={kind:"method",name:N,span:W(D.start,D.end),isExported:!1,methodKind:E,modifiers:p,parameters:d.length>0?d:void 0,returnType:a};A.push(M)}else if(D.type==="PropertyDefinition"||D.type==="TSAbstractPropertyDefinition"){let C=D,N=c_(C.key),g=u(C);if(D.type==="TSAbstractPropertyDefinition"&&!g.includes("abstract"))g.push("abstract");let R={kind:"property",name:N,span:W(D.start,D.end),isExported:!1,modifiers:g};A.push(R)}return A}function m(B){let A=[];for(let D of B)if(D.type==="TSMethodSignature"){let C=D,N=c_(C.key),g=C.params.map(U),R=H(C.returnType);A.push({kind:"method",name:N,span:W(D.start,D.end),isExported:!1,modifiers:[],methodKind:"method",parameters:g.length>0?g:void 0,returnType:R})}else if(D.type==="TSPropertySignature"){let C=D,N=c_(C.key),g=H(C.typeAnnotation),R={kind:"property",name:N,span:W(D.start,D.end),isExported:!1,modifiers:C.readonly?["readonly"]:[],returnType:g};A.push(R)}return A}function j(B,A){let D=B.type;if(D==="FunctionDeclaration"||D==="FunctionExpression"||D==="TSDeclareFunction"||D==="TSEmptyBodyFunctionExpression"){let C=B,N=C.id?.name??"default",g=C.params.map(U),R=H(C.returnType),E=u(C,C),p=O(C.decorators??[]),d=L(C.typeParameters),a={kind:"function",name:N,span:W(B.start,B.end),isExported:A,modifiers:E,parameters:g.length>0?g:void 0,returnType:R,decorators:p.length>0?p:void 0};if(d&&d.length>0)a.typeParameters=d;return a}if(D==="ClassDeclaration"||D==="ClassExpression"){let C=B,N=C.id?.name??"default",g=w(C),R=F(C.body.body),E=O(C.decorators),p=u(C),d=L(C.typeParameters),a={kind:"class",name:N,span:W(B.start,B.end),isExported:A,modifiers:p,heritage:g.length>0?g:void 0,members:R.length>0?R:void 0,decorators:E.length>0?E:void 0};if(d&&d.length>0)a.typeParameters=d;return a}if(D==="VariableDeclaration"){let C=B,N=[];for(let g of C.declarations){let{id:R,init:E}=g;if(R.type==="ObjectPattern"||R.type==="ArrayPattern"){let S=S_(R);for(let k of S)N.push({kind:"variable",name:k,span:W(R.start,R.end),isExported:A,modifiers:[]});continue}let p="name"in R&&typeof R.name==="string"?R.name:"unknown",d="variable",a,M;if(E){if(E.type==="FunctionExpression"||E.type==="ArrowFunctionExpression"){d="function";let S=E;a=S.params.map(U),M=H(S.returnType)}}let q=[];N.push({kind:d,name:p,span:W(g.start,g.end),isExported:A,modifiers:q,parameters:a,returnType:M})}if(N.length===0)return null;if(N.length===1)return N[0];return N}if(D==="TSTypeAliasDeclaration")return{kind:"type",name:B.id.name,span:W(B.start,B.end),isExported:A,modifiers:[]};if(D==="TSInterfaceDeclaration"){let C=B,N=C.id.name,g=T(C),R=m(C.body.body),E=L(C.typeParameters),p={kind:"interface",name:N,span:W(B.start,B.end),isExported:A,modifiers:[],heritage:g.length>0?g:void 0,members:R.length>0?R:void 0};if(E&&E.length>0)p.typeParameters=E;return p}if(D==="TSEnumDeclaration"){let C=B,N=C.id.name,g=u(C),E=C.body.members.map((p)=>{let d=p.id;return{kind:"property",name:"name"in d&&typeof d.name==="string"?d.name:("value"in d)&&typeof d.value==="string"?d.value:"unknown",span:W(p.start,p.end),isExported:!1,modifiers:[]}});return{kind:"enum",name:N,span:W(B.start,B.end),isExported:A,modifiers:g,members:E.length>0?E:void 0}}if(D==="TSModuleDeclaration"){let C=B,N=C.id.name??C.id.value??"unknown",g=u(C);return{kind:"namespace",name:N,span:W(B.start,B.end),isExported:A,modifiers:g}}return null}let P=[],r=new Set;for(let B of $.body){let A=null,D=B;if(D.type==="ExportNamedDeclaration"){let N=D;if(N.declaration){if(A=j(N.declaration,!0),A&&!Array.isArray(A))A.span=W(N.start,N.end);else if(Array.isArray(A))for(let g of A)g.span=W(N.start,N.end)}else if(!N.source&&N.specifiers)for(let g of N.specifiers){let R=g.local,E="name"in R?R.name:R.value;if(E)r.add(E)}}else if(D.type==="ExportDefaultDeclaration"){let N=D,g=N.declaration;if(g){if(A=j(g,!0),A&&!Array.isArray(A))A.name="id"in g&&g.id&&typeof g.id.name==="string"?g.id.name:"default",A.isExported=!0,A.span=W(N.start,N.end);else if(!A&&"type"in g&&g.type==="Identifier"){let R=g.name;if(R)r.add(R)}}}else{let N=D.type;if(N==="FunctionDeclaration"||N==="TSDeclareFunction"||N==="ClassDeclaration"||N==="VariableDeclaration"||N==="TSTypeAliasDeclaration"||N==="TSInterfaceDeclaration"||N==="TSEnumDeclaration"||N==="TSModuleDeclaration")A=j(D,!1)}let C=Array.isArray(A)?A:A?[A]:[];for(let N of C){let g=B.start,R=X(g);if(R){let E=l_(R);if(!$J(E))N.jsDoc=E}P.push(N)}}if(r.size>0){for(let B of P)if(!B.isExported&&r.has(B.name))B.isExported=!0}return P}function JJ(_){if(_.kind==="function"||_.kind==="method"){let $=_.parameters?.length??0,J=_.modifiers.includes("async")?1:0;return`params:${$}|async:${J}`}return null}function QJ(_){let $={};if(_.jsDoc)$.jsDoc=_.jsDoc;if(_.kind==="function"||_.kind==="method"){if(_.parameters!==void 0)$.parameters=_.parameters;if(_.returnType!==void 0)$.returnType=_.returnType}if(_.heritage?.length)$.heritage=_.heritage;if(_.decorators?.length)$.decorators=_.decorators;if(_.typeParameters?.length)$.typeParameters=_.typeParameters;if(_.modifiers?.length)$.modifiers=_.modifiers;if(_.members?.length)$.members=_.members.map((J)=>{let Q=J.modifiers.find((z)=>z==="private"||z==="protected"||z==="public");return{name:J.name,kind:J.methodKind??J.kind,type:J.returnType,visibility:Q,isStatic:J.modifiers.includes("static")||void 0,isReadonly:J.modifiers.includes("readonly")||void 0}});return Object.keys($).length>0?JSON.stringify($):null}function zJ(_){let $=[_.kind];if(_.modifiers.length)$.push(`mod:${[..._.modifiers].sort().join(",")}`);if(_.typeParameters?.length)$.push(`tp:${_.typeParameters.length}`);if(_.heritage?.length){let J=[..._.heritage].sort((Q,z)=>Q.name.localeCompare(z.name)).map((Q)=>`${Q.kind}:${Q.name}`).join(",");$.push(`her:${J}`)}if(_.decorators?.length)$.push(`dec:${[..._.decorators].map((J)=>J.name).sort().join(",")}`);if(_.methodKind)$.push(`mk:${_.methodKind}`);if(_.parameters)$.push(`p:${_.parameters.length}`);if(_.returnType)$.push(`rt:${_.returnType}`);if(_.members?.length){let J=_.members.map((Q)=>`${Q.kind}:${Q.modifiers.join(",")}:${Q.parameters?.length??""}:${Q.returnType??""}`).sort().join(";");$.push(`mem:${_.members.length}:${O_(J)}`)}return O_($.join("|"))}function s$(_,$,J,Q,z){let Y=JJ(_),Z=O_(`${$}|${_.kind}|${Y??""}`),W=zJ(_);return{project:J,filePath:Q,kind:_.kind,name:$,startLine:_.span.start.line,startColumn:_.span.start.column,endLine:_.span.end.line,endColumn:_.span.end.column,isExported:_.isExported?1:0,signature:Y,fingerprint:Z,detailJson:QJ(_),contentHash:z,indexedAt:new Date().toISOString(),structuralFingerprint:W}}function K$(_){let{parsed:$,project:J,filePath:Q,contentHash:z,symbolRepo:Y}=_,Z=T_($),W=[];for(let X of Z){W.push(s$(X,X.name,J,Q,z));for(let H of X.members??[])W.push(s$(H,`${X.name}.${H.name}`,J,Q,z))}Y.replaceFileSymbols(J,Q,z,W)}import{resolve as L$,dirname as WJ,extname as YJ}from"path";function D_(_,$,J){let Q=(z)=>{let Y=YJ(z);if(Y==="")return[z+".ts",z+".d.ts",z+"/index.ts",z+"/index.d.ts",z+".mts",z+"/index.mts",z+".cts",z+"/index.cts"];if(Y===".js")return[z.slice(0,-3)+".ts"];if(Y===".mjs")return[z.slice(0,-4)+".mts"];if(Y===".cjs")return[z.slice(0,-4)+".cts"];return[z]};if($.startsWith(".")){let z=Z_(L$(WJ(_),$));return Q(z)}if(J)for(let[z,Y]of J.paths){if(Y.length===0)continue;let Z=z.indexOf("*");if(Z===-1){if($===z){let W=[];for(let X of Y)W.push(...Q(Z_(L$(J.baseUrl,X))));return W}}else{let W=z.slice(0,Z),X=z.slice(Z+1);if($.startsWith(W)&&(X===""||$.endsWith(X))){let H=$.slice(W.length,X===""?void 0:$.length-X.length),O=[];for(let U of Y)O.push(...Q(Z_(L$(J.baseUrl,U.replace("*",H)))));return O}}}return[]}function r$(_,$,J,Q=D_){let z=new Map,Y=_.body??[];for(let Z of Y){if(Z.type!=="ImportDeclaration")continue;let W=Z.source?.value??"",X=Q($,W,J);if(X.length===0)continue;let H=X[0],O=Z.specifiers??[];for(let U of O)switch(U.type){case"ImportSpecifier":z.set(U.local.name,{path:H,importedName:U.imported.name});break;case"ImportDefaultSpecifier":z.set(U.local.name,{path:H,importedName:"default"});break;case"ImportNamespaceSpecifier":z.set(U.local.name,{path:H,importedName:"*"});break}}return z}import{Visitor as ZJ}from"oxc-parser";function a_(_){return"name"in _&&typeof _.name==="string"?_.name:("value"in _)&&typeof _.value==="string"?_.value:"unknown"}function XJ(_){return!_.startsWith(".")&&!_.startsWith("/")}function u_(_,$,J,Q){let z=Q(_,$,J),Y=z.length>0?z[0]:null,Z=Y===null&&XJ($);return{resolved:Y,isExternal:Z}}function OJ(_,$,J,Q,z){for(let Y of _.staticImports){let Z=Y.moduleRequest.value,{resolved:W,isExternal:X}=u_($,Z,J,Q),H=W===null?{dstFilePath:null,specifier:Z}:{dstFilePath:W};if(Y.entries.length===0){let O={};if(X)O.isExternal=!0;if(W===null&&!X)O.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,...H,dstSymbolName:null,...Object.keys(O).length>0?{metaJson:JSON.stringify(O)}:{}});continue}for(let O of Y.entries){let U=O.isType,K={};if(U)K.isType=!0;if(X)K.isExternal=!0;if(W===null&&!X)K.isUnresolved=!0;let u,L,w=O.importName.kind;if(w==="Default")u="default",L=O.localName.value;else if(w==="NamespaceObject")u="*",L=O.localName.value,K.importKind="namespace";else u=O.importName.name??"unknown",L=O.localName.value;z.push({type:U?"type-references":"imports",srcFilePath:$,srcSymbolName:L,...H,dstSymbolName:u,...Object.keys(K).length>0?{metaJson:JSON.stringify(K)}:{}})}}}function VJ(_,$,J,Q,z){let Y=new Map;for(let Z of _.staticImports)for(let W of Z.entries)Y.set(W.localName.value,Z.moduleRequest.value);for(let Z of _.staticExports)for(let W of Z.entries){let X=null;if(W.moduleRequest)X=W.moduleRequest.value;else if(W.localName.name)X=Y.get(W.localName.name)??null;if(!X)continue;let{resolved:H,isExternal:O}=u_($,X,J,Q),U=W.exportName.name??"default",K=W.exportName.kind,u=W.localName.name??W.importName.name??U,L=W.isType,w={isReExport:!0};if(K==="None");else w.specifiers=[{local:u,exported:U}];if(L)w.isType=!0;if(O)w.isExternal=!0;if(H===null&&!O)w.isUnresolved=!0;let T=null,F=W.importName.kind;if(F==="All"||F==="AllButDefault"){if(K==="Name"&&U)T=U,w.namespaceAlias=U}z.push({type:L?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:T,metaJson:JSON.stringify(w),...H===null?{specifier:X}:{}})}}function UJ(_,$,J,Q,z){for(let Y of _.body){let Z=Y;if(Z.type==="ImportDeclaration"){let W=Z,X=W.source.value,{resolved:H,isExternal:O}=u_($,X,J,Q),U=W.importKind==="type",K=W.specifiers,u=H===null?{dstFilePath:null,specifier:X}:{dstFilePath:H};if(K.length===0){let L={};if(U)L.isType=!0;if(O)L.isExternal=!0;if(H===null&&!O)L.isUnresolved=!0;z.push({type:U?"type-references":"imports",srcFilePath:$,srcSymbolName:null,...u,dstSymbolName:null,...Object.keys(L).length>0?{metaJson:JSON.stringify(L)}:{}})}else for(let L of K){let w=L.type,T=U||w==="ImportSpecifier"&&L.importKind==="type",F={};if(T)F.isType=!0;if(O)F.isExternal=!0;if(H===null&&!O)F.isUnresolved=!0;let m,j;if(w==="ImportDefaultSpecifier")m="default",j=L.local.name;else if(w==="ImportNamespaceSpecifier")m="*",j=L.local.name,F.importKind="namespace";else m=a_(L.imported),j=L.local.name;z.push({type:T?"type-references":"imports",srcFilePath:$,srcSymbolName:j,...u,dstSymbolName:m,...Object.keys(F).length>0?{metaJson:JSON.stringify(F)}:{}})}continue}if(Z.type==="ExportAllDeclaration"){let W=Z,X=W.source.value,{resolved:H,isExternal:O}=u_($,X,J,Q),U=W.exportKind==="type",K=W.exported,u=K?a_(K):null,L={isReExport:!0};if(U)L.isType=!0;if(O)L.isExternal=!0;if(H===null&&!O)L.isUnresolved=!0;if(u)L.namespaceAlias=u;z.push({type:U?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:u,metaJson:JSON.stringify(L),...H===null?{specifier:X}:{}});continue}if(Z.type==="ExportNamedDeclaration"){let W=Z;if(!W.source)continue;let X=W.source.value,{resolved:H,isExternal:O}=u_($,X,J,Q),U=W.exportKind==="type",K=W.specifiers??[];for(let u of K){let L=U||u.exportKind==="type",w=a_(u.local),T=a_(u.exported),F={isReExport:!0,specifiers:[{local:w,exported:T}]};if(L)F.isType=!0;if(O)F.isExternal=!0;if(H===null&&!O)F.isUnresolved=!0;z.push({type:L?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:null,metaJson:JSON.stringify(F),...H===null?{specifier:X}:{}})}}}}function HJ(_,$,J,Q,z){new ZJ({ImportExpression(Z){let W=Z.source;if(W.type!=="Literal"||typeof W.value!=="string")return;let X=W.value,{resolved:H,isExternal:O}=u_($,X,J,Q),U={isDynamic:!0};if(O)U.isExternal=!0;if(H===null&&!O)U.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:null,metaJson:JSON.stringify(U),...H===null?{specifier:X}:{}})},CallExpression(Z){let W=Z.callee,X=!1;if(W.type==="Identifier"&&W.name==="require");else if(W.type==="MemberExpression"&&!W.computed){let w=W,T=w.object,F=w.property;if(T.type==="Identifier"&&T.name==="require"&&F.name==="resolve")X=!0;else return}else return;let H=Z.arguments;if(H.length===0)return;let O=H[0];if(O.type!=="Literal"||typeof O.value!=="string")return;let U=O.value,{resolved:K,isExternal:u}=u_($,U,J,Q),L={isRequire:!0};if(X)L.isRequireResolve=!0;if(u)L.isExternal=!0;if(K===null&&!u)L.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:K,dstSymbolName:null,metaJson:JSON.stringify(L),...K===null?{specifier:U}:{}})}}).visit(_)}function o$(_,$,J,Q=D_,z){let Y=[];if(z)OJ(z,$,J,Q,Y),VJ(z,$,J,Q,Y);else UJ(_,$,J,Q,Y);return HJ(_,$,J,Q,Y),Y}import{walk as MJ}from"oxc-walker";function R_(_){if(!_||typeof _!=="object"||Array.isArray(_))return null;let $=_;if($.type==="Identifier"){let J=$.name;return{root:J,parts:[],full:J}}if($.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if($.type==="Super")return{root:"super",parts:[],full:"super"};if($.type==="MemberExpression"){let J=[],Q=$;while(Q.type==="MemberExpression"){let Z=Q.property;if(!Z||typeof Z.name!=="string")return null;J.push(Z.name),Q=Q.object}let z;if(Q.type==="Identifier")z=Q.name;else if(Q.type==="ThisExpression")z="this";else if(Q.type==="Super")z="super";else return null;J.reverse();let Y=[z,...J].join(".");return{root:z,parts:J,full:Y}}return null}function t$(_,$,J){let Q=[],z=[],Y=[];function Z(){if(z.length>0)return z[z.length-1]??null;return null}function W(O){if(!O)return null;let U=J.get(O.root);if(O.parts.length===0){if(U)return{dstFilePath:U.path,dstSymbolName:U.importedName,resolution:"import"};return{dstFilePath:$,dstSymbolName:O.root,resolution:"local"}}else{if(U&&U.importedName==="*"){let K=O.parts[O.parts.length-1];return{dstFilePath:U.path,dstSymbolName:K,resolution:"namespace"}}return{dstFilePath:$,dstSymbolName:O.full,resolution:"local-member"}}}function X(O,U){let K=R_(O.callee),u=W(K);if(u){let L=Z(),w={};if(U)w.isNew=!0;if(L===null)w.scope="module";Q.push({type:"calls",srcFilePath:$,srcSymbolName:L,dstFilePath:u.dstFilePath,dstSymbolName:u.dstSymbolName,...Object.keys(w).length>0?{metaJson:JSON.stringify(w)}:{}})}}function H(O,U){if(O.type==="FunctionDeclaration"){z.push(O.id?.name??"anonymous");return}if(O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){if(U?.type==="VariableDeclarator"){let L=U.id,w=L.type==="Identifier"?L.name:"anonymous";z.push(w);return}if(U?.type==="MethodDefinition"||U?.type==="TSAbstractMethodDefinition"){let L=U.key,w=Y[Y.length-1]??"",T="name"in L?L.name:"anonymous",F=w?`${w}.${T}`:T;z.push(F);return}let K=Z(),u=K?`${K}.<anonymous>`:"<anonymous>";z.push(u)}}return MJ(_,{enter(O,U){if(O.type==="ClassDeclaration"||O.type==="ClassExpression"){Y.push(O.id?.name??"AnonymousClass");return}if(O.type==="FunctionDeclaration"||O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){H(O,U);return}if(O.type==="CallExpression"){X(O,!1);return}if(O.type==="NewExpression"){X(O,!0);return}},leave(O){if(O.type==="ClassDeclaration"||O.type==="ClassExpression"){Y.pop();return}if(O.type==="FunctionDeclaration"||O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){z.pop();return}}}),Q}import{Visitor as KJ}from"oxc-parser";function e$(_,$,J){let Q=[];function z(Z){let W=Z.id?.name??"AnonymousClass";if(Z.superClass){let H=R_(Z.superClass);if(H){let O=B$(H,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:W,...O})}}let X=Z.implements??[];for(let H of X){let O=R_(H.expression);if(!O)continue;let U=B$(O,$,J);Q.push({type:"implements",srcFilePath:$,srcSymbolName:W,...U})}}return new KJ({TSInterfaceDeclaration(Z){let W=Z.id.name??"AnonymousInterface",X=Z.extends;for(let H of X){let O=R_(H.expression);if(!O)continue;let U=B$(O,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:W,...U})}},ClassDeclaration(Z){z(Z)},ClassExpression(Z){z(Z)}}).visit(_),Q}function B$(_,$,J){let Q=J.get(_.root);if(Q){if(Q.importedName==="*"){let z=_.parts[_.parts.length-1]??_.root;return{dstFilePath:Q.path,dstSymbolName:z,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:Q.path,dstSymbolName:_.parts.length>0?_.full:Q.importedName}}return{dstFilePath:$,dstSymbolName:_.full,metaJson:JSON.stringify({isLocal:!0})}}function s_(_,$,J,Q=D_,z){let Y=r$(_,$,J,Q),Z=o$(_,$,J,Q,z),W=t$(_,$,Y),X=e$(_,$,Y);return[...Z,...W,...X]}function w$(_){let{ast:$,project:J,filePath:Q,relationRepo:z,projectRoot:Y,tsconfigPaths:Z,knownFiles:W,boundaries:X,module:H}=_,O=q_(Y,Q),K=s_($,O,Z,W?(L,w,T)=>{let F=D_(L,w,T);for(let m of F){let j=j_(Y,m);if(X){let P=o(j,X);if(W.has(`${P}::${j}`))return[m]}else if(W.has(`${J}::${j}`))return[m]}return[]}:void 0,H),u=[];for(let L of K){if(L.dstFilePath===null){let m=j_(Y,L.srcFilePath),j;if(L.metaJson)try{j=JSON.parse(L.metaJson)}catch{}let P=j?.isExternal===!0;u.push({project:J,type:L.type,srcFilePath:m,srcSymbolName:L.srcSymbolName??null,dstProject:null,dstFilePath:null,dstSymbolName:L.dstSymbolName??null,metaJson:L.metaJson??null,specifier:L.specifier??null,isExternal:P?1:0});continue}let w=j_(Y,L.dstFilePath);if(w.startsWith(".."))continue;let T=j_(Y,L.srcFilePath),F=X?o(w,X):J;u.push({project:J,type:L.type,srcFilePath:T,srcSymbolName:L.srcSymbolName??null,dstProject:F,dstFilePath:w,dstSymbolName:L.dstSymbolName??null,metaJson:L.metaJson??null,specifier:L.specifier??null,isExternal:0})}return z.replaceFileRelations(J,Q,u),u.length}import{isErr as LJ}from"@zipbul/result";var _0=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function BJ(_){let $=T_(_),J=[];for(let Q of $){J.push({name:Q.name,startLine:Q.span.start.line});for(let z of Q.members??[])J.push({name:`${Q.name}.${z.name}`,startLine:z.span.start.line})}return J.sort((Q,z)=>Q.startLine-z.startLine),J}function D$(_,$,J){let Q=0,z=_.length-1;while(Q<=z){let Y=Q+z>>1;if(_[Y].startLine<=$)Q=Y+1;else z=Y-1}if(Q<_.length){let Y=_[Q];if(Y.startLine-$<=J)return Y.name}return null}function r_(_,$,J){let Q=X_(_,$),z=X_(_,J);return{start:Q,end:z}}function $0(_){let{comments:$,sourceText:J}=_;if(!$.length)return[];let Q=y_(J),z=BJ(_),Y=[],Z=[...$].sort((X,H)=>X.start-H.start),W=null;for(let X of Z)if(X.type==="Block"&&X.value.startsWith("*")){W=null;let H=`/*${X.value}*/`,O=l_(H);if(LJ(O))continue;let U=O;if(!U.tags?.length)continue;let K=X_(Q,X.end),u=D$(z,K.line,3),L=J.slice(X.start,X.end);for(let w of U.tags){let T=[w.name,w.description].filter(Boolean).join(" "),F=`@${w.tag}`,m=L.indexOf(F),j;if(m>=0){let P=X.start+m,r=J.indexOf(`
|
|
2
|
+
var g1=Object.defineProperty;var q1=(_)=>_;function S1(_,$){this[_]=q1.bind(null,$)}var T1=(_,$)=>{for(var J in $)g1(_,J,{get:$[J],enumerable:!0,configurable:!0,set:S1.bind($,J)})};var P$=import.meta.require;import{isErr as n_}from"@zipbul/result";import m_ from"path";import{existsSync as cJ}from"fs";import{err as f$,isErr as E1}from"@zipbul/result";import{Database as v1}from"bun:sqlite";import{mkdirSync as b1,unlinkSync as n$,existsSync as m$}from"fs";import{dirname as y1,join as x$}from"path";import{drizzle as P1}from"drizzle-orm/bun-sqlite";import{migrate as f1}from"drizzle-orm/bun-sqlite/migrator";class V extends Error{type;constructor(_,$,J){super($,J);this.type=_;this.name="GildashError"}}var L_=".gildash",h_="gildash.db";var Y$={};T1(Y$,{watcherOwner:()=>j1,symbols:()=>n,symbolChangelog:()=>Q_,relations:()=>G,files:()=>__,annotations:()=>Z_});import{sql as R1}from"drizzle-orm";import{sqliteTable as A_,text as b,integer as e,real as k1,index as z_,primaryKey as F1,foreignKey as W$,check as G1}from"drizzle-orm/sqlite-core";var __=A_("files",{project:b("project").notNull(),filePath:b("file_path").notNull(),mtimeMs:k1("mtime_ms").notNull(),size:e("size").notNull(),contentHash:b("content_hash").notNull(),updatedAt:b("updated_at").notNull(),lineCount:e("line_count")},(_)=>[F1({columns:[_.project,_.filePath]})]),n=A_("symbols",{id:e("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),filePath:b("file_path").notNull(),kind:b("kind").notNull(),name:b("name").notNull(),startLine:e("start_line").notNull(),startColumn:e("start_column").notNull(),endLine:e("end_line").notNull(),endColumn:e("end_column").notNull(),isExported:e("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"),structuralFingerprint:b("structural_fingerprint")},(_)=>[z_("idx_symbols_project_file").on(_.project,_.filePath),z_("idx_symbols_project_kind").on(_.project,_.kind),z_("idx_symbols_project_name").on(_.project,_.name),z_("idx_symbols_fingerprint").on(_.project,_.fingerprint),W$({columns:[_.project,_.filePath],foreignColumns:[__.project,__.filePath]}).onDelete("cascade")]),G=A_("relations",{id:e("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"),dstFilePath:b("dst_file_path"),dstSymbolName:b("dst_symbol_name"),metaJson:b("meta_json"),specifier:b("specifier"),isExternal:e("is_external").notNull().default(0)},(_)=>[z_("idx_relations_src").on(_.project,_.srcFilePath),z_("idx_relations_dst").on(_.dstProject,_.dstFilePath),z_("idx_relations_type").on(_.project,_.type),z_("idx_relations_project_type_src").on(_.project,_.type,_.srcFilePath),z_("idx_relations_specifier").on(_.project,_.specifier),W$({columns:[_.project,_.srcFilePath],foreignColumns:[__.project,__.filePath]}).onDelete("cascade")]),Z_=A_("annotations",{id:e("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),filePath:b("file_path").notNull(),tag:b("tag").notNull(),value:b("value").notNull().default(""),source:b("source").notNull(),symbolName:b("symbol_name"),startLine:e("start_line").notNull(),startColumn:e("start_column").notNull(),endLine:e("end_line").notNull(),endColumn:e("end_column").notNull(),indexedAt:b("indexed_at").notNull()},(_)=>[z_("idx_annotations_project_file").on(_.project,_.filePath),z_("idx_annotations_project_tag").on(_.project,_.tag),z_("idx_annotations_project_symbol").on(_.project,_.symbolName),W$({columns:[_.project,_.filePath],foreignColumns:[__.project,__.filePath]}).onDelete("cascade")]),Q_=A_("symbol_changelog",{id:e("id").primaryKey({autoIncrement:!0}),project:b("project").notNull(),changeType:b("change_type").notNull(),symbolName:b("symbol_name").notNull(),symbolKind:b("symbol_kind").notNull(),filePath:b("file_path").notNull(),oldName:b("old_name"),oldFilePath:b("old_file_path"),fingerprint:b("fingerprint"),changedAt:b("changed_at").notNull(),isFullIndex:e("is_full_index").notNull().default(0),indexRunId:b("index_run_id").notNull()},(_)=>[z_("idx_changelog_project_changed_at").on(_.project,_.changedAt),z_("idx_changelog_project_name").on(_.project,_.symbolName),z_("idx_changelog_project_run").on(_.project,_.indexRunId)]),j1=A_("watcher_owner",{id:e("id").primaryKey(),pid:e("pid").notNull(),startedAt:b("started_at").notNull(),heartbeatAt:b("heartbeat_at").notNull(),instanceId:b("instance_id")},(_)=>[G1("watcher_owner_singleton",R1`${_.id} = 1`)]);class Z${client=null;drizzle=null;dbPath;txDepth=0;constructor(_){this.dbPath=x$(_.projectRoot,L_,h_)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{b1(y1(this.dbPath),{recursive:!0}),this.client=new v1(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=P1(this.client,{schema:Y$}),f1(this.drizzle,{migrationsFolder:x$(import.meta.dirname,"migrations")});let _=this.client.prepare("PRAGMA foreign_key_check").all();if(_.length>0)throw Error(`FK integrity violation after migration: ${JSON.stringify(_.slice(0,5))}`);this.client.run("PRAGMA foreign_keys = ON"),this.registerRegexpUdf(this.client)}catch(_){if(this.isCorruptionError(_)&&m$(this.dbPath)){this.closeClient(),n$(this.dbPath);for(let J of["-wal","-shm"]){let Q=this.dbPath+J;if(m$(Q))n$(Q)}let $=this.open();if(E1($))return f$(new V("store",`Failed to recover database at ${this.dbPath}`,{cause:$.data}));return $}return f$(new V("store",`Failed to open database at ${this.dbPath}`,{cause:_}))}}close(){this.closeClient(),this.drizzle=null}transaction(_){let $=this.requireClient();if(this.txDepth===0){this.txDepth++;try{return $.transaction(()=>_(this))()}finally{this.txDepth--}}let J=`sp_${this.txDepth++}`;$.run(`SAVEPOINT "${J}"`);try{let Q=_(this);return $.run(`RELEASE SAVEPOINT "${J}"`),Q}catch(Q){throw $.run(`ROLLBACK TO SAVEPOINT "${J}"`),$.run(`RELEASE SAVEPOINT "${J}"`),Q}finally{this.txDepth--}}immediateTransaction(_){let $=this.requireClient();this.txDepth++,$.run("BEGIN IMMEDIATE");try{let J=_();return $.run("COMMIT"),J}catch(J){throw $.run("ROLLBACK"),J}finally{this.txDepth--}}getTableNames(){return this.requireClient().query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(($)=>$.name)}selectOwner(){return this.requireClient().prepare("SELECT pid, heartbeat_at, instance_id FROM watcher_owner WHERE id = 1").get()??void 0}insertOwner(_,$){let J=new Date().toISOString();this.requireClient().prepare("INSERT INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(_,J,J,$??null)}replaceOwner(_,$){let J=new Date().toISOString();this.requireClient().prepare("INSERT OR REPLACE INTO watcher_owner (id, pid, started_at, heartbeat_at, instance_id) VALUES (1, ?, ?, ?, ?)").run(_,J,J,$??null)}touchOwner(_){let $=new Date().toISOString();this.requireClient().prepare("UPDATE watcher_owner SET heartbeat_at = ? WHERE id = 1 AND pid = ?").run($,_)}deleteOwner(_){this.requireClient().prepare("DELETE FROM watcher_owner WHERE id = 1 AND pid = ?").run(_)}registerRegexpUdf(_){let $=_;if(typeof $.function!=="function")return;$.function.call(_,"regexp",(J,Q)=>{try{return new RegExp(J).test(Q)?1:0}catch{return 0}})}requireClient(){if(!this.client)throw Error("Database is not open. Call open() first.");return this.client}closeClient(){if(this.client)this.client.close(),this.client=null}isCorruptionError(_){if(!(_ instanceof Error))return!1;let $=_.message.toLowerCase();return $.includes("malformed")||$.includes("corrupt")||$.includes("not a database")||$.includes("disk i/o error")||$.includes("sqlite_corrupt")}}import{eq as F_,and as h$}from"drizzle-orm";class X${db;constructor(_){this.db=_}getFile(_,$){return this.db.drizzleDb.select().from(__).where(h$(F_(__.project,_),F_(__.filePath,$))).get()??null}upsertFile(_){this.db.drizzleDb.insert(__).values({project:_.project,filePath:_.filePath,mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}).onConflictDoUpdate({target:[__.project,__.filePath],set:{mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}}).run()}getAllFiles(_){return this.db.drizzleDb.select().from(__).where(F_(__.project,_)).all()}getFilesMap(_){let $=this.getAllFiles(_),J=new Map;for(let Q of $)J.set(Q.filePath,Q);return J}deleteFile(_,$){this.db.drizzleDb.delete(__).where(h$(F_(__.project,_),F_(__.filePath,$))).run()}}import{eq as $_,and as w_,sql as p_,count as n1}from"drizzle-orm";function g_(_){return _.replaceAll("\x00","").trim().split(/\s+/).map(($)=>$.trim()).filter(($)=>$.length>0).map(($)=>`"${$.replaceAll('"','""')}"*`).join(" ")}var p$=50;class O${db;constructor(_){this.db=_}replaceFileSymbols(_,$,J,Q){if(this.db.drizzleDb.delete(n).where(w_($_(n.project,_),$_(n.filePath,$))).run(),!Q.length)return;let z=new Date().toISOString(),Y=Q.map((Z)=>({project:_,filePath:$,kind:Z.kind??"unknown",name:Z.name??"",startLine:Z.startLine??0,startColumn:Z.startColumn??0,endLine:Z.endLine??0,endColumn:Z.endColumn??0,isExported:Z.isExported??0,signature:Z.signature??null,fingerprint:Z.fingerprint??null,detailJson:Z.detailJson??null,contentHash:J,indexedAt:Z.indexedAt??z,resolvedType:Z.resolvedType??null,structuralFingerprint:Z.structuralFingerprint??null}));for(let Z=0;Z<Y.length;Z+=p$)this.db.drizzleDb.insert(n).values(Y.slice(Z,Z+p$)).run()}getFileSymbols(_,$){return this.db.drizzleDb.select().from(n).where(w_($_(n.project,_),$_(n.filePath,$))).all()}searchByName(_,$,J={}){let Q=J.limit??50,z=g_($);if(!z)return[];return this.db.drizzleDb.select().from(n).where(w_(p_`${n.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${z})`,$_(n.project,_),J.kind?$_(n.kind,J.kind):void 0)).orderBy(n.name).limit(Q).all()}searchByKind(_,$){return this.db.drizzleDb.select().from(n).where(w_($_(n.project,_),$_(n.kind,$))).orderBy(n.name).all()}getStats(_){let $=this.db.drizzleDb.select({symbolCount:n1(),fileCount:p_`COUNT(DISTINCT ${n.filePath})`}).from(n).where($_(n.project,_)).get();return{symbolCount:$?.symbolCount??0,fileCount:$?.fileCount??0}}getByFingerprint(_,$){return this.db.drizzleDb.select().from(n).where(w_($_(n.project,_),$_(n.fingerprint,$))).all()}deleteFileSymbols(_,$){this.db.drizzleDb.delete(n).where(w_($_(n.project,_),$_(n.filePath,$))).run()}searchByQuery(_){let $=this.db.drizzleDb.select().from(n).where(w_(_.ftsQuery?p_`${n.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${_.ftsQuery})`:void 0,_.exactName?$_(n.name,_.exactName):void 0,_.project!==void 0?$_(n.project,_.project):void 0,_.kind?$_(n.kind,_.kind):void 0,_.filePath!==void 0?$_(n.filePath,_.filePath):void 0,_.isExported!==void 0?$_(n.isExported,_.isExported?1:0):void 0,_.decorator?p_`${n.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${_.decorator})`:void 0,_.resolvedType!==void 0?$_(n.resolvedType,_.resolvedType):void 0)).orderBy(n.name);if(!_.regex)return(_.limit!==void 0?$.limit(_.limit):$).all();let J;try{J=new RegExp(_.regex)}catch{throw new V("validation",`Invalid regex pattern: ${_.regex}`)}if(_.limit===void 0)return $.all().filter((Y)=>J.test(Y.name));let Q=[];for(let z of[5,20,100]){let Y=_.limit*z,Z=$.limit(Y).all();if(Q=Z.filter((W)=>J.test(W.name)),Q.length>=_.limit||Z.length<Y)return Q.slice(0,_.limit)}return Q.slice(0,_.limit)}}import{eq as c,and as V_,isNull as i$,or as m1}from"drizzle-orm";var G_={project:G.project,type:G.type,srcFilePath:G.srcFilePath,srcSymbolName:G.srcSymbolName,dstProject:G.dstProject,dstFilePath:G.dstFilePath,dstSymbolName:G.dstSymbolName,metaJson:G.metaJson,specifier:G.specifier,isExternal:G.isExternal};class V${db;constructor(_){this.db=_}replaceFileRelations(_,$,J){this.db.transaction((Q)=>{if(Q.drizzleDb.delete(G).where(V_(c(G.project,_),c(G.srcFilePath,$))).run(),!J.length)return;for(let z of J)Q.drizzleDb.insert(G).values({project:_,type:z.type??"unknown",srcFilePath:z.srcFilePath??$,srcSymbolName:z.srcSymbolName??null,dstProject:z.dstProject??(z.dstFilePath!=null?_:null),dstFilePath:z.dstFilePath??null,dstSymbolName:z.dstSymbolName??null,metaJson:z.metaJson??null,specifier:z.specifier??null,isExternal:z.isExternal??0}).run()})}getOutgoing(_,$,J){if(J!==void 0)return this.db.drizzleDb.select(G_).from(G).where(V_(c(G.project,_),c(G.srcFilePath,$),m1(c(G.srcSymbolName,J),i$(G.srcSymbolName)))).all();return this.db.drizzleDb.select(G_).from(G).where(V_(c(G.project,_),c(G.srcFilePath,$))).all()}getIncoming(_){let{dstProject:$,dstFilePath:J}=_;return this.db.drizzleDb.select(G_).from(G).where(V_(c(G.dstProject,$),c(G.dstFilePath,J))).all()}getByType(_,$){return this.db.drizzleDb.select(G_).from(G).where(V_(c(G.project,_),c(G.type,$))).all()}deleteFileRelations(_,$){this.db.drizzleDb.delete(G).where(V_(c(G.project,_),c(G.srcFilePath,$))).run()}deleteIncomingRelations(_,$){this.db.drizzleDb.delete(G).where(V_(c(G.dstProject,_),c(G.dstFilePath,$))).run()}searchRelations(_){let $=this.db.drizzleDb.select(G_).from(G).where(V_(_.project!==void 0?c(G.project,_.project):void 0,_.srcFilePath!==void 0?c(G.srcFilePath,_.srcFilePath):void 0,_.srcSymbolName!==void 0?c(G.srcSymbolName,_.srcSymbolName):void 0,_.dstProject!==void 0?c(G.dstProject,_.dstProject):void 0,_.dstFilePath!==void 0?c(G.dstFilePath,_.dstFilePath):void 0,_.dstSymbolName!==void 0?c(G.dstSymbolName,_.dstSymbolName):void 0,_.type!==void 0?c(G.type,_.type):void 0,_.specifier!==void 0?c(G.specifier,_.specifier):void 0,_.isExternal!==void 0?c(G.isExternal,_.isExternal?1:0):void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}retargetRelations(_){let{dstProject:$,oldFile:J,oldSymbol:Q,newFile:z,newSymbol:Y,newDstProject:Z}=_,W=Q===null?V_(c(G.dstProject,$),c(G.dstFilePath,J),i$(G.dstSymbolName)):V_(c(G.dstProject,$),c(G.dstFilePath,J),c(G.dstSymbolName,Q)),X={dstFilePath:z,dstSymbolName:Y};if(Z!==void 0)X.dstProject=Z;this.db.drizzleDb.update(G).set(X).where(W).run()}}import{err as l$}from"@zipbul/result";import{subscribe as x1}from"@parcel/watcher";import U$ from"path";import d$ from"path";function W_(_){return _.replaceAll("\\","/")}function j_(_,$){return W_(d$.relative(_,$))}function q_(_,$){return W_(d$.resolve(_,$))}var h1=["**/.git/**",`**/${L_}/**`,"**/dist/**","**/node_modules/**"],p1=new Set(["package.json","tsconfig.json"]);function i1(_){if(_==="update")return"change";if(_==="create")return"create";return"delete"}class H${#_;#$;#J;#z;#Q;#Y;constructor(_,$=x1,J=console){this.#$=_.projectRoot,this.#J=[...h1,..._.ignorePatterns??[]],this.#z=new Set((_.extensions??[".ts",".mts",".cts"]).map((Q)=>Q.toLowerCase())),this.#Q=$,this.#Y=J}async start(_){try{this.#_=await this.#Q(this.#$,($,J)=>{if($){this.#Y.error(new V("watcher","Callback error",{cause:$}));return}try{for(let Q of J){let z=W_(U$.relative(this.#$,Q.path));if(z.startsWith(".."))continue;let Y=U$.basename(z),Z=U$.extname(z).toLowerCase();if(!p1.has(Y)&&!this.#z.has(Z))continue;if(z.endsWith(".d.ts"))continue;_({eventType:i1(Q.type),filePath:z})}}catch(Q){this.#Y.error(new V("watcher","Callback error",{cause:Q}))}},{ignore:this.#J})}catch($){return l$(new V("watcher","Failed to subscribe watcher",{cause:$}))}}async close(){if(!this.#_)return;try{await this.#_.unsubscribe(),this.#_=void 0}catch(_){return l$(new V("watcher","Failed to close watcher",{cause:_}))}}}import M$ from"path";import{promises as d1}from"fs";var l1=["**/node_modules/**","**/.git/**",`**/${L_}/**`,"**/dist/**"];async function i_(_){let $=[];for await(let J of d1.glob("**/package.json",{cwd:_,exclude:l1})){let Q=W_(M$.dirname(J)),z=M$.join(_,J),Y=await Bun.file(z).json(),Z=typeof Y?.name==="string"&&Y.name.length>0?Y.name:M$.basename(Q==="."?_:Q);$.push({dir:Q,project:Z})}return $.sort((J,Q)=>Q.dir.length-J.dir.length),$}function o(_,$,J="default"){let Q=W_(_);for(let z of $){if(z.dir===".")return z.project;if(Q===z.dir||Q.startsWith(`${z.dir}/`))return z.project}return J}import E_ from"path";var B_=new Map;async function c1(_){let $=Bun.file(_);if(!await $.exists())return null;try{let J=await $.text(),Q=Bun.JSONC.parse(J);return typeof Q==="object"&&Q!==null?Q:null}catch{return null}}function a1(_,$){if($.startsWith(".")){let J=E_.resolve(_,$);return J.endsWith(".json")?J:J+".json"}return E_.resolve(_,"node_modules",$)}async function c$(_,$=5){if($<=0)return null;let J=await c1(_);if(!J)return null;let Q=J.extends;if(typeof Q!=="string"||!Q)return J;let z=a1(E_.dirname(_),Q),Y=await c$(z,$-1);if(!Y)return J;let Z=typeof Y.compilerOptions==="object"&&Y.compilerOptions!==null?Y.compilerOptions:{},W=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:{};return{...Y,...J,compilerOptions:{...Z,...W}}}async function v_(_){if(B_.has(_))return B_.get(_)??null;let $=E_.join(_,"tsconfig.json"),J=await c$($);if(!J)return B_.set(_,null),null;let Q=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:null;if(!Q)return B_.set(_,null),null;let z=typeof Q.baseUrl==="string"?Q.baseUrl:null,Y=typeof Q.paths==="object"&&Q.paths!==null?Q.paths:null;if(!z&&!Y)return B_.set(_,null),null;let Z=z?E_.resolve(_,z):_,W=new Map;if(Y)for(let[H,O]of Object.entries(Y)){if(!Array.isArray(O))continue;let U=O.filter((K)=>typeof K==="string");W.set(H,U)}let X={baseUrl:Z,paths:W};return B_.set(_,X),X}function d_(_){if(_){B_.delete(_);return}B_.clear()}function O_(_){let $=Bun.hash.xxHash64(_);return BigInt.asUintN(64,BigInt($)).toString(16).padStart(16,"0")}import{isErr as Q0}from"@zipbul/result";import{err as s1}from"@zipbul/result";import{parseSync as r1}from"oxc-parser";function b_(_,$,J,Q=r1){try{let z={preserveParens:!1,...J},Y=Q(_,$,z);return{filePath:_,program:Y.program,errors:Y.errors,comments:Y.comments,sourceText:$,module:Y.module}}catch(z){return s1(new V("parse",`Failed to parse file: ${_}`,{cause:z}))}}import{promises as o1}from"fs";import{join as t1}from"path";async function a$(_){let{projectRoot:$,extensions:J,ignorePatterns:Q,fileRepo:z}=_,Y=z.getFilesMap(),Z=new Set,W=[],X=[],H=Q.map((U)=>new Bun.Glob(U));for await(let U of o1.glob("**/*",{cwd:$})){let K=W_(U);if(!J.some((P)=>K.endsWith(P)))continue;if(K.startsWith("node_modules/")||K.includes("/node_modules/"))continue;if(H.some((P)=>P.match(K)))continue;Z.add(K);let u=t1($,K),L=Bun.file(u),{size:w,lastModified:T}=L,F=Y.get(K);if(!F){let P=await L.text(),r=O_(P);W.push({filePath:K,contentHash:r,mtimeMs:T,size:w});continue}if(F.mtimeMs===T&&F.size===w){X.push({filePath:K,contentHash:F.contentHash,mtimeMs:T,size:w});continue}let m=await L.text(),j=O_(m);if(j===F.contentHash)X.push({filePath:K,contentHash:j,mtimeMs:T,size:w});else W.push({filePath:K,contentHash:j,mtimeMs:T,size:w})}let O=[];for(let U of Y.keys())if(!Z.has(U))O.push(U);return{changed:W,unchanged:X,deleted:O}}function y_(_){let $=[0];for(let J=0;J<_.length;J++)if(_[J]===`
|
|
3
|
+
`)$.push(J+1);return $}function X_(_,$){let J=0,Q=_.length-1;while(J<Q){let z=J+Q+1>>1;if(_[z]<=$)J=z;else Q=z-1}return{line:J+1,column:$-_[J]}}import{err as e1}from"@zipbul/result";import{parse as _J}from"comment-parser";function l_(_){try{let $=_.trim();if($.startsWith("/**"))$=$.slice(3);if($.endsWith("*/"))$=$.slice(0,-2);let Q=_J(`/** ${$} */`)[0]??{description:"",tags:[]};return{description:(Q.description??"").trim(),tags:(Q.tags??[]).map((z)=>({tag:z.tag??"",name:z.name??"",type:z.type??"",description:z.description??"",optional:z.optional??!1,...z.default!==void 0?{default:z.default}:{}}))}}catch($){return e1(new V("parse","Failed to parse JSDoc comment",{cause:$}))}}import{isErr as $J}from"@zipbul/result";function c_(_){if("name"in _&&typeof _.name==="string")return _.name;if("value"in _&&typeof _.value==="string")return _.value;return"unknown"}function S_(_){if(_.type==="Identifier")return[_.name];if(_.type==="ObjectPattern"){let $=[];for(let J of _.properties)if(J.type==="RestElement")$.push(...S_(J.argument));else $.push(...S_(J.value));return $}if(_.type==="ArrayPattern"){let $=[];for(let J of _.elements){if(!J)continue;if(J.type==="RestElement")$.push(...S_(J.argument));else $.push(...S_(J))}return $}if(_.type==="AssignmentPattern")return S_(_.left);return[]}function T_(_){let{program:$,sourceText:J,comments:Q}=_,z=y_(J),Y=Q.filter((B)=>B.type==="Block"&&B.value.startsWith("*")).sort((B,A)=>B.end-A.end),Z=$.body.map((B)=>B.start).sort((B,A)=>B-A);function W(B,A){return{start:X_(z,B),end:X_(z,A)}}function X(B){let A=0,D=Y.length-1,C=-1;while(A<=D){let g=A+D>>>1;if(Y[g].end<=B)C=g,A=g+1;else D=g-1}if(C<0)return;let N=Y[C];A=0,D=Z.length-1;while(A<=D){let g=A+D>>>1,R=Z[g];if(R<=N.end)A=g+1;else if(R>=B)D=g-1;else return}return`/*${N.value}*/`}function H(B){if(!B)return;let A="typeAnnotation"in B&&B.typeAnnotation?B.typeAnnotation:B;return J.slice(A.start,A.end)}function O(B){if(!B||B.length===0)return[];return B.map((A)=>{let D=A.expression;if(D.type==="CallExpression"){let C=D,N=C.callee,g="name"in N&&typeof N.name==="string"?N.name:("property"in N)&&N.property&&typeof N.property.name==="string"?N.property.name:"unknown",R=C.arguments.map((E)=>J.slice(E.start,E.end));return{name:g,arguments:R.length>0?R:void 0}}if(D.type==="Identifier")return{name:D.name??"unknown"};return{name:J.slice(D.start,D.end)}})}function U(B){if(B.type==="TSParameterProperty"){let D=B;return K(D.parameter,D.parameter.decorators)}if(B.type==="RestElement"){let D=B,C=D.argument,g=`...${"name"in C&&typeof C.name==="string"?C.name:"unknown"}`,R=D.typeAnnotation,E=R?H(R):void 0,p={name:g,isOptional:!1};if(E)p.type=E;return p}let A=B;return K(A,A.decorators)}function K(B,A){if(B.type==="AssignmentPattern"){let{left:p,right:d}=B,a="name"in p&&typeof p.name==="string"?p.name:"unknown",M="typeAnnotation"in p?p.typeAnnotation:null,q=M?H(M):void 0,S=J.slice(d.start,d.end),k="decorators"in p&&Array.isArray(p.decorators)?p.decorators:[],f=O(k),I={name:a,isOptional:!0,defaultValue:S};if(q)I.type=q;if(f.length>0)I.decorators=f;return I}let D="name"in B&&typeof B.name==="string"?B.name:("pattern"in B)&&B.pattern&&typeof B.pattern.name==="string"?B.pattern.name:"unknown",C=!!(("optional"in B)&&B.optional),N="typeAnnotation"in B?B.typeAnnotation:null,g=N?H(N):void 0,R=O(A??[]),E={name:D,isOptional:C};if(g)E.type=g;if(R.length>0)E.decorators=R;return E}function u(B,A){let D=[];if(A?.async)D.push("async");if(B.static)D.push("static");if(B.abstract)D.push("abstract");if(B.readonly)D.push("readonly");if(B.override)D.push("override");if(B.declare)D.push("declare");if(B.const)D.push("const");let C=B.accessibility;if(C==="private")D.push("private");else if(C==="protected")D.push("protected");else if(C==="public")D.push("public");return D}function L(B){if(!B)return;let A=B.params.flatMap((D)=>{let C=D.name.name;return C?[C]:[]});return A.length>0?A:void 0}function w(B){let A=[];if(B.superClass){let C=J.slice(B.superClass.start,B.superClass.end);A.push({kind:"extends",name:C})}let D=B.implements??[];for(let C of D){let N=C.expression,g=J.slice(N.start,N.end);A.push({kind:"implements",name:g})}return A}function T(B){let A=[],D=B.extends;for(let C of D){let N=C.expression,g=J.slice(N.start,N.end);A.push({kind:"extends",name:g})}return A}function F(B){let A=[];for(let D of B)if(D.type==="MethodDefinition"||D.type==="TSAbstractMethodDefinition"){let C=D,N=c_(C.key),g=C.value,R=C.kind,E=R==="constructor"?"constructor":R==="get"?"getter":R==="set"?"setter":"method",p=u(C,g);if(D.type==="TSAbstractMethodDefinition"&&!p.includes("abstract"))p.push("abstract");let d=g.params.map(U),a=H(g.returnType),M={kind:"method",name:N,span:W(D.start,D.end),isExported:!1,methodKind:E,modifiers:p,parameters:d.length>0?d:void 0,returnType:a};A.push(M)}else if(D.type==="PropertyDefinition"||D.type==="TSAbstractPropertyDefinition"){let C=D,N=c_(C.key),g=u(C);if(D.type==="TSAbstractPropertyDefinition"&&!g.includes("abstract"))g.push("abstract");let R={kind:"property",name:N,span:W(D.start,D.end),isExported:!1,modifiers:g};A.push(R)}return A}function m(B){let A=[];for(let D of B)if(D.type==="TSMethodSignature"){let C=D,N=c_(C.key),g=C.params.map(U),R=H(C.returnType);A.push({kind:"method",name:N,span:W(D.start,D.end),isExported:!1,modifiers:[],methodKind:"method",parameters:g.length>0?g:void 0,returnType:R})}else if(D.type==="TSPropertySignature"){let C=D,N=c_(C.key),g=H(C.typeAnnotation),R={kind:"property",name:N,span:W(D.start,D.end),isExported:!1,modifiers:C.readonly?["readonly"]:[],returnType:g};A.push(R)}return A}function j(B,A){let D=B.type;if(D==="FunctionDeclaration"||D==="FunctionExpression"||D==="TSDeclareFunction"||D==="TSEmptyBodyFunctionExpression"){let C=B,N=C.id?.name??"default",g=C.params.map(U),R=H(C.returnType),E=u(C,C),p=O(C.decorators??[]),d=L(C.typeParameters),a={kind:"function",name:N,span:W(B.start,B.end),isExported:A,modifiers:E,parameters:g.length>0?g:void 0,returnType:R,decorators:p.length>0?p:void 0};if(d&&d.length>0)a.typeParameters=d;return a}if(D==="ClassDeclaration"||D==="ClassExpression"){let C=B,N=C.id?.name??"default",g=w(C),R=F(C.body.body),E=O(C.decorators),p=u(C),d=L(C.typeParameters),a={kind:"class",name:N,span:W(B.start,B.end),isExported:A,modifiers:p,heritage:g.length>0?g:void 0,members:R.length>0?R:void 0,decorators:E.length>0?E:void 0};if(d&&d.length>0)a.typeParameters=d;return a}if(D==="VariableDeclaration"){let C=B,N=[];for(let g of C.declarations){let{id:R,init:E}=g;if(R.type==="ObjectPattern"||R.type==="ArrayPattern"){let S=S_(R);for(let k of S)N.push({kind:"variable",name:k,span:W(R.start,R.end),isExported:A,modifiers:[]});continue}let p="name"in R&&typeof R.name==="string"?R.name:"unknown",d="variable",a,M;if(E){if(E.type==="FunctionExpression"||E.type==="ArrowFunctionExpression"){d="function";let S=E;a=S.params.map(U),M=H(S.returnType)}}let q=[];N.push({kind:d,name:p,span:W(g.start,g.end),isExported:A,modifiers:q,parameters:a,returnType:M})}if(N.length===0)return null;if(N.length===1)return N[0];return N}if(D==="TSTypeAliasDeclaration")return{kind:"type",name:B.id.name,span:W(B.start,B.end),isExported:A,modifiers:[]};if(D==="TSInterfaceDeclaration"){let C=B,N=C.id.name,g=T(C),R=m(C.body.body),E=L(C.typeParameters),p={kind:"interface",name:N,span:W(B.start,B.end),isExported:A,modifiers:[],heritage:g.length>0?g:void 0,members:R.length>0?R:void 0};if(E&&E.length>0)p.typeParameters=E;return p}if(D==="TSEnumDeclaration"){let C=B,N=C.id.name,g=u(C),E=C.body.members.map((p)=>{let d=p.id;return{kind:"property",name:"name"in d&&typeof d.name==="string"?d.name:("value"in d)&&typeof d.value==="string"?d.value:"unknown",span:W(p.start,p.end),isExported:!1,modifiers:[]}});return{kind:"enum",name:N,span:W(B.start,B.end),isExported:A,modifiers:g,members:E.length>0?E:void 0}}if(D==="TSModuleDeclaration"){let C=B,N=C.id.name??C.id.value??"unknown",g=u(C);return{kind:"namespace",name:N,span:W(B.start,B.end),isExported:A,modifiers:g}}return null}let P=[],r=new Set;for(let B of $.body){let A=null,D=B;if(D.type==="ExportNamedDeclaration"){let N=D;if(N.declaration){if(A=j(N.declaration,!0),A&&!Array.isArray(A))A.span=W(N.start,N.end);else if(Array.isArray(A))for(let g of A)g.span=W(N.start,N.end)}else if(!N.source&&N.specifiers)for(let g of N.specifiers){let R=g.local,E="name"in R?R.name:R.value;if(E)r.add(E)}}else if(D.type==="ExportDefaultDeclaration"){let N=D,g=N.declaration;if(g){if(A=j(g,!0),A&&!Array.isArray(A))A.name="id"in g&&g.id&&typeof g.id.name==="string"?g.id.name:"default",A.isExported=!0,A.span=W(N.start,N.end);else if(!A&&"type"in g&&g.type==="Identifier"){let R=g.name;if(R)r.add(R)}}}else{let N=D.type;if(N==="FunctionDeclaration"||N==="TSDeclareFunction"||N==="ClassDeclaration"||N==="VariableDeclaration"||N==="TSTypeAliasDeclaration"||N==="TSInterfaceDeclaration"||N==="TSEnumDeclaration"||N==="TSModuleDeclaration")A=j(D,!1)}let C=Array.isArray(A)?A:A?[A]:[];for(let N of C){let g=B.start,R=X(g);if(R){let E=l_(R);if(!$J(E))N.jsDoc=E}P.push(N)}}if(r.size>0){for(let B of P)if(!B.isExported&&r.has(B.name))B.isExported=!0}return P}function JJ(_){if(_.kind==="function"||_.kind==="method"){let $=_.parameters?.length??0,J=_.modifiers.includes("async")?1:0;return`params:${$}|async:${J}`}return null}function QJ(_){let $={};if(_.jsDoc)$.jsDoc=_.jsDoc;if(_.kind==="function"||_.kind==="method"){if(_.parameters!==void 0)$.parameters=_.parameters;if(_.returnType!==void 0)$.returnType=_.returnType}if(_.heritage?.length)$.heritage=_.heritage;if(_.decorators?.length)$.decorators=_.decorators;if(_.typeParameters?.length)$.typeParameters=_.typeParameters;if(_.modifiers?.length)$.modifiers=_.modifiers;if(_.members?.length)$.members=_.members.map((J)=>{let Q=J.modifiers.find((z)=>z==="private"||z==="protected"||z==="public");return{name:J.name,kind:J.methodKind??J.kind,type:J.returnType,visibility:Q,isStatic:J.modifiers.includes("static")||void 0,isReadonly:J.modifiers.includes("readonly")||void 0}});return Object.keys($).length>0?JSON.stringify($):null}function zJ(_){let $=[_.kind];if(_.modifiers.length)$.push(`mod:${[..._.modifiers].sort().join(",")}`);if(_.typeParameters?.length)$.push(`tp:${_.typeParameters.length}`);if(_.heritage?.length){let J=[..._.heritage].sort((Q,z)=>Q.name.localeCompare(z.name)).map((Q)=>`${Q.kind}:${Q.name}`).join(",");$.push(`her:${J}`)}if(_.decorators?.length)$.push(`dec:${[..._.decorators].map((J)=>J.name).sort().join(",")}`);if(_.methodKind)$.push(`mk:${_.methodKind}`);if(_.parameters)$.push(`p:${_.parameters.length}`);if(_.returnType)$.push(`rt:${_.returnType}`);if(_.members?.length){let J=_.members.map((Q)=>`${Q.kind}:${Q.modifiers.join(",")}:${Q.parameters?.length??""}:${Q.returnType??""}`).sort().join(";");$.push(`mem:${_.members.length}:${O_(J)}`)}return O_($.join("|"))}function s$(_,$,J,Q,z){let Y=JJ(_),Z=O_(`${$}|${_.kind}|${Y??""}`),W=zJ(_);return{project:J,filePath:Q,kind:_.kind,name:$,startLine:_.span.start.line,startColumn:_.span.start.column,endLine:_.span.end.line,endColumn:_.span.end.column,isExported:_.isExported?1:0,signature:Y,fingerprint:Z,detailJson:QJ(_),contentHash:z,indexedAt:new Date().toISOString(),structuralFingerprint:W}}function K$(_){let{parsed:$,project:J,filePath:Q,contentHash:z,symbolRepo:Y}=_,Z=T_($),W=[];for(let X of Z){W.push(s$(X,X.name,J,Q,z));for(let H of X.members??[])W.push(s$(H,`${X.name}.${H.name}`,J,Q,z))}Y.replaceFileSymbols(J,Q,z,W)}import{resolve as L$,dirname as WJ,extname as YJ}from"path";function D_(_,$,J){let Q=(z)=>{let Y=YJ(z);if(Y==="")return[z+".ts",z+".d.ts",z+"/index.ts",z+"/index.d.ts",z+".mts",z+"/index.mts",z+".cts",z+"/index.cts"];if(Y===".js")return[z.slice(0,-3)+".ts"];if(Y===".mjs")return[z.slice(0,-4)+".mts"];if(Y===".cjs")return[z.slice(0,-4)+".cts"];return[z]};if($.startsWith(".")){let z=W_(L$(WJ(_),$));return Q(z)}if(J)for(let[z,Y]of J.paths){if(Y.length===0)continue;let Z=z.indexOf("*");if(Z===-1){if($===z){let W=[];for(let X of Y)W.push(...Q(W_(L$(J.baseUrl,X))));return W}}else{let W=z.slice(0,Z),X=z.slice(Z+1);if($.startsWith(W)&&(X===""||$.endsWith(X))){let H=$.slice(W.length,X===""?void 0:$.length-X.length),O=[];for(let U of Y)O.push(...Q(W_(L$(J.baseUrl,U.replace("*",H)))));return O}}}return[]}function r$(_,$,J,Q=D_){let z=new Map,Y=_.body??[];for(let Z of Y){if(Z.type!=="ImportDeclaration")continue;let W=Z.source?.value??"",X=Q($,W,J);if(X.length===0)continue;let H=X[0],O=Z.specifiers??[];for(let U of O)switch(U.type){case"ImportSpecifier":z.set(U.local.name,{path:H,importedName:U.imported.name});break;case"ImportDefaultSpecifier":z.set(U.local.name,{path:H,importedName:"default"});break;case"ImportNamespaceSpecifier":z.set(U.local.name,{path:H,importedName:"*"});break}}return z}import{Visitor as ZJ}from"oxc-parser";function a_(_){return"name"in _&&typeof _.name==="string"?_.name:("value"in _)&&typeof _.value==="string"?_.value:"unknown"}function XJ(_){return!_.startsWith(".")&&!_.startsWith("/")}function u_(_,$,J,Q){let z=Q(_,$,J),Y=z.length>0?z[0]:null,Z=Y===null&&XJ($);return{resolved:Y,isExternal:Z}}function OJ(_,$,J,Q,z){for(let Y of _.staticImports){let Z=Y.moduleRequest.value,{resolved:W,isExternal:X}=u_($,Z,J,Q),H=W===null?{dstFilePath:null,specifier:Z}:{dstFilePath:W};if(Y.entries.length===0){let O={};if(X)O.isExternal=!0;if(W===null&&!X)O.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,...H,dstSymbolName:null,...Object.keys(O).length>0?{metaJson:JSON.stringify(O)}:{}});continue}for(let O of Y.entries){let U=O.isType,K={};if(U)K.isType=!0;if(X)K.isExternal=!0;if(W===null&&!X)K.isUnresolved=!0;let u,L,w=O.importName.kind;if(w==="Default")u="default",L=O.localName.value;else if(w==="NamespaceObject")u="*",L=O.localName.value,K.importKind="namespace";else u=O.importName.name??"unknown",L=O.localName.value;z.push({type:U?"type-references":"imports",srcFilePath:$,srcSymbolName:L,...H,dstSymbolName:u,...Object.keys(K).length>0?{metaJson:JSON.stringify(K)}:{}})}}}function VJ(_,$,J,Q,z){let Y=new Map;for(let Z of _.staticImports)for(let W of Z.entries)Y.set(W.localName.value,Z.moduleRequest.value);for(let Z of _.staticExports)for(let W of Z.entries){let X=null;if(W.moduleRequest)X=W.moduleRequest.value;else if(W.localName.name)X=Y.get(W.localName.name)??null;if(!X)continue;let{resolved:H,isExternal:O}=u_($,X,J,Q),U=W.exportName.name??"default",K=W.exportName.kind,u=W.localName.name??W.importName.name??U,L=W.isType,w={isReExport:!0};if(K==="None");else w.specifiers=[{local:u,exported:U}];if(L)w.isType=!0;if(O)w.isExternal=!0;if(H===null&&!O)w.isUnresolved=!0;let T=null,F=W.importName.kind;if(F==="All"||F==="AllButDefault"){if(K==="Name"&&U)T=U,w.namespaceAlias=U}z.push({type:L?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:T,metaJson:JSON.stringify(w),...H===null?{specifier:X}:{}})}}function UJ(_,$,J,Q,z){for(let Y of _.body){let Z=Y;if(Z.type==="ImportDeclaration"){let W=Z,X=W.source.value,{resolved:H,isExternal:O}=u_($,X,J,Q),U=W.importKind==="type",K=W.specifiers,u=H===null?{dstFilePath:null,specifier:X}:{dstFilePath:H};if(K.length===0){let L={};if(U)L.isType=!0;if(O)L.isExternal=!0;if(H===null&&!O)L.isUnresolved=!0;z.push({type:U?"type-references":"imports",srcFilePath:$,srcSymbolName:null,...u,dstSymbolName:null,...Object.keys(L).length>0?{metaJson:JSON.stringify(L)}:{}})}else for(let L of K){let w=L.type,T=U||w==="ImportSpecifier"&&L.importKind==="type",F={};if(T)F.isType=!0;if(O)F.isExternal=!0;if(H===null&&!O)F.isUnresolved=!0;let m,j;if(w==="ImportDefaultSpecifier")m="default",j=L.local.name;else if(w==="ImportNamespaceSpecifier")m="*",j=L.local.name,F.importKind="namespace";else m=a_(L.imported),j=L.local.name;z.push({type:T?"type-references":"imports",srcFilePath:$,srcSymbolName:j,...u,dstSymbolName:m,...Object.keys(F).length>0?{metaJson:JSON.stringify(F)}:{}})}continue}if(Z.type==="ExportAllDeclaration"){let W=Z,X=W.source.value,{resolved:H,isExternal:O}=u_($,X,J,Q),U=W.exportKind==="type",K=W.exported,u=K?a_(K):null,L={isReExport:!0};if(U)L.isType=!0;if(O)L.isExternal=!0;if(H===null&&!O)L.isUnresolved=!0;if(u)L.namespaceAlias=u;z.push({type:U?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:u,metaJson:JSON.stringify(L),...H===null?{specifier:X}:{}});continue}if(Z.type==="ExportNamedDeclaration"){let W=Z;if(!W.source)continue;let X=W.source.value,{resolved:H,isExternal:O}=u_($,X,J,Q),U=W.exportKind==="type",K=W.specifiers??[];for(let u of K){let L=U||u.exportKind==="type",w=a_(u.local),T=a_(u.exported),F={isReExport:!0,specifiers:[{local:w,exported:T}]};if(L)F.isType=!0;if(O)F.isExternal=!0;if(H===null&&!O)F.isUnresolved=!0;z.push({type:L?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:null,metaJson:JSON.stringify(F),...H===null?{specifier:X}:{}})}}}}function HJ(_,$,J,Q,z){new ZJ({ImportExpression(Z){let W=Z.source;if(W.type!=="Literal"||typeof W.value!=="string")return;let X=W.value,{resolved:H,isExternal:O}=u_($,X,J,Q),U={isDynamic:!0};if(O)U.isExternal=!0;if(H===null&&!O)U.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:null,metaJson:JSON.stringify(U),...H===null?{specifier:X}:{}})},CallExpression(Z){let W=Z.callee,X=!1;if(W.type==="Identifier"&&W.name==="require");else if(W.type==="MemberExpression"&&!W.computed){let w=W,T=w.object,F=w.property;if(T.type==="Identifier"&&T.name==="require"&&F.name==="resolve")X=!0;else return}else return;let H=Z.arguments;if(H.length===0)return;let O=H[0];if(O.type!=="Literal"||typeof O.value!=="string")return;let U=O.value,{resolved:K,isExternal:u}=u_($,U,J,Q),L={isRequire:!0};if(X)L.isRequireResolve=!0;if(u)L.isExternal=!0;if(K===null&&!u)L.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:K,dstSymbolName:null,metaJson:JSON.stringify(L),...K===null?{specifier:U}:{}})}}).visit(_)}function o$(_,$,J,Q=D_,z){let Y=[];if(z)OJ(z,$,J,Q,Y),VJ(z,$,J,Q,Y);else UJ(_,$,J,Q,Y);return HJ(_,$,J,Q,Y),Y}import{walk as MJ}from"oxc-walker";function R_(_){if(!_||typeof _!=="object"||Array.isArray(_))return null;let $=_;if($.type==="Identifier"){let J=$.name;return{root:J,parts:[],full:J}}if($.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if($.type==="Super")return{root:"super",parts:[],full:"super"};if($.type==="MemberExpression"){let J=[],Q=$;while(Q.type==="MemberExpression"){let Z=Q.property;if(!Z||typeof Z.name!=="string")return null;J.push(Z.name),Q=Q.object}let z;if(Q.type==="Identifier")z=Q.name;else if(Q.type==="ThisExpression")z="this";else if(Q.type==="Super")z="super";else return null;J.reverse();let Y=[z,...J].join(".");return{root:z,parts:J,full:Y}}return null}function t$(_,$,J){let Q=[],z=[],Y=[];function Z(){if(z.length>0)return z[z.length-1]??null;return null}function W(O){if(!O)return null;let U=J.get(O.root);if(O.parts.length===0){if(U)return{dstFilePath:U.path,dstSymbolName:U.importedName,resolution:"import"};return{dstFilePath:$,dstSymbolName:O.root,resolution:"local"}}else{if(U&&U.importedName==="*"){let K=O.parts[O.parts.length-1];return{dstFilePath:U.path,dstSymbolName:K,resolution:"namespace"}}return{dstFilePath:$,dstSymbolName:O.full,resolution:"local-member"}}}function X(O,U){let K=R_(O.callee),u=W(K);if(u){let L=Z(),w={};if(U)w.isNew=!0;if(L===null)w.scope="module";Q.push({type:"calls",srcFilePath:$,srcSymbolName:L,dstFilePath:u.dstFilePath,dstSymbolName:u.dstSymbolName,...Object.keys(w).length>0?{metaJson:JSON.stringify(w)}:{}})}}function H(O,U){if(O.type==="FunctionDeclaration"){z.push(O.id?.name??"anonymous");return}if(O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){if(U?.type==="VariableDeclarator"){let L=U.id,w=L.type==="Identifier"?L.name:"anonymous";z.push(w);return}if(U?.type==="MethodDefinition"||U?.type==="TSAbstractMethodDefinition"){let L=U.key,w=Y[Y.length-1]??"",T="name"in L?L.name:"anonymous",F=w?`${w}.${T}`:T;z.push(F);return}let K=Z(),u=K?`${K}.<anonymous>`:"<anonymous>";z.push(u)}}return MJ(_,{enter(O,U){if(O.type==="ClassDeclaration"||O.type==="ClassExpression"){Y.push(O.id?.name??"AnonymousClass");return}if(O.type==="FunctionDeclaration"||O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){H(O,U);return}if(O.type==="CallExpression"){X(O,!1);return}if(O.type==="NewExpression"){X(O,!0);return}},leave(O){if(O.type==="ClassDeclaration"||O.type==="ClassExpression"){Y.pop();return}if(O.type==="FunctionDeclaration"||O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){z.pop();return}}}),Q}import{Visitor as KJ}from"oxc-parser";function e$(_,$,J){let Q=[];function z(Z){let W=Z.id?.name??"AnonymousClass";if(Z.superClass){let H=R_(Z.superClass);if(H){let O=B$(H,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:W,...O})}}let X=Z.implements??[];for(let H of X){let O=R_(H.expression);if(!O)continue;let U=B$(O,$,J);Q.push({type:"implements",srcFilePath:$,srcSymbolName:W,...U})}}return new KJ({TSInterfaceDeclaration(Z){let W=Z.id.name??"AnonymousInterface",X=Z.extends;for(let H of X){let O=R_(H.expression);if(!O)continue;let U=B$(O,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:W,...U})}},ClassDeclaration(Z){z(Z)},ClassExpression(Z){z(Z)}}).visit(_),Q}function B$(_,$,J){let Q=J.get(_.root);if(Q){if(Q.importedName==="*"){let z=_.parts[_.parts.length-1]??_.root;return{dstFilePath:Q.path,dstSymbolName:z,metaJson:JSON.stringify({isNamespaceImport:!0})}}return{dstFilePath:Q.path,dstSymbolName:_.parts.length>0?_.full:Q.importedName}}return{dstFilePath:$,dstSymbolName:_.full,metaJson:JSON.stringify({isLocal:!0})}}function s_(_,$,J,Q=D_,z){let Y=r$(_,$,J,Q),Z=o$(_,$,J,Q,z),W=t$(_,$,Y),X=e$(_,$,Y);return[...Z,...W,...X]}function w$(_){let{ast:$,project:J,filePath:Q,relationRepo:z,projectRoot:Y,tsconfigPaths:Z,knownFiles:W,boundaries:X,module:H}=_,O=q_(Y,Q),K=s_($,O,Z,W?(L,w,T)=>{let F=D_(L,w,T);for(let m of F){let j=j_(Y,m);if(X){let P=o(j,X);if(W.has(`${P}::${j}`))return[m]}else if(W.has(`${J}::${j}`))return[m]}return[]}:void 0,H),u=[];for(let L of K){if(L.dstFilePath===null){let m=j_(Y,L.srcFilePath),j;if(L.metaJson)try{j=JSON.parse(L.metaJson)}catch{}let P=j?.isExternal===!0;u.push({project:J,type:L.type,srcFilePath:m,srcSymbolName:L.srcSymbolName??null,dstProject:null,dstFilePath:null,dstSymbolName:L.dstSymbolName??null,metaJson:L.metaJson??null,specifier:L.specifier??null,isExternal:P?1:0});continue}let w=j_(Y,L.dstFilePath);if(w.startsWith(".."))continue;let T=j_(Y,L.srcFilePath),F=X?o(w,X):J;u.push({project:J,type:L.type,srcFilePath:T,srcSymbolName:L.srcSymbolName??null,dstProject:F,dstFilePath:w,dstSymbolName:L.dstSymbolName??null,metaJson:L.metaJson??null,specifier:L.specifier??null,isExternal:0})}return z.replaceFileRelations(J,Q,u),u.length}import{isErr as LJ}from"@zipbul/result";var _0=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function BJ(_){let $=T_(_),J=[];for(let Q of $){J.push({name:Q.name,startLine:Q.span.start.line});for(let z of Q.members??[])J.push({name:`${Q.name}.${z.name}`,startLine:z.span.start.line})}return J.sort((Q,z)=>Q.startLine-z.startLine),J}function D$(_,$,J){let Q=0,z=_.length-1;while(Q<=z){let Y=Q+z>>1;if(_[Y].startLine<=$)Q=Y+1;else z=Y-1}if(Q<_.length){let Y=_[Q];if(Y.startLine-$<=J)return Y.name}return null}function r_(_,$,J){let Q=X_(_,$),z=X_(_,J);return{start:Q,end:z}}function $0(_){let{comments:$,sourceText:J}=_;if(!$.length)return[];let Q=y_(J),z=BJ(_),Y=[],Z=[...$].sort((X,H)=>X.start-H.start),W=null;for(let X of Z)if(X.type==="Block"&&X.value.startsWith("*")){W=null;let H=`/*${X.value}*/`,O=l_(H);if(LJ(O))continue;let U=O;if(!U.tags?.length)continue;let K=X_(Q,X.end),u=D$(z,K.line,3),L=J.slice(X.start,X.end);for(let w of U.tags){let T=[w.name,w.description].filter(Boolean).join(" "),F=`@${w.tag}`,m=L.indexOf(F),j;if(m>=0){let P=X.start+m,r=J.indexOf(`
|
|
4
4
|
`,P),B=r>=0?Math.min(r,X.end):X.end;j=r_(Q,P,B)}else j=r_(Q,X.start,X.end);Y.push({tag:w.tag,value:T,source:"jsdoc",span:j,symbolName:u})}}else if(X.type==="Block"){W=null;let H=X.value.split(`
|
|
5
5
|
`),O=0;for(let U of H){let K=U.replace(/^\s*\*?\s?/,""),u=_0.exec(K);if(u){let L=u[1],w=u[2]?.trim()??"",T=`@${L}`,F=U.indexOf(T),m=X.start+2+O+(F>=0?F:0),j=X.start+2+O+U.length,P=r_(Q,m,j),r=X_(Q,X.end),B=D$(z,r.line,3);Y.push({tag:L,value:w,source:"block",span:P,symbolName:B})}O+=U.length+1}}else{let H=X.value,O=_0.exec(H),U=X_(Q,X.start),K=X_(Q,X.end);if(O){let u=O[1],L=O[2]?.trim()??"",w=`@${u}`,T=H.indexOf(w),F=X.start+2+(T>=0?T:0),m=r_(Q,F,X.end),j=D$(z,K.line,3),P={tag:u,value:L,source:"line",span:m,symbolName:j};Y.push(P),W={annotation:P,endLine:K.line}}else if(W&&U.line===W.endLine+1){let u=H.trim();if(u)W.annotation.value+=" "+u,W.annotation.span.end=X_(Q,X.end),W.endLine=K.line}else W=null}return Y}function u$(_){let{parsed:$,project:J,filePath:Q,annotationRepo:z}=_,Y=$0($);if(z.deleteFileAnnotations(J,Q),!Y.length)return 0;let Z=new Date().toISOString(),W=Y.map((X)=>({project:J,filePath:Q,tag:X.tag,value:X.value,source:X.source,symbolName:X.symbolName,startLine:X.span.start.line,startColumn:X.span.start.column,endLine:X.span.end.line,endColumn:X.span.end.column,indexedAt:Z}));return z.insertBatch(J,Q,W),Y.length}function J0(_,$){let J=[],Q=[],z=[];for(let[O,U]of $)if(!_.has(O))J.push({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint});for(let[O,U]of _)if(!$.has(O))Q.push({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint});if(!J.length||!Q.length)return{renamed:z,added:J,removed:Q};let Y=new Map,Z=new Map;for(let O of J){let U=Y.get(O.filePath)??[];U.push(O),Y.set(O.filePath,U)}for(let O of Q){let U=Z.get(O.filePath)??[];U.push(O),Z.set(O.filePath,U)}let W=new Set,X=new Set;for(let[O,U]of Y){let K=Z.get(O);if(!K)continue;for(let u of new Set(U.map((L)=>L.kind))){let L=U.filter((j)=>j.kind===u&&!W.has(j)),w=K.filter((j)=>j.kind===u&&!X.has(j));if(!L.length||!w.length)continue;let T=(j,P)=>{return P.get(`${j.filePath}::${j.name}`)?.structuralFingerprint??null},F=(j,P)=>{return P.get(`${j.filePath}::${j.name}`)?.startLine??0},m=new Map;for(let j of w){let P=T(j,_);if(!P)continue;let r=m.get(P)??[];r.push(j),m.set(P,r)}for(let j of L){if(W.has(j))continue;let P=T(j,$);if(!P)continue;let r=m.get(P);if(!r)continue;let B=r.filter((D)=>!X.has(D));if(!B.length)continue;let A=B[0];if(B.length>1){let D=F(j,$),C=Math.abs(F(A,_)-D);for(let N=1;N<B.length;N++){let g=Math.abs(F(B[N],_)-D);if(g<C)C=g,A=B[N]}}z.push({oldName:A.name,newName:j.name,filePath:O,kind:u}),W.add(j),X.add(A)}}}let H=z.filter((O)=>!O.oldName.includes("."));for(let O of H){let U=`${O.oldName}.`,K=`${O.newName}.`,u=Q.filter((w)=>w.filePath===O.filePath&&w.name.startsWith(U)&&!X.has(w)),L=J.filter((w)=>w.filePath===O.filePath&&w.name.startsWith(K)&&!W.has(w));for(let w of u){let T=w.name.slice(U.length),F=L.find((m)=>m.name.slice(K.length)===T);if(F)z.push({oldName:w.name,newName:F.name,filePath:O.filePath,kind:w.kind}),W.add(F),X.add(w)}}return{renamed:z,added:J.filter((O)=>!W.has(O)),removed:Q.filter((O)=>!X.has(O))}}var wJ=100,z0=50;class I${opts;logger;callbacks=new Set;indexingLock=!1;pendingEvents=[];debounceTimer=null;currentIndexing=null;pendingFullIndex=!1;pendingFullIndexWaiters=[];tsconfigPathsRaw;boundariesRefresh=null;lastPruneAt=0;constructor(_){this.opts=_,this.logger=_.logger??console,this.tsconfigPathsRaw=v_(_.projectRoot)}get tsconfigPaths(){return this.tsconfigPathsRaw}fullIndex(){return this.startIndex(void 0,!0)}incrementalIndex(_){return this.startIndex(_,!1)}onIndexed(_){return this.callbacks.add(_),()=>this.callbacks.delete(_)}handleWatcherEvent(_){if(_.filePath.endsWith("tsconfig.json")){d_(this.opts.projectRoot),this.tsconfigPathsRaw=v_(this.opts.projectRoot),this.fullIndex().catch(($)=>{this.logger.error("[IndexCoordinator] fullIndex failed after tsconfig change:",$)});return}if(_.filePath.endsWith("package.json")){let $=this.opts.discoverProjectsFn??i_;this.boundariesRefresh=$(this.opts.projectRoot).then((J)=>{this.opts.boundaries=J})}if(this.pendingEvents.push(_),this.debounceTimer===null)this.debounceTimer=setTimeout(()=>{this.debounceTimer=null,this.flushPending()},wJ)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(_,$){if(this.indexingLock){if($)return this.pendingFullIndex=!0,new Promise((Q,z)=>{this.pendingFullIndexWaiters.push({resolve:Q,reject:z})});return this.currentIndexing}this.indexingLock=!0;let J=this.doIndex(_,$).then((Q)=>{return this.fireCallbacks(Q),Q}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let Q=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((z)=>{for(let Y of Q)Y.resolve(z)}).catch((z)=>{for(let Y of Q)Y.reject(z)})}else if(this.pendingEvents.length>0){let Q=this.pendingEvents.splice(0);this.startIndex(Q,!1).catch((z)=>this.logger.error("[IndexCoordinator] incremental drain error",z))}});return this.currentIndexing=J,J}async doIndex(_,$){let J=Date.now(),{fileRepo:Q,symbolRepo:z,relationRepo:Y,dbConnection:Z}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let W,X;if(_!==void 0)W=_.filter((M)=>M.eventType==="create"||M.eventType==="change").map((M)=>({filePath:M.filePath,contentHash:"",mtimeMs:0,size:0})),X=_.filter((M)=>M.eventType==="delete").map((M)=>M.filePath);else{let M=new Map;for(let S of this.opts.boundaries)for(let[k,f]of Q.getFilesMap(S.project))M.set(k,f);let q=await a$({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>M}});W=q.changed,X=q.deleted}let H=await this.tsconfigPathsRaw??void 0,O=new Map;for(let M of X){let q=o(M,this.opts.boundaries),S=z.getFileSymbols(q,M);O.set(M,S)}let U=crypto.randomUUID(),K=new Map,u=new Map,L=(M)=>({name:M.name,filePath:M.filePath,kind:M.kind,fingerprint:M.fingerprint,structuralFingerprint:M.structuralFingerprint??null,startLine:M.startLine,isExported:M.isExported??0});if($)for(let M of this.opts.boundaries)for(let q of Q.getAllFiles(M.project))for(let S of z.getFileSymbols(M.project,q.filePath))K.set(`${S.filePath}::${S.name}`,L(S));else{for(let M of W){let q=o(M.filePath,this.opts.boundaries);for(let S of z.getFileSymbols(q,M.filePath))K.set(`${S.filePath}::${S.name}`,L(S))}for(let[,M]of O)for(let q of M)K.set(`${q.filePath}::${q.name}`,L(q))}let w=(M)=>`${M.type}|${M.srcFilePath}|${M.dstFilePath??""}|${M.srcSymbolName??""}|${M.dstSymbolName??""}|${O_(M.metaJson??"")}`,T=new Map;if($)for(let M of this.opts.boundaries)for(let q of Q.getAllFiles(M.project))for(let S of Y.getOutgoing(M.project,q.filePath))T.set(w(S),S);else{for(let M of W){let q=o(M.filePath,this.opts.boundaries);for(let S of Y.getOutgoing(q,M.filePath))T.set(w(S),S)}for(let M of X){let q=o(M,this.opts.boundaries);for(let S of Y.getOutgoing(q,M))T.set(w(S),S)}}let{annotationRepo:F,changelogRepo:m}=this.opts,j=()=>{for(let M of X){let q=o(M,this.opts.boundaries);if(z.deleteFileSymbols(q,M),Y.deleteFileRelations(q,M),Y.deleteIncomingRelations(q,M),F)F.deleteFileAnnotations(q,M);Q.deleteFile(q,M)}},P=0,r=async()=>{let{projectRoot:M,boundaries:q}=this.opts,{parseCache:S}=this.opts,k=0,f=0,I=0,t=[],v=[];for(let y of W)try{let l=q_(M,y.filePath),K_=Bun.file(l),N_=await K_.text(),b$=y.contentHash||O_(N_),y$=o(y.filePath,q);Q.upsertFile({project:y$,filePath:y.filePath,mtimeMs:K_.lastModified,size:K_.size,contentHash:b$,updatedAt:new Date().toISOString(),lineCount:N_.split(`
|
|
6
6
|
`).length});let z$=(this.opts.parseSourceFn??b_)(l,N_);if(Q0(z$))throw z$.data;let A1=z$;v.push({filePath:y.filePath,text:N_,contentHash:b$,parsed:A1,project:y$})}catch(l){this.logger.error(`[IndexCoordinator] Failed to prepare ${y.filePath}:`,l),t.push(y.filePath)}let x=new Set;for(let y of q)for(let[l]of Q.getFilesMap(y.project))x.add(`${y.project}::${l}`);return Z.transaction(()=>{for(let y of v){if(K$({parsed:y.parsed,project:y.project,filePath:y.filePath,contentHash:y.contentHash,symbolRepo:z}),f+=w$({ast:y.parsed.program,project:y.project,filePath:y.filePath,relationRepo:Y,projectRoot:M,tsconfigPaths:H,knownFiles:x,boundaries:q,module:y.parsed.module}),F)I+=u$({parsed:y.parsed,project:y.project,filePath:y.filePath,annotationRepo:F});S.set(y.filePath,y.parsed),k+=z.getFileSymbols(y.project,y.filePath).length}}),{symbols:k,relations:f,annotations:I,failedFiles:t}},B=0,A=0,D=[];if($){let{projectRoot:M,boundaries:q}=this.opts,{parseCache:S}=this.opts,k=[];for(let I=0;I<W.length;I+=z0){let t=W.slice(I,I+z0),v=await Promise.allSettled(t.map(async(x)=>{let y=q_(M,x.filePath),l=Bun.file(y),K_=await l.text(),N_=x.contentHash||O_(K_);return{filePath:x.filePath,text:K_,contentHash:N_,mtimeMs:l.lastModified,size:l.size}}));for(let x=0;x<v.length;x++){let y=v[x];if(y.status==="fulfilled")k.push(y.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",y.reason),D.push(t[x].filePath)}}let f=[];Z.transaction(()=>{for(let v of k){let x=o(v.filePath,q);Q.deleteFile(x,v.filePath)}for(let v of X){let x=o(v,q);if(z.deleteFileSymbols(x,v),Y.deleteFileRelations(x,v),Y.deleteIncomingRelations(x,v),F)F.deleteFileAnnotations(x,v);Q.deleteFile(x,v)}for(let v of k){let x=o(v.filePath,q);Q.upsertFile({project:x,filePath:v.filePath,mtimeMs:v.mtimeMs,size:v.size,contentHash:v.contentHash,updatedAt:new Date().toISOString(),lineCount:v.text.split(`
|
|
7
|
-
`).length})}let I=new Set;for(let v of q)for(let[x]of Q.getFilesMap(v.project))I.add(`${v.project}::${x}`);let t=this.opts.parseSourceFn??b_;for(let v of k){let x=o(v.filePath,q),y=t(q_(M,v.filePath),v.text);if(Q0(y))throw y.data;let l=y;if(f.push({filePath:v.filePath,parsed:l}),K$({parsed:l,project:x,filePath:v.filePath,contentHash:v.contentHash,symbolRepo:z}),F)P+=u$({parsed:l,project:x,filePath:v.filePath,annotationRepo:F});A+=w$({ast:l.program,project:x,filePath:v.filePath,relationRepo:Y,projectRoot:M,tsconfigPaths:H,knownFiles:I,boundaries:q,module:l.module}),B+=z.getFileSymbols(x,v.filePath).length}});for(let I of f)S.set(I.filePath,I.parsed)}else{j();let M=await r();B=M.symbols,A=M.relations,P=M.annotations,D=M.failedFiles}for(let M of W){let q=o(M.filePath,this.opts.boundaries);for(let S of z.getFileSymbols(q,M.filePath))u.set(`${S.filePath}::${S.name}`,L(S))}let C=new Map;for(let M of W){let q=o(M.filePath,this.opts.boundaries);for(let S of Y.getOutgoing(q,M.filePath))C.set(w(S),S)}let N=(M)=>({type:M.type,srcFilePath:M.srcFilePath,dstFilePath:M.dstFilePath,srcSymbolName:M.srcSymbolName,dstSymbolName:M.dstSymbolName,dstProject:M.dstProject,metaJson:M.metaJson}),g={added:[...C.entries()].filter(([M])=>!T.has(M)).map(([,M])=>N(M)),removed:[...T.entries()].filter(([M])=>!C.has(M)).map(([,M])=>N(M))},R={added:[],modified:[],removed:[]};for(let[M,q]of u){let S=K.get(M);if(!S)R.added.push({name:q.name,filePath:q.filePath,kind:q.kind,isExported:Boolean(q.isExported)});else{let k=S.fingerprint!==q.fingerprint,f=S.isExported!==q.isExported,I=S.structuralFingerprint!==null&&q.structuralFingerprint!==null&&S.structuralFingerprint!==q.structuralFingerprint;if(k||f||I)R.modified.push({name:q.name,filePath:q.filePath,kind:q.kind,isExported:Boolean(q.isExported)})}}for(let[M,q]of K)if(!u.has(M))R.removed.push({name:q.name,filePath:q.filePath,kind:q.kind,isExported:Boolean(q.isExported)});let E=J0(K,u),p=new Set(E.renamed.map((M)=>`${M.filePath}::${M.oldName}`)),d=new Set(E.renamed.map((M)=>`${M.filePath}::${M.newName}`));R.added=R.added.filter((M)=>!d.has(`${M.filePath}::${M.name}`)),R.removed=R.removed.filter((M)=>!p.has(`${M.filePath}::${M.name}`));let a=[];if(!$){for(let[M,q]of O)for(let S of q){if(!S.fingerprint)continue;let k=o(M,this.opts.boundaries),f=z.getByFingerprint(k,S.fingerprint);if(f.length===1){let I=f[0];Y.retargetRelations({dstProject:k,oldFile:M,oldSymbol:S.name,newFile:I.filePath,newSymbol:I.name}),a.push({name:I.name,filePath:I.filePath,kind:I.kind,oldFilePath:M,isExported:I.isExported??0})}}for(let M of E.removed){let S=K.get(`${M.filePath}::${M.name}`)?.fingerprint;if(!S)continue;let k=o(M.filePath,this.opts.boundaries),f=z.getByFingerprint(k,S);if(f.length===1){let I=f[0];if(I.filePath!==M.filePath||I.name!==M.name)Y.retargetRelations({dstProject:k,oldFile:M.filePath,oldSymbol:M.name,newFile:I.filePath,newSymbol:I.name}),a.push({name:I.name,filePath:I.filePath,kind:I.kind,oldFilePath:M.filePath,isExported:I.isExported??0})}}}if(a.length){let M=new Set(a.map((S)=>`${S.filePath}::${S.name}`)),q=new Set(a.map((S)=>`${S.oldFilePath}::${S.name}`));R.added=R.added.filter((S)=>!M.has(`${S.filePath}::${S.name}`)),R.removed=R.removed.filter((S)=>!q.has(`${S.filePath}::${S.name}`))}if(m){let M=new Date().toISOString(),q=$?1:0,S=[];for(let k of R.added){let f=`${k.filePath}::${k.name}`,I=u.get(f),t=o(k.filePath,this.opts.boundaries);S.push({project:t,changeType:"added",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:I?.fingerprint??null,changedAt:M,isFullIndex:q,indexRunId:U})}for(let k of R.modified){let f=u.get(`${k.filePath}::${k.name}`),I=o(k.filePath,this.opts.boundaries);S.push({project:I,changeType:"modified",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:f?.fingerprint??null,changedAt:M,isFullIndex:q,indexRunId:U})}for(let k of R.removed){let f=`${k.filePath}::${k.name}`,I=K.get(f),t=o(k.filePath,this.opts.boundaries);S.push({project:t,changeType:"removed",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:I?.fingerprint??null,changedAt:M,isFullIndex:q,indexRunId:U})}for(let k of E.renamed){let f=u.get(`${k.filePath}::${k.newName}`),I=o(k.filePath,this.opts.boundaries);S.push({project:I,changeType:"renamed",symbolName:k.newName,symbolKind:k.kind,filePath:k.filePath,oldName:k.oldName,oldFilePath:null,fingerprint:f?.fingerprint??null,changedAt:M,isFullIndex:q,indexRunId:U})}for(let k of a){let f=u.get(`${k.filePath}::${k.name}`),I=o(k.filePath,this.opts.boundaries);S.push({project:I,changeType:"moved",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:k.oldFilePath,fingerprint:f?.fingerprint??null,changedAt:M,isFullIndex:q,indexRunId:U})}if(S.length)try{Z.transaction(()=>{m.insertBatch(S)})}catch(k){this.logger.error("[IndexCoordinator] changelog insert failed:",k)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let k=new Date(Date.now()-2592000000).toISOString();try{for(let f of this.opts.boundaries)m.pruneOlderThan(f.project,k)}catch(f){this.logger.error("[IndexCoordinator] changelog pruning failed:",f)}}}return{indexedFiles:W.length,removedFiles:X.length,totalSymbols:B,totalRelations:A,totalAnnotations:P,durationMs:Date.now()-J,changedFiles:W.map((M)=>M.filePath),deletedFiles:[...X],failedFiles:D,changedSymbols:R,renamedSymbols:E.renamed.map((M)=>({oldName:M.oldName,newName:M.newName,filePath:M.filePath,kind:M.kind,isExported:Boolean(u.get(`${M.filePath}::${M.newName}`)?.isExported)})),movedSymbols:a.map((M)=>({name:M.name,oldFilePath:M.oldFilePath,newFilePath:M.filePath,kind:M.kind,isExported:Boolean(M.isExported)})),changedRelations:g}}fireCallbacks(_){for(let $ of this.callbacks)try{$(_)}catch(J){this.logger.error("[IndexCoordinator] onIndexed callback threw:",J)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let _=this.pendingEvents.splice(0);this.startIndex(_,!1).catch(($)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",$))}}}function DJ(_){try{return process.kill(_,0),!0}catch($){if(typeof $==="object"&&$&&"code"in $)return $.code!=="ESRCH";return!0}}function uJ(_){let $=new Date(_).getTime();return Number.isNaN($)?0:$}function W0(_,$,J={}){let Q=J.now??Date.now,z=J.isAlive??DJ,Y=J.staleAfterSeconds??60,Z=J.instanceId;return _.immediateTransaction(()=>{let W=_.selectOwner();if(!W)return _.insertOwner($,Z),"owner";let X=Math.floor((Q()-uJ(W.heartbeat_at))/1000),H=z(W.pid);if(H&&Z&&W.instance_id&&W.instance_id!==Z&&W.pid!==$)return _.replaceOwner($,Z),"owner";if(H&&X<Y)return"reader";return _.replaceOwner($,Z),"owner"})}function Y0(_,$){_.deleteOwner($)}function Z0(_,$){_.touchOwner($)}class P_{#_;#$=new Map;constructor(_){this.#_=Math.max(1,_)}get size(){return this.#$.size}has(_){return this.#$.has(_)}get(_){if(!this.#$.has(_))return;let $=this.#$.get(_);return this.#$.delete(_),this.#$.set(_,$),$}set(_,$){if(this.#$.has(_))this.#$.delete(_);if(this.#$.set(_,$),this.#$.size>this.#_){let J=this.#$.keys().next().value;if(J!==void 0)this.#$.delete(J)}}delete(_){return this.#$.delete(_)}clear(){this.#$.clear()}}class C${lru;constructor(_=500){this.lru=new P_(_)}get(_){return this.lru.get(_)}set(_,$){this.lru.set(_,$)}invalidate(_){this.lru.delete(_)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function N$(_){let{symbolRepo:$,project:J,query:Q}=_,z=Q.project??J,Y={kind:Q.kind,filePath:Q.filePath,isExported:Q.isExported,project:z,limit:Q.limit,resolvedType:Q.resolvedType};if(Q.text)if(Q.exact)Y.exactName=Q.text;else{let W=g_(Q.text);if(W)Y.ftsQuery=W}if(Q.decorator)Y.decorator=Q.decorator;if(Q.regex)Y.regex=Q.regex;return $.searchByQuery(Y).map((W)=>{let X=W.name.indexOf(".");return{id:W.id,filePath:W.filePath,kind:W.kind,name:W.name,memberName:X>=0?W.name.slice(X+1):null,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 A$(_){let{relationRepo:$,project:J,query:Q}=_;if(Q.srcFilePath&&Q.srcFilePathPattern)throw new V("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if(Q.dstFilePath&&Q.dstFilePathPattern)throw new V("validation","dstFilePath and dstFilePathPattern are mutually exclusive");let z=Q.project??J,Y=Q.limit,Z=!!(Q.srcFilePathPattern||Q.dstFilePathPattern),W=Z?void 0:Y,H=$.searchRelations({srcFilePath:Q.srcFilePath,srcSymbolName:Q.srcSymbolName,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,dstProject:Q.dstProject,type:Q.type,project:z,specifier:Q.specifier,isExternal:Q.isExternal,limit:W}).map((O)=>{let U;if(O.metaJson)try{U=JSON.parse(O.metaJson)}catch{}return{type:O.type,srcFilePath:O.srcFilePath,srcSymbolName:O.srcSymbolName,dstFilePath:O.dstFilePath,dstSymbolName:O.dstSymbolName,dstProject:O.dstProject,metaJson:O.metaJson??void 0,meta:U,...O.specifier!=null?{specifier:O.specifier}:{}}});if(Q.srcFilePathPattern||Q.dstFilePathPattern){let O=Q.srcFilePathPattern?new Bun.Glob(Q.srcFilePathPattern):null,U=Q.dstFilePathPattern?new Bun.Glob(Q.dstFilePathPattern):null;H=H.filter((K)=>(!O||O.match(K.srcFilePath))&&(!U||K.dstFilePath===null||U.match(K.dstFilePath)))}if(Z&&Y!==void 0&&H.length>Y)H=H.slice(0,Y);return H}import{findInFiles as IJ,Lang as CJ}from"@ast-grep/napi";async function g$(_){if(_.filePaths.length===0)return[];let $=[];return await IJ(CJ.TypeScript,{paths:_.filePaths,matcher:{rule:{pattern:_.pattern}}},(J,Q)=>{if(J){console.warn("[patternSearch] findInFiles callback error:",J);return}for(let z of Q){let Y=z.range();$.push({filePath:z.getRoot().filename(),startLine:Y.start.line+1,endLine:Y.end.line+1,matchedText:z.text()})}}),$}import J_ from"typescript";import{isErr as bJ}from"@zipbul/result";import U_ from"typescript";import NJ from"path";import{err as q$}from"@zipbul/result";function AJ(_){try{return P$("fs").readFileSync(_,"utf-8")}catch{return}}function gJ(_){try{return P$("fs").readFileSync(_,"utf-8")}catch{return}}class o_{#_;#$;#J=!1;__testing__;constructor(_,$){this.#_=_,this.#$=$,this.__testing__={host:$}}static create(_,$={}){let J=$.readConfigFile??AJ,Q=$.resolveNonTrackedFile??gJ,z=NJ.dirname(_),Y=J(_);if(Y===void 0)return q$(new V("semantic",`tsconfig not found: ${_}`));let Z=U_.parseJsonText(_,Y),W=Z.parseDiagnostics;if(W&&W.length>0){let U=W.map((K)=>U_.flattenDiagnosticMessageText(K.messageText,`
|
|
7
|
+
`).length})}let I=new Set;for(let v of q)for(let[x]of Q.getFilesMap(v.project))I.add(`${v.project}::${x}`);let t=this.opts.parseSourceFn??b_;for(let v of k){let x=o(v.filePath,q),y=t(q_(M,v.filePath),v.text);if(Q0(y))throw y.data;let l=y;if(f.push({filePath:v.filePath,parsed:l}),K$({parsed:l,project:x,filePath:v.filePath,contentHash:v.contentHash,symbolRepo:z}),F)P+=u$({parsed:l,project:x,filePath:v.filePath,annotationRepo:F});A+=w$({ast:l.program,project:x,filePath:v.filePath,relationRepo:Y,projectRoot:M,tsconfigPaths:H,knownFiles:I,boundaries:q,module:l.module}),B+=z.getFileSymbols(x,v.filePath).length}});for(let I of f)S.set(I.filePath,I.parsed)}else{j();let M=await r();B=M.symbols,A=M.relations,P=M.annotations,D=M.failedFiles}for(let M of W){let q=o(M.filePath,this.opts.boundaries);for(let S of z.getFileSymbols(q,M.filePath))u.set(`${S.filePath}::${S.name}`,L(S))}let C=new Map;for(let M of W){let q=o(M.filePath,this.opts.boundaries);for(let S of Y.getOutgoing(q,M.filePath))C.set(w(S),S)}let N=(M)=>({type:M.type,srcFilePath:M.srcFilePath,dstFilePath:M.dstFilePath,srcSymbolName:M.srcSymbolName,dstSymbolName:M.dstSymbolName,dstProject:M.dstProject,metaJson:M.metaJson}),g={added:[...C.entries()].filter(([M])=>!T.has(M)).map(([,M])=>N(M)),removed:[...T.entries()].filter(([M])=>!C.has(M)).map(([,M])=>N(M))},R={added:[],modified:[],removed:[]};for(let[M,q]of u){let S=K.get(M);if(!S)R.added.push({name:q.name,filePath:q.filePath,kind:q.kind,isExported:Boolean(q.isExported)});else{let k=S.fingerprint!==q.fingerprint,f=S.isExported!==q.isExported,I=S.structuralFingerprint!==null&&q.structuralFingerprint!==null&&S.structuralFingerprint!==q.structuralFingerprint;if(k||f||I)R.modified.push({name:q.name,filePath:q.filePath,kind:q.kind,isExported:Boolean(q.isExported)})}}for(let[M,q]of K)if(!u.has(M))R.removed.push({name:q.name,filePath:q.filePath,kind:q.kind,isExported:Boolean(q.isExported)});let E=J0(K,u),p=new Set(E.renamed.map((M)=>`${M.filePath}::${M.oldName}`)),d=new Set(E.renamed.map((M)=>`${M.filePath}::${M.newName}`));R.added=R.added.filter((M)=>!d.has(`${M.filePath}::${M.name}`)),R.removed=R.removed.filter((M)=>!p.has(`${M.filePath}::${M.name}`));let a=[];if(!$){for(let[M,q]of O)for(let S of q){if(!S.fingerprint)continue;let k=o(M,this.opts.boundaries),f=z.getByFingerprint(k,S.fingerprint);if(f.length===1){let I=f[0];Y.retargetRelations({dstProject:k,oldFile:M,oldSymbol:S.name,newFile:I.filePath,newSymbol:I.name}),a.push({name:I.name,filePath:I.filePath,kind:I.kind,oldFilePath:M,isExported:I.isExported??0})}}for(let M of E.removed){let S=K.get(`${M.filePath}::${M.name}`)?.fingerprint;if(!S)continue;let k=o(M.filePath,this.opts.boundaries),f=z.getByFingerprint(k,S);if(f.length===1){let I=f[0];if(I.filePath!==M.filePath||I.name!==M.name)Y.retargetRelations({dstProject:k,oldFile:M.filePath,oldSymbol:M.name,newFile:I.filePath,newSymbol:I.name}),a.push({name:I.name,filePath:I.filePath,kind:I.kind,oldFilePath:M.filePath,isExported:I.isExported??0})}}}if(a.length){let M=new Set(a.map((S)=>`${S.filePath}::${S.name}`)),q=new Set(a.map((S)=>`${S.oldFilePath}::${S.name}`));R.added=R.added.filter((S)=>!M.has(`${S.filePath}::${S.name}`)),R.removed=R.removed.filter((S)=>!q.has(`${S.filePath}::${S.name}`))}if(m){let M=new Date().toISOString(),q=$?1:0,S=[];for(let k of R.added){let f=`${k.filePath}::${k.name}`,I=u.get(f),t=o(k.filePath,this.opts.boundaries);S.push({project:t,changeType:"added",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:I?.fingerprint??null,changedAt:M,isFullIndex:q,indexRunId:U})}for(let k of R.modified){let f=u.get(`${k.filePath}::${k.name}`),I=o(k.filePath,this.opts.boundaries);S.push({project:I,changeType:"modified",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:f?.fingerprint??null,changedAt:M,isFullIndex:q,indexRunId:U})}for(let k of R.removed){let f=`${k.filePath}::${k.name}`,I=K.get(f),t=o(k.filePath,this.opts.boundaries);S.push({project:t,changeType:"removed",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:null,fingerprint:I?.fingerprint??null,changedAt:M,isFullIndex:q,indexRunId:U})}for(let k of E.renamed){let f=u.get(`${k.filePath}::${k.newName}`),I=o(k.filePath,this.opts.boundaries);S.push({project:I,changeType:"renamed",symbolName:k.newName,symbolKind:k.kind,filePath:k.filePath,oldName:k.oldName,oldFilePath:null,fingerprint:f?.fingerprint??null,changedAt:M,isFullIndex:q,indexRunId:U})}for(let k of a){let f=u.get(`${k.filePath}::${k.name}`),I=o(k.filePath,this.opts.boundaries);S.push({project:I,changeType:"moved",symbolName:k.name,symbolKind:k.kind,filePath:k.filePath,oldName:null,oldFilePath:k.oldFilePath,fingerprint:f?.fingerprint??null,changedAt:M,isFullIndex:q,indexRunId:U})}if(S.length)try{Z.transaction(()=>{m.insertBatch(S)})}catch(k){this.logger.error("[IndexCoordinator] changelog insert failed:",k)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let k=new Date(Date.now()-2592000000).toISOString();try{for(let f of this.opts.boundaries)m.pruneOlderThan(f.project,k)}catch(f){this.logger.error("[IndexCoordinator] changelog pruning failed:",f)}}}return{indexedFiles:W.length,removedFiles:X.length,totalSymbols:B,totalRelations:A,totalAnnotations:P,durationMs:Date.now()-J,changedFiles:W.map((M)=>M.filePath),deletedFiles:[...X],failedFiles:D,changedSymbols:R,renamedSymbols:E.renamed.map((M)=>({oldName:M.oldName,newName:M.newName,filePath:M.filePath,kind:M.kind,isExported:Boolean(u.get(`${M.filePath}::${M.newName}`)?.isExported)})),movedSymbols:a.map((M)=>({name:M.name,oldFilePath:M.oldFilePath,newFilePath:M.filePath,kind:M.kind,isExported:Boolean(M.isExported)})),changedRelations:g}}fireCallbacks(_){for(let $ of this.callbacks)try{$(_)}catch(J){this.logger.error("[IndexCoordinator] onIndexed callback threw:",J)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let _=this.pendingEvents.splice(0);this.startIndex(_,!1).catch(($)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",$))}}}function DJ(_){try{return process.kill(_,0),!0}catch($){if(typeof $==="object"&&$&&"code"in $)return $.code!=="ESRCH";return!0}}function uJ(_){let $=new Date(_).getTime();return Number.isNaN($)?0:$}function W0(_,$,J={}){let Q=J.now??Date.now,z=J.isAlive??DJ,Y=J.staleAfterSeconds??60,Z=J.instanceId;return _.immediateTransaction(()=>{let W=_.selectOwner();if(!W)return _.insertOwner($,Z),"owner";let X=Math.floor((Q()-uJ(W.heartbeat_at))/1000),H=z(W.pid);if(H&&Z&&W.instance_id&&W.instance_id!==Z&&W.pid!==$)return _.replaceOwner($,Z),"owner";if(H&&X<Y)return"reader";return _.replaceOwner($,Z),"owner"})}function Y0(_,$){_.deleteOwner($)}function Z0(_,$){_.touchOwner($)}class P_{#_;#$=new Map;constructor(_){this.#_=Math.max(1,_)}get size(){return this.#$.size}has(_){return this.#$.has(_)}get(_){if(!this.#$.has(_))return;let $=this.#$.get(_);return this.#$.delete(_),this.#$.set(_,$),$}set(_,$){if(this.#$.has(_))this.#$.delete(_);if(this.#$.set(_,$),this.#$.size>this.#_){let J=this.#$.keys().next().value;if(J!==void 0)this.#$.delete(J)}}delete(_){return this.#$.delete(_)}clear(){this.#$.clear()}}class C${lru;constructor(_=500){this.lru=new P_(_)}get(_){return this.lru.get(_)}set(_,$){this.lru.set(_,$)}invalidate(_){this.lru.delete(_)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function N$(_){let{symbolRepo:$,project:J,query:Q}=_,z=Q.project??J,Y={kind:Q.kind,filePath:Q.filePath,isExported:Q.isExported,project:z,limit:Q.limit,resolvedType:Q.resolvedType};if(Q.text)if(Q.exact)Y.exactName=Q.text;else{let W=g_(Q.text);if(W)Y.ftsQuery=W}if(Q.decorator)Y.decorator=Q.decorator;if(Q.regex)Y.regex=Q.regex;return $.searchByQuery(Y).map((W)=>{let X=W.name.indexOf(".");return{id:W.id,filePath:W.filePath,kind:W.kind,name:W.name,memberName:X>=0?W.name.slice(X+1):null,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 A$(_){let{relationRepo:$,project:J,query:Q}=_;if(Q.srcFilePath&&Q.srcFilePathPattern)throw new V("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if(Q.dstFilePath&&Q.dstFilePathPattern)throw new V("validation","dstFilePath and dstFilePathPattern are mutually exclusive");let z=Q.project??J,Y=Q.limit,Z=!!(Q.srcFilePathPattern||Q.dstFilePathPattern),W=Z?void 0:Y,H=$.searchRelations({srcFilePath:Q.srcFilePath,srcSymbolName:Q.srcSymbolName,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,dstProject:Q.dstProject,type:Q.type,project:z,specifier:Q.specifier,isExternal:Q.isExternal,limit:W}).map((O)=>{let U;if(O.metaJson)try{U=JSON.parse(O.metaJson)}catch{}return{type:O.type,srcFilePath:O.srcFilePath,srcSymbolName:O.srcSymbolName,dstFilePath:O.dstFilePath,dstSymbolName:O.dstSymbolName,dstProject:O.dstProject,isExternal:O.isExternal===1,specifier:O.specifier,metaJson:O.metaJson??void 0,meta:U}});if(Q.srcFilePathPattern||Q.dstFilePathPattern){let O=Q.srcFilePathPattern?new Bun.Glob(Q.srcFilePathPattern):null,U=Q.dstFilePathPattern?new Bun.Glob(Q.dstFilePathPattern):null;H=H.filter((K)=>(!O||O.match(K.srcFilePath))&&(!U||K.dstFilePath===null||U.match(K.dstFilePath)))}if(Z&&Y!==void 0&&H.length>Y)H=H.slice(0,Y);return H}import{findInFiles as IJ,Lang as CJ}from"@ast-grep/napi";async function g$(_){if(_.filePaths.length===0)return[];let $=[];return await IJ(CJ.TypeScript,{paths:_.filePaths,matcher:{rule:{pattern:_.pattern}}},(J,Q)=>{if(J){console.warn("[patternSearch] findInFiles callback error:",J);return}for(let z of Q){let Y=z.range();$.push({filePath:z.getRoot().filename(),startLine:Y.start.line+1,endLine:Y.end.line+1,matchedText:z.text()})}}),$}import J_ from"typescript";import{isErr as bJ}from"@zipbul/result";import U_ from"typescript";import NJ from"path";import{err as q$}from"@zipbul/result";function AJ(_){try{return P$("fs").readFileSync(_,"utf-8")}catch{return}}function gJ(_){try{return P$("fs").readFileSync(_,"utf-8")}catch{return}}class o_{#_;#$;#J=!1;__testing__;constructor(_,$){this.#_=_,this.#$=$,this.__testing__={host:$}}static create(_,$={}){let J=$.readConfigFile??AJ,Q=$.resolveNonTrackedFile??gJ,z=NJ.dirname(_),Y=J(_);if(Y===void 0)return q$(new V("semantic",`tsconfig not found: ${_}`));let Z=U_.parseJsonText(_,Y),W=Z.parseDiagnostics;if(W&&W.length>0){let U=W.map((K)=>U_.flattenDiagnosticMessageText(K.messageText,`
|
|
8
8
|
`)).join("; ");return q$(new V("semantic",`tsconfig parse error: ${U}`))}let X=U_.parseJsonSourceFileConfigFileContent(Z,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(U)=>J(U)!==void 0||Q(U)!==void 0,readFile:(U)=>J(U)??Q(U)},z);if(X.errors.length>0){let U=X.errors.filter((K)=>K.category===U_.DiagnosticCategory.Error&&K.code!==18003);if(U.length>0){let K=U.map((u)=>U_.flattenDiagnosticMessageText(u.messageText,`
|
|
9
|
-
`)).join("; ");return q$(new V("semantic",`tsconfig compile error: ${K}`))}}let H=new X0(X.fileNames,X.options,z,Q),O=U_.createLanguageService(H);return new o_(O,H)}get isDisposed(){return this.#J}getProgram(){this.#z();let _=this.#_.getProgram();if(!_)throw Error("TscProgram: LanguageService returned null Program");return _}getChecker(){return this.#z(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#z(),this.#_}notifyFileChanged(_,$){if(this.#J)return;this.#$.updateFile(_,$)}removeFile(_){if(this.#J)return;this.#$.removeFile(_)}dispose(){if(this.#J)return;this.#J=!0,this.#_.dispose()}#z(){if(this.#J)throw Error("TscProgram is disposed")}}class X0{#_;#$;#J;#z;#Q=new Map;constructor(_,$,J,Q){this.#_=new Set(_),this.#$=$,this.#J=J,this.#z=Q}updateFile(_,$){let J=this.#Q.get(_);if(J)J.version+=1,J.content=$;else this.#Q.set(_,{version:1,content:$})}removeFile(_){this.#Q.delete(_),this.#_.delete(_)}getScriptFileNames(){let _=[...this.#Q.keys()];return[...[...this.#_].filter((J)=>!this.#Q.has(J)),..._]}getScriptVersion(_){let $=this.#Q.get(_);return $?String($.version):"0"}getScriptSnapshot(_){let $=this.#Q.get(_);if($)return U_.ScriptSnapshot.fromString($.content);let J=this.#z(_);if(J!==void 0)return U_.ScriptSnapshot.fromString(J);return}getCurrentDirectory(){return this.#J}getCompilationSettings(){return this.#$}getDefaultLibFileName(_){return U_.getDefaultLibFilePath(_)}fileExists(_){if(this.#Q.has(_))return!0;return this.#z(_)!==void 0}readFile(_){let $=this.#Q.get(_);if($)return $.content;return this.#z(_)}}import s from"typescript";import qJ from"typescript";function W_(_,$){if($<0||$>=_.getEnd())return;function J(Q){let z=Q.getStart(_,!1),Y=Q.getEnd();if($<z||$>=Y)return;let Z;return qJ.forEachChild(Q,(W)=>{if(!Z)Z=J(W)}),Z??Q}return J(_)}var t_=8;function SJ(_){return!!(_.flags&s.TypeFlags.Object)&&!!(_.objectFlags&s.ObjectFlags.Reference)}function H_(_,$,J=0){let Q=_.typeToString($),z=$.flags,Y=!!(z&s.TypeFlags.Union),Z=!!(z&s.TypeFlags.Intersection),W;if(J<t_&&SJ($)){let K=_.getTypeArguments($);if(K.length>0)W=K}let X=!!(z&s.TypeFlags.TypeParameter)||W!==void 0&&W.length>0,H;if(Y&&J<t_)H=$.types.map((K)=>H_(_,K,J+1));else if(Z&&J<t_)H=$.types.map((K)=>H_(_,K,J+1));let O;if(W&&W.length>0)O=W.map((K)=>H_(_,K,J+1));let U;if(J<t_&&!!(z&s.TypeFlags.Object)&&!Y&&!Z){let K=_.getPropertiesOfType($);if(K.length>0&&K.length<=50){let u=$.symbol?.declarations?.[0];U=[];for(let L of K){let w=L.declarations?.[0]??u;if(!w)continue;try{let T=_.getTypeOfSymbolAtLocation(L,w);U.push({name:L.getName(),type:H_(_,T,J+1)})}catch{}}if(U.length===0)U=void 0}}return{text:Q,flags:z,isUnion:Y,isIntersection:Z,isGeneric:X,members:H,typeArguments:O,properties:U}}function TJ(_){return s.isFunctionDeclaration(_)||s.isVariableDeclaration(_)||s.isClassDeclaration(_)||s.isInterfaceDeclaration(_)||s.isTypeAliasDeclaration(_)||s.isEnumDeclaration(_)||s.isMethodDeclaration(_)||s.isPropertyDeclaration(_)||s.isPropertySignature(_)||s.isMethodSignature(_)}class S${program;constructor(_){this.program=_}collectAt(_,$){let J=this.program.getProgram(),Q=this.program.getChecker();if($<0)return null;let z=J.getSourceFile(_);if(!z)return null;if($>=z.getEnd())return null;let Y=W_(z,$);if(!Y)return null;if(!s.isIdentifier(Y)&&!s.isTypeNode(Y))return null;try{let Z=Q.getTypeAtLocation(Y);return H_(Q,Z)}catch{return null}}isAssignableTo(_,$,J,Q){let z=this.program.getChecker(),Y=this.program.getProgram(),Z=Y.getSourceFile(_);if(!Z)return null;let W=W_(Z,$);if(!W||!s.isIdentifier(W))return null;let X=Y.getSourceFile(J);if(!X)return null;let H=W_(X,Q);if(!H||!s.isIdentifier(H))return null;try{let O=z.getTypeAtLocation(W),U=z.getTypeAtLocation(H);return z.isTypeAssignableTo(O,U)}catch{return null}}isAssignableToType(_,$,J,Q){let z=this.program.getChecker(),Z=this.program.getProgram().getSourceFile(_);if(!Z)return null;let W=W_(Z,$);if(!W||!s.isIdentifier(W)&&!s.isTypeNode(W))return null;let X=`${_}.__gildash_probe__.ts`,H=`declare const __gildash_probe__: ${J};`;this.program.notifyFileChanged(X,H);try{let O=z.getTypeAtLocation(W),K=this.program.getProgram().getSourceFile(X);if(!K)return null;let u=this.program.getChecker(),L=K.statements[0];if(!L||!s.isVariableStatement(L))return null;let w=L.declarationList.declarations[0];if(!w)return null;let T=u.getTypeAtLocation(w.name);if(Q?.anyConstituent&&O.isUnion())return O.types.some((F)=>u.isTypeAssignableTo(F,T));return u.isTypeAssignableTo(O,T)}catch{return null}finally{this.program.removeFile(X)}}collectFile(_){let $=new Map,J=this.program.getProgram(),Q=this.program.getChecker(),z=J.getSourceFile(_);if(!z)return $;function Y(Z){if(TJ(Z)&&Z.name&&s.isIdentifier(Z.name)){let W=Z.name;try{let X=Q.getTypeAtLocation(W),H=W.getStart(z);$.set(H,H_(Q,X))}catch{}}s.forEachChild(Z,Y)}return Y(z),$}}import M_ from"typescript";var RJ=1000,kJ=1;function FJ(_){let $=_.declarations?.[0],J=$?.getSourceFile(),Q=$?M_.getNameOfDeclaration($):void 0;return{name:_.getName(),filePath:J?.fileName??"",position:Q?.getStart(J,!1)??$?.getStart(J,!1)??0}}function e_(_,$=0,J){let Q=_.declarations?.[0],z=Q?.getSourceFile(),Y=Q?M_.getNameOfDeclaration(Q):void 0,Z=z?.fileName??"",W=Y?.getStart(z,!1)??Q?.getStart(z,!1)??0,X={name:_.getName(),filePath:Z,position:W},H=_;if(H.parent)X.parent=FJ(H.parent);let O=J&&!!(_.flags&M_.SymbolFlags.Alias)?J.getAliasedSymbol(_):_;if($<kJ){let U=O.flags,K=!!(U&M_.SymbolFlags.Enum),u=!!(U&(M_.SymbolFlags.NamespaceModule|M_.SymbolFlags.ValueModule)),L=!!(U&(M_.SymbolFlags.Class|M_.SymbolFlags.Interface));if(K&&O.exports&&O.exports.size>0){let w=[];O.exports.forEach((T)=>{w.push(e_(T,$+1,J))}),X.members=w}else if(L&&O.members&&O.members.size>0){let w=[];O.members.forEach((T)=>{w.push(e_(T,$+1,J))}),X.members=w}if(u&&O.exports&&O.exports.size>0){let w=[];O.exports.forEach((T)=>{w.push(e_(T,$+1,J))}),X.exports=w}}return X}class T${#_;#$;#J=new Map;constructor(_,$=RJ){this.#_=_,this.#$=new P_($)}get(_,$){if(this.#_.isDisposed)return null;let J=`${_}:${$}`,Q=this.#$.get(J);if(Q!==void 0)return Q;let Y=this.#_.getProgram().getSourceFile(_);if(!Y)return null;let Z=W_(Y,$);if(!Z||!M_.isIdentifier(Z))return null;let W=this.#_.getChecker(),X=W.getSymbolAtLocation(Z);if(!X)return null;let H=e_(X,0,W);this.#$.set(J,H);let O=this.#J.get(_);if(!O)O=new Set,this.#J.set(_,O);return O.add(J),H}invalidate(_){let $=this.#J.get(_);if($){for(let J of $)this.#$.delete(J);this.#J.delete(_)}}clear(){this.#$.clear(),this.#J.clear()}}import GJ from"typescript";class R${#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=W_(Q,$);if(!z||!GJ.isIdentifier(z))return[];let Z=this.#_.getLanguageService().findReferences(_,$);if(!Z||Z.length===0)return[];let W=[];for(let X of Z)for(let H of X.references){let O=J.getSourceFile(H.fileName);if(!O)continue;let{line:U,character:K}=O.getLineAndCharacterOfPosition(H.textSpan.start);W.push({filePath:H.fileName,position:H.textSpan.start,line:U+1,column:K,isDefinition:H.isDefinition??!1,isWrite:H.isWriteAccess??!1})}return W}}import i from"typescript";function jJ(_,$){let J=W_(_,$);if(!J)return;if(O0(J))return J;let Q=J.parent;for(let z=0;z<5&&Q;z++){if(O0(Q))return Q;Q=Q.parent}return J}function O0(_){return i.isClassDeclaration(_)||i.isClassExpression(_)||i.isFunctionDeclaration(_)||i.isFunctionExpression(_)||i.isArrowFunction(_)||i.isVariableDeclaration(_)||i.isObjectLiteralExpression(_)}function V0(_){if(i.isClassDeclaration(_)||i.isClassExpression(_))return"class";if(i.isFunctionDeclaration(_)||i.isFunctionExpression(_)||i.isArrowFunction(_))return"function";if(i.isObjectLiteralExpression(_))return"object";if(i.isVariableDeclaration(_)&&_.initializer)return V0(_.initializer);return"class"}function EJ(_,$){if(i.isClassDeclaration(_)||i.isFunctionDeclaration(_))return _.name?.getText($)??"";if(i.isClassExpression(_))return _.name?.getText($)??"";if(i.isVariableDeclaration(_)&&i.isIdentifier(_.name))return _.name.getText($);if(i.isFunctionExpression(_))return _.name?.getText($)??"";if(i.isArrowFunction(_)&&_.parent&&i.isVariableDeclaration(_.parent)){if(i.isIdentifier(_.parent.name))return _.parent.name.getText($)}if(i.isObjectLiteralExpression(_)&&_.parent&&i.isVariableDeclaration(_.parent)){if(i.isIdentifier(_.parent.name))return _.parent.name.getText($)}return""}function vJ(_){if(!i.isClassDeclaration(_)&&!i.isClassExpression(_))return!1;let $=_.heritageClauses;if(!$)return!1;return $.some((J)=>J.token===i.SyntaxKind.ImplementsKeyword)}class k${#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=W_(Q,$);if(!z||!i.isIdentifier(z))return[];let Z=this.#_.getLanguageService().getImplementationAtPosition(_,$);if(!Z||Z.length===0)return[];let W=[];for(let X of Z){if(X.kind===i.ScriptElementKind.interfaceElement||X.kind===i.ScriptElementKind.typeElement)continue;let H=J.getSourceFile(X.fileName);if(!H)continue;let O=jJ(H,X.textSpan.start);if(!O)continue;let U=V0(O),K=EJ(O,H),u=vJ(O);W.push({filePath:X.fileName,symbolName:K,position:X.textSpan.start,kind:U,isExplicit:u})}return W}}function yJ(_){if(J_.isFunctionDeclaration(_))return"function";if(J_.isClassDeclaration(_))return"class";if(J_.isInterfaceDeclaration(_))return"interface";if(J_.isTypeAliasDeclaration(_))return"type";if(J_.isEnumDeclaration(_))return"enum";if(J_.isVariableDeclaration(_))return"const";if(J_.isVariableStatement(_))return"const";return"unknown"}function U0(_){if(_>=97&&_<=122)return!0;if(_>=65&&_<=90)return!0;if(_>=48&&_<=57)return!0;if(_===95||_===36)return!0;return!1}class _${#_;#$;#J;#z;#Q;#Y=!1;constructor(_,$,J,Q,z){this.#_=_,this.#$=$,this.#J=J,this.#z=Q,this.#Q=z}static create(_,$={}){let J=o_.create(_,{readConfigFile:$.readConfigFile,resolveNonTrackedFile:$.resolveNonTrackedFile});if(bJ(J))return J;let Q=J,z=$.typeCollector??new S$(Q),Y=$.symbolGraph??new T$(Q),Z=$.referenceResolver??new R$(Q),W=$.implementationFinder??new k$(Q);return new _$(Q,z,Y,Z,W)}get isDisposed(){return this.#Y}collectTypeAt(_,$){return this.#W(),this.#$.collectAt(_,$)}collectFileTypes(_){return this.#W(),this.#$.collectFile(_)}findReferences(_,$){return this.#W(),this.#z.findAt(_,$)}findImplementations(_,$){return this.#W(),this.#Q.findAt(_,$)}isTypeAssignableTo(_,$,J,Q){return this.#W(),this.#$.isAssignableTo(_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return this.#W(),this.#$.isAssignableToType(_,$,J,Q)}getSymbolNode(_,$){return this.#W(),this.#J.get(_,$)}getBaseTypes(_,$){this.#W();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let z=W_(Q,$);if(!z)return null;let Y=this.#_.getChecker(),Z=Y.getTypeAtLocation(z);if(!(Z.flags&J_.TypeFlags.Object)||!(Z.objectFlags&J_.ObjectFlags.ClassOrInterface))return null;let W=Y.getBaseTypes(Z);if(!W||W.length===0)return[];return W.map((X)=>H_(Y,X))}getModuleInterface(_){this.#W();let $=[],Q=this.#_.getProgram().getSourceFile(_);if(!Q)return{filePath:_,exports:$};let z=this.#_.getChecker(),Y=z.getSymbolAtLocation(Q);if(Y){let Z=z.getExportsOfModule(Y);for(let W of Z){let X=W.getName(),H=W.declarations?.[0],O="unknown";if(H){if(O=yJ(H),O==="unknown"&&J_.isExportAssignment(H))O="const"}let U=null;try{let K=z.getTypeOfSymbolAtLocation(W,H??Q);U=H_(z,K)}catch{}$.push({name:X,kind:O,resolvedType:U})}}return{filePath:_,exports:$}}notifyFileChanged(_,$){if(this.#Y)return;this.#_.notifyFileChanged(_,$),this.#J.invalidate(_)}notifyFileDeleted(_){if(this.#Y)return;this.#_.removeFile(_),this.#J.invalidate(_)}lineColumnToPosition(_,$,J){this.#W();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;try{return J_.getPositionOfLineAndCharacter(Q,$-1,J)}catch{return null}}findNamePosition(_,$,J){this.#W();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let z=Q.getFullText(),Y=$;while(Y<z.length){let Z=z.indexOf(J,Y);if(Z<0)return null;let W=Z>0?z.charCodeAt(Z-1):32,X=Z+J.length<z.length?z.charCodeAt(Z+J.length):32;if(!U0(W)&&!U0(X))return Z;Y=Z+1}return null}getDiagnostics(_,$){this.#W();let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z={[J_.DiagnosticCategory.Error]:"error",[J_.DiagnosticCategory.Warning]:"warning",[J_.DiagnosticCategory.Suggestion]:"suggestion",[J_.DiagnosticCategory.Message]:"suggestion"};return(($?.preEmit)?J_.getPreEmitDiagnostics(J,Q):J.getSemanticDiagnostics(Q)).map((Z)=>{let W=1,X=0;if(Z.file&&Z.start!==void 0){let H=J_.getLineAndCharacterOfPosition(Z.file,Z.start);W=H.line+1,X=H.character}return{filePath:Z.file?.fileName??_,line:W,column:X,message:J_.flattenDiagnosticMessageText(Z.messageText,`
|
|
10
|
-
`),code:Z.code,category:z[Z.category]??"error"}})}dispose(){if(this.#Y)return;this.#Y=!0,this.#_.dispose(),this.#J.clear()}#W(){if(this.#Y)throw Error("SemanticLayer is disposed")}}import{eq as I_,and as H0,sql as PJ}from"drizzle-orm";var M0=80;class F${db;constructor(_){this.db=_}insertBatch(_,$,J){if(!J.length)return;let Q=J.map((z)=>({project:_,filePath:$,tag:z.tag,value:z.value,source:z.source,symbolName:z.symbolName,startLine:z.startLine,startColumn:z.startColumn,endLine:z.endLine,endColumn:z.endColumn,indexedAt:z.indexedAt}));for(let z=0;z<Q.length;z+=M0)this.db.drizzleDb.insert(Y_).values(Q.slice(z,z+M0)).run()}deleteFileAnnotations(_,$){this.db.drizzleDb.delete(Y_).where(H0(I_(Y_.project,_),I_(Y_.filePath,$))).run()}search(_){let $=this.db.drizzleDb.select().from(Y_).where(H0(_.project?I_(Y_.project,_.project):void 0,_.tag?I_(Y_.tag,_.tag):void 0,_.filePath?I_(Y_.filePath,_.filePath):void 0,_.symbolName?I_(Y_.symbolName,_.symbolName):void 0,_.source?I_(Y_.source,_.source):void 0,_.ftsQuery?PJ`${Y_.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${_.ftsQuery})`:void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}}import{eq as k_,and as K0,sql as f_,gt as fJ,gte as nJ}from"drizzle-orm";var L0=80;class G${db;constructor(_){this.db=_}insertBatch(_){if(!_.length)return;let $=_.map((J)=>({project:J.project,changeType:J.changeType,symbolName:J.symbolName,symbolKind:J.symbolKind,filePath:J.filePath,oldName:J.oldName,oldFilePath:J.oldFilePath,fingerprint:J.fingerprint,changedAt:J.changedAt,isFullIndex:J.isFullIndex,indexRunId:J.indexRunId}));for(let J=0;J<$.length;J+=L0)this.db.drizzleDb.insert(Q_).values($.slice(J,J+L0)).run()}getSince(_){return this.db.drizzleDb.select().from(Q_).where(K0(k_(Q_.project,_.project),nJ(Q_.changedAt,_.since),_.symbolName?k_(Q_.symbolName,_.symbolName):void 0,_.changeTypes?.length?f_`${Q_.changeType} IN (${f_.join(_.changeTypes.map(($)=>f_`${$}`),f_`, `)})`:void 0,_.filePath?k_(Q_.filePath,_.filePath):void 0,_.includeFullIndex?void 0:k_(Q_.isFullIndex,0),_.indexRunId?k_(Q_.indexRunId,_.indexRunId):void 0,_.afterId?fJ(Q_.id,_.afterId):void 0)).orderBy(Q_.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete(Q_).where(K0(k_(Q_.project,_),f_`${Q_.changedAt} < ${$}`)).run().changes}}function B0(_){let{annotationRepo:$,project:J,query:Q}=_,z=Q.project??J,Y;if(Q.text){let W=g_(Q.text);if(W)Y=W}return $.search({project:z,tag:Q.tag,filePath:Q.filePath,symbolName:Q.symbolName,source:Q.source,ftsQuery:Y,limit:Q.limit}).map((W)=>({tag:W.tag,value:W.value,source:W.source,filePath:W.filePath,symbolName:W.symbolName,span:{start:{line:W.startLine,column:W.startColumn},end:{line:W.endLine,column:W.endColumn}}}))}class $${options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(_){this.options=_}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let $=[this.options.project,...this.options.additionalProjects??[]].flatMap((J)=>[...this.options.relationRepo.getByType(J,"imports"),...this.options.relationRepo.getByType(J,"type-references"),...this.options.relationRepo.getByType(J,"re-exports")]);for(let J of $){let{srcFilePath:Q,dstFilePath:z}=J;if(z===null)continue;if(!this.adjacencyList.has(Q))this.adjacencyList.set(Q,new Set);if(this.adjacencyList.get(Q).add(z),!this.adjacencyList.has(z))this.adjacencyList.set(z,new Set);if(!this.reverseAdjacencyList.has(z))this.reverseAdjacencyList.set(z,new Set);this.reverseAdjacencyList.get(z).add(Q)}}patchFiles(_,$,J){let Q=new Set([..._,...$]);for(let z of Q){let Y=this.adjacencyList.get(z);if(Y){for(let W of Y)this.reverseAdjacencyList.get(W)?.delete(z);Y.clear()}let Z=this.reverseAdjacencyList.get(z);if(Z){for(let W of Z)this.adjacencyList.get(W)?.delete(z);Z.clear()}}for(let z of $)this.adjacencyList.delete(z),this.reverseAdjacencyList.delete(z);for(let z of _){let Y=J(z);for(let Z of Y){if(!this.adjacencyList.has(Z.srcFilePath))this.adjacencyList.set(Z.srcFilePath,new Set);if(this.adjacencyList.get(Z.srcFilePath).add(Z.dstFilePath),!this.adjacencyList.has(Z.dstFilePath))this.adjacencyList.set(Z.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(Z.dstFilePath))this.reverseAdjacencyList.set(Z.dstFilePath,new Set);this.reverseAdjacencyList.get(Z.dstFilePath).add(Z.srcFilePath)}}}getDependencies(_){return Array.from(this.adjacencyList.get(_)??[])}getDependents(_){return Array.from(this.reverseAdjacencyList.get(_)??[])}getTransitiveDependents(_){let $=new Set,J=[_];while(J.length>0){let Q=J.shift();for(let z of this.reverseAdjacencyList.get(Q)??[])if(!$.has(z))$.add(z),J.push(z)}return Array.from($)}hasCycle(){let _=new Set,$=new Set;for(let J of this.adjacencyList.keys()){if(_.has(J))continue;let Q=[{node:J,entered:!1}];while(Q.length>0){let z=Q.pop();if(z.entered){$.delete(z.node);continue}if($.has(z.node))return!0;if(_.has(z.node))continue;_.add(z.node),$.add(z.node),Q.push({node:z.node,entered:!0});for(let Y of this.adjacencyList.get(z.node)??[]){if($.has(Y))return!0;if(!_.has(Y))Q.push({node:Y,entered:!1})}}}return!1}getAffectedByChange(_){let $=new Set;for(let J of _)for(let Q of this.getTransitiveDependents(J))$.add(Q);return Array.from($)}getAdjacencyList(){let _=new Map;for(let[$,J]of this.adjacencyList)_.set($,Array.from(J));return _}getTransitiveDependencies(_){let $=new Set,J=[_];while(J.length>0){let Q=J.shift();for(let z of this.adjacencyList.get(Q)??[])if(!$.has(z))$.add(z),J.push(z)}return Array.from($)}getCyclePaths(_){let $=_?.maxCycles??1/0;if($<=0)return[];let J=new Map;for(let[Q,z]of this.adjacencyList)J.set(Q,Array.from(z));return iJ(J,$)}}var mJ=(_,$)=>_.localeCompare($);function xJ(_){let $=_.length>1&&_[0]===_[_.length-1]?_.slice(0,-1):[..._];if($.length===0)return[];let J=$;for(let Q=1;Q<$.length;Q++){let z=$.slice(Q).concat($.slice(0,Q));if(z.join("::")<J.join("::"))J=z}return[...J]}function j$(_,$,J){let Q=xJ(J);if(Q.length===0)return!1;let z=Q.join("->");if(_.has(z))return!1;return _.add(z),$.push(Q),!0}function hJ(_){let $=0,J=[],Q=new Set,z=new Map,Y=new Map,Z=[],W=(X)=>{z.set(X,$),Y.set(X,$),$+=1,J.push(X),Q.add(X);for(let H of _.get(X)??[])if(!z.has(H))W(H),Y.set(X,Math.min(Y.get(X)??0,Y.get(H)??0));else if(Q.has(H))Y.set(X,Math.min(Y.get(X)??0,z.get(H)??0));if(Y.get(X)===z.get(X)){let H=[],O="";do O=J.pop()??"",Q.delete(O),H.push(O);while(O!==X&&J.length>0);Z.push(H)}};for(let X of _.keys())if(!z.has(X))W(X);return{components:Z}}function pJ(_,$,J){let Q=[],z=new Set,Y=[..._].sort(mJ),Z=(W,X,H)=>{X.delete(W);let O=H.get(W);if(!O)return;for(let U of O)if(X.has(U))Z(U,X,H);O.clear()};for(let W=0;W<Y.length&&Q.length<J;W++){let X=Y[W]??"",H=new Set(Y.slice(W)),O=new Set,U=new Map,K=[],u=(w)=>($.get(w)??[]).filter((T)=>H.has(T)),L=(w)=>{if(Q.length>=J)return!0;let T=!1;K.push(w),O.add(w);for(let F of u(w)){if(Q.length>=J)break;if(F===X)j$(z,Q,K.concat(X)),T=!0;else if(!O.has(F)){if(L(F))T=!0}}if(T)Z(w,O,U);else for(let F of u(w)){let m=U.get(F)??new Set;m.add(w),U.set(F,m)}return K.pop(),T};L(X)}return Q}function iJ(_,$){let{components:J}=hJ(_),Q=[],z=new Set;for(let Y of J){if(Q.length>=$)break;if(Y.length===0)continue;if(Y.length===1){let X=Y[0]??"";if((_.get(X)??[]).includes(X))j$(z,Q,[X,X]);continue}let Z=$-Q.length,W=pJ(Y,_,Z);for(let X of W){if(Q.length>=$)break;j$(z,Q,X)}}return Q}var dJ=15000;function J$(_){_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}function C_(_,$){let J=$??"__cross__";if(_.graphCache&&_.graphCacheBuiltAt!==null){if(Date.now()-_.graphCacheBuiltAt>dJ)_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}if(_.graphCache&&_.graphCacheKey===J)return _.graphCache;let Q=new $$({relationRepo:_.relationRepo,project:$??_.defaultProject,additionalProjects:$?void 0:_.boundaries?.map((z)=>z.project)});return Q.build(),_.graphCache=Q,_.graphCacheKey=J,_.graphCacheBuiltAt=Date.now(),Q}function w0(_,$,J,Q=1e4){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{srcFilePath:$,type:"imports",project:J??_.defaultProject,limit:Q}}).filter((z)=>z.dstFilePath!==null).map((z)=>z.dstFilePath)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getDependencies failed",{cause:z})}}function D0(_,$,J,Q=1e4){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{dstFilePath:$,type:"imports",project:J??_.defaultProject,limit:Q}}).map((z)=>z.srcFilePath)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getDependents failed",{cause:z})}}async function u0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,J).getAffectedByChange($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getAffected failed",{cause:Q})}}async function I0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,$).hasCycle()}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: hasCycle failed",{cause:J})}}async function C0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,$).getAdjacencyList()}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: getImportGraph failed",{cause:J})}}async function N0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,J).getTransitiveDependencies($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getTransitiveDependencies failed",{cause:Q})}}async function A0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,J).getTransitiveDependents($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getTransitiveDependents failed",{cause:Q})}}async function g0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,$).getCyclePaths(J)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getCyclePaths failed",{cause:Q})}}async function q0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=C_(_,J);return{filePath:$,fanIn:Q.getDependents($).length,fanOut:Q.getDependencies($).length}}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getFanMetrics failed",{cause:Q})}}var aJ=30000,S0=15000,sJ=10;function rJ(_,$){return(J)=>{for(let Q of _.onFileChangedCallbacks)try{Q(J)}catch(z){_.logger.error("[Gildash] onFileChanged callback threw:",z)}if($.handleWatcherEvent?.(J),_.semanticLayer)if(J.eventType==="delete")try{_.semanticLayer.notifyFileDeleted(J.filePath)}catch(Q){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",Q);for(let z of _.onErrorCallbacks)try{z(Q instanceof V?Q:new V("semantic","semantic notifyFileDeleted failed",{cause:Q}))}catch{}}else _.readFileFn(J.filePath).then((Q)=>{try{_.semanticLayer?.notifyFileChanged(J.filePath,Q)}catch(z){_.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",z);for(let Y of _.onErrorCallbacks)try{Y(z instanceof V?z:new V("semantic","semantic notifyFileChanged failed",{cause:z}))}catch{}}}).catch((Q)=>{_.logger.error("[Gildash] failed to read file for semantic layer",J.filePath,Q);try{_.semanticLayer?.notifyFileDeleted(J.filePath)}catch(z){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",z)}})}}async function oJ(_){if(!_.semanticLayer)return;let $=_.fileRepo.getAllFiles(_.defaultProject);await Promise.all($.map(async(J)=>{try{let Q=m_.resolve(_.projectRoot,J.filePath),z=await _.readFileFn(Q);_.semanticLayer?.notifyFileChanged(Q,z)}catch{}}))}async function T0(_,$){let J=_.coordinatorFactory?_.coordinatorFactory():new I$({projectRoot:_.projectRoot,boundaries:_.boundaries,extensions:_.extensions,ignorePatterns:_.ignorePatterns,dbConnection:_.db,parseCache:_.parseCache,fileRepo:_.fileRepo,symbolRepo:_.symbolRepo,relationRepo:_.relationRepo,annotationRepo:_.annotationRepo??void 0,changelogRepo:_.changelogRepo??void 0,logger:_.logger});_.coordinator=J;for(let Q of _.onIndexedCallbacks)J.onIndexed(Q);if(J.onIndexed((Q)=>{let z=Q.changedFiles.length+Q.deletedFiles.length;if(_.graphCache&&z>0&&z<100){let Y=_.relationRepo;_.graphCache.patchFiles(Q.changedFiles,Q.deletedFiles,(Z)=>{return[_.defaultProject,..._.boundaries.map((X)=>X.project)].flatMap((X)=>Y.getByType(X,"imports").concat(Y.getByType(X,"type-references")).concat(Y.getByType(X,"re-exports"))).filter((X)=>X.dstFilePath!==null&&(X.srcFilePath===Z||X.dstFilePath===Z)).map((X)=>({srcFilePath:X.srcFilePath,dstFilePath:X.dstFilePath}))}),_.graphCacheBuiltAt=Date.now()}else J$(_)}),$.isWatchMode){let Q=_.watcherFactory?_.watcherFactory():new H$({projectRoot:_.projectRoot,ignorePatterns:_.ignorePatterns,extensions:_.extensions},void 0,_.logger);await Q.start(rJ(_,J)).then((z)=>{if(n_(z))throw z.data}),_.watcher=Q,_.timer=setInterval(()=>{_.updateHeartbeatFn(_.db,process.pid)},aJ)}await J.fullIndex(),await oJ(_)}function tJ(_,$){let J=["SIGTERM","SIGINT","beforeExit"];for(let Q of J){let z=()=>{$().catch((Y)=>_.logger.error("[Gildash] close error during signal",Q,Y))};if(Q==="beforeExit")process.on("beforeExit",z);else process.on(Q,z);_.signalHandlers.push([Q,z])}}async function R0(_){let{projectRoot:$,extensions:J=[".ts",".mts",".cts"],ignorePatterns:Q=["**/node_modules/**"],parseCacheCapacity:z=500,logger:Y=console,existsSyncFn:Z=cJ,dbConnectionFactory:W,watcherFactory:X,coordinatorFactory:H,repositoryFactory:O,acquireWatcherRoleFn:U=W0,releaseWatcherRoleFn:K=Y0,updateHeartbeatFn:u=Z0,discoverProjectsFn:L=i_,parseSourceFn:w=b_,extractSymbolsFn:T=T_,extractRelationsFn:F=s_,symbolSearchFn:m=N$,relationSearchFn:j=A$,patternSearchFn:P=g$,loadTsconfigPathsFn:r=v_,readFileFn:B=async(E)=>Bun.file(E).text(),unlinkFn:A=async(E)=>{await Bun.file(E).unlink()},watchMode:D,semantic:C,semanticLayerFactory:N}=_;if(!m_.isAbsolute($))throw new V("validation",`Gildash: projectRoot must be an absolute path, got: "${$}"`);if(!Z($))throw new V("validation",`Gildash: projectRoot does not exist: "${$}"`);let g=W?W():new Z$({projectRoot:$}),R=g.open();if(n_(R))throw R.data;try{let E=await L($),p=E[0]?.project??m_.basename($),d=O?O():(()=>{let t=g;return{fileRepo:new X$(t),symbolRepo:new O$(t),relationRepo:new V$(t),parseCache:new C$(z)}})(),a=O?null:g,M=a?new F$(a):null,q=a?new G$(a):null,S=D??!0,k=crypto.randomUUID(),f;if(S)f=await Promise.resolve(U(g,process.pid,{instanceId:k}));else f="owner";let I={projectRoot:$,extensions:J,ignorePatterns:Q,logger:Y,defaultProject:p,role:f,db:g,symbolRepo:d.symbolRepo,relationRepo:d.relationRepo,fileRepo:d.fileRepo,parseCache:d.parseCache,annotationRepo:M,changelogRepo:q,annotationSearchFn:B0,releaseWatcherRoleFn:K,parseSourceFn:w,extractSymbolsFn:T,extractRelationsFn:F,symbolSearchFn:m,relationSearchFn:j,patternSearchFn:P,readFileFn:B,unlinkFn:A,existsSyncFn:Z,acquireWatcherRoleFn:U,updateHeartbeatFn:u,watcherFactory:X,coordinatorFactory:H,instanceId:k,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:E,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(d_($),I.tsconfigPaths=await r($),C){let t=m_.join($,"tsconfig.json");try{if(N)I.semanticLayer=N(t);else{let v=_$.create(t);if(n_(v))throw v.data;I.semanticLayer=v}}catch(v){if(v instanceof V)throw v;throw new V("semantic","Gildash: semantic layer creation failed",{cause:v})}}if(f==="owner")await T0(I,{isWatchMode:S});else{let t=0,v=async()=>{try{let x=await Promise.resolve(I.acquireWatcherRoleFn(I.db,process.pid,{instanceId:I.instanceId}));if(t=0,x==="owner"){I.role="owner";for(let y of I.onRoleChangedCallbacks)try{y("owner")}catch(l){I.logger.error("[Gildash] onRoleChanged callback threw:",l)}clearInterval(I.timer),I.timer=null;try{await T0(I,{isWatchMode:!0})}catch(y){if(I.logger.error("[Gildash] owner promotion failed, reverting to reader",y),I.role="reader",I.timer!==null)clearInterval(I.timer),I.timer=null;if(I.watcher){let l=await I.watcher.close();if(n_(l))I.logger.error("[Gildash] watcher close error during promotion rollback",l.data);I.watcher=null}if(I.coordinator)await I.coordinator.shutdown().catch((l)=>I.logger.error("[Gildash] coordinator shutdown error during promotion rollback",l)),I.coordinator=null;try{I.releaseWatcherRoleFn(I.db,process.pid)}catch(l){I.logger.error("[Gildash] failed to release watcher role during promotion rollback",l)}I.timer=setInterval(v,S0)}}}catch(x){t++;let y=x instanceof V?x:new V("watcher","Gildash: healthcheck error",{cause:x});for(let l of I.onErrorCallbacks)try{l(y)}catch(K_){I.logger.error("[Gildash] onError callback threw:",K_)}if(I.logger.error("[Gildash] healthcheck error",x),t>=sJ)I.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(I.timer),I.timer=null,Q$(I).catch((l)=>I.logger.error("[Gildash] close error during healthcheck shutdown",l))}};I.timer=setInterval(v,S0)}if(S)tJ(I,()=>Q$(I));return I}catch(E){if(g.close(),E instanceof V)throw E;throw new V("store","Gildash: initialization failed",{cause:E})}}async function Q$(_,$){if(_.closed)return;_.closed=!0;let J=[];for(let[Q,z]of _.signalHandlers)if(Q==="beforeExit")process.off("beforeExit",z);else process.off(Q,z);if(_.signalHandlers=[],_.semanticLayer){try{_.semanticLayer.dispose()}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}_.semanticLayer=null}if(_.coordinator)try{await _.coordinator.shutdown()}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}if(_.watcher){let Q=await _.watcher.close();if(n_(Q))J.push(Q.data)}if(_.timer!==null)clearInterval(_.timer),_.timer=null;try{_.releaseWatcherRoleFn(_.db,process.pid)}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}try{_.db.close()}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}if($?.cleanup)for(let Q of["","-wal","-shm"])try{await _.unlinkFn(m_.join(_.projectRoot,L_,h_+Q))}catch{}if(J.length>0)throw new V("close","Gildash: one or more errors occurred during close()",{cause:J})}import{isErr as k0}from"@zipbul/result";function F0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");let z=_.parseSourceFn($,J,Q);if(k0(z))throw z.data;return _.parseCache.set($,z),z}async function G0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");let Q=new Map,z=[];return await Promise.all($.map(async(Y)=>{try{let Z=await _.readFileFn(Y),W=_.parseSourceFn(Y,Z,J);if(!k0(W))Q.set(Y,W);else z.push({filePath:Y,error:W.data})}catch(Z){z.push({filePath:Y,error:Z instanceof Error?Z:Error(String(Z))})}})),{parsed:Q,failures:z}}function j0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.parseCache.get($)}function E0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.extractSymbolsFn($)}function v0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.extractRelationsFn($.program,$.filePath,_.tsconfigPaths??void 0)}import b0 from"path";function y0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.symbolRepo.getStats($??_.defaultProject)}catch(J){if(J instanceof V)throw J;throw new V("store","Gildash: getStats failed",{cause:J})}}function E$(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: searchSymbols failed",{cause:J})}}function P0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: searchRelations failed",{cause:J})}}function f0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:void 0,query:$})}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: searchAllSymbols failed",{cause:J})}}function n0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:void 0,query:$})}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: searchAllRelations failed",{cause:J})}}function m0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.fileRepo.getAllFiles($??_.defaultProject)}catch(J){if(J instanceof V)throw J;throw new V("store","Gildash: listIndexedFiles failed",{cause:J})}}function x0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{srcFilePath:$,dstFilePath:$,limit:1e4}})}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getInternalRelations failed",{cause:Q})}}function h0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,Y=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:J,limit:1}});if(Y.length===0)return null;let Z=Y[0],W=Z.detail,X={...Z,members:W.members,jsDoc:W.jsDoc,parameters:W.parameters,returnType:W.returnType,heritage:W.heritage,decorators:W.decorators,typeParameters:W.typeParameters};if(_.semanticLayer)try{let H=b0.isAbsolute(J)?J:b0.resolve(_.projectRoot,J),O=_.semanticLayer.lineColumnToPosition(H,Z.span.start.line,Z.span.start.column);if(O!==null){let U=_.semanticLayer.findNamePosition(H,O,Z.name)??O,K=_.semanticLayer.collectTypeAt(H,U);if(K)X.resolvedType=K}}catch{}return X}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getFullSymbol failed",{cause:z})}}function p0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=J??_.defaultProject,z=_.fileRepo.getFile(Q,$);if(!z)throw new V("search",`Gildash: file '${$}' is not in the index`);let Y=_.symbolRepo.getFileSymbols(Q,$),Z=_.relationRepo.getOutgoing(Q,$);return{filePath:z.filePath,lineCount:z.lineCount??0,size:z.size,symbolCount:Y.length,exportedSymbolCount:Y.filter((W)=>W.isExported).length,relationCount:Z.length}}catch(Q){if(Q instanceof V)throw Q;throw new V("store","Gildash: getFileStats failed",{cause:Q})}}function i0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.fileRepo.getFile(J??_.defaultProject,$)}catch(Q){if(Q instanceof V)throw Q;throw new V("store","Gildash: getFileInfo failed",{cause:Q})}}function d0(_,$,J){return E$(_,{filePath:$,project:J??void 0,limit:1e4})}function l0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:J??_.defaultProject,query:{filePath:$,isExported:!0}}).map((Y)=>({name:Y.name,kind:Y.kind,parameters:Y.detail.parameters?`(${Y.detail.parameters.map((Z)=>`${Z.name}${Z.isOptional?"?":""}: ${Z.type??"unknown"}`).join(", ")})`:void 0,returnType:Y.detail.returnType??void 0,jsDoc:Y.detail.jsDoc?.description??void 0}));return{filePath:$,exports:z}}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getModuleInterface failed",{cause:Q})}}import h from"path";function x_(_,$,J,Q){let z=Q??_.defaultProject,Y=h.isAbsolute(J)?h.relative(_.projectRoot,J):J,Z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:Y,limit:1}});if(Z.length===0)return null;let W=Z[0],X=h.isAbsolute(J)?J:h.resolve(_.projectRoot,J),H=_.semanticLayer.lineColumnToPosition(X,W.span.start.line,W.span.start.column);if(H===null)return null;let O=_.semanticLayer.findNamePosition(X,H,W.name)??H;return{sym:W,position:O,absPath:X}}function c0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=x_(_,$,J,Q);if(!z)return null;return _.semanticLayer.collectTypeAt(z.absPath,z.position)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getResolvedType failed",{cause:z})}}function a0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=x_(_,$,J,Q);if(!z)throw new V("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findReferences(z.absPath,z.position)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getSemanticReferences failed",{cause:z})}}function s0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=x_(_,$,J,Q);if(!z)throw new V("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findImplementations(z.absPath,z.position)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getImplementations failed",{cause:z})}}function r0(_,$,J,Q,z,Y){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Z=x_(_,$,J,Y);if(!Z)throw new V("search",`Gildash: source symbol '${$}' not found in '${J}'`);let W=x_(_,Q,z,Y);if(!W)throw new V("search",`Gildash: target symbol '${Q}' not found in '${z}'`);return _.semanticLayer.isTypeAssignableTo(Z.absPath,Z.position,W.absPath,W.position)}catch(Z){if(Z instanceof V)throw Z;throw new V("semantic","Gildash: isTypeAssignableTo failed",{cause:Z})}}function o0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let J=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.collectFileTypes(J)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: getFileTypes failed",{cause:J})}}function t0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=h.isAbsolute($)?$:h.resolve(_.projectRoot,$),Y=_.semanticLayer.lineColumnToPosition(z,J,Q);if(Y===null)return null;return _.semanticLayer.collectTypeAt(z,Y)}catch(z){if(z instanceof V)throw z;throw new V("semantic","Gildash: getResolvedTypeAt failed",{cause:z})}}function e0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let J=h.isAbsolute($.source.filePath)?$.source.filePath:h.resolve(_.projectRoot,$.source.filePath),Q=h.isAbsolute($.target.filePath)?$.target.filePath:h.resolve(_.projectRoot,$.target.filePath),z=_.semanticLayer.lineColumnToPosition(J,$.source.line,$.source.column);if(z===null)return null;let Y=_.semanticLayer.lineColumnToPosition(Q,$.target.line,$.target.column);if(Y===null)return null;return _.semanticLayer.isTypeAssignableTo(J,z,Q,Y)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: isTypeAssignableToAt failed",{cause:J})}}function _1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{return _.semanticLayer.getModuleInterface($)}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: getSemanticModuleInterface failed",{cause:J})}}function $1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.getBaseTypes(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getBaseTypes failed",{cause:Q})}}function J1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.collectTypeAt(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getResolvedTypeAtPosition failed",{cause:Q})}}function Q1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.findReferences(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getSemanticReferencesAtPosition failed",{cause:Q})}}function z1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.findImplementations(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getImplementationsAtPosition failed",{cause:Q})}}function W1(_,$,J,Q,z){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Y=h.isAbsolute($)?$:h.resolve(_.projectRoot,$),Z=h.isAbsolute(Q)?Q:h.resolve(_.projectRoot,Q);return _.semanticLayer.isTypeAssignableTo(Y,J,Z,z)}catch(Y){if(Y instanceof V)throw Y;throw new V("semantic","Gildash: isTypeAssignableToAtPosition failed",{cause:Y})}}function Y1(_,$,J,Q,z){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Y=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToType(Y,J,Q,z)}catch(Y){if(Y instanceof V)throw Y;throw new V("semantic","Gildash: isTypeAssignableToType failed",{cause:Y})}}function Z1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.lineColumnToPosition(z,J,Q)}catch(z){if(z instanceof V)throw z;throw new V("semantic","Gildash: lineColumnToPosition failed",{cause:z})}}function X1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.findNamePosition(z,J,Q)}catch(z){if(z instanceof V)throw z;throw new V("semantic","Gildash: findNamePosition failed",{cause:z})}}function O1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.getSymbolNode(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getSymbolNode failed",{cause:Q})}}function V1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.getDiagnostics(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getSemanticDiagnostics failed",{cause:Q})}}function U1(_,$){let J=new Map(_.map((W)=>[`${W.name}::${W.filePath}`,W])),Q=new Map($.map((W)=>[`${W.name}::${W.filePath}`,W])),z=[],Y=[],Z=[];for(let[W,X]of Q){let H=J.get(W);if(!H)z.push(X);else if(H.fingerprint!==X.fingerprint)Z.push({before:H,after:X})}for(let[W,X]of J)if(!Q.has(W))Y.push(X);return{added:z,removed:Y,modified:Z}}function H1(_,$){if(_.onIndexedCallbacks.add($),!_.coordinator)return()=>{_.onIndexedCallbacks.delete($)};let J=_.coordinator.onIndexed($);return()=>{_.onIndexedCallbacks.delete($),J()}}async function M1(_){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.coordinator)throw new V("closed","Gildash: reindex() is not available for readers");try{let $=await _.coordinator.fullIndex();return J$(_),$}catch($){if($ instanceof V)throw $;throw new V("index","Gildash: reindex failed",{cause:$})}}function K1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");let z=Q??_.defaultProject,Y=new Set,Z=[],W=$,X=J;for(;;){let H=`${X}::${W}`;if(Y.has(H))return{originalName:W,originalFilePath:X,reExportChain:Z,circular:!0};Y.add(H);let O=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{type:"re-exports",srcFilePath:X,limit:500}}),U,K;for(let u of O){let L;if(u.metaJson)try{let T=JSON.parse(u.metaJson);if(Array.isArray(T.specifiers))L=T.specifiers}catch{}if(!L)continue;let w=L.find((T)=>T.exported===W);if(!w)continue;U=u.dstFilePath??void 0,K=w.local;break}if(!U||!K)return{originalName:W,originalFilePath:X,reExportChain:Z,circular:!1};Z.push({filePath:X,exportedAs:W}),X=U,W=K}}function L1(_,$){return _.onFileChangedCallbacks.add($),()=>{_.onFileChangedCallbacks.delete($)}}function B1(_,$){return _.onErrorCallbacks.add($),()=>{_.onErrorCallbacks.delete($)}}function w1(_,$){return _.onRoleChangedCallbacks.add($),()=>{_.onRoleChangedCallbacks.delete($)}}async function D1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=J?.project??_.defaultProject,z=J?.filePaths?J.filePaths:_.fileRepo.getAllFiles(Q).map((Y)=>Y.filePath);return await _.patternSearchFn({pattern:$,filePaths:z})}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: findPattern failed",{cause:Q})}}async function u1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,Y=new Set,Z=(W,X,H)=>{let O=`${W}::${X}`;if(Y.has(O))return{symbolName:W,filePath:X,kind:H,children:[]};Y.add(O);let u=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{srcFilePath:X,srcSymbolName:W,limit:1000}}).filter((L)=>L.type==="extends"||L.type==="implements").filter((L)=>L.dstSymbolName!=null&&L.dstFilePath!=null).map((L)=>Z(L.dstSymbolName,L.dstFilePath,L.type));return{symbolName:W,filePath:X,kind:H,children:u}};return Z($,J)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getHeritageChain failed",{cause:z})}}function I1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.annotationRepo||!_.annotationSearchFn)return[];return _.annotationSearchFn({annotationRepo:_.annotationRepo,project:$.project??_.defaultProject,query:$})}function C1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.changelogRepo)return[];let Q=$ instanceof Date?$.toISOString():$,z=J?.project??_.defaultProject,Y=J?.limit??1000;return _.changelogRepo.getSince({project:z,since:Q,symbolName:J?.symbolName,changeTypes:J?.changeTypes,filePath:J?.filePath,includeFullIndex:J?.includeFullIndex,indexRunId:J?.indexRunId,afterId:J?.afterId,limit:Y}).map((W)=>({changeType:W.changeType,symbolName:W.symbolName,symbolKind:W.symbolKind,filePath:W.filePath,oldName:W.oldName,oldFilePath:W.oldFilePath,fingerprint:W.fingerprint,changedAt:W.changedAt,isFullIndex:W.isFullIndex===1,indexRunId:W.indexRunId}))}function N1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.changelogRepo)return 0;let J=$ instanceof Date?$.toISOString():$,Q=0,z=[_.defaultProject,..._.boundaries.map((Z)=>Z.project)],Y=[...new Set(z)];for(let Z of Y)Q+=_.changelogRepo.pruneOlderThan(Z,J);return Q}class v${_ctx;get projectRoot(){return this._ctx.projectRoot}get role(){return this._ctx.role}get projects(){return[...this._ctx.boundaries]}constructor(_){this._ctx=_}static async open(_){let $=await R0(_);return new v$($)}async close(_){return Q$(this._ctx,_)}parseSource(_,$,J){return F0(this._ctx,_,$,J)}async batchParse(_,$){return G0(this._ctx,_,$)}getParsedAst(_){return j0(this._ctx,_)}extractSymbols(_){return E0(this._ctx,_)}extractRelations(_){return v0(this._ctx,_)}getStats(_){return y0(this._ctx,_)}searchSymbols(_){return E$(this._ctx,_)}searchRelations(_){return P0(this._ctx,_)}searchAllSymbols(_){return f0(this._ctx,_)}searchAllRelations(_){return n0(this._ctx,_)}listIndexedFiles(_){return m0(this._ctx,_)}getInternalRelations(_,$){return x0(this._ctx,_,$)}getFullSymbol(_,$,J){return h0(this._ctx,_,$,J)}getFileStats(_,$){return p0(this._ctx,_,$)}getFileInfo(_,$){return i0(this._ctx,_,$)}getSymbolsByFile(_,$){return d0(this._ctx,_,$)}getModuleInterface(_,$){return l0(this._ctx,_,$)}getDependencies(_,$,J=1e4){return w0(this._ctx,_,$,J)}getDependents(_,$,J=1e4){return D0(this._ctx,_,$,J)}async getAffected(_,$){return u0(this._ctx,_,$)}async hasCycle(_){return I0(this._ctx,_)}async getImportGraph(_){return C0(this._ctx,_)}async getTransitiveDependencies(_,$){return N0(this._ctx,_,$)}async getTransitiveDependents(_,$){return A0(this._ctx,_,$)}async getCyclePaths(_,$){return g0(this._ctx,_,$)}async getFanMetrics(_,$){return q0(this._ctx,_,$)}getResolvedType(_,$,J){return c0(this._ctx,_,$,J)}getSemanticReferences(_,$,J){return a0(this._ctx,_,$,J)}getImplementations(_,$,J){return s0(this._ctx,_,$,J)}isTypeAssignableTo(_,$,J,Q,z){return r0(this._ctx,_,$,J,Q,z)}getSemanticModuleInterface(_){return _1(this._ctx,_)}getFileTypes(_){return o0(this._ctx,_)}getResolvedTypeAt(_,$,J){return t0(this._ctx,_,$,J)}isTypeAssignableToAt(_){return e0(this._ctx,_)}getResolvedTypeAtPosition(_,$){return J1(this._ctx,_,$)}getSemanticReferencesAtPosition(_,$){return Q1(this._ctx,_,$)}getImplementationsAtPosition(_,$){return z1(this._ctx,_,$)}isTypeAssignableToAtPosition(_,$,J,Q){return W1(this._ctx,_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return Y1(this._ctx,_,$,J,Q)}lineColumnToPosition(_,$,J){return Z1(this._ctx,_,$,J)}findNamePosition(_,$,J){return X1(this._ctx,_,$,J)}getSymbolNode(_,$){return O1(this._ctx,_,$)}getBaseTypes(_,$){return $1(this._ctx,_,$)}getSemanticDiagnostics(_,$){return V1(this._ctx,_,$)}diffSymbols(_,$){return U1(_,$)}onIndexed(_){return H1(this._ctx,_)}async reindex(){return M1(this._ctx)}resolveSymbol(_,$,J){return K1(this._ctx,_,$,J)}async findPattern(_,$){return D1(this._ctx,_,$)}async getHeritageChain(_,$,J){return u1(this._ctx,_,$,J)}onFileChanged(_){return L1(this._ctx,_)}onError(_){return B1(this._ctx,_)}onRoleChanged(_){return w1(this._ctx,_)}searchAnnotations(_){return I1(this._ctx,_)}getSymbolChanges(_,$){return C1(this._ctx,_,$)}pruneChangelog(_){return N1(this._ctx,_)}}import{Visitor as e4,visitorKeys as _3}from"oxc-parser";export{_3 as visitorKeys,N$ as symbolSearch,A$ as relationSearch,g$ as patternSearch,X_ as getLineColumn,y_ as buildLineOffsets,e4 as Visitor,V as GildashError,v$ as Gildash,$$ as DependencyGraph};
|
|
9
|
+
`)).join("; ");return q$(new V("semantic",`tsconfig compile error: ${K}`))}}let H=new X0(X.fileNames,X.options,z,Q),O=U_.createLanguageService(H);return new o_(O,H)}get isDisposed(){return this.#J}getProgram(){this.#z();let _=this.#_.getProgram();if(!_)throw Error("TscProgram: LanguageService returned null Program");return _}getChecker(){return this.#z(),this.getProgram().getTypeChecker()}getLanguageService(){return this.#z(),this.#_}notifyFileChanged(_,$){if(this.#J)return;this.#$.updateFile(_,$)}removeFile(_){if(this.#J)return;this.#$.removeFile(_)}dispose(){if(this.#J)return;this.#J=!0,this.#_.dispose()}#z(){if(this.#J)throw Error("TscProgram is disposed")}}class X0{#_;#$;#J;#z;#Q=new Map;constructor(_,$,J,Q){this.#_=new Set(_),this.#$=$,this.#J=J,this.#z=Q}updateFile(_,$){let J=this.#Q.get(_);if(J)J.version+=1,J.content=$;else this.#Q.set(_,{version:1,content:$})}removeFile(_){this.#Q.delete(_),this.#_.delete(_)}getScriptFileNames(){let _=[...this.#Q.keys()];return[...[...this.#_].filter((J)=>!this.#Q.has(J)),..._]}getScriptVersion(_){let $=this.#Q.get(_);return $?String($.version):"0"}getScriptSnapshot(_){let $=this.#Q.get(_);if($)return U_.ScriptSnapshot.fromString($.content);let J=this.#z(_);if(J!==void 0)return U_.ScriptSnapshot.fromString(J);return}getCurrentDirectory(){return this.#J}getCompilationSettings(){return this.#$}getDefaultLibFileName(_){return U_.getDefaultLibFilePath(_)}fileExists(_){if(this.#Q.has(_))return!0;return this.#z(_)!==void 0}readFile(_){let $=this.#Q.get(_);if($)return $.content;return this.#z(_)}}import s from"typescript";import qJ from"typescript";function Y_(_,$){if($<0||$>=_.getEnd())return;function J(Q){let z=Q.getStart(_,!1),Y=Q.getEnd();if($<z||$>=Y)return;let Z;return qJ.forEachChild(Q,(W)=>{if(!Z)Z=J(W)}),Z??Q}return J(_)}var t_=8;function SJ(_){return!!(_.flags&s.TypeFlags.Object)&&!!(_.objectFlags&s.ObjectFlags.Reference)}function H_(_,$,J=0){let Q=_.typeToString($),z=$.flags,Y=!!(z&s.TypeFlags.Union),Z=!!(z&s.TypeFlags.Intersection),W;if(J<t_&&SJ($)){let K=_.getTypeArguments($);if(K.length>0)W=K}let X=!!(z&s.TypeFlags.TypeParameter)||W!==void 0&&W.length>0,H;if(Y&&J<t_)H=$.types.map((K)=>H_(_,K,J+1));else if(Z&&J<t_)H=$.types.map((K)=>H_(_,K,J+1));let O;if(W&&W.length>0)O=W.map((K)=>H_(_,K,J+1));let U;if(J<t_&&!!(z&s.TypeFlags.Object)&&!Y&&!Z){let K=_.getPropertiesOfType($);if(K.length>0&&K.length<=50){let u=$.symbol?.declarations?.[0];U=[];for(let L of K){let w=L.declarations?.[0]??u;if(!w)continue;try{let T=_.getTypeOfSymbolAtLocation(L,w);U.push({name:L.getName(),type:H_(_,T,J+1)})}catch{}}if(U.length===0)U=void 0}}return{text:Q,flags:z,isUnion:Y,isIntersection:Z,isGeneric:X,members:H,typeArguments:O,properties:U}}function TJ(_){return s.isFunctionDeclaration(_)||s.isVariableDeclaration(_)||s.isClassDeclaration(_)||s.isInterfaceDeclaration(_)||s.isTypeAliasDeclaration(_)||s.isEnumDeclaration(_)||s.isMethodDeclaration(_)||s.isPropertyDeclaration(_)||s.isPropertySignature(_)||s.isMethodSignature(_)}class S${program;constructor(_){this.program=_}collectAt(_,$){let J=this.program.getProgram(),Q=this.program.getChecker();if($<0)return null;let z=J.getSourceFile(_);if(!z)return null;if($>=z.getEnd())return null;let Y=Y_(z,$);if(!Y)return null;if(!s.isIdentifier(Y)&&!s.isTypeNode(Y))return null;try{let Z=Q.getTypeAtLocation(Y);return H_(Q,Z)}catch{return null}}isAssignableTo(_,$,J,Q){let z=this.program.getChecker(),Y=this.program.getProgram(),Z=Y.getSourceFile(_);if(!Z)return null;let W=Y_(Z,$);if(!W||!s.isIdentifier(W))return null;let X=Y.getSourceFile(J);if(!X)return null;let H=Y_(X,Q);if(!H||!s.isIdentifier(H))return null;try{let O=z.getTypeAtLocation(W),U=z.getTypeAtLocation(H);return z.isTypeAssignableTo(O,U)}catch{return null}}isAssignableToType(_,$,J,Q){let z=this.program.getChecker(),Z=this.program.getProgram().getSourceFile(_);if(!Z)return null;let W=Y_(Z,$);if(!W||!s.isIdentifier(W)&&!s.isTypeNode(W))return null;let X=`${_}.__gildash_probe__.ts`,H=`declare const __gildash_probe__: ${J};`;this.program.notifyFileChanged(X,H);try{let O=z.getTypeAtLocation(W),K=this.program.getProgram().getSourceFile(X);if(!K)return null;let u=this.program.getChecker(),L=K.statements[0];if(!L||!s.isVariableStatement(L))return null;let w=L.declarationList.declarations[0];if(!w)return null;let T=u.getTypeAtLocation(w.name);if(Q?.anyConstituent&&O.isUnion())return O.types.some((F)=>u.isTypeAssignableTo(F,T));return u.isTypeAssignableTo(O,T)}catch{return null}finally{this.program.removeFile(X)}}collectFile(_){let $=new Map,J=this.program.getProgram(),Q=this.program.getChecker(),z=J.getSourceFile(_);if(!z)return $;function Y(Z){if(TJ(Z)&&Z.name&&s.isIdentifier(Z.name)){let W=Z.name;try{let X=Q.getTypeAtLocation(W),H=W.getStart(z);$.set(H,H_(Q,X))}catch{}}s.forEachChild(Z,Y)}return Y(z),$}}import M_ from"typescript";var RJ=1000,kJ=1;function FJ(_){let $=_.declarations?.[0],J=$?.getSourceFile(),Q=$?M_.getNameOfDeclaration($):void 0;return{name:_.getName(),filePath:J?.fileName??"",position:Q?.getStart(J,!1)??$?.getStart(J,!1)??0}}function e_(_,$=0,J){let Q=_.declarations?.[0],z=Q?.getSourceFile(),Y=Q?M_.getNameOfDeclaration(Q):void 0,Z=z?.fileName??"",W=Y?.getStart(z,!1)??Q?.getStart(z,!1)??0,X={name:_.getName(),filePath:Z,position:W},H=_;if(H.parent)X.parent=FJ(H.parent);let O=J&&!!(_.flags&M_.SymbolFlags.Alias)?J.getAliasedSymbol(_):_;if($<kJ){let U=O.flags,K=!!(U&M_.SymbolFlags.Enum),u=!!(U&(M_.SymbolFlags.NamespaceModule|M_.SymbolFlags.ValueModule)),L=!!(U&(M_.SymbolFlags.Class|M_.SymbolFlags.Interface));if(K&&O.exports&&O.exports.size>0){let w=[];O.exports.forEach((T)=>{w.push(e_(T,$+1,J))}),X.members=w}else if(L&&O.members&&O.members.size>0){let w=[];O.members.forEach((T)=>{w.push(e_(T,$+1,J))}),X.members=w}if(u&&O.exports&&O.exports.size>0){let w=[];O.exports.forEach((T)=>{w.push(e_(T,$+1,J))}),X.exports=w}}return X}class T${#_;#$;#J=new Map;constructor(_,$=RJ){this.#_=_,this.#$=new P_($)}get(_,$){if(this.#_.isDisposed)return null;let J=`${_}:${$}`,Q=this.#$.get(J);if(Q!==void 0)return Q;let Y=this.#_.getProgram().getSourceFile(_);if(!Y)return null;let Z=Y_(Y,$);if(!Z||!M_.isIdentifier(Z))return null;let W=this.#_.getChecker(),X=W.getSymbolAtLocation(Z);if(!X)return null;let H=e_(X,0,W);this.#$.set(J,H);let O=this.#J.get(_);if(!O)O=new Set,this.#J.set(_,O);return O.add(J),H}invalidate(_){let $=this.#J.get(_);if($){for(let J of $)this.#$.delete(J);this.#J.delete(_)}}clear(){this.#$.clear(),this.#J.clear()}}import GJ from"typescript";class R${#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=Y_(Q,$);if(!z||!GJ.isIdentifier(z))return[];let Z=this.#_.getLanguageService().findReferences(_,$);if(!Z||Z.length===0)return[];let W=[];for(let X of Z)for(let H of X.references){let O=J.getSourceFile(H.fileName);if(!O)continue;let{line:U,character:K}=O.getLineAndCharacterOfPosition(H.textSpan.start);W.push({filePath:H.fileName,position:H.textSpan.start,line:U+1,column:K,isDefinition:H.isDefinition??!1,isWrite:H.isWriteAccess??!1})}return W}}import i from"typescript";function jJ(_,$){let J=Y_(_,$);if(!J)return;if(O0(J))return J;let Q=J.parent;for(let z=0;z<5&&Q;z++){if(O0(Q))return Q;Q=Q.parent}return J}function O0(_){return i.isClassDeclaration(_)||i.isClassExpression(_)||i.isFunctionDeclaration(_)||i.isFunctionExpression(_)||i.isArrowFunction(_)||i.isVariableDeclaration(_)||i.isObjectLiteralExpression(_)}function V0(_){if(i.isClassDeclaration(_)||i.isClassExpression(_))return"class";if(i.isFunctionDeclaration(_)||i.isFunctionExpression(_)||i.isArrowFunction(_))return"function";if(i.isObjectLiteralExpression(_))return"object";if(i.isVariableDeclaration(_)&&_.initializer)return V0(_.initializer);return"class"}function EJ(_,$){if(i.isClassDeclaration(_)||i.isFunctionDeclaration(_))return _.name?.getText($)??"";if(i.isClassExpression(_))return _.name?.getText($)??"";if(i.isVariableDeclaration(_)&&i.isIdentifier(_.name))return _.name.getText($);if(i.isFunctionExpression(_))return _.name?.getText($)??"";if(i.isArrowFunction(_)&&_.parent&&i.isVariableDeclaration(_.parent)){if(i.isIdentifier(_.parent.name))return _.parent.name.getText($)}if(i.isObjectLiteralExpression(_)&&_.parent&&i.isVariableDeclaration(_.parent)){if(i.isIdentifier(_.parent.name))return _.parent.name.getText($)}return""}function vJ(_){if(!i.isClassDeclaration(_)&&!i.isClassExpression(_))return!1;let $=_.heritageClauses;if(!$)return!1;return $.some((J)=>J.token===i.SyntaxKind.ImplementsKeyword)}class k${#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=Y_(Q,$);if(!z||!i.isIdentifier(z))return[];let Z=this.#_.getLanguageService().getImplementationAtPosition(_,$);if(!Z||Z.length===0)return[];let W=[];for(let X of Z){if(X.kind===i.ScriptElementKind.interfaceElement||X.kind===i.ScriptElementKind.typeElement)continue;let H=J.getSourceFile(X.fileName);if(!H)continue;let O=jJ(H,X.textSpan.start);if(!O)continue;let U=V0(O),K=EJ(O,H),u=vJ(O);W.push({filePath:X.fileName,symbolName:K,position:X.textSpan.start,kind:U,isExplicit:u})}return W}}function yJ(_){if(J_.isFunctionDeclaration(_))return"function";if(J_.isClassDeclaration(_))return"class";if(J_.isInterfaceDeclaration(_))return"interface";if(J_.isTypeAliasDeclaration(_))return"type";if(J_.isEnumDeclaration(_))return"enum";if(J_.isVariableDeclaration(_))return"const";if(J_.isVariableStatement(_))return"const";return"unknown"}function U0(_){if(_>=97&&_<=122)return!0;if(_>=65&&_<=90)return!0;if(_>=48&&_<=57)return!0;if(_===95||_===36)return!0;return!1}class _${#_;#$;#J;#z;#Q;#Y=!1;constructor(_,$,J,Q,z){this.#_=_,this.#$=$,this.#J=J,this.#z=Q,this.#Q=z}static create(_,$={}){let J=o_.create(_,{readConfigFile:$.readConfigFile,resolveNonTrackedFile:$.resolveNonTrackedFile});if(bJ(J))return J;let Q=J,z=$.typeCollector??new S$(Q),Y=$.symbolGraph??new T$(Q),Z=$.referenceResolver??new R$(Q),W=$.implementationFinder??new k$(Q);return new _$(Q,z,Y,Z,W)}get isDisposed(){return this.#Y}collectTypeAt(_,$){return this.#W(),this.#$.collectAt(_,$)}collectFileTypes(_){return this.#W(),this.#$.collectFile(_)}findReferences(_,$){return this.#W(),this.#z.findAt(_,$)}findImplementations(_,$){return this.#W(),this.#Q.findAt(_,$)}isTypeAssignableTo(_,$,J,Q){return this.#W(),this.#$.isAssignableTo(_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return this.#W(),this.#$.isAssignableToType(_,$,J,Q)}getSymbolNode(_,$){return this.#W(),this.#J.get(_,$)}getBaseTypes(_,$){this.#W();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let z=Y_(Q,$);if(!z)return null;let Y=this.#_.getChecker(),Z=Y.getTypeAtLocation(z);if(!(Z.flags&J_.TypeFlags.Object)||!(Z.objectFlags&J_.ObjectFlags.ClassOrInterface))return null;let W=Y.getBaseTypes(Z);if(!W||W.length===0)return[];return W.map((X)=>H_(Y,X))}getModuleInterface(_){this.#W();let $=[],Q=this.#_.getProgram().getSourceFile(_);if(!Q)return{filePath:_,exports:$};let z=this.#_.getChecker(),Y=z.getSymbolAtLocation(Q);if(Y){let Z=z.getExportsOfModule(Y);for(let W of Z){let X=W.getName(),H=W.declarations?.[0],O="unknown";if(H){if(O=yJ(H),O==="unknown"&&J_.isExportAssignment(H))O="const"}let U=null;try{let K=z.getTypeOfSymbolAtLocation(W,H??Q);U=H_(z,K)}catch{}$.push({name:X,kind:O,resolvedType:U})}}return{filePath:_,exports:$}}notifyFileChanged(_,$){if(this.#Y)return;this.#_.notifyFileChanged(_,$),this.#J.invalidate(_)}notifyFileDeleted(_){if(this.#Y)return;this.#_.removeFile(_),this.#J.invalidate(_)}lineColumnToPosition(_,$,J){this.#W();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;try{return J_.getPositionOfLineAndCharacter(Q,$-1,J)}catch{return null}}findNamePosition(_,$,J){this.#W();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let z=Q.getFullText(),Y=$;while(Y<z.length){let Z=z.indexOf(J,Y);if(Z<0)return null;let W=Z>0?z.charCodeAt(Z-1):32,X=Z+J.length<z.length?z.charCodeAt(Z+J.length):32;if(!U0(W)&&!U0(X))return Z;Y=Z+1}return null}getDiagnostics(_,$){this.#W();let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z={[J_.DiagnosticCategory.Error]:"error",[J_.DiagnosticCategory.Warning]:"warning",[J_.DiagnosticCategory.Suggestion]:"suggestion",[J_.DiagnosticCategory.Message]:"suggestion"};return(($?.preEmit)?J_.getPreEmitDiagnostics(J,Q):J.getSemanticDiagnostics(Q)).map((Z)=>{let W=1,X=0;if(Z.file&&Z.start!==void 0){let H=J_.getLineAndCharacterOfPosition(Z.file,Z.start);W=H.line+1,X=H.character}return{filePath:Z.file?.fileName??_,line:W,column:X,message:J_.flattenDiagnosticMessageText(Z.messageText,`
|
|
10
|
+
`),code:Z.code,category:z[Z.category]??"error"}})}dispose(){if(this.#Y)return;this.#Y=!0,this.#_.dispose(),this.#J.clear()}#W(){if(this.#Y)throw Error("SemanticLayer is disposed")}}import{eq as I_,and as H0,sql as PJ}from"drizzle-orm";var M0=80;class F${db;constructor(_){this.db=_}insertBatch(_,$,J){if(!J.length)return;let Q=J.map((z)=>({project:_,filePath:$,tag:z.tag,value:z.value,source:z.source,symbolName:z.symbolName,startLine:z.startLine,startColumn:z.startColumn,endLine:z.endLine,endColumn:z.endColumn,indexedAt:z.indexedAt}));for(let z=0;z<Q.length;z+=M0)this.db.drizzleDb.insert(Z_).values(Q.slice(z,z+M0)).run()}deleteFileAnnotations(_,$){this.db.drizzleDb.delete(Z_).where(H0(I_(Z_.project,_),I_(Z_.filePath,$))).run()}search(_){let $=this.db.drizzleDb.select().from(Z_).where(H0(_.project?I_(Z_.project,_.project):void 0,_.tag?I_(Z_.tag,_.tag):void 0,_.filePath?I_(Z_.filePath,_.filePath):void 0,_.symbolName?I_(Z_.symbolName,_.symbolName):void 0,_.source?I_(Z_.source,_.source):void 0,_.ftsQuery?PJ`${Z_.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${_.ftsQuery})`:void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}}import{eq as k_,and as K0,sql as f_,gt as fJ,gte as nJ}from"drizzle-orm";var L0=80;class G${db;constructor(_){this.db=_}insertBatch(_){if(!_.length)return;let $=_.map((J)=>({project:J.project,changeType:J.changeType,symbolName:J.symbolName,symbolKind:J.symbolKind,filePath:J.filePath,oldName:J.oldName,oldFilePath:J.oldFilePath,fingerprint:J.fingerprint,changedAt:J.changedAt,isFullIndex:J.isFullIndex,indexRunId:J.indexRunId}));for(let J=0;J<$.length;J+=L0)this.db.drizzleDb.insert(Q_).values($.slice(J,J+L0)).run()}getSince(_){return this.db.drizzleDb.select().from(Q_).where(K0(k_(Q_.project,_.project),nJ(Q_.changedAt,_.since),_.symbolName?k_(Q_.symbolName,_.symbolName):void 0,_.changeTypes?.length?f_`${Q_.changeType} IN (${f_.join(_.changeTypes.map(($)=>f_`${$}`),f_`, `)})`:void 0,_.filePath?k_(Q_.filePath,_.filePath):void 0,_.includeFullIndex?void 0:k_(Q_.isFullIndex,0),_.indexRunId?k_(Q_.indexRunId,_.indexRunId):void 0,_.afterId?fJ(Q_.id,_.afterId):void 0)).orderBy(Q_.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete(Q_).where(K0(k_(Q_.project,_),f_`${Q_.changedAt} < ${$}`)).run().changes}}function B0(_){let{annotationRepo:$,project:J,query:Q}=_,z=Q.project??J,Y;if(Q.text){let W=g_(Q.text);if(W)Y=W}return $.search({project:z,tag:Q.tag,filePath:Q.filePath,symbolName:Q.symbolName,source:Q.source,ftsQuery:Y,limit:Q.limit}).map((W)=>({tag:W.tag,value:W.value,source:W.source,filePath:W.filePath,symbolName:W.symbolName,span:{start:{line:W.startLine,column:W.startColumn},end:{line:W.endLine,column:W.endColumn}}}))}class $${options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(_){this.options=_}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let $=[this.options.project,...this.options.additionalProjects??[]].flatMap((J)=>[...this.options.relationRepo.getByType(J,"imports"),...this.options.relationRepo.getByType(J,"type-references"),...this.options.relationRepo.getByType(J,"re-exports")]);for(let J of $){let{srcFilePath:Q,dstFilePath:z}=J;if(z===null)continue;if(!this.adjacencyList.has(Q))this.adjacencyList.set(Q,new Set);if(this.adjacencyList.get(Q).add(z),!this.adjacencyList.has(z))this.adjacencyList.set(z,new Set);if(!this.reverseAdjacencyList.has(z))this.reverseAdjacencyList.set(z,new Set);this.reverseAdjacencyList.get(z).add(Q)}}patchFiles(_,$,J){let Q=new Set([..._,...$]);for(let z of Q){let Y=this.adjacencyList.get(z);if(Y){for(let W of Y)this.reverseAdjacencyList.get(W)?.delete(z);Y.clear()}let Z=this.reverseAdjacencyList.get(z);if(Z){for(let W of Z)this.adjacencyList.get(W)?.delete(z);Z.clear()}}for(let z of $)this.adjacencyList.delete(z),this.reverseAdjacencyList.delete(z);for(let z of _){let Y=J(z);for(let Z of Y){if(!this.adjacencyList.has(Z.srcFilePath))this.adjacencyList.set(Z.srcFilePath,new Set);if(this.adjacencyList.get(Z.srcFilePath).add(Z.dstFilePath),!this.adjacencyList.has(Z.dstFilePath))this.adjacencyList.set(Z.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(Z.dstFilePath))this.reverseAdjacencyList.set(Z.dstFilePath,new Set);this.reverseAdjacencyList.get(Z.dstFilePath).add(Z.srcFilePath)}}}getDependencies(_){return Array.from(this.adjacencyList.get(_)??[])}getDependents(_){return Array.from(this.reverseAdjacencyList.get(_)??[])}getTransitiveDependents(_){let $=new Set,J=[_];while(J.length>0){let Q=J.shift();for(let z of this.reverseAdjacencyList.get(Q)??[])if(!$.has(z))$.add(z),J.push(z)}return Array.from($)}hasCycle(){let _=new Set,$=new Set;for(let J of this.adjacencyList.keys()){if(_.has(J))continue;let Q=[{node:J,entered:!1}];while(Q.length>0){let z=Q.pop();if(z.entered){$.delete(z.node);continue}if($.has(z.node))return!0;if(_.has(z.node))continue;_.add(z.node),$.add(z.node),Q.push({node:z.node,entered:!0});for(let Y of this.adjacencyList.get(z.node)??[]){if($.has(Y))return!0;if(!_.has(Y))Q.push({node:Y,entered:!1})}}}return!1}getAffectedByChange(_){let $=new Set;for(let J of _)for(let Q of this.getTransitiveDependents(J))$.add(Q);return Array.from($)}getAdjacencyList(){let _=new Map;for(let[$,J]of this.adjacencyList)_.set($,Array.from(J));return _}getTransitiveDependencies(_){let $=new Set,J=[_];while(J.length>0){let Q=J.shift();for(let z of this.adjacencyList.get(Q)??[])if(!$.has(z))$.add(z),J.push(z)}return Array.from($)}getCyclePaths(_){let $=_?.maxCycles??1/0;if($<=0)return[];let J=new Map;for(let[Q,z]of this.adjacencyList)J.set(Q,Array.from(z));return iJ(J,$)}}var mJ=(_,$)=>_.localeCompare($);function xJ(_){let $=_.length>1&&_[0]===_[_.length-1]?_.slice(0,-1):[..._];if($.length===0)return[];let J=$;for(let Q=1;Q<$.length;Q++){let z=$.slice(Q).concat($.slice(0,Q));if(z.join("::")<J.join("::"))J=z}return[...J]}function j$(_,$,J){let Q=xJ(J);if(Q.length===0)return!1;let z=Q.join("->");if(_.has(z))return!1;return _.add(z),$.push(Q),!0}function hJ(_){let $=0,J=[],Q=new Set,z=new Map,Y=new Map,Z=[],W=(X)=>{z.set(X,$),Y.set(X,$),$+=1,J.push(X),Q.add(X);for(let H of _.get(X)??[])if(!z.has(H))W(H),Y.set(X,Math.min(Y.get(X)??0,Y.get(H)??0));else if(Q.has(H))Y.set(X,Math.min(Y.get(X)??0,z.get(H)??0));if(Y.get(X)===z.get(X)){let H=[],O="";do O=J.pop()??"",Q.delete(O),H.push(O);while(O!==X&&J.length>0);Z.push(H)}};for(let X of _.keys())if(!z.has(X))W(X);return{components:Z}}function pJ(_,$,J){let Q=[],z=new Set,Y=[..._].sort(mJ),Z=(W,X,H)=>{X.delete(W);let O=H.get(W);if(!O)return;for(let U of O)if(X.has(U))Z(U,X,H);O.clear()};for(let W=0;W<Y.length&&Q.length<J;W++){let X=Y[W]??"",H=new Set(Y.slice(W)),O=new Set,U=new Map,K=[],u=(w)=>($.get(w)??[]).filter((T)=>H.has(T)),L=(w)=>{if(Q.length>=J)return!0;let T=!1;K.push(w),O.add(w);for(let F of u(w)){if(Q.length>=J)break;if(F===X)j$(z,Q,K.concat(X)),T=!0;else if(!O.has(F)){if(L(F))T=!0}}if(T)Z(w,O,U);else for(let F of u(w)){let m=U.get(F)??new Set;m.add(w),U.set(F,m)}return K.pop(),T};L(X)}return Q}function iJ(_,$){let{components:J}=hJ(_),Q=[],z=new Set;for(let Y of J){if(Q.length>=$)break;if(Y.length===0)continue;if(Y.length===1){let X=Y[0]??"";if((_.get(X)??[]).includes(X))j$(z,Q,[X,X]);continue}let Z=$-Q.length,W=pJ(Y,_,Z);for(let X of W){if(Q.length>=$)break;j$(z,Q,X)}}return Q}var dJ=15000;function J$(_){_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}function C_(_,$){let J=$??"__cross__";if(_.graphCache&&_.graphCacheBuiltAt!==null){if(Date.now()-_.graphCacheBuiltAt>dJ)_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}if(_.graphCache&&_.graphCacheKey===J)return _.graphCache;let Q=new $$({relationRepo:_.relationRepo,project:$??_.defaultProject,additionalProjects:$?void 0:_.boundaries?.map((z)=>z.project)});return Q.build(),_.graphCache=Q,_.graphCacheKey=J,_.graphCacheBuiltAt=Date.now(),Q}function w0(_,$,J,Q=1e4){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{srcFilePath:$,type:"imports",project:J??_.defaultProject,limit:Q}}).filter((z)=>z.dstFilePath!==null).map((z)=>z.dstFilePath)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getDependencies failed",{cause:z})}}function D0(_,$,J,Q=1e4){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{dstFilePath:$,type:"imports",project:J??_.defaultProject,limit:Q}}).map((z)=>z.srcFilePath)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getDependents failed",{cause:z})}}async function u0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,J).getAffectedByChange($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getAffected failed",{cause:Q})}}async function I0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,$).hasCycle()}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: hasCycle failed",{cause:J})}}async function C0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,$).getAdjacencyList()}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: getImportGraph failed",{cause:J})}}async function N0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,J).getTransitiveDependencies($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getTransitiveDependencies failed",{cause:Q})}}async function A0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,J).getTransitiveDependents($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getTransitiveDependents failed",{cause:Q})}}async function g0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return C_(_,$).getCyclePaths(J)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getCyclePaths failed",{cause:Q})}}async function q0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=C_(_,J);return{filePath:$,fanIn:Q.getDependents($).length,fanOut:Q.getDependencies($).length}}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getFanMetrics failed",{cause:Q})}}var aJ=30000,S0=15000,sJ=10;function rJ(_,$){return(J)=>{for(let Q of _.onFileChangedCallbacks)try{Q(J)}catch(z){_.logger.error("[Gildash] onFileChanged callback threw:",z)}if($.handleWatcherEvent?.(J),_.semanticLayer)if(J.eventType==="delete")try{_.semanticLayer.notifyFileDeleted(J.filePath)}catch(Q){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",Q);for(let z of _.onErrorCallbacks)try{z(Q instanceof V?Q:new V("semantic","semantic notifyFileDeleted failed",{cause:Q}))}catch{}}else _.readFileFn(J.filePath).then((Q)=>{try{_.semanticLayer?.notifyFileChanged(J.filePath,Q)}catch(z){_.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",z);for(let Y of _.onErrorCallbacks)try{Y(z instanceof V?z:new V("semantic","semantic notifyFileChanged failed",{cause:z}))}catch{}}}).catch((Q)=>{_.logger.error("[Gildash] failed to read file for semantic layer",J.filePath,Q);try{_.semanticLayer?.notifyFileDeleted(J.filePath)}catch(z){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",z)}})}}async function oJ(_){if(!_.semanticLayer)return;let $=_.fileRepo.getAllFiles(_.defaultProject);await Promise.all($.map(async(J)=>{try{let Q=m_.resolve(_.projectRoot,J.filePath),z=await _.readFileFn(Q);_.semanticLayer?.notifyFileChanged(Q,z)}catch{}}))}async function T0(_,$){let J=_.coordinatorFactory?_.coordinatorFactory():new I$({projectRoot:_.projectRoot,boundaries:_.boundaries,extensions:_.extensions,ignorePatterns:_.ignorePatterns,dbConnection:_.db,parseCache:_.parseCache,fileRepo:_.fileRepo,symbolRepo:_.symbolRepo,relationRepo:_.relationRepo,annotationRepo:_.annotationRepo??void 0,changelogRepo:_.changelogRepo??void 0,logger:_.logger});_.coordinator=J;for(let Q of _.onIndexedCallbacks)J.onIndexed(Q);if(J.onIndexed((Q)=>{let z=Q.changedFiles.length+Q.deletedFiles.length;if(_.graphCache&&z>0&&z<100){let Y=_.relationRepo;_.graphCache.patchFiles(Q.changedFiles,Q.deletedFiles,(Z)=>{return[_.defaultProject,..._.boundaries.map((X)=>X.project)].flatMap((X)=>Y.getByType(X,"imports").concat(Y.getByType(X,"type-references")).concat(Y.getByType(X,"re-exports"))).filter((X)=>X.dstFilePath!==null&&(X.srcFilePath===Z||X.dstFilePath===Z)).map((X)=>({srcFilePath:X.srcFilePath,dstFilePath:X.dstFilePath}))}),_.graphCacheBuiltAt=Date.now()}else J$(_)}),$.isWatchMode){let Q=_.watcherFactory?_.watcherFactory():new H$({projectRoot:_.projectRoot,ignorePatterns:_.ignorePatterns,extensions:_.extensions},void 0,_.logger);await Q.start(rJ(_,J)).then((z)=>{if(n_(z))throw z.data}),_.watcher=Q,_.timer=setInterval(()=>{_.updateHeartbeatFn(_.db,process.pid)},aJ)}await J.fullIndex(),await oJ(_)}function tJ(_,$){let J=["SIGTERM","SIGINT","beforeExit"];for(let Q of J){let z=()=>{$().catch((Y)=>_.logger.error("[Gildash] close error during signal",Q,Y))};if(Q==="beforeExit")process.on("beforeExit",z);else process.on(Q,z);_.signalHandlers.push([Q,z])}}async function R0(_){let{projectRoot:$,extensions:J=[".ts",".mts",".cts"],ignorePatterns:Q=["**/node_modules/**"],parseCacheCapacity:z=500,logger:Y=console,existsSyncFn:Z=cJ,dbConnectionFactory:W,watcherFactory:X,coordinatorFactory:H,repositoryFactory:O,acquireWatcherRoleFn:U=W0,releaseWatcherRoleFn:K=Y0,updateHeartbeatFn:u=Z0,discoverProjectsFn:L=i_,parseSourceFn:w=b_,extractSymbolsFn:T=T_,extractRelationsFn:F=s_,symbolSearchFn:m=N$,relationSearchFn:j=A$,patternSearchFn:P=g$,loadTsconfigPathsFn:r=v_,readFileFn:B=async(E)=>Bun.file(E).text(),unlinkFn:A=async(E)=>{await Bun.file(E).unlink()},watchMode:D,semantic:C,semanticLayerFactory:N}=_;if(!m_.isAbsolute($))throw new V("validation",`Gildash: projectRoot must be an absolute path, got: "${$}"`);if(!Z($))throw new V("validation",`Gildash: projectRoot does not exist: "${$}"`);let g=W?W():new Z$({projectRoot:$}),R=g.open();if(n_(R))throw R.data;try{let E=await L($),p=E[0]?.project??m_.basename($),d=O?O():(()=>{let t=g;return{fileRepo:new X$(t),symbolRepo:new O$(t),relationRepo:new V$(t),parseCache:new C$(z)}})(),a=O?null:g,M=a?new F$(a):null,q=a?new G$(a):null,S=D??!0,k=crypto.randomUUID(),f;if(S)f=await Promise.resolve(U(g,process.pid,{instanceId:k}));else f="owner";let I={projectRoot:$,extensions:J,ignorePatterns:Q,logger:Y,defaultProject:p,role:f,db:g,symbolRepo:d.symbolRepo,relationRepo:d.relationRepo,fileRepo:d.fileRepo,parseCache:d.parseCache,annotationRepo:M,changelogRepo:q,annotationSearchFn:B0,releaseWatcherRoleFn:K,parseSourceFn:w,extractSymbolsFn:T,extractRelationsFn:F,symbolSearchFn:m,relationSearchFn:j,patternSearchFn:P,readFileFn:B,unlinkFn:A,existsSyncFn:Z,acquireWatcherRoleFn:U,updateHeartbeatFn:u,watcherFactory:X,coordinatorFactory:H,instanceId:k,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:E,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(d_($),I.tsconfigPaths=await r($),C){let t=m_.join($,"tsconfig.json");try{if(N)I.semanticLayer=N(t);else{let v=_$.create(t);if(n_(v))throw v.data;I.semanticLayer=v}}catch(v){if(v instanceof V)throw v;throw new V("semantic","Gildash: semantic layer creation failed",{cause:v})}}if(f==="owner")await T0(I,{isWatchMode:S});else{let t=0,v=async()=>{try{let x=await Promise.resolve(I.acquireWatcherRoleFn(I.db,process.pid,{instanceId:I.instanceId}));if(t=0,x==="owner"){I.role="owner";for(let y of I.onRoleChangedCallbacks)try{y("owner")}catch(l){I.logger.error("[Gildash] onRoleChanged callback threw:",l)}clearInterval(I.timer),I.timer=null;try{await T0(I,{isWatchMode:!0})}catch(y){if(I.logger.error("[Gildash] owner promotion failed, reverting to reader",y),I.role="reader",I.timer!==null)clearInterval(I.timer),I.timer=null;if(I.watcher){let l=await I.watcher.close();if(n_(l))I.logger.error("[Gildash] watcher close error during promotion rollback",l.data);I.watcher=null}if(I.coordinator)await I.coordinator.shutdown().catch((l)=>I.logger.error("[Gildash] coordinator shutdown error during promotion rollback",l)),I.coordinator=null;try{I.releaseWatcherRoleFn(I.db,process.pid)}catch(l){I.logger.error("[Gildash] failed to release watcher role during promotion rollback",l)}I.timer=setInterval(v,S0)}}}catch(x){t++;let y=x instanceof V?x:new V("watcher","Gildash: healthcheck error",{cause:x});for(let l of I.onErrorCallbacks)try{l(y)}catch(K_){I.logger.error("[Gildash] onError callback threw:",K_)}if(I.logger.error("[Gildash] healthcheck error",x),t>=sJ)I.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(I.timer),I.timer=null,Q$(I).catch((l)=>I.logger.error("[Gildash] close error during healthcheck shutdown",l))}};I.timer=setInterval(v,S0)}if(S)tJ(I,()=>Q$(I));return I}catch(E){if(g.close(),E instanceof V)throw E;throw new V("store","Gildash: initialization failed",{cause:E})}}async function Q$(_,$){if(_.closed)return;_.closed=!0;let J=[];for(let[Q,z]of _.signalHandlers)if(Q==="beforeExit")process.off("beforeExit",z);else process.off(Q,z);if(_.signalHandlers=[],_.semanticLayer){try{_.semanticLayer.dispose()}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}_.semanticLayer=null}if(_.coordinator)try{await _.coordinator.shutdown()}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}if(_.watcher){let Q=await _.watcher.close();if(n_(Q))J.push(Q.data)}if(_.timer!==null)clearInterval(_.timer),_.timer=null;try{_.releaseWatcherRoleFn(_.db,process.pid)}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}try{_.db.close()}catch(Q){J.push(Q instanceof Error?Q:Error(String(Q)))}if($?.cleanup)for(let Q of["","-wal","-shm"])try{await _.unlinkFn(m_.join(_.projectRoot,L_,h_+Q))}catch{}if(J.length>0)throw new V("close","Gildash: one or more errors occurred during close()",{cause:J})}import{isErr as k0}from"@zipbul/result";function F0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");let z=_.parseSourceFn($,J,Q);if(k0(z))throw z.data;return _.parseCache.set($,z),z}async function G0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");let Q=new Map,z=[];return await Promise.all($.map(async(Y)=>{try{let Z=await _.readFileFn(Y),W=_.parseSourceFn(Y,Z,J);if(!k0(W))Q.set(Y,W);else z.push({filePath:Y,error:W.data})}catch(Z){z.push({filePath:Y,error:Z instanceof Error?Z:Error(String(Z))})}})),{parsed:Q,failures:z}}function j0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.parseCache.get($)}function E0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.extractSymbolsFn($)}function v0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.extractRelationsFn($.program,$.filePath,_.tsconfigPaths??void 0)}import b0 from"path";function y0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.symbolRepo.getStats($??_.defaultProject)}catch(J){if(J instanceof V)throw J;throw new V("store","Gildash: getStats failed",{cause:J})}}function E$(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: searchSymbols failed",{cause:J})}}function P0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: searchRelations failed",{cause:J})}}function f0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:void 0,query:$})}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: searchAllSymbols failed",{cause:J})}}function n0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:void 0,query:$})}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: searchAllRelations failed",{cause:J})}}function m0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.fileRepo.getAllFiles($??_.defaultProject)}catch(J){if(J instanceof V)throw J;throw new V("store","Gildash: listIndexedFiles failed",{cause:J})}}function x0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{srcFilePath:$,dstFilePath:$,limit:1e4}})}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getInternalRelations failed",{cause:Q})}}function h0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,Y=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:J,limit:1}});if(Y.length===0)return null;let Z=Y[0],W=Z.detail,X={...Z,members:W.members,jsDoc:W.jsDoc,parameters:W.parameters,returnType:W.returnType,heritage:W.heritage,decorators:W.decorators,typeParameters:W.typeParameters};if(_.semanticLayer)try{let H=b0.isAbsolute(J)?J:b0.resolve(_.projectRoot,J),O=_.semanticLayer.lineColumnToPosition(H,Z.span.start.line,Z.span.start.column);if(O!==null){let U=_.semanticLayer.findNamePosition(H,O,Z.name)??O,K=_.semanticLayer.collectTypeAt(H,U);if(K)X.resolvedType=K}}catch{}return X}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getFullSymbol failed",{cause:z})}}function p0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=J??_.defaultProject,z=_.fileRepo.getFile(Q,$);if(!z)throw new V("search",`Gildash: file '${$}' is not in the index`);let Y=_.symbolRepo.getFileSymbols(Q,$),Z=_.relationRepo.getOutgoing(Q,$);return{filePath:z.filePath,lineCount:z.lineCount??0,size:z.size,symbolCount:Y.length,exportedSymbolCount:Y.filter((W)=>W.isExported).length,relationCount:Z.length}}catch(Q){if(Q instanceof V)throw Q;throw new V("store","Gildash: getFileStats failed",{cause:Q})}}function i0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return _.fileRepo.getFile(J??_.defaultProject,$)}catch(Q){if(Q instanceof V)throw Q;throw new V("store","Gildash: getFileInfo failed",{cause:Q})}}function d0(_,$,J){return E$(_,{filePath:$,project:J??void 0,limit:1e4})}function l0(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:J??_.defaultProject,query:{filePath:$,isExported:!0}}).map((Y)=>({name:Y.name,kind:Y.kind,parameters:Y.detail.parameters?`(${Y.detail.parameters.map((Z)=>`${Z.name}${Z.isOptional?"?":""}: ${Z.type??"unknown"}`).join(", ")})`:void 0,returnType:Y.detail.returnType??void 0,jsDoc:Y.detail.jsDoc?.description??void 0}));return{filePath:$,exports:z}}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getModuleInterface failed",{cause:Q})}}import h from"path";function x_(_,$,J,Q){let z=Q??_.defaultProject,Y=h.isAbsolute(J)?h.relative(_.projectRoot,J):J,Z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:Y,limit:1}});if(Z.length===0)return null;let W=Z[0],X=h.isAbsolute(J)?J:h.resolve(_.projectRoot,J),H=_.semanticLayer.lineColumnToPosition(X,W.span.start.line,W.span.start.column);if(H===null)return null;let O=_.semanticLayer.findNamePosition(X,H,W.name)??H;return{sym:W,position:O,absPath:X}}function c0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=x_(_,$,J,Q);if(!z)return null;return _.semanticLayer.collectTypeAt(z.absPath,z.position)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getResolvedType failed",{cause:z})}}function a0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=x_(_,$,J,Q);if(!z)throw new V("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findReferences(z.absPath,z.position)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getSemanticReferences failed",{cause:z})}}function s0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=x_(_,$,J,Q);if(!z)throw new V("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findImplementations(z.absPath,z.position)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getImplementations failed",{cause:z})}}function r0(_,$,J,Q,z,Y){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Z=x_(_,$,J,Y);if(!Z)throw new V("search",`Gildash: source symbol '${$}' not found in '${J}'`);let W=x_(_,Q,z,Y);if(!W)throw new V("search",`Gildash: target symbol '${Q}' not found in '${z}'`);return _.semanticLayer.isTypeAssignableTo(Z.absPath,Z.position,W.absPath,W.position)}catch(Z){if(Z instanceof V)throw Z;throw new V("semantic","Gildash: isTypeAssignableTo failed",{cause:Z})}}function o0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let J=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.collectFileTypes(J)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: getFileTypes failed",{cause:J})}}function t0(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=h.isAbsolute($)?$:h.resolve(_.projectRoot,$),Y=_.semanticLayer.lineColumnToPosition(z,J,Q);if(Y===null)return null;return _.semanticLayer.collectTypeAt(z,Y)}catch(z){if(z instanceof V)throw z;throw new V("semantic","Gildash: getResolvedTypeAt failed",{cause:z})}}function e0(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let J=h.isAbsolute($.source.filePath)?$.source.filePath:h.resolve(_.projectRoot,$.source.filePath),Q=h.isAbsolute($.target.filePath)?$.target.filePath:h.resolve(_.projectRoot,$.target.filePath),z=_.semanticLayer.lineColumnToPosition(J,$.source.line,$.source.column);if(z===null)return null;let Y=_.semanticLayer.lineColumnToPosition(Q,$.target.line,$.target.column);if(Y===null)return null;return _.semanticLayer.isTypeAssignableTo(J,z,Q,Y)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: isTypeAssignableToAt failed",{cause:J})}}function _1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{return _.semanticLayer.getModuleInterface($)}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: getSemanticModuleInterface failed",{cause:J})}}function $1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.getBaseTypes(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getBaseTypes failed",{cause:Q})}}function J1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.collectTypeAt(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getResolvedTypeAtPosition failed",{cause:Q})}}function Q1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.findReferences(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getSemanticReferencesAtPosition failed",{cause:Q})}}function z1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.findImplementations(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getImplementationsAtPosition failed",{cause:Q})}}function W1(_,$,J,Q,z){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Y=h.isAbsolute($)?$:h.resolve(_.projectRoot,$),Z=h.isAbsolute(Q)?Q:h.resolve(_.projectRoot,Q);return _.semanticLayer.isTypeAssignableTo(Y,J,Z,z)}catch(Y){if(Y instanceof V)throw Y;throw new V("semantic","Gildash: isTypeAssignableToAtPosition failed",{cause:Y})}}function Y1(_,$,J,Q,z){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Y=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToType(Y,J,Q,z)}catch(Y){if(Y instanceof V)throw Y;throw new V("semantic","Gildash: isTypeAssignableToType failed",{cause:Y})}}function Z1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.lineColumnToPosition(z,J,Q)}catch(z){if(z instanceof V)throw z;throw new V("semantic","Gildash: lineColumnToPosition failed",{cause:z})}}function X1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let z=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.findNamePosition(z,J,Q)}catch(z){if(z instanceof V)throw z;throw new V("semantic","Gildash: findNamePosition failed",{cause:z})}}function O1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.getSymbolNode(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getSymbolNode failed",{cause:Q})}}function V1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Q=h.isAbsolute($)?$:h.resolve(_.projectRoot,$);return _.semanticLayer.getDiagnostics(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getSemanticDiagnostics failed",{cause:Q})}}function U1(_,$){let J=new Map(_.map((W)=>[`${W.name}::${W.filePath}`,W])),Q=new Map($.map((W)=>[`${W.name}::${W.filePath}`,W])),z=[],Y=[],Z=[];for(let[W,X]of Q){let H=J.get(W);if(!H)z.push(X);else if(H.fingerprint!==X.fingerprint)Z.push({before:H,after:X})}for(let[W,X]of J)if(!Q.has(W))Y.push(X);return{added:z,removed:Y,modified:Z}}function H1(_,$){if(_.onIndexedCallbacks.add($),!_.coordinator)return()=>{_.onIndexedCallbacks.delete($)};let J=_.coordinator.onIndexed($);return()=>{_.onIndexedCallbacks.delete($),J()}}async function M1(_){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.coordinator)throw new V("closed","Gildash: reindex() is not available for readers");try{let $=await _.coordinator.fullIndex();return J$(_),$}catch($){if($ instanceof V)throw $;throw new V("index","Gildash: reindex failed",{cause:$})}}function K1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");let z=Q??_.defaultProject,Y=new Set,Z=[],W=$,X=J;for(;;){let H=`${X}::${W}`;if(Y.has(H))return{originalName:W,originalFilePath:X,reExportChain:Z,circular:!0};Y.add(H);let O=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{type:"re-exports",srcFilePath:X,limit:500}}),U,K;for(let u of O){let L;if(u.metaJson)try{let T=JSON.parse(u.metaJson);if(Array.isArray(T.specifiers))L=T.specifiers}catch{}if(!L)continue;let w=L.find((T)=>T.exported===W);if(!w)continue;U=u.dstFilePath??void 0,K=w.local;break}if(!U||!K)return{originalName:W,originalFilePath:X,reExportChain:Z,circular:!1};Z.push({filePath:X,exportedAs:W}),X=U,W=K}}function L1(_,$){return _.onFileChangedCallbacks.add($),()=>{_.onFileChangedCallbacks.delete($)}}function B1(_,$){return _.onErrorCallbacks.add($),()=>{_.onErrorCallbacks.delete($)}}function w1(_,$){return _.onRoleChangedCallbacks.add($),()=>{_.onRoleChangedCallbacks.delete($)}}async function D1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=J?.project??_.defaultProject,z=J?.filePaths?J.filePaths:_.fileRepo.getAllFiles(Q).map((Y)=>Y.filePath);return await _.patternSearchFn({pattern:$,filePaths:z})}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: findPattern failed",{cause:Q})}}async function u1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,Y=new Set,Z=(W,X,H)=>{let O=`${W}::${X}`;if(Y.has(O))return{symbolName:W,filePath:X,kind:H,children:[]};Y.add(O);let u=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{srcFilePath:X,srcSymbolName:W,limit:1000}}).filter((L)=>L.type==="extends"||L.type==="implements").filter((L)=>L.dstSymbolName!=null&&L.dstFilePath!=null).map((L)=>Z(L.dstSymbolName,L.dstFilePath,L.type));return{symbolName:W,filePath:X,kind:H,children:u}};return Z($,J)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getHeritageChain failed",{cause:z})}}function I1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.annotationRepo||!_.annotationSearchFn)return[];return _.annotationSearchFn({annotationRepo:_.annotationRepo,project:$.project??_.defaultProject,query:$})}function C1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.changelogRepo)return[];let Q=$ instanceof Date?$.toISOString():$,z=J?.project??_.defaultProject,Y=J?.limit??1000;return _.changelogRepo.getSince({project:z,since:Q,symbolName:J?.symbolName,changeTypes:J?.changeTypes,filePath:J?.filePath,includeFullIndex:J?.includeFullIndex,indexRunId:J?.indexRunId,afterId:J?.afterId,limit:Y}).map((W)=>({changeType:W.changeType,symbolName:W.symbolName,symbolKind:W.symbolKind,filePath:W.filePath,oldName:W.oldName,oldFilePath:W.oldFilePath,fingerprint:W.fingerprint,changedAt:W.changedAt,isFullIndex:W.isFullIndex===1,indexRunId:W.indexRunId}))}function N1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.changelogRepo)return 0;let J=$ instanceof Date?$.toISOString():$,Q=0,z=[_.defaultProject,..._.boundaries.map((Z)=>Z.project)],Y=[...new Set(z)];for(let Z of Y)Q+=_.changelogRepo.pruneOlderThan(Z,J);return Q}class v${_ctx;get projectRoot(){return this._ctx.projectRoot}get role(){return this._ctx.role}get projects(){return[...this._ctx.boundaries]}constructor(_){this._ctx=_}static async open(_){let $=await R0(_);return new v$($)}async close(_){return Q$(this._ctx,_)}parseSource(_,$,J){return F0(this._ctx,_,$,J)}async batchParse(_,$){return G0(this._ctx,_,$)}getParsedAst(_){return j0(this._ctx,_)}extractSymbols(_){return E0(this._ctx,_)}extractRelations(_){return v0(this._ctx,_)}getStats(_){return y0(this._ctx,_)}searchSymbols(_){return E$(this._ctx,_)}searchRelations(_){return P0(this._ctx,_)}searchAllSymbols(_){return f0(this._ctx,_)}searchAllRelations(_){return n0(this._ctx,_)}listIndexedFiles(_){return m0(this._ctx,_)}getInternalRelations(_,$){return x0(this._ctx,_,$)}getFullSymbol(_,$,J){return h0(this._ctx,_,$,J)}getFileStats(_,$){return p0(this._ctx,_,$)}getFileInfo(_,$){return i0(this._ctx,_,$)}getSymbolsByFile(_,$){return d0(this._ctx,_,$)}getModuleInterface(_,$){return l0(this._ctx,_,$)}getDependencies(_,$,J=1e4){return w0(this._ctx,_,$,J)}getDependents(_,$,J=1e4){return D0(this._ctx,_,$,J)}async getAffected(_,$){return u0(this._ctx,_,$)}async hasCycle(_){return I0(this._ctx,_)}async getImportGraph(_){return C0(this._ctx,_)}async getTransitiveDependencies(_,$){return N0(this._ctx,_,$)}async getTransitiveDependents(_,$){return A0(this._ctx,_,$)}async getCyclePaths(_,$){return g0(this._ctx,_,$)}async getFanMetrics(_,$){return q0(this._ctx,_,$)}getResolvedType(_,$,J){return c0(this._ctx,_,$,J)}getSemanticReferences(_,$,J){return a0(this._ctx,_,$,J)}getImplementations(_,$,J){return s0(this._ctx,_,$,J)}isTypeAssignableTo(_,$,J,Q,z){return r0(this._ctx,_,$,J,Q,z)}getSemanticModuleInterface(_){return _1(this._ctx,_)}getFileTypes(_){return o0(this._ctx,_)}getResolvedTypeAt(_,$,J){return t0(this._ctx,_,$,J)}isTypeAssignableToAt(_){return e0(this._ctx,_)}getResolvedTypeAtPosition(_,$){return J1(this._ctx,_,$)}getSemanticReferencesAtPosition(_,$){return Q1(this._ctx,_,$)}getImplementationsAtPosition(_,$){return z1(this._ctx,_,$)}isTypeAssignableToAtPosition(_,$,J,Q){return W1(this._ctx,_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return Y1(this._ctx,_,$,J,Q)}lineColumnToPosition(_,$,J){return Z1(this._ctx,_,$,J)}findNamePosition(_,$,J){return X1(this._ctx,_,$,J)}getSymbolNode(_,$){return O1(this._ctx,_,$)}getBaseTypes(_,$){return $1(this._ctx,_,$)}getSemanticDiagnostics(_,$){return V1(this._ctx,_,$)}diffSymbols(_,$){return U1(_,$)}onIndexed(_){return H1(this._ctx,_)}async reindex(){return M1(this._ctx)}resolveSymbol(_,$,J){return K1(this._ctx,_,$,J)}async findPattern(_,$){return D1(this._ctx,_,$)}async getHeritageChain(_,$,J){return u1(this._ctx,_,$,J)}onFileChanged(_){return L1(this._ctx,_)}onError(_){return B1(this._ctx,_)}onRoleChanged(_){return w1(this._ctx,_)}searchAnnotations(_){return I1(this._ctx,_)}getSymbolChanges(_,$){return C1(this._ctx,_,$)}pruneChangelog(_){return N1(this._ctx,_)}}import{Visitor as _3,visitorKeys as $3}from"oxc-parser";export{$3 as visitorKeys,N$ as symbolSearch,A$ as relationSearch,g$ as patternSearch,W_ as normalizePath,X_ as getLineColumn,y_ as buildLineOffsets,_3 as Visitor,V as GildashError,v$ as Gildash,$$ as DependencyGraph};
|
|
@@ -33,6 +33,11 @@ export type { GildashInternalOptions } from './lifecycle';
|
|
|
33
33
|
* (e.g. `'src/utils.ts'`). The `project` parameter defaults to the primary
|
|
34
34
|
* project (first discovered boundary) when omitted.
|
|
35
35
|
*
|
|
36
|
+
* **Path guarantee:** All file paths returned by gildash APIs (`filePath`,
|
|
37
|
+
* `srcFilePath`, `dstFilePath`, `originalFilePath`, etc.) use forward slash
|
|
38
|
+
* (`/`) as separator, regardless of platform. Consumers may safely omit
|
|
39
|
+
* platform-specific path normalization.
|
|
40
|
+
*
|
|
36
41
|
* Create an instance with the static {@link Gildash.open} factory.
|
|
37
42
|
* Always call {@link Gildash.close} when done to release resources.
|
|
38
43
|
*/
|
package/dist/src/index.d.ts
CHANGED
|
@@ -21,6 +21,7 @@ export type { SymbolNode } from "./semantic/symbol-graph";
|
|
|
21
21
|
export type { AnnotationSource, ExtractedAnnotation } from "./extractor/types";
|
|
22
22
|
export type { AnnotationSearchQuery, AnnotationSearchResult } from "./search/annotation-search";
|
|
23
23
|
export type { SymbolChange, SymbolChangeType, SymbolChangeQueryOptions } from "./gildash/types";
|
|
24
|
+
export { normalizePath } from './common/path-utils';
|
|
24
25
|
export { buildLineOffsets, getLineColumn } from './parser/source-position';
|
|
25
26
|
export type { SourcePosition, SourceSpan } from './parser/types';
|
|
26
27
|
export type { Program, Node } from 'oxc-parser';
|
|
@@ -4,8 +4,12 @@ import type { RelationRecord } from '../store/repositories/relation.repository';
|
|
|
4
4
|
* A {@link CodeRelation} enriched with the destination project identifier
|
|
5
5
|
* as stored in the relation index.
|
|
6
6
|
*/
|
|
7
|
-
export interface StoredCodeRelation extends CodeRelation {
|
|
7
|
+
export interface StoredCodeRelation extends Omit<CodeRelation, 'specifier'> {
|
|
8
8
|
dstProject: string | null;
|
|
9
|
+
/** Whether this relation targets an external (bare specifier) package. */
|
|
10
|
+
isExternal: boolean;
|
|
11
|
+
/** The raw import specifier string (e.g. `'lodash'`, `'./missing'`). `null` when the import was resolved to a file. */
|
|
12
|
+
specifier: string | null;
|
|
9
13
|
}
|
|
10
14
|
/**
|
|
11
15
|
* Filters for {@link relationSearch}.
|