@zipbul/gildash 0.19.1 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +9 -9
- package/dist/src/extractor/index.d.ts +1 -1
- package/dist/src/extractor/types.d.ts +68 -2
- package/dist/src/gildash/types.d.ts +3 -1
- package/dist/src/index.d.ts +2 -2
- package/dist/src/search/index.d.ts +1 -1
- package/dist/src/search/pattern-search.d.ts +13 -0
- package/dist/src/search/symbol-search.d.ts +7 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
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
|
-
`,
|
|
5
|
-
`),
|
|
6
|
-
`).length});let z$=(this.opts.parseSourceFn??
|
|
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
|
|
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};
|
|
2
|
+
var R1=Object.defineProperty;var T1=(_)=>_;function F1(_,$){this[_]=T1.bind(null,$)}var k1=(_,$)=>{for(var J in $)R1(_,J,{get:$[J],enumerable:!0,configurable:!0,set:F1.bind($,J)})};var y$=import.meta.require;import{isErr as m_}from"@zipbul/result";import k_ from"path";import{existsSync as tJ}from"fs";import{err as x$,isErr as f1}from"@zipbul/result";import{Database as P1}from"bun:sqlite";import{mkdirSync as y1,unlinkSync as m$,existsSync as n$}from"fs";import{dirname as x1,join as h$}from"path";import{drizzle as m1}from"drizzle-orm/bun-sqlite";import{migrate as n1}from"drizzle-orm/bun-sqlite/migrator";class O extends Error{type;constructor(_,$,J){super($,J);this.type=_;this.name="GildashError"}}var L_=".gildash",h_="gildash.db";var Y$={};k1(Y$,{watcherOwner:()=>b1,symbols:()=>h,symbolChangelog:()=>J_,relations:()=>E,files:()=>e,annotations:()=>Z_});import{sql as G1}from"drizzle-orm";import{sqliteTable as q_,text as P,integer as t,real as j1,index as W_,primaryKey as E1,foreignKey as W$,check as v1}from"drizzle-orm/sqlite-core";var e=q_("files",{project:P("project").notNull(),filePath:P("file_path").notNull(),mtimeMs:j1("mtime_ms").notNull(),size:t("size").notNull(),contentHash:P("content_hash").notNull(),updatedAt:P("updated_at").notNull(),lineCount:t("line_count")},(_)=>[E1({columns:[_.project,_.filePath]})]),h=q_("symbols",{id:t("id").primaryKey({autoIncrement:!0}),project:P("project").notNull(),filePath:P("file_path").notNull(),kind:P("kind").notNull(),name:P("name").notNull(),startLine:t("start_line").notNull(),startColumn:t("start_column").notNull(),endLine:t("end_line").notNull(),endColumn:t("end_column").notNull(),isExported:t("is_exported").notNull().default(0),signature:P("signature"),fingerprint:P("fingerprint"),detailJson:P("detail_json"),contentHash:P("content_hash").notNull(),indexedAt:P("indexed_at").notNull(),resolvedType:P("resolved_type"),structuralFingerprint:P("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:[e.project,e.filePath]}).onDelete("cascade")]),E=q_("relations",{id:t("id").primaryKey({autoIncrement:!0}),project:P("project").notNull(),type:P("type").notNull(),srcFilePath:P("src_file_path").notNull(),srcSymbolName:P("src_symbol_name"),dstProject:P("dst_project"),dstFilePath:P("dst_file_path"),dstSymbolName:P("dst_symbol_name"),metaJson:P("meta_json"),specifier:P("specifier"),isExternal:t("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:[e.project,e.filePath]}).onDelete("cascade")]),Z_=q_("annotations",{id:t("id").primaryKey({autoIncrement:!0}),project:P("project").notNull(),filePath:P("file_path").notNull(),tag:P("tag").notNull(),value:P("value").notNull().default(""),source:P("source").notNull(),symbolName:P("symbol_name"),startLine:t("start_line").notNull(),startColumn:t("start_column").notNull(),endLine:t("end_line").notNull(),endColumn:t("end_column").notNull(),indexedAt:P("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:[e.project,e.filePath]}).onDelete("cascade")]),J_=q_("symbol_changelog",{id:t("id").primaryKey({autoIncrement:!0}),project:P("project").notNull(),changeType:P("change_type").notNull(),symbolName:P("symbol_name").notNull(),symbolKind:P("symbol_kind").notNull(),filePath:P("file_path").notNull(),oldName:P("old_name"),oldFilePath:P("old_file_path"),fingerprint:P("fingerprint"),changedAt:P("changed_at").notNull(),isFullIndex:t("is_full_index").notNull().default(0),indexRunId:P("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=q_("watcher_owner",{id:t("id").primaryKey(),pid:t("pid").notNull(),startedAt:P("started_at").notNull(),heartbeatAt:P("heartbeat_at").notNull(),instanceId:P("instance_id")},(_)=>[v1("watcher_owner_singleton",G1`${_.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{y1(x1(this.dbPath),{recursive:!0}),this.client=new P1(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$}),n1(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(_)&&n$(this.dbPath)){this.closeClient(),m$(this.dbPath);for(let J of["-wal","-shm"]){let Q=this.dbPath+J;if(n$(Q))m$(Q)}let $=this.open();if(f1($))return x$(new O("store",`Failed to recover database at ${this.dbPath}`,{cause:$.data}));return $}return x$(new O("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 G_,and as p$}from"drizzle-orm";class X${db;constructor(_){this.db=_}getFile(_,$){return this.db.drizzleDb.select().from(e).where(p$(G_(e.project,_),G_(e.filePath,$))).get()??null}upsertFile(_){this.db.drizzleDb.insert(e).values({project:_.project,filePath:_.filePath,mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}).onConflictDoUpdate({target:[e.project,e.filePath],set:{mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}}).run()}getAllFiles(_){return this.db.drizzleDb.select().from(e).where(G_(e.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(e).where(p$(G_(e.project,_),G_(e.filePath,$))).run()}}import{eq as __,and as B_,sql as p_,count as h1}from"drizzle-orm";function u_(_){return _.replaceAll("\x00","").trim().split(/\s+/).map(($)=>$.trim()).filter(($)=>$.length>0).map(($)=>`"${$.replaceAll('"','""')}"*`).join(" ")}var i$=50;class V${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+=i$)this.db.drizzleDb.insert(h).values(W.slice(Z,Z+i$)).run()}getFileSymbols(_,$){return this.db.drizzleDb.select().from(h).where(B_(__(h.project,_),__(h.filePath,$))).all()}searchByName(_,$,J={}){let Q=J.limit??50,z=u_($);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 O("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 c,and as O_,isNull as d$,or as p1}from"drizzle-orm";var j_={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 O${db;constructor(_){this.db=_}replaceFileRelations(_,$,J){this.db.transaction((Q)=>{if(Q.drizzleDb.delete(E).where(O_(c(E.project,_),c(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(j_).from(E).where(O_(c(E.project,_),c(E.srcFilePath,$),p1(c(E.srcSymbolName,J),d$(E.srcSymbolName)))).all();return this.db.drizzleDb.select(j_).from(E).where(O_(c(E.project,_),c(E.srcFilePath,$))).all()}getIncoming(_){let{dstProject:$,dstFilePath:J}=_;return this.db.drizzleDb.select(j_).from(E).where(O_(c(E.dstProject,$),c(E.dstFilePath,J))).all()}getByType(_,$){return this.db.drizzleDb.select(j_).from(E).where(O_(c(E.project,_),c(E.type,$))).all()}deleteFileRelations(_,$){this.db.drizzleDb.delete(E).where(O_(c(E.project,_),c(E.srcFilePath,$))).run()}deleteIncomingRelations(_,$){this.db.drizzleDb.delete(E).where(O_(c(E.dstProject,_),c(E.dstFilePath,$))).run()}searchRelations(_){let $=this.db.drizzleDb.select(j_).from(E).where(O_(_.project!==void 0?c(E.project,_.project):void 0,_.srcFilePath!==void 0?c(E.srcFilePath,_.srcFilePath):void 0,_.srcSymbolName!==void 0?c(E.srcSymbolName,_.srcSymbolName):void 0,_.dstProject!==void 0?c(E.dstProject,_.dstProject):void 0,_.dstFilePath!==void 0?c(E.dstFilePath,_.dstFilePath):void 0,_.dstSymbolName!==void 0?c(E.dstSymbolName,_.dstSymbolName):void 0,_.type!==void 0?c(E.type,_.type):void 0,_.specifier!==void 0?c(E.specifier,_.specifier):void 0,_.isExternal!==void 0?c(E.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?O_(c(E.dstProject,$),c(E.dstFilePath,J),d$(E.dstSymbolName)):O_(c(E.dstProject,$),c(E.dstFilePath,J),c(E.dstSymbolName,Q)),X={dstFilePath:z,dstSymbolName:W};if(Z!==void 0)X.dstProject=Z;this.db.drizzleDb.update(E).set(X).where(Y).run()}}import{err as c$}from"@zipbul/result";import{subscribe as i1}from"@parcel/watcher";import U$ from"path";import l$ from"path";function Y_(_){return _.replaceAll("\\","/")}function E_(_,$){return Y_(l$.relative(_,$))}function S_(_,$){return Y_(l$.resolve(_,$))}var d1=["**/.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(_,$=i1,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 O("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 O("watcher","Callback error",{cause:Q}))}},{ignore:this.#J})}catch($){return c$(new O("watcher","Failed to subscribe watcher",{cause:$}))}}async close(){if(!this.#_)return;try{await this.#_.unsubscribe(),this.#_=void 0}catch(_){return c$(new O("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 i_(_){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 r(_,$,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 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=v_.resolve(_,$);return J.endsWith(".json")?J:J+".json"}return v_.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(v_.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 $=v_.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?v_.resolve(_,z):_,Y=new Map;if(W)for(let[H,V]of Object.entries(W)){if(!Array.isArray(V))continue;let U=V.filter((B)=>typeof B==="string");Y.set(H,U)}let X={baseUrl:Z,paths:Y};return w_.set(_,X),X}function d_(_){if(_){w_.delete(_);return}w_.clear()}function V_(_){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 f_(_,$,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 O("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=[],H=Q.map((U)=>new Bun.Glob(U));for await(let U of _J.glob("**/*",{cwd:$})){let B=Y_(U);if(!J.some((p)=>B.endsWith(p)))continue;if(B.startsWith("node_modules/")||B.includes("/node_modules/"))continue;if(H.some((p)=>p.match(B)))continue;Z.add(B);let q=$J($,B),L=Bun.file(q),{size:C,lastModified:T}=L,F=W.get(B);if(!F){let p=await L.text(),s=V_(p);Y.push({filePath:B,contentHash:s,mtimeMs:T,size:C});continue}if(F.mtimeMs===T&&F.size===C){X.push({filePath:B,contentHash:F.contentHash,mtimeMs:T,size:C});continue}let x=await L.text(),b=V_(x);if(b===F.contentHash)X.push({filePath:B,contentHash:b,mtimeMs:T,size:C});else Y.push({filePath:B,contentHash:b,mtimeMs:T,size:C})}let V=[];for(let U of W.keys())if(!Z.has(U))V.push(U);return{changed:Y,unchanged:X,deleted:V}}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 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 O("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 g_(_){if(_.type==="Identifier")return[{name:_.name,start:_.start,end:_.end}];if(_.type==="ObjectPattern"){let $=[];for(let J of _.properties)if(J.type==="RestElement")$.push(...g_(J.argument));else $.push(...g_(J.value));return $}if(_.type==="ArrayPattern"){let $=[];for(let J of _.elements){if(!J)continue;if(J.type==="RestElement")$.push(...g_(J.argument));else $.push(...g_(J))}return $}if(_.type==="AssignmentPattern")return g_(_.left);return[]}function R_(_){let{program:$,sourceText:J,comments:Q}=_,z=P_(J),W=Q.filter((K)=>K.type==="Block"&&K.value.startsWith("*")).sort((K,u)=>K.end-u.end),Z=$.body.map((K)=>K.start).sort((K,u)=>K-u);function Y(K,u){return{start:X_(z,K),end:X_(z,u)}}function X(K){let u=0,D=W.length-1,w=-1;while(u<=D){let N=u+D>>>1;if(W[N].end<=K)w=N,u=N+1;else D=N-1}if(w<0)return;let A=W[w];u=0,D=Z.length-1;while(u<=D){let N=u+D>>>1,k=Z[N];if(k<=A.end)u=N+1;else if(k>=K)D=N-1;else return}return`/*${A.value}*/`}function H(K){if(!K)return;let u="typeAnnotation"in K&&K.typeAnnotation?K.typeAnnotation:K;return J.slice(u.start,u.end)}let V=8;function U(K,u=0){if(u>=V)return{kind:"unresolvable",sourceText:J.slice(K.start,K.end)};let D=K.type;if(D==="Literal"){let w=K.value;if(w===null)return{kind:"null",value:null};if(typeof w==="string")return{kind:"string",value:w};if(typeof w==="number")return{kind:"number",value:w};if(typeof w==="boolean")return{kind:"boolean",value:w};return{kind:"unresolvable",sourceText:J.slice(K.start,K.end)}}if(D==="Identifier"){let w=K.name;if(w==="undefined")return{kind:"undefined",value:null};return{kind:"identifier",name:w}}if(D==="MemberExpression"){if(K.computed)return{kind:"unresolvable",sourceText:J.slice(K.start,K.end)};let w=J.slice(K.object.start,K.object.end),A=K.property.name??J.slice(K.property.start,K.property.end);return{kind:"member",object:w,property:A}}if(D==="CallExpression"){let w=K.callee,A=J.slice(w.start,w.end),k=(K.arguments??[]).map((j)=>U(j,u+1));return{kind:"call",callee:A,arguments:k}}if(D==="NewExpression"){let w=K.callee,A=J.slice(w.start,w.end),k=(K.arguments??[]).map((j)=>U(j,u+1));return{kind:"new",callee:A,arguments:k}}if(D==="ObjectExpression")return{kind:"object",properties:(K.properties??[]).map((N)=>{if(N.type==="SpreadElement"){let R=N.argument;return{key:"...",value:{kind:"spread",argument:U(R,u+1)}}}let k=N.key,j=k.name??k.value,v=j!=null?String(j):J.slice(k.start,k.end),M=N.value,I=N.computed||void 0,g=N.shorthand||void 0;return{key:v,value:U(M,u+1),computed:I,shorthand:g}})};if(D==="ArrayExpression")return{kind:"array",elements:(K.elements??[]).map((N)=>{if(!N)return{kind:"undefined",value:null};return U(N,u+1)})};if(D==="SpreadElement"){let w=K.argument;return{kind:"spread",argument:U(w,u+1)}}if(D==="ArrowFunctionExpression"||D==="FunctionExpression")return{kind:"function",sourceText:J.slice(K.start,K.end)};if(D==="TemplateLiteral"||D==="TaggedTemplateExpression")return{kind:"template",sourceText:J.slice(K.start,K.end)};if(D==="UnaryExpression"){let{operator:w,argument:A}=K;if(w==="-"&&A.type==="Literal"&&typeof A.value==="number")return{kind:"number",value:-A.value};if(w==="void")return{kind:"undefined",value:null};return{kind:"unresolvable",sourceText:J.slice(K.start,K.end)}}if(D==="TSAsExpression"||D==="TSSatisfiesExpression"||D==="TSNonNullExpression"||D==="TSTypeAssertion"||D==="TSInstantiationExpression"||D==="ParenthesizedExpression"){let w=K.expression;if(w)return U(w,u)}return{kind:"unresolvable",sourceText:J.slice(K.start,K.end)}}function B(K){if(!K||K.length===0)return[];return K.map((u)=>{let D=u.expression;if(D.type==="CallExpression"){let w=D,A=w.callee,N="name"in A&&typeof A.name==="string"?A.name:("property"in A)&&A.property&&typeof A.property.name==="string"?A.property.name:"unknown",k=w.arguments.map((j)=>U(j));return{name:N,arguments:k.length>0?k:void 0}}if(D.type==="Identifier")return{name:D.name??"unknown"};return{name:J.slice(D.start,D.end)}})}function q(K){if(K.type==="TSParameterProperty"){let D=K;return L(D.parameter,D.parameter.decorators)}if(K.type==="RestElement"){let D=K,w=D.argument,N=`...${"name"in w&&typeof w.name==="string"?w.name:"unknown"}`,k=D.typeAnnotation,j=k?H(k):void 0,v={name:N,isOptional:!1};if(j)v.type=j;return v}let u=K;return L(u,u.decorators)}function L(K,u){if(K.type==="AssignmentPattern"){let{left:v,right:M}=K,I="name"in v&&typeof v.name==="string"?v.name:"unknown",g="typeAnnotation"in v?v.typeAnnotation:null,R=g?H(g):void 0,m=J.slice(M.start,M.end),S="decorators"in v&&Array.isArray(v.decorators)?v.decorators:[],f=B(S),G={name:I,isOptional:!0,defaultValue:m};if(R)G.type=R;if(f.length>0)G.decorators=f;return G}let D="name"in K&&typeof K.name==="string"?K.name:("pattern"in K)&&K.pattern&&typeof K.pattern.name==="string"?K.pattern.name:"unknown",w=!!(("optional"in K)&&K.optional),A="typeAnnotation"in K?K.typeAnnotation:null,N=A?H(A):void 0,k=B(u??[]),j={name:D,isOptional:w};if(N)j.type=N;if(k.length>0)j.decorators=k;return j}function C(K,u){let D=[];if(u?.async)D.push("async");if(K.static)D.push("static");if(K.abstract)D.push("abstract");if(K.readonly)D.push("readonly");if(K.override)D.push("override");if(K.declare)D.push("declare");if(K.const)D.push("const");let w=K.accessibility;if(w==="private")D.push("private");else if(w==="protected")D.push("protected");else if(w==="public")D.push("public");return D}function T(K){if(!K)return;let u=K.params.flatMap((D)=>{let w=D.name.name;return w?[w]:[]});return u.length>0?u:void 0}function F(K){let u=[];if(K.superClass){let w=J.slice(K.superClass.start,K.superClass.end);u.push({kind:"extends",name:w})}let D=K.implements??[];for(let w of D){let A=w.expression,N=J.slice(A.start,A.end);u.push({kind:"implements",name:N})}return u}function x(K){let u=[],D=K.extends;for(let w of D){let A=w.expression,N=J.slice(A.start,A.end);u.push({kind:"extends",name:N})}return u}function b(K){let u=[];for(let D of K)if(D.type==="MethodDefinition"||D.type==="TSAbstractMethodDefinition"){let w=D,A=c_(w.key),N=w.value,k=w.kind,j=k==="constructor"?"constructor":k==="get"?"getter":k==="set"?"setter":"method",v=C(w,N);if(D.type==="TSAbstractMethodDefinition"&&!v.includes("abstract"))v.push("abstract");let M=N.params.map(q),I=H(N.returnType),g={kind:"method",name:A,span:Y(D.start,D.end),isExported:!1,methodKind:j,modifiers:v,parameters:M.length>0?M:void 0,returnType:I};u.push(g)}else if(D.type==="PropertyDefinition"||D.type==="TSAbstractPropertyDefinition"){let w=D,A=c_(w.key),N=C(w);if(D.type==="TSAbstractPropertyDefinition"&&!N.includes("abstract"))N.push("abstract");let k=H(w.typeAnnotation),j=w.value,v=j?U(j):void 0,M=B(w.decorators??[]),I={kind:"property",name:A,span:Y(D.start,D.end),isExported:!1,modifiers:N,returnType:k,initializer:v};if(M.length>0)I.decorators=M;u.push(I)}return u}function p(K){let u=[];for(let D of K)if(D.type==="TSMethodSignature"){let w=D,A=c_(w.key),N=w.params.map(q),k=H(w.returnType);u.push({kind:"method",name:A,span:Y(D.start,D.end),isExported:!1,modifiers:[],methodKind:"method",parameters:N.length>0?N:void 0,returnType:k})}else if(D.type==="TSPropertySignature"){let w=D,A=c_(w.key),N=H(w.typeAnnotation),k={kind:"property",name:A,span:Y(D.start,D.end),isExported:!1,modifiers:w.readonly?["readonly"]:[],returnType:N};u.push(k)}return u}function s(K,u){let D=K.type;if(D==="FunctionDeclaration"||D==="FunctionExpression"||D==="TSDeclareFunction"||D==="TSEmptyBodyFunctionExpression"){let w=K,A=w.id?.name??"default",N=w.params.map(q),k=H(w.returnType),j=C(w,w),v=B(w.decorators??[]),M=T(w.typeParameters),I={kind:"function",name:A,span:Y(K.start,K.end),isExported:u,modifiers:j,parameters:N.length>0?N:void 0,returnType:k,decorators:v.length>0?v:void 0};if(M&&M.length>0)I.typeParameters=M;return I}if(D==="ClassDeclaration"||D==="ClassExpression"){let w=K,A=w.id?.name??"default",N=F(w),k=b(w.body.body),j=B(w.decorators),v=C(w),M=T(w.typeParameters),I={kind:"class",name:A,span:Y(K.start,K.end),isExported:u,modifiers:v,heritage:N.length>0?N:void 0,members:k.length>0?k:void 0,decorators:j.length>0?j:void 0};if(M&&M.length>0)I.typeParameters=M;return I}if(D==="VariableDeclaration"){let w=K,A=[];for(let N of w.declarations){let{id:k,init:j}=N;if(k.type==="ObjectPattern"||k.type==="ArrayPattern"){let f=g_(k);for(let G of f)A.push({kind:"variable",name:G.name,span:Y(G.start,G.end),isExported:u,modifiers:[]});continue}let v="name"in k&&typeof k.name==="string"?k.name:"unknown",M="variable",I,g,R;if(j)if(j.type==="FunctionExpression"||j.type==="ArrowFunctionExpression"){M="function";let f=j;I=f.params.map(q),g=H(f.returnType)}else R=U(j);let m=[],S={kind:M,name:v,span:Y(N.start,N.end),isExported:u,modifiers:m,parameters:I,returnType:g};if(R)S.initializer=R;A.push(S)}if(A.length===0)return null;if(A.length===1)return A[0];return A}if(D==="TSTypeAliasDeclaration")return{kind:"type",name:K.id.name,span:Y(K.start,K.end),isExported:u,modifiers:[]};if(D==="TSInterfaceDeclaration"){let w=K,A=w.id.name,N=x(w),k=p(w.body.body),j=T(w.typeParameters),v={kind:"interface",name:A,span:Y(K.start,K.end),isExported:u,modifiers:[],heritage:N.length>0?N:void 0,members:k.length>0?k:void 0};if(j&&j.length>0)v.typeParameters=j;return v}if(D==="TSEnumDeclaration"){let w=K,A=w.id.name,N=C(w),j=w.body.members.map((v)=>{let M=v.id,I="name"in M&&typeof M.name==="string"?M.name:("value"in M)&&typeof M.value==="string"?M.value:"unknown",g=v.initializer,R=g?U(g):void 0,m={kind:"property",name:I,span:Y(v.start,v.end),isExported:!1,modifiers:[]};if(R)m.initializer=R;return m});return{kind:"enum",name:A,span:Y(K.start,K.end),isExported:u,modifiers:N,members:j.length>0?j:void 0}}if(D==="TSModuleDeclaration"){let w=K,A=w.id.name??w.id.value??"unknown",N=C(w),k=[];if(w.body?.type==="TSModuleBlock")for(let j of w.body.body??[]){if(j.type!=="ExportNamedDeclaration")continue;let v=j.declaration;if(!v)continue;let M=s(v,!1);if(M)if(Array.isArray(M))k.push(...M);else k.push(M)}return{kind:"namespace",name:A,span:Y(K.start,K.end),isExported:u,modifiers:N,members:k.length>0?k:void 0}}return null}let o=[],z_=new Set;for(let K of $.body){let u=null,D=K;if(D.type==="ExportNamedDeclaration"){let A=D;if(A.declaration){if(u=s(A.declaration,!0),u&&!Array.isArray(u))u.span=Y(A.start,A.end)}else if(!A.source&&A.specifiers)for(let N of A.specifiers){let k=N.local,j="name"in k?k.name:k.value;if(j)z_.add(j)}}else if(D.type==="ExportDefaultDeclaration"){let A=D,N=A.declaration;if(N){if(u=s(N,!0),u&&!Array.isArray(u))u.name="id"in N&&N.id&&typeof N.id.name==="string"?N.id.name:"default",u.isExported=!0,u.span=Y(A.start,A.end);else if(!u&&"type"in N&&N.type==="Identifier"){let k=N.name;if(k)z_.add(k)}}}else{let A=D.type;if(A==="FunctionDeclaration"||A==="TSDeclareFunction"||A==="ClassDeclaration"||A==="VariableDeclaration"||A==="TSTypeAliasDeclaration"||A==="TSInterfaceDeclaration"||A==="TSEnumDeclaration"||A==="TSModuleDeclaration")u=s(D,!1)}let w=Array.isArray(u)?u:u?[u]:[];for(let A of w){let N=K.start,k=X(N);if(k){let j=l_(k);if(!zJ(j))A.jsDoc=j}o.push(A)}}if(z_.size>0){for(let K of o)if(!K.isExported&&z_.has(K.name))K.isExported=!0}return o}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(_.initializer)$.initializer=_.initializer;if(_.members?.length)$.members=_.members.map((J)=>{let Q=J.modifiers.find((W)=>W==="private"||W==="protected"||W==="public"),z={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};if(J.initializer)z.initializer=J.initializer;if(J.decorators?.length)z.decorators=J.decorators;return z});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}:${V_(J)}`)}return V_($.join("|"))}function r$(_,$,J,Q,z){let W=WJ(_),Z=V_(`${$}|${_.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 H of X.members??[])Y.push(r$(H,`${X.name}.${H.name}`,J,Q,z))}W.replaceFileSymbols(J,Q,z,Y)}import{resolve as L$,dirname as XJ,extname as VJ}from"path";function D_(_,$,J){let Q=(z)=>{let W=VJ(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 H=$.slice(Y.length,X===""?void 0:$.length-X.length),V=[];for(let U of W)V.push(...Q(Y_(L$(J.baseUrl,U.replace("*",H)))));return V}}}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 H=X[0],V=Z.specifiers??[];for(let U of V)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 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),H=Y===null?{dstFilePath:null,specifier:Z}:{dstFilePath:Y};if(W.entries.length===0){let V={};if(X)V.isExternal=!0;if(Y===null&&!X)V.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,...H,dstSymbolName:null,...Object.keys(V).length>0?{metaJson:JSON.stringify(V)}:{}});continue}for(let V of W.entries){let U=V.isType,B={};if(U)B.isType=!0;if(X)B.isExternal=!0;if(Y===null&&!X)B.isUnresolved=!0;let q,L,C=V.importName.kind;if(C==="Default")q="default",L=V.localName.value;else if(C==="NamespaceObject")q="*",L=V.localName.value,B.importKind="namespace";else q=V.importName.name??"unknown",L=V.localName.value;z.push({type:U?"type-references":"imports",srcFilePath:$,srcSymbolName:L,...H,dstSymbolName:q,...Object.keys(B).length>0?{metaJson:JSON.stringify(B)}:{}})}}}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:H,isExternal:V}=I_($,X,J,Q),U=Y.exportName.name??"default",B=Y.exportName.kind,q=Y.localName.name??Y.importName.name??U,L=Y.isType,C={isReExport:!0};if(B==="None");else C.specifiers=[{local:q,exported:U}];if(L)C.isType=!0;if(V)C.isExternal=!0;if(H===null&&!V)C.isUnresolved=!0;let T=null,F=null,x=Y.importName.kind;if(x==="All"||x==="AllButDefault"){if(B==="Name"&&U)F=U,C.namespaceAlias=U}else F=q,T=U;z.push({type:L?"type-references":"re-exports",srcFilePath:$,srcSymbolName:T,dstFilePath:H,dstSymbolName:F,metaJson:JSON.stringify(C),...H===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:H,isExternal:V}=I_($,X,J,Q),U=Y.importKind==="type",B=Y.specifiers,q=H===null?{dstFilePath:null,specifier:X}:{dstFilePath:H};if(B.length===0){let L={};if(U)L.isType=!0;if(V)L.isExternal=!0;if(H===null&&!V)L.isUnresolved=!0;z.push({type:U?"type-references":"imports",srcFilePath:$,srcSymbolName:null,...q,dstSymbolName:null,...Object.keys(L).length>0?{metaJson:JSON.stringify(L)}:{}})}else for(let L of B){let C=L.type,T=U||C==="ImportSpecifier"&&L.importKind==="type",F={};if(T)F.isType=!0;if(V)F.isExternal=!0;if(H===null&&!V)F.isUnresolved=!0;let x,b;if(C==="ImportDefaultSpecifier")x="default",b=L.local.name;else if(C==="ImportNamespaceSpecifier")x="*",b=L.local.name,F.importKind="namespace";else x=a_(L.imported),b=L.local.name;z.push({type:T?"type-references":"imports",srcFilePath:$,srcSymbolName:b,...q,dstSymbolName:x,...Object.keys(F).length>0?{metaJson:JSON.stringify(F)}:{}})}continue}if(Z.type==="ExportAllDeclaration"){let Y=Z,X=Y.source.value,{resolved:H,isExternal:V}=I_($,X,J,Q),U=Y.exportKind==="type",B=Y.exported,q=B?a_(B):null,L={isReExport:!0};if(U)L.isType=!0;if(V)L.isExternal=!0;if(H===null&&!V)L.isUnresolved=!0;if(q)L.namespaceAlias=q;z.push({type:U?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:H,dstSymbolName:q,metaJson:JSON.stringify(L),...H===null?{specifier:X}:{}});continue}if(Z.type==="ExportNamedDeclaration"){let Y=Z;if(!Y.source)continue;let X=Y.source.value,{resolved:H,isExternal:V}=I_($,X,J,Q),U=Y.exportKind==="type",B=Y.specifiers??[];for(let q of B){let L=U||q.exportKind==="type",C=a_(q.local),T=a_(q.exported),F={isReExport:!0,specifiers:[{local:C,exported:T}]};if(L)F.isType=!0;if(V)F.isExternal=!0;if(H===null&&!V)F.isUnresolved=!0;z.push({type:L?"type-references":"re-exports",srcFilePath:$,srcSymbolName:T,dstFilePath:H,dstSymbolName:C,metaJson:JSON.stringify(F),...H===null?{specifier:X}:{}})}}}}function LJ(_,$,J,Q,z){new OJ({ImportExpression(Z){let Y=Z.source;if(Y.type!=="Literal"||typeof Y.value!=="string")return;let X=Y.value,{resolved:H,isExternal:V}=I_($,X,J,Q),U={isDynamic:!0};if(V)U.isExternal=!0;if(H===null&&!V)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 Y=Z.callee,X=!1;if(Y.type==="Identifier"&&Y.name==="require");else if(Y.type==="MemberExpression"&&!Y.computed){let C=Y,T=C.object,F=C.property;if(T.type==="Identifier"&&T.name==="require"&&F.name==="resolve")X=!0;else return}else return;let H=Z.arguments;if(H.length===0)return;let V=H[0];if(V.type!=="Literal"||typeof V.value!=="string")return;let U=V.value,{resolved:B,isExternal:q}=I_($,U,J,Q),L={isRequire:!0};if(X)L.isRequireResolve=!0;if(q)L.isExternal=!0;if(B===null&&!q)L.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:B,dstSymbolName:null,metaJson:JSON.stringify(L),...B===null?{specifier:U}:{}})}}).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(V){if(!V)return null;let U=J.get(V.root);if(V.parts.length===0){if(U)return{dstFilePath:U.path,dstSymbolName:U.importedName,resolution:"import"};return{dstFilePath:$,dstSymbolName:V.root,resolution:"local"}}else{if(U&&U.importedName==="*"){let B=V.parts[V.parts.length-1];return{dstFilePath:U.path,dstSymbolName:B,resolution:"namespace"}}return{dstFilePath:$,dstSymbolName:V.full,resolution:"local-member"}}}function X(V,U){let B=T_(V.callee),q=Y(B);if(q){let L=Z(),C={};if(U)C.isNew=!0;if(L===null)C.scope="module";Q.push({type:"calls",srcFilePath:$,srcSymbolName:L,dstFilePath:q.dstFilePath,dstSymbolName:q.dstSymbolName,...Object.keys(C).length>0?{metaJson:JSON.stringify(C)}:{}})}}function H(V,U){if(V.type==="FunctionDeclaration"){z.push(V.id?.name??"anonymous");return}if(V.type==="FunctionExpression"||V.type==="ArrowFunctionExpression"){if(U?.type==="VariableDeclarator"){let L=U.id,C=L.type==="Identifier"?L.name:"anonymous";z.push(C);return}if(U?.type==="MethodDefinition"||U?.type==="TSAbstractMethodDefinition"){let L=U.key,C=W[W.length-1]??"",T="name"in L?L.name:"anonymous",F=C?`${C}.${T}`:T;z.push(F);return}let B=Z(),q=B?`${B}.<anonymous>`:"<anonymous>";z.push(q)}}return wJ(_,{enter(V,U){if(V.type==="ClassDeclaration"||V.type==="ClassExpression"){W.push(V.id?.name??"AnonymousClass");return}if(V.type==="FunctionDeclaration"||V.type==="FunctionExpression"||V.type==="ArrowFunctionExpression"){H(V,U);return}if(V.type==="CallExpression"){X(V,!1);return}if(V.type==="NewExpression"){X(V,!0);return}},leave(V){if(V.type==="ClassDeclaration"||V.type==="ClassExpression"){W.pop();return}if(V.type==="FunctionDeclaration"||V.type==="FunctionExpression"||V.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 H=T_(Z.superClass);if(H){let V=w$(H,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Y,...V})}}let X=Z.implements??[];for(let H of X){let V=T_(H.expression);if(!V)continue;let U=w$(V,$,J);Q.push({type:"implements",srcFilePath:$,srcSymbolName:Y,...U})}}return new BJ({TSInterfaceDeclaration(Z){let Y=Z.id.name??"AnonymousInterface",X=Z.extends;for(let H of X){let V=T_(H.expression);if(!V)continue;let U=w$(V,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Y,...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 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:H}=_,V=S_(W,Q),B=s_($,V,Z,Y?(L,C,T)=>{let F=D_(L,C,T);for(let x of F){let b=E_(W,x);if(X){let p=r(b,X);if(Y.has(`${p}::${b}`))return[x]}else if(Y.has(`${J}::${b}`))return[x]}return[]}:void 0,H),q=[];for(let L of B){if(L.dstFilePath===null){let x=E_(W,L.srcFilePath),b;if(L.metaJson)try{b=JSON.parse(L.metaJson)}catch{}let p=b?.isExternal===!0;q.push({project:J,type:L.type,srcFilePath:x,srcSymbolName:L.srcSymbolName??null,dstProject:null,dstFilePath:null,dstSymbolName:L.dstSymbolName??null,metaJson:L.metaJson??null,specifier:L.specifier??null,isExternal:p?1:0});continue}let C=E_(W,L.dstFilePath);if(C.startsWith(".."))continue;let T=E_(W,L.srcFilePath),F=X?r(C,X):J;q.push({project:J,type:L.type,srcFilePath:T,srcSymbolName:L.srcSymbolName??null,dstProject:F,dstFilePath:C,dstSymbolName:L.dstSymbolName??null,metaJson:L.metaJson??null,specifier:L.specifier??null,isExternal:0})}return z.replaceFileRelations(J,Q,q),q.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=P_(J),z=IJ(_),W=[],Z=[...$].sort((X,H)=>X.start-H.start),Y=null;for(let X of Z)if(X.type==="Block"&&X.value.startsWith("*")){Y=null;let H=`/*${X.value}*/`,V=l_(H);if(DJ(V))continue;let U=V;if(!U.tags?.length)continue;let B=X_(Q,X.end),q=D$(z,B.line,3),L=J.slice(X.start,X.end);for(let C of U.tags){let T=[C.name,C.description].filter(Boolean).join(" "),F=`@${C.tag}`,x=L.indexOf(F),b;if(x>=0){let p=X.start+x,s=J.indexOf(`
|
|
4
|
+
`,p),o=s>=0?Math.min(s,X.end):X.end;b=r_(Q,p,o)}else b=r_(Q,X.start,X.end);W.push({tag:C.tag,value:T,source:"jsdoc",span:b,symbolName:q})}}else if(X.type==="Block"){Y=null;let H=X.value.split(`
|
|
5
|
+
`),V=0;for(let U of H){let B=U.replace(/^\s*\*?\s?/,""),q=$0.exec(B);if(q){let L=q[1],C=q[2]?.trim()??"",T=`@${L}`,F=U.indexOf(T),x=X.start+2+V+(F>=0?F:0),b=X.start+2+V+U.length,p=r_(Q,x,b),s=X_(Q,X.end),o=D$(z,s.line,3);W.push({tag:L,value:C,source:"block",span:p,symbolName:o})}V+=U.length+1}}else{let H=X.value,V=$0.exec(H),U=X_(Q,X.start),B=X_(Q,X.end);if(V){let q=V[1],L=V[2]?.trim()??"",C=`@${q}`,T=H.indexOf(C),F=X.start+2+(T>=0?T:0),x=r_(Q,F,X.end),b=D$(z,B.line,3),p={tag:q,value:L,source:"line",span:x,symbolName:b};W.push(p),Y={annotation:p,endLine:B.line}}else if(Y&&U.line===Y.endLine+1){let q=H.trim();if(q)Y.annotation.value+=" "+q,Y.annotation.span.end=X_(Q,X.end),Y.endLine=B.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[V,U]of $)if(!_.has(V))J.push({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint});for(let[V,U]of _)if(!$.has(V))Q.push({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint});if(!J.length||!Q.length)return{renamed:z,added:J,removed:Q};let W=new Map,Z=new Map;for(let V of J){let U=W.get(V.filePath)??[];U.push(V),W.set(V.filePath,U)}for(let V of Q){let U=Z.get(V.filePath)??[];U.push(V),Z.set(V.filePath,U)}let Y=new Set,X=new Set;for(let[V,U]of W){let B=Z.get(V);if(!B)continue;for(let q of new Set(U.map((L)=>L.kind))){let L=U.filter((b)=>b.kind===q&&!Y.has(b)),C=B.filter((b)=>b.kind===q&&!X.has(b));if(!L.length||!C.length)continue;let T=(b,p)=>{return p.get(`${b.filePath}::${b.name}`)?.structuralFingerprint??null},F=(b,p)=>{return p.get(`${b.filePath}::${b.name}`)?.startLine??0},x=new Map;for(let b of C){let p=T(b,_);if(!p)continue;let s=x.get(p)??[];s.push(b),x.set(p,s)}for(let b of L){if(Y.has(b))continue;let p=T(b,$);if(!p)continue;let s=x.get(p);if(!s)continue;let o=s.filter((K)=>!X.has(K));if(!o.length)continue;let z_=o[0];if(o.length>1){let K=F(b,$),u=Math.abs(F(z_,_)-K);for(let D=1;D<o.length;D++){let w=Math.abs(F(o[D],_)-K);if(w<u)u=w,z_=o[D]}}z.push({oldName:z_.name,newName:b.name,filePath:V,kind:q}),Y.add(b),X.add(z_)}}}let H=z.filter((V)=>!V.oldName.includes("."));for(let V of H){let U=`${V.oldName}.`,B=`${V.newName}.`,q=Q.filter((C)=>C.filePath===V.filePath&&C.name.startsWith(U)&&!X.has(C)),L=J.filter((C)=>C.filePath===V.filePath&&C.name.startsWith(B)&&!Y.has(C));for(let C of q){let T=C.name.slice(U.length),F=L.find((x)=>x.name.slice(B.length)===T);if(F)z.push({oldName:C.name,newName:F.name,filePath:V.filePath,kind:C.kind}),Y.add(F),X.add(C)}}return{renamed:z,added:J.filter((V)=>!Y.has(V)),removed:Q.filter((V)=>!X.has(V))}}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")){d_(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??i_;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 g of this.opts.boundaries)for(let[R,m]of Q.getFilesMap(g.project))M.set(R,m);let I=await s$({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>M}});Y=I.changed,X=I.deleted}let H=await this.tsconfigPathsRaw??void 0,V=new Map;for(let M of X){let I=r(M,this.opts.boundaries),g=z.getFileSymbols(I,M);V.set(M,g)}let U=crypto.randomUUID(),B=new Map,q=new Map,L=(M)=>({name:M.name,filePath:M.filePath,kind:M.kind,fingerprint:M.fingerprint,structuralFingerprint:M.structuralFingerprint??null,startLine:M.startLine,isExported:M.isExported??0});if($)for(let M of this.opts.boundaries)for(let I of Q.getAllFiles(M.project))for(let g of z.getFileSymbols(M.project,I.filePath))B.set(`${g.filePath}::${g.name}`,L(g));else{for(let M of Y){let I=r(M.filePath,this.opts.boundaries);for(let g of z.getFileSymbols(I,M.filePath))B.set(`${g.filePath}::${g.name}`,L(g))}for(let[,M]of V)for(let I of M)B.set(`${I.filePath}::${I.name}`,L(I))}let C=(M)=>`${M.type}|${M.srcFilePath}|${M.dstFilePath??""}|${M.srcSymbolName??""}|${M.dstSymbolName??""}|${V_(M.metaJson??"")}`,T=new Map;if($)for(let M of this.opts.boundaries)for(let I of Q.getAllFiles(M.project))for(let g of W.getOutgoing(M.project,I.filePath))T.set(C(g),g);else{for(let M of Y){let I=r(M.filePath,this.opts.boundaries);for(let g of W.getOutgoing(I,M.filePath))T.set(C(g),g)}for(let M of X){let I=r(M,this.opts.boundaries);for(let g of W.getOutgoing(I,M))T.set(C(g),g)}}let{annotationRepo:F,changelogRepo:x}=this.opts,b=()=>{for(let M of X){let I=r(M,this.opts.boundaries);if(z.deleteFileSymbols(I,M),W.deleteFileRelations(I,M),W.deleteIncomingRelations(I,M),F)F.deleteFileAnnotations(I,M);Q.deleteFile(I,M)}},p=0,s=async()=>{let{projectRoot:M,boundaries:I}=this.opts,{parseCache:g}=this.opts,R=0,m=0,S=0,f=[],G=[];for(let y of Y)try{let l=S_(M,y.filePath),K_=Bun.file(l),N_=await K_.text(),f$=y.contentHash||V_(N_),P$=r(y.filePath,I);Q.upsertFile({project:P$,filePath:y.filePath,mtimeMs:K_.lastModified,size:K_.size,contentHash:f$,updatedAt:new Date().toISOString(),lineCount:N_.split(`
|
|
6
|
+
`).length});let z$=(this.opts.parseSourceFn??f_)(l,N_);if(z0(z$))throw z$.data;let g1=z$;G.push({filePath:y.filePath,text:N_,contentHash:f$,parsed:g1,project:P$})}catch(l){this.logger.error(`[IndexCoordinator] Failed to prepare ${y.filePath}:`,l),f.push(y.filePath)}let i=new Set;for(let y of I)for(let[l]of Q.getFilesMap(y.project))i.add(`${y.project}::${l}`);return Z.transaction(()=>{for(let y of G){if(K$({parsed:y.parsed,project:y.project,filePath:y.filePath,contentHash:y.contentHash,symbolRepo:z}),m+=B$({ast:y.parsed.program,project:y.project,filePath:y.filePath,relationRepo:W,projectRoot:M,tsconfigPaths:H,knownFiles:i,boundaries:I,module:y.parsed.module}),F)S+=I$({parsed:y.parsed,project:y.project,filePath:y.filePath,annotationRepo:F});g.set(y.filePath,y.parsed),R+=z.getFileSymbols(y.project,y.filePath).length}}),{symbols:R,relations:m,annotations:S,failedFiles:f}},o=0,z_=0,K=[];if($){let{projectRoot:M,boundaries:I}=this.opts,{parseCache:g}=this.opts,R=[];for(let S=0;S<Y.length;S+=W0){let f=Y.slice(S,S+W0),G=await Promise.allSettled(f.map(async(i)=>{let y=S_(M,i.filePath),l=Bun.file(y),K_=await l.text(),N_=i.contentHash||V_(K_);return{filePath:i.filePath,text:K_,contentHash:N_,mtimeMs:l.lastModified,size:l.size}}));for(let i=0;i<G.length;i++){let y=G[i];if(y.status==="fulfilled")R.push(y.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",y.reason),K.push(f[i].filePath)}}let m=[];Z.transaction(()=>{for(let G of R){let i=r(G.filePath,I);Q.deleteFile(i,G.filePath)}for(let G of X){let i=r(G,I);if(z.deleteFileSymbols(i,G),W.deleteFileRelations(i,G),W.deleteIncomingRelations(i,G),F)F.deleteFileAnnotations(i,G);Q.deleteFile(i,G)}for(let G of R){let i=r(G.filePath,I);Q.upsertFile({project:i,filePath:G.filePath,mtimeMs:G.mtimeMs,size:G.size,contentHash:G.contentHash,updatedAt:new Date().toISOString(),lineCount:G.text.split(`
|
|
7
|
+
`).length})}let S=new Set;for(let G of I)for(let[i]of Q.getFilesMap(G.project))S.add(`${G.project}::${i}`);let f=this.opts.parseSourceFn??f_;for(let G of R){let i=r(G.filePath,I),y=f(S_(M,G.filePath),G.text);if(z0(y))throw y.data;let l=y;if(m.push({filePath:G.filePath,parsed:l}),K$({parsed:l,project:i,filePath:G.filePath,contentHash:G.contentHash,symbolRepo:z}),F)p+=I$({parsed:l,project:i,filePath:G.filePath,annotationRepo:F});z_+=B$({ast:l.program,project:i,filePath:G.filePath,relationRepo:W,projectRoot:M,tsconfigPaths:H,knownFiles:S,boundaries:I,module:l.module}),o+=z.getFileSymbols(i,G.filePath).length}});for(let S of m)g.set(S.filePath,S.parsed)}else{b();let M=await s();o=M.symbols,z_=M.relations,p=M.annotations,K=M.failedFiles}for(let M of Y){let I=r(M.filePath,this.opts.boundaries);for(let g of z.getFileSymbols(I,M.filePath))q.set(`${g.filePath}::${g.name}`,L(g))}let u=new Map;for(let M of Y){let I=r(M.filePath,this.opts.boundaries);for(let g of W.getOutgoing(I,M.filePath))u.set(C(g),g)}let D=(M)=>({type:M.type,srcFilePath:M.srcFilePath,dstFilePath:M.dstFilePath,srcSymbolName:M.srcSymbolName,dstSymbolName:M.dstSymbolName,dstProject:M.dstProject,metaJson:M.metaJson}),w={added:[...u.entries()].filter(([M])=>!T.has(M)).map(([,M])=>D(M)),removed:[...T.entries()].filter(([M])=>!u.has(M)).map(([,M])=>D(M))},A={added:[],modified:[],removed:[]};for(let[M,I]of q){let g=B.get(M);if(!g)A.added.push({name:I.name,filePath:I.filePath,kind:I.kind,isExported:Boolean(I.isExported)});else{let R=g.fingerprint!==I.fingerprint,m=g.isExported!==I.isExported,S=g.structuralFingerprint!==null&&I.structuralFingerprint!==null&&g.structuralFingerprint!==I.structuralFingerprint;if(R||m||S)A.modified.push({name:I.name,filePath:I.filePath,kind:I.kind,isExported:Boolean(I.isExported)})}}for(let[M,I]of B)if(!q.has(M))A.removed.push({name:I.name,filePath:I.filePath,kind:I.kind,isExported:Boolean(I.isExported)});let N=Q0(B,q),k=new Set(N.renamed.map((M)=>`${M.filePath}::${M.oldName}`)),j=new Set(N.renamed.map((M)=>`${M.filePath}::${M.newName}`));A.added=A.added.filter((M)=>!j.has(`${M.filePath}::${M.name}`)),A.removed=A.removed.filter((M)=>!k.has(`${M.filePath}::${M.name}`));let v=[];if(!$){for(let[I,g]of V)for(let R of g){if(!R.fingerprint)continue;let m=r(I,this.opts.boundaries),S=z.getByFingerprint(m,R.fingerprint);if(S.length===1){let f=S[0];W.retargetRelations({dstProject:m,oldFile:I,oldSymbol:R.name,newFile:f.filePath,newSymbol:f.name}),v.push({name:f.name,filePath:f.filePath,kind:f.kind,oldFilePath:I,isExported:f.isExported??0})}}let M=new Set(v.map((I)=>`${I.oldFilePath}::${I.name}`));for(let I of N.removed){if(M.has(`${I.filePath}::${I.name}`))continue;let R=B.get(`${I.filePath}::${I.name}`)?.fingerprint;if(!R)continue;let m=r(I.filePath,this.opts.boundaries),S=z.getByFingerprint(m,R);if(S.length===1){let f=S[0];if(f.filePath!==I.filePath||f.name!==I.name)W.retargetRelations({dstProject:m,oldFile:I.filePath,oldSymbol:I.name,newFile:f.filePath,newSymbol:f.name}),v.push({name:f.name,filePath:f.filePath,kind:f.kind,oldFilePath:I.filePath,isExported:f.isExported??0})}}}if(v.length){let M=new Set(v.map((g)=>`${g.filePath}::${g.name}`)),I=new Set(v.map((g)=>`${g.oldFilePath}::${g.name}`));A.added=A.added.filter((g)=>!M.has(`${g.filePath}::${g.name}`)),A.removed=A.removed.filter((g)=>!I.has(`${g.filePath}::${g.name}`))}if(x){let M=new Date().toISOString(),I=$?1:0,g=[];for(let R of A.added){let m=`${R.filePath}::${R.name}`,S=q.get(m),f=r(R.filePath,this.opts.boundaries);g.push({project:f,changeType:"added",symbolName:R.name,symbolKind:R.kind,filePath:R.filePath,oldName:null,oldFilePath:null,fingerprint:S?.fingerprint??null,changedAt:M,isFullIndex:I,indexRunId:U})}for(let R of A.modified){let m=q.get(`${R.filePath}::${R.name}`),S=r(R.filePath,this.opts.boundaries);g.push({project:S,changeType:"modified",symbolName:R.name,symbolKind:R.kind,filePath:R.filePath,oldName:null,oldFilePath:null,fingerprint:m?.fingerprint??null,changedAt:M,isFullIndex:I,indexRunId:U})}for(let R of A.removed){let m=`${R.filePath}::${R.name}`,S=B.get(m),f=r(R.filePath,this.opts.boundaries);g.push({project:f,changeType:"removed",symbolName:R.name,symbolKind:R.kind,filePath:R.filePath,oldName:null,oldFilePath:null,fingerprint:S?.fingerprint??null,changedAt:M,isFullIndex:I,indexRunId:U})}for(let R of N.renamed){let m=q.get(`${R.filePath}::${R.newName}`),S=r(R.filePath,this.opts.boundaries);g.push({project:S,changeType:"renamed",symbolName:R.newName,symbolKind:R.kind,filePath:R.filePath,oldName:R.oldName,oldFilePath:null,fingerprint:m?.fingerprint??null,changedAt:M,isFullIndex:I,indexRunId:U})}for(let R of v){let m=q.get(`${R.filePath}::${R.name}`),S=r(R.filePath,this.opts.boundaries);g.push({project:S,changeType:"moved",symbolName:R.name,symbolKind:R.kind,filePath:R.filePath,oldName:null,oldFilePath:R.oldFilePath,fingerprint:m?.fingerprint??null,changedAt:M,isFullIndex:I,indexRunId:U})}if(g.length)try{Z.transaction(()=>{x.insertBatch(g)})}catch(R){this.logger.error("[IndexCoordinator] changelog insert failed:",R)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let R=new Date(Date.now()-2592000000).toISOString();try{for(let m of this.opts.boundaries)x.pruneOlderThan(m.project,R)}catch(m){this.logger.error("[IndexCoordinator] changelog pruning failed:",m)}}}return{indexedFiles:Y.length,removedFiles:X.length,totalSymbols:o,totalRelations:z_,totalAnnotations:p,durationMs:Date.now()-J,changedFiles:Y.map((M)=>M.filePath),deletedFiles:[...X],failedFiles:K,changedSymbols:A,renamedSymbols:N.renamed.map((M)=>({oldName:M.oldName,newName:M.newName,filePath:M.filePath,kind:M.kind,isExported:Boolean(q.get(`${M.filePath}::${M.newName}`)?.isExported)})),movedSymbols:v.map((M)=>({name:M.name,oldFilePath:M.oldFilePath,newFilePath:M.filePath,kind:M.kind,isExported:Boolean(M.isExported)})),changedRelations:w}}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 NJ(_){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()-NJ(Y.heartbeat_at))/1000),H=z(Y.pid);if(H&&Z&&Y.instance_id&&Y.instance_id!==Z&&Y.pid===$)return _.replaceOwner($,Z),"owner";if(H&&X<W)return"reader";return _.replaceOwner($,Z),"owner"})}function Z0(_,$){_.deleteOwner($)}function X0(_,$){_.touchOwner($)}class y_{#_;#$=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 y_(_)}get(_){return this.lru.get(_)}set(_,$){this.lru.set(_,$)}invalidate(_){this.lru.delete(_)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function N$(_){let{symbolRepo:$,project:J,query:Q}=_,z=Q.project??J,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=u_(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 q$(_){let{relationRepo:$,project:J,query:Q}=_;if(Q.srcFilePath&&Q.srcFilePathPattern)throw new O("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if(Q.dstFilePath&&Q.dstFilePathPattern)throw new O("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,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:Y}).map((V)=>{let U;if(V.metaJson)try{U=JSON.parse(V.metaJson)}catch{}return{type:V.type,srcFilePath:V.srcFilePath,srcSymbolName:V.srcSymbolName,dstFilePath:V.dstFilePath,dstSymbolName:V.dstSymbolName,dstProject:V.dstProject,isExternal:V.isExternal===1,specifier:V.specifier,metaJson:V.metaJson??void 0,meta:U}});if(Q.srcFilePathPattern||Q.dstFilePathPattern){let V=Q.srcFilePathPattern?new Bun.Glob(Q.srcFilePathPattern):null,U=Q.dstFilePathPattern?new Bun.Glob(Q.dstFilePathPattern):null;H=H.filter((B)=>(!V||V.match(B.srcFilePath))&&(!U||B.dstFilePath===null||U.match(B.dstFilePath)))}if(Z&&W!==void 0&&H.length>W)H=H.slice(0,W);return H}import{findInFiles as qJ,Lang as uJ}from"@ast-grep/napi";function SJ(_){let $=new Set,J=/\${1,3}([A-Z_][A-Z_0-9]*)/g,Q;while((Q=J.exec(_))!==null)$.add(Q[0]);return[...$]}function gJ(_,$){if($.length===0)return;let J={},Q=!1;for(let z of $){let W=_.getMatch(z);if(W){let Y=W.range();J[z]={text:W.text(),startLine:Y.start.line+1,endLine:Y.end.line+1},Q=!0;continue}let Z=_.getMultipleMatches(z);if(Z.length>0){let Y=Z[0].range(),X=Z[Z.length-1].range();J[z]={text:Z.map((H)=>H.text()).join(", "),startLine:Y.start.line+1,endLine:X.end.line+1},Q=!0}}return Q?J:void 0}async function u$(_){if(_.filePaths.length===0)return[];let $=SJ(_.pattern),J=[];return await qJ(uJ.TypeScript,{paths:_.filePaths,matcher:{rule:{pattern:_.pattern}}},(Q,z)=>{if(Q){console.warn("[patternSearch] findInFiles callback error:",Q);return}for(let W of z){let Z=W.range(),Y={filePath:W.getRoot().filename(),startLine:Z.start.line+1,endLine:Z.end.line+1,matchedText:W.text()},X=gJ(W,$);if(X)Y.captures=X;J.push(Y)}}),J}import $_ from"typescript";import{isErr as mJ}from"@zipbul/result";import H_ from"typescript";import RJ from"path";import{err as S$}from"@zipbul/result";function TJ(_){try{return y$("fs").readFileSync(_,"utf-8")}catch{return}}function FJ(_){try{return y$("fs").readFileSync(_,"utf-8")}catch{return}}class o_{#_;#$;#J=!1;__testing__;constructor(_,$){this.#_=_,this.#$=$,this.__testing__={host:$}}static create(_,$={}){let J=$.readConfigFile??TJ,Q=$.resolveNonTrackedFile??FJ,z=RJ.dirname(_),W=J(_);if(W===void 0)return S$(new O("semantic",`tsconfig not found: ${_}`));let Z=H_.parseJsonText(_,W),Y=Z.parseDiagnostics;if(Y&&Y.length>0){let U=Y.map((B)=>H_.flattenDiagnosticMessageText(B.messageText,`
|
|
8
|
+
`)).join("; ");return S$(new O("semantic",`tsconfig parse error: ${U}`))}let X=H_.parseJsonSourceFileConfigFileContent(Z,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(U)=>J(U)!==void 0||Q(U)!==void 0,readFile:(U)=>J(U)??Q(U)},z);if(X.errors.length>0){let U=X.errors.filter((B)=>B.category===H_.DiagnosticCategory.Error&&B.code!==18003);if(U.length>0){let B=U.map((q)=>H_.flattenDiagnosticMessageText(q.messageText,`
|
|
9
|
+
`)).join("; ");return S$(new O("semantic",`tsconfig compile error: ${B}`))}}let H=new V0(X.fileNames,X.options,z,Q),V=H_.createLanguageService(H);return new o_(V,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 V0{#_;#$;#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 a from"typescript";import kJ from"typescript";function Q_(_,$){if($<0||$>=_.getEnd())return;function J(Q){let z=Q.getStart(_,!1),W=Q.getEnd();if($<z||$>=W)return;let Z;return kJ.forEachChild(Q,(Y)=>{if(!Z)Z=J(Y)}),Z??Q}return J(_)}var t_=8;function GJ(_){return!!(_.flags&a.TypeFlags.Object)&&!!(_.objectFlags&a.ObjectFlags.Reference)}function U_(_,$,J=0,Q){if(Q){let L=Q.get($);if(L)return L}let z=_.typeToString($),W=$.flags,Z=!!(W&a.TypeFlags.Union),Y=!!(W&a.TypeFlags.Intersection),X;if(J<t_&&GJ($)){let L=_.getTypeArguments($);if(L.length>0)X=L}let H=!!(W&a.TypeFlags.TypeParameter)||X!==void 0&&X.length>0,V;if(Z&&J<t_)V=$.types.map((L)=>U_(_,L,J+1,Q));else if(Y&&J<t_)V=$.types.map((L)=>U_(_,L,J+1,Q));let U;if(X&&X.length>0)U=X.map((L)=>U_(_,L,J+1,Q));let B;if(J<t_&&!!(W&a.TypeFlags.Object)&&!Z&&!Y){let L=_.getPropertiesOfType($);if(L.length>0&&L.length<=50){let C=$.symbol?.declarations?.[0];B=[];for(let T of L){let F=T.declarations?.[0]??C;if(!F)continue;try{let x=_.getTypeOfSymbolAtLocation(T,F);B.push({name:T.getName(),type:U_(_,x,J+1,Q)})}catch{}}if(B.length===0)B=void 0}}let q={text:z,flags:W,isUnion:Z,isIntersection:Y,isGeneric:H,members:V,typeArguments:U,properties:B};if(Q)Q.set($,q);return q}function jJ(_){return a.isFunctionDeclaration(_)||a.isVariableDeclaration(_)||a.isClassDeclaration(_)||a.isInterfaceDeclaration(_)||a.isTypeAliasDeclaration(_)||a.isEnumDeclaration(_)||a.isMethodDeclaration(_)||a.isPropertyDeclaration(_)||a.isPropertySignature(_)||a.isMethodSignature(_)}var g$="/__gildash_type_probe__.ts";class R${program;#_=null;constructor(_){this.program=_}#$(_){if(this.#_===_)return;this.program.notifyFileChanged(g$,`declare const __gildash_probe__: ${_};`),this.#_=_}#J(_,$){let J=_.getSourceFile(g$);if(!J)return null;let Q=J.statements[0];if(!Q||!a.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(g$),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=Q_(z,$);if(!W)return null;if(!a.isIdentifier(W)&&!a.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=Q_(Z,$);if(!Y||!a.isIdentifier(Y))return null;let X=W.getSourceFile(J);if(!X)return null;let H=Q_(X,Q);if(!H||!a.isIdentifier(H))return null;try{let V=z.getTypeAtLocation(Y),U=z.getTypeAtLocation(H);return z.isTypeAssignableTo(V,U)}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=Q_(Z,$);if(!Y||!a.isIdentifier(Y)&&!a.isTypeNode(Y))return null;try{let X=this.#J(z,W);if(!X)return null;let H=W.getTypeAtLocation(Y);if(Q?.anyConstituent&&H.isUnion())return H.types.some((V)=>W.isTypeAssignableTo(V,X));return W.isTypeAssignableTo(H,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 H=Y.getEnd();for(let V of $){if(V<0||V>=H)continue;let U=Q_(Y,V);if(!U||!a.isIdentifier(U)&&!a.isTypeNode(U))continue;try{let B=Z.getTypeAtLocation(U);if(Q?.anyConstituent&&B.isUnion())z.set(V,B.types.some((q)=>Z.isTypeAssignableTo(q,X)));else z.set(V,Z.isTypeAssignableTo(B,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 H=Q_(W,X);if(!H)continue;if(!a.isIdentifier(H)&&!a.isTypeNode(H))continue;try{let V=z.getTypeAtLocation(H);J.set(X,U_(z,V,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(jJ(Y)&&Y.name&&a.isIdentifier(Y.name)){let X=Y.name;try{let H=Q.getTypeAtLocation(X),V=X.getStart(z);$.set(V,U_(Q,H,0,W))}catch{}}a.forEachChild(Y,Z)}return Z(z),$}}import M_ from"typescript";var EJ=1000,vJ=1;function bJ(_){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},H=_;if(H.parent)X.parent=bJ(H.parent);let V=J&&!!(_.flags&M_.SymbolFlags.Alias)?J.getAliasedSymbol(_):_;if($<vJ){let U=V.flags,B=!!(U&M_.SymbolFlags.Enum),q=!!(U&(M_.SymbolFlags.NamespaceModule|M_.SymbolFlags.ValueModule)),L=!!(U&(M_.SymbolFlags.Class|M_.SymbolFlags.Interface));if(B&&V.exports&&V.exports.size>0){let C=[];V.exports.forEach((T)=>{C.push(e_(T,$+1,J))}),X.members=C}else if(L&&V.members&&V.members.size>0){let C=[];V.members.forEach((T)=>{C.push(e_(T,$+1,J))}),X.members=C}if(q&&V.exports&&V.exports.size>0){let C=[];V.exports.forEach((T)=>{C.push(e_(T,$+1,J))}),X.exports=C}}return X}class T${#_;#$;#J=new Map;constructor(_,$=EJ){this.#_=_,this.#$=new y_($)}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=Q_(W,$);if(!Z||!M_.isIdentifier(Z))return null;let Y=this.#_.getChecker(),X=Y.getSymbolAtLocation(Z);if(!X)return null;let H=e_(X,0,Y);this.#$.set(J,H);let V=this.#J.get(_);if(!V)V=new Set,this.#J.set(_,V);return V.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 fJ from"typescript";class F${#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=Q_(Q,$);if(!z||!fJ.isIdentifier(z))return[];let Z=this.#_.getLanguageService().findReferences(_,$);if(!Z||Z.length===0)return[];let Y=[];for(let X of Z)for(let H of X.references){let V=J.getSourceFile(H.fileName);if(!V)continue;let{line:U,character:B}=V.getLineAndCharacterOfPosition(H.textSpan.start);Y.push({filePath:H.fileName,position:H.textSpan.start,line:U+1,column:B,isDefinition:H.isDefinition??!1,isWrite:H.isWriteAccess??!1})}return Y}}import d from"typescript";function PJ(_,$){let J=Q_(_,$);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 d.isClassDeclaration(_)||d.isClassExpression(_)||d.isFunctionDeclaration(_)||d.isFunctionExpression(_)||d.isArrowFunction(_)||d.isVariableDeclaration(_)||d.isObjectLiteralExpression(_)}function U0(_){if(d.isClassDeclaration(_)||d.isClassExpression(_))return"class";if(d.isFunctionDeclaration(_)||d.isFunctionExpression(_)||d.isArrowFunction(_))return"function";if(d.isObjectLiteralExpression(_))return"object";if(d.isVariableDeclaration(_)&&_.initializer)return U0(_.initializer);return"class"}function yJ(_,$){if(d.isClassDeclaration(_)||d.isFunctionDeclaration(_))return _.name?.getText($)??"";if(d.isClassExpression(_))return _.name?.getText($)??"";if(d.isVariableDeclaration(_)&&d.isIdentifier(_.name))return _.name.getText($);if(d.isFunctionExpression(_))return _.name?.getText($)??"";if(d.isArrowFunction(_)&&_.parent&&d.isVariableDeclaration(_.parent)){if(d.isIdentifier(_.parent.name))return _.parent.name.getText($)}if(d.isObjectLiteralExpression(_)&&_.parent&&d.isVariableDeclaration(_.parent)){if(d.isIdentifier(_.parent.name))return _.parent.name.getText($)}return""}function xJ(_){if(!d.isClassDeclaration(_)&&!d.isClassExpression(_))return!1;let $=_.heritageClauses;if(!$)return!1;return $.some((J)=>J.token===d.SyntaxKind.ImplementsKeyword)}class k${#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=Q_(Q,$);if(!z||!d.isIdentifier(z))return[];let Z=this.#_.getLanguageService().getImplementationAtPosition(_,$);if(!Z||Z.length===0)return[];let Y=[];for(let X of Z){if(X.kind===d.ScriptElementKind.interfaceElement||X.kind===d.ScriptElementKind.typeElement)continue;let H=J.getSourceFile(X.fileName);if(!H)continue;let V=PJ(H,X.textSpan.start);if(!V)continue;let U=U0(V),B=yJ(V,H),q=xJ(V);Y.push({filePath:X.fileName,symbolName:B,position:X.textSpan.start,kind:U,isExplicit:q})}return Y}}function nJ(_){if($_.isFunctionDeclaration(_))return"function";if($_.isClassDeclaration(_))return"class";if($_.isInterfaceDeclaration(_))return"interface";if($_.isTypeAliasDeclaration(_))return"type";if($_.isEnumDeclaration(_))return"enum";if($_.isVariableDeclaration(_))return"const";if($_.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(mJ(J))return J;let Q=J,z=$.typeCollector??new R$(Q),W=$.symbolGraph??new T$(Q),Z=$.referenceResolver??new F$(Q),Y=$.implementationFinder??new k$(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=Q_(Q,$);if(!z)return null;let W=this.#_.getChecker(),Z=W.getTypeAtLocation(z);if(!(Z.flags&$_.TypeFlags.Object)||!(Z.objectFlags&$_.ObjectFlags.ClassOrInterface))return null;let Y=W.getBaseTypes(Z);if(!Y||Y.length===0)return[];let X=new Map;return Y.map((H)=>U_(W,H,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 H=X.getName(),V=X.declarations?.[0],U="unknown";if(V){if(U=nJ(V),U==="unknown"&&$_.isExportAssignment(V))U="const"}let B=null;try{let q=z.getTypeOfSymbolAtLocation(X,V??Q);B=U_(z,q,0,Y)}catch{}$.push({name:H,kind:U,resolvedType:B})}}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 $_.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={[$_.DiagnosticCategory.Error]:"error",[$_.DiagnosticCategory.Warning]:"warning",[$_.DiagnosticCategory.Suggestion]:"suggestion",[$_.DiagnosticCategory.Message]:"suggestion"};return(($?.preEmit)?$_.getPreEmitDiagnostics(J,Q):J.getSemanticDiagnostics(Q)).map((Z)=>{let Y=1,X=0;if(Z.file&&Z.start!==void 0){let H=$_.getLineAndCharacterOfPosition(Z.file,Z.start);Y=H.line+1,X=H.character}return{filePath:Z.file?.fileName??_,line:Y,column:X,message:$_.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 hJ}from"drizzle-orm";var K0=80;class G${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?hJ`${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 F_,and as L0,sql as x_,gt as pJ,gte as iJ}from"drizzle-orm";var w0=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+=w0)this.db.drizzleDb.insert(J_).values($.slice(J,J+w0)).run()}getSince(_){return this.db.drizzleDb.select().from(J_).where(L0(F_(J_.project,_.project),iJ(J_.changedAt,_.since),_.symbolName?F_(J_.symbolName,_.symbolName):void 0,_.changeTypes?.length?x_`${J_.changeType} IN (${x_.join(_.changeTypes.map(($)=>x_`${$}`),x_`, `)})`:void 0,_.filePath?F_(J_.filePath,_.filePath):void 0,_.includeFullIndex?void 0:F_(J_.isFullIndex,0),_.indexRunId?F_(J_.indexRunId,_.indexRunId):void 0,_.afterId?pJ(J_.id,_.afterId):void 0)).orderBy(J_.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete(J_).where(L0(F_(J_.project,_),x_`${J_.changedAt} < ${$}`)).run().changes}}function B0(_){let{annotationRepo:$,project:J,query:Q}=_,z=Q.project??J,W;if(Q.text){let Y=u_(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 sJ(J,$)}}var dJ=(_,$)=>_.localeCompare($);function lJ(_){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 E$(_,$,J){let Q=lJ(J);if(Q.length===0)return!1;let z=Q.join("->");if(_.has(z))return!1;return _.add(z),$.push(Q),!0}function cJ(_){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 H of _.get(X)??[])if(!z.has(H))Y(H),W.set(X,Math.min(W.get(X)??0,W.get(H)??0));else if(Q.has(H))W.set(X,Math.min(W.get(X)??0,z.get(H)??0));if(W.get(X)===z.get(X)){let H=[],V="";do V=J.pop()??"",Q.delete(V),H.push(V);while(V!==X&&J.length>0);Z.push(H)}};for(let X of _.keys())if(!z.has(X))Y(X);return{components:Z}}function aJ(_,$,J){let Q=[],z=new Set,W=[..._].sort(dJ),Z=(Y,X,H)=>{X.delete(Y);let V=H.get(Y);if(!V)return;for(let U of V)if(X.has(U))Z(U,X,H);V.clear()};for(let Y=0;Y<W.length&&Q.length<J;Y++){let X=W[Y]??"",H=new Set(W.slice(Y)),V=new Set,U=new Map,B=[],q=(C)=>($.get(C)??[]).filter((T)=>H.has(T)),L=(C)=>{if(Q.length>=J)return!0;let T=!1;B.push(C),V.add(C);for(let F of q(C)){if(Q.length>=J)break;if(F===X)E$(z,Q,B.concat(X)),T=!0;else if(!V.has(F)){if(L(F))T=!0}}if(T)Z(C,V,U);else for(let F of q(C)){let x=U.get(F)??new Set;x.add(C),U.set(F,x)}return B.pop(),T};L(X)}return Q}function sJ(_,$){let{components:J}=cJ(_),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))E$(z,Q,[X,X]);continue}let Z=$-Q.length,Y=aJ(W,_,Z);for(let X of Y){if(Q.length>=$)break;E$(z,Q,X)}}return Q}var rJ=15000;function J$(_){_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}function A_(_,$){let J=$??"__cross__";if(_.graphCache&&_.graphCacheBuiltAt!==null){if(Date.now()-_.graphCacheBuiltAt>rJ)_.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 O("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 O)throw z;throw new O("search","Gildash: getDependencies failed",{cause:z})}}function I0(_,$,J,Q=1e4){if(_.closed)throw new O("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 O)throw z;throw new O("search","Gildash: getDependents failed",{cause:z})}}async function C0(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return A_(_,J).getAffectedByChange($)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getAffected failed",{cause:Q})}}async function A0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return A_(_,$).hasCycle()}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: hasCycle failed",{cause:J})}}async function N0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return A_(_,$).getAdjacencyList()}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: getImportGraph failed",{cause:J})}}async function q0(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return A_(_,J).getTransitiveDependencies($)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getTransitiveDependencies failed",{cause:Q})}}async function u0(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return A_(_,J).getTransitiveDependents($)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getTransitiveDependents failed",{cause:Q})}}async function S0(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return A_(_,$).getCyclePaths(J)}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getCyclePaths failed",{cause:Q})}}async function g0(_,$,J){if(_.closed)throw new O("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 O)throw Q;throw new O("search","Gildash: getFanMetrics failed",{cause:Q})}}var eJ=30000,R0=15000,_Q=10;function $Q(_,$){_.boundaries=$,_.defaultProject=$[0]?.project??k_.basename(_.projectRoot)}function JQ(_,$){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 O?Q:new O("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 O?z:new O("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 QQ(_){if(!_.semanticLayer)return;let $=_.fileRepo.getAllFiles(_.defaultProject);await Promise.all($.map(async(J)=>{try{let Q=k_.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)=>$Q(_,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(JQ(_,J)).then((z)=>{if(m_(z))throw z.data}),_.watcher=Q,_.timer=setInterval(()=>{_.updateHeartbeatFn(_.db,process.pid)},eJ)}await J.fullIndex(),await QQ(_)}function zQ(_,$){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 F0(_){let{projectRoot:$,extensions:J=[".ts",".mts",".cts"],ignorePatterns:Q=["**/node_modules/**"],parseCacheCapacity:z=500,logger:W=console,existsSyncFn:Z=tJ,dbConnectionFactory:Y,watcherFactory:X,coordinatorFactory:H,repositoryFactory:V,acquireWatcherRoleFn:U=Y0,releaseWatcherRoleFn:B=Z0,updateHeartbeatFn:q=X0,discoverProjectsFn:L=i_,parseSourceFn:C=f_,extractSymbolsFn:T=R_,extractRelationsFn:F=s_,symbolSearchFn:x=N$,relationSearchFn:b=q$,patternSearchFn:p=u$,loadTsconfigPathsFn:s=b_,readFileFn:o=async(N)=>Bun.file(N).text(),unlinkFn:z_=async(N)=>{await Bun.file(N).unlink()},watchMode:K,semantic:u,semanticLayerFactory:D}=_;if(!k_.isAbsolute($))throw new O("validation",`Gildash: projectRoot must be an absolute path, got: "${$}"`);if(!Z($))throw new O("validation",`Gildash: projectRoot does not exist: "${$}"`);let w=Y?Y():new Z$({projectRoot:$}),A=w.open();if(m_(A))throw A.data;try{let N=await L($),k=N[0]?.project??k_.basename($),j=V?V():(()=>{let f=w;return{fileRepo:new X$(f),symbolRepo:new V$(f),relationRepo:new O$(f),parseCache:new A$(z)}})(),v=V?null:w,M=v?new G$(v):null,I=v?new j$(v):null,g=K??!0,R=crypto.randomUUID(),m;if(g)m=await Promise.resolve(U(w,process.pid,{instanceId:R}));else m="owner";let S={projectRoot:$,extensions:J,ignorePatterns:Q,logger:W,defaultProject:k,role:m,db:w,symbolRepo:j.symbolRepo,relationRepo:j.relationRepo,fileRepo:j.fileRepo,parseCache:j.parseCache,annotationRepo:M,changelogRepo:I,annotationSearchFn:B0,releaseWatcherRoleFn:B,parseSourceFn:C,extractSymbolsFn:T,extractRelationsFn:F,symbolSearchFn:x,relationSearchFn:b,patternSearchFn:p,readFileFn:o,unlinkFn:z_,existsSyncFn:Z,acquireWatcherRoleFn:U,updateHeartbeatFn:q,watcherFactory:X,coordinatorFactory:H,instanceId:R,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:N,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(d_($),S.tsconfigPaths=await s($),u){let f=k_.join($,"tsconfig.json");try{if(D)S.semanticLayer=D(f);else{let G=_$.create(f);if(m_(G))throw G.data;S.semanticLayer=G}}catch(G){if(G instanceof O)throw G;throw new O("semantic","Gildash: semantic layer creation failed",{cause:G})}}if(m==="owner")await T0(S,{isWatchMode:g});else{let f=0,G=async()=>{try{let i=await Promise.resolve(S.acquireWatcherRoleFn(S.db,process.pid,{instanceId:S.instanceId}));if(f=0,i==="owner"){S.role="owner";for(let y of S.onRoleChangedCallbacks)try{y("owner")}catch(l){S.logger.error("[Gildash] onRoleChanged callback threw:",l)}clearInterval(S.timer),S.timer=null;try{await T0(S,{isWatchMode:!0})}catch(y){if(S.logger.error("[Gildash] owner promotion failed, reverting to reader",y),S.role="reader",S.timer!==null)clearInterval(S.timer),S.timer=null;if(S.watcher){let l=await S.watcher.close();if(m_(l))S.logger.error("[Gildash] watcher close error during promotion rollback",l.data);S.watcher=null}if(S.coordinator)await S.coordinator.shutdown().catch((l)=>S.logger.error("[Gildash] coordinator shutdown error during promotion rollback",l)),S.coordinator=null;try{S.releaseWatcherRoleFn(S.db,process.pid)}catch(l){S.logger.error("[Gildash] failed to release watcher role during promotion rollback",l)}S.timer=setInterval(G,R0)}}}catch(i){f++;let y=i instanceof O?i:new O("watcher","Gildash: healthcheck error",{cause:i});for(let l of S.onErrorCallbacks)try{l(y)}catch(K_){S.logger.error("[Gildash] onError callback threw:",K_)}if(S.logger.error("[Gildash] healthcheck error",i),f>=_Q)S.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(S.timer),S.timer=null,Q$(S).catch((l)=>S.logger.error("[Gildash] close error during healthcheck shutdown",l))}};S.timer=setInterval(G,R0)}if(g)zQ(S,()=>Q$(S));return S}catch(N){if(w.close(),N instanceof O)throw N;throw new O("store","Gildash: initialization failed",{cause:N})}}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(k_.join(_.projectRoot,L_,h_+Q))}catch{}if(J.length>0)throw new O("close","Gildash: one or more errors occurred during close()",{cause:J})}import{isErr as k0}from"@zipbul/result";function G0(_,$,J,Q){if(_.closed)throw new O("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 O("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(!k0(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 E0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");return _.parseCache.get($)}function v0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");return _.extractSymbolsFn($)}function b0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");return _.extractRelationsFn($.program,$.filePath,_.tsconfigPaths??void 0)}import f0 from"path";function P0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.symbolRepo.getStats($??_.defaultProject)}catch(J){if(J instanceof O)throw J;throw new O("store","Gildash: getStats failed",{cause:J})}}function v$(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: searchSymbols failed",{cause:J})}}function y0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:_.defaultProject,query:$})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: searchRelations failed",{cause:J})}}function x0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.symbolSearchFn({symbolRepo:_.symbolRepo,project:void 0,query:$})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: searchAllSymbols failed",{cause:J})}}function m0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:void 0,query:$})}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: searchAllRelations failed",{cause:J})}}function n0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.fileRepo.getAllFiles($??_.defaultProject)}catch(J){if(J instanceof O)throw J;throw new O("store","Gildash: listIndexedFiles failed",{cause:J})}}function h0(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.relationSearchFn({relationRepo:_.relationRepo,project:J??_.defaultProject,query:{srcFilePath:$,dstFilePath:$,limit:1e4}})}catch(Q){if(Q instanceof O)throw Q;throw new O("search","Gildash: getInternalRelations failed",{cause:Q})}}function p0(_,$,J,Q){if(_.closed)throw new O("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,initializer:Y.initializer};if(_.semanticLayer)try{let H=f0.isAbsolute(J)?J:f0.resolve(_.projectRoot,J),V=_.semanticLayer.lineColumnToPosition(H,Z.span.start.line,Z.span.start.column);if(V!==null){let U=_.semanticLayer.findNamePosition(H,V,Z.name)??V,B=_.semanticLayer.collectTypeAt(H,U);if(B)X.resolvedType=B}}catch{}return X}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getFullSymbol failed",{cause:z})}}function i0(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let Q=J??_.defaultProject,z=_.fileRepo.getFile(Q,$);if(!z)throw new O("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 O)throw Q;throw new O("store","Gildash: getFileStats failed",{cause:Q})}}function d0(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");try{return _.fileRepo.getFile(J??_.defaultProject,$)}catch(Q){if(Q instanceof O)throw Q;throw new O("store","Gildash: getFileInfo failed",{cause:Q})}}function l0(_,$,J){return v$(_,{filePath:$,project:J??void 0,limit:1e4})}function c0(_,$,J){if(_.closed)throw new O("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 O)throw Q;throw new O("search","Gildash: getModuleInterface failed",{cause:Q})}}import n from"path";function n_(_,$,J,Q){let z=Q??_.defaultProject,W=n.isAbsolute(J)?n.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=n.isAbsolute(J)?J:n.resolve(_.projectRoot,J),H=_.semanticLayer.lineColumnToPosition(X,Y.span.start.line,Y.span.start.column);if(H===null)return null;let V=_.semanticLayer.findNamePosition(X,H,Y.name)??H;return{sym:Y,position:V,absPath:X}}function a0(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=n_(_,$,J,Q);if(!z)return null;return _.semanticLayer.collectTypeAt(z.absPath,z.position)}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getResolvedType failed",{cause:z})}}function s0(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=n_(_,$,J,Q);if(!z)throw new O("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findReferences(z.absPath,z.position)}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getSemanticReferences failed",{cause:z})}}function r0(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=n_(_,$,J,Q);if(!z)throw new O("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findImplementations(z.absPath,z.position)}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getImplementations failed",{cause:z})}}function o0(_,$,J,Q,z,W){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Z=n_(_,$,J,W);if(!Z)throw new O("search",`Gildash: source symbol '${$}' not found in '${J}'`);let Y=n_(_,Q,z,W);if(!Y)throw new O("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 O)throw Z;throw new O("semantic","Gildash: isTypeAssignableTo failed",{cause:Z})}}function t0(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let J=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.collectFileTypes(J)}catch(J){if(J instanceof O)throw J;throw new O("semantic","Gildash: getFileTypes failed",{cause:J})}}function e0(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=n.isAbsolute($)?$:n.resolve(_.projectRoot,$),W=_.semanticLayer.lineColumnToPosition(z,J,Q);if(W===null)return null;return _.semanticLayer.collectTypeAt(z,W)}catch(z){if(z instanceof O)throw z;throw new O("semantic","Gildash: getResolvedTypeAt failed",{cause:z})}}function _1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let J=n.isAbsolute($.source.filePath)?$.source.filePath:n.resolve(_.projectRoot,$.source.filePath),Q=n.isAbsolute($.target.filePath)?$.target.filePath:n.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 O)throw J;throw new O("semantic","Gildash: isTypeAssignableToAt failed",{cause:J})}}function $1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{return _.semanticLayer.getModuleInterface($)}catch(J){if(J instanceof O)throw J;throw new O("search","Gildash: getSemanticModuleInterface failed",{cause:J})}}function J1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.getBaseTypes(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getBaseTypes failed",{cause:Q})}}function Q1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.collectTypesAtPositions(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getResolvedTypesAtPositions failed",{cause:Q})}}function z1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.collectTypeAt(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getResolvedTypeAtPosition failed",{cause:Q})}}function W1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.findReferences(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getSemanticReferencesAtPosition failed",{cause:Q})}}function Y1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.findImplementations(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getImplementationsAtPosition failed",{cause:Q})}}function Z1(_,$,J,Q,z){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=n.isAbsolute($)?$:n.resolve(_.projectRoot,$),Z=n.isAbsolute(Q)?Q:n.resolve(_.projectRoot,Q);return _.semanticLayer.isTypeAssignableTo(W,J,Z,z)}catch(W){if(W instanceof O)throw W;throw new O("semantic","Gildash: isTypeAssignableToAtPosition failed",{cause:W})}}function X1(_,$,J,Q,z){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToType(W,J,Q,z)}catch(W){if(W instanceof O)throw W;throw new O("semantic","Gildash: isTypeAssignableToType failed",{cause:W})}}function V1(_,$,J,Q,z){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let W=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtPositions(W,J,Q,z)}catch(W){if(W instanceof O)throw W;throw new O("semantic","Gildash: isTypeAssignableToTypeAtPositions failed",{cause:W})}}function O1(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.lineColumnToPosition(z,J,Q)}catch(z){if(z instanceof O)throw z;throw new O("semantic","Gildash: lineColumnToPosition failed",{cause:z})}}function U1(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let z=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.findNamePosition(z,J,Q)}catch(z){if(z instanceof O)throw z;throw new O("semantic","Gildash: findNamePosition failed",{cause:z})}}function H1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.getSymbolNode(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("semantic","Gildash: getSymbolNode failed",{cause:Q})}}function M1(_,$,J){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new O("semantic","Gildash: semantic layer is not enabled");try{let Q=n.isAbsolute($)?$:n.resolve(_.projectRoot,$);return _.semanticLayer.getDiagnostics(Q,J)}catch(Q){if(Q instanceof O)throw Q;throw new O("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 H=J.get(Y);if(!H)z.push(X);else if(H.fingerprint!==X.fingerprint)Z.push({before:H,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 O("closed","Gildash: instance is closed");if(!_.coordinator)throw new O("closed","Gildash: reindex() is not available for readers");try{let $=await _.coordinator.fullIndex();return J$(_),$}catch($){if($ instanceof O)throw $;throw new O("index","Gildash: reindex failed",{cause:$})}}function B1(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");let z=Q??_.defaultProject,W=new Set,Z=[],Y=$,X=J;for(;;){let H=`${X}::${Y}`;if(W.has(H))return{originalName:Y,originalFilePath:X,reExportChain:Z,circular:!0};W.add(H);let V=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{type:"re-exports",srcFilePath:X,limit:500}}),U,B;for(let q of V){let L;if(q.metaJson)try{let T=JSON.parse(q.metaJson);if(Array.isArray(T.specifiers))L=T.specifiers}catch{}if(!L)continue;let C=L.find((T)=>T.exported===Y);if(!C)continue;U=q.dstFilePath??void 0,B=C.local;break}if(!U||!B)return{originalName:Y,originalFilePath:X,reExportChain:Z,circular:!1};Z.push({filePath:X,exportedAs:Y}),X=U,Y=B}}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 O("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 O)throw Q;throw new O("search","Gildash: findPattern failed",{cause:Q})}}async function N1(_,$,J,Q){if(_.closed)throw new O("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,W=new Set,Z=(Y,X,H)=>{let V=`${Y}::${X}`;if(W.has(V))return{symbolName:Y,filePath:X,kind:H,children:[]};W.add(V);let q=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{srcFilePath:X,srcSymbolName:Y,limit:1000}}).filter((L)=>L.type==="extends"||L.type==="implements").filter((L)=>L.dstSymbolName!=null&&L.dstFilePath!=null).map((L)=>Z(L.dstSymbolName,L.dstFilePath,L.type));return{symbolName:Y,filePath:X,kind:H,children:q}};return Z($,J)}catch(z){if(z instanceof O)throw z;throw new O("search","Gildash: getHeritageChain failed",{cause:z})}}function q1(_,$){if(_.closed)throw new O("closed","Gildash: instance is closed");if(!_.annotationRepo||!_.annotationSearchFn)return[];return _.annotationSearchFn({annotationRepo:_.annotationRepo,project:$.project??_.defaultProject,query:$})}function u1(_,$,J){if(_.closed)throw new O("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 S1(_,$){if(_.closed)throw new O("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 F0(_);return new b$($)}async close(_){return Q$(this._ctx,_)}parseSource(_,$,J){return G0(this._ctx,_,$,J)}async batchParse(_,$){return j0(this._ctx,_,$)}getParsedAst(_){return E0(this._ctx,_)}extractSymbols(_){return v0(this._ctx,_)}extractRelations(_){return b0(this._ctx,_)}getStats(_){return P0(this._ctx,_)}searchSymbols(_){return v$(this._ctx,_)}searchRelations(_){return y0(this._ctx,_)}searchAllSymbols(_){return x0(this._ctx,_)}searchAllRelations(_){return m0(this._ctx,_)}listIndexedFiles(_){return n0(this._ctx,_)}getInternalRelations(_,$){return h0(this._ctx,_,$)}getFullSymbol(_,$,J){return p0(this._ctx,_,$,J)}getFileStats(_,$){return i0(this._ctx,_,$)}getFileInfo(_,$){return d0(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 N0(this._ctx,_)}async getTransitiveDependencies(_,$){return q0(this._ctx,_,$)}async getTransitiveDependents(_,$){return u0(this._ctx,_,$)}async getCyclePaths(_,$){return S0(this._ctx,_,$)}async getFanMetrics(_,$){return g0(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 V1(this._ctx,_,$,J,Q)}lineColumnToPosition(_,$,J){return O1(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 N1(this._ctx,_,$,J)}onFileChanged(_){return D1(this._ctx,_)}onError(_){return I1(this._ctx,_)}onRoleChanged(_){return C1(this._ctx,_)}searchAnnotations(_){return q1(this._ctx,_)}getSymbolChanges(_,$){return u1(this._ctx,_,$)}pruneChangelog(_){return S1(this._ctx,_)}}import{Visitor as Y3,visitorKeys as Z3}from"oxc-parser";export{Z3 as visitorKeys,N$ as symbolSearch,q$ as relationSearch,u$ as patternSearch,Y_ as normalizePath,X_ as getLineColumn,P_ as buildLineOffsets,Y3 as Visitor,O as GildashError,b$ as Gildash,$$ as DependencyGraph};
|
|
@@ -5,4 +5,4 @@ export { extractImports } from './imports-extractor';
|
|
|
5
5
|
export { extractCalls } from './calls-extractor';
|
|
6
6
|
export { extractHeritage } from './heritage-extractor';
|
|
7
7
|
export { resolveImport, buildImportMap } from './extractor-utils';
|
|
8
|
-
export type { ExtractedSymbol, SymbolKind, CodeRelation, Parameter, Modifier, Heritage, Decorator, JsDocBlock, JsDocTag, ImportReference, QualifiedName, AnnotationSource, ExtractedAnnotation, } from './types';
|
|
8
|
+
export type { ExtractedSymbol, SymbolKind, CodeRelation, Parameter, Modifier, Heritage, Decorator, ExpressionValue, ExpressionLiteral, ExpressionIdentifier, ExpressionMember, ExpressionCall, ExpressionNew, ExpressionObject, ExpressionObjectProperty, ExpressionArray, ExpressionSpread, ExpressionFunction, ExpressionTemplate, ExpressionUnresolvable, JsDocBlock, JsDocTag, ImportReference, QualifiedName, AnnotationSource, ExtractedAnnotation, } from './types';
|
|
@@ -1,4 +1,68 @@
|
|
|
1
1
|
import type { SourcePosition, SourceSpan } from '../parser/types';
|
|
2
|
+
/**
|
|
3
|
+
* A structured representation of a JavaScript/TypeScript expression.
|
|
4
|
+
*
|
|
5
|
+
* Used for decorator arguments, variable initializers, enum member values,
|
|
6
|
+
* and property initializers — anywhere an expression's structure matters
|
|
7
|
+
* beyond its raw source text.
|
|
8
|
+
*
|
|
9
|
+
* The extractor does **not** resolve imports; use relation queries for that.
|
|
10
|
+
*/
|
|
11
|
+
export type ExpressionValue = ExpressionLiteral | ExpressionIdentifier | ExpressionMember | ExpressionCall | ExpressionNew | ExpressionObject | ExpressionArray | ExpressionSpread | ExpressionFunction | ExpressionTemplate | ExpressionUnresolvable;
|
|
12
|
+
export interface ExpressionLiteral {
|
|
13
|
+
kind: 'string' | 'number' | 'boolean' | 'null' | 'undefined';
|
|
14
|
+
value: string | number | boolean | null;
|
|
15
|
+
}
|
|
16
|
+
export interface ExpressionIdentifier {
|
|
17
|
+
kind: 'identifier';
|
|
18
|
+
name: string;
|
|
19
|
+
}
|
|
20
|
+
export interface ExpressionMember {
|
|
21
|
+
kind: 'member';
|
|
22
|
+
/** Full dot-separated expression text, e.g. `'HttpMethod.Get'`. */
|
|
23
|
+
object: string;
|
|
24
|
+
property: string;
|
|
25
|
+
}
|
|
26
|
+
export interface ExpressionCall {
|
|
27
|
+
kind: 'call';
|
|
28
|
+
callee: string;
|
|
29
|
+
arguments: ExpressionValue[];
|
|
30
|
+
}
|
|
31
|
+
export interface ExpressionNew {
|
|
32
|
+
kind: 'new';
|
|
33
|
+
callee: string;
|
|
34
|
+
arguments: ExpressionValue[];
|
|
35
|
+
}
|
|
36
|
+
export interface ExpressionObject {
|
|
37
|
+
kind: 'object';
|
|
38
|
+
properties: ExpressionObjectProperty[];
|
|
39
|
+
}
|
|
40
|
+
export interface ExpressionObjectProperty {
|
|
41
|
+
key: string;
|
|
42
|
+
value: ExpressionValue;
|
|
43
|
+
computed?: boolean;
|
|
44
|
+
shorthand?: boolean;
|
|
45
|
+
}
|
|
46
|
+
export interface ExpressionArray {
|
|
47
|
+
kind: 'array';
|
|
48
|
+
elements: ExpressionValue[];
|
|
49
|
+
}
|
|
50
|
+
export interface ExpressionSpread {
|
|
51
|
+
kind: 'spread';
|
|
52
|
+
argument: ExpressionValue;
|
|
53
|
+
}
|
|
54
|
+
export interface ExpressionFunction {
|
|
55
|
+
kind: 'function';
|
|
56
|
+
sourceText: string;
|
|
57
|
+
}
|
|
58
|
+
export interface ExpressionTemplate {
|
|
59
|
+
kind: 'template';
|
|
60
|
+
sourceText: string;
|
|
61
|
+
}
|
|
62
|
+
export interface ExpressionUnresolvable {
|
|
63
|
+
kind: 'unresolvable';
|
|
64
|
+
sourceText: string;
|
|
65
|
+
}
|
|
2
66
|
/**
|
|
3
67
|
* The kind of a symbol extracted from TypeScript source.
|
|
4
68
|
*
|
|
@@ -49,8 +113,8 @@ export interface Heritage {
|
|
|
49
113
|
export interface Decorator {
|
|
50
114
|
/** Decorator name without `@`. */
|
|
51
115
|
name: string;
|
|
52
|
-
/**
|
|
53
|
-
arguments?:
|
|
116
|
+
/** Structured decorator call arguments. */
|
|
117
|
+
arguments?: ExpressionValue[];
|
|
54
118
|
}
|
|
55
119
|
/**
|
|
56
120
|
* A single JSDoc tag parsed from a documentation comment.
|
|
@@ -113,6 +177,8 @@ export interface ExtractedSymbol {
|
|
|
113
177
|
heritage?: Heritage[];
|
|
114
178
|
/** Decorators applied to this symbol. */
|
|
115
179
|
decorators?: Decorator[];
|
|
180
|
+
/** Initializer expression (enum member values, property defaults, variable initializers). */
|
|
181
|
+
initializer?: ExpressionValue;
|
|
116
182
|
/** Nested members (class fields, methods, interface properties, enum members). */
|
|
117
183
|
members?: ExtractedSymbol[];
|
|
118
184
|
/** Parsed JSDoc comment associated with this symbol. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ParsedFile } from '../parser/types';
|
|
2
2
|
import type { SymbolSearchResult, SymbolDetail } from '../search/symbol-search';
|
|
3
|
-
import type { SymbolKind, Decorator } from '../extractor/types';
|
|
3
|
+
import type { SymbolKind, Decorator, ExpressionValue } from '../extractor/types';
|
|
4
4
|
import type { ResolvedType } from '../semantic/types';
|
|
5
5
|
/**
|
|
6
6
|
* Minimal logger interface accepted by {@link Gildash}.
|
|
@@ -70,6 +70,8 @@ export interface FullSymbol extends SymbolSearchResult {
|
|
|
70
70
|
decorators?: Decorator[];
|
|
71
71
|
/** Generic type parameter names. */
|
|
72
72
|
typeParameters?: string[];
|
|
73
|
+
/** Initializer expression (enum member values, property defaults, variable initializers). */
|
|
74
|
+
initializer?: ExpressionValue;
|
|
73
75
|
/** Resolved type from the Semantic Layer (available when `semantic: true`). */
|
|
74
76
|
resolvedType?: ResolvedType;
|
|
75
77
|
}
|
package/dist/src/index.d.ts
CHANGED
|
@@ -8,10 +8,10 @@ export { relationSearch } from "./search/relation-search";
|
|
|
8
8
|
export type { RelationSearchQuery, StoredCodeRelation } from "./search/relation-search";
|
|
9
9
|
export { DependencyGraph } from "./search/dependency-graph";
|
|
10
10
|
export { patternSearch } from "./search/pattern-search";
|
|
11
|
-
export type { PatternMatch } from "./search/pattern-search";
|
|
11
|
+
export type { PatternMatch, PatternCapture } from "./search/pattern-search";
|
|
12
12
|
export type { IndexResult } from "./indexer/index-coordinator";
|
|
13
13
|
export type { ProjectBoundary } from "./common/project-discovery";
|
|
14
|
-
export type { CodeRelation, ExtractedSymbol, SymbolKind, Decorator, Parameter, Heritage, Modifier, JsDocBlock, JsDocTag } from "./extractor/types";
|
|
14
|
+
export type { CodeRelation, ExtractedSymbol, SymbolKind, Decorator, Parameter, Heritage, Modifier, JsDocBlock, JsDocTag, ExpressionValue, ExpressionLiteral, ExpressionIdentifier, ExpressionMember, ExpressionCall, ExpressionNew, ExpressionObject, ExpressionObjectProperty, ExpressionArray, ExpressionSpread, ExpressionFunction, ExpressionTemplate, ExpressionUnresolvable } from "./extractor/types";
|
|
15
15
|
export type { SymbolStats } from "./store/repositories/symbol.repository";
|
|
16
16
|
export type { WatcherRole, FileChangeEvent } from "./watcher/types";
|
|
17
17
|
export type { ParsedFile } from "./parser/types";
|
|
@@ -5,6 +5,6 @@ export type { RelationSearchQuery, IRelationRepo } from './relation-search';
|
|
|
5
5
|
export { DependencyGraph } from './dependency-graph';
|
|
6
6
|
export type { IDependencyGraphRepo } from './dependency-graph';
|
|
7
7
|
export { patternSearch } from './pattern-search';
|
|
8
|
-
export type { PatternMatch, PatternSearchOptions } from './pattern-search';
|
|
8
|
+
export type { PatternMatch, PatternCapture, PatternSearchOptions } from './pattern-search';
|
|
9
9
|
export { annotationSearch } from './annotation-search';
|
|
10
10
|
export type { AnnotationSearchQuery, AnnotationSearchResult, IAnnotationRepo } from './annotation-search';
|
|
@@ -1,3 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A captured metavariable from an ast-grep pattern match.
|
|
3
|
+
*/
|
|
4
|
+
export interface PatternCapture {
|
|
5
|
+
/** Source text of the captured node. */
|
|
6
|
+
text: string;
|
|
7
|
+
/** 1-based start line number. */
|
|
8
|
+
startLine: number;
|
|
9
|
+
/** 1-based end line number. */
|
|
10
|
+
endLine: number;
|
|
11
|
+
}
|
|
1
12
|
/**
|
|
2
13
|
* A single structural-pattern match found in a source file.
|
|
3
14
|
*/
|
|
@@ -10,6 +21,8 @@ export interface PatternMatch {
|
|
|
10
21
|
endLine: number;
|
|
11
22
|
/** Source text of the matched node. */
|
|
12
23
|
matchedText: string;
|
|
24
|
+
/** Named captures from metavariables in the pattern (e.g. `$METHOD`, `$$$ARGS`). */
|
|
25
|
+
captures?: Record<string, PatternCapture>;
|
|
13
26
|
}
|
|
14
27
|
/**
|
|
15
28
|
* Options for {@link patternSearch}.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { SymbolKind, Modifier, Decorator, JsDocBlock } from '../extractor/types';
|
|
1
|
+
import type { SymbolKind, Modifier, Decorator, JsDocBlock, ExpressionValue } from '../extractor/types';
|
|
2
2
|
import type { SymbolRecord } from '../store/repositories/symbol.repository';
|
|
3
3
|
/**
|
|
4
4
|
* Filters for {@link symbolSearch}.
|
|
@@ -66,6 +66,8 @@ export interface SymbolDetail {
|
|
|
66
66
|
typeParameters?: string[];
|
|
67
67
|
/** Declaration modifiers. */
|
|
68
68
|
modifiers?: Modifier[];
|
|
69
|
+
/** Initializer expression (enum member values, property defaults, variable initializers). */
|
|
70
|
+
initializer?: ExpressionValue;
|
|
69
71
|
/** Class/interface members. */
|
|
70
72
|
members?: Array<{
|
|
71
73
|
name: string;
|
|
@@ -74,6 +76,10 @@ export interface SymbolDetail {
|
|
|
74
76
|
visibility?: string;
|
|
75
77
|
isStatic?: boolean;
|
|
76
78
|
isReadonly?: boolean;
|
|
79
|
+
/** Member initializer expression. */
|
|
80
|
+
initializer?: ExpressionValue;
|
|
81
|
+
/** Decorators applied to this member. */
|
|
82
|
+
decorators?: Decorator[];
|
|
77
83
|
}>;
|
|
78
84
|
/** Parsed JSDoc comment associated with this symbol. */
|
|
79
85
|
jsDoc?: JsDocBlock;
|