@zipbul/gildash 0.31.0 → 0.33.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/README.md +11 -0
- package/dist/index.js +9 -9
- package/dist/src/gildash/context.d.ts +1 -1
- package/dist/src/gildash/index.d.ts +57 -1
- package/dist/src/gildash/semantic-api.d.ts +15 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/semantic/ast-node-utils.d.ts +15 -0
- package/dist/src/semantic/index.d.ts +15 -1
- package/dist/src/semantic/reference-resolver.d.ts +11 -0
- package/dist/src/semantic/standalone-bindings.d.ts +36 -0
- package/dist/src/semantic/tsc-program.d.ts +5 -0
- package/dist/src/semantic/type-collector.d.ts +39 -1
- package/dist/src/semantic/types.d.ts +15 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -355,12 +355,23 @@ Requires `semantic: true` at open time.
|
|
|
355
355
|
| `getEnrichedReferencesAtPosition(filePath, position)` | `EnrichedReference[]` | Enriched references to the symbol at a position |
|
|
356
356
|
| `getFileBindings(filePath)` | `FileBinding[]` | All bindings in a file (single pass), each with its in-file enriched references — `O(identifiers)` for dataflow |
|
|
357
357
|
| `getFileBindingsBatch(files)` | `Map<string, FileBinding[]>` | Batch `getFileBindings` over many in-memory `{ filePath, content }` — one tsc rebuild for the whole batch |
|
|
358
|
+
| `getStandaloneFileBindings(filePath, content)` | `FileBinding[]` | Isolated `O(file)` bindings for a self-contained source — never touches the shared program (no cross-file/global resolution) |
|
|
358
359
|
| `notifyFileChanged(filePath, content)` | `void` | Register/replace an ad-hoc in-memory source (idempotent on identical content) |
|
|
359
360
|
| `notifyFileDeleted(filePath)` | `void` | Remove an ad-hoc in-memory source |
|
|
360
361
|
| `getImplementationsAtPosition(filePath, position)` | `Implementation[]` | Implementations of the symbol at a position |
|
|
361
362
|
| `isTypeAssignableToAtPosition(opts)` | `boolean` | Assignability check between two byte positions |
|
|
362
363
|
| `isTypeAssignableToTypeAtPositions(opts)` | `boolean` | Assignability check from a position to an arbitrary type string |
|
|
363
364
|
|
|
365
|
+
#### By byte span (expression-level)
|
|
366
|
+
|
|
367
|
+
Resolve a type fact for the **expression node exactly spanning** a byte range. `ByteSpan` is `{ start: number; end: number }` (0-based, half-open) and aligns 1:1 with `oxc-parser` node offsets. Each matches the node whose `[getStart(), getEnd())` equals the span exactly, else returns `null` — no nearest-node fallback.
|
|
368
|
+
|
|
369
|
+
| Method | Returns | Description |
|
|
370
|
+
|--------|---------|-------------|
|
|
371
|
+
| `getExpressionTypeAtSpan(filePath, span)` | `ResolvedType \| null` | Type of the spanned expression — a call `f()` → result type, `obj.m()` → method return, `obj.prop` → property type (any expression, unlike the identifier-only position lookups) |
|
|
372
|
+
| `isThenableAtSpan(filePath, span, opts?)` | `boolean \| null` | Whether the spanned expression's type is a thenable (callable `then` with ≥1 param); recurses union/intersection, excludes `any`. `opts.anyConstituent` (default `true`): a union is thenable if **some** member is |
|
|
373
|
+
| `getContextualCallReturnsAtSpan(filePath, span)` | `ResolvedType[] \| null` | Return types of the contextual type's call signatures at an argument span (overload-selected, `undefined`/`null` stripped). `[]` = not a callable slot; `null` = no contextual type |
|
|
374
|
+
|
|
364
375
|
#### File-level / utilities / diagnostics
|
|
365
376
|
|
|
366
377
|
| Method | Returns | Description |
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var n$=Object.defineProperty;var p$=(_)=>_;function d$(_,$){this[_]=p$.bind(null,$)}var l$=(_,$)=>{for(var J in $)n$(_,J,{get:$[J],enumerable:!0,configurable:!0,set:d$.bind($,J)})};var d0=import.meta.require;import{isErr as c_}from"@zipbul/result";import P_ from"path";import{existsSync as EQ}from"fs";import{err as l0,isErr as o$}from"@zipbul/result";import{Database as t$}from"bun:sqlite";import{mkdirSync as e$,unlinkSync as i0,existsSync as c0}from"fs";import{dirname as _J,join as a0}from"path";import{drizzle as $J}from"drizzle-orm/bun-sqlite";import{migrate as JJ}from"drizzle-orm/bun-sqlite/migrator";class V extends Error{type;constructor(_,$,J){super($,J);this.type=_;this.name="GildashError"}}var A_=".gildash",a_="gildash.db";var O0={};l$(O0,{watcherOwner:()=>r$,symbols:()=>x,symbolChangelog:()=>$_,relations:()=>v,files:()=>o,annotations:()=>Z_});import{sql as i$}from"drizzle-orm";import{sqliteTable as j_,text as f,integer as r,real as c$,index as Q_,primaryKey as a$,foreignKey as V0,check as s$}from"drizzle-orm/sqlite-core";var o=j_("files",{project:f("project").notNull(),filePath:f("file_path").notNull(),mtimeMs:c$("mtime_ms").notNull(),size:r("size").notNull(),contentHash:f("content_hash").notNull(),updatedAt:f("updated_at").notNull(),lineCount:r("line_count")},(_)=>[a$({columns:[_.project,_.filePath]})]),x=j_("symbols",{id:r("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),filePath:f("file_path").notNull(),kind:f("kind").notNull(),name:f("name").notNull(),startLine:r("start_line").notNull(),startColumn:r("start_column").notNull(),endLine:r("end_line").notNull(),endColumn:r("end_column").notNull(),isExported:r("is_exported").notNull().default(0),signature:f("signature"),fingerprint:f("fingerprint"),detailJson:f("detail_json"),contentHash:f("content_hash").notNull(),indexedAt:f("indexed_at").notNull(),resolvedType:f("resolved_type"),structuralFingerprint:f("structural_fingerprint")},(_)=>[Q_("idx_symbols_project_file").on(_.project,_.filePath),Q_("idx_symbols_project_kind").on(_.project,_.kind),Q_("idx_symbols_project_name").on(_.project,_.name),Q_("idx_symbols_fingerprint").on(_.project,_.fingerprint),V0({columns:[_.project,_.filePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),v=j_("relations",{id:r("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),type:f("type").notNull(),srcFilePath:f("src_file_path").notNull(),srcSymbolName:f("src_symbol_name"),dstProject:f("dst_project"),dstFilePath:f("dst_file_path"),dstSymbolName:f("dst_symbol_name"),metaJson:f("meta_json"),specifier:f("specifier"),isExternal:r("is_external").notNull().default(0)},(_)=>[Q_("idx_relations_src").on(_.project,_.srcFilePath),Q_("idx_relations_dst").on(_.dstProject,_.dstFilePath),Q_("idx_relations_type").on(_.project,_.type),Q_("idx_relations_project_type_src").on(_.project,_.type,_.srcFilePath),Q_("idx_relations_specifier").on(_.project,_.specifier),V0({columns:[_.project,_.srcFilePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),Z_=j_("annotations",{id:r("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),filePath:f("file_path").notNull(),tag:f("tag").notNull(),value:f("value").notNull().default(""),source:f("source").notNull(),symbolName:f("symbol_name"),startLine:r("start_line").notNull(),startColumn:r("start_column").notNull(),endLine:r("end_line").notNull(),endColumn:r("end_column").notNull(),indexedAt:f("indexed_at").notNull()},(_)=>[Q_("idx_annotations_project_file").on(_.project,_.filePath),Q_("idx_annotations_project_tag").on(_.project,_.tag),Q_("idx_annotations_project_symbol").on(_.project,_.symbolName),V0({columns:[_.project,_.filePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),$_=j_("symbol_changelog",{id:r("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),changeType:f("change_type").notNull(),symbolName:f("symbol_name").notNull(),symbolKind:f("symbol_kind").notNull(),filePath:f("file_path").notNull(),oldName:f("old_name"),oldFilePath:f("old_file_path"),fingerprint:f("fingerprint"),changedAt:f("changed_at").notNull(),isFullIndex:r("is_full_index").notNull().default(0),indexRunId:f("index_run_id").notNull()},(_)=>[Q_("idx_changelog_project_changed_at").on(_.project,_.changedAt),Q_("idx_changelog_project_name").on(_.project,_.symbolName),Q_("idx_changelog_project_run").on(_.project,_.indexRunId)]),r$=j_("watcher_owner",{id:r("id").primaryKey(),pid:r("pid").notNull(),startedAt:f("started_at").notNull(),heartbeatAt:f("heartbeat_at").notNull(),instanceId:f("instance_id")},(_)=>[s$("watcher_owner_singleton",i$`${_.id} = 1`)]);class H0{client=null;drizzle=null;dbPath;txDepth=0;constructor(_){this.dbPath=a0(_.projectRoot,A_,a_)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{e$(_J(this.dbPath),{recursive:!0}),this.client=new t$(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=$J(this.client,{schema:O0}),JJ(this.drizzle,{migrationsFolder:a0(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(_)&&c0(this.dbPath)){this.closeClient(),i0(this.dbPath);for(let J of["-wal","-shm"]){let Q=this.dbPath+J;if(c0(Q))i0(Q)}let $=this.open();if(o$($))return l0(new V("store",`Failed to recover database at ${this.dbPath}`,{cause:$.data}));return $}return l0(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 y_,and as s0}from"drizzle-orm";class K0{db;constructor(_){this.db=_}getFile(_,$){return this.db.drizzleDb.select().from(o).where(s0(y_(o.project,_),y_(o.filePath,$))).get()??null}upsertFile(_){this.db.drizzleDb.insert(o).values({project:_.project,filePath:_.filePath,mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}).onConflictDoUpdate({target:[o.project,o.filePath],set:{mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}}).run()}getAllFiles(_){return this.db.drizzleDb.select().from(o).where(y_(o.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(o).where(s0(y_(o.project,_),y_(o.filePath,$))).run()}}import{eq as t,and as N_,sql as s_,count as QJ}from"drizzle-orm";function k_(_){return _.replaceAll("\x00","").trim().split(/\s+/).map(($)=>$.trim()).filter(($)=>$.length>0).map(($)=>`"${$.replaceAll('"','""')}"*`).join(" ")}var r0=50;class M0{db;constructor(_){this.db=_}replaceFileSymbols(_,$,J,Q){if(this.db.drizzleDb.delete(x).where(N_(t(x.project,_),t(x.filePath,$))).run(),!Q.length)return;let z=new Date().toISOString(),W=Q.map((Z)=>({project:_,filePath:$,kind:Z.kind??"unknown",name:Z.name??"",startLine:Z.startLine??0,startColumn:Z.startColumn??0,endLine:Z.endLine??0,endColumn:Z.endColumn??0,isExported:Z.isExported??0,signature:Z.signature??null,fingerprint:Z.fingerprint??null,detailJson:Z.detailJson??null,contentHash:J,indexedAt:Z.indexedAt??z,resolvedType:Z.resolvedType??null,structuralFingerprint:Z.structuralFingerprint??null}));for(let Z=0;Z<W.length;Z+=r0)this.db.drizzleDb.insert(x).values(W.slice(Z,Z+r0)).run()}getFileSymbols(_,$){return this.db.drizzleDb.select().from(x).where(N_(t(x.project,_),t(x.filePath,$))).all()}searchByName(_,$,J={}){let Q=J.limit??50,z=k_($);if(!z)return[];return this.db.drizzleDb.select().from(x).where(N_(s_`${x.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${z})`,t(x.project,_),J.kind?t(x.kind,J.kind):void 0)).orderBy(x.name).limit(Q).all()}searchByKind(_,$){return this.db.drizzleDb.select().from(x).where(N_(t(x.project,_),t(x.kind,$))).orderBy(x.name).all()}getStats(_){let $=this.db.drizzleDb.select({symbolCount:QJ(),fileCount:s_`COUNT(DISTINCT ${x.filePath})`}).from(x).where(t(x.project,_)).get();return{symbolCount:$?.symbolCount??0,fileCount:$?.fileCount??0}}getByFingerprint(_,$){return this.db.drizzleDb.select().from(x).where(N_(t(x.project,_),t(x.fingerprint,$))).all()}deleteFileSymbols(_,$){this.db.drizzleDb.delete(x).where(N_(t(x.project,_),t(x.filePath,$))).run()}searchByQuery(_){let $=this.db.drizzleDb.select().from(x).where(N_(_.ftsQuery?s_`${x.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${_.ftsQuery})`:void 0,_.exactName?t(x.name,_.exactName):void 0,_.project!==void 0?t(x.project,_.project):void 0,_.kind?t(x.kind,_.kind):void 0,_.filePath!==void 0?t(x.filePath,_.filePath):void 0,_.isExported!==void 0?t(x.isExported,_.isExported?1:0):void 0,_.decorator?s_`${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?t(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((W)=>J.test(W.name));let Q=[];for(let z of[5,20,100]){let W=_.limit*z,Z=$.limit(W).all();if(Q=Z.filter((Y)=>J.test(Y.name)),Q.length>=_.limit||Z.length<W)return Q.slice(0,_.limit)}return Q.slice(0,_.limit)}}import{eq as m,and as M_,isNull as o0,or as zJ}from"drizzle-orm";var x_={project:v.project,type:v.type,srcFilePath:v.srcFilePath,srcSymbolName:v.srcSymbolName,dstProject:v.dstProject,dstFilePath:v.dstFilePath,dstSymbolName:v.dstSymbolName,metaJson:v.metaJson,specifier:v.specifier,isExternal:v.isExternal};class L0{db;constructor(_){this.db=_}replaceFileRelations(_,$,J){this.db.transaction((Q)=>{if(Q.drizzleDb.delete(v).where(M_(m(v.project,_),m(v.srcFilePath,$))).run(),!J.length)return;for(let z of J)Q.drizzleDb.insert(v).values({project:_,type:z.type??"unknown",srcFilePath:z.srcFilePath??$,srcSymbolName:z.srcSymbolName??null,dstProject:z.dstProject??(z.dstFilePath!=null?_:null),dstFilePath:z.dstFilePath??null,dstSymbolName:z.dstSymbolName??null,metaJson:z.metaJson??null,specifier:z.specifier??null,isExternal:z.isExternal??0}).run()})}getOutgoing(_,$,J){if(J!==void 0)return this.db.drizzleDb.select(x_).from(v).where(M_(m(v.project,_),m(v.srcFilePath,$),zJ(m(v.srcSymbolName,J),o0(v.srcSymbolName)))).all();return this.db.drizzleDb.select(x_).from(v).where(M_(m(v.project,_),m(v.srcFilePath,$))).all()}getIncoming(_){let{dstProject:$,dstFilePath:J}=_;return this.db.drizzleDb.select(x_).from(v).where(M_(m(v.dstProject,$),m(v.dstFilePath,J))).all()}getByType(_,$){return this.db.drizzleDb.select(x_).from(v).where(M_(m(v.project,_),m(v.type,$))).all()}deleteFileRelations(_,$){this.db.drizzleDb.delete(v).where(M_(m(v.project,_),m(v.srcFilePath,$))).run()}deleteIncomingRelations(_,$){this.db.drizzleDb.delete(v).where(M_(m(v.dstProject,_),m(v.dstFilePath,$))).run()}searchRelations(_){let $=this.db.drizzleDb.select(x_).from(v).where(M_(_.project!==void 0?m(v.project,_.project):void 0,_.srcFilePath!==void 0?m(v.srcFilePath,_.srcFilePath):void 0,_.srcSymbolName!==void 0?m(v.srcSymbolName,_.srcSymbolName):void 0,_.dstProject!==void 0?m(v.dstProject,_.dstProject):void 0,_.dstFilePath!==void 0?m(v.dstFilePath,_.dstFilePath):void 0,_.dstSymbolName!==void 0?m(v.dstSymbolName,_.dstSymbolName):void 0,_.type!==void 0?m(v.type,_.type):void 0,_.specifier!==void 0?m(v.specifier,_.specifier):void 0,_.isExternal!==void 0?m(v.isExternal,_.isExternal?1:0):void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}retargetRelations(_){let{dstProject:$,oldFile:J,oldSymbol:Q,newFile:z,newSymbol:W,newDstProject:Z}=_,Y=Q===null?M_(m(v.dstProject,$),m(v.dstFilePath,J),o0(v.dstSymbolName)):M_(m(v.dstProject,$),m(v.dstFilePath,J),m(v.dstSymbolName,Q)),X={dstFilePath:z,dstSymbolName:W};if(Z!==void 0)X.dstProject=Z;this.db.drizzleDb.update(v).set(X).where(Y).run()}}import{err as e0}from"@zipbul/result";import{subscribe as WJ}from"@parcel/watcher";import B0 from"path";import t0 from"path";function z_(_){return _.replaceAll("\\","/")}function h_(_,$){return z_(t0.relative(_,$))}function g_(_,$){return z_(t0.resolve(_,$))}var YJ=["**/.git/**",`**/${A_}/**`,"**/dist/**","**/node_modules/**"],ZJ=new Set(["package.json","tsconfig.json"]);function XJ(_){if(_==="update")return"change";if(_==="create")return"create";return"delete"}class w0{#_;#$;#J;#z;#W;#Y;constructor(_,$=WJ,J=console){this.#$=_.projectRoot,this.#J=[...YJ,..._.ignorePatterns??[]],this.#z=new Set((_.extensions??[".ts",".mts",".cts"]).map((Q)=>Q.toLowerCase())),this.#W=$,this.#Y=J}async start(_){try{this.#_=await this.#W(this.#$,($,J)=>{if($){this.#Y.error(new V("watcher","Callback error",{cause:$}));return}try{for(let Q of J){let z=z_(B0.relative(this.#$,Q.path));if(z.startsWith(".."))continue;let W=B0.basename(z),Z=B0.extname(z).toLowerCase();if(!ZJ.has(W)&&!this.#z.has(Z))continue;if(z.endsWith(".d.ts"))continue;_({eventType:XJ(Q.type),filePath:z})}}catch(Q){this.#Y.error(new V("watcher","Callback error",{cause:Q}))}},{ignore:this.#J})}catch($){return e0(new V("watcher","Failed to subscribe watcher",{cause:$}))}}async close(){if(!this.#_)return;try{await this.#_.unsubscribe(),this.#_=void 0}catch(_){return e0(new V("watcher","Failed to close watcher",{cause:_}))}}}import I0 from"path";var UJ=["**/node_modules/**","**/.git/**",`**/${A_}/**`,"**/dist/**"],VJ=UJ.map((_)=>new Bun.Glob(_));function OJ(_){return new Bun.Glob("**/package.json").scan({cwd:_,followSymlinks:!1})}async function r_(_,$=OJ){let J=[];for await(let Q of $(_)){let z=z_(Q);if(VJ.some((M)=>M.match(z)))continue;let W=z_(I0.dirname(Q)),Z=I0.join(_,Q),Y=await Bun.file(Z).json(),X=typeof Y?.name==="string"&&Y.name.length>0?Y.name:I0.basename(W==="."?_:W);J.push({dir:W,project:X})}return J.sort((Q,z)=>z.dir.length-Q.dir.length),J}function a(_,$,J="default"){let Q=z_(_);for(let z of $){if(z.dir===".")return z.project;if(Q===z.dir||Q.startsWith(`${z.dir}/`))return z.project}return J}import m_ from"path";var q_=new Map;async function HJ(_){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 KJ(_,$){if($.startsWith(".")){let J=m_.resolve(_,$);return J.endsWith(".json")?J:J+".json"}return m_.resolve(_,"node_modules",$)}async function _1(_,$=5){if($<=0)return null;let J=await HJ(_);if(!J)return null;let Q=J.extends;if(typeof Q!=="string"||!Q)return J;let z=KJ(m_.dirname(_),Q),W=await _1(z,$-1);if(!W)return J;let Z=typeof W.compilerOptions==="object"&&W.compilerOptions!==null?W.compilerOptions:{},Y=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:{};return{...W,...J,compilerOptions:{...Z,...Y}}}async function n_(_){if(q_.has(_))return q_.get(_)??null;let $=m_.join(_,"tsconfig.json"),J=await _1($);if(!J)return q_.set(_,null),null;let Q=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:null;if(!Q)return q_.set(_,null),null;let z=typeof Q.baseUrl==="string"?Q.baseUrl:null,W=typeof Q.paths==="object"&&Q.paths!==null?Q.paths:null;if(!z&&!W)return q_.set(_,null),null;let Z=z?m_.resolve(_,z):_,Y=new Map;if(W)for(let[M,O]of Object.entries(W)){if(!Array.isArray(O))continue;let L=O.filter((D)=>typeof D==="string");Y.set(M,L)}let X={baseUrl:Z,paths:Y};return q_.set(_,X),X}function o_(_){if(_){q_.delete(_);return}q_.clear()}function H_(_){let $=Bun.hash.xxHash64(_);return BigInt.asUintN(64,BigInt($)).toString(16).padStart(16,"0")}import{isErr as O1}from"@zipbul/result";import{err as MJ}from"@zipbul/result";import{parseSync as LJ}from"oxc-parser";function E_(_,$,J,Q=LJ){try{let z={preserveParens:!1,...J},W=Q(_,$,z);return{filePath:_,program:W.program,errors:W.errors,comments:W.comments,sourceText:$,module:W.module}}catch(z){return MJ(new V("parse",`Failed to parse file: ${_}`,{cause:z}))}}import{join as BJ}from"path";function wJ(_,$){let J=$.length===1?`**/*${$[0]}`:`**/*{${$.join(",")}}`;return new Bun.Glob(J).scan({cwd:_,followSymlinks:!1})}async function $1(_){let{projectRoot:$,extensions:J,ignorePatterns:Q,fileRepo:z,scanFilesFn:W=wJ}=_,Z=z.getFilesMap(),Y=new Set,X=[],M=[],O=Q.map((D)=>new Bun.Glob(D));for await(let D of W($,J)){let N=z_(D);if(!J.some((l)=>N.endsWith(l)))continue;if(N.startsWith("node_modules/")||N.includes("/node_modules/"))continue;if(O.some((l)=>l.match(N)))continue;Y.add(N);let w=BJ($,N),R=Bun.file(w),{size:G,lastModified:F}=R,u=Z.get(N);if(!u){let l=await R.text(),i=H_(l);X.push({filePath:N,contentHash:i,mtimeMs:F,size:G});continue}if(u.mtimeMs===F&&u.size===G){M.push({filePath:N,contentHash:u.contentHash,mtimeMs:F,size:G});continue}let E=await R.text(),y=H_(E);if(y===u.contentHash)M.push({filePath:N,contentHash:y,mtimeMs:F,size:G});else X.push({filePath:N,contentHash:y,mtimeMs:F,size:G})}let L=[];for(let D of Z.keys())if(!Y.has(D))L.push(D);return{changed:X,unchanged:M,deleted:L}}function p_(_){let $=[0];for(let J=0;J<_.length;J++)if(_[J]===`
|
|
3
|
-
`)$.push(J+1);return $}function O_(_,$){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 IJ}from"@zipbul/result";import{parse as CJ}from"comment-parser";function t_(_){try{let $=_.trim();if($.startsWith("/**"))$=$.slice(3);if($.endsWith("*/"))$=$.slice(0,-2);let Q=CJ(`/** ${$} */`)[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 IJ(new V("parse","Failed to parse JSDoc comment",{cause:$}))}}import{isErr as DJ}from"@zipbul/result";function AJ(_){if("name"in _&&typeof _.name==="string")return _.name;if("value"in _){let $=_.value;if(typeof $==="string")return $;if(typeof $==="number"||typeof $==="bigint"||typeof $==="boolean")return String($)}return"unknown"}function v_(_){if(_.type==="Identifier")return[{name:_.name,start:_.start,end:_.end}];if(_.type==="ObjectPattern"){let $=[];for(let J of _.properties)if(J.type==="RestElement")$.push(...v_(J.argument));else $.push(...v_(J.value));return $}if(_.type==="ArrayPattern"){let $=[];for(let J of _.elements){if(!J)continue;if(J.type==="RestElement")$.push(...v_(J.argument));else $.push(...v_(J))}return $}if(_.type==="AssignmentPattern")return v_(_.left);return[]}function qJ(_){let $=new Map;for(let J of _.module.staticImports){let Q=J.moduleRequest.value;for(let z of J.entries){let W=z.localName.value,Z=z.importName.kind==="Name"?z.importName.name:void 0,Y={specifier:Q};if(Z&&Z!==W)Y.originalName=Z;$.set(W,Y)}}return $}function R_(_){let{program:$,sourceText:J,comments:Q}=_,z=p_(J),W=qJ(_),Z=Q.filter((C)=>C.type==="Block"&&C.value.startsWith("*")).sort((C,q)=>C.end-q.end),Y=$.body.map((C)=>C.start).sort((C,q)=>C-q);function X(C,q){return F(C,q)}function M(C,q,U){if(C.type==="PrivateIdentifier")return{kind:"private"};if(!q&&C.type==="Identifier")return;return X(C,U)}function O(C,q){if(q)return J.slice(C.start,C.end);if(C.type==="PrivateIdentifier")return`#${C.name}`;return AJ(C)}function L(C,q,U){let H=C;if(!q&&H.type==="Identifier")return{kind:"string",value:H.name};return X(C,U)}function D(C,q){return{start:O_(z,C),end:O_(z,q)}}function N(C){let q=0,U=Z.length-1,H=-1;while(q<=U){let B=q+U>>>1;if(Z[B].end<=C)H=B,q=B+1;else U=B-1}if(H<0)return;let K=Z[H];q=0,U=Y.length-1;while(q<=U){let B=q+U>>>1,A=Y[B];if(A<=K.end)q=B+1;else if(A>=C)U=B-1;else return}return`/*${K.value}*/`}function w(C){if(!C)return;let q="typeAnnotation"in C&&C.typeAnnotation?C.typeAnnotation:C;return J.slice(q.start,q.end)}let R=8;function G(C){if(C.type==="Identifier")return W.get(C.name);if(C.type==="MemberExpression"){let q=C.object;if(q.type==="Identifier")return W.get(q.name)}return}function F(C,q=0){let U=C;if(q>=R)return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)};let H=U.type;if(H==="Literal"){let K=U.value;if(typeof K==="bigint")return{kind:"bigint",value:typeof U.bigint==="string"?U.bigint:K.toString()};if(typeof U.regex==="object"&&U.regex!==null)return{kind:"regex",value:J.slice(U.start,U.end)};if(K===null)return{kind:"null",value:null};if(typeof K==="string")return{kind:"string",value:K};if(typeof K==="number")return{kind:"number",value:K};if(typeof K==="boolean")return{kind:"boolean",value:K};return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}if(H==="Identifier"){let K=U.name;if(K==="undefined")return{kind:"undefined",value:null};let B=W.get(K),A={kind:"identifier",name:K};if(B){if(A.importSource=B.specifier,B.originalName)A.originalName=B.originalName}return A}if(H==="MemberExpression"){if(U.computed){let j=U.property;if(j.type==="Literal"&&typeof j.value==="string"){let g=U.object,b=J.slice(g.start,g.end),d=g.type==="Identifier"?g.name:void 0,J_=d?W.get(d):void 0,V_={kind:"member",object:b,property:j.value};if(J_)V_.importSource=J_.specifier;return V_}return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}let K=U.object,B=J.slice(K.start,K.end),A=U.property.name??J.slice(U.property.start,U.property.end),I=K.type==="Identifier"?K.name:void 0,S=I?W.get(I):void 0,T={kind:"member",object:B,property:A};if(S)T.importSource=S.specifier;return T}if(H==="CallExpression"){let K=U.callee,B=J.slice(K.start,K.end),I=(U.arguments??[]).map((j)=>F(j,q+1)),S=G(K),T={kind:"call",callee:B,arguments:I};if(S)T.importSource=S.specifier;return T}if(H==="NewExpression"){let K=U.callee,B=J.slice(K.start,K.end),I=(U.arguments??[]).map((j)=>F(j,q+1)),S=G(K),T={kind:"new",callee:B,arguments:I};if(S)T.importSource=S.specifier;return T}if(H==="ObjectExpression"){let K=U.properties??[],B=[];for(let A of K){if(A.type==="SpreadElement"){let d=A.argument;B.push({kind:"spread",argument:F(d,q+1)});continue}let I=A.key,S=A.computed===!0,T=A.value,j=A.shorthand||void 0,b={kind:"property",key:L(I,S,q+1),value:F(T,q+1)};if(j)b.shorthand=!0;B.push(b)}return{kind:"object",properties:B}}if(H==="ArrayExpression")return{kind:"array",elements:(U.elements??[]).map((A)=>{if(!A)return{kind:"undefined",value:null};return F(A,q+1)})};if(H==="SpreadElement"){let K=U.argument;return{kind:"spread",argument:F(K,q+1)}}if(H==="ArrowFunctionExpression"||H==="FunctionExpression"){let B=U.params.map(E),A={kind:"function",sourceText:J.slice(U.start,U.end)};if(B.length>0)A.parameters=B;return A}if(H==="TemplateLiteral"||H==="TaggedTemplateExpression")return{kind:"template",sourceText:J.slice(U.start,U.end)};if(H==="UnaryExpression"){let{operator:K,argument:B}=U;if(K==="-"&&B.type==="Literal"&&typeof B.value==="number")return{kind:"number",value:-B.value};if(K==="void")return{kind:"undefined",value:null};return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}if(H==="TSAsExpression"||H==="TSSatisfiesExpression"||H==="TSNonNullExpression"||H==="TSTypeAssertion"||H==="TSInstantiationExpression"||H==="ParenthesizedExpression"||H==="ChainExpression"){let K=U.expression;if(K)return F(K,q)}return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}function u(C){if(!C||C.length===0)return[];return C.map((q)=>{let U=q.expression;if(U.type==="CallExpression"){let H=U,K=H.callee,B="name"in K&&typeof K.name==="string"?K.name:("property"in K)&&K.property&&typeof K.property.name==="string"?K.property.name:"unknown",A=H.arguments.map((I)=>F(I));return{name:B,arguments:A.length>0?A:void 0}}if(U.type==="Identifier")return{name:U.name??"unknown"};return{name:J.slice(U.start,U.end)}})}function E(C){if(C.type==="TSParameterProperty"){let U=C;return l(U.parameter,U.decorators)}if(C.type==="RestElement"){let U=C,H=U.argument,B=`...${"name"in H&&typeof H.name==="string"?H.name:"unknown"}`,A=U.typeAnnotation,I=A?w(A):void 0,S={name:B,isOptional:!1};if(I)S.type=I;return S}let q=C;return l(q,q.decorators)}function y(C){if(!C)return;let q="typeAnnotation"in C&&C.typeAnnotation?C.typeAnnotation:null;if(!q)return;let H=q.typeName?.name;if(!H)return;return W.get(H)?.specifier}function l(C,q){if(C.type==="AssignmentPattern"){let{left:T,right:j}=C,g="name"in T&&typeof T.name==="string"?T.name:"unknown",b="typeAnnotation"in T?T.typeAnnotation:null,d=b?w(b):void 0,J_=y(b),V_=J.slice(j.start,j.end),B_="decorators"in T&&Array.isArray(T.decorators)?T.decorators:[],U0=u(B_),D_={name:g,isOptional:!0,defaultValue:V_};if(d)D_.type=d;if(J_)D_.typeImportSource=J_;if(U0.length>0)D_.decorators=U0;return D_}let U="name"in C&&typeof C.name==="string"?C.name:("pattern"in C)&&C.pattern&&typeof C.pattern.name==="string"?C.pattern.name:"unknown",H=!!(("optional"in C)&&C.optional),K="typeAnnotation"in C?C.typeAnnotation:null,B=K?w(K):void 0,A=y(K),I=u(q??[]),S={name:U,isOptional:H};if(B)S.type=B;if(A)S.typeImportSource=A;if(I.length>0)S.decorators=I;return S}function i(C,q){let U=[];if(q?.async)U.push("async");if(C.static)U.push("static");if(C.abstract)U.push("abstract");if(C.readonly)U.push("readonly");if(C.override)U.push("override");if(C.declare)U.push("declare");if(C.const)U.push("const");let H=C.accessibility;if(H==="private")U.push("private");else if(H==="protected")U.push("protected");else if(H==="public")U.push("public");return U}function W_(C){if(!C)return;let q=C.params.flatMap((U)=>{let H=U.name.name;return H?[H]:[]});return q.length>0?q:void 0}function X_(C){let q=[];if(C.superClass){let H=J.slice(C.superClass.start,C.superClass.end);q.push({kind:"extends",name:H})}let U=C.implements??[];for(let H of U){let K=H.expression,B=J.slice(K.start,K.end);q.push({kind:"implements",name:B})}return q}function K_(C){let q=[],U=C.extends;for(let H of U){let K=H.expression,B=J.slice(K.start,K.end);q.push({kind:"extends",name:B})}return q}function U_(C){let q=[];for(let U of C)if(U.type==="MethodDefinition"||U.type==="TSAbstractMethodDefinition"){let H=U,K=O(H.key,H.computed),B=M(H.key,H.computed,0),A=H.value,I=H.kind,S=I==="constructor"?"constructor":I==="get"?"getter":I==="set"?"setter":"method",T=i(H,A);if(U.type==="TSAbstractMethodDefinition"&&!T.includes("abstract"))T.push("abstract");let j=A.params.map(E),g=w(A.returnType),b=u(H.decorators??[]),d={kind:"method",name:K,span:D(U.start,U.end),isExported:!1,methodKind:S,modifiers:T,parameters:j.length>0?j:void 0,returnType:g};if(B)d.key=B;if(b.length>0)d.decorators=b;q.push(d)}else if(U.type==="PropertyDefinition"||U.type==="TSAbstractPropertyDefinition"||U.type==="AccessorProperty"||U.type==="TSAbstractAccessorProperty"){let H=U,K=O(H.key,H.computed),B=M(H.key,H.computed,0),A=i(H);if(U.type==="TSAbstractPropertyDefinition"||U.type==="TSAbstractAccessorProperty"){if(!A.includes("abstract"))A.push("abstract")}if(U.type==="AccessorProperty"||U.type==="TSAbstractAccessorProperty")A.push("accessor");let I=w(H.typeAnnotation),S=H.value,T=S?F(S):void 0,j=u(H.decorators??[]),g={kind:"property",name:K,span:D(U.start,U.end),isExported:!1,modifiers:A,returnType:I,initializer:T};if(B)g.key=B;if(j.length>0)g.decorators=j;q.push(g)}return q}function Y_(C){let q=[];for(let U of C)if(U.type==="TSMethodSignature"){let H=U,K=O(H.key,H.computed),B=M(H.key,H.computed,0),A=H.params.map(E),I=w(H.returnType),S={kind:"method",name:K,span:D(U.start,U.end),isExported:!1,modifiers:[],methodKind:"method",parameters:A.length>0?A:void 0,returnType:I};if(B)S.key=B;q.push(S)}else if(U.type==="TSPropertySignature"){let H=U,K=O(H.key,H.computed),B=M(H.key,H.computed,0),A=w(H.typeAnnotation),I={kind:"property",name:K,span:D(U.start,U.end),isExported:!1,modifiers:H.readonly?["readonly"]:[],returnType:A};if(B)I.key=B;q.push(I)}return q}function c(C,q){let U=C.type;if(U==="FunctionDeclaration"||U==="FunctionExpression"||U==="TSDeclareFunction"||U==="TSEmptyBodyFunctionExpression"){let H=C,K=H.id?.name??"default",B=H.params.map(E),A=w(H.returnType),I=i(H,H),S=u(H.decorators??[]),T=W_(H.typeParameters),j={kind:"function",name:K,span:D(C.start,C.end),isExported:q,modifiers:I,parameters:B.length>0?B:void 0,returnType:A,decorators:S.length>0?S:void 0};if(T&&T.length>0)j.typeParameters=T;return j}if(U==="ClassDeclaration"||U==="ClassExpression"){let H=C,K=H.id?.name??"default",B=X_(H),A=U_(H.body.body),I=u(H.decorators),S=i(H),T=W_(H.typeParameters),j={kind:"class",name:K,span:D(C.start,C.end),isExported:q,modifiers:S,heritage:B.length>0?B:void 0,members:A.length>0?A:void 0,decorators:I.length>0?I:void 0};if(T&&T.length>0)j.typeParameters=T;return j}if(U==="VariableDeclaration"){let H=C,K=[];for(let B of H.declarations){let{id:A,init:I}=B;if(A.type==="ObjectPattern"||A.type==="ArrayPattern"){let V_=v_(A);for(let B_ of V_)K.push({kind:"variable",name:B_.name,span:D(B_.start,B_.end),isExported:q,modifiers:[]});continue}let S="name"in A&&typeof A.name==="string"?A.name:"unknown",T="variable",j,g,b;if(I)if(I.type==="FunctionExpression"||I.type==="ArrowFunctionExpression"){T="function";let V_=I;j=V_.params.map(E),g=w(V_.returnType)}else b=F(I);let d=[],J_={kind:T,name:S,span:D(B.start,B.end),isExported:q,modifiers:d,parameters:j,returnType:g};if(b)J_.initializer=b;K.push(J_)}if(K.length===0)return null;if(K.length===1)return K[0];return K}if(U==="TSTypeAliasDeclaration")return{kind:"type",name:C.id.name,span:D(C.start,C.end),isExported:q,modifiers:[]};if(U==="TSInterfaceDeclaration"){let H=C,K=H.id.name,B=K_(H),A=Y_(H.body.body),I=W_(H.typeParameters),S={kind:"interface",name:K,span:D(C.start,C.end),isExported:q,modifiers:[],heritage:B.length>0?B:void 0,members:A.length>0?A:void 0};if(I&&I.length>0)S.typeParameters=I;return S}if(U==="TSEnumDeclaration"){let H=C,K=H.id.name,B=i(H),I=H.body.members.map((S)=>{let T=S.id,j=T.type!=="Identifier",g="name"in T&&typeof T.name==="string"?T.name:("value"in T)&&typeof T.value==="string"?T.value:"unknown",b=S.initializer?F(S.initializer):void 0,d={kind:"property",name:g,span:D(S.start,S.end),isExported:!1,modifiers:[]};if(j)d.key=X(T,0);if(b)d.initializer=b;return d});return{kind:"enum",name:K,span:D(C.start,C.end),isExported:q,modifiers:B,members:I.length>0?I:void 0}}if(U==="TSModuleDeclaration"){let H=C,K=H.id.name??H.id.value??"unknown",B=i(H),A=[];if(H.body?.type==="TSModuleBlock")for(let I of H.body.body??[]){if(I.type!=="ExportNamedDeclaration")continue;let S=I.declaration;if(!S)continue;let T=c(S,!1);if(T)if(Array.isArray(T))A.push(...T);else A.push(T)}return{kind:"namespace",name:K,span:D(C.start,C.end),isExported:q,modifiers:B,members:A.length>0?A:void 0}}return null}let s=[],C_=new Set;for(let C of $.body){let q=null,U=C;if(U.type==="ExportNamedDeclaration"){let K=U;if(K.declaration){if(q=c(K.declaration,!0),q&&!Array.isArray(q))q.span=D(K.start,K.end)}else if(!K.source&&K.specifiers)for(let B of K.specifiers){let A=B.local,I="name"in A?A.name:A.value;if(I)C_.add(I)}}else if(U.type==="ExportDefaultDeclaration"){let K=U,B=K.declaration;if(B){if(q=c(B,!0),q&&!Array.isArray(q))q.name="id"in B&&B.id&&typeof B.id.name==="string"?B.id.name:"default",q.isExported=!0,q.span=D(K.start,K.end);else if(!q&&"type"in B&&B.type==="Identifier"){let A=B.name;if(A)C_.add(A)}}}else{let K=U.type;if(K==="FunctionDeclaration"||K==="TSDeclareFunction"||K==="ClassDeclaration"||K==="VariableDeclaration"||K==="TSTypeAliasDeclaration"||K==="TSInterfaceDeclaration"||K==="TSEnumDeclaration"||K==="TSModuleDeclaration")q=c(U,!1)}let H=Array.isArray(q)?q:q?[q]:[];for(let K of H){let B=C.start,A=N(B);if(A){let I=t_(A);if(!DJ(I))K.jsDoc=I}s.push(K)}}if(C_.size>0){for(let C of s)if(!C.isExported&&C_.has(C.name))C.isExported=!0}return s}function e_(_){if(_===null||typeof _!=="object")return JSON.stringify(_);if(Array.isArray(_))return`[${_.map(e_).join(",")}]`;let $=_;return`{${Object.keys($).sort().map((Q)=>`${JSON.stringify(Q)}:${e_($[Q])}`).join(",")}}`}function NJ(_){if(_.kind==="function"||_.kind==="method"){let $=_.parameters?.length??0,J=_.modifiers.includes("async")?1:0;return`params:${$}|async:${J}`}return null}function RJ(_){let $={};if(_.jsDoc)$.jsDoc=_.jsDoc;if(_.kind==="function"||_.kind==="method"){if(_.parameters!==void 0)$.parameters=_.parameters;if(_.returnType!==void 0)$.returnType=_.returnType}if(_.heritage?.length)$.heritage=_.heritage;if(_.decorators?.length)$.decorators=_.decorators;if(_.typeParameters?.length)$.typeParameters=_.typeParameters;if(_.modifiers?.length)$.modifiers=_.modifiers;if(_.initializer)$.initializer=_.initializer;if(_.key)$.key=_.key;if(_.members?.length)$.members=_.members.map((J)=>{let Q=J.modifiers.find((W)=>W==="private"||W==="protected"||W==="public"),z={name:J.name,kind:J.methodKind??J.kind,type:J.returnType,visibility:Q,isStatic:J.modifiers.includes("static")||void 0,isReadonly:J.modifiers.includes("readonly")||void 0,isAccessor:J.modifiers.includes("accessor")||void 0};if(J.key)z.key=J.key;if(J.initializer)z.initializer=J.initializer;if(J.decorators?.length)z.decorators=J.decorators;return z});return Object.keys($).length>0?JSON.stringify($):null}function TJ(_){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(_.key)$.push(`k:${e_(_.key)}`);if(_.members?.length){let J=_.members.map((Q)=>`${Q.kind}:${Q.modifiers.join(",")}:${Q.parameters?.length??""}:${Q.returnType??""}:${Q.key?e_(Q.key):""}`).sort().join(";");$.push(`mem:${_.members.length}:${H_(J)}`)}return H_($.join("|"))}function J1(_,$,J,Q,z){let W=NJ(_),Z=H_(`${$}|${_.kind}|${W??""}`),Y=TJ(_);return{project:J,filePath:Q,kind:_.kind,name:$,startLine:_.span.start.line,startColumn:_.span.start.column,endLine:_.span.end.line,endColumn:_.span.end.column,isExported:_.isExported?1:0,signature:W,fingerprint:Z,detailJson:RJ(_),contentHash:z,indexedAt:new Date().toISOString(),structuralFingerprint:Y}}function C0(_){let{parsed:$,project:J,filePath:Q,contentHash:z,symbolRepo:W}=_,Z=R_($),Y=[];for(let X of Z){Y.push(J1(X,X.name,J,Q,z));for(let M of X.members??[])Y.push(J1(M,`${X.name}.${M.name}`,J,Q,z))}W.replaceFileSymbols(J,Q,z,Y)}import{resolve as D0,dirname as SJ,extname as FJ}from"path";function T_(_,$,J){let Q=(z)=>{let W=FJ(z);if(W===".js")return[z.slice(0,-3)+".ts"];if(W===".mjs")return[z.slice(0,-4)+".mts"];if(W===".cjs")return[z.slice(0,-4)+".cts"];if(W===".ts"||W===".mts"||W===".cts"||W===".d.ts")return[z];return[z+".ts",z+".d.ts",z+"/index.ts",z+"/index.d.ts",z+".mts",z+"/index.mts",z+".cts",z+"/index.cts"]};if($.startsWith(".")){let z=z_(D0(SJ(_),$));return Q(z)}if(J)for(let[z,W]of J.paths){if(W.length===0)continue;let Z=z.indexOf("*");if(Z===-1){if($===z){let Y=[];for(let X of W)Y.push(...Q(z_(D0(J.baseUrl,X))));return Y}}else{let Y=z.slice(0,Z),X=z.slice(Z+1);if($.startsWith(Y)&&(X===""||$.endsWith(X))){let M=$.slice(Y.length,X===""?void 0:$.length-X.length),O=[];for(let L of W)O.push(...Q(z_(D0(J.baseUrl,L.replace("*",M)))));return O}}}return[]}function Q1(_,$,J,Q=T_){let z=new Map,W=_.body??[];for(let Z of W){if(Z.type!=="ImportDeclaration")continue;let Y=Z.source?.value??"",X=Q($,Y,J);if(X.length===0)continue;let M=X[0],O=Z.specifiers??[];for(let L of O)switch(L.type){case"ImportSpecifier":z.set(L.local.name,{path:M,importedName:L.imported.name});break;case"ImportDefaultSpecifier":z.set(L.local.name,{path:M,importedName:"default"});break;case"ImportNamespaceSpecifier":z.set(L.local.name,{path:M,importedName:"*"});break}}return z}import{Visitor as GJ}from"oxc-parser";function _0(_){return"name"in _&&typeof _.name==="string"?_.name:("value"in _)&&typeof _.value==="string"?_.value:"unknown"}function jJ(_){return!_.startsWith(".")&&!_.startsWith("/")}function S_(_,$,J,Q){let z=Q(_,$,J),W=z.length>0?z[0]:null,Z=W===null&&jJ($);return{resolved:W,isExternal:Z}}function kJ(_,$,J,Q,z){for(let W of _.staticImports){let Z=W.moduleRequest.value,{resolved:Y,isExternal:X}=S_($,Z,J,Q),M={dstFilePath:Y,specifier:Z};if(W.entries.length===0){let O={};if(X)O.isExternal=!0;if(Y===null&&!X)O.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,...M,dstSymbolName:null,...Object.keys(O).length>0?{metaJson:JSON.stringify(O)}:{}});continue}for(let O of W.entries){let L=O.isType,D={};if(L)D.isType=!0;if(X)D.isExternal=!0;if(Y===null&&!X)D.isUnresolved=!0;let N,w,R=O.importName.kind;if(R==="Default")N="default",w=O.localName.value;else if(R==="NamespaceObject")N="*",w=O.localName.value,D.importKind="namespace";else N=O.importName.name??"unknown",w=O.localName.value;z.push({type:L?"type-references":"imports",srcFilePath:$,srcSymbolName:w,...M,dstSymbolName:N,...Object.keys(D).length>0?{metaJson:JSON.stringify(D)}:{}})}}}function gJ(_,$,J,Q,z){let W=new Map;for(let Z of _.staticImports)for(let Y of Z.entries)W.set(Y.localName.value,Z.moduleRequest.value);for(let Z of _.staticExports)for(let Y of Z.entries){let X=null;if(Y.moduleRequest)X=Y.moduleRequest.value;else if(Y.localName.name)X=W.get(Y.localName.name)??null;if(!X)continue;let{resolved:M,isExternal:O}=S_($,X,J,Q),L=Y.exportName.name??"default",D=Y.exportName.kind,N=Y.localName.name??Y.importName.name??L,w=Y.isType,R={isReExport:!0};if(D==="None");else R.specifiers=[{local:N,exported:L}];if(w)R.isType=!0;if(O)R.isExternal=!0;if(M===null&&!O)R.isUnresolved=!0;let G=null,F=null,u=Y.importName.kind;if(u==="All"||u==="AllButDefault"){if(D==="Name"&&L)F=L,R.namespaceAlias=L}else F=N,G=L;z.push({type:w?"type-references":"re-exports",srcFilePath:$,srcSymbolName:G,dstFilePath:M,dstSymbolName:F,specifier:X,metaJson:JSON.stringify(R)})}}function EJ(_,$,J,Q,z){for(let W of _.body){let Z=W;if(Z.type==="ImportDeclaration"){let Y=Z,X=Y.source.value,{resolved:M,isExternal:O}=S_($,X,J,Q),L=Y.importKind==="type",D=Y.specifiers,N={dstFilePath:M,specifier:X};if(D.length===0){let w={};if(L)w.isType=!0;if(O)w.isExternal=!0;if(M===null&&!O)w.isUnresolved=!0;z.push({type:L?"type-references":"imports",srcFilePath:$,srcSymbolName:null,...N,dstSymbolName:null,...Object.keys(w).length>0?{metaJson:JSON.stringify(w)}:{}})}else for(let w of D){let R=w.type,G=L||R==="ImportSpecifier"&&w.importKind==="type",F={};if(G)F.isType=!0;if(O)F.isExternal=!0;if(M===null&&!O)F.isUnresolved=!0;let u,E;if(R==="ImportDefaultSpecifier")u="default",E=w.local.name;else if(R==="ImportNamespaceSpecifier")u="*",E=w.local.name,F.importKind="namespace";else u=_0(w.imported),E=w.local.name;z.push({type:G?"type-references":"imports",srcFilePath:$,srcSymbolName:E,...N,dstSymbolName:u,...Object.keys(F).length>0?{metaJson:JSON.stringify(F)}:{}})}continue}if(Z.type==="ExportAllDeclaration"){let Y=Z,X=Y.source.value,{resolved:M,isExternal:O}=S_($,X,J,Q),L=Y.exportKind==="type",D=Y.exported,N=D?_0(D):null,w={isReExport:!0};if(L)w.isType=!0;if(O)w.isExternal=!0;if(M===null&&!O)w.isUnresolved=!0;if(N)w.namespaceAlias=N;z.push({type:L?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:M,dstSymbolName:N,specifier:X,metaJson:JSON.stringify(w)});continue}if(Z.type==="ExportNamedDeclaration"){let Y=Z;if(!Y.source)continue;let X=Y.source.value,{resolved:M,isExternal:O}=S_($,X,J,Q),L=Y.exportKind==="type",D=Y.specifiers??[];for(let N of D){let w=L||N.exportKind==="type",R=_0(N.local),G=_0(N.exported),F={isReExport:!0,specifiers:[{local:R,exported:G}]};if(w)F.isType=!0;if(O)F.isExternal=!0;if(M===null&&!O)F.isUnresolved=!0;z.push({type:w?"type-references":"re-exports",srcFilePath:$,srcSymbolName:G,dstFilePath:M,dstSymbolName:R,specifier:X,metaJson:JSON.stringify(F)})}}}}function vJ(_,$,J,Q,z){new GJ({ImportExpression(Z){let Y=Z.source;if(Y.type!=="Literal"||typeof Y.value!=="string")return;let X=Y.value,{resolved:M,isExternal:O}=S_($,X,J,Q),L={isDynamic:!0};if(O)L.isExternal=!0;if(M===null&&!O)L.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:M,dstSymbolName:null,specifier:X,metaJson:JSON.stringify(L)})},CallExpression(Z){let Y=Z.callee,X=!1;if(Y.type==="Identifier"&&Y.name==="require");else if(Y.type==="MemberExpression"&&!Y.computed){let R=Y,G=R.object,F=R.property;if(G.type==="Identifier"&&G.name==="require"&&F.name==="resolve")X=!0;else return}else return;let M=Z.arguments;if(M.length===0)return;let O=M[0];if(O.type!=="Literal"||typeof O.value!=="string")return;let L=O.value,{resolved:D,isExternal:N}=S_($,L,J,Q),w={isRequire:!0};if(X)w.isRequireResolve=!0;if(N)w.isExternal=!0;if(D===null&&!N)w.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:D,dstSymbolName:null,specifier:L,metaJson:JSON.stringify(w)})}}).visit(_)}function z1(_,$,J,Q=T_,z){let W=[];if(z)kJ(z,$,J,Q,W),gJ(z,$,J,Q,W);else EJ(_,$,J,Q,W);return vJ(_,$,J,Q,W),W}import{walk as lJ}from"oxc-walker";function uJ(_){return _.type==="FunctionDeclaration"||_.type==="FunctionExpression"||_.type==="ArrowFunctionExpression"}function bJ(_){return _.type==="ArrowFunctionExpression"}function PJ(_){return _.type==="AssignmentExpression"}function fJ(_){return _.type==="CallExpression"}function yJ(_){return _.type==="FunctionDeclaration"}function xJ(_){return _.type==="FunctionExpression"}function hJ(_){return _.type==="Identifier"}function mJ(_){return _.type==="MemberExpression"}function nJ(_){return _.type==="TSQualifiedName"}function pJ(_){return _.type==="VariableDeclaration"}var W1=new Map,dJ=new Proxy({},{get(_,$,J){if(typeof $!=="string")return Reflect.get(_,$,J);let Q=$.charCodeAt(0);if(Q<65||Q>90)return Reflect.get(_,$,J);let z=W1.get($);if(z===void 0)z=(W)=>W!==null&&W!==void 0&&W.type===$,W1.set($,z);return z}});function u_(_){if(!_||typeof _!=="object"||Array.isArray(_))return null;let $=_;if($.type==="Identifier"){let J=$.name;return{root:J,parts:[],full:J}}if($.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if($.type==="Super")return{root:"super",parts:[],full:"super"};if($.type==="MemberExpression"){let J=[],Q=$;while(Q.type==="MemberExpression"){let Z=Q.property;if(!Z||typeof Z.name!=="string")return null;J.push(Z.name),Q=Q.object}let z;if(Q.type==="Identifier")z=Q.name;else if(Q.type==="ThisExpression")z="this";else if(Q.type==="Super")z="super";else return null;J.reverse();let W=[z,...J].join(".");return{root:z,parts:J,full:W}}return null}function Y1(_,$,J){let Q=[],z=[],W=[];function Z(){if(z.length>0)return z[z.length-1]??null;return null}function Y(O){if(!O)return null;let L=J.get(O.root);if(O.parts.length===0){if(L)return{dstFilePath:L.path,dstSymbolName:L.importedName,resolution:"import"};return{dstFilePath:$,dstSymbolName:O.root,resolution:"local"}}else{if(L&&L.importedName==="*"){let D=O.parts[O.parts.length-1];return{dstFilePath:L.path,dstSymbolName:D,resolution:"namespace"}}return{dstFilePath:$,dstSymbolName:O.full,resolution:"local-member"}}}function X(O,L){let D=u_(O.callee),N=Y(D);if(N){let w=Z(),R={};if(L)R.isNew=!0;if(w===null)R.scope="module";Q.push({type:"calls",srcFilePath:$,srcSymbolName:w,dstFilePath:N.dstFilePath,dstSymbolName:N.dstSymbolName,...Object.keys(R).length>0?{metaJson:JSON.stringify(R)}:{}})}}function M(O,L){if(O.type==="FunctionDeclaration"){z.push(O.id?.name??"anonymous");return}if(O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){if(L?.type==="VariableDeclarator"){let w=L.id,R=w.type==="Identifier"?w.name:"anonymous";z.push(R);return}if(L?.type==="MethodDefinition"||L?.type==="TSAbstractMethodDefinition"){let w=L.key,R=W[W.length-1]??"",G="name"in w?w.name:"anonymous",F=R?`${R}.${G}`:G;z.push(F);return}let D=Z(),N=D?`${D}.<anonymous>`:"<anonymous>";z.push(N)}}return lJ(_,{enter(O,L){if(O.type==="ClassDeclaration"||O.type==="ClassExpression"){W.push(O.id?.name??"AnonymousClass");return}if(O.type==="FunctionDeclaration"||O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){M(O,L);return}if(O.type==="CallExpression"){X(O,!1);return}if(O.type==="NewExpression"){X(O,!0);return}},leave(O){if(O.type==="ClassDeclaration"||O.type==="ClassExpression"){W.pop();return}if(O.type==="FunctionDeclaration"||O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){z.pop();return}}}),Q}import{Visitor as iJ}from"oxc-parser";function Z1(_,$,J){let Q=[];function z(Z){let Y=Z.id?.name??"AnonymousClass";if(Z.superClass){let M=u_(Z.superClass);if(M){let O=A0(M,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Y,...O})}}let X=Z.implements??[];for(let M of X){let O=u_(M.expression);if(!O)continue;let L=A0(O,$,J);Q.push({type:"implements",srcFilePath:$,srcSymbolName:Y,...L})}}return new iJ({TSInterfaceDeclaration(Z){let Y=Z.id.name??"AnonymousInterface",X=Z.extends;for(let M of X){let O=u_(M.expression);if(!O)continue;let L=A0(O,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Y,...L})}},ClassDeclaration(Z){z(Z)},ClassExpression(Z){z(Z)}}).visit(_),Q}function A0(_,$,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 d_(_,$,J,Q=T_,z){let W=Q1(_,$,J,Q),Z=z1(_,$,J,Q,z),Y=Y1(_,$,W),X=Z1(_,$,W);return[...Z,...Y,...X]}function q0(_){let{ast:$,project:J,filePath:Q,relationRepo:z,projectRoot:W,tsconfigPaths:Z,knownFiles:Y,boundaries:X,module:M}=_,O=g_(W,Q),D=d_($,O,Z,Y?(w,R,G)=>{let F=T_(w,R,G);for(let u of F){let E=h_(W,u);if(X){let y=a(E,X);if(Y.has(`${y}::${E}`))return[u]}else if(Y.has(`${J}::${E}`))return[u]}return[]}:void 0,M),N=[];for(let w of D){if(w.dstFilePath===null){let u=h_(W,w.srcFilePath),E;if(w.metaJson)try{E=JSON.parse(w.metaJson)}catch{}let y=E?.isExternal===!0;N.push({project:J,type:w.type,srcFilePath:u,srcSymbolName:w.srcSymbolName??null,dstProject:null,dstFilePath:null,dstSymbolName:w.dstSymbolName??null,metaJson:w.metaJson??null,specifier:w.specifier??null,isExternal:y?1:0});continue}let R=h_(W,w.dstFilePath);if(R.startsWith(".."))continue;let G=h_(W,w.srcFilePath),F=X?a(R,X):J;N.push({project:J,type:w.type,srcFilePath:G,srcSymbolName:w.srcSymbolName??null,dstProject:F,dstFilePath:R,dstSymbolName:w.dstSymbolName??null,metaJson:w.metaJson??null,specifier:w.specifier??null,isExternal:0})}return z.replaceFileRelations(J,Q,N),N.length}import{isErr as cJ}from"@zipbul/result";var X1=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function aJ(_){let $=R_(_),J=[];for(let Q of $){J.push({name:Q.name,startLine:Q.span.start.line});for(let z of Q.members??[])J.push({name:`${Q.name}.${z.name}`,startLine:z.span.start.line})}return J.sort((Q,z)=>Q.startLine-z.startLine),J}function N0(_,$,J){let Q=0,z=_.length-1;while(Q<=z){let W=Q+z>>1;if(_[W].startLine<=$)Q=W+1;else z=W-1}if(Q<_.length){let W=_[Q];if(W.startLine-$<=J)return W.name}return null}function $0(_,$,J){let Q=O_(_,$),z=O_(_,J);return{start:Q,end:z}}function U1(_){let{comments:$,sourceText:J}=_;if(!$.length)return[];let Q=p_(J),z=aJ(_),W=[],Z=[...$].sort((X,M)=>X.start-M.start),Y=null;for(let X of Z)if(X.type==="Block"&&X.value.startsWith("*")){Y=null;let M=`/*${X.value}*/`,O=t_(M);if(cJ(O))continue;let L=O;if(!L.tags?.length)continue;let D=O_(Q,X.end),N=N0(z,D.line,3),w=J.slice(X.start,X.end);for(let R of L.tags){let G=[R.name,R.description].filter(Boolean).join(" "),F=`@${R.tag}`,u=w.indexOf(F),E;if(u>=0){let y=X.start+u,l=J.indexOf(`
|
|
4
|
-
`,
|
|
5
|
-
`),O=0;for(let L of M){let
|
|
6
|
-
`).length});let
|
|
7
|
-
`).length})}let I=new Set;for(let T of H)for(let[j]of Q.getFilesMap(T.project))I.add(`${T.project}::${j}`);let S=this.opts.parseSourceFn??E_;for(let T of B){let j=a(T.filePath,H),g=S(g_(U,T.filePath),T.text);if(O1(g))throw g.data;let b=g;if(A.push({filePath:T.filePath,parsed:b}),C0({parsed:b,project:j,filePath:T.filePath,contentHash:T.contentHash,symbolRepo:z}),F)y+=R0({parsed:b,project:j,filePath:T.filePath,annotationRepo:F});W_+=q0({ast:b.program,project:j,filePath:T.filePath,relationRepo:W,projectRoot:U,tsconfigPaths:M,knownFiles:I,boundaries:H,module:b.module}),i+=z.getFileSymbols(j,T.filePath).length}});for(let I of A)K.set(I.filePath,I.parsed)}else{E();let U=await l();i=U.symbols,W_=U.relations,y=U.annotations,X_=U.failedFiles}for(let U of Y){let H=a(U.filePath,this.opts.boundaries);for(let K of z.getFileSymbols(H,U.filePath))N.set(`${K.filePath}::${K.name}`,w(K))}let K_=new Map;for(let U of Y){let H=a(U.filePath,this.opts.boundaries);for(let K of W.getOutgoing(H,U.filePath))K_.set(R(K),K)}let U_=(U)=>({type:U.type,srcFilePath:U.srcFilePath,dstFilePath:U.dstFilePath,srcSymbolName:U.srcSymbolName,dstSymbolName:U.dstSymbolName,dstProject:U.dstProject,metaJson:U.metaJson}),Y_={added:[...K_.entries()].filter(([U])=>!G.has(U)).map(([,U])=>U_(U)),removed:[...G.entries()].filter(([U])=>!K_.has(U)).map(([,U])=>U_(U))},c={added:[],modified:[],removed:[]};for(let[U,H]of N){let K=D.get(U);if(!K)c.added.push({name:H.name,filePath:H.filePath,kind:H.kind,isExported:Boolean(H.isExported)});else{let B=K.fingerprint!==H.fingerprint,A=K.isExported!==H.isExported,I=K.structuralFingerprint!==null&&H.structuralFingerprint!==null&&K.structuralFingerprint!==H.structuralFingerprint;if(B||A||I)c.modified.push({name:H.name,filePath:H.filePath,kind:H.kind,isExported:Boolean(H.isExported)})}}for(let[U,H]of D)if(!N.has(U))c.removed.push({name:H.name,filePath:H.filePath,kind:H.kind,isExported:Boolean(H.isExported)});let s=V1(D,N),C_=new Set(s.renamed.map((U)=>`${U.filePath}::${U.oldName}`)),C=new Set(s.renamed.map((U)=>`${U.filePath}::${U.newName}`));c.added=c.added.filter((U)=>!C.has(`${U.filePath}::${U.name}`)),c.removed=c.removed.filter((U)=>!C_.has(`${U.filePath}::${U.name}`));let q=[];if(!$){for(let[H,K]of O)for(let B of K){if(!B.fingerprint)continue;let A=a(H,this.opts.boundaries),I=z.getByFingerprint(A,B.fingerprint);if(I.length===1){let S=I[0];W.retargetRelations({dstProject:A,oldFile:H,oldSymbol:B.name,newFile:S.filePath,newSymbol:S.name}),q.push({name:S.name,filePath:S.filePath,kind:S.kind,oldFilePath:H,isExported:S.isExported??0})}}let U=new Set(q.map((H)=>`${H.oldFilePath}::${H.name}`));for(let H of s.removed){if(U.has(`${H.filePath}::${H.name}`))continue;let B=D.get(`${H.filePath}::${H.name}`)?.fingerprint;if(!B)continue;let A=a(H.filePath,this.opts.boundaries),I=z.getByFingerprint(A,B);if(I.length===1){let S=I[0];if(S.filePath!==H.filePath||S.name!==H.name)W.retargetRelations({dstProject:A,oldFile:H.filePath,oldSymbol:H.name,newFile:S.filePath,newSymbol:S.name}),q.push({name:S.name,filePath:S.filePath,kind:S.kind,oldFilePath:H.filePath,isExported:S.isExported??0})}}}if(q.length){let U=new Set(q.map((K)=>`${K.filePath}::${K.name}`)),H=new Set(q.map((K)=>`${K.oldFilePath}::${K.name}`));c.added=c.added.filter((K)=>!U.has(`${K.filePath}::${K.name}`)),c.removed=c.removed.filter((K)=>!H.has(`${K.filePath}::${K.name}`))}if(u){let U=new Date().toISOString(),H=$?1:0,K=[];for(let B of c.added){let A=`${B.filePath}::${B.name}`,I=N.get(A),S=a(B.filePath,this.opts.boundaries);K.push({project:S,changeType:"added",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:null,fingerprint:I?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:L})}for(let B of c.modified){let A=N.get(`${B.filePath}::${B.name}`),I=a(B.filePath,this.opts.boundaries);K.push({project:I,changeType:"modified",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:null,fingerprint:A?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:L})}for(let B of c.removed){let A=`${B.filePath}::${B.name}`,I=D.get(A),S=a(B.filePath,this.opts.boundaries);K.push({project:S,changeType:"removed",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:null,fingerprint:I?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:L})}for(let B of s.renamed){let A=N.get(`${B.filePath}::${B.newName}`),I=a(B.filePath,this.opts.boundaries);K.push({project:I,changeType:"renamed",symbolName:B.newName,symbolKind:B.kind,filePath:B.filePath,oldName:B.oldName,oldFilePath:null,fingerprint:A?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:L})}for(let B of q){let A=N.get(`${B.filePath}::${B.name}`),I=a(B.filePath,this.opts.boundaries);K.push({project:I,changeType:"moved",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:B.oldFilePath,fingerprint:A?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:L})}if(K.length)try{Z.transaction(()=>{u.insertBatch(K)})}catch(B){this.logger.error("[IndexCoordinator] changelog insert failed:",B)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let B=new Date(Date.now()-2592000000).toISOString();try{for(let A of this.opts.boundaries)u.pruneOlderThan(A.project,B)}catch(A){this.logger.error("[IndexCoordinator] changelog pruning failed:",A)}}}return{indexedFiles:Y.length,removedFiles:X.length,totalSymbols:i,totalRelations:W_,totalAnnotations:y,durationMs:Date.now()-J,changedFiles:Y.map((U)=>U.filePath),deletedFiles:[...X],failedFiles:X_,changedSymbols:c,renamedSymbols:s.renamed.map((U)=>({oldName:U.oldName,newName:U.newName,filePath:U.filePath,kind:U.kind,isExported:Boolean(N.get(`${U.filePath}::${U.newName}`)?.isExported)})),movedSymbols:q.map((U)=>({name:U.name,oldFilePath:U.oldFilePath,newFilePath:U.filePath,kind:U.kind,isExported:Boolean(U.isExported)})),changedRelations:Y_}}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 rJ(_){try{return process.kill(_,0),!0}catch($){if(typeof $==="object"&&$&&"code"in $)return $.code!=="ESRCH";return!0}}function oJ(_){let $=new Date(_).getTime();return Number.isNaN($)?0:$}function K1(_,$,J={}){let Q=J.now??Date.now,z=J.isAlive??rJ,W=J.staleAfterSeconds??60,Z=J.instanceId;return _.immediateTransaction(()=>{let Y=_.selectOwner();if(!Y)return _.insertOwner($,Z),"owner";let X=Math.floor((Q()-oJ(Y.heartbeat_at))/1000),M=z(Y.pid);if(M&&Z&&Y.instance_id&&Y.instance_id!==Z&&Y.pid===$)return _.replaceOwner($,Z),"owner";if(M&&X<W)return"reader";return _.replaceOwner($,Z),"owner"})}function M1(_,$){_.deleteOwner($)}function L1(_,$){_.touchOwner($)}class l_{#_;#$=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 S0{lru;constructor(_=500){this.lru=new l_(_)}get(_){return this.lru.get(_)}set(_,$){this.lru.set(_,$)}invalidate(_){this.lru.delete(_)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function F0(_){let{symbolRepo:$,project:J,query:Q}=_,z=Q.project??J,W={kind:Q.kind,filePath:Q.filePath,isExported:Q.isExported,project:z,limit:Q.limit,resolvedType:Q.resolvedType};if(Q.text)if(Q.exact)W.exactName=Q.text;else{let Y=k_(Q.text);if(Y)W.ftsQuery=Y}if(Q.decorator)W.decorator=Q.decorator;if(Q.regex)W.regex=Q.regex;return $.searchByQuery(W).map((Y)=>{let X=Y.name.indexOf(".");return{id:Y.id,filePath:Y.filePath,kind:Y.kind,name:Y.name,memberName:X>=0?Y.name.slice(X+1):null,span:{start:{line:Y.startLine,column:Y.startColumn},end:{line:Y.endLine,column:Y.endColumn}},isExported:Y.isExported===1,signature:Y.signature,fingerprint:Y.fingerprint,detail:Y.detailJson?(()=>{try{return JSON.parse(Y.detailJson)}catch{return{}}})():{}}})}function G0(_){let{relationRepo:$,project:J,query:Q}=_;if(Q.srcFilePath&&Q.srcFilePathPattern)throw new V("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if(Q.dstFilePath&&Q.dstFilePathPattern)throw new V("validation","dstFilePath and dstFilePathPattern are mutually exclusive");let z=Q.project??J,W=Q.limit,Z=!!(Q.srcFilePathPattern||Q.dstFilePathPattern),Y=Z?void 0:W,M=$.searchRelations({srcFilePath:Q.srcFilePath,srcSymbolName:Q.srcSymbolName,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,dstProject:Q.dstProject,type:Q.type,project:z,specifier:Q.specifier,isExternal:Q.isExternal,limit:Y}).map((O)=>{let L;if(O.metaJson)try{L=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:L}});if(Q.srcFilePathPattern||Q.dstFilePathPattern){let O=Q.srcFilePathPattern?new Bun.Glob(Q.srcFilePathPattern):null,L=Q.dstFilePathPattern?new Bun.Glob(Q.dstFilePathPattern):null;M=M.filter((D)=>(!O||O.match(D.srcFilePath))&&(!L||D.dstFilePath===null||L.match(D.dstFilePath)))}if(Z&&W!==void 0&&M.length>W)M=M.slice(0,W);return M}import{findInFiles as tJ,Lang as eJ}from"@ast-grep/napi";function _Q(_){let $=new Set,J=/\${1,3}([A-Z_][A-Z_0-9]*)/g,Q;while((Q=J.exec(_))!==null)$.add(Q[0]);return[...$]}function $Q(_){return _.replace(/^\$+/,"")}function JQ(_,$){if($.length===0)return;let J={},Q=!1;for(let z of $){let W=$Q(z),Z=_.getMatch(W);if(Z){let X=Z.range();J[z]={text:Z.text(),startLine:X.start.line+1,endLine:X.end.line+1,startColumn:X.start.column,endColumn:X.end.column,startOffset:X.start.index,endOffset:X.end.index},Q=!0;continue}let Y=_.getMultipleMatches(W);if(Y.length>0){let X=Y[0].range(),M=Y[Y.length-1].range();J[z]={text:Y.map((O)=>O.text()).join(", "),startLine:X.start.line+1,endLine:M.end.line+1,startColumn:X.start.column,endColumn:M.end.column,startOffset:X.start.index,endOffset:M.end.index},Q=!0}}return Q?J:void 0}async function j0(_){if(_.filePaths.length===0)return[];let $=_Q(_.pattern),J=[];return await tJ(eJ.TypeScript,{paths:_.filePaths,matcher:{rule:{pattern:_.pattern}}},(Q,z)=>{if(Q){console.warn("[patternSearch] findInFiles callback error:",Q);return}for(let W of z){let Z=W.range(),Y={filePath:W.getRoot().filename(),startLine:Z.start.line+1,endLine:Z.end.line+1,startColumn:Z.start.column,endColumn:Z.end.column,startOffset:Z.start.index,endOffset:Z.end.index,matchedText:W.text()},X=JQ(W,$);if(X)Y.captures=X;J.push(Y)}}),J}import __ from"typescript";import{isErr as DQ}from"@zipbul/result";import w_ from"typescript";import QQ from"path";import{err as k0}from"@zipbul/result";function zQ(_){try{return d0("fs").readFileSync(_,"utf-8")}catch{return}}function WQ(_){try{return d0("fs").readFileSync(_,"utf-8")}catch{return}}class J0{#_;#$;#J=!1;__testing__;constructor(_,$){this.#_=_,this.#$=$,this.__testing__={host:$}}static create(_,$={}){let J=$.readConfigFile??zQ,Q=$.resolveNonTrackedFile??WQ,z=QQ.dirname(_),W=J(_);if(W===void 0)return k0(new V("semantic",`tsconfig not found: ${_}`));let Z=w_.parseJsonText(_,W),Y=Z.parseDiagnostics;if(Y&&Y.length>0){let L=Y.map((D)=>w_.flattenDiagnosticMessageText(D.messageText,`
|
|
8
|
-
`)).join("; ");return
|
|
9
|
-
`)).join("; ");return k0(new V("semantic",`tsconfig compile error: ${D}`))}}let M=new B1(X.fileNames,X.options,z,Q),O=w_.createLanguageService(M);return new J0(O,M)}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 B1{#_;#$;#J;#z;#W=new Map;#Y=new Map;#Q=new Map;constructor(_,$,J,Q){this.#_=new Set(_),this.#$=$,this.#J=J,this.#z=Q}updateFile(_,$){let J=this.#W.get(_);if(J){if(J.content===$)return;this.#Y.delete(`${_}:${J.version}`),J.version+=1,J.content=$}else this.#W.set(_,{version:1,content:$})}removeFile(_){let $=this.#W.get(_);if($)this.#Y.delete(`${_}:${$.version}`);this.#W.delete(_),this.#_.delete(_)}getScriptFileNames(){let _=[...this.#W.keys()];return[...[...this.#_].filter((J)=>!this.#W.has(J)),..._]}getScriptVersion(_){let $=this.#W.get(_);return $?String($.version):"0"}getScriptSnapshot(_){let $=this.#W.get(_);if($){let z=`${_}:${$.version}`,W=this.#Y.get(z);if(!W)W=w_.ScriptSnapshot.fromString($.content),this.#Y.set(z,W);return W}let J=this.#Q.get(_);if(J)return J;let Q=this.#z(_);if(Q!==void 0)return J=w_.ScriptSnapshot.fromString(Q),this.#Q.set(_,J),J;return}getCurrentDirectory(){return this.#J}getCompilationSettings(){return this.#$}getDefaultLibFileName(_){return w_.getDefaultLibFilePath(_)}fileExists(_){if(this.#W.has(_))return!0;return this.#z(_)!==void 0}readFile(_){let $=this.#W.get(_);if($)return $.content;return this.#z(_)}}import n from"typescript";import w1 from"typescript";function e(_,$){if($<0||$>=_.getEnd())return;let J,Q=(z)=>{if($<z.getStart(_,!1)||$>=z.getEnd())return;J=z,w1.forEachChild(z,Q)};return w1.forEachChild(_,Q),J}var Q0=8;function YQ(_){return!!(_.flags&n.TypeFlags.Object)&&!!(_.objectFlags&n.ObjectFlags.Reference)}function L_(_,$,J=0,Q){if(Q){let w=Q.get($);if(w)return w}let z=_.typeToString($),W=$.flags,Z=!!(W&n.TypeFlags.Union),Y=!!(W&n.TypeFlags.Intersection),X;if(J<Q0&&YQ($)){let w=_.getTypeArguments($);if(w.length>0)X=w}let M=!!(W&n.TypeFlags.TypeParameter)||X!==void 0&&X.length>0,O;if(Z&&J<Q0)O=$.types.map((w)=>L_(_,w,J+1,Q));else if(Y&&J<Q0)O=$.types.map((w)=>L_(_,w,J+1,Q));let L;if(X&&X.length>0)L=X.map((w)=>L_(_,w,J+1,Q));let D;if(J<Q0&&!!(W&n.TypeFlags.Object)&&!Z&&!Y){let w=_.getPropertiesOfType($);if(w.length>0&&w.length<=50){let R=$.symbol?.declarations?.[0];D=[];for(let G of w){let F=G.declarations?.[0]??R;if(!F)continue;try{let u=_.getTypeOfSymbolAtLocation(G,F);D.push({name:G.getName(),type:L_(_,u,J+1,Q)})}catch{}}if(D.length===0)D=void 0}}let N={text:z,flags:W,isUnion:Z,isIntersection:Y,isGeneric:M,members:O,typeArguments:L,properties:D};if(Q)Q.set($,N);return N}function ZQ(_){return n.isFunctionDeclaration(_)||n.isVariableDeclaration(_)||n.isClassDeclaration(_)||n.isInterfaceDeclaration(_)||n.isTypeAliasDeclaration(_)||n.isEnumDeclaration(_)||n.isMethodDeclaration(_)||n.isPropertyDeclaration(_)||n.isPropertySignature(_)||n.isMethodSignature(_)}var g0="/__gildash_type_probe__.ts";class E0{program;#_=null;constructor(_){this.program=_}#$(_){if(this.#_===_)return;this.program.notifyFileChanged(g0,`declare const __gildash_probe__: ${_};`),this.#_=_}#J(_,$){let J=_.getSourceFile(g0);if(!J)return null;let Q=J.statements[0];if(!Q||!n.isVariableStatement(Q))return null;let z=Q.declarationList.declarations[0];if(!z)return null;return $.getTypeAtLocation(z.name)}clearProbe(){if(this.#_!==null)this.program.removeFile(g0),this.#_=null}collectAt(_,$){let J=this.program.getProgram(),Q=J.getTypeChecker();if($<0)return null;let z=J.getSourceFile(_);if(!z)return null;if($>=z.getEnd())return null;let W=e(z,$);if(!W)return null;if(!n.isIdentifier(W)&&!n.isTypeNode(W))return null;try{let Z=Q.getTypeAtLocation(W);return L_(Q,Z,0,new Map)}catch{return null}}isAssignableTo(_,$,J,Q){let z=this.program.getProgram(),W=z.getTypeChecker(),Z=z.getSourceFile(_);if(!Z)return null;let Y=e(Z,$);if(!Y||!n.isIdentifier(Y))return null;let X=z.getSourceFile(J);if(!X)return null;let M=e(X,Q);if(!M||!n.isIdentifier(M))return null;try{let O=W.getTypeAtLocation(Y),L=W.getTypeAtLocation(M);return W.isTypeAssignableTo(O,L)}catch{return null}}isAssignableToType(_,$,J,Q){this.#$(J);let z=this.program.getProgram(),W=z.getTypeChecker(),Z=z.getSourceFile(_);if(!Z)return null;let Y=e(Z,$);if(!Y||!n.isIdentifier(Y)&&!n.isTypeNode(Y))return null;try{let X=this.#J(z,W);if(!X)return null;let M=W.getTypeAtLocation(Y);if(Q?.anyConstituent&&M.isUnion())return M.types.some((O)=>W.isTypeAssignableTo(O,X));return W.isTypeAssignableTo(M,X)}catch{return null}}isAssignableToTypeAtPositions(_,$,J,Q){let z=new Map;if($.length===0)return z;this.#$(J);let W=this.program.getProgram(),Z=W.getTypeChecker(),Y=W.getSourceFile(_);if(!Y)return z;try{let X=this.#J(W,Z);if(!X)return z;let M=Y.getEnd();for(let O of $){if(O<0||O>=M)continue;let L=e(Y,O);if(!L||!n.isIdentifier(L)&&!n.isTypeNode(L))continue;try{let D=Z.getTypeAtLocation(L);if(Q?.anyConstituent&&D.isUnion())z.set(O,D.types.some((N)=>Z.isTypeAssignableTo(N,X)));else z.set(O,Z.isTypeAssignableTo(D,X))}catch{}}}catch{}return z}collectAtPositions(_,$){let J=new Map;if($.length===0)return J;let Q=this.program.getProgram(),z=Q.getTypeChecker(),W=Q.getSourceFile(_);if(!W)return J;let Z=W.getEnd(),Y=new Map;for(let X of $){if(X<0||X>=Z)continue;let M=e(W,X);if(!M)continue;if(!n.isIdentifier(M)&&!n.isTypeNode(M))continue;try{let O=z.getTypeAtLocation(M);J.set(X,L_(z,O,0,Y))}catch{}}return J}collectFile(_){let $=new Map,J=this.program.getProgram(),Q=J.getTypeChecker(),z=J.getSourceFile(_);if(!z)return $;let W=new Map;function Z(Y){if(ZQ(Y)&&Y.name&&n.isIdentifier(Y.name)){let X=Y.name;try{let M=Q.getTypeAtLocation(X),O=X.getStart(z);$.set(O,L_(Q,M,0,W))}catch{}}n.forEachChild(Y,Z)}return Z(z),$}}import I_ from"typescript";var XQ=1000,UQ=1;function VQ(_){let $=_.declarations?.[0],J=$?.getSourceFile(),Q=$?I_.getNameOfDeclaration($):void 0;return{name:_.getName(),filePath:J?.fileName??"",position:Q?.getStart(J,!1)??$?.getStart(J,!1)??0}}function z0(_,$=0,J){let Q=_.declarations?.[0],z=Q?.getSourceFile(),W=Q?I_.getNameOfDeclaration(Q):void 0,Z=z?.fileName??"",Y=W?.getStart(z,!1)??Q?.getStart(z,!1)??0,X={name:_.getName(),filePath:Z,position:Y},M=_;if(M.parent)X.parent=VQ(M.parent);let O=J&&!!(_.flags&I_.SymbolFlags.Alias)?J.getAliasedSymbol(_):_;if($<UQ){let L=O.flags,D=!!(L&I_.SymbolFlags.Enum),N=!!(L&(I_.SymbolFlags.NamespaceModule|I_.SymbolFlags.ValueModule)),w=!!(L&(I_.SymbolFlags.Class|I_.SymbolFlags.Interface));if(D&&O.exports&&O.exports.size>0){let R=[];O.exports.forEach((G)=>{R.push(z0(G,$+1,J))}),X.members=R}else if(w&&O.members&&O.members.size>0){let R=[];O.members.forEach((G)=>{R.push(z0(G,$+1,J))}),X.members=R}if(N&&O.exports&&O.exports.size>0){let R=[];O.exports.forEach((G)=>{R.push(z0(G,$+1,J))}),X.exports=R}}return X}class v0{#_;#$;constructor(_,$=XQ){this.#_=_,this.#$=new l_($)}get(_,$){if(this.#_.isDisposed)return null;let J=`${_}:${$}`,Q=this.#$.get(J);if(Q!==void 0)return Q;let z=this.#_.getProgram(),W=z.getSourceFile(_);if(!W)return null;let Z=e(W,$);if(!Z||!I_.isIdentifier(Z))return null;let Y=z.getTypeChecker(),X=Y.getSymbolAtLocation(Z);if(!X)return null;let M=z0(X,0,Y);return this.#$.set(J,M),M}clear(){this.#$.clear()}}import p from"typescript";import k from"typescript";function u0(_){if(_.getSourceFile().isDeclarationFile)return!0;for(let $=_;$;$=$.parent)if(OQ($))return!0;return!1}function OQ(_){if(!k.canHaveModifiers(_))return!1;return k.getModifiers(_)?.some((J)=>J.kind===k.SyntaxKind.DeclareKeyword)??!1}function b0(_){let $=(Q,z)=>({kind:Q,pos:z.getStart(),end:z.getEnd()}),J=_.parent;while(J){if(k.isSourceFile(J)||k.isModuleDeclaration(J))return $("module",J);if(k.isFunctionLike(J))return $("function",J);if(k.isClassStaticBlockDeclaration(J))return $("function",J);if(k.isPropertyDeclaration(J))return $("function",J);if(k.isBlock(J)){let Q=J.parent;if(Q&&(k.isFunctionLike(Q)||k.isClassStaticBlockDeclaration(Q)))return $("function",Q);return $("block",J)}if(k.isForStatement(J)||k.isForInStatement(J)||k.isForOfStatement(J)||k.isCatchClause(J)||k.isCaseBlock(J)||k.isWithStatement(J))return $("block",J);J=J.parent}return $("module",_.getSourceFile())}function P0(_){let $=_.parent;if(!$)return;if(k.isVariableDeclaration($)&&$.name===_)return"declaration";if(k.isParameter($)&&$.name===_)return"declaration";if(k.isBindingElement($)&&$.name===_)return"declaration";if((k.isForOfStatement($)||k.isForInStatement($))&&$.initializer===_)return"assignment";if((k.isPrefixUnaryExpression($)||k.isPostfixUnaryExpression($))&&$.operand===_&&($.operator===k.SyntaxKind.PlusPlusToken||$.operator===k.SyntaxKind.MinusMinusToken))return"update";let J=_;while(J.parent&&k.isParenthesizedExpression(J.parent))J=J.parent;let Q=J.parent;if(Q&&k.isBinaryExpression(Q)&&Q.left===J)return HQ(Q.operatorToken.kind);if(KQ(_))return"assignment";return}function HQ(_){switch(_){case k.SyntaxKind.EqualsToken:return"assignment";case k.SyntaxKind.PlusEqualsToken:case k.SyntaxKind.MinusEqualsToken:case k.SyntaxKind.AsteriskEqualsToken:case k.SyntaxKind.AsteriskAsteriskEqualsToken:case k.SyntaxKind.SlashEqualsToken:case k.SyntaxKind.PercentEqualsToken:case k.SyntaxKind.LessThanLessThanEqualsToken:case k.SyntaxKind.GreaterThanGreaterThanEqualsToken:case k.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken:case k.SyntaxKind.AmpersandEqualsToken:case k.SyntaxKind.BarEqualsToken:case k.SyntaxKind.CaretEqualsToken:return"compound-assignment";case k.SyntaxKind.AmpersandAmpersandEqualsToken:case k.SyntaxKind.BarBarEqualsToken:case k.SyntaxKind.QuestionQuestionEqualsToken:return"logical-assignment";default:return}}function KQ(_){let $=_.parent;if(!$)return!1;if(!(k.isShorthandPropertyAssignment($)&&$.name===_||k.isPropertyAssignment($)&&$.initializer===_||k.isArrayLiteralExpression($)||k.isSpreadAssignment($)&&$.expression===_||k.isSpreadElement($)&&$.expression===_))return!1;let Q=$;while(Q.parent){let z=Q.parent;if(k.isBinaryExpression(z)&&z.left===Q&&z.operatorToken.kind===k.SyntaxKind.EqualsToken)return!0;if(k.isObjectLiteralExpression(z)||k.isArrayLiteralExpression(z)||k.isPropertyAssignment(z)||k.isShorthandPropertyAssignment(z)||k.isSpreadAssignment(z)||k.isSpreadElement(z)){Q=z;continue}return!1}return!1}class f0{#_;constructor(_){this.#_=_}findAt(_,$){let J=this.#$(_,$);if(!J)return[];let Q=this.#_.getProgram(),z=[];for(let W of J)for(let Z of W.references){let Y=Q.getSourceFile(Z.fileName);if(!Y)continue;z.push(I1(Z,Y))}return z}findEnrichedAt(_,$){let J=this.#$(_,$);if(!J)return[];let Q=this.#_.getProgram(),z=Q.getTypeChecker(),W=[];for(let Z of J){let Y=this.#J(Z,Q,z);for(let X of Z.references){let M=Q.getSourceFile(X.fileName);if(!M)continue;let O=e(M,X.textSpan.start),L=O&&p.isIdentifier(O)?O:void 0;W.push({...I1(X,M),writeKind:L?P0(L):void 0,isAmbient:Y,enclosingScope:b0(L??M)})}}return W}findFileBindings(_){if(this.#_.isDisposed)return[];let $=this.#_.getProgram(),J=$.getSourceFile(_);if(!J)return[];let Q=$.getTypeChecker(),z=new Map,W=(Y)=>{if(p.isIdentifier(Y)&&!MQ(Y)){let X=BQ(Y,Q);if(X){let M=z.get(X);if(M)M.push(Y);else z.set(X,[Y])}}p.forEachChild(Y,W)};p.forEachChild(J,W);let Z=[];for(let[Y,X]of z){let M=Y.declarations;if(!M||M.length===0)continue;if(M.every(LQ))continue;let O=M.every(u0),L=new Set(M.map((G)=>p.getNameOfDeclaration(G)).filter((G)=>G!==void 0)),D=M[0],N=p.getNameOfDeclaration(D)??D,w=D.getSourceFile(),R=X.map((G)=>{let F=G.getStart(J),{line:u,character:E}=J.getLineAndCharacterOfPosition(F),y=P0(G);return{filePath:J.fileName,position:F,line:u+1,column:E,isDefinition:L.has(G),isWrite:y!==void 0,writeKind:y,isAmbient:O,enclosingScope:b0(G)}});Z.push({declaration:{filePath:w.fileName,position:N.getStart(w),name:Y.getName(),isAmbient:O},references:R})}return Z}#$(_,$){if(this.#_.isDisposed)return null;let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let z=e(Q,$);if(!z||!p.isIdentifier(z))return null;let W=this.#_.getLanguageService().findReferences(_,$);if(!W||W.length===0)return null;return W}#J(_,$,J){let Q=_.definition,z=$.getSourceFile(Q.fileName);if(!z)return!1;let W=e(z,Q.textSpan.start);if(!W)return!1;let Y=J.getSymbolAtLocation(W)?.declarations;if(!Y||Y.length===0)return!1;return Y.every(u0)}}function MQ(_){let $=_.parent;return p.isPropertyAccessExpression($)&&$.name===_||p.isQualifiedName($)&&$.right===_||p.isPropertyAssignment($)&&$.name===_||p.isBindingElement($)&&$.propertyName===_||p.isJsxAttribute($)&&$.name===_||p.isImportSpecifier($)&&$.propertyName===_||p.isModuleDeclaration($)&&$.name===_&&($.flags&p.NodeFlags.GlobalAugmentation)!==0}function LQ(_){return p.isPropertyDeclaration(_)||p.isPropertySignature(_)||p.isMethodDeclaration(_)||p.isMethodSignature(_)||p.isGetAccessorDeclaration(_)||p.isSetAccessorDeclaration(_)||p.isEnumMember(_)||p.isParameter(_)&&p.isIndexSignatureDeclaration(_.parent)}function BQ(_,$){let J=_.parent;if(p.isShorthandPropertyAssignment(J))return $.getShorthandAssignmentValueSymbol(J);if(p.isExportSpecifier(J)){let Q=J.parent.parent;if(p.isExportDeclaration(Q)&&Q.moduleSpecifier)return;return(J.propertyName??J.name)===_?$.getExportSpecifierLocalTargetSymbol(J):void 0}return $.getSymbolAtLocation(_)}function I1(_,$){let{line:J,character:Q}=$.getLineAndCharacterOfPosition(_.textSpan.start);return{filePath:_.fileName,position:_.textSpan.start,line:J+1,column:Q,isDefinition:_.isDefinition??!1,isWrite:_.isWriteAccess??!1}}import h from"typescript";function wQ(_,$){let J=e(_,$);if(!J)return;if(C1(J))return J;let Q=J.parent;for(let z=0;z<5&&Q;z++){if(C1(Q))return Q;Q=Q.parent}return J}function C1(_){return h.isClassDeclaration(_)||h.isClassExpression(_)||h.isFunctionDeclaration(_)||h.isFunctionExpression(_)||h.isArrowFunction(_)||h.isVariableDeclaration(_)||h.isObjectLiteralExpression(_)}function D1(_){if(h.isClassDeclaration(_)||h.isClassExpression(_))return"class";if(h.isFunctionDeclaration(_)||h.isFunctionExpression(_)||h.isArrowFunction(_))return"function";if(h.isObjectLiteralExpression(_))return"object";if(h.isVariableDeclaration(_)&&_.initializer)return D1(_.initializer);return"class"}function IQ(_,$){if(h.isClassDeclaration(_)||h.isFunctionDeclaration(_))return _.name?.getText($)??"";if(h.isClassExpression(_))return _.name?.getText($)??"";if(h.isVariableDeclaration(_)&&h.isIdentifier(_.name))return _.name.getText($);if(h.isFunctionExpression(_))return _.name?.getText($)??"";if(h.isArrowFunction(_)&&_.parent&&h.isVariableDeclaration(_.parent)){if(h.isIdentifier(_.parent.name))return _.parent.name.getText($)}if(h.isObjectLiteralExpression(_)&&_.parent&&h.isVariableDeclaration(_.parent)){if(h.isIdentifier(_.parent.name))return _.parent.name.getText($)}return""}function CQ(_){if(!h.isClassDeclaration(_)&&!h.isClassExpression(_))return!1;let $=_.heritageClauses;if(!$)return!1;return $.some((J)=>J.token===h.SyntaxKind.ImplementsKeyword)}class y0{#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=e(Q,$);if(!z||!h.isIdentifier(z))return[];let Z=this.#_.getLanguageService().getImplementationAtPosition(_,$);if(!Z||Z.length===0)return[];let Y=[];for(let X of Z){if(X.kind===h.ScriptElementKind.interfaceElement||X.kind===h.ScriptElementKind.typeElement)continue;let M=J.getSourceFile(X.fileName);if(!M)continue;let O=wQ(M,X.textSpan.start);if(!O)continue;let L=D1(O),D=IQ(O,M),N=CQ(O);Y.push({filePath:X.fileName,symbolName:D,position:X.textSpan.start,kind:L,isExplicit:N})}return Y}}function AQ(_){if(__.isFunctionDeclaration(_))return"function";if(__.isClassDeclaration(_))return"class";if(__.isInterfaceDeclaration(_))return"interface";if(__.isTypeAliasDeclaration(_))return"type";if(__.isEnumDeclaration(_))return"enum";if(__.isVariableDeclaration(_))return"const";if(__.isVariableStatement(_))return"const";return"unknown"}function A1(_){if(_>=97&&_<=122)return!0;if(_>=65&&_<=90)return!0;if(_>=48&&_<=57)return!0;if(_===95||_===36)return!0;return!1}class W0{#_;#$;#J;#z;#W;#Y=!1;constructor(_,$,J,Q,z){this.#_=_,this.#$=$,this.#J=J,this.#z=Q,this.#W=z}static create(_,$={}){let J=J0.create(_,{readConfigFile:$.readConfigFile,resolveNonTrackedFile:$.resolveNonTrackedFile});if(DQ(J))return J;let Q=J,z=$.typeCollector??new E0(Q),W=$.symbolGraph??new v0(Q),Z=$.referenceResolver??new f0(Q),Y=$.implementationFinder??new y0(Q);return new W0(Q,z,W,Z,Y)}get isDisposed(){return this.#Y}collectTypeAt(_,$){return this.#Q(),this.#$.collectAt(_,$)}collectFileTypes(_){return this.#Q(),this.#$.collectFile(_)}collectTypesAtPositions(_,$){return this.#Q(),this.#$.collectAtPositions(_,$)}findReferences(_,$){return this.#Q(),this.#z.findAt(_,$)}findEnrichedReferences(_,$){return this.#Q(),this.#z.findEnrichedAt(_,$)}getFileBindings(_){return this.#Q(),this.#z.findFileBindings(_)}getFileBindingsBatch(_){this.#Q();for(let J of _)this.notifyFileChanged(J.filePath,J.content);let $=new Map;for(let J of _)$.set(J.filePath,this.#z.findFileBindings(J.filePath));return $}findImplementations(_,$){return this.#Q(),this.#W.findAt(_,$)}isTypeAssignableTo(_,$,J,Q){return this.#Q(),this.#$.isAssignableTo(_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return this.#Q(),this.#$.isAssignableToType(_,$,J,Q)}isTypeAssignableToTypeAtPositions(_,$,J,Q){return this.#Q(),this.#$.isAssignableToTypeAtPositions(_,$,J,Q)}getSymbolNode(_,$){return this.#Q(),this.#J.get(_,$)}getBaseTypes(_,$){this.#Q();let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return null;let z=e(Q,$);if(!z)return null;let W=J.getTypeChecker(),Z=W.getTypeAtLocation(z);if(!(Z.flags&__.TypeFlags.Object)||!(Z.objectFlags&__.ObjectFlags.ClassOrInterface))return null;let Y=W.getBaseTypes(Z);if(!Y||Y.length===0)return[];let X=new Map;return Y.map((M)=>L_(W,M,0,X))}getModuleInterface(_){this.#Q();let $=[],J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return{filePath:_,exports:$};let z=J.getTypeChecker(),W=z.getSymbolAtLocation(Q);if(W){let Z=z.getExportsOfModule(W),Y=new Map;for(let X of Z){let M=X.getName(),O=X.declarations?.[0],L="unknown";if(O){if(L=AQ(O),L==="unknown"&&__.isExportAssignment(O))L="const"}let D=null;try{let N=z.getTypeOfSymbolAtLocation(X,O??Q);D=L_(z,N,0,Y)}catch{}$.push({name:M,kind:L,resolvedType:D})}}return{filePath:_,exports:$}}notifyFileChanged(_,$){if(this.#Y)return;this.#_.notifyFileChanged(_,$),this.#J.clear()}notifyFileDeleted(_){if(this.#Y)return;this.#_.removeFile(_),this.#J.clear()}lineColumnToPosition(_,$,J){this.#Q();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;try{return __.getPositionOfLineAndCharacter(Q,$-1,J)}catch{return null}}findNamePosition(_,$,J){this.#Q();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let z=Q.getFullText(),W=$;while(W<z.length){let Z=z.indexOf(J,W);if(Z<0)return null;let Y=Z>0?z.charCodeAt(Z-1):32,X=Z+J.length<z.length?z.charCodeAt(Z+J.length):32;if(!A1(Y)&&!A1(X))return Z;W=Z+1}return null}getDiagnostics(_,$){this.#Q();let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z={[__.DiagnosticCategory.Error]:"error",[__.DiagnosticCategory.Warning]:"warning",[__.DiagnosticCategory.Suggestion]:"suggestion",[__.DiagnosticCategory.Message]:"suggestion"};return(($?.preEmit)?__.getPreEmitDiagnostics(J,Q):J.getSemanticDiagnostics(Q)).map((Z)=>{let Y=1,X=0;if(Z.file&&Z.start!==void 0){let M=__.getLineAndCharacterOfPosition(Z.file,Z.start);Y=M.line+1,X=M.character}return{filePath:Z.file?.fileName??_,line:Y,column:X,message:__.flattenDiagnosticMessageText(Z.messageText,`
|
|
10
|
-
`),code:Z.code,category:z[Z.category]??"error"}})}dispose(){if(this.#Y)return;this.#Y=!0,this.#$.clearProbe(),this.#_.dispose(),this.#J.clear()}#Q(){if(this.#Y)throw Error("SemanticLayer is disposed")}}import{eq as F_,and as q1,sql as qQ}from"drizzle-orm";var N1=80;class x0{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+=N1)this.db.drizzleDb.insert(Z_).values(Q.slice(z,z+N1)).run()}deleteFileAnnotations(_,$){this.db.drizzleDb.delete(Z_).where(q1(F_(Z_.project,_),F_(Z_.filePath,$))).run()}search(_){let $=this.db.drizzleDb.select().from(Z_).where(q1(_.project?F_(Z_.project,_.project):void 0,_.tag?F_(Z_.tag,_.tag):void 0,_.filePath?F_(Z_.filePath,_.filePath):void 0,_.symbolName?F_(Z_.symbolName,_.symbolName):void 0,_.source?F_(Z_.source,_.source):void 0,_.ftsQuery?qQ`${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 b_,and as R1,sql as i_,gt as NQ,gte as RQ}from"drizzle-orm";var T1=80;class h0{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+=T1)this.db.drizzleDb.insert($_).values($.slice(J,J+T1)).run()}getSince(_){return this.db.drizzleDb.select().from($_).where(R1(b_($_.project,_.project),RQ($_.changedAt,_.since),_.symbolName?b_($_.symbolName,_.symbolName):void 0,_.changeTypes?.length?i_`${$_.changeType} IN (${i_.join(_.changeTypes.map(($)=>i_`${$}`),i_`, `)})`:void 0,_.filePath?b_($_.filePath,_.filePath):void 0,_.includeFullIndex?void 0:b_($_.isFullIndex,0),_.indexRunId?b_($_.indexRunId,_.indexRunId):void 0,_.afterId?NQ($_.id,_.afterId):void 0)).orderBy($_.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete($_).where(R1(b_($_.project,_),i_`${$_.changedAt} < ${$}`)).run().changes}}function S1(_){let{annotationRepo:$,project:J,query:Q}=_,z=Q.project??J,W;if(Q.text){let Y=k_(Q.text);if(Y)W=Y}return $.search({project:z,tag:Q.tag,filePath:Q.filePath,symbolName:Q.symbolName,source:Q.source,ftsQuery:W,limit:Q.limit}).map((Y)=>({tag:Y.tag,value:Y.value,source:Y.source,filePath:Y.filePath,symbolName:Y.symbolName,span:{start:{line:Y.startLine,column:Y.startColumn},end:{line:Y.endLine,column:Y.endColumn}}}))}class Y0{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(_){this.options=_}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let $=[this.options.project,...this.options.additionalProjects??[]].flatMap((J)=>[...this.options.relationRepo.getByType(J,"imports"),...this.options.relationRepo.getByType(J,"type-references"),...this.options.relationRepo.getByType(J,"re-exports")]);for(let J of $){let{srcFilePath:Q,dstFilePath:z}=J;if(z===null)continue;if(!this.adjacencyList.has(Q))this.adjacencyList.set(Q,new Set);if(this.adjacencyList.get(Q).add(z),!this.adjacencyList.has(z))this.adjacencyList.set(z,new Set);if(!this.reverseAdjacencyList.has(z))this.reverseAdjacencyList.set(z,new Set);this.reverseAdjacencyList.get(z).add(Q)}}patchFiles(_,$,J){let Q=new Set([..._,...$]);for(let z of Q){let W=this.adjacencyList.get(z);if(W){for(let Y of W)this.reverseAdjacencyList.get(Y)?.delete(z);W.clear()}let Z=this.reverseAdjacencyList.get(z);if(Z){for(let Y of Z)this.adjacencyList.get(Y)?.delete(z);Z.clear()}}for(let z of $)this.adjacencyList.delete(z),this.reverseAdjacencyList.delete(z);for(let z of _){let W=J(z);for(let Z of W){if(!this.adjacencyList.has(Z.srcFilePath))this.adjacencyList.set(Z.srcFilePath,new Set);if(this.adjacencyList.get(Z.srcFilePath).add(Z.dstFilePath),!this.adjacencyList.has(Z.dstFilePath))this.adjacencyList.set(Z.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(Z.dstFilePath))this.reverseAdjacencyList.set(Z.dstFilePath,new Set);this.reverseAdjacencyList.get(Z.dstFilePath).add(Z.srcFilePath)}}}getDependencies(_){return Array.from(this.adjacencyList.get(_)??[])}getDependents(_){return Array.from(this.reverseAdjacencyList.get(_)??[])}getTransitiveDependents(_){let $=new Set,J=[_];while(J.length>0){let Q=J.shift();for(let z of this.reverseAdjacencyList.get(Q)??[])if(!$.has(z))$.add(z),J.push(z)}return Array.from($)}hasCycle(){let _=new Set,$=new Set;for(let J of this.adjacencyList.keys()){if(_.has(J))continue;let Q=[{node:J,entered:!1}];while(Q.length>0){let z=Q.pop();if(z.entered){$.delete(z.node);continue}if($.has(z.node))return!0;if(_.has(z.node))continue;_.add(z.node),$.add(z.node),Q.push({node:z.node,entered:!0});for(let W of this.adjacencyList.get(z.node)??[]){if($.has(W))return!0;if(!_.has(W))Q.push({node:W,entered:!1})}}}return!1}getAffectedByChange(_){let $=new Set;for(let J of _)for(let Q of this.getTransitiveDependents(J))$.add(Q);return Array.from($)}getAdjacencyList(){let _=new Map;for(let[$,J]of this.adjacencyList)_.set($,Array.from(J));return _}getTransitiveDependencies(_){let $=new Set,J=[_];while(J.length>0){let Q=J.shift();for(let z of this.adjacencyList.get(Q)??[])if(!$.has(z))$.add(z),J.push(z)}return Array.from($)}getCyclePaths(_){let $=_?.maxCycles??1/0;if($<=0)return[];let J=new Map;for(let[Q,z]of this.adjacencyList)J.set(Q,Array.from(z));return jQ(J,$)}}var TQ=(_,$)=>_.localeCompare($);function SQ(_){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 m0(_,$,J){let Q=SQ(J);if(Q.length===0)return!1;let z=Q.join("->");if(_.has(z))return!1;return _.add(z),$.push(Q),!0}function FQ(_){let $=0,J=[],Q=new Set,z=new Map,W=new Map,Z=[],Y=(X)=>{z.set(X,$),W.set(X,$),$+=1,J.push(X),Q.add(X);for(let M of _.get(X)??[])if(!z.has(M))Y(M),W.set(X,Math.min(W.get(X)??0,W.get(M)??0));else if(Q.has(M))W.set(X,Math.min(W.get(X)??0,z.get(M)??0));if(W.get(X)===z.get(X)){let M=[],O="";do O=J.pop()??"",Q.delete(O),M.push(O);while(O!==X&&J.length>0);Z.push(M)}};for(let X of _.keys())if(!z.has(X))Y(X);return{components:Z}}function GQ(_,$,J){let Q=[],z=new Set,W=[..._].sort(TQ),Z=(Y,X,M)=>{X.delete(Y);let O=M.get(Y);if(!O)return;for(let L of O)if(X.has(L))Z(L,X,M);O.clear()};for(let Y=0;Y<W.length&&Q.length<J;Y++){let X=W[Y]??"",M=new Set(W.slice(Y)),O=new Set,L=new Map,D=[],N=(R)=>($.get(R)??[]).filter((G)=>M.has(G)),w=(R)=>{if(Q.length>=J)return!0;let G=!1;D.push(R),O.add(R);for(let F of N(R)){if(Q.length>=J)break;if(F===X)m0(z,Q,D.concat(X)),G=!0;else if(!O.has(F)){if(w(F))G=!0}}if(G)Z(R,O,L);else for(let F of N(R)){let u=L.get(F)??new Set;u.add(R),L.set(F,u)}return D.pop(),G};w(X)}return Q}function jQ(_,$){let{components:J}=FQ(_),Q=[],z=new Set;for(let W of J){if(Q.length>=$)break;if(W.length===0)continue;if(W.length===1){let X=W[0]??"";if((_.get(X)??[]).includes(X))m0(z,Q,[X,X]);continue}let Z=$-Q.length,Y=GQ(W,_,Z);for(let X of Y){if(Q.length>=$)break;m0(z,Q,X)}}return Q}var kQ=15000;function Z0(_){_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}function G_(_,$){let J=$??"__cross__";if(_.graphCache&&_.graphCacheBuiltAt!==null){if(Date.now()-_.graphCacheBuiltAt>kQ)_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}if(_.graphCache&&_.graphCacheKey===J)return _.graphCache;let Q=new Y0({relationRepo:_.relationRepo,project:$??_.defaultProject,additionalProjects:$?void 0:_.boundaries?.map((z)=>z.project)});return Q.build(),_.graphCache=Q,_.graphCacheKey=J,_.graphCacheBuiltAt=Date.now(),Q}function F1(_,$,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 G1(_,$,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 j1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return G_(_,J).getAffectedByChange($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getAffected failed",{cause:Q})}}async function k1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return G_(_,$).hasCycle()}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: hasCycle failed",{cause:J})}}async function g1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return G_(_,$).getAdjacencyList()}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: getImportGraph failed",{cause:J})}}async function E1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return G_(_,J).getTransitiveDependencies($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getTransitiveDependencies failed",{cause:Q})}}async function v1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return G_(_,J).getTransitiveDependents($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getTransitiveDependents failed",{cause:Q})}}async function u1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return G_(_,$).getCyclePaths(J)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getCyclePaths failed",{cause:Q})}}async function b1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=G_(_,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 vQ=30000,P1=15000,uQ=10;function bQ(_,$){_.boundaries=$,_.defaultProject=$[0]?.project??P_.basename(_.projectRoot)}function PQ(_,$){return(J)=>{for(let Q of _.onFileChangedCallbacks)try{Q(J)}catch(z){_.logger.error("[Gildash] onFileChanged callback threw:",z)}if($.handleWatcherEvent?.(J),_.semanticLayer)if(J.eventType==="delete")try{_.semanticLayer.notifyFileDeleted(J.filePath)}catch(Q){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",Q);for(let z of _.onErrorCallbacks)try{z(Q instanceof V?Q:new V("semantic","semantic notifyFileDeleted failed",{cause:Q}))}catch{}}else _.readFileFn(J.filePath).then((Q)=>{try{_.semanticLayer?.notifyFileChanged(J.filePath,Q)}catch(z){_.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",z);for(let W of _.onErrorCallbacks)try{W(z instanceof V?z:new V("semantic","semantic notifyFileChanged failed",{cause:z}))}catch{}}}).catch((Q)=>{_.logger.error("[Gildash] failed to read file for semantic layer",J.filePath,Q);try{_.semanticLayer?.notifyFileDeleted(J.filePath)}catch(z){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",z)}})}}async function fQ(_){if(!_.semanticLayer)return;let $=_.fileRepo.getAllFiles(_.defaultProject);await Promise.all($.map(async(J)=>{try{let Q=P_.resolve(_.projectRoot,J.filePath),z=await _.readFileFn(Q);_.semanticLayer?.notifyFileChanged(Q,z)}catch{}}))}async function f1(_,$){let J=_.coordinatorFactory?_.coordinatorFactory():new T0({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)=>bQ(_,Q),logger:_.logger});_.coordinator=J;for(let Q of _.onIndexedCallbacks)J.onIndexed(Q);if(J.onIndexed((Q)=>{let z=Q.changedFiles.length+Q.deletedFiles.length;if(_.graphCache&&z>0&&z<100){let W=_.relationRepo;_.graphCache.patchFiles(Q.changedFiles,Q.deletedFiles,(Z)=>{return[_.defaultProject,..._.boundaries.map((X)=>X.project)].flatMap((X)=>W.getByType(X,"imports").concat(W.getByType(X,"type-references")).concat(W.getByType(X,"re-exports"))).filter((X)=>X.dstFilePath!==null&&(X.srcFilePath===Z||X.dstFilePath===Z)).map((X)=>({srcFilePath:X.srcFilePath,dstFilePath:X.dstFilePath}))}),_.graphCacheBuiltAt=Date.now()}else Z0(_)}),$.isWatchMode){let Q=_.watcherFactory?_.watcherFactory():new w0({projectRoot:_.projectRoot,ignorePatterns:_.ignorePatterns,extensions:_.extensions},void 0,_.logger);await Q.start(PQ(_,J)).then((z)=>{if(c_(z))throw z.data}),_.watcher=Q,_.timer=setInterval(()=>{if(_.closed)return;_.updateHeartbeatFn(_.db,process.pid)},vQ)}await J.fullIndex(),await fQ(_)}function yQ(_,$){let J=["SIGTERM","SIGINT","beforeExit"];for(let Q of J){let z=()=>{$().catch((W)=>_.logger.error("[Gildash] close error during signal",Q,W))};if(Q==="beforeExit")process.on("beforeExit",z);else process.on(Q,z);_.signalHandlers.push([Q,z])}}async function y1(_){let{projectRoot:$,extensions:J=[".ts",".mts",".cts"],ignorePatterns:Q=["**/node_modules/**"],parseCacheCapacity:z=500,logger:W=console,existsSyncFn:Z=EQ,dbConnectionFactory:Y,watcherFactory:X,coordinatorFactory:M,repositoryFactory:O,acquireWatcherRoleFn:L=K1,releaseWatcherRoleFn:D=M1,updateHeartbeatFn:N=L1,discoverProjectsFn:w=r_,parseSourceFn:R=E_,extractSymbolsFn:G=R_,extractRelationsFn:F=d_,symbolSearchFn:u=F0,relationSearchFn:E=G0,patternSearchFn:y=j0,loadTsconfigPathsFn:l=n_,readFileFn:i=async(s)=>Bun.file(s).text(),unlinkFn:W_=async(s)=>{await Bun.file(s).unlink()},watchMode:X_,semantic:K_,semanticLayerFactory:U_}=_;if(!P_.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 Y_=Y?Y():new H0({projectRoot:$}),c=Y_.open();if(c_(c))throw c.data;try{let s=await w($),C_=s[0]?.project??P_.basename($),C=O?O():(()=>{let S=Y_;return{fileRepo:new K0(S),symbolRepo:new M0(S),relationRepo:new L0(S),parseCache:new S0(z)}})(),q=O?null:Y_,U=q?new x0(q):null,H=q?new h0(q):null,K=X_??!0,B=crypto.randomUUID(),A;if(K)A=await Promise.resolve(L(Y_,process.pid,{instanceId:B}));else A="owner";let I={projectRoot:$,extensions:J,ignorePatterns:Q,logger:W,defaultProject:C_,role:A,db:Y_,symbolRepo:C.symbolRepo,relationRepo:C.relationRepo,fileRepo:C.fileRepo,parseCache:C.parseCache,annotationRepo:U,changelogRepo:H,annotationSearchFn:S1,releaseWatcherRoleFn:D,parseSourceFn:R,extractSymbolsFn:G,extractRelationsFn:F,symbolSearchFn:u,relationSearchFn:E,patternSearchFn:y,readFileFn:i,unlinkFn:W_,existsSyncFn:Z,acquireWatcherRoleFn:L,updateHeartbeatFn:N,watcherFactory:X,coordinatorFactory:M,instanceId:B,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:s,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(o_($),I.tsconfigPaths=await l($),K_){let S=P_.join($,"tsconfig.json");try{if(U_)I.semanticLayer=U_(S);else{let T=W0.create(S);if(c_(T))throw T.data;I.semanticLayer=T}}catch(T){if(T instanceof V)throw T;throw new V("semantic","Gildash: semantic layer creation failed",{cause:T})}}if(A==="owner")await f1(I,{isWatchMode:K});else{let S=0,T=async()=>{try{let j=await Promise.resolve(I.acquireWatcherRoleFn(I.db,process.pid,{instanceId:I.instanceId}));if(S=0,j==="owner"){I.role="owner";for(let g of I.onRoleChangedCallbacks)try{g("owner")}catch(b){I.logger.error("[Gildash] onRoleChanged callback threw:",b)}clearInterval(I.timer),I.timer=null;try{await f1(I,{isWatchMode:!0})}catch(g){if(I.logger.error("[Gildash] owner promotion failed, reverting to reader",g),I.role="reader",I.timer!==null)clearInterval(I.timer),I.timer=null;if(I.watcher){let b=await I.watcher.close();if(c_(b))I.logger.error("[Gildash] watcher close error during promotion rollback",b.data);I.watcher=null}if(I.coordinator)await I.coordinator.shutdown().catch((b)=>I.logger.error("[Gildash] coordinator shutdown error during promotion rollback",b)),I.coordinator=null;try{I.releaseWatcherRoleFn(I.db,process.pid)}catch(b){I.logger.error("[Gildash] failed to release watcher role during promotion rollback",b)}I.timer=setInterval(T,P1)}}}catch(j){S++;let g=j instanceof V?j:new V("watcher","Gildash: healthcheck error",{cause:j});for(let b of I.onErrorCallbacks)try{b(g)}catch(d){I.logger.error("[Gildash] onError callback threw:",d)}if(I.logger.error("[Gildash] healthcheck error",j),S>=uQ)I.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(I.timer),I.timer=null,X0(I).catch((b)=>I.logger.error("[Gildash] close error during healthcheck shutdown",b))}};I.timer=setInterval(T,P1)}if(K)yQ(I,()=>X0(I));return I}catch(s){if(Y_.close(),s instanceof V)throw s;throw new V("store","Gildash: initialization failed",{cause:s})}}async function X0(_,$){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(c_(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(P_.join(_.projectRoot,A_,a_+Q))}catch{}if(J.length>0)throw new V("close","Gildash: one or more errors occurred during close()",{cause:J})}import{isErr as x1}from"@zipbul/result";function h1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");let z=_.parseSourceFn($,J,Q);if(x1(z))throw z.data;return _.parseCache.set($,z),z}async function m1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");let Q=new Map,z=[];return await Promise.all($.map(async(W)=>{try{let Z=await _.readFileFn(W),Y=_.parseSourceFn(W,Z,J);if(!x1(Y))Q.set(W,Y);else z.push({filePath:W,error:Y.data})}catch(Z){z.push({filePath:W,error:Z instanceof Error?Z:Error(String(Z))})}})),{parsed:Q,failures:z}}function n1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.parseCache.get($)}function p1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.extractSymbolsFn($)}function d1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.extractRelationsFn($.program,$.filePath,_.tsconfigPaths??void 0)}import l1 from"path";function i1(_,$){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 n0(_,$){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 c1(_,$){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 a1(_,$){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 s1(_,$){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 r1(_,$){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 o1(_,$,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 t1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,W=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:J,limit:1}});if(W.length===0)return null;let Z=W[0],Y=Z.detail,X={...Z,members:Y.members,jsDoc:Y.jsDoc,parameters:Y.parameters,returnType:Y.returnType,heritage:Y.heritage,decorators:Y.decorators,typeParameters:Y.typeParameters,initializer:Y.initializer};if(_.semanticLayer)try{let M=l1.isAbsolute(J)?J:l1.resolve(_.projectRoot,J),O=_.semanticLayer.lineColumnToPosition(M,Z.span.start.line,Z.span.start.column);if(O!==null){let L=_.semanticLayer.findNamePosition(M,O,Z.name)??O,D=_.semanticLayer.collectTypeAt(M,L);if(D)X.resolvedType=D}}catch{}return X}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getFullSymbol failed",{cause:z})}}function e1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=J??_.defaultProject,z=_.fileRepo.getFile(Q,$);if(!z)throw new V("search",`Gildash: file '${$}' is not in the index`);let W=_.symbolRepo.getFileSymbols(Q,$),Z=_.relationRepo.getOutgoing(Q,$);return{filePath:z.filePath,lineCount:z.lineCount??0,size:z.size,symbolCount:W.length,exportedSymbolCount:W.filter((Y)=>Y.isExported).length,relationCount:Z.length}}catch(Q){if(Q instanceof V)throw Q;throw new V("store","Gildash: getFileStats failed",{cause:Q})}}function _$(_,$,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 $$(_,$,J){return n0(_,{filePath:$,project:J??void 0,limit:1e4})}function J$(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:J??_.defaultProject,query:{filePath:$,isExported:!0}}).map((W)=>({name:W.name,kind:W.kind,parameters:W.detail.parameters?`(${W.detail.parameters.map((Z)=>`${Z.name}${Z.isOptional?"?":""}: ${Z.type??"unknown"}`).join(", ")})`:void 0,returnType:W.detail.returnType??void 0,jsDoc:W.detail.jsDoc?.description??void 0}));return{filePath:$,exports:z}}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getModuleInterface failed",{cause:Q})}}import P from"path";function f_(_,$,J,Q){let z=Q??_.defaultProject,W=P.isAbsolute(J)?P.relative(_.projectRoot,J):J,Z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:W,limit:1}});if(Z.length===0)return null;let Y=Z[0],X=P.isAbsolute(J)?J:P.resolve(_.projectRoot,J),M=_.semanticLayer.lineColumnToPosition(X,Y.span.start.line,Y.span.start.column);if(M===null)return null;let O=_.semanticLayer.findNamePosition(X,M,Y.name)??M;return{sym:Y,position:O,absPath:X}}function Q$(_,$,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=f_(_,$,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 z$(_,$,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=f_(_,$,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 W$(_,$,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=f_(_,$,J,Q);if(!z)throw new V("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findEnrichedReferences(z.absPath,z.position)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getEnrichedReferences failed",{cause:z})}}function Y$(_,$,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=f_(_,$,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 Z$(_,$,J,Q,z,W){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Z=f_(_,$,J,W);if(!Z)throw new V("search",`Gildash: source symbol '${$}' not found in '${J}'`);let Y=f_(_,Q,z,W);if(!Y)throw new V("search",`Gildash: target symbol '${Q}' not found in '${z}'`);return _.semanticLayer.isTypeAssignableTo(Z.absPath,Z.position,Y.absPath,Y.position)}catch(Z){if(Z instanceof V)throw Z;throw new V("semantic","Gildash: isTypeAssignableTo failed",{cause:Z})}}function X$(_,$){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 U$(_,$,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,$),W=_.semanticLayer.lineColumnToPosition(z,J,Q);if(W===null)return null;return _.semanticLayer.collectTypeAt(z,W)}catch(z){if(z instanceof V)throw z;throw new V("semantic","Gildash: getResolvedTypeAt failed",{cause:z})}}function V$(_,$){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 W=_.semanticLayer.lineColumnToPosition(Q,$.target.line,$.target.column);if(W===null)return null;return _.semanticLayer.isTypeAssignableTo(J,z,Q,W)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: isTypeAssignableToAt failed",{cause:J})}}function O$(_,$){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 H$(_,$,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 K$(_,$,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 M$(_,$,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 L$(_,$,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 B$(_,$,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.findEnrichedReferences(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getEnrichedReferencesAtPosition failed",{cause:Q})}}function w$(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let J=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.getFileBindings(J)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: getFileBindings failed",{cause:J})}}function I$(_,$){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=$.map((W)=>({orig:W.filePath,abs:P.isAbsolute(W.filePath)?W.filePath:P.resolve(_.projectRoot,W.filePath),content:W.content})),Q=_.semanticLayer.getFileBindingsBatch(J.map((W)=>({filePath:W.abs,content:W.content}))),z=new Map;for(let W of J)z.set(W.orig,Q.get(W.abs)??[]);return z}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: getFileBindingsBatch failed",{cause:J})}}function C$(_,$,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,$);_.semanticLayer.notifyFileChanged(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: notifyFileChanged failed",{cause:Q})}}function D$(_,$){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,$);_.semanticLayer.notifyFileDeleted(J)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: notifyFileDeleted failed",{cause:J})}}function A$(_,$,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 q$(_,$,J,Q,z){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let W=P.isAbsolute($)?$:P.resolve(_.projectRoot,$),Z=P.isAbsolute(Q)?Q:P.resolve(_.projectRoot,Q);return _.semanticLayer.isTypeAssignableTo(W,J,Z,z)}catch(W){if(W instanceof V)throw W;throw new V("semantic","Gildash: isTypeAssignableToAtPosition failed",{cause:W})}}function N$(_,$,J,Q,z){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let W=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToType(W,J,Q,z)}catch(W){if(W instanceof V)throw W;throw new V("semantic","Gildash: isTypeAssignableToType failed",{cause:W})}}function R$(_,$,J,Q,z){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let W=P.isAbsolute($)?$:P.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtPositions(W,J,Q,z)}catch(W){if(W instanceof V)throw W;throw new V("semantic","Gildash: isTypeAssignableToTypeAtPositions failed",{cause:W})}}function T$(_,$,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 S$(_,$,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 F$(_,$,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 G$(_,$,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 j$(_,$){let J=new Map(_.map((Y)=>[`${Y.name}::${Y.filePath}`,Y])),Q=new Map($.map((Y)=>[`${Y.name}::${Y.filePath}`,Y])),z=[],W=[],Z=[];for(let[Y,X]of Q){let M=J.get(Y);if(!M)z.push(X);else if(M.fingerprint!==X.fingerprint)Z.push({before:M,after:X})}for(let[Y,X]of J)if(!Q.has(Y))W.push(X);return{added:z,removed:W,modified:Z}}function k$(_,$){if(_.onIndexedCallbacks.add($),!_.coordinator)return()=>{_.onIndexedCallbacks.delete($)};let J=_.coordinator.onIndexed($);return()=>{_.onIndexedCallbacks.delete($),J()}}async function g$(_){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 Z0(_),$}catch($){if($ instanceof V)throw $;throw new V("index","Gildash: reindex failed",{cause:$})}}function E$(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");let z=Q??_.defaultProject,W=new Set,Z=[],Y=$,X=J;for(;;){let M=`${X}::${Y}`;if(W.has(M))return{originalName:Y,originalFilePath:X,reExportChain:Z,circular:!0};W.add(M);let O=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{type:"re-exports",srcFilePath:X,limit:500}}),L,D;for(let N of O){let w;if(N.metaJson)try{let G=JSON.parse(N.metaJson);if(Array.isArray(G.specifiers))w=G.specifiers}catch{}if(!w)continue;let R=w.find((G)=>G.exported===Y);if(!R)continue;L=N.dstFilePath??void 0,D=R.local;break}if(!L||!D)return{originalName:Y,originalFilePath:X,reExportChain:Z,circular:!1};Z.push({filePath:X,exportedAs:Y}),X=L,Y=D}}function v$(_,$){return _.onFileChangedCallbacks.add($),()=>{_.onFileChangedCallbacks.delete($)}}function u$(_,$){return _.onErrorCallbacks.add($),()=>{_.onErrorCallbacks.delete($)}}function b$(_,$){return _.onRoleChangedCallbacks.add($),()=>{_.onRoleChangedCallbacks.delete($)}}async function P$(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=J?.project??_.defaultProject,z=J?.filePaths?J.filePaths:_.fileRepo.getAllFiles(Q).map((W)=>W.filePath);return await _.patternSearchFn({pattern:$,filePaths:z})}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: findPattern failed",{cause:Q})}}async function f$(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,W=new Set,Z=(Y,X,M)=>{let O=`${Y}::${X}`;if(W.has(O))return{symbolName:Y,filePath:X,kind:M,children:[]};W.add(O);let N=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{srcFilePath:X,srcSymbolName:Y,limit:1000}}).filter((w)=>w.type==="extends"||w.type==="implements").filter((w)=>w.dstSymbolName!=null&&w.dstFilePath!=null).map((w)=>Z(w.dstSymbolName,w.dstFilePath,w.type));return{symbolName:Y,filePath:X,kind:M,children:N}};return Z($,J)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getHeritageChain failed",{cause:z})}}function y$(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.annotationRepo||!_.annotationSearchFn)return[];return _.annotationSearchFn({annotationRepo:_.annotationRepo,project:$.project??_.defaultProject,query:$})}function x$(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.changelogRepo)return[];let Q=$ instanceof Date?$.toISOString():$,z=J?.project??_.defaultProject,W=J?.limit??1000;return _.changelogRepo.getSince({project:z,since:Q,symbolName:J?.symbolName,changeTypes:J?.changeTypes,filePath:J?.filePath,includeFullIndex:J?.includeFullIndex,indexRunId:J?.indexRunId,afterId:J?.afterId,limit:W}).map((Y)=>({changeType:Y.changeType,symbolName:Y.symbolName,symbolKind:Y.symbolKind,filePath:Y.filePath,oldName:Y.oldName,oldFilePath:Y.oldFilePath,fingerprint:Y.fingerprint,changedAt:Y.changedAt,isFullIndex:Y.isFullIndex===1,indexRunId:Y.indexRunId}))}function h$(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.changelogRepo)return 0;let J=$ instanceof Date?$.toISOString():$,Q=0,z=[_.defaultProject,..._.boundaries.map((Z)=>Z.project)],W=[...new Set(z)];for(let Z of W)Q+=_.changelogRepo.pruneOlderThan(Z,J);return Q}class p0{_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 y1(_);return new p0($)}async close(_){return X0(this._ctx,_)}parseSource(_,$,J){return h1(this._ctx,_,$,J)}async batchParse(_,$){return m1(this._ctx,_,$)}getParsedAst(_){return n1(this._ctx,_)}extractSymbols(_){return p1(this._ctx,_)}extractRelations(_){return d1(this._ctx,_)}getStats(_){return i1(this._ctx,_)}searchSymbols(_){return n0(this._ctx,_)}searchRelations(_){return c1(this._ctx,_)}searchAllSymbols(_){return a1(this._ctx,_)}searchAllRelations(_){return s1(this._ctx,_)}listIndexedFiles(_){return r1(this._ctx,_)}getInternalRelations(_,$){return o1(this._ctx,_,$)}getFullSymbol(_,$,J){return t1(this._ctx,_,$,J)}getFileStats(_,$){return e1(this._ctx,_,$)}getFileInfo(_,$){return _$(this._ctx,_,$)}getSymbolsByFile(_,$){return $$(this._ctx,_,$)}getModuleInterface(_,$){return J$(this._ctx,_,$)}getDependencies(_,$,J=1e4){return F1(this._ctx,_,$,J)}getDependents(_,$,J=1e4){return G1(this._ctx,_,$,J)}async getAffected(_,$){return j1(this._ctx,_,$)}async hasCycle(_){return k1(this._ctx,_)}async getImportGraph(_){return g1(this._ctx,_)}async getTransitiveDependencies(_,$){return E1(this._ctx,_,$)}async getTransitiveDependents(_,$){return v1(this._ctx,_,$)}async getCyclePaths(_,$){return u1(this._ctx,_,$)}async getFanMetrics(_,$){return b1(this._ctx,_,$)}getResolvedType(_,$,J){return Q$(this._ctx,_,$,J)}getSemanticReferences(_,$,J){return z$(this._ctx,_,$,J)}getEnrichedReferences(_,$,J){return W$(this._ctx,_,$,J)}getImplementations(_,$,J){return Y$(this._ctx,_,$,J)}isTypeAssignableTo(_,$,J,Q,z){return Z$(this._ctx,_,$,J,Q,z)}getSemanticModuleInterface(_){return O$(this._ctx,_)}getFileTypes(_){return X$(this._ctx,_)}getResolvedTypeAt(_,$,J){return U$(this._ctx,_,$,J)}isTypeAssignableToAt(_){return V$(this._ctx,_)}getResolvedTypeAtPosition(_,$){return M$(this._ctx,_,$)}getResolvedTypesAtPositions(_,$){return K$(this._ctx,_,$)}getSemanticReferencesAtPosition(_,$){return L$(this._ctx,_,$)}getEnrichedReferencesAtPosition(_,$){return B$(this._ctx,_,$)}getFileBindings(_){return w$(this._ctx,_)}getFileBindingsBatch(_){return I$(this._ctx,_)}notifyFileChanged(_,$){C$(this._ctx,_,$)}notifyFileDeleted(_){D$(this._ctx,_)}getImplementationsAtPosition(_,$){return A$(this._ctx,_,$)}isTypeAssignableToAtPosition(_,$,J,Q){return q$(this._ctx,_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return N$(this._ctx,_,$,J,Q)}isTypeAssignableToTypeAtPositions(_,$,J,Q){return R$(this._ctx,_,$,J,Q)}lineColumnToPosition(_,$,J){return T$(this._ctx,_,$,J)}findNamePosition(_,$,J){return S$(this._ctx,_,$,J)}getSymbolNode(_,$){return F$(this._ctx,_,$)}getBaseTypes(_,$){return H$(this._ctx,_,$)}getSemanticDiagnostics(_,$){return G$(this._ctx,_,$)}diffSymbols(_,$){return j$(_,$)}onIndexed(_){return k$(this._ctx,_)}async reindex(){return g$(this._ctx)}resolveSymbol(_,$,J){return E$(this._ctx,_,$,J)}async findPattern(_,$){return P$(this._ctx,_,$)}async getHeritageChain(_,$,J){return f$(this._ctx,_,$,J)}onFileChanged(_){return v$(this._ctx,_)}onError(_){return u$(this._ctx,_)}onRoleChanged(_){return b$(this._ctx,_)}searchAnnotations(_){return y$(this._ctx,_)}getSymbolChanges(_,$){return x$(this._ctx,_,$)}pruneChangelog(_){return h$(this._ctx,_)}}import{Visitor as p5,visitorKeys as d5}from"oxc-parser";import{walk as i5,parseAndWalk as c5,ScopeTracker as a5}from"oxc-walker";export{i5 as walk,d5 as visitorKeys,F0 as symbolSearch,G0 as relationSearch,j0 as patternSearch,E_ as parseSource,c5 as parseAndWalk,z_ as normalizePath,pJ as isVariableDeclaration,nJ as isTSQualifiedName,mJ as isMemberExpression,hJ as isIdentifier,uJ as isFunctionNode,xJ as isFunctionExpression,yJ as isFunctionDeclaration,fJ as isCallExpression,PJ as isAssignmentExpression,bJ as isArrowFunctionExpression,dJ as is,O_ as getLineColumn,R_ as extractSymbols,d_ as extractRelations,p_ as buildLineOffsets,p5 as Visitor,a5 as ScopeTracker,V as GildashError,p0 as Gildash,Y0 as DependencyGraph};
|
|
2
|
+
var o$=Object.defineProperty;var t$=(_)=>_;function e$(_,$){this[_]=t$.bind(null,$)}var _J=(_,$)=>{for(var J in $)o$(_,J,{get:$[J],enumerable:!0,configurable:!0,set:e$.bind($,J)})};var s0=import.meta.require;import{isErr as a_}from"@zipbul/result";import P_ from"path";import{existsSync as hQ}from"fs";import{err as r0,isErr as YJ}from"@zipbul/result";import{Database as ZJ}from"bun:sqlite";import{mkdirSync as XJ,unlinkSync as o0,existsSync as t0}from"fs";import{dirname as UJ,join as e0}from"path";import{drizzle as VJ}from"drizzle-orm/bun-sqlite";import{migrate as OJ}from"drizzle-orm/bun-sqlite/migrator";class V extends Error{type;constructor(_,$,J){super($,J);this.type=_;this.name="GildashError"}}var A_=".gildash",s_="gildash.db";var L0={};_J(L0,{watcherOwner:()=>WJ,symbols:()=>y,symbolChangelog:()=>$_,relations:()=>u,files:()=>o,annotations:()=>Z_});import{sql as $J}from"drizzle-orm";import{sqliteTable as j_,text as f,integer as r,real as JJ,index as Q_,primaryKey as QJ,foreignKey as M0,check as zJ}from"drizzle-orm/sqlite-core";var o=j_("files",{project:f("project").notNull(),filePath:f("file_path").notNull(),mtimeMs:JJ("mtime_ms").notNull(),size:r("size").notNull(),contentHash:f("content_hash").notNull(),updatedAt:f("updated_at").notNull(),lineCount:r("line_count")},(_)=>[QJ({columns:[_.project,_.filePath]})]),y=j_("symbols",{id:r("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),filePath:f("file_path").notNull(),kind:f("kind").notNull(),name:f("name").notNull(),startLine:r("start_line").notNull(),startColumn:r("start_column").notNull(),endLine:r("end_line").notNull(),endColumn:r("end_column").notNull(),isExported:r("is_exported").notNull().default(0),signature:f("signature"),fingerprint:f("fingerprint"),detailJson:f("detail_json"),contentHash:f("content_hash").notNull(),indexedAt:f("indexed_at").notNull(),resolvedType:f("resolved_type"),structuralFingerprint:f("structural_fingerprint")},(_)=>[Q_("idx_symbols_project_file").on(_.project,_.filePath),Q_("idx_symbols_project_kind").on(_.project,_.kind),Q_("idx_symbols_project_name").on(_.project,_.name),Q_("idx_symbols_fingerprint").on(_.project,_.fingerprint),M0({columns:[_.project,_.filePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),u=j_("relations",{id:r("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),type:f("type").notNull(),srcFilePath:f("src_file_path").notNull(),srcSymbolName:f("src_symbol_name"),dstProject:f("dst_project"),dstFilePath:f("dst_file_path"),dstSymbolName:f("dst_symbol_name"),metaJson:f("meta_json"),specifier:f("specifier"),isExternal:r("is_external").notNull().default(0)},(_)=>[Q_("idx_relations_src").on(_.project,_.srcFilePath),Q_("idx_relations_dst").on(_.dstProject,_.dstFilePath),Q_("idx_relations_type").on(_.project,_.type),Q_("idx_relations_project_type_src").on(_.project,_.type,_.srcFilePath),Q_("idx_relations_specifier").on(_.project,_.specifier),M0({columns:[_.project,_.srcFilePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),Z_=j_("annotations",{id:r("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),filePath:f("file_path").notNull(),tag:f("tag").notNull(),value:f("value").notNull().default(""),source:f("source").notNull(),symbolName:f("symbol_name"),startLine:r("start_line").notNull(),startColumn:r("start_column").notNull(),endLine:r("end_line").notNull(),endColumn:r("end_column").notNull(),indexedAt:f("indexed_at").notNull()},(_)=>[Q_("idx_annotations_project_file").on(_.project,_.filePath),Q_("idx_annotations_project_tag").on(_.project,_.tag),Q_("idx_annotations_project_symbol").on(_.project,_.symbolName),M0({columns:[_.project,_.filePath],foreignColumns:[o.project,o.filePath]}).onDelete("cascade")]),$_=j_("symbol_changelog",{id:r("id").primaryKey({autoIncrement:!0}),project:f("project").notNull(),changeType:f("change_type").notNull(),symbolName:f("symbol_name").notNull(),symbolKind:f("symbol_kind").notNull(),filePath:f("file_path").notNull(),oldName:f("old_name"),oldFilePath:f("old_file_path"),fingerprint:f("fingerprint"),changedAt:f("changed_at").notNull(),isFullIndex:r("is_full_index").notNull().default(0),indexRunId:f("index_run_id").notNull()},(_)=>[Q_("idx_changelog_project_changed_at").on(_.project,_.changedAt),Q_("idx_changelog_project_name").on(_.project,_.symbolName),Q_("idx_changelog_project_run").on(_.project,_.indexRunId)]),WJ=j_("watcher_owner",{id:r("id").primaryKey(),pid:r("pid").notNull(),startedAt:f("started_at").notNull(),heartbeatAt:f("heartbeat_at").notNull(),instanceId:f("instance_id")},(_)=>[zJ("watcher_owner_singleton",$J`${_.id} = 1`)]);class B0{client=null;drizzle=null;dbPath;txDepth=0;constructor(_){this.dbPath=e0(_.projectRoot,A_,s_)}get drizzleDb(){if(!this.drizzle)throw Error("Database is not open. Call open() first.");return this.drizzle}open(){try{XJ(UJ(this.dbPath),{recursive:!0}),this.client=new ZJ(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=VJ(this.client,{schema:L0}),OJ(this.drizzle,{migrationsFolder:e0(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(_)&&t0(this.dbPath)){this.closeClient(),o0(this.dbPath);for(let J of["-wal","-shm"]){let Q=this.dbPath+J;if(t0(Q))o0(Q)}let $=this.open();if(YJ($))return r0(new V("store",`Failed to recover database at ${this.dbPath}`,{cause:$.data}));return $}return r0(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 y_,and as _1}from"drizzle-orm";class w0{db;constructor(_){this.db=_}getFile(_,$){return this.db.drizzleDb.select().from(o).where(_1(y_(o.project,_),y_(o.filePath,$))).get()??null}upsertFile(_){this.db.drizzleDb.insert(o).values({project:_.project,filePath:_.filePath,mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}).onConflictDoUpdate({target:[o.project,o.filePath],set:{mtimeMs:_.mtimeMs,size:_.size,contentHash:_.contentHash,updatedAt:_.updatedAt,lineCount:_.lineCount??null}}).run()}getAllFiles(_){return this.db.drizzleDb.select().from(o).where(y_(o.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(o).where(_1(y_(o.project,_),y_(o.filePath,$))).run()}}import{eq as t,and as N_,sql as r_,count as HJ}from"drizzle-orm";function k_(_){return _.replaceAll("\x00","").trim().split(/\s+/).map(($)=>$.trim()).filter(($)=>$.length>0).map(($)=>`"${$.replaceAll('"','""')}"*`).join(" ")}var $1=50;class I0{db;constructor(_){this.db=_}replaceFileSymbols(_,$,J,Q){if(this.db.drizzleDb.delete(y).where(N_(t(y.project,_),t(y.filePath,$))).run(),!Q.length)return;let z=new Date().toISOString(),W=Q.map((Z)=>({project:_,filePath:$,kind:Z.kind??"unknown",name:Z.name??"",startLine:Z.startLine??0,startColumn:Z.startColumn??0,endLine:Z.endLine??0,endColumn:Z.endColumn??0,isExported:Z.isExported??0,signature:Z.signature??null,fingerprint:Z.fingerprint??null,detailJson:Z.detailJson??null,contentHash:J,indexedAt:Z.indexedAt??z,resolvedType:Z.resolvedType??null,structuralFingerprint:Z.structuralFingerprint??null}));for(let Z=0;Z<W.length;Z+=$1)this.db.drizzleDb.insert(y).values(W.slice(Z,Z+$1)).run()}getFileSymbols(_,$){return this.db.drizzleDb.select().from(y).where(N_(t(y.project,_),t(y.filePath,$))).all()}searchByName(_,$,J={}){let Q=J.limit??50,z=k_($);if(!z)return[];return this.db.drizzleDb.select().from(y).where(N_(r_`${y.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${z})`,t(y.project,_),J.kind?t(y.kind,J.kind):void 0)).orderBy(y.name).limit(Q).all()}searchByKind(_,$){return this.db.drizzleDb.select().from(y).where(N_(t(y.project,_),t(y.kind,$))).orderBy(y.name).all()}getStats(_){let $=this.db.drizzleDb.select({symbolCount:HJ(),fileCount:r_`COUNT(DISTINCT ${y.filePath})`}).from(y).where(t(y.project,_)).get();return{symbolCount:$?.symbolCount??0,fileCount:$?.fileCount??0}}getByFingerprint(_,$){return this.db.drizzleDb.select().from(y).where(N_(t(y.project,_),t(y.fingerprint,$))).all()}deleteFileSymbols(_,$){this.db.drizzleDb.delete(y).where(N_(t(y.project,_),t(y.filePath,$))).run()}searchByQuery(_){let $=this.db.drizzleDb.select().from(y).where(N_(_.ftsQuery?r_`${y.id} IN (SELECT rowid FROM symbols_fts WHERE symbols_fts MATCH ${_.ftsQuery})`:void 0,_.exactName?t(y.name,_.exactName):void 0,_.project!==void 0?t(y.project,_.project):void 0,_.kind?t(y.kind,_.kind):void 0,_.filePath!==void 0?t(y.filePath,_.filePath):void 0,_.isExported!==void 0?t(y.isExported,_.isExported?1:0):void 0,_.decorator?r_`${y.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?t(y.resolvedType,_.resolvedType):void 0)).orderBy(y.name);if(!_.regex)return(_.limit!==void 0?$.limit(_.limit):$).all();let J;try{J=new RegExp(_.regex)}catch{throw new V("validation",`Invalid regex pattern: ${_.regex}`)}if(_.limit===void 0)return $.all().filter((W)=>J.test(W.name));let Q=[];for(let z of[5,20,100]){let W=_.limit*z,Z=$.limit(W).all();if(Q=Z.filter((Y)=>J.test(Y.name)),Q.length>=_.limit||Z.length<W)return Q.slice(0,_.limit)}return Q.slice(0,_.limit)}}import{eq as n,and as L_,isNull as J1,or as KJ}from"drizzle-orm";var x_={project:u.project,type:u.type,srcFilePath:u.srcFilePath,srcSymbolName:u.srcSymbolName,dstProject:u.dstProject,dstFilePath:u.dstFilePath,dstSymbolName:u.dstSymbolName,metaJson:u.metaJson,specifier:u.specifier,isExternal:u.isExternal};class D0{db;constructor(_){this.db=_}replaceFileRelations(_,$,J){this.db.transaction((Q)=>{if(Q.drizzleDb.delete(u).where(L_(n(u.project,_),n(u.srcFilePath,$))).run(),!J.length)return;for(let z of J)Q.drizzleDb.insert(u).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(x_).from(u).where(L_(n(u.project,_),n(u.srcFilePath,$),KJ(n(u.srcSymbolName,J),J1(u.srcSymbolName)))).all();return this.db.drizzleDb.select(x_).from(u).where(L_(n(u.project,_),n(u.srcFilePath,$))).all()}getIncoming(_){let{dstProject:$,dstFilePath:J}=_;return this.db.drizzleDb.select(x_).from(u).where(L_(n(u.dstProject,$),n(u.dstFilePath,J))).all()}getByType(_,$){return this.db.drizzleDb.select(x_).from(u).where(L_(n(u.project,_),n(u.type,$))).all()}deleteFileRelations(_,$){this.db.drizzleDb.delete(u).where(L_(n(u.project,_),n(u.srcFilePath,$))).run()}deleteIncomingRelations(_,$){this.db.drizzleDb.delete(u).where(L_(n(u.dstProject,_),n(u.dstFilePath,$))).run()}searchRelations(_){let $=this.db.drizzleDb.select(x_).from(u).where(L_(_.project!==void 0?n(u.project,_.project):void 0,_.srcFilePath!==void 0?n(u.srcFilePath,_.srcFilePath):void 0,_.srcSymbolName!==void 0?n(u.srcSymbolName,_.srcSymbolName):void 0,_.dstProject!==void 0?n(u.dstProject,_.dstProject):void 0,_.dstFilePath!==void 0?n(u.dstFilePath,_.dstFilePath):void 0,_.dstSymbolName!==void 0?n(u.dstSymbolName,_.dstSymbolName):void 0,_.type!==void 0?n(u.type,_.type):void 0,_.specifier!==void 0?n(u.specifier,_.specifier):void 0,_.isExternal!==void 0?n(u.isExternal,_.isExternal?1:0):void 0));return(_.limit!==void 0?$.limit(_.limit):$).all()}retargetRelations(_){let{dstProject:$,oldFile:J,oldSymbol:Q,newFile:z,newSymbol:W,newDstProject:Z}=_,Y=Q===null?L_(n(u.dstProject,$),n(u.dstFilePath,J),J1(u.dstSymbolName)):L_(n(u.dstProject,$),n(u.dstFilePath,J),n(u.dstSymbolName,Q)),X={dstFilePath:z,dstSymbolName:W};if(Z!==void 0)X.dstProject=Z;this.db.drizzleDb.update(u).set(X).where(Y).run()}}import{err as z1}from"@zipbul/result";import{subscribe as MJ}from"@parcel/watcher";import C0 from"path";import Q1 from"path";function z_(_){return _.replaceAll("\\","/")}function m_(_,$){return z_(Q1.relative(_,$))}function g_(_,$){return z_(Q1.resolve(_,$))}var LJ=["**/.git/**",`**/${A_}/**`,"**/dist/**","**/node_modules/**"],BJ=new Set(["package.json","tsconfig.json"]);function wJ(_){if(_==="update")return"change";if(_==="create")return"create";return"delete"}class A0{#_;#$;#Q;#z;#W;#Y;constructor(_,$=MJ,J=console){this.#$=_.projectRoot,this.#Q=[...LJ,..._.ignorePatterns??[]],this.#z=new Set((_.extensions??[".ts",".mts",".cts"]).map((Q)=>Q.toLowerCase())),this.#W=$,this.#Y=J}async start(_){try{this.#_=await this.#W(this.#$,($,J)=>{if($){this.#Y.error(new V("watcher","Callback error",{cause:$}));return}try{for(let Q of J){let z=z_(C0.relative(this.#$,Q.path));if(z.startsWith(".."))continue;let W=C0.basename(z),Z=C0.extname(z).toLowerCase();if(!BJ.has(W)&&!this.#z.has(Z))continue;if(z.endsWith(".d.ts"))continue;_({eventType:wJ(Q.type),filePath:z})}}catch(Q){this.#Y.error(new V("watcher","Callback error",{cause:Q}))}},{ignore:this.#Q})}catch($){return z1(new V("watcher","Failed to subscribe watcher",{cause:$}))}}async close(){if(!this.#_)return;try{await this.#_.unsubscribe(),this.#_=void 0}catch(_){return z1(new V("watcher","Failed to close watcher",{cause:_}))}}}import q0 from"path";var IJ=["**/node_modules/**","**/.git/**",`**/${A_}/**`,"**/dist/**"],DJ=IJ.map((_)=>new Bun.Glob(_));function CJ(_){return new Bun.Glob("**/package.json").scan({cwd:_,followSymlinks:!1})}async function o_(_,$=CJ){let J=[];for await(let Q of $(_)){let z=z_(Q);if(DJ.some((M)=>M.match(z)))continue;let W=z_(q0.dirname(Q)),Z=q0.join(_,Q),Y=await Bun.file(Z).json(),X=typeof Y?.name==="string"&&Y.name.length>0?Y.name:q0.basename(W==="."?_:W);J.push({dir:W,project:X})}return J.sort((Q,z)=>z.dir.length-Q.dir.length),J}function a(_,$,J="default"){let Q=z_(_);for(let z of $){if(z.dir===".")return z.project;if(Q===z.dir||Q.startsWith(`${z.dir}/`))return z.project}return J}import h_ from"path";var q_=new Map;async function AJ(_){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 qJ(_,$){if($.startsWith(".")){let J=h_.resolve(_,$);return J.endsWith(".json")?J:J+".json"}return h_.resolve(_,"node_modules",$)}async function W1(_,$=5){if($<=0)return null;let J=await AJ(_);if(!J)return null;let Q=J.extends;if(typeof Q!=="string"||!Q)return J;let z=qJ(h_.dirname(_),Q),W=await W1(z,$-1);if(!W)return J;let Z=typeof W.compilerOptions==="object"&&W.compilerOptions!==null?W.compilerOptions:{},Y=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:{};return{...W,...J,compilerOptions:{...Z,...Y}}}async function n_(_){if(q_.has(_))return q_.get(_)??null;let $=h_.join(_,"tsconfig.json"),J=await W1($);if(!J)return q_.set(_,null),null;let Q=typeof J.compilerOptions==="object"&&J.compilerOptions!==null?J.compilerOptions:null;if(!Q)return q_.set(_,null),null;let z=typeof Q.baseUrl==="string"?Q.baseUrl:null,W=typeof Q.paths==="object"&&Q.paths!==null?Q.paths:null;if(!z&&!W)return q_.set(_,null),null;let Z=z?h_.resolve(_,z):_,Y=new Map;if(W)for(let[M,O]of Object.entries(W)){if(!Array.isArray(O))continue;let L=O.filter((C)=>typeof C==="string");Y.set(M,L)}let X={baseUrl:Z,paths:Y};return q_.set(_,X),X}function t_(_){if(_){q_.delete(_);return}q_.clear()}function K_(_){let $=Bun.hash.xxHash64(_);return BigInt.asUintN(64,BigInt($)).toString(16).padStart(16,"0")}import{isErr as B1}from"@zipbul/result";import{err as NJ}from"@zipbul/result";import{parseSync as RJ}from"oxc-parser";function v_(_,$,J,Q=RJ){try{let z={preserveParens:!1,...J},W=Q(_,$,z);return{filePath:_,program:W.program,errors:W.errors,comments:W.comments,sourceText:$,module:W.module}}catch(z){return NJ(new V("parse",`Failed to parse file: ${_}`,{cause:z}))}}import{join as TJ}from"path";function SJ(_,$){let J=$.length===1?`**/*${$[0]}`:`**/*{${$.join(",")}}`;return new Bun.Glob(J).scan({cwd:_,followSymlinks:!1})}async function Y1(_){let{projectRoot:$,extensions:J,ignorePatterns:Q,fileRepo:z,scanFilesFn:W=SJ}=_,Z=z.getFilesMap(),Y=new Set,X=[],M=[],O=Q.map((C)=>new Bun.Glob(C));for await(let C of W($,J)){let N=z_(C);if(!J.some((l)=>N.endsWith(l)))continue;if(N.startsWith("node_modules/")||N.includes("/node_modules/"))continue;if(O.some((l)=>l.match(N)))continue;Y.add(N);let w=TJ($,N),R=Bun.file(w),{size:F,lastModified:G}=R,E=Z.get(N);if(!E){let l=await R.text(),i=K_(l);X.push({filePath:N,contentHash:i,mtimeMs:G,size:F});continue}if(E.mtimeMs===G&&E.size===F){M.push({filePath:N,contentHash:E.contentHash,mtimeMs:G,size:F});continue}let b=await R.text(),m=K_(b);if(m===E.contentHash)M.push({filePath:N,contentHash:m,mtimeMs:G,size:F});else X.push({filePath:N,contentHash:m,mtimeMs:G,size:F})}let L=[];for(let C of Z.keys())if(!Y.has(C))L.push(C);return{changed:X,unchanged:M,deleted:L}}function p_(_){let $=[0];for(let J=0;J<_.length;J++)if(_[J]===`
|
|
3
|
+
`)$.push(J+1);return $}function O_(_,$){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 GJ}from"@zipbul/result";import{parse as FJ}from"comment-parser";function e_(_){try{let $=_.trim();if($.startsWith("/**"))$=$.slice(3);if($.endsWith("*/"))$=$.slice(0,-2);let Q=FJ(`/** ${$} */`)[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 GJ(new V("parse","Failed to parse JSDoc comment",{cause:$}))}}import{isErr as jJ}from"@zipbul/result";function kJ(_){if("name"in _&&typeof _.name==="string")return _.name;if("value"in _){let $=_.value;if(typeof $==="string")return $;if(typeof $==="number"||typeof $==="bigint"||typeof $==="boolean")return String($)}return"unknown"}function E_(_){if(_.type==="Identifier")return[{name:_.name,start:_.start,end:_.end}];if(_.type==="ObjectPattern"){let $=[];for(let J of _.properties)if(J.type==="RestElement")$.push(...E_(J.argument));else $.push(...E_(J.value));return $}if(_.type==="ArrayPattern"){let $=[];for(let J of _.elements){if(!J)continue;if(J.type==="RestElement")$.push(...E_(J.argument));else $.push(...E_(J))}return $}if(_.type==="AssignmentPattern")return E_(_.left);return[]}function gJ(_){let $=new Map;for(let J of _.module.staticImports){let Q=J.moduleRequest.value;for(let z of J.entries){let W=z.localName.value,Z=z.importName.kind==="Name"?z.importName.name:void 0,Y={specifier:Q};if(Z&&Z!==W)Y.originalName=Z;$.set(W,Y)}}return $}function R_(_){let{program:$,sourceText:J,comments:Q}=_,z=p_(J),W=gJ(_),Z=Q.filter((D)=>D.type==="Block"&&D.value.startsWith("*")).sort((D,q)=>D.end-q.end),Y=$.body.map((D)=>D.start).sort((D,q)=>D-q);function X(D,q){return G(D,q)}function M(D,q,U){if(D.type==="PrivateIdentifier")return{kind:"private"};if(!q&&D.type==="Identifier")return;return X(D,U)}function O(D,q){if(q)return J.slice(D.start,D.end);if(D.type==="PrivateIdentifier")return`#${D.name}`;return kJ(D)}function L(D,q,U){let H=D;if(!q&&H.type==="Identifier")return{kind:"string",value:H.name};return X(D,U)}function C(D,q){return{start:O_(z,D),end:O_(z,q)}}function N(D){let q=0,U=Z.length-1,H=-1;while(q<=U){let B=q+U>>>1;if(Z[B].end<=D)H=B,q=B+1;else U=B-1}if(H<0)return;let K=Z[H];q=0,U=Y.length-1;while(q<=U){let B=q+U>>>1,A=Y[B];if(A<=K.end)q=B+1;else if(A>=D)U=B-1;else return}return`/*${K.value}*/`}function w(D){if(!D)return;let q="typeAnnotation"in D&&D.typeAnnotation?D.typeAnnotation:D;return J.slice(q.start,q.end)}let R=8;function F(D){if(D.type==="Identifier")return W.get(D.name);if(D.type==="MemberExpression"){let q=D.object;if(q.type==="Identifier")return W.get(q.name)}return}function G(D,q=0){let U=D;if(q>=R)return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)};let H=U.type;if(H==="Literal"){let K=U.value;if(typeof K==="bigint")return{kind:"bigint",value:typeof U.bigint==="string"?U.bigint:K.toString()};if(typeof U.regex==="object"&&U.regex!==null)return{kind:"regex",value:J.slice(U.start,U.end)};if(K===null)return{kind:"null",value:null};if(typeof K==="string")return{kind:"string",value:K};if(typeof K==="number")return{kind:"number",value:K};if(typeof K==="boolean")return{kind:"boolean",value:K};return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}if(H==="Identifier"){let K=U.name;if(K==="undefined")return{kind:"undefined",value:null};let B=W.get(K),A={kind:"identifier",name:K};if(B){if(A.importSource=B.specifier,B.originalName)A.originalName=B.originalName}return A}if(H==="MemberExpression"){if(U.computed){let j=U.property;if(j.type==="Literal"&&typeof j.value==="string"){let g=U.object,P=J.slice(g.start,g.end),d=g.type==="Identifier"?g.name:void 0,J_=d?W.get(d):void 0,V_={kind:"member",object:P,property:j.value};if(J_)V_.importSource=J_.specifier;return V_}return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}let K=U.object,B=J.slice(K.start,K.end),A=U.property.name??J.slice(U.property.start,U.property.end),I=K.type==="Identifier"?K.name:void 0,S=I?W.get(I):void 0,T={kind:"member",object:B,property:A};if(S)T.importSource=S.specifier;return T}if(H==="CallExpression"){let K=U.callee,B=J.slice(K.start,K.end),I=(U.arguments??[]).map((j)=>G(j,q+1)),S=F(K),T={kind:"call",callee:B,arguments:I};if(S)T.importSource=S.specifier;return T}if(H==="NewExpression"){let K=U.callee,B=J.slice(K.start,K.end),I=(U.arguments??[]).map((j)=>G(j,q+1)),S=F(K),T={kind:"new",callee:B,arguments:I};if(S)T.importSource=S.specifier;return T}if(H==="ObjectExpression"){let K=U.properties??[],B=[];for(let A of K){if(A.type==="SpreadElement"){let d=A.argument;B.push({kind:"spread",argument:G(d,q+1)});continue}let I=A.key,S=A.computed===!0,T=A.value,j=A.shorthand||void 0,P={kind:"property",key:L(I,S,q+1),value:G(T,q+1)};if(j)P.shorthand=!0;B.push(P)}return{kind:"object",properties:B}}if(H==="ArrayExpression")return{kind:"array",elements:(U.elements??[]).map((A)=>{if(!A)return{kind:"undefined",value:null};return G(A,q+1)})};if(H==="SpreadElement"){let K=U.argument;return{kind:"spread",argument:G(K,q+1)}}if(H==="ArrowFunctionExpression"||H==="FunctionExpression"){let B=U.params.map(b),A={kind:"function",sourceText:J.slice(U.start,U.end)};if(B.length>0)A.parameters=B;return A}if(H==="TemplateLiteral"||H==="TaggedTemplateExpression")return{kind:"template",sourceText:J.slice(U.start,U.end)};if(H==="UnaryExpression"){let{operator:K,argument:B}=U;if(K==="-"&&B.type==="Literal"&&typeof B.value==="number")return{kind:"number",value:-B.value};if(K==="void")return{kind:"undefined",value:null};return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}if(H==="TSAsExpression"||H==="TSSatisfiesExpression"||H==="TSNonNullExpression"||H==="TSTypeAssertion"||H==="TSInstantiationExpression"||H==="ParenthesizedExpression"||H==="ChainExpression"){let K=U.expression;if(K)return G(K,q)}return{kind:"unresolvable",sourceText:J.slice(U.start,U.end)}}function E(D){if(!D||D.length===0)return[];return D.map((q)=>{let U=q.expression;if(U.type==="CallExpression"){let H=U,K=H.callee,B="name"in K&&typeof K.name==="string"?K.name:("property"in K)&&K.property&&typeof K.property.name==="string"?K.property.name:"unknown",A=H.arguments.map((I)=>G(I));return{name:B,arguments:A.length>0?A:void 0}}if(U.type==="Identifier")return{name:U.name??"unknown"};return{name:J.slice(U.start,U.end)}})}function b(D){if(D.type==="TSParameterProperty"){let U=D;return l(U.parameter,U.decorators)}if(D.type==="RestElement"){let U=D,H=U.argument,B=`...${"name"in H&&typeof H.name==="string"?H.name:"unknown"}`,A=U.typeAnnotation,I=A?w(A):void 0,S={name:B,isOptional:!1};if(I)S.type=I;return S}let q=D;return l(q,q.decorators)}function m(D){if(!D)return;let q="typeAnnotation"in D&&D.typeAnnotation?D.typeAnnotation:null;if(!q)return;let H=q.typeName?.name;if(!H)return;return W.get(H)?.specifier}function l(D,q){if(D.type==="AssignmentPattern"){let{left:T,right:j}=D,g="name"in T&&typeof T.name==="string"?T.name:"unknown",P="typeAnnotation"in T?T.typeAnnotation:null,d=P?w(P):void 0,J_=m(P),V_=J.slice(j.start,j.end),B_="decorators"in T&&Array.isArray(T.decorators)?T.decorators:[],K0=E(B_),C_={name:g,isOptional:!0,defaultValue:V_};if(d)C_.type=d;if(J_)C_.typeImportSource=J_;if(K0.length>0)C_.decorators=K0;return C_}let U="name"in D&&typeof D.name==="string"?D.name:("pattern"in D)&&D.pattern&&typeof D.pattern.name==="string"?D.pattern.name:"unknown",H=!!(("optional"in D)&&D.optional),K="typeAnnotation"in D?D.typeAnnotation:null,B=K?w(K):void 0,A=m(K),I=E(q??[]),S={name:U,isOptional:H};if(B)S.type=B;if(A)S.typeImportSource=A;if(I.length>0)S.decorators=I;return S}function i(D,q){let U=[];if(q?.async)U.push("async");if(D.static)U.push("static");if(D.abstract)U.push("abstract");if(D.readonly)U.push("readonly");if(D.override)U.push("override");if(D.declare)U.push("declare");if(D.const)U.push("const");let H=D.accessibility;if(H==="private")U.push("private");else if(H==="protected")U.push("protected");else if(H==="public")U.push("public");return U}function W_(D){if(!D)return;let q=D.params.flatMap((U)=>{let H=U.name.name;return H?[H]:[]});return q.length>0?q:void 0}function X_(D){let q=[];if(D.superClass){let H=J.slice(D.superClass.start,D.superClass.end);q.push({kind:"extends",name:H})}let U=D.implements??[];for(let H of U){let K=H.expression,B=J.slice(K.start,K.end);q.push({kind:"implements",name:B})}return q}function M_(D){let q=[],U=D.extends;for(let H of U){let K=H.expression,B=J.slice(K.start,K.end);q.push({kind:"extends",name:B})}return q}function U_(D){let q=[];for(let U of D)if(U.type==="MethodDefinition"||U.type==="TSAbstractMethodDefinition"){let H=U,K=O(H.key,H.computed),B=M(H.key,H.computed,0),A=H.value,I=H.kind,S=I==="constructor"?"constructor":I==="get"?"getter":I==="set"?"setter":"method",T=i(H,A);if(U.type==="TSAbstractMethodDefinition"&&!T.includes("abstract"))T.push("abstract");let j=A.params.map(b),g=w(A.returnType),P=E(H.decorators??[]),d={kind:"method",name:K,span:C(U.start,U.end),isExported:!1,methodKind:S,modifiers:T,parameters:j.length>0?j:void 0,returnType:g};if(B)d.key=B;if(P.length>0)d.decorators=P;q.push(d)}else if(U.type==="PropertyDefinition"||U.type==="TSAbstractPropertyDefinition"||U.type==="AccessorProperty"||U.type==="TSAbstractAccessorProperty"){let H=U,K=O(H.key,H.computed),B=M(H.key,H.computed,0),A=i(H);if(U.type==="TSAbstractPropertyDefinition"||U.type==="TSAbstractAccessorProperty"){if(!A.includes("abstract"))A.push("abstract")}if(U.type==="AccessorProperty"||U.type==="TSAbstractAccessorProperty")A.push("accessor");let I=w(H.typeAnnotation),S=H.value,T=S?G(S):void 0,j=E(H.decorators??[]),g={kind:"property",name:K,span:C(U.start,U.end),isExported:!1,modifiers:A,returnType:I,initializer:T};if(B)g.key=B;if(j.length>0)g.decorators=j;q.push(g)}return q}function Y_(D){let q=[];for(let U of D)if(U.type==="TSMethodSignature"){let H=U,K=O(H.key,H.computed),B=M(H.key,H.computed,0),A=H.params.map(b),I=w(H.returnType),S={kind:"method",name:K,span:C(U.start,U.end),isExported:!1,modifiers:[],methodKind:"method",parameters:A.length>0?A:void 0,returnType:I};if(B)S.key=B;q.push(S)}else if(U.type==="TSPropertySignature"){let H=U,K=O(H.key,H.computed),B=M(H.key,H.computed,0),A=w(H.typeAnnotation),I={kind:"property",name:K,span:C(U.start,U.end),isExported:!1,modifiers:H.readonly?["readonly"]:[],returnType:A};if(B)I.key=B;q.push(I)}return q}function c(D,q){let U=D.type;if(U==="FunctionDeclaration"||U==="FunctionExpression"||U==="TSDeclareFunction"||U==="TSEmptyBodyFunctionExpression"){let H=D,K=H.id?.name??"default",B=H.params.map(b),A=w(H.returnType),I=i(H,H),S=E(H.decorators??[]),T=W_(H.typeParameters),j={kind:"function",name:K,span:C(D.start,D.end),isExported:q,modifiers:I,parameters:B.length>0?B:void 0,returnType:A,decorators:S.length>0?S:void 0};if(T&&T.length>0)j.typeParameters=T;return j}if(U==="ClassDeclaration"||U==="ClassExpression"){let H=D,K=H.id?.name??"default",B=X_(H),A=U_(H.body.body),I=E(H.decorators),S=i(H),T=W_(H.typeParameters),j={kind:"class",name:K,span:C(D.start,D.end),isExported:q,modifiers:S,heritage:B.length>0?B:void 0,members:A.length>0?A:void 0,decorators:I.length>0?I:void 0};if(T&&T.length>0)j.typeParameters=T;return j}if(U==="VariableDeclaration"){let H=D,K=[];for(let B of H.declarations){let{id:A,init:I}=B;if(A.type==="ObjectPattern"||A.type==="ArrayPattern"){let V_=E_(A);for(let B_ of V_)K.push({kind:"variable",name:B_.name,span:C(B_.start,B_.end),isExported:q,modifiers:[]});continue}let S="name"in A&&typeof A.name==="string"?A.name:"unknown",T="variable",j,g,P;if(I)if(I.type==="FunctionExpression"||I.type==="ArrowFunctionExpression"){T="function";let V_=I;j=V_.params.map(b),g=w(V_.returnType)}else P=G(I);let d=[],J_={kind:T,name:S,span:C(B.start,B.end),isExported:q,modifiers:d,parameters:j,returnType:g};if(P)J_.initializer=P;K.push(J_)}if(K.length===0)return null;if(K.length===1)return K[0];return K}if(U==="TSTypeAliasDeclaration")return{kind:"type",name:D.id.name,span:C(D.start,D.end),isExported:q,modifiers:[]};if(U==="TSInterfaceDeclaration"){let H=D,K=H.id.name,B=M_(H),A=Y_(H.body.body),I=W_(H.typeParameters),S={kind:"interface",name:K,span:C(D.start,D.end),isExported:q,modifiers:[],heritage:B.length>0?B:void 0,members:A.length>0?A:void 0};if(I&&I.length>0)S.typeParameters=I;return S}if(U==="TSEnumDeclaration"){let H=D,K=H.id.name,B=i(H),I=H.body.members.map((S)=>{let T=S.id,j=T.type!=="Identifier",g="name"in T&&typeof T.name==="string"?T.name:("value"in T)&&typeof T.value==="string"?T.value:"unknown",P=S.initializer?G(S.initializer):void 0,d={kind:"property",name:g,span:C(S.start,S.end),isExported:!1,modifiers:[]};if(j)d.key=X(T,0);if(P)d.initializer=P;return d});return{kind:"enum",name:K,span:C(D.start,D.end),isExported:q,modifiers:B,members:I.length>0?I:void 0}}if(U==="TSModuleDeclaration"){let H=D,K=H.id.name??H.id.value??"unknown",B=i(H),A=[];if(H.body?.type==="TSModuleBlock")for(let I of H.body.body??[]){if(I.type!=="ExportNamedDeclaration")continue;let S=I.declaration;if(!S)continue;let T=c(S,!1);if(T)if(Array.isArray(T))A.push(...T);else A.push(T)}return{kind:"namespace",name:K,span:C(D.start,D.end),isExported:q,modifiers:B,members:A.length>0?A:void 0}}return null}let s=[],D_=new Set;for(let D of $.body){let q=null,U=D;if(U.type==="ExportNamedDeclaration"){let K=U;if(K.declaration){if(q=c(K.declaration,!0),q&&!Array.isArray(q))q.span=C(K.start,K.end)}else if(!K.source&&K.specifiers)for(let B of K.specifiers){let A=B.local,I="name"in A?A.name:A.value;if(I)D_.add(I)}}else if(U.type==="ExportDefaultDeclaration"){let K=U,B=K.declaration;if(B){if(q=c(B,!0),q&&!Array.isArray(q))q.name="id"in B&&B.id&&typeof B.id.name==="string"?B.id.name:"default",q.isExported=!0,q.span=C(K.start,K.end);else if(!q&&"type"in B&&B.type==="Identifier"){let A=B.name;if(A)D_.add(A)}}}else{let K=U.type;if(K==="FunctionDeclaration"||K==="TSDeclareFunction"||K==="ClassDeclaration"||K==="VariableDeclaration"||K==="TSTypeAliasDeclaration"||K==="TSInterfaceDeclaration"||K==="TSEnumDeclaration"||K==="TSModuleDeclaration")q=c(U,!1)}let H=Array.isArray(q)?q:q?[q]:[];for(let K of H){let B=D.start,A=N(B);if(A){let I=e_(A);if(!jJ(I))K.jsDoc=I}s.push(K)}}if(D_.size>0){for(let D of s)if(!D.isExported&&D_.has(D.name))D.isExported=!0}return s}function _0(_){if(_===null||typeof _!=="object")return JSON.stringify(_);if(Array.isArray(_))return`[${_.map(_0).join(",")}]`;let $=_;return`{${Object.keys($).sort().map((Q)=>`${JSON.stringify(Q)}:${_0($[Q])}`).join(",")}}`}function vJ(_){if(_.kind==="function"||_.kind==="method"){let $=_.parameters?.length??0,J=_.modifiers.includes("async")?1:0;return`params:${$}|async:${J}`}return null}function EJ(_){let $={};if(_.jsDoc)$.jsDoc=_.jsDoc;if(_.kind==="function"||_.kind==="method"){if(_.parameters!==void 0)$.parameters=_.parameters;if(_.returnType!==void 0)$.returnType=_.returnType}if(_.heritage?.length)$.heritage=_.heritage;if(_.decorators?.length)$.decorators=_.decorators;if(_.typeParameters?.length)$.typeParameters=_.typeParameters;if(_.modifiers?.length)$.modifiers=_.modifiers;if(_.initializer)$.initializer=_.initializer;if(_.key)$.key=_.key;if(_.members?.length)$.members=_.members.map((J)=>{let Q=J.modifiers.find((W)=>W==="private"||W==="protected"||W==="public"),z={name:J.name,kind:J.methodKind??J.kind,type:J.returnType,visibility:Q,isStatic:J.modifiers.includes("static")||void 0,isReadonly:J.modifiers.includes("readonly")||void 0,isAccessor:J.modifiers.includes("accessor")||void 0};if(J.key)z.key=J.key;if(J.initializer)z.initializer=J.initializer;if(J.decorators?.length)z.decorators=J.decorators;return z});return Object.keys($).length>0?JSON.stringify($):null}function uJ(_){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(_.key)$.push(`k:${_0(_.key)}`);if(_.members?.length){let J=_.members.map((Q)=>`${Q.kind}:${Q.modifiers.join(",")}:${Q.parameters?.length??""}:${Q.returnType??""}:${Q.key?_0(Q.key):""}`).sort().join(";");$.push(`mem:${_.members.length}:${K_(J)}`)}return K_($.join("|"))}function Z1(_,$,J,Q,z){let W=vJ(_),Z=K_(`${$}|${_.kind}|${W??""}`),Y=uJ(_);return{project:J,filePath:Q,kind:_.kind,name:$,startLine:_.span.start.line,startColumn:_.span.start.column,endLine:_.span.end.line,endColumn:_.span.end.column,isExported:_.isExported?1:0,signature:W,fingerprint:Z,detailJson:EJ(_),contentHash:z,indexedAt:new Date().toISOString(),structuralFingerprint:Y}}function N0(_){let{parsed:$,project:J,filePath:Q,contentHash:z,symbolRepo:W}=_,Z=R_($),Y=[];for(let X of Z){Y.push(Z1(X,X.name,J,Q,z));for(let M of X.members??[])Y.push(Z1(M,`${X.name}.${M.name}`,J,Q,z))}W.replaceFileSymbols(J,Q,z,Y)}import{resolve as R0,dirname as bJ,extname as PJ}from"path";function T_(_,$,J){let Q=(z)=>{let W=PJ(z);if(W===".js")return[z.slice(0,-3)+".ts"];if(W===".mjs")return[z.slice(0,-4)+".mts"];if(W===".cjs")return[z.slice(0,-4)+".cts"];if(W===".ts"||W===".mts"||W===".cts"||W===".d.ts")return[z];return[z+".ts",z+".d.ts",z+"/index.ts",z+"/index.d.ts",z+".mts",z+"/index.mts",z+".cts",z+"/index.cts"]};if($.startsWith(".")){let z=z_(R0(bJ(_),$));return Q(z)}if(J)for(let[z,W]of J.paths){if(W.length===0)continue;let Z=z.indexOf("*");if(Z===-1){if($===z){let Y=[];for(let X of W)Y.push(...Q(z_(R0(J.baseUrl,X))));return Y}}else{let Y=z.slice(0,Z),X=z.slice(Z+1);if($.startsWith(Y)&&(X===""||$.endsWith(X))){let M=$.slice(Y.length,X===""?void 0:$.length-X.length),O=[];for(let L of W)O.push(...Q(z_(R0(J.baseUrl,L.replace("*",M)))));return O}}}return[]}function X1(_,$,J,Q=T_){let z=new Map,W=_.body??[];for(let Z of W){if(Z.type!=="ImportDeclaration")continue;let Y=Z.source?.value??"",X=Q($,Y,J);if(X.length===0)continue;let M=X[0],O=Z.specifiers??[];for(let L of O)switch(L.type){case"ImportSpecifier":z.set(L.local.name,{path:M,importedName:L.imported.name});break;case"ImportDefaultSpecifier":z.set(L.local.name,{path:M,importedName:"default"});break;case"ImportNamespaceSpecifier":z.set(L.local.name,{path:M,importedName:"*"});break}}return z}import{Visitor as fJ}from"oxc-parser";function $0(_){return"name"in _&&typeof _.name==="string"?_.name:("value"in _)&&typeof _.value==="string"?_.value:"unknown"}function yJ(_){return!_.startsWith(".")&&!_.startsWith("/")}function S_(_,$,J,Q){let z=Q(_,$,J),W=z.length>0?z[0]:null,Z=W===null&&yJ($);return{resolved:W,isExternal:Z}}function xJ(_,$,J,Q,z){for(let W of _.staticImports){let Z=W.moduleRequest.value,{resolved:Y,isExternal:X}=S_($,Z,J,Q),M={dstFilePath:Y,specifier:Z};if(W.entries.length===0){let O={};if(X)O.isExternal=!0;if(Y===null&&!X)O.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,...M,dstSymbolName:null,...Object.keys(O).length>0?{metaJson:JSON.stringify(O)}:{}});continue}for(let O of W.entries){let L=O.isType,C={};if(L)C.isType=!0;if(X)C.isExternal=!0;if(Y===null&&!X)C.isUnresolved=!0;let N,w,R=O.importName.kind;if(R==="Default")N="default",w=O.localName.value;else if(R==="NamespaceObject")N="*",w=O.localName.value,C.importKind="namespace";else N=O.importName.name??"unknown",w=O.localName.value;z.push({type:L?"type-references":"imports",srcFilePath:$,srcSymbolName:w,...M,dstSymbolName:N,...Object.keys(C).length>0?{metaJson:JSON.stringify(C)}:{}})}}}function mJ(_,$,J,Q,z){let W=new Map;for(let Z of _.staticImports)for(let Y of Z.entries)W.set(Y.localName.value,Z.moduleRequest.value);for(let Z of _.staticExports)for(let Y of Z.entries){let X=null;if(Y.moduleRequest)X=Y.moduleRequest.value;else if(Y.localName.name)X=W.get(Y.localName.name)??null;if(!X)continue;let{resolved:M,isExternal:O}=S_($,X,J,Q),L=Y.exportName.name??"default",C=Y.exportName.kind,N=Y.localName.name??Y.importName.name??L,w=Y.isType,R={isReExport:!0};if(C==="None");else R.specifiers=[{local:N,exported:L}];if(w)R.isType=!0;if(O)R.isExternal=!0;if(M===null&&!O)R.isUnresolved=!0;let F=null,G=null,E=Y.importName.kind;if(E==="All"||E==="AllButDefault"){if(C==="Name"&&L)G=L,R.namespaceAlias=L}else G=N,F=L;z.push({type:w?"type-references":"re-exports",srcFilePath:$,srcSymbolName:F,dstFilePath:M,dstSymbolName:G,specifier:X,metaJson:JSON.stringify(R)})}}function hJ(_,$,J,Q,z){for(let W of _.body){let Z=W;if(Z.type==="ImportDeclaration"){let Y=Z,X=Y.source.value,{resolved:M,isExternal:O}=S_($,X,J,Q),L=Y.importKind==="type",C=Y.specifiers,N={dstFilePath:M,specifier:X};if(C.length===0){let w={};if(L)w.isType=!0;if(O)w.isExternal=!0;if(M===null&&!O)w.isUnresolved=!0;z.push({type:L?"type-references":"imports",srcFilePath:$,srcSymbolName:null,...N,dstSymbolName:null,...Object.keys(w).length>0?{metaJson:JSON.stringify(w)}:{}})}else for(let w of C){let R=w.type,F=L||R==="ImportSpecifier"&&w.importKind==="type",G={};if(F)G.isType=!0;if(O)G.isExternal=!0;if(M===null&&!O)G.isUnresolved=!0;let E,b;if(R==="ImportDefaultSpecifier")E="default",b=w.local.name;else if(R==="ImportNamespaceSpecifier")E="*",b=w.local.name,G.importKind="namespace";else E=$0(w.imported),b=w.local.name;z.push({type:F?"type-references":"imports",srcFilePath:$,srcSymbolName:b,...N,dstSymbolName:E,...Object.keys(G).length>0?{metaJson:JSON.stringify(G)}:{}})}continue}if(Z.type==="ExportAllDeclaration"){let Y=Z,X=Y.source.value,{resolved:M,isExternal:O}=S_($,X,J,Q),L=Y.exportKind==="type",C=Y.exported,N=C?$0(C):null,w={isReExport:!0};if(L)w.isType=!0;if(O)w.isExternal=!0;if(M===null&&!O)w.isUnresolved=!0;if(N)w.namespaceAlias=N;z.push({type:L?"type-references":"re-exports",srcFilePath:$,srcSymbolName:null,dstFilePath:M,dstSymbolName:N,specifier:X,metaJson:JSON.stringify(w)});continue}if(Z.type==="ExportNamedDeclaration"){let Y=Z;if(!Y.source)continue;let X=Y.source.value,{resolved:M,isExternal:O}=S_($,X,J,Q),L=Y.exportKind==="type",C=Y.specifiers??[];for(let N of C){let w=L||N.exportKind==="type",R=$0(N.local),F=$0(N.exported),G={isReExport:!0,specifiers:[{local:R,exported:F}]};if(w)G.isType=!0;if(O)G.isExternal=!0;if(M===null&&!O)G.isUnresolved=!0;z.push({type:w?"type-references":"re-exports",srcFilePath:$,srcSymbolName:F,dstFilePath:M,dstSymbolName:R,specifier:X,metaJson:JSON.stringify(G)})}}}}function nJ(_,$,J,Q,z){new fJ({ImportExpression(Z){let Y=Z.source;if(Y.type!=="Literal"||typeof Y.value!=="string")return;let X=Y.value,{resolved:M,isExternal:O}=S_($,X,J,Q),L={isDynamic:!0};if(O)L.isExternal=!0;if(M===null&&!O)L.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:M,dstSymbolName:null,specifier:X,metaJson:JSON.stringify(L)})},CallExpression(Z){let Y=Z.callee,X=!1;if(Y.type==="Identifier"&&Y.name==="require");else if(Y.type==="MemberExpression"&&!Y.computed){let R=Y,F=R.object,G=R.property;if(F.type==="Identifier"&&F.name==="require"&&G.name==="resolve")X=!0;else return}else return;let M=Z.arguments;if(M.length===0)return;let O=M[0];if(O.type!=="Literal"||typeof O.value!=="string")return;let L=O.value,{resolved:C,isExternal:N}=S_($,L,J,Q),w={isRequire:!0};if(X)w.isRequireResolve=!0;if(N)w.isExternal=!0;if(C===null&&!N)w.isUnresolved=!0;z.push({type:"imports",srcFilePath:$,srcSymbolName:null,dstFilePath:C,dstSymbolName:null,specifier:L,metaJson:JSON.stringify(w)})}}).visit(_)}function U1(_,$,J,Q=T_,z){let W=[];if(z)xJ(z,$,J,Q,W),mJ(z,$,J,Q,W);else hJ(_,$,J,Q,W);return nJ(_,$,J,Q,W),W}import{walk as _Q}from"oxc-walker";function pJ(_){return _.type==="FunctionDeclaration"||_.type==="FunctionExpression"||_.type==="ArrowFunctionExpression"}function dJ(_){return _.type==="ArrowFunctionExpression"}function lJ(_){return _.type==="AssignmentExpression"}function iJ(_){return _.type==="CallExpression"}function cJ(_){return _.type==="FunctionDeclaration"}function aJ(_){return _.type==="FunctionExpression"}function sJ(_){return _.type==="Identifier"}function rJ(_){return _.type==="MemberExpression"}function oJ(_){return _.type==="TSQualifiedName"}function tJ(_){return _.type==="VariableDeclaration"}var V1=new Map,eJ=new Proxy({},{get(_,$,J){if(typeof $!=="string")return Reflect.get(_,$,J);let Q=$.charCodeAt(0);if(Q<65||Q>90)return Reflect.get(_,$,J);let z=V1.get($);if(z===void 0)z=(W)=>W!==null&&W!==void 0&&W.type===$,V1.set($,z);return z}});function u_(_){if(!_||typeof _!=="object"||Array.isArray(_))return null;let $=_;if($.type==="Identifier"){let J=$.name;return{root:J,parts:[],full:J}}if($.type==="ThisExpression")return{root:"this",parts:[],full:"this"};if($.type==="Super")return{root:"super",parts:[],full:"super"};if($.type==="MemberExpression"){let J=[],Q=$;while(Q.type==="MemberExpression"){let Z=Q.property;if(!Z||typeof Z.name!=="string")return null;J.push(Z.name),Q=Q.object}let z;if(Q.type==="Identifier")z=Q.name;else if(Q.type==="ThisExpression")z="this";else if(Q.type==="Super")z="super";else return null;J.reverse();let W=[z,...J].join(".");return{root:z,parts:J,full:W}}return null}function O1(_,$,J){let Q=[],z=[],W=[];function Z(){if(z.length>0)return z[z.length-1]??null;return null}function Y(O){if(!O)return null;let L=J.get(O.root);if(O.parts.length===0){if(L)return{dstFilePath:L.path,dstSymbolName:L.importedName,resolution:"import"};return{dstFilePath:$,dstSymbolName:O.root,resolution:"local"}}else{if(L&&L.importedName==="*"){let C=O.parts[O.parts.length-1];return{dstFilePath:L.path,dstSymbolName:C,resolution:"namespace"}}return{dstFilePath:$,dstSymbolName:O.full,resolution:"local-member"}}}function X(O,L){let C=u_(O.callee),N=Y(C);if(N){let w=Z(),R={};if(L)R.isNew=!0;if(w===null)R.scope="module";Q.push({type:"calls",srcFilePath:$,srcSymbolName:w,dstFilePath:N.dstFilePath,dstSymbolName:N.dstSymbolName,...Object.keys(R).length>0?{metaJson:JSON.stringify(R)}:{}})}}function M(O,L){if(O.type==="FunctionDeclaration"){z.push(O.id?.name??"anonymous");return}if(O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){if(L?.type==="VariableDeclarator"){let w=L.id,R=w.type==="Identifier"?w.name:"anonymous";z.push(R);return}if(L?.type==="MethodDefinition"||L?.type==="TSAbstractMethodDefinition"){let w=L.key,R=W[W.length-1]??"",F="name"in w?w.name:"anonymous",G=R?`${R}.${F}`:F;z.push(G);return}let C=Z(),N=C?`${C}.<anonymous>`:"<anonymous>";z.push(N)}}return _Q(_,{enter(O,L){if(O.type==="ClassDeclaration"||O.type==="ClassExpression"){W.push(O.id?.name??"AnonymousClass");return}if(O.type==="FunctionDeclaration"||O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){M(O,L);return}if(O.type==="CallExpression"){X(O,!1);return}if(O.type==="NewExpression"){X(O,!0);return}},leave(O){if(O.type==="ClassDeclaration"||O.type==="ClassExpression"){W.pop();return}if(O.type==="FunctionDeclaration"||O.type==="FunctionExpression"||O.type==="ArrowFunctionExpression"){z.pop();return}}}),Q}import{Visitor as $Q}from"oxc-parser";function H1(_,$,J){let Q=[];function z(Z){let Y=Z.id?.name??"AnonymousClass";if(Z.superClass){let M=u_(Z.superClass);if(M){let O=T0(M,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Y,...O})}}let X=Z.implements??[];for(let M of X){let O=u_(M.expression);if(!O)continue;let L=T0(O,$,J);Q.push({type:"implements",srcFilePath:$,srcSymbolName:Y,...L})}}return new $Q({TSInterfaceDeclaration(Z){let Y=Z.id.name??"AnonymousInterface",X=Z.extends;for(let M of X){let O=u_(M.expression);if(!O)continue;let L=T0(O,$,J);Q.push({type:"extends",srcFilePath:$,srcSymbolName:Y,...L})}},ClassDeclaration(Z){z(Z)},ClassExpression(Z){z(Z)}}).visit(_),Q}function T0(_,$,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 d_(_,$,J,Q=T_,z){let W=X1(_,$,J,Q),Z=U1(_,$,J,Q,z),Y=O1(_,$,W),X=H1(_,$,W);return[...Z,...Y,...X]}function S0(_){let{ast:$,project:J,filePath:Q,relationRepo:z,projectRoot:W,tsconfigPaths:Z,knownFiles:Y,boundaries:X,module:M}=_,O=g_(W,Q),C=d_($,O,Z,Y?(w,R,F)=>{let G=T_(w,R,F);for(let E of G){let b=m_(W,E);if(X){let m=a(b,X);if(Y.has(`${m}::${b}`))return[E]}else if(Y.has(`${J}::${b}`))return[E]}return[]}:void 0,M),N=[];for(let w of C){if(w.dstFilePath===null){let E=m_(W,w.srcFilePath),b;if(w.metaJson)try{b=JSON.parse(w.metaJson)}catch{}let m=b?.isExternal===!0;N.push({project:J,type:w.type,srcFilePath:E,srcSymbolName:w.srcSymbolName??null,dstProject:null,dstFilePath:null,dstSymbolName:w.dstSymbolName??null,metaJson:w.metaJson??null,specifier:w.specifier??null,isExternal:m?1:0});continue}let R=m_(W,w.dstFilePath);if(R.startsWith(".."))continue;let F=m_(W,w.srcFilePath),G=X?a(R,X):J;N.push({project:J,type:w.type,srcFilePath:F,srcSymbolName:w.srcSymbolName??null,dstProject:G,dstFilePath:R,dstSymbolName:w.dstSymbolName??null,metaJson:w.metaJson??null,specifier:w.specifier??null,isExternal:0})}return z.replaceFileRelations(J,Q,N),N.length}import{isErr as JQ}from"@zipbul/result";var K1=/(?:^|\s)@([a-zA-Z][\w-]*\w|[a-zA-Z])\s*(.*)$/m;function QQ(_){let $=R_(_),J=[];for(let Q of $){J.push({name:Q.name,startLine:Q.span.start.line});for(let z of Q.members??[])J.push({name:`${Q.name}.${z.name}`,startLine:z.span.start.line})}return J.sort((Q,z)=>Q.startLine-z.startLine),J}function G0(_,$,J){let Q=0,z=_.length-1;while(Q<=z){let W=Q+z>>1;if(_[W].startLine<=$)Q=W+1;else z=W-1}if(Q<_.length){let W=_[Q];if(W.startLine-$<=J)return W.name}return null}function J0(_,$,J){let Q=O_(_,$),z=O_(_,J);return{start:Q,end:z}}function M1(_){let{comments:$,sourceText:J}=_;if(!$.length)return[];let Q=p_(J),z=QQ(_),W=[],Z=[...$].sort((X,M)=>X.start-M.start),Y=null;for(let X of Z)if(X.type==="Block"&&X.value.startsWith("*")){Y=null;let M=`/*${X.value}*/`,O=e_(M);if(JQ(O))continue;let L=O;if(!L.tags?.length)continue;let C=O_(Q,X.end),N=G0(z,C.line,3),w=J.slice(X.start,X.end);for(let R of L.tags){let F=[R.name,R.description].filter(Boolean).join(" "),G=`@${R.tag}`,E=w.indexOf(G),b;if(E>=0){let m=X.start+E,l=J.indexOf(`
|
|
4
|
+
`,m),i=l>=0?Math.min(l,X.end):X.end;b=J0(Q,m,i)}else b=J0(Q,X.start,X.end);W.push({tag:R.tag,value:F,source:"jsdoc",span:b,symbolName:N})}}else if(X.type==="Block"){Y=null;let M=X.value.split(`
|
|
5
|
+
`),O=0;for(let L of M){let C=L.replace(/^\s*\*?\s?/,""),N=K1.exec(C);if(N){let w=N[1],R=N[2]?.trim()??"",F=`@${w}`,G=L.indexOf(F),E=X.start+2+O+(G>=0?G:0),b=X.start+2+O+L.length,m=J0(Q,E,b),l=O_(Q,X.end),i=G0(z,l.line,3);W.push({tag:w,value:R,source:"block",span:m,symbolName:i})}O+=L.length+1}}else{let M=X.value,O=K1.exec(M),L=O_(Q,X.start),C=O_(Q,X.end);if(O){let N=O[1],w=O[2]?.trim()??"",R=`@${N}`,F=M.indexOf(R),G=X.start+2+(F>=0?F:0),E=J0(Q,G,X.end),b=G0(z,C.line,3),m={tag:N,value:w,source:"line",span:E,symbolName:b};W.push(m),Y={annotation:m,endLine:C.line}}else if(Y&&L.line===Y.endLine+1){let N=M.trim();if(N)Y.annotation.value+=" "+N,Y.annotation.span.end=O_(Q,X.end),Y.endLine=C.line}else Y=null}return W}function F0(_){let{parsed:$,project:J,filePath:Q,annotationRepo:z}=_,W=M1($);if(z.deleteFileAnnotations(J,Q),!W.length)return 0;let Z=new Date().toISOString(),Y=W.map((X)=>({project:J,filePath:Q,tag:X.tag,value:X.value,source:X.source,symbolName:X.symbolName,startLine:X.span.start.line,startColumn:X.span.start.column,endLine:X.span.end.line,endColumn:X.span.end.column,indexedAt:Z}));return z.insertBatch(J,Q,Y),W.length}function L1(_,$){let J=[],Q=[],z=[];for(let[O,L]of $)if(!_.has(O))J.push({name:L.name,filePath:L.filePath,kind:L.kind,fingerprint:L.fingerprint});for(let[O,L]of _)if(!$.has(O))Q.push({name:L.name,filePath:L.filePath,kind:L.kind,fingerprint:L.fingerprint});if(!J.length||!Q.length)return{renamed:z,added:J,removed:Q};let W=new Map,Z=new Map;for(let O of J){let L=W.get(O.filePath)??[];L.push(O),W.set(O.filePath,L)}for(let O of Q){let L=Z.get(O.filePath)??[];L.push(O),Z.set(O.filePath,L)}let Y=new Set,X=new Set;for(let[O,L]of W){let C=Z.get(O);if(!C)continue;for(let N of new Set(L.map((w)=>w.kind))){let w=L.filter((b)=>b.kind===N&&!Y.has(b)),R=C.filter((b)=>b.kind===N&&!X.has(b));if(!w.length||!R.length)continue;let F=(b,m)=>{return m.get(`${b.filePath}::${b.name}`)?.structuralFingerprint??null},G=(b,m)=>{return m.get(`${b.filePath}::${b.name}`)?.startLine??0},E=new Map;for(let b of R){let m=F(b,_);if(!m)continue;let l=E.get(m)??[];l.push(b),E.set(m,l)}for(let b of w){if(Y.has(b))continue;let m=F(b,$);if(!m)continue;let l=E.get(m);if(!l)continue;let i=l.filter((X_)=>!X.has(X_));if(!i.length)continue;let W_=i[0];if(i.length>1){let X_=G(b,$),M_=Math.abs(G(W_,_)-X_);for(let U_=1;U_<i.length;U_++){let Y_=Math.abs(G(i[U_],_)-X_);if(Y_<M_)M_=Y_,W_=i[U_]}}z.push({oldName:W_.name,newName:b.name,filePath:O,kind:N}),Y.add(b),X.add(W_)}}}let M=z.filter((O)=>!O.oldName.includes("."));for(let O of M){let L=`${O.oldName}.`,C=`${O.newName}.`,N=Q.filter((R)=>R.filePath===O.filePath&&R.name.startsWith(L)&&!X.has(R)),w=J.filter((R)=>R.filePath===O.filePath&&R.name.startsWith(C)&&!Y.has(R));for(let R of N){let F=R.name.slice(L.length),G=w.find((E)=>E.name.slice(C.length)===F);if(G)z.push({oldName:R.name,newName:G.name,filePath:O.filePath,kind:R.kind}),Y.add(G),X.add(R)}}return{renamed:z,added:J.filter((O)=>!Y.has(O)),removed:Q.filter((O)=>!X.has(O))}}var zQ=100,w1=50;class j0{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=n_(_.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")){t_(this.opts.projectRoot),this.tsconfigPathsRaw=n_(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??o_;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()},zQ)}async shutdown(){if(this.debounceTimer!==null)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.currentIndexing)await this.currentIndexing}startIndex(_,$){if(this.indexingLock){if($)return this.pendingFullIndex=!0,new Promise((Q,z)=>{this.pendingFullIndexWaiters.push({resolve:Q,reject:z})});return this.currentIndexing}this.indexingLock=!0;let J=this.doIndex(_,$).then((Q)=>{return this.fireCallbacks(Q),Q}).finally(()=>{if(this.indexingLock=!1,this.currentIndexing=null,this.pendingFullIndex){this.pendingFullIndex=!1;let Q=this.pendingFullIndexWaiters.splice(0);this.startIndex(void 0,!0).then((z)=>{for(let W of Q)W.resolve(z)}).catch((z)=>{for(let W of Q)W.reject(z)})}else if(this.pendingEvents.length>0){let Q=this.pendingEvents.splice(0);this.startIndex(Q,!1).catch((z)=>this.logger.error("[IndexCoordinator] incremental drain error",z))}});return this.currentIndexing=J,J}async doIndex(_,$){let J=Date.now(),{fileRepo:Q,symbolRepo:z,relationRepo:W,dbConnection:Z}=this.opts;if(this.boundariesRefresh)await this.boundariesRefresh,this.boundariesRefresh=null;let Y,X;if(_!==void 0)Y=_.filter((U)=>U.eventType==="create"||U.eventType==="change").map((U)=>({filePath:U.filePath,contentHash:"",mtimeMs:0,size:0})),X=_.filter((U)=>U.eventType==="delete").map((U)=>U.filePath);else{let U=new Map;for(let K of this.opts.boundaries)for(let[B,A]of Q.getFilesMap(K.project))U.set(B,A);let H=await Y1({projectRoot:this.opts.projectRoot,extensions:this.opts.extensions,ignorePatterns:this.opts.ignorePatterns,fileRepo:{getFilesMap:()=>U}});Y=H.changed,X=H.deleted}let M=await this.tsconfigPathsRaw??void 0,O=new Map;for(let U of X){let H=a(U,this.opts.boundaries),K=z.getFileSymbols(H,U);O.set(U,K)}let L=crypto.randomUUID(),C=new Map,N=new Map,w=(U)=>({name:U.name,filePath:U.filePath,kind:U.kind,fingerprint:U.fingerprint,structuralFingerprint:U.structuralFingerprint??null,startLine:U.startLine,isExported:U.isExported??0});if($)for(let U of this.opts.boundaries)for(let H of Q.getAllFiles(U.project))for(let K of z.getFileSymbols(U.project,H.filePath))C.set(`${K.filePath}::${K.name}`,w(K));else{for(let U of Y){let H=a(U.filePath,this.opts.boundaries);for(let K of z.getFileSymbols(H,U.filePath))C.set(`${K.filePath}::${K.name}`,w(K))}for(let[,U]of O)for(let H of U)C.set(`${H.filePath}::${H.name}`,w(H))}let R=(U)=>`${U.type}|${U.srcFilePath}|${U.dstFilePath??""}|${U.srcSymbolName??""}|${U.dstSymbolName??""}|${K_(U.metaJson??"")}`,F=new Map;if($)for(let U of this.opts.boundaries)for(let H of Q.getAllFiles(U.project))for(let K of W.getOutgoing(U.project,H.filePath))F.set(R(K),K);else{for(let U of Y){let H=a(U.filePath,this.opts.boundaries);for(let K of W.getOutgoing(H,U.filePath))F.set(R(K),K)}for(let U of X){let H=a(U,this.opts.boundaries);for(let K of W.getOutgoing(H,U))F.set(R(K),K)}}let{annotationRepo:G,changelogRepo:E}=this.opts,b=()=>{for(let U of X){let H=a(U,this.opts.boundaries);if(z.deleteFileSymbols(H,U),W.deleteFileRelations(H,U),W.deleteIncomingRelations(H,U),G)G.deleteFileAnnotations(H,U);Q.deleteFile(H,U)}},m=0,l=async()=>{let{projectRoot:U,boundaries:H}=this.opts,{parseCache:K}=this.opts,B=0,A=0,I=0,S=[],T=[];for(let g of Y)try{let P=g_(U,g.filePath),d=Bun.file(P),J_=await d.text(),V_=g.contentHash||K_(J_),B_=a(g.filePath,H);Q.upsertFile({project:B_,filePath:g.filePath,mtimeMs:d.lastModified,size:d.size,contentHash:V_,updatedAt:new Date().toISOString(),lineCount:J_.split(`
|
|
6
|
+
`).length});let C_=(this.opts.parseSourceFn??v_)(P,J_);if(B1(C_))throw C_.data;let r$=C_;T.push({filePath:g.filePath,text:J_,contentHash:V_,parsed:r$,project:B_})}catch(P){this.logger.error(`[IndexCoordinator] Failed to prepare ${g.filePath}:`,P),S.push(g.filePath)}let j=new Set;for(let g of H)for(let[P]of Q.getFilesMap(g.project))j.add(`${g.project}::${P}`);return Z.transaction(()=>{for(let g of T){if(N0({parsed:g.parsed,project:g.project,filePath:g.filePath,contentHash:g.contentHash,symbolRepo:z}),A+=S0({ast:g.parsed.program,project:g.project,filePath:g.filePath,relationRepo:W,projectRoot:U,tsconfigPaths:M,knownFiles:j,boundaries:H,module:g.parsed.module}),G)I+=F0({parsed:g.parsed,project:g.project,filePath:g.filePath,annotationRepo:G});K.set(g.filePath,g.parsed),B+=z.getFileSymbols(g.project,g.filePath).length}}),{symbols:B,relations:A,annotations:I,failedFiles:S}},i=0,W_=0,X_=[];if($){let{projectRoot:U,boundaries:H}=this.opts,{parseCache:K}=this.opts,B=[];for(let I=0;I<Y.length;I+=w1){let S=Y.slice(I,I+w1),T=await Promise.allSettled(S.map(async(j)=>{let g=g_(U,j.filePath),P=Bun.file(g),d=await P.text(),J_=j.contentHash||K_(d);return{filePath:j.filePath,text:d,contentHash:J_,mtimeMs:P.lastModified,size:P.size}}));for(let j=0;j<T.length;j++){let g=T[j];if(g.status==="fulfilled")B.push(g.value);else this.logger.error("[IndexCoordinator] Failed to pre-read file:",g.reason),X_.push(S[j].filePath)}}let A=[];Z.transaction(()=>{for(let T of B){let j=a(T.filePath,H);Q.deleteFile(j,T.filePath)}for(let T of X){let j=a(T,H);if(z.deleteFileSymbols(j,T),W.deleteFileRelations(j,T),W.deleteIncomingRelations(j,T),G)G.deleteFileAnnotations(j,T);Q.deleteFile(j,T)}for(let T of B){let j=a(T.filePath,H);Q.upsertFile({project:j,filePath:T.filePath,mtimeMs:T.mtimeMs,size:T.size,contentHash:T.contentHash,updatedAt:new Date().toISOString(),lineCount:T.text.split(`
|
|
7
|
+
`).length})}let I=new Set;for(let T of H)for(let[j]of Q.getFilesMap(T.project))I.add(`${T.project}::${j}`);let S=this.opts.parseSourceFn??v_;for(let T of B){let j=a(T.filePath,H),g=S(g_(U,T.filePath),T.text);if(B1(g))throw g.data;let P=g;if(A.push({filePath:T.filePath,parsed:P}),N0({parsed:P,project:j,filePath:T.filePath,contentHash:T.contentHash,symbolRepo:z}),G)m+=F0({parsed:P,project:j,filePath:T.filePath,annotationRepo:G});W_+=S0({ast:P.program,project:j,filePath:T.filePath,relationRepo:W,projectRoot:U,tsconfigPaths:M,knownFiles:I,boundaries:H,module:P.module}),i+=z.getFileSymbols(j,T.filePath).length}});for(let I of A)K.set(I.filePath,I.parsed)}else{b();let U=await l();i=U.symbols,W_=U.relations,m=U.annotations,X_=U.failedFiles}for(let U of Y){let H=a(U.filePath,this.opts.boundaries);for(let K of z.getFileSymbols(H,U.filePath))N.set(`${K.filePath}::${K.name}`,w(K))}let M_=new Map;for(let U of Y){let H=a(U.filePath,this.opts.boundaries);for(let K of W.getOutgoing(H,U.filePath))M_.set(R(K),K)}let U_=(U)=>({type:U.type,srcFilePath:U.srcFilePath,dstFilePath:U.dstFilePath,srcSymbolName:U.srcSymbolName,dstSymbolName:U.dstSymbolName,dstProject:U.dstProject,metaJson:U.metaJson}),Y_={added:[...M_.entries()].filter(([U])=>!F.has(U)).map(([,U])=>U_(U)),removed:[...F.entries()].filter(([U])=>!M_.has(U)).map(([,U])=>U_(U))},c={added:[],modified:[],removed:[]};for(let[U,H]of N){let K=C.get(U);if(!K)c.added.push({name:H.name,filePath:H.filePath,kind:H.kind,isExported:Boolean(H.isExported)});else{let B=K.fingerprint!==H.fingerprint,A=K.isExported!==H.isExported,I=K.structuralFingerprint!==null&&H.structuralFingerprint!==null&&K.structuralFingerprint!==H.structuralFingerprint;if(B||A||I)c.modified.push({name:H.name,filePath:H.filePath,kind:H.kind,isExported:Boolean(H.isExported)})}}for(let[U,H]of C)if(!N.has(U))c.removed.push({name:H.name,filePath:H.filePath,kind:H.kind,isExported:Boolean(H.isExported)});let s=L1(C,N),D_=new Set(s.renamed.map((U)=>`${U.filePath}::${U.oldName}`)),D=new Set(s.renamed.map((U)=>`${U.filePath}::${U.newName}`));c.added=c.added.filter((U)=>!D.has(`${U.filePath}::${U.name}`)),c.removed=c.removed.filter((U)=>!D_.has(`${U.filePath}::${U.name}`));let q=[];if(!$){for(let[H,K]of O)for(let B of K){if(!B.fingerprint)continue;let A=a(H,this.opts.boundaries),I=z.getByFingerprint(A,B.fingerprint);if(I.length===1){let S=I[0];W.retargetRelations({dstProject:A,oldFile:H,oldSymbol:B.name,newFile:S.filePath,newSymbol:S.name}),q.push({name:S.name,filePath:S.filePath,kind:S.kind,oldFilePath:H,isExported:S.isExported??0})}}let U=new Set(q.map((H)=>`${H.oldFilePath}::${H.name}`));for(let H of s.removed){if(U.has(`${H.filePath}::${H.name}`))continue;let B=C.get(`${H.filePath}::${H.name}`)?.fingerprint;if(!B)continue;let A=a(H.filePath,this.opts.boundaries),I=z.getByFingerprint(A,B);if(I.length===1){let S=I[0];if(S.filePath!==H.filePath||S.name!==H.name)W.retargetRelations({dstProject:A,oldFile:H.filePath,oldSymbol:H.name,newFile:S.filePath,newSymbol:S.name}),q.push({name:S.name,filePath:S.filePath,kind:S.kind,oldFilePath:H.filePath,isExported:S.isExported??0})}}}if(q.length){let U=new Set(q.map((K)=>`${K.filePath}::${K.name}`)),H=new Set(q.map((K)=>`${K.oldFilePath}::${K.name}`));c.added=c.added.filter((K)=>!U.has(`${K.filePath}::${K.name}`)),c.removed=c.removed.filter((K)=>!H.has(`${K.filePath}::${K.name}`))}if(E){let U=new Date().toISOString(),H=$?1:0,K=[];for(let B of c.added){let A=`${B.filePath}::${B.name}`,I=N.get(A),S=a(B.filePath,this.opts.boundaries);K.push({project:S,changeType:"added",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:null,fingerprint:I?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:L})}for(let B of c.modified){let A=N.get(`${B.filePath}::${B.name}`),I=a(B.filePath,this.opts.boundaries);K.push({project:I,changeType:"modified",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:null,fingerprint:A?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:L})}for(let B of c.removed){let A=`${B.filePath}::${B.name}`,I=C.get(A),S=a(B.filePath,this.opts.boundaries);K.push({project:S,changeType:"removed",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:null,fingerprint:I?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:L})}for(let B of s.renamed){let A=N.get(`${B.filePath}::${B.newName}`),I=a(B.filePath,this.opts.boundaries);K.push({project:I,changeType:"renamed",symbolName:B.newName,symbolKind:B.kind,filePath:B.filePath,oldName:B.oldName,oldFilePath:null,fingerprint:A?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:L})}for(let B of q){let A=N.get(`${B.filePath}::${B.name}`),I=a(B.filePath,this.opts.boundaries);K.push({project:I,changeType:"moved",symbolName:B.name,symbolKind:B.kind,filePath:B.filePath,oldName:null,oldFilePath:B.oldFilePath,fingerprint:A?.fingerprint??null,changedAt:U,isFullIndex:H,indexRunId:L})}if(K.length)try{Z.transaction(()=>{E.insertBatch(K)})}catch(B){this.logger.error("[IndexCoordinator] changelog insert failed:",B)}if(Date.now()-this.lastPruneAt>3600000){this.lastPruneAt=Date.now();let B=new Date(Date.now()-2592000000).toISOString();try{for(let A of this.opts.boundaries)E.pruneOlderThan(A.project,B)}catch(A){this.logger.error("[IndexCoordinator] changelog pruning failed:",A)}}}return{indexedFiles:Y.length,removedFiles:X.length,totalSymbols:i,totalRelations:W_,totalAnnotations:m,durationMs:Date.now()-J,changedFiles:Y.map((U)=>U.filePath),deletedFiles:[...X],failedFiles:X_,changedSymbols:c,renamedSymbols:s.renamed.map((U)=>({oldName:U.oldName,newName:U.newName,filePath:U.filePath,kind:U.kind,isExported:Boolean(N.get(`${U.filePath}::${U.newName}`)?.isExported)})),movedSymbols:q.map((U)=>({name:U.name,oldFilePath:U.oldFilePath,newFilePath:U.filePath,kind:U.kind,isExported:Boolean(U.isExported)})),changedRelations:Y_}}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 WQ(_){try{return process.kill(_,0),!0}catch($){if(typeof $==="object"&&$&&"code"in $)return $.code!=="ESRCH";return!0}}function YQ(_){let $=new Date(_).getTime();return Number.isNaN($)?0:$}function I1(_,$,J={}){let Q=J.now??Date.now,z=J.isAlive??WQ,W=J.staleAfterSeconds??60,Z=J.instanceId;return _.immediateTransaction(()=>{let Y=_.selectOwner();if(!Y)return _.insertOwner($,Z),"owner";let X=Math.floor((Q()-YQ(Y.heartbeat_at))/1000),M=z(Y.pid);if(M&&Z&&Y.instance_id&&Y.instance_id!==Z&&Y.pid===$)return _.replaceOwner($,Z),"owner";if(M&&X<W)return"reader";return _.replaceOwner($,Z),"owner"})}function D1(_,$){_.deleteOwner($)}function C1(_,$){_.touchOwner($)}class l_{#_;#$=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 k0{lru;constructor(_=500){this.lru=new l_(_)}get(_){return this.lru.get(_)}set(_,$){this.lru.set(_,$)}invalidate(_){this.lru.delete(_)}invalidateAll(){this.lru.clear()}size(){return this.lru.size}}function g0(_){let{symbolRepo:$,project:J,query:Q}=_,z=Q.project??J,W={kind:Q.kind,filePath:Q.filePath,isExported:Q.isExported,project:z,limit:Q.limit,resolvedType:Q.resolvedType};if(Q.text)if(Q.exact)W.exactName=Q.text;else{let Y=k_(Q.text);if(Y)W.ftsQuery=Y}if(Q.decorator)W.decorator=Q.decorator;if(Q.regex)W.regex=Q.regex;return $.searchByQuery(W).map((Y)=>{let X=Y.name.indexOf(".");return{id:Y.id,filePath:Y.filePath,kind:Y.kind,name:Y.name,memberName:X>=0?Y.name.slice(X+1):null,span:{start:{line:Y.startLine,column:Y.startColumn},end:{line:Y.endLine,column:Y.endColumn}},isExported:Y.isExported===1,signature:Y.signature,fingerprint:Y.fingerprint,detail:Y.detailJson?(()=>{try{return JSON.parse(Y.detailJson)}catch{return{}}})():{}}})}function v0(_){let{relationRepo:$,project:J,query:Q}=_;if(Q.srcFilePath&&Q.srcFilePathPattern)throw new V("validation","srcFilePath and srcFilePathPattern are mutually exclusive");if(Q.dstFilePath&&Q.dstFilePathPattern)throw new V("validation","dstFilePath and dstFilePathPattern are mutually exclusive");let z=Q.project??J,W=Q.limit,Z=!!(Q.srcFilePathPattern||Q.dstFilePathPattern),Y=Z?void 0:W,M=$.searchRelations({srcFilePath:Q.srcFilePath,srcSymbolName:Q.srcSymbolName,dstFilePath:Q.dstFilePath,dstSymbolName:Q.dstSymbolName,dstProject:Q.dstProject,type:Q.type,project:z,specifier:Q.specifier,isExternal:Q.isExternal,limit:Y}).map((O)=>{let L;if(O.metaJson)try{L=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:L}});if(Q.srcFilePathPattern||Q.dstFilePathPattern){let O=Q.srcFilePathPattern?new Bun.Glob(Q.srcFilePathPattern):null,L=Q.dstFilePathPattern?new Bun.Glob(Q.dstFilePathPattern):null;M=M.filter((C)=>(!O||O.match(C.srcFilePath))&&(!L||C.dstFilePath===null||L.match(C.dstFilePath)))}if(Z&&W!==void 0&&M.length>W)M=M.slice(0,W);return M}import{findInFiles as ZQ,Lang as XQ}from"@ast-grep/napi";function UQ(_){let $=new Set,J=/\${1,3}([A-Z_][A-Z_0-9]*)/g,Q;while((Q=J.exec(_))!==null)$.add(Q[0]);return[...$]}function VQ(_){return _.replace(/^\$+/,"")}function OQ(_,$){if($.length===0)return;let J={},Q=!1;for(let z of $){let W=VQ(z),Z=_.getMatch(W);if(Z){let X=Z.range();J[z]={text:Z.text(),startLine:X.start.line+1,endLine:X.end.line+1,startColumn:X.start.column,endColumn:X.end.column,startOffset:X.start.index,endOffset:X.end.index},Q=!0;continue}let Y=_.getMultipleMatches(W);if(Y.length>0){let X=Y[0].range(),M=Y[Y.length-1].range();J[z]={text:Y.map((O)=>O.text()).join(", "),startLine:X.start.line+1,endLine:M.end.line+1,startColumn:X.start.column,endColumn:M.end.column,startOffset:X.start.index,endOffset:M.end.index},Q=!0}}return Q?J:void 0}async function E0(_){if(_.filePaths.length===0)return[];let $=UQ(_.pattern),J=[];return await ZQ(XQ.TypeScript,{paths:_.filePaths,matcher:{rule:{pattern:_.pattern}}},(Q,z)=>{if(Q){console.warn("[patternSearch] findInFiles callback error:",Q);return}for(let W of z){let Z=W.range(),Y={filePath:W.getRoot().filename(),startLine:Z.start.line+1,endLine:Z.end.line+1,startColumn:Z.start.column,endColumn:Z.end.column,startOffset:Z.start.index,endOffset:Z.end.index,matchedText:W.text()},X=OQ(W,$);if(X)Y.captures=X;J.push(Y)}}),J}import __ from"typescript";import{isErr as jQ}from"@zipbul/result";import w_ from"typescript";import HQ from"path";import{err as u0}from"@zipbul/result";function KQ(_){try{return s0("fs").readFileSync(_,"utf-8")}catch{return}}function MQ(_){try{return s0("fs").readFileSync(_,"utf-8")}catch{return}}class Q0{#_;#$;#Q=!1;__testing__;constructor(_,$){this.#_=_,this.#$=$,this.__testing__={host:$}}static create(_,$={}){let J=$.readConfigFile??KQ,Q=$.resolveNonTrackedFile??MQ,z=HQ.dirname(_),W=J(_);if(W===void 0)return u0(new V("semantic",`tsconfig not found: ${_}`));let Z=w_.parseJsonText(_,W),Y=Z.parseDiagnostics;if(Y&&Y.length>0){let L=Y.map((C)=>w_.flattenDiagnosticMessageText(C.messageText,`
|
|
8
|
+
`)).join("; ");return u0(new V("semantic",`tsconfig parse error: ${L}`))}let X=w_.parseJsonSourceFileConfigFileContent(Z,{useCaseSensitiveFileNames:!0,readDirectory:()=>[],fileExists:(L)=>J(L)!==void 0||Q(L)!==void 0,readFile:(L)=>J(L)??Q(L)},z);if(X.errors.length>0){let L=X.errors.filter((C)=>C.category===w_.DiagnosticCategory.Error&&C.code!==18003);if(L.length>0){let C=L.map((N)=>w_.flattenDiagnosticMessageText(N.messageText,`
|
|
9
|
+
`)).join("; ");return u0(new V("semantic",`tsconfig compile error: ${C}`))}}let M=new A1(X.fileNames,X.options,z,Q),O=w_.createLanguageService(M);return new Q0(O,M)}get isDisposed(){return this.#Q}getProgram(){this.#z();let _=this.#_.getProgram();if(!_)throw Error("TscProgram: LanguageService returned null Program");return _}getChecker(){return this.#z(),this.getProgram().getTypeChecker()}getCompilerOptions(){return this.#z(),this.#$.getCompilationSettings()}getLanguageService(){return this.#z(),this.#_}notifyFileChanged(_,$){if(this.#Q)return;this.#$.updateFile(_,$)}removeFile(_){if(this.#Q)return;this.#$.removeFile(_)}dispose(){if(this.#Q)return;this.#Q=!0,this.#_.dispose()}#z(){if(this.#Q)throw Error("TscProgram is disposed")}}class A1{#_;#$;#Q;#z;#W=new Map;#Y=new Map;#J=new Map;constructor(_,$,J,Q){this.#_=new Set(_),this.#$=$,this.#Q=J,this.#z=Q}updateFile(_,$){let J=this.#W.get(_);if(J){if(J.content===$)return;this.#Y.delete(`${_}:${J.version}`),J.version+=1,J.content=$}else this.#W.set(_,{version:1,content:$})}removeFile(_){let $=this.#W.get(_);if($)this.#Y.delete(`${_}:${$.version}`);this.#W.delete(_),this.#_.delete(_)}getScriptFileNames(){let _=[...this.#W.keys()];return[...[...this.#_].filter((J)=>!this.#W.has(J)),..._]}getScriptVersion(_){let $=this.#W.get(_);return $?String($.version):"0"}getScriptSnapshot(_){let $=this.#W.get(_);if($){let z=`${_}:${$.version}`,W=this.#Y.get(z);if(!W)W=w_.ScriptSnapshot.fromString($.content),this.#Y.set(z,W);return W}let J=this.#J.get(_);if(J)return J;let Q=this.#z(_);if(Q!==void 0)return J=w_.ScriptSnapshot.fromString(Q),this.#J.set(_,J),J;return}getCurrentDirectory(){return this.#Q}getCompilationSettings(){return this.#$}getDefaultLibFileName(_){return w_.getDefaultLibFilePath(_)}fileExists(_){if(this.#W.has(_))return!0;return this.#z(_)!==void 0}readFile(_){let $=this.#W.get(_);if($)return $.content;return this.#z(_)}}import x from"typescript";import z0 from"typescript";function e(_,$){if($<0||$>=_.getEnd())return;let J,Q=(z)=>{if($<z.getStart(_,!1)||$>=z.getEnd())return;J=z,z0.forEachChild(z,Q)};return z0.forEachChild(_,Q),J}function W0(_,$,J){if($<0||J<=$||J>_.getEnd())return;let Q,z=(W)=>{let Z=W.getStart(_,!1),Y=W.getEnd();if($<Z||J>Y)return;if(Z===$&&Y===J)Q=W;z0.forEachChild(W,z)};return z0.forEachChild(_,z),Q}var Y0=8;function LQ(_){return!!(_.flags&x.TypeFlags.Object)&&!!(_.objectFlags&x.ObjectFlags.Reference)}function H_(_,$,J=0,Q){if(Q){let w=Q.get($);if(w)return w}let z=_.typeToString($),W=$.flags,Z=!!(W&x.TypeFlags.Union),Y=!!(W&x.TypeFlags.Intersection),X;if(J<Y0&&LQ($)){let w=_.getTypeArguments($);if(w.length>0)X=w}let M=!!(W&x.TypeFlags.TypeParameter)||X!==void 0&&X.length>0,O;if(Z&&J<Y0)O=$.types.map((w)=>H_(_,w,J+1,Q));else if(Y&&J<Y0)O=$.types.map((w)=>H_(_,w,J+1,Q));let L;if(X&&X.length>0)L=X.map((w)=>H_(_,w,J+1,Q));let C;if(J<Y0&&!!(W&x.TypeFlags.Object)&&!Z&&!Y){let w=_.getPropertiesOfType($);if(w.length>0&&w.length<=50){let R=$.symbol?.declarations?.[0];C=[];for(let F of w){let G=F.declarations?.[0]??R;if(!G)continue;try{let E=_.getTypeOfSymbolAtLocation(F,G);C.push({name:F.getName(),type:H_(_,E,J+1,Q)})}catch{}}if(C.length===0)C=void 0}}let N={text:z,flags:W,isUnion:Z,isIntersection:Y,isGeneric:M,members:O,typeArguments:L,properties:C};if(Q)Q.set($,N);return N}function Z0(_,$,J){if($.flags&x.TypeFlags.Any)return!1;if($.isUnion()){let Z=$.types.filter((Y)=>!(Y.flags&(x.TypeFlags.Void|x.TypeFlags.Undefined|x.TypeFlags.Null)));return J?Z.some((Y)=>Z0(_,Y,J)):Z.length>0&&Z.every((Y)=>Z0(_,Y,J))}if($.isIntersection())return $.types.some((Z)=>Z0(_,Z,J));let Q=_.getPropertyOfType($,"then");if(!Q)return!1;let z=Q.declarations?.[0];if(!z)return!1;return _.getTypeOfSymbolAtLocation(Q,z).getCallSignatures().some((Z)=>Z.parameters.length>=1)}function BQ(_){return x.isFunctionDeclaration(_)||x.isVariableDeclaration(_)||x.isClassDeclaration(_)||x.isInterfaceDeclaration(_)||x.isTypeAliasDeclaration(_)||x.isEnumDeclaration(_)||x.isMethodDeclaration(_)||x.isPropertyDeclaration(_)||x.isPropertySignature(_)||x.isMethodSignature(_)}var b0="/__gildash_type_probe__.ts";class P0{program;#_=null;constructor(_){this.program=_}#$(_){if(this.#_===_)return;this.program.notifyFileChanged(b0,`declare const __gildash_probe__: ${_};`),this.#_=_}#Q(_,$){let J=_.getSourceFile(b0);if(!J)return null;let Q=J.statements[0];if(!Q||!x.isVariableStatement(Q))return null;let z=Q.declarationList.declarations[0];if(!z)return null;return $.getTypeAtLocation(z.name)}clearProbe(){if(this.#_!==null)this.program.removeFile(b0),this.#_=null}collectAt(_,$){let J=this.program.getProgram(),Q=J.getTypeChecker();if($<0)return null;let z=J.getSourceFile(_);if(!z)return null;if($>=z.getEnd())return null;let W=e(z,$);if(!W)return null;if(!x.isIdentifier(W)&&!x.isTypeNode(W))return null;try{let Z=Q.getTypeAtLocation(W);return H_(Q,Z,0,new Map)}catch{return null}}collectAtSpan(_,$){let J=this.program.getProgram(),Q=J.getTypeChecker(),z=J.getSourceFile(_);if(!z)return null;let W=W0(z,$.start,$.end);if(!W)return null;try{let Z=Q.getTypeAtLocation(W);return H_(Q,Z,0,new Map)}catch{return null}}isThenableAtSpan(_,$,J){let Q=this.program.getProgram(),z=Q.getTypeChecker(),W=Q.getSourceFile(_);if(!W)return null;let Z=W0(W,$.start,$.end);if(!Z)return null;try{let Y=z.getTypeAtLocation(Z);return Z0(z,Y,J?.anyConstituent??!0)}catch{return null}}contextualCallReturnsAtSpan(_,$){let J=this.program.getProgram(),Q=J.getTypeChecker(),z=J.getSourceFile(_);if(!z)return null;let W=W0(z,$.start,$.end);if(!W||!x.isExpression(W))return null;try{let Z=Q.getContextualType(W);if(!Z)return null;let Y=Z.isUnion()?Z.types.filter((O)=>!(O.flags&(x.TypeFlags.Void|x.TypeFlags.Undefined|x.TypeFlags.Null))):[Z],X=new Map,M=[];for(let O of Y)for(let L of O.getCallSignatures()){let C=Q.getReturnTypeOfSignature(L);M.push(H_(Q,C,0,X))}return M}catch{return null}}isAssignableTo(_,$,J,Q){let z=this.program.getProgram(),W=z.getTypeChecker(),Z=z.getSourceFile(_);if(!Z)return null;let Y=e(Z,$);if(!Y||!x.isIdentifier(Y))return null;let X=z.getSourceFile(J);if(!X)return null;let M=e(X,Q);if(!M||!x.isIdentifier(M))return null;try{let O=W.getTypeAtLocation(Y),L=W.getTypeAtLocation(M);return W.isTypeAssignableTo(O,L)}catch{return null}}isAssignableToType(_,$,J,Q){this.#$(J);let z=this.program.getProgram(),W=z.getTypeChecker(),Z=z.getSourceFile(_);if(!Z)return null;let Y=e(Z,$);if(!Y||!x.isIdentifier(Y)&&!x.isTypeNode(Y))return null;try{let X=this.#Q(z,W);if(!X)return null;let M=W.getTypeAtLocation(Y);if(Q?.anyConstituent&&M.isUnion())return M.types.some((O)=>W.isTypeAssignableTo(O,X));return W.isTypeAssignableTo(M,X)}catch{return null}}isAssignableToTypeAtPositions(_,$,J,Q){let z=new Map;if($.length===0)return z;this.#$(J);let W=this.program.getProgram(),Z=W.getTypeChecker(),Y=W.getSourceFile(_);if(!Y)return z;try{let X=this.#Q(W,Z);if(!X)return z;let M=Y.getEnd();for(let O of $){if(O<0||O>=M)continue;let L=e(Y,O);if(!L||!x.isIdentifier(L)&&!x.isTypeNode(L))continue;try{let C=Z.getTypeAtLocation(L);if(Q?.anyConstituent&&C.isUnion())z.set(O,C.types.some((N)=>Z.isTypeAssignableTo(N,X)));else z.set(O,Z.isTypeAssignableTo(C,X))}catch{}}}catch{}return z}collectAtPositions(_,$){let J=new Map;if($.length===0)return J;let Q=this.program.getProgram(),z=Q.getTypeChecker(),W=Q.getSourceFile(_);if(!W)return J;let Z=W.getEnd(),Y=new Map;for(let X of $){if(X<0||X>=Z)continue;let M=e(W,X);if(!M)continue;if(!x.isIdentifier(M)&&!x.isTypeNode(M))continue;try{let O=z.getTypeAtLocation(M);J.set(X,H_(z,O,0,Y))}catch{}}return J}collectFile(_){let $=new Map,J=this.program.getProgram(),Q=J.getTypeChecker(),z=J.getSourceFile(_);if(!z)return $;let W=new Map;function Z(Y){if(BQ(Y)&&Y.name&&x.isIdentifier(Y.name)){let X=Y.name;try{let M=Q.getTypeAtLocation(X),O=X.getStart(z);$.set(O,H_(Q,M,0,W))}catch{}}x.forEachChild(Y,Z)}return Z(z),$}}import I_ from"typescript";var wQ=1000,IQ=1;function DQ(_){let $=_.declarations?.[0],J=$?.getSourceFile(),Q=$?I_.getNameOfDeclaration($):void 0;return{name:_.getName(),filePath:J?.fileName??"",position:Q?.getStart(J,!1)??$?.getStart(J,!1)??0}}function X0(_,$=0,J){let Q=_.declarations?.[0],z=Q?.getSourceFile(),W=Q?I_.getNameOfDeclaration(Q):void 0,Z=z?.fileName??"",Y=W?.getStart(z,!1)??Q?.getStart(z,!1)??0,X={name:_.getName(),filePath:Z,position:Y},M=_;if(M.parent)X.parent=DQ(M.parent);let O=J&&!!(_.flags&I_.SymbolFlags.Alias)?J.getAliasedSymbol(_):_;if($<IQ){let L=O.flags,C=!!(L&I_.SymbolFlags.Enum),N=!!(L&(I_.SymbolFlags.NamespaceModule|I_.SymbolFlags.ValueModule)),w=!!(L&(I_.SymbolFlags.Class|I_.SymbolFlags.Interface));if(C&&O.exports&&O.exports.size>0){let R=[];O.exports.forEach((F)=>{R.push(X0(F,$+1,J))}),X.members=R}else if(w&&O.members&&O.members.size>0){let R=[];O.members.forEach((F)=>{R.push(X0(F,$+1,J))}),X.members=R}if(N&&O.exports&&O.exports.size>0){let R=[];O.exports.forEach((F)=>{R.push(X0(F,$+1,J))}),X.exports=R}}return X}class f0{#_;#$;constructor(_,$=wQ){this.#_=_,this.#$=new l_($)}get(_,$){if(this.#_.isDisposed)return null;let J=`${_}:${$}`,Q=this.#$.get(J);if(Q!==void 0)return Q;let z=this.#_.getProgram(),W=z.getSourceFile(_);if(!W)return null;let Z=e(W,$);if(!Z||!I_.isIdentifier(Z))return null;let Y=z.getTypeChecker(),X=Y.getSymbolAtLocation(Z);if(!X)return null;let M=X0(X,0,Y);return this.#$.set(J,M),M}clear(){this.#$.clear()}}import p from"typescript";import k from"typescript";function y0(_){if(_.getSourceFile().isDeclarationFile)return!0;for(let $=_;$;$=$.parent)if(CQ($))return!0;return!1}function CQ(_){if(!k.canHaveModifiers(_))return!1;return k.getModifiers(_)?.some((J)=>J.kind===k.SyntaxKind.DeclareKeyword)??!1}function x0(_){let $=(Q,z)=>({kind:Q,pos:z.getStart(),end:z.getEnd()}),J=_.parent;while(J){if(k.isSourceFile(J)||k.isModuleDeclaration(J))return $("module",J);if(k.isFunctionLike(J))return $("function",J);if(k.isClassStaticBlockDeclaration(J))return $("function",J);if(k.isPropertyDeclaration(J))return $("function",J);if(k.isBlock(J)){let Q=J.parent;if(Q&&(k.isFunctionLike(Q)||k.isClassStaticBlockDeclaration(Q)))return $("function",Q);return $("block",J)}if(k.isForStatement(J)||k.isForInStatement(J)||k.isForOfStatement(J)||k.isCatchClause(J)||k.isCaseBlock(J)||k.isWithStatement(J))return $("block",J);J=J.parent}return $("module",_.getSourceFile())}function m0(_){let $=_.parent;if(!$)return;if(k.isVariableDeclaration($)&&$.name===_)return"declaration";if(k.isParameter($)&&$.name===_)return"declaration";if(k.isBindingElement($)&&$.name===_)return"declaration";if((k.isForOfStatement($)||k.isForInStatement($))&&$.initializer===_)return"assignment";if((k.isPrefixUnaryExpression($)||k.isPostfixUnaryExpression($))&&$.operand===_&&($.operator===k.SyntaxKind.PlusPlusToken||$.operator===k.SyntaxKind.MinusMinusToken))return"update";let J=_;while(J.parent&&k.isParenthesizedExpression(J.parent))J=J.parent;let Q=J.parent;if(Q&&k.isBinaryExpression(Q)&&Q.left===J)return AQ(Q.operatorToken.kind);if(qQ(_))return"assignment";return}function AQ(_){switch(_){case k.SyntaxKind.EqualsToken:return"assignment";case k.SyntaxKind.PlusEqualsToken:case k.SyntaxKind.MinusEqualsToken:case k.SyntaxKind.AsteriskEqualsToken:case k.SyntaxKind.AsteriskAsteriskEqualsToken:case k.SyntaxKind.SlashEqualsToken:case k.SyntaxKind.PercentEqualsToken:case k.SyntaxKind.LessThanLessThanEqualsToken:case k.SyntaxKind.GreaterThanGreaterThanEqualsToken:case k.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken:case k.SyntaxKind.AmpersandEqualsToken:case k.SyntaxKind.BarEqualsToken:case k.SyntaxKind.CaretEqualsToken:return"compound-assignment";case k.SyntaxKind.AmpersandAmpersandEqualsToken:case k.SyntaxKind.BarBarEqualsToken:case k.SyntaxKind.QuestionQuestionEqualsToken:return"logical-assignment";default:return}}function qQ(_){let $=_.parent;if(!$)return!1;if(!(k.isShorthandPropertyAssignment($)&&$.name===_||k.isPropertyAssignment($)&&$.initializer===_||k.isArrayLiteralExpression($)||k.isSpreadAssignment($)&&$.expression===_||k.isSpreadElement($)&&$.expression===_))return!1;let Q=$;while(Q.parent){let z=Q.parent;if(k.isBinaryExpression(z)&&z.left===Q&&z.operatorToken.kind===k.SyntaxKind.EqualsToken)return!0;if(k.isObjectLiteralExpression(z)||k.isArrayLiteralExpression(z)||k.isPropertyAssignment(z)||k.isShorthandPropertyAssignment(z)||k.isSpreadAssignment(z)||k.isSpreadElement(z)){Q=z;continue}return!1}return!1}class h0{#_;constructor(_){this.#_=_}findAt(_,$){let J=this.#$(_,$);if(!J)return[];let Q=this.#_.getProgram(),z=[];for(let W of J)for(let Z of W.references){let Y=Q.getSourceFile(Z.fileName);if(!Y)continue;z.push(q1(Z,Y))}return z}findEnrichedAt(_,$){let J=this.#$(_,$);if(!J)return[];let Q=this.#_.getProgram(),z=Q.getTypeChecker(),W=[];for(let Z of J){let Y=this.#Q(Z,Q,z);for(let X of Z.references){let M=Q.getSourceFile(X.fileName);if(!M)continue;let O=e(M,X.textSpan.start),L=O&&p.isIdentifier(O)?O:void 0;W.push({...q1(X,M),writeKind:L?m0(L):void 0,isAmbient:Y,enclosingScope:x0(L??M)})}}return W}findFileBindings(_){if(this.#_.isDisposed)return[];let $=this.#_.getProgram(),J=$.getSourceFile(_);if(!J)return[];return n0(J,$.getTypeChecker())}#$(_,$){if(this.#_.isDisposed)return null;let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let z=e(Q,$);if(!z||!p.isIdentifier(z))return null;let W=this.#_.getLanguageService().findReferences(_,$);if(!W||W.length===0)return null;return W}#Q(_,$,J){let Q=_.definition,z=$.getSourceFile(Q.fileName);if(!z)return!1;let W=e(z,Q.textSpan.start);if(!W)return!1;let Y=J.getSymbolAtLocation(W)?.declarations;if(!Y||Y.length===0)return!1;return Y.every(y0)}}function n0(_,$){let J=new Map,Q=(W)=>{if(p.isIdentifier(W)&&!NQ(W)){let Z=TQ(W,$);if(Z){let Y=J.get(Z);if(Y)Y.push(W);else J.set(Z,[W])}}p.forEachChild(W,Q)};p.forEachChild(_,Q);let z=[];for(let[W,Z]of J){let Y=W.declarations;if(!Y||Y.length===0)continue;if(Y.every(RQ))continue;let X=Y.every(y0),M=new Set(Y.map((w)=>p.getNameOfDeclaration(w)).filter((w)=>w!==void 0)),O=Y[0],L=p.getNameOfDeclaration(O)??O,C=O.getSourceFile(),N=Z.map((w)=>{let R=w.getStart(_),{line:F,character:G}=_.getLineAndCharacterOfPosition(R),E=m0(w);return{filePath:_.fileName,position:R,line:F+1,column:G,isDefinition:M.has(w),isWrite:E!==void 0,writeKind:E,isAmbient:X,enclosingScope:x0(w)}});z.push({declaration:{filePath:C.fileName,position:L.getStart(C),name:W.getName(),isAmbient:X},references:N})}return z}function NQ(_){let $=_.parent;return p.isPropertyAccessExpression($)&&$.name===_||p.isQualifiedName($)&&$.right===_||p.isPropertyAssignment($)&&$.name===_||p.isBindingElement($)&&$.propertyName===_||p.isJsxAttribute($)&&$.name===_||p.isImportSpecifier($)&&$.propertyName===_||p.isModuleDeclaration($)&&$.name===_&&($.flags&p.NodeFlags.GlobalAugmentation)!==0}function RQ(_){return p.isPropertyDeclaration(_)||p.isPropertySignature(_)||p.isMethodDeclaration(_)||p.isMethodSignature(_)||p.isGetAccessorDeclaration(_)||p.isSetAccessorDeclaration(_)||p.isEnumMember(_)||p.isParameter(_)&&p.isIndexSignatureDeclaration(_.parent)}function TQ(_,$){let J=_.parent;if(p.isShorthandPropertyAssignment(J))return $.getShorthandAssignmentValueSymbol(J);if(p.isExportSpecifier(J)){let Q=J.parent.parent;if(p.isExportDeclaration(Q)&&Q.moduleSpecifier)return;return(J.propertyName??J.name)===_?$.getExportSpecifierLocalTargetSymbol(J):void 0}return $.getSymbolAtLocation(_)}function q1(_,$){let{line:J,character:Q}=$.getLineAndCharacterOfPosition(_.textSpan.start);return{filePath:_.fileName,position:_.textSpan.start,line:J+1,column:Q,isDefinition:_.isDefinition??!1,isWrite:_.isWriteAccess??!1}}import i_ from"typescript";function N1(_,$,J={}){let Q=i_.createSourceFile(_,$,J.target??i_.ScriptTarget.ESNext,!0),z={target:J.target,module:J.module,jsx:J.jsx??(_.endsWith(".tsx")?i_.JsxEmit.Preserve:void 0),jsxFactory:J.jsxFactory,jsxFragmentFactory:J.jsxFragmentFactory,jsxImportSource:J.jsxImportSource,experimentalDecorators:J.experimentalDecorators,useDefineForClassFields:J.useDefineForClassFields,noLib:!0,noResolve:!0,types:[]},W=i_.createCompilerHost(z,!0);W.getSourceFile=(X)=>X===_?Q:void 0;let Z=i_.createProgram([_],z,W),Y=Z.getSourceFile(_);if(!Y)return[];return n0(Y,Z.getTypeChecker())}import h from"typescript";function SQ(_,$){let J=e(_,$);if(!J)return;if(R1(J))return J;let Q=J.parent;for(let z=0;z<5&&Q;z++){if(R1(Q))return Q;Q=Q.parent}return J}function R1(_){return h.isClassDeclaration(_)||h.isClassExpression(_)||h.isFunctionDeclaration(_)||h.isFunctionExpression(_)||h.isArrowFunction(_)||h.isVariableDeclaration(_)||h.isObjectLiteralExpression(_)}function T1(_){if(h.isClassDeclaration(_)||h.isClassExpression(_))return"class";if(h.isFunctionDeclaration(_)||h.isFunctionExpression(_)||h.isArrowFunction(_))return"function";if(h.isObjectLiteralExpression(_))return"object";if(h.isVariableDeclaration(_)&&_.initializer)return T1(_.initializer);return"class"}function GQ(_,$){if(h.isClassDeclaration(_)||h.isFunctionDeclaration(_))return _.name?.getText($)??"";if(h.isClassExpression(_))return _.name?.getText($)??"";if(h.isVariableDeclaration(_)&&h.isIdentifier(_.name))return _.name.getText($);if(h.isFunctionExpression(_))return _.name?.getText($)??"";if(h.isArrowFunction(_)&&_.parent&&h.isVariableDeclaration(_.parent)){if(h.isIdentifier(_.parent.name))return _.parent.name.getText($)}if(h.isObjectLiteralExpression(_)&&_.parent&&h.isVariableDeclaration(_.parent)){if(h.isIdentifier(_.parent.name))return _.parent.name.getText($)}return""}function FQ(_){if(!h.isClassDeclaration(_)&&!h.isClassExpression(_))return!1;let $=_.heritageClauses;if(!$)return!1;return $.some((J)=>J.token===h.SyntaxKind.ImplementsKeyword)}class p0{#_;constructor(_){this.#_=_}findAt(_,$){if(this.#_.isDisposed)return[];let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z=e(Q,$);if(!z||!h.isIdentifier(z))return[];let Z=this.#_.getLanguageService().getImplementationAtPosition(_,$);if(!Z||Z.length===0)return[];let Y=[];for(let X of Z){if(X.kind===h.ScriptElementKind.interfaceElement||X.kind===h.ScriptElementKind.typeElement)continue;let M=J.getSourceFile(X.fileName);if(!M)continue;let O=SQ(M,X.textSpan.start);if(!O)continue;let L=T1(O),C=GQ(O,M),N=FQ(O);Y.push({filePath:X.fileName,symbolName:C,position:X.textSpan.start,kind:L,isExplicit:N})}return Y}}function kQ(_){if(__.isFunctionDeclaration(_))return"function";if(__.isClassDeclaration(_))return"class";if(__.isInterfaceDeclaration(_))return"interface";if(__.isTypeAliasDeclaration(_))return"type";if(__.isEnumDeclaration(_))return"enum";if(__.isVariableDeclaration(_))return"const";if(__.isVariableStatement(_))return"const";return"unknown"}function S1(_){if(_>=97&&_<=122)return!0;if(_>=65&&_<=90)return!0;if(_>=48&&_<=57)return!0;if(_===95||_===36)return!0;return!1}class U0{#_;#$;#Q;#z;#W;#Y=!1;constructor(_,$,J,Q,z){this.#_=_,this.#$=$,this.#Q=J,this.#z=Q,this.#W=z}static create(_,$={}){let J=Q0.create(_,{readConfigFile:$.readConfigFile,resolveNonTrackedFile:$.resolveNonTrackedFile});if(jQ(J))return J;let Q=J,z=$.typeCollector??new P0(Q),W=$.symbolGraph??new f0(Q),Z=$.referenceResolver??new h0(Q),Y=$.implementationFinder??new p0(Q);return new U0(Q,z,W,Z,Y)}get isDisposed(){return this.#Y}collectTypeAt(_,$){return this.#J(),this.#$.collectAt(_,$)}collectFileTypes(_){return this.#J(),this.#$.collectFile(_)}collectTypesAtPositions(_,$){return this.#J(),this.#$.collectAtPositions(_,$)}collectAtSpan(_,$){return this.#J(),this.#$.collectAtSpan(_,$)}isThenableAtSpan(_,$,J){return this.#J(),this.#$.isThenableAtSpan(_,$,J)}contextualCallReturnsAtSpan(_,$){return this.#J(),this.#$.contextualCallReturnsAtSpan(_,$)}findReferences(_,$){return this.#J(),this.#z.findAt(_,$)}findEnrichedReferences(_,$){return this.#J(),this.#z.findEnrichedAt(_,$)}getFileBindings(_){return this.#J(),this.#z.findFileBindings(_)}getStandaloneFileBindings(_,$){this.#J();let J=this.#_.getCompilerOptions();return N1(_,$,{target:J.target,module:J.module,jsx:J.jsx,jsxFactory:J.jsxFactory,jsxFragmentFactory:J.jsxFragmentFactory,jsxImportSource:J.jsxImportSource,experimentalDecorators:J.experimentalDecorators,useDefineForClassFields:J.useDefineForClassFields})}getFileBindingsBatch(_){this.#J();for(let J of _)this.notifyFileChanged(J.filePath,J.content);let $=new Map;for(let J of _)$.set(J.filePath,this.#z.findFileBindings(J.filePath));return $}findImplementations(_,$){return this.#J(),this.#W.findAt(_,$)}isTypeAssignableTo(_,$,J,Q){return this.#J(),this.#$.isAssignableTo(_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return this.#J(),this.#$.isAssignableToType(_,$,J,Q)}isTypeAssignableToTypeAtPositions(_,$,J,Q){return this.#J(),this.#$.isAssignableToTypeAtPositions(_,$,J,Q)}getSymbolNode(_,$){return this.#J(),this.#Q.get(_,$)}getBaseTypes(_,$){this.#J();let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return null;let z=e(Q,$);if(!z)return null;let W=J.getTypeChecker(),Z=W.getTypeAtLocation(z);if(!(Z.flags&__.TypeFlags.Object)||!(Z.objectFlags&__.ObjectFlags.ClassOrInterface))return null;let Y=W.getBaseTypes(Z);if(!Y||Y.length===0)return[];let X=new Map;return Y.map((M)=>H_(W,M,0,X))}getModuleInterface(_){this.#J();let $=[],J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return{filePath:_,exports:$};let z=J.getTypeChecker(),W=z.getSymbolAtLocation(Q);if(W){let Z=z.getExportsOfModule(W),Y=new Map;for(let X of Z){let M=X.getName(),O=X.declarations?.[0],L="unknown";if(O){if(L=kQ(O),L==="unknown"&&__.isExportAssignment(O))L="const"}let C=null;try{let N=z.getTypeOfSymbolAtLocation(X,O??Q);C=H_(z,N,0,Y)}catch{}$.push({name:M,kind:L,resolvedType:C})}}return{filePath:_,exports:$}}notifyFileChanged(_,$){if(this.#Y)return;this.#_.notifyFileChanged(_,$),this.#Q.clear()}notifyFileDeleted(_){if(this.#Y)return;this.#_.removeFile(_),this.#Q.clear()}lineColumnToPosition(_,$,J){this.#J();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;try{return __.getPositionOfLineAndCharacter(Q,$-1,J)}catch{return null}}findNamePosition(_,$,J){this.#J();let Q=this.#_.getProgram().getSourceFile(_);if(!Q)return null;let z=Q.getFullText(),W=$;while(W<z.length){let Z=z.indexOf(J,W);if(Z<0)return null;let Y=Z>0?z.charCodeAt(Z-1):32,X=Z+J.length<z.length?z.charCodeAt(Z+J.length):32;if(!S1(Y)&&!S1(X))return Z;W=Z+1}return null}getDiagnostics(_,$){this.#J();let J=this.#_.getProgram(),Q=J.getSourceFile(_);if(!Q)return[];let z={[__.DiagnosticCategory.Error]:"error",[__.DiagnosticCategory.Warning]:"warning",[__.DiagnosticCategory.Suggestion]:"suggestion",[__.DiagnosticCategory.Message]:"suggestion"};return(($?.preEmit)?__.getPreEmitDiagnostics(J,Q):J.getSemanticDiagnostics(Q)).map((Z)=>{let Y=1,X=0;if(Z.file&&Z.start!==void 0){let M=__.getLineAndCharacterOfPosition(Z.file,Z.start);Y=M.line+1,X=M.character}return{filePath:Z.file?.fileName??_,line:Y,column:X,message:__.flattenDiagnosticMessageText(Z.messageText,`
|
|
10
|
+
`),code:Z.code,category:z[Z.category]??"error"}})}dispose(){if(this.#Y)return;this.#Y=!0,this.#$.clearProbe(),this.#_.dispose(),this.#Q.clear()}#J(){if(this.#Y)throw Error("SemanticLayer is disposed")}}import{eq as G_,and as G1,sql as gQ}from"drizzle-orm";var F1=80;class d0{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+=F1)this.db.drizzleDb.insert(Z_).values(Q.slice(z,z+F1)).run()}deleteFileAnnotations(_,$){this.db.drizzleDb.delete(Z_).where(G1(G_(Z_.project,_),G_(Z_.filePath,$))).run()}search(_){let $=this.db.drizzleDb.select().from(Z_).where(G1(_.project?G_(Z_.project,_.project):void 0,_.tag?G_(Z_.tag,_.tag):void 0,_.filePath?G_(Z_.filePath,_.filePath):void 0,_.symbolName?G_(Z_.symbolName,_.symbolName):void 0,_.source?G_(Z_.source,_.source):void 0,_.ftsQuery?gQ`${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 b_,and as j1,sql as c_,gt as vQ,gte as EQ}from"drizzle-orm";var k1=80;class l0{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+=k1)this.db.drizzleDb.insert($_).values($.slice(J,J+k1)).run()}getSince(_){return this.db.drizzleDb.select().from($_).where(j1(b_($_.project,_.project),EQ($_.changedAt,_.since),_.symbolName?b_($_.symbolName,_.symbolName):void 0,_.changeTypes?.length?c_`${$_.changeType} IN (${c_.join(_.changeTypes.map(($)=>c_`${$}`),c_`, `)})`:void 0,_.filePath?b_($_.filePath,_.filePath):void 0,_.includeFullIndex?void 0:b_($_.isFullIndex,0),_.indexRunId?b_($_.indexRunId,_.indexRunId):void 0,_.afterId?vQ($_.id,_.afterId):void 0)).orderBy($_.id).limit(_.limit).all()}pruneOlderThan(_,$){return this.db.drizzleDb.delete($_).where(j1(b_($_.project,_),c_`${$_.changedAt} < ${$}`)).run().changes}}function g1(_){let{annotationRepo:$,project:J,query:Q}=_,z=Q.project??J,W;if(Q.text){let Y=k_(Q.text);if(Y)W=Y}return $.search({project:z,tag:Q.tag,filePath:Q.filePath,symbolName:Q.symbolName,source:Q.source,ftsQuery:W,limit:Q.limit}).map((Y)=>({tag:Y.tag,value:Y.value,source:Y.source,filePath:Y.filePath,symbolName:Y.symbolName,span:{start:{line:Y.startLine,column:Y.startColumn},end:{line:Y.endLine,column:Y.endColumn}}}))}class V0{options;adjacencyList=new Map;reverseAdjacencyList=new Map;constructor(_){this.options=_}build(){this.adjacencyList=new Map,this.reverseAdjacencyList=new Map;let $=[this.options.project,...this.options.additionalProjects??[]].flatMap((J)=>[...this.options.relationRepo.getByType(J,"imports"),...this.options.relationRepo.getByType(J,"type-references"),...this.options.relationRepo.getByType(J,"re-exports")]);for(let J of $){let{srcFilePath:Q,dstFilePath:z}=J;if(z===null)continue;if(!this.adjacencyList.has(Q))this.adjacencyList.set(Q,new Set);if(this.adjacencyList.get(Q).add(z),!this.adjacencyList.has(z))this.adjacencyList.set(z,new Set);if(!this.reverseAdjacencyList.has(z))this.reverseAdjacencyList.set(z,new Set);this.reverseAdjacencyList.get(z).add(Q)}}patchFiles(_,$,J){let Q=new Set([..._,...$]);for(let z of Q){let W=this.adjacencyList.get(z);if(W){for(let Y of W)this.reverseAdjacencyList.get(Y)?.delete(z);W.clear()}let Z=this.reverseAdjacencyList.get(z);if(Z){for(let Y of Z)this.adjacencyList.get(Y)?.delete(z);Z.clear()}}for(let z of $)this.adjacencyList.delete(z),this.reverseAdjacencyList.delete(z);for(let z of _){let W=J(z);for(let Z of W){if(!this.adjacencyList.has(Z.srcFilePath))this.adjacencyList.set(Z.srcFilePath,new Set);if(this.adjacencyList.get(Z.srcFilePath).add(Z.dstFilePath),!this.adjacencyList.has(Z.dstFilePath))this.adjacencyList.set(Z.dstFilePath,new Set);if(!this.reverseAdjacencyList.has(Z.dstFilePath))this.reverseAdjacencyList.set(Z.dstFilePath,new Set);this.reverseAdjacencyList.get(Z.dstFilePath).add(Z.srcFilePath)}}}getDependencies(_){return Array.from(this.adjacencyList.get(_)??[])}getDependents(_){return Array.from(this.reverseAdjacencyList.get(_)??[])}getTransitiveDependents(_){let $=new Set,J=[_];while(J.length>0){let Q=J.shift();for(let z of this.reverseAdjacencyList.get(Q)??[])if(!$.has(z))$.add(z),J.push(z)}return Array.from($)}hasCycle(){let _=new Set,$=new Set;for(let J of this.adjacencyList.keys()){if(_.has(J))continue;let Q=[{node:J,entered:!1}];while(Q.length>0){let z=Q.pop();if(z.entered){$.delete(z.node);continue}if($.has(z.node))return!0;if(_.has(z.node))continue;_.add(z.node),$.add(z.node),Q.push({node:z.node,entered:!0});for(let W of this.adjacencyList.get(z.node)??[]){if($.has(W))return!0;if(!_.has(W))Q.push({node:W,entered:!1})}}}return!1}getAffectedByChange(_){let $=new Set;for(let J of _)for(let Q of this.getTransitiveDependents(J))$.add(Q);return Array.from($)}getAdjacencyList(){let _=new Map;for(let[$,J]of this.adjacencyList)_.set($,Array.from(J));return _}getTransitiveDependencies(_){let $=new Set,J=[_];while(J.length>0){let Q=J.shift();for(let z of this.adjacencyList.get(Q)??[])if(!$.has(z))$.add(z),J.push(z)}return Array.from($)}getCyclePaths(_){let $=_?.maxCycles??1/0;if($<=0)return[];let J=new Map;for(let[Q,z]of this.adjacencyList)J.set(Q,Array.from(z));return yQ(J,$)}}var uQ=(_,$)=>_.localeCompare($);function bQ(_){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 i0(_,$,J){let Q=bQ(J);if(Q.length===0)return!1;let z=Q.join("->");if(_.has(z))return!1;return _.add(z),$.push(Q),!0}function PQ(_){let $=0,J=[],Q=new Set,z=new Map,W=new Map,Z=[],Y=(X)=>{z.set(X,$),W.set(X,$),$+=1,J.push(X),Q.add(X);for(let M of _.get(X)??[])if(!z.has(M))Y(M),W.set(X,Math.min(W.get(X)??0,W.get(M)??0));else if(Q.has(M))W.set(X,Math.min(W.get(X)??0,z.get(M)??0));if(W.get(X)===z.get(X)){let M=[],O="";do O=J.pop()??"",Q.delete(O),M.push(O);while(O!==X&&J.length>0);Z.push(M)}};for(let X of _.keys())if(!z.has(X))Y(X);return{components:Z}}function fQ(_,$,J){let Q=[],z=new Set,W=[..._].sort(uQ),Z=(Y,X,M)=>{X.delete(Y);let O=M.get(Y);if(!O)return;for(let L of O)if(X.has(L))Z(L,X,M);O.clear()};for(let Y=0;Y<W.length&&Q.length<J;Y++){let X=W[Y]??"",M=new Set(W.slice(Y)),O=new Set,L=new Map,C=[],N=(R)=>($.get(R)??[]).filter((F)=>M.has(F)),w=(R)=>{if(Q.length>=J)return!0;let F=!1;C.push(R),O.add(R);for(let G of N(R)){if(Q.length>=J)break;if(G===X)i0(z,Q,C.concat(X)),F=!0;else if(!O.has(G)){if(w(G))F=!0}}if(F)Z(R,O,L);else for(let G of N(R)){let E=L.get(G)??new Set;E.add(R),L.set(G,E)}return C.pop(),F};w(X)}return Q}function yQ(_,$){let{components:J}=PQ(_),Q=[],z=new Set;for(let W of J){if(Q.length>=$)break;if(W.length===0)continue;if(W.length===1){let X=W[0]??"";if((_.get(X)??[]).includes(X))i0(z,Q,[X,X]);continue}let Z=$-Q.length,Y=fQ(W,_,Z);for(let X of Y){if(Q.length>=$)break;i0(z,Q,X)}}return Q}var xQ=15000;function O0(_){_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}function F_(_,$){let J=$??"__cross__";if(_.graphCache&&_.graphCacheBuiltAt!==null){if(Date.now()-_.graphCacheBuiltAt>xQ)_.graphCache=null,_.graphCacheKey=null,_.graphCacheBuiltAt=null}if(_.graphCache&&_.graphCacheKey===J)return _.graphCache;let Q=new V0({relationRepo:_.relationRepo,project:$??_.defaultProject,additionalProjects:$?void 0:_.boundaries?.map((z)=>z.project)});return Q.build(),_.graphCache=Q,_.graphCacheKey=J,_.graphCacheBuiltAt=Date.now(),Q}function v1(_,$,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 E1(_,$,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 u1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return F_(_,J).getAffectedByChange($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getAffected failed",{cause:Q})}}async function b1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return F_(_,$).hasCycle()}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: hasCycle failed",{cause:J})}}async function P1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return F_(_,$).getAdjacencyList()}catch(J){if(J instanceof V)throw J;throw new V("search","Gildash: getImportGraph failed",{cause:J})}}async function f1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return F_(_,J).getTransitiveDependencies($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getTransitiveDependencies failed",{cause:Q})}}async function y1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return F_(_,J).getTransitiveDependents($)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getTransitiveDependents failed",{cause:Q})}}async function x1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{return F_(_,$).getCyclePaths(J)}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getCyclePaths failed",{cause:Q})}}async function m1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=F_(_,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 nQ=30000,h1=15000,pQ=10;function dQ(_,$){_.boundaries=$,_.defaultProject=$[0]?.project??P_.basename(_.projectRoot)}function lQ(_,$){return(J)=>{for(let Q of _.onFileChangedCallbacks)try{Q(J)}catch(z){_.logger.error("[Gildash] onFileChanged callback threw:",z)}if($.handleWatcherEvent?.(J),_.semanticLayer)if(J.eventType==="delete")try{_.semanticLayer.notifyFileDeleted(J.filePath)}catch(Q){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw:",Q);for(let z of _.onErrorCallbacks)try{z(Q instanceof V?Q:new V("semantic","semantic notifyFileDeleted failed",{cause:Q}))}catch{}}else _.readFileFn(J.filePath).then((Q)=>{try{_.semanticLayer?.notifyFileChanged(J.filePath,Q)}catch(z){_.logger.error("[Gildash] semanticLayer.notifyFileChanged threw:",z);for(let W of _.onErrorCallbacks)try{W(z instanceof V?z:new V("semantic","semantic notifyFileChanged failed",{cause:z}))}catch{}}}).catch((Q)=>{_.logger.error("[Gildash] failed to read file for semantic layer",J.filePath,Q);try{_.semanticLayer?.notifyFileDeleted(J.filePath)}catch(z){_.logger.error("[Gildash] semanticLayer.notifyFileDeleted threw during read error recovery:",z)}})}}async function iQ(_){if(!_.semanticLayer)return;let $=_.fileRepo.getAllFiles(_.defaultProject);await Promise.all($.map(async(J)=>{try{let Q=P_.resolve(_.projectRoot,J.filePath),z=await _.readFileFn(Q);_.semanticLayer?.notifyFileChanged(Q,z)}catch{}}))}async function n1(_,$){let J=_.coordinatorFactory?_.coordinatorFactory():new j0({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)=>dQ(_,Q),logger:_.logger});_.coordinator=J;for(let Q of _.onIndexedCallbacks)J.onIndexed(Q);if(J.onIndexed((Q)=>{let z=Q.changedFiles.length+Q.deletedFiles.length;if(_.graphCache&&z>0&&z<100){let W=_.relationRepo;_.graphCache.patchFiles(Q.changedFiles,Q.deletedFiles,(Z)=>{return[_.defaultProject,..._.boundaries.map((X)=>X.project)].flatMap((X)=>W.getByType(X,"imports").concat(W.getByType(X,"type-references")).concat(W.getByType(X,"re-exports"))).filter((X)=>X.dstFilePath!==null&&(X.srcFilePath===Z||X.dstFilePath===Z)).map((X)=>({srcFilePath:X.srcFilePath,dstFilePath:X.dstFilePath}))}),_.graphCacheBuiltAt=Date.now()}else O0(_)}),$.isWatchMode){let Q=_.watcherFactory?_.watcherFactory():new A0({projectRoot:_.projectRoot,ignorePatterns:_.ignorePatterns,extensions:_.extensions},void 0,_.logger);await Q.start(lQ(_,J)).then((z)=>{if(a_(z))throw z.data}),_.watcher=Q,_.timer=setInterval(()=>{if(_.closed)return;_.updateHeartbeatFn(_.db,process.pid)},nQ)}await J.fullIndex(),await iQ(_)}function cQ(_,$){let J=["SIGTERM","SIGINT","beforeExit"];for(let Q of J){let z=()=>{$().catch((W)=>_.logger.error("[Gildash] close error during signal",Q,W))};if(Q==="beforeExit")process.on("beforeExit",z);else process.on(Q,z);_.signalHandlers.push([Q,z])}}async function p1(_){let{projectRoot:$,extensions:J=[".ts",".mts",".cts"],ignorePatterns:Q=["**/node_modules/**"],parseCacheCapacity:z=500,logger:W=console,existsSyncFn:Z=hQ,dbConnectionFactory:Y,watcherFactory:X,coordinatorFactory:M,repositoryFactory:O,acquireWatcherRoleFn:L=I1,releaseWatcherRoleFn:C=D1,updateHeartbeatFn:N=C1,discoverProjectsFn:w=o_,parseSourceFn:R=v_,extractSymbolsFn:F=R_,extractRelationsFn:G=d_,symbolSearchFn:E=g0,relationSearchFn:b=v0,patternSearchFn:m=E0,loadTsconfigPathsFn:l=n_,readFileFn:i=async(s)=>Bun.file(s).text(),unlinkFn:W_=async(s)=>{await Bun.file(s).unlink()},watchMode:X_,semantic:M_,semanticLayerFactory:U_}=_;if(!P_.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 Y_=Y?Y():new B0({projectRoot:$}),c=Y_.open();if(a_(c))throw c.data;try{let s=await w($),D_=s[0]?.project??P_.basename($),D=O?O():(()=>{let S=Y_;return{fileRepo:new w0(S),symbolRepo:new I0(S),relationRepo:new D0(S),parseCache:new k0(z)}})(),q=O?null:Y_,U=q?new d0(q):null,H=q?new l0(q):null,K=X_??!0,B=crypto.randomUUID(),A;if(K)A=await Promise.resolve(L(Y_,process.pid,{instanceId:B}));else A="owner";let I={projectRoot:$,extensions:J,ignorePatterns:Q,logger:W,defaultProject:D_,role:A,db:Y_,symbolRepo:D.symbolRepo,relationRepo:D.relationRepo,fileRepo:D.fileRepo,parseCache:D.parseCache,annotationRepo:U,changelogRepo:H,annotationSearchFn:g1,releaseWatcherRoleFn:C,parseSourceFn:R,extractSymbolsFn:F,extractRelationsFn:G,symbolSearchFn:E,relationSearchFn:b,patternSearchFn:m,readFileFn:i,unlinkFn:W_,existsSyncFn:Z,acquireWatcherRoleFn:L,updateHeartbeatFn:N,watcherFactory:X,coordinatorFactory:M,instanceId:B,closed:!1,coordinator:null,watcher:null,timer:null,signalHandlers:[],tsconfigPaths:null,boundaries:s,onIndexedCallbacks:new Set,onFileChangedCallbacks:new Set,onErrorCallbacks:new Set,onRoleChangedCallbacks:new Set,graphCache:null,graphCacheKey:null,graphCacheBuiltAt:null,semanticLayer:null};if(t_($),I.tsconfigPaths=await l($),M_){let S=P_.join($,"tsconfig.json");try{if(U_)I.semanticLayer=U_(S);else{let T=U0.create(S);if(a_(T))throw T.data;I.semanticLayer=T}}catch(T){if(T instanceof V)throw T;throw new V("semantic","Gildash: semantic layer creation failed",{cause:T})}}if(A==="owner")await n1(I,{isWatchMode:K});else{let S=0,T=async()=>{try{let j=await Promise.resolve(I.acquireWatcherRoleFn(I.db,process.pid,{instanceId:I.instanceId}));if(S=0,j==="owner"){I.role="owner";for(let g of I.onRoleChangedCallbacks)try{g("owner")}catch(P){I.logger.error("[Gildash] onRoleChanged callback threw:",P)}clearInterval(I.timer),I.timer=null;try{await n1(I,{isWatchMode:!0})}catch(g){if(I.logger.error("[Gildash] owner promotion failed, reverting to reader",g),I.role="reader",I.timer!==null)clearInterval(I.timer),I.timer=null;if(I.watcher){let P=await I.watcher.close();if(a_(P))I.logger.error("[Gildash] watcher close error during promotion rollback",P.data);I.watcher=null}if(I.coordinator)await I.coordinator.shutdown().catch((P)=>I.logger.error("[Gildash] coordinator shutdown error during promotion rollback",P)),I.coordinator=null;try{I.releaseWatcherRoleFn(I.db,process.pid)}catch(P){I.logger.error("[Gildash] failed to release watcher role during promotion rollback",P)}I.timer=setInterval(T,h1)}}}catch(j){S++;let g=j instanceof V?j:new V("watcher","Gildash: healthcheck error",{cause:j});for(let P of I.onErrorCallbacks)try{P(g)}catch(d){I.logger.error("[Gildash] onError callback threw:",d)}if(I.logger.error("[Gildash] healthcheck error",j),S>=pQ)I.logger.error("[Gildash] healthcheck failed too many times, shutting down"),clearInterval(I.timer),I.timer=null,H0(I).catch((P)=>I.logger.error("[Gildash] close error during healthcheck shutdown",P))}};I.timer=setInterval(T,h1)}if(K)cQ(I,()=>H0(I));return I}catch(s){if(Y_.close(),s instanceof V)throw s;throw new V("store","Gildash: initialization failed",{cause:s})}}async function H0(_,$){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(a_(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(P_.join(_.projectRoot,A_,s_+Q))}catch{}if(J.length>0)throw new V("close","Gildash: one or more errors occurred during close()",{cause:J})}import{isErr as d1}from"@zipbul/result";function l1(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");let z=_.parseSourceFn($,J,Q);if(d1(z))throw z.data;return _.parseCache.set($,z),z}async function i1(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");let Q=new Map,z=[];return await Promise.all($.map(async(W)=>{try{let Z=await _.readFileFn(W),Y=_.parseSourceFn(W,Z,J);if(!d1(Y))Q.set(W,Y);else z.push({filePath:W,error:Y.data})}catch(Z){z.push({filePath:W,error:Z instanceof Error?Z:Error(String(Z))})}})),{parsed:Q,failures:z}}function c1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.parseCache.get($)}function a1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.extractSymbolsFn($)}function s1(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");return _.extractRelationsFn($.program,$.filePath,_.tsconfigPaths??void 0)}import r1 from"path";function o1(_,$){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 c0(_,$){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 t1(_,$){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 e1(_,$){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 _$(_,$){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 $$(_,$){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 J$(_,$,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 Q$(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,W=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:J,limit:1}});if(W.length===0)return null;let Z=W[0],Y=Z.detail,X={...Z,members:Y.members,jsDoc:Y.jsDoc,parameters:Y.parameters,returnType:Y.returnType,heritage:Y.heritage,decorators:Y.decorators,typeParameters:Y.typeParameters,initializer:Y.initializer};if(_.semanticLayer)try{let M=r1.isAbsolute(J)?J:r1.resolve(_.projectRoot,J),O=_.semanticLayer.lineColumnToPosition(M,Z.span.start.line,Z.span.start.column);if(O!==null){let L=_.semanticLayer.findNamePosition(M,O,Z.name)??O,C=_.semanticLayer.collectTypeAt(M,L);if(C)X.resolvedType=C}}catch{}return X}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getFullSymbol failed",{cause:z})}}function z$(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=J??_.defaultProject,z=_.fileRepo.getFile(Q,$);if(!z)throw new V("search",`Gildash: file '${$}' is not in the index`);let W=_.symbolRepo.getFileSymbols(Q,$),Z=_.relationRepo.getOutgoing(Q,$);return{filePath:z.filePath,lineCount:z.lineCount??0,size:z.size,symbolCount:W.length,exportedSymbolCount:W.filter((Y)=>Y.isExported).length,relationCount:Z.length}}catch(Q){if(Q instanceof V)throw Q;throw new V("store","Gildash: getFileStats failed",{cause:Q})}}function W$(_,$,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 Y$(_,$,J){return c0(_,{filePath:$,project:J??void 0,limit:1e4})}function Z$(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:J??_.defaultProject,query:{filePath:$,isExported:!0}}).map((W)=>({name:W.name,kind:W.kind,parameters:W.detail.parameters?`(${W.detail.parameters.map((Z)=>`${Z.name}${Z.isOptional?"?":""}: ${Z.type??"unknown"}`).join(", ")})`:void 0,returnType:W.detail.returnType??void 0,jsDoc:W.detail.jsDoc?.description??void 0}));return{filePath:$,exports:z}}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: getModuleInterface failed",{cause:Q})}}import v from"path";function f_(_,$,J,Q){let z=Q??_.defaultProject,W=v.isAbsolute(J)?v.relative(_.projectRoot,J):J,Z=_.symbolSearchFn({symbolRepo:_.symbolRepo,project:z,query:{text:$,exact:!0,filePath:W,limit:1}});if(Z.length===0)return null;let Y=Z[0],X=v.isAbsolute(J)?J:v.resolve(_.projectRoot,J),M=_.semanticLayer.lineColumnToPosition(X,Y.span.start.line,Y.span.start.column);if(M===null)return null;let O=_.semanticLayer.findNamePosition(X,M,Y.name)??M;return{sym:Y,position:O,absPath:X}}function X$(_,$,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=f_(_,$,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 U$(_,$,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=f_(_,$,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 V$(_,$,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=f_(_,$,J,Q);if(!z)throw new V("search",`Gildash: symbol '${$}' not found in '${J}'`);return _.semanticLayer.findEnrichedReferences(z.absPath,z.position)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getEnrichedReferences failed",{cause:z})}}function O$(_,$,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=f_(_,$,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 H$(_,$,J,Q,z,W){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let Z=f_(_,$,J,W);if(!Z)throw new V("search",`Gildash: source symbol '${$}' not found in '${J}'`);let Y=f_(_,Q,z,W);if(!Y)throw new V("search",`Gildash: target symbol '${Q}' not found in '${z}'`);return _.semanticLayer.isTypeAssignableTo(Z.absPath,Z.position,Y.absPath,Y.position)}catch(Z){if(Z instanceof V)throw Z;throw new V("semantic","Gildash: isTypeAssignableTo failed",{cause:Z})}}function K$(_,$){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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.collectFileTypes(J)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: getFileTypes failed",{cause:J})}}function M$(_,$,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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$),W=_.semanticLayer.lineColumnToPosition(z,J,Q);if(W===null)return null;return _.semanticLayer.collectTypeAt(z,W)}catch(z){if(z instanceof V)throw z;throw new V("semantic","Gildash: getResolvedTypeAt failed",{cause:z})}}function L$(_,$){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=v.isAbsolute($.source.filePath)?$.source.filePath:v.resolve(_.projectRoot,$.source.filePath),Q=v.isAbsolute($.target.filePath)?$.target.filePath:v.resolve(_.projectRoot,$.target.filePath),z=_.semanticLayer.lineColumnToPosition(J,$.source.line,$.source.column);if(z===null)return null;let W=_.semanticLayer.lineColumnToPosition(Q,$.target.line,$.target.column);if(W===null)return null;return _.semanticLayer.isTypeAssignableTo(J,z,Q,W)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: isTypeAssignableToAt failed",{cause:J})}}function B$(_,$){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 w$(_,$,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=v.isAbsolute($)?$:v.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 I$(_,$,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=v.isAbsolute($)?$:v.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 D$(_,$,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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.collectAtSpan(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getExpressionTypeAtSpan failed",{cause:Q})}}function C$(_,$,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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.isThenableAtSpan(z,J,Q)}catch(z){if(z instanceof V)throw z;throw new V("semantic","Gildash: isThenableAtSpan failed",{cause:z})}}function A$(_,$,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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.contextualCallReturnsAtSpan(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getContextualCallReturnsAtSpan failed",{cause:Q})}}function q$(_,$,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=v.isAbsolute($)?$:v.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 N$(_,$,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=v.isAbsolute($)?$:v.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 R$(_,$,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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.findEnrichedReferences(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getEnrichedReferencesAtPosition failed",{cause:Q})}}function T$(_,$){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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.getFileBindings(J)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: getFileBindings failed",{cause:J})}}function S$(_,$){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=$.map((W)=>({orig:W.filePath,abs:v.isAbsolute(W.filePath)?W.filePath:v.resolve(_.projectRoot,W.filePath),content:W.content})),Q=_.semanticLayer.getFileBindingsBatch(J.map((W)=>({filePath:W.abs,content:W.content}))),z=new Map;for(let W of J)z.set(W.orig,Q.get(W.abs)??[]);return z}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: getFileBindingsBatch failed",{cause:J})}}function G$(_,$,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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.getStandaloneFileBindings(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: getStandaloneFileBindings failed",{cause:Q})}}function F$(_,$,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=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);_.semanticLayer.notifyFileChanged(Q,J)}catch(Q){if(Q instanceof V)throw Q;throw new V("semantic","Gildash: notifyFileChanged failed",{cause:Q})}}function 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 J=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);_.semanticLayer.notifyFileDeleted(J)}catch(J){if(J instanceof V)throw J;throw new V("semantic","Gildash: notifyFileDeleted failed",{cause:J})}}function k$(_,$,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=v.isAbsolute($)?$:v.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 g$(_,$,J,Q,z){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let W=v.isAbsolute($)?$:v.resolve(_.projectRoot,$),Z=v.isAbsolute(Q)?Q:v.resolve(_.projectRoot,Q);return _.semanticLayer.isTypeAssignableTo(W,J,Z,z)}catch(W){if(W instanceof V)throw W;throw new V("semantic","Gildash: isTypeAssignableToAtPosition failed",{cause:W})}}function v$(_,$,J,Q,z){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let W=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToType(W,J,Q,z)}catch(W){if(W instanceof V)throw W;throw new V("semantic","Gildash: isTypeAssignableToType failed",{cause:W})}}function E$(_,$,J,Q,z){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.semanticLayer)throw new V("semantic","Gildash: semantic layer is not enabled");try{let W=v.isAbsolute($)?$:v.resolve(_.projectRoot,$);return _.semanticLayer.isTypeAssignableToTypeAtPositions(W,J,Q,z)}catch(W){if(W instanceof V)throw W;throw new V("semantic","Gildash: isTypeAssignableToTypeAtPositions failed",{cause:W})}}function u$(_,$,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=v.isAbsolute($)?$:v.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 b$(_,$,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=v.isAbsolute($)?$:v.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 P$(_,$,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=v.isAbsolute($)?$:v.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 f$(_,$,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=v.isAbsolute($)?$:v.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 y$(_,$){let J=new Map(_.map((Y)=>[`${Y.name}::${Y.filePath}`,Y])),Q=new Map($.map((Y)=>[`${Y.name}::${Y.filePath}`,Y])),z=[],W=[],Z=[];for(let[Y,X]of Q){let M=J.get(Y);if(!M)z.push(X);else if(M.fingerprint!==X.fingerprint)Z.push({before:M,after:X})}for(let[Y,X]of J)if(!Q.has(Y))W.push(X);return{added:z,removed:W,modified:Z}}function x$(_,$){if(_.onIndexedCallbacks.add($),!_.coordinator)return()=>{_.onIndexedCallbacks.delete($)};let J=_.coordinator.onIndexed($);return()=>{_.onIndexedCallbacks.delete($),J()}}async function m$(_){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 O0(_),$}catch($){if($ instanceof V)throw $;throw new V("index","Gildash: reindex failed",{cause:$})}}function h$(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");let z=Q??_.defaultProject,W=new Set,Z=[],Y=$,X=J;for(;;){let M=`${X}::${Y}`;if(W.has(M))return{originalName:Y,originalFilePath:X,reExportChain:Z,circular:!0};W.add(M);let O=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{type:"re-exports",srcFilePath:X,limit:500}}),L,C;for(let N of O){let w;if(N.metaJson)try{let F=JSON.parse(N.metaJson);if(Array.isArray(F.specifiers))w=F.specifiers}catch{}if(!w)continue;let R=w.find((F)=>F.exported===Y);if(!R)continue;L=N.dstFilePath??void 0,C=R.local;break}if(!L||!C)return{originalName:Y,originalFilePath:X,reExportChain:Z,circular:!1};Z.push({filePath:X,exportedAs:Y}),X=L,Y=C}}function n$(_,$){return _.onFileChangedCallbacks.add($),()=>{_.onFileChangedCallbacks.delete($)}}function p$(_,$){return _.onErrorCallbacks.add($),()=>{_.onErrorCallbacks.delete($)}}function d$(_,$){return _.onRoleChangedCallbacks.add($),()=>{_.onRoleChangedCallbacks.delete($)}}async function l$(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let Q=J?.project??_.defaultProject,z=J?.filePaths?J.filePaths:_.fileRepo.getAllFiles(Q).map((W)=>W.filePath);return await _.patternSearchFn({pattern:$,filePaths:z})}catch(Q){if(Q instanceof V)throw Q;throw new V("search","Gildash: findPattern failed",{cause:Q})}}async function i$(_,$,J,Q){if(_.closed)throw new V("closed","Gildash: instance is closed");try{let z=Q??_.defaultProject,W=new Set,Z=(Y,X,M)=>{let O=`${Y}::${X}`;if(W.has(O))return{symbolName:Y,filePath:X,kind:M,children:[]};W.add(O);let N=_.relationSearchFn({relationRepo:_.relationRepo,project:z,query:{srcFilePath:X,srcSymbolName:Y,limit:1000}}).filter((w)=>w.type==="extends"||w.type==="implements").filter((w)=>w.dstSymbolName!=null&&w.dstFilePath!=null).map((w)=>Z(w.dstSymbolName,w.dstFilePath,w.type));return{symbolName:Y,filePath:X,kind:M,children:N}};return Z($,J)}catch(z){if(z instanceof V)throw z;throw new V("search","Gildash: getHeritageChain failed",{cause:z})}}function c$(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.annotationRepo||!_.annotationSearchFn)return[];return _.annotationSearchFn({annotationRepo:_.annotationRepo,project:$.project??_.defaultProject,query:$})}function a$(_,$,J){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.changelogRepo)return[];let Q=$ instanceof Date?$.toISOString():$,z=J?.project??_.defaultProject,W=J?.limit??1000;return _.changelogRepo.getSince({project:z,since:Q,symbolName:J?.symbolName,changeTypes:J?.changeTypes,filePath:J?.filePath,includeFullIndex:J?.includeFullIndex,indexRunId:J?.indexRunId,afterId:J?.afterId,limit:W}).map((Y)=>({changeType:Y.changeType,symbolName:Y.symbolName,symbolKind:Y.symbolKind,filePath:Y.filePath,oldName:Y.oldName,oldFilePath:Y.oldFilePath,fingerprint:Y.fingerprint,changedAt:Y.changedAt,isFullIndex:Y.isFullIndex===1,indexRunId:Y.indexRunId}))}function s$(_,$){if(_.closed)throw new V("closed","Gildash: instance is closed");if(!_.changelogRepo)return 0;let J=$ instanceof Date?$.toISOString():$,Q=0,z=[_.defaultProject,..._.boundaries.map((Z)=>Z.project)],W=[...new Set(z)];for(let Z of W)Q+=_.changelogRepo.pruneOlderThan(Z,J);return Q}class a0{_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 p1(_);return new a0($)}async close(_){return H0(this._ctx,_)}parseSource(_,$,J){return l1(this._ctx,_,$,J)}async batchParse(_,$){return i1(this._ctx,_,$)}getParsedAst(_){return c1(this._ctx,_)}extractSymbols(_){return a1(this._ctx,_)}extractRelations(_){return s1(this._ctx,_)}getStats(_){return o1(this._ctx,_)}searchSymbols(_){return c0(this._ctx,_)}searchRelations(_){return t1(this._ctx,_)}searchAllSymbols(_){return e1(this._ctx,_)}searchAllRelations(_){return _$(this._ctx,_)}listIndexedFiles(_){return $$(this._ctx,_)}getInternalRelations(_,$){return J$(this._ctx,_,$)}getFullSymbol(_,$,J){return Q$(this._ctx,_,$,J)}getFileStats(_,$){return z$(this._ctx,_,$)}getFileInfo(_,$){return W$(this._ctx,_,$)}getSymbolsByFile(_,$){return Y$(this._ctx,_,$)}getModuleInterface(_,$){return Z$(this._ctx,_,$)}getDependencies(_,$,J=1e4){return v1(this._ctx,_,$,J)}getDependents(_,$,J=1e4){return E1(this._ctx,_,$,J)}async getAffected(_,$){return u1(this._ctx,_,$)}async hasCycle(_){return b1(this._ctx,_)}async getImportGraph(_){return P1(this._ctx,_)}async getTransitiveDependencies(_,$){return f1(this._ctx,_,$)}async getTransitiveDependents(_,$){return y1(this._ctx,_,$)}async getCyclePaths(_,$){return x1(this._ctx,_,$)}async getFanMetrics(_,$){return m1(this._ctx,_,$)}getResolvedType(_,$,J){return X$(this._ctx,_,$,J)}getSemanticReferences(_,$,J){return U$(this._ctx,_,$,J)}getEnrichedReferences(_,$,J){return V$(this._ctx,_,$,J)}getImplementations(_,$,J){return O$(this._ctx,_,$,J)}isTypeAssignableTo(_,$,J,Q,z){return H$(this._ctx,_,$,J,Q,z)}getSemanticModuleInterface(_){return B$(this._ctx,_)}getFileTypes(_){return K$(this._ctx,_)}getResolvedTypeAt(_,$,J){return M$(this._ctx,_,$,J)}isTypeAssignableToAt(_){return L$(this._ctx,_)}getResolvedTypeAtPosition(_,$){return q$(this._ctx,_,$)}getResolvedTypesAtPositions(_,$){return I$(this._ctx,_,$)}getExpressionTypeAtSpan(_,$){return D$(this._ctx,_,$)}isThenableAtSpan(_,$,J){return C$(this._ctx,_,$,J)}getContextualCallReturnsAtSpan(_,$){return A$(this._ctx,_,$)}getSemanticReferencesAtPosition(_,$){return N$(this._ctx,_,$)}getEnrichedReferencesAtPosition(_,$){return R$(this._ctx,_,$)}getFileBindings(_){return T$(this._ctx,_)}getFileBindingsBatch(_){return S$(this._ctx,_)}getStandaloneFileBindings(_,$){return G$(this._ctx,_,$)}notifyFileChanged(_,$){F$(this._ctx,_,$)}notifyFileDeleted(_){j$(this._ctx,_)}getImplementationsAtPosition(_,$){return k$(this._ctx,_,$)}isTypeAssignableToAtPosition(_,$,J,Q){return g$(this._ctx,_,$,J,Q)}isTypeAssignableToType(_,$,J,Q){return v$(this._ctx,_,$,J,Q)}isTypeAssignableToTypeAtPositions(_,$,J,Q){return E$(this._ctx,_,$,J,Q)}lineColumnToPosition(_,$,J){return u$(this._ctx,_,$,J)}findNamePosition(_,$,J){return b$(this._ctx,_,$,J)}getSymbolNode(_,$){return P$(this._ctx,_,$)}getBaseTypes(_,$){return w$(this._ctx,_,$)}getSemanticDiagnostics(_,$){return f$(this._ctx,_,$)}diffSymbols(_,$){return y$(_,$)}onIndexed(_){return x$(this._ctx,_)}async reindex(){return m$(this._ctx)}resolveSymbol(_,$,J){return h$(this._ctx,_,$,J)}async findPattern(_,$){return l$(this._ctx,_,$)}async getHeritageChain(_,$,J){return i$(this._ctx,_,$,J)}onFileChanged(_){return n$(this._ctx,_)}onError(_){return p$(this._ctx,_)}onRoleChanged(_){return d$(this._ctx,_)}searchAnnotations(_){return c$(this._ctx,_)}getSymbolChanges(_,$){return a$(this._ctx,_,$)}pruneChangelog(_){return s$(this._ctx,_)}}import{Visitor as J2,visitorKeys as Q2}from"oxc-parser";import{walk as W2,parseAndWalk as Y2,ScopeTracker as Z2}from"oxc-walker";export{W2 as walk,Q2 as visitorKeys,g0 as symbolSearch,v0 as relationSearch,E0 as patternSearch,v_ as parseSource,Y2 as parseAndWalk,z_ as normalizePath,tJ as isVariableDeclaration,oJ as isTSQualifiedName,rJ as isMemberExpression,sJ as isIdentifier,pJ as isFunctionNode,aJ as isFunctionExpression,cJ as isFunctionDeclaration,iJ as isCallExpression,lJ as isAssignmentExpression,dJ as isArrowFunctionExpression,eJ as is,O_ as getLineColumn,R_ as extractSymbols,d_ as extractRelations,p_ as buildLineOffsets,J2 as Visitor,Z2 as ScopeTracker,V as GildashError,a0 as Gildash,V0 as DependencyGraph};
|
|
@@ -57,7 +57,7 @@ export type CoordinatorLike = Pick<IndexCoordinator, 'fullIndex' | 'shutdown' |
|
|
|
57
57
|
handleWatcherEvent?(event: FileChangeEvent): void;
|
|
58
58
|
};
|
|
59
59
|
export type WatcherLike = Pick<ProjectWatcher, 'start' | 'close'>;
|
|
60
|
-
export type SemanticLayerLike = Pick<SemanticLayer, 'collectTypeAt' | 'collectFileTypes' | 'collectTypesAtPositions' | 'findReferences' | 'findEnrichedReferences' | 'getFileBindings' | 'getFileBindingsBatch' | 'findImplementations' | 'isTypeAssignableTo' | 'isTypeAssignableToType' | 'isTypeAssignableToTypeAtPositions' | 'getModuleInterface' | 'getSymbolNode' | 'getBaseTypes' | 'getDiagnostics' | 'notifyFileChanged' | 'notifyFileDeleted' | 'dispose' | 'isDisposed' | 'lineColumnToPosition' | 'findNamePosition'>;
|
|
60
|
+
export type SemanticLayerLike = Pick<SemanticLayer, 'collectTypeAt' | 'collectFileTypes' | 'collectTypesAtPositions' | 'collectAtSpan' | 'isThenableAtSpan' | 'contextualCallReturnsAtSpan' | 'findReferences' | 'findEnrichedReferences' | 'getFileBindings' | 'getFileBindingsBatch' | 'getStandaloneFileBindings' | 'findImplementations' | 'isTypeAssignableTo' | 'isTypeAssignableToType' | 'isTypeAssignableToTypeAtPositions' | 'getModuleInterface' | 'getSymbolNode' | 'getBaseTypes' | 'getDiagnostics' | 'notifyFileChanged' | 'notifyFileDeleted' | 'dispose' | 'isDisposed' | 'lineColumnToPosition' | 'findNamePosition'>;
|
|
61
61
|
/** Internal shared state for all Gildash API modules. */
|
|
62
62
|
export interface GildashContext {
|
|
63
63
|
readonly projectRoot: string;
|
|
@@ -9,7 +9,7 @@ import type { RelationSearchQuery } from '../search/relation-search';
|
|
|
9
9
|
import type { SymbolStats } from '../store/repositories/symbol.repository';
|
|
10
10
|
import type { FileRecord } from '../store/repositories/file.repository';
|
|
11
11
|
import type { PatternMatch } from '../search/pattern-search';
|
|
12
|
-
import type { ResolvedType, SemanticReference, EnrichedReference, FileBinding, Implementation, SemanticModuleInterface, SemanticDiagnostic, GetDiagnosticsOptions } from '../semantic/types';
|
|
12
|
+
import type { ResolvedType, ByteSpan, SemanticReference, EnrichedReference, FileBinding, Implementation, SemanticModuleInterface, SemanticDiagnostic, GetDiagnosticsOptions } from '../semantic/types';
|
|
13
13
|
import type { SymbolNode } from '../semantic/symbol-graph';
|
|
14
14
|
import type { GildashContext } from './context';
|
|
15
15
|
import type { FileChangeEvent } from '../watcher/types';
|
|
@@ -438,6 +438,47 @@ export declare class Gildash {
|
|
|
438
438
|
* @throws {GildashError} With type `'semantic'` if tsc initialisation fails.
|
|
439
439
|
*/
|
|
440
440
|
getResolvedTypesAtPositions(filePath: string, positions: number[]): Map<number, ResolvedType>;
|
|
441
|
+
/**
|
|
442
|
+
* Resolve the type of the **expression node** exactly spanning `span`.
|
|
443
|
+
*
|
|
444
|
+
* Unlike {@link getResolvedTypeAtPosition} (innermost node at a single offset,
|
|
445
|
+
* identifier/type-node only), this matches the node whose byte range exactly
|
|
446
|
+
* equals `span` and accepts any expression — so a call `f()` resolves to the
|
|
447
|
+
* call **result** type, `obj.m()` to the method return, `obj.prop` to the
|
|
448
|
+
* property type. No node exactly spans `span` → `null` (no fallback).
|
|
449
|
+
*
|
|
450
|
+
* @param filePath - Relative path to the file.
|
|
451
|
+
* @param span - Byte range `{ start, end }` (matches `oxc-parser` node offsets).
|
|
452
|
+
* @returns Resolved type, or `null` if no expression exactly spans the range.
|
|
453
|
+
* @throws {GildashError} `'semantic'` if the semantic layer is not enabled.
|
|
454
|
+
*/
|
|
455
|
+
getExpressionTypeAtSpan(filePath: string, span: ByteSpan): ResolvedType | null;
|
|
456
|
+
/**
|
|
457
|
+
* Whether the type of the expression spanning `span` is a **thenable**
|
|
458
|
+
* (callable `then` whose signature has ≥1 parameter — the ECMAScript /
|
|
459
|
+
* typescript-eslint definition). Recurses union/intersection on the live type
|
|
460
|
+
* (so `A & PromiseLike<X>` is detected); excludes `any`.
|
|
461
|
+
*
|
|
462
|
+
* @param options.anyConstituent - default `true`: a union is thenable if **some**
|
|
463
|
+
* member is; `false` requires **every** non-nullish member to be thenable.
|
|
464
|
+
* @returns `true`/`false`, or `null` if the span resolves no node/type.
|
|
465
|
+
* @throws {GildashError} `'semantic'` if the semantic layer is not enabled.
|
|
466
|
+
*/
|
|
467
|
+
isThenableAtSpan(filePath: string, span: ByteSpan, options?: {
|
|
468
|
+
anyConstituent?: boolean;
|
|
469
|
+
}): boolean | null;
|
|
470
|
+
/**
|
|
471
|
+
* The return types of the call signatures of the **contextual type** at the
|
|
472
|
+
* argument expression spanning `span` (overload-selected; `undefined`/`null`
|
|
473
|
+
* stripped before signature enumeration). For void-callback detection the
|
|
474
|
+
* caller asserts every returned type is `void`/`undefined`.
|
|
475
|
+
*
|
|
476
|
+
* @returns `ResolvedType[]` (possibly empty when the contextual type has no
|
|
477
|
+
* call signatures, i.e. not a callback slot), or `null` when there is no
|
|
478
|
+
* contextual type at the span.
|
|
479
|
+
* @throws {GildashError} `'semantic'` if the semantic layer is not enabled.
|
|
480
|
+
*/
|
|
481
|
+
getContextualCallReturnsAtSpan(filePath: string, span: ByteSpan): ResolvedType[] | null;
|
|
441
482
|
/**
|
|
442
483
|
* Find all semantic references to the symbol at a specific byte position.
|
|
443
484
|
*
|
|
@@ -481,6 +522,21 @@ export declare class Gildash {
|
|
|
481
522
|
filePath: string;
|
|
482
523
|
content: string;
|
|
483
524
|
}>): Map<string, FileBinding[]>;
|
|
525
|
+
/**
|
|
526
|
+
* Resolve a self-contained in-memory source's bindings in ISOLATION — without
|
|
527
|
+
* touching the shared project program. `O(file)` and constant regardless of
|
|
528
|
+
* project size; use this for ad-hoc sources (e.g. test fixtures) instead of
|
|
529
|
+
* {@link notifyFileChanged} + {@link getFileBindings}, which forces a full
|
|
530
|
+
* re-typecheck of the whole project on the next query.
|
|
531
|
+
*
|
|
532
|
+
* Local binding identity (var hoisting, shadowing, destructuring, writeKind,
|
|
533
|
+
* enclosingScope) matches {@link getFileBindings}. Cross-file imports and
|
|
534
|
+
* global/lib symbols are NOT resolved — they are omitted. For sources that
|
|
535
|
+
* need repo/global symbol identity, use {@link getFileBindings}.
|
|
536
|
+
*
|
|
537
|
+
* @throws {GildashError} With type `'semantic'` if the semantic layer is off.
|
|
538
|
+
*/
|
|
539
|
+
getStandaloneFileBindings(filePath: string, content: string): FileBinding[];
|
|
484
540
|
/**
|
|
485
541
|
* Register or replace an in-memory file in the semantic layer (tsc Program).
|
|
486
542
|
* Identical content is a no-op (no recompute). Pair with {@link getFileBindings}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { SymbolSearchResult } from '../search/symbol-search';
|
|
2
|
-
import type { ResolvedType, SemanticReference, EnrichedReference, FileBinding, Implementation, SemanticModuleInterface, SemanticDiagnostic, GetDiagnosticsOptions } from '../semantic/types';
|
|
2
|
+
import type { ResolvedType, ByteSpan, SemanticReference, EnrichedReference, FileBinding, Implementation, SemanticModuleInterface, SemanticDiagnostic, GetDiagnosticsOptions } from '../semantic/types';
|
|
3
3
|
import type { SymbolNode } from '../semantic/symbol-graph';
|
|
4
4
|
import type { GildashContext } from './context';
|
|
5
5
|
/**
|
|
@@ -44,6 +44,14 @@ export declare function getSemanticModuleInterface(ctx: GildashContext, filePath
|
|
|
44
44
|
export declare function getBaseTypes(ctx: GildashContext, filePath: string, position: number): ResolvedType[] | null;
|
|
45
45
|
/** Retrieve resolved types at multiple byte offsets in a single file (batch). */
|
|
46
46
|
export declare function getResolvedTypesAtPositions(ctx: GildashContext, filePath: string, positions: number[]): Map<number, ResolvedType>;
|
|
47
|
+
/** Resolve the type of the expression node exactly spanning `span` (call result, member, etc.). */
|
|
48
|
+
export declare function getExpressionTypeAtSpan(ctx: GildashContext, filePath: string, span: ByteSpan): ResolvedType | null;
|
|
49
|
+
/** Whether the type of the expression spanning `span` is a thenable (callable `then` with ≥1 param). */
|
|
50
|
+
export declare function isThenableAtSpan(ctx: GildashContext, filePath: string, span: ByteSpan, options?: {
|
|
51
|
+
anyConstituent?: boolean;
|
|
52
|
+
}): boolean | null;
|
|
53
|
+
/** Return types of the contextual call signatures at the argument expression spanning `span`. */
|
|
54
|
+
export declare function getContextualCallReturnsAtSpan(ctx: GildashContext, filePath: string, span: ByteSpan): ResolvedType[] | null;
|
|
47
55
|
/** Retrieve the resolved type at a byte offset without line/column conversion. */
|
|
48
56
|
export declare function getResolvedTypeAtPosition(ctx: GildashContext, filePath: string, position: number): ResolvedType | null;
|
|
49
57
|
/** Find all semantic references at a byte offset. */
|
|
@@ -61,6 +69,12 @@ export declare function getFileBindingsBatch(ctx: GildashContext, files: Readonl
|
|
|
61
69
|
filePath: string;
|
|
62
70
|
content: string;
|
|
63
71
|
}>): Map<string, FileBinding[]>;
|
|
72
|
+
/**
|
|
73
|
+
* Resolve a self-contained source's bindings in isolation (no shared-program
|
|
74
|
+
* touch) — O(file), constant regardless of project size. Cross-file imports and
|
|
75
|
+
* global/lib symbols are not resolved (use getFileBindings for those).
|
|
76
|
+
*/
|
|
77
|
+
export declare function getStandaloneFileBindings(ctx: GildashContext, filePath: string, content: string): FileBinding[];
|
|
64
78
|
/** Register/replace an in-memory file in the semantic layer (tsc Program). */
|
|
65
79
|
export declare function notifyFileChanged(ctx: GildashContext, filePath: string, content: string): void;
|
|
66
80
|
/** Remove an in-memory file from the semantic layer (tsc Program). */
|
package/dist/src/index.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ export type { SymbolStats } from "./store/repositories/symbol.repository";
|
|
|
16
16
|
export type { WatcherRole, FileChangeEvent } from "./watcher/types";
|
|
17
17
|
export type { ParsedFile } from "./parser/types";
|
|
18
18
|
export type { FileRecord } from "./store/repositories/file.repository";
|
|
19
|
-
export type { ResolvedType, SemanticReference, EnrichedReference, FileBinding, Implementation, SemanticModuleInterface, SemanticDiagnostic, GetDiagnosticsOptions } from "./semantic/types";
|
|
19
|
+
export type { ResolvedType, ByteSpan, SemanticReference, EnrichedReference, FileBinding, Implementation, SemanticModuleInterface, SemanticDiagnostic, GetDiagnosticsOptions } from "./semantic/types";
|
|
20
20
|
export type { WriteKind, ScopeKind, EnclosingScope } from "./semantic/reference-classifier";
|
|
21
21
|
export type { SymbolNode } from "./semantic/symbol-graph";
|
|
22
22
|
export type { AnnotationSource, ExtractedAnnotation } from "./extractor/types";
|
|
@@ -10,3 +10,18 @@ import ts from "typescript";
|
|
|
10
10
|
* (`getStart() <= pos < getEnd()`) 자식으로만 재귀하므로 가이드된 하강이다.
|
|
11
11
|
*/
|
|
12
12
|
export declare function findNodeAtPosition(sourceFile: ts.SourceFile, pos: number): ts.Node | undefined;
|
|
13
|
+
/**
|
|
14
|
+
* `[start, end)` 바이트 범위와 **정확히 일치하는** 표현식 노드를 반환한다.
|
|
15
|
+
* (`node.getStart(sf,false) === start && node.getEnd() === end`)
|
|
16
|
+
*
|
|
17
|
+
* 동일 범위를 갖는 노드가 둘 이상이면 **최내곽**(innermost)을 돌려준다. 실제로 span이
|
|
18
|
+
* 겹치는 유일한 경우는 **세미콜론 없는 표현식 문**(ASI)이다 — `ExpressionStatement`가
|
|
19
|
+
* 내부 표현식과 같은 span을 갖는다. 이때 의미 있는 타입은 *표현식* 쪽이므로(문 자체는
|
|
20
|
+
* `getTypeAtLocation`이 `any`로 푼다) innermost를 택한다. (`(f())`처럼 괄호가 글자를
|
|
21
|
+
* 더하는 래퍼는 자식과 span이 달라 애초에 tie가 아니다.)
|
|
22
|
+
*
|
|
23
|
+
* 정확히 일치하는 노드가 없으면 `undefined` — 가장 가까운 노드로의 fallback은 하지
|
|
24
|
+
* 않는다(틀린 노드 추정 방지). `getStart`는 leading trivia를 건너뛰므로 `oxc-parser`의
|
|
25
|
+
* `node.start`/`node.end`와 1:1로 정렬한다.
|
|
26
|
+
*/
|
|
27
|
+
export declare function findNodeAtSpan(sourceFile: ts.SourceFile, start: number, end: number): ts.Node | undefined;
|
|
@@ -11,7 +11,7 @@ import { TypeCollector } from "./type-collector";
|
|
|
11
11
|
import { SymbolGraph, type SymbolNode } from "./symbol-graph";
|
|
12
12
|
import { ReferenceResolver } from "./reference-resolver";
|
|
13
13
|
import { ImplementationFinder } from "./implementation-finder";
|
|
14
|
-
import type { ResolvedType, SemanticReference, EnrichedReference, FileBinding, Implementation, SemanticModuleInterface, SemanticDiagnostic, GetDiagnosticsOptions } from "./types";
|
|
14
|
+
import type { ResolvedType, ByteSpan, SemanticReference, EnrichedReference, FileBinding, Implementation, SemanticModuleInterface, SemanticDiagnostic, GetDiagnosticsOptions } from "./types";
|
|
15
15
|
export interface SemanticLayerOptions extends TscProgramOptions {
|
|
16
16
|
/** Override TypeCollector (for testing). */
|
|
17
17
|
typeCollector?: TypeCollector;
|
|
@@ -36,9 +36,23 @@ export declare class SemanticLayer {
|
|
|
36
36
|
collectTypeAt(filePath: string, position: number): ResolvedType | null;
|
|
37
37
|
collectFileTypes(filePath: string): Map<number, ResolvedType>;
|
|
38
38
|
collectTypesAtPositions(filePath: string, positions: number[]): Map<number, ResolvedType>;
|
|
39
|
+
collectAtSpan(filePath: string, span: ByteSpan): ResolvedType | null;
|
|
40
|
+
isThenableAtSpan(filePath: string, span: ByteSpan, options?: {
|
|
41
|
+
anyConstituent?: boolean;
|
|
42
|
+
}): boolean | null;
|
|
43
|
+
contextualCallReturnsAtSpan(filePath: string, span: ByteSpan): ResolvedType[] | null;
|
|
39
44
|
findReferences(filePath: string, position: number): SemanticReference[];
|
|
40
45
|
findEnrichedReferences(filePath: string, position: number): EnrichedReference[];
|
|
41
46
|
getFileBindings(filePath: string): FileBinding[];
|
|
47
|
+
/**
|
|
48
|
+
* Resolve bindings for a self-contained in-memory source in ISOLATION — a
|
|
49
|
+
* throwaway single-file program that never touches the shared project program.
|
|
50
|
+
* `O(file)` and constant regardless of project size, unlike notifying an ad-hoc
|
|
51
|
+
* file (which invalidates the whole TypeChecker). Local binding identity is
|
|
52
|
+
* identical to {@link getFileBindings}; cross-file imports and global/lib
|
|
53
|
+
* symbols are not resolved (omitted) — for those use {@link getFileBindings}.
|
|
54
|
+
*/
|
|
55
|
+
getStandaloneFileBindings(filePath: string, content: string): FileBinding[];
|
|
42
56
|
/**
|
|
43
57
|
* Register all `files` then collect their bindings, keyed by file path. Notifies
|
|
44
58
|
* every file *before* any query so the Program rebuilds once (O(1)) instead of
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* 텍스트 검색과 달리 심볼 identity 기반으로 참조를 찾으므로
|
|
5
5
|
* rename, re-export, shadowing을 정확히 처리한다.
|
|
6
6
|
*/
|
|
7
|
+
import ts from "typescript";
|
|
7
8
|
import type { EnrichedReference, FileBinding, SemanticReference } from "./types";
|
|
8
9
|
import type { TscProgram } from "./tsc-program";
|
|
9
10
|
export declare class ReferenceResolver {
|
|
@@ -30,3 +31,13 @@ export declare class ReferenceResolver {
|
|
|
30
31
|
*/
|
|
31
32
|
findFileBindings(filePath: string): FileBinding[];
|
|
32
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* Collect every binding referenced in `sourceFile`, grouped by symbol identity,
|
|
36
|
+
* in a single AST pass (no per-symbol `findReferences`). Shared by the
|
|
37
|
+
* shared-program path ({@link ReferenceResolver.findFileBindings}) and the
|
|
38
|
+
* standalone single-file path.
|
|
39
|
+
*
|
|
40
|
+
* The binder handles `var` hoisting / shadowing, so a block `var` and an outer
|
|
41
|
+
* read land in the same group. References are limited to `sourceFile`.
|
|
42
|
+
*/
|
|
43
|
+
export declare function collectBindings(sourceFile: ts.SourceFile, checker: ts.TypeChecker): FileBinding[];
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* standalone-bindings — resolve a self-contained source's bindings in isolation.
|
|
3
|
+
*
|
|
4
|
+
* Builds a throwaway single-file tsc program (`noLib`, `noResolve`) and runs the
|
|
5
|
+
* shared {@link collectBindings} core. It never touches the shared project
|
|
6
|
+
* program, so its cost is independent of project size — unlike notifying an
|
|
7
|
+
* ad-hoc file into the shared program, which invalidates the whole TypeChecker
|
|
8
|
+
* (full re-typecheck on the next query). The source content is served in-memory
|
|
9
|
+
* (never read from disk); `noResolve` still lets the compiler host issue
|
|
10
|
+
* existence stats for any import specifiers, but no file contents are read and
|
|
11
|
+
* bindings are unaffected.
|
|
12
|
+
*
|
|
13
|
+
* Scope: LOCAL/intra-file binding identity only (var hoisting, shadowing,
|
|
14
|
+
* destructuring, writeKind, enclosingScope). It does NOT resolve cross-file
|
|
15
|
+
* import targets or global/lib symbols — those are omitted (the shared-program
|
|
16
|
+
* path surfaces them as ambient bindings, which dataflow consumers exclude).
|
|
17
|
+
*/
|
|
18
|
+
import ts from "typescript";
|
|
19
|
+
import type { FileBinding } from "./types";
|
|
20
|
+
/** Syntax-affecting compiler options inherited from the project for parsing parity. */
|
|
21
|
+
export interface StandaloneParseOptions {
|
|
22
|
+
target?: ts.ScriptTarget;
|
|
23
|
+
module?: ts.ModuleKind;
|
|
24
|
+
jsx?: ts.JsxEmit;
|
|
25
|
+
jsxFactory?: string;
|
|
26
|
+
jsxFragmentFactory?: string;
|
|
27
|
+
jsxImportSource?: string;
|
|
28
|
+
experimentalDecorators?: boolean;
|
|
29
|
+
useDefineForClassFields?: boolean;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Resolve `content`'s bindings as a self-contained source. `filePath` is used
|
|
33
|
+
* only for the returned `declaration.filePath` and to pick the `.tsx` parser;
|
|
34
|
+
* `content` is authoritative (never read from disk).
|
|
35
|
+
*/
|
|
36
|
+
export declare function buildStandaloneBindings(filePath: string, content: string, inherited?: StandaloneParseOptions): FileBinding[];
|
|
@@ -43,6 +43,11 @@ export declare class TscProgram {
|
|
|
43
43
|
get isDisposed(): boolean;
|
|
44
44
|
getProgram(): ts.Program;
|
|
45
45
|
getChecker(): ts.TypeChecker;
|
|
46
|
+
/**
|
|
47
|
+
* The project's compiler options, read from the host without forcing a
|
|
48
|
+
* Program sync (so callers that don't need the Program stay cheap).
|
|
49
|
+
*/
|
|
50
|
+
getCompilerOptions(): ts.CompilerOptions;
|
|
46
51
|
getLanguageService(): ts.LanguageService;
|
|
47
52
|
/**
|
|
48
53
|
* Notify that a file's content has changed (or a new file was added).
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* 각 심볼 위치의 타입을 ResolvedType으로 변환한다.
|
|
6
6
|
*/
|
|
7
7
|
import ts from "typescript";
|
|
8
|
-
import type { ResolvedType } from "./types";
|
|
8
|
+
import type { ResolvedType, ByteSpan } from "./types";
|
|
9
9
|
import type { TscProgram } from "./tsc-program";
|
|
10
10
|
/**
|
|
11
11
|
* `ts.Type`을 `ResolvedType`으로 재귀 변환한다.
|
|
@@ -30,6 +30,44 @@ export declare class TypeCollector {
|
|
|
30
30
|
* - `TscProgram`이 disposed 상태이면 throw (getProgram이 throw)
|
|
31
31
|
*/
|
|
32
32
|
collectAt(filePath: string, position: number): ResolvedType | null;
|
|
33
|
+
/**
|
|
34
|
+
* Resolve the type of the **expression node** that exactly spans `span`
|
|
35
|
+
* (`[getStart(), getEnd())` === `[span.start, span.end)`); the innermost on a
|
|
36
|
+
* tie (e.g. the expression inside a semicolon-less `ExpressionStatement`, not
|
|
37
|
+
* the statement — which would resolve to `any`). Unlike {@link collectAt},
|
|
38
|
+
* accepts any expression node (Call/Member/Await/…),
|
|
39
|
+
* so `f()` resolves to the call **result** type. No exact match → `null` (no
|
|
40
|
+
* fallback). Returns existing {@link ResolvedType} (incl. raw `.flags`).
|
|
41
|
+
*
|
|
42
|
+
*/
|
|
43
|
+
collectAtSpan(filePath: string, span: ByteSpan): ResolvedType | null;
|
|
44
|
+
/**
|
|
45
|
+
* Whether the type of the expression exactly spanning `span` is a **thenable**
|
|
46
|
+
* (ECMAScript / typescript-eslint definition: a callable `then` member whose
|
|
47
|
+
* call signature has ≥1 parameter). Recurses union/intersection on the live
|
|
48
|
+
* `ts.Type` (so `A & PromiseLike<X>` resolves); excludes `any`. `null` when the
|
|
49
|
+
* span resolves no node / type. `options.anyConstituent` (default `true`): a
|
|
50
|
+
* union is thenable if **some** member is.
|
|
51
|
+
*
|
|
52
|
+
*/
|
|
53
|
+
isThenableAtSpan(filePath: string, span: ByteSpan, options?: {
|
|
54
|
+
anyConstituent?: boolean;
|
|
55
|
+
}): boolean | null;
|
|
56
|
+
/**
|
|
57
|
+
* The return types of the call signatures of the **contextual type** at the
|
|
58
|
+
* argument expression spanning `span` (overload-selected, `undefined`/`null`
|
|
59
|
+
* stripped before signature enumeration). For a void-callback slot the caller
|
|
60
|
+
* checks every returned type is `void`/`undefined`. `null` when there is no
|
|
61
|
+
* contextual type; `[]` when the contextual type has no call signatures
|
|
62
|
+
* (not a callback slot).
|
|
63
|
+
*
|
|
64
|
+
* When the contextual type is a union of function types
|
|
65
|
+
* (`(() => void) | (() => number)`), the returns of **all** members are
|
|
66
|
+
* included — the caller's "every return is void" check then naturally rejects
|
|
67
|
+
* the value-returning member.
|
|
68
|
+
*
|
|
69
|
+
*/
|
|
70
|
+
contextualCallReturnsAtSpan(filePath: string, span: ByteSpan): ResolvedType[] | null;
|
|
33
71
|
/**
|
|
34
72
|
* 두 위치의 타입 호환성을 검사한다.
|
|
35
73
|
*
|
|
@@ -5,6 +5,21 @@
|
|
|
5
5
|
* The Semantic Layer is opt-in via `Gildash.open({ semantic: true })`.
|
|
6
6
|
*/
|
|
7
7
|
import type { WriteKind, EnclosingScope } from './reference-classifier';
|
|
8
|
+
/**
|
|
9
|
+
* A half-open byte range `[start, end)` (0-based character offsets) identifying an
|
|
10
|
+
* **expression node** within a source file.
|
|
11
|
+
*
|
|
12
|
+
* Unlike {@link SourceSpan} (line/column based), `ByteSpan` is byte-offset based so
|
|
13
|
+
* it aligns 1:1 with `oxc-parser`'s `node.start` / `node.end`. The span-based
|
|
14
|
+
* semantic primitives resolve the node whose `[getStart(), getEnd())` exactly
|
|
15
|
+
* equals the span; if no node matches exactly they return `null` (no fallback).
|
|
16
|
+
*/
|
|
17
|
+
export interface ByteSpan {
|
|
18
|
+
/** Inclusive 0-based start byte offset. */
|
|
19
|
+
start: number;
|
|
20
|
+
/** Exclusive 0-based end byte offset. */
|
|
21
|
+
end: number;
|
|
22
|
+
}
|
|
8
23
|
/**
|
|
9
24
|
* The resolved type of a TypeScript symbol, as determined by the tsc TypeChecker.
|
|
10
25
|
*
|