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