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