@zipbul/gildash 0.19.1 → 0.21.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 +78 -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 eJ}from"fs";import{err as x$,isErr as P1}from"@zipbul/result";import{Database as f1}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:()=>n,symbolChangelog:()=>__,relations:()=>G,files:()=>r,annotations:()=>Z_});import{sql as G1}from"drizzle-orm";import{sqliteTable as q_,text as f,integer as s,real as j1,index as Q_,primaryKey as E1,foreignKey as W$,check as v1}from"drizzle-orm/sqlite-core";var r=q_("files",{project:f("project").notNull(),filePath:f("file_path").notNull(),mtimeMs:j1("mtime_ms").notNull(),size:s("size").notNull(),contentHash:f("content_hash").notNull(),updatedAt:f("updated_at").notNull(),lineCount:s("line_count")},(_)=>[E1({columns:[_.project,_.filePath]})]),n=q_("symbols",{id:s("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),filePath:f("file_path").notNull(),kind:f("kind").notNull(),name:f("name").notNull(),startLine:s("start_line").notNull(),startColumn:s("start_column").notNull(),endLine:s("end_line").notNull(),endColumn:s("end_column").notNull(),isExported:s("is_exported").notNull().default(0),signature:f("signature"),fingerprint:f("fingerprint"),detailJson:f("detail_json"),contentHash:f("content_hash").notNull(),indexedAt:f("indexed_at").notNull(),resolvedType:f("resolved_type"),structuralFingerprint:f("structural_fingerprint")},(_)=>[Q_("idx_symbols_project_file").on(_.project,_.filePath),Q_("idx_symbols_project_kind").on(_.project,_.kind),Q_("idx_symbols_project_name").on(_.project,_.name),Q_("idx_symbols_fingerprint").on(_.project,_.fingerprint),W$({columns:[_.project,_.filePath],foreignColumns:[r.project,r.filePath]}).onDelete("cascade")]),G=q_("relations",{id:s("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),type:f("type").notNull(),srcFilePath:f("src_file_path").notNull(),srcSymbolName:f("src_symbol_name"),dstProject:f("dst_project"),dstFilePath:f("dst_file_path"),dstSymbolName:f("dst_symbol_name"),metaJson:f("meta_json"),specifier:f("specifier"),isExternal:s("is_external").notNull().default(0)},(_)=>[Q_("idx_relations_src").on(_.project,_.srcFilePath),Q_("idx_relations_dst").on(_.dstProject,_.dstFilePath),Q_("idx_relations_type").on(_.project,_.type),Q_("idx_relations_project_type_src").on(_.project,_.type,_.srcFilePath),Q_("idx_relations_specifier").on(_.project,_.specifier),W$({columns:[_.project,_.srcFilePath],foreignColumns:[r.project,r.filePath]}).onDelete("cascade")]),Z_=q_("annotations",{id:s("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),filePath:f("file_path").notNull(),tag:f("tag").notNull(),value:f("value").notNull().default(""),source:f("source").notNull(),symbolName:f("symbol_name"),startLine:s("start_line").notNull(),startColumn:s("start_column").notNull(),endLine:s("end_line").notNull(),endColumn:s("end_column").notNull(),indexedAt:f("indexed_at").notNull()},(_)=>[Q_("idx_annotations_project_file").on(_.project,_.filePath),Q_("idx_annotations_project_tag").on(_.project,_.tag),Q_("idx_annotations_project_symbol").on(_.project,_.symbolName),W$({columns:[_.project,_.filePath],foreignColumns:[r.project,r.filePath]}).onDelete("cascade")]),__=q_("symbol_changelog",{id:s("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),changeType:f("change_type").notNull(),symbolName:f("symbol_name").notNull(),symbolKind:f("symbol_kind").notNull(),filePath:f("file_path").notNull(),oldName:f("old_name"),oldFilePath:f("old_file_path"),fingerprint:f("fingerprint"),changedAt:f("changed_at").notNull(),isFullIndex:s("is_full_index").notNull().default(0),indexRunId:f("index_run_id").notNull()},(_)=>[Q_("idx_changelog_project_changed_at").on(_.project,_.changedAt),Q_("idx_changelog_project_name").on(_.project,_.symbolName),Q_("idx_changelog_project_run").on(_.project,_.indexRunId)]),b1=q_("watcher_owner",{id:s("id").primaryKey(),pid:s("pid").notNull(),startedAt:f("started_at").notNull(),heartbeatAt:f("heartbeat_at").notNull(),instanceId:f("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 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$}),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(P1($))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(r).where(p$(G_(r.project,_),G_(r.filePath,$))).get()??null}upsertFile(_){this.db.drizzleDb.insert(r).values({project:_.project,filePath:_.filePath,mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}).onConflictDoUpdate({target:[r.project,r.filePath],set:{mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}}).run()}getAllFiles(_){return this.db.drizzleDb.select().from(r).where(G_(r.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(r).where(p$(G_(r.project,_),G_(r.filePath,$))).run()}}import{eq as o,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(n).where(B_(o(n.project,_),o(n.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(n).values(W.slice(Z,Z+i$)).run()}getFileSymbols(_,$){return this.db.drizzleDb.select().from(n).where(B_(o(n.project,_),o(n.filePath,$))).all()}searchByName(_,$,J={}){let Q=J.limit??50,z=u_($);if(!z)return[];return this.db.drizzleDb.select().from(n).where(B_(p_`${n.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${z})`,o(n.project,_),J.kind?o(n.kind,J.kind):void 0)).orderBy(n.name).limit(Q).all()}searchByKind(_,$){return this.db.drizzleDb.select().from(n).where(B_(o(n.project,_),o(n.kind,$))).orderBy(n.name).all()}getStats(_){let $=this.db.drizzleDb.select({symbolCount:h1(),fileCount:p_`COUNT(DISTINCT ${n.filePath})`}).from(n).where(o(n.project,_)).get();return{symbolCount:$?.symbolCount??0,fileCount:$?.fileCount??0}}getByFingerprint(_,$){return this.db.drizzleDb.select().from(n).where(B_(o(n.project,_),o(n.fingerprint,$))).all()}deleteFileSymbols(_,$){this.db.drizzleDb.delete(n).where(B_(o(n.project,_),o(n.filePath,$))).run()}searchByQuery(_){let $=this.db.drizzleDb.select().from(n).where(B_(_.ftsQuery?p_`${n.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${_.ftsQuery})`:void 0,_.exactName?o(n.name,_.exactName):void 0,_.project!==void 0?o(n.project,_.project):void 0,_.kind?o(n.kind,_.kind):void 0,_.filePath!==void 0?o(n.filePath,_.filePath):void 0,_.isExported!==void 0?o(n.isExported,_.isExported?1:0):void 0,_.decorator?p_`${n.id} IN (SELECT s.id FROM symbols s, json_each(s.detail_json, '$.decorators') je WHERE json_extract(je.value, '$.name') = ${_.decorator})`:void 0,_.resolvedType!==void 0?o(n.resolvedType,_.resolvedType):void 0)).orderBy(n.name);if(!_.regex)return(_.limit!==void 0?$.limit(_.limit):$).all();let J;try{J=new RegExp(_.regex)}catch{throw new 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 d,and as O_,isNull as d$,or as p1}from"drizzle-orm";var j_={project:G.project,type:G.type,srcFilePath:G.srcFilePath,srcSymbolName:G.srcSymbolName,dstProject:G.dstProject,dstFilePath:G.dstFilePath,dstSymbolName:G.dstSymbolName,metaJson:G.metaJson,specifier:G.specifier,isExternal:G.isExternal};class O${db;constructor(_){this.db=_}replaceFileRelations(_,$,J){this.db.transaction((Q)=>{if(Q.drizzleDb.delete(G).where(O_(d(G.project,_),d(G.srcFilePath,$))).run(),!J.length)return;for(let z of J)Q.drizzleDb.insert(G).values({project:_,type:z.type??"unknown",srcFilePath:z.srcFilePath??$,srcSymbolName:z.srcSymbolName??null,dstProject:z.dstProject??(z.dstFilePath!=null?_:null),dstFilePath:z.dstFilePath??null,dstSymbolName:z.dstSymbolName??null,metaJson:z.metaJson??null,specifier:z.specifier??null,isExternal:z.isExternal??0}).run()})}getOutgoing(_,$,J){if(J!==void 0)return this.db.drizzleDb.select(j_).from(G).where(O_(d(G.project,_),d(G.srcFilePath,$),p1(d(G.srcSymbolName,J),d$(G.srcSymbolName)))).all();return this.db.drizzleDb.select(j_).from(G).where(O_(d(G.project,_),d(G.srcFilePath,$))).all()}getIncoming(_){let{dstProject:$,dstFilePath:J}=_;return this.db.drizzleDb.select(j_).from(G).where(O_(d(G.dstProject,$),d(G.dstFilePath,J))).all()}getByType(_,$){return this.db.drizzleDb.select(j_).from(G).where(O_(d(G.project,_),d(G.type,$))).all()}deleteFileRelations(_,$){this.db.drizzleDb.delete(G).where(O_(d(G.project,_),d(G.srcFilePath,$))).run()}deleteIncomingRelations(_,$){this.db.drizzleDb.delete(G).where(O_(d(G.dstProject,_),d(G.dstFilePath,$))).run()}searchRelations(_){let $=this.db.drizzleDb.select(j_).from(G).where(O_(_.project!==void 0?d(G.project,_.project):void 0,_.srcFilePath!==void 0?d(G.srcFilePath,_.srcFilePath):void 0,_.srcSymbolName!==void 0?d(G.srcSymbolName,_.srcSymbolName):void 0,_.dstProject!==void 0?d(G.dstProject,_.dstProject):void 0,_.dstFilePath!==void 0?d(G.dstFilePath,_.dstFilePath):void 0,_.dstSymbolName!==void 0?d(G.dstSymbolName,_.dstSymbolName):void 0,_.type!==void 0?d(G.type,_.type):void 0,_.specifier!==void 0?d(G.specifier,_.specifier):void 0,_.isExternal!==void 0?d(G.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_(d(G.dstProject,$),d(G.dstFilePath,J),d$(G.dstSymbolName)):O_(d(G.dstProject,$),d(G.dstFilePath,J),d(G.dstSymbolName,Q)),X={dstFilePath:z,dstSymbolName:W};if(Z!==void 0)X.dstProject=Z;this.db.drizzleDb.update(G).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 W_(_){return _.replaceAll("\\","/")}function E_(_,$){return W_(l$.relative(_,$))}function S_(_,$){return W_(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=W_(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 K$ 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=W_(K$.dirname(J)),z=K$.join(_,J),W=await Bun.file(z).json(),Z=typeof W?.name==="string"&&W.name.length>0?W.name:K$.basename(Q==="."?_:Q);$.push({dir:Q,project:Z})}return $.sort((J,Q)=>Q.dir.length-J.dir.length),$}function c(_,$,J="default"){let Q=W_(_);for(let z of $){if(z.dir===".")return z.project;if(Q===z.dir||Q.startsWith(`${z.dir}/`))return z.project}return J}import 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[K,V]of Object.entries(W)){if(!Array.isArray(V))continue;let H=V.filter((I)=>typeof I==="string");Y.set(K,H)}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 P_(_,$,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=[],K=Q.map((H)=>new Bun.Glob(H));for await(let H of _J.glob("**/*",{cwd:$})){let I=W_(H);if(!J.some((h)=>I.endsWith(h)))continue;if(I.startsWith("node_modules/")||I.includes("/node_modules/"))continue;if(K.some((h)=>h.match(I)))continue;Z.add(I);let N=$J($,I),B=Bun.file(N),{size:A,lastModified:k}=B,F=W.get(I);if(!F){let h=await B.text(),a=V_(h);Y.push({filePath:I,contentHash:a,mtimeMs:k,size:A});continue}if(F.mtimeMs===k&&F.size===A){X.push({filePath:I,contentHash:F.contentHash,mtimeMs:k,size:A});continue}let y=await B.text(),v=V_(y);if(v===F.contentHash)X.push({filePath:I,contentHash:v,mtimeMs:k,size:A});else Y.push({filePath:I,contentHash:v,mtimeMs:k,size:A})}let V=[];for(let H of W.keys())if(!Z.has(H))V.push(H);return{changed:Y,unchanged:X,deleted:V}}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 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 WJ(_){let $=new Map;for(let J of _.module.staticImports){let Q=J.moduleRequest.value;for(let z of J.entries){let W=z.localName.value,Z=z.importName.kind==="Name"?z.importName.name:void 0,Y={specifier:Q};if(Z&&Z!==W)Y.originalName=Z;$.set(W,Y)}}return $}function R_(_){let{program:$,sourceText:J,comments:Q}=_,z=f_(J),W=WJ(_),Z=Q.filter((M)=>M.type==="Block"&&M.value.startsWith("*")).sort((M,q)=>M.end-q.end),Y=$.body.map((M)=>M.start).sort((M,q)=>M-q);function X(M,q){return{start:X_(z,M),end:X_(z,q)}}function K(M){let q=0,D=Z.length-1,w=-1;while(q<=D){let S=q+D>>>1;if(Z[S].end<=M)w=S,q=S+1;else D=S-1}if(w<0)return;let u=Z[w];q=0,D=Y.length-1;while(q<=D){let S=q+D>>>1,T=Y[S];if(T<=u.end)q=S+1;else if(T>=M)D=S-1;else return}return`/*${u.value}*/`}function V(M){if(!M)return;let q="typeAnnotation"in M&&M.typeAnnotation?M.typeAnnotation:M;return J.slice(q.start,q.end)}let H=8;function I(M){if(M.type==="Identifier")return W.get(M.name);if(M.type==="MemberExpression"){let q=M.object;if(q.type==="Identifier")return W.get(q.name)}return}function N(M,q=0){if(q>=H)return{kind:"unresolvable",sourceText:J.slice(M.start,M.end)};let D=M.type;if(D==="Literal"){let w=M.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(M.start,M.end)}}if(D==="Identifier"){let w=M.name;if(w==="undefined")return{kind:"undefined",value:null};let u=W.get(w),S={kind:"identifier",name:w};if(u){if(S.importSource=u.specifier,u.originalName)S.originalName=u.originalName}return S}if(D==="MemberExpression"){if(M.computed)return{kind:"unresolvable",sourceText:J.slice(M.start,M.end)};let w=M.object,u=J.slice(w.start,w.end),S=M.property.name??J.slice(M.property.start,M.property.end),T=w.type==="Identifier"?w.name:void 0,U=T?W.get(T):void 0,L={kind:"member",object:u,property:S};if(U)L.importSource=U.specifier;return L}if(D==="CallExpression"){let w=M.callee,u=J.slice(w.start,w.end),T=(M.arguments??[]).map((C)=>N(C,q+1)),U=I(w),L={kind:"call",callee:u,arguments:T};if(U)L.importSource=U.specifier;return L}if(D==="NewExpression"){let w=M.callee,u=J.slice(w.start,w.end),T=(M.arguments??[]).map((C)=>N(C,q+1)),U=I(w),L={kind:"new",callee:u,arguments:T};if(U)L.importSource=U.specifier;return L}if(D==="ObjectExpression")return{kind:"object",properties:(M.properties??[]).map((S)=>{if(S.type==="SpreadElement"){let g=S.argument;return{key:"...",value:{kind:"spread",argument:N(g,q+1)}}}let T=S.key,U=T.name??T.value,L=U!=null?String(U):J.slice(T.start,T.end),C=S.value,R=S.computed||void 0,b=S.shorthand||void 0;return{key:L,value:N(C,q+1),computed:R,shorthand:b}})};if(D==="ArrayExpression")return{kind:"array",elements:(M.elements??[]).map((S)=>{if(!S)return{kind:"undefined",value:null};return N(S,q+1)})};if(D==="SpreadElement"){let w=M.argument;return{kind:"spread",argument:N(w,q+1)}}if(D==="ArrowFunctionExpression"||D==="FunctionExpression")return{kind:"function",sourceText:J.slice(M.start,M.end)};if(D==="TemplateLiteral"||D==="TaggedTemplateExpression")return{kind:"template",sourceText:J.slice(M.start,M.end)};if(D==="UnaryExpression"){let{operator:w,argument:u}=M;if(w==="-"&&u.type==="Literal"&&typeof u.value==="number")return{kind:"number",value:-u.value};if(w==="void")return{kind:"undefined",value:null};return{kind:"unresolvable",sourceText:J.slice(M.start,M.end)}}if(D==="TSAsExpression"||D==="TSSatisfiesExpression"||D==="TSNonNullExpression"||D==="TSTypeAssertion"||D==="TSInstantiationExpression"||D==="ParenthesizedExpression"){let w=M.expression;if(w)return N(w,q)}return{kind:"unresolvable",sourceText:J.slice(M.start,M.end)}}function B(M){if(!M||M.length===0)return[];return M.map((q)=>{let D=q.expression;if(D.type==="CallExpression"){let w=D,u=w.callee,S="name"in u&&typeof u.name==="string"?u.name:("property"in u)&&u.property&&typeof u.property.name==="string"?u.property.name:"unknown",T=w.arguments.map((U)=>N(U));return{name:S,arguments:T.length>0?T:void 0}}if(D.type==="Identifier")return{name:D.name??"unknown"};return{name:J.slice(D.start,D.end)}})}function A(M){if(M.type==="TSParameterProperty"){let D=M;return k(D.parameter,D.parameter.decorators)}if(M.type==="RestElement"){let D=M,w=D.argument,S=`...${"name"in w&&typeof w.name==="string"?w.name:"unknown"}`,T=D.typeAnnotation,U=T?V(T):void 0,L={name:S,isOptional:!1};if(U)L.type=U;return L}let q=M;return k(q,q.decorators)}function k(M,q){if(M.type==="AssignmentPattern"){let{left:L,right:C}=M,R="name"in L&&typeof L.name==="string"?L.name:"unknown",b="typeAnnotation"in L?L.typeAnnotation:null,g=b?V(b):void 0,P=J.slice(C.start,C.end),j="decorators"in L&&Array.isArray(L.decorators)?L.decorators:[],x=B(j),E={name:R,isOptional:!0,defaultValue:P};if(g)E.type=g;if(x.length>0)E.decorators=x;return E}let D="name"in M&&typeof M.name==="string"?M.name:("pattern"in M)&&M.pattern&&typeof M.pattern.name==="string"?M.pattern.name:"unknown",w=!!(("optional"in M)&&M.optional),u="typeAnnotation"in M?M.typeAnnotation:null,S=u?V(u):void 0,T=B(q??[]),U={name:D,isOptional:w};if(S)U.type=S;if(T.length>0)U.decorators=T;return U}function F(M,q){let D=[];if(q?.async)D.push("async");if(M.static)D.push("static");if(M.abstract)D.push("abstract");if(M.readonly)D.push("readonly");if(M.override)D.push("override");if(M.declare)D.push("declare");if(M.const)D.push("const");let w=M.accessibility;if(w==="private")D.push("private");else if(w==="protected")D.push("protected");else if(w==="public")D.push("public");return D}function y(M){if(!M)return;let q=M.params.flatMap((D)=>{let w=D.name.name;return w?[w]:[]});return q.length>0?q:void 0}function v(M){let q=[];if(M.superClass){let w=J.slice(M.superClass.start,M.superClass.end);q.push({kind:"extends",name:w})}let D=M.implements??[];for(let w of D){let u=w.expression,S=J.slice(u.start,u.end);q.push({kind:"implements",name:S})}return q}function h(M){let q=[],D=M.extends;for(let w of D){let u=w.expression,S=J.slice(u.start,u.end);q.push({kind:"extends",name:S})}return q}function a(M){let q=[];for(let D of M)if(D.type==="MethodDefinition"||D.type==="TSAbstractMethodDefinition"){let w=D,u=c_(w.key),S=w.value,T=w.kind,U=T==="constructor"?"constructor":T==="get"?"getter":T==="set"?"setter":"method",L=F(w,S);if(D.type==="TSAbstractMethodDefinition"&&!L.includes("abstract"))L.push("abstract");let C=S.params.map(A),R=V(S.returnType),b={kind:"method",name:u,span:X(D.start,D.end),isExported:!1,methodKind:U,modifiers:L,parameters:C.length>0?C:void 0,returnType:R};q.push(b)}else if(D.type==="PropertyDefinition"||D.type==="TSAbstractPropertyDefinition"){let w=D,u=c_(w.key),S=F(w);if(D.type==="TSAbstractPropertyDefinition"&&!S.includes("abstract"))S.push("abstract");let T=V(w.typeAnnotation),U=w.value,L=U?N(U):void 0,C=B(w.decorators??[]),R={kind:"property",name:u,span:X(D.start,D.end),isExported:!1,modifiers:S,returnType:T,initializer:L};if(C.length>0)R.decorators=C;q.push(R)}return q}function t(M){let q=[];for(let D of M)if(D.type==="TSMethodSignature"){let w=D,u=c_(w.key),S=w.params.map(A),T=V(w.returnType);q.push({kind:"method",name:u,span:X(D.start,D.end),isExported:!1,modifiers:[],methodKind:"method",parameters:S.length>0?S:void 0,returnType:T})}else if(D.type==="TSPropertySignature"){let w=D,u=c_(w.key),S=V(w.typeAnnotation),T={kind:"property",name:u,span:X(D.start,D.end),isExported:!1,modifiers:w.readonly?["readonly"]:[],returnType:S};q.push(T)}return q}function J_(M,q){let D=M.type;if(D==="FunctionDeclaration"||D==="FunctionExpression"||D==="TSDeclareFunction"||D==="TSEmptyBodyFunctionExpression"){let w=M,u=w.id?.name??"default",S=w.params.map(A),T=V(w.returnType),U=F(w,w),L=B(w.decorators??[]),C=y(w.typeParameters),R={kind:"function",name:u,span:X(M.start,M.end),isExported:q,modifiers:U,parameters:S.length>0?S:void 0,returnType:T,decorators:L.length>0?L:void 0};if(C&&C.length>0)R.typeParameters=C;return R}if(D==="ClassDeclaration"||D==="ClassExpression"){let w=M,u=w.id?.name??"default",S=v(w),T=a(w.body.body),U=B(w.decorators),L=F(w),C=y(w.typeParameters),R={kind:"class",name:u,span:X(M.start,M.end),isExported:q,modifiers:L,heritage:S.length>0?S:void 0,members:T.length>0?T:void 0,decorators:U.length>0?U:void 0};if(C&&C.length>0)R.typeParameters=C;return R}if(D==="VariableDeclaration"){let w=M,u=[];for(let S of w.declarations){let{id:T,init:U}=S;if(T.type==="ObjectPattern"||T.type==="ArrayPattern"){let x=g_(T);for(let E of x)u.push({kind:"variable",name:E.name,span:X(E.start,E.end),isExported:q,modifiers:[]});continue}let L="name"in T&&typeof T.name==="string"?T.name:"unknown",C="variable",R,b,g;if(U)if(U.type==="FunctionExpression"||U.type==="ArrowFunctionExpression"){C="function";let x=U;R=x.params.map(A),b=V(x.returnType)}else g=N(U);let P=[],j={kind:C,name:L,span:X(S.start,S.end),isExported:q,modifiers:P,parameters:R,returnType:b};if(g)j.initializer=g;u.push(j)}if(u.length===0)return null;if(u.length===1)return u[0];return u}if(D==="TSTypeAliasDeclaration")return{kind:"type",name:M.id.name,span:X(M.start,M.end),isExported:q,modifiers:[]};if(D==="TSInterfaceDeclaration"){let w=M,u=w.id.name,S=h(w),T=t(w.body.body),U=y(w.typeParameters),L={kind:"interface",name:u,span:X(M.start,M.end),isExported:q,modifiers:[],heritage:S.length>0?S:void 0,members:T.length>0?T:void 0};if(U&&U.length>0)L.typeParameters=U;return L}if(D==="TSEnumDeclaration"){let w=M,u=w.id.name,S=F(w),U=w.body.members.map((L)=>{let C=L.id,R="name"in C&&typeof C.name==="string"?C.name:("value"in C)&&typeof C.value==="string"?C.value:"unknown",b=L.initializer,g=b?N(b):void 0,P={kind:"property",name:R,span:X(L.start,L.end),isExported:!1,modifiers:[]};if(g)P.initializer=g;return P});return{kind:"enum",name:u,span:X(M.start,M.end),isExported:q,modifiers:S,members:U.length>0?U:void 0}}if(D==="TSModuleDeclaration"){let w=M,u=w.id.name??w.id.value??"unknown",S=F(w),T=[];if(w.body?.type==="TSModuleBlock")for(let U of w.body.body??[]){if(U.type!=="ExportNamedDeclaration")continue;let L=U.declaration;if(!L)continue;let C=J_(L,!1);if(C)if(Array.isArray(C))T.push(...C);else T.push(C)}return{kind:"namespace",name:u,span:X(M.start,M.end),isExported:q,modifiers:S,members:T.length>0?T:void 0}}return null}let z_=[],Y_=new Set;for(let M of $.body){let q=null,D=M;if(D.type==="ExportNamedDeclaration"){let u=D;if(u.declaration){if(q=J_(u.declaration,!0),q&&!Array.isArray(q))q.span=X(u.start,u.end)}else if(!u.source&&u.specifiers)for(let S of u.specifiers){let T=S.local,U="name"in T?T.name:T.value;if(U)Y_.add(U)}}else if(D.type==="ExportDefaultDeclaration"){let u=D,S=u.declaration;if(S){if(q=J_(S,!0),q&&!Array.isArray(q))q.name="id"in S&&S.id&&typeof S.id.name==="string"?S.id.name:"default",q.isExported=!0,q.span=X(u.start,u.end);else if(!q&&"type"in S&&S.type==="Identifier"){let T=S.name;if(T)Y_.add(T)}}}else{let u=D.type;if(u==="FunctionDeclaration"||u==="TSDeclareFunction"||u==="ClassDeclaration"||u==="VariableDeclaration"||u==="TSTypeAliasDeclaration"||u==="TSInterfaceDeclaration"||u==="TSEnumDeclaration"||u==="TSModuleDeclaration")q=J_(D,!1)}let w=Array.isArray(q)?q:q?[q]:[];for(let u of w){let S=M.start,T=K(S);if(T){let U=l_(T);if(!zJ(U))u.jsDoc=U}z_.push(u)}}if(Y_.size>0){for(let M of z_)if(!M.isExported&&Y_.has(M.name))M.isExported=!0}return z_}function YJ(_){if(_.kind==="function"||_.kind==="method"){let $=_.parameters?.length??0,J=_.modifiers.includes("async")?1:0;return`params:${$}|async:${J}`}return null}function ZJ(_){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 XJ(_){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=YJ(_),Z=V_(`${$}|${_.kind}|${W??""}`),Y=XJ(_);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:ZJ(_),contentHash:z,indexedAt:new Date().toISOString(),structuralFingerprint:Y}}function M$(_){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 K of X.members??[])Y.push(r$(K,`${X.name}.${K.name}`,J,Q,z))}W.replaceFileSymbols(J,Q,z,Y)}import{resolve as L$,dirname as VJ,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=W_(L$(VJ(_),$));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(W_(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 K=$.slice(Y.length,X===""?void 0:$.length-X.length),V=[];for(let H of W)V.push(...Q(W_(L$(J.baseUrl,H.replace("*",K)))));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 K=X[0],V=Z.specifiers??[];for(let H of V)switch(H.type){case"ImportSpecifier":z.set(H.local.name,{path:K,importedName:H.imported.name});break;case"ImportDefaultSpecifier":z.set(H.local.name,{path:K,importedName:"default"});break;case"ImportNamespaceSpecifier":z.set(H.local.name,{path:K,importedName:"*"});break}}return z}import{Visitor as UJ}from"oxc-parser";function a_(_){return"name"in _&&typeof _.name==="string"?_.name:("value"in _)&&typeof _.value==="string"?_.value:"unknown"}function HJ(_){return!_.startsWith(".")&&!_.startsWith("/")}function I_(_,$,J,Q){let z=Q(_,$,J),W=z.length>0?z[0]:null,Z=W===null&&HJ($);return{resolved:W,isExternal:Z}}function KJ(_,$,J,Q,z){for(let W of _.staticImports){let Z=W.moduleRequest.value,{resolved:Y,isExternal:X}=I_($,Z,J,Q),K=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,...K,dstSymbolName:null,...Object.keys(V).length>0?{metaJson:JSON.stringify(V)}:{}});continue}for(let V of W.entries){let H=V.isType,I={};if(H)I.isType=!0;if(X)I.isExternal=!0;if(Y===null&&!X)I.isUnresolved=!0;let N,B,A=V.importName.kind;if(A==="Default")N="default",B=V.localName.value;else if(A==="NamespaceObject")N="*",B=V.localName.value,I.importKind="namespace";else N=V.importName.name??"unknown",B=V.localName.value;z.push({type:H?"type-references":"imports",srcFilePath:$,srcSymbolName:B,...K,dstSymbolName:N,...Object.keys(I).length>0?{metaJson:JSON.stringify(I)}:{}})}}}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:K,isExternal:V}=I_($,X,J,Q),H=Y.exportName.name??"default",I=Y.exportName.kind,N=Y.localName.name??Y.importName.name??H,B=Y.isType,A={isReExport:!0};if(I==="None");else A.specifiers=[{local:N,exported:H}];if(B)A.isType=!0;if(V)A.isExternal=!0;if(K===null&&!V)A.isUnresolved=!0;let k=null,F=null,y=Y.importName.kind;if(y==="All"||y==="AllButDefault"){if(I==="Name"&&H)F=H,A.namespaceAlias=H}else F=N,k=H;z.push({type:B?"type-references":"re-exports",srcFilePath:$,srcSymbolName:k,dstFilePath:K,dstSymbolName:F,metaJson:JSON.stringify(A),...K===null?{specifier:X}:{}})}}function LJ(_,$,J,Q,z){for(let W of _.body){let Z=W;if(Z.type==="ImportDeclaration"){let Y=Z,X=Y.source.value,{resolved:K,isExternal:V}=I_($,X,J,Q),H=Y.importKind==="type",I=Y.specifiers,N=K===null?{dstFilePath:null,specifier:X}:{dstFilePath:K};if(I.length===0){let B={};if(H)B.isType=!0;if(V)B.isExternal=!0;if(K===null&&!V)B.isUnresolved=!0;z.push({type:H?"type-references":"imports",srcFilePath:$,srcSymbolName:null,...N,dstSymbolName:null,...Object.keys(B).length>0?{metaJson:JSON.stringify(B)}:{}})}else for(let B of I){let A=B.type,k=H||A==="ImportSpecifier"&&B.importKind==="type",F={};if(k)F.isType=!0;if(V)F.isExternal=!0;if(K===null&&!V)F.isUnresolved=!0;let y,v;if(A==="ImportDefaultSpecifier")y="default",v=B.local.name;else if(A==="ImportNamespaceSpecifier")y="*",v=B.local.name,F.importKind="namespace";else y=a_(B.imported),v=B.local.name;z.push({type:k?"type-references":"imports",srcFilePath:$,srcSymbolName:v,...N,dstSymbolName:y,...Object.keys(F).length>0?{metaJson:JSON.stringify(F)}:{}})}continue}if(Z.type==="ExportAllDeclaration"){let Y=Z,X=Y.source.value,{resolved:K,isExternal:V}=I_($,X,J,Q),H=Y.exportKind==="type",I=Y.exported,N=I?a_(I):null,B={isReExport:!0};if(H)B.isType=!0;if(V)B.isExternal=!0;if(K===null&&!V)B.isUnresolved=!0;if(N)B.namespaceAlias=N;z.push({type:H?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:K,dstSymbolName:N,metaJson:JSON.stringify(B),...K===null?{specifier:X}:{}});continue}if(Z.type==="ExportNamedDeclaration"){let Y=Z;if(!Y.source)continue;let X=Y.source.value,{resolved:K,isExternal:V}=I_($,X,J,Q),H=Y.exportKind==="type",I=Y.specifiers??[];for(let N of I){let B=H||N.exportKind==="type",A=a_(N.local),k=a_(N.exported),F={isReExport:!0,specifiers:[{local:A,exported:k}]};if(B)F.isType=!0;if(V)F.isExternal=!0;if(K===null&&!V)F.isUnresolved=!0;z.push({type:B?"type-references":"re-exports",srcFilePath:$,srcSymbolName:k,dstFilePath:K,dstSymbolName:A,metaJson:JSON.stringify(F),...K===null?{specifier:X}:{}})}}}}function wJ(_,$,J,Q,z){new UJ({ImportExpression(Z){let Y=Z.source;if(Y.type!=="Literal"||typeof Y.value!=="string")return;let X=Y.value,{resolved:K,isExternal:V}=I_($,X,J,Q),H={isDynamic:!0};if(V)H.isExternal=!0;if(K===null&&!V)H.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:K,dstSymbolName:null,metaJson:JSON.stringify(H),...K===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 A=Y,k=A.object,F=A.property;if(k.type==="Identifier"&&k.name==="require"&&F.name==="resolve")X=!0;else return}else return;let K=Z.arguments;if(K.length===0)return;let V=K[0];if(V.type!=="Literal"||typeof V.value!=="string")return;let H=V.value,{resolved:I,isExternal:N}=I_($,H,J,Q),B={isRequire:!0};if(X)B.isRequireResolve=!0;if(N)B.isExternal=!0;if(I===null&&!N)B.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:I,dstSymbolName:null,metaJson:JSON.stringify(B),...I===null?{specifier:H}:{}})}}).visit(_)}function t$(_,$,J,Q=D_,z){let W=[];if(z)KJ(z,$,J,Q,W),MJ(z,$,J,Q,W);else LJ(_,$,J,Q,W);return wJ(_,$,J,Q,W),W}import{walk as BJ}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 H=J.get(V.root);if(V.parts.length===0){if(H)return{dstFilePath:H.path,dstSymbolName:H.importedName,resolution:"import"};return{dstFilePath:$,dstSymbolName:V.root,resolution:"local"}}else{if(H&&H.importedName==="*"){let I=V.parts[V.parts.length-1];return{dstFilePath:H.path,dstSymbolName:I,resolution:"namespace"}}return{dstFilePath:$,dstSymbolName:V.full,resolution:"local-member"}}}function X(V,H){let I=T_(V.callee),N=Y(I);if(N){let B=Z(),A={};if(H)A.isNew=!0;if(B===null)A.scope="module";Q.push({type:"calls",srcFilePath:$,srcSymbolName:B,dstFilePath:N.dstFilePath,dstSymbolName:N.dstSymbolName,...Object.keys(A).length>0?{metaJson:JSON.stringify(A)}:{}})}}function K(V,H){if(V.type==="FunctionDeclaration"){z.push(V.id?.name??"anonymous");return}if(V.type==="FunctionExpression"||V.type==="ArrowFunctionExpression"){if(H?.type==="VariableDeclarator"){let B=H.id,A=B.type==="Identifier"?B.name:"anonymous";z.push(A);return}if(H?.type==="MethodDefinition"||H?.type==="TSAbstractMethodDefinition"){let B=H.key,A=W[W.length-1]??"",k="name"in B?B.name:"anonymous",F=A?`${A}.${k}`:k;z.push(F);return}let I=Z(),N=I?`${I}.<anonymous>`:"<anonymous>";z.push(N)}}return BJ(_,{enter(V,H){if(V.type==="ClassDeclaration"||V.type==="ClassExpression"){W.push(V.id?.name??"AnonymousClass");return}if(V.type==="FunctionDeclaration"||V.type==="FunctionExpression"||V.type==="ArrowFunctionExpression"){K(V,H);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 DJ}from"oxc-parser";function _0(_,$,J){let Q=[];function z(Z){let Y=Z.id?.name??"AnonymousClass";if(Z.superClass){let K=T_(Z.superClass);if(K){let V=w$(K,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Y,...V})}}let X=Z.implements??[];for(let K of X){let V=T_(K.expression);if(!V)continue;let H=w$(V,$,J);Q.push({type:"implements",srcFilePath:$,srcSymbolName:Y,...H})}}return new DJ({TSInterfaceDeclaration(Z){let Y=Z.id.name??"AnonymousInterface",X=Z.extends;for(let K of X){let V=T_(K.expression);if(!V)continue;let H=w$(V,$,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:K}=_,V=S_(W,Q),I=s_($,V,Z,Y?(B,A,k)=>{let F=D_(B,A,k);for(let y of F){let v=E_(W,y);if(X){let h=c(v,X);if(Y.has(`${h}::${v}`))return[y]}else if(Y.has(`${J}::${v}`))return[y]}return[]}:void 0,K),N=[];for(let B of I){if(B.dstFilePath===null){let y=E_(W,B.srcFilePath),v;if(B.metaJson)try{v=JSON.parse(B.metaJson)}catch{}let h=v?.isExternal===!0;N.push({project:J,type:B.type,srcFilePath:y,srcSymbolName:B.srcSymbolName??null,dstProject:null,dstFilePath:null,dstSymbolName:B.dstSymbolName??null,metaJson:B.metaJson??null,specifier:B.specifier??null,isExternal:h?1:0});continue}let A=E_(W,B.dstFilePath);if(A.startsWith(".."))continue;let k=E_(W,B.srcFilePath),F=X?c(A,X):J;N.push({project:J,type:B.type,srcFilePath:k,srcSymbolName:B.srcSymbolName??null,dstProject:F,dstFilePath:A,dstSymbolName:B.dstSymbolName??null,metaJson:B.metaJson??null,specifier:B.specifier??null,isExternal:0})}return z.replaceFileRelations(J,Q,N),N.length}import{isErr as IJ}from"@zipbul/result";var $0=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function CJ(_){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=CJ(_),W=[],Z=[...$].sort((X,K)=>X.start-K.start),Y=null;for(let X of Z)if(X.type==="Block"&&X.value.startsWith("*")){Y=null;let K=`/*${X.value}*/`,V=l_(K);if(IJ(V))continue;let H=V;if(!H.tags?.length)continue;let I=X_(Q,X.end),N=D$(z,I.line,3),B=J.slice(X.start,X.end);for(let A of H.tags){let k=[A.name,A.description].filter(Boolean).join(" "),F=`@${A.tag}`,y=B.indexOf(F),v;if(y>=0){let h=X.start+y,a=J.indexOf(`
|
|
4
|
+
`,h),t=a>=0?Math.min(a,X.end):X.end;v=r_(Q,h,t)}else v=r_(Q,X.start,X.end);W.push({tag:A.tag,value:k,source:"jsdoc",span:v,symbolName:N})}}else if(X.type==="Block"){Y=null;let K=X.value.split(`
|
|
5
|
+
`),V=0;for(let H of K){let I=H.replace(/^\s*\*?\s?/,""),N=$0.exec(I);if(N){let B=N[1],A=N[2]?.trim()??"",k=`@${B}`,F=H.indexOf(k),y=X.start+2+V+(F>=0?F:0),v=X.start+2+V+H.length,h=r_(Q,y,v),a=X_(Q,X.end),t=D$(z,a.line,3);W.push({tag:B,value:A,source:"block",span:h,symbolName:t})}V+=H.length+1}}else{let K=X.value,V=$0.exec(K),H=X_(Q,X.start),I=X_(Q,X.end);if(V){let N=V[1],B=V[2]?.trim()??"",A=`@${N}`,k=K.indexOf(A),F=X.start+2+(k>=0?k:0),y=r_(Q,F,X.end),v=D$(z,I.line,3),h={tag:N,value:B,source:"line",span:y,symbolName:v};W.push(h),Y={annotation:h,endLine:I.line}}else if(Y&&H.line===Y.endLine+1){let N=K.trim();if(N)Y.annotation.value+=" "+N,Y.annotation.span.end=X_(Q,X.end),Y.endLine=I.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,H]of $)if(!_.has(V))J.push({name:H.name,filePath:H.filePath,kind:H.kind,fingerprint:H.fingerprint});for(let[V,H]of _)if(!$.has(V))Q.push({name:H.name,filePath:H.filePath,kind:H.kind,fingerprint:H.fingerprint});if(!J.length||!Q.length)return{renamed:z,added:J,removed:Q};let W=new Map,Z=new Map;for(let V of J){let H=W.get(V.filePath)??[];H.push(V),W.set(V.filePath,H)}for(let V of Q){let H=Z.get(V.filePath)??[];H.push(V),Z.set(V.filePath,H)}let Y=new Set,X=new Set;for(let[V,H]of W){let I=Z.get(V);if(!I)continue;for(let N of new Set(H.map((B)=>B.kind))){let B=H.filter((v)=>v.kind===N&&!Y.has(v)),A=I.filter((v)=>v.kind===N&&!X.has(v));if(!B.length||!A.length)continue;let k=(v,h)=>{return h.get(`${v.filePath}::${v.name}`)?.structuralFingerprint??null},F=(v,h)=>{return h.get(`${v.filePath}::${v.name}`)?.startLine??0},y=new Map;for(let v of A){let h=k(v,_);if(!h)continue;let a=y.get(h)??[];a.push(v),y.set(h,a)}for(let v of B){if(Y.has(v))continue;let h=k(v,$);if(!h)continue;let a=y.get(h);if(!a)continue;let t=a.filter((z_)=>!X.has(z_));if(!t.length)continue;let J_=t[0];if(t.length>1){let z_=F(v,$),Y_=Math.abs(F(J_,_)-z_);for(let M=1;M<t.length;M++){let q=Math.abs(F(t[M],_)-z_);if(q<Y_)Y_=q,J_=t[M]}}z.push({oldName:J_.name,newName:v.name,filePath:V,kind:N}),Y.add(v),X.add(J_)}}}let K=z.filter((V)=>!V.oldName.includes("."));for(let V of K){let H=`${V.oldName}.`,I=`${V.newName}.`,N=Q.filter((A)=>A.filePath===V.filePath&&A.name.startsWith(H)&&!X.has(A)),B=J.filter((A)=>A.filePath===V.filePath&&A.name.startsWith(I)&&!Y.has(A));for(let A of N){let k=A.name.slice(H.length),F=B.find((y)=>y.name.slice(I.length)===k);if(F)z.push({oldName:A.name,newName:F.name,filePath:V.filePath,kind:A.kind}),Y.add(F),X.add(A)}}return{renamed:z,added:J.filter((V)=>!Y.has(V)),removed:Q.filter((V)=>!X.has(V))}}var AJ=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()},AJ)}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((U)=>U.eventType==="create"||U.eventType==="change").map((U)=>({filePath:U.filePath,contentHash:"",mtimeMs:0,size:0})),X=_.filter((U)=>U.eventType==="delete").map((U)=>U.filePath);else{let U=new Map;for(let C of this.opts.boundaries)for(let[R,b]of Q.getFilesMap(C.project))U.set(R,b);let L=await s$({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>U}});Y=L.changed,X=L.deleted}let K=await this.tsconfigPathsRaw??void 0,V=new Map;for(let U of X){let L=c(U,this.opts.boundaries),C=z.getFileSymbols(L,U);V.set(U,C)}let H=crypto.randomUUID(),I=new Map,N=new Map,B=(U)=>({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint,structuralFingerprint:U.structuralFingerprint??null,startLine:U.startLine,isExported:U.isExported??0});if($)for(let U of this.opts.boundaries)for(let L of Q.getAllFiles(U.project))for(let C of z.getFileSymbols(U.project,L.filePath))I.set(`${C.filePath}::${C.name}`,B(C));else{for(let U of Y){let L=c(U.filePath,this.opts.boundaries);for(let C of z.getFileSymbols(L,U.filePath))I.set(`${C.filePath}::${C.name}`,B(C))}for(let[,U]of V)for(let L of U)I.set(`${L.filePath}::${L.name}`,B(L))}let A=(U)=>`${U.type}|${U.srcFilePath}|${U.dstFilePath??""}|${U.srcSymbolName??""}|${U.dstSymbolName??""}|${V_(U.metaJson??"")}`,k=new Map;if($)for(let U of this.opts.boundaries)for(let L of Q.getAllFiles(U.project))for(let C of W.getOutgoing(U.project,L.filePath))k.set(A(C),C);else{for(let U of Y){let L=c(U.filePath,this.opts.boundaries);for(let C of W.getOutgoing(L,U.filePath))k.set(A(C),C)}for(let U of X){let L=c(U,this.opts.boundaries);for(let C of W.getOutgoing(L,U))k.set(A(C),C)}}let{annotationRepo:F,changelogRepo:y}=this.opts,v=()=>{for(let U of X){let L=c(U,this.opts.boundaries);if(z.deleteFileSymbols(L,U),W.deleteFileRelations(L,U),W.deleteIncomingRelations(L,U),F)F.deleteFileAnnotations(L,U);Q.deleteFile(L,U)}},h=0,a=async()=>{let{projectRoot:U,boundaries:L}=this.opts,{parseCache:C}=this.opts,R=0,b=0,g=0,P=[],j=[];for(let E of Y)try{let i=S_(U,E.filePath),M_=Bun.file(i),N_=await M_.text(),P$=E.contentHash||V_(N_),f$=c(E.filePath,L);Q.upsertFile({project:f$,filePath:E.filePath,mtimeMs:M_.lastModified,size:M_.size,contentHash:P$,updatedAt:new Date().toISOString(),lineCount:N_.split(`
|
|
6
|
+
`).length});let z$=(this.opts.parseSourceFn??P_)(i,N_);if(z0(z$))throw z$.data;let g1=z$;j.push({filePath:E.filePath,text:N_,contentHash:P$,parsed:g1,project:f$})}catch(i){this.logger.error(`[IndexCoordinator] Failed to prepare ${E.filePath}:`,i),P.push(E.filePath)}let x=new Set;for(let E of L)for(let[i]of Q.getFilesMap(E.project))x.add(`${E.project}::${i}`);return Z.transaction(()=>{for(let E of j){if(M$({parsed:E.parsed,project:E.project,filePath:E.filePath,contentHash:E.contentHash,symbolRepo:z}),b+=B$({ast:E.parsed.program,project:E.project,filePath:E.filePath,relationRepo:W,projectRoot:U,tsconfigPaths:K,knownFiles:x,boundaries:L,module:E.parsed.module}),F)g+=I$({parsed:E.parsed,project:E.project,filePath:E.filePath,annotationRepo:F});C.set(E.filePath,E.parsed),R+=z.getFileSymbols(E.project,E.filePath).length}}),{symbols:R,relations:b,annotations:g,failedFiles:P}},t=0,J_=0,z_=[];if($){let{projectRoot:U,boundaries:L}=this.opts,{parseCache:C}=this.opts,R=[];for(let g=0;g<Y.length;g+=W0){let P=Y.slice(g,g+W0),j=await Promise.allSettled(P.map(async(x)=>{let E=S_(U,x.filePath),i=Bun.file(E),M_=await i.text(),N_=x.contentHash||V_(M_);return{filePath:x.filePath,text:M_,contentHash:N_,mtimeMs:i.lastModified,size:i.size}}));for(let x=0;x<j.length;x++){let E=j[x];if(E.status==="fulfilled")R.push(E.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",E.reason),z_.push(P[x].filePath)}}let b=[];Z.transaction(()=>{for(let j of R){let x=c(j.filePath,L);Q.deleteFile(x,j.filePath)}for(let j of X){let x=c(j,L);if(z.deleteFileSymbols(x,j),W.deleteFileRelations(x,j),W.deleteIncomingRelations(x,j),F)F.deleteFileAnnotations(x,j);Q.deleteFile(x,j)}for(let j of R){let x=c(j.filePath,L);Q.upsertFile({project:x,filePath:j.filePath,mtimeMs:j.mtimeMs,size:j.size,contentHash:j.contentHash,updatedAt:new Date().toISOString(),lineCount:j.text.split(`
|
|
7
|
+
`).length})}let g=new Set;for(let j of L)for(let[x]of Q.getFilesMap(j.project))g.add(`${j.project}::${x}`);let P=this.opts.parseSourceFn??P_;for(let j of R){let x=c(j.filePath,L),E=P(S_(U,j.filePath),j.text);if(z0(E))throw E.data;let i=E;if(b.push({filePath:j.filePath,parsed:i}),M$({parsed:i,project:x,filePath:j.filePath,contentHash:j.contentHash,symbolRepo:z}),F)h+=I$({parsed:i,project:x,filePath:j.filePath,annotationRepo:F});J_+=B$({ast:i.program,project:x,filePath:j.filePath,relationRepo:W,projectRoot:U,tsconfigPaths:K,knownFiles:g,boundaries:L,module:i.module}),t+=z.getFileSymbols(x,j.filePath).length}});for(let g of b)C.set(g.filePath,g.parsed)}else{v();let U=await a();t=U.symbols,J_=U.relations,h=U.annotations,z_=U.failedFiles}for(let U of Y){let L=c(U.filePath,this.opts.boundaries);for(let C of z.getFileSymbols(L,U.filePath))N.set(`${C.filePath}::${C.name}`,B(C))}let Y_=new Map;for(let U of Y){let L=c(U.filePath,this.opts.boundaries);for(let C of W.getOutgoing(L,U.filePath))Y_.set(A(C),C)}let M=(U)=>({type:U.type,srcFilePath:U.srcFilePath,dstFilePath:U.dstFilePath,srcSymbolName:U.srcSymbolName,dstSymbolName:U.dstSymbolName,dstProject:U.dstProject,metaJson:U.metaJson}),q={added:[...Y_.entries()].filter(([U])=>!k.has(U)).map(([,U])=>M(U)),removed:[...k.entries()].filter(([U])=>!Y_.has(U)).map(([,U])=>M(U))},D={added:[],modified:[],removed:[]};for(let[U,L]of N){let C=I.get(U);if(!C)D.added.push({name:L.name,filePath:L.filePath,kind:L.kind,isExported:Boolean(L.isExported)});else{let R=C.fingerprint!==L.fingerprint,b=C.isExported!==L.isExported,g=C.structuralFingerprint!==null&&L.structuralFingerprint!==null&&C.structuralFingerprint!==L.structuralFingerprint;if(R||b||g)D.modified.push({name:L.name,filePath:L.filePath,kind:L.kind,isExported:Boolean(L.isExported)})}}for(let[U,L]of I)if(!N.has(U))D.removed.push({name:L.name,filePath:L.filePath,kind:L.kind,isExported:Boolean(L.isExported)});let w=Q0(I,N),u=new Set(w.renamed.map((U)=>`${U.filePath}::${U.oldName}`)),S=new Set(w.renamed.map((U)=>`${U.filePath}::${U.newName}`));D.added=D.added.filter((U)=>!S.has(`${U.filePath}::${U.name}`)),D.removed=D.removed.filter((U)=>!u.has(`${U.filePath}::${U.name}`));let T=[];if(!$){for(let[L,C]of V)for(let R of C){if(!R.fingerprint)continue;let b=c(L,this.opts.boundaries),g=z.getByFingerprint(b,R.fingerprint);if(g.length===1){let P=g[0];W.retargetRelations({dstProject:b,oldFile:L,oldSymbol:R.name,newFile:P.filePath,newSymbol:P.name}),T.push({name:P.name,filePath:P.filePath,kind:P.kind,oldFilePath:L,isExported:P.isExported??0})}}let U=new Set(T.map((L)=>`${L.oldFilePath}::${L.name}`));for(let L of w.removed){if(U.has(`${L.filePath}::${L.name}`))continue;let R=I.get(`${L.filePath}::${L.name}`)?.fingerprint;if(!R)continue;let b=c(L.filePath,this.opts.boundaries),g=z.getByFingerprint(b,R);if(g.length===1){let P=g[0];if(P.filePath!==L.filePath||P.name!==L.name)W.retargetRelations({dstProject:b,oldFile:L.filePath,oldSymbol:L.name,newFile:P.filePath,newSymbol:P.name}),T.push({name:P.name,filePath:P.filePath,kind:P.kind,oldFilePath:L.filePath,isExported:P.isExported??0})}}}if(T.length){let U=new Set(T.map((C)=>`${C.filePath}::${C.name}`)),L=new Set(T.map((C)=>`${C.oldFilePath}::${C.name}`));D.added=D.added.filter((C)=>!U.has(`${C.filePath}::${C.name}`)),D.removed=D.removed.filter((C)=>!L.has(`${C.filePath}::${C.name}`))}if(y){let U=new Date().toISOString(),L=$?1:0,C=[];for(let R of D.added){let b=`${R.filePath}::${R.name}`,g=N.get(b),P=c(R.filePath,this.opts.boundaries);C.push({project:P,changeType:"added",symbolName:R.name,symbolKind:R.kind,filePath:R.filePath,oldName:null,oldFilePath:null,fingerprint:g?.fingerprint??null,changedAt:U,isFullIndex:L,indexRunId:H})}for(let R of D.modified){let b=N.get(`${R.filePath}::${R.name}`),g=c(R.filePath,this.opts.boundaries);C.push({project:g,changeType:"modified",symbolName:R.name,symbolKind:R.kind,filePath:R.filePath,oldName:null,oldFilePath:null,fingerprint:b?.fingerprint??null,changedAt:U,isFullIndex:L,indexRunId:H})}for(let R of D.removed){let b=`${R.filePath}::${R.name}`,g=I.get(b),P=c(R.filePath,this.opts.boundaries);C.push({project:P,changeType:"removed",symbolName:R.name,symbolKind:R.kind,filePath:R.filePath,oldName:null,oldFilePath:null,fingerprint:g?.fingerprint??null,changedAt:U,isFullIndex:L,indexRunId:H})}for(let R of w.renamed){let b=N.get(`${R.filePath}::${R.newName}`),g=c(R.filePath,this.opts.boundaries);C.push({project:g,changeType:"renamed",symbolName:R.newName,symbolKind:R.kind,filePath:R.filePath,oldName:R.oldName,oldFilePath:null,fingerprint:b?.fingerprint??null,changedAt:U,isFullIndex:L,indexRunId:H})}for(let R of T){let b=N.get(`${R.filePath}::${R.name}`),g=c(R.filePath,this.opts.boundaries);C.push({project:g,changeType:"moved",symbolName:R.name,symbolKind:R.kind,filePath:R.filePath,oldName:null,oldFilePath:R.oldFilePath,fingerprint:b?.fingerprint??null,changedAt:U,isFullIndex:L,indexRunId:H})}if(C.length)try{Z.transaction(()=>{y.insertBatch(C)})}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 b of this.opts.boundaries)y.pruneOlderThan(b.project,R)}catch(b){this.logger.error("[IndexCoordinator] changelog pruning failed:",b)}}}return{indexedFiles:Y.length,removedFiles:X.length,totalSymbols:t,totalRelations:J_,totalAnnotations:h,durationMs:Date.now()-J,changedFiles:Y.map((U)=>U.filePath),deletedFiles:[...X],failedFiles:z_,changedSymbols:D,renamedSymbols:w.renamed.map((U)=>({oldName:U.oldName,newName:U.newName,filePath:U.filePath,kind:U.kind,isExported:Boolean(N.get(`${U.filePath}::${U.newName}`)?.isExported)})),movedSymbols:T.map((U)=>({name:U.name,oldFilePath:U.oldFilePath,newFilePath:U.filePath,kind:U.kind,isExported:Boolean(U.isExported)})),changedRelations:q}}fireCallbacks(_){for(let $ of this.callbacks)try{$(_)}catch(J){this.logger.error("[IndexCoordinator] onIndexed callback threw:",J)}}flushPending(){if(this.indexingLock)return;if(this.pendingEvents.length>0){let _=this.pendingEvents.splice(0);this.startIndex(_,!1).catch(($)=>this.logger.error("[IndexCoordinator] flushPending startIndex error:",$))}}}function NJ(_){try{return process.kill(_,0),!0}catch($){if(typeof $==="object"&&$&&"code"in $)return $.code!=="ESRCH";return!0}}function qJ(_){let $=new Date(_).getTime();return Number.isNaN($)?0:$}function Y0(_,$,J={}){let Q=J.now??Date.now,z=J.isAlive??NJ,W=J.staleAfterSeconds??60,Z=J.instanceId;return _.immediateTransaction(()=>{let Y=_.selectOwner();if(!Y)return _.insertOwner($,Z),"owner";let X=Math.floor((Q()-qJ(Y.heartbeat_at))/1000),K=z(Y.pid);if(K&&Z&&Y.instance_id&&Y.instance_id!==Z&&Y.pid===$)return _.replaceOwner($,Z),"owner";if(K&&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,K=$.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 H;if(V.metaJson)try{H=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:H}});if(Q.srcFilePathPattern||Q.dstFilePathPattern){let V=Q.srcFilePathPattern?new Bun.Glob(Q.srcFilePathPattern):null,H=Q.dstFilePathPattern?new Bun.Glob(Q.dstFilePathPattern):null;K=K.filter((I)=>(!V||V.match(I.srcFilePath))&&(!H||I.dstFilePath===null||H.match(I.dstFilePath)))}if(Z&&W!==void 0&&K.length>W)K=K.slice(0,W);return K}import{findInFiles as uJ,Lang as SJ}from"@ast-grep/napi";function gJ(_){let $=new Set,J=/\${1,3}([A-Z_][A-Z_0-9]*)/g,Q;while((Q=J.exec(_))!==null)$.add(Q[0]);return[...$]}function RJ(_,$){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((K)=>K.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 $=gJ(_.pattern),J=[];return await uJ(SJ.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=RJ(W,$);if(X)Y.captures=X;J.push(Y)}}),J}import e from"typescript";import{isErr as nJ}from"@zipbul/result";import H_ from"typescript";import TJ from"path";import{err as S$}from"@zipbul/result";function FJ(_){try{return y$("fs").readFileSync(_,"utf-8")}catch{return}}function kJ(_){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??FJ,Q=$.resolveNonTrackedFile??kJ,z=TJ.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 H=Y.map((I)=>H_.flattenDiagnosticMessageText(I.messageText,`
|
|
8
|
+
`)).join("; ");return S$(new O("semantic",`tsconfig parse error: ${H}`))}let X=H_.parseJsonSourceFileConfigFileContent(Z,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(H)=>J(H)!==void 0||Q(H)!==void 0,readFile:(H)=>J(H)??Q(H)},z);if(X.errors.length>0){let H=X.errors.filter((I)=>I.category===H_.DiagnosticCategory.Error&&I.code!==18003);if(H.length>0){let I=H.map((N)=>H_.flattenDiagnosticMessageText(N.messageText,`
|
|
9
|
+
`)).join("; ");return S$(new O("semantic",`tsconfig compile error: ${I}`))}}let K=new V0(X.fileNames,X.options,z,Q),V=H_.createLanguageService(K);return new o_(V,K)}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 l from"typescript";import GJ from"typescript";function $_(_,$){if($<0||$>=_.getEnd())return;function J(Q){let z=Q.getStart(_,!1),W=Q.getEnd();if($<z||$>=W)return;let Z;return GJ.forEachChild(Q,(Y)=>{if(!Z)Z=J(Y)}),Z??Q}return J(_)}var t_=8;function jJ(_){return!!(_.flags&l.TypeFlags.Object)&&!!(_.objectFlags&l.ObjectFlags.Reference)}function U_(_,$,J=0,Q){if(Q){let B=Q.get($);if(B)return B}let z=_.typeToString($),W=$.flags,Z=!!(W&l.TypeFlags.Union),Y=!!(W&l.TypeFlags.Intersection),X;if(J<t_&&jJ($)){let B=_.getTypeArguments($);if(B.length>0)X=B}let K=!!(W&l.TypeFlags.TypeParameter)||X!==void 0&&X.length>0,V;if(Z&&J<t_)V=$.types.map((B)=>U_(_,B,J+1,Q));else if(Y&&J<t_)V=$.types.map((B)=>U_(_,B,J+1,Q));let H;if(X&&X.length>0)H=X.map((B)=>U_(_,B,J+1,Q));let I;if(J<t_&&!!(W&l.TypeFlags.Object)&&!Z&&!Y){let B=_.getPropertiesOfType($);if(B.length>0&&B.length<=50){let A=$.symbol?.declarations?.[0];I=[];for(let k of B){let F=k.declarations?.[0]??A;if(!F)continue;try{let y=_.getTypeOfSymbolAtLocation(k,F);I.push({name:k.getName(),type:U_(_,y,J+1,Q)})}catch{}}if(I.length===0)I=void 0}}let N={text:z,flags:W,isUnion:Z,isIntersection:Y,isGeneric:K,members:V,typeArguments:H,properties:I};if(Q)Q.set($,N);return N}function EJ(_){return l.isFunctionDeclaration(_)||l.isVariableDeclaration(_)||l.isClassDeclaration(_)||l.isInterfaceDeclaration(_)||l.isTypeAliasDeclaration(_)||l.isEnumDeclaration(_)||l.isMethodDeclaration(_)||l.isPropertyDeclaration(_)||l.isPropertySignature(_)||l.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||!l.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=$_(z,$);if(!W)return null;if(!l.isIdentifier(W)&&!l.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,$);if(!Y||!l.isIdentifier(Y))return null;let X=W.getSourceFile(J);if(!X)return null;let K=$_(X,Q);if(!K||!l.isIdentifier(K))return null;try{let V=z.getTypeAtLocation(Y),H=z.getTypeAtLocation(K);return z.isTypeAssignableTo(V,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,$);if(!Y||!l.isIdentifier(Y)&&!l.isTypeNode(Y))return null;try{let X=this.#J(z,W);if(!X)return null;let K=W.getTypeAtLocation(Y);if(Q?.anyConstituent&&K.isUnion())return K.types.some((V)=>W.isTypeAssignableTo(V,X));return W.isTypeAssignableTo(K,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 K=Y.getEnd();for(let V of $){if(V<0||V>=K)continue;let H=$_(Y,V);if(!H||!l.isIdentifier(H)&&!l.isTypeNode(H))continue;try{let I=Z.getTypeAtLocation(H);if(Q?.anyConstituent&&I.isUnion())z.set(V,I.types.some((N)=>Z.isTypeAssignableTo(N,X)));else z.set(V,Z.isTypeAssignableTo(I,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 K=$_(W,X);if(!K)continue;if(!l.isIdentifier(K)&&!l.isTypeNode(K))continue;try{let V=z.getTypeAtLocation(K);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(EJ(Y)&&Y.name&&l.isIdentifier(Y.name)){let X=Y.name;try{let K=Q.getTypeAtLocation(X),V=X.getStart(z);$.set(V,U_(Q,K,0,W))}catch{}}l.forEachChild(Y,Z)}return Z(z),$}}import K_ from"typescript";var vJ=1000,bJ=1;function PJ(_){let $=_.declarations?.[0],J=$?.getSourceFile(),Q=$?K_.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?K_.getNameOfDeclaration(Q):void 0,Z=z?.fileName??"",Y=W?.getStart(z,!1)??Q?.getStart(z,!1)??0,X={name:_.getName(),filePath:Z,position:Y},K=_;if(K.parent)X.parent=PJ(K.parent);let V=J&&!!(_.flags&K_.SymbolFlags.Alias)?J.getAliasedSymbol(_):_;if($<bJ){let H=V.flags,I=!!(H&K_.SymbolFlags.Enum),N=!!(H&(K_.SymbolFlags.NamespaceModule|K_.SymbolFlags.ValueModule)),B=!!(H&(K_.SymbolFlags.Class|K_.SymbolFlags.Interface));if(I&&V.exports&&V.exports.size>0){let A=[];V.exports.forEach((k)=>{A.push(e_(k,$+1,J))}),X.members=A}else if(B&&V.members&&V.members.size>0){let A=[];V.members.forEach((k)=>{A.push(e_(k,$+1,J))}),X.members=A}if(N&&V.exports&&V.exports.size>0){let A=[];V.exports.forEach((k)=>{A.push(e_(k,$+1,J))}),X.exports=A}}return X}class T${#_;#$;#J=new Map;constructor(_,$=vJ){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=$_(W,$);if(!Z||!K_.isIdentifier(Z))return null;let Y=this.#_.getChecker(),X=Y.getSymbolAtLocation(Z);if(!X)return null;let K=e_(X,0,Y);this.#$.set(J,K);let V=this.#J.get(_);if(!V)V=new Set,this.#J.set(_,V);return V.add(J),K}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,$);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 K of X.references){let V=J.getSourceFile(K.fileName);if(!V)continue;let{line:H,character:I}=V.getLineAndCharacterOfPosition(K.textSpan.start);Y.push({filePath:K.fileName,position:K.textSpan.start,line:H+1,column:I,isDefinition:K.isDefinition??!1,isWrite:K.isWriteAccess??!1})}return Y}}import p from"typescript";function yJ(_,$){let J=$_(_,$);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 p.isClassDeclaration(_)||p.isClassExpression(_)||p.isFunctionDeclaration(_)||p.isFunctionExpression(_)||p.isArrowFunction(_)||p.isVariableDeclaration(_)||p.isObjectLiteralExpression(_)}function U0(_){if(p.isClassDeclaration(_)||p.isClassExpression(_))return"class";if(p.isFunctionDeclaration(_)||p.isFunctionExpression(_)||p.isArrowFunction(_))return"function";if(p.isObjectLiteralExpression(_))return"object";if(p.isVariableDeclaration(_)&&_.initializer)return U0(_.initializer);return"class"}function xJ(_,$){if(p.isClassDeclaration(_)||p.isFunctionDeclaration(_))return _.name?.getText($)??"";if(p.isClassExpression(_))return _.name?.getText($)??"";if(p.isVariableDeclaration(_)&&p.isIdentifier(_.name))return _.name.getText($);if(p.isFunctionExpression(_))return _.name?.getText($)??"";if(p.isArrowFunction(_)&&_.parent&&p.isVariableDeclaration(_.parent)){if(p.isIdentifier(_.parent.name))return _.parent.name.getText($)}if(p.isObjectLiteralExpression(_)&&_.parent&&p.isVariableDeclaration(_.parent)){if(p.isIdentifier(_.parent.name))return _.parent.name.getText($)}return""}function mJ(_){if(!p.isClassDeclaration(_)&&!p.isClassExpression(_))return!1;let $=_.heritageClauses;if(!$)return!1;return $.some((J)=>J.token===p.SyntaxKind.ImplementsKeyword)}class k${#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=$_(Q,$);if(!z||!p.isIdentifier(z))return[];let Z=this.#_.getLanguageService().getImplementationAtPosition(_,$);if(!Z||Z.length===0)return[];let Y=[];for(let X of Z){if(X.kind===p.ScriptElementKind.interfaceElement||X.kind===p.ScriptElementKind.typeElement)continue;let K=J.getSourceFile(X.fileName);if(!K)continue;let V=yJ(K,X.textSpan.start);if(!V)continue;let H=U0(V),I=xJ(V,K),N=mJ(V);Y.push({filePath:X.fileName,symbolName:I,position:X.textSpan.start,kind:H,isExplicit:N})}return Y}}function hJ(_){if(e.isFunctionDeclaration(_))return"function";if(e.isClassDeclaration(_))return"class";if(e.isInterfaceDeclaration(_))return"interface";if(e.isTypeAliasDeclaration(_))return"type";if(e.isEnumDeclaration(_))return"enum";if(e.isVariableDeclaration(_))return"const";if(e.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(nJ(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,$);if(!z)return null;let W=this.#_.getChecker(),Z=W.getTypeAtLocation(z);if(!(Z.flags&e.TypeFlags.Object)||!(Z.objectFlags&e.ObjectFlags.ClassOrInterface))return null;let Y=W.getBaseTypes(Z);if(!Y||Y.length===0)return[];let X=new Map;return Y.map((K)=>U_(W,K,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 K=X.getName(),V=X.declarations?.[0],H="unknown";if(V){if(H=hJ(V),H==="unknown"&&e.isExportAssignment(V))H="const"}let I=null;try{let N=z.getTypeOfSymbolAtLocation(X,V??Q);I=U_(z,N,0,Y)}catch{}$.push({name:K,kind:H,resolvedType:I})}}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 e.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={[e.DiagnosticCategory.Error]:"error",[e.DiagnosticCategory.Warning]:"warning",[e.DiagnosticCategory.Suggestion]:"suggestion",[e.DiagnosticCategory.Message]:"suggestion"};return(($?.preEmit)?e.getPreEmitDiagnostics(J,Q):J.getSemanticDiagnostics(Q)).map((Z)=>{let Y=1,X=0;if(Z.file&&Z.start!==void 0){let K=e.getLineAndCharacterOfPosition(Z.file,Z.start);Y=K.line+1,X=K.character}return{filePath:Z.file?.fileName??_,line:Y,column:X,message:e.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 K0,sql as pJ}from"drizzle-orm";var M0=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+=M0)this.db.drizzleDb.insert(Z_).values(Q.slice(z,z+M0)).run()}deleteFileAnnotations(_,$){this.db.drizzleDb.delete(Z_).where(K0(C_(Z_.project,_),C_(Z_.filePath,$))).run()}search(_){let $=this.db.drizzleDb.select().from(Z_).where(K0(_.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?pJ`${Z_.id} IN (SELECT rowid FROM annotations_fts WHERE annotations_fts MATCH ${_.ftsQuery})`:void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}}import{eq as F_,and as L0,sql as x_,gt as iJ,gte as dJ}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(__).values($.slice(J,J+w0)).run()}getSince(_){return this.db.drizzleDb.select().from(__).where(L0(F_(__.project,_.project),dJ(__.changedAt,_.since),_.symbolName?F_(__.symbolName,_.symbolName):void 0,_.changeTypes?.length?x_`${__.changeType} IN (${x_.join(_.changeTypes.map(($)=>x_`${$}`),x_`, `)})`:void 0,_.filePath?F_(__.filePath,_.filePath):void 0,_.includeFullIndex?void 0:F_(__.isFullIndex,0),_.indexRunId?F_(__.indexRunId,_.indexRunId):void 0,_.afterId?iJ(__.id,_.afterId):void 0)).orderBy(__.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete(__).where(L0(F_(__.project,_),x_`${__.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 rJ(J,$)}}var lJ=(_,$)=>_.localeCompare($);function cJ(_){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=cJ(J);if(Q.length===0)return!1;let z=Q.join("->");if(_.has(z))return!1;return _.add(z),$.push(Q),!0}function aJ(_){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 K of _.get(X)??[])if(!z.has(K))Y(K),W.set(X,Math.min(W.get(X)??0,W.get(K)??0));else if(Q.has(K))W.set(X,Math.min(W.get(X)??0,z.get(K)??0));if(W.get(X)===z.get(X)){let K=[],V="";do V=J.pop()??"",Q.delete(V),K.push(V);while(V!==X&&J.length>0);Z.push(K)}};for(let X of _.keys())if(!z.has(X))Y(X);return{components:Z}}function sJ(_,$,J){let Q=[],z=new Set,W=[..._].sort(lJ),Z=(Y,X,K)=>{X.delete(Y);let V=K.get(Y);if(!V)return;for(let H of V)if(X.has(H))Z(H,X,K);V.clear()};for(let Y=0;Y<W.length&&Q.length<J;Y++){let X=W[Y]??"",K=new Set(W.slice(Y)),V=new Set,H=new Map,I=[],N=(A)=>($.get(A)??[]).filter((k)=>K.has(k)),B=(A)=>{if(Q.length>=J)return!0;let k=!1;I.push(A),V.add(A);for(let F of N(A)){if(Q.length>=J)break;if(F===X)E$(z,Q,I.concat(X)),k=!0;else if(!V.has(F)){if(B(F))k=!0}}if(k)Z(A,V,H);else for(let F of N(A)){let y=H.get(F)??new Set;y.add(A),H.set(F,y)}return I.pop(),k};B(X)}return Q}function rJ(_,$){let{components:J}=aJ(_),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=sJ(W,_,Z);for(let X of Y){if(Q.length>=$)break;E$(z,Q,X)}}return Q}var oJ=15000;function J$(_){_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}function A_(_,$){let J=$??"__cross__";if(_.graphCache&&_.graphCacheBuiltAt!==null){if(Date.now()-_.graphCacheBuiltAt>oJ)_.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 _Q=30000,R0=15000,$Q=10;function JQ(_,$){_.boundaries=$,_.defaultProject=$[0]?.project??k_.basename(_.projectRoot)}function QQ(_,$){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 zQ(_){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)=>JQ(_,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(QQ(_,J)).then((z)=>{if(m_(z))throw z.data}),_.watcher=Q,_.timer=setInterval(()=>{_.updateHeartbeatFn(_.db,process.pid)},_Q)}await J.fullIndex(),await zQ(_)}function WQ(_,$){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=eJ,dbConnectionFactory:Y,watcherFactory:X,coordinatorFactory:K,repositoryFactory:V,acquireWatcherRoleFn:H=Y0,releaseWatcherRoleFn:I=Z0,updateHeartbeatFn:N=X0,discoverProjectsFn:B=i_,parseSourceFn:A=P_,extractSymbolsFn:k=R_,extractRelationsFn:F=s_,symbolSearchFn:y=N$,relationSearchFn:v=q$,patternSearchFn:h=u$,loadTsconfigPathsFn:a=b_,readFileFn:t=async(w)=>Bun.file(w).text(),unlinkFn:J_=async(w)=>{await Bun.file(w).unlink()},watchMode:z_,semantic:Y_,semanticLayerFactory:M}=_;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 q=Y?Y():new Z$({projectRoot:$}),D=q.open();if(m_(D))throw D.data;try{let w=await B($),u=w[0]?.project??k_.basename($),S=V?V():(()=>{let P=q;return{fileRepo:new X$(P),symbolRepo:new V$(P),relationRepo:new O$(P),parseCache:new A$(z)}})(),T=V?null:q,U=T?new G$(T):null,L=T?new j$(T):null,C=z_??!0,R=crypto.randomUUID(),b;if(C)b=await Promise.resolve(H(q,process.pid,{instanceId:R}));else b="owner";let g={projectRoot:$,extensions:J,ignorePatterns:Q,logger:W,defaultProject:u,role:b,db:q,symbolRepo:S.symbolRepo,relationRepo:S.relationRepo,fileRepo:S.fileRepo,parseCache:S.parseCache,annotationRepo:U,changelogRepo:L,annotationSearchFn:B0,releaseWatcherRoleFn:I,parseSourceFn:A,extractSymbolsFn:k,extractRelationsFn:F,symbolSearchFn:y,relationSearchFn:v,patternSearchFn:h,readFileFn:t,unlinkFn:J_,existsSyncFn:Z,acquireWatcherRoleFn:H,updateHeartbeatFn:N,watcherFactory:X,coordinatorFactory:K,instanceId:R,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:w,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(d_($),g.tsconfigPaths=await a($),Y_){let P=k_.join($,"tsconfig.json");try{if(M)g.semanticLayer=M(P);else{let j=_$.create(P);if(m_(j))throw j.data;g.semanticLayer=j}}catch(j){if(j instanceof O)throw j;throw new O("semantic","Gildash: semantic layer creation failed",{cause:j})}}if(b==="owner")await T0(g,{isWatchMode:C});else{let P=0,j=async()=>{try{let x=await Promise.resolve(g.acquireWatcherRoleFn(g.db,process.pid,{instanceId:g.instanceId}));if(P=0,x==="owner"){g.role="owner";for(let E of g.onRoleChangedCallbacks)try{E("owner")}catch(i){g.logger.error("[Gildash] onRoleChanged callback threw:",i)}clearInterval(g.timer),g.timer=null;try{await T0(g,{isWatchMode:!0})}catch(E){if(g.logger.error("[Gildash] owner promotion failed, reverting to reader",E),g.role="reader",g.timer!==null)clearInterval(g.timer),g.timer=null;if(g.watcher){let i=await g.watcher.close();if(m_(i))g.logger.error("[Gildash] watcher close error during promotion rollback",i.data);g.watcher=null}if(g.coordinator)await g.coordinator.shutdown().catch((i)=>g.logger.error("[Gildash] coordinator shutdown error during promotion rollback",i)),g.coordinator=null;try{g.releaseWatcherRoleFn(g.db,process.pid)}catch(i){g.logger.error("[Gildash] failed to release watcher role during promotion rollback",i)}g.timer=setInterval(j,R0)}}}catch(x){P++;let E=x instanceof O?x:new O("watcher","Gildash: healthcheck error",{cause:x});for(let i of g.onErrorCallbacks)try{i(E)}catch(M_){g.logger.error("[Gildash] onError callback threw:",M_)}if(g.logger.error("[Gildash] healthcheck error",x),P>=$Q)g.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(g.timer),g.timer=null,Q$(g).catch((i)=>g.logger.error("[Gildash] close error during healthcheck shutdown",i))}};g.timer=setInterval(j,R0)}if(C)WQ(g,()=>Q$(g));return g}catch(w){if(q.close(),w instanceof O)throw w;throw new O("store","Gildash: initialization failed",{cause:w})}}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 P0 from"path";function f0(_,$){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 K=P0.isAbsolute(J)?J:P0.resolve(_.projectRoot,J),V=_.semanticLayer.lineColumnToPosition(K,Z.span.start.line,Z.span.start.column);if(V!==null){let H=_.semanticLayer.findNamePosition(K,V,Z.name)??V,I=_.semanticLayer.collectTypeAt(K,H);if(I)X.resolvedType=I}}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 m from"path";function n_(_,$,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),K=_.semanticLayer.lineColumnToPosition(X,Y.span.start.line,Y.span.start.column);if(K===null)return null;let V=_.semanticLayer.findNamePosition(X,K,Y.name)??K;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=m.isAbsolute($)?$:m.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=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 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=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 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=m.isAbsolute($)?$:m.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=m.isAbsolute($)?$:m.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=m.isAbsolute($)?$:m.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=m.isAbsolute($)?$:m.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=m.isAbsolute($)?$:m.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=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 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=m.isAbsolute($)?$:m.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=m.isAbsolute($)?$:m.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=m.isAbsolute($)?$:m.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=m.isAbsolute($)?$:m.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=m.isAbsolute($)?$:m.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 K1(_,$,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=m.isAbsolute($)?$:m.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 M1(_,$){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 K=J.get(Y);if(!K)z.push(X);else if(K.fingerprint!==X.fingerprint)Z.push({before:K,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 K=`${X}::${Y}`;if(W.has(K))return{originalName:Y,originalFilePath:X,reExportChain:Z,circular:!0};W.add(K);let V=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{type:"re-exports",srcFilePath:X,limit:500}}),H,I;for(let N of V){let B;if(N.metaJson)try{let k=JSON.parse(N.metaJson);if(Array.isArray(k.specifiers))B=k.specifiers}catch{}if(!B)continue;let A=B.find((k)=>k.exported===Y);if(!A)continue;H=N.dstFilePath??void 0,I=A.local;break}if(!H||!I)return{originalName:Y,originalFilePath:X,reExportChain:Z,circular:!1};Z.push({filePath:X,exportedAs:Y}),X=H,Y=I}}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,K)=>{let V=`${Y}::${X}`;if(W.has(V))return{symbolName:Y,filePath:X,kind:K,children:[]};W.add(V);let N=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{srcFilePath:X,srcSymbolName:Y,limit:1000}}).filter((B)=>B.type==="extends"||B.type==="implements").filter((B)=>B.dstSymbolName!=null&&B.dstFilePath!=null).map((B)=>Z(B.dstSymbolName,B.dstFilePath,B.type));return{symbolName:Y,filePath:X,kind:K,children:N}};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 f0(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 K1(this._ctx,_,$)}diffSymbols(_,$){return M1(_,$)}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 Z3,visitorKeys as X3}from"oxc-parser";export{X3 as visitorKeys,N$ as symbolSearch,q$ as relationSearch,u$ as patternSearch,W_ as normalizePath,X_ as getLineColumn,f_ as buildLineOffsets,Z3 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,78 @@
|
|
|
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
|
+
/** Import specifier if this identifier is imported (e.g. `'./my.service'`, `'@zipbul/http-adapter'`). */
|
|
20
|
+
importSource?: string;
|
|
21
|
+
/** Original exported name when imported under an alias (e.g. `import { Foo as Bar }` → `'Foo'`). */
|
|
22
|
+
originalName?: string;
|
|
23
|
+
}
|
|
24
|
+
export interface ExpressionMember {
|
|
25
|
+
kind: 'member';
|
|
26
|
+
/** Full dot-separated expression text, e.g. `'HttpMethod.Get'`. */
|
|
27
|
+
object: string;
|
|
28
|
+
property: string;
|
|
29
|
+
/** Import specifier of the object identifier. */
|
|
30
|
+
importSource?: string;
|
|
31
|
+
}
|
|
32
|
+
export interface ExpressionCall {
|
|
33
|
+
kind: 'call';
|
|
34
|
+
callee: string;
|
|
35
|
+
/** Import specifier of the callee (simple identifier or leftmost member object). */
|
|
36
|
+
importSource?: string;
|
|
37
|
+
arguments: ExpressionValue[];
|
|
38
|
+
}
|
|
39
|
+
export interface ExpressionNew {
|
|
40
|
+
kind: 'new';
|
|
41
|
+
callee: string;
|
|
42
|
+
/** Import specifier of the callee (simple identifier or leftmost member object). */
|
|
43
|
+
importSource?: string;
|
|
44
|
+
arguments: ExpressionValue[];
|
|
45
|
+
}
|
|
46
|
+
export interface ExpressionObject {
|
|
47
|
+
kind: 'object';
|
|
48
|
+
properties: ExpressionObjectProperty[];
|
|
49
|
+
}
|
|
50
|
+
export interface ExpressionObjectProperty {
|
|
51
|
+
key: string;
|
|
52
|
+
value: ExpressionValue;
|
|
53
|
+
computed?: boolean;
|
|
54
|
+
shorthand?: boolean;
|
|
55
|
+
}
|
|
56
|
+
export interface ExpressionArray {
|
|
57
|
+
kind: 'array';
|
|
58
|
+
elements: ExpressionValue[];
|
|
59
|
+
}
|
|
60
|
+
export interface ExpressionSpread {
|
|
61
|
+
kind: 'spread';
|
|
62
|
+
argument: ExpressionValue;
|
|
63
|
+
}
|
|
64
|
+
export interface ExpressionFunction {
|
|
65
|
+
kind: 'function';
|
|
66
|
+
sourceText: string;
|
|
67
|
+
}
|
|
68
|
+
export interface ExpressionTemplate {
|
|
69
|
+
kind: 'template';
|
|
70
|
+
sourceText: string;
|
|
71
|
+
}
|
|
72
|
+
export interface ExpressionUnresolvable {
|
|
73
|
+
kind: 'unresolvable';
|
|
74
|
+
sourceText: string;
|
|
75
|
+
}
|
|
2
76
|
/**
|
|
3
77
|
* The kind of a symbol extracted from TypeScript source.
|
|
4
78
|
*
|
|
@@ -49,8 +123,8 @@ export interface Heritage {
|
|
|
49
123
|
export interface Decorator {
|
|
50
124
|
/** Decorator name without `@`. */
|
|
51
125
|
name: string;
|
|
52
|
-
/**
|
|
53
|
-
arguments?:
|
|
126
|
+
/** Structured decorator call arguments. */
|
|
127
|
+
arguments?: ExpressionValue[];
|
|
54
128
|
}
|
|
55
129
|
/**
|
|
56
130
|
* A single JSDoc tag parsed from a documentation comment.
|
|
@@ -113,6 +187,8 @@ export interface ExtractedSymbol {
|
|
|
113
187
|
heritage?: Heritage[];
|
|
114
188
|
/** Decorators applied to this symbol. */
|
|
115
189
|
decorators?: Decorator[];
|
|
190
|
+
/** Initializer expression (enum member values, property defaults, variable initializers). */
|
|
191
|
+
initializer?: ExpressionValue;
|
|
116
192
|
/** Nested members (class fields, methods, interface properties, enum members). */
|
|
117
193
|
members?: ExtractedSymbol[];
|
|
118
194
|
/** 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;
|